@metamask/snaps-execution-environments 3.1.0 → 3.3.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.
@@ -13,6 +13,7 @@ Object.defineProperty(exports, "BaseSnapExecutor", {
13
13
  const _jsonrpcengine = require("@metamask/json-rpc-engine");
14
14
  const _providers = require("@metamask/providers");
15
15
  const _rpcerrors = require("@metamask/rpc-errors");
16
+ const _snapssdk = require("@metamask/snaps-sdk");
16
17
  const _snapsutils = require("@metamask/snaps-utils");
17
18
  const _utils = require("@metamask/utils");
18
19
  const _superstruct = require("superstruct");
@@ -23,6 +24,21 @@ const _globalEvents = require("./globalEvents");
23
24
  const _sortParams = require("./sortParams");
24
25
  const _utils1 = require("./utils");
25
26
  const _validation = require("./validation");
27
+ function _check_private_redeclaration(obj, privateCollection) {
28
+ if (privateCollection.has(obj)) {
29
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
30
+ }
31
+ }
32
+ function _class_private_method_get(receiver, privateSet, fn) {
33
+ if (!privateSet.has(receiver)) {
34
+ throw new TypeError("attempted to get private field on non-instance");
35
+ }
36
+ return fn;
37
+ }
38
+ function _class_private_method_init(obj, privateSet) {
39
+ _check_private_redeclaration(obj, privateSet);
40
+ privateSet.add(obj);
41
+ }
26
42
  function _define_property(obj, key, value) {
27
43
  if (key in obj) {
28
44
  Object.defineProperty(obj, key, {
@@ -74,14 +90,15 @@ const unhandledError = _rpcerrors.rpcErrors.internal({
74
90
  ]
75
91
  }
76
92
  };
93
+ var _write = /*#__PURE__*/ new WeakSet(), _notify = /*#__PURE__*/ new WeakSet(), _respond = /*#__PURE__*/ new WeakSet();
77
94
  class BaseSnapExecutor {
78
95
  errorHandler(error, data) {
79
96
  const serializedError = (0, _rpcerrors.serializeError)(error, {
80
97
  fallbackError: unhandledError,
81
98
  shouldIncludeStack: false
82
99
  });
83
- const errorData = (0, _snapsutils.getErrorData)(serializedError);
84
- this.notify({
100
+ const errorData = (0, _snapssdk.getErrorData)(serializedError);
101
+ _class_private_method_get(this, _notify, notify).call(this, {
85
102
  method: 'UnhandledError',
86
103
  params: {
87
104
  error: {
@@ -92,6 +109,8 @@ class BaseSnapExecutor {
92
109
  }
93
110
  }
94
111
  }
112
+ }).catch((notifyError)=>{
113
+ (0, _snapsutils.logError)(notifyError);
95
114
  });
96
115
  }
97
116
  async onCommandRequest(message) {
@@ -103,7 +122,7 @@ class BaseSnapExecutor {
103
122
  }
104
123
  const { id, method, params } = message;
105
124
  if (!(0, _utils.hasProperty)(EXECUTION_ENVIRONMENT_METHODS, method)) {
106
- this.respond(id, {
125
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
107
126
  error: _rpcerrors.rpcErrors.methodNotFound({
108
127
  data: {
109
128
  method
@@ -117,7 +136,7 @@ class BaseSnapExecutor {
117
136
  const paramsAsArray = (0, _sortParams.sortParamKeys)(methodObject.params, params);
118
137
  const [error] = (0, _superstruct.validate)(paramsAsArray, methodObject.struct);
119
138
  if (error) {
120
- this.respond(id, {
139
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
121
140
  error: _rpcerrors.rpcErrors.invalidParams({
122
141
  message: `Invalid parameters for method "${method}": ${error.message}.`,
123
142
  data: {
@@ -130,43 +149,17 @@ class BaseSnapExecutor {
130
149
  }
131
150
  try {
132
151
  const result = await this.methods[method](...paramsAsArray);
133
- this.respond(id, {
152
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
134
153
  result
135
154
  });
136
155
  } catch (rpcError) {
137
- this.respond(id, {
156
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
138
157
  error: (0, _rpcerrors.serializeError)(rpcError, {
139
158
  fallbackError
140
159
  })
141
160
  });
142
161
  }
143
162
  }
144
- notify(requestObject) {
145
- if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
146
- throw _rpcerrors.rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
147
- }
148
- this.commandStream.write({
149
- ...requestObject,
150
- jsonrpc: '2.0'
151
- });
152
- }
153
- respond(id, requestObject) {
154
- if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
155
- // Instead of throwing, we directly respond with an error.
156
- // This prevents an issue where we wouldn't respond when errors were non-serializable
157
- this.commandStream.write({
158
- error: (0, _rpcerrors.serializeError)(_rpcerrors.rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
159
- id,
160
- jsonrpc: '2.0'
161
- });
162
- return;
163
- }
164
- this.commandStream.write({
165
- ...requestObject,
166
- id,
167
- jsonrpc: '2.0'
168
- });
169
- }
170
163
  /**
171
164
  * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw
172
165
  * on errors.
@@ -282,16 +275,18 @@ class BaseSnapExecutor {
282
275
  const request = async (args)=>{
283
276
  const sanitizedArgs = (0, _utils1.sanitizeRequestArguments)(args);
284
277
  (0, _utils1.assertSnapOutboundRequest)(sanitizedArgs);
285
- this.notify({
286
- method: 'OutboundRequest'
287
- });
288
- try {
289
- return await (0, _utils1.withTeardown)(originalRequest(sanitizedArgs), this);
290
- } finally{
291
- this.notify({
292
- method: 'OutboundResponse'
278
+ return await (0, _utils1.withTeardown)((async ()=>{
279
+ await _class_private_method_get(this, _notify, notify).call(this, {
280
+ method: 'OutboundRequest'
293
281
  });
294
- }
282
+ try {
283
+ return await originalRequest(sanitizedArgs);
284
+ } finally{
285
+ await _class_private_method_get(this, _notify, notify).call(this, {
286
+ method: 'OutboundResponse'
287
+ });
288
+ }
289
+ })(), this);
295
290
  };
296
291
  // Proxy target is intentionally set to be an empty object, to ensure
297
292
  // that access to the prototype chain is not possible.
@@ -320,16 +315,18 @@ class BaseSnapExecutor {
320
315
  const request = async (args)=>{
321
316
  const sanitizedArgs = (0, _utils1.sanitizeRequestArguments)(args);
322
317
  (0, _utils1.assertEthereumOutboundRequest)(sanitizedArgs);
323
- this.notify({
324
- method: 'OutboundRequest'
325
- });
326
- try {
327
- return await (0, _utils1.withTeardown)(originalRequest(sanitizedArgs), this);
328
- } finally{
329
- this.notify({
330
- method: 'OutboundResponse'
318
+ return await (0, _utils1.withTeardown)((async ()=>{
319
+ await _class_private_method_get(this, _notify, notify).call(this, {
320
+ method: 'OutboundRequest'
331
321
  });
332
- }
322
+ try {
323
+ return await originalRequest(sanitizedArgs);
324
+ } finally{
325
+ await _class_private_method_get(this, _notify, notify).call(this, {
326
+ method: 'OutboundResponse'
327
+ });
328
+ }
329
+ })(), this);
333
330
  };
334
331
  const streamProviderProxy = (0, _utils1.proxyStreamProvider)(provider, request);
335
332
  return harden(streamProviderProxy);
@@ -383,6 +380,12 @@ class BaseSnapExecutor {
383
380
  }
384
381
  }
385
382
  constructor(commandStream, rpcStream){
383
+ // Awaitable function that writes back to the command stream
384
+ // To prevent snap execution from blocking writing we wrap in a promise
385
+ // and await it before continuing execution
386
+ _class_private_method_init(this, _write);
387
+ _class_private_method_init(this, _notify);
388
+ _class_private_method_init(this, _respond);
386
389
  _define_property(this, "snapData", void 0);
387
390
  _define_property(this, "commandStream", void 0);
388
391
  _define_property(this, "rpcStream", void 0);
@@ -426,5 +429,42 @@ class BaseSnapExecutor {
426
429
  }, this.onTerminate.bind(this));
427
430
  }
428
431
  }
432
+ async function write(chunk) {
433
+ return new Promise((resolve, reject)=>{
434
+ this.commandStream.write(chunk, (error)=>{
435
+ if (error) {
436
+ reject(error);
437
+ return;
438
+ }
439
+ resolve();
440
+ });
441
+ });
442
+ }
443
+ async function notify(requestObject) {
444
+ if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
445
+ throw _rpcerrors.rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
446
+ }
447
+ await _class_private_method_get(this, _write, write).call(this, {
448
+ ...requestObject,
449
+ jsonrpc: '2.0'
450
+ });
451
+ }
452
+ async function respond(id, requestObject) {
453
+ if (!(0, _utils.isValidJson)(requestObject) || !(0, _utils.isObject)(requestObject)) {
454
+ // Instead of throwing, we directly respond with an error.
455
+ // This prevents an issue where we wouldn't respond when errors were non-serializable
456
+ await _class_private_method_get(this, _write, write).call(this, {
457
+ error: (0, _rpcerrors.serializeError)(_rpcerrors.rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
458
+ id,
459
+ jsonrpc: '2.0'
460
+ });
461
+ return;
462
+ }
463
+ await _class_private_method_get(this, _write, write).call(this, {
464
+ ...requestObject,
465
+ id,
466
+ jsonrpc: '2.0'
467
+ });
468
+ }
429
469
 
430
470
  //# sourceMappingURL=BaseSnapExecutor.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"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 { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';\nimport type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\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 getErrorData,\n unwrapError,\n} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\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} 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 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 });\n }\n\n private async onCommandRequest(message: JsonRpcRequest) {\n if (!isJsonRpcRequest(message)) {\n throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\n }\n\n const { id, method, params } = message;\n\n if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {\n 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 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 this.respond(id, { result });\n } catch (rpcError) {\n this.respond(id, {\n error: serializeError(rpcError, {\n fallbackError,\n }),\n });\n }\n }\n\n protected notify(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n this.commandStream.write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n protected respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\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 this.commandStream.write({\n error: serializeError(\n rpcErrors.internal(\n 'JSON-RPC responses must be JSON serializable objects.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n this.commandStream.write({\n ...requestObject,\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,\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\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): SnapsGlobalObject {\n const originalRequest = provider.request.bind(provider);\n\n const request = async (args: RequestArguments) => {\n const sanitizedArgs = sanitizeRequestArguments(args);\n assertSnapOutboundRequest(sanitizedArgs);\n this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) as SnapsGlobalObject;\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 this.notify({ method: 'OutboundRequest' });\n try {\n return await withTeardown(originalRequest(sanitizedArgs), this as any);\n } finally {\n this.notify({ method: 'OutboundResponse' });\n }\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, 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"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","unhandledError","rpcErrors","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","serializedError","serializeError","shouldIncludeStack","errorData","getErrorData","notify","method","onCommandRequest","isJsonRpcRequest","invalidRequest","id","hasProperty","respond","methodNotFound","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","result","methods","rpcError","requestObject","isValidJson","isObject","commandStream","write","jsonrpc","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","Error","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","unwrapError","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","bind","args","sanitizedArgs","sanitizeRequestArguments","assertSnapOutboundRequest","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","WrappedSnapError","size","lastTeardown","Map","on","catch","logError","getCommandMethodImplementations","target","handlerType","handler","required","assert","methodNotSupported","getSafeJson","replace"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BA+GnDA;;;eAAAA;;;+BA9G2B;2BACT;2BAEuB;4BAc/C;uBAcA;6BAEkB;yBAEL;0BAE4B;4BACf;8BACqB;4BACxB;wBAOvB;4BAMA;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;IACpBC,MAAMC,qBAAU,CAACC,GAAG,CAACC,QAAQ;IAC7BC,SAAS;AACX;AAEA,MAAMC,iBAAiBC,oBAAS,CAC7BH,QAAQ,CAAO;IACdC,SAAS;AACX,GACCG,SAAS;AAUZ;;;;CAIC,GACD,MAAMC,gCAAgC;IACpCC,MAAM;QACJC,QAAQC,sCAA0B;QAClCC,QAAQ,EAAE;IACZ;IACAC,aAAa;QACXH,QAAQI,6CAAiC;QACzCF,QAA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AAW;gBACxBlF,SAAS;YACX;YAEA,uEAAuE;YACvE,IAAI;gBACF,OAAO8G,IAAAA,kBAAW,EAAC9G;YACrB,EAAE,OAAOrB,OAAO;gBACd,MAAMd,oBAAS,CAACH,QAAQ,CACtB,CAAC,sCAAsC,EAAEiB,MAAMhB,OAAO,CAACoJ,OAAO,CAC5D,wBACA,IACA,CAAC;YAEP;QACF,GACA,IAAI,CAACxD,WAAW,CAACe,IAAI,CAAC,IAAI;IAE9B;AAmXF"}
1
+ {"version":3,"sources":["../../../src/common/BaseSnapExecutor.ts"],"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 { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\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} from '@metamask/snaps-utils';\nimport type {\n JsonRpcNotification,\n JsonRpcId,\n JsonRpcRequest,\n Json,\n} from '@metamask/utils';\nimport {\n isObject,\n isValidJson,\n assert,\n isJsonRpcRequest,\n hasProperty,\n getSafeJson,\n} from '@metamask/utils';\nimport type { Duplex } from 'stream';\nimport { validate } from 'superstruct';\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} 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 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 throw rpcErrors.invalidRequest({\n message: 'Command stream received a non-JSON-RPC request.',\n data: message,\n });\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(requestObject: Omit<JsonRpcNotification, 'jsonrpc'>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\n throw rpcErrors.internal(\n 'JSON-RPC notifications must be JSON serializable objects',\n );\n }\n\n await this.#write({\n ...requestObject,\n jsonrpc: '2.0',\n });\n }\n\n async #respond(id: JsonRpcId, requestObject: Record<string, unknown>) {\n if (!isValidJson(requestObject) || !isObject(requestObject)) {\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.',\n ),\n ),\n id,\n jsonrpc: '2.0',\n });\n return;\n }\n\n await this.#write({\n ...requestObject,\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,\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\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({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\n }\n })(),\n this as any,\n );\n };\n\n // Proxy target is intentionally set to be an empty object, to ensure\n // that access to the prototype chain is not possible.\n const snapGlobalProxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return typeof prop === 'string' && ['request'].includes(prop);\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n }\n\n return undefined;\n },\n },\n ) 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({ method: 'OutboundRequest' });\n try {\n return await originalRequest(sanitizedArgs);\n } finally {\n await this.#notify({ method: 'OutboundResponse' });\n }\n })(),\n this as any,\n );\n };\n\n const streamProviderProxy = proxyStreamProvider(provider, 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"],"names":["BaseSnapExecutor","fallbackError","code","errorCodes","rpc","internal","message","unhandledError","rpcErrors","serialize","EXECUTION_ENVIRONMENT_METHODS","ping","struct","PingRequestArgumentsStruct","params","executeSnap","ExecuteSnapRequestArgumentsStruct","terminate","TerminateRequestArgumentsStruct","snapRpc","SnapRpcRequestArgumentsStruct","errorHandler","error","data","serializedError","serializeError","shouldIncludeStack","errorData","getErrorData","notify","method","catch","notifyError","logError","onCommandRequest","isJsonRpcRequest","invalidRequest","id","hasProperty","respond","methodNotFound","methodObject","paramsAsArray","sortParamKeys","validate","invalidParams","result","methods","rpcError","startSnap","snapId","sourceCode","_endowments","log","snapPromiseErrorHandler","removeEventListener","snapErrorHandler","Error","reason","provider","StreamProvider","rpcStream","jsonRpcStreamName","rpcMiddleware","createIdRemapMiddleware","initialize","snap","createSnapGlobal","ethereum","createEIP1193Provider","snapModule","exports","endowments","teardown","endowmentTeardown","createEndowments","snapData","set","idleTeardown","runningEvaluations","Set","addEventListener","compartment","Compartment","module","globalThis","self","global","window","executeInSnapContext","evaluate","registerSnapExports","removeSnap","cause","unwrapError","onTerminate","forEach","evaluation","stop","clear","get","SNAP_EXPORT_NAMES","reduce","acc","exportName","snapExport","validator","SNAP_EXPORTS","originalRequest","request","bind","args","sanitizedArgs","sanitizeRequestArguments","assertSnapOutboundRequest","withTeardown","snapGlobalProxy","Proxy","has","_target","prop","includes","undefined","harden","assertEthereumOutboundRequest","streamProviderProxy","proxyStreamProvider","delete","executor","stopPromise","Promise","_","reject","evaluationData","add","race","WrappedSnapError","size","lastTeardown","commandStream","Map","on","getCommandMethodImplementations","target","handlerType","handler","required","assert","methodNotSupported","getSafeJson","replace","chunk","resolve","write","requestObject","isValidJson","isObject","jsonrpc"],"mappings":"AAAA,qFAAqF;AACrF,gEAAgE;;;;;+BA+GnDA;;;eAAAA;;;+BA9G2B;2BACT;2BAEuB;0BAEzB;4BAYtB;uBAcA;6BAEkB;yBAEL;0BAE4B;4BACf;8BACqB;4BACxB;wBAOvB;4BAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYP,MAAMC,gBAAgB;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EAAEJ,QAAAA,YAAN,IAAI,EAAQ;QAChB,GAAGC,aAAa;QAChBrH;QACAwH,SAAS;IACX;AACF"}
@@ -58,6 +58,8 @@ function getHandlerArguments(origin, handler, request) {
58
58
  return {
59
59
  request
60
60
  };
61
+ case _snapsutils.HandlerType.OnHomePage:
62
+ return {};
61
63
  default:
62
64
  return (0, _utils.assertExhaustive)(handler);
63
65
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAgCgBA,mBAAmB;eAAnBA;;IA6DAC,+BAA+B;eAA/BA;;;4BA7FY;uBACK;4BAc1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACT,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEI,MAAM,EAAEC,OAAO,EAAE,GAChCX,QAAQI,MAAM;gBAEhB,OAAOM,SACH;oBACEJ;oBACAI;gBACF,IACA;oBACEJ;oBACAK;gBACF;YACN;QACA,KAAKV,uBAAW,CAACW,YAAY;QAC7B,KAAKX,uBAAW,CAACY,gBAAgB;YAC/B,OAAO;gBAAEf;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACa,SAAS;QAC1B,KAAKb,uBAAW,CAACc,SAAS;QAC1B,KAAKd,uBAAW,CAACe,QAAQ;YACvB,OAAO;gBAAEhB;YAAQ;QAEnB;YACE,OAAOiB,IAAAA,uBAAgB,EAAClB;IAC5B;AACF;AAaO,SAASF,gCACdqB,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQ/B,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMmB,WACLW,QACA/B,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/common/commands.ts"],"sourcesContent":["import { HandlerType } from '@metamask/snaps-utils';\nimport { assertExhaustive } from '@metamask/utils';\n\nimport type { InvokeSnap, InvokeSnapArgs } from './BaseSnapExecutor';\nimport type {\n ExecuteSnap,\n JsonRpcRequestWithoutId,\n Ping,\n PossibleLookupRequestArgs,\n SnapRpc,\n Terminate,\n} from './validation';\nimport {\n assertIsOnTransactionRequestArguments,\n assertIsOnNameLookupRequestArguments,\n} from './validation';\n\nexport type CommandMethodsMapping = {\n ping: Ping;\n terminate: Terminate;\n executeSnap: ExecuteSnap;\n snapRpc: SnapRpc;\n};\n\n/**\n * Formats the arguments for the given handler.\n *\n * @param origin - The origin of the request.\n * @param handler - The handler to pass the request to.\n * @param request - The request object.\n * @returns The formatted arguments.\n */\nexport function getHandlerArguments(\n origin: string,\n handler: HandlerType,\n request: JsonRpcRequestWithoutId,\n): InvokeSnapArgs {\n // `request` is already validated by the time this function is called.\n\n switch (handler) {\n case HandlerType.OnTransaction: {\n assertIsOnTransactionRequestArguments(request.params);\n\n const { transaction, chainId, transactionOrigin } = request.params;\n return {\n transaction,\n chainId,\n transactionOrigin,\n };\n }\n case HandlerType.OnNameLookup: {\n assertIsOnNameLookupRequestArguments(request.params);\n\n // TS complains that domain/address are not part of the type\n // casting here as we've already validated the request args in the above step.\n const { chainId, domain, address } =\n request.params as unknown as PossibleLookupRequestArgs;\n\n return domain\n ? {\n chainId,\n domain,\n }\n : {\n chainId,\n address,\n };\n }\n case HandlerType.OnRpcRequest:\n case HandlerType.OnKeyringRequest:\n return { origin, request };\n\n case HandlerType.OnCronjob:\n case HandlerType.OnInstall:\n case HandlerType.OnUpdate:\n return { request };\n\n case HandlerType.OnHomePage:\n return {};\n\n default:\n return assertExhaustive(handler);\n }\n}\n\n/**\n * Gets an object mapping internal, \"command\" JSON-RPC method names to their\n * implementations.\n *\n * @param startSnap - A function that starts a snap.\n * @param invokeSnap - A function that invokes the RPC method handler of a\n * snap.\n * @param onTerminate - A function that will be called when this executor is\n * terminated in order to handle cleanup tasks.\n * @returns An object containing the \"command\" method implementations.\n */\nexport function getCommandMethodImplementations(\n startSnap: (...args: Parameters<ExecuteSnap>) => Promise<void>,\n invokeSnap: InvokeSnap,\n onTerminate: () => void,\n): CommandMethodsMapping {\n return {\n ping: async () => Promise.resolve('OK'),\n terminate: async () => {\n onTerminate();\n return Promise.resolve('OK');\n },\n\n executeSnap: async (snapId, sourceCode, endowments) => {\n await startSnap(snapId, sourceCode, endowments);\n return 'OK';\n },\n\n snapRpc: async (target, handler, origin, request) => {\n return (\n (await invokeSnap(\n target,\n handler,\n getHandlerArguments(origin, handler, request),\n )) ?? null\n );\n },\n };\n}\n"],"names":["getHandlerArguments","getCommandMethodImplementations","origin","handler","request","HandlerType","OnTransaction","assertIsOnTransactionRequestArguments","params","transaction","chainId","transactionOrigin","OnNameLookup","assertIsOnNameLookupRequestArguments","domain","address","OnRpcRequest","OnKeyringRequest","OnCronjob","OnInstall","OnUpdate","OnHomePage","assertExhaustive","startSnap","invokeSnap","onTerminate","ping","Promise","resolve","terminate","executeSnap","snapId","sourceCode","endowments","snapRpc","target"],"mappings":";;;;;;;;;;;IAgCgBA,mBAAmB;eAAnBA;;IAgEAC,+BAA+B;eAA/BA;;;4BAhGY;uBACK;4BAc1B;AAiBA,SAASD,oBACdE,MAAc,EACdC,OAAoB,EACpBC,OAAgC;IAEhC,sEAAsE;IAEtE,OAAQD;QACN,KAAKE,uBAAW,CAACC,aAAa;YAAE;gBAC9BC,IAAAA,iDAAqC,EAACH,QAAQI,MAAM;gBAEpD,MAAM,EAAEC,WAAW,EAAEC,OAAO,EAAEC,iBAAiB,EAAE,GAAGP,QAAQI,MAAM;gBAClE,OAAO;oBACLC;oBACAC;oBACAC;gBACF;YACF;QACA,KAAKN,uBAAW,CAACO,YAAY;YAAE;gBAC7BC,IAAAA,gDAAoC,EAACT,QAAQI,MAAM;gBAEnD,4DAA4D;gBAC5D,8EAA8E;gBAC9E,MAAM,EAAEE,OAAO,EAAEI,MAAM,EAAEC,OAAO,EAAE,GAChCX,QAAQI,MAAM;gBAEhB,OAAOM,SACH;oBACEJ;oBACAI;gBACF,IACA;oBACEJ;oBACAK;gBACF;YACN;QACA,KAAKV,uBAAW,CAACW,YAAY;QAC7B,KAAKX,uBAAW,CAACY,gBAAgB;YAC/B,OAAO;gBAAEf;gBAAQE;YAAQ;QAE3B,KAAKC,uBAAW,CAACa,SAAS;QAC1B,KAAKb,uBAAW,CAACc,SAAS;QAC1B,KAAKd,uBAAW,CAACe,QAAQ;YACvB,OAAO;gBAAEhB;YAAQ;QAEnB,KAAKC,uBAAW,CAACgB,UAAU;YACzB,OAAO,CAAC;QAEV;YACE,OAAOC,IAAAA,uBAAgB,EAACnB;IAC5B;AACF;AAaO,SAASF,gCACdsB,SAA8D,EAC9DC,UAAsB,EACtBC,WAAuB;IAEvB,OAAO;QACLC,MAAM,UAAYC,QAAQC,OAAO,CAAC;QAClCC,WAAW;YACTJ;YACA,OAAOE,QAAQC,OAAO,CAAC;QACzB;QAEAE,aAAa,OAAOC,QAAQC,YAAYC;YACtC,MAAMV,UAAUQ,QAAQC,YAAYC;YACpC,OAAO;QACT;QAEAC,SAAS,OAAOC,QAAQhC,SAASD,QAAQE;YACvC,OACE,AAAC,MAAMoB,WACLW,QACAhC,SACAH,oBAAoBE,QAAQC,SAASC,aACjC;QAEV;IACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/commonEndowmentFactory.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: SnapId;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"],"names":["commonEndowments","endowment","AbortController","name","AbortSignal","ArrayBuffer","atob","bind","BigInt","BigInt64Array","BigUint64Array","btoa","DataView","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","URL","WebAssembly","buildCommonEndowments","endowmentFactories","crypto","interval","math","network","timeout","textDecoder","textEncoder","date","consoleEndowment","forEach","endowmentSpecification","names","factory","boundEndowment","rootRealmGlobal","harden","push"],"mappings":";;;;+BA4FA;;;eAAA;;;8BA1FgC;gEACH;+DACV;6DACF;iEACI;6DACJ;gEACG;oEACI;oEACA;gEACJ;;;;;;AAiBpB,6BAA6B;AAC7B,MAAMA,mBAAmD;IACvD;QAAEC,WAAWC;QAAiBC,MAAM;IAAkB;IACtD;QAAEF,WAAWG;QAAaD,MAAM;IAAc;IAC9C;QAAEF,WAAWI;QAAaF,MAAM;IAAc;IAC9C;QAAEF,WAAWK;QAAMH,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWO;QAAQL,MAAM;IAAS;IACpC;QAAEF,WAAWQ;QAAeN,MAAM;IAAgB;IAClD;QAAEF,WAAWS;QAAgBP,MAAM;IAAiB;IACpD;QAAEF,WAAWU;QAAMR,MAAM;QAAQI,MAAM;IAAK;IAC5C;QAAEN,WAAWW;QAAUT,MAAM;IAAW;IACxC;QAAEF,WAAWY;QAAcV,MAAM;IAAe;IAChD;QAAEF,WAAWa;QAAcX,MAAM;IAAe;IAChD;QAAEF,WAAWc;QAAWZ,MAAM;IAAY;IAC1C;QAAEF,WAAWe;QAAYb,MAAM;IAAa;IAC5C;QAAEF,WAAWgB;QAAYd,MAAM;IAAa;IAC5C;QAAEF,WAAWiB;QAAYf,MAAM;IAAa;IAC5C;QAAEF,WAAWkB;QAAmBhB,MAAM;IAAoB;IAC1D;QAAEF,WAAWmB;QAAajB,MAAM;IAAc;IAC9C;QAAEF,WAAWoB;QAAalB,MAAM;IAAc;IAC9C;QAAEF,WAAWqB;QAAKnB,MAAM;IAAM;IAC9B;QAAEF,WAAWsB;QAAapB,MAAM;IAAc;CAC/C;AAED;;;;;;CAMC,GACD,MAAMqB,wBAAwB;IAC5B,MAAMC,qBAAyC;QAC7CC,eAAM;QACNC,iBAAQ;QACRC,aAAI;QACJC,gBAAO;QACPC,gBAAO;QACPC,oBAAW;QACXC,oBAAW;QACXC,aAAI;QACJC,gBAAgB;KACjB;IAEDlC,iBAAiBmC,OAAO,CAAC,CAACC;QACxB,MAAMnC,YAAY;YAChBoC,OAAO;gBAACD,uBAAuBjC,IAAI;aAAC;YACpCmC,SAAS;gBACP,MAAMC,iBACJ,OAAOH,uBAAuBnC,SAAS,KAAK,cAC5CmC,uBAAuB7B,IAAI,GACvB6B,uBAAuBnC,SAAS,CAACM,IAAI,CAACiC,6BAAe,IACrDJ,uBAAuBnC,SAAS;gBACtC,OAAO;oBACL,CAACmC,uBAAuBjC,IAAI,CAAC,EAAEsC,OAAOF;gBACxC;YACF;QACF;QACAd,mBAAmBiB,IAAI,CAACzC;IAC1B;IAEA,OAAOwB;AACT;MAEA,WAAeD"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/commonEndowmentFactory.ts"],"sourcesContent":["import { rootRealmGlobal } from '../globalObject';\nimport consoleEndowment from './console';\nimport crypto from './crypto';\nimport date from './date';\nimport interval from './interval';\nimport math from './math';\nimport network from './network';\nimport textDecoder from './textDecoder';\nimport textEncoder from './textEncoder';\nimport timeout from './timeout';\n\nexport type EndowmentFactoryOptions = {\n snapId?: string;\n};\n\nexport type EndowmentFactory = {\n names: readonly string[];\n factory: (options?: EndowmentFactoryOptions) => { [key: string]: unknown };\n};\n\nexport type CommonEndowmentSpecification = {\n endowment: unknown;\n name: string;\n bind?: boolean;\n};\n\n// Array of common endowments\nconst commonEndowments: CommonEndowmentSpecification[] = [\n { endowment: AbortController, name: 'AbortController' },\n { endowment: AbortSignal, name: 'AbortSignal' },\n { endowment: ArrayBuffer, name: 'ArrayBuffer' },\n { endowment: atob, name: 'atob', bind: true },\n { endowment: BigInt, name: 'BigInt' },\n { endowment: BigInt64Array, name: 'BigInt64Array' },\n { endowment: BigUint64Array, name: 'BigUint64Array' },\n { endowment: btoa, name: 'btoa', bind: true },\n { endowment: DataView, name: 'DataView' },\n { endowment: Float32Array, name: 'Float32Array' },\n { endowment: Float64Array, name: 'Float64Array' },\n { endowment: Int8Array, name: 'Int8Array' },\n { endowment: Int16Array, name: 'Int16Array' },\n { endowment: Int32Array, name: 'Int32Array' },\n { endowment: Uint8Array, name: 'Uint8Array' },\n { endowment: Uint8ClampedArray, name: 'Uint8ClampedArray' },\n { endowment: Uint16Array, name: 'Uint16Array' },\n { endowment: Uint32Array, name: 'Uint32Array' },\n { endowment: URL, name: 'URL' },\n { endowment: WebAssembly, name: 'WebAssembly' },\n];\n\n/**\n * Creates a consolidated collection of common endowments.\n * This function will return factories for all common endowments including\n * the additionally attenuated. All hardened with SES.\n *\n * @returns An object with common endowments.\n */\nconst buildCommonEndowments = (): EndowmentFactory[] => {\n const endowmentFactories: EndowmentFactory[] = [\n crypto,\n interval,\n math,\n network,\n timeout,\n textDecoder,\n textEncoder,\n date,\n consoleEndowment,\n ];\n\n commonEndowments.forEach((endowmentSpecification) => {\n const endowment = {\n names: [endowmentSpecification.name] as const,\n factory: () => {\n const boundEndowment =\n typeof endowmentSpecification.endowment === 'function' &&\n endowmentSpecification.bind\n ? endowmentSpecification.endowment.bind(rootRealmGlobal)\n : endowmentSpecification.endowment;\n return {\n [endowmentSpecification.name]: harden(boundEndowment),\n } as const;\n },\n };\n endowmentFactories.push(endowment);\n });\n\n return endowmentFactories;\n};\n\nexport default buildCommonEndowments;\n"],"names":["commonEndowments","endowment","AbortController","name","AbortSignal","ArrayBuffer","atob","bind","BigInt","BigInt64Array","BigUint64Array","btoa","DataView","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","URL","WebAssembly","buildCommonEndowments","endowmentFactories","crypto","interval","math","network","timeout","textDecoder","textEncoder","date","consoleEndowment","forEach","endowmentSpecification","names","factory","boundEndowment","rootRealmGlobal","harden","push"],"mappings":";;;;+BA0FA;;;eAAA;;;8BA1FgC;gEACH;+DACV;6DAC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I;aAAC;YACpCmC,SAAS;gBACP,MAAMC,iBACJ,OAAOH,uBAAuBnC,SAAS,KAAK,cAC5CmC,uBAAuB7B,IAAI,GACvB6B,uBAAuBnC,SAAS,CAACM,IAAI,CAACiC,6BAAe,IACrDJ,uBAAuBnC,SAAS;gBACtC,OAAO;oBACL,CAACmC,uBAAuBjC,IAAI,CAAC,EAAEsC,OAAOF;gBACxC;YACF;QACF;QACAd,mBAAmBiB,IAAI,CAACzC;IAC1B;IAEA,OAAOwB;AACT;MAEA,WAAeD"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in (typeof consoleFunctions)[number]]: (typeof rootRealmGlobal.console)[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: SnapId, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["consoleAttenuatedMethods","consoleMethods","Set","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","assert","undefined","keys","Object","getOwnPropertyNames","rootRealmGlobal","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;IAMaA,wBAAwB;eAAxBA;;IAaAC,cAAc;eAAdA;;IA6Gb,OAA+B;eAA/B;;;uBA/HuB;8BAES;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AAWC,QAAQC,YAAYkB;YAEtC;YACA,GAAGrB,iBAAiBe,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACd,SAAmB,GAAGkB;wBAC5BT,6BAAe,CAACC,OAAO,CAACI,IAAI,IACvBhB,WAAWC,QAAQC,YAAYkB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAASlB;AACX;MAEA,WAAegB"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/console.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\n\nexport const consoleAttenuatedMethods = new Set([\n 'log',\n 'assert',\n 'error',\n 'debug',\n 'info',\n 'warn',\n]);\n\n/**\n * A set of all the `console` values that will be passed to the snap. This has\n * all the values that are available in both the browser and Node.js.\n */\nexport const consoleMethods = new Set([\n 'debug',\n 'error',\n 'info',\n 'log',\n 'warn',\n 'dir',\n 'dirxml',\n 'table',\n 'trace',\n 'group',\n 'groupCollapsed',\n 'groupEnd',\n 'clear',\n 'count',\n 'countReset',\n 'assert',\n 'profile',\n 'profileEnd',\n 'time',\n 'timeLog',\n 'timeEnd',\n 'timeStamp',\n 'context',\n]);\n\nconst consoleFunctions = ['log', 'error', 'debug', 'info', 'warn'] as const;\n\ntype ConsoleFunctions = {\n [Key in (typeof consoleFunctions)[number]]: (typeof rootRealmGlobal.console)[Key];\n};\n\n/**\n * Gets the appropriate (prepended) message to pass to one of the attenuated\n * method calls.\n *\n * @param snapId - Id of the snap that we're getting a message for.\n * @param message - The id of the snap that will interact with the endowment.\n * @param args - The array of additional arguments.\n * @returns An array of arguments to be passed into an attenuated console method call.\n */\nfunction getMessage(snapId: string, message: unknown, ...args: unknown[]) {\n const prefix = `[Snap: ${snapId}]`;\n\n // If the first argument is a string, prepend the prefix to the message, and keep the\n // rest of the arguments as-is.\n if (typeof message === 'string') {\n return [`${prefix} ${message}`, ...args];\n }\n\n // Otherwise, the `message` is an object, array, etc., so add the prefix as a separate\n // message to the arguments.\n return [prefix, message, ...args];\n}\n\n/**\n * Create a a {@link console} object, with the same properties as the global\n * {@link console} object, but with some methods replaced.\n *\n * @param options - Factory options used in construction of the endowment.\n * @param options.snapId - The id of the snap that will interact with the endowment.\n * @returns The {@link console} object with the replaced methods.\n */\nfunction createConsole({ snapId }: EndowmentFactoryOptions = {}) {\n assert(snapId !== undefined);\n const keys = Object.getOwnPropertyNames(\n rootRealmGlobal.console,\n ) as (keyof typeof console)[];\n\n const attenuatedConsole = keys.reduce((target, key) => {\n if (consoleMethods.has(key) && !consoleAttenuatedMethods.has(key)) {\n return { ...target, [key]: rootRealmGlobal.console[key] };\n }\n\n return target;\n }, {});\n\n return harden({\n console: {\n ...attenuatedConsole,\n assert: (\n value: any,\n message?: string | undefined,\n ...optionalParams: any[]\n ) => {\n rootRealmGlobal.console.assert(\n value,\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n ...consoleFunctions.reduce<ConsoleFunctions>((target, key) => {\n return {\n ...target,\n [key]: (message?: unknown, ...optionalParams: any[]) => {\n rootRealmGlobal.console[key](\n ...getMessage(snapId, message, ...optionalParams),\n );\n },\n };\n }, {} as ConsoleFunctions),\n },\n });\n}\n\nconst endowmentModule = {\n names: ['console'] as const,\n factory: createConsole,\n};\n\nexport default endowmentModule;\n"],"names":["consoleAttenuatedMethods","consoleMethods","Set","consoleFunctions","getMessage","snapId","message","args","prefix","createConsole","assert","undefined","keys","Object","getOwnPropertyNames","rootRealmGlobal","console","attenuatedConsole","reduce","target","key","has","harden","value","optionalParams","endowmentModule","names","factory"],"mappings":";;;;;;;;;;;IAKaA,wBAAwB;eAAxBA;;IAaAC,cAAc;eAAdA;;IA6Gb,OAA+B;eAA/B;;;uBA/HuB;8BAES;AAGzB,MAAM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,YAAYkB;YAEtC;YACA,GAAGrB,iBAAiBe,MAAM,CAAmB,CAACC,QAAQC;gBACpD,OAAO;oBACL,GAAGD,MAAM;oBACT,CAACC,IAAI,EAAE,CAACd,SAAmB,GAAGkB;wBAC5BT,6BAAe,CAACC,OAAO,CAACI,IAAI,IACvBhB,WAAWC,QAAQC,YAAYkB;oBAEtC;gBACF;YACF,GAAG,CAAC,EAAsB;QAC5B;IACF;AACF;AAEA,MAAMC,kBAAkB;IACtBC,OAAO;QAAC;KAAU;IAClBC,SAASlB;AACX;MAEA,WAAegB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsGlobalObject } from '@metamask/snaps-rpc-methods';\nimport type { SnapId } from '@metamask/snaps-utils';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsGlobalObject,\n ethereum: StreamProvider,\n snapId: SnapId,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw rpcErrors.internal(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"],"names":["createEndowments","registeredEndowments","buildCommonEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","snap","ethereum","snapId","endowments","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","hasProperty","teardownFunction","endowment","get","Object","assign","push","rootRealmGlobal","logWarning","globalValue","rpcErrors","internal","teardown","Promise","all","map"],"mappings":";;;;+BAsDgBA;;;eAAAA;;;2BArDU;4BAGC;uBACC;8BAEI;+EAEE;;;;;;AAelC;;CAEC,GACD,MAAMC,uBAAuBC,IAAAA,+BAAqB;AAElD;;;;CAIC,GACD,MAAMC,qBAAqBF,qBAAqBG,MAAM,CAAC,CAACC,WAAWC;IACjEA,QAAQC,KAAK,CAACC,OAAO,CAAC,CAACC;QACrBJ,UAAUK,GAAG,CAACD,MAAMH,QAAQK,OAAO;IACrC;IACA,OAAON;AACT,GAAG,IAAIO;AAeA,SAASZ,iBACda,IAAuB,EACvBC,QAAwB,EACxBC,MAAc,EACdC,aAAuB,EAAE;IAEzB,MAAMC,uBAAgD,CAAC;IAEvD,0EAA0E;IAC1E,yEAAyE;IACzE,2CAA2C;IAC3C,MAAMC,SAASF,WAAWZ,MAAM,CAI9B,CAAC,EAAEe,aAAa,EAAEC,SAAS,EAAE,EAAEC;QAC7B,oEAAoE;QACpE,IAAIlB,mBAAmBmB,GAAG,CAACD,gBAAgB;YACzC,IAAI,CAACE,IAAAA,kBAAW,EAACN,sBAAsBI,gBAAgB;gBACrD,uEAAuE;gBACvE,gEAAgE;gBAChE,wEAAwE;gBACxE,4CAA4C;gBAC5C,2DAA2D;gBAE3D,mEAAmE;gBACnE,oEAAoE;gBACpE,MAAM,EAAEG,gBAAgB,EAAE,GAAGC,WAAW,GAAGtB,mBAAmBuB,GAAG,CAC/DL,eACC;oBAAEN;gBAAO;gBACZY,OAAOC,MAAM,CAACX,sBAAsBQ;gBACpC,IAAID,kBAAkB;oBACpBJ,UAAUS,IAAI,CAACL;gBACjB;YACF;YACAL,aAAa,CAACE,cAAc,GAAGJ,oBAAoB,CAACI,cAAc;QACpE,OAAO,IAAIA,kBAAkB,YAAY;YACvC,iDAAiD;YACjDF,aAAa,CAACE,cAAc,GAAGP;QACjC,OAAO,IAAIO,iBAAiBS,6BAAe,EAAE;YAC3CC,IAAAA,sBAAU,EAAC,CAAC,4BAA4B,EAAEV,cAAc,CAAC,CAAC;YAC1D,uEAAuE;YACvE,iBAAiB;YACjB,MAAMW,cAAc,AAACF,6BAAe,AAA4B,CAC9DT,cACD;YACDF,aAAa,CAACE,cAAc,GAAGW;QACjC,OAAO;YACL,uEAAuE;YACvE,oCAAoC;YACpC,MAAMC,oBAAS,CAACC,QAAQ,CAAC,CAAC,oBAAoB,EAAEb,cAAc,EAAE,CAAC;QACnE;QACA,OAAO;YAAEF;YAAeC;QAAU;IACpC,GACA;QACED,eAAe;YAAEN;QAAK;QACtBO,WAAW,EAAE;IACf;IAGF,MAAMe,WAAW;QACf,MAAMC,QAAQC,GAAG,CACfnB,OAAOE,SAAS,CAACkB,GAAG,CAAC,CAACd,mBAAqBA;IAE/C;IACA,OAAO;QAAER,YAAYE,OAAOC,aAAa;QAAEgB;IAAS;AACtD"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/index.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { SnapsProvider } from '@metamask/snaps-sdk';\nimport { logWarning } from '@metamask/snaps-utils';\nimport { hasProperty } from '@metamask/utils';\n\nimport { rootRealmGlobal } from '../globalObject';\nimport type { EndowmentFactoryOptions } from './commonEndowmentFactory';\nimport buildCommonEndowments from './commonEndowmentFactory';\n\ntype EndowmentFactoryResult = {\n /**\n * A function that performs any necessary teardown when the snap becomes idle.\n *\n * NOTE:** The endowments are not reconstructed if the snap is re-invoked\n * before being terminated, so the teardown operation must not render the\n * endowments unusable; it should simply restore the endowments to their\n * original state.\n */\n teardownFunction?: () => Promise<void> | void;\n [key: string]: unknown;\n};\n\n/**\n * Retrieve consolidated endowment factories for common endowments.\n */\nconst registeredEndowments = buildCommonEndowments();\n\n/**\n * A map of endowment names to their factory functions. Some endowments share\n * the same factory function, but we only call each factory once for each snap.\n * See {@link createEndowments} for details.\n */\nconst endowmentFactories = registeredEndowments.reduce((factories, builder) => {\n builder.names.forEach((name) => {\n factories.set(name, builder.factory);\n });\n return factories;\n}, new Map<string, (options?: EndowmentFactoryOptions) => EndowmentFactoryResult>());\n\n/**\n * Gets the endowments for a particular Snap. Some endowments, like `setTimeout`\n * and `clearTimeout`, must be attenuated so that they can only affect behavior\n * within the Snap's own realm. Therefore, we use factory functions to create\n * such attenuated / modified endowments. Otherwise, the value that's on the\n * root realm global will be used.\n *\n * @param snap - The Snaps global API object.\n * @param ethereum - The Snap's EIP-1193 provider object.\n * @param snapId - The id of the snap that will use the created endowments.\n * @param endowments - The list of endowments to provide to the snap.\n * @returns An object containing the Snap's endowments.\n */\nexport function createEndowments(\n snap: SnapsProvider,\n ethereum: StreamProvider,\n snapId: string,\n endowments: string[] = [],\n): { endowments: Record<string, unknown>; teardown: () => Promise<void> } {\n const attenuatedEndowments: Record<string, unknown> = {};\n\n // TODO: All endowments should be hardened to prevent covert communication\n // channels. Hardening the returned objects breaks tests elsewhere in the\n // monorepo, so further research is needed.\n const result = endowments.reduce<{\n allEndowments: Record<string, unknown>;\n teardowns: (() => Promise<void> | void)[];\n }>(\n ({ allEndowments, teardowns }, endowmentName) => {\n // First, check if the endowment has a factory, and default to that.\n if (endowmentFactories.has(endowmentName)) {\n if (!hasProperty(attenuatedEndowments, endowmentName)) {\n // Call the endowment factory for the current endowment. If the factory\n // creates multiple endowments, they will all be assigned to the\n // `attenuatedEndowments` object, but will only be passed on to the snap\n // if explicitly listed among its endowment.\n // This may not have an actual use case, but, safety first.\n\n // We just confirmed that endowmentFactories has the specified key.\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const { teardownFunction, ...endowment } = endowmentFactories.get(\n endowmentName,\n )!({ snapId });\n Object.assign(attenuatedEndowments, endowment);\n if (teardownFunction) {\n teardowns.push(teardownFunction);\n }\n }\n allEndowments[endowmentName] = attenuatedEndowments[endowmentName];\n } else if (endowmentName === 'ethereum') {\n // Special case for adding the EIP-1193 provider.\n allEndowments[endowmentName] = ethereum;\n } else if (endowmentName in rootRealmGlobal) {\n logWarning(`Access to unhardened global ${endowmentName}.`);\n // If the endowment doesn't have a factory, just use whatever is on the\n // global object.\n const globalValue = (rootRealmGlobal as Record<string, unknown>)[\n endowmentName\n ];\n allEndowments[endowmentName] = globalValue;\n } else {\n // If we get to this point, we've been passed an endowment that doesn't\n // exist in our current environment.\n throw rpcErrors.internal(`Unknown endowment: \"${endowmentName}\".`);\n }\n return { allEndowments, teardowns };\n },\n {\n allEndowments: { snap },\n teardowns: [],\n },\n );\n\n const teardown = async () => {\n await Promise.all(\n result.teardowns.map((teardownFunction) => teardownFunction()),\n );\n };\n return { endowments: result.allEndowments, teardown };\n}\n"],"names":["createEndowments","registeredEndowments","buildCommonEndowments","endowmentFactories","reduce","factories","builder","names","forEach","name","set","factory","Map","snap","ethereum","snapId","endowments","attenuatedEndowments","result","allEndowments","teardowns","endowmentName","has","hasProperty","teardownFunction","endowment","get","Object","assign","push","rootRealmGlobal","logWarning","globalValue","rpcErrors","internal","teardown","Promise","all","map"],"mappings":";;;;+BAqDgBA;;;eAAAA;;;2BApDU;4BAEC;uBACC;8BAEI;+EAEE;;;;;;AAelC;;CAEC,GACD,MAAMC,uBAAuBC,IAAAA,+BAAqB;AAElD;;;;CAIC,GACD,MAAMC,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