From 8abdbbbf633f96fde2346c4ae70e538895fd7829 Mon Sep 17 00:00:00 2001 From: Richard Moore Date: Thu, 27 Aug 2020 14:22:58 -0400 Subject: [PATCH] Updating shims for constrained environments (#944, #993). --- packages/shims/dist/index.js | 1412 +----------------------- packages/shims/dist/index.min.js | 2 +- packages/shims/src/es6-promise.auto.js | 1158 ------------------- packages/shims/src/index.js | 173 +-- 4 files changed, 164 insertions(+), 2581 deletions(-) delete mode 100644 packages/shims/src/es6-promise.auto.js diff --git a/packages/shims/dist/index.js b/packages/shims/dist/index.js index 6f4a6ebc89..47063ed747 100644 --- a/packages/shims/dist/index.js +++ b/packages/shims/dist/index.js @@ -1,190 +1,4 @@ (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],2:[function(require,module,exports){ /** * See: https://github.com/MaxArt2501/base64-js * The MIT License (MIT) @@ -285,1170 +99,7 @@ process.umask = function() { return 0; }; }; }); -},{}],3:[function(require,module,exports){ -(function (process,global){ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE - * @version 4.1.0+f046478d - */ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.ES6Promise = factory()); -}(this, (function () { 'use strict'; - -function objectOrFunction(x) { - var type = typeof x; - return x !== null && (type === 'object' || type === 'function'); -} - -function isFunction(x) { - return typeof x === 'function'; -} - -var _isArray = undefined; -if (Array.isArray) { - _isArray = Array.isArray; -} else { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; -} - -var isArray = _isArray; - -var len = 0; -var vertxNext = undefined; -var customSchedulerFn = undefined; - -var asap = function asap(callback, arg) { - queue[len] = callback; - queue[len + 1] = arg; - len += 2; - if (len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - if (customSchedulerFn) { - customSchedulerFn(flush); - } else { - scheduleFlush(); - } - } -}; - -function setScheduler(scheduleFn) { - customSchedulerFn = scheduleFn; -} - -function setAsap(asapFn) { - asap = asapFn; -} - -var browserWindow = typeof window !== 'undefined' ? window : undefined; -var browserGlobal = browserWindow || {}; -var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; -var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; - -// test for web worker but not in IE10 -var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; - -// node -function useNextTick() { - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // see https://github.com/cujojs/when/issues/410 for details - return function () { - return process.nextTick(flush); - }; -} - -// vertx -function useVertxTimer() { - if (typeof vertxNext !== 'undefined') { - return function () { - vertxNext(flush); - }; - } - - return useSetTimeout(); -} - -function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function () { - node.data = iterations = ++iterations % 2; - }; -} - -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - return channel.port2.postMessage(0); - }; -} - -function useSetTimeout() { - // Store setTimeout reference so es6-promise will be unaffected by - // other code modifying setTimeout (like sinon.useFakeTimers()) - var globalSetTimeout = setTimeout; - return function () { - return globalSetTimeout(flush, 1); - }; -} - -var queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i += 2) { - var callback = queue[i]; - var arg = queue[i + 1]; - - callback(arg); - - queue[i] = undefined; - queue[i + 1] = undefined; - } - - len = 0; -} - -function attemptVertx() { - try { - var r = require; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch (e) { - return useSetTimeout(); - } -} - -var scheduleFlush = undefined; -// Decide what async method to use to triggering processing of queued callbacks: -if (isNode) { - scheduleFlush = useNextTick(); -} else if (BrowserMutationObserver) { - scheduleFlush = useMutationObserver(); -} else if (isWorker) { - scheduleFlush = useMessageChannel(); -} else if (browserWindow === undefined && typeof require === 'function') { - scheduleFlush = attemptVertx(); -} else { - scheduleFlush = useSetTimeout(); -} - -function then(onFulfillment, onRejection) { - var _arguments = arguments; - - var parent = this; - - var child = new this.constructor(noop); - - if (child[PROMISE_ID] === undefined) { - makePromise(child); - } - - var _state = parent._state; - - if (_state) { - (function () { - var callback = _arguments[_state - 1]; - asap(function () { - return invokeCallback(_state, child, callback, parent._result); - }); - })(); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } - - return child; -} - -/** - `Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: - - ```javascript - let promise = new Promise(function(resolve, reject){ - resolve(1); - }); - - promise.then(function(value){ - // value === 1 - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - let promise = Promise.resolve(1); - - promise.then(function(value){ - // value === 1 - }); - ``` - - @method resolve - @static - @param {Any} value value that the returned promise will be resolved with - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` -*/ -function resolve$1(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(noop); - resolve(promise, object); - return promise; -} - -var PROMISE_ID = Math.random().toString(36).substring(16); - -function noop() {} - -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; - -var GET_THEN_ERROR = new ErrorObject(); - -function selfFulfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} - -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} - -function getThen(promise) { - try { - return promise.then; - } catch (error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } -} - -function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { - try { - then$$1.call(value, fulfillmentHandler, rejectionHandler); - } catch (e) { - return e; - } -} - -function handleForeignThenable(promise, thenable, then$$1) { - asap(function (promise) { - var sealed = false; - var error = tryThen(then$$1, thenable, function (value) { - if (sealed) { - return; - } - sealed = true; - if (thenable !== value) { - resolve(promise, value); - } else { - fulfill(promise, value); - } - }, function (reason) { - if (sealed) { - return; - } - sealed = true; - - reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - reject(promise, error); - } - }, promise); -} - -function handleOwnThenable(promise, thenable) { - if (thenable._state === FULFILLED) { - fulfill(promise, thenable._result); - } else if (thenable._state === REJECTED) { - reject(promise, thenable._result); - } else { - subscribe(thenable, undefined, function (value) { - return resolve(promise, value); - }, function (reason) { - return reject(promise, reason); - }); - } -} - -function handleMaybeThenable(promise, maybeThenable, then$$1) { - if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { - handleOwnThenable(promise, maybeThenable); - } else { - if (then$$1 === GET_THEN_ERROR) { - reject(promise, GET_THEN_ERROR.error); - GET_THEN_ERROR.error = null; - } else if (then$$1 === undefined) { - fulfill(promise, maybeThenable); - } else if (isFunction(then$$1)) { - handleForeignThenable(promise, maybeThenable, then$$1); - } else { - fulfill(promise, maybeThenable); - } - } -} - -function resolve(promise, value) { - if (promise === value) { - reject(promise, selfFulfillment()); - } else if (objectOrFunction(value)) { - handleMaybeThenable(promise, value, getThen(value)); - } else { - fulfill(promise, value); - } -} - -function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - publish(promise); -} - -function fulfill(promise, value) { - if (promise._state !== PENDING) { - return; - } - - promise._result = value; - promise._state = FULFILLED; - - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} - -function reject(promise, reason) { - if (promise._state !== PENDING) { - return; - } - promise._state = REJECTED; - promise._result = reason; - - asap(publishRejection, promise); -} - -function subscribe(parent, child, onFulfillment, onRejection) { - var _subscribers = parent._subscribers; - var length = _subscribers.length; - - parent._onerror = null; - - _subscribers[length] = child; - _subscribers[length + FULFILLED] = onFulfillment; - _subscribers[length + REJECTED] = onRejection; - - if (length === 0 && parent._state) { - asap(publish, parent); - } -} - -function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { - return; - } - - var child = undefined, - callback = undefined, - detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; -} - -function ErrorObject() { - this.error = null; -} - -var TRY_CATCH_ERROR = new ErrorObject(); - -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch (e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } -} - -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value = undefined, - error = undefined, - succeeded = undefined, - failed = undefined; - - if (hasCallback) { - value = tryCatch(callback, detail); - - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value.error = null; - } else { - succeeded = true; - } - - if (promise === value) { - reject(promise, cannotReturnOwn()); - return; - } - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== PENDING) { - // noop - } else if (hasCallback && succeeded) { - resolve(promise, value); - } else if (failed) { - reject(promise, error); - } else if (settled === FULFILLED) { - fulfill(promise, value); - } else if (settled === REJECTED) { - reject(promise, value); - } -} - -function initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value) { - resolve(promise, value); - }, function rejectPromise(reason) { - reject(promise, reason); - }); - } catch (e) { - reject(promise, e); - } -} - -var id = 0; -function nextId() { - return id++; -} - -function makePromise(promise) { - promise[PROMISE_ID] = id++; - promise._state = undefined; - promise._result = undefined; - promise._subscribers = []; -} - -function Enumerator$1(Constructor, input) { - this._instanceConstructor = Constructor; - this.promise = new Constructor(noop); - - if (!this.promise[PROMISE_ID]) { - makePromise(this.promise); - } - - if (isArray(input)) { - this.length = input.length; - this._remaining = input.length; - - this._result = new Array(this.length); - - if (this.length === 0) { - fulfill(this.promise, this._result); - } else { - this.length = this.length || 0; - this._enumerate(input); - if (this._remaining === 0) { - fulfill(this.promise, this._result); - } - } - } else { - reject(this.promise, validationError()); - } -} - -function validationError() { - return new Error('Array Methods must be provided an Array'); -} - -Enumerator$1.prototype._enumerate = function (input) { - for (var i = 0; this._state === PENDING && i < input.length; i++) { - this._eachEntry(input[i], i); - } -}; - -Enumerator$1.prototype._eachEntry = function (entry, i) { - var c = this._instanceConstructor; - var resolve$$1 = c.resolve; - - if (resolve$$1 === resolve$1) { - var _then = getThen(entry); - - if (_then === then && entry._state !== PENDING) { - this._settledAt(entry._state, i, entry._result); - } else if (typeof _then !== 'function') { - this._remaining--; - this._result[i] = entry; - } else if (c === Promise$3) { - var promise = new c(noop); - handleMaybeThenable(promise, entry, _then); - this._willSettleAt(promise, i); - } else { - this._willSettleAt(new c(function (resolve$$1) { - return resolve$$1(entry); - }), i); - } - } else { - this._willSettleAt(resolve$$1(entry), i); - } -}; - -Enumerator$1.prototype._settledAt = function (state, i, value) { - var promise = this.promise; - - if (promise._state === PENDING) { - this._remaining--; - - if (state === REJECTED) { - reject(promise, value); - } else { - this._result[i] = value; - } - } - - if (this._remaining === 0) { - fulfill(promise, this._result); - } -}; - -Enumerator$1.prototype._willSettleAt = function (promise, i) { - var enumerator = this; - - subscribe(promise, undefined, function (value) { - return enumerator._settledAt(FULFILLED, i, value); - }, function (reason) { - return enumerator._settledAt(REJECTED, i, reason); - }); -}; - -/** - `Promise.all` accepts an array of promises, and returns a new promise which - is fulfilled with an array of fulfillment values for the passed promises, or - rejected with the reason of the first passed promise to be rejected. It casts all - elements of the passed iterable to promises as it runs this algorithm. - - Example: - - ```javascript - let promise1 = resolve(1); - let promise2 = resolve(2); - let promise3 = resolve(3); - let promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` - - If any of the `promises` given to `all` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - Example: - - ```javascript - let promise1 = resolve(1); - let promise2 = reject(new Error("2")); - let promise3 = reject(new Error("3")); - let promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` - - @method all - @static - @param {Array} entries array of promises - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all `promises` have been - fulfilled, or rejected if any of them become rejected. - @static -*/ -function all$1(entries) { - return new Enumerator$1(this, entries).promise; -} - -/** - `Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. - - Example: - - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 2'); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // result === 'promise 2' because it was resolved before promise1 - // was resolved. - }); - ``` - - `Promise.race` is deterministic in that only the state of the first - settled promise matters. For example, even if other promises given to the - `promises` array argument are resolved, but the first settled promise has - become rejected before the other promises became fulfilled, the returned - promise will become rejected: - - ```javascript - let promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - let promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // Code here never runs - }, function(reason){ - // reason.message === 'promise 2' because promise 2 became rejected before - // promise 1 became fulfilled - }); - ``` - - An example real-world use case is implementing timeouts: - - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` - - @method race - @static - @param {Array} promises array of promises to observe - Useful for tooling. - @return {Promise} a promise which settles in the same way as the first passed - promise to settle. -*/ -function race$1(entries) { - /*jshint validthis:true */ - var Constructor = this; - - if (!isArray(entries)) { - return new Constructor(function (_, reject) { - return reject(new TypeError('You must pass an array to race.')); - }); - } else { - return new Constructor(function (resolve, reject) { - var length = entries.length; - for (var i = 0; i < length; i++) { - Constructor.resolve(entries[i]).then(resolve, reject); - } - }); - } -} - -/** - `Promise.reject` returns a promise rejected with the passed `reason`. - It is shorthand for the following: - - ```javascript - let promise = new Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - let promise = Promise.reject(new Error('WHOOPS')); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - @method reject - @static - @param {Any} reason value that the returned promise will be rejected with. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. -*/ -function reject$1(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(noop); - reject(promise, reason); - return promise; -} - -function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); -} - -function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); -} - -/** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise's eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - let promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - let xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor -*/ -function Promise$3(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; - - if (noop !== resolver) { - typeof resolver !== 'function' && needsResolver(); - this instanceof Promise$3 ? initializePromise(this, resolver) : needsNew(); - } -} - -Promise$3.all = all$1; -Promise$3.race = race$1; -Promise$3.resolve = resolve$1; -Promise$3.reject = reject$1; -Promise$3._setScheduler = setScheduler; -Promise$3._setAsap = setAsap; -Promise$3._asap = asap; - -Promise$3.prototype = { - constructor: Promise$3, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - let result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - let author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: then, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function _catch(onRejection) { - return this.then(null, onRejection); - } -}; - -/*global self*/ -function polyfill$1() { - var local = undefined; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { - // silently ignored - } - - if (promiseToString === '[object Promise]' && !P.cast) { - return; - } - } - - local.Promise = Promise$3; -} - -// Strange compat.. -Promise$3.polyfill = polyfill$1; -Promise$3.Promise = Promise$3; - -Promise$3.polyfill(); - -return Promise$3; - -}))); - - - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":1}],4:[function(require,module,exports){ +},{}],2:[function(require,module,exports){ (function (global){ 'use strict'; @@ -1502,9 +153,9 @@ if (!global.btoa) { // Shim Promise // @TODO: Check first? -if (window.Promise == null) { - var promise = require('./es6-promise.auto.js'); -} +//if (window.Promise == null) { +// var promise = require('./es6-promise.auto.js'); +//} // Shim ArrayBuffer.isView if (!ArrayBuffer.isView) { @@ -1521,6 +172,53 @@ if (!global.nextTick) { global.nextTick = function (callback) { setTimeout(callback, 0); } } +// Shim crypto.getRandomValues +// @TOOD: Investigate: https://github.com/brix/crypto-js/issues/7 +if (!global.crypto) { global.crypto = { }; } +if (!global.crypto.getRandomValues) { + shims.push("crypto.getRandomValues"); + console.log("WARNING: This environment is missing a secure random source; generated private keys may be at risk, think VERY carefully about not adding a better secure source."); + global.crypto.getRandomValues = function(buffer) { + var start = Math.floor((new Date()).getTime()) % buffer.length; + for (var i = 0; i < buffer.length; i++) { + buffer[(start + i) % buffer.length] = Math.floor(Math.random() * 256); + } + } +} + +// Shim FileReader.readAsArrayBuffer +// https://github.com/facebook/react-native/issues/21209 +(function() { + try { + var fr = new FileReader(); + try { + fr.readAsArrayBuffer(new Blob([ "hello" ], { type: "text/plain" })); + return; + } catch (error) { } + + shims.push("FileReader.prototype.readAsArrayBuffer"); + FileReader.prototype.readAsArrayBuffer = function (blob) { + if (this.readyState === this.LOADING) throw new Error("InvalidStateError"); + this._setReadyState(this.LOADING); + this._result = null; + this._error = null; + var fr = new FileReader(); + fr.onloadend = () => { + var content = atob(fr.result.split(",").pop().trim()); + var buffer = new ArrayBuffer(content.length); + var view = new Uint8Array(buffer); + view.set(Array.from(content).map(c => c.charCodeAt(0))); + this._result = buffer; + this._setReadyState(this.DONE); + }; + fr.readAsDataURL(blob); + } + + } catch (error) { + console.log("Missing FileReader; unsupported platform"); + } +})(); + if (shims.length) { console.log("Shims Injected:"); for (var i = 0; i < shims.length; i++) { @@ -1528,11 +226,11 @@ if (shims.length) { } } -// @TOOD: Add crypto.rand? -// - https://github.com/brix/crypto-js/issues/7 + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./base64.js":2,"./es6-promise.auto.js":3,"./unorm.js":5}],5:[function(require,module,exports){ +},{"./base64.js":1,"./unorm.js":3}],3:[function(require,module,exports){ (function (root) { "use strict"; @@ -1976,4 +674,4 @@ UChar.udata={ } }(this)); -},{}]},{},[4]); +},{}]},{},[2]); diff --git a/packages/shims/dist/index.min.js b/packages/shims/dist/index.min.js index 23b011f531..2b305e1974 100644 --- a/packages/shims/dist/index.min.js +++ b/packages/shims/dist/index.min.js @@ -1 +1 @@ -!function(){return function t(r,e,n){function o(s,u){if(!e[s]){if(!r[s]){var a="function"==typeof require&&require;if(!u&&a)return a(s,!0);if(i)return i(s,!0);var f=new Error("Cannot find module '"+s+"'");throw f.code="MODULE_NOT_FOUND",f}var c=e[s]={exports:{}};r[s][0].call(c.exports,function(t){return o(r[s][1][t]||t)},c,c.exports,t,r,e,n)}return e[s].exports}for(var i="function"==typeof require&&require,s=0;s1)for(var e=1;e255||(o=t.charCodeAt(u++))>255||(i=t.charCodeAt(u++))>255)throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");s+=n.charAt((r=e<<16|o<<8|i)>>18&63)+n.charAt(r>>12&63)+n.charAt(r>>6&63)+n.charAt(63&r)}return a?s.slice(0,a-3)+"===".substring(a):s},t.atob=function(t){if(t=String(t).replace(/[\t\n\f\r ]+/g,""),!o.test(t))throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");t+="==".slice(2-(3&t.length));for(var r,e,i,s="",u=0;u>16&255):64===i?String.fromCharCode(r>>16&255,r>>8&255):String.fromCharCode(r>>16&255,r>>8&255,255&r);return s}}},"function"==typeof define&&define.amd?define([],function(){o(n)}):o(n)},{}],3:[function(t,r,e){(function(n,o){!function(t,n){"object"==typeof e&&void 0!==r?r.exports=n():"function"==typeof define&&define.amd?define(n):t.ES6Promise=n()}(this,function(){"use strict";function r(t){return"function"==typeof t}var e=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)},i=0,s=void 0,u=void 0,a=function(t,r){v[i]=t,v[i+1]=r,2===(i+=2)&&(u?u(g):_())};var f="undefined"!=typeof window?window:void 0,c=f||{},h=c.MutationObserver||c.WebKitMutationObserver,l="undefined"==typeof self&&void 0!==n&&"[object process]"==={}.toString.call(n),p="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function d(){var t=setTimeout;return function(){return t(g,1)}}var v=new Array(1e3);function g(){for(var t=0;t>8&255]>n&&(d[r]=o),o},function(t,r,e){return e?t(r,e):new p(r,null)},function(t,r,e){var n;if(r=55296&&t<=56319},p.isLowSurrogate=function(t){return t>=56320&&t<=57343},p.prototype.prepFeature=function(){this.feature||(this.feature=p.fromCharCode(this.codepoint,!0).feature)},p.prototype.toString=function(){if(this.codepoint<65536)return String.fromCharCode(this.codepoint);var t=this.codepoint-65536;return String.fromCharCode(Math.floor(t/1024)+55296,t%1024+56320)},p.prototype.getDecomp=function(){return this.prepFeature(),this.feature[0]||null},p.prototype.isCompatibility=function(){return this.prepFeature(),!!this.feature[1]&&256&this.feature[1]},p.prototype.isExclude=function(){return this.prepFeature(),!!this.feature[1]&&512&this.feature[1]},p.prototype.getCanonicalClass=function(){return this.prepFeature(),this.feature[1]?255&this.feature[1]:0},p.prototype.getComposite=function(t){if(this.prepFeature(),!this.feature[2])return null;var r=this.feature[2][t.codepoint];return r?p.fromCharCode(r):null};var w=function(t){this.str=t,this.cursor=0};w.prototype.next=function(){if(this.str&&this.cursor0;--e){if(this.resBuf[e-1].getCanonicalClass()<=t)break}this.resBuf.splice(e,0,r)}while(0!==t);return this.resBuf.shift()};var _=function(t){this.it=t,this.procBuf=[],this.resBuf=[],this.lastClass=null};_.prototype.next=function(){for(;0===this.resBuf.length;){var t=this.it.next();if(!t){this.resBuf=this.procBuf,this.procBuf=[];break}if(0===this.procBuf.length)this.lastClass=t.getCanonicalClass(),this.procBuf.push(t);else{var r=this.procBuf[0].getComposite(t),e=t.getCanonicalClass();r&&(this.lastClass255||(o=t.charCodeAt(s++))>255||(i=t.charCodeAt(s++))>255)throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");a+=n.charAt((r=e<<16|o<<8|i)>>18&63)+n.charAt(r>>12&63)+n.charAt(r>>6&63)+n.charAt(63&r)}return u?a.slice(0,u-3)+"===".substring(u):a},t.atob=function(t){if(t=String(t).replace(/[\t\n\f\r ]+/g,""),!o.test(t))throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");t+="==".slice(2-(3&t.length));for(var r,e,i,a="",s=0;s>16&255):64===i?String.fromCharCode(r>>16&255,r>>8&255):String.fromCharCode(r>>16&255,r>>8&255,255&r);return a}}},"function"==typeof define&&define.amd?define([],function(){o(n)}):o(n)},{}],2:[function(t,r,e){(function(r){"use strict";var e=[];try{for(var n=[],o=["NFD","NFC","NFKD","NFKC"],i=0;i{var t=atob(r.result.split(",").pop().trim()),e=new ArrayBuffer(t.length);new Uint8Array(e).set(Array.from(t).map(t=>t.charCodeAt(0))),this._result=e,this._setReadyState(this.DONE)}),r.readAsDataURL(t)}}catch(t){console.log("Missing FileReader; unsupported platform")}}(),e.length){console.log("Shims Injected:");for(i=0;i>8&255]>n&&(d[r]=o),o},function(t,r,e){return e?t(r,e):new p(r,null)},function(t,r,e){var n;if(r=55296&&t<=56319},p.isLowSurrogate=function(t){return t>=56320&&t<=57343},p.prototype.prepFeature=function(){this.feature||(this.feature=p.fromCharCode(this.codepoint,!0).feature)},p.prototype.toString=function(){if(this.codepoint<65536)return String.fromCharCode(this.codepoint);var t=this.codepoint-65536;return String.fromCharCode(Math.floor(t/1024)+55296,t%1024+56320)},p.prototype.getDecomp=function(){return this.prepFeature(),this.feature[0]||null},p.prototype.isCompatibility=function(){return this.prepFeature(),!!this.feature[1]&&256&this.feature[1]},p.prototype.isExclude=function(){return this.prepFeature(),!!this.feature[1]&&512&this.feature[1]},p.prototype.getCanonicalClass=function(){return this.prepFeature(),this.feature[1]?255&this.feature[1]:0},p.prototype.getComposite=function(t){if(this.prepFeature(),!this.feature[2])return null;var r=this.feature[2][t.codepoint];return r?p.fromCharCode(r):null};var y=function(t){this.str=t,this.cursor=0};y.prototype.next=function(){if(this.str&&this.cursor0;--e){if(this.resBuf[e-1].getCanonicalClass()<=t)break}this.resBuf.splice(e,0,r)}while(0!==t);return this.resBuf.shift()};var b=function(t){this.it=t,this.procBuf=[],this.resBuf=[],this.lastClass=null};b.prototype.next=function(){for(;0===this.resBuf.length;){var t=this.it.next();if(!t){this.resBuf=this.procBuf,this.procBuf=[];break}if(0===this.procBuf.length)this.lastClass=t.getCanonicalClass(),this.procBuf.push(t);else{var r=this.procBuf[0].getComposite(t),e=t.getCanonicalClass();r&&(this.lastClass postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor -*/ -function Promise$3(resolver) { - this[PROMISE_ID] = nextId(); - this._result = this._state = undefined; - this._subscribers = []; - - if (noop !== resolver) { - typeof resolver !== 'function' && needsResolver(); - this instanceof Promise$3 ? initializePromise(this, resolver) : needsNew(); - } -} - -Promise$3.all = all$1; -Promise$3.race = race$1; -Promise$3.resolve = resolve$1; -Promise$3.reject = reject$1; -Promise$3._setScheduler = setScheduler; -Promise$3._setAsap = setAsap; -Promise$3._asap = asap; - -Promise$3.prototype = { - constructor: Promise$3, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - let result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - let author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: then, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function _catch(onRejection) { - return this.then(null, onRejection); - } -}; - -/*global self*/ -function polyfill$1() { - var local = undefined; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P) { - var promiseToString = null; - try { - promiseToString = Object.prototype.toString.call(P.resolve()); - } catch (e) { - // silently ignored - } - - if (promiseToString === '[object Promise]' && !P.cast) { - return; - } - } - - local.Promise = Promise$3; -} - -// Strange compat.. -Promise$3.polyfill = polyfill$1; -Promise$3.Promise = Promise$3; - -Promise$3.polyfill(); - -return Promise$3; - -}))); - diff --git a/packages/shims/src/index.js b/packages/shims/src/index.js index 9057c2dc00..330683cf2b 100644 --- a/packages/shims/src/index.js +++ b/packages/shims/src/index.js @@ -1,80 +1,123 @@ 'use strict'; -var shims = []; +(function() { -// Shim String.prototype.normalize -try { - var missing = []; + var shims = []; - // Some platforms are missing certain normalization forms - var forms = ["NFD", "NFC", "NFKD", "NFKC"]; - for (var i = 0; i < forms.length; i++) { - try { - if ("test".normalize(forms[i]) !== "test") { - throw new Error("failed to normalize"); + // Shim String.prototype.normalize + try { + var missing = []; + + // Some platforms are missing certain normalization forms + var forms = ["NFD", "NFC", "NFKD", "NFKC"]; + for (var i = 0; i < forms.length; i++) { + try { + if ("test".normalize(forms[i]) !== "test") { + throw new Error("failed to normalize"); + } + } catch(error) { + missing.push(forms[i]); } - } catch(error) { - missing.push(forms[i]); } + + if (missing.length) { + shims.push("String.prototype.normalize (missing: " + missing.join(", ") + ")"); + throw new Error('bad normalize'); + } + + // Some platforms have a native normalize, but it is broken; so we force our shim + if (String.fromCharCode(0xe9).normalize('NFD') !== String.fromCharCode(0x65, 0x0301)) { + shims.push("String.prototype.normalize (broken)"); + throw new Error('bad normalize'); + } + } catch (error) { + var unorm = require('./unorm.js'); + String.prototype.normalize = function(form) { + var func = unorm[(form || 'NFC').toLowerCase()]; + if (!func) { throw new RangeError('invalid form - ' + form); } + return func(this); + } + } + + // Shim atob and btoa + var base64 = require('./base64.js'); + if (!global.atob) { + shims.push("atob"); + global.atob = base64.atob; + } + if (!global.btoa) { + shims.push("btoa"); + global.btoa = base64.btoa; } - if (missing.length) { - shims.push("String.prototype.normalize (missing: " + missing.join(", ") + ")"); - throw new Error('bad normalize'); + // Shim ArrayBuffer.isView + if (!ArrayBuffer.isView) { + shims.push("ArrayBuffer.isView"); + ArrayBuffer.isView = function(obj) { + // @TODO: This should probably check various instanceof aswell + return !!(obj.buffer); + } } - // Some platforms have a native normalize, but it is broken; so we force our shim - if (String.fromCharCode(0xe9).normalize('NFD') !== String.fromCharCode(0x65, 0x0301)) { - shims.push("String.prototype.normalize (broken)"); - throw new Error('bad normalize'); + // Shim nextTick + if (!global.nextTick) { + shims.push("nextTick"); + global.nextTick = function (callback) { setTimeout(callback, 0); } } -} catch (error) { - var unorm = require('./unorm.js'); - String.prototype.normalize = function(form) { - var func = unorm[(form || 'NFC').toLowerCase()]; - if (!func) { throw new RangeError('invalid form - ' + form); } - return func(this); + + // Shim crypto.getRandomValues + // @TOOD: Investigate: https://github.com/brix/crypto-js/issues/7 + if (!global.crypto) { global.crypto = { }; } + if (!global.crypto.getRandomValues) { + shims.push("crypto.getRandomValues"); + console.log("WARNING: This environment is missing a secure random source; generated private keys may be at risk, think VERY carefully about not adding a better secure source."); + global.crypto.getRandomValues = function(buffer) { + var start = Math.floor((new Date()).getTime()) % buffer.length; + for (var i = 0; i < buffer.length; i++) { + buffer[(start + i) % buffer.length] = Math.floor(Math.random() * 256); + } + } } -} - -// Shim atob and btoa -var base64 = require('./base64.js'); -if (!global.atob) { - shims.push("atob"); - global.atob = base64.atob; -} -if (!global.btoa) { - shims.push("btoa"); - global.btoa = base64.btoa; -} - -// Shim Promise -// @TODO: Check first? -if (window.Promise == null) { - var promise = require('./es6-promise.auto.js'); -} - -// Shim ArrayBuffer.isView -if (!ArrayBuffer.isView) { - shims.push("ArrayBuffer.isView"); - ArrayBuffer.isView = function(obj) { - // @TODO: This should probably check various instanceof aswell - return !!(obj.buffer); + + // Shim FileReader.readAsArrayBuffer + // https://github.com/facebook/react-native/issues/21209 + try { + var fr = new FileReader(); + try { + fr.readAsArrayBuffer(new Blob([ "hello" ], { type: "text/plain" })); + return; + } catch (error) { } + + shims.push("FileReader.prototype.readAsArrayBuffer"); + FileReader.prototype.readAsArrayBuffer = function (blob) { + if (this.readyState === this.LOADING) throw new Error("InvalidStateError"); + this._setReadyState(this.LOADING); + this._result = null; + this._error = null; + var fr = new FileReader(); + fr.onloadend = () => { + var content = atob(fr.result.split(",").pop().trim()); + var buffer = new ArrayBuffer(content.length); + var view = new Uint8Array(buffer); + view.set(Array.from(content).map(c => c.charCodeAt(0))); + this._result = buffer; + this._setReadyState(this.DONE); + }; + fr.readAsDataURL(blob); + } + + } catch (error) { + console.log("Missing FileReader; unsupported platform"); } -} - -// Shim nextTick -if (!global.nextTick) { - shims.push("nextTick"); - global.nextTick = function (callback) { setTimeout(callback, 0); } -} - -if (shims.length) { - console.log("Shims Injected:"); - for (var i = 0; i < shims.length; i++) { - console.log(' - ' + shims[i]); + + if (shims.length) { + console.log("Shims Injected:"); + for (var i = 0; i < shims.length; i++) { + console.log(' - ' + shims[i]); + } } -} -// @TOOD: Add crypto.rand? -// - https://github.com/brix/crypto-js/issues/7 +})(); + + +