Socket
Socket
Sign inDemoInstall

workbox-background-sync

Package Overview
Dependencies
Maintainers
7
Versions
97
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

workbox-background-sync - npm Package Compare versions

Comparing version 7.0.0 to 7.1.0

269

build/workbox-background-sync.dev.js

@@ -6,6 +6,5 @@ this.workbox = this.workbox || {};

function _extends() {
_extends = Object.assign || function (target) {
_extends = Object.assign ? Object.assign.bind() : function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {

@@ -17,6 +16,4 @@ if (Object.prototype.hasOwnProperty.call(source, key)) {

}
return target;
};
return _extends.apply(this, arguments);

@@ -26,15 +23,12 @@ }

const instanceOfAny = (object, constructors) => constructors.some(c => object instanceof c);
let idbProxyableTypes;
let cursorAdvanceMethods; // This is a function to prevent it throwing up in node environments.
let cursorAdvanceMethods;
// This is a function to prevent it throwing up in node environments.
function getIdbProxyableTypes() {
return idbProxyableTypes || (idbProxyableTypes = [IDBDatabase, IDBObjectStore, IDBIndex, IDBCursor, IDBTransaction]);
} // This is a function to prevent it throwing up in node environments.
}
// This is a function to prevent it throwing up in node environments.
function getCursorAdvanceMethods() {
return cursorAdvanceMethods || (cursorAdvanceMethods = [IDBCursor.prototype.advance, IDBCursor.prototype.continue, IDBCursor.prototype.continuePrimaryKey]);
}
const cursorRequestMap = new WeakMap();

@@ -45,3 +39,2 @@ const transactionDoneMap = new WeakMap();

const reverseTransformCache = new WeakMap();
function promisifyRequest(request) {

@@ -53,3 +46,2 @@ const promise = new Promise((resolve, reject) => {

};
const success = () => {

@@ -59,3 +51,2 @@ resolve(wrap(request.result));

};
const error = () => {

@@ -65,3 +56,2 @@ reject(request.error);

};
request.addEventListener('success', success);

@@ -75,11 +65,10 @@ request.addEventListener('error', error);

cursorRequestMap.set(value, request);
} // Catching to avoid "Uncaught Promise exceptions"
}).catch(() => {}); // This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
}
// Catching to avoid "Uncaught Promise exceptions"
}).catch(() => {});
// This mapping exists in reverseTransformCache but doesn't doesn't exist in transformCache. This
// is because we create many promises from a single IDBRequest.
reverseTransformCache.set(promise, request);
return promise;
}
function cacheDonePromiseForTransaction(tx) {

@@ -94,3 +83,2 @@ // Early bail if we've already created a done promise for this transaction.

};
const complete = () => {

@@ -100,3 +88,2 @@ resolve();

};
const error = () => {

@@ -106,11 +93,9 @@ reject(tx.error || new DOMException('AbortError', 'AbortError'));

};
tx.addEventListener('complete', complete);
tx.addEventListener('error', error);
tx.addEventListener('abort', error);
}); // Cache it for later retrieval.
});
// Cache it for later retrieval.
transactionDoneMap.set(tx, done);
}
let idbProxyTraps = {

@@ -120,18 +105,15 @@ get(target, prop, receiver) {

// Special handling for transaction.done.
if (prop === 'done') return transactionDoneMap.get(target); // Polyfill for objectStoreNames because of Edge.
if (prop === 'done') return transactionDoneMap.get(target);
// Polyfill for objectStoreNames because of Edge.
if (prop === 'objectStoreNames') {
return target.objectStoreNames || transactionStoreNamesMap.get(target);
} // Make tx.store return the only store in the transaction, or undefined if there are many.
}
// Make tx.store return the only store in the transaction, or undefined if there are many.
if (prop === 'store') {
return receiver.objectStoreNames[1] ? undefined : receiver.objectStore(receiver.objectStoreNames[0]);
}
} // Else transform whatever we get back.
}
// Else transform whatever we get back.
return wrap(target[prop]);
},
set(target, prop, value) {

@@ -141,3 +123,2 @@ target[prop] = value;

},
has(target, prop) {

@@ -147,12 +128,8 @@ if (target instanceof IDBTransaction && (prop === 'done' || prop === 'store')) {

}
return prop in target;
}
};
function replaceTraps(callback) {
idbProxyTraps = callback(idbProxyTraps);
}
function wrapFunction(func) {

@@ -168,3 +145,4 @@ // Due to expected object equality (which is enforced by the caching in `wrap`), we

};
} // Cursor methods are special, as the behaviour is a little more different to standard IDB. In
}
// Cursor methods are special, as the behaviour is a little more different to standard IDB. In
// IDB, you advance the cursor and wait for a new 'success' on the IDBRequest that gave you the

@@ -174,4 +152,2 @@ // cursor. It's kinda like a promise that can resolve with many values. That doesn't make sense

// undefined if the end of the cursor has been reached.
if (getCursorAdvanceMethods().includes(func)) {

@@ -185,3 +161,2 @@ return function (...args) {

}
return function (...args) {

@@ -193,23 +168,21 @@ // Calling the original function with the proxy as 'this' causes ILLEGAL INVOCATION, so we use

}
function transformCachableValue(value) {
if (typeof value === 'function') return wrapFunction(value); // This doesn't return, it just creates a 'done' promise for the transaction,
if (typeof value === 'function') return wrapFunction(value);
// This doesn't return, it just creates a 'done' promise for the transaction,
// which is later returned for transaction.done (see idbObjectHandler).
if (value instanceof IDBTransaction) cacheDonePromiseForTransaction(value);
if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps); // Return the same value back if we're not going to transform it.
if (instanceOfAny(value, getIdbProxyableTypes())) return new Proxy(value, idbProxyTraps);
// Return the same value back if we're not going to transform it.
return value;
}
function wrap(value) {
// We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
// IDB is weird and a single IDBRequest can yield many responses, so these can't be cached.
if (value instanceof IDBRequest) return promisifyRequest(value); // If we've already transformed this value before, reuse the transformed value.
if (value instanceof IDBRequest) return promisifyRequest(value);
// If we've already transformed this value before, reuse the transformed value.
// This is faster, but it also provides object equality.
if (transformCache.has(value)) return transformCache.get(value);
const newValue = transformCachableValue(value); // Not all types are transformed.
const newValue = transformCachableValue(value);
// Not all types are transformed.
// These may be primitive types, so they can't be WeakMap keys.
if (newValue !== value) {

@@ -219,6 +192,4 @@ transformCache.set(value, newValue);

}
return newValue;
}
const unwrap = value => reverseTransformCache.get(value);

@@ -233,3 +204,2 @@

*/
function openDB(name, version, {

@@ -243,3 +213,2 @@ blocked,

const openPromise = wrap(request);
if (upgrade) {

@@ -250,3 +219,2 @@ request.addEventListener('upgradeneeded', event => {

}
if (blocked) request.addEventListener('blocked', () => blocked());

@@ -259,7 +227,5 @@ openPromise.then(db => {

}
const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count'];
const writeMethods = ['put', 'add', 'delete', 'clear'];
const cachedMethods = new Map();
function getMethod(target, prop) {

@@ -269,3 +235,2 @@ if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === 'string')) {

}
if (cachedMethods.get(prop)) return cachedMethods.get(prop);

@@ -275,8 +240,7 @@ const targetFuncName = prop.replace(/FromIndex$/, '');

const isWrite = writeMethods.includes(targetFuncName);
if ( // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
if (
// Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
!(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))) {
return;
}
const method = async function (storeName, ...args) {

@@ -286,3 +250,4 @@ // isWrite ? 'readwrite' : undefined gzipps better, but fails in Edge :(

let target = tx.store;
if (useIndex) target = target.index(args.shift()); // Must reject if op rejects.
if (useIndex) target = target.index(args.shift());
// Must reject if op rejects.
// If it's a write operation, must reject if tx.done rejects.

@@ -292,10 +257,7 @@ // Must reject with op rejection first.

// Must handle both promises (no unhandled rejections)
return (await Promise.all([target[targetFuncName](...args), isWrite && tx.done]))[0];
};
cachedMethods.set(prop, method);
return method;
}
replaceTraps(oldTraps => _extends({}, oldTraps, {

@@ -306,2 +268,3 @@ get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),

// @ts-ignore
try {

@@ -329,3 +292,2 @@ self['workbox:background-sync:7.0.0'] && _();

*/
class QueueDb {

@@ -340,4 +302,2 @@ constructor() {

*/
async addEntry(entry) {

@@ -356,4 +316,2 @@ const db = await this.getDb();

*/
async getFirstEntryId() {

@@ -370,4 +328,2 @@ const db = await this.getDb();

*/
async getAllEntriesByQueueName(queueName) {

@@ -384,4 +340,2 @@ const db = await this.getDb();

*/
async getEntryCountByQueueName(queueName) {

@@ -396,4 +350,2 @@ const db = await this.getDb();

*/
async deleteEntry(id) {

@@ -408,4 +360,2 @@ const db = await this.getDb();

*/
async getFirstEntryByQueueName(queueName) {

@@ -419,4 +369,2 @@ return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'next');

*/
async getLastEntryByQueueName(queueName) {

@@ -434,4 +382,2 @@ return await this.getEndEntryFromIndex(IDBKeyRange.only(queueName), 'prev');

*/
async getEndEntryFromIndex(query, direction) {

@@ -447,4 +393,2 @@ const db = await this.getDb();

*/
async getDb() {

@@ -456,3 +400,2 @@ if (!this._db) {

}
return this._db;

@@ -467,4 +410,2 @@ }

*/
_upgradeDb(db, oldVersion) {

@@ -476,3 +417,2 @@ if (oldVersion > 0 && oldVersion < DB_VERSION) {

}
const objStore = db.createObjectStore(REQUEST_OBJECT_STORE_NAME, {

@@ -486,3 +426,2 @@ autoIncrement: true,

}
}

@@ -504,3 +443,2 @@

*/
class QueueStore {

@@ -525,4 +463,2 @@ /**

*/
async pushEntry(entry) {

@@ -542,5 +478,4 @@ {

});
} // Don't specify an ID since one is automatically generated.
}
// Don't specify an ID since one is automatically generated.
delete entry.id;

@@ -558,4 +493,2 @@ entry.queueName = this._queueName;

*/
async unshiftEntry(entry) {

@@ -576,5 +509,3 @@ {

}
const firstId = await this._queueDb.getFirstEntryId();
if (firstId) {

@@ -587,3 +518,2 @@ // Pick an ID one less than the lowest ID in the object store.

}
entry.queueName = this._queueName;

@@ -597,4 +527,2 @@ await this._queueDb.addEntry(entry);

*/
async popEntry() {

@@ -608,4 +536,2 @@ return this._removeEntry(await this._queueDb.getLastEntryByQueueName(this._queueName));

*/
async shiftEntry() {

@@ -620,4 +546,2 @@ return this._removeEntry(await this._queueDb.getFirstEntryByQueueName(this._queueName));

*/
async getAll() {

@@ -632,4 +556,2 @@ return await this._queueDb.getAllEntriesByQueueName(this._queueName);

*/
async size() {

@@ -648,4 +570,2 @@ return await this._queueDb.getEntryCountByQueueName(this._queueName);

*/
async deleteEntry(id) {

@@ -661,4 +581,2 @@ await this._queueDb.deleteEntry(id);

*/
async _removeEntry(entry) {

@@ -668,6 +586,4 @@ if (entry) {

}
return entry;
}
}

@@ -690,3 +606,2 @@

*/
class StorableRequest {

@@ -704,4 +619,4 @@ /**

headers: {}
}; // Set the body if present.
};
// Set the body if present.
if (request.method !== 'GET') {

@@ -713,10 +628,8 @@ // Use ArrayBuffer to support non-text request bodies.

requestData.body = await request.clone().arrayBuffer();
} // Convert the headers from an iterable to an object.
}
// Convert the headers from an iterable to an object.
for (const [key, value] of request.headers.entries()) {
requestData.headers[key] = value;
} // Add all other serializable request properties
}
// Add all other serializable request properties
for (const prop of serializableProperties) {

@@ -727,3 +640,2 @@ if (request[prop] !== undefined) {

}
return new StorableRequest(requestData);

@@ -739,4 +651,2 @@ }

*/
constructor(requestData) {

@@ -756,10 +666,8 @@ {

});
} // If the request's mode is `navigate`, convert it to `same-origin` since
}
// If the request's mode is `navigate`, convert it to `same-origin` since
// navigation requests can't be constructed via script.
if (requestData['mode'] === 'navigate') {
requestData['mode'] = 'same-origin';
}
this._requestData = requestData;

@@ -772,12 +680,8 @@ }

*/
toObject() {
const requestData = Object.assign({}, this._requestData);
requestData.headers = Object.assign({}, this._requestData.headers);
if (requestData.body) {
requestData.body = requestData.body.slice(0);
}
return requestData;

@@ -790,4 +694,2 @@ }

*/
toRequest() {

@@ -801,8 +703,5 @@ return new Request(this._requestData.url, this._requestData);

*/
clone() {
return new StorableRequest(this.toObject());
}
}

@@ -819,3 +718,2 @@

const MAX_RETENTION_TIME = 60 * 24 * 7; // 7 days in minutes
const queueNames = new Set();

@@ -831,3 +729,2 @@ /**

*/
const convertEntry = queueStoreEntry => {

@@ -838,7 +735,5 @@ const queueEntry = {

};
if (queueStoreEntry.metadata) {
queueEntry.metadata = queueStoreEntry.metadata;
}
return queueEntry;

@@ -853,4 +748,2 @@ };

*/
class Queue {

@@ -888,4 +781,4 @@ /**

this._syncInProgress = false;
this._requestsAddedDuringSync = false; // Ensure the store name is not already being used
this._requestsAddedDuringSync = false;
// Ensure the store name is not already being used
if (queueNames.has(name)) {

@@ -898,3 +791,2 @@ throw new WorkboxError_js.WorkboxError('duplicate-queue-name', {

}
this._name = name;

@@ -905,3 +797,2 @@ this._onSync = onSync || this.replayRequests;

this._queueStore = new QueueStore(this._name);
this._addSyncListener();

@@ -912,4 +803,2 @@ }

*/
get name() {

@@ -934,4 +823,2 @@ return this._name;

*/
async pushRequest(entry) {

@@ -952,3 +839,2 @@ {

}
await this._addRequest(entry, 'push');

@@ -972,4 +858,2 @@ }

*/
async unshiftRequest(entry) {

@@ -990,3 +874,2 @@ {

}
await this._addRequest(entry, 'unshift');

@@ -1001,4 +884,2 @@ }

*/
async popRequest() {

@@ -1014,4 +895,2 @@ return this._removeRequest('pop');

*/
async shiftRequest() {

@@ -1026,4 +905,2 @@ return this._removeRequest('shift');

*/
async getAll() {

@@ -1033,3 +910,2 @@ const allEntries = await this._queueStore.getAll();

const unexpiredEntries = [];
for (const entry of allEntries) {

@@ -1039,3 +915,2 @@ // Ignore requests older than maxRetentionTime. Call this function

const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000;
if (now - entry.timestamp > maxRetentionTimeInMs) {

@@ -1047,3 +922,2 @@ await this._queueStore.deleteEntry(entry.id);

}
return unexpiredEntries;

@@ -1057,4 +931,2 @@ }

*/
async size() {

@@ -1073,4 +945,2 @@ return await this._queueStore.size();

*/
async _addRequest({

@@ -1085,8 +955,7 @@ request,

timestamp
}; // Only include metadata if it's present.
};
// Only include metadata if it's present.
if (metadata) {
entry.metadata = metadata;
}
switch (operation) {

@@ -1096,3 +965,2 @@ case 'push':

break;
case 'unshift':

@@ -1102,10 +970,8 @@ await this._queueStore.unshiftEntry(entry);

}
{
logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(request.url)}' has ` + `been added to background sync queue '${this._name}'.`);
} // Don't register for a sync if we're in the middle of a sync. Instead,
}
// Don't register for a sync if we're in the middle of a sync. Instead,
// we wait until the sync is complete and call register if
// `this._requestsAddedDuringSync` is true.
if (this._syncInProgress) {

@@ -1125,8 +991,5 @@ this._requestsAddedDuringSync = true;

*/
async _removeRequest(operation) {
const now = Date.now();
let entry;
switch (operation) {

@@ -1136,3 +999,2 @@ case 'pop':

break;
case 'shift':

@@ -1142,3 +1004,2 @@ entry = await this._queueStore.shiftEntry();

}
if (entry) {

@@ -1148,7 +1009,5 @@ // Ignore requests older than maxRetentionTime. Call this function

const maxRetentionTimeInMs = this._maxRetentionTime * 60 * 1000;
if (now - entry.timestamp > maxRetentionTimeInMs) {
return this._removeRequest(operation);
}
return convertEntry(entry);

@@ -1164,11 +1023,7 @@ } else {

*/
async replayRequests() {
let entry;
while (entry = await this.shiftRequest()) {
try {
await fetch(entry.request.clone());
if ("dev" !== 'production') {

@@ -1179,7 +1034,5 @@ logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(entry.request.url)}' ` + `has been replayed in queue '${this._name}'`);

await this.unshiftRequest(entry);
{
logger_js.logger.log(`Request for '${getFriendlyURL_js.getFriendlyURL(entry.request.url)}' ` + `failed to replay, putting it back in queue '${this._name}'`);
}
throw new WorkboxError_js.WorkboxError('queue-replay-failed', {

@@ -1190,3 +1043,2 @@ name: this._name

}
{

@@ -1199,4 +1051,2 @@ logger_js.logger.log(`All requests in queue '${this.name}' have successfully ` + `replayed; the queue is now empty!`);

*/
async registerSync() {

@@ -1223,4 +1073,2 @@ // See https://github.com/GoogleChrome/workbox/issues/2393

*/
_addSyncListener() {

@@ -1234,7 +1082,5 @@ // See https://github.com/GoogleChrome/workbox/issues/2393

}
const syncComplete = async () => {
this._syncInProgress = true;
let syncError;
try {

@@ -1246,5 +1092,5 @@ await this._onSync({

if (error instanceof Error) {
syncError = error; // Rethrow the error. Note: the logic in the finally clause
syncError = error;
// Rethrow the error. Note: the logic in the finally clause
// will run before this gets rethrown.
throw syncError;

@@ -1261,3 +1107,2 @@ }

}
this._syncInProgress = false;

@@ -1267,3 +1112,2 @@ this._requestsAddedDuringSync = false;

};
event.waitUntil(syncComplete());

@@ -1275,7 +1119,6 @@ }

logger_js.logger.log(`Background sync replaying without background sync event`);
} // If the browser doesn't support background sync, or the developer has
}
// If the browser doesn't support background sync, or the developer has
// opted-in to not using it, retry every time the service worker starts up
// as a fallback.
void this._onSync({

@@ -1294,8 +1137,5 @@ queue: this

*/
static get _queueNames() {
return queueNames;
}
}

@@ -1316,3 +1156,2 @@

*/
class BackgroundSyncPlugin {

@@ -1339,6 +1178,4 @@ /**

};
this._queue = new Queue(name, options);
}
}

@@ -1353,3 +1190,3 @@

}({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private));
})({}, workbox.core._private, workbox.core._private, workbox.core._private, workbox.core._private);
//# sourceMappingURL=workbox-background-sync.dev.js.map

2

build/workbox-background-sync.prod.js

@@ -1,2 +0,2 @@

this.workbox=this.workbox||{},this.workbox.backgroundSync=function(t,e,s,n){"use strict";function r(){return r=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},r.apply(this,arguments)}const a=(t,e)=>e.some((e=>t instanceof e));let i,c;const o=new WeakMap,u=new WeakMap,h=new WeakMap,y=new WeakMap,w=new WeakMap;let f={get(t,e,s){if(t instanceof IDBTransaction){if("done"===e)return u.get(t);if("objectStoreNames"===e)return t.objectStoreNames||h.get(t);if("store"===e)return s.objectStoreNames[1]?void 0:s.objectStore(s.objectStoreNames[0])}return m(t[e])},set:(t,e,s)=>(t[e]=s,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function l(t){return t!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(c||(c=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(p(this),e),m(o.get(this))}:function(...e){return m(t.apply(p(this),e))}:function(e,...s){const n=t.call(p(this),e,...s);return h.set(n,e.sort?e.sort():[e]),m(n)}}function d(t){return"function"==typeof t?l(t):(t instanceof IDBTransaction&&function(t){if(u.has(t))return;const e=new Promise(((e,s)=>{const n=()=>{t.removeEventListener("complete",r),t.removeEventListener("error",a),t.removeEventListener("abort",a)},r=()=>{e(),n()},a=()=>{s(t.error||new DOMException("AbortError","AbortError")),n()};t.addEventListener("complete",r),t.addEventListener("error",a),t.addEventListener("abort",a)}));u.set(t,e)}(t),a(t,i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,f):t)}function m(t){if(t instanceof IDBRequest)return function(t){const e=new Promise(((e,s)=>{const n=()=>{t.removeEventListener("success",r),t.removeEventListener("error",a)},r=()=>{e(m(t.result)),n()},a=()=>{s(t.error),n()};t.addEventListener("success",r),t.addEventListener("error",a)}));return e.then((e=>{e instanceof IDBCursor&&o.set(e,t)})).catch((()=>{})),w.set(e,t),e}(t);if(y.has(t))return y.get(t);const e=d(t);return e!==t&&(y.set(t,e),w.set(e,t)),e}const p=t=>w.get(t);const g=["get","getKey","getAll","getAllKeys","count"],D=["put","add","delete","clear"],b=new Map;function B(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(b.get(e))return b.get(e);const s=e.replace(/FromIndex$/,""),n=e!==s,r=D.includes(s);if(!(s in(n?IDBIndex:IDBObjectStore).prototype)||!r&&!g.includes(s))return;const a=async function(t,...e){const a=this.transaction(t,r?"readwrite":"readonly");let i=a.store;return n&&(i=i.index(e.shift())),(await Promise.all([i[s](...e),r&&a.done]))[0]};return b.set(e,a),a}f=(t=>r({},t,{get:(e,s,n)=>B(e,s)||t.get(e,s,n),has:(e,s)=>!!B(e,s)||t.has(e,s)}))(f);try{self["workbox:background-sync:7.0.0"]&&_()}catch(t){}const I="requests",q="queueName";class k{constructor(){this.t=null}async addEntry(t){const e=(await this.getDb()).transaction(I,"readwrite",{durability:"relaxed"});await e.store.add(t),await e.done}async getFirstEntryId(){const t=await this.getDb(),e=await t.transaction(I).store.openCursor();return null==e?void 0:e.value.id}async getAllEntriesByQueueName(t){const e=await this.getDb(),s=await e.getAllFromIndex(I,q,IDBKeyRange.only(t));return s||new Array}async getEntryCountByQueueName(t){return(await this.getDb()).countFromIndex(I,q,IDBKeyRange.only(t))}async deleteEntry(t){const e=await this.getDb();await e.delete(I,t)}async getFirstEntryByQueueName(t){return await this.getEndEntryFromIndex(IDBKeyRange.only(t),"next")}async getLastEntryByQueueName(t){return await this.getEndEntryFromIndex(IDBKeyRange.only(t),"prev")}async getEndEntryFromIndex(t,e){const s=await this.getDb(),n=await s.transaction(I).store.index(q).openCursor(t,e);return null==n?void 0:n.value}async getDb(){return this.t||(this.t=await function(t,e,{blocked:s,upgrade:n,blocking:r,terminated:a}={}){const i=indexedDB.open(t,e),c=m(i);return n&&i.addEventListener("upgradeneeded",(t=>{n(m(i.result),t.oldVersion,t.newVersion,m(i.transaction))})),s&&i.addEventListener("blocked",(()=>s())),c.then((t=>{a&&t.addEventListener("close",(()=>a())),r&&t.addEventListener("versionchange",(()=>r()))})).catch((()=>{})),c}("workbox-background-sync",3,{upgrade:this.i})),this.t}i(t,e){e>0&&e<3&&t.objectStoreNames.contains(I)&&t.deleteObjectStore(I);t.createObjectStore(I,{autoIncrement:!0,keyPath:"id"}).createIndex(q,q,{unique:!1})}}class E{constructor(t){this.o=t,this.u=new k}async pushEntry(t){delete t.id,t.queueName=this.o,await this.u.addEntry(t)}async unshiftEntry(t){const e=await this.u.getFirstEntryId();e?t.id=e-1:delete t.id,t.queueName=this.o,await this.u.addEntry(t)}async popEntry(){return this.h(await this.u.getLastEntryByQueueName(this.o))}async shiftEntry(){return this.h(await this.u.getFirstEntryByQueueName(this.o))}async getAll(){return await this.u.getAllEntriesByQueueName(this.o)}async size(){return await this.u.getEntryCountByQueueName(this.o)}async deleteEntry(t){await this.u.deleteEntry(t)}async h(t){return t&&await this.deleteEntry(t.id),t}}const R=["method","referrer","referrerPolicy","mode","credentials","cache","redirect","integrity","keepalive"];class x{static async fromRequest(t){const e={url:t.url,headers:{}};"GET"!==t.method&&(e.body=await t.clone().arrayBuffer());for(const[s,n]of t.headers.entries())e.headers[s]=n;for(const s of R)void 0!==t[s]&&(e[s]=t[s]);return new x(e)}constructor(t){"navigate"===t.mode&&(t.mode="same-origin"),this.l=t}toObject(){const t=Object.assign({},this.l);return t.headers=Object.assign({},this.l.headers),t.body&&(t.body=t.body.slice(0)),t}toRequest(){return new Request(this.l.url,this.l)}clone(){return new x(this.toObject())}}const v="workbox-background-sync",j=new Set,S=t=>{const e={request:new x(t.requestData).toRequest(),timestamp:t.timestamp};return t.metadata&&(e.metadata=t.metadata),e};class A{constructor(t,{forceSyncFallback:s,onSync:n,maxRetentionTime:r}={}){if(this.m=!1,this.p=!1,j.has(t))throw new e.WorkboxError("duplicate-queue-name",{name:t});j.add(t),this.g=t,this.D=n||this.replayRequests,this.B=r||10080,this.I=Boolean(s),this.q=new E(this.g),this.k()}get name(){return this.g}async pushRequest(t){await this.R(t,"push")}async unshiftRequest(t){await this.R(t,"unshift")}async popRequest(){return this.v("pop")}async shiftRequest(){return this.v("shift")}async getAll(){const t=await this.q.getAll(),e=Date.now(),s=[];for(const n of t){const t=60*this.B*1e3;e-n.timestamp>t?await this.q.deleteEntry(n.id):s.push(S(n))}return s}async size(){return await this.q.size()}async R({request:t,metadata:e,timestamp:s=Date.now()},n){const r={requestData:(await x.fromRequest(t.clone())).toObject(),timestamp:s};switch(e&&(r.metadata=e),n){case"push":await this.q.pushEntry(r);break;case"unshift":await this.q.unshiftEntry(r)}this.m?this.p=!0:await this.registerSync()}async v(t){const e=Date.now();let s;switch(t){case"pop":s=await this.q.popEntry();break;case"shift":s=await this.q.shiftEntry()}if(s){const n=60*this.B*1e3;return e-s.timestamp>n?this.v(t):S(s)}}async replayRequests(){let t;for(;t=await this.shiftRequest();)try{await fetch(t.request.clone())}catch(s){throw await this.unshiftRequest(t),new e.WorkboxError("queue-replay-failed",{name:this.g})}}async registerSync(){if("sync"in self.registration&&!this.I)try{await self.registration.sync.register(`${v}:${this.g}`)}catch(t){}}k(){"sync"in self.registration&&!this.I?self.addEventListener("sync",(t=>{if(t.tag===`${v}:${this.g}`){const e=async()=>{let e;this.m=!0;try{await this.D({queue:this})}catch(t){if(t instanceof Error)throw e=t,e}finally{!this.p||e&&!t.lastChance||await this.registerSync(),this.m=!1,this.p=!1}};t.waitUntil(e())}})):this.D({queue:this})}static get j(){return j}}return t.BackgroundSyncPlugin=class{constructor(t,e){this.fetchDidFail=async({request:t})=>{await this.S.pushRequest({request:t})},this.S=new A(t,e)}},t.Queue=A,t.QueueStore=E,t.StorableRequest=x,t}({},workbox.core._private,workbox.core._private,workbox.core._private);
this.workbox=this.workbox||{},this.workbox.backgroundSync=function(t,e,s,n){"use strict";function r(){return r=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var s=arguments[e];for(var n in s)Object.prototype.hasOwnProperty.call(s,n)&&(t[n]=s[n])}return t},r.apply(this,arguments)}const a=(t,e)=>e.some((e=>t instanceof e));let i,c;const o=new WeakMap,u=new WeakMap,h=new WeakMap,y=new WeakMap,w=new WeakMap;let f={get(t,e,s){if(t instanceof IDBTransaction){if("done"===e)return u.get(t);if("objectStoreNames"===e)return t.objectStoreNames||h.get(t);if("store"===e)return s.objectStoreNames[1]?void 0:s.objectStore(s.objectStoreNames[0])}return m(t[e])},set:(t,e,s)=>(t[e]=s,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function l(t){return t!==IDBDatabase.prototype.transaction||"objectStoreNames"in IDBTransaction.prototype?(c||(c=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(p(this),e),m(o.get(this))}:function(...e){return m(t.apply(p(this),e))}:function(e,...s){const n=t.call(p(this),e,...s);return h.set(n,e.sort?e.sort():[e]),m(n)}}function d(t){return"function"==typeof t?l(t):(t instanceof IDBTransaction&&function(t){if(u.has(t))return;const e=new Promise(((e,s)=>{const n=()=>{t.removeEventListener("complete",r),t.removeEventListener("error",a),t.removeEventListener("abort",a)},r=()=>{e(),n()},a=()=>{s(t.error||new DOMException("AbortError","AbortError")),n()};t.addEventListener("complete",r),t.addEventListener("error",a),t.addEventListener("abort",a)}));u.set(t,e)}(t),a(t,i||(i=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,f):t)}function m(t){if(t instanceof IDBRequest)return function(t){const e=new Promise(((e,s)=>{const n=()=>{t.removeEventListener("success",r),t.removeEventListener("error",a)},r=()=>{e(m(t.result)),n()},a=()=>{s(t.error),n()};t.addEventListener("success",r),t.addEventListener("error",a)}));return e.then((e=>{e instanceof IDBCursor&&o.set(e,t)})).catch((()=>{})),w.set(e,t),e}(t);if(y.has(t))return y.get(t);const e=d(t);return e!==t&&(y.set(t,e),w.set(e,t)),e}const p=t=>w.get(t);const g=["get","getKey","getAll","getAllKeys","count"],b=["put","add","delete","clear"],D=new Map;function B(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(D.get(e))return D.get(e);const s=e.replace(/FromIndex$/,""),n=e!==s,r=b.includes(s);if(!(s in(n?IDBIndex:IDBObjectStore).prototype)||!r&&!g.includes(s))return;const a=async function(t,...e){const a=this.transaction(t,r?"readwrite":"readonly");let i=a.store;return n&&(i=i.index(e.shift())),(await Promise.all([i[s](...e),r&&a.done]))[0]};return D.set(e,a),a}f=(t=>r({},t,{get:(e,s,n)=>B(e,s)||t.get(e,s,n),has:(e,s)=>!!B(e,s)||t.has(e,s)}))(f);try{self["workbox:background-sync:7.0.0"]&&_()}catch(t){}const I="requests",q="queueName";class k{constructor(){this.t=null}async addEntry(t){const e=(await this.getDb()).transaction(I,"readwrite",{durability:"relaxed"});await e.store.add(t),await e.done}async getFirstEntryId(){const t=await this.getDb(),e=await t.transaction(I).store.openCursor();return null==e?void 0:e.value.id}async getAllEntriesByQueueName(t){const e=await this.getDb(),s=await e.getAllFromIndex(I,q,IDBKeyRange.only(t));return s||new Array}async getEntryCountByQueueName(t){return(await this.getDb()).countFromIndex(I,q,IDBKeyRange.only(t))}async deleteEntry(t){const e=await this.getDb();await e.delete(I,t)}async getFirstEntryByQueueName(t){return await this.getEndEntryFromIndex(IDBKeyRange.only(t),"next")}async getLastEntryByQueueName(t){return await this.getEndEntryFromIndex(IDBKeyRange.only(t),"prev")}async getEndEntryFromIndex(t,e){const s=await this.getDb(),n=await s.transaction(I).store.index(q).openCursor(t,e);return null==n?void 0:n.value}async getDb(){return this.t||(this.t=await function(t,e,{blocked:s,upgrade:n,blocking:r,terminated:a}={}){const i=indexedDB.open(t,e),c=m(i);return n&&i.addEventListener("upgradeneeded",(t=>{n(m(i.result),t.oldVersion,t.newVersion,m(i.transaction))})),s&&i.addEventListener("blocked",(()=>s())),c.then((t=>{a&&t.addEventListener("close",(()=>a())),r&&t.addEventListener("versionchange",(()=>r()))})).catch((()=>{})),c}("workbox-background-sync",3,{upgrade:this.i})),this.t}i(t,e){e>0&&e<3&&t.objectStoreNames.contains(I)&&t.deleteObjectStore(I);t.createObjectStore(I,{autoIncrement:!0,keyPath:"id"}).createIndex(q,q,{unique:!1})}}class E{constructor(t){this.o=t,this.u=new k}async pushEntry(t){delete t.id,t.queueName=this.o,await this.u.addEntry(t)}async unshiftEntry(t){const e=await this.u.getFirstEntryId();e?t.id=e-1:delete t.id,t.queueName=this.o,await this.u.addEntry(t)}async popEntry(){return this.h(await this.u.getLastEntryByQueueName(this.o))}async shiftEntry(){return this.h(await this.u.getFirstEntryByQueueName(this.o))}async getAll(){return await this.u.getAllEntriesByQueueName(this.o)}async size(){return await this.u.getEntryCountByQueueName(this.o)}async deleteEntry(t){await this.u.deleteEntry(t)}async h(t){return t&&await this.deleteEntry(t.id),t}}const R=["method","referrer","referrerPolicy","mode","credentials","cache","redirect","integrity","keepalive"];class x{static async fromRequest(t){const e={url:t.url,headers:{}};"GET"!==t.method&&(e.body=await t.clone().arrayBuffer());for(const[s,n]of t.headers.entries())e.headers[s]=n;for(const s of R)void 0!==t[s]&&(e[s]=t[s]);return new x(e)}constructor(t){"navigate"===t.mode&&(t.mode="same-origin"),this.l=t}toObject(){const t=Object.assign({},this.l);return t.headers=Object.assign({},this.l.headers),t.body&&(t.body=t.body.slice(0)),t}toRequest(){return new Request(this.l.url,this.l)}clone(){return new x(this.toObject())}}const v="workbox-background-sync",j=new Set,O=t=>{const e={request:new x(t.requestData).toRequest(),timestamp:t.timestamp};return t.metadata&&(e.metadata=t.metadata),e};class S{constructor(t,{forceSyncFallback:s,onSync:n,maxRetentionTime:r}={}){if(this.m=!1,this.p=!1,j.has(t))throw new e.WorkboxError("duplicate-queue-name",{name:t});j.add(t),this.g=t,this.D=n||this.replayRequests,this.B=r||10080,this.I=Boolean(s),this.q=new E(this.g),this.k()}get name(){return this.g}async pushRequest(t){await this.R(t,"push")}async unshiftRequest(t){await this.R(t,"unshift")}async popRequest(){return this.v("pop")}async shiftRequest(){return this.v("shift")}async getAll(){const t=await this.q.getAll(),e=Date.now(),s=[];for(const n of t){const t=60*this.B*1e3;e-n.timestamp>t?await this.q.deleteEntry(n.id):s.push(O(n))}return s}async size(){return await this.q.size()}async R({request:t,metadata:e,timestamp:s=Date.now()},n){const r={requestData:(await x.fromRequest(t.clone())).toObject(),timestamp:s};switch(e&&(r.metadata=e),n){case"push":await this.q.pushEntry(r);break;case"unshift":await this.q.unshiftEntry(r)}this.m?this.p=!0:await this.registerSync()}async v(t){const e=Date.now();let s;switch(t){case"pop":s=await this.q.popEntry();break;case"shift":s=await this.q.shiftEntry()}if(s){const n=60*this.B*1e3;return e-s.timestamp>n?this.v(t):O(s)}}async replayRequests(){let t;for(;t=await this.shiftRequest();)try{await fetch(t.request.clone())}catch(s){throw await this.unshiftRequest(t),new e.WorkboxError("queue-replay-failed",{name:this.g})}}async registerSync(){if("sync"in self.registration&&!this.I)try{await self.registration.sync.register(`${v}:${this.g}`)}catch(t){}}k(){"sync"in self.registration&&!this.I?self.addEventListener("sync",(t=>{if(t.tag===`${v}:${this.g}`){const e=async()=>{let e;this.m=!0;try{await this.D({queue:this})}catch(t){if(t instanceof Error)throw e=t,e}finally{!this.p||e&&!t.lastChance||await this.registerSync(),this.m=!1,this.p=!1}};t.waitUntil(e())}})):this.D({queue:this})}static get j(){return j}}return t.BackgroundSyncPlugin=class{constructor(t,e){this.fetchDidFail=async({request:t})=>{await this.O.pushRequest({request:t})},this.O=new S(t,e)}},t.Queue=S,t.QueueStore=E,t.StorableRequest=x,t}({},workbox.core._private,workbox.core._private,workbox.core._private);
//# sourceMappingURL=workbox-background-sync.prod.js.map
{
"name": "workbox-background-sync",
"version": "7.0.0",
"version": "7.1.0",
"license": "MIT",

@@ -28,5 +28,5 @@ "author": "Google's Web DevRel Team",

"idb": "^7.0.1",
"workbox-core": "7.0.0"
"workbox-core": "7.1.0"
},
"gitHead": "c1d11636823e5e3a89520f7a531970a39304b14a"
"gitHead": "9e69c4269c35e2db9fbba4d13e4e6206c7b66d2a"
}
// @ts-ignore
try{self['workbox:background-sync:7.0.0']&&_()}catch(e){}
try{self['workbox:background-sync:7.1.0']&&_()}catch(e){}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc