webext-redux
Advanced tools
Comparing version 3.0.0-mv3.0 to 3.0.0
@@ -5,78 +5,132 @@ (function (global, factory) { | ||
(global = global || self, factory(global.WebextRedux = {})); | ||
}(this, function (exports) { 'use strict'; | ||
}(this, (function (exports) { 'use strict'; | ||
function _classCallCheck(instance, Constructor) { | ||
if (!(instance instanceof Constructor)) { | ||
throw new TypeError("Cannot call a class as a function"); | ||
function _arrayLikeToArray(r, a) { | ||
(null == a || a > r.length) && (a = r.length); | ||
for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; | ||
return n; | ||
} | ||
function _arrayWithoutHoles(r) { | ||
if (Array.isArray(r)) return _arrayLikeToArray(r); | ||
} | ||
function _classCallCheck(a, n) { | ||
if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); | ||
} | ||
function _defineProperties(e, r) { | ||
for (var t = 0; t < r.length; t++) { | ||
var o = r[t]; | ||
o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); | ||
} | ||
} | ||
function _defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
function _createClass(e, r, t) { | ||
return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { | ||
writable: !1 | ||
}), e; | ||
} | ||
function _createForOfIteratorHelper(r, e) { | ||
var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; | ||
if (!t) { | ||
if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { | ||
t && (r = t); | ||
var n = 0, | ||
F = function () {}; | ||
return { | ||
s: F, | ||
n: function () { | ||
return n >= r.length ? { | ||
done: !0 | ||
} : { | ||
done: !1, | ||
value: r[n++] | ||
}; | ||
}, | ||
e: function (r) { | ||
throw r; | ||
}, | ||
f: F | ||
}; | ||
} | ||
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
var o, | ||
a = !0, | ||
u = !1; | ||
return { | ||
s: function () { | ||
t = t.call(r); | ||
}, | ||
n: function () { | ||
var r = t.next(); | ||
return a = r.done, r; | ||
}, | ||
e: function (r) { | ||
u = !0, o = r; | ||
}, | ||
f: function () { | ||
try { | ||
a || null == t.return || t.return(); | ||
} finally { | ||
if (u) throw o; | ||
} | ||
} | ||
}; | ||
} | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
return Constructor; | ||
function _defineProperty(e, r, t) { | ||
return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { | ||
value: t, | ||
enumerable: !0, | ||
configurable: !0, | ||
writable: !0 | ||
}) : e[r] = t, e; | ||
} | ||
function _defineProperty(obj, key, value) { | ||
if (key in obj) { | ||
Object.defineProperty(obj, key, { | ||
value: value, | ||
enumerable: true, | ||
configurable: true, | ||
writable: true | ||
}); | ||
} else { | ||
obj[key] = value; | ||
function _iterableToArray(r) { | ||
if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); | ||
} | ||
function _nonIterableSpread() { | ||
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
function ownKeys(e, r) { | ||
var t = Object.keys(e); | ||
if (Object.getOwnPropertySymbols) { | ||
var o = Object.getOwnPropertySymbols(e); | ||
r && (o = o.filter(function (r) { | ||
return Object.getOwnPropertyDescriptor(e, r).enumerable; | ||
})), t.push.apply(t, o); | ||
} | ||
return obj; | ||
return t; | ||
} | ||
function _objectSpread(target) { | ||
for (var i = 1; i < arguments.length; i++) { | ||
var source = arguments[i] != null ? arguments[i] : {}; | ||
var ownKeys = Object.keys(source); | ||
if (typeof Object.getOwnPropertySymbols === 'function') { | ||
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { | ||
return Object.getOwnPropertyDescriptor(source, sym).enumerable; | ||
})); | ||
} | ||
ownKeys.forEach(function (key) { | ||
_defineProperty(target, key, source[key]); | ||
function _objectSpread2(e) { | ||
for (var r = 1; r < arguments.length; r++) { | ||
var t = null != arguments[r] ? arguments[r] : {}; | ||
r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { | ||
_defineProperty(e, r, t[r]); | ||
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { | ||
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); | ||
}); | ||
} | ||
return target; | ||
return e; | ||
} | ||
function _toConsumableArray(arr) { | ||
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); | ||
function _toConsumableArray(r) { | ||
return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); | ||
} | ||
function _arrayWithoutHoles(arr) { | ||
if (Array.isArray(arr)) { | ||
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; | ||
return arr2; | ||
function _toPrimitive(t, r) { | ||
if ("object" != typeof t || !t) return t; | ||
var e = t[Symbol.toPrimitive]; | ||
if (void 0 !== e) { | ||
var i = e.call(t, r || "default"); | ||
if ("object" != typeof i) return i; | ||
throw new TypeError("@@toPrimitive must return a primitive value."); | ||
} | ||
return ("string" === r ? String : Number)(t); | ||
} | ||
function _iterableToArray(iter) { | ||
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); | ||
function _toPropertyKey(t) { | ||
var i = _toPrimitive(t, "string"); | ||
return "symbol" == typeof i ? i : i + ""; | ||
} | ||
function _nonIterableSpread() { | ||
throw new TypeError("Invalid attempt to spread non-iterable instance"); | ||
function _unsupportedIterableToArray(r, a) { | ||
if (r) { | ||
if ("string" == typeof r) return _arrayLikeToArray(r, a); | ||
var t = {}.toString.call(r).slice(8, -1); | ||
return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; | ||
} | ||
} | ||
@@ -713,31 +767,31 @@ | ||
// from the Proxy Stores to background | ||
var DISPATCH_TYPE = 'chromex.dispatch'; // Message type for fetching current state from | ||
var DISPATCH_TYPE = "webext.dispatch"; | ||
// Message type for fetching current state from | ||
// background to Proxy Stores | ||
var FETCH_STATE_TYPE = "webext.fetch_state"; | ||
var FETCH_STATE_TYPE = 'chromex.fetch_state'; // Message type for state update events from | ||
// Message type for state update events from | ||
// background to Proxy Stores | ||
var STATE_TYPE = "webext.state"; | ||
var STATE_TYPE = 'chromex.state'; // Message type for state patch events from | ||
// Message type for state patch events from | ||
// background to Proxy Stores | ||
var PATCH_STATE_TYPE = "webext.patch_state"; | ||
var PATCH_STATE_TYPE = 'chromex.patch_state'; // The default name for the port communication via | ||
// react-chrome-redux | ||
// The default name for the store channel | ||
var DEFAULT_CHANNEL_NAME = "webext.channel"; | ||
var DEFAULT_PORT_NAME = "chromex.port_name"; | ||
var noop = function noop(payload) { | ||
return payload; | ||
}; | ||
var transformPayload = function transformPayload(message) { | ||
var transformer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop; | ||
return _objectSpread({}, message, message.payload ? { | ||
return _objectSpread2(_objectSpread2({}, message), message.payload ? { | ||
payload: transformer(message.payload) | ||
} : {}); | ||
}; | ||
var deserializeListener = function deserializeListener(listener) { | ||
var deserializer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop; | ||
var shouldDeserialize = arguments.length > 2 ? arguments[2] : undefined; | ||
// If a shouldDeserialize function is passed, return a function that uses it | ||
@@ -750,12 +804,9 @@ // to check if any given message payload should be deserialized | ||
} | ||
if (shouldDeserialize.apply(void 0, [message].concat(args))) { | ||
return listener.apply(void 0, [transformPayload(message, deserializer)].concat(args)); | ||
} | ||
return listener.apply(void 0, [message].concat(args)); | ||
}; | ||
} // Otherwise, return a function that tries to deserialize on every message | ||
} | ||
// Otherwise, return a function that tries to deserialize on every message | ||
return function (message) { | ||
@@ -765,6 +816,6 @@ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
} | ||
return listener.apply(void 0, [transformPayload(message, deserializer)].concat(args)); | ||
}; | ||
}; | ||
/** | ||
@@ -806,4 +857,2 @@ * A function returned from withDeserializer that, when called, wraps addListenerFn with the | ||
*/ | ||
var withDeserializer = function withDeserializer() { | ||
@@ -817,2 +866,3 @@ var deserializer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop; | ||
}; | ||
/** | ||
@@ -832,3 +882,2 @@ * Given a serializer, returns a function that takes a message sending | ||
*/ | ||
var withSerializer = function withSerializer() { | ||
@@ -842,7 +891,5 @@ var serializer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop; | ||
} | ||
if (args.length <= messageArgIndex) { | ||
throw new Error("Message in request could not be serialized. " + "Expected message in position ".concat(messageArgIndex, " but only received ").concat(args.length, " args.")); | ||
} | ||
args[messageArgIndex] = transformPayload(args[messageArgIndex], serializer); | ||
@@ -855,4 +902,5 @@ return sendMessageFn.apply(void 0, args); | ||
// The `change` value for updated or inserted fields resulting from shallow diff | ||
var DIFF_STATUS_UPDATED = 'updated'; // The `change` value for removed fields resulting from shallow diff | ||
var DIFF_STATUS_UPDATED = 'updated'; | ||
// The `change` value for removed fields resulting from shallow diff | ||
var DIFF_STATUS_REMOVED = 'removed'; | ||
@@ -864,5 +912,4 @@ | ||
var change = _ref.change, | ||
key = _ref.key, | ||
value = _ref.value; | ||
key = _ref.key, | ||
value = _ref.value; | ||
switch (change) { | ||
@@ -872,9 +919,6 @@ case DIFF_STATUS_UPDATED: | ||
break; | ||
case DIFF_STATUS_REMOVED: | ||
Reflect.deleteProperty(newObj, key); | ||
break; | ||
default: // do nothing | ||
// do nothing | ||
} | ||
@@ -892,3 +936,2 @@ }); | ||
var api; | ||
try { | ||
@@ -901,7 +944,5 @@ // eslint-disable-next-line no-undef | ||
} | ||
if (!api) { | ||
throw new Error("Browser API is not present"); | ||
} | ||
return api; | ||
@@ -912,3 +953,3 @@ } | ||
var defaultOpts = { | ||
portName: DEFAULT_PORT_NAME, | ||
channelName: DEFAULT_CHANNEL_NAME, | ||
state: {}, | ||
@@ -919,44 +960,44 @@ serializer: noop, | ||
}; | ||
var Store = | ||
/*#__PURE__*/ | ||
function () { | ||
var Store = /*#__PURE__*/function () { | ||
/** | ||
* Creates a new Proxy store | ||
* @param {object} options An object of form {portName, state, serializer, deserializer, diffStrategy}, where `portName` is a required string and defines the name of the port for state transition changes, `state` is the initial state of this store (default `{}`) `serializer` is a function to serialize outgoing message payloads (default is passthrough), `deserializer` is a function to deserialize incoming message payloads (default is passthrough), and patchStrategy is one of the included patching strategies (default is shallow diff) or a custom patching function. | ||
* @param {object} options | ||
* @param {string} options.channelName The name of the channel for this store. | ||
* @param {object} options.state The initial state of the store (default | ||
* `{}`). | ||
* @param {function} options.serializer A function to serialize outgoing | ||
* messages (default is passthrough). | ||
* @param {function} options.deserializer A function to deserialize incoming | ||
* messages (default is passthrough). | ||
* @param {function} options.patchStrategy A function to patch the state with | ||
* incoming messages. Use one of the included patching strategies or a custom | ||
* patching function. (default is shallow diff). | ||
*/ | ||
function Store() { | ||
var _this = this; | ||
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultOpts, | ||
_ref$portName = _ref.portName, | ||
portName = _ref$portName === void 0 ? defaultOpts.portName : _ref$portName, | ||
_ref$state = _ref.state, | ||
state = _ref$state === void 0 ? defaultOpts.state : _ref$state, | ||
_ref$serializer = _ref.serializer, | ||
serializer = _ref$serializer === void 0 ? defaultOpts.serializer : _ref$serializer, | ||
_ref$deserializer = _ref.deserializer, | ||
deserializer = _ref$deserializer === void 0 ? defaultOpts.deserializer : _ref$deserializer, | ||
_ref$patchStrategy = _ref.patchStrategy, | ||
patchStrategy = _ref$patchStrategy === void 0 ? defaultOpts.patchStrategy : _ref$patchStrategy; | ||
_ref$channelName = _ref.channelName, | ||
channelName = _ref$channelName === void 0 ? defaultOpts.channelName : _ref$channelName, | ||
_ref$state = _ref.state, | ||
state = _ref$state === void 0 ? defaultOpts.state : _ref$state, | ||
_ref$serializer = _ref.serializer, | ||
serializer = _ref$serializer === void 0 ? defaultOpts.serializer : _ref$serializer, | ||
_ref$deserializer = _ref.deserializer, | ||
deserializer = _ref$deserializer === void 0 ? defaultOpts.deserializer : _ref$deserializer, | ||
_ref$patchStrategy = _ref.patchStrategy, | ||
patchStrategy = _ref$patchStrategy === void 0 ? defaultOpts.patchStrategy : _ref$patchStrategy; | ||
_classCallCheck(this, Store); | ||
if (!portName) { | ||
throw new Error('portName is required in options'); | ||
if (!channelName) { | ||
throw new Error('channelName is required in options'); | ||
} | ||
if (typeof serializer !== 'function') { | ||
throw new Error('serializer must be a function'); | ||
} | ||
if (typeof deserializer !== 'function') { | ||
throw new Error('deserializer must be a function'); | ||
} | ||
if (typeof patchStrategy !== 'function') { | ||
throw new Error('patchStrategy must be one of the included patching strategies or a custom patching function'); | ||
} | ||
this.portName = portName; | ||
this.channelName = channelName; | ||
this.readyResolved = false; | ||
@@ -967,7 +1008,8 @@ this.readyPromise = new Promise(function (resolve) { | ||
this.browserAPI = getBrowserAPI(); | ||
this.initializeStore = this.initializeStore.bind(this); // We request the latest available state data to initialise our store | ||
this.initializeStore = this.initializeStore.bind(this); | ||
// We request the latest available state data to initialise our store | ||
this.browserAPI.runtime.sendMessage({ | ||
type: FETCH_STATE_TYPE, | ||
portName: portName | ||
channelName: channelName | ||
}, undefined, this.initializeStore); | ||
@@ -977,3 +1019,2 @@ this.deserializer = deserializer; | ||
var _this$browserAPI$runt; | ||
return (_this$browserAPI$runt = _this.browserAPI.runtime.onMessage).addListener.apply(_this$browserAPI$runt, arguments); | ||
@@ -983,35 +1024,41 @@ }); | ||
var _this$browserAPI$runt2; | ||
return (_this$browserAPI$runt2 = _this.browserAPI.runtime).sendMessage.apply(_this$browserAPI$runt2, arguments); | ||
}, 0); | ||
}); | ||
this.listeners = []; | ||
this.state = state; | ||
this.patchStrategy = patchStrategy; // Don't use shouldDeserialize here, since no one else should be using this port | ||
this.patchStrategy = patchStrategy; | ||
/** | ||
* Determine if the message should be run through the deserializer. We want | ||
* to skip processing messages that probably didn't come from this library. | ||
* Note that the listener below is still called for each message so it needs | ||
* its own guard, the shouldDeserialize predicate only skips _deserializing_ | ||
* the message. | ||
*/ | ||
var shouldDeserialize = function shouldDeserialize(message) { | ||
return Boolean(message) && typeof message.type === "string" && message.channelName === _this.channelName; | ||
}; | ||
this.serializedPortListener(function (message) { | ||
if (message.portName === _this.portName) { | ||
switch (message.type) { | ||
case STATE_TYPE: | ||
_this.replaceState(message.payload); | ||
if (!_this.readyResolved) { | ||
_this.readyResolved = true; | ||
_this.readyResolve(); | ||
} | ||
break; | ||
case PATCH_STATE_TYPE: | ||
_this.patchState(message.payload); | ||
break; | ||
default: // do nothing | ||
} | ||
if (!message || message.channelName !== _this.channelName) { | ||
return; | ||
} | ||
}); | ||
switch (message.type) { | ||
case STATE_TYPE: | ||
_this.replaceState(message.payload); | ||
if (!_this.readyResolved) { | ||
_this.readyResolved = true; | ||
_this.readyResolve(); | ||
} | ||
break; | ||
case PATCH_STATE_TYPE: | ||
_this.patchState(message.payload); | ||
break; | ||
// do nothing | ||
} | ||
}, shouldDeserialize); | ||
this.dispatch = this.dispatch.bind(this); // add this context to dispatch | ||
this.getState = this.getState.bind(this); // add this context to getState | ||
this.subscribe = this.subscribe.bind(this); // add this context to subscribe | ||
} | ||
/** | ||
@@ -1022,15 +1069,12 @@ * Returns a promise that resolves when the store is ready. Optionally a callback may be passed in instead. | ||
*/ | ||
_createClass(Store, [{ | ||
return _createClass(Store, [{ | ||
key: "ready", | ||
value: function ready() { | ||
var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; | ||
if (cb !== null) { | ||
return this.readyPromise.then(cb); | ||
} | ||
return this.readyPromise; | ||
} | ||
/** | ||
@@ -1041,3 +1085,2 @@ * Subscribes a listener function for all state changes | ||
*/ | ||
}, { | ||
@@ -1047,3 +1090,2 @@ key: "subscribe", | ||
var _this2 = this; | ||
this.listeners.push(listener); | ||
@@ -1056,2 +1098,3 @@ return function () { | ||
} | ||
/** | ||
@@ -1061,3 +1104,2 @@ * Replaces the state for only the keys in the updated state. Notifies all listeners of state change. | ||
*/ | ||
}, { | ||
@@ -1071,2 +1113,3 @@ key: "patchState", | ||
} | ||
/** | ||
@@ -1076,3 +1119,2 @@ * Replace the current state with a new state. Notifies all listeners of state change. | ||
*/ | ||
}, { | ||
@@ -1086,2 +1128,3 @@ key: "replaceState", | ||
} | ||
/** | ||
@@ -1091,3 +1134,2 @@ * Get the current state of the store | ||
*/ | ||
}, { | ||
@@ -1098,6 +1140,6 @@ key: "getState", | ||
} | ||
/** | ||
* Stub function to stay consistent with Redux Store API. No-op. | ||
*/ | ||
}, { | ||
@@ -1108,2 +1150,3 @@ key: "replaceReducer", | ||
} | ||
/** | ||
@@ -1114,3 +1157,2 @@ * Dispatch an action to the background using messaging passing | ||
*/ | ||
}, { | ||
@@ -1120,7 +1162,6 @@ key: "dispatch", | ||
var _this3 = this; | ||
return new Promise(function (resolve, reject) { | ||
_this3.serializedMessageSender({ | ||
type: DISPATCH_TYPE, | ||
portName: _this3.portName, | ||
channelName: _this3.channelName, | ||
payload: data | ||
@@ -1134,9 +1175,6 @@ }, null, function (resp) { | ||
} | ||
var error = resp.error, | ||
value = resp.value; | ||
value = resp.value; | ||
if (error) { | ||
var _bgErr = new Error("".concat(backgroundErrPrefix).concat(error)); | ||
reject(lodash_assignin(_bgErr, error)); | ||
@@ -1153,4 +1191,5 @@ } else { | ||
if (message && message.type === FETCH_STATE_TYPE) { | ||
this.replaceState(message.payload); // Resolve if readyPromise has not been resolved. | ||
this.replaceState(message.payload); | ||
// Resolve if readyPromise has not been resolved. | ||
if (!this.readyResolved) { | ||
@@ -1163,4 +1202,2 @@ this.readyResolved = true; | ||
}]); | ||
return Store; | ||
}(); | ||
@@ -1174,3 +1211,2 @@ | ||
} | ||
if (funcs.length === 0) { | ||
@@ -1181,7 +1217,5 @@ return function (arg) { | ||
} | ||
if (funcs.length === 1) { | ||
return funcs[0]; | ||
} | ||
return funcs.reduce(function (a, b) { | ||
@@ -1192,6 +1226,6 @@ return function () { | ||
}); | ||
} // Based on redux implementation of applyMiddleware to support all standard | ||
} | ||
// Based on redux implementation of applyMiddleware to support all standard | ||
// redux middlewares | ||
function applyMiddleware(store) { | ||
@@ -1201,7 +1235,5 @@ for (var _len2 = arguments.length, middlewares = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
} | ||
var _dispatch = function dispatch() { | ||
throw new Error('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.'); | ||
}; | ||
var middlewareAPI = { | ||
@@ -1230,3 +1262,2 @@ getState: store.getState.bind(store), | ||
*/ | ||
function shallowDiff$1(oldObj, newObj) { | ||
@@ -1256,15 +1287,13 @@ var difference = []; | ||
var resolve = function resolve() {}; | ||
var fnPromise = new Promise(function (resolve_) { | ||
return resolve = resolve_; | ||
}); | ||
var listener = function listener(message, sender, sendResponse) { | ||
fnPromise.then(function (fn) { | ||
fn(message, sender, sendResponse); | ||
}); // Allow response to be async | ||
}); | ||
// Allow response to be async | ||
return true; | ||
}; | ||
return { | ||
@@ -1282,3 +1311,2 @@ setListener: resolve, | ||
*/ | ||
var promiseResponder = function promiseResponder(dispatchResult, send) { | ||
@@ -1290,3 +1318,3 @@ Promise.resolve(dispatchResult).then(function (res) { | ||
}); | ||
}).catch(function (err) { | ||
})["catch"](function (err) { | ||
console.error("error dispatching result:", err); | ||
@@ -1299,5 +1327,4 @@ send({ | ||
}; | ||
var defaultOpts$1 = { | ||
portName: DEFAULT_PORT_NAME, | ||
channelName: DEFAULT_CHANNEL_NAME, | ||
dispatchResponder: promiseResponder, | ||
@@ -1308,2 +1335,3 @@ serializer: noop, | ||
}; | ||
/** | ||
@@ -1313,4 +1341,3 @@ * @typedef {function} WrapStore | ||
* @param {Object} options | ||
* @param {string} options.portName The name of the port for state transition | ||
* changes. | ||
* @param {string} options.channelName The name of the channel for this store. | ||
* @param {function} options.dispatchResponder A function that takes the result | ||
@@ -1334,7 +1361,7 @@ * of a store dispatch and optionally implements custom logic for responding to | ||
*/ | ||
var wrapStore = (function () { | ||
var browserAPI = getBrowserAPI(); | ||
var wrapStore = (function () { | ||
var browserAPI = getBrowserAPI(); // Setup message listeners synchronously to avoid dropping messages if the | ||
// Setup message listeners synchronously to avoid dropping messages if the | ||
// extension is woken by a message. | ||
var stateProviderListener = createDeferredListener(); | ||
@@ -1346,35 +1373,30 @@ var actionListener = createDeferredListener(); | ||
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultOpts$1, | ||
_ref$portName = _ref.portName, | ||
portName = _ref$portName === void 0 ? defaultOpts$1.portName : _ref$portName, | ||
_ref$dispatchResponde = _ref.dispatchResponder, | ||
dispatchResponder = _ref$dispatchResponde === void 0 ? defaultOpts$1.dispatchResponder : _ref$dispatchResponde, | ||
_ref$serializer = _ref.serializer, | ||
serializer = _ref$serializer === void 0 ? defaultOpts$1.serializer : _ref$serializer, | ||
_ref$deserializer = _ref.deserializer, | ||
deserializer = _ref$deserializer === void 0 ? defaultOpts$1.deserializer : _ref$deserializer, | ||
_ref$diffStrategy = _ref.diffStrategy, | ||
diffStrategy = _ref$diffStrategy === void 0 ? defaultOpts$1.diffStrategy : _ref$diffStrategy; | ||
if (!portName) { | ||
throw new Error("portName is required in options"); | ||
_ref$channelName = _ref.channelName, | ||
channelName = _ref$channelName === void 0 ? defaultOpts$1.channelName : _ref$channelName, | ||
_ref$dispatchResponde = _ref.dispatchResponder, | ||
dispatchResponder = _ref$dispatchResponde === void 0 ? defaultOpts$1.dispatchResponder : _ref$dispatchResponde, | ||
_ref$serializer = _ref.serializer, | ||
serializer = _ref$serializer === void 0 ? defaultOpts$1.serializer : _ref$serializer, | ||
_ref$deserializer = _ref.deserializer, | ||
deserializer = _ref$deserializer === void 0 ? defaultOpts$1.deserializer : _ref$deserializer, | ||
_ref$diffStrategy = _ref.diffStrategy, | ||
diffStrategy = _ref$diffStrategy === void 0 ? defaultOpts$1.diffStrategy : _ref$diffStrategy; | ||
if (!channelName) { | ||
throw new Error("channelName is required in options"); | ||
} | ||
if (typeof serializer !== "function") { | ||
throw new Error("serializer must be a function"); | ||
} | ||
if (typeof deserializer !== "function") { | ||
throw new Error("deserializer must be a function"); | ||
} | ||
if (typeof diffStrategy !== "function") { | ||
throw new Error("diffStrategy must be one of the included diffing strategies or a custom diff function"); | ||
} | ||
/** | ||
* Respond to dispatches from UI components | ||
*/ | ||
var dispatchResponse = function dispatchResponse(request, sender, sendResponse) { | ||
if (request.type === DISPATCH_TYPE && request.portName === portName) { | ||
if (request.type === DISPATCH_TYPE && request.channelName === channelName) { | ||
var action = Object.assign({}, request.payload, { | ||
@@ -1384,3 +1406,2 @@ _sender: sender | ||
var dispatchResult = null; | ||
try { | ||
@@ -1392,3 +1413,2 @@ dispatchResult = store.dispatch(action); | ||
} | ||
dispatchResponder(dispatchResult, sendResponse); | ||
@@ -1398,47 +1418,29 @@ return true; | ||
}; | ||
/** | ||
* Setup for state updates | ||
*/ | ||
var serializedMessagePoster = withSerializer(serializer)(function () { | ||
var _browserAPI$runtime; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
var onErrorCallback = function onErrorCallback() { | ||
if (browserAPI.runtime.lastError) ; | ||
}; | ||
(_browserAPI$runtime = browserAPI.runtime).sendMessage.apply(_browserAPI$runtime, args.concat([onErrorCallback])); // We will broadcast state changes to all tabs to sync state across content scripts | ||
(_browserAPI$runtime = browserAPI.runtime).sendMessage.apply(_browserAPI$runtime, args.concat([onErrorCallback])); | ||
// We will broadcast state changes to all tabs to sync state across content scripts | ||
return browserAPI.tabs.query({}, function (tabs) { | ||
var _iteratorNormalCompletion = true; | ||
var _didIteratorError = false; | ||
var _iteratorError = undefined; | ||
var _iterator = _createForOfIteratorHelper(tabs), | ||
_step; | ||
try { | ||
for (var _iterator = tabs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
for (_iterator.s(); !(_step = _iterator.n()).done;) { | ||
var _browserAPI$tabs; | ||
var tab = _step.value; | ||
(_browserAPI$tabs = browserAPI.tabs).sendMessage.apply(_browserAPI$tabs, [tab.id].concat(args, [onErrorCallback])); | ||
} | ||
} catch (err) { | ||
_didIteratorError = true; | ||
_iteratorError = err; | ||
_iterator.e(err); | ||
} finally { | ||
try { | ||
if (!_iteratorNormalCompletion && _iterator.return != null) { | ||
_iterator.return(); | ||
} | ||
} finally { | ||
if (_didIteratorError) { | ||
throw _iteratorError; | ||
} | ||
} | ||
_iterator.f(); | ||
} | ||
@@ -1448,7 +1450,5 @@ }); | ||
var currentState = store.getState(); | ||
var patchState = function patchState() { | ||
var newState = store.getState(); | ||
var diff = diffStrategy(currentState, newState); | ||
if (diff.length) { | ||
@@ -1459,31 +1459,27 @@ currentState = newState; | ||
payload: diff, | ||
portName: portName // Notifying what extension is broadcasting the state changes | ||
channelName: channelName // Notifying what store is broadcasting the state changes | ||
}); | ||
} | ||
}; // Send patched state down connected port on every redux store state change | ||
}; | ||
// Send patched state to listeners on every redux store state change | ||
store.subscribe(patchState); | ||
store.subscribe(patchState); // Send store's initial state through port | ||
// Send store's initial state | ||
serializedMessagePoster({ | ||
type: STATE_TYPE, | ||
payload: currentState, | ||
portName: portName // Notifying what extension is broadcasting the state changes | ||
channelName: channelName // Notifying what store is broadcasting the state changes | ||
}); | ||
var withPayloadDeserializer = withDeserializer(deserializer); | ||
var shouldDeserialize = function shouldDeserialize(request) { | ||
return request.type === DISPATCH_TYPE && request.portName === portName; | ||
return request.type === DISPATCH_TYPE && request.channelName === channelName; | ||
}; | ||
/** | ||
* State provider for content-script initialization | ||
*/ | ||
stateProviderListener.setListener(function (request, sender, sendResponse) { | ||
var state = store.getState(); | ||
if (request.type === FETCH_STATE_TYPE && request.portName === portName) { | ||
if (request.type === FETCH_STATE_TYPE && request.channelName === channelName) { | ||
sendResponse({ | ||
@@ -1495,6 +1491,6 @@ type: FETCH_STATE_TYPE, | ||
}); | ||
/** | ||
* Setup action handler | ||
*/ | ||
withPayloadDeserializer(actionListener.setListener)(dispatchResponse, shouldDeserialize); | ||
@@ -1514,7 +1510,5 @@ }; | ||
var alias = aliases[action.type]; | ||
if (alias) { | ||
return next(alias(action)); | ||
} | ||
return next(action); | ||
@@ -1533,2 +1527,2 @@ }; | ||
})); | ||
}))); |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).WebextRedux={})}(this,(function(e){"use strict";function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function r(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{},o=Object.keys(r);"function"==typeof Object.getOwnPropertySymbols&&(o=o.concat(Object.getOwnPropertySymbols(r).filter((function(e){return Object.getOwnPropertyDescriptor(r,e).enumerable})))),o.forEach((function(t){n(e,t,r[t])}))}return e}function i(e){return function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);e.length>t;t++)r[t]=e[t];return r}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var a=/^(?:0|[1-9]\d*)$/;function c(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var u=Object.prototype,s=u.hasOwnProperty,l=u.toString,f=u.propertyIsEnumerable,p=Math.max;function h(e,t){var r=S(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&z(e)}(e)&&s.call(e,"callee")&&(!f.call(e,"callee")||"[object Arguments]"==l.call(e))}(e)?function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}(e.length,String):[],n=r.length,o=!!n;for(var i in e)!t&&!s.call(e,i)||o&&("length"==i||v(i,n))||r.push(i);return r}function d(e,t,r){var n=e[t];s.call(e,t)&&g(n,r)&&(void 0!==r||t in e)||(e[t]=r)}function y(e){if(!P(e))return function(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}(e);var t,r,n=(t=e)===("function"==typeof(r=t&&t.constructor)&&r.prototype||u),o=[];for(var i in e)("constructor"!=i||!n&&s.call(e,i))&&o.push(i);return o}function v(e,t){return!!(t=null==t?9007199254740991:t)&&("number"==typeof e||a.test(e))&&e>-1&&e%1==0&&t>e}function g(e,t){return e===t||e!=e&&t!=t}var m,b,w,S=Array.isArray;function z(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&9007199254740991>=e}(e.length)&&!function(e){var t=P(e)?l.call(e):"";return"[object Function]"==t||"[object GeneratorFunction]"==t}(e)}function P(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}var j=(m=function(e,t){!function(e,t,r,n){r||(r={});for(var o=-1,i=t.length;++o<i;){var a=t[o],c=n?n(r[a],e[a],a,r,e):void 0;d(r,a,void 0===c?e[a]:c)}}(t,function(e){return z(e)?h(e,!0):y(e)}(t),e)},b=function(e,t){var r=-1,n=t.length,o=n>1?t[n-1]:void 0,i=n>2?t[2]:void 0;for(o=m.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(e,t,r){if(!P(r))return!1;var n=typeof t;return!!("number"==n?z(r)&&v(t,r.length):"string"==n&&t in r)&&g(r[t],e)}(t[0],t[1],i)&&(o=3>n?void 0:o,n=1),e=Object(e);++r<n;){var a=t[r];a&&m(e,a,r,o)}return e},w=p(void 0===w?b.length-1:w,0),function(){for(var e=arguments,t=-1,r=p(e.length-w,0),n=Array(r);++t<r;)n[t]=e[w+t];t=-1;for(var o=Array(w+1);++t<w;)o[t]=e[t];return o[w]=n,c(b,this,o)}),E=function(e){return e},A=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E;return o({},e,e.payload?{payload:t(e.payload)}:{})},O=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:E,r=arguments.length>2?arguments[2]:void 0;return r?function(n){for(var o=arguments.length,i=Array(o>1?o-1:0),a=1;o>a;a++)i[a-1]=arguments[a];return r.apply(void 0,[n].concat(i))?e.apply(void 0,[A(n,t)].concat(i)):e.apply(void 0,[n].concat(i))}:function(r){for(var n=arguments.length,o=Array(n>1?n-1:0),i=1;n>i;i++)o[i-1]=arguments[i];return e.apply(void 0,[A(r,t)].concat(o))}},k=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E;return function(t){return function(r,n){return t(O(r,e,n))}}},x=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:E;return function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return function(){for(var n=arguments.length,o=Array(n),i=0;n>i;i++)o[i]=arguments[i];if(r>=o.length)throw Error("Message in request could not be serialized. "+"Expected message in position ".concat(r," but only received ").concat(o.length," args."));return o[r]=A(o[r],e),t.apply(void 0,o)}}};function N(){var e;try{e=self.chrome||self.browser||browser}catch(t){e=browser}if(!e)throw Error("Browser API is not present");return e}var R="\nLooks like there is an error in the background page. You might want to inspect your background page for more details.\n",M={portName:"chromex.port_name",state:{},serializer:E,deserializer:E,patchStrategy:function(e,t){var r=Object.assign({},e);return t.forEach((function(e){var t=e.key,n=e.value;switch(e.change){case"updated":r[t]=n;break;case"removed":Reflect.deleteProperty(r,t)}})),r}};function _(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return 0===t.length?function(e){return e}:1===t.length?t[0]:t.reduce((function(e,t){return function(){return e(t.apply(void 0,arguments))}}))}var L=function(){var e=function(){},t=new Promise((function(t){return e=t}));return{setListener:e,listener:function(e,r,n){return t.then((function(t){t(e,r,n)})),!0}}},I={portName:"chromex.port_name",dispatchResponder:function(e,t){Promise.resolve(e).then((function(e){t({error:null,value:e})})).catch((function(e){console.error("error dispatching result:",e),t({error:e.message,value:null})}))},serializer:E,deserializer:E,diffStrategy:function(e,t){var r=[];return Object.keys(t).forEach((function(n){e[n]!==t[n]&&r.push({key:n,value:t[n],change:"updated"})})),Object.keys(e).forEach((function(e){t.hasOwnProperty(e)||r.push({key:e,change:"removed"})})),r}};e.Store=function(){function e(){var r=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:M,o=n.portName,i=void 0===o?M.portName:o,a=n.state,c=void 0===a?M.state:a,u=n.serializer,s=void 0===u?M.serializer:u,l=n.deserializer,f=void 0===l?M.deserializer:l,p=n.patchStrategy,h=void 0===p?M.patchStrategy:p;if(t(this,e),!i)throw Error("portName is required in options");if("function"!=typeof s)throw Error("serializer must be a function");if("function"!=typeof f)throw Error("deserializer must be a function");if("function"!=typeof h)throw Error("patchStrategy must be one of the included patching strategies or a custom patching function");this.portName=i,this.readyResolved=!1,this.readyPromise=new Promise((function(e){return r.readyResolve=e})),this.browserAPI=N(),this.initializeStore=this.initializeStore.bind(this),this.browserAPI.runtime.sendMessage({type:"chromex.fetch_state",portName:i},void 0,this.initializeStore),this.deserializer=f,this.serializedPortListener=k(f)((function(){var e;return(e=r.browserAPI.runtime.onMessage).addListener.apply(e,arguments)})),this.serializedMessageSender=x(s)((function(){var e;return(e=r.browserAPI.runtime).sendMessage.apply(e,arguments)}),0),this.listeners=[],this.state=c,this.patchStrategy=h,this.serializedPortListener((function(e){if(e.portName===r.portName)switch(e.type){case"chromex.state":r.replaceState(e.payload),r.readyResolved||(r.readyResolved=!0,r.readyResolve());break;case"chromex.patch_state":r.patchState(e.payload)}})),this.dispatch=this.dispatch.bind(this)}var n,o,i;return n=e,(o=[{key:"ready",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return null!==e?this.readyPromise.then(e):this.readyPromise}},{key:"subscribe",value:function(e){var t=this;return this.listeners.push(e),function(){t.listeners=t.listeners.filter((function(t){return t!==e}))}}},{key:"patchState",value:function(e){this.state=this.patchStrategy(this.state,e),this.listeners.forEach((function(e){return e()}))}},{key:"replaceState",value:function(e){this.state=e,this.listeners.forEach((function(e){return e()}))}},{key:"getState",value:function(){return this.state}},{key:"replaceReducer",value:function(){}},{key:"dispatch",value:function(e){var t=this;return new Promise((function(r,n){t.serializedMessageSender({type:"chromex.dispatch",portName:t.portName,payload:e},null,(function(e){if(e){var o=e.error,i=e.value;if(o){var a=Error("".concat(R).concat(o));n(j(a,o))}else r(i&&i.payload)}else{var c=t.browserAPI.runtime.lastError,u=Error("".concat(R).concat(c));n(j(u,c))}}))}))}},{key:"initializeStore",value:function(e){e&&"chromex.fetch_state"===e.type&&(this.replaceState(e.payload),this.readyResolved||(this.readyResolved=!0,this.readyResolve()))}}])&&r(n.prototype,o),i&&r(n,i),e}(),e.alias=function(e){return function(){return function(t){return function(r){var n=e[r.type];return t(n?n(r):r)}}}},e.applyMiddleware=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];var o=function(){throw Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},a={getState:e.getState.bind(e),dispatch:function(){return o.apply(void 0,arguments)}};return r=(r||[]).map((function(e){return e(a)})),o=_.apply(void 0,i(r))(e.dispatch),e.dispatch=o,e},e.createWrapStore=function(){var e=N(),t=L(),r=L();return e.runtime.onMessage.addListener(t.listener),e.runtime.onMessage.addListener(r.listener),function(n){var o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:I,i=o.portName,a=void 0===i?I.portName:i,c=o.dispatchResponder,u=void 0===c?I.dispatchResponder:c,s=o.serializer,l=void 0===s?I.serializer:s,f=o.deserializer,p=void 0===f?I.deserializer:f,h=o.diffStrategy,d=void 0===h?I.diffStrategy:h;if(!a)throw Error("portName is required in options");if("function"!=typeof l)throw Error("serializer must be a function");if("function"!=typeof p)throw Error("deserializer must be a function");if("function"!=typeof d)throw Error("diffStrategy must be one of the included diffing strategies or a custom diff function");var y=function(e,t,r){if("chromex.dispatch"===e.type&&e.portName===a){var o=Object.assign({},e.payload,{_sender:t}),i=null;try{i=n.dispatch(o)}catch(e){i=Promise.reject(e.message),console.error(e)}return u(i,r),!0}},v=x(l)((function(){for(var t,r=arguments.length,n=Array(r),o=0;r>o;o++)n[o]=arguments[o];var i=function(){};return(t=e.runtime).sendMessage.apply(t,n.concat([i])),e.tabs.query({},(function(t){var r=!0,o=!1,a=void 0;try{for(var c,u=t[Symbol.iterator]();!(r=(c=u.next()).done);r=!0){var s;(s=e.tabs).sendMessage.apply(s,[c.value.id].concat(n,[i]))}}catch(e){o=!0,a=e}finally{try{r||null==u.return||u.return()}finally{if(o)throw a}}}))})),g=n.getState(),m=function(){var e=n.getState(),t=d(g,e);t.length&&(g=e,v({type:"chromex.patch_state",payload:t,portName:a}))};n.subscribe(m),v({type:"chromex.state",payload:g,portName:a});var b=k(p),w=function(e){return"chromex.dispatch"===e.type&&e.portName===a};t.setListener((function(e,t,r){var o=n.getState();"chromex.fetch_state"===e.type&&e.portName===a&&r({type:"chromex.fetch_state",payload:o})})),b(r.setListener)(y,w)}},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).WebextRedux={})}(this,(function(e){"use strict";function t(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=Array(t);t>r;r++)n[r]=e[r];return n}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var r=0;t.length>r;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,s(n.key),n)}}function i(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=l(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,i=function(){};return{s:i,n:function(){return e.length>n?{done:!1,value:e[n++]}:{done:!0}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,o=!0,c=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return o=e.done,e},e:function(e){c=!0,a=e},f:function(){try{o||null==r.return||r.return()}finally{if(c)throw a}}}}function a(e,t,r){return(t=s(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function c(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?o(Object(r),!0).forEach((function(t){a(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):o(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function u(e){return function(e){if(Array.isArray(e))return t(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||l(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function s(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var n=r.call(e,t||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function l(e,r){if(e){if("string"==typeof e)return t(e,r);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?t(e,r):void 0}}var f=/^(?:0|[1-9]\d*)$/;function h(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var d=Object.prototype,p=d.hasOwnProperty,y=d.toString,v=d.propertyIsEnumerable,b=Math.max;function g(e,t){var r=E(e)||function(e){return function(e){return function(e){return!!e&&"object"==typeof e}(e)&&z(e)}(e)&&p.call(e,"callee")&&(!v.call(e,"callee")||"[object Arguments]"==y.call(e))}(e)?function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}(e.length,String):[],n=r.length,i=!!n;for(var a in e)!t&&!p.call(e,a)||i&&("length"==a||S(a,n))||r.push(a);return r}function m(e,t,r){var n=e[t];p.call(e,t)&&j(n,r)&&(void 0!==r||t in e)||(e[t]=r)}function w(e){if(!N(e))return function(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}(e);var t,r,n=(t=e)===("function"==typeof(r=t&&t.constructor)&&r.prototype||d),i=[];for(var a in e)("constructor"!=a||!n&&p.call(e,a))&&i.push(a);return i}function S(e,t){return!!(t=null==t?9007199254740991:t)&&("number"==typeof e||f.test(e))&&e>-1&&e%1==0&&t>e}function j(e,t){return e===t||e!=e&&t!=t}var P,O,A,E=Array.isArray;function z(e){return null!=e&&function(e){return"number"==typeof e&&e>-1&&e%1==0&&9007199254740991>=e}(e.length)&&!function(e){var t=N(e)?y.call(e):"";return"[object Function]"==t||"[object GeneratorFunction]"==t}(e)}function N(e){var t=typeof e;return!!e&&("object"==t||"function"==t)}var k=(P=function(e,t){!function(e,t,r,n){r||(r={});for(var i=-1,a=t.length;++i<a;){var o=t[i],c=n?n(r[o],e[o],o,r,e):void 0;m(r,o,void 0===c?e[o]:c)}}(t,function(e){return z(e)?g(e,!0):w(e)}(t),e)},O=function(e,t){var r=-1,n=t.length,i=n>1?t[n-1]:void 0,a=n>2?t[2]:void 0;for(i=P.length>3&&"function"==typeof i?(n--,i):void 0,a&&function(e,t,r){if(!N(r))return!1;var n=typeof t;return!!("number"==n?z(r)&&S(t,r.length):"string"==n&&t in r)&&j(r[t],e)}(t[0],t[1],a)&&(i=3>n?void 0:i,n=1),e=Object(e);++r<n;){var o=t[r];o&&P(e,o,r,i)}return e},A=b(void 0===A?O.length-1:A,0),function(){for(var e=arguments,t=-1,r=b(e.length-A,0),n=Array(r);++t<r;)n[t]=e[A+t];t=-1;for(var i=Array(A+1);++t<A;)i[t]=e[t];return i[A]=n,h(O,this,i)}),x=function(e){return e},M=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:x;return c(c({},e),e.payload?{payload:t(e.payload)}:{})},R=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:x,r=arguments.length>2?arguments[2]:void 0;return r?function(n){for(var i=arguments.length,a=Array(i>1?i-1:0),o=1;i>o;o++)a[o-1]=arguments[o];return r.apply(void 0,[n].concat(a))?e.apply(void 0,[M(n,t)].concat(a)):e.apply(void 0,[n].concat(a))}:function(r){for(var n=arguments.length,i=Array(n>1?n-1:0),a=1;n>a;a++)i[a-1]=arguments[a];return e.apply(void 0,[M(r,t)].concat(i))}},I=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:x;return function(t){return function(r,n){return t(R(r,e,n))}}},L=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:x;return function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return function(){for(var n=arguments.length,i=Array(n),a=0;n>a;a++)i[a]=arguments[a];if(r>=i.length)throw Error("Message in request could not be serialized. "+"Expected message in position ".concat(r," but only received ").concat(i.length," args."));return i[r]=M(i[r],e),t.apply(void 0,i)}}};function _(){var e;try{e=self.chrome||self.browser||browser}catch(t){e=browser}if(!e)throw Error("Browser API is not present");return e}var D="\nLooks like there is an error in the background page. You might want to inspect your background page for more details.\n",q={channelName:"webext.channel",state:{},serializer:x,deserializer:x,patchStrategy:function(e,t){var r=Object.assign({},e);return t.forEach((function(e){var t=e.key,n=e.value;switch(e.change){case"updated":r[t]=n;break;case"removed":Reflect.deleteProperty(r,t)}})),r}};function T(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return 0===t.length?function(e){return e}:1===t.length?t[0]:t.reduce((function(e,t){return function(){return e(t.apply(void 0,arguments))}}))}var C=function(){var e=function(){},t=new Promise((function(t){return e=t}));return{setListener:e,listener:function(e,r,n){return t.then((function(t){t(e,r,n)})),!0}}},F={channelName:"webext.channel",dispatchResponder:function(e,t){Promise.resolve(e).then((function(e){t({error:null,value:e})})).catch((function(e){console.error("error dispatching result:",e),t({error:e.message,value:null})}))},serializer:x,deserializer:x,diffStrategy:function(e,t){var r=[];return Object.keys(t).forEach((function(n){e[n]!==t[n]&&r.push({key:n,value:t[n],change:"updated"})})),Object.keys(e).forEach((function(e){t.hasOwnProperty(e)||r.push({key:e,change:"removed"})})),r}};e.Store=function(){return e=function e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:q,i=n.channelName,a=void 0===i?q.channelName:i,o=n.state,c=void 0===o?q.state:o,u=n.serializer,s=void 0===u?q.serializer:u,l=n.deserializer,f=void 0===l?q.deserializer:l,h=n.patchStrategy,d=void 0===h?q.patchStrategy:h;if(r(this,e),!a)throw Error("channelName is required in options");if("function"!=typeof s)throw Error("serializer must be a function");if("function"!=typeof f)throw Error("deserializer must be a function");if("function"!=typeof d)throw Error("patchStrategy must be one of the included patching strategies or a custom patching function");this.channelName=a,this.readyResolved=!1,this.readyPromise=new Promise((function(e){return t.readyResolve=e})),this.browserAPI=_(),this.initializeStore=this.initializeStore.bind(this),this.browserAPI.runtime.sendMessage({type:"webext.fetch_state",channelName:a},void 0,this.initializeStore),this.deserializer=f,this.serializedPortListener=I(f)((function(){var e;return(e=t.browserAPI.runtime.onMessage).addListener.apply(e,arguments)})),this.serializedMessageSender=L(s)((function(){var e;return(e=t.browserAPI.runtime).sendMessage.apply(e,arguments)})),this.listeners=[],this.state=c,this.patchStrategy=d;var p=function(e){return!!e&&"string"==typeof e.type&&e.channelName===t.channelName};this.serializedPortListener((function(e){if(e&&e.channelName===t.channelName)switch(e.type){case"webext.state":t.replaceState(e.payload),t.readyResolved||(t.readyResolved=!0,t.readyResolve());break;case"webext.patch_state":t.patchState(e.payload)}}),p),this.dispatch=this.dispatch.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)},(t=[{key:"ready",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return null!==e?this.readyPromise.then(e):this.readyPromise}},{key:"subscribe",value:function(e){var t=this;return this.listeners.push(e),function(){t.listeners=t.listeners.filter((function(t){return t!==e}))}}},{key:"patchState",value:function(e){this.state=this.patchStrategy(this.state,e),this.listeners.forEach((function(e){return e()}))}},{key:"replaceState",value:function(e){this.state=e,this.listeners.forEach((function(e){return e()}))}},{key:"getState",value:function(){return this.state}},{key:"replaceReducer",value:function(){}},{key:"dispatch",value:function(e){var t=this;return new Promise((function(r,n){t.serializedMessageSender({type:"webext.dispatch",channelName:t.channelName,payload:e},null,(function(e){if(e){var i=e.error,a=e.value;if(i){var o=Error("".concat(D).concat(i));n(k(o,i))}else r(a&&a.payload)}else{var c=t.browserAPI.runtime.lastError,u=Error("".concat(D).concat(c));n(k(u,c))}}))}))}},{key:"initializeStore",value:function(e){e&&"webext.fetch_state"===e.type&&(this.replaceState(e.payload),this.readyResolved||(this.readyResolved=!0,this.readyResolve()))}}])&&n(e.prototype,t),i&&n(e,i),Object.defineProperty(e,"prototype",{writable:!1}),e;var e,t,i}(),e.alias=function(e){return function(){return function(t){return function(r){var n=e[r.type];return t(n?n(r):r)}}}},e.applyMiddleware=function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];var i=function(){throw Error("Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")},a={getState:e.getState.bind(e),dispatch:function(){return i.apply(void 0,arguments)}};return r=(r||[]).map((function(e){return e(a)})),i=T.apply(void 0,u(r))(e.dispatch),e.dispatch=i,e},e.createWrapStore=function(){var e=_(),t=C(),r=C();return e.runtime.onMessage.addListener(t.listener),e.runtime.onMessage.addListener(r.listener),function(n){var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:F,o=a.channelName,c=void 0===o?F.channelName:o,u=a.dispatchResponder,s=void 0===u?F.dispatchResponder:u,l=a.serializer,f=void 0===l?F.serializer:l,h=a.deserializer,d=void 0===h?F.deserializer:h,p=a.diffStrategy,y=void 0===p?F.diffStrategy:p;if(!c)throw Error("channelName is required in options");if("function"!=typeof f)throw Error("serializer must be a function");if("function"!=typeof d)throw Error("deserializer must be a function");if("function"!=typeof y)throw Error("diffStrategy must be one of the included diffing strategies or a custom diff function");var v=function(e,t,r){if("webext.dispatch"===e.type&&e.channelName===c){var i=Object.assign({},e.payload,{_sender:t}),a=null;try{a=n.dispatch(i)}catch(e){a=Promise.reject(e.message),console.error(e)}return s(a,r),!0}},b=L(f)((function(){for(var t,r=arguments.length,n=Array(r),a=0;r>a;a++)n[a]=arguments[a];var o=function(){};return(t=e.runtime).sendMessage.apply(t,n.concat([o])),e.tabs.query({},(function(t){var r,a=i(t);try{for(a.s();!(r=a.n()).done;){var c;(c=e.tabs).sendMessage.apply(c,[r.value.id].concat(n,[o]))}}catch(e){a.e(e)}finally{a.f()}}))})),g=n.getState(),m=function(){var e=n.getState(),t=y(g,e);t.length&&(g=e,b({type:"webext.patch_state",payload:t,channelName:c}))};n.subscribe(m),b({type:"webext.state",payload:g,channelName:c});var w=I(d),S=function(e){return"webext.dispatch"===e.type&&e.channelName===c};t.setListener((function(e,t,r){var i=n.getState();"webext.fetch_state"===e.type&&e.channelName===c&&r({type:"webext.fetch_state",payload:i})})),w(r.setListener)(v,S)}},Object.defineProperty(e,"__esModule",{value:!0})})); |
@@ -7,8 +7,18 @@ import * as redux from "redux"; | ||
export class Store<S = any, A extends redux.Action = redux.AnyAction> { | ||
/** | ||
/** | ||
* Creates a new Proxy store | ||
* @param options An object of form {portName, state}, where `portName` is a required string and defines the name of the port for state transition changes and `state` is the initial state of this store (default `{}`) | ||
* @param {object} options | ||
* @param {string} options.channelName The name of the channel for this store. | ||
* @param {object} options.state The initial state of the store (default | ||
* `{}`). | ||
* @param {function} options.serializer A function to serialize outgoing | ||
* messages (default is passthrough). | ||
* @param {function} options.deserializer A function to deserialize incoming | ||
* messages (default is passthrough). | ||
* @param {function} options.patchStrategy A function to patch the state with | ||
* incoming messages. Use one of the included patching strategies or a custom | ||
* patching function. (default is shallow diff). | ||
*/ | ||
constructor(options?: { | ||
portName?: string; | ||
channelName?: string; | ||
state?: any; | ||
@@ -86,3 +96,3 @@ serializer?: Function; | ||
configuration?: { | ||
portName?: string; | ||
channelName?: string; | ||
dispatchResponder?( | ||
@@ -89,0 +99,0 @@ dispatchResult: any, |
@@ -6,4 +6,3 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
exports["default"] = void 0; | ||
/** | ||
@@ -14,3 +13,3 @@ * Simple middleware intercepts actions and replaces with | ||
*/ | ||
var _default = function _default(aliases) { | ||
var _default = exports["default"] = function _default(aliases) { | ||
return function () { | ||
@@ -20,7 +19,5 @@ return function (next) { | ||
var alias = aliases[action.type]; | ||
if (alias) { | ||
return next(alias(action)); | ||
} | ||
return next(action); | ||
@@ -30,4 +27,2 @@ }; | ||
}; | ||
}; | ||
exports.default = _default; | ||
}; |
@@ -6,22 +6,20 @@ "use strict"; | ||
}); | ||
exports.DEFAULT_PORT_NAME = exports.PATCH_STATE_TYPE = exports.STATE_TYPE = exports.FETCH_STATE_TYPE = exports.DISPATCH_TYPE = void 0; | ||
exports.STATE_TYPE = exports.PATCH_STATE_TYPE = exports.FETCH_STATE_TYPE = exports.DISPATCH_TYPE = exports.DEFAULT_CHANNEL_NAME = void 0; | ||
// Message type used for dispatch events | ||
// from the Proxy Stores to background | ||
var DISPATCH_TYPE = 'chromex.dispatch'; // Message type for fetching current state from | ||
var DISPATCH_TYPE = exports.DISPATCH_TYPE = "webext.dispatch"; | ||
// Message type for fetching current state from | ||
// background to Proxy Stores | ||
var FETCH_STATE_TYPE = exports.FETCH_STATE_TYPE = "webext.fetch_state"; | ||
exports.DISPATCH_TYPE = DISPATCH_TYPE; | ||
var FETCH_STATE_TYPE = 'chromex.fetch_state'; // Message type for state update events from | ||
// Message type for state update events from | ||
// background to Proxy Stores | ||
var STATE_TYPE = exports.STATE_TYPE = "webext.state"; | ||
exports.FETCH_STATE_TYPE = FETCH_STATE_TYPE; | ||
var STATE_TYPE = 'chromex.state'; // Message type for state patch events from | ||
// Message type for state patch events from | ||
// background to Proxy Stores | ||
var PATCH_STATE_TYPE = exports.PATCH_STATE_TYPE = "webext.patch_state"; | ||
exports.STATE_TYPE = STATE_TYPE; | ||
var PATCH_STATE_TYPE = 'chromex.patch_state'; // The default name for the port communication via | ||
// react-chrome-redux | ||
exports.PATCH_STATE_TYPE = PATCH_STATE_TYPE; | ||
var DEFAULT_PORT_NAME = "chromex.port_name"; | ||
exports.DEFAULT_PORT_NAME = DEFAULT_PORT_NAME; | ||
// The default name for the store channel | ||
var DEFAULT_CHANNEL_NAME = exports.DEFAULT_CHANNEL_NAME = "webext.channel"; |
@@ -9,32 +9,27 @@ "use strict"; | ||
get: function get() { | ||
return _Store.default; | ||
return _Store["default"]; | ||
} | ||
}); | ||
Object.defineProperty(exports, "applyMiddleware", { | ||
Object.defineProperty(exports, "alias", { | ||
enumerable: true, | ||
get: function get() { | ||
return _applyMiddleware.default; | ||
return _alias["default"]; | ||
} | ||
}); | ||
Object.defineProperty(exports, "createWrapStore", { | ||
Object.defineProperty(exports, "applyMiddleware", { | ||
enumerable: true, | ||
get: function get() { | ||
return _wrapStore.default; | ||
return _applyMiddleware["default"]; | ||
} | ||
}); | ||
Object.defineProperty(exports, "alias", { | ||
Object.defineProperty(exports, "createWrapStore", { | ||
enumerable: true, | ||
get: function get() { | ||
return _alias.default; | ||
return _wrapStore["default"]; | ||
} | ||
}); | ||
var _Store = _interopRequireDefault(require("./store/Store")); | ||
var _applyMiddleware = _interopRequireDefault(require("./store/applyMiddleware")); | ||
var _wrapStore = _interopRequireDefault(require("./wrap-store/wrapStore")); | ||
var _alias = _interopRequireDefault(require("./alias/alias")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } |
@@ -7,18 +7,15 @@ "use strict"; | ||
exports.createDeferredListener = void 0; | ||
var createDeferredListener = function createDeferredListener() { | ||
var createDeferredListener = exports.createDeferredListener = function createDeferredListener() { | ||
var resolve = function resolve() {}; | ||
var fnPromise = new Promise(function (resolve_) { | ||
return resolve = resolve_; | ||
}); | ||
var listener = function listener(message, sender, sendResponse) { | ||
fnPromise.then(function (fn) { | ||
fn(message, sender, sendResponse); | ||
}); // Allow response to be async | ||
}); | ||
// Allow response to be async | ||
return true; | ||
}; | ||
return { | ||
@@ -28,4 +25,2 @@ setListener: resolve, | ||
}; | ||
}; | ||
exports.createDeferredListener = createDeferredListener; | ||
}; |
@@ -7,24 +7,20 @@ "use strict"; | ||
exports.withSerializer = exports.withDeserializer = exports.noop = void 0; | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
var noop = function noop(payload) { | ||
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } | ||
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } | ||
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
var noop = exports.noop = function noop(payload) { | ||
return payload; | ||
}; | ||
exports.noop = noop; | ||
var transformPayload = function transformPayload(message) { | ||
var transformer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop; | ||
return _objectSpread({}, message, message.payload ? { | ||
return _objectSpread(_objectSpread({}, message), message.payload ? { | ||
payload: transformer(message.payload) | ||
} : {}); | ||
}; | ||
var deserializeListener = function deserializeListener(listener) { | ||
var deserializer = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : noop; | ||
var shouldDeserialize = arguments.length > 2 ? arguments[2] : undefined; | ||
// If a shouldDeserialize function is passed, return a function that uses it | ||
@@ -37,12 +33,9 @@ // to check if any given message payload should be deserialized | ||
} | ||
if (shouldDeserialize.apply(void 0, [message].concat(args))) { | ||
return listener.apply(void 0, [transformPayload(message, deserializer)].concat(args)); | ||
} | ||
return listener.apply(void 0, [message].concat(args)); | ||
}; | ||
} // Otherwise, return a function that tries to deserialize on every message | ||
} | ||
// Otherwise, return a function that tries to deserialize on every message | ||
return function (message) { | ||
@@ -52,6 +45,6 @@ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
} | ||
return listener.apply(void 0, [transformPayload(message, deserializer)].concat(args)); | ||
}; | ||
}; | ||
/** | ||
@@ -93,5 +86,3 @@ * A function returned from withDeserializer that, when called, wraps addListenerFn with the | ||
*/ | ||
var withDeserializer = function withDeserializer() { | ||
var withDeserializer = exports.withDeserializer = function withDeserializer() { | ||
var deserializer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop; | ||
@@ -104,2 +95,3 @@ return function (addListenerFn) { | ||
}; | ||
/** | ||
@@ -119,7 +111,3 @@ * Given a serializer, returns a function that takes a message sending | ||
*/ | ||
exports.withDeserializer = withDeserializer; | ||
var withSerializer = function withSerializer() { | ||
var withSerializer = exports.withSerializer = function withSerializer() { | ||
var serializer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : noop; | ||
@@ -132,7 +120,5 @@ return function (sendMessageFn) { | ||
} | ||
if (args.length <= messageArgIndex) { | ||
throw new Error("Message in request could not be serialized. " + "Expected message in position ".concat(messageArgIndex, " but only received ").concat(args.length, " args.")); | ||
} | ||
args[messageArgIndex] = transformPayload(args[messageArgIndex], serializer); | ||
@@ -142,4 +128,2 @@ return sendMessageFn.apply(void 0, args); | ||
}; | ||
}; | ||
exports.withSerializer = withSerializer; | ||
}; |
@@ -6,12 +6,9 @@ "use strict"; | ||
}); | ||
exports.default = applyMiddleware; | ||
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } | ||
function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } | ||
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } | ||
exports["default"] = applyMiddleware; | ||
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); } | ||
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } | ||
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } | ||
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); } | ||
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); } | ||
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } | ||
// Function taken from redux source | ||
@@ -23,3 +20,2 @@ // https://github.com/reactjs/redux/blob/master/src/compose.js | ||
} | ||
if (funcs.length === 0) { | ||
@@ -30,7 +26,5 @@ return function (arg) { | ||
} | ||
if (funcs.length === 1) { | ||
return funcs[0]; | ||
} | ||
return funcs.reduce(function (a, b) { | ||
@@ -41,6 +35,6 @@ return function () { | ||
}); | ||
} // Based on redux implementation of applyMiddleware to support all standard | ||
} | ||
// Based on redux implementation of applyMiddleware to support all standard | ||
// redux middlewares | ||
function applyMiddleware(store) { | ||
@@ -50,7 +44,5 @@ for (var _len2 = arguments.length, middlewares = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { | ||
} | ||
var _dispatch = function dispatch() { | ||
throw new Error('Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.'); | ||
}; | ||
var middlewareAPI = { | ||
@@ -57,0 +49,0 @@ getState: store.getState.bind(store), |
@@ -6,72 +6,65 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
exports["default"] = void 0; | ||
var _lodash = _interopRequireDefault(require("lodash.assignin")); | ||
var _constants = require("../constants"); | ||
var _serialization = require("../serialization"); | ||
var _patch = _interopRequireDefault(require("../strategies/shallowDiff/patch")); | ||
var _util = require("../util"); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } | ||
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } | ||
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } | ||
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } | ||
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } | ||
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
var backgroundErrPrefix = '\nLooks like there is an error in the background page. ' + 'You might want to inspect your background page for more details.\n'; | ||
var defaultOpts = { | ||
portName: _constants.DEFAULT_PORT_NAME, | ||
channelName: _constants.DEFAULT_CHANNEL_NAME, | ||
state: {}, | ||
serializer: _serialization.noop, | ||
deserializer: _serialization.noop, | ||
patchStrategy: _patch.default | ||
patchStrategy: _patch["default"] | ||
}; | ||
var Store = | ||
/*#__PURE__*/ | ||
function () { | ||
var Store = /*#__PURE__*/function () { | ||
/** | ||
* Creates a new Proxy store | ||
* @param {object} options An object of form {portName, state, serializer, deserializer, diffStrategy}, where `portName` is a required string and defines the name of the port for state transition changes, `state` is the initial state of this store (default `{}`) `serializer` is a function to serialize outgoing message payloads (default is passthrough), `deserializer` is a function to deserialize incoming message payloads (default is passthrough), and patchStrategy is one of the included patching strategies (default is shallow diff) or a custom patching function. | ||
* @param {object} options | ||
* @param {string} options.channelName The name of the channel for this store. | ||
* @param {object} options.state The initial state of the store (default | ||
* `{}`). | ||
* @param {function} options.serializer A function to serialize outgoing | ||
* messages (default is passthrough). | ||
* @param {function} options.deserializer A function to deserialize incoming | ||
* messages (default is passthrough). | ||
* @param {function} options.patchStrategy A function to patch the state with | ||
* incoming messages. Use one of the included patching strategies or a custom | ||
* patching function. (default is shallow diff). | ||
*/ | ||
function Store() { | ||
var _this = this; | ||
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultOpts, | ||
_ref$portName = _ref.portName, | ||
portName = _ref$portName === void 0 ? defaultOpts.portName : _ref$portName, | ||
_ref$state = _ref.state, | ||
state = _ref$state === void 0 ? defaultOpts.state : _ref$state, | ||
_ref$serializer = _ref.serializer, | ||
serializer = _ref$serializer === void 0 ? defaultOpts.serializer : _ref$serializer, | ||
_ref$deserializer = _ref.deserializer, | ||
deserializer = _ref$deserializer === void 0 ? defaultOpts.deserializer : _ref$deserializer, | ||
_ref$patchStrategy = _ref.patchStrategy, | ||
patchStrategy = _ref$patchStrategy === void 0 ? defaultOpts.patchStrategy : _ref$patchStrategy; | ||
_ref$channelName = _ref.channelName, | ||
channelName = _ref$channelName === void 0 ? defaultOpts.channelName : _ref$channelName, | ||
_ref$state = _ref.state, | ||
state = _ref$state === void 0 ? defaultOpts.state : _ref$state, | ||
_ref$serializer = _ref.serializer, | ||
serializer = _ref$serializer === void 0 ? defaultOpts.serializer : _ref$serializer, | ||
_ref$deserializer = _ref.deserializer, | ||
deserializer = _ref$deserializer === void 0 ? defaultOpts.deserializer : _ref$deserializer, | ||
_ref$patchStrategy = _ref.patchStrategy, | ||
patchStrategy = _ref$patchStrategy === void 0 ? defaultOpts.patchStrategy : _ref$patchStrategy; | ||
_classCallCheck(this, Store); | ||
if (!portName) { | ||
throw new Error('portName is required in options'); | ||
if (!channelName) { | ||
throw new Error('channelName is required in options'); | ||
} | ||
if (typeof serializer !== 'function') { | ||
throw new Error('serializer must be a function'); | ||
} | ||
if (typeof deserializer !== 'function') { | ||
throw new Error('deserializer must be a function'); | ||
} | ||
if (typeof patchStrategy !== 'function') { | ||
throw new Error('patchStrategy must be one of the included patching strategies or a custom patching function'); | ||
} | ||
this.portName = portName; | ||
this.channelName = channelName; | ||
this.readyResolved = false; | ||
@@ -82,7 +75,8 @@ this.readyPromise = new Promise(function (resolve) { | ||
this.browserAPI = (0, _util.getBrowserAPI)(); | ||
this.initializeStore = this.initializeStore.bind(this); // We request the latest available state data to initialise our store | ||
this.initializeStore = this.initializeStore.bind(this); | ||
// We request the latest available state data to initialise our store | ||
this.browserAPI.runtime.sendMessage({ | ||
type: _constants.FETCH_STATE_TYPE, | ||
portName: portName | ||
channelName: channelName | ||
}, undefined, this.initializeStore); | ||
@@ -92,3 +86,2 @@ this.deserializer = deserializer; | ||
var _this$browserAPI$runt; | ||
return (_this$browserAPI$runt = _this.browserAPI.runtime.onMessage).addListener.apply(_this$browserAPI$runt, arguments); | ||
@@ -98,35 +91,42 @@ }); | ||
var _this$browserAPI$runt2; | ||
return (_this$browserAPI$runt2 = _this.browserAPI.runtime).sendMessage.apply(_this$browserAPI$runt2, arguments); | ||
}, 0); | ||
}); | ||
this.listeners = []; | ||
this.state = state; | ||
this.patchStrategy = patchStrategy; // Don't use shouldDeserialize here, since no one else should be using this port | ||
this.patchStrategy = patchStrategy; | ||
/** | ||
* Determine if the message should be run through the deserializer. We want | ||
* to skip processing messages that probably didn't come from this library. | ||
* Note that the listener below is still called for each message so it needs | ||
* its own guard, the shouldDeserialize predicate only skips _deserializing_ | ||
* the message. | ||
*/ | ||
var shouldDeserialize = function shouldDeserialize(message) { | ||
return Boolean(message) && typeof message.type === "string" && message.channelName === _this.channelName; | ||
}; | ||
this.serializedPortListener(function (message) { | ||
if (message.portName === _this.portName) { | ||
switch (message.type) { | ||
case _constants.STATE_TYPE: | ||
_this.replaceState(message.payload); | ||
if (!_this.readyResolved) { | ||
_this.readyResolved = true; | ||
_this.readyResolve(); | ||
} | ||
break; | ||
case _constants.PATCH_STATE_TYPE: | ||
_this.patchState(message.payload); | ||
break; | ||
default: // do nothing | ||
} | ||
if (!message || message.channelName !== _this.channelName) { | ||
return; | ||
} | ||
}); | ||
switch (message.type) { | ||
case _constants.STATE_TYPE: | ||
_this.replaceState(message.payload); | ||
if (!_this.readyResolved) { | ||
_this.readyResolved = true; | ||
_this.readyResolve(); | ||
} | ||
break; | ||
case _constants.PATCH_STATE_TYPE: | ||
_this.patchState(message.payload); | ||
break; | ||
default: | ||
// do nothing | ||
} | ||
}, shouldDeserialize); | ||
this.dispatch = this.dispatch.bind(this); // add this context to dispatch | ||
this.getState = this.getState.bind(this); // add this context to getState | ||
this.subscribe = this.subscribe.bind(this); // add this context to subscribe | ||
} | ||
/** | ||
@@ -137,15 +137,12 @@ * Returns a promise that resolves when the store is ready. Optionally a callback may be passed in instead. | ||
*/ | ||
_createClass(Store, [{ | ||
return _createClass(Store, [{ | ||
key: "ready", | ||
value: function ready() { | ||
var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; | ||
if (cb !== null) { | ||
return this.readyPromise.then(cb); | ||
} | ||
return this.readyPromise; | ||
} | ||
/** | ||
@@ -156,3 +153,2 @@ * Subscribes a listener function for all state changes | ||
*/ | ||
}, { | ||
@@ -162,3 +158,2 @@ key: "subscribe", | ||
var _this2 = this; | ||
this.listeners.push(listener); | ||
@@ -171,2 +166,3 @@ return function () { | ||
} | ||
/** | ||
@@ -176,3 +172,2 @@ * Replaces the state for only the keys in the updated state. Notifies all listeners of state change. | ||
*/ | ||
}, { | ||
@@ -186,2 +181,3 @@ key: "patchState", | ||
} | ||
/** | ||
@@ -191,3 +187,2 @@ * Replace the current state with a new state. Notifies all listeners of state change. | ||
*/ | ||
}, { | ||
@@ -201,2 +196,3 @@ key: "replaceState", | ||
} | ||
/** | ||
@@ -206,3 +202,2 @@ * Get the current state of the store | ||
*/ | ||
}, { | ||
@@ -213,6 +208,6 @@ key: "getState", | ||
} | ||
/** | ||
* Stub function to stay consistent with Redux Store API. No-op. | ||
*/ | ||
}, { | ||
@@ -223,2 +218,3 @@ key: "replaceReducer", | ||
} | ||
/** | ||
@@ -229,3 +225,2 @@ * Dispatch an action to the background using messaging passing | ||
*/ | ||
}, { | ||
@@ -235,7 +230,6 @@ key: "dispatch", | ||
var _this3 = this; | ||
return new Promise(function (resolve, reject) { | ||
_this3.serializedMessageSender({ | ||
type: _constants.DISPATCH_TYPE, | ||
portName: _this3.portName, | ||
channelName: _this3.channelName, | ||
payload: data | ||
@@ -246,13 +240,10 @@ }, null, function (resp) { | ||
var bgErr = new Error("".concat(backgroundErrPrefix).concat(_error)); | ||
reject((0, _lodash.default)(bgErr, _error)); | ||
reject((0, _lodash["default"])(bgErr, _error)); | ||
return; | ||
} | ||
var error = resp.error, | ||
value = resp.value; | ||
value = resp.value; | ||
if (error) { | ||
var _bgErr = new Error("".concat(backgroundErrPrefix).concat(error)); | ||
reject((0, _lodash.default)(_bgErr, error)); | ||
reject((0, _lodash["default"])(_bgErr, error)); | ||
} else { | ||
@@ -268,4 +259,5 @@ resolve(value && value.payload); | ||
if (message && message.type === _constants.FETCH_STATE_TYPE) { | ||
this.replaceState(message.payload); // Resolve if readyPromise has not been resolved. | ||
this.replaceState(message.payload); | ||
// Resolve if readyPromise has not been resolved. | ||
if (!this.readyResolved) { | ||
@@ -278,7 +270,3 @@ this.readyResolved = true; | ||
}]); | ||
return Store; | ||
}(); | ||
var _default = Store; | ||
exports.default = _default; | ||
var _default = exports["default"] = Store; |
@@ -6,12 +6,9 @@ "use strict"; | ||
}); | ||
exports.DIFF_STATUS_ARRAY_UPDATED = exports.DIFF_STATUS_KEYS_UPDATED = exports.DIFF_STATUS_REMOVED = exports.DIFF_STATUS_UPDATED = void 0; | ||
exports.DIFF_STATUS_UPDATED = exports.DIFF_STATUS_REMOVED = exports.DIFF_STATUS_KEYS_UPDATED = exports.DIFF_STATUS_ARRAY_UPDATED = void 0; | ||
// The `change` value for updated or inserted fields resulting from shallow diff | ||
var DIFF_STATUS_UPDATED = 'updated'; // The `change` value for removed fields resulting from shallow diff | ||
var DIFF_STATUS_UPDATED = exports.DIFF_STATUS_UPDATED = 'updated'; | ||
exports.DIFF_STATUS_UPDATED = DIFF_STATUS_UPDATED; | ||
var DIFF_STATUS_REMOVED = 'removed'; | ||
exports.DIFF_STATUS_REMOVED = DIFF_STATUS_REMOVED; | ||
var DIFF_STATUS_KEYS_UPDATED = 'updated_keys'; | ||
exports.DIFF_STATUS_KEYS_UPDATED = DIFF_STATUS_KEYS_UPDATED; | ||
var DIFF_STATUS_ARRAY_UPDATED = 'updated_array'; | ||
exports.DIFF_STATUS_ARRAY_UPDATED = DIFF_STATUS_ARRAY_UPDATED; | ||
// The `change` value for removed fields resulting from shallow diff | ||
var DIFF_STATUS_REMOVED = exports.DIFF_STATUS_REMOVED = 'removed'; | ||
var DIFF_STATUS_KEYS_UPDATED = exports.DIFF_STATUS_KEYS_UPDATED = 'updated_keys'; | ||
var DIFF_STATUS_ARRAY_UPDATED = exports.DIFF_STATUS_ARRAY_UPDATED = 'updated_array'; |
@@ -7,3 +7,2 @@ "use strict"; | ||
exports.applyPatch = applyPatch; | ||
/** | ||
@@ -19,7 +18,5 @@ * Patches an array based on a patch description returning the patched array. | ||
var sameStart = 0; | ||
for (var i = 0; i < patch.length; ++i) { | ||
var patchItem = patch[i]; | ||
sameStart !== patchItem.oldPos && segments.push(a.slice(sameStart, patchItem.oldPos)); | ||
if (patchItem.type === "add") { | ||
@@ -34,6 +31,6 @@ segments.push(patchItem.items); | ||
} | ||
sameStart !== a.length && segments.push(a.slice(sameStart)); | ||
sameStart !== a.length && segments.push(a.slice(sameStart)); // eslint-disable-next-line prefer-reflect | ||
// eslint-disable-next-line prefer-reflect | ||
return [].concat.apply([], segments); | ||
} |
@@ -7,7 +7,4 @@ "use strict"; | ||
exports.diff = diff; | ||
var _lcs = _interopRequireDefault(require("./lcs")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } | ||
/** | ||
@@ -29,3 +26,3 @@ * Computes the differences between the two arrays. | ||
}; | ||
(0, _lcs.default)(a, b, compareFunc, function (type, oldArr, oldStart, oldEnd, newArr, newStart, newEnd) { | ||
(0, _lcs["default"])(a, b, compareFunc, function (type, oldArr, oldStart, oldEnd, newArr, newStart, newEnd) { | ||
if (type === "add") { | ||
@@ -32,0 +29,0 @@ for (var i = newStart; i < newEnd; ++i) { |
@@ -6,6 +6,7 @@ "use strict"; | ||
}); | ||
exports.default = bestSubSequence; | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
exports["default"] = bestSubSequence; | ||
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
/* eslint-disable no-bitwise */ | ||
@@ -23,3 +24,3 @@ | ||
var M = a.length, | ||
N = b.length; | ||
N = b.length; | ||
var MAX = M + N; | ||
@@ -29,7 +30,5 @@ var v = { | ||
}; | ||
for (var d = 0; d <= MAX; ++d) { | ||
for (var k = -d; k <= d; k += 2) { | ||
var x = void 0; | ||
if (k === -d || k !== d && v[k - 1] + 1 < v[k + 1]) { | ||
@@ -40,5 +39,3 @@ x = v[k + 1]; | ||
} | ||
var y = x - k; | ||
while (x < M && y < N && compareFunc(a[x], b[y])) { | ||
@@ -48,14 +45,10 @@ x++; | ||
} | ||
if (x === M && y === N) { | ||
return d; | ||
} | ||
v[k] = x; | ||
} | ||
} | ||
return -1; // never reach | ||
} | ||
var Direct = { | ||
@@ -68,2 +61,3 @@ none: 0, | ||
Direct.all = Direct.horizontal | Direct.vertical | Direct.diagonal; | ||
/** | ||
@@ -83,6 +77,3 @@ * | ||
*/ | ||
function getSolution(a, aStart, aEnd, b, bStart, bEnd, d, startDirect, endDirect, compareFunc, elementsChanged) { | ||
var _preview, _preview2; | ||
if (d === 0) { | ||
@@ -94,3 +85,2 @@ elementsChanged("same", a, aStart, aEnd, b, bStart, bEnd); | ||
var addFirst = (startDirect & Direct.vertical ? 1 : 0) + (endDirect & Direct.horizontal ? 1 : 0); | ||
if (removeFirst >= addFirst) { | ||
@@ -103,11 +93,8 @@ aStart !== aEnd && elementsChanged("remove", a, aStart, aEnd, b, bStart, bStart); | ||
} | ||
return; | ||
} | ||
var M = aEnd - aStart, | ||
N = bEnd - bStart; | ||
N = bEnd - bStart; | ||
var HALF = Math.floor(N / 2); | ||
var now = {}; | ||
for (var k = -d - 1; k <= d + 1; ++k) { | ||
@@ -120,13 +107,11 @@ now[k] = { | ||
} | ||
var preview = (_preview = {}, _defineProperty(_preview, -d - 1, { | ||
var preview = _defineProperty(_defineProperty({}, -d - 1, { | ||
d: Infinity, | ||
segments: 0, | ||
direct: Direct.none | ||
}), _defineProperty(_preview, d + 1, { | ||
}), d + 1, { | ||
d: Infinity, | ||
segments: 0, | ||
direct: Direct.none | ||
}), _preview); | ||
}); | ||
for (var y = 0; y <= HALF; ++y) { | ||
@@ -136,6 +121,4 @@ var _ref = [preview, now]; | ||
preview = _ref[1]; | ||
var _loop = function _loop(_k) { | ||
var _loop = function _loop() { | ||
var x = y + _k; | ||
if (y === 0 && x === 0) { | ||
@@ -147,5 +130,4 @@ now[_k] = { | ||
}; | ||
return "continue"; | ||
return 1; // continue | ||
} | ||
var currentPoints = [{ | ||
@@ -160,3 +142,2 @@ direct: Direct.horizontal, | ||
}]; | ||
if (x > 0 && x <= M && y > 0 && y <= N && compareFunc(a[aStart + x - 1], b[bStart + y - 1])) { | ||
@@ -169,3 +150,2 @@ currentPoints.push({ | ||
} | ||
var bestValue = currentPoints.reduce(function (best, info) { | ||
@@ -177,3 +157,2 @@ if (best.d > info.d) { | ||
} | ||
return best; | ||
@@ -188,12 +167,7 @@ }); | ||
}; | ||
for (var _k = -d; _k <= d; ++_k) { | ||
var _ret = _loop(_k); | ||
if (_ret === "continue") continue; | ||
if (_loop()) continue; | ||
} | ||
} | ||
var now2 = {}; | ||
for (var _k2 = -d - 1; _k2 <= d + 1; ++_k2) { | ||
@@ -206,13 +180,11 @@ now2[_k2] = { | ||
} | ||
var preview2 = (_preview2 = {}, _defineProperty(_preview2, -d - 1, { | ||
var preview2 = _defineProperty(_defineProperty({}, -d - 1, { | ||
d: Infinity, | ||
segments: 0, | ||
direct: Direct.none | ||
}), _defineProperty(_preview2, d + 1, { | ||
}), d + 1, { | ||
d: Infinity, | ||
segments: 0, | ||
direct: Direct.none | ||
}), _preview2); | ||
}); | ||
for (var _y = N; _y >= HALF; --_y) { | ||
@@ -222,6 +194,4 @@ var _ref2 = [preview2, now2]; | ||
preview2 = _ref2[1]; | ||
var _loop2 = function _loop2(_k3) { | ||
var _loop2 = function _loop2() { | ||
var x = _y + _k3; | ||
if (_y === N && x === M) { | ||
@@ -233,5 +203,4 @@ now2[_k3] = { | ||
}; | ||
return "continue"; | ||
return 1; // continue | ||
} | ||
var currentPoints = [{ | ||
@@ -246,3 +215,2 @@ direct: Direct.horizontal, | ||
}]; | ||
if (x >= 0 && x < M && _y >= 0 && _y < N && compareFunc(a[aStart + x], b[bStart + _y])) { | ||
@@ -255,3 +223,2 @@ currentPoints.push({ | ||
} | ||
var bestValue = currentPoints.reduce(function (best, info) { | ||
@@ -263,3 +230,2 @@ if (best.d > info.d) { | ||
} | ||
return best; | ||
@@ -274,10 +240,6 @@ }); | ||
}; | ||
for (var _k3 = d; _k3 >= -d; --_k3) { | ||
var _ret2 = _loop2(_k3); | ||
if (_ret2 === "continue") continue; | ||
if (_loop2()) continue; | ||
} | ||
} | ||
var best = { | ||
@@ -289,6 +251,4 @@ k: -1, | ||
}; | ||
for (var _k4 = -d; _k4 <= d; ++_k4) { | ||
var dSum = now[_k4].d + now2[_k4].d; | ||
if (dSum < best.d) { | ||
@@ -301,3 +261,2 @@ best.k = _k4; | ||
var segments = now[_k4].segments + now2[_k4].segments + (now[_k4].segments & now2[_k4].segments ? 0 : 1); | ||
if (segments < best.segments) { | ||
@@ -316,3 +275,2 @@ best.k = _k4; | ||
} | ||
if (HALF + best.k === 0 && HALF === 0) { | ||
@@ -323,6 +281,6 @@ HALF++; | ||
} | ||
getSolution(a, aStart, aStart + HALF + best.k, b, bStart, bStart + HALF, now[best.k].d, startDirect, now2[best.k].direct, compareFunc, elementsChanged); | ||
getSolution(a, aStart + HALF + best.k, aEnd, b, bStart + HALF, bEnd, now2[best.k].d, now[best.k].direct, endDirect, compareFunc, elementsChanged); | ||
} | ||
/** | ||
@@ -335,4 +293,2 @@ * | ||
*/ | ||
function bestSubSequence(a, b, compareFunc, elementsChanged) { | ||
@@ -339,0 +295,0 @@ var d = lcs(a, b, compareFunc); |
@@ -7,7 +7,4 @@ "use strict"; | ||
exports.getPatch = getPatch; | ||
var _lcs = _interopRequireDefault(require("./lcs")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } | ||
/** | ||
@@ -28,2 +25,3 @@ * Computes the patch necessary to turn array a into array b. | ||
var lastRemove = null; | ||
/** | ||
@@ -39,3 +37,2 @@ * | ||
*/ | ||
function pushChange(type, oldArr, oldStart, oldEnd, newArr, newStart, newEnd) { | ||
@@ -46,7 +43,5 @@ if (type === "same") { | ||
} | ||
if (lastAdd) { | ||
patch.push(lastAdd); | ||
} | ||
lastRemove = null; | ||
@@ -63,10 +58,7 @@ lastAdd = null; | ||
} | ||
for (var i = oldStart; i < oldEnd; ++i) { | ||
lastRemove.items.push(oldArr[i]); | ||
} | ||
if (lastAdd) { | ||
lastAdd.oldPos += oldEnd - oldStart; | ||
if (lastRemove.oldPos === oldStart) { | ||
@@ -85,3 +77,2 @@ lastRemove.newPos -= oldEnd - oldStart; | ||
} | ||
for (var _i = newStart; _i < newEnd; ++_i) { | ||
@@ -92,6 +83,5 @@ lastAdd.items.push(newArr[_i]); | ||
} | ||
(0, _lcs.default)(a, b, compareFunc, pushChange); | ||
(0, _lcs["default"])(a, b, compareFunc, pushChange); | ||
pushChange("same", [], 0, 0, [], 0, 0); | ||
return patch; | ||
} |
@@ -6,8 +6,5 @@ "use strict"; | ||
}); | ||
exports.default = _default; | ||
exports["default"] = _default; | ||
var _lcs = _interopRequireDefault(require("./lcs")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } | ||
/** | ||
@@ -25,3 +22,3 @@ * | ||
var ret = []; | ||
(0, _lcs.default)(a, b, compareFunc, function (type, oldArr, oldStart, oldEnd) { | ||
(0, _lcs["default"])(a, b, compareFunc, function (type, oldArr, oldStart, oldEnd) { | ||
if (type === "same") { | ||
@@ -28,0 +25,0 @@ for (var i = oldStart; i < oldEnd; ++i) { |
@@ -12,13 +12,11 @@ "use strict"; | ||
get: function get() { | ||
return _same.default; | ||
return _same["default"]; | ||
} | ||
}); | ||
var _same = _interopRequireDefault(require("./diff/same")); | ||
var _diff = require("./diff/diff"); | ||
Object.keys(_diff).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; | ||
if (key in exports && exports[key] === _diff[key]) return; | ||
Object.defineProperty(exports, key, { | ||
@@ -31,8 +29,7 @@ enumerable: true, | ||
}); | ||
var _patch = require("./diff/patch"); | ||
Object.keys(_patch).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; | ||
if (key in exports && exports[key] === _patch[key]) return; | ||
Object.defineProperty(exports, key, { | ||
@@ -45,8 +42,7 @@ enumerable: true, | ||
}); | ||
var _apply = require("./diff/apply"); | ||
Object.keys(_apply).forEach(function (key) { | ||
if (key === "default" || key === "__esModule") return; | ||
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; | ||
if (key in exports && exports[key] === _apply[key]) return; | ||
Object.defineProperty(exports, key, { | ||
@@ -59,3 +55,2 @@ enumerable: true, | ||
}); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } |
@@ -6,20 +6,15 @@ "use strict"; | ||
}); | ||
exports.default = diffObjects; | ||
exports["default"] = diffObjects; | ||
var _constants = require("../constants"); | ||
var _arrayDiff = require("./arrayDiff"); | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } | ||
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } | ||
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } | ||
var objectConstructor = {}.constructor; | ||
function isObject(o) { | ||
return _typeof(o) === "object" && o !== null && o.constructor === objectConstructor; | ||
} | ||
function shouldTreatAsValue(oldObj, newObj) { | ||
@@ -29,3 +24,2 @@ var bothAreArrays = Array.isArray(oldObj) && Array.isArray(newObj); | ||
} | ||
function diffValues(oldObj, newObj, shouldContinue, context) { | ||
@@ -38,6 +32,6 @@ // If it's null, use the current value | ||
}; | ||
} // If it's a non-object, or if the type is changing, or if it's an array, | ||
} | ||
// If it's a non-object, or if the type is changing, or if it's an array, | ||
// just go with the current value. | ||
if (shouldTreatAsValue(oldObj, newObj) || !shouldContinue(oldObj, newObj, context)) { | ||
@@ -49,3 +43,2 @@ return { | ||
} | ||
if (Array.isArray(oldObj) && Array.isArray(newObj)) { | ||
@@ -56,5 +49,5 @@ return { | ||
}; | ||
} // If it's an object, compute the differences for each key. | ||
} | ||
// If it's an object, compute the differences for each key. | ||
return { | ||
@@ -65,2 +58,3 @@ change: _constants.DIFF_STATUS_KEYS_UPDATED, | ||
} | ||
/** | ||
@@ -81,4 +75,2 @@ * Performs a deep diff on two objects, created a nested list of patches. For objects, each key is compared. | ||
*/ | ||
function diffObjects(oldObj, newObj) { | ||
@@ -89,5 +81,6 @@ var shouldContinue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () { | ||
var context = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; | ||
var difference = []; // For each key in the current state, | ||
var difference = []; | ||
// For each key in the current state, | ||
// get the differences in values. | ||
Object.keys(newObj).forEach(function (key) { | ||
@@ -99,5 +92,6 @@ if (oldObj[key] !== newObj[key]) { | ||
} | ||
}); // For each key previously present, | ||
}); | ||
// For each key previously present, | ||
// record its deletion. | ||
Object.keys(oldObj).forEach(function (key) { | ||
@@ -104,0 +98,0 @@ if (!newObj.hasOwnProperty(key)) { |
@@ -6,8 +6,5 @@ "use strict"; | ||
}); | ||
exports.default = makeDiff; | ||
exports["default"] = makeDiff; | ||
var _diff = _interopRequireDefault(require("./diff")); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } | ||
/** | ||
@@ -27,4 +24,4 @@ * A higher order function that takes a `shouldContinue` function | ||
return function (oldObj, newObj) { | ||
return (0, _diff.default)(oldObj, newObj, shouldContinue); | ||
return (0, _diff["default"])(oldObj, newObj, shouldContinue); | ||
}; | ||
} |
@@ -6,12 +6,11 @@ "use strict"; | ||
}); | ||
exports.default = patchObject; | ||
exports["default"] = patchObject; | ||
var _constants = require("../constants"); | ||
var _arrayDiff = require("./arrayDiff"); | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } | ||
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } | ||
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } | ||
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } | ||
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } | ||
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } | ||
/** | ||
@@ -25,8 +24,8 @@ * Patches the given object according to the specified list of patches. | ||
return obj; | ||
} // Start with a shallow copy of the object. | ||
} | ||
// Start with a shallow copy of the object. | ||
var newObject = _objectSpread({}, obj); | ||
var newObject = _objectSpread({}, obj); // Iterate through the patches. | ||
// Iterate through the patches. | ||
difference.forEach(function (patch) { | ||
@@ -37,14 +36,17 @@ // If the value is an object whose keys are being updated, | ||
newObject[patch.key] = patchObject(newObject[patch.key], patch.value); | ||
} // If the key has been deleted, delete it. | ||
} | ||
// If the key has been deleted, delete it. | ||
else if (patch.change === _constants.DIFF_STATUS_REMOVED) { | ||
Reflect.deleteProperty(newObject, patch.key); | ||
} // If the key has been updated to a new value, update it. | ||
else if (patch.change === _constants.DIFF_STATUS_UPDATED) { | ||
newObject[patch.key] = patch.value; | ||
} // If the value is an array, update it | ||
else if (patch.change === _constants.DIFF_STATUS_ARRAY_UPDATED) { | ||
newObject[patch.key] = (0, _arrayDiff.applyPatch)(newObject[patch.key], patch.value); | ||
} | ||
Reflect.deleteProperty(newObject, patch.key); | ||
} | ||
// If the key has been updated to a new value, update it. | ||
else if (patch.change === _constants.DIFF_STATUS_UPDATED) { | ||
newObject[patch.key] = patch.value; | ||
} | ||
// If the value is an array, update it | ||
else if (patch.change === _constants.DIFF_STATUS_ARRAY_UPDATED) { | ||
newObject[patch.key] = (0, _arrayDiff.applyPatch)(newObject[patch.key], patch.value); | ||
} | ||
}); | ||
return newObject; | ||
} |
@@ -6,6 +6,4 @@ "use strict"; | ||
}); | ||
exports.default = shallowDiff; | ||
exports["default"] = shallowDiff; | ||
var _constants = require("../constants"); | ||
/** | ||
@@ -12,0 +10,0 @@ * Returns a new Object containing only the fields in `new` that differ from `old` |
@@ -6,6 +6,4 @@ "use strict"; | ||
}); | ||
exports.default = _default; | ||
exports["default"] = _default; | ||
var _constants = require("../constants"); | ||
function _default(obj, difference) { | ||
@@ -15,5 +13,4 @@ var newObj = Object.assign({}, obj); | ||
var change = _ref.change, | ||
key = _ref.key, | ||
value = _ref.value; | ||
key = _ref.key, | ||
value = _ref.value; | ||
switch (change) { | ||
@@ -23,9 +20,7 @@ case _constants.DIFF_STATUS_UPDATED: | ||
break; | ||
case _constants.DIFF_STATUS_REMOVED: | ||
Reflect.deleteProperty(newObj, key); | ||
break; | ||
default: // do nothing | ||
default: | ||
// do nothing | ||
} | ||
@@ -32,0 +27,0 @@ }); |
@@ -7,3 +7,2 @@ "use strict"; | ||
exports.getBrowserAPI = getBrowserAPI; | ||
/** | ||
@@ -16,3 +15,2 @@ * Looks for a global browser api, first checking the chrome namespace and then | ||
var api; | ||
try { | ||
@@ -25,8 +23,6 @@ // eslint-disable-next-line no-undef | ||
} | ||
if (!api) { | ||
throw new Error("Browser API is not present"); | ||
} | ||
return api; | ||
} |
@@ -6,16 +6,12 @@ "use strict"; | ||
}); | ||
exports.default = void 0; | ||
exports["default"] = void 0; | ||
var _constants = require("../constants"); | ||
var _serialization = require("../serialization"); | ||
var _util = require("../util"); | ||
var _diff = _interopRequireDefault(require("../strategies/shallowDiff/diff")); | ||
var _listener = require("../listener"); | ||
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } | ||
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } | ||
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } | ||
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } | ||
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } | ||
/** | ||
@@ -33,3 +29,3 @@ * Responder for promisified results | ||
}); | ||
}).catch(function (err) { | ||
})["catch"](function (err) { | ||
console.error("error dispatching result:", err); | ||
@@ -42,10 +38,10 @@ send({ | ||
}; | ||
var defaultOpts = { | ||
portName: _constants.DEFAULT_PORT_NAME, | ||
channelName: _constants.DEFAULT_CHANNEL_NAME, | ||
dispatchResponder: promiseResponder, | ||
serializer: _serialization.noop, | ||
deserializer: _serialization.noop, | ||
diffStrategy: _diff.default | ||
diffStrategy: _diff["default"] | ||
}; | ||
/** | ||
@@ -55,4 +51,3 @@ * @typedef {function} WrapStore | ||
* @param {Object} options | ||
* @param {string} options.portName The name of the port for state transition | ||
* changes. | ||
* @param {string} options.channelName The name of the channel for this store. | ||
* @param {function} options.dispatchResponder A function that takes the result | ||
@@ -76,7 +71,7 @@ * of a store dispatch and optionally implements custom logic for responding to | ||
*/ | ||
var _default = exports["default"] = function _default() { | ||
var browserAPI = (0, _util.getBrowserAPI)(); | ||
var _default = function _default() { | ||
var browserAPI = (0, _util.getBrowserAPI)(); // Setup message listeners synchronously to avoid dropping messages if the | ||
// Setup message listeners synchronously to avoid dropping messages if the | ||
// extension is woken by a message. | ||
var stateProviderListener = (0, _listener.createDeferredListener)(); | ||
@@ -88,35 +83,30 @@ var actionListener = (0, _listener.createDeferredListener)(); | ||
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultOpts, | ||
_ref$portName = _ref.portName, | ||
portName = _ref$portName === void 0 ? defaultOpts.portName : _ref$portName, | ||
_ref$dispatchResponde = _ref.dispatchResponder, | ||
dispatchResponder = _ref$dispatchResponde === void 0 ? defaultOpts.dispatchResponder : _ref$dispatchResponde, | ||
_ref$serializer = _ref.serializer, | ||
serializer = _ref$serializer === void 0 ? defaultOpts.serializer : _ref$serializer, | ||
_ref$deserializer = _ref.deserializer, | ||
deserializer = _ref$deserializer === void 0 ? defaultOpts.deserializer : _ref$deserializer, | ||
_ref$diffStrategy = _ref.diffStrategy, | ||
diffStrategy = _ref$diffStrategy === void 0 ? defaultOpts.diffStrategy : _ref$diffStrategy; | ||
if (!portName) { | ||
throw new Error("portName is required in options"); | ||
_ref$channelName = _ref.channelName, | ||
channelName = _ref$channelName === void 0 ? defaultOpts.channelName : _ref$channelName, | ||
_ref$dispatchResponde = _ref.dispatchResponder, | ||
dispatchResponder = _ref$dispatchResponde === void 0 ? defaultOpts.dispatchResponder : _ref$dispatchResponde, | ||
_ref$serializer = _ref.serializer, | ||
serializer = _ref$serializer === void 0 ? defaultOpts.serializer : _ref$serializer, | ||
_ref$deserializer = _ref.deserializer, | ||
deserializer = _ref$deserializer === void 0 ? defaultOpts.deserializer : _ref$deserializer, | ||
_ref$diffStrategy = _ref.diffStrategy, | ||
diffStrategy = _ref$diffStrategy === void 0 ? defaultOpts.diffStrategy : _ref$diffStrategy; | ||
if (!channelName) { | ||
throw new Error("channelName is required in options"); | ||
} | ||
if (typeof serializer !== "function") { | ||
throw new Error("serializer must be a function"); | ||
} | ||
if (typeof deserializer !== "function") { | ||
throw new Error("deserializer must be a function"); | ||
} | ||
if (typeof diffStrategy !== "function") { | ||
throw new Error("diffStrategy must be one of the included diffing strategies or a custom diff function"); | ||
} | ||
/** | ||
* Respond to dispatches from UI components | ||
*/ | ||
var dispatchResponse = function dispatchResponse(request, sender, sendResponse) { | ||
if (request.type === _constants.DISPATCH_TYPE && request.portName === portName) { | ||
if (request.type === _constants.DISPATCH_TYPE && request.channelName === channelName) { | ||
var action = Object.assign({}, request.payload, { | ||
@@ -126,3 +116,2 @@ _sender: sender | ||
var dispatchResult = null; | ||
try { | ||
@@ -134,3 +123,2 @@ dispatchResult = store.dispatch(action); | ||
} | ||
dispatchResponder(dispatchResult, sendResponse); | ||
@@ -140,49 +128,32 @@ return true; | ||
}; | ||
/** | ||
* Setup for state updates | ||
*/ | ||
var serializedMessagePoster = (0, _serialization.withSerializer)(serializer)(function () { | ||
var _browserAPI$runtime; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
var onErrorCallback = function onErrorCallback() { | ||
if (browserAPI.runtime.lastError) {// do nothing - errors can be present | ||
if (browserAPI.runtime.lastError) { | ||
// do nothing - errors can be present | ||
// if no content script exists on receiver | ||
} | ||
}; | ||
(_browserAPI$runtime = browserAPI.runtime).sendMessage.apply(_browserAPI$runtime, args.concat([onErrorCallback])); // We will broadcast state changes to all tabs to sync state across content scripts | ||
(_browserAPI$runtime = browserAPI.runtime).sendMessage.apply(_browserAPI$runtime, args.concat([onErrorCallback])); | ||
// We will broadcast state changes to all tabs to sync state across content scripts | ||
return browserAPI.tabs.query({}, function (tabs) { | ||
var _iteratorNormalCompletion = true; | ||
var _didIteratorError = false; | ||
var _iteratorError = undefined; | ||
var _iterator = _createForOfIteratorHelper(tabs), | ||
_step; | ||
try { | ||
for (var _iterator = tabs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { | ||
for (_iterator.s(); !(_step = _iterator.n()).done;) { | ||
var _browserAPI$tabs; | ||
var tab = _step.value; | ||
(_browserAPI$tabs = browserAPI.tabs).sendMessage.apply(_browserAPI$tabs, [tab.id].concat(args, [onErrorCallback])); | ||
} | ||
} catch (err) { | ||
_didIteratorError = true; | ||
_iteratorError = err; | ||
_iterator.e(err); | ||
} finally { | ||
try { | ||
if (!_iteratorNormalCompletion && _iterator.return != null) { | ||
_iterator.return(); | ||
} | ||
} finally { | ||
if (_didIteratorError) { | ||
throw _iteratorError; | ||
} | ||
} | ||
_iterator.f(); | ||
} | ||
@@ -192,7 +163,5 @@ }); | ||
var currentState = store.getState(); | ||
var patchState = function patchState() { | ||
var newState = store.getState(); | ||
var diff = diffStrategy(currentState, newState); | ||
if (diff.length) { | ||
@@ -203,31 +172,27 @@ currentState = newState; | ||
payload: diff, | ||
portName: portName // Notifying what extension is broadcasting the state changes | ||
channelName: channelName // Notifying what store is broadcasting the state changes | ||
}); | ||
} | ||
}; // Send patched state down connected port on every redux store state change | ||
}; | ||
// Send patched state to listeners on every redux store state change | ||
store.subscribe(patchState); | ||
store.subscribe(patchState); // Send store's initial state through port | ||
// Send store's initial state | ||
serializedMessagePoster({ | ||
type: _constants.STATE_TYPE, | ||
payload: currentState, | ||
portName: portName // Notifying what extension is broadcasting the state changes | ||
channelName: channelName // Notifying what store is broadcasting the state changes | ||
}); | ||
var withPayloadDeserializer = (0, _serialization.withDeserializer)(deserializer); | ||
var shouldDeserialize = function shouldDeserialize(request) { | ||
return request.type === _constants.DISPATCH_TYPE && request.portName === portName; | ||
return request.type === _constants.DISPATCH_TYPE && request.channelName === channelName; | ||
}; | ||
/** | ||
* State provider for content-script initialization | ||
*/ | ||
stateProviderListener.setListener(function (request, sender, sendResponse) { | ||
var state = store.getState(); | ||
if (request.type === _constants.FETCH_STATE_TYPE && request.portName === portName) { | ||
if (request.type === _constants.FETCH_STATE_TYPE && request.channelName === channelName) { | ||
sendResponse({ | ||
@@ -239,10 +204,8 @@ type: _constants.FETCH_STATE_TYPE, | ||
}); | ||
/** | ||
* Setup action handler | ||
*/ | ||
withPayloadDeserializer(actionListener.setListener)(dispatchResponse, shouldDeserialize); | ||
}; | ||
}; | ||
exports.default = _default; | ||
}; |
{ | ||
"name": "webext-redux", | ||
"version": "3.0.0-mv3.0", | ||
"version": "3.0.0", | ||
"description": "A set of utilities for building Redux applications in Web Extensions.", | ||
@@ -9,9 +9,9 @@ "main": "lib/index.js", | ||
"umd-build": "rollup -c", | ||
"build": "./node_modules/.bin/babel src --out-dir lib && npm run umd-build", | ||
"lint-src": "./node_modules/.bin/eslint src/**/*.js", | ||
"lint-test": "./node_modules/.bin/eslint test/**/*.js", | ||
"build": "babel src --out-dir lib && npm run umd-build", | ||
"lint-src": "eslint src/{**/,}*.js", | ||
"lint-test": "eslint test/{**/,}*.js", | ||
"lint": "npm run lint-src && npm run lint-test", | ||
"prepublishOnly": "npm run build", | ||
"pretest": "./node_modules/.bin/babel src --out-dir lib", | ||
"test-run": "./node_modules/.bin/mocha --require @babel/register --recursive", | ||
"pretest": "babel src --out-dir lib", | ||
"test-run": "mocha --require @babel/register --recursive", | ||
"test": "npm run lint && npm run test-run" | ||
@@ -43,3 +43,3 @@ }, | ||
"mocha": "^5.2.0", | ||
"redux": "^4.0.4", | ||
"redux": "5.0.1", | ||
"rollup": "^1.22.0", | ||
@@ -54,4 +54,4 @@ "rollup-plugin-babel": "^4.3.3", | ||
"peerDependencies": { | ||
"redux": ">= 3 <= 4" | ||
"redux": ">= 3 <= 5" | ||
} | ||
} |
@@ -63,6 +63,7 @@ # WebExt Redux | ||
import {wrapStore} from 'webext-redux'; | ||
import {createWrapStore} from 'webext-redux'; | ||
const store; // a normal Redux store | ||
const wrapStore = createWrapStore() | ||
wrapStore(store); | ||
@@ -73,5 +74,6 @@ ``` | ||
> [!NOTE] | ||
> `createWrapStore()` sets up listeners for browser messaging. In MV3, it must be registered synchronously when the service worker starts. This ensures `dispatch()` calls that wake the service worker are received. Messages are queued internally until `wrapStore()` is called, and the events can be dispatched to the store. | ||
### 3. Optional: Apply any redux middleware to your *Proxy Store* with `applyMiddleware()` | ||
@@ -115,3 +117,3 @@ | ||
import { applyMiddleware, createStore } from 'redux'; | ||
import { alias, wrapStore } from 'webext-redux'; | ||
import { alias } from 'webext-redux'; | ||
@@ -264,6 +266,2 @@ const aliases = { | ||
## Security | ||
`webext-redux` supports `onMessageExternal` which is fired when a message is sent from another extension, app, or website. By default, if `externally_connectable` is not declared in your extension's manifest, all extensions or apps will be able to send messages to your extension, but no websites will be able to. You can follow [this](https://developer.chrome.com/extensions/manifest/externally_connectable) to address your needs appropriately. | ||
## Custom Serialization | ||
@@ -303,4 +301,5 @@ | ||
import {wrapStore} from 'webext-redux'; | ||
import {createWrapStore} from 'webext-redux'; | ||
const wrapStore = createWrapStore(); | ||
const store; // a normal Redux store | ||
@@ -373,5 +372,6 @@ | ||
import {wrapStore} from 'webext-redux'; | ||
import {createWrapStore} from 'webext-redux'; | ||
import deepDiff from 'webext-redux/lib/strategies/deepDiff/diff'; | ||
const wrapStore = createWrapStore(); | ||
const store; // a normal Redux store | ||
@@ -404,5 +404,6 @@ | ||
import {wrapStore} from 'webext-redux'; | ||
import {createWrapStore} from 'webext-redux'; | ||
import makeDiff from 'webext-redux/lib/strategies/deepDiff/makeDiff'; | ||
const wrapStore = createWrapStore(); | ||
const store; // a normal Redux store | ||
@@ -433,3 +434,3 @@ | ||
You can also provide your own diffing and patching strategies, using the `diffStrategy` parameter in `wrapStore` and the `patchStrategy` parameter in `Store`, repsectively. A diffing strategy should be a function that takes two arguments - the old state and the new state - and returns a patch, which can be of any form. A patch strategy is a function that takes two arguments - the old state and a patch - and returns the new state. | ||
You can also provide your own diffing and patching strategies, using the `diffStrategy` parameter in `wrapStore` and the `patchStrategy` parameter in `Store`, respectively. A diffing strategy should be a function that takes two arguments - the old state and the new state - and returns a patch, which can be of any form. A patch strategy is a function that takes two arguments - the old state and a patch - and returns the new state. | ||
When using a custom diffing and patching strategy, you are responsible for making sure that they function as expected; that is, that `patchStrategy(oldState, diffStrategy(oldState, newState))` is equal to `newState`. | ||
@@ -446,3 +447,3 @@ | ||
* [Store](https://github.com/tshaddix/webext-redux/wiki/Store) | ||
* [wrapStore](https://github.com/tshaddix/webext-redux/wiki/wrapStore) | ||
* [createWrapStore](https://github.com/tshaddix/webext-redux/wiki/createWrapStore) | ||
* [alias](https://github.com/tshaddix/webext-redux/wiki/alias) | ||
@@ -449,0 +450,0 @@ |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
New author
Supply chain riskA new npm collaborator published a version of the package for the first time. New collaborators are usually benign additions to a project, but do indicate a change to the security surface area of a package.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
150157
3052
0
470
0