UNPKG

20.2 kBSource Map (JSON)View Raw
1{"version":3,"names":[],"mappings":"","sources":["packages/workbox-background-sync/browser.mjs"],"sourcesContent":["this.workbox = this.workbox || {};\nthis.workbox.backgroundSync = (function (DBWrapper_mjs,WorkboxError_mjs,logger_mjs,assert_mjs,getFriendlyURL_mjs) {\n 'use strict';\n\n try {\n self.workbox.v['workbox:background-sync:3.6.2'] = 1;\n } catch (e) {} // eslint-disable-line\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n const serializableProperties = ['method', 'referrer', 'referrerPolicy', 'mode', 'credentials', 'cache', 'redirect', 'integrity', 'keepalive'];\n\n /**\n * A class to make it easier to serialize and de-serialize requests so they\n * can be stored in IndexedDB.\n *\n * @private\n */\n class StorableRequest {\n /**\n * Converts a Request object to a plain object that can be structured\n * cloned or JSON-stringified.\n *\n * @param {Request} request\n * @return {Promise<StorableRequest>}\n *\n * @private\n */\n static fromRequest(request) {\n return babelHelpers.asyncToGenerator(function* () {\n const requestInit = { headers: {} };\n\n // Set the body if present.\n if (request.method !== 'GET') {\n // Use blob to support non-text request bodies,\n // and clone first in case the caller still needs the request.\n requestInit.body = yield request.clone().blob();\n }\n\n // Convert the headers from an iterable to an object.\n for (const [key, value] of request.headers.entries()) {\n requestInit.headers[key] = value;\n }\n\n // Add all other serializable request properties\n for (const prop of serializableProperties) {\n if (request[prop] !== undefined) {\n requestInit[prop] = request[prop];\n }\n }\n\n return new StorableRequest({ url: request.url, requestInit });\n })();\n }\n\n /**\n * Accepts a URL and RequestInit dictionary that can be used to create a\n * new Request object. A timestamp is also generated so consumers can\n * reference when the object was created.\n *\n * @param {Object} param1\n * @param {string} param1.url\n * @param {Object} param1.requestInit\n * See: https://fetch.spec.whatwg.org/#requestinit\n * @param {number} param1.timestamp The time the request was created,\n * defaulting to the current time if not specified.\n *\n * @private\n */\n constructor({ url, requestInit, timestamp = Date.now() }) {\n this.url = url;\n this.requestInit = requestInit;\n\n // \"Private\"\n this._timestamp = timestamp;\n }\n\n /**\n * Gets the private _timestamp property.\n *\n * @return {number}\n *\n * @private\n */\n get timestamp() {\n return this._timestamp;\n }\n\n /**\n * Coverts this instance to a plain Object.\n *\n * @return {Object}\n *\n * @private\n */\n toObject() {\n return {\n url: this.url,\n timestamp: this.timestamp,\n requestInit: this.requestInit\n };\n }\n\n /**\n * Converts this instance to a Request.\n *\n * @return {Request}\n *\n * @private\n */\n toRequest() {\n return new Request(this.url, this.requestInit);\n }\n\n /**\n * Creates and returns a deep clone of the instance.\n *\n * @return {StorableRequest}\n *\n * @private\n */\n clone() {\n const requestInit = Object.assign({}, this.requestInit);\n requestInit.headers = Object.assign({}, this.requestInit.headers);\n if (this.requestInit.body) {\n requestInit.body = this.requestInit.body.slice();\n }\n\n return new StorableRequest({\n url: this.url,\n timestamp: this.timestamp,\n requestInit\n });\n }\n }\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n const DB_NAME = 'workbox-background-sync';\n const OBJECT_STORE_NAME = 'requests';\n const INDEXED_PROP = 'queueName';\n const TAG_PREFIX = 'workbox-background-sync';\n const MAX_RETENTION_TIME = 60 * 24 * 7; // 7 days in minutes\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n /**\n * A class to manage storing requests from a Queue in IndexedbDB,\n * indexed by their queue name for easier access.\n *\n * @private\n */\n class QueueStore {\n /**\n * Associates this instance with a Queue instance, so entries added can be\n * identified by their queue name.\n *\n * @param {Queue} queue\n *\n * @private\n */\n constructor(queue) {\n this._queue = queue;\n this._db = new DBWrapper_mjs.DBWrapper(DB_NAME, 1, {\n onupgradeneeded: evt => evt.target.result.createObjectStore(OBJECT_STORE_NAME, { autoIncrement: true }).createIndex(INDEXED_PROP, INDEXED_PROP, { unique: false })\n });\n }\n\n /**\n * Takes a StorableRequest instance, converts it to an object and adds it\n * as an entry in the object store.\n *\n * @param {StorableRequest} storableRequest\n *\n * @private\n */\n addEntry(storableRequest) {\n var _this = this;\n\n return babelHelpers.asyncToGenerator(function* () {\n yield _this._db.add(OBJECT_STORE_NAME, {\n queueName: _this._queue.name,\n storableRequest: storableRequest.toObject()\n });\n })();\n }\n\n /**\n * Gets the oldest entry in the object store, removes it, and returns the\n * value as a StorableRequest instance. If no entry exists, it returns\n * undefined.\n *\n * @return {StorableRequest|undefined}\n *\n * @private\n */\n getAndRemoveOldestEntry() {\n var _this2 = this;\n\n return babelHelpers.asyncToGenerator(function* () {\n const [entry] = yield _this2._db.getAllMatching(OBJECT_STORE_NAME, {\n index: INDEXED_PROP,\n query: IDBKeyRange.only(_this2._queue.name),\n count: 1,\n includeKeys: true\n });\n\n if (entry) {\n yield _this2._db.delete(OBJECT_STORE_NAME, entry.primaryKey);\n return new StorableRequest(entry.value.storableRequest);\n }\n })();\n }\n }\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n const queueNames = new Set();\n\n /**\n * A class to manage storing failed requests in IndexedDB and retrying them\n * later. All parts of the storing and replaying process are observable via\n * callbacks.\n *\n * @memberof workbox.backgroundSync\n */\n class Queue {\n /**\n * Creates an instance of Queue with the given options\n *\n * @param {string} name The unique name for this queue. This name must be\n * unique as it's used to register sync events and store requests\n * in IndexedDB specific to this instance. An error will be thrown if\n * a duplicate name is detected.\n * @param {Object} [options]\n * @param {Object} [options.callbacks] Callbacks to observe the lifecycle of\n * queued requests. Use these to respond to or modify the requests\n * during the replay process.\n * @param {function(StorableRequest):undefined}\n * [options.callbacks.requestWillEnqueue]\n * Invoked immediately before the request is stored to IndexedDB. Use\n * this callback to modify request data at store time.\n * @param {function(StorableRequest):undefined}\n * [options.callbacks.requestWillReplay]\n * Invoked immediately before the request is re-fetched. Use this\n * callback to modify request data at fetch time.\n * @param {function(Array<StorableRequest>):undefined}\n * [options.callbacks.queueDidReplay]\n * Invoked after all requests in the queue have successfully replayed.\n * @param {number} [options.maxRetentionTime = 7 days] The amount of time (in\n * minutes) a request may be retried. After this amount of time has\n * passed, the request will be deleted from the queue.\n */\n constructor(name, {\n callbacks = {},\n maxRetentionTime = MAX_RETENTION_TIME\n } = {}) {\n // Ensure the store name is not already being used\n if (queueNames.has(name)) {\n throw new WorkboxError_mjs.WorkboxError('duplicate-queue-name', { name });\n } else {\n queueNames.add(name);\n }\n\n this._name = name;\n this._callbacks = callbacks;\n this._maxRetentionTime = maxRetentionTime;\n this._queueStore = new QueueStore(this);\n\n this._addSyncListener();\n }\n\n /**\n * @return {string}\n */\n get name() {\n return this._name;\n }\n\n /**\n * Stores the passed request into IndexedDB. The database used is\n * `workbox-background-sync` and the object store name is the same as\n * the name this instance was created with (to guarantee it's unique).\n *\n * @param {Request} request The request object to store.\n */\n addRequest(request) {\n var _this = this;\n\n return babelHelpers.asyncToGenerator(function* () {\n {\n assert_mjs.assert.isInstance(request, Request, {\n moduleName: 'workbox-background-sync',\n className: 'Queue',\n funcName: 'addRequest',\n paramName: 'request'\n });\n }\n\n const storableRequest = yield StorableRequest.fromRequest(request.clone());\n yield _this._runCallback('requestWillEnqueue', storableRequest);\n yield _this._queueStore.addEntry(storableRequest);\n yield _this._registerSync();\n {\n logger_mjs.logger.log(`Request for '${getFriendlyURL_mjs.getFriendlyURL(storableRequest.url)}' has been\n added to background sync queue '${_this._name}'.`);\n }\n })();\n }\n\n /**\n * Retrieves all stored requests in IndexedDB and retries them. If the\n * queue contained requests that were successfully replayed, the\n * `queueDidReplay` callback is invoked (which implies the queue is\n * now empty). If any of the requests fail, a new sync registration is\n * created to retry again later.\n */\n replayRequests() {\n var _this2 = this;\n\n return babelHelpers.asyncToGenerator(function* () {\n const now = Date.now();\n const replayedRequests = [];\n const failedRequests = [];\n\n let storableRequest;\n while (storableRequest = yield _this2._queueStore.getAndRemoveOldestEntry()) {\n // Make a copy so the unmodified request can be stored\n // in the event of a replay failure.\n const storableRequestClone = storableRequest.clone();\n\n // Ignore requests older than maxRetentionTime.\n const maxRetentionTimeInMs = _this2._maxRetentionTime * 60 * 1000;\n if (now - storableRequest.timestamp > maxRetentionTimeInMs) {\n continue;\n }\n\n yield _this2._runCallback('requestWillReplay', storableRequest);\n\n const replay = { request: storableRequest.toRequest() };\n\n try {\n // Clone the request before fetching so callbacks get an unused one.\n replay.response = yield fetch(replay.request.clone());\n {\n logger_mjs.logger.log(`Request for '${getFriendlyURL_mjs.getFriendlyURL(storableRequest.url)}'\n has been replayed`);\n }\n } catch (err) {\n {\n logger_mjs.logger.log(`Request for '${getFriendlyURL_mjs.getFriendlyURL(storableRequest.url)}'\n failed to replay`);\n }\n replay.error = err;\n failedRequests.push(storableRequestClone);\n }\n\n replayedRequests.push(replay);\n }\n\n yield _this2._runCallback('queueDidReplay', replayedRequests);\n\n // If any requests failed, put the failed requests back in the queue\n // and rethrow the failed requests count.\n if (failedRequests.length) {\n yield Promise.all(failedRequests.map(function (storableRequest) {\n return _this2._queueStore.addEntry(storableRequest);\n }));\n\n throw new WorkboxError_mjs.WorkboxError('queue-replay-failed', { name: _this2._name, count: failedRequests.length });\n }\n })();\n }\n\n /**\n * Runs the passed callback if it exists.\n *\n * @private\n * @param {string} name The name of the callback on this._callbacks.\n * @param {...*} args The arguments to invoke the callback with.\n */\n _runCallback(name, ...args) {\n var _this3 = this;\n\n return babelHelpers.asyncToGenerator(function* () {\n if (typeof _this3._callbacks[name] === 'function') {\n yield _this3._callbacks[name].apply(null, args);\n }\n })();\n }\n\n /**\n * In sync-supporting browsers, this adds a listener for the sync event.\n * In non-sync-supporting browsers, this will retry the queue on service\n * worker startup.\n *\n * @private\n */\n _addSyncListener() {\n if ('sync' in registration) {\n self.addEventListener('sync', event => {\n if (event.tag === `${TAG_PREFIX}:${this._name}`) {\n {\n logger_mjs.logger.log(`Background sync for tag '${event.tag}'\n has been received, starting replay now`);\n }\n event.waitUntil(this.replayRequests());\n }\n });\n } else {\n {\n logger_mjs.logger.log(`Background sync replaying without background sync event`);\n }\n // If the browser doesn't support background sync, retry\n // every time the service worker starts up as a fallback.\n this.replayRequests();\n }\n }\n\n /**\n * Registers a sync event with a tag unique to this instance.\n *\n * @private\n */\n _registerSync() {\n var _this4 = this;\n\n return babelHelpers.asyncToGenerator(function* () {\n if ('sync' in registration) {\n try {\n yield registration.sync.register(`${TAG_PREFIX}:${_this4._name}`);\n } catch (err) {\n // This means the registration failed for some reason, possibly due to\n // the user disabling it.\n {\n logger_mjs.logger.warn(`Unable to register sync event for '${_this4._name}'.`, err);\n }\n }\n }\n })();\n }\n\n /**\n * Returns the set of queue names. This is primarily used to reset the list\n * of queue names in tests.\n *\n * @return {Set}\n *\n * @private\n */\n static get _queueNames() {\n return queueNames;\n }\n }\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n /**\n * A class implementing the `fetchDidFail` lifecycle callback. This makes it\n * easier to add failed requests to a background sync Queue.\n *\n * @memberof workbox.backgroundSync\n */\n class Plugin {\n /**\n * @param {...*} queueArgs Args to forward to the composed Queue instance.\n * See the [Queue]{@link workbox.backgroundSync.Queue} documentation for\n * parameter details.\n */\n constructor(...queueArgs) {\n this._queue = new Queue(...queueArgs);\n this.fetchDidFail = this.fetchDidFail.bind(this);\n }\n\n /**\n * @param {Object} options\n * @param {Request} options.request\n * @private\n */\n fetchDidFail({ request }) {\n var _this = this;\n\n return babelHelpers.asyncToGenerator(function* () {\n yield _this._queue.addRequest(request);\n })();\n }\n }\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n var publicAPI = /*#__PURE__*/Object.freeze({\n Queue: Queue,\n Plugin: Plugin\n });\n\n /*\n Copyright 2017 Google Inc. All Rights Reserved.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\n return publicAPI;\n\n}(workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private,workbox.core._private));\n"],"file":"workbox-background-sync.dev.js"}
\No newline at end of file