@metamask/snaps-execution-environments 6.8.0 → 6.9.1

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/dist/browserify/iframe/bundle.js +1 -1
  3. package/dist/browserify/node-process/bundle.js +1 -1
  4. package/dist/browserify/node-thread/bundle.js +1 -1
  5. package/dist/browserify/webview/index.html +1 -1
  6. package/dist/browserify/worker-executor/bundle.js +1 -1
  7. package/dist/browserify/worker-pool/bundle.js +1 -1
  8. package/dist/common/BaseSnapExecutor.cjs +58 -58
  9. package/dist/common/BaseSnapExecutor.cjs.map +1 -1
  10. package/dist/common/BaseSnapExecutor.mjs +58 -58
  11. package/dist/common/BaseSnapExecutor.mjs.map +1 -1
  12. package/dist/common/endowments/network.cjs +52 -39
  13. package/dist/common/endowments/network.cjs.map +1 -1
  14. package/dist/common/endowments/network.mjs +52 -39
  15. package/dist/common/endowments/network.mjs.map +1 -1
  16. package/dist/common/utils.cjs +0 -1
  17. package/dist/common/utils.cjs.map +1 -1
  18. package/dist/common/utils.d.cts.map +1 -1
  19. package/dist/common/utils.d.mts.map +1 -1
  20. package/dist/common/utils.mjs +0 -1
  21. package/dist/common/utils.mjs.map +1 -1
  22. package/dist/proxy/ProxySnapExecutor.cjs +69 -72
  23. package/dist/proxy/ProxySnapExecutor.cjs.map +1 -1
  24. package/dist/proxy/ProxySnapExecutor.mjs +68 -71
  25. package/dist/proxy/ProxySnapExecutor.mjs.map +1 -1
  26. package/dist/webview/WebViewExecutorStream.cjs +22 -9
  27. package/dist/webview/WebViewExecutorStream.cjs.map +1 -1
  28. package/dist/webview/WebViewExecutorStream.mjs +22 -9
  29. package/dist/webview/WebViewExecutorStream.mjs.map +1 -1
  30. package/dist/webworker/pool/WebWorkerPool.cjs +130 -133
  31. package/dist/webworker/pool/WebWorkerPool.cjs.map +1 -1
  32. package/dist/webworker/pool/WebWorkerPool.mjs +129 -132
  33. package/dist/webworker/pool/WebWorkerPool.mjs.map +1 -1
  34. package/package.json +3 -3
@@ -1 +1 @@
1
- {"version":3,"file":"BaseSnapExecutor.mjs","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;AAChE,OAAO,EAAE,uBAAuB,EAAE,kCAAkC;AAEpE,OAAO,EAAE,cAAc,EAAE,4CAA4C;AACrE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,EAAE,6BAA6B;AAE7E,OAAO,EAAE,YAAY,EAAE,4BAA4B;AAMnD,OAAO,EACL,iBAAiB,EACjB,QAAQ,EACR,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,OAAO,EACR,8BAA8B;AAC/B,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,8BAA8B;AAOrD,OAAO,EACL,MAAM,EACN,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,eAAe,EAChB,wBAAwB;AAGzB,OAAO,EAAE,GAAG,EAAE,uBAAmB;AAEjC,OAAO,EAAE,+BAA+B,EAAE,uBAAmB;AAC7D,OAAO,EAAE,gBAAgB,EAAE,+BAAqB;AAChD,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,2BAAuB;AACvE,OAAO,EAAE,aAAa,EAAE,yBAAqB;AAC7C,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,EACzB,wBAAwB,EACxB,mBAAmB,EACnB,YAAY,EACZ,eAAe,EAChB,oBAAgB;AACjB,OAAO,EACL,iCAAiC,EACjC,0BAA0B,EAC1B,6BAA6B,EAC7B,+BAA+B,EAChC,yBAAqB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,UAAU,CAAC,GAAG,CAAC,QAAQ;IAC7B,OAAO,EAAE,6BAA6B;CACvC,CAAC;AAEF,MAAM,cAAc,GAAG,SAAS;KAC7B,QAAQ,CAAO;IACd,OAAO,EAAE,sBAAsB;CAChC,CAAC;KACD,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,CAAC,CAAC;QACpC,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,kBAAkB,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;YAE/C,IAAI,IAAI,CAAC,kBAAkB,CAAC,IAAI,KAAK,CAAC,EAAE,CAAC;gBACvC,IAAI,CAAC,YAAY,IAAI,CAAC,CAAC;gBACvB,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;YAC5B,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers';\nimport { StreamProvider } from '@metamask/providers/stream-provider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport { validate, is } from '@metamask/superstruct';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, unknown>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments({\n snap,\n ethereum,\n snapId,\n endowments: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapGlobalProxy = proxyStreamProvider(request) as SnapsProvider;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"BaseSnapExecutor.mjs","sourceRoot":"","sources":["../../src/common/BaseSnapExecutor.ts"],"names":[],"mappings":";;;;;;AAAA,qFAAqF;AACrF,gEAAgE;AAChE,OAAO,EAAE,uBAAuB,EAAE,kCAAkC;AAEpE,OAAO,EAAE,cAAc,EAAE,4CAA4C;AACrE,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,EAAE,6BAA6B;AAE7E,OAAO,EAAE,YAAY,EAAE,4BAA4B;AAMnD,OAAO,EACL,iBAAiB,EACjB,QAAQ,EACR,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,OAAO,EACR,8BAA8B;AAC/B,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,8BAA8B;AAOrD,OAAO,EACL,MAAM,EACN,gBAAgB,EAChB,WAAW,EACX,WAAW,EACX,eAAe,EAChB,wBAAwB;AAGzB,OAAO,EAAE,GAAG,EAAE,uBAAmB;AAEjC,OAAO,EAAE,+BAA+B,EAAE,uBAAmB;AAC7D,OAAO,EAAE,gBAAgB,EAAE,+BAAqB;AAChD,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,2BAAuB;AACvE,OAAO,EAAE,aAAa,EAAE,yBAAqB;AAC7C,OAAO,EACL,6BAA6B,EAC7B,yBAAyB,EACzB,wBAAwB,EACxB,mBAAmB,EACnB,YAAY,EACZ,eAAe,EAChB,oBAAgB;AACjB,OAAO,EACL,iCAAiC,EACjC,0BAA0B,EAC1B,6BAA6B,EAC7B,+BAA+B,EAChC,yBAAqB;AAYtB,MAAM,aAAa,GAAG;IACpB,IAAI,EAAE,UAAU,CAAC,GAAG,CAAC,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AK;KACf,CAAC,CAAC;AACL,CAAC,8BAED,KAAK,oCAAU,EAAa,EAAE,QAAiC;IAC7D,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC/B,0DAA0D;QAC1D,qFAAqF;QACrF,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;YAChB,KAAK,EAAE,cAAc,CACnB,SAAS,CAAC,QAAQ,CAChB,0EAA0E,CAC3E,CACF;YACD,EAAE;YACF,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,MAAM,uBAAA,IAAI,4DAAO,MAAX,IAAI,EAAQ;QAChB,GAAG,QAAQ;QACX,EAAE;QACF,OAAO,EAAE,KAAK;KACf,CAAC,CAAC;AACL,CAAC","sourcesContent":["// eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment\n/// <reference path=\"../../../../node_modules/ses/types.d.ts\" />\nimport { createIdRemapMiddleware } from '@metamask/json-rpc-engine';\nimport type { RequestArguments } from '@metamask/providers';\nimport { StreamProvider } from '@metamask/providers/stream-provider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { getErrorData } from '@metamask/snaps-sdk';\nimport type {\n SnapExports,\n HandlerType,\n SnapExportsParameters,\n} from '@metamask/snaps-utils';\nimport {\n SNAP_EXPORT_NAMES,\n logError,\n SNAP_EXPORTS,\n WrappedSnapError,\n unwrapError,\n logInfo,\n} from '@metamask/snaps-utils';\nimport { validate, is } from '@metamask/superstruct';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n JsonRpcIdStruct,\n} from '@metamask/utils';\nimport type { Duplex } from 'readable-stream';\n\nimport { log } from '../logging';\nimport type { CommandMethodsMapping } from './commands';\nimport { getCommandMethodImplementations } from './commands';\nimport { createEndowments } from './endowments';\nimport { addEventListener, removeEventListener } from './globalEvents';\nimport { sortParamKeys } from './sortParams';\nimport {\n assertEthereumOutboundRequest,\n assertSnapOutboundRequest,\n sanitizeRequestArguments,\n proxyStreamProvider,\n withTeardown,\n isValidResponse,\n} from './utils';\nimport {\n ExecuteSnapRequestArgumentsStruct,\n PingRequestArgumentsStruct,\n SnapRpcRequestArgumentsStruct,\n TerminateRequestArgumentsStruct,\n} from './validation';\n\ntype EvaluationData = {\n stop: () => void;\n};\n\ntype SnapData = {\n exports: SnapExports;\n runningEvaluations: Set<EvaluationData>;\n idleTeardown: () => Promise<void>;\n};\n\nconst fallbackError = {\n code: errorCodes.rpc.internal,\n message: 'Execution Environment Error',\n};\n\nconst unhandledError = rpcErrors\n .internal<Json>({\n message: 'Unhandled Snap Error',\n })\n .serialize();\n\nexport type InvokeSnapArgs = Omit<SnapExportsParameters[0], 'chainId'>;\n\nexport type InvokeSnap = (\n target: string,\n handler: HandlerType,\n args: InvokeSnapArgs | undefined,\n) => Promise<Json>;\n\n/**\n * The supported methods in the execution environment. The validator checks the\n * incoming JSON-RPC request, and the `params` property is used for sorting the\n * parameters, if they are an object.\n */\nconst EXECUTION_ENVIRONMENT_METHODS = {\n ping: {\n struct: PingRequestArgumentsStruct,\n params: [],\n },\n executeSnap: {\n struct: ExecuteSnapRequestArgumentsStruct,\n params: ['snapId', 'sourceCode', 'endowments'],\n },\n terminate: {\n struct: TerminateRequestArgumentsStruct,\n params: [],\n },\n snapRpc: {\n struct: SnapRpcRequestArgumentsStruct,\n params: ['target', 'handler', 'origin', 'request'],\n },\n};\n\ntype Methods = typeof EXECUTION_ENVIRONMENT_METHODS;\n\nexport type NotifyFunction = (\n notification: Omit<JsonRpcNotification, 'jsonrpc'>,\n) => Promise<void>;\n\nexport class BaseSnapExecutor {\n private readonly snapData: Map<string, SnapData>;\n\n private readonly commandStream: Duplex;\n\n private readonly rpcStream: Duplex;\n\n private readonly methods: CommandMethodsMapping;\n\n private snapErrorHandler?: (event: ErrorEvent) => void;\n\n private snapPromiseErrorHandler?: (event: PromiseRejectionEvent) => void;\n\n private lastTeardown = 0;\n\n protected constructor(commandStream: Duplex, rpcStream: Duplex) {\n this.snapData = new Map();\n this.commandStream = commandStream;\n this.commandStream.on('data', (data) => {\n this.onCommandRequest(data).catch((error) => {\n // TODO: Decide how to handle errors.\n logError(error);\n });\n });\n this.rpcStream = rpcStream;\n\n this.methods = getCommandMethodImplementations(\n this.startSnap.bind(this),\n async (target, handlerType, args) => {\n const data = this.snapData.get(target);\n // We're capturing the handler in case someone modifies the data object\n // before the call.\n const handler = data?.exports[handlerType];\n const { required } = SNAP_EXPORTS[handlerType];\n\n assert(\n !required || handler !== undefined,\n `No ${handlerType} handler exported for snap \"${target}`,\n rpcErrors.methodNotSupported,\n );\n\n // Certain handlers are not required. If they are not exported, we\n // return null.\n if (!handler) {\n return null;\n }\n\n let result = await this.executeInSnapContext(target, () =>\n // TODO: fix handler args type cast\n handler(args as any),\n );\n\n // The handler might not return anything, but undefined is not valid JSON.\n if (result === undefined) {\n result = null;\n }\n\n // /!\\ Always return only sanitized JSON to prevent security flaws. /!\\\n try {\n return getSafeJson(result);\n } catch (error) {\n throw rpcErrors.internal(\n `Received non-JSON-serializable value: ${error.message.replace(\n /^Assertion failed: /u,\n '',\n )}`,\n );\n }\n },\n this.onTerminate.bind(this),\n );\n }\n\n private errorHandler(error: unknown, data: Record<string, Json>) {\n const serializedError = serializeError(error, {\n fallbackError: unhandledError,\n shouldIncludeStack: false,\n });\n\n const errorData = getErrorData(serializedError);\n\n this.#notify({\n method: 'UnhandledError',\n params: {\n error: {\n ...serializedError,\n data: {\n ...errorData,\n ...data,\n },\n },\n },\n }).catch((notifyError) => {\n logError(notifyError);\n });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n if (\n hasProperty(message, 'id') &&\n is((message as Pick<JsonRpcRequest, 'id'>).id, JsonRpcIdStruct)\n ) {\n // Instead of throwing, we directly respond with an error.\n // We can only do this if the message ID is still valid.\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC requests must be JSON serializable objects.',\n ),\n ),\n id: (message as Pick<JsonRpcRequest, 'id'>).id,\n jsonrpc: '2.0',\n });\n } else {\n logInfo(\n 'Command stream received a non-JSON-RPC request, and was unable to respond.',\n );\n }\n return;\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n await this.#respond(id, {\n error: rpcErrors\n .methodNotFound({\n data: {\n method,\n },\n })\n .serialize(),\n });\n return;\n }\n\n const methodObject = EXECUTION_ENVIRONMENT_METHODS[method as keyof Methods];\n\n // support params by-name and by-position\n const paramsAsArray = sortParamKeys(methodObject.params, params);\n\n const [error] = validate<any, any>(paramsAsArray, methodObject.struct);\n if (error) {\n await this.#respond(id, {\n error: rpcErrors\n .invalidParams({\n message: `Invalid parameters for method \"${method}\": ${error.message}.`,\n data: {\n method,\n params: paramsAsArray,\n },\n })\n .serialize(),\n });\n return;\n }\n\n try {\n const result = await (this.methods as any)[method](...paramsAsArray);\n await this.#respond(id, { result });\n } catch (rpcError) {\n await this.#respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n // Awaitable function that writes back to the command stream\n // To prevent snap execution from blocking writing we wrap in a promise\n // and await it before continuing execution\n async #write(chunk: Json) {\n return new Promise<void>((resolve, reject) => {\n this.commandStream.write(chunk, (error) => {\n if (error) {\n reject(error);\n return;\n }\n resolve();\n });\n });\n }\n\n async #notify(notification: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidResponse(notification)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects smaller than 64 MB.',\n );\n }\n\n await this.#write({\n ...notification,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, response: Record<string, unknown>) {\n if (!isValidResponse(response)) {\n // Instead of throwing, we directly respond with an error.\n // This prevents an issue where we wouldn't respond when errors were non-serializable\n await this.#write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects smaller than 64 MB.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...response,\n id,\n jsonrpc: '2.0',\n });\n }\n\n /**\n * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw\n * on errors.\n *\n * @param snapId - The id of the snap.\n * @param sourceCode - The source code of the snap, in IIFE format.\n * @param _endowments - An array of the names of the endowments.\n */\n protected async startSnap(\n snapId: string,\n sourceCode: string,\n _endowments: string[],\n ): Promise<void> {\n log(`Starting snap '${snapId}' in worker.`);\n if (this.snapPromiseErrorHandler) {\n removeEventListener('unhandledrejection', this.snapPromiseErrorHandler);\n }\n\n if (this.snapErrorHandler) {\n removeEventListener('error', this.snapErrorHandler);\n }\n\n this.snapErrorHandler = (error: ErrorEvent) => {\n this.errorHandler(error.error, { snapId });\n };\n\n this.snapPromiseErrorHandler = (error: PromiseRejectionEvent) => {\n this.errorHandler(error instanceof Error ? error : error.reason, {\n snapId,\n });\n };\n\n const provider = new StreamProvider(this.rpcStream, {\n jsonRpcStreamName: 'metamask-provider',\n rpcMiddleware: [createIdRemapMiddleware()],\n });\n\n await provider.initialize();\n\n const snap = this.createSnapGlobal(provider);\n const ethereum = this.createEIP1193Provider(provider);\n // We specifically use any type because the Snap can modify the object any way they want\n const snapModule: any = { exports: {} };\n\n try {\n const { endowments, teardown: endowmentTeardown } = createEndowments({\n snap,\n ethereum,\n snapId,\n endowments: _endowments,\n notify: this.#notify.bind(this),\n });\n\n // !!! Ensure that this is the only place the data is being set.\n // Other methods access the object value and mutate its properties.\n this.snapData.set(snapId, {\n idleTeardown: endowmentTeardown,\n runningEvaluations: new Set(),\n exports: {},\n });\n\n addEventListener('unhandledRejection', this.snapPromiseErrorHandler);\n addEventListener('error', this.snapErrorHandler);\n\n const compartment = new Compartment({\n ...endowments,\n module: snapModule,\n exports: snapModule.exports,\n });\n\n // All of those are JavaScript runtime specific and self referential,\n // but we add them for compatibility sake with external libraries.\n //\n // We can't do that in the injected globals object above\n // because SES creates its own globalThis\n compartment.globalThis.self = compartment.globalThis;\n compartment.globalThis.global = compartment.globalThis;\n compartment.globalThis.window = compartment.globalThis;\n\n await this.executeInSnapContext(snapId, () => {\n compartment.evaluate(sourceCode);\n this.registerSnapExports(snapId, snapModule);\n });\n } catch (error) {\n this.removeSnap(snapId);\n\n const [cause] = unwrapError(error);\n throw rpcErrors.internal({\n message: `Error while running snap '${snapId}': ${cause.message}`,\n data: {\n cause: cause.serialize(),\n },\n });\n }\n }\n\n /**\n * Cancels all running evaluations of all snaps and clears all snap data.\n * NOTE:** Should only be called in response to the `terminate` RPC command.\n */\n protected onTerminate() {\n // `stop()` tears down snap endowments.\n // Teardown will also be run for each snap as soon as there are\n // no more running evaluations for that snap.\n this.snapData.forEach((data) =>\n data.runningEvaluations.forEach((evaluation) => evaluation.stop()),\n );\n this.snapData.clear();\n }\n\n private registerSnapExports(snapId: string, snapModule: any) {\n const data = this.snapData.get(snapId);\n // Somebody deleted the snap before we could register.\n if (!data) {\n return;\n }\n\n data.exports = SNAP_EXPORT_NAMES.reduce((acc, exportName) => {\n const snapExport = snapModule.exports[exportName];\n const { validator } = SNAP_EXPORTS[exportName];\n if (validator(snapExport)) {\n return { ...acc, [exportName]: snapExport };\n }\n return acc;\n }, {});\n\n // If the Snap has no valid exports after this, fail.\n assert(Object.keys(data.exports).length > 0, 'Snap has no valid exports.');\n }\n\n /**\n * Instantiates a snap API object (i.e. `globalThis.snap`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The snap provider object.\n */\n private createSnapGlobal(provider: StreamProvider): SnapsProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'snap.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'snap.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const snapGlobalProxy = proxyStreamProvider(request) as SnapsProvider;\n\n return harden(snapGlobalProxy);\n }\n\n /**\n * Instantiates an EIP-1193 Ethereum provider object (i.e. `globalThis.ethereum`).\n *\n * @param provider - A StreamProvider connected to MetaMask.\n * @returns The EIP-1193 Ethereum provider object.\n */\n private createEIP1193Provider(provider: StreamProvider): StreamProvider {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertEthereumOutboundRequest(sanitizedArgs);\n return await withTeardown(\n (async () => {\n await this.#notify({\n method: 'OutboundRequest',\n params: { source: 'ethereum.request' },\n });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({\n method: 'OutboundResponse',\n params: { source: 'ethereum.request' },\n });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(request);\n\n return harden(streamProviderProxy);\n }\n\n /**\n * Removes the snap with the given name.\n *\n * @param snapId - The id of the snap to remove.\n */\n private removeSnap(snapId: string): void {\n this.snapData.delete(snapId);\n }\n\n /**\n * Calls the specified executor function in the context of the specified snap.\n * Essentially, this means that the operation performed by the executor is\n * counted as an evaluation of the specified snap. When the count of running\n * evaluations of a snap reaches zero, its endowments are torn down.\n *\n * @param snapId - The id of the snap whose context to execute in.\n * @param executor - The function that will be executed in the snap's context.\n * @returns The executor's return value.\n * @template Result - The return value of the executor.\n */\n private async executeInSnapContext<Result>(\n snapId: string,\n executor: () => Promise<Result> | Result,\n ): Promise<Result> {\n const data = this.snapData.get(snapId);\n if (data === undefined) {\n throw rpcErrors.internal(\n `Tried to execute in context of unknown snap: \"${snapId}\".`,\n );\n }\n\n let stop: () => void;\n const stopPromise = new Promise<never>(\n (_, reject) =>\n (stop = () =>\n reject(\n // TODO(rekmarks): Specify / standardize error code for this case.\n rpcErrors.internal(\n `The snap \"${snapId}\" has been terminated during execution.`,\n ),\n )),\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const evaluationData = { stop: stop! };\n\n try {\n data.runningEvaluations.add(evaluationData);\n // Notice that we have to await this executor.\n // If we didn't, we would decrease the amount of running evaluations\n // before the promise actually resolves\n return await Promise.race([executor(), stopPromise]);\n } catch (error) {\n throw new WrappedSnapError(error);\n } finally {\n data.runningEvaluations.delete(evaluationData);\n\n if (data.runningEvaluations.size === 0) {\n this.lastTeardown += 1;\n await data.idleTeardown();\n }\n }\n }\n}\n"]}
@@ -1,4 +1,16 @@
1
1
  "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _ResponseWrapper_teardownRef, _ResponseWrapper_ogResponse, _ResponseWrapper_onStart, _ResponseWrapper_onFinish;
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
15
  const utils_1 = require("@metamask/utils");
4
16
  const utils_2 = require("../utils.cjs");
@@ -7,103 +19,104 @@ const utils_2 = require("../utils.cjs");
7
19
  * That way, a teardown process can stop any processes left.
8
20
  */
9
21
  class ResponseWrapper {
10
- #teardownRef;
11
- #ogResponse;
12
- #onStart;
13
- #onFinish;
14
22
  constructor(ogResponse, teardownRef, onStart, onFinish) {
15
- this.#ogResponse = ogResponse;
16
- this.#teardownRef = teardownRef;
17
- this.#onStart = onStart;
18
- this.#onFinish = onFinish;
23
+ _ResponseWrapper_teardownRef.set(this, void 0);
24
+ _ResponseWrapper_ogResponse.set(this, void 0);
25
+ _ResponseWrapper_onStart.set(this, void 0);
26
+ _ResponseWrapper_onFinish.set(this, void 0);
27
+ __classPrivateFieldSet(this, _ResponseWrapper_ogResponse, ogResponse, "f");
28
+ __classPrivateFieldSet(this, _ResponseWrapper_teardownRef, teardownRef, "f");
29
+ __classPrivateFieldSet(this, _ResponseWrapper_onStart, onStart, "f");
30
+ __classPrivateFieldSet(this, _ResponseWrapper_onFinish, onFinish, "f");
19
31
  }
20
32
  get body() {
21
- return this.#ogResponse.body;
33
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").body;
22
34
  }
23
35
  get bodyUsed() {
24
- return this.#ogResponse.bodyUsed;
36
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").bodyUsed;
25
37
  }
26
38
  get headers() {
27
- return this.#ogResponse.headers;
39
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").headers;
28
40
  }
29
41
  get ok() {
30
- return this.#ogResponse.ok;
42
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").ok;
31
43
  }
32
44
  get redirected() {
33
- return this.#ogResponse.redirected;
45
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").redirected;
34
46
  }
35
47
  get status() {
36
- return this.#ogResponse.status;
48
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").status;
37
49
  }
38
50
  get statusText() {
39
- return this.#ogResponse.statusText;
51
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").statusText;
40
52
  }
41
53
  get type() {
42
- return this.#ogResponse.type;
54
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").type;
43
55
  }
44
56
  get url() {
45
- return this.#ogResponse.url;
57
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").url;
46
58
  }
47
59
  async text() {
48
60
  return await (0, utils_2.withTeardown)((async () => {
49
- await this.#onStart();
61
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
50
62
  try {
51
- return await this.#ogResponse.text();
63
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").text();
52
64
  }
53
65
  finally {
54
- await this.#onFinish();
66
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
55
67
  }
56
- })(), this.#teardownRef);
68
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
57
69
  }
58
70
  async arrayBuffer() {
59
71
  return await (0, utils_2.withTeardown)((async () => {
60
- await this.#onStart();
72
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
61
73
  try {
62
- return await this.#ogResponse.arrayBuffer();
74
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").arrayBuffer();
63
75
  }
64
76
  finally {
65
- await this.#onFinish();
77
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
66
78
  }
67
- })(), this.#teardownRef);
79
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
68
80
  }
69
81
  async blob() {
70
82
  return await (0, utils_2.withTeardown)((async () => {
71
- await this.#onStart();
83
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
72
84
  try {
73
- return await this.#ogResponse.blob();
85
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").blob();
74
86
  }
75
87
  finally {
76
- await this.#onFinish();
88
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
77
89
  }
78
- })(), this.#teardownRef);
90
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
79
91
  }
80
92
  clone() {
81
- const newResponse = this.#ogResponse.clone();
82
- return new ResponseWrapper(newResponse, this.#teardownRef, this.#onStart, this.#onFinish);
93
+ const newResponse = __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").clone();
94
+ return new ResponseWrapper(newResponse, __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"), __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f"), __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f"));
83
95
  }
84
96
  async formData() {
85
97
  return await (0, utils_2.withTeardown)((async () => {
86
- await this.#onStart();
98
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
87
99
  try {
88
- return await this.#ogResponse.formData();
100
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").formData();
89
101
  }
90
102
  finally {
91
- await this.#onFinish();
103
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
92
104
  }
93
- })(), this.#teardownRef);
105
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
94
106
  }
95
107
  async json() {
96
108
  return await (0, utils_2.withTeardown)((async () => {
97
- await this.#onStart();
109
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
98
110
  try {
99
- return await this.#ogResponse.json();
111
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").json();
100
112
  }
101
113
  finally {
102
- await this.#onFinish();
114
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
103
115
  }
104
- })(), this.#teardownRef);
116
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
105
117
  }
106
118
  }
119
+ _ResponseWrapper_teardownRef = new WeakMap(), _ResponseWrapper_ogResponse = new WeakMap(), _ResponseWrapper_onStart = new WeakMap(), _ResponseWrapper_onFinish = new WeakMap();
107
120
  /**
108
121
  * Create a network endowment, consisting of a `fetch` function.
109
122
  * This allows us to provide a teardown function, so that we can cancel
@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CAAC,MAAM,CAAC,kBAAkB,CAAC,CACjD,CAAC;YACJ,CAAC;YACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,CAAC,EAAE,EACJ,WAAW,CACZ,CAAC;IACJ,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;QAClC,WAAW,CAAC,YAAY,IAAI,CAAC,CAAC;QAC9B,MAAM,QAAQ,GAAoB,EAAE,CAAC;QACrC,eAAe,CAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QACjE,eAAe,CAAC,KAAK,EAAE,CAAC;QACxB,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC,CAAC;IAEF,OAAO;QACL,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QACrB,4EAA4E;QAC5E,gEAAgE;QAChE,yFAAyF;QACzF,uEAAuE;QACvE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC;QACxB,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC;QACxB,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC;QAC1B,gBAAgB;KACjB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,CAAU;IAC3D,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { assert } from '@metamask/utils';\n\nimport { withTeardown } from '../utils';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n #onStart: () => Promise<void>;\n\n #onFinish: () => Promise<void>;\n\n constructor(\n ogResponse: Response,\n teardownRef: { lastTeardown: number },\n onStart: () => Promise<void>,\n onFinish: () => Promise<void>,\n ) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n this.#onStart = onStart;\n this.#onFinish = onFinish;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return await withTeardown<string>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.text();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return await withTeardown<ArrayBuffer>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.arrayBuffer();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async blob(): Promise<Blob> {\n return await withTeardown<Blob>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.blob();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(\n newResponse,\n this.#teardownRef,\n this.#onStart,\n this.#onFinish,\n );\n }\n\n async formData(): Promise<FormData> {\n return await withTeardown<FormData>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.formData();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async json(): Promise<any> {\n return await withTeardown(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.json();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @param options - An options bag.\n * @param options.notify - A reference to the notify function of the snap executor.\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = ({ notify }: EndowmentFactoryOptions = {}) => {\n assert(notify, 'Notify must be passed to network endowment factory');\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let started = false;\n const onStart = async () => {\n if (!started) {\n started = true;\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n }\n };\n\n let finished = false;\n const onFinish = async () => {\n if (!finished) {\n finished = true;\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n };\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n return await withTeardown(\n (async () => {\n try {\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await fetchPromise,\n teardownRef,\n onStart,\n onFinish,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n })(),\n teardownRef,\n );\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n // Request, Headers and Response are the endowments injected alongside fetch\n // only when 'endowment:network-access' permission is requested,\n // therefore these are hardened as part of fetch dependency injection within its factory.\n // These endowments are not (and should never be) available by default.\n Request: harden(Request),\n Headers: harden(Headers),\n Response: harden(Response),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'Request', 'Headers', 'Response'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"]}
1
+ {"version":3,"file":"network.cjs","sourceRoot":"","sources":["../../../src/common/endowments/network.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,2CAAyC;AAEzC,wCAAwC;AAGxC;;;GAGG;AACH,MAAM,eAAe;IASnB,YACE,UAAoB,EACpB,WAAqC,EACrC,OAA4B,EAC5B,QAA6B;QAZtB,+CAAuC;QAEhD,8CAAsB;QAEtB,2CAA8B;QAE9B,4CAA+B;QAQ7B,uBAAA,IAAI,+BAAe,UAAU,MAAA,CAAC;QAC9B,uBAAA,IAAI,gCAA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,CAAC;IAEF,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;QAClC,WAAW,CAAC,YAAY,IAAI,CAAC,CAAC;QAC9B,MAAM,QAAQ,GAAoB,EAAE,CAAC;QACrC,eAAe,CAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QACjE,eAAe,CAAC,KAAK,EAAE,CAAC;QACxB,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC,CAAC;IAEF,OAAO;QACL,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QACrB,4EAA4E;QAC5E,gEAAgE;QAChE,yFAAyF;QACzF,uEAAuE;QACvE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC;QACxB,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC;QACxB,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC;QAC1B,gBAAgB;KACjB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,CAAU;IAC3D,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,kBAAe,eAAe,CAAC","sourcesContent":["import { assert } from '@metamask/utils';\n\nimport { withTeardown } from '../utils';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n #onStart: () => Promise<void>;\n\n #onFinish: () => Promise<void>;\n\n constructor(\n ogResponse: Response,\n teardownRef: { lastTeardown: number },\n onStart: () => Promise<void>,\n onFinish: () => Promise<void>,\n ) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n this.#onStart = onStart;\n this.#onFinish = onFinish;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return await withTeardown<string>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.text();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return await withTeardown<ArrayBuffer>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.arrayBuffer();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async blob(): Promise<Blob> {\n return await withTeardown<Blob>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.blob();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(\n newResponse,\n this.#teardownRef,\n this.#onStart,\n this.#onFinish,\n );\n }\n\n async formData(): Promise<FormData> {\n return await withTeardown<FormData>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.formData();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async json(): Promise<any> {\n return await withTeardown(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.json();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @param options - An options bag.\n * @param options.notify - A reference to the notify function of the snap executor.\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = ({ notify }: EndowmentFactoryOptions = {}) => {\n assert(notify, 'Notify must be passed to network endowment factory');\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let started = false;\n const onStart = async () => {\n if (!started) {\n started = true;\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n }\n };\n\n let finished = false;\n const onFinish = async () => {\n if (!finished) {\n finished = true;\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n };\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n return await withTeardown(\n (async () => {\n try {\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await fetchPromise,\n teardownRef,\n onStart,\n onFinish,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n })(),\n teardownRef,\n );\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n // Request, Headers and Response are the endowments injected alongside fetch\n // only when 'endowment:network-access' permission is requested,\n // therefore these are hardened as part of fetch dependency injection within its factory.\n // These endowments are not (and should never be) available by default.\n Request: harden(Request),\n Headers: harden(Headers),\n Response: harden(Response),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'Request', 'Headers', 'Response'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"]}
@@ -1,3 +1,15 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _ResponseWrapper_teardownRef, _ResponseWrapper_ogResponse, _ResponseWrapper_onStart, _ResponseWrapper_onFinish;
1
13
  import { assert } from "@metamask/utils";
2
14
  import { withTeardown } from "../utils.mjs";
3
15
  /**
@@ -5,103 +17,104 @@ import { withTeardown } from "../utils.mjs";
5
17
  * That way, a teardown process can stop any processes left.
6
18
  */
7
19
  class ResponseWrapper {
8
- #teardownRef;
9
- #ogResponse;
10
- #onStart;
11
- #onFinish;
12
20
  constructor(ogResponse, teardownRef, onStart, onFinish) {
13
- this.#ogResponse = ogResponse;
14
- this.#teardownRef = teardownRef;
15
- this.#onStart = onStart;
16
- this.#onFinish = onFinish;
21
+ _ResponseWrapper_teardownRef.set(this, void 0);
22
+ _ResponseWrapper_ogResponse.set(this, void 0);
23
+ _ResponseWrapper_onStart.set(this, void 0);
24
+ _ResponseWrapper_onFinish.set(this, void 0);
25
+ __classPrivateFieldSet(this, _ResponseWrapper_ogResponse, ogResponse, "f");
26
+ __classPrivateFieldSet(this, _ResponseWrapper_teardownRef, teardownRef, "f");
27
+ __classPrivateFieldSet(this, _ResponseWrapper_onStart, onStart, "f");
28
+ __classPrivateFieldSet(this, _ResponseWrapper_onFinish, onFinish, "f");
17
29
  }
18
30
  get body() {
19
- return this.#ogResponse.body;
31
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").body;
20
32
  }
21
33
  get bodyUsed() {
22
- return this.#ogResponse.bodyUsed;
34
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").bodyUsed;
23
35
  }
24
36
  get headers() {
25
- return this.#ogResponse.headers;
37
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").headers;
26
38
  }
27
39
  get ok() {
28
- return this.#ogResponse.ok;
40
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").ok;
29
41
  }
30
42
  get redirected() {
31
- return this.#ogResponse.redirected;
43
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").redirected;
32
44
  }
33
45
  get status() {
34
- return this.#ogResponse.status;
46
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").status;
35
47
  }
36
48
  get statusText() {
37
- return this.#ogResponse.statusText;
49
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").statusText;
38
50
  }
39
51
  get type() {
40
- return this.#ogResponse.type;
52
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").type;
41
53
  }
42
54
  get url() {
43
- return this.#ogResponse.url;
55
+ return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").url;
44
56
  }
45
57
  async text() {
46
58
  return await withTeardown((async () => {
47
- await this.#onStart();
59
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
48
60
  try {
49
- return await this.#ogResponse.text();
61
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").text();
50
62
  }
51
63
  finally {
52
- await this.#onFinish();
64
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
53
65
  }
54
- })(), this.#teardownRef);
66
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
55
67
  }
56
68
  async arrayBuffer() {
57
69
  return await withTeardown((async () => {
58
- await this.#onStart();
70
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
59
71
  try {
60
- return await this.#ogResponse.arrayBuffer();
72
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").arrayBuffer();
61
73
  }
62
74
  finally {
63
- await this.#onFinish();
75
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
64
76
  }
65
- })(), this.#teardownRef);
77
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
66
78
  }
67
79
  async blob() {
68
80
  return await withTeardown((async () => {
69
- await this.#onStart();
81
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
70
82
  try {
71
- return await this.#ogResponse.blob();
83
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").blob();
72
84
  }
73
85
  finally {
74
- await this.#onFinish();
86
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
75
87
  }
76
- })(), this.#teardownRef);
88
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
77
89
  }
78
90
  clone() {
79
- const newResponse = this.#ogResponse.clone();
80
- return new ResponseWrapper(newResponse, this.#teardownRef, this.#onStart, this.#onFinish);
91
+ const newResponse = __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").clone();
92
+ return new ResponseWrapper(newResponse, __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"), __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f"), __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f"));
81
93
  }
82
94
  async formData() {
83
95
  return await withTeardown((async () => {
84
- await this.#onStart();
96
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
85
97
  try {
86
- return await this.#ogResponse.formData();
98
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").formData();
87
99
  }
88
100
  finally {
89
- await this.#onFinish();
101
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
90
102
  }
91
- })(), this.#teardownRef);
103
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
92
104
  }
93
105
  async json() {
94
106
  return await withTeardown((async () => {
95
- await this.#onStart();
107
+ await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
96
108
  try {
97
- return await this.#ogResponse.json();
109
+ return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").json();
98
110
  }
99
111
  finally {
100
- await this.#onFinish();
112
+ await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
101
113
  }
102
- })(), this.#teardownRef);
114
+ })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
103
115
  }
104
116
  }
117
+ _ResponseWrapper_teardownRef = new WeakMap(), _ResponseWrapper_ogResponse = new WeakMap(), _ResponseWrapper_onStart = new WeakMap(), _ResponseWrapper_onFinish = new WeakMap();
105
118
  /**
106
119
  * Create a network endowment, consisting of a `fetch` function.
107
120
  * This allows us to provide a teardown function, so that we can cancel
@@ -1 +1 @@
1
- {"version":3,"file":"network.mjs","sourceRoot":"","sources":["../../../src/common/endowments/network.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,wBAAwB;AAEzC,OAAO,EAAE,YAAY,EAAE,qBAAiB;AAGxC;;;GAGG;AACH,MAAM,eAAe;IACV,YAAY,CAA2B;IAEhD,WAAW,CAAW;IAEtB,QAAQ,CAAsB;IAE9B,SAAS,CAAsB;IAE/B,YACE,UAAoB,EACpB,WAAqC,EACrC,OAA4B,EAC5B,QAA6B;QAE7B,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,CAAC,YAAY,GAAG,WAAW,CAAC;QAChC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC;QACxB,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;IAC5B,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,WAAW,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC;IAClC,CAAC;IAED,IAAI,EAAE;QACJ,OAAO,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC;IACrC,CAAC;IAED,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC;IACjC,CAAC;IAED,IAA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utils';\n\nimport { withTeardown } from '../utils';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n #onStart: () => Promise<void>;\n\n #onFinish: () => Promise<void>;\n\n constructor(\n ogResponse: Response,\n teardownRef: { lastTeardown: number },\n onStart: () => Promise<void>,\n onFinish: () => Promise<void>,\n ) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n this.#onStart = onStart;\n this.#onFinish = onFinish;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return await withTeardown<string>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.text();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return await withTeardown<ArrayBuffer>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.arrayBuffer();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async blob(): Promise<Blob> {\n return await withTeardown<Blob>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.blob();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(\n newResponse,\n this.#teardownRef,\n this.#onStart,\n this.#onFinish,\n );\n }\n\n async formData(): Promise<FormData> {\n return await withTeardown<FormData>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.formData();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async json(): Promise<any> {\n return await withTeardown(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.json();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @param options - An options bag.\n * @param options.notify - A reference to the notify function of the snap executor.\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = ({ notify }: EndowmentFactoryOptions = {}) => {\n assert(notify, 'Notify must be passed to network endowment factory');\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let started = false;\n const onStart = async () => {\n if (!started) {\n started = true;\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n }\n };\n\n let finished = false;\n const onFinish = async () => {\n if (!finished) {\n finished = true;\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n };\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n return await withTeardown(\n (async () => {\n try {\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await fetchPromise,\n teardownRef,\n onStart,\n onFinish,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n })(),\n teardownRef,\n );\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n // Request, Headers and Response are the endowments injected alongside fetch\n // only when 'endowment:network-access' permission is requested,\n // therefore these are hardened as part of fetch dependency injection within its factory.\n // These endowments are not (and should never be) available by default.\n Request: harden(Request),\n Headers: harden(Headers),\n Response: harden(Response),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'Request', 'Headers', 'Response'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"]}
1
+ {"version":3,"file":"network.mjs","sourceRoot":"","sources":["../../../src/common/endowments/network.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM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AAQ,CACd,GAAG,CAAC,IAAI;gBACR,2FAA2F;gBAC3F,GAAG,EAAE,CAAC,eAAe,CAAC,MAAM,CAAC,kBAAkB,CAAC,CACjD,CAAC;YACJ,CAAC;YACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;QACrB,CAAC,CAAC,EAAE,EACJ,WAAW,CACZ,CAAC;IACJ,CAAC,CAAC;IAEF,MAAM,gBAAgB,GAAG,KAAK,IAAI,EAAE;QAClC,WAAW,CAAC,YAAY,IAAI,CAAC,CAAC;QAC9B,MAAM,QAAQ,GAAoB,EAAE,CAAC;QACrC,eAAe,CAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QACjE,eAAe,CAAC,KAAK,EAAE,CAAC;QACxB,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC9B,CAAC,CAAC;IAEF,OAAO;QACL,KAAK,EAAE,MAAM,CAAC,MAAM,CAAC;QACrB,4EAA4E;QAC5E,gEAAgE;QAChE,yFAAyF;QACzF,uEAAuE;QACvE,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC;QACxB,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC;QACxB,QAAQ,EAAE,MAAM,CAAC,QAAQ,CAAC;QAC1B,gBAAgB;KACjB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,eAAe,GAAG;IACtB,KAAK,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,CAAU;IAC3D,OAAO,EAAE,aAAa;CACvB,CAAC;AACF,eAAe,eAAe,CAAC","sourcesContent":["import { assert } from '@metamask/utils';\n\nimport { withTeardown } from '../utils';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\n/**\n * This class wraps a Response object.\n * That way, a teardown process can stop any processes left.\n */\nclass ResponseWrapper implements Response {\n readonly #teardownRef: { lastTeardown: number };\n\n #ogResponse: Response;\n\n #onStart: () => Promise<void>;\n\n #onFinish: () => Promise<void>;\n\n constructor(\n ogResponse: Response,\n teardownRef: { lastTeardown: number },\n onStart: () => Promise<void>,\n onFinish: () => Promise<void>,\n ) {\n this.#ogResponse = ogResponse;\n this.#teardownRef = teardownRef;\n this.#onStart = onStart;\n this.#onFinish = onFinish;\n }\n\n get body(): ReadableStream<Uint8Array> | null {\n return this.#ogResponse.body;\n }\n\n get bodyUsed() {\n return this.#ogResponse.bodyUsed;\n }\n\n get headers() {\n return this.#ogResponse.headers;\n }\n\n get ok() {\n return this.#ogResponse.ok;\n }\n\n get redirected() {\n return this.#ogResponse.redirected;\n }\n\n get status() {\n return this.#ogResponse.status;\n }\n\n get statusText() {\n return this.#ogResponse.statusText;\n }\n\n get type() {\n return this.#ogResponse.type;\n }\n\n get url() {\n return this.#ogResponse.url;\n }\n\n async text() {\n return await withTeardown<string>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.text();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async arrayBuffer(): Promise<ArrayBuffer> {\n return await withTeardown<ArrayBuffer>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.arrayBuffer();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async blob(): Promise<Blob> {\n return await withTeardown<Blob>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.blob();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n clone(): Response {\n const newResponse = this.#ogResponse.clone();\n return new ResponseWrapper(\n newResponse,\n this.#teardownRef,\n this.#onStart,\n this.#onFinish,\n );\n }\n\n async formData(): Promise<FormData> {\n return await withTeardown<FormData>(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.formData();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n\n async json(): Promise<any> {\n return await withTeardown(\n (async () => {\n await this.#onStart();\n try {\n return await this.#ogResponse.json();\n } finally {\n await this.#onFinish();\n }\n })(),\n this.#teardownRef,\n );\n }\n}\n\n/**\n * Create a network endowment, consisting of a `fetch` function.\n * This allows us to provide a teardown function, so that we can cancel\n * any pending requests, connections, streams, etc. that may be open when a snap\n * is terminated.\n *\n * This wraps the original implementation of `fetch`,\n * to ensure that a bad actor cannot get access to the original function, thus\n * potentially preventing the network requests from being torn down.\n *\n * @param options - An options bag.\n * @param options.notify - A reference to the notify function of the snap executor.\n * @returns An object containing a wrapped `fetch`\n * function, as well as a teardown function.\n */\nconst createNetwork = ({ notify }: EndowmentFactoryOptions = {}) => {\n assert(notify, 'Notify must be passed to network endowment factory');\n // Open fetch calls or open body streams\n const openConnections = new Set<{ cancel: () => Promise<void> }>();\n // Track last teardown count\n const teardownRef = { lastTeardown: 0 };\n\n // Remove items from openConnections after they were garbage collected\n const cleanup = new FinalizationRegistry<() => void>(\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n (callback) => callback(),\n );\n\n const _fetch: typeof fetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n const abortController = new AbortController();\n if (init?.signal !== null && init?.signal !== undefined) {\n const originalSignal = init.signal;\n // Merge abort controllers\n originalSignal.addEventListener(\n 'abort',\n () => {\n abortController.abort((originalSignal as any).reason);\n },\n { once: true },\n );\n }\n\n let started = false;\n const onStart = async () => {\n if (!started) {\n started = true;\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n }\n };\n\n let finished = false;\n const onFinish = async () => {\n if (!finished) {\n finished = true;\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n };\n\n let res: Response;\n let openFetchConnection: { cancel: () => Promise<void> } | undefined;\n return await withTeardown(\n (async () => {\n try {\n await notify({\n method: 'OutboundRequest',\n params: { source: 'fetch' },\n });\n const fetchPromise = fetch(input, {\n ...init,\n signal: abortController.signal,\n });\n\n openFetchConnection = {\n cancel: async () => {\n abortController.abort();\n try {\n await fetchPromise;\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openFetchConnection);\n\n res = new ResponseWrapper(\n await fetchPromise,\n teardownRef,\n onStart,\n onFinish,\n );\n } finally {\n if (openFetchConnection !== undefined) {\n openConnections.delete(openFetchConnection);\n }\n await notify({\n method: 'OutboundResponse',\n params: { source: 'fetch' },\n });\n }\n\n if (res.body !== null) {\n const body = new WeakRef<ReadableStream>(res.body);\n\n const openBodyConnection = {\n cancel:\n /* istanbul ignore next: see it.todo('can be torn down during body read') test */\n async () => {\n try {\n await body.deref()?.cancel();\n } catch {\n /* do nothing */\n }\n },\n };\n openConnections.add(openBodyConnection);\n cleanup.register(\n res.body,\n /* istanbul ignore next: can't test garbage collection without modifying node parameters */\n () => openConnections.delete(openBodyConnection),\n );\n }\n return harden(res);\n })(),\n teardownRef,\n );\n };\n\n const teardownFunction = async () => {\n teardownRef.lastTeardown += 1;\n const promises: Promise<void>[] = [];\n openConnections.forEach(({ cancel }) => promises.push(cancel()));\n openConnections.clear();\n await Promise.all(promises);\n };\n\n return {\n fetch: harden(_fetch),\n // Request, Headers and Response are the endowments injected alongside fetch\n // only when 'endowment:network-access' permission is requested,\n // therefore these are hardened as part of fetch dependency injection within its factory.\n // These endowments are not (and should never be) available by default.\n Request: harden(Request),\n Headers: harden(Headers),\n Response: harden(Response),\n teardownFunction,\n };\n};\n\nconst endowmentModule = {\n names: ['fetch', 'Request', 'Headers', 'Response'] as const,\n factory: createNetwork,\n};\nexport default endowmentModule;\n"]}