@metamask-previews/notification-services-controller 0.0.0-preview-7ff4bd7f → 0.0.0-preview-bc4ac8fa
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/NotificationServicesController/NotificationServicesController.js +3 -3
- package/dist/NotificationServicesController/NotificationServicesController.mjs +3 -3
- package/dist/NotificationServicesController/index.js +4 -4
- package/dist/NotificationServicesController/index.mjs +4 -4
- package/dist/NotificationServicesController/services/onchain-notifications.js +2 -2
- package/dist/NotificationServicesController/services/onchain-notifications.mjs +1 -1
- package/dist/NotificationServicesPushController/NotificationServicesPushController.js +5 -5
- package/dist/NotificationServicesPushController/NotificationServicesPushController.mjs +5 -5
- package/dist/NotificationServicesPushController/index.js +6 -6
- package/dist/NotificationServicesPushController/index.mjs +6 -6
- package/dist/NotificationServicesPushController/services/push/push-web.js +3 -3
- package/dist/NotificationServicesPushController/services/push/push-web.mjs +3 -3
- package/dist/NotificationServicesPushController/services/services.js +3 -3
- package/dist/NotificationServicesPushController/services/services.mjs +3 -3
- package/dist/NotificationServicesPushController/utils/get-notification-message.js +3 -3
- package/dist/NotificationServicesPushController/utils/get-notification-message.mjs +3 -3
- package/dist/NotificationServicesPushController/utils/index.js +3 -3
- package/dist/NotificationServicesPushController/utils/index.mjs +3 -3
- package/dist/{chunk-RNE2I5IN.mjs → chunk-3F4M3OUO.mjs} +4 -4
- package/dist/chunk-3F4M3OUO.mjs.map +1 -0
- package/dist/{chunk-UZXBH6WS.mjs → chunk-5OYPOYXZ.mjs} +2 -2
- package/dist/chunk-5OYPOYXZ.mjs.map +1 -0
- package/dist/{chunk-DKQBDI4C.js → chunk-5WWCWQCE.js} +1 -1
- package/dist/chunk-5WWCWQCE.js.map +1 -0
- package/dist/{chunk-EG5NZ5DA.js → chunk-6B5FOWRH.js} +5 -5
- package/dist/chunk-6B5FOWRH.js.map +1 -0
- package/dist/{chunk-3O5NGZWB.js → chunk-DNTK4U5M.js} +892 -2266
- package/dist/chunk-DNTK4U5M.js.map +1 -0
- package/dist/{chunk-IG3CMJBW.mjs → chunk-KTQP5UDT.mjs} +898 -2272
- package/dist/chunk-KTQP5UDT.mjs.map +1 -0
- package/dist/{chunk-ODZ6V4PH.mjs → chunk-OUPWMPLU.mjs} +1 -1
- package/dist/chunk-OUPWMPLU.mjs.map +1 -0
- package/dist/chunk-UIRZIKC3.mjs +187 -0
- package/dist/chunk-UIRZIKC3.mjs.map +1 -0
- package/dist/chunk-VOZ7Y2OO.js +187 -0
- package/dist/chunk-VOZ7Y2OO.js.map +1 -0
- package/dist/{chunk-3NF7QYJN.js → chunk-XNBTOK6G.js} +7 -7
- package/dist/chunk-XNBTOK6G.js.map +1 -0
- package/dist/index.js +6 -6
- package/dist/index.mjs +5 -5
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/NotificationServicesController/NotificationServicesController.d.ts +1 -1
- package/dist/types/NotificationServicesController/NotificationServicesController.d.ts.map +1 -1
- package/dist/types/NotificationServicesController/index.d.ts +0 -2
- package/dist/types/NotificationServicesController/index.d.ts.map +1 -1
- package/dist/types/NotificationServicesPushController/NotificationServicesPushController.d.ts +1 -1
- package/dist/types/NotificationServicesPushController/NotificationServicesPushController.d.ts.map +1 -1
- package/dist/types/NotificationServicesPushController/index.d.ts +0 -2
- package/dist/types/NotificationServicesPushController/index.d.ts.map +1 -1
- package/package.json +4 -2
- package/dist/chunk-3NF7QYJN.js.map +0 -1
- package/dist/chunk-3O5NGZWB.js.map +0 -1
- package/dist/chunk-DKQBDI4C.js.map +0 -1
- package/dist/chunk-EG5NZ5DA.js.map +0 -1
- package/dist/chunk-IG3CMJBW.mjs.map +0 -1
- package/dist/chunk-KPO4QJHS.js +0 -965
- package/dist/chunk-KPO4QJHS.js.map +0 -1
- package/dist/chunk-ODZ6V4PH.mjs.map +0 -1
- package/dist/chunk-RNE2I5IN.mjs.map +0 -1
- package/dist/chunk-UZXBH6WS.mjs.map +0 -1
- package/dist/chunk-ZJRT7ACU.mjs +0 -965
- package/dist/chunk-ZJRT7ACU.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/ms/index.js","../../../node_modules/debug/src/common.js","../../../node_modules/debug/src/browser.js","../../../node_modules/nock/lib/common.js","../../../node_modules/propagate/index.js","../../../node_modules/nock/lib/global_emitter.js","../../../node_modules/nock/lib/socket.js","../../../node_modules/nock/lib/playback_interceptor.js","../../../node_modules/nock/lib/intercepted_request_router.js","../../../node_modules/json-stringify-safe/stringify.js","../../../node_modules/nock/lib/match_body.js","../../../node_modules/nock/lib/interceptor.js","../../../node_modules/nock/lib/intercept.js","../../../node_modules/nock/lib/recorder.js","../../../node_modules/nock/lib/scope.js","../../../node_modules/nock/lib/back.js","../../../node_modules/nock/index.js","../../profile-sync-controller/src/sdk/env.ts","../../../node_modules/@noble/ciphers/src/_assert.ts","../../../node_modules/@noble/ciphers/src/utils.ts","../../../node_modules/@noble/ciphers/src/_polyval.ts","../../../node_modules/@noble/ciphers/src/aes.ts","../../../node_modules/@noble/ciphers/src/crypto.ts","../../../node_modules/@noble/ciphers/src/webcrypto.ts","../../../node_modules/@noble/hashes/src/_assert.ts","../../../node_modules/@noble/hashes/src/utils.ts","../../../node_modules/@noble/hashes/src/hmac.ts","../../../node_modules/@noble/hashes/src/pbkdf2.ts","../../../node_modules/@noble/hashes/src/_md.ts","../../../node_modules/@noble/hashes/src/sha256.ts","../../../node_modules/@metamask/snaps-utils/src/handler-types.ts","../../profile-sync-controller/src/controllers/authentication/auth-snap-requests.ts","../../profile-sync-controller/src/controllers/user-storage/index.ts","../../profile-sync-controller/src/controllers/user-storage/UserStorageController.ts","../../../node_modules/@noble/hashes/src/scrypt.ts","../../profile-sync-controller/src/controllers/user-storage/encryption/utils.ts","../../profile-sync-controller/src/controllers/user-storage/encryption/cache.ts","../../profile-sync-controller/src/controllers/user-storage/encryption/encryption.ts","../../profile-sync-controller/src/controllers/user-storage/encryption/index.ts","../../profile-sync-controller/src/controllers/user-storage/services.ts","../../profile-sync-controller/src/controllers/user-storage/schema.ts","../../profile-sync-controller/src/controllers/user-storage/__fixtures__/index.ts","../../profile-sync-controller/src/controllers/user-storage/__fixtures__/mockStorage.ts","../../profile-sync-controller/src/controllers/user-storage/__fixtures__/mockResponses.ts","../../profile-sync-controller/src/controllers/user-storage/__fixtures__/mockServices.ts","../src/NotificationServicesController/services/onchain-notifications.ts"],"sourcesContent":["/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","'use strict'\n\nconst debug = require('debug')('nock.common')\nconst timers = require('timers')\nconst url = require('url')\nconst util = require('util')\n\n/**\n * Normalizes the request options so that it always has `host` property.\n *\n * @param {Object} options - a parsed options object of the request\n */\nfunction normalizeRequestOptions(options) {\n options.proto = options.proto || 'http'\n options.port = options.port || (options.proto === 'http' ? 80 : 443)\n if (options.host) {\n debug('options.host:', options.host)\n if (!options.hostname) {\n if (options.host.split(':').length === 2) {\n options.hostname = options.host.split(':')[0]\n } else {\n options.hostname = options.host\n }\n }\n }\n debug('options.hostname in the end: %j', options.hostname)\n options.host = `${options.hostname || 'localhost'}:${options.port}`\n debug('options.host in the end: %j', options.host)\n\n /// lowercase host names\n ;['hostname', 'host'].forEach(function (attr) {\n if (options[attr]) {\n options[attr] = options[attr].toLowerCase()\n }\n })\n\n return options\n}\n\n/**\n * Returns true if the data contained in buffer can be reconstructed\n * from its utf8 representation.\n *\n * @param {Object} buffer - a Buffer object\n * @returns {boolean}\n */\nfunction isUtf8Representable(buffer) {\n const utfEncodedBuffer = buffer.toString('utf8')\n const reconstructedBuffer = Buffer.from(utfEncodedBuffer, 'utf8')\n return reconstructedBuffer.equals(buffer)\n}\n\n// Array where all information about all the overridden requests are held.\nlet requestOverrides = {}\n\n/**\n * Overrides the current `request` function of `http` and `https` modules with\n * our own version which intercepts issues HTTP/HTTPS requests and forwards them\n * to the given `newRequest` function.\n *\n * @param {Function} newRequest - a function handling requests; it accepts four arguments:\n * - proto - a string with the overridden module's protocol name (either `http` or `https`)\n * - overriddenRequest - the overridden module's request function already bound to module's object\n * - options - the options of the issued request\n * - callback - the callback of the issued request\n */\nfunction overrideRequests(newRequest) {\n debug('overriding requests')\n ;['http', 'https'].forEach(function (proto) {\n debug('- overriding request for', proto)\n\n const moduleName = proto // 1 to 1 match of protocol and module is fortunate :)\n const module = require(proto)\n const overriddenRequest = module.request\n const overriddenGet = module.get\n\n if (requestOverrides[moduleName]) {\n throw new Error(\n `Module's request already overridden for ${moduleName} protocol.`,\n )\n }\n\n // Store the properties of the overridden request so that it can be restored later on.\n requestOverrides[moduleName] = {\n module,\n request: overriddenRequest,\n get: overriddenGet,\n }\n // https://nodejs.org/api/http.html#http_http_request_url_options_callback\n module.request = function (input, options, callback) {\n return newRequest(proto, overriddenRequest.bind(module), [\n input,\n options,\n callback,\n ])\n }\n // https://nodejs.org/api/http.html#http_http_get_options_callback\n module.get = function (input, options, callback) {\n const req = newRequest(proto, overriddenGet.bind(module), [\n input,\n options,\n callback,\n ])\n req.end()\n return req\n }\n\n debug('- overridden request for', proto)\n })\n}\n\n/**\n * Restores `request` function of `http` and `https` modules to values they\n * held before they were overridden by us.\n */\nfunction restoreOverriddenRequests() {\n debug('restoring requests')\n Object.entries(requestOverrides).forEach(\n ([proto, { module, request, get }]) => {\n debug('- restoring request for', proto)\n module.request = request\n module.get = get\n debug('- restored request for', proto)\n },\n )\n requestOverrides = {}\n}\n\n/**\n * In WHATWG URL vernacular, this returns the origin portion of a URL.\n * However, the port is not included if it's standard and not already present on the host.\n */\nfunction normalizeOrigin(proto, host, port) {\n const hostHasPort = host.includes(':')\n const portIsStandard =\n (proto === 'http' && (port === 80 || port === '80')) ||\n (proto === 'https' && (port === 443 || port === '443'))\n const portStr = hostHasPort || portIsStandard ? '' : `:${port}`\n\n return `${proto}://${host}${portStr}`\n}\n\n/**\n * Get high level information about request as string\n * @param {Object} options\n * @param {string} options.method\n * @param {number|string} options.port\n * @param {string} options.proto Set internally. always http or https\n * @param {string} options.hostname\n * @param {string} options.path\n * @param {Object} options.headers\n * @param {string} body\n * @return {string}\n */\nfunction stringifyRequest(options, body) {\n const { method = 'GET', path = '', port } = options\n const origin = normalizeOrigin(options.proto, options.hostname, port)\n\n const log = {\n method,\n url: `${origin}${path}`,\n headers: options.headers,\n }\n\n if (body) {\n log.body = body\n }\n\n return JSON.stringify(log, null, 2)\n}\n\nfunction isContentEncoded(headers) {\n const contentEncoding = headers['content-encoding']\n return typeof contentEncoding === 'string' && contentEncoding !== ''\n}\n\nfunction contentEncoding(headers, encoder) {\n const contentEncoding = headers['content-encoding']\n return contentEncoding !== undefined && contentEncoding.toString() === encoder\n}\n\nfunction isJSONContent(headers) {\n // https://tools.ietf.org/html/rfc8259\n const contentType = String(headers['content-type'] || '').toLowerCase()\n return contentType.startsWith('application/json')\n}\n\n/**\n * Return a new object with all field names of the headers lower-cased.\n *\n * Duplicates throw an error.\n */\nfunction headersFieldNamesToLowerCase(headers, throwOnDuplicate) {\n if (!isPlainObject(headers)) {\n throw Error('Headers must be provided as an object')\n }\n\n const lowerCaseHeaders = {}\n Object.entries(headers).forEach(([fieldName, fieldValue]) => {\n const key = fieldName.toLowerCase()\n if (lowerCaseHeaders[key] !== undefined) {\n if (throwOnDuplicate) {\n throw Error(\n `Failed to convert header keys to lower case due to field name conflict: ${key}`,\n )\n } else {\n debug(\n `Duplicate header provided in request: ${key}. Only the last value can be matched.`,\n )\n }\n }\n lowerCaseHeaders[key] = fieldValue\n })\n\n return lowerCaseHeaders\n}\n\nconst headersFieldsArrayToLowerCase = headers => [\n ...new Set(headers.map(fieldName => fieldName.toLowerCase())),\n]\n\n/**\n * Converts the various accepted formats of headers into a flat array representing \"raw headers\".\n *\n * Nock allows headers to be provided as a raw array, a plain object, or a Map.\n *\n * While all the header names are expected to be strings, the values are left intact as they can\n * be functions, strings, or arrays of strings.\n *\n * https://nodejs.org/api/http.html#http_message_rawheaders\n */\nfunction headersInputToRawArray(headers) {\n if (headers === undefined) {\n return []\n }\n\n if (Array.isArray(headers)) {\n // If the input is an array, assume it's already in the raw format and simply return a copy\n // but throw an error if there aren't an even number of items in the array\n if (headers.length % 2) {\n throw new Error(\n `Raw headers must be provided as an array with an even number of items. [fieldName, value, ...]`,\n )\n }\n return [...headers]\n }\n\n // [].concat(...) is used instead of Array.flat until v11 is the minimum Node version\n if (util.types.isMap(headers)) {\n return [].concat(...Array.from(headers, ([k, v]) => [k.toString(), v]))\n }\n\n if (isPlainObject(headers)) {\n return [].concat(...Object.entries(headers))\n }\n\n throw new Error(\n `Headers must be provided as an array of raw values, a Map, or a plain Object. ${headers}`,\n )\n}\n\n/**\n * Converts an array of raw headers to an object, using the same rules as Nodes `http.IncomingMessage.headers`.\n *\n * Header names/keys are lower-cased.\n */\nfunction headersArrayToObject(rawHeaders) {\n if (!Array.isArray(rawHeaders)) {\n throw Error('Expected a header array')\n }\n\n const accumulator = {}\n\n forEachHeader(rawHeaders, (value, fieldName) => {\n addHeaderLine(accumulator, fieldName, value)\n })\n\n return accumulator\n}\n\nconst noDuplicatesHeaders = new Set([\n 'age',\n 'authorization',\n 'content-length',\n 'content-type',\n 'etag',\n 'expires',\n 'from',\n 'host',\n 'if-modified-since',\n 'if-unmodified-since',\n 'last-modified',\n 'location',\n 'max-forwards',\n 'proxy-authorization',\n 'referer',\n 'retry-after',\n 'user-agent',\n])\n\n/**\n * Set key/value data in accordance with Node's logic for folding duplicate headers.\n *\n * The `value` param should be a function, string, or array of strings.\n *\n * Node's docs and source:\n * https://nodejs.org/api/http.html#http_message_headers\n * https://github.com/nodejs/node/blob/908292cf1f551c614a733d858528ffb13fb3a524/lib/_http_incoming.js#L245\n *\n * Header names are lower-cased.\n * Duplicates in raw headers are handled in the following ways, depending on the header name:\n * - Duplicates of field names listed in `noDuplicatesHeaders` (above) are discarded.\n * - `set-cookie` is always an array. Duplicates are added to the array.\n * - For duplicate `cookie` headers, the values are joined together with '; '.\n * - For all other headers, the values are joined together with ', '.\n *\n * Node's implementation is larger because it highly optimizes for not having to call `toLowerCase()`.\n * We've opted to always call `toLowerCase` in exchange for a more concise function.\n *\n * While Node has the luxury of knowing `value` is always a string, we do an extra step of coercion at the top.\n */\nfunction addHeaderLine(headers, name, value) {\n let values // code below expects `values` to be an array of strings\n if (typeof value === 'function') {\n // Function values are evaluated towards the end of the response, before that we use a placeholder\n // string just to designate that the header exists. Useful when `Content-Type` is set with a function.\n values = [value.name]\n } else if (Array.isArray(value)) {\n values = value.map(String)\n } else {\n values = [String(value)]\n }\n\n const key = name.toLowerCase()\n if (key === 'set-cookie') {\n // Array header -- only Set-Cookie at the moment\n if (headers['set-cookie'] === undefined) {\n headers['set-cookie'] = values\n } else {\n headers['set-cookie'].push(...values)\n }\n } else if (noDuplicatesHeaders.has(key)) {\n if (headers[key] === undefined) {\n // Drop duplicates\n headers[key] = values[0]\n }\n } else {\n if (headers[key] !== undefined) {\n values = [headers[key], ...values]\n }\n\n const separator = key === 'cookie' ? '; ' : ', '\n headers[key] = values.join(separator)\n }\n}\n\n/**\n * Deletes the given `fieldName` property from `headers` object by performing\n * case-insensitive search through keys.\n *\n * @headers {Object} headers - object of header field names and values\n * @fieldName {String} field name - string with the case-insensitive field name\n */\nfunction deleteHeadersField(headers, fieldNameToDelete) {\n if (!isPlainObject(headers)) {\n throw Error('headers must be an object')\n }\n\n if (typeof fieldNameToDelete !== 'string') {\n throw Error('field name must be a string')\n }\n\n const lowerCaseFieldNameToDelete = fieldNameToDelete.toLowerCase()\n\n // Search through the headers and delete all values whose field name matches the given field name.\n Object.keys(headers)\n .filter(fieldName => fieldName.toLowerCase() === lowerCaseFieldNameToDelete)\n .forEach(fieldName => delete headers[fieldName])\n}\n\n/**\n * Utility for iterating over a raw headers array.\n *\n * The callback is called with:\n * - The header value. string, array of strings, or a function\n * - The header field name. string\n * - Index of the header field in the raw header array.\n */\nfunction forEachHeader(rawHeaders, callback) {\n for (let i = 0; i < rawHeaders.length; i += 2) {\n callback(rawHeaders[i + 1], rawHeaders[i], i)\n }\n}\n\nfunction percentDecode(str) {\n try {\n return decodeURIComponent(str.replace(/\\+/g, ' '))\n } catch (e) {\n return str\n }\n}\n\n/**\n * URI encode the provided string, stringently adhering to RFC 3986.\n *\n * RFC 3986 reserves !, ', (, ), and * but encodeURIComponent does not encode them so we do it manually.\n *\n * https://tools.ietf.org/html/rfc3986\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent\n */\nfunction percentEncode(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {\n return `%${c.charCodeAt(0).toString(16).toUpperCase()}`\n })\n}\n\nfunction matchStringOrRegexp(target, pattern) {\n const targetStr =\n target === undefined || target === null ? '' : String(target)\n\n if (pattern instanceof RegExp) {\n // if the regexp happens to have a global flag, we want to ensure we test the entire target\n pattern.lastIndex = 0\n return pattern.test(targetStr)\n }\n return targetStr === String(pattern)\n}\n\n/**\n * Formats a query parameter.\n *\n * @param key The key of the query parameter to format.\n * @param value The value of the query parameter to format.\n * @param stringFormattingFn The function used to format string values. Can\n * be used to encode or decode the query value.\n *\n * @returns *[] the formatted [key, value] pair.\n */\nfunction formatQueryValue(key, value, stringFormattingFn) {\n // TODO: Probably refactor code to replace `switch(true)` with `if`/`else`.\n switch (true) {\n case typeof value === 'number': // fall-through\n case typeof value === 'boolean':\n value = value.toString()\n break\n case value === null:\n case value === undefined:\n value = ''\n break\n case typeof value === 'string':\n if (stringFormattingFn) {\n value = stringFormattingFn(value)\n }\n break\n case value instanceof RegExp:\n break\n case Array.isArray(value): {\n value = value.map(function (val, idx) {\n return formatQueryValue(idx, val, stringFormattingFn)[1]\n })\n break\n }\n case typeof value === 'object': {\n value = Object.entries(value).reduce(function (acc, [subKey, subVal]) {\n const subPair = formatQueryValue(subKey, subVal, stringFormattingFn)\n acc[subPair[0]] = subPair[1]\n\n return acc\n }, {})\n break\n }\n }\n\n if (stringFormattingFn) key = stringFormattingFn(key)\n return [key, value]\n}\n\nfunction isStream(obj) {\n return (\n obj &&\n typeof obj !== 'string' &&\n !Buffer.isBuffer(obj) &&\n typeof obj.setEncoding === 'function'\n )\n}\n\n/**\n * Converts the arguments from the various signatures of http[s].request into a standard\n * options object and an optional callback function.\n *\n * https://nodejs.org/api/http.html#http_http_request_url_options_callback\n *\n * Taken from the beginning of the native `ClientRequest`.\n * https://github.com/nodejs/node/blob/908292cf1f551c614a733d858528ffb13fb3a524/lib/_http_client.js#L68\n */\nfunction normalizeClientRequestArgs(input, options, cb) {\n if (typeof input === 'string') {\n input = urlToOptions(new url.URL(input))\n } else if (input instanceof url.URL) {\n input = urlToOptions(input)\n } else {\n cb = options\n options = input\n input = null\n }\n\n if (typeof options === 'function') {\n cb = options\n options = input || {}\n } else {\n options = Object.assign(input || {}, options)\n }\n\n return { options, callback: cb }\n}\n\n/**\n * Utility function that converts a URL object into an ordinary\n * options object as expected by the http.request and https.request APIs.\n *\n * This was copied from Node's source\n * https://github.com/nodejs/node/blob/908292cf1f551c614a733d858528ffb13fb3a524/lib/internal/url.js#L1257\n */\nfunction urlToOptions(url) {\n const options = {\n protocol: url.protocol,\n hostname:\n typeof url.hostname === 'string' && url.hostname.startsWith('[')\n ? url.hostname.slice(1, -1)\n : url.hostname,\n hash: url.hash,\n search: url.search,\n pathname: url.pathname,\n path: `${url.pathname}${url.search || ''}`,\n href: url.href,\n }\n if (url.port !== '') {\n options.port = Number(url.port)\n }\n if (url.username || url.password) {\n options.auth = `${url.username}:${url.password}`\n }\n return options\n}\n\n/**\n * Determines if request data matches the expected schema.\n *\n * Used for comparing decoded search parameters, request body JSON objects,\n * and URL decoded request form bodies.\n *\n * Performs a general recursive strict comparison with two caveats:\n * - The expected data can use regexp to compare values\n * - JSON path notation and nested objects are considered equal\n */\nconst dataEqual = (expected, actual) => {\n if (isPlainObject(expected)) {\n expected = expand(expected)\n }\n if (isPlainObject(actual)) {\n actual = expand(actual)\n }\n return deepEqual(expected, actual)\n}\n\n/**\n * Performs a recursive strict comparison between two values.\n *\n * Expected values or leaf nodes of expected object values that are RegExp use test() for comparison.\n */\nfunction deepEqual(expected, actual) {\n debug('deepEqual comparing', typeof expected, expected, typeof actual, actual)\n if (expected instanceof RegExp) {\n return expected.test(actual)\n }\n\n if (Array.isArray(expected) && Array.isArray(actual)) {\n if (expected.length !== actual.length) {\n return false\n }\n\n return expected.every((expVal, idx) => deepEqual(expVal, actual[idx]))\n }\n\n if (isPlainObject(expected) && isPlainObject(actual)) {\n const allKeys = Array.from(\n new Set(Object.keys(expected).concat(Object.keys(actual))),\n )\n\n return allKeys.every(key => deepEqual(expected[key], actual[key]))\n }\n\n return expected === actual\n}\n\nconst timeouts = []\nconst intervals = []\nconst immediates = []\n\nconst wrapTimer =\n (timer, ids) =>\n (...args) => {\n const id = timer(...args)\n ids.push(id)\n return id\n }\n\nconst setTimeout = wrapTimer(timers.setTimeout, timeouts)\nconst setInterval = wrapTimer(timers.setInterval, intervals)\nconst setImmediate = wrapTimer(timers.setImmediate, immediates)\n\nfunction clearTimer(clear, ids) {\n while (ids.length) {\n clear(ids.shift())\n }\n}\n\nfunction removeAllTimers() {\n clearTimer(clearTimeout, timeouts)\n clearTimer(clearInterval, intervals)\n clearTimer(clearImmediate, immediates)\n}\n\n/**\n * Check if the Client Request has been cancelled.\n *\n * Until Node 14 is the minimum, we need to look at both flags to see if the request has been cancelled.\n * The two flags have the same purpose, but the Node maintainers are migrating from `abort(ed)` to\n * `destroy(ed)` terminology, to be more consistent with `stream.Writable`.\n * In Node 14.x+, Calling `abort()` will set both `aborted` and `destroyed` to true, however,\n * calling `destroy()` will only set `destroyed` to true.\n * Falling back on checking if the socket is destroyed to cover the case of Node <14.x where\n * `destroy()` is called, but `destroyed` is undefined.\n *\n * Node Client Request history:\n * - `request.abort()`: Added in: v0.3.8, Deprecated since: v14.1.0, v13.14.0\n * - `request.aborted`: Added in: v0.11.14, Became a boolean instead of a timestamp: v11.0.0, Not deprecated (yet)\n * - `request.destroy()`: Added in: v0.3.0\n * - `request.destroyed`: Added in: v14.1.0, v13.14.0\n *\n * @param {ClientRequest} req\n * @returns {boolean}\n */\nfunction isRequestDestroyed(req) {\n return !!(\n req.destroyed === true ||\n req.aborted ||\n (req.socket && req.socket.destroyed)\n )\n}\n\n/**\n * Returns true if the given value is a plain object and not an Array.\n * @param {*} value\n * @returns {boolean}\n */\nfunction isPlainObject(value) {\n if (typeof value !== 'object' || value === null) return false\n\n if (Object.prototype.toString.call(value) !== '[object Object]') return false\n\n const proto = Object.getPrototypeOf(value)\n if (proto === null) return true\n\n const Ctor =\n Object.prototype.hasOwnProperty.call(proto, 'constructor') &&\n proto.constructor\n return (\n typeof Ctor === 'function' &&\n Ctor instanceof Ctor &&\n Function.prototype.call(Ctor) === Function.prototype.call(value)\n )\n}\n\nconst prototypePollutionBlockList = ['__proto__', 'prototype', 'constructor']\nconst blocklistFilter = function (part) {\n return prototypePollutionBlockList.indexOf(part) === -1\n}\n\n/**\n * Converts flat objects whose keys use JSON path notation to nested objects.\n *\n * The input object is not mutated.\n *\n * @example\n * { 'foo[bar][0]': 'baz' } -> { foo: { bar: [ 'baz' ] } }\n */\nconst expand = input => {\n if (input === undefined || input === null) {\n return input\n }\n\n const keys = Object.keys(input)\n\n const result = {}\n let resultPtr = result\n\n for (let path of keys) {\n const originalPath = path\n if (path.indexOf('[') >= 0) {\n path = path.replace(/\\[/g, '.').replace(/]/g, '')\n }\n\n const parts = path.split('.')\n\n const check = parts.filter(blocklistFilter)\n\n if (check.length !== parts.length) {\n return undefined\n }\n resultPtr = result\n const lastIndex = parts.length - 1\n\n for (let i = 0; i < parts.length; ++i) {\n const part = parts[i]\n if (i === lastIndex) {\n if (Array.isArray(resultPtr)) {\n resultPtr[+part] = input[originalPath]\n } else {\n resultPtr[part] = input[originalPath]\n }\n } else {\n if (resultPtr[part] === undefined || resultPtr[part] === null) {\n const nextPart = parts[i + 1]\n if (/^\\d+$/.test(nextPart)) {\n resultPtr[part] = []\n } else {\n resultPtr[part] = {}\n }\n }\n resultPtr = resultPtr[part]\n }\n }\n }\n return result\n}\n\nmodule.exports = {\n contentEncoding,\n dataEqual,\n deleteHeadersField,\n expand,\n forEachHeader,\n formatQueryValue,\n headersArrayToObject,\n headersFieldNamesToLowerCase,\n headersFieldsArrayToLowerCase,\n headersInputToRawArray,\n isContentEncoded,\n isJSONContent,\n isPlainObject,\n isRequestDestroyed,\n isStream,\n isUtf8Representable,\n matchStringOrRegexp,\n normalizeClientRequestArgs,\n normalizeOrigin,\n normalizeRequestOptions,\n overrideRequests,\n percentDecode,\n percentEncode,\n removeAllTimers,\n restoreOverriddenRequests,\n setImmediate,\n setInterval,\n setTimeout,\n stringifyRequest,\n}\n","'use strict'\n\nfunction propagate(events, source, dest) {\n if (arguments.length < 3) {\n dest = source\n source = events\n events = undefined\n }\n\n // events should be an array or object\n const eventsIsObject = typeof events === 'object'\n if (events && !eventsIsObject) events = [events]\n\n if (eventsIsObject) {\n return explicitPropagate(events, source, dest)\n }\n\n const shouldPropagate = eventName =>\n events === undefined || events.includes(eventName)\n\n const oldEmit = source.emit\n\n // Returns true if the event had listeners, false otherwise.\n // https://nodejs.org/api/events.html#events_emitter_emit_eventname_args\n source.emit = (eventName, ...args) => {\n const oldEmitHadListeners = oldEmit.call(source, eventName, ...args)\n\n let destEmitHadListeners = false\n if (shouldPropagate(eventName)) {\n destEmitHadListeners = dest.emit(eventName, ...args)\n }\n\n return oldEmitHadListeners || destEmitHadListeners\n }\n\n function end() {\n source.emit = oldEmit\n }\n\n return {\n end,\n }\n}\n\nmodule.exports = propagate\n\nfunction explicitPropagate(events, source, dest) {\n let eventsIn\n let eventsOut\n if (Array.isArray(events)) {\n eventsIn = events\n eventsOut = events\n } else {\n eventsIn = Object.keys(events)\n eventsOut = eventsIn.map(function(key) {\n return events[key]\n })\n }\n\n const listeners = eventsOut.map(function(event) {\n return function() {\n const args = Array.prototype.slice.call(arguments)\n args.unshift(event)\n dest.emit.apply(dest, args)\n }\n })\n\n listeners.forEach(register)\n\n return {\n end,\n }\n\n function register(listener, i) {\n source.on(eventsIn[i], listener)\n }\n\n function unregister(listener, i) {\n source.removeListener(eventsIn[i], listener)\n }\n\n function end() {\n listeners.forEach(unregister)\n }\n}\n","'use strict'\n\nconst { EventEmitter } = require('events')\n\nmodule.exports = new EventEmitter()\n","'use strict'\n\nconst { EventEmitter } = require('events')\nconst debug = require('debug')('nock.socket')\n\nmodule.exports = class Socket extends EventEmitter {\n constructor(options) {\n super()\n\n // Pretend this is a TLSSocket\n if (options.proto === 'https') {\n // https://github.com/nock/nock/issues/158\n this.authorized = true\n // https://github.com/nock/nock/issues/2147\n this.encrypted = true\n }\n\n this.bufferSize = 0\n this.writableLength = 0\n this.writable = true\n this.readable = true\n this.pending = false\n this.destroyed = false\n this.connecting = true\n\n // Undocumented flag used by ClientRequest to ensure errors aren't double-fired\n this._hadError = false\n\n // Maximum allowed delay. 0 means unlimited.\n this.timeout = 0\n\n const ipv6 = options.family === 6\n this.remoteFamily = ipv6 ? 'IPv6' : 'IPv4'\n this.localAddress = this.remoteAddress = ipv6 ? '::1' : '127.0.0.1'\n this.localPort = this.remotePort = parseInt(options.port)\n }\n\n setNoDelay() {}\n setKeepAlive() {}\n resume() {}\n ref() {}\n unref() {}\n write() {}\n\n address() {\n return {\n port: this.remotePort,\n family: this.remoteFamily,\n address: this.remoteAddress,\n }\n }\n\n setTimeout(timeoutMs, fn) {\n this.timeout = timeoutMs\n if (fn) {\n this.once('timeout', fn)\n }\n return this\n }\n\n /**\n * Artificial delay that will trip socket timeouts when appropriate.\n *\n * Doesn't actually wait for time to pass.\n * Timeout events don't necessarily end the request.\n * While many clients choose to abort the request upon a timeout, Node itself does not.\n */\n applyDelay(delayMs) {\n if (this.timeout && delayMs > this.timeout) {\n debug('socket timeout')\n this.emit('timeout')\n }\n }\n\n getPeerCertificate() {\n return Buffer.from(\n (Math.random() * 10000 + Date.now()).toString(),\n ).toString('base64')\n }\n\n /**\n * Denotes that no more I/O activity should happen on this socket.\n *\n * The implementation in Node if far more complex as it juggles underlying async streams.\n * For the purposes of Nock, we just need it to set some flags and on the first call\n * emit a 'close' and optional 'error' event. Both events propagate through the request object.\n */\n destroy(err) {\n if (this.destroyed) {\n return this\n }\n\n debug('socket destroy')\n this.destroyed = true\n this.readable = this.writable = false\n this.readableEnded = this.writableFinished = true\n\n process.nextTick(() => {\n if (err) {\n this._hadError = true\n this.emit('error', err)\n }\n this.emit('close')\n })\n\n return this\n }\n}\n","'use strict'\n\nconst stream = require('stream')\nconst util = require('util')\nconst zlib = require('zlib')\nconst debug = require('debug')('nock.playback_interceptor')\nconst common = require('./common')\n\nfunction parseJSONRequestBody(req, requestBody) {\n if (!requestBody || !common.isJSONContent(req.headers)) {\n return requestBody\n }\n\n if (common.contentEncoding(req.headers, 'gzip')) {\n requestBody = String(zlib.gunzipSync(Buffer.from(requestBody, 'hex')))\n } else if (common.contentEncoding(req.headers, 'deflate')) {\n requestBody = String(zlib.inflateSync(Buffer.from(requestBody, 'hex')))\n }\n\n return JSON.parse(requestBody)\n}\n\nfunction parseFullReplyResult(response, fullReplyResult) {\n debug('full response from callback result: %j', fullReplyResult)\n\n if (!Array.isArray(fullReplyResult)) {\n throw Error('A single function provided to .reply MUST return an array')\n }\n\n if (fullReplyResult.length > 3) {\n throw Error(\n 'The array returned from the .reply callback contains too many values',\n )\n }\n\n const [status, body = '', headers] = fullReplyResult\n\n if (!Number.isInteger(status)) {\n throw new Error(`Invalid ${typeof status} value for status code`)\n }\n\n response.statusCode = status\n response.rawHeaders.push(...common.headersInputToRawArray(headers))\n debug('response.rawHeaders after reply: %j', response.rawHeaders)\n\n return body\n}\n\n/**\n * Determine which of the default headers should be added to the response.\n *\n * Don't include any defaults whose case-insensitive keys are already on the response.\n */\nfunction selectDefaultHeaders(existingHeaders, defaultHeaders) {\n if (!defaultHeaders.length) {\n return [] // return early if we don't need to bother\n }\n\n const definedHeaders = new Set()\n const result = []\n\n common.forEachHeader(existingHeaders, (_, fieldName) => {\n definedHeaders.add(fieldName.toLowerCase())\n })\n common.forEachHeader(defaultHeaders, (value, fieldName) => {\n if (!definedHeaders.has(fieldName.toLowerCase())) {\n result.push(fieldName, value)\n }\n })\n\n return result\n}\n\n// Presents a list of Buffers as a Readable\nclass ReadableBuffers extends stream.Readable {\n constructor(buffers, opts = {}) {\n super(opts)\n\n this.buffers = buffers\n }\n\n _read(_size) {\n while (this.buffers.length) {\n if (!this.push(this.buffers.shift())) {\n return\n }\n }\n this.push(null)\n }\n}\n\nfunction convertBodyToStream(body) {\n if (common.isStream(body)) {\n return body\n }\n\n if (body === undefined) {\n return new ReadableBuffers([])\n }\n\n if (Buffer.isBuffer(body)) {\n return new ReadableBuffers([body])\n }\n\n if (typeof body !== 'string') {\n body = JSON.stringify(body)\n }\n\n return new ReadableBuffers([Buffer.from(body)])\n}\n\n/**\n * Play back an interceptor using the given request and mock response.\n */\nfunction playbackInterceptor({\n req,\n socket,\n options,\n requestBodyString,\n requestBodyIsUtf8Representable,\n response,\n interceptor,\n}) {\n const { logger } = interceptor.scope\n\n function start() {\n req.headers = req.getHeaders()\n\n interceptor.scope.emit('request', req, interceptor, requestBodyString)\n\n if (typeof interceptor.errorMessage !== 'undefined') {\n let error\n if (typeof interceptor.errorMessage === 'object') {\n error = interceptor.errorMessage\n } else {\n error = new Error(interceptor.errorMessage)\n }\n\n const delay = interceptor.delayBodyInMs + interceptor.delayConnectionInMs\n common.setTimeout(() => req.destroy(error), delay)\n return\n }\n\n // This will be null if we have a fullReplyFunction,\n // in that case status code will be set in `parseFullReplyResult`\n response.statusCode = interceptor.statusCode\n\n // Clone headers/rawHeaders to not override them when evaluating later\n response.rawHeaders = [...interceptor.rawHeaders]\n logger('response.rawHeaders:', response.rawHeaders)\n\n // TODO: MAJOR: Don't tack the request onto the interceptor.\n // The only reason we do this is so that it's available inside reply functions.\n // It would be better to pass the request as an argument to the functions instead.\n // Not adding the req as a third arg now because it should first be decided if (path, body, req)\n // is the signature we want to go with going forward.\n interceptor.req = req\n\n if (interceptor.replyFunction) {\n const parsedRequestBody = parseJSONRequestBody(req, requestBodyString)\n\n let fn = interceptor.replyFunction\n if (fn.length === 3) {\n // Handle the case of an async reply function, the third parameter being the callback.\n fn = util.promisify(fn)\n }\n\n // At this point `fn` is either a synchronous function or a promise-returning function;\n // wrapping in `Promise.resolve` makes it into a promise either way.\n Promise.resolve(fn.call(interceptor, options.path, parsedRequestBody))\n .then(continueWithResponseBody)\n .catch(err => req.destroy(err))\n return\n }\n\n if (interceptor.fullReplyFunction) {\n const parsedRequestBody = parseJSONRequestBody(req, requestBodyString)\n\n let fn = interceptor.fullReplyFunction\n if (fn.length === 3) {\n fn = util.promisify(fn)\n }\n\n Promise.resolve(fn.call(interceptor, options.path, parsedRequestBody))\n .then(continueWithFullResponse)\n .catch(err => req.destroy(err))\n return\n }\n\n if (\n common.isContentEncoded(interceptor.headers) &&\n !common.isStream(interceptor.body)\n ) {\n // If the content is encoded we know that the response body *must* be an array\n // of response buffers which should be mocked one by one.\n // (otherwise decompressions after the first one fails as unzip expects to receive\n // buffer by buffer and not one single merged buffer)\n const bufferData = Array.isArray(interceptor.body)\n ? interceptor.body\n : [interceptor.body]\n const responseBuffers = bufferData.map(data => Buffer.from(data, 'hex'))\n const responseBody = new ReadableBuffers(responseBuffers)\n continueWithResponseBody(responseBody)\n return\n }\n\n // If we get to this point, the body is either a string or an object that\n // will eventually be JSON stringified.\n let responseBody = interceptor.body\n\n // If the request was not UTF8-representable then we assume that the\n // response won't be either. In that case we send the response as a Buffer\n // object as that's what the client will expect.\n if (!requestBodyIsUtf8Representable && typeof responseBody === 'string') {\n // Try to create the buffer from the interceptor's body response as hex.\n responseBody = Buffer.from(responseBody, 'hex')\n\n // Creating buffers does not necessarily throw errors; check for difference in size.\n if (\n !responseBody ||\n (interceptor.body.length > 0 && responseBody.length === 0)\n ) {\n // We fallback on constructing buffer from utf8 representation of the body.\n responseBody = Buffer.from(interceptor.body, 'utf8')\n }\n }\n\n return continueWithResponseBody(responseBody)\n }\n\n function continueWithFullResponse(fullReplyResult) {\n let responseBody\n try {\n responseBody = parseFullReplyResult(response, fullReplyResult)\n } catch (err) {\n req.destroy(err)\n return\n }\n\n continueWithResponseBody(responseBody)\n }\n\n function prepareResponseHeaders(body) {\n const defaultHeaders = [...interceptor.scope._defaultReplyHeaders]\n\n // Include a JSON content type when JSON.stringify is called on the body.\n // This is a convenience added by Nock that has no analog in Node. It's added to the\n // defaults, so it will be ignored if the caller explicitly provided the header already.\n const isJSON =\n body !== undefined &&\n typeof body !== 'string' &&\n !Buffer.isBuffer(body) &&\n !common.isStream(body)\n\n if (isJSON) {\n defaultHeaders.push('Content-Type', 'application/json')\n }\n\n response.rawHeaders.push(\n ...selectDefaultHeaders(response.rawHeaders, defaultHeaders),\n )\n\n // Evaluate functional headers.\n common.forEachHeader(response.rawHeaders, (value, fieldName, i) => {\n if (typeof value === 'function') {\n response.rawHeaders[i + 1] = value(req, response, body)\n }\n })\n\n response.headers = common.headersArrayToObject(response.rawHeaders)\n }\n\n function continueWithResponseBody(rawBody) {\n prepareResponseHeaders(rawBody)\n const bodyAsStream = convertBodyToStream(rawBody)\n bodyAsStream.pause()\n\n // IncomingMessage extends Readable so we can't simply pipe.\n bodyAsStream.on('data', function (chunk) {\n response.push(chunk)\n })\n bodyAsStream.on('end', function () {\n // https://nodejs.org/dist/latest-v10.x/docs/api/http.html#http_message_complete\n response.complete = true\n response.push(null)\n\n interceptor.scope.emit('replied', req, interceptor)\n })\n bodyAsStream.on('error', function (err) {\n response.emit('error', err)\n })\n\n const { delayBodyInMs, delayConnectionInMs } = interceptor\n\n function respond() {\n if (common.isRequestDestroyed(req)) {\n return\n }\n\n // Even though we've had the response object for awhile at this point,\n // we only attach it to the request immediately before the `response`\n // event because, as in Node, it alters the error handling around aborts.\n req.res = response\n response.req = req\n\n logger('emitting response')\n req.emit('response', response)\n\n common.setTimeout(() => bodyAsStream.resume(), delayBodyInMs)\n }\n\n socket.applyDelay(delayConnectionInMs)\n common.setTimeout(respond, delayConnectionInMs)\n }\n\n // Calling `start` immediately could take the request all the way to the connection delay\n // during a single microtask execution. This setImmediate stalls the playback to ensure the\n // correct events are emitted first ('socket', 'finish') and any aborts in the queue or\n // called during a 'finish' listener can be called.\n common.setImmediate(() => {\n if (!common.isRequestDestroyed(req)) {\n start()\n }\n })\n}\n\nmodule.exports = { playbackInterceptor }\n","'use strict'\n\nconst debug = require('debug')('nock.request_overrider')\nconst {\n IncomingMessage,\n ClientRequest,\n request: originalHttpRequest,\n} = require('http')\nconst { request: originalHttpsRequest } = require('https')\nconst propagate = require('propagate')\nconst common = require('./common')\nconst globalEmitter = require('./global_emitter')\nconst Socket = require('./socket')\nconst { playbackInterceptor } = require('./playback_interceptor')\n\nfunction socketOnClose(req) {\n debug('socket close')\n\n if (!req.res && !req.socket._hadError) {\n // If we don't have a response then we know that the socket\n // ended prematurely and we need to emit an error on the request.\n req.socket._hadError = true\n const err = new Error('socket hang up')\n err.code = 'ECONNRESET'\n req.emit('error', err)\n }\n req.emit('close')\n}\n\n/**\n * Given a group of interceptors, appropriately route an outgoing request.\n * Identify which interceptor ought to respond, if any, then delegate to\n * `playbackInterceptor()` to consume the request itself.\n */\nclass InterceptedRequestRouter {\n constructor({ req, options, interceptors }) {\n this.req = req\n this.options = {\n // We may be changing the options object and we don't want those changes\n // affecting the user so we use a clone of the object.\n ...options,\n // We use lower-case header field names throughout Nock.\n headers: common.headersFieldNamesToLowerCase(\n options.headers || {},\n false,\n ),\n }\n this.interceptors = interceptors\n\n this.socket = new Socket(options)\n\n // support setting `timeout` using request `options`\n // https://nodejs.org/docs/latest-v12.x/api/http.html#http_http_request_url_options_callback\n // any timeout in the request options override any timeout in the agent options.\n // per https://github.com/nodejs/node/pull/21204\n const timeout =\n options.timeout ||\n (options.agent && options.agent.options && options.agent.options.timeout)\n\n if (timeout) {\n this.socket.setTimeout(timeout)\n }\n\n this.response = new IncomingMessage(this.socket)\n this.requestBodyBuffers = []\n this.playbackStarted = false\n\n // For parity with Node, it's important the socket event is emitted before we begin playback.\n // This flag is set when playback is triggered if we haven't yet gotten the\n // socket event to indicate that playback should start as soon as it comes in.\n this.readyToStartPlaybackOnSocketEvent = false\n\n this.attachToReq()\n\n // Emit a fake socket event on the next tick to mimic what would happen on a real request.\n // Some clients listen for a 'socket' event to be emitted before calling end(),\n // which causes Nock to hang.\n process.nextTick(() => this.connectSocket())\n }\n\n attachToReq() {\n const { req, options } = this\n\n for (const [name, val] of Object.entries(options.headers)) {\n req.setHeader(name.toLowerCase(), val)\n }\n\n if (options.auth && !options.headers.authorization) {\n req.setHeader(\n // We use lower-case header field names throughout Nock.\n 'authorization',\n `Basic ${Buffer.from(options.auth).toString('base64')}`,\n )\n }\n\n req.path = options.path\n req.method = options.method\n\n req.write = (...args) => this.handleWrite(...args)\n req.end = (...args) => this.handleEnd(...args)\n req.flushHeaders = (...args) => this.handleFlushHeaders(...args)\n\n // https://github.com/nock/nock/issues/256\n if (options.headers.expect === '100-continue') {\n common.setImmediate(() => {\n debug('continue')\n req.emit('continue')\n })\n }\n }\n\n connectSocket() {\n const { req, socket } = this\n\n if (common.isRequestDestroyed(req)) {\n return\n }\n\n // ClientRequest.connection is an alias for ClientRequest.socket\n // https://nodejs.org/api/http.html#http_request_socket\n // https://github.com/nodejs/node/blob/b0f75818f39ed4e6bd80eb7c4010c1daf5823ef7/lib/_http_client.js#L640-L641\n // The same Socket is shared between the request and response to mimic native behavior.\n req.socket = req.connection = socket\n\n propagate(['error', 'timeout'], socket, req)\n socket.on('close', () => socketOnClose(req))\n\n socket.connecting = false\n req.emit('socket', socket)\n\n // https://nodejs.org/api/net.html#net_event_connect\n socket.emit('connect')\n\n // https://nodejs.org/api/tls.html#tls_event_secureconnect\n if (socket.authorized) {\n socket.emit('secureConnect')\n }\n\n if (this.readyToStartPlaybackOnSocketEvent) {\n this.maybeStartPlayback()\n }\n }\n\n // from docs: When write function is called with empty string or buffer, it does nothing and waits for more input.\n // However, actually implementation checks the state of finished and aborted before checking if the first arg is empty.\n handleWrite(...args) {\n debug('request write')\n\n let [buffer, encoding] = args\n\n const { req } = this\n\n if (req.finished) {\n const err = new Error('write after end')\n err.code = 'ERR_STREAM_WRITE_AFTER_END'\n process.nextTick(() => req.emit('error', err))\n\n // It seems odd to return `true` here, not sure why you'd want to have\n // the stream potentially written to more, but it's what Node does.\n // https://github.com/nodejs/node/blob/a9270dcbeba4316b1e179b77ecb6c46af5aa8c20/lib/_http_outgoing.js#L662-L665\n return true\n }\n\n if (req.socket && req.socket.destroyed) {\n return false\n }\n\n if (!buffer) {\n return true\n }\n\n if (!Buffer.isBuffer(buffer)) {\n buffer = Buffer.from(buffer, encoding)\n }\n this.requestBodyBuffers.push(buffer)\n\n // writable.write encoding param is optional\n // so if callback is present it's the last argument\n const callback = args.length > 1 ? args[args.length - 1] : undefined\n // can't use instanceof Function because some test runners\n // run tests in vm.runInNewContext where Function is not same\n // as that in the current context\n // https://github.com/nock/nock/pull/1754#issuecomment-571531407\n if (typeof callback === 'function') {\n callback()\n }\n\n common.setImmediate(function () {\n req.emit('drain')\n })\n\n return false\n }\n\n handleEnd(chunk, encoding, callback) {\n debug('request end')\n const { req } = this\n\n // handle the different overloaded arg signatures\n if (typeof chunk === 'function') {\n callback = chunk\n chunk = null\n } else if (typeof encoding === 'function') {\n callback = encoding\n encoding = null\n }\n\n if (typeof callback === 'function') {\n req.once('finish', callback)\n }\n\n if (chunk) {\n req.write(chunk, encoding)\n }\n req.finished = true\n this.maybeStartPlayback()\n\n return req\n }\n\n handleFlushHeaders() {\n debug('request flushHeaders')\n this.maybeStartPlayback()\n }\n\n /**\n * Set request headers of the given request. This is needed both during the\n * routing phase, in case header filters were specified, and during the\n * interceptor-playback phase, to correctly pass mocked request headers.\n * TODO There are some problems with this; see https://github.com/nock/nock/issues/1718\n */\n setHostHeaderUsingInterceptor(interceptor) {\n const { req, options } = this\n\n // If a filtered scope is being used we have to use scope's host in the\n // header, otherwise 'host' header won't match.\n // NOTE: We use lower-case header field names throughout Nock.\n const HOST_HEADER = 'host'\n if (interceptor.__nock_filteredScope && interceptor.__nock_scopeHost) {\n options.headers[HOST_HEADER] = interceptor.__nock_scopeHost\n req.setHeader(HOST_HEADER, interceptor.__nock_scopeHost)\n } else {\n // For all other cases, we always add host header equal to the requested\n // host unless it was already defined.\n if (options.host && !req.getHeader(HOST_HEADER)) {\n let hostHeader = options.host\n\n if (options.port === 80 || options.port === 443) {\n hostHeader = hostHeader.split(':')[0]\n }\n\n req.setHeader(HOST_HEADER, hostHeader)\n }\n }\n }\n\n maybeStartPlayback() {\n const { req, socket, playbackStarted } = this\n\n // In order to get the events in the right order we need to delay playback\n // if we get here before the `socket` event is emitted.\n if (socket.connecting) {\n this.readyToStartPlaybackOnSocketEvent = true\n return\n }\n\n if (!common.isRequestDestroyed(req) && !playbackStarted) {\n this.startPlayback()\n }\n }\n\n startPlayback() {\n debug('ending')\n this.playbackStarted = true\n\n const { req, response, socket, options, interceptors } = this\n\n Object.assign(options, {\n // Re-update `options` with the current value of `req.path` because badly\n // behaving agents like superagent like to change `req.path` mid-flight.\n path: req.path,\n // Similarly, node-http-proxy will modify headers in flight, so we have\n // to put the headers back into options.\n // https://github.com/nock/nock/pull/1484\n headers: req.getHeaders(),\n // Fixes https://github.com/nock/nock/issues/976\n protocol: `${options.proto}:`,\n })\n\n interceptors.forEach(interceptor => {\n this.setHostHeaderUsingInterceptor(interceptor)\n })\n\n const requestBodyBuffer = Buffer.concat(this.requestBodyBuffers)\n // When request body is a binary buffer we internally use in its hexadecimal\n // representation.\n const requestBodyIsUtf8Representable =\n common.isUtf8Representable(requestBodyBuffer)\n const requestBodyString = requestBodyBuffer.toString(\n requestBodyIsUtf8Representable ? 'utf8' : 'hex',\n )\n\n const matchedInterceptor = interceptors.find(i =>\n i.match(req, options, requestBodyString),\n )\n\n if (matchedInterceptor) {\n matchedInterceptor.scope.logger(\n 'interceptor identified, starting mocking',\n )\n\n matchedInterceptor.markConsumed()\n\n // wait to emit the finish event until we know for sure an Interceptor is going to playback.\n // otherwise an unmocked request might emit finish twice.\n req.emit('finish')\n\n playbackInterceptor({\n req,\n socket,\n options,\n requestBodyString,\n requestBodyIsUtf8Representable,\n response,\n interceptor: matchedInterceptor,\n })\n } else {\n globalEmitter.emit('no match', req, options, requestBodyString)\n\n // Try to find a hostname match that allows unmocked.\n const allowUnmocked = interceptors.some(\n i => i.matchHostName(options) && i.options.allowUnmocked,\n )\n\n if (allowUnmocked && req instanceof ClientRequest) {\n const newReq =\n options.proto === 'https'\n ? originalHttpsRequest(options)\n : originalHttpRequest(options)\n\n propagate(newReq, req)\n // We send the raw buffer as we received it, not as we interpreted it.\n newReq.end(requestBodyBuffer)\n } else {\n const reqStr = common.stringifyRequest(options, requestBodyString)\n const err = new Error(`Nock: No match for request ${reqStr}`)\n err.code = 'ERR_NOCK_NO_MATCH'\n err.statusCode = err.status = 404\n req.destroy(err)\n }\n }\n }\n}\n\nmodule.exports = { InterceptedRequestRouter }\n","exports = module.exports = stringify\nexports.getSerialize = serializer\n\nfunction stringify(obj, replacer, spaces, cycleReplacer) {\n return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)\n}\n\nfunction serializer(replacer, cycleReplacer) {\n var stack = [], keys = []\n\n if (cycleReplacer == null) cycleReplacer = function(key, value) {\n if (stack[0] === value) return \"[Circular ~]\"\n return \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\"\n }\n\n return function(key, value) {\n if (stack.length > 0) {\n var thisPos = stack.indexOf(this)\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)\n if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)\n }\n else stack.push(value)\n\n return replacer == null ? value : replacer.call(this, key, value)\n }\n}\n","'use strict'\n\nconst querystring = require('querystring')\n\nconst common = require('./common')\n\nmodule.exports = function matchBody(options, spec, body) {\n if (spec instanceof RegExp) {\n return spec.test(body)\n }\n\n if (Buffer.isBuffer(spec)) {\n const encoding = common.isUtf8Representable(spec) ? 'utf8' : 'hex'\n spec = spec.toString(encoding)\n }\n\n const contentType = (\n (options.headers &&\n (options.headers['Content-Type'] || options.headers['content-type'])) ||\n ''\n ).toString()\n\n const isMultipart = contentType.includes('multipart')\n const isUrlencoded = contentType.includes('application/x-www-form-urlencoded')\n\n // try to transform body to json\n let json\n if (typeof spec === 'object' || typeof spec === 'function') {\n try {\n json = JSON.parse(body)\n } catch (err) {\n // not a valid JSON string\n }\n if (json !== undefined) {\n body = json\n } else if (isUrlencoded) {\n body = querystring.parse(body)\n }\n }\n\n if (typeof spec === 'function') {\n return spec.call(options, body)\n }\n\n // strip line endings from both so that we get a match no matter what OS we are running on\n // if Content-Type does not contain 'multipart'\n if (!isMultipart && typeof body === 'string') {\n body = body.replace(/\\r?\\n|\\r/g, '')\n }\n\n if (!isMultipart && typeof spec === 'string') {\n spec = spec.replace(/\\r?\\n|\\r/g, '')\n }\n\n // Because the nature of URL encoding, all the values in the body must be cast to strings.\n // dataEqual does strict checking, so we have to cast the non-regexp values in the spec too.\n if (isUrlencoded) {\n spec = mapValuesDeep(spec, val => (val instanceof RegExp ? val : `${val}`))\n }\n\n return common.dataEqual(spec, body)\n}\n\nfunction mapValues(object, cb) {\n const keys = Object.keys(object)\n for (const key of keys) {\n object[key] = cb(object[key], key, object)\n }\n return object\n}\n\n/**\n * Based on lodash issue discussion\n * https://github.com/lodash/lodash/issues/1244\n */\nfunction mapValuesDeep(obj, cb) {\n if (Array.isArray(obj)) {\n return obj.map(v => mapValuesDeep(v, cb))\n }\n if (common.isPlainObject(obj)) {\n return mapValues(obj, v => mapValuesDeep(v, cb))\n }\n return cb(obj)\n}\n","'use strict'\n\nconst stringify = require('json-stringify-safe')\nconst querystring = require('querystring')\nconst { URL, URLSearchParams } = require('url')\n\nconst common = require('./common')\nconst { remove } = require('./intercept')\nconst matchBody = require('./match_body')\n\nlet fs\ntry {\n fs = require('fs')\n} catch (err) {\n // do nothing, we're in the browser\n}\n\nmodule.exports = class Interceptor {\n /**\n *\n * Valid argument types for `uri`:\n * - A string used for strict comparisons with pathname.\n * The search portion of the URI may also be postfixed, in which case the search params\n * are striped and added via the `query` method.\n * - A RegExp instance that tests against only the pathname of requests.\n * - A synchronous function bound to this Interceptor instance. It's provided the pathname\n * of requests and must return a boolean denoting if the request is considered a match.\n */\n constructor(scope, uri, method, requestBody, interceptorOptions) {\n const uriIsStr = typeof uri === 'string'\n // Check for leading slash. Uri can be either a string or a regexp, but\n // When enabled filteringScope ignores the passed URL entirely so we skip validation.\n\n if (\n uriIsStr &&\n !scope.scopeOptions.filteringScope &&\n !scope.basePathname &&\n !uri.startsWith('/') &&\n !uri.startsWith('*')\n ) {\n throw Error(\n `Non-wildcard URL path strings must begin with a slash (otherwise they won't match anything) (got: ${uri})`,\n )\n }\n\n if (!method) {\n throw new Error(\n 'The \"method\" parameter is required for an intercept call.',\n )\n }\n\n this.scope = scope\n this.interceptorMatchHeaders = []\n this.method = method.toUpperCase()\n this.uri = uri\n this._key = `${this.method} ${scope.basePath}${scope.basePathname}${\n uriIsStr ? '' : '/'\n }${uri}`\n this.basePath = this.scope.basePath\n this.path = uriIsStr ? scope.basePathname + uri : uri\n this.queries = null\n\n this.options = interceptorOptions || {}\n this.counter = 1\n this._requestBody = requestBody\n\n // We use lower-case header field names throughout Nock.\n this.reqheaders = common.headersFieldNamesToLowerCase(\n scope.scopeOptions.reqheaders || {},\n true,\n )\n this.badheaders = common.headersFieldsArrayToLowerCase(\n scope.scopeOptions.badheaders || [],\n )\n\n this.delayBodyInMs = 0\n this.delayConnectionInMs = 0\n\n this.optional = false\n\n // strip off literal query parameters if they were provided as part of the URI\n if (uriIsStr && uri.includes('?')) {\n // localhost is a dummy value because the URL constructor errors for only relative inputs\n const parsedURL = new URL(this.path, 'http://localhost')\n this.path = parsedURL.pathname\n this.query(parsedURL.searchParams)\n this._key = `${this.method} ${scope.basePath}${this.path}`\n }\n }\n\n optionally(flag = true) {\n // The default behaviour of optionally() with no arguments is to make the mock optional.\n if (typeof flag !== 'boolean') {\n throw new Error('Invalid arguments: argument should be a boolean')\n }\n\n this.optional = flag\n\n return this\n }\n\n replyWithError(errorMessage) {\n this.errorMessage = errorMessage\n\n this.options = {\n ...this.scope.scopeOptions,\n ...this.options,\n }\n\n this.scope.add(this._key, this)\n return this.scope\n }\n\n reply(statusCode, body, rawHeaders) {\n // support the format of only passing in a callback\n if (typeof statusCode === 'function') {\n if (arguments.length > 1) {\n // It's not very Javascript-y to throw an error for extra args to a function, but because\n // of legacy behavior, this error was added to reduce confusion for those migrating.\n throw Error(\n 'Invalid arguments. When providing a function for the first argument, .reply does not accept other arguments.',\n )\n }\n this.statusCode = null\n this.fullReplyFunction = statusCode\n } else {\n if (statusCode !== undefined && !Number.isInteger(statusCode)) {\n throw new Error(`Invalid ${typeof statusCode} value for status code`)\n }\n\n this.statusCode = statusCode || 200\n if (typeof body === 'function') {\n this.replyFunction = body\n body = null\n }\n }\n\n this.options = {\n ...this.scope.scopeOptions,\n ...this.options,\n }\n\n this.rawHeaders = common.headersInputToRawArray(rawHeaders)\n\n if (this.scope.date) {\n // https://tools.ietf.org/html/rfc7231#section-7.1.1.2\n this.rawHeaders.push('Date', this.scope.date.toUTCString())\n }\n\n // Prepare the headers temporarily so we can make best guesses about content-encoding and content-type\n // below as well as while the response is being processed in RequestOverrider.end().\n // Including all the default headers is safe for our purposes because of the specific headers we introspect.\n // A more thoughtful process is used to merge the default headers when the response headers are finally computed.\n this.headers = common.headersArrayToObject(\n this.rawHeaders.concat(this.scope._defaultReplyHeaders),\n )\n\n // If the content is not encoded we may need to transform the response body.\n // Otherwise, we leave it as it is.\n if (\n body &&\n typeof body !== 'string' &&\n !Buffer.isBuffer(body) &&\n !common.isStream(body) &&\n !common.isContentEncoded(this.headers)\n ) {\n try {\n body = stringify(body)\n } catch (err) {\n throw new Error('Error encoding response body into JSON')\n }\n\n if (!this.headers['content-type']) {\n // https://tools.ietf.org/html/rfc7231#section-3.1.1.5\n this.rawHeaders.push('Content-Type', 'application/json')\n }\n }\n\n if (this.scope.contentLen) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n if (typeof body === 'string') {\n this.rawHeaders.push('Content-Length', body.length)\n } else if (Buffer.isBuffer(body)) {\n this.rawHeaders.push('Content-Length', body.byteLength)\n }\n }\n\n this.scope.logger('reply.headers:', this.headers)\n this.scope.logger('reply.rawHeaders:', this.rawHeaders)\n\n this.body = body\n\n this.scope.add(this._key, this)\n return this.scope\n }\n\n replyWithFile(statusCode, filePath, headers) {\n if (!fs) {\n throw new Error('No fs')\n }\n this.filePath = filePath\n return this.reply(\n statusCode,\n () => {\n const readStream = fs.createReadStream(filePath)\n readStream.pause()\n return readStream\n },\n headers,\n )\n }\n\n // Also match request headers\n // https://github.com/nock/nock/issues/163\n reqheaderMatches(options, key) {\n const reqHeader = this.reqheaders[key]\n let header = options.headers[key]\n\n // https://github.com/nock/nock/issues/399\n // https://github.com/nock/nock/issues/822\n if (header && typeof header !== 'string' && header.toString) {\n header = header.toString()\n }\n\n // We skip 'host' header comparison unless it's available in both mock and\n // actual request. This because 'host' may get inserted by Nock itself and\n // then get recorded. NOTE: We use lower-case header field names throughout\n // Nock. See https://github.com/nock/nock/pull/196.\n if (key === 'host' && (header === undefined || reqHeader === undefined)) {\n return true\n }\n\n if (reqHeader !== undefined && header !== undefined) {\n if (typeof reqHeader === 'function') {\n return reqHeader(header)\n } else if (common.matchStringOrRegexp(header, reqHeader)) {\n return true\n }\n }\n\n this.scope.logger(\n \"request header field doesn't match:\",\n key,\n header,\n reqHeader,\n )\n return false\n }\n\n match(req, options, body) {\n // check if the logger is enabled because the stringifies can be expensive.\n if (this.scope.logger.enabled) {\n this.scope.logger(\n 'attempting match %s, body = %s',\n stringify(options),\n stringify(body),\n )\n }\n\n const method = (options.method || 'GET').toUpperCase()\n let { path = '/' } = options\n let matches\n let matchKey\n const { proto } = options\n\n if (this.method !== method) {\n this.scope.logger(\n `Method did not match. Request ${method} Interceptor ${this.method}`,\n )\n return false\n }\n\n if (this.scope.transformPathFunction) {\n path = this.scope.transformPathFunction(path)\n }\n\n const requestMatchesFilter = ({ name, value: predicate }) => {\n const headerValue = req.getHeader(name)\n if (typeof predicate === 'function') {\n return predicate(headerValue)\n } else {\n return common.matchStringOrRegexp(headerValue, predicate)\n }\n }\n\n if (\n !this.scope.matchHeaders.every(requestMatchesFilter) ||\n !this.interceptorMatchHeaders.every(requestMatchesFilter)\n ) {\n this.scope.logger(\"headers don't match\")\n return false\n }\n\n const reqHeadersMatch = Object.keys(this.reqheaders).every(key =>\n this.reqheaderMatches(options, key),\n )\n\n if (!reqHeadersMatch) {\n this.scope.logger(\"headers don't match\")\n return false\n }\n\n if (\n this.scope.scopeOptions.conditionally &&\n !this.scope.scopeOptions.conditionally()\n ) {\n this.scope.logger(\n 'matching failed because Scope.conditionally() did not validate',\n )\n return false\n }\n\n const badHeaders = this.badheaders.filter(\n header => header in options.headers,\n )\n\n if (badHeaders.length) {\n this.scope.logger('request contains bad headers', ...badHeaders)\n return false\n }\n\n // Match query strings when using query()\n if (this.queries === null) {\n this.scope.logger('query matching skipped')\n } else {\n // can't rely on pathname or search being in the options, but path has a default\n const [pathname, search] = path.split('?')\n const matchQueries = this.matchQuery({ search })\n\n this.scope.logger(\n matchQueries ? 'query matching succeeded' : 'query matching failed',\n )\n\n if (!matchQueries) {\n return false\n }\n\n // If the query string was explicitly checked then subsequent checks against\n // the path using a callback or regexp only validate the pathname.\n path = pathname\n }\n\n // If we have a filtered scope then we use it instead reconstructing the\n // scope from the request options (proto, host and port) as these two won't\n // necessarily match and we have to remove the scope that was matched (vs.\n // that was defined).\n if (this.__nock_filteredScope) {\n matchKey = this.__nock_filteredScope\n } else {\n matchKey = common.normalizeOrigin(proto, options.host, options.port)\n }\n\n if (typeof this.uri === 'function') {\n matches =\n common.matchStringOrRegexp(matchKey, this.basePath) &&\n // This is a false positive, as `uri` is not bound to `this`.\n // eslint-disable-next-line no-useless-call\n this.uri.call(this, path)\n } else {\n matches =\n common.matchStringOrRegexp(matchKey, this.basePath) &&\n common.matchStringOrRegexp(path, this.path)\n }\n\n this.scope.logger(`matching ${matchKey}${path} to ${this._key}: ${matches}`)\n\n if (matches && this._requestBody !== undefined) {\n if (this.scope.transformRequestBodyFunction) {\n body = this.scope.transformRequestBodyFunction(body, this._requestBody)\n }\n\n matches = matchBody(options, this._requestBody, body)\n if (!matches) {\n this.scope.logger(\n \"bodies don't match: \\n\",\n this._requestBody,\n '\\n',\n body,\n )\n }\n }\n\n return matches\n }\n\n /**\n * Return true when the interceptor's method, protocol, host, port, and path\n * match the provided options.\n */\n matchOrigin(options) {\n const isPathFn = typeof this.path === 'function'\n const isRegex = this.path instanceof RegExp\n const isRegexBasePath = this.scope.basePath instanceof RegExp\n\n const method = (options.method || 'GET').toUpperCase()\n let { path } = options\n const { proto } = options\n\n // NOTE: Do not split off the query params as the regex could use them\n if (!isRegex) {\n path = path ? path.split('?')[0] : ''\n }\n\n if (this.scope.transformPathFunction) {\n path = this.scope.transformPathFunction(path)\n }\n const comparisonKey = isPathFn || isRegex ? this.__nock_scopeKey : this._key\n const matchKey = `${method} ${proto}://${options.host}${path}`\n\n if (isPathFn) {\n return !!(matchKey.match(comparisonKey) && this.path(path))\n }\n\n if (isRegex && !isRegexBasePath) {\n return !!matchKey.match(comparisonKey) && this.path.test(path)\n }\n\n if (isRegexBasePath) {\n return this.scope.basePath.test(matchKey) && !!path.match(this.path)\n }\n\n return comparisonKey === matchKey\n }\n\n matchHostName(options) {\n const { basePath } = this.scope\n\n if (basePath instanceof RegExp) {\n return basePath.test(options.hostname)\n }\n\n return options.hostname === this.scope.urlParts.hostname\n }\n\n matchQuery(options) {\n if (this.queries === true) {\n return true\n }\n\n const reqQueries = querystring.parse(options.search)\n this.scope.logger('Interceptor queries: %j', this.queries)\n this.scope.logger(' Request queries: %j', reqQueries)\n\n if (typeof this.queries === 'function') {\n return this.queries(reqQueries)\n }\n\n return common.dataEqual(this.queries, reqQueries)\n }\n\n filteringPath(...args) {\n this.scope.filteringPath(...args)\n return this\n }\n\n // TODO filtering by path is valid on the intercept level, but not filtering\n // by request body?\n\n markConsumed() {\n this.interceptionCounter++\n\n remove(this)\n\n if (!this.scope.shouldPersist() && this.counter < 1) {\n this.scope.remove(this._key, this)\n }\n }\n\n matchHeader(name, value) {\n this.interceptorMatchHeaders.push({ name, value })\n return this\n }\n\n basicAuth({ user, pass = '' }) {\n const encoded = Buffer.from(`${user}:${pass}`).toString('base64')\n this.matchHeader('authorization', `Basic ${encoded}`)\n return this\n }\n\n /**\n * Set query strings for the interceptor\n * @name query\n * @param queries Object of query string name,values (accepts regexp values)\n * @public\n * @example\n * // Will match 'http://zombo.com/?q=t'\n * nock('http://zombo.com').get('/').query({q: 't'});\n */\n query(queries) {\n if (this.queries !== null) {\n throw Error(`Query parameters have already been defined`)\n }\n\n // Allow all query strings to match this route\n if (queries === true) {\n this.queries = queries\n return this\n }\n\n if (typeof queries === 'function') {\n this.queries = queries\n return this\n }\n\n let strFormattingFn\n if (this.scope.scopeOptions.encodedQueryParams) {\n strFormattingFn = common.percentDecode\n }\n\n if (queries instanceof URLSearchParams || typeof queries === 'string') {\n // Normalize the data into the shape that is matched against.\n // Duplicate keys are handled by combining the values into an array.\n queries = querystring.parse(queries.toString())\n } else if (!common.isPlainObject(queries)) {\n throw Error(`Argument Error: ${queries}`)\n }\n\n this.queries = {}\n for (const [key, value] of Object.entries(queries)) {\n const formatted = common.formatQueryValue(key, value, strFormattingFn)\n const [formattedKey, formattedValue] = formatted\n this.queries[formattedKey] = formattedValue\n }\n\n return this\n }\n\n /**\n * Set number of times will repeat the interceptor\n * @name times\n * @param newCounter Number of times to repeat (should be > 0)\n * @public\n * @example\n * // Will repeat mock 5 times for same king of request\n * nock('http://zombo.com).get('/').times(5).reply(200, 'Ok');\n */\n times(newCounter) {\n if (newCounter < 1) {\n return this\n }\n\n this.counter = newCounter\n\n return this\n }\n\n /**\n * An sugar syntax for times(1)\n * @name once\n * @see {@link times}\n * @public\n * @example\n * nock('http://zombo.com).get('/').once().reply(200, 'Ok');\n */\n once() {\n return this.times(1)\n }\n\n /**\n * An sugar syntax for times(2)\n * @name twice\n * @see {@link times}\n * @public\n * @example\n * nock('http://zombo.com).get('/').twice().reply(200, 'Ok');\n */\n twice() {\n return this.times(2)\n }\n\n /**\n * An sugar syntax for times(3).\n * @name thrice\n * @see {@link times}\n * @public\n * @example\n * nock('http://zombo.com).get('/').thrice().reply(200, 'Ok');\n */\n thrice() {\n return this.times(3)\n }\n\n /**\n * Delay the response by a certain number of ms.\n *\n * @param {(integer|object)} opts - Number of milliseconds to wait, or an object\n * @param {integer} [opts.head] - Number of milliseconds to wait before response is sent\n * @param {integer} [opts.body] - Number of milliseconds to wait before response body is sent\n * @return {Interceptor} - the current interceptor for chaining\n */\n delay(opts) {\n let headDelay\n let bodyDelay\n if (typeof opts === 'number') {\n headDelay = opts\n bodyDelay = 0\n } else if (typeof opts === 'object') {\n headDelay = opts.head || 0\n bodyDelay = opts.body || 0\n } else {\n throw new Error(`Unexpected input opts ${opts}`)\n }\n\n return this.delayConnection(headDelay).delayBody(bodyDelay)\n }\n\n /**\n * Delay the response body by a certain number of ms.\n *\n * @param {integer} ms - Number of milliseconds to wait before response is sent\n * @return {Interceptor} - the current interceptor for chaining\n */\n delayBody(ms) {\n this.delayBodyInMs = ms\n return this\n }\n\n /**\n * Delay the connection by a certain number of ms.\n *\n * @param {integer} ms - Number of milliseconds to wait\n * @return {Interceptor} - the current interceptor for chaining\n */\n delayConnection(ms) {\n this.delayConnectionInMs = ms\n return this\n }\n}\n","'use strict'\n\n/**\n * @module nock/intercept\n */\n\nconst { InterceptedRequestRouter } = require('./intercepted_request_router')\nconst common = require('./common')\nconst { inherits } = require('util')\nconst http = require('http')\nconst debug = require('debug')('nock.intercept')\nconst globalEmitter = require('./global_emitter')\n\n/**\n * @name NetConnectNotAllowedError\n * @private\n * @desc Error trying to make a connection when disabled external access.\n * @class\n * @example\n * nock.disableNetConnect();\n * http.get('http://zombo.com');\n * // throw NetConnectNotAllowedError\n */\nfunction NetConnectNotAllowedError(host, path) {\n Error.call(this)\n\n this.name = 'NetConnectNotAllowedError'\n this.code = 'ENETUNREACH'\n this.message = `Nock: Disallowed net connect for \"${host}${path}\"`\n\n Error.captureStackTrace(this, this.constructor)\n}\n\ninherits(NetConnectNotAllowedError, Error)\n\nlet allInterceptors = {}\nlet allowNetConnect\n\n/**\n * Enabled real request.\n * @public\n * @param {String|RegExp} matcher=RegExp.new('.*') Expression to match\n * @example\n * // Enables all real requests\n * nock.enableNetConnect();\n * @example\n * // Enables real requests for url that matches google\n * nock.enableNetConnect('google');\n * @example\n * // Enables real requests for url that matches google and amazon\n * nock.enableNetConnect(/(google|amazon)/);\n * @example\n * // Enables real requests for url that includes google\n * nock.enableNetConnect(host => host.includes('google'));\n */\nfunction enableNetConnect(matcher) {\n if (typeof matcher === 'string') {\n allowNetConnect = new RegExp(matcher)\n } else if (matcher instanceof RegExp) {\n allowNetConnect = matcher\n } else if (typeof matcher === 'function') {\n allowNetConnect = { test: matcher }\n } else {\n allowNetConnect = /.*/\n }\n}\n\nfunction isEnabledForNetConnect(options) {\n common.normalizeRequestOptions(options)\n\n const enabled = allowNetConnect && allowNetConnect.test(options.host)\n debug('Net connect', enabled ? '' : 'not', 'enabled for', options.host)\n return enabled\n}\n\n/**\n * Disable all real requests.\n * @public\n * @example\n * nock.disableNetConnect();\n */\nfunction disableNetConnect() {\n allowNetConnect = undefined\n}\n\nfunction isOn() {\n return !isOff()\n}\n\nfunction isOff() {\n return process.env.NOCK_OFF === 'true'\n}\n\nfunction addInterceptor(key, interceptor, scope, scopeOptions, host) {\n if (!(key in allInterceptors)) {\n allInterceptors[key] = { key, interceptors: [] }\n }\n interceptor.__nock_scope = scope\n\n // We need scope's key and scope options for scope filtering function (if defined)\n interceptor.__nock_scopeKey = key\n interceptor.__nock_scopeOptions = scopeOptions\n // We need scope's host for setting correct request headers for filtered scopes.\n interceptor.__nock_scopeHost = host\n interceptor.interceptionCounter = 0\n\n if (scopeOptions.allowUnmocked) allInterceptors[key].allowUnmocked = true\n\n allInterceptors[key].interceptors.push(interceptor)\n}\n\nfunction remove(interceptor) {\n if (interceptor.__nock_scope.shouldPersist() || --interceptor.counter > 0) {\n return\n }\n\n const { basePath } = interceptor\n const interceptors =\n (allInterceptors[basePath] && allInterceptors[basePath].interceptors) || []\n\n // TODO: There is a clearer way to write that we want to delete the first\n // matching instance. I'm also not sure why we couldn't delete _all_\n // matching instances.\n interceptors.some(function (thisInterceptor, i) {\n return thisInterceptor === interceptor ? interceptors.splice(i, 1) : false\n })\n}\n\nfunction removeAll() {\n Object.keys(allInterceptors).forEach(function (key) {\n allInterceptors[key].interceptors.forEach(function (interceptor) {\n interceptor.scope.keyedInterceptors = {}\n })\n })\n allInterceptors = {}\n}\n\n/**\n * Return all the Interceptors whose Scopes match against the base path of the provided options.\n *\n * @returns {Interceptor[]}\n */\nfunction interceptorsFor(options) {\n common.normalizeRequestOptions(options)\n\n debug('interceptors for %j', options.host)\n\n const basePath = `${options.proto}://${options.host}`\n\n debug('filtering interceptors for basepath', basePath)\n\n // First try to use filteringScope if any of the interceptors has it defined.\n for (const { key, interceptors, allowUnmocked } of Object.values(\n allInterceptors,\n )) {\n for (const interceptor of interceptors) {\n const { filteringScope } = interceptor.__nock_scopeOptions\n\n // If scope filtering function is defined and returns a truthy value then\n // we have to treat this as a match.\n if (filteringScope && filteringScope(basePath)) {\n interceptor.scope.logger('found matching scope interceptor')\n\n // Keep the filtered scope (its key) to signal the rest of the module\n // that this wasn't an exact but filtered match.\n interceptors.forEach(ic => {\n ic.__nock_filteredScope = ic.__nock_scopeKey\n })\n return interceptors\n }\n }\n\n if (common.matchStringOrRegexp(basePath, key)) {\n if (allowUnmocked && interceptors.length === 0) {\n debug('matched base path with allowUnmocked (no matching interceptors)')\n return [\n {\n options: { allowUnmocked: true },\n matchOrigin() {\n return false\n },\n },\n ]\n } else {\n debug(\n `matched base path (${interceptors.length} interceptor${\n interceptors.length > 1 ? 's' : ''\n })`,\n )\n return interceptors\n }\n }\n }\n\n return undefined\n}\n\nfunction removeInterceptor(options) {\n // Lazily import to avoid circular imports.\n const Interceptor = require('./interceptor')\n\n let baseUrl, key, method, proto\n if (options instanceof Interceptor) {\n baseUrl = options.basePath\n key = options._key\n } else {\n proto = options.proto ? options.proto : 'http'\n\n common.normalizeRequestOptions(options)\n baseUrl = `${proto}://${options.host}`\n method = (options.method && options.method.toUpperCase()) || 'GET'\n key = `${method} ${baseUrl}${options.path || '/'}`\n }\n\n if (\n allInterceptors[baseUrl] &&\n allInterceptors[baseUrl].interceptors.length > 0\n ) {\n for (let i = 0; i < allInterceptors[baseUrl].interceptors.length; i++) {\n const interceptor = allInterceptors[baseUrl].interceptors[i]\n if (\n options instanceof Interceptor\n ? interceptor === options\n : interceptor._key === key\n ) {\n allInterceptors[baseUrl].interceptors.splice(i, 1)\n interceptor.scope.remove(key, interceptor)\n break\n }\n }\n\n return true\n }\n\n return false\n}\n// Variable where we keep the ClientRequest we have overridden\n// (which might or might not be node's original http.ClientRequest)\nlet originalClientRequest\n\nfunction ErroringClientRequest(error) {\n http.OutgoingMessage.call(this)\n process.nextTick(\n function () {\n this.emit('error', error)\n }.bind(this),\n )\n}\n\ninherits(ErroringClientRequest, http.ClientRequest)\n\nfunction overrideClientRequest() {\n // Here's some background discussion about overriding ClientRequest:\n // - https://github.com/nodejitsu/mock-request/issues/4\n // - https://github.com/nock/nock/issues/26\n // It would be good to add a comment that explains this more clearly.\n debug('Overriding ClientRequest')\n\n // ----- Extending http.ClientRequest\n\n // Define the overriding client request that nock uses internally.\n function OverriddenClientRequest(...args) {\n const { options, callback } = common.normalizeClientRequestArgs(...args)\n\n if (Object.keys(options).length === 0) {\n // As weird as it is, it's possible to call `http.request` without\n // options, and it makes a request to localhost or somesuch. We should\n // support it too, for parity. However it doesn't work today, and fixing\n // it seems low priority. Giving an explicit error is nicer than\n // crashing with a weird stack trace. `http[s].request()`, nock's other\n // client-facing entry point, makes a similar check.\n // https://github.com/nock/nock/pull/1386\n // https://github.com/nock/nock/pull/1440\n throw Error(\n 'Creating a ClientRequest with empty `options` is not supported in Nock',\n )\n }\n\n http.OutgoingMessage.call(this)\n\n // Filter the interceptors per request options.\n const interceptors = interceptorsFor(options)\n\n if (isOn() && interceptors) {\n debug('using', interceptors.length, 'interceptors')\n\n // Use filtered interceptors to intercept requests.\n // TODO: this shouldn't be a class anymore\n // the overrider explicitly overrides methods and attrs on the request so the `assign` below should be removed.\n const overrider = new InterceptedRequestRouter({\n req: this,\n options,\n interceptors,\n })\n Object.assign(this, overrider)\n\n if (callback) {\n this.once('response', callback)\n }\n } else {\n debug('falling back to original ClientRequest')\n\n // Fallback to original ClientRequest if nock is off or the net connection is enabled.\n if (isOff() || isEnabledForNetConnect(options)) {\n originalClientRequest.apply(this, arguments)\n } else {\n common.setImmediate(\n function () {\n const error = new NetConnectNotAllowedError(\n options.host,\n options.path,\n )\n this.emit('error', error)\n }.bind(this),\n )\n }\n }\n }\n inherits(OverriddenClientRequest, http.ClientRequest)\n\n // Override the http module's request but keep the original so that we can use it and later restore it.\n // NOTE: We only override http.ClientRequest as https module also uses it.\n originalClientRequest = http.ClientRequest\n http.ClientRequest = OverriddenClientRequest\n\n debug('ClientRequest overridden')\n}\n\nfunction restoreOverriddenClientRequest() {\n debug('restoring overridden ClientRequest')\n\n // Restore the ClientRequest we have overridden.\n if (!originalClientRequest) {\n debug('- ClientRequest was not overridden')\n } else {\n http.ClientRequest = originalClientRequest\n originalClientRequest = undefined\n\n debug('- ClientRequest restored')\n }\n}\n\nfunction isActive() {\n // If ClientRequest has been overwritten by Nock then originalClientRequest is not undefined.\n // This means that Nock has been activated.\n return originalClientRequest !== undefined\n}\n\nfunction interceptorScopes() {\n const nestedInterceptors = Object.values(allInterceptors).map(\n i => i.interceptors,\n )\n const scopes = new Set([].concat(...nestedInterceptors).map(i => i.scope))\n return [...scopes]\n}\n\nfunction isDone() {\n return interceptorScopes().every(scope => scope.isDone())\n}\n\nfunction pendingMocks() {\n return [].concat(...interceptorScopes().map(scope => scope.pendingMocks()))\n}\n\nfunction activeMocks() {\n return [].concat(...interceptorScopes().map(scope => scope.activeMocks()))\n}\n\nfunction activate() {\n if (originalClientRequest) {\n throw new Error('Nock already active')\n }\n\n // ----- Overriding http.request and https.request:\n\n common.overrideRequests(function (proto, overriddenRequest, args) {\n // NOTE: overriddenRequest is already bound to its module.\n\n const { options, callback } = common.normalizeClientRequestArgs(...args)\n\n if (Object.keys(options).length === 0) {\n // As weird as it is, it's possible to call `http.request` without\n // options, and it makes a request to localhost or somesuch. We should\n // support it too, for parity. However it doesn't work today, and fixing\n // it seems low priority. Giving an explicit error is nicer than\n // crashing with a weird stack trace. `new ClientRequest()`, nock's\n // other client-facing entry point, makes a similar check.\n // https://github.com/nock/nock/pull/1386\n // https://github.com/nock/nock/pull/1440\n throw Error(\n 'Making a request with empty `options` is not supported in Nock',\n )\n }\n\n // The option per the docs is `protocol`. Its unclear if this line is meant to override that and is misspelled or if\n // the intend is to explicitly keep track of which module was called using a separate name.\n // Either way, `proto` is used as the source of truth from here on out.\n options.proto = proto\n\n const interceptors = interceptorsFor(options)\n\n if (isOn() && interceptors) {\n const matches = interceptors.some(interceptor =>\n interceptor.matchOrigin(options),\n )\n const allowUnmocked = interceptors.some(\n interceptor => interceptor.options.allowUnmocked,\n )\n\n if (!matches && allowUnmocked) {\n let req\n if (proto === 'https') {\n const { ClientRequest } = http\n http.ClientRequest = originalClientRequest\n req = overriddenRequest(options, callback)\n http.ClientRequest = ClientRequest\n } else {\n req = overriddenRequest(options, callback)\n }\n globalEmitter.emit('no match', req)\n return req\n }\n\n // NOTE: Since we already overrode the http.ClientRequest we are in fact constructing\n // our own OverriddenClientRequest.\n return new http.ClientRequest(options, callback)\n } else {\n globalEmitter.emit('no match', options)\n if (isOff() || isEnabledForNetConnect(options)) {\n return overriddenRequest(options, callback)\n } else {\n const error = new NetConnectNotAllowedError(options.host, options.path)\n return new ErroringClientRequest(error)\n }\n }\n })\n\n overrideClientRequest()\n}\n\nmodule.exports = {\n addInterceptor,\n remove,\n removeAll,\n removeInterceptor,\n isOn,\n activate,\n isActive,\n isDone,\n pendingMocks,\n activeMocks,\n enableNetConnect,\n disableNetConnect,\n restoreOverriddenClientRequest,\n abortPendingRequests: common.removeAllTimers,\n}\n","'use strict'\n\nconst debug = require('debug')('nock.recorder')\nconst querystring = require('querystring')\nconst { inspect } = require('util')\n\nconst common = require('./common')\nconst { restoreOverriddenClientRequest } = require('./intercept')\n\nconst SEPARATOR = '\\n<<<<<<-- cut here -->>>>>>\\n'\nlet recordingInProgress = false\nlet outputs = []\n\nfunction getScope(options) {\n const { proto, host, port } = common.normalizeRequestOptions(options)\n return common.normalizeOrigin(proto, host, port)\n}\n\nfunction getMethod(options) {\n return options.method || 'GET'\n}\n\nfunction getBodyFromChunks(chunks, headers) {\n // If we have headers and there is content-encoding it means that the body\n // shouldn't be merged but instead persisted as an array of hex strings so\n // that the response chunks can be mocked one by one.\n if (headers && common.isContentEncoded(headers)) {\n return {\n body: chunks.map(chunk => chunk.toString('hex')),\n }\n }\n\n const mergedBuffer = Buffer.concat(chunks)\n\n // The merged buffer can be one of three things:\n // 1. A UTF-8-representable string buffer which represents a JSON object.\n // 2. A UTF-8-representable buffer which doesn't represent a JSON object.\n // 3. A non-UTF-8-representable buffer which then has to be recorded as a hex string.\n const isUtf8Representable = common.isUtf8Representable(mergedBuffer)\n if (isUtf8Representable) {\n const maybeStringifiedJson = mergedBuffer.toString('utf8')\n try {\n return {\n isUtf8Representable,\n body: JSON.parse(maybeStringifiedJson),\n }\n } catch (err) {\n return {\n isUtf8Representable,\n body: maybeStringifiedJson,\n }\n }\n } else {\n return {\n isUtf8Representable,\n body: mergedBuffer.toString('hex'),\n }\n }\n}\n\nfunction generateRequestAndResponseObject({\n req,\n bodyChunks,\n options,\n res,\n dataChunks,\n reqheaders,\n}) {\n const { body, isUtf8Representable } = getBodyFromChunks(\n dataChunks,\n res.headers,\n )\n options.path = req.path\n\n return {\n scope: getScope(options),\n method: getMethod(options),\n path: options.path,\n // Is it deliberate that `getBodyFromChunks()` is called a second time?\n body: getBodyFromChunks(bodyChunks).body,\n status: res.statusCode,\n response: body,\n rawHeaders: res.rawHeaders,\n reqheaders: reqheaders || undefined,\n // When content-encoding is enabled, isUtf8Representable is `undefined`,\n // so we explicitly check for `false`.\n responseIsBinary: isUtf8Representable === false,\n }\n}\n\nfunction generateRequestAndResponse({\n req,\n bodyChunks,\n options,\n res,\n dataChunks,\n reqheaders,\n}) {\n const requestBody = getBodyFromChunks(bodyChunks).body\n const responseBody = getBodyFromChunks(dataChunks, res.headers).body\n\n // Remove any query params from options.path so they can be added in the query() function\n let { path } = options\n const queryIndex = req.path.indexOf('?')\n let queryObj = {}\n if (queryIndex !== -1) {\n // Remove the query from the path\n path = path.substring(0, queryIndex)\n\n const queryStr = req.path.slice(queryIndex + 1)\n queryObj = querystring.parse(queryStr)\n }\n\n // Escape any single quotes in the path as the output uses them\n path = path.replace(/'/g, `\\\\'`)\n\n // Always encode the query parameters when recording.\n const encodedQueryObj = {}\n for (const key in queryObj) {\n const formattedPair = common.formatQueryValue(\n key,\n queryObj[key],\n common.percentEncode,\n )\n encodedQueryObj[formattedPair[0]] = formattedPair[1]\n }\n\n const lines = []\n\n // We want a leading newline.\n lines.push('')\n\n const scope = getScope(options)\n lines.push(`nock('${scope}', {\"encodedQueryParams\":true})`)\n\n const methodName = getMethod(options).toLowerCase()\n if (requestBody) {\n lines.push(` .${methodName}('${path}', ${JSON.stringify(requestBody)})`)\n } else {\n lines.push(` .${methodName}('${path}')`)\n }\n\n Object.entries(reqheaders || {}).forEach(([fieldName, fieldValue]) => {\n const safeName = JSON.stringify(fieldName)\n const safeValue = JSON.stringify(fieldValue)\n lines.push(` .matchHeader(${safeName}, ${safeValue})`)\n })\n\n if (queryIndex !== -1) {\n lines.push(` .query(${JSON.stringify(encodedQueryObj)})`)\n }\n\n const statusCode = res.statusCode.toString()\n const stringifiedResponseBody = JSON.stringify(responseBody)\n const headers = inspect(res.rawHeaders)\n lines.push(` .reply(${statusCode}, ${stringifiedResponseBody}, ${headers});`)\n\n return lines.join('\\n')\n}\n\n// This module variable is used to identify a unique recording ID in order to skip\n// spurious requests that sometimes happen. This problem has been, so far,\n// exclusively detected in nock's unit testing where 'checks if callback is specified'\n// interferes with other tests as its t.end() is invoked without waiting for request\n// to finish (which is the point of the test).\nlet currentRecordingId = 0\n\nconst defaultRecordOptions = {\n dont_print: false,\n enable_reqheaders_recording: false,\n logging: console.log, // eslint-disable-line no-console\n output_objects: false,\n use_separator: true,\n}\n\nfunction record(recOptions) {\n // Trying to start recording with recording already in progress implies an error\n // in the recording configuration (double recording makes no sense and used to lead\n // to duplicates in output)\n if (recordingInProgress) {\n throw new Error('Nock recording already in progress')\n }\n\n recordingInProgress = true\n\n // Set the new current recording ID and capture its value in this instance of record().\n currentRecordingId = currentRecordingId + 1\n const thisRecordingId = currentRecordingId\n\n // Originally the parameter was a dont_print boolean flag.\n // To keep the existing code compatible we take that case into account.\n if (typeof recOptions === 'boolean') {\n recOptions = { dont_print: recOptions }\n }\n\n recOptions = { ...defaultRecordOptions, ...recOptions }\n\n debug('start recording', thisRecordingId, recOptions)\n\n const {\n dont_print: dontPrint,\n enable_reqheaders_recording: enableReqHeadersRecording,\n logging,\n output_objects: outputObjects,\n use_separator: useSeparator,\n } = recOptions\n\n debug(thisRecordingId, 'restoring overridden requests before new overrides')\n // To preserve backward compatibility (starting recording wasn't throwing if nock was already active)\n // we restore any requests that may have been overridden by other parts of nock (e.g. intercept)\n // NOTE: This is hacky as hell but it keeps the backward compatibility *and* allows correct\n // behavior in the face of other modules also overriding ClientRequest.\n common.restoreOverriddenRequests()\n // We restore ClientRequest as it messes with recording of modules that also override ClientRequest (e.g. xhr2)\n restoreOverriddenClientRequest()\n\n // We override the requests so that we can save information on them before executing.\n common.overrideRequests(function (proto, overriddenRequest, rawArgs) {\n const { options, callback } = common.normalizeClientRequestArgs(...rawArgs)\n const bodyChunks = []\n\n // Node 0.11 https.request calls http.request -- don't want to record things\n // twice.\n /* istanbul ignore if */\n if (options._recording) {\n return overriddenRequest(options, callback)\n }\n options._recording = true\n\n const req = overriddenRequest(options, function (res) {\n debug(thisRecordingId, 'intercepting', proto, 'request to record')\n\n // We put our 'end' listener to the front of the listener array.\n res.once('end', function () {\n debug(thisRecordingId, proto, 'intercepted request ended')\n\n let reqheaders\n // Ignore request headers completely unless it was explicitly enabled by the user (see README)\n if (enableReqHeadersRecording) {\n // We never record user-agent headers as they are worse than useless -\n // they actually make testing more difficult without providing any benefit (see README)\n reqheaders = req.getHeaders()\n common.deleteHeadersField(reqheaders, 'user-agent')\n }\n\n const generateFn = outputObjects\n ? generateRequestAndResponseObject\n : generateRequestAndResponse\n let out = generateFn({\n req,\n bodyChunks,\n options,\n res,\n dataChunks,\n reqheaders,\n })\n\n debug('out:', out)\n\n // Check that the request was made during the current recording.\n // If it hasn't then skip it. There is no other simple way to handle\n // this as it depends on the timing of requests and responses. Throwing\n // will make some recordings/unit tests fail randomly depending on how\n // fast/slow the response arrived.\n // If you are seeing this error then you need to make sure that all\n // the requests made during a single recording session finish before\n // ending the same recording session.\n if (thisRecordingId !== currentRecordingId) {\n debug('skipping recording of an out-of-order request', out)\n return\n }\n\n outputs.push(out)\n\n if (!dontPrint) {\n if (useSeparator) {\n if (typeof out !== 'string') {\n out = JSON.stringify(out, null, 2)\n }\n logging(SEPARATOR + out + SEPARATOR)\n } else {\n logging(out)\n }\n }\n })\n\n let encoding\n // We need to be aware of changes to the stream's encoding so that we\n // don't accidentally mangle the data.\n const { setEncoding } = res\n res.setEncoding = function (newEncoding) {\n encoding = newEncoding\n return setEncoding.apply(this, arguments)\n }\n\n const dataChunks = []\n // Replace res.push with our own implementation that stores chunks\n const origResPush = res.push\n res.push = function (data) {\n if (data) {\n if (encoding) {\n data = Buffer.from(data, encoding)\n }\n dataChunks.push(data)\n }\n\n return origResPush.call(res, data)\n }\n\n if (callback) {\n callback(res, options, callback)\n }\n\n debug('finished setting up intercepting')\n\n // We override both the http and the https modules; when we are\n // serializing the request, we need to know which was called.\n // By stuffing the state, we can make sure that nock records\n // the intended protocol.\n if (proto === 'https') {\n options.proto = 'https'\n }\n })\n\n const recordChunk = (chunk, encoding) => {\n debug(thisRecordingId, 'new', proto, 'body chunk')\n if (!Buffer.isBuffer(chunk)) {\n chunk = Buffer.from(chunk, encoding)\n }\n bodyChunks.push(chunk)\n }\n\n const oldWrite = req.write\n req.write = function (chunk, encoding) {\n if (typeof chunk !== 'undefined') {\n recordChunk(chunk, encoding)\n oldWrite.apply(req, arguments)\n } else {\n throw new Error('Data was undefined.')\n }\n }\n\n // Starting in Node 8, `OutgoingMessage.end()` directly calls an internal\n // `write_` function instead of proxying to the public\n // `OutgoingMessage.write()` method, so we have to wrap `end` too.\n const oldEnd = req.end\n req.end = function (chunk, encoding, callback) {\n debug('req.end')\n if (typeof chunk === 'function') {\n callback = chunk\n chunk = null\n } else if (typeof encoding === 'function') {\n callback = encoding\n encoding = null\n }\n\n if (chunk) {\n recordChunk(chunk, encoding)\n }\n oldEnd.call(req, chunk, encoding, callback)\n }\n\n return req\n })\n}\n\n// Restore *all* the overridden http/https modules' properties.\nfunction restore() {\n debug(\n currentRecordingId,\n 'restoring all the overridden http/https properties',\n )\n\n common.restoreOverriddenRequests()\n restoreOverriddenClientRequest()\n recordingInProgress = false\n}\n\nfunction clear() {\n outputs = []\n}\n\nmodule.exports = {\n record,\n outputs: () => outputs,\n restore,\n clear,\n}\n","'use strict'\n\n/**\n * @module nock/scope\n */\nconst { addInterceptor, isOn } = require('./intercept')\nconst common = require('./common')\nconst assert = require('assert')\nconst url = require('url')\nconst debug = require('debug')('nock.scope')\nconst { EventEmitter } = require('events')\nconst Interceptor = require('./interceptor')\n\nconst { URL, Url: LegacyUrl } = url\nlet fs\n\ntry {\n fs = require('fs')\n} catch (err) {\n // do nothing, we're in the browser\n}\n\n/**\n * Normalizes the passed url for consistent internal processing\n * @param {string|LegacyUrl|URL} u\n */\nfunction normalizeUrl(u) {\n if (!(u instanceof URL)) {\n if (u instanceof LegacyUrl) {\n return normalizeUrl(new URL(url.format(u)))\n }\n // If the url is invalid, let the URL library report it\n return normalizeUrl(new URL(u))\n }\n\n if (!/https?:/.test(u.protocol)) {\n throw new TypeError(\n `Protocol '${u.protocol}' not recognized. This commonly occurs when a hostname and port are included without a protocol, producing a URL that is valid but confusing, and probably not what you want.`,\n )\n }\n\n return {\n href: u.href,\n origin: u.origin,\n protocol: u.protocol,\n username: u.username,\n password: u.password,\n host: u.host,\n hostname:\n // strip brackets from IPv6\n typeof u.hostname === 'string' && u.hostname.startsWith('[')\n ? u.hostname.slice(1, -1)\n : u.hostname,\n port: u.port || (u.protocol === 'http:' ? 80 : 443),\n pathname: u.pathname,\n search: u.search,\n searchParams: u.searchParams,\n hash: u.hash,\n }\n}\n\n/**\n * @param {string|RegExp|LegacyUrl|URL} basePath\n * @param {Object} options\n * @param {boolean} options.allowUnmocked\n * @param {string[]} options.badheaders\n * @param {function} options.conditionally\n * @param {boolean} options.encodedQueryParams\n * @param {function} options.filteringScope\n * @param {Object} options.reqheaders\n * @constructor\n */\nclass Scope extends EventEmitter {\n constructor(basePath, options) {\n super()\n\n this.keyedInterceptors = {}\n this.interceptors = []\n this.transformPathFunction = null\n this.transformRequestBodyFunction = null\n this.matchHeaders = []\n this.scopeOptions = options || {}\n this.urlParts = {}\n this._persist = false\n this.contentLen = false\n this.date = null\n this.basePath = basePath\n this.basePathname = ''\n this.port = null\n this._defaultReplyHeaders = []\n\n let logNamespace = String(basePath)\n\n if (!(basePath instanceof RegExp)) {\n this.urlParts = normalizeUrl(basePath)\n this.port = this.urlParts.port\n this.basePathname = this.urlParts.pathname.replace(/\\/$/, '')\n this.basePath = `${this.urlParts.protocol}//${this.urlParts.hostname}:${this.port}`\n logNamespace = this.urlParts.host\n }\n\n this.logger = debug.extend(logNamespace)\n }\n\n add(key, interceptor) {\n if (!(key in this.keyedInterceptors)) {\n this.keyedInterceptors[key] = []\n }\n this.keyedInterceptors[key].push(interceptor)\n addInterceptor(\n this.basePath,\n interceptor,\n this,\n this.scopeOptions,\n this.urlParts.hostname,\n )\n }\n\n remove(key, interceptor) {\n if (this._persist) {\n return\n }\n const arr = this.keyedInterceptors[key]\n if (arr) {\n arr.splice(arr.indexOf(interceptor), 1)\n if (arr.length === 0) {\n delete this.keyedInterceptors[key]\n }\n }\n }\n\n intercept(uri, method, requestBody, interceptorOptions) {\n const ic = new Interceptor(\n this,\n uri,\n method,\n requestBody,\n interceptorOptions,\n )\n\n this.interceptors.push(ic)\n return ic\n }\n\n get(uri, requestBody, options) {\n return this.intercept(uri, 'GET', requestBody, options)\n }\n\n post(uri, requestBody, options) {\n return this.intercept(uri, 'POST', requestBody, options)\n }\n\n put(uri, requestBody, options) {\n return this.intercept(uri, 'PUT', requestBody, options)\n }\n\n head(uri, requestBody, options) {\n return this.intercept(uri, 'HEAD', requestBody, options)\n }\n\n patch(uri, requestBody, options) {\n return this.intercept(uri, 'PATCH', requestBody, options)\n }\n\n merge(uri, requestBody, options) {\n return this.intercept(uri, 'MERGE', requestBody, options)\n }\n\n delete(uri, requestBody, options) {\n return this.intercept(uri, 'DELETE', requestBody, options)\n }\n\n options(uri, requestBody, options) {\n return this.intercept(uri, 'OPTIONS', requestBody, options)\n }\n\n // Returns the list of keys for non-optional Interceptors that haven't been completed yet.\n // TODO: This assumes that completed mocks are removed from the keyedInterceptors list\n // (when persistence is off). We should change that (and this) in future.\n pendingMocks() {\n return this.activeMocks().filter(key =>\n this.keyedInterceptors[key].some(({ interceptionCounter, optional }) => {\n const persistedAndUsed = this._persist && interceptionCounter > 0\n return !persistedAndUsed && !optional\n }),\n )\n }\n\n // Returns all keyedInterceptors that are active.\n // This includes incomplete interceptors, persisted but complete interceptors, and\n // optional interceptors, but not non-persisted and completed interceptors.\n activeMocks() {\n return Object.keys(this.keyedInterceptors)\n }\n\n isDone() {\n if (!isOn()) {\n return true\n }\n\n return this.pendingMocks().length === 0\n }\n\n done() {\n assert.ok(\n this.isDone(),\n `Mocks not yet satisfied:\\n${this.pendingMocks().join('\\n')}`,\n )\n }\n\n buildFilter() {\n const filteringArguments = arguments\n\n if (arguments[0] instanceof RegExp) {\n return function (candidate) {\n /* istanbul ignore if */\n if (typeof candidate !== 'string') {\n // Given the way nock is written, it seems like `candidate` will always\n // be a string, regardless of what options might be passed to it.\n // However the code used to contain a truthiness test of `candidate`.\n // The check is being preserved for now.\n throw Error(\n `Nock internal assertion failed: typeof candidate is ${typeof candidate}. If you encounter this error, please report it as a bug.`,\n )\n }\n return candidate.replace(filteringArguments[0], filteringArguments[1])\n }\n } else if (typeof arguments[0] === 'function') {\n return arguments[0]\n }\n }\n\n filteringPath() {\n this.transformPathFunction = this.buildFilter.apply(this, arguments)\n if (!this.transformPathFunction) {\n throw new Error(\n 'Invalid arguments: filtering path should be a function or a regular expression',\n )\n }\n return this\n }\n\n filteringRequestBody() {\n this.transformRequestBodyFunction = this.buildFilter.apply(this, arguments)\n if (!this.transformRequestBodyFunction) {\n throw new Error(\n 'Invalid arguments: filtering request body should be a function or a regular expression',\n )\n }\n return this\n }\n\n matchHeader(name, value) {\n // We use lower-case header field names throughout Nock.\n this.matchHeaders.push({ name: name.toLowerCase(), value })\n return this\n }\n\n defaultReplyHeaders(headers) {\n this._defaultReplyHeaders = common.headersInputToRawArray(headers)\n return this\n }\n\n persist(flag = true) {\n if (typeof flag !== 'boolean') {\n throw new Error('Invalid arguments: argument should be a boolean')\n }\n this._persist = flag\n return this\n }\n\n /**\n * @private\n * @returns {boolean}\n */\n shouldPersist() {\n return this._persist\n }\n\n replyContentLength() {\n this.contentLen = true\n return this\n }\n\n replyDate(d) {\n this.date = d || new Date()\n return this\n }\n\n clone() {\n return new Scope(this.basePath, this.scopeOptions)\n }\n}\n\nfunction loadDefs(path) {\n if (!fs) {\n throw new Error('No fs')\n }\n\n const contents = fs.readFileSync(path)\n return JSON.parse(contents)\n}\n\nfunction load(path) {\n return define(loadDefs(path))\n}\n\nfunction getStatusFromDefinition(nockDef) {\n // Backward compatibility for when `status` was encoded as string in `reply`.\n if (nockDef.reply !== undefined) {\n const parsedReply = parseInt(nockDef.reply, 10)\n if (isNaN(parsedReply)) {\n throw Error('`reply`, when present, must be a numeric string')\n }\n\n return parsedReply\n }\n\n const DEFAULT_STATUS_OK = 200\n return nockDef.status || DEFAULT_STATUS_OK\n}\n\nfunction getScopeFromDefinition(nockDef) {\n // Backward compatibility for when `port` was part of definition.\n if (nockDef.port !== undefined) {\n // Include `port` into scope if it doesn't exist.\n const options = url.parse(nockDef.scope)\n if (options.port === null) {\n return `${nockDef.scope}:${nockDef.port}`\n } else {\n if (parseInt(options.port) !== parseInt(nockDef.port)) {\n throw new Error(\n 'Mismatched port numbers in scope and port properties of nock definition.',\n )\n }\n }\n }\n\n return nockDef.scope\n}\n\nfunction tryJsonParse(string) {\n try {\n return JSON.parse(string)\n } catch (err) {\n return string\n }\n}\n\nfunction define(nockDefs) {\n const scopes = []\n\n nockDefs.forEach(function (nockDef) {\n const nscope = getScopeFromDefinition(nockDef)\n const npath = nockDef.path\n if (!nockDef.method) {\n throw Error('Method is required')\n }\n const method = nockDef.method.toLowerCase()\n const status = getStatusFromDefinition(nockDef)\n const rawHeaders = nockDef.rawHeaders || []\n const reqheaders = nockDef.reqheaders || {}\n const badheaders = nockDef.badheaders || []\n const options = { ...nockDef.options }\n\n // We use request headers for both filtering (see below) and mocking.\n // Here we are setting up mocked request headers but we don't want to\n // be changing the user's options object so we clone it first.\n options.reqheaders = reqheaders\n options.badheaders = badheaders\n\n // Response is not always JSON as it could be a string or binary data or\n // even an array of binary buffers (e.g. when content is encoded).\n let response\n if (!nockDef.response) {\n response = ''\n // TODO: Rename `responseIsBinary` to `responseIsUtf8Representable`.\n } else if (nockDef.responseIsBinary) {\n response = Buffer.from(nockDef.response, 'hex')\n } else {\n response =\n typeof nockDef.response === 'string'\n ? tryJsonParse(nockDef.response)\n : nockDef.response\n }\n\n const scope = new Scope(nscope, options)\n\n // If request headers were specified filter by them.\n Object.entries(reqheaders).forEach(([fieldName, value]) => {\n scope.matchHeader(fieldName, value)\n })\n\n const acceptableFilters = ['filteringRequestBody', 'filteringPath']\n acceptableFilters.forEach(filter => {\n if (nockDef[filter]) {\n scope[filter](nockDef[filter])\n }\n })\n\n scope\n .intercept(npath, method, nockDef.body)\n .reply(status, response, rawHeaders)\n\n scopes.push(scope)\n })\n\n return scopes\n}\n\nmodule.exports = {\n Scope,\n load,\n loadDefs,\n define,\n}\n","'use strict'\n\nconst assert = require('assert')\nconst recorder = require('./recorder')\nconst {\n activate,\n disableNetConnect,\n enableNetConnect,\n removeAll: cleanAll,\n} = require('./intercept')\nconst { loadDefs, define } = require('./scope')\n\nconst { format } = require('util')\nconst path = require('path')\nconst debug = require('debug')('nock.back')\n\nlet _mode = null\n\nlet fs\n\ntry {\n fs = require('fs')\n} catch (err) {\n // do nothing, probably in browser\n}\n\n/**\n * nock the current function with the fixture given\n *\n * @param {string} fixtureName - the name of the fixture, e.x. 'foo.json'\n * @param {object} options - [optional] extra options for nock with, e.x. `{ assert: true }`\n * @param {function} nockedFn - [optional] callback function to be executed with the given fixture being loaded;\n * if defined the function will be called with context `{ scopes: loaded_nocks || [] }`\n * set as `this` and `nockDone` callback function as first and only parameter;\n * if not defined a promise resolving to `{nockDone, context}` where `context` is\n * aforementioned `{ scopes: loaded_nocks || [] }`\n *\n * List of options:\n *\n * @param {function} before - a preprocessing function, gets called before nock.define\n * @param {function} after - a postprocessing function, gets called after nock.define\n * @param {function} afterRecord - a postprocessing function, gets called after recording. Is passed the array\n * of scopes recorded and should return the array scopes to save to the fixture\n * @param {function} recorder - custom options to pass to the recorder\n *\n */\nfunction Back(fixtureName, options, nockedFn) {\n if (!Back.fixtures) {\n throw new Error(\n 'Back requires nock.back.fixtures to be set\\n' +\n 'Ex:\\n' +\n \"\\trequire(nock).back.fixtures = '/path/to/fixtures/'\",\n )\n }\n\n if (typeof fixtureName !== 'string') {\n throw new Error('Parameter fixtureName must be a string')\n }\n\n if (arguments.length === 1) {\n options = {}\n } else if (arguments.length === 2) {\n // If 2nd parameter is a function then `options` has been omitted\n // otherwise `options` haven't been omitted but `nockedFn` was.\n if (typeof options === 'function') {\n nockedFn = options\n options = {}\n }\n }\n\n _mode.setup()\n\n const fixture = path.join(Back.fixtures, fixtureName)\n const context = _mode.start(fixture, options)\n\n const nockDone = function () {\n _mode.finish(fixture, options, context)\n }\n\n debug('context:', context)\n\n // If nockedFn is a function then invoke it, otherwise return a promise resolving to nockDone.\n if (typeof nockedFn === 'function') {\n nockedFn.call(context, nockDone)\n } else {\n return Promise.resolve({ nockDone, context })\n }\n}\n\n/*******************************************************************************\n * Modes *\n *******************************************************************************/\n\nconst wild = {\n setup: function () {\n cleanAll()\n recorder.restore()\n activate()\n enableNetConnect()\n },\n\n start: function () {\n return load() // don't load anything but get correct context\n },\n\n finish: function () {\n // nothing to do\n },\n}\n\nconst dryrun = {\n setup: function () {\n recorder.restore()\n cleanAll()\n activate()\n // We have to explicitly enable net connectivity as by default it's off.\n enableNetConnect()\n },\n\n start: function (fixture, options) {\n const contexts = load(fixture, options)\n\n enableNetConnect()\n return contexts\n },\n\n finish: function () {\n // nothing to do\n },\n}\n\nconst record = {\n setup: function () {\n recorder.restore()\n recorder.clear()\n cleanAll()\n activate()\n disableNetConnect()\n },\n\n start: function (fixture, options) {\n if (!fs) {\n throw new Error('no fs')\n }\n const context = load(fixture, options)\n\n if (!context.isLoaded) {\n recorder.record({\n dont_print: true,\n output_objects: true,\n ...options.recorder,\n })\n\n context.isRecording = true\n }\n\n return context\n },\n\n finish: function (fixture, options, context) {\n if (context.isRecording) {\n let outputs = recorder.outputs()\n\n if (typeof options.afterRecord === 'function') {\n outputs = options.afterRecord(outputs)\n }\n\n outputs =\n typeof outputs === 'string' ? outputs : JSON.stringify(outputs, null, 4)\n debug('recorder outputs:', outputs)\n\n fs.mkdirSync(path.dirname(fixture), { recursive: true })\n fs.writeFileSync(fixture, outputs)\n }\n },\n}\n\nconst update = {\n setup: function () {\n recorder.restore()\n recorder.clear()\n cleanAll()\n activate()\n disableNetConnect()\n },\n\n start: function (fixture, options) {\n if (!fs) {\n throw new Error('no fs')\n }\n const context = removeFixture(fixture)\n recorder.record({\n dont_print: true,\n output_objects: true,\n ...options.recorder,\n })\n\n context.isRecording = true\n\n return context\n },\n\n finish: function (fixture, options, context) {\n let outputs = recorder.outputs()\n\n if (typeof options.afterRecord === 'function') {\n outputs = options.afterRecord(outputs)\n }\n\n outputs =\n typeof outputs === 'string' ? outputs : JSON.stringify(outputs, null, 4)\n debug('recorder outputs:', outputs)\n\n fs.mkdirSync(path.dirname(fixture), { recursive: true })\n fs.writeFileSync(fixture, outputs)\n },\n}\n\nconst lockdown = {\n setup: function () {\n recorder.restore()\n recorder.clear()\n cleanAll()\n activate()\n disableNetConnect()\n },\n\n start: function (fixture, options) {\n return load(fixture, options)\n },\n\n finish: function () {\n // nothing to do\n },\n}\n\nfunction load(fixture, options) {\n const context = {\n scopes: [],\n assertScopesFinished: function () {\n assertScopes(this.scopes, fixture)\n },\n query: function () {\n const nested = this.scopes.map(scope =>\n scope.interceptors.map(interceptor => ({\n method: interceptor.method,\n uri: interceptor.uri,\n basePath: interceptor.basePath,\n path: interceptor.path,\n queries: interceptor.queries,\n counter: interceptor.counter,\n body: interceptor.body,\n statusCode: interceptor.statusCode,\n optional: interceptor.optional,\n })),\n )\n\n return [].concat.apply([], nested)\n },\n }\n\n if (fixture && fixtureExists(fixture)) {\n let scopes = loadDefs(fixture)\n applyHook(scopes, options.before)\n\n scopes = define(scopes)\n applyHook(scopes, options.after)\n\n context.scopes = scopes\n context.isLoaded = true\n }\n\n return context\n}\n\nfunction removeFixture(fixture, options) {\n const context = {\n scopes: [],\n assertScopesFinished: function () {},\n }\n\n if (fixture && fixtureExists(fixture)) {\n /* istanbul ignore next - fs.unlinkSync is for node 10 support */\n fs.rmSync ? fs.rmSync(fixture) : fs.unlinkSync(fixture)\n }\n context.isLoaded = false\n return context\n}\n\nfunction applyHook(scopes, fn) {\n if (!fn) {\n return\n }\n\n if (typeof fn !== 'function') {\n throw new Error('processing hooks must be a function')\n }\n\n scopes.forEach(fn)\n}\n\nfunction fixtureExists(fixture) {\n if (!fs) {\n throw new Error('no fs')\n }\n\n return fs.existsSync(fixture)\n}\n\nfunction assertScopes(scopes, fixture) {\n const pending = scopes\n .filter(scope => !scope.isDone())\n .map(scope => scope.pendingMocks())\n\n if (pending.length) {\n assert.fail(\n format(\n '%j was not used, consider removing %s to rerecord fixture',\n [].concat(...pending),\n fixture,\n ),\n )\n }\n}\n\nconst Modes = {\n wild, // all requests go out to the internet, dont replay anything, doesnt record anything\n\n dryrun, // use recorded nocks, allow http calls, doesnt record anything, useful for writing new tests (default)\n\n record, // use recorded nocks, record new nocks\n\n update, // allow http calls, record all nocks, don't use recorded nocks\n\n lockdown, // use recorded nocks, disables all http calls even when not nocked, doesnt record\n}\n\nBack.setMode = function (mode) {\n if (!(mode in Modes)) {\n throw new Error(`Unknown mode: ${mode}`)\n }\n\n Back.currentMode = mode\n debug('New nock back mode:', Back.currentMode)\n\n _mode = Modes[mode]\n _mode.setup()\n}\n\nBack.fixtures = null\nBack.currentMode = null\n\nmodule.exports = Back\n","'use strict'\n\nconst back = require('./lib/back')\nconst emitter = require('./lib/global_emitter')\nconst {\n activate,\n isActive,\n isDone,\n isOn,\n pendingMocks,\n activeMocks,\n removeInterceptor,\n disableNetConnect,\n enableNetConnect,\n removeAll,\n abortPendingRequests,\n} = require('./lib/intercept')\nconst recorder = require('./lib/recorder')\nconst { Scope, load, loadDefs, define } = require('./lib/scope')\n\nmodule.exports = (basePath, options) => new Scope(basePath, options)\n\nObject.assign(module.exports, {\n activate,\n isActive,\n isDone,\n pendingMocks,\n activeMocks,\n removeInterceptor,\n disableNetConnect,\n enableNetConnect,\n cleanAll: removeAll,\n abortPendingRequests,\n load,\n loadDefs,\n define,\n emitter,\n recorder: {\n rec: recorder.record,\n clear: recorder.clear,\n play: recorder.outputs,\n },\n restore: recorder.restore,\n back,\n})\n\n// We always activate Nock on import, overriding the globals.\n// Setting the Back mode \"activates\" Nock by overriding the global entries in the `http/s` modules.\n// If Nock Back is configured, we need to honor that setting for backward compatibility,\n// otherwise we rely on Nock Back's default initializing side effect.\nif (isOn()) {\n back.setMode(process.env.NOCK_BACK_MODE || 'dryrun')\n}\n","export const enum Env {\n DEV = 'dev',\n UAT = 'uat',\n PRD = 'prd',\n}\n\nexport const enum Platform {\n MOBILE = 'mobile',\n EXTENSION = 'extension',\n PORTFOLIO = 'portfolio',\n INFURA = 'infura',\n}\n\ntype EnvUrlsEntry = {\n authApiUrl: string;\n oidcApiUrl: string;\n userStorageApiUrl: string;\n};\n\nconst ENV_URLS: Record<Env, EnvUrlsEntry> = {\n dev: {\n authApiUrl: 'https://authentication.dev-api.cx.metamask.io',\n oidcApiUrl: 'https://oidc.dev-api.cx.metamask.io',\n userStorageApiUrl: 'https://user-storage.dev-api.cx.metamask.io',\n },\n uat: {\n authApiUrl: 'https://authentication.uat-api.cx.metamask.io',\n oidcApiUrl: 'https://oidc.uat-api.cx.metamask.io',\n userStorageApiUrl: 'https://user-storage.uat-api.cx.metamask.io',\n },\n prd: {\n authApiUrl: 'https://authentication.api.cx.metamask.io',\n oidcApiUrl: 'https://oidc.api.cx.metamask.io',\n userStorageApiUrl: 'https://user-storage.api.cx.metamask.io',\n },\n};\n\n/**\n * Validates and returns correct environment endpoints\n *\n * @param env - environment field\n * @returns the correct environment url\n * @throws on invalid environment passed\n */\nexport function getEnvUrls(env: Env): EnvUrlsEntry {\n if (!ENV_URLS[env]) {\n throw new Error('invalid environment configuration');\n }\n return ENV_URLS[env];\n}\n\n/**\n * Returns the valid OIDC Client ID (used during authorization)\n *\n * @param env - environment field\n * @param platform - platform field\n * @returns the OIDC client id for the environment\n */\nexport function getOidcClientId(env: Env, platform: Platform): string {\n const clientIds = {\n [Env.DEV]: {\n [Platform.PORTFOLIO]: 'c7ca94a0-5d52-4635-9502-1a50a9c410cc',\n [Platform.MOBILE]: 'e83c7cc9-267d-4fb4-8fec-f0e3bbe5ae8e',\n [Platform.EXTENSION]: 'f1a963d7-50dc-4cb5-8d81-f1f3654f0df3',\n [Platform.INFURA]: 'bd887006-0d55-481a-a395-5ff9a0dc52c9',\n },\n [Env.UAT]: {\n [Platform.PORTFOLIO]: '8f2dd4ac-db07-4819-9ba5-1ee0ec1b56d1',\n [Platform.MOBILE]: 'c3cfdcd2-51d6-4fae-ad2c-ff238c8fef53',\n [Platform.EXTENSION]: 'a9de167c-c9a6-43d8-af39-d301fd44c485',\n [Platform.INFURA]: '01929890-7002-4c97-9913-8f6c09a6d674',\n },\n [Env.PRD]: {\n [Platform.PORTFOLIO]: '35e1cd62-49c5-4be8-8b6e-a5212f2d2cfb',\n [Platform.MOBILE]: '75fa62a3-9ca0-4b91-9fe5-76bec86b0257',\n [Platform.EXTENSION]: '1132f10a-b4e5-4390-a5f2-d9c6022db564',\n [Platform.INFURA]: '', // unset\n },\n };\n\n if (!clientIds[env]) {\n throw new Error(`invalid env ${env}: cannot determine oidc client id`);\n }\n\n if (!clientIds[env][platform]) {\n throw new Error(\n `invalid env ${env} and platform ${platform} combination: cannot determine oidc client id`,\n );\n }\n\n return clientIds[env][platform];\n}\n","function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\nexport type Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('hash must be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n","/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */\nimport { bytes as abytes, isBytes } from './_assert.js';\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u16 = (arr: TypedArray) =>\n new Uint16Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 2));\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// big-endian hardware is rare. Just in case someone still decides to run ciphers:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`string expected, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/**\n * @example bytesToUtf8(new Uint8Array([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n else if (isBytes(data)) data = data.slice();\n else throw new Error(`Uint8Array expected, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts: T2\n): T1 & T2 {\n if (opts == null || typeof opts !== 'object') throw new Error('options must be defined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n}\n\n// This will allow to re-use with composable things like packed & base encoders\n// Also, we probably can make tags composable\nexport type Cipher = {\n encrypt(plaintext: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array): Uint8Array;\n};\n\nexport type AsyncCipher = {\n encrypt(plaintext: Uint8Array): Promise<Uint8Array>;\n decrypt(ciphertext: Uint8Array): Promise<Uint8Array>;\n};\n\nexport type CipherWithOutput = Cipher & {\n encrypt(plaintext: Uint8Array, output?: Uint8Array): Uint8Array;\n decrypt(ciphertext: Uint8Array, output?: Uint8Array): Uint8Array;\n};\n\n// Params is outside return type, so it is accessible before calling constructor\n// If function support multiple nonceLength's, we return best one\nexport type CipherParams = { blockSize: number; nonceLength?: number; tagLength?: number };\nexport type CipherCons<T extends any[]> = (key: Uint8Array, ...args: T) => Cipher;\n/**\n * @__NO_SIDE_EFFECTS__\n */\nexport const wrapCipher = <C extends CipherCons<any>, P extends CipherParams>(\n params: P,\n c: C\n): C & P => {\n Object.assign(c, params);\n return c as C & P;\n};\n\nexport type XorStream = (\n key: Uint8Array,\n nonce: Uint8Array,\n data: Uint8Array,\n output?: Uint8Array,\n counter?: number\n) => Uint8Array;\n\n// Polyfill for Safari 14\nexport function setBigUint64(\n view: DataView,\n byteOffset: number,\n value: bigint,\n isLE: boolean\n): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\nexport function u64Lengths(ciphertext: Uint8Array, AAD?: Uint8Array) {\n const num = new Uint8Array(16);\n const view = createView(num);\n setBigUint64(view, 0, BigInt(AAD ? AAD.length : 0), true);\n setBigUint64(view, 8, BigInt(ciphertext.length), true);\n return num;\n}\n","import { createView, toBytes, Input, Hash, u32 } from './utils.js';\nimport { bytes as abytes, exists as aexists, output as aoutput } from './_assert.js';\n\n// GHash from AES-GCM and its little-endian \"mirror image\" Polyval from AES-SIV.\n// Implemented in terms of GHash with conversion function for keys\n// GCM GHASH from NIST SP800-38d, SIV from RFC 8452.\n// https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\n\n// GHASH modulo: x^128 + x^7 + x^2 + x + 1\n// POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1\n\nconst BLOCK_SIZE = 16;\n// TODO: rewrite\n// temporary padding buffer\nconst ZEROS16 = /* @__PURE__ */ new Uint8Array(16);\nconst ZEROS32 = u32(ZEROS16);\nconst POLY = 0xe1; // v = 2*v % POLY\n\n// v = 2*v % POLY\n// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x\n// We can multiply any number using montgomery ladder and this function (works as double, add is simple xor)\nconst mul2 = (s0: number, s1: number, s2: number, s3: number) => {\n const hiBit = s3 & 1;\n return {\n s3: (s2 << 31) | (s3 >>> 1),\n s2: (s1 << 31) | (s2 >>> 1),\n s1: (s0 << 31) | (s1 >>> 1),\n s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly\n };\n};\n\nconst swapLE = (n: number) =>\n (((n >>> 0) & 0xff) << 24) |\n (((n >>> 8) & 0xff) << 16) |\n (((n >>> 16) & 0xff) << 8) |\n ((n >>> 24) & 0xff) |\n 0;\n\n/**\n * `mulX_POLYVAL(ByteReverse(H))` from spec\n * @param k mutated in place\n */\nexport function _toGHASHKey(k: Uint8Array): Uint8Array {\n k.reverse();\n const hiBit = k[15] & 1;\n // k >>= 1\n let carry = 0;\n for (let i = 0; i < k.length; i++) {\n const t = k[i];\n k[i] = (t >>> 1) | carry;\n carry = (t & 1) << 7;\n }\n k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000;\n return k;\n}\n\ntype Value = { s0: number; s1: number; s2: number; s3: number };\n\nconst estimateWindow = (bytes: number) => {\n if (bytes > 64 * 1024) return 8;\n if (bytes > 1024) return 4;\n return 2;\n};\n\nclass GHASH implements Hash<GHASH> {\n readonly blockLen = BLOCK_SIZE;\n readonly outputLen = BLOCK_SIZE;\n protected s0 = 0;\n protected s1 = 0;\n protected s2 = 0;\n protected s3 = 0;\n protected finished = false;\n protected t: Value[];\n private W: number;\n private windowSize: number;\n // We select bits per window adaptively based on expectedLength\n constructor(key: Input, expectedLength?: number) {\n key = toBytes(key);\n abytes(key, 16);\n const kView = createView(key);\n let k0 = kView.getUint32(0, false);\n let k1 = kView.getUint32(4, false);\n let k2 = kView.getUint32(8, false);\n let k3 = kView.getUint32(12, false);\n // generate table of doubled keys (half of montgomery ladder)\n const doubles: Value[] = [];\n for (let i = 0; i < 128; i++) {\n doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });\n ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));\n }\n const W = estimateWindow(expectedLength || 1024);\n if (![1, 2, 4, 8].includes(W))\n throw new Error(`ghash: wrong window size=${W}, should be 2, 4 or 8`);\n this.W = W;\n const bits = 128; // always 128 bits;\n const windows = bits / W;\n const windowSize = (this.windowSize = 2 ** W);\n const items: Value[] = [];\n // Create precompute table for window of W bits\n for (let w = 0; w < windows; w++) {\n // truth table: 00, 01, 10, 11\n for (let byte = 0; byte < windowSize; byte++) {\n // prettier-ignore\n let s0 = 0, s1 = 0, s2 = 0, s3 = 0;\n for (let j = 0; j < W; j++) {\n const bit = (byte >>> (W - j - 1)) & 1;\n if (!bit) continue;\n const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];\n (s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3);\n }\n items.push({ s0, s1, s2, s3 });\n }\n }\n this.t = items;\n }\n protected _updateBlock(s0: number, s1: number, s2: number, s3: number) {\n (s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3);\n const { W, t, windowSize } = this;\n // prettier-ignore\n let o0 = 0, o1 = 0, o2 = 0, o3 = 0;\n const mask = (1 << W) - 1; // 2**W will kill performance.\n let w = 0;\n for (const num of [s0, s1, s2, s3]) {\n for (let bytePos = 0; bytePos < 4; bytePos++) {\n const byte = (num >>> (8 * bytePos)) & 0xff;\n for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {\n const bit = (byte >>> (W * bitPos)) & mask;\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];\n (o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3);\n w += 1;\n }\n }\n }\n this.s0 = o0;\n this.s1 = o1;\n this.s2 = o2;\n this.s3 = o3;\n }\n update(data: Input): this {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n const left = data.length % BLOCK_SIZE;\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(b32[i * 4 + 0], b32[i * 4 + 1], b32[i * 4 + 2], b32[i * 4 + 3]);\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(ZEROS32[0], ZEROS32[1], ZEROS32[2], ZEROS32[3]);\n ZEROS32.fill(0); // clean tmp buffer\n }\n return this;\n }\n destroy() {\n const { t } = this;\n // clean precompute table\n for (const elm of t) {\n (elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0);\n }\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out;\n }\n digest(): Uint8Array {\n const res = new Uint8Array(BLOCK_SIZE);\n this.digestInto(res);\n this.destroy();\n return res;\n }\n}\n\nclass Polyval extends GHASH {\n constructor(key: Input, expectedLength?: number) {\n key = toBytes(key);\n const ghKey = _toGHASHKey(key.slice());\n super(ghKey, expectedLength);\n ghKey.fill(0);\n }\n update(data: Input): this {\n data = toBytes(data);\n aexists(this);\n const b32 = u32(data);\n const left = data.length % BLOCK_SIZE;\n const blocks = Math.floor(data.length / BLOCK_SIZE);\n for (let i = 0; i < blocks; i++) {\n this._updateBlock(\n swapLE(b32[i * 4 + 3]),\n swapLE(b32[i * 4 + 2]),\n swapLE(b32[i * 4 + 1]),\n swapLE(b32[i * 4 + 0])\n );\n }\n if (left) {\n ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));\n this._updateBlock(\n swapLE(ZEROS32[3]),\n swapLE(ZEROS32[2]),\n swapLE(ZEROS32[1]),\n swapLE(ZEROS32[0])\n );\n ZEROS32.fill(0); // clean tmp buffer\n }\n return this;\n }\n digestInto(out: Uint8Array) {\n aexists(this);\n aoutput(out, this);\n this.finished = true;\n // tmp ugly hack\n const { s0, s1, s2, s3 } = this;\n const o32 = u32(out);\n o32[0] = s0;\n o32[1] = s1;\n o32[2] = s2;\n o32[3] = s3;\n return out.reverse();\n }\n}\n\nexport type CHash = ReturnType<typeof wrapConstructorWithKey>;\nfunction wrapConstructorWithKey<H extends Hash<H>>(\n hashCons: (key: Input, expectedLength?: number) => Hash<H>\n) {\n const hashC = (msg: Input, key: Input): Uint8Array =>\n hashCons(key, msg.length).update(toBytes(msg)).digest();\n const tmp = hashCons(new Uint8Array(16), 0);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (key: Input, expectedLength?: number) => hashCons(key, expectedLength);\n return hashC;\n}\n\nexport const ghash = wrapConstructorWithKey(\n (key, expectedLength) => new GHASH(key, expectedLength)\n);\nexport const polyval = wrapConstructorWithKey(\n (key, expectedLength) => new Polyval(key, expectedLength)\n);\n","// prettier-ignore\nimport {\n wrapCipher, Cipher, CipherWithOutput,\n createView, setBigUint64, equalBytes, u32, u8,\n} from './utils.js';\nimport { ghash, polyval } from './_polyval.js';\nimport { bytes as abytes } from './_assert.js';\n\n/*\nAES (Advanced Encryption Standard) aka Rijndael block cipher.\n\nData is split into 128-bit blocks. Encrypted in 10/12/14 rounds (128/192/256 bits). In every round:\n1. **S-box**, table substitution\n2. **Shift rows**, cyclic shift left of all rows of data array\n3. **Mix columns**, multiplying every column by fixed polynomial\n4. **Add round key**, round_key xor i-th column of array\n\nResources:\n- FIPS-197 https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf\n- Original proposal: https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf\n*/\n\nconst BLOCK_SIZE = 16;\nconst BLOCK_SIZE32 = 4;\nconst EMPTY_BLOCK = new Uint8Array(BLOCK_SIZE);\nconst POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8\n\n// TODO: remove multiplication, binary ops only\nfunction mul2(n: number) {\n return (n << 1) ^ (POLY & -(n >> 7));\n}\n\nfunction mul(a: number, b: number) {\n let res = 0;\n for (; b > 0; b >>= 1) {\n // Montgomery ladder\n res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time).\n a = mul2(a); // a = 2*a\n }\n return res;\n}\n\n// AES S-box is generated using finite field inversion,\n// an affine transform, and xor of a constant 0x63.\nconst sbox = /* @__PURE__ */ (() => {\n let t = new Uint8Array(256);\n for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x;\n const box = new Uint8Array(256);\n box[0] = 0x63; // first elm\n for (let i = 0; i < 255; i++) {\n let x = t[255 - i];\n x |= x << 8;\n box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff;\n }\n return box;\n})();\n\n// Inverted S-box\nconst invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));\n\n// Rotate u32 by 8\nconst rotr32_8 = (n: number) => (n << 24) | (n >>> 8);\nconst rotl32_8 = (n: number) => (n << 8) | (n >>> 24);\n\n// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes:\n// - LE instead of BE\n// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23;\n// so index is u16, instead of u8. This speeds up things, unexpectedly\nfunction genTtable(sbox: Uint8Array, fn: (n: number) => number) {\n if (sbox.length !== 256) throw new Error('Wrong sbox length');\n const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j]));\n const T1 = T0.map(rotl32_8);\n const T2 = T1.map(rotl32_8);\n const T3 = T2.map(rotl32_8);\n const T01 = new Uint32Array(256 * 256);\n const T23 = new Uint32Array(256 * 256);\n const sbox2 = new Uint16Array(256 * 256);\n for (let i = 0; i < 256; i++) {\n for (let j = 0; j < 256; j++) {\n const idx = i * 256 + j;\n T01[idx] = T0[i] ^ T1[j];\n T23[idx] = T2[i] ^ T3[j];\n sbox2[idx] = (sbox[i] << 8) | sbox[j];\n }\n }\n return { sbox, sbox2, T0, T1, T2, T3, T01, T23 };\n}\n\nconst tableEncoding = /* @__PURE__ */ genTtable(\n sbox,\n (s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)\n);\nconst tableDecoding = /* @__PURE__ */ genTtable(\n invSbox,\n (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)\n);\n\nconst xPowers = /* @__PURE__ */ (() => {\n const p = new Uint8Array(16);\n for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x;\n return p;\n})();\n\nexport function expandKeyLE(key: Uint8Array): Uint32Array {\n abytes(key);\n const len = key.length;\n if (![16, 24, 32].includes(len))\n throw new Error(`aes: wrong key size: should be 16, 24 or 32, got: ${len}`);\n const { sbox2 } = tableEncoding;\n const k32 = u32(key);\n const Nk = k32.length;\n const subByte = (n: number) => applySbox(sbox2, n, n, n, n);\n const xk = new Uint32Array(len + 28); // expanded key\n xk.set(k32);\n // 4.3.1 Key expansion\n for (let i = Nk; i < xk.length; i++) {\n let t = xk[i - 1];\n if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];\n else if (Nk > 6 && i % Nk === 4) t = subByte(t);\n xk[i] = xk[i - Nk] ^ t;\n }\n return xk;\n}\n\nexport function expandKeyDecLE(key: Uint8Array): Uint32Array {\n const encKey = expandKeyLE(key);\n const xk = encKey.slice();\n const Nk = encKey.length;\n const { sbox2 } = tableEncoding;\n const { T0, T1, T2, T3 } = tableDecoding;\n // Inverse key by chunks of 4 (rounds)\n for (let i = 0; i < Nk; i += 4) {\n for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j];\n }\n encKey.fill(0);\n // apply InvMixColumn except first & last round\n for (let i = 4; i < Nk - 4; i++) {\n const x = xk[i];\n const w = applySbox(sbox2, x, x, x, x);\n xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24];\n }\n return xk;\n}\n\n// Apply tables\nfunction apply0123(\n T01: Uint32Array,\n T23: Uint32Array,\n s0: number,\n s1: number,\n s2: number,\n s3: number\n) {\n return (\n T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^\n T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]\n );\n}\n\nfunction applySbox(sbox2: Uint16Array, s0: number, s1: number, s2: number, s3: number) {\n return (\n sbox2[(s0 & 0xff) | (s1 & 0xff00)] |\n (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)\n );\n}\n\nfunction encrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) {\n const { sbox2, T01, T23 } = tableEncoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // last round (without mixcolumns, so using SBOX2 table)\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\nfunction decrypt(xk: Uint32Array, s0: number, s1: number, s2: number, s3: number) {\n const { sbox2, T01, T23 } = tableDecoding;\n let k = 0;\n (s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++]);\n const rounds = xk.length / 4 - 2;\n for (let i = 0; i < rounds; i++) {\n const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);\n const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);\n const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);\n const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);\n (s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3);\n }\n // Last round\n const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);\n const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);\n const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);\n const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);\n return { s0: t0, s1: t1, s2: t2, s3: t3 };\n}\n\nfunction getDst(len: number, dst?: Uint8Array) {\n if (!dst) return new Uint8Array(len);\n abytes(dst);\n if (dst.length < len)\n throw new Error(`aes: wrong destination length, expected at least ${len}, got: ${dst.length}`);\n return dst;\n}\n\n// TODO: investigate merging with ctr32\nfunction ctrCounter(xk: Uint32Array, nonce: Uint8Array, src: Uint8Array, dst?: Uint8Array) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const ctr = nonce;\n const c32 = u32(ctr);\n // Fill block (empty, ctr=0)\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n const src32 = u32(src);\n const dst32 = u32(dst);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n // Full 128 bit counter with wrap around\n let carry = 1;\n for (let i = ctr.length - 1; i >= 0; i--) {\n carry = (carry + (ctr[i] & 0xff)) | 0;\n ctr[i] = carry & 0xff;\n carry >>>= 8;\n }\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than block)\n // It's possible to handle > u32 fast, but is it worth it?\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n }\n return dst;\n}\n\n// AES CTR with overflowing 32 bit counter\n// It's possible to do 32le significantly simpler (and probably faster) by using u32.\n// But, we need both, and perf bottleneck is in ghash anyway.\nfunction ctr32(\n xk: Uint32Array,\n isLE: boolean,\n nonce: Uint8Array,\n src: Uint8Array,\n dst?: Uint8Array\n) {\n abytes(nonce, BLOCK_SIZE);\n abytes(src);\n dst = getDst(src.length, dst);\n const ctr = nonce; // write new value to nonce, so it can be re-used\n const c32 = u32(ctr);\n const view = createView(ctr);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const ctrPos = isLE ? 0 : 12;\n const srcLen = src.length;\n // Fill block (empty, ctr=0)\n let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value\n let { s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]);\n // process blocks\n for (let i = 0; i + 4 <= src32.length; i += 4) {\n dst32[i + 0] = src32[i + 0] ^ s0;\n dst32[i + 1] = src32[i + 1] ^ s1;\n dst32[i + 2] = src32[i + 2] ^ s2;\n dst32[i + 3] = src32[i + 3] ^ s3;\n ctrNum = (ctrNum + 1) >>> 0; // u32 wrap\n view.setUint32(ctrPos, ctrNum, isLE);\n ({ s0, s1, s2, s3 } = encrypt(xk, c32[0], c32[1], c32[2], c32[3]));\n }\n // leftovers (less than a block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n const b32 = new Uint32Array([s0, s1, s2, s3]);\n const buf = u8(b32);\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n }\n return dst;\n}\n\n/**\n * CTR: counter mode. Creates stream cipher.\n * Requires good IV. Parallelizable. OK, but no MAC.\n */\nexport const ctr = wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function ctr(key: Uint8Array, nonce: Uint8Array): CipherWithOutput {\n abytes(key);\n abytes(nonce, BLOCK_SIZE);\n function processCtr(buf: Uint8Array, dst?: Uint8Array) {\n const xk = expandKeyLE(key);\n const n = nonce.slice();\n const out = ctrCounter(xk, n, buf, dst);\n xk.fill(0);\n n.fill(0);\n return out;\n }\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCtr(plaintext, dst),\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCtr(ciphertext, dst),\n };\n }\n);\n\nfunction validateBlockDecrypt(data: Uint8Array) {\n abytes(data);\n if (data.length % BLOCK_SIZE !== 0) {\n throw new Error(\n `aes/(cbc-ecb).decrypt ciphertext should consist of blocks with size ${BLOCK_SIZE}`\n );\n }\n}\n\nfunction validateBlockEncrypt(plaintext: Uint8Array, pcks5: boolean, dst?: Uint8Array) {\n let outLen = plaintext.length;\n const remaining = outLen % BLOCK_SIZE;\n if (!pcks5 && remaining !== 0)\n throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding');\n const b = u32(plaintext);\n if (pcks5) {\n let left = BLOCK_SIZE - remaining;\n if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block\n outLen = outLen + left;\n }\n const out = getDst(outLen, dst);\n const o = u32(out);\n return { b, o, out };\n}\n\nfunction validatePCKS(data: Uint8Array, pcks5: boolean) {\n if (!pcks5) return data;\n const len = data.length;\n if (!len) throw new Error(`aes/pcks5: empty ciphertext not allowed`);\n const lastByte = data[len - 1];\n if (lastByte <= 0 || lastByte > 16) throw new Error(`aes/pcks5: wrong padding byte: ${lastByte}`);\n const out = data.subarray(0, -lastByte);\n for (let i = 0; i < lastByte; i++)\n if (data[len - i - 1] !== lastByte) throw new Error(`aes/pcks5: wrong padding`);\n return out;\n}\n\nfunction padPCKS(left: Uint8Array) {\n const tmp = new Uint8Array(16);\n const tmp32 = u32(tmp);\n tmp.set(left);\n const paddingByte = BLOCK_SIZE - left.length;\n for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte;\n return tmp32;\n}\n\nexport type BlockOpts = { disablePadding?: boolean };\n\n/**\n * ECB: Electronic CodeBook. Simple deterministic replacement.\n * Dangerous: always map x to y. See [AES Penguin](https://words.filippo.io/the-ecb-penguin/).\n */\nexport const ecb = wrapCipher(\n { blockSize: 16 },\n function ecb(key: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n abytes(key);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => {\n abytes(plaintext);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const xk = expandKeyLE(key);\n let i = 0;\n for (; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return _out;\n },\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const out = getDst(ciphertext.length, dst);\n const b = u32(ciphertext);\n const o = u32(out);\n for (let i = 0; i + 4 <= b.length; ) {\n const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return validatePCKS(out, pcks5);\n },\n };\n }\n);\n\n/**\n * CBC: Cipher-Block-Chaining. Key is previous round’s block.\n * Fragile: needs proper padding. Unauthenticated: needs MAC.\n */\nexport const cbc = wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function cbc(key: Uint8Array, iv: Uint8Array, opts: BlockOpts = {}): CipherWithOutput {\n abytes(key);\n abytes(iv, 16);\n const pcks5 = !opts.disablePadding;\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => {\n const xk = expandKeyLE(key);\n const { b, o, out: _out } = validateBlockEncrypt(plaintext, pcks5, dst);\n const n32 = u32(iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n let i = 0;\n for (; i + 4 <= b.length; ) {\n (s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n if (pcks5) {\n const tmp32 = padPCKS(plaintext.subarray(i * 4));\n (s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3]);\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n (o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3);\n }\n xk.fill(0);\n return _out;\n },\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => {\n validateBlockDecrypt(ciphertext);\n const xk = expandKeyDecLE(key);\n const n32 = u32(iv);\n const out = getDst(ciphertext.length, dst);\n const b = u32(ciphertext);\n const o = u32(out);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= b.length; ) {\n // prettier-ignore\n const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3;\n (s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3]);\n const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3);\n (o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3);\n }\n xk.fill(0);\n return validatePCKS(out, pcks5);\n },\n };\n }\n);\n\n/**\n * CFB: Cipher Feedback Mode. The input for the block cipher is the previous cipher output.\n * Unauthenticated: needs MAC.\n */\nexport const cfb = wrapCipher(\n { blockSize: 16, nonceLength: 16 },\n function cfb(key: Uint8Array, iv: Uint8Array): CipherWithOutput {\n abytes(key);\n abytes(iv, 16);\n function processCfb(src: Uint8Array, isEncrypt: boolean, dst?: Uint8Array) {\n const xk = expandKeyLE(key);\n const srcLen = src.length;\n dst = getDst(srcLen, dst);\n const src32 = u32(src);\n const dst32 = u32(dst);\n const next32 = isEncrypt ? dst32 : src32;\n const n32 = u32(iv);\n // prettier-ignore\n let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3];\n for (let i = 0; i + 4 <= src32.length; ) {\n const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3);\n dst32[i + 0] = src32[i + 0] ^ e0;\n dst32[i + 1] = src32[i + 1] ^ e1;\n dst32[i + 2] = src32[i + 2] ^ e2;\n dst32[i + 3] = src32[i + 3] ^ e3;\n (s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++]);\n }\n // leftovers (less than block)\n const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32);\n if (start < srcLen) {\n ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3));\n const buf = u8(new Uint32Array([s0, s1, s2, s3]));\n for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos];\n buf.fill(0);\n }\n xk.fill(0);\n return dst;\n }\n return {\n encrypt: (plaintext: Uint8Array, dst?: Uint8Array) => processCfb(plaintext, true, dst),\n decrypt: (ciphertext: Uint8Array, dst?: Uint8Array) => processCfb(ciphertext, false, dst),\n };\n }\n);\n\n// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen\nfunction computeTag(\n fn: typeof ghash,\n isLE: boolean,\n key: Uint8Array,\n data: Uint8Array,\n AAD?: Uint8Array\n) {\n const h = fn.create(key, data.length + (AAD?.length || 0));\n if (AAD) h.update(AAD);\n h.update(data);\n const num = new Uint8Array(16);\n const view = createView(num);\n if (AAD) setBigUint64(view, 0, BigInt(AAD.length * 8), isLE);\n setBigUint64(view, 8, BigInt(data.length * 8), isLE);\n h.update(num);\n return h.digest();\n}\n\n/**\n * GCM: Galois/Counter Mode.\n * Good, modern version of CTR, parallel, with MAC.\n * Be careful: MACs can be forged.\n */\nexport const gcm = wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16 },\n function gcm(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n abytes(nonce);\n // Nonce can be pretty much anything (even 1 byte). But smaller nonces less secure.\n if (nonce.length === 0) throw new Error('aes/gcm: empty nonce');\n const tagLength = 16;\n function _computeTag(authKey: Uint8Array, tagMask: Uint8Array, data: Uint8Array) {\n const tag = computeTag(ghash, false, authKey, data, AAD);\n for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i];\n return tag;\n }\n function deriveKeys() {\n const xk = expandKeyLE(key);\n const authKey = EMPTY_BLOCK.slice();\n const counter = EMPTY_BLOCK.slice();\n ctr32(xk, false, counter, counter, authKey);\n if (nonce.length === 12) {\n counter.set(nonce);\n } else {\n // Spec (NIST 800-38d) supports variable size nonce.\n // Not supported for now, but can be useful.\n const nonceLen = EMPTY_BLOCK.slice();\n const view = createView(nonceLen);\n setBigUint64(view, 8, BigInt(nonce.length * 8), false);\n // ghash(nonce || u64be(0) || u64be(nonceLen*8))\n ghash.create(authKey).update(nonce).update(nonceLen).digestInto(counter);\n }\n const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);\n return { xk, authKey, counter, tagMask };\n }\n return {\n encrypt: (plaintext: Uint8Array) => {\n abytes(plaintext);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const out = new Uint8Array(plaintext.length + tagLength);\n ctr32(xk, false, counter, plaintext, out);\n const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));\n out.set(tag, plaintext.length);\n xk.fill(0);\n return out;\n },\n decrypt: (ciphertext: Uint8Array) => {\n abytes(ciphertext);\n if (ciphertext.length < tagLength)\n throw new Error(`aes/gcm: ciphertext less than tagLen (${tagLength})`);\n const { xk, authKey, counter, tagMask } = deriveKeys();\n const data = ciphertext.subarray(0, -tagLength);\n const passedTag = ciphertext.subarray(-tagLength);\n const tag = _computeTag(authKey, tagMask, data);\n if (!equalBytes(tag, passedTag)) throw new Error('aes/gcm: invalid ghash tag');\n const out = ctr32(xk, false, counter, data);\n authKey.fill(0);\n tagMask.fill(0);\n xk.fill(0);\n return out;\n },\n };\n }\n);\n\nconst limit = (name: string, min: number, max: number) => (value: number) => {\n if (!Number.isSafeInteger(value) || min > value || value > max)\n throw new Error(`${name}: invalid value=${value}, must be [${min}..${max}]`);\n};\n\n/**\n * AES-GCM-SIV: classic AES-GCM with nonce-misuse resistance.\n * Guarantees that, when a nonce is repeated, the only security loss is that identical\n * plaintexts will produce identical ciphertexts.\n * RFC 8452, https://datatracker.ietf.org/doc/html/rfc8452\n */\nexport const siv = wrapCipher(\n { blockSize: 16, nonceLength: 12, tagLength: 16 },\n function siv(key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): Cipher {\n const tagLength = 16;\n // From RFC 8452: Section 6\n const AAD_LIMIT = limit('AAD', 0, 2 ** 36);\n const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36);\n const NONCE_LIMIT = limit('nonce', 12, 12);\n const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16);\n abytes(nonce);\n NONCE_LIMIT(nonce.length);\n if (AAD) {\n abytes(AAD);\n AAD_LIMIT(AAD.length);\n }\n function deriveKeys() {\n const len = key.length;\n if (len !== 16 && len !== 24 && len !== 32)\n throw new Error(`key length must be 16, 24 or 32 bytes, got: ${len} bytes`);\n const xk = expandKeyLE(key);\n const encKey = new Uint8Array(len);\n const authKey = new Uint8Array(16);\n const n32 = u32(nonce);\n // prettier-ignore\n let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2];\n let counter = 0;\n for (const derivedKey of [authKey, encKey].map(u32)) {\n const d32 = u32(derivedKey);\n for (let i = 0; i < d32.length; i += 2) {\n // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ...\n const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3);\n d32[i + 0] = o0;\n d32[i + 1] = o1;\n s0 = ++counter; // increment counter inside state\n }\n }\n xk.fill(0);\n return { authKey, encKey: expandKeyLE(encKey) };\n }\n function _computeTag(encKey: Uint32Array, authKey: Uint8Array, data: Uint8Array) {\n const tag = computeTag(polyval, true, authKey, data, AAD);\n // Compute the expected tag by XORing S_s and the nonce, clearing the\n // most significant bit of the last byte and encrypting with the\n // message-encryption key.\n for (let i = 0; i < 12; i++) tag[i] ^= nonce[i];\n tag[15] &= 0x7f; // Clear the highest bit\n // encrypt tag as block\n const t32 = u32(tag);\n // prettier-ignore\n let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3];\n ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3));\n (t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3);\n return tag;\n }\n // actual decrypt/encrypt of message.\n function processSiv(encKey: Uint32Array, tag: Uint8Array, input: Uint8Array) {\n let block = tag.slice();\n block[15] |= 0x80; // Force highest bit\n return ctr32(encKey, true, block, input);\n }\n return {\n encrypt: (plaintext: Uint8Array) => {\n abytes(plaintext);\n PLAIN_LIMIT(plaintext.length);\n const { encKey, authKey } = deriveKeys();\n const tag = _computeTag(encKey, authKey, plaintext);\n const out = new Uint8Array(plaintext.length + tagLength);\n out.set(tag, plaintext.length);\n out.set(processSiv(encKey, tag, plaintext));\n encKey.fill(0);\n authKey.fill(0);\n return out;\n },\n decrypt: (ciphertext: Uint8Array) => {\n abytes(ciphertext);\n CIPHER_LIMIT(ciphertext.length);\n const tag = ciphertext.subarray(-tagLength);\n const { encKey, authKey } = deriveKeys();\n const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength));\n const expectedTag = _computeTag(encKey, authKey, plaintext);\n encKey.fill(0);\n authKey.fill(0);\n if (!equalBytes(tag, expectedTag)) throw new Error('invalid polyval tag');\n return plaintext;\n },\n };\n }\n);\n\nfunction isBytes32(a: unknown): a is Uint8Array {\n return (\n a != null &&\n typeof a === 'object' &&\n (a instanceof Uint32Array || a.constructor.name === 'Uint32Array')\n );\n}\n\nfunction encryptBlock(xk: Uint32Array, block: Uint8Array) {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\nfunction decryptBlock(xk: Uint32Array, block: Uint8Array) {\n abytes(block, 16);\n if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE');\n const b32 = u32(block);\n let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]);\n (b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3);\n return block;\n}\n\n// Highly unsafe private functions for implementing new modes or ciphers based on AES\n// Can change at any time, no API guarantees\nexport const unsafe = {\n expandKeyLE,\n expandKeyDecLE,\n encrypt,\n decrypt,\n encryptBlock,\n decryptBlock,\n ctrCounter,\n ctr32,\n};\n","// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record<string, any> | undefined;\nconst cr = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (cr && typeof cr.getRandomValues === 'function')\n return cr.getRandomValues(new Uint8Array(bytesLength));\n throw new Error('crypto.getRandomValues must be defined');\n}\n\nexport function getWebcryptoSubtle() {\n if (cr && typeof cr.subtle === 'object' && cr.subtle != null) return cr.subtle;\n throw new Error('crypto.subtle must be defined');\n}\n","// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.js on#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\n//\n// Use full path so that Node.js can rewrite it to `cryptoNode.js`.\nimport { randomBytes, getWebcryptoSubtle } from '@noble/ciphers/crypto';\nimport { AsyncCipher, Cipher, concatBytes } from './utils.js';\nimport { number, bytes as abytes } from './_assert.js';\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport { randomBytes, getWebcryptoSubtle };\n\ntype RemoveNonceInner<T extends any[], Ret> = ((...args: T) => Ret) extends (\n arg0: any,\n arg1: any,\n ...rest: infer R\n) => any\n ? (key: Uint8Array, ...args: R) => Ret\n : never;\n\ntype RemoveNonce<T extends (...args: any) => any> = RemoveNonceInner<Parameters<T>, ReturnType<T>>;\ntype CipherWithNonce = ((key: Uint8Array, nonce: Uint8Array, ...args: any[]) => Cipher) & {\n nonceLength: number;\n};\n\n// Uses CSPRG for nonce, nonce injected in ciphertext\nexport function managedNonce<T extends CipherWithNonce>(fn: T): RemoveNonce<T> {\n number(fn.nonceLength);\n return ((key: Uint8Array, ...args: any[]): any => ({\n encrypt: (plaintext: Uint8Array, ...argsEnc: any[]) => {\n const { nonceLength } = fn;\n const nonce = randomBytes(nonceLength);\n const ciphertext = (fn(key, nonce, ...args).encrypt as any)(plaintext, ...argsEnc);\n const out = concatBytes(nonce, ciphertext);\n ciphertext.fill(0);\n return out;\n },\n decrypt: (ciphertext: Uint8Array, ...argsDec: any[]) => {\n const { nonceLength } = fn;\n const nonce = ciphertext.subarray(0, nonceLength);\n const data = ciphertext.subarray(nonceLength);\n return (fn(key, nonce, ...args).decrypt as any)(data, ...argsDec);\n },\n })) as RemoveNonce<T>;\n}\n\n// Overridable\nexport const utils = {\n async encrypt(key: Uint8Array, keyParams: any, cryptParams: any, plaintext: Uint8Array) {\n const cr = getWebcryptoSubtle();\n const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']);\n const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext);\n return new Uint8Array(ciphertext);\n },\n async decrypt(key: Uint8Array, keyParams: any, cryptParams: any, ciphertext: Uint8Array) {\n const cr = getWebcryptoSubtle();\n const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']);\n const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext);\n return new Uint8Array(plaintext);\n },\n};\n\nconst mode = {\n CBC: 'AES-CBC',\n CTR: 'AES-CTR',\n GCM: 'AES-GCM',\n} as const;\ntype BlockMode = (typeof mode)[keyof typeof mode];\n\nfunction getCryptParams(algo: BlockMode, nonce: Uint8Array, AAD?: Uint8Array) {\n if (algo === mode.CBC) return { name: mode.CBC, iv: nonce };\n if (algo === mode.CTR) return { name: mode.CTR, counter: nonce, length: 64 };\n if (algo === mode.GCM) return { name: mode.GCM, iv: nonce, additionalData: AAD };\n throw new Error('unknown aes block mode');\n}\n\nfunction generate(algo: BlockMode) {\n return (key: Uint8Array, nonce: Uint8Array, AAD?: Uint8Array): AsyncCipher => {\n abytes(key);\n abytes(nonce);\n const keyParams = { name: algo, length: key.length * 8 };\n const cryptParams = getCryptParams(algo, nonce, AAD);\n return {\n // keyLength,\n encrypt(plaintext: Uint8Array) {\n abytes(plaintext);\n return utils.encrypt(key, keyParams, cryptParams, plaintext);\n },\n decrypt(ciphertext: Uint8Array) {\n abytes(ciphertext);\n return utils.decrypt(key, keyParams, cryptParams, ciphertext);\n },\n };\n };\n}\n\nexport const cbc = generate(mode.CBC);\nexport const ctr = generate(mode.CTR);\nexport const gcm = generate(mode.GCM);\n\n// // Type tests\n// import { siv, gcm, ctr, ecb, cbc } from '../aes.js';\n// import { xsalsa20poly1305 } from '../salsa.js';\n// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.js';\n\n// const wsiv = managedNonce(siv);\n// const wgcm = managedNonce(gcm);\n// const wctr = managedNonce(ctr);\n// const wcbc = managedNonce(cbc);\n// const wsalsapoly = managedNonce(xsalsa20poly1305);\n// const wchacha = managedNonce(chacha20poly1305);\n// const wxchacha = managedNonce(xchacha20poly1305);\n\n// // should fail\n// const wcbc2 = managedNonce(managedNonce(cbc));\n// const wecb = managedNonce(ecb);\n","function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\n// copied from utils\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType<typeof wrapConstructor>;\n\nexport function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n","import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { hmac } from './hmac.js';\nimport { Hash, CHash, Input, createView, toBytes, checkOpts, asyncLoop } from './utils.js';\n\n// PBKDF (RFC 2898)\nexport type Pbkdf2Opt = {\n c: number; // Iterations\n dkLen?: number; // Desired key length in bytes (Intended output length in octets of the derived key\n asyncTick?: number; // Maximum time in ms for which async function can block execution\n};\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash: CHash, _password: Input, _salt: Input, _opts: Pbkdf2Opt) {\n assertHash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n assertNumber(c);\n assertNumber(dkLen);\n assertNumber(asyncTick);\n if (c < 1) throw new Error('PBKDF2: iterations (c) should be >= 1');\n const password = toBytes(_password);\n const salt = toBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output<T extends Hash<T>>(\n PRF: Hash<T>,\n PRFSalt: Hash<T>,\n DK: Uint8Array,\n prfW: Hash<T>,\n u: Uint8Array\n) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n u.fill(0);\n return DK;\n}\n\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n */\nexport function pbkdf2(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\nexport async function pbkdf2Async(hash: CHash, password: Input, salt: Input, opts: Pbkdf2Opt) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n","import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Choice: a ? b : c\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n","import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n","export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnSignature = 'onSignature',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n OnHomePage = 'onHomePage',\n OnUserInput = 'onUserInput',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n","import type { HandleSnapRequest } from '@metamask/snaps-controllers';\nimport type { SnapId } from '@metamask/snaps-sdk';\nimport { HandlerType } from '@metamask/snaps-utils';\n\ntype SnapRPCRequest = Parameters<HandleSnapRequest['handler']>[0];\n\nconst snapId = 'npm:@metamask/message-signing-snap' as SnapId;\n\n/**\n * Constructs Request to Message Signing Snap to get Public Key\n *\n * @returns Snap Public Key Request\n */\nexport function createSnapPublicKeyRequest(): SnapRPCRequest {\n return {\n snapId,\n origin: '',\n handler: HandlerType.OnRpcRequest,\n request: {\n method: 'getPublicKey',\n },\n };\n}\n\n/**\n * Constructs Request to get Message Signing Snap to sign a message.\n *\n * @param message - message to sign\n * @returns Snap Sign Message Request\n */\nexport function createSnapSignMessageRequest(\n message: `metamask:${string}`,\n): SnapRPCRequest {\n return {\n snapId,\n origin: '',\n handler: HandlerType.OnRpcRequest,\n request: {\n method: 'signMessage',\n params: { message },\n },\n };\n}\n","import Controller from './UserStorageController';\n\nexport { Controller };\nexport * from './UserStorageController';\nexport * from './encryption';\nexport * as Mocks from './__fixtures__';\n","import type {\n RestrictedControllerMessenger,\n StateMetadata,\n} from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport type { HandleSnapRequest } from '@metamask/snaps-controllers';\n\nimport { createSnapSignMessageRequest } from '../authentication/auth-snap-requests';\nimport type {\n AuthenticationControllerGetBearerToken,\n AuthenticationControllerGetSessionProfile,\n AuthenticationControllerIsSignedIn,\n AuthenticationControllerPerformSignIn,\n AuthenticationControllerPerformSignOut,\n} from '../authentication/AuthenticationController';\nimport { createSHA256Hash } from './encryption';\nimport type { UserStorageEntryKeys } from './schema';\nimport { getUserStorage, upsertUserStorage } from './services';\n\n// TODO: fix external dependencies\nexport declare type NotificationServicesControllerDisableNotificationServices =\n {\n type: `NotificationServicesController:disableNotificationServices`;\n handler: () => Promise<void>;\n };\n\nexport declare type NotificationServicesControllerSelectIsNotificationServicesEnabled =\n {\n type: `NotificationServicesController:selectIsNotificationServicesEnabled`;\n handler: () => boolean;\n };\n\nconst controllerName = 'UserStorageController';\n\n// State\nexport type UserStorageControllerState = {\n /**\n * Condition used by UI and to determine if we can use some of the User Storage methods.\n */\n isProfileSyncingEnabled: boolean;\n /**\n * Loading state for the profile syncing update\n */\n isProfileSyncingUpdateLoading: boolean;\n};\n\nconst defaultState: UserStorageControllerState = {\n isProfileSyncingEnabled: true,\n isProfileSyncingUpdateLoading: false,\n};\n\nconst metadata: StateMetadata<UserStorageControllerState> = {\n isProfileSyncingEnabled: {\n persist: true,\n anonymous: true,\n },\n isProfileSyncingUpdateLoading: {\n persist: false,\n anonymous: false,\n },\n};\n\n// Messenger Actions\ntype CreateActionsObj<Controller extends keyof UserStorageController> = {\n [K in Controller]: {\n type: `${typeof controllerName}:${K}`;\n handler: UserStorageController[K];\n };\n};\ntype ActionsObj = CreateActionsObj<\n | 'performGetStorage'\n | 'performSetStorage'\n | 'getStorageKey'\n | 'enableProfileSyncing'\n | 'disableProfileSyncing'\n>;\nexport type Actions = ActionsObj[keyof ActionsObj];\nexport type UserStorageControllerPerformGetStorage =\n ActionsObj['performGetStorage'];\nexport type UserStorageControllerPerformSetStorage =\n ActionsObj['performSetStorage'];\nexport type UserStorageControllerGetStorageKey = ActionsObj['getStorageKey'];\nexport type UserStorageControllerEnableProfileSyncing =\n ActionsObj['enableProfileSyncing'];\nexport type UserStorageControllerDisableProfileSyncing =\n ActionsObj['disableProfileSyncing'];\n\n// Allowed Actions\nexport type AllowedActions =\n // Snap Requests\n | HandleSnapRequest\n // Auth Requests\n | AuthenticationControllerGetBearerToken\n | AuthenticationControllerGetSessionProfile\n | AuthenticationControllerPerformSignIn\n | AuthenticationControllerIsSignedIn\n | AuthenticationControllerPerformSignOut\n // Metamask Notifications\n | NotificationServicesControllerDisableNotificationServices\n | NotificationServicesControllerSelectIsNotificationServicesEnabled;\n\n// Messenger\nexport type UserStorageControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n Actions | AllowedActions,\n never,\n AllowedActions['type'],\n never\n>;\n\n/**\n * Reusable controller that allows any team to store synchronized data for a given user.\n * These can be settings shared cross MetaMask clients, or data we want to persist when uninstalling/reinstalling.\n *\n * NOTE:\n * - data stored on UserStorage is FULLY encrypted, with the only keys stored/managed on the client.\n * - No one can access this data unless they are have the SRP and are able to run the signing snap.\n */\nexport default class UserStorageController extends BaseController<\n typeof controllerName,\n UserStorageControllerState,\n UserStorageControllerMessenger\n> {\n #auth = {\n getBearerToken: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:getBearerToken',\n );\n },\n getProfileId: async () => {\n const sessionProfile = await this.messagingSystem.call(\n 'AuthenticationController:getSessionProfile',\n );\n return sessionProfile?.profileId;\n },\n isAuthEnabled: () => {\n return this.messagingSystem.call('AuthenticationController:isSignedIn');\n },\n signIn: async () => {\n return await this.messagingSystem.call(\n 'AuthenticationController:performSignIn',\n );\n },\n signOut: async () => {\n return this.messagingSystem.call(\n 'AuthenticationController:performSignOut',\n );\n },\n };\n\n #notificationServices = {\n disableNotificationServices: async () => {\n return await this.messagingSystem.call(\n 'NotificationServicesController:disableNotificationServices',\n );\n },\n selectIsNotificationServicesEnabled: async () => {\n return this.messagingSystem.call(\n 'NotificationServicesController:selectIsNotificationServicesEnabled',\n );\n },\n };\n\n getMetaMetricsState: () => boolean;\n\n constructor(params: {\n messenger: UserStorageControllerMessenger;\n state?: UserStorageControllerState;\n getMetaMetricsState: () => boolean;\n }) {\n super({\n messenger: params.messenger,\n metadata,\n name: controllerName,\n state: { ...defaultState, ...params.state },\n });\n\n this.getMetaMetricsState = params.getMetaMetricsState;\n this.#registerMessageHandlers();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system\n * actions.\n */\n #registerMessageHandlers(): void {\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performGetStorage',\n this.performGetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:performSetStorage',\n this.performSetStorage.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:getStorageKey',\n this.getStorageKey.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:enableProfileSyncing',\n this.enableProfileSyncing.bind(this),\n );\n\n this.messagingSystem.registerActionHandler(\n 'UserStorageController:disableProfileSyncing',\n this.disableProfileSyncing.bind(this),\n );\n }\n\n public async enableProfileSyncing(): Promise<void> {\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const authEnabled = this.#auth.isAuthEnabled();\n if (!authEnabled) {\n await this.#auth.signIn();\n }\n\n this.update((state) => {\n state.isProfileSyncingEnabled = true;\n });\n\n this.#setIsProfileSyncingUpdateLoading(false);\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to enable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n public async setIsProfileSyncingEnabled(\n isProfileSyncingEnabled: boolean,\n ): Promise<void> {\n this.update((state) => {\n state.isProfileSyncingEnabled = isProfileSyncingEnabled;\n });\n }\n\n public async disableProfileSyncing(): Promise<void> {\n const isAlreadyDisabled = !this.state.isProfileSyncingEnabled;\n if (isAlreadyDisabled) {\n return;\n }\n\n try {\n this.#setIsProfileSyncingUpdateLoading(true);\n\n const isNotificationServicesEnabled =\n await this.#notificationServices.selectIsNotificationServicesEnabled();\n\n if (isNotificationServicesEnabled) {\n await this.#notificationServices.disableNotificationServices();\n }\n\n const isMetaMetricsParticipation = this.getMetaMetricsState();\n\n if (!isMetaMetricsParticipation) {\n this.messagingSystem.call('AuthenticationController:performSignOut');\n }\n\n this.#setIsProfileSyncingUpdateLoading(false);\n\n this.update((state) => {\n state.isProfileSyncingEnabled = false;\n });\n } catch (e) {\n this.#setIsProfileSyncingUpdateLoading(false);\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(\n `${controllerName} - failed to disable profile syncing - ${errorMessage}`,\n );\n }\n }\n\n /**\n * Allows retrieval of stored data. Data stored is string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param entryKey - entry key that matches schema\n * @returns the decrypted string contents found from user storage (or null if not found)\n */\n public async performGetStorage(\n entryKey: UserStorageEntryKeys,\n ): Promise<string | null> {\n this.#assertProfileSyncingEnabled();\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n const result = await getUserStorage({\n entryKey,\n bearerToken,\n storageKey,\n });\n\n return result;\n }\n\n /**\n * Allows storage of user data. Data stored must be string formatted.\n * Developers can extend the entry path and entry name through the `schema.ts` file.\n *\n * @param entryKey - entry key that matches schema\n * @param value - The string data you want to store.\n * @returns nothing. NOTE that an error is thrown if fails to store data.\n */\n public async performSetStorage(\n entryKey: UserStorageEntryKeys,\n value: string,\n ): Promise<void> {\n this.#assertProfileSyncingEnabled();\n const { bearerToken, storageKey } =\n await this.#getStorageKeyAndBearerToken();\n\n await upsertUserStorage(value, {\n entryKey,\n bearerToken,\n storageKey,\n });\n }\n\n /**\n * Retrieves the storage key, for internal use only!\n *\n * @returns the storage key\n */\n public async getStorageKey(): Promise<string> {\n this.#assertProfileSyncingEnabled();\n const storageKey = await this.#createStorageKey();\n return storageKey;\n }\n\n #assertProfileSyncingEnabled(): void {\n if (!this.state.isProfileSyncingEnabled) {\n throw new Error(\n `${controllerName}: Unable to call method, user is not authenticated`,\n );\n }\n }\n\n /**\n * Utility to get the bearer token and storage key\n */\n async #getStorageKeyAndBearerToken(): Promise<{\n bearerToken: string;\n storageKey: string;\n }> {\n const bearerToken = await this.#auth.getBearerToken();\n if (!bearerToken) {\n throw new Error('UserStorageController - unable to get bearer token');\n }\n const storageKey = await this.#createStorageKey();\n\n return { bearerToken, storageKey };\n }\n\n /**\n * Rather than storing the storage key, we can compute the storage key when needed.\n *\n * @returns the storage key\n */\n async #createStorageKey(): Promise<string> {\n const id: string = await this.#auth.getProfileId();\n if (!id) {\n throw new Error('UserStorageController - unable to create storage key');\n }\n\n const storageKeySignature = await this.#snapSignMessage(`metamask:${id}`);\n const storageKey = createSHA256Hash(storageKeySignature);\n return storageKey;\n }\n\n /**\n * Signs a specific message using an underlying auth snap.\n *\n * @param message - A specific tagged message to sign.\n * @returns A Signature created by the snap.\n */\n #snapSignMessage(message: `metamask:${string}`): Promise<string> {\n return this.messagingSystem.call(\n 'SnapController:handleRequest',\n createSnapSignMessageRequest(message),\n ) as Promise<string>;\n }\n\n #setIsProfileSyncingUpdateLoading(\n isProfileSyncingUpdateLoading: boolean,\n ): void {\n this.update((state) => {\n state.isProfileSyncingUpdateLoading = isProfileSyncingUpdateLoading;\n });\n }\n}\n","import { number as assertNumber } from './_assert.js';\nimport { sha256 } from './sha256.js';\nimport { pbkdf2 } from './pbkdf2.js';\nimport { rotl, asyncLoop, checkOpts, Input, u32, isLE, byteSwap32 } from './utils.js';\n\n// RFC 7914 Scrypt KDF\n\n// The main Scrypt loop: uses Salsa extensively.\n// Six versions of the function were tried, this is the fastest one.\n// prettier-ignore\nfunction XorAndSalsa(\n prev: Uint32Array,\n pi: number,\n input: Uint32Array,\n ii: number,\n out: Uint32Array,\n oi: number\n) {\n // Based on https://cr.yp.to/salsa20.html\n // Xor blocks\n let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];\n let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];\n let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];\n let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];\n let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];\n let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];\n let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];\n let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];\n // Save state to temporary variables (salsa)\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03,\n x04 = y04, x05 = y05, x06 = y06, x07 = y07,\n x08 = y08, x09 = y09, x10 = y10, x11 = y11,\n x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n // Main loop (salsa)\n for (let i = 0; i < 8; i += 2) {\n x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9);\n x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18);\n x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9);\n x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18);\n x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9);\n x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18);\n x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9);\n x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18);\n x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9);\n x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18);\n x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9);\n x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18);\n x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9);\n x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18);\n x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9);\n x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18);\n }\n // Write output (salsa)\n out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;\n}\n\nfunction BlockMix(input: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) {\n // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)\n let head = oi + 0;\n let tail = oi + 16 * r;\n for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]\n for (let i = 0; i < r; i++, head += 16, ii += 16) {\n // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1\n XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])\n if (i > 0) tail += 16; // First iteration overwrites tmp value in tail\n XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])\n }\n}\n\nexport type ScryptOpts = {\n N: number; // cost factor\n r: number; // block size\n p: number; // parallelization\n dkLen?: number; // key length\n asyncTick?: number; // block execution max time\n maxmem?: number;\n onProgress?: (progress: number) => void;\n};\n\n// Common prologue and epilogue for sync/async functions\nfunction scryptInit(password: Input, salt: Input, _opts?: ScryptOpts) {\n // Maxmem - 1GB+1KB by default\n const opts = checkOpts(\n {\n dkLen: 32,\n asyncTick: 10,\n maxmem: 1024 ** 3 + 1024,\n },\n _opts\n );\n const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;\n assertNumber(N);\n assertNumber(r);\n assertNumber(p);\n assertNumber(dkLen);\n assertNumber(asyncTick);\n assertNumber(maxmem);\n if (onProgress !== undefined && typeof onProgress !== 'function')\n throw new Error('progressCb should be function');\n const blockSize = 128 * r;\n const blockSize32 = blockSize / 4;\n if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) {\n // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function\n // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future.\n throw new Error(\n 'Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'\n );\n }\n if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) {\n throw new Error(\n 'Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'\n );\n }\n if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) {\n throw new Error(\n 'Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'\n );\n }\n const memUsed = blockSize * (N + p);\n if (memUsed > maxmem) {\n throw new Error(\n `Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`\n );\n }\n // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)\n // Since it has only one iteration there is no reason to use async variant\n const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });\n const B32 = u32(B);\n // Re-used between parallel iterations. Array(iterations) of B\n const V = u32(new Uint8Array(blockSize * N));\n const tmp = u32(new Uint8Array(blockSize));\n let blockMixCb = () => {};\n if (onProgress) {\n const totalBlockMix = 2 * N * p;\n // Invoke callback if progress changes from 10.01 to 10.02\n // Allows to draw smooth progress bar on up to 8K screen\n const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);\n let blockMixCnt = 0;\n blockMixCb = () => {\n blockMixCnt++;\n if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))\n onProgress(blockMixCnt / totalBlockMix);\n };\n }\n return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };\n}\n\nfunction scryptOutput(\n password: Input,\n dkLen: number,\n B: Uint8Array,\n V: Uint32Array,\n tmp: Uint32Array\n) {\n const res = pbkdf2(sha256, password, B, { c: 1, dkLen });\n B.fill(0);\n V.fill(0);\n tmp.fill(0);\n return res;\n}\n\n/**\n * Scrypt KDF from RFC 7914.\n * @param password - pass\n * @param salt - salt\n * @param opts - parameters\n * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)\n * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance\n * - `p` is parallelization factor (1 is common)\n * - `dkLen` is output key length in bytes e.g. 32.\n * - `asyncTick` - (default: 10) max time in ms for which async function can block execution\n * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt\n * - `onProgress` - callback function that would be executed for progress report\n * @returns Derived key\n */\nexport function scrypt(password: Input, salt: Input, opts: ScryptOpts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(\n password,\n salt,\n opts\n );\n if (!isLE) byteSwap32(B32);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i]\n for (let i = 0, pos = 0; i < N - 1; i++) {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n }\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n for (let i = 0; i < N; i++) {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n }\n }\n if (!isLE) byteSwap32(B32);\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n\n/**\n * Scrypt KDF from RFC 7914.\n */\nexport async function scryptAsync(password: Input, salt: Input, opts: ScryptOpts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(\n password,\n salt,\n opts\n );\n if (!isLE) byteSwap32(B32);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i]\n let pos = 0;\n await asyncLoop(N - 1, asyncTick, () => {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n });\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n await asyncLoop(N, asyncTick, () => {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n });\n }\n if (!isLE) byteSwap32(B32);\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n","export const byteArrayToBase64 = (byteArray: Uint8Array) => {\n return Buffer.from(byteArray).toString('base64');\n};\n\nexport const base64ToByteArray = (base64: string) => {\n return new Uint8Array(Buffer.from(base64, 'base64'));\n};\n\nexport const bytesToUtf8 = (byteArray: Uint8Array) => {\n const decoder = new TextDecoder('utf-8');\n return decoder.decode(byteArray);\n};\n","import { base64ToByteArray, byteArrayToBase64 } from './utils';\n\ntype CachedEntry = {\n salt: Uint8Array;\n base64Salt: string;\n key: Uint8Array;\n};\n\nconst MAX_PASSWORD_CACHES = 3;\nconst MAX_SALT_CACHES = 10;\n\n/**\n * In-Memory Caching derived keys based from a given salt and password.\n */\ntype PasswordMemCachedKDF = {\n [hashedPassword: string]: Map<string, Uint8Array>;\n};\nlet inMemCachedKDF: PasswordMemCachedKDF = {};\nconst getPasswordCache = (hashedPassword: string) => {\n inMemCachedKDF[hashedPassword] ??= new Map();\n return inMemCachedKDF[hashedPassword];\n};\n\n/**\n * Returns a given cached derived key from a hashed password and salt\n *\n * @param hashedPassword - hashed password for cache lookup\n * @param salt - provide salt to receive cached key\n * @returns cached key\n */\nexport function getCachedKeyBySalt(\n hashedPassword: string,\n salt: Uint8Array,\n): CachedEntry | undefined {\n const cache = getPasswordCache(hashedPassword);\n const base64Salt = byteArrayToBase64(salt);\n const cachedKey = cache.get(base64Salt);\n if (!cachedKey) {\n return undefined;\n }\n\n return {\n salt,\n base64Salt,\n key: cachedKey,\n };\n}\n\n/**\n * Gets any cached key for a given hashed password\n *\n * @param hashedPassword - hashed password for cache lookup\n * @returns any (the first) cached key\n */\nexport function getAnyCachedKey(\n hashedPassword: string,\n): CachedEntry | undefined {\n const cache = getPasswordCache(hashedPassword);\n\n // Takes 1 item from an Iterator via Map.entries()\n const cachedEntry: [string, Uint8Array] | undefined = cache\n .entries()\n .next().value;\n\n if (!cachedEntry) {\n return undefined;\n }\n\n const base64Salt = cachedEntry[0];\n const bytesSalt = base64ToByteArray(base64Salt);\n return {\n salt: bytesSalt,\n base64Salt,\n key: cachedEntry[1],\n };\n}\n\n/**\n * Sets a key to the in memory cache.\n * We have set an arbitrary size of 10 cached keys per hashed password.\n *\n * @param hashedPassword - hashed password for cache lookup\n * @param salt - salt to set new derived key\n * @param key - derived key we are setting\n */\nexport function setCachedKey(\n hashedPassword: string,\n salt: Uint8Array,\n key: Uint8Array,\n): void {\n // Max password caches\n if (Object.keys(inMemCachedKDF).length > MAX_PASSWORD_CACHES) {\n inMemCachedKDF = {};\n }\n\n const cache = getPasswordCache(hashedPassword);\n const base64Salt = byteArrayToBase64(salt);\n\n // Max salt caches\n if (cache.size > MAX_SALT_CACHES) {\n cache.clear();\n }\n\n cache.set(base64Salt, key);\n}\n","import { gcm } from '@noble/ciphers/aes';\nimport { randomBytes } from '@noble/ciphers/webcrypto';\nimport { scrypt } from '@noble/hashes/scrypt';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { utf8ToBytes, concatBytes, bytesToHex } from '@noble/hashes/utils';\n\nimport { getAnyCachedKey, getCachedKeyBySalt, setCachedKey } from './cache';\nimport { base64ToByteArray, byteArrayToBase64, bytesToUtf8 } from './utils';\n\nexport type EncryptedPayload = {\n // version\n v: '1';\n\n // key derivation function algorithm - scrypt\n t: 'scrypt';\n\n // data\n d: string;\n\n // encryption options - scrypt\n o: {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n N: number;\n r: number;\n p: number;\n dkLen: number;\n };\n\n // Salt options\n saltLen: number;\n};\n\n// Nonce/Key Sizes\nconst ALGORITHM_NONCE_SIZE = 12; // 12 bytes\nconst ALGORITHM_KEY_SIZE = 16; // 16 bytes\n\n// Scrypt settings\n// see: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt\nconst SCRYPT_SALT_SIZE = 16; // 16 bytes\nconst SCRYPT_N = 2 ** 17; // CPU/memory cost parameter (must be a power of 2, > 1)\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst SCRYPT_r = 8; // Block size parameter\n// eslint-disable-next-line @typescript-eslint/naming-convention\nconst SCRYPT_p = 1; // Parallelization parameter\n\nclass EncryptorDecryptor {\n encryptString(plaintext: string, password: string): string {\n try {\n return this.#encryptStringV1(plaintext, password);\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to encrypt string - ${errorMessage}`);\n }\n }\n\n decryptString(encryptedDataStr: string, password: string): string {\n try {\n const encryptedData: EncryptedPayload = JSON.parse(encryptedDataStr);\n if (encryptedData.v === '1') {\n if (encryptedData.t === 'scrypt') {\n return this.#decryptStringV1(encryptedData, password);\n }\n }\n throw new Error(\n `Unsupported encrypted data payload - ${encryptedDataStr}`,\n );\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : JSON.stringify(e);\n throw new Error(`Unable to decrypt string - ${errorMessage}`);\n }\n }\n\n #encryptStringV1(plaintext: string, password: string): string {\n const { key, salt } = this.#getOrGenerateScryptKey(password, {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n });\n\n // Encrypt and prepend salt.\n const plaintextRaw = utf8ToBytes(plaintext);\n const ciphertextAndNonceAndSalt = concatBytes(\n salt,\n this.#encrypt(plaintextRaw, key),\n );\n\n // Convert to Base64\n const encryptedData = byteArrayToBase64(ciphertextAndNonceAndSalt);\n\n const encryptedPayload: EncryptedPayload = {\n v: '1',\n t: 'scrypt',\n d: encryptedData,\n o: {\n N: SCRYPT_N,\n r: SCRYPT_r,\n p: SCRYPT_p,\n dkLen: ALGORITHM_KEY_SIZE,\n },\n saltLen: SCRYPT_SALT_SIZE,\n };\n\n return JSON.stringify(encryptedPayload);\n }\n\n #decryptStringV1(data: EncryptedPayload, password: string): string {\n const { o, d: base64CiphertextAndNonceAndSalt, saltLen } = data;\n\n // Decode the base64.\n const ciphertextAndNonceAndSalt = base64ToByteArray(\n base64CiphertextAndNonceAndSalt,\n );\n\n // Create buffers of salt and ciphertextAndNonce.\n const salt = ciphertextAndNonceAndSalt.slice(0, saltLen);\n const ciphertextAndNonce = ciphertextAndNonceAndSalt.slice(\n saltLen,\n ciphertextAndNonceAndSalt.length,\n );\n\n // Derive the key.\n const { key } = this.#getOrGenerateScryptKey(\n password,\n {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n },\n salt,\n );\n\n // Decrypt and return result.\n return bytesToUtf8(this.#decrypt(ciphertextAndNonce, key));\n }\n\n #encrypt(plaintext: Uint8Array, key: Uint8Array): Uint8Array {\n const nonce = randomBytes(ALGORITHM_NONCE_SIZE);\n\n // Encrypt and prepend nonce.\n const ciphertext = gcm(key, nonce).encrypt(plaintext);\n\n return concatBytes(nonce, ciphertext);\n }\n\n #decrypt(ciphertextAndNonce: Uint8Array, key: Uint8Array): Uint8Array {\n // Create buffers of nonce and ciphertext.\n const nonce = ciphertextAndNonce.slice(0, ALGORITHM_NONCE_SIZE);\n const ciphertext = ciphertextAndNonce.slice(\n ALGORITHM_NONCE_SIZE,\n ciphertextAndNonce.length,\n );\n\n // Decrypt and return result.\n return gcm(key, nonce).decrypt(ciphertext);\n }\n\n #getOrGenerateScryptKey(\n password: string,\n o: EncryptedPayload['o'],\n salt?: Uint8Array,\n ) {\n const hashedPassword = createSHA256Hash(password);\n const cachedKey = salt\n ? getCachedKeyBySalt(hashedPassword, salt)\n : getAnyCachedKey(hashedPassword);\n\n if (cachedKey) {\n return {\n key: cachedKey.key,\n salt: cachedKey.salt,\n };\n }\n\n const newSalt = salt ?? randomBytes(SCRYPT_SALT_SIZE);\n const newKey = scrypt(password, newSalt, {\n N: o.N,\n r: o.r,\n p: o.p,\n dkLen: o.dkLen,\n });\n setCachedKey(hashedPassword, newSalt, newKey);\n\n return {\n key: newKey,\n salt: newSalt,\n };\n }\n}\n\nconst encryption = new EncryptorDecryptor();\nexport default encryption;\n\n/**\n * Receive a SHA256 hash from a given string\n * @param data - input\n * @returns sha256 hash\n */\nexport function createSHA256Hash(data: string): string {\n const hashedData = sha256(data);\n return bytesToHex(hashedData);\n}\n","import Encryption from './encryption';\n\nexport { Encryption };\nexport * from './encryption';\nexport default Encryption;\n","import log from 'loglevel';\n\nimport { Env, getEnvUrls } from '../../sdk';\nimport encryption from './encryption';\nimport type { UserStorageEntryKeys } from './schema';\nimport { createEntryPath } from './schema';\n\nconst ENV_URLS = getEnvUrls(Env.PRD);\n\nexport const USER_STORAGE_API: string = ENV_URLS.userStorageApiUrl;\nexport const USER_STORAGE_ENDPOINT = `${USER_STORAGE_API}/api/v1/userstorage`;\n\n/**\n * This is the Server Response shape\n */\nexport type GetUserStorageResponse = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n HashedKey: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n Data: string;\n};\n\nexport type UserStorageOptions = {\n bearerToken: string;\n entryKey: UserStorageEntryKeys;\n storageKey: string;\n};\n\n/**\n * User Storage Service - Get Storage Entry.\n *\n * @param opts - User Storage Options\n * @returns The storage entry, or null if fails to find entry\n */\nexport async function getUserStorage(\n opts: UserStorageOptions,\n): Promise<string | null> {\n try {\n const path = createEntryPath(opts.entryKey, opts.storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}${path}`);\n\n const userStorageResponse = await fetch(url.toString(), {\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${opts.bearerToken}`,\n },\n });\n\n // Acceptable error - since indicates entry does not exist.\n if (userStorageResponse.status === 404) {\n return null;\n }\n\n if (userStorageResponse.status !== 200) {\n throw new Error('Unable to get User Storage');\n }\n\n const userStorage: GetUserStorageResponse | null =\n await userStorageResponse.json();\n const encryptedData = userStorage?.Data ?? null;\n\n if (!encryptedData) {\n return null;\n }\n\n const decryptedData = encryption.decryptString(\n encryptedData,\n opts.storageKey,\n );\n\n return decryptedData;\n } catch (e) {\n log.error('Failed to get user storage', e);\n return null;\n }\n}\n\n/**\n * User Storage Service - Set Storage Entry.\n *\n * @param data - data to store\n * @param opts - storage options\n */\nexport async function upsertUserStorage(\n data: string,\n opts: UserStorageOptions,\n): Promise<void> {\n const encryptedData = encryption.encryptString(data, opts.storageKey);\n const path = createEntryPath(opts.entryKey, opts.storageKey);\n const url = new URL(`${USER_STORAGE_ENDPOINT}${path}`);\n\n const res = await fetch(url.toString(), {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${opts.bearerToken}`,\n },\n body: JSON.stringify({ data: encryptedData }),\n });\n\n if (!res.ok) {\n throw new Error('user-storage - unable to upsert data');\n }\n}\n","import { createSHA256Hash } from './encryption';\n\ntype UserStorageEntry = { path: string; entryName: string };\n\n/**\n * The User Storage Endpoint requires a path and an entry name.\n * Developers can provide additional paths by extending this variable below\n */\nexport const USER_STORAGE_ENTRIES = {\n notificationSettings: {\n path: 'notifications',\n entryName: 'notificationSettings',\n },\n} satisfies Record<string, UserStorageEntry>;\n\nexport type UserStorageEntryKeys = keyof typeof USER_STORAGE_ENTRIES;\n\n/**\n * Constructs a unique entry path for a user.\n * This can be done due to the uniqueness of the storage key (no users will share the same storage key).\n * The users entry is a unique hash that cannot be reversed.\n *\n * @param entryKey - storage schema entry key\n * @param storageKey - users storage key\n * @returns path to store entry\n */\nexport function createEntryPath(\n entryKey: UserStorageEntryKeys,\n storageKey: string,\n): string {\n const entry = USER_STORAGE_ENTRIES[entryKey];\n if (!entry) {\n throw new Error(`user-storage - invalid entry provided: ${entryKey}`);\n }\n\n const hashedKey = createSHA256Hash(entry.entryName + storageKey);\n return `/${entry.path}/${hashedKey}`;\n}\n","export * from './mockResponses';\nexport * from './mockServices';\nexport * from './mockStorage';\n","import encryption, { createSHA256Hash } from '../encryption';\n\nexport const MOCK_STORAGE_KEY_SIGNATURE = 'mockStorageKey';\nexport const MOCK_STORAGE_KEY = createSHA256Hash(MOCK_STORAGE_KEY_SIGNATURE);\nexport const MOCK_STORAGE_DATA = JSON.stringify({ hello: 'world' });\nexport const MOCK_ENCRYPTED_STORAGE_DATA = encryption.encryptString(\n MOCK_STORAGE_DATA,\n MOCK_STORAGE_KEY,\n);\n","import { createEntryPath } from '../schema';\nimport type { GetUserStorageResponse } from '../services';\nimport { USER_STORAGE_ENDPOINT } from '../services';\nimport { MOCK_ENCRYPTED_STORAGE_DATA, MOCK_STORAGE_KEY } from './mockStorage';\n\ntype MockResponse = {\n url: string;\n requestMethod: 'GET' | 'POST' | 'PUT';\n response: unknown;\n};\n\nexport const MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT = `${USER_STORAGE_ENDPOINT}${createEntryPath(\n 'notificationSettings',\n MOCK_STORAGE_KEY,\n)}`;\n\nconst MOCK_GET_USER_STORAGE_RESPONSE: GetUserStorageResponse = {\n HashedKey: 'HASHED_KEY',\n Data: MOCK_ENCRYPTED_STORAGE_DATA,\n};\n\nexport const getMockUserStorageGetResponse = () => {\n return {\n url: MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT,\n requestMethod: 'GET',\n response: MOCK_GET_USER_STORAGE_RESPONSE,\n } satisfies MockResponse;\n};\n\nexport const getMockUserStoragePutResponse = () => {\n return {\n url: MOCK_USER_STORAGE_NOTIFICATIONS_ENDPOINT,\n requestMethod: 'PUT',\n response: null,\n } satisfies MockResponse;\n};\n","import nock from 'nock';\n\nimport {\n getMockUserStorageGetResponse,\n getMockUserStoragePutResponse,\n} from './mockResponses';\n\ntype MockReply = {\n status: nock.StatusCode;\n body?: nock.Body;\n};\n\nexport const mockEndpointGetUserStorage = (mockReply?: MockReply) => {\n const mockResponse = getMockUserStorageGetResponse();\n const reply = mockReply ?? {\n status: 200,\n body: mockResponse.response,\n };\n\n const mockEndpoint = nock(mockResponse.url)\n .get('')\n .reply(reply.status, reply.body);\n\n return mockEndpoint;\n};\n\nexport const mockEndpointUpsertUserStorage = (\n mockReply?: Pick<MockReply, 'status'>,\n) => {\n const mockResponse = getMockUserStoragePutResponse();\n const mockEndpoint = nock(mockResponse.url)\n .put('')\n .reply(mockReply?.status ?? 204);\n return mockEndpoint;\n};\n","import { UserStorageController } from '@metamask/profile-sync-controller';\nimport log from 'loglevel';\n\nimport type { TRIGGER_TYPES } from '../constants/notification-schema';\nimport type { OnChainRawNotification } from '../types/on-chain-notification/on-chain-notification';\nimport type { components } from '../types/on-chain-notification/schema';\nimport type { UserStorage } from '../types/user-storage/user-storage';\nimport {\n traverseUserStorageTriggers,\n toggleUserStorageTriggerStatus,\n makeApiCall,\n} from '../utils/utils';\n\nexport type NotificationTrigger = {\n id: string;\n chainId: string;\n kind: string;\n address: string;\n};\n\nexport const TRIGGER_API = 'https://trigger.api.cx.metamask.io';\nexport const NOTIFICATION_API = 'https://notification.api.cx.metamask.io';\nexport const TRIGGER_API_BATCH_ENDPOINT = `${TRIGGER_API}/api/v1/triggers/batch`;\nexport const NOTIFICATION_API_LIST_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications`;\nexport const NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY = (page: number) =>\n `${NOTIFICATION_API_LIST_ENDPOINT}?page=${page}&per_page=100`;\nexport const NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT = `${NOTIFICATION_API}/api/v1/notifications/mark-as-read`;\n\n/**\n * Creates on-chain triggers based on the provided notification triggers.\n * This method generates a unique token for each trigger using the trigger ID and storage key,\n * proving ownership of the trigger being updated. It then makes an API call to create these triggers.\n * Upon successful creation, it updates the userStorage to reflect the new trigger status.\n *\n * @param userStorage - The user's storage object where triggers and their statuses are stored.\n * @param storageKey - A key used along with the trigger ID to generate a unique token for each trigger.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param triggers - An array of notification triggers to be created. Each trigger includes an ID, chain ID, kind, and address.\n * @returns A promise that resolves to void. Throws an error if the API call fails or if there's an issue creating the triggers.\n */\nexport async function createOnChainTriggers(\n userStorage: UserStorage,\n storageKey: string,\n bearerToken: string,\n triggers: NotificationTrigger[],\n): Promise<void> {\n type RequestPayloadTrigger = {\n id: string;\n // this is the trigger token, generated by using the uuid + storage key. It proves you own the trigger you are updating\n token: string;\n config: {\n kind: string;\n // eslint-disable-next-line @typescript-eslint/naming-convention\n chain_id: number;\n address: string;\n };\n };\n const triggersToCreate: RequestPayloadTrigger[] = triggers.map((t) => ({\n id: t.id,\n token: UserStorageController.createSHA256Hash(t.id + storageKey),\n config: {\n kind: t.kind,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n chain_id: Number(t.chainId),\n address: t.address,\n },\n }));\n\n if (triggersToCreate.length === 0) {\n return;\n }\n\n const response = await makeApiCall(\n bearerToken,\n TRIGGER_API_BATCH_ENDPOINT,\n 'POST',\n triggersToCreate,\n );\n\n if (!response.ok) {\n const errorData = await response.json().catch(() => undefined);\n log.error('Error creating triggers:', errorData);\n throw new Error('OnChain Notifications - unable to create triggers');\n }\n\n // If the trigger creation was fine\n // then update the userStorage\n for (const trigger of triggersToCreate) {\n toggleUserStorageTriggerStatus(\n userStorage,\n trigger.config.address,\n String(trigger.config.chain_id),\n trigger.id,\n true,\n );\n }\n}\n\n/**\n * Deletes on-chain triggers based on the provided UUIDs.\n * This method generates a unique token for each trigger using the UUID and storage key,\n * proving ownership of the trigger being deleted. It then makes an API call to delete these triggers.\n * Upon successful deletion, it updates the userStorage to remove the deleted trigger statuses.\n *\n * @param userStorage - The user's storage object where triggers and their statuses are stored.\n * @param storageKey - A key used along with the UUID to generate a unique token for each trigger.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param uuids - An array of UUIDs representing the triggers to be deleted.\n * @returns A promise that resolves to the updated UserStorage object. Throws an error if the API call fails or if there's an issue deleting the triggers.\n */\nexport async function deleteOnChainTriggers(\n userStorage: UserStorage,\n storageKey: string,\n bearerToken: string,\n uuids: string[],\n): Promise<UserStorage> {\n const triggersToDelete = uuids.map((uuid) => ({\n id: uuid,\n token: UserStorageController.createSHA256Hash(uuid + storageKey),\n }));\n\n try {\n const response = await makeApiCall(\n bearerToken,\n TRIGGER_API_BATCH_ENDPOINT,\n 'DELETE',\n triggersToDelete,\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to delete on-chain notifications for uuids ${uuids.join(', ')}`,\n );\n }\n\n // Update the state of the deleted trigger to false\n for (const uuid of uuids) {\n for (const address in userStorage) {\n if (address in userStorage) {\n for (const chainId in userStorage[address]) {\n if (userStorage?.[address]?.[chainId]?.[uuid]) {\n delete userStorage[address][chainId][uuid];\n }\n }\n }\n }\n }\n\n // Follow-up cleanup, if an address had no triggers whatsoever, then we can delete the address\n const isEmpty = (obj = {}) => Object.keys(obj).length === 0;\n for (const address in userStorage) {\n if (address in userStorage) {\n for (const chainId in userStorage[address]) {\n // Chain isEmpty Check\n if (isEmpty(userStorage?.[address]?.[chainId])) {\n delete userStorage[address][chainId];\n }\n }\n\n // Address isEmpty Check\n if (isEmpty(userStorage?.[address])) {\n delete userStorage[address];\n }\n }\n }\n } catch (err) {\n log.error(\n `Error deleting on-chain notifications for uuids ${uuids.join(', ')}:`,\n err,\n );\n throw err;\n }\n\n return userStorage;\n}\n\n/**\n * Fetches on-chain notifications for the given user storage and BearerToken.\n * This method iterates through the userStorage to find enabled triggers and fetches notifications for those triggers.\n * It makes paginated API calls to the notifications service, transforming and aggregating the notifications into a single array.\n * The process stops either when all pages have been fetched or when a page has less than 100 notifications, indicating the end of the data.\n *\n * @param userStorage - The user's storage object containing trigger information.\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @returns A promise that resolves to an array of OnChainRawNotification objects. If no triggers are enabled or an error occurs, it may return an empty array.\n */\nexport async function getOnChainNotifications(\n userStorage: UserStorage,\n bearerToken: string,\n): Promise<OnChainRawNotification[]> {\n const triggerIds = traverseUserStorageTriggers(userStorage, {\n mapTrigger: (t) => {\n if (!t.enabled) {\n return undefined;\n }\n return t.id;\n },\n });\n\n if (triggerIds.length === 0) {\n return [];\n }\n\n const onChainNotifications: OnChainRawNotification[] = [];\n const PAGE_LIMIT = 2;\n for (let page = 1; page <= PAGE_LIMIT; page++) {\n try {\n const response = await makeApiCall(\n bearerToken,\n NOTIFICATION_API_LIST_ENDPOINT_PAGE_QUERY(page),\n 'POST',\n // eslint-disable-next-line @typescript-eslint/naming-convention\n { trigger_ids: triggerIds },\n );\n\n const notifications = (await response.json()) as OnChainRawNotification[];\n\n // Transform and sort notifications\n const transformedNotifications = notifications\n .map(\n (\n n: components['schemas']['Notification'],\n ): OnChainRawNotification | undefined => {\n if (!n.data?.kind) {\n return undefined;\n }\n\n return {\n ...n,\n type: n.data.kind as TRIGGER_TYPES,\n } as OnChainRawNotification;\n },\n )\n .filter((n): n is OnChainRawNotification => Boolean(n));\n\n onChainNotifications.push(...transformedNotifications);\n\n // if less than 100 notifications on page, then means we reached end\n if (notifications.length < 100) {\n page = PAGE_LIMIT + 1;\n break;\n }\n } catch (err) {\n log.error(\n `Error fetching on-chain notifications for trigger IDs ${triggerIds.join(\n ', ',\n )}:`,\n err,\n );\n // do nothing\n }\n }\n\n return onChainNotifications;\n}\n\n/**\n * Marks the specified notifications as read.\n * This method sends a POST request to the notifications service to mark the provided notification IDs as read.\n * If the operation is successful, it completes without error. If the operation fails, it throws an error with details.\n *\n * @param bearerToken - The JSON Web Token used for authentication in the API call.\n * @param notificationIds - An array of notification IDs to be marked as read.\n * @returns A promise that resolves to void. The promise will reject if there's an error during the API call or if the response status is not 200.\n */\nexport async function markNotificationsAsRead(\n bearerToken: string,\n notificationIds: string[],\n): Promise<void> {\n if (notificationIds.length === 0) {\n return;\n }\n\n try {\n const response = await makeApiCall(\n bearerToken,\n NOTIFICATION_API_MARK_ALL_AS_READ_ENDPOINT,\n 'POST',\n { ids: notificationIds },\n );\n\n if (response.status !== 200) {\n const errorData = await response.json().catch(() => undefined);\n throw new Error(\n `Error marking notifications as read: ${errorData?.message as string}`,\n );\n }\n } catch (err) {\n log.error('Error marking notifications as read:', err);\n throw err;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAIA,QAAI,IAAI;AACR,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AACZ,QAAI,IAAI,IAAI;AAgBZ,WAAO,UAAU,SAAS,KAAK,SAAS;AACtC,gBAAU,WAAW,CAAC;AACtB,UAAI,OAAO,OAAO;AAClB,UAAI,SAAS,YAAY,IAAI,SAAS,GAAG;AACvC,eAAO,MAAM,GAAG;AAAA,MAClB,WAAW,SAAS,YAAY,SAAS,GAAG,GAAG;AAC7C,eAAO,QAAQ,OAAO,QAAQ,GAAG,IAAI,SAAS,GAAG;AAAA,MACnD;AACA,YAAM,IAAI;AAAA,QACR,0DACE,KAAK,UAAU,GAAG;AAAA,MACtB;AAAA,IACF;AAUA,aAAS,MAAM,KAAK;AAClB,YAAM,OAAO,GAAG;AAChB,UAAI,IAAI,SAAS,KAAK;AACpB;AAAA,MACF;AACA,UAAI,QAAQ,mIAAmI;AAAA,QAC7I;AAAA,MACF;AACA,UAAI,CAAC,OAAO;AACV;AAAA,MACF;AACA,UAAI,IAAI,WAAW,MAAM,CAAC,CAAC;AAC3B,UAAI,QAAQ,MAAM,CAAC,KAAK,MAAM,YAAY;AAC1C,cAAQ,MAAM;AAAA,QACZ,KAAK;AAAA,QACL,KAAK;AAAA,QACL,KAAK;AAAA,QACL,K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M,WAAW,MAAM;AAAA,QACrB;AAAA,QACA,0CAA0C,IAAI;AAAA,QAC9C;AAAA;AAAA,QAEA,EAAE,aAAa,WAAW;AAAA,MAC5B;AAEA,YAAM,gBAAiB,MAAM,SAAS,KAAK;AAG3C,YAAM,2BAA2B,cAC9B;AAAA,QACC,CACE,MACuC;AACvC,cAAI,CAAC,EAAE,MAAM,MAAM;AACjB,mBAAO;AAAA,UACT;AAEA,iBAAO;AAAA,YACL,GAAG;AAAA,YACH,MAAM,EAAE,KAAK;AAAA,UACf;AAAA,QACF;AAAA,MACF,EACC,OAAO,CAAC,MAAmC,QAAQ,CAAC,CAAC;AAExD,2BAAqB,KAAK,GAAG,wBAAwB;AAGrD,UAAI,cAAc,SAAS,KAAK;AAC9B,eAAO,aAAa;AACpB;AAAA,MACF;AAAA,IACF,SAAS,KAAK;AACZ,MAAAA,KAAI;AAAA,QACF,yDAAyD,WAAW;AAAA,UAClE;AAAA,QACF,CAAC;AAAA,QACD;AAAA,MACF;AAAA,IAEF;AAAA,EACF;AAEA,SAAO;AACT;AAWA,eAAsB,wBACpB,aACA,iBACe;AACf,MAAI,gBAAgB,WAAW,GAAG;AAChC;AAAA,EACF;AAEA,MAAI;AACF,UAAM,WAAW,MAAM;AAAA,MACrB;AAAA,MACA;AAAA,MACA;AAAA,MACA,EAAE,KAAK,gBAAgB;AAAA,IACzB;AAEA,QAAI,SAAS,WAAW,KAAK;AAC3B,YAAM,YAAY,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,MAAS;AAC7D,YAAM,IAAI;AAAA,QACR,wCAAwC,WAAW,OAAiB;AAAA,MACtE;AAAA,IACF;AAAA,EACF,SAAS,KAAK;AACZ,IAAAA,KAAI,MAAM,wCAAwC,GAAG;AACrD,UAAM;AAAA,EACR;AACF;","names":["hash","require_common","module","log","contentEncoding","url","responseBody","URL","callback","URL","mode","isLE","bytes","BLOCK_SIZE","POLY","mul2","sbox","sbox2","t0","t1","t2","t3","ctr","i","isLE","ecb","cbc","cfb","gcm","siv","cr","cbc","ctr","gcm","number","isBytes","bytes","number","exists","output","u32","createView","isLE","bytes","utf8ToBytes","toBytes","bytes","hash","toBytes","exists","bytes","hash","number","toBytes","createView","setBigUint64","isLE","createView","exists","toBytes","output","HandlerType","number","u32","isLE","utf8ToBytes","encryption_default","ENV_URLS","encryption_default","encryption_default","nock","log","log"]}
|