@metamask/snaps-execution-environments 6.7.2 → 6.8.0

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.
@@ -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,SAA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D,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
+ {"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,E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CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;YAC5C,8CAA8C;YAC9C,oEAAoE;YACpE,uCAAuC;YACvC,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,WAAW,CAAC,CAAC,CAAC;QACvD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,gBAAgB,CAAC,KAAK,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,16 +1,4 @@
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;
14
2
  Object.defineProperty(exports, "__esModule", { value: true });
15
3
  const utils_1 = require("@metamask/utils");
16
4
  const utils_2 = require("../utils.cjs");
@@ -19,104 +7,103 @@ const utils_2 = require("../utils.cjs");
19
7
  * That way, a teardown process can stop any processes left.
20
8
  */
21
9
  class ResponseWrapper {
10
+ #teardownRef;
11
+ #ogResponse;
12
+ #onStart;
13
+ #onFinish;
22
14
  constructor(ogResponse, teardownRef, onStart, 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");
15
+ this.#ogResponse = ogResponse;
16
+ this.#teardownRef = teardownRef;
17
+ this.#onStart = onStart;
18
+ this.#onFinish = onFinish;
31
19
  }
32
20
  get body() {
33
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").body;
21
+ return this.#ogResponse.body;
34
22
  }
35
23
  get bodyUsed() {
36
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").bodyUsed;
24
+ return this.#ogResponse.bodyUsed;
37
25
  }
38
26
  get headers() {
39
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").headers;
27
+ return this.#ogResponse.headers;
40
28
  }
41
29
  get ok() {
42
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").ok;
30
+ return this.#ogResponse.ok;
43
31
  }
44
32
  get redirected() {
45
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").redirected;
33
+ return this.#ogResponse.redirected;
46
34
  }
47
35
  get status() {
48
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").status;
36
+ return this.#ogResponse.status;
49
37
  }
50
38
  get statusText() {
51
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").statusText;
39
+ return this.#ogResponse.statusText;
52
40
  }
53
41
  get type() {
54
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").type;
42
+ return this.#ogResponse.type;
55
43
  }
56
44
  get url() {
57
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").url;
45
+ return this.#ogResponse.url;
58
46
  }
59
47
  async text() {
60
48
  return await (0, utils_2.withTeardown)((async () => {
61
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
49
+ await this.#onStart();
62
50
  try {
63
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").text();
51
+ return await this.#ogResponse.text();
64
52
  }
65
53
  finally {
66
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
54
+ await this.#onFinish();
67
55
  }
68
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
56
+ })(), this.#teardownRef);
69
57
  }
70
58
  async arrayBuffer() {
71
59
  return await (0, utils_2.withTeardown)((async () => {
72
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
60
+ await this.#onStart();
73
61
  try {
74
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").arrayBuffer();
62
+ return await this.#ogResponse.arrayBuffer();
75
63
  }
76
64
  finally {
77
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
65
+ await this.#onFinish();
78
66
  }
79
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
67
+ })(), this.#teardownRef);
80
68
  }
81
69
  async blob() {
82
70
  return await (0, utils_2.withTeardown)((async () => {
83
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
71
+ await this.#onStart();
84
72
  try {
85
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").blob();
73
+ return await this.#ogResponse.blob();
86
74
  }
87
75
  finally {
88
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
76
+ await this.#onFinish();
89
77
  }
90
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
78
+ })(), this.#teardownRef);
91
79
  }
92
80
  clone() {
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"));
81
+ const newResponse = this.#ogResponse.clone();
82
+ return new ResponseWrapper(newResponse, this.#teardownRef, this.#onStart, this.#onFinish);
95
83
  }
96
84
  async formData() {
97
85
  return await (0, utils_2.withTeardown)((async () => {
98
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
86
+ await this.#onStart();
99
87
  try {
100
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").formData();
88
+ return await this.#ogResponse.formData();
101
89
  }
102
90
  finally {
103
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
91
+ await this.#onFinish();
104
92
  }
105
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
93
+ })(), this.#teardownRef);
106
94
  }
107
95
  async json() {
108
96
  return await (0, utils_2.withTeardown)((async () => {
109
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
97
+ await this.#onStart();
110
98
  try {
111
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").json();
99
+ return await this.#ogResponse.json();
112
100
  }
113
101
  finally {
114
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
102
+ await this.#onFinish();
115
103
  }
116
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
104
+ })(), this.#teardownRef);
117
105
  }
118
106
  }
119
- _ResponseWrapper_teardownRef = new WeakMap(), _ResponseWrapper_ogResponse = new WeakMap(), _ResponseWrapper_onStart = new WeakMap(), _ResponseWrapper_onFinish = new WeakMap();
120
107
  /**
121
108
  * Create a network endowment, consisting of a `fetch` function.
122
109
  * This allows us to provide a teardown function, so that we can cancel
@@ -1 +1 @@
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,gCAAgB,WAAW,MAAA,CAAC;QAChC,uBAAA,IAAI,4BAAY,OAAO,MAAA,CAAC;QACxB,uBAAA,IAAI,6BAAa,QAAQ,MAAA,CAAC;IAC5B,CAAC;IAED,IAAI,IAAI;QACN,OAAO,uBAAA,IAAI,mCAAY,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,uBAAA,IAAI,mCAAY,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,uBAAA,IAAI,mCAAY,CAAC,OAAO,CAAC;IAClC,CAAC;IAED,IAAI,EAAE;QACJ,OAAO,uBAAA,IAAI,mCAAY,CAAC,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,uBAAA,IAAI,mCAAY,CAAC,UAAU,CAAC;IACrC,CAAC;IAED,IAAI,MAAM;QACR,OAAO,uBAAA,IAAI,mCAAY,CAAC,MAAM,CAAC;IACjC,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,uBAAA,IAAI,mCAAY,CAAC,UAAU,CAAC;IACrC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,uBAAA,IAAI,mCAAY,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,IAAI,GAAG;QACL,OAAO,uBAAA,IAAI,mCAAY,CAAC,GAAG,CAAC;IAC9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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,wCAA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C,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,15 +1,3 @@
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;
13
1
  import { assert } from "@metamask/utils";
14
2
  import { withTeardown } from "../utils.mjs";
15
3
  /**
@@ -17,104 +5,103 @@ import { withTeardown } from "../utils.mjs";
17
5
  * That way, a teardown process can stop any processes left.
18
6
  */
19
7
  class ResponseWrapper {
8
+ #teardownRef;
9
+ #ogResponse;
10
+ #onStart;
11
+ #onFinish;
20
12
  constructor(ogResponse, teardownRef, onStart, 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");
13
+ this.#ogResponse = ogResponse;
14
+ this.#teardownRef = teardownRef;
15
+ this.#onStart = onStart;
16
+ this.#onFinish = onFinish;
29
17
  }
30
18
  get body() {
31
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").body;
19
+ return this.#ogResponse.body;
32
20
  }
33
21
  get bodyUsed() {
34
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").bodyUsed;
22
+ return this.#ogResponse.bodyUsed;
35
23
  }
36
24
  get headers() {
37
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").headers;
25
+ return this.#ogResponse.headers;
38
26
  }
39
27
  get ok() {
40
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").ok;
28
+ return this.#ogResponse.ok;
41
29
  }
42
30
  get redirected() {
43
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").redirected;
31
+ return this.#ogResponse.redirected;
44
32
  }
45
33
  get status() {
46
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").status;
34
+ return this.#ogResponse.status;
47
35
  }
48
36
  get statusText() {
49
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").statusText;
37
+ return this.#ogResponse.statusText;
50
38
  }
51
39
  get type() {
52
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").type;
40
+ return this.#ogResponse.type;
53
41
  }
54
42
  get url() {
55
- return __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").url;
43
+ return this.#ogResponse.url;
56
44
  }
57
45
  async text() {
58
46
  return await withTeardown((async () => {
59
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
47
+ await this.#onStart();
60
48
  try {
61
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").text();
49
+ return await this.#ogResponse.text();
62
50
  }
63
51
  finally {
64
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
52
+ await this.#onFinish();
65
53
  }
66
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
54
+ })(), this.#teardownRef);
67
55
  }
68
56
  async arrayBuffer() {
69
57
  return await withTeardown((async () => {
70
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
58
+ await this.#onStart();
71
59
  try {
72
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").arrayBuffer();
60
+ return await this.#ogResponse.arrayBuffer();
73
61
  }
74
62
  finally {
75
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
63
+ await this.#onFinish();
76
64
  }
77
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
65
+ })(), this.#teardownRef);
78
66
  }
79
67
  async blob() {
80
68
  return await withTeardown((async () => {
81
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
69
+ await this.#onStart();
82
70
  try {
83
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").blob();
71
+ return await this.#ogResponse.blob();
84
72
  }
85
73
  finally {
86
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
74
+ await this.#onFinish();
87
75
  }
88
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
76
+ })(), this.#teardownRef);
89
77
  }
90
78
  clone() {
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"));
79
+ const newResponse = this.#ogResponse.clone();
80
+ return new ResponseWrapper(newResponse, this.#teardownRef, this.#onStart, this.#onFinish);
93
81
  }
94
82
  async formData() {
95
83
  return await withTeardown((async () => {
96
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
84
+ await this.#onStart();
97
85
  try {
98
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").formData();
86
+ return await this.#ogResponse.formData();
99
87
  }
100
88
  finally {
101
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
89
+ await this.#onFinish();
102
90
  }
103
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
91
+ })(), this.#teardownRef);
104
92
  }
105
93
  async json() {
106
94
  return await withTeardown((async () => {
107
- await __classPrivateFieldGet(this, _ResponseWrapper_onStart, "f").call(this);
95
+ await this.#onStart();
108
96
  try {
109
- return await __classPrivateFieldGet(this, _ResponseWrapper_ogResponse, "f").json();
97
+ return await this.#ogResponse.json();
110
98
  }
111
99
  finally {
112
- await __classPrivateFieldGet(this, _ResponseWrapper_onFinish, "f").call(this);
100
+ await this.#onFinish();
113
101
  }
114
- })(), __classPrivateFieldGet(this, _ResponseWrapper_teardownRef, "f"));
102
+ })(), this.#teardownRef);
115
103
  }
116
104
  }
117
- _ResponseWrapper_teardownRef = new WeakMap(), _ResponseWrapper_ogResponse = new WeakMap(), _ResponseWrapper_onStart = new WeakMap(), _ResponseWrapper_onFinish = new WeakMap();
118
105
  /**
119
106
  * Create a network endowment, consisting of a `fetch` function.
120
107
  * 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;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,gCAAgB,WAAW,MAAA,CAAC;QAChC,uBAAA,IAAI,4BAAY,OAAO,MAAA,CAAC;QACxB,uBAAA,IAAI,6BAAa,QAAQ,MAAA,CAAC;IAC5B,CAAC;IAED,IAAI,IAAI;QACN,OAAO,uBAAA,IAAI,mCAAY,CAAC,IAAI,CAAC;IAC/B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,uBAAA,IAAI,mCAAY,CAAC,QAAQ,CAAC;IACnC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,uBAAA,IAAI,mCAAY,CAAC,OAAO,CAAC;IAClC,CAAC;IAED,IAAI,EAAE;QACJ,OAAO,uBAAA,IAAI,mCAAY,CAAC,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,uBAAA,IAAI,mCAAY,CAAC,UAAU,CAAC;IACrC,CAAC;IAED,IAAI,MAAM;QACR,OAAO,uBAAA,IAA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;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"]}
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,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC;IACrC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;I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,CAAC;gBACxC,OAAO,CAAC,QAAQ,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"]}