@metamask/snaps-execution-environments 3.0.0 → 3.2.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/dist/browserify/iframe/bundle.js +5 -5
  3. package/dist/browserify/node-process/bundle.js +4 -4
  4. package/dist/browserify/node-thread/bundle.js +4 -4
  5. package/dist/browserify/offscreen/bundle.js +4 -4
  6. package/dist/browserify/worker-executor/bundle.js +5 -5
  7. package/dist/browserify/worker-pool/bundle.js +4 -4
  8. package/dist/cjs/common/BaseSnapExecutor.js +123 -74
  9. package/dist/cjs/common/BaseSnapExecutor.js.map +1 -1
  10. package/dist/cjs/common/commands.js +2 -0
  11. package/dist/cjs/common/commands.js.map +1 -1
  12. package/dist/cjs/common/endowments/index.js +2 -1
  13. package/dist/cjs/common/endowments/index.js.map +1 -1
  14. package/dist/cjs/common/endowments/interval.js +2 -1
  15. package/dist/cjs/common/endowments/interval.js.map +1 -1
  16. package/dist/cjs/common/endowments/timeout.js +2 -1
  17. package/dist/cjs/common/endowments/timeout.js.map +1 -1
  18. package/dist/cjs/common/globalEvents.js +2 -1
  19. package/dist/cjs/common/globalEvents.js.map +1 -1
  20. package/dist/cjs/common/globalObject.js.map +1 -1
  21. package/dist/cjs/common/utils.js +7 -21
  22. package/dist/cjs/common/utils.js.map +1 -1
  23. package/dist/cjs/common/validation.js +3 -2
  24. package/dist/cjs/common/validation.js.map +1 -1
  25. package/dist/esm/common/BaseSnapExecutor.js +123 -74
  26. package/dist/esm/common/BaseSnapExecutor.js.map +1 -1
  27. package/dist/esm/common/commands.js +2 -0
  28. package/dist/esm/common/commands.js.map +1 -1
  29. package/dist/esm/common/endowments/index.js +2 -1
  30. package/dist/esm/common/endowments/index.js.map +1 -1
  31. package/dist/esm/common/endowments/interval.js +2 -1
  32. package/dist/esm/common/endowments/interval.js.map +1 -1
  33. package/dist/esm/common/endowments/timeout.js +2 -1
  34. package/dist/esm/common/endowments/timeout.js.map +1 -1
  35. package/dist/esm/common/globalEvents.js +2 -1
  36. package/dist/esm/common/globalEvents.js.map +1 -1
  37. package/dist/esm/common/globalObject.js.map +1 -1
  38. package/dist/esm/common/utils.js +7 -25
  39. package/dist/esm/common/utils.js.map +1 -1
  40. package/dist/esm/common/validation.js +3 -2
  41. package/dist/esm/common/validation.js.map +1 -1
  42. package/dist/types/common/BaseSnapExecutor.d.ts +2 -3
  43. package/dist/types/common/endowments/index.d.ts +1 -1
  44. package/dist/types/common/utils.d.ts +0 -9
  45. package/package.json +18 -19
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/common/endowments/timeout.ts"],"sourcesContent":["const MINIMUM_TIMEOUT = 10;\n\n/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw new Error(\n `The timeout handler must be a function. Received: ${typeof handler}`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, Math.max(MINIMUM_TIMEOUT, timeout ?? 0));\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: harden(_setTimeout),\n clearTimeout: harden(_clearTimeout),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"],"names":["MINIMUM_TIMEOUT","createTimeout","registeredHandles","Map","_setTimeout","handler","timeout","Error","harden","handle","Object","freeze","create","platformHandle","setTimeout","delete","Math","max","set","_clearTimeout","get","undefined","clearTimeout","teardownFunction","keys","endowmentModule","names","factory"],"mappings":";;;;+BAwDA;;;eAAA;;;AAxDA,MAAMA,kBAAkB;AAExB;;;;;;;;;CASC,GACD,MAAMC,gBAAgB;IACpB,MAAMC,oBAAoB,IAAIC;IAC9B,MAAMC,cAAc,CAACC,SAAuBC;QAC1C,IAAI,OAAOD,YAAY,YAAY;YACjC,MAAM,IAAIE,MACR,CAAC,kDAAkD,EAAE,OAAOF,QAAQ,CAAC;QAEzE;QACAG,OAAOH;QACP,MAAMI,SAASC,OAAOC,MAAM,CAACD,OAAOE,MAAM,CAAC;QAC3C,MAAMC,iBAAiBC,WAAW;YAChCZ,kBAAkBa,MAAM,CAACN;YACzBJ;QACF,GAAGW,KAAKC,GAAG,CAACjB,iBAAiBM,WAAW;QAExCJ,kBAAkBgB,GAAG,CAACT,QAAQI;QAC9B,OAAOJ;IACT;IAEA,MAAMU,gBAAgB,CAACV;QACrB,MAAMI,iBAAiBX,kBAAkBkB,GAAG,CAACX;QAC7C,IAAII,mBAAmBQ,WAAW;YAChCC,aAAaT;YACbX,kBAAkBa,MAAM,CAACN;QAC3B;IACF;IAEA,MAAMc,mBAAmB;QACvB,KAAK,MAAMd,UAAUP,kBAAkBsB,IAAI,GAAI;YAC7CL,cAAcV;QAChB;IACF;IAEA,OAAO;QACLK,YAAYN,OAAOJ;QACnBkB,cAAcd,OAAOW;QACrBI;IACF;AACF;AAEA,MAAME,kBAAkB;IACtBC,OAAO;QAAC;QAAc;KAAe;IACrCC,SAAS1B;AACX;MACA,WAAewB"}
1
+ {"version":3,"sources":["../../../../src/common/endowments/timeout.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\n\nconst MINIMUM_TIMEOUT = 10;\n\n/**\n * Creates a pair of `setTimeout` and `clearTimeout` functions attenuated such\n * that:\n * - `setTimeout` throws if its \"handler\" parameter is not a function.\n * - `clearTimeout` only clears timeouts created by its sibling `setTimeout`,\n * or else no-ops.\n *\n * @returns An object with the attenuated `setTimeout` and `clearTimeout`\n * functions.\n */\nconst createTimeout = () => {\n const registeredHandles = new Map<unknown, unknown>();\n const _setTimeout = (handler: TimerHandler, timeout?: number): unknown => {\n if (typeof handler !== 'function') {\n throw rpcErrors.internal(\n `The timeout handler must be a function. Received: ${typeof handler}.`,\n );\n }\n harden(handler);\n const handle = Object.freeze(Object.create(null));\n const platformHandle = setTimeout(() => {\n registeredHandles.delete(handle);\n handler();\n }, Math.max(MINIMUM_TIMEOUT, timeout ?? 0));\n\n registeredHandles.set(handle, platformHandle);\n return handle;\n };\n\n const _clearTimeout = (handle: unknown): void => {\n const platformHandle = registeredHandles.get(handle);\n if (platformHandle !== undefined) {\n clearTimeout(platformHandle as any);\n registeredHandles.delete(handle);\n }\n };\n\n const teardownFunction = (): void => {\n for (const handle of registeredHandles.keys()) {\n _clearTimeout(handle);\n }\n };\n\n return {\n setTimeout: harden(_setTimeout),\n clearTimeout: harden(_clearTimeout),\n teardownFunction,\n } as const;\n};\n\nconst endowmentModule = {\n names: ['setTimeout', 'clearTimeout'] as const,\n factory: createTimeout,\n};\nexport default endowmentModule;\n"],"names":["MINIMUM_TIMEOUT","createTimeout","registeredHandles","Map","_setTimeout","handler","timeout","rpcErrors","internal","harden","handle","Object","freeze","create","platformHandle","setTimeout","delete","Math","max","set","_clearTimeout","get","undefined","clearTimeout","teardownFunction","keys","endowmentModule","names","factory"],"mappings":";;;;+BA0DA;;;eAAA;;;2BA1D0B;AAE1B,MAAMA,kBAAkB;AAExB;;;;;;;;;CASC,GACD,MAAMC,gBAAgB;IACpB,MAAMC,oBAAoB,IAAIC;IAC9B,MAAMC,cAAc,CAACC,SAAuBC;QAC1C,IAAI,OAAOD,YAAY,YAAY;YACjC,MAAME,oBAAS,CAACC,QAAQ,CACtB,CAAC,kDAAkD,EAAE,OAAOH,QAAQ,CAAC,CAAC;QAE1E;QACAI,OAAOJ;QACP,MAAMK,SAASC,OAAOC,MAAM,CAACD,OAAOE,MAAM,CAAC;QAC3C,MAAMC,iBAAiBC,WAAW;YAChCb,kBAAkBc,MAAM,CAACN;YACzBL;QACF,GAAGY,KAAKC,GAAG,CAAClB,iBAAiBM,WAAW;QAExCJ,kBAAkBiB,GAAG,CAACT,QAAQI;QAC9B,OAAOJ;IACT;IAEA,MAAMU,gBAAgB,CAACV;QACrB,MAAMI,iBAAiBZ,kBAAkBmB,GAAG,CAACX;QAC7C,IAAII,mBAAmBQ,WAAW;YAChCC,aAAaT;YACbZ,kBAAkBc,MAAM,CAACN;QAC3B;IACF;IAEA,MAAMc,mBAAmB;QACvB,KAAK,MAAMd,UAAUR,kBAAkBuB,IAAI,GAAI;YAC7CL,cAAcV;QAChB;IACF;IAEA,OAAO;QACLK,YAAYN,OAAOL;QACnBmB,cAAcd,OAAOW;QACrBI;IACF;AACF;AAEA,MAAME,kBAAkB;IACtBC,OAAO;QAAC;QAAc;KAAe;IACrCC,SAAS3B;AACX;MACA,WAAeyB"}
@@ -16,6 +16,7 @@ _export(exports, {
16
16
  return removeEventListener;
17
17
  }
18
18
  });
19
+ const _rpcerrors = require("@metamask/rpc-errors");
19
20
  const _globalObject = require("./globalObject");
20
21
  function addEventListener(event, listener) {
21
22
  if ('addEventListener' in _globalObject.rootRealmGlobal && typeof _globalObject.rootRealmGlobal.addEventListener === 'function') {
@@ -24,7 +25,7 @@ function addEventListener(event, listener) {
24
25
  if (_globalObject.rootRealmGlobal.process && 'on' in _globalObject.rootRealmGlobal.process && typeof _globalObject.rootRealmGlobal.process.on === 'function') {
25
26
  return _globalObject.rootRealmGlobal.process.on(event, listener);
26
27
  }
27
- throw new Error('Platform agnostic addEventListener failed');
28
+ throw _rpcerrors.rpcErrors.internal('Platform agnostic addEventListener failed.');
28
29
  }
29
30
  function removeEventListener(event, listener) {
30
31
  if ('removeEventListener' in _globalObject.rootRealmGlobal && typeof _globalObject.rootRealmGlobal.removeEventListener === 'function') {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/globalEvents.ts"],"sourcesContent":["import { rootRealmGlobal } from './globalObject';\n\n/**\n * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`\n *\n * @param event - The event to listen for.\n * @param listener - The listener to be triggered when the event occurs.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function addEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'addEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.addEventListener === 'function'\n ) {\n return rootRealmGlobal.addEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'on' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.on === 'function'\n ) {\n return rootRealmGlobal.process.on(event, listener);\n }\n\n throw new Error('Platform agnostic addEventListener failed');\n}\n\n/**\n * Removes an event listener platform agnostically, trying both `globalThis.removeEventListener` and `globalThis.process.removeListener`\n *\n * @param event - The event to remove the listener for.\n * @param listener - The currently attached listener.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function removeEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'removeEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.removeEventListener === 'function'\n ) {\n return rootRealmGlobal.removeEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'removeListener' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.removeListener === 'function'\n ) {\n return rootRealmGlobal.process.removeListener(event, listener);\n }\n\n throw new Error('Platform agnostic removeEventListener failed');\n}\n"],"names":["addEventListener","removeEventListener","event","listener","rootRealmGlobal","toLowerCase","process","on","Error","removeListener"],"mappings":";;;;;;;;;;;IAUgBA,gBAAgB;eAAhBA;;IA8BAC,mBAAmB;eAAnBA;;;8BAxCgB;AAUzB,SAASD,iBACdE,KAAa,EACbC,QAAkC;IAElC,IACE,sBAAsBC,6BAAe,IACrC,OAAOA,6BAAe,CAACJ,gBAAgB,KAAK,YAC5C;QACA,OAAOI,6BAAe,CAACJ,gBAAgB,CAACE,MAAMG,WAAW,IAAIF;IAC/D;IAEA,IACEC,6BAAe,CAACE,OAAO,IACvB,QAAQF,6BAAe,CAACE,OAAO,IAC/B,OAAOF,6BAAe,CAACE,OAAO,CAACC,EAAE,KAAK,YACtC;QACA,OAAOH,6BAAe,CAACE,OAAO,CAACC,EAAE,CAACL,OAAOC;IAC3C;IAEA,MAAM,IAAIK,MAAM;AAClB;AAUO,SAASP,oBACdC,KAAa,EACbC,QAAkC;IAElC,IACE,yBAAyBC,6BAAe,IACxC,OAAOA,6BAAe,CAACH,mBAAmB,KAAK,YAC/C;QACA,OAAOG,6BAAe,CAACH,mBAAmB,CAACC,MAAMG,WAAW,IAAIF;IAClE;IAEA,IACEC,6BAAe,CAACE,OAAO,IACvB,oBAAoBF,6BAAe,CAACE,OAAO,IAC3C,OAAOF,6BAAe,CAACE,OAAO,CAACG,cAAc,KAAK,YAClD;QACA,OAAOL,6BAAe,CAACE,OAAO,CAACG,cAAc,CAACP,OAAOC;IACvD;IAEA,MAAM,IAAIK,MAAM;AAClB"}
1
+ {"version":3,"sources":["../../../src/common/globalEvents.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\n\nimport { rootRealmGlobal } from './globalObject';\n\n/**\n * Adds an event listener platform agnostically, trying both `globalThis.addEventListener` and `globalThis.process.on`\n *\n * @param event - The event to listen for.\n * @param listener - The listener to be triggered when the event occurs.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function addEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'addEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.addEventListener === 'function'\n ) {\n return rootRealmGlobal.addEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'on' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.on === 'function'\n ) {\n return rootRealmGlobal.process.on(event, listener);\n }\n\n throw rpcErrors.internal('Platform agnostic addEventListener failed.');\n}\n\n/**\n * Removes an event listener platform agnostically, trying both `globalThis.removeEventListener` and `globalThis.process.removeListener`\n *\n * @param event - The event to remove the listener for.\n * @param listener - The currently attached listener.\n * @returns The result of the platform agnostic operation if any.\n * @throws If none of the platform options are present.\n */\nexport function removeEventListener(\n event: string,\n listener: (...args: any[]) => void,\n) {\n if (\n 'removeEventListener' in rootRealmGlobal &&\n typeof rootRealmGlobal.removeEventListener === 'function'\n ) {\n return rootRealmGlobal.removeEventListener(event.toLowerCase(), listener);\n }\n\n if (\n rootRealmGlobal.process &&\n 'removeListener' in rootRealmGlobal.process &&\n typeof rootRealmGlobal.process.removeListener === 'function'\n ) {\n return rootRealmGlobal.process.removeListener(event, listener);\n }\n\n throw new Error('Platform agnostic removeEventListener failed');\n}\n"],"names":["addEventListener","removeEventListener","event","listener","rootRealmGlobal","toLowerCase","process","on","rpcErrors","internal","removeListener","Error"],"mappings":";;;;;;;;;;;IAYgBA,gBAAgB;eAAhBA;;IA8BAC,mBAAmB;eAAnBA;;;2BA1CU;8BAEM;AAUzB,SAASD,iBACdE,KAAa,EACbC,QAAkC;IAElC,IACE,sBAAsBC,6BAAe,IACrC,OAAOA,6BAAe,CAACJ,gBAAgB,KAAK,YAC5C;QACA,OAAOI,6BAAe,CAACJ,gBAAgB,CAACE,MAAMG,WAAW,IAAIF;IAC/D;IAEA,IACEC,6BAAe,CAACE,OAAO,IACvB,QAAQF,6BAAe,CAACE,OAAO,IAC/B,OAAOF,6BAAe,CAACE,OAAO,CAACC,EAAE,KAAK,YACtC;QACA,OAAOH,6BAAe,CAACE,OAAO,CAACC,EAAE,CAACL,OAAOC;IAC3C;IAEA,MAAMK,oBAAS,CAACC,QAAQ,CAAC;AAC3B;AAUO,SAASR,oBACdC,KAAa,EACbC,QAAkC;IAElC,IACE,yBAAyBC,6BAAe,IACxC,OAAOA,6BAAe,CAACH,mBAAmB,KAAK,YAC/C;QACA,OAAOG,6BAAe,CAACH,mBAAmB,CAACC,MAAMG,WAAW,IAAIF;IAClE;IAEA,IACEC,6BAAe,CAACE,OAAO,IACvB,oBAAoBF,6BAAe,CAACE,OAAO,IAC3C,OAAOF,6BAAe,CAACE,OAAO,CAACI,cAAc,KAAK,YAClD;QACA,OAAON,6BAAe,CAACE,OAAO,CAACI,cAAc,CAACR,OAAOC;IACvD;IAEA,MAAM,IAAIQ,MAAM;AAClB"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/globalObject.ts"],"sourcesContent":["enum GlobalObjectNames {\n // The globalThis entry is incorrectly identified as shadowing the global\n // globalThis.\n /* eslint-disable @typescript-eslint/naming-convention */\n // eslint-disable-next-line @typescript-eslint/no-shadow\n globalThis = 'globalThis',\n global = 'global',\n self = 'self',\n window = 'window',\n /* eslint-enavle @typescript-eslint/naming-convention */\n}\n\nlet _rootRealmGlobal: typeof globalThis;\nlet _rootRealmGlobalName: string;\n\n/* istanbul ignore next */\n/* eslint-disable no-negated-condition */\nif (typeof globalThis !== 'undefined') {\n _rootRealmGlobal = globalThis;\n _rootRealmGlobalName = GlobalObjectNames.globalThis;\n} else if (typeof self !== 'undefined') {\n _rootRealmGlobal = self;\n _rootRealmGlobalName = GlobalObjectNames.self;\n} else if (typeof window !== 'undefined') {\n _rootRealmGlobal = window;\n _rootRealmGlobalName = GlobalObjectNames.window;\n} else if (typeof global !== 'undefined') {\n _rootRealmGlobal = global;\n _rootRealmGlobalName = GlobalObjectNames.global;\n} else {\n throw new Error('Unknown realm type; failed to identify global object.');\n}\n/* eslint-enable no-negated-condition */\n\n/**\n * A platform-agnostic alias for the root realm global object.\n */\nconst rootRealmGlobal = _rootRealmGlobal;\n\n/**\n * The string literal corresponding to the name of the root realm global object.\n */\nconst rootRealmGlobalName = _rootRealmGlobalName;\n\nexport { rootRealmGlobal, rootRealmGlobalName };\n"],"names":["rootRealmGlobal","rootRealmGlobalName","GlobalObjectNames","globalThis","global","self","window","_rootRealmGlobal","_rootRealmGlobalName","Error"],"mappings":";;;;;;;;;;;IA4CSA,eAAe;eAAfA;;IAAiBC,mBAAmB;eAAnBA;;;IA5C1B;UAAKC,iBAAiB;IAAjBA,kBACH,yEAAyE;IACzE,cAAc;IACd,uDAAuD,GACvD,wDAAwD;IACxDC,gBAAAA;IALGD,kBAMHE,YAAAA;IANGF,kBAOHG,UAAAA;IAPGH,kBAQHI,YAAAA;GARGJ,sBAAAA;AAYL,IAAIK;AACJ,IAAIC;AAEJ,wBAAwB,GACxB,uCAAuC,GACvC,IAAI,OAAOL,eAAe,aAAa;IACrCI,mBAAmBJ;IACnBK,uBAAuBN,kBAAkBC,UAAU;AACrD,OAAO,IAAI,OAAOE,SAAS,aAAa;IACtCE,mBAAmBF;IACnBG,uBAAuBN,kBAAkBG,IAAI;AAC/C,OAAO,IAAI,OAAOC,WAAW,aAAa;IACxCC,mBAAmBD;IACnBE,uBAAuBN,kBAAkBI,MAAM;AACjD,OAAO,IAAI,OAAOF,WAAW,aAAa;IACxCG,mBAAmBH;IACnBI,uBAAuBN,kBAAkBE,MAAM;AACjD,OAAO;IACL,MAAM,IAAIK,MAAM;AAClB;AACA,sCAAsC,GAEtC;;CAEC,GACD,MAAMT,kBAAkBO;AAExB;;CAEC,GACD,MAAMN,sBAAsBO"}
1
+ {"version":3,"sources":["../../../src/common/globalObject.ts"],"sourcesContent":["enum GlobalObjectNames {\n // The globalThis entry is incorrectly identified as shadowing the global\n // globalThis.\n /* eslint-disable @typescript-eslint/naming-convention */\n // eslint-disable-next-line @typescript-eslint/no-shadow\n globalThis = 'globalThis',\n global = 'global',\n self = 'self',\n window = 'window',\n /* eslint-enable @typescript-eslint/naming-convention */\n}\n\nlet _rootRealmGlobal: typeof globalThis;\nlet _rootRealmGlobalName: string;\n\n/* istanbul ignore next */\n/* eslint-disable no-negated-condition */\nif (typeof globalThis !== 'undefined') {\n _rootRealmGlobal = globalThis;\n _rootRealmGlobalName = GlobalObjectNames.globalThis;\n} else if (typeof self !== 'undefined') {\n _rootRealmGlobal = self;\n _rootRealmGlobalName = GlobalObjectNames.self;\n} else if (typeof window !== 'undefined') {\n _rootRealmGlobal = window;\n _rootRealmGlobalName = GlobalObjectNames.window;\n} else if (typeof global !== 'undefined') {\n _rootRealmGlobal = global;\n _rootRealmGlobalName = GlobalObjectNames.global;\n} else {\n throw new Error('Unknown realm type; failed to identify global object.');\n}\n/* eslint-enable no-negated-condition */\n\n/**\n * A platform-agnostic alias for the root realm global object.\n */\nconst rootRealmGlobal = _rootRealmGlobal;\n\n/**\n * The string literal corresponding to the name of the root realm global object.\n */\nconst rootRealmGlobalName = _rootRealmGlobalName;\n\nexport { rootRealmGlobal, rootRealmGlobalName };\n"],"names":["rootRealmGlobal","rootRealmGlobalName","GlobalObjectNames","globalThis","global","self","window","_rootRealmGlobal","_rootRealmGlobalName","Error"],"mappings":";;;;;;;;;;;IA4CSA,eAAe;eAAfA;;IAAiBC,mBAAmB;eAAnBA;;;IA5C1B;UAAKC,iBAAiB;IAAjBA,kBACH,yEAAyE;IACzE,cAAc;IACd,uDAAuD,GACvD,wDAAwD;IACxDC,gBAAAA;IALGD,kBAMHE,YAAAA;IANGF,kBAOHG,UAAAA;IAPGH,kBAQHI,YAAAA;GARGJ,sBAAAA;AAYL,IAAIK;AACJ,IAAIC;AAEJ,wBAAwB,GACxB,uCAAuC,GACvC,IAAI,OAAOL,eAAe,aAAa;IACrCI,mBAAmBJ;IACnBK,uBAAuBN,kBAAkBC,UAAU;AACrD,OAAO,IAAI,OAAOE,SAAS,aAAa;IACtCE,mBAAmBF;IACnBG,uBAAuBN,kBAAkBG,IAAI;AAC/C,OAAO,IAAI,OAAOC,WAAW,aAAa;IACxCC,mBAAmBD;IACnBE,uBAAuBN,kBAAkBI,MAAM;AACjD,OAAO,IAAI,OAAOF,WAAW,aAAa;IACxCG,mBAAmBH;IACnBI,uBAAuBN,kBAAkBE,MAAM;AACjD,OAAO;IACL,MAAM,IAAIK,MAAM;AAClB;AACA,sCAAsC,GAEtC;;CAEC,GACD,MAAMT,kBAAkBO;AAExB;;CAEC,GACD,MAAMN,sBAAsBO"}
@@ -9,9 +9,6 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
- constructError: function() {
13
- return constructError;
14
- },
15
12
  withTeardown: function() {
16
13
  return withTeardown;
17
14
  },
@@ -31,20 +28,9 @@ _export(exports, {
31
28
  return sanitizeRequestArguments;
32
29
  }
33
30
  });
31
+ const _rpcerrors = require("@metamask/rpc-errors");
34
32
  const _utils = require("@metamask/utils");
35
- const _ethrpcerrors = require("eth-rpc-errors");
36
33
  const _logging = require("../logging");
37
- function constructError(originalError) {
38
- let _originalError;
39
- if (originalError instanceof Error) {
40
- _originalError = originalError;
41
- } else if (typeof originalError === 'string') {
42
- _originalError = new Error(originalError);
43
- // The stack is useless in this case.
44
- delete _originalError.stack;
45
- }
46
- return _originalError;
47
- }
48
34
  async function withTeardown(originalPromise, teardownRef) {
49
35
  const myTeardown = teardownRef.lastTeardown;
50
36
  return new Promise((resolve, reject)=>{
@@ -109,27 +95,27 @@ const BLOCKED_RPC_METHODS = Object.freeze([
109
95
  ]);
110
96
  function assertSnapOutboundRequest(args) {
111
97
  // Disallow any non `wallet_` or `snap_` methods for separation of concerns.
112
- (0, _utils.assert)(String.prototype.startsWith.call(args.method, 'wallet_') || String.prototype.startsWith.call(args.method, 'snap_'), 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.');
113
- (0, _utils.assert)(!BLOCKED_RPC_METHODS.includes(args.method), _ethrpcerrors.ethErrors.rpc.methodNotFound({
98
+ (0, _utils.assert)(String.prototype.startsWith.call(args.method, 'wallet_') || String.prototype.startsWith.call(args.method, 'snap_'), 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.', _rpcerrors.rpcErrors.methodNotSupported);
99
+ (0, _utils.assert)(!BLOCKED_RPC_METHODS.includes(args.method), _rpcerrors.rpcErrors.methodNotFound({
114
100
  data: {
115
101
  method: args.method
116
102
  }
117
103
  }));
118
- (0, _utils.assertStruct)(args, _utils.JsonStruct, 'Provided value is not JSON-RPC compatible');
104
+ (0, _utils.assertStruct)(args, _utils.JsonStruct, 'Provided value is not JSON-RPC compatible', _rpcerrors.rpcErrors.invalidParams);
119
105
  }
120
106
  function assertEthereumOutboundRequest(args) {
121
107
  // Disallow snaps methods for separation of concerns.
122
- (0, _utils.assert)(!String.prototype.startsWith.call(args.method, 'snap_'), _ethrpcerrors.ethErrors.rpc.methodNotFound({
108
+ (0, _utils.assert)(!String.prototype.startsWith.call(args.method, 'snap_'), _rpcerrors.rpcErrors.methodNotFound({
123
109
  data: {
124
110
  method: args.method
125
111
  }
126
112
  }));
127
- (0, _utils.assert)(!BLOCKED_RPC_METHODS.includes(args.method), _ethrpcerrors.ethErrors.rpc.methodNotFound({
113
+ (0, _utils.assert)(!BLOCKED_RPC_METHODS.includes(args.method), _rpcerrors.rpcErrors.methodNotFound({
128
114
  data: {
129
115
  method: args.method
130
116
  }
131
117
  }));
132
- (0, _utils.assertStruct)(args, _utils.JsonStruct, 'Provided value is not JSON-RPC compatible');
118
+ (0, _utils.assertStruct)(args, _utils.JsonStruct, 'Provided value is not JSON-RPC compatible', _rpcerrors.rpcErrors.invalidParams);
133
119
  }
134
120
  function sanitizeRequestArguments(value) {
135
121
  // Before passing to getSafeJson we run the value through JSON serialization.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { assert, assertStruct, getSafeJson, JsonStruct } from '@metamask/utils';\nimport { ethErrors } from 'eth-rpc-errors';\n\nimport { log } from '../logging';\n\n/**\n * Takes an error that was thrown, determines if it is\n * an error object. If it is then it will return that. Otherwise,\n * an error object is created with the original error message.\n *\n * @param originalError - The error that was originally thrown.\n * @returns An error object.\n */\nexport function constructError(originalError: unknown) {\n let _originalError: Error | undefined;\n if (originalError instanceof Error) {\n _originalError = originalError;\n } else if (typeof originalError === 'string') {\n _originalError = new Error(originalError);\n // The stack is useless in this case.\n delete _originalError.stack;\n }\n return _originalError;\n}\n\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\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 proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendRawTransaction',\n 'eth_sendTransaction',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n ethErrors.rpc.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(args, JsonStruct, 'Provided value is not JSON-RPC compatible');\n}\n\n/**\n * Gets a sanitized value to be used for passing to the underlying MetaMask provider.\n *\n * @param value - An unsanitized value from a snap.\n * @returns A sanitized value ready to be passed to a MetaMask provider.\n */\nexport function sanitizeRequestArguments(value: unknown): RequestArguments {\n // Before passing to getSafeJson we run the value through JSON serialization.\n // This lets request arguments contain undefined which is normally disallowed.\n const json = JSON.parse(JSON.stringify(value));\n return getSafeJson(json) as RequestArguments;\n}\n"],"names":["constructError","withTeardown","proxyStreamProvider","BLOCKED_RPC_METHODS","assertSnapOutboundRequest","assertEthereumOutboundRequest","sanitizeRequestArguments","originalError","_originalError","Error","stack","originalPromise","teardownRef","myTeardown","lastTeardown","Promise","resolve","reject","then","value","log","catch","reason","provider","request","proxy","Proxy","has","_target","prop","includes","get","undefined","Object","freeze","args","assert","String","prototype","startsWith","call","method","ethErrors","rpc","methodNotFound","data","assertStruct","JsonStruct","json","JSON","parse","stringify","getSafeJson"],"mappings":";;;;;;;;;;;IAegBA,cAAc;eAAdA;;IAsBMC,YAAY;eAAZA;;IAoCNC,mBAAmB;eAAnBA;;IA+BHC,mBAAmB;eAAnBA;;IAyBGC,yBAAyB;eAAzBA;;IAuBAC,6BAA6B;eAA7BA;;IA2BAC,wBAAwB;eAAxBA;;;uBAjL8C;8BACpC;yBAEN;AAUb,SAASN,eAAeO,aAAsB;IACnD,IAAIC;IACJ,IAAID,yBAAyBE,OAAO;QAClCD,iBAAiBD;IACnB,OAAO,IAAI,OAAOA,kBAAkB,UAAU;QAC5CC,iBAAiB,IAAIC,MAAMF;QAC3B,qCAAqC;QACrC,OAAOC,eAAeE,KAAK;IAC7B;IACA,OAAOF;AACT;AAYO,eAAeP,aACpBU,eAA8B,EAC9BC,WAAqC;IAErC,MAAMC,aAAaD,YAAYE,YAAY;IAC3C,OAAO,IAAIC,QAAc,CAACC,SAASC;QACjCN,gBACGO,IAAI,CAAC,CAACC;YACL,IAAIP,YAAYE,YAAY,KAAKD,YAAY;gBAC3CG,QAAQG;YACV,OAAO;gBACLC,IAAAA,YAAG,EACD;YAEJ;QACF,GACCC,KAAK,C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J,CAACC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACL,KAAKM,MAAM,EAAE,UAC/CC,uBAAS,CAACC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFL,IAAAA,aAAM,EACJ,CAACjC,oBAAoB2B,QAAQ,CAACK,KAAKM,MAAM,GACzCC,uBAAS,CAACC,GAAG,CAACC,cAAc,CAAC;QAC3BC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EAACX,MAAMY,iBAAU,EAAE;AACjC;AAQO,SAASzC,yBAAyBa,KAAc;IACrD,6EAA6E;IAC7E,8EAA8E;IAC9E,MAAM6B,OAAOC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAAChC;IACvC,OAAOiC,IAAAA,kBAAW,EAACJ;AACrB"}
1
+ {"version":3,"sources":["../../../src/common/utils.ts"],"sourcesContent":["import type { StreamProvider } from '@metamask/providers';\nimport type { RequestArguments } from '@metamask/providers/dist/BaseProvider';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport { assert, assertStruct, getSafeJson, JsonStruct } from '@metamask/utils';\n\nimport { log } from '../logging';\n/**\n * Make proxy for Promise and handle the teardown process properly.\n * If the teardown is called in the meanwhile, Promise result will not be\n * exposed to the snap anymore and warning will be logged to the console.\n *\n * @param originalPromise - Original promise.\n * @param teardownRef - Reference containing teardown count.\n * @param teardownRef.lastTeardown - Number of the last teardown.\n * @returns New proxy promise.\n */\nexport async function withTeardown<Type>(\n originalPromise: Promise<Type>,\n teardownRef: { lastTeardown: number },\n): Promise<Type> {\n const myTeardown = teardownRef.lastTeardown;\n return new Promise<Type>((resolve, reject) => {\n originalPromise\n .then((value) => {\n if (teardownRef.lastTeardown === myTeardown) {\n resolve(value);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n })\n .catch((reason) => {\n if (teardownRef.lastTeardown === myTeardown) {\n reject(reason);\n } else {\n log(\n 'Late promise received after Snap finished execution. Promise will be dropped.',\n );\n }\n });\n });\n}\n\n/**\n * Returns a Proxy that narrows down (attenuates) the fields available on\n * the StreamProvider and replaces the request implementation.\n *\n * @param provider - Instance of a StreamProvider to be limited.\n * @param request - Custom attenuated request object.\n * @returns Proxy to the StreamProvider instance.\n */\nexport function proxyStreamProvider(\n provider: StreamProvider,\n request: unknown,\n): StreamProvider {\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 proxy = new Proxy(\n {},\n {\n has(_target: object, prop: string | symbol) {\n return (\n typeof prop === 'string' &&\n ['request', 'on', 'removeListener'].includes(prop)\n );\n },\n get(_target, prop: keyof StreamProvider) {\n if (prop === 'request') {\n return request;\n } else if (['on', 'removeListener'].includes(prop)) {\n return provider[prop];\n }\n\n return undefined;\n },\n },\n );\n\n return proxy as StreamProvider;\n}\n\n// We're blocking these RPC methods for v1, will revisit later.\nexport const BLOCKED_RPC_METHODS = Object.freeze([\n 'wallet_requestSnaps',\n 'wallet_requestPermissions',\n // We disallow all of these confirmations for now, since the screens are not ready for Snaps.\n 'eth_sendRawTransaction',\n 'eth_sendTransaction',\n 'eth_sign',\n 'eth_signTypedData',\n 'eth_signTypedData_v1',\n 'eth_signTypedData_v3',\n 'eth_signTypedData_v4',\n 'eth_decrypt',\n 'eth_getEncryptionPublicKey',\n 'wallet_addEthereumChain',\n 'wallet_switchEthereumChain',\n 'wallet_watchAsset',\n 'wallet_registerOnboarding',\n 'wallet_scanQRCode',\n]);\n\n/**\n * Asserts the validity of request arguments for a snap outbound request using the `snap.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertSnapOutboundRequest(args: RequestArguments) {\n // Disallow any non `wallet_` or `snap_` methods for separation of concerns.\n assert(\n String.prototype.startsWith.call(args.method, 'wallet_') ||\n String.prototype.startsWith.call(args.method, 'snap_'),\n 'The global Snap API only allows RPC methods starting with `wallet_*` and `snap_*`.',\n rpcErrors.methodNotSupported,\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Asserts the validity of request arguments for an ethereum outbound request using the `ethereum.request` API.\n *\n * @param args - The arguments to validate.\n */\nexport function assertEthereumOutboundRequest(args: RequestArguments) {\n // Disallow snaps methods for separation of concerns.\n assert(\n !String.prototype.startsWith.call(args.method, 'snap_'),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assert(\n !BLOCKED_RPC_METHODS.includes(args.method),\n rpcErrors.methodNotFound({\n data: {\n method: args.method,\n },\n }),\n );\n assertStruct(\n args,\n JsonStruct,\n 'Provided value is not JSON-RPC compatible',\n rpcErrors.invalidParams,\n );\n}\n\n/**\n * Gets a sanitized value to be used for passing to the underlying MetaMask provider.\n *\n * @param value - An unsanitized value from a snap.\n * @returns A sanitized value ready to be passed to a MetaMask provider.\n */\nexport function sanitizeRequestArguments(value: unknown): RequestArguments {\n // Before passing to getSafeJson we run the value through JSON serialization.\n // This lets request arguments contain undefined which is normally disallowed.\n const json = JSON.parse(JSON.stringify(value));\n return getSafeJson(json) as RequestArguments;\n}\n"],"names":["withTeardown","proxyStreamProvider","BLOCKED_RPC_METHODS","assertSnapOutboundRequest","assertEthereumOutboundRequest","sanitizeRequestArguments","originalPromise","teardownRef","myTeardown","lastTeardown","Promise","resolve","reject","then","value","log","catch","reason","provider","request","proxy","Proxy","has","_target","prop","includes","get","undefined","Object","freeze","args","assert","String","prototype","startsWith","call","method","rpcErrors","methodNotSupported","methodNotFound","data","assertStruct","JsonStruct","invalidParams","json","JSON","parse","stringify","getSafeJson"],"mappings":";;;;;;;;;;;IAgBsBA,YAAY;eAAZA;;IAoCNC,mBAAmB;eAAnBA;;IA+BHC,mBAAmB;eAAnBA;;IAyBGC,yBAAyB;eAAzBA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C,UAAU,CAACC,IAAI,CAACL,KAAKM,MAAM,EAAE,UAChD,sFACAC,oBAAS,CAACC,kBAAkB;IAE9BP,IAAAA,aAAM,EACJ,CAAC7B,oBAAoBuB,QAAQ,CAACK,KAAKM,MAAM,GACzCC,oBAAS,CAACE,cAAc,CAAC;QACvBC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EACVX,MACAY,iBAAU,EACV,6CACAL,oBAAS,CAACM,aAAa;AAE3B;AAOO,SAASvC,8BAA8B0B,IAAsB;IAClE,qDAAqD;IACrDC,IAAAA,aAAM,EACJ,CAACC,OAAOC,SAAS,CAACC,UAAU,CAACC,IAAI,CAACL,KAAKM,MAAM,EAAE,UAC/CC,oBAAS,CAACE,cAAc,CAAC;QACvBC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFL,IAAAA,aAAM,EACJ,CAAC7B,oBAAoBuB,QAAQ,CAACK,KAAKM,MAAM,GACzCC,oBAAS,CAACE,cAAc,CAAC;QACvBC,MAAM;YACJJ,QAAQN,KAAKM,MAAM;QACrB;IACF;IAEFK,IAAAA,mBAAY,EACVX,MACAY,iBAAU,EACV,6CACAL,oBAAS,CAACM,aAAa;AAE3B;AAQO,SAAStC,yBAAyBS,KAAc;IACrD,6EAA6E;IAC7E,8EAA8E;IAC9E,MAAM8B,OAAOC,KAAKC,KAAK,CAACD,KAAKE,SAAS,CAACjC;IACvC,OAAOkC,IAAAA,kBAAW,EAACJ;AACrB"}
@@ -46,6 +46,7 @@ _export(exports, {
46
46
  return assertIsOnNameLookupRequestArguments;
47
47
  }
48
48
  });
49
+ const _rpcerrors = require("@metamask/rpc-errors");
49
50
  const _snapsutils = require("@metamask/snaps-utils");
50
51
  const _utils = require("@metamask/utils");
51
52
  const _superstruct = require("superstruct");
@@ -90,7 +91,7 @@ const OnTransactionRequestArgumentsStruct = (0, _superstruct.object)({
90
91
  transactionOrigin: (0, _superstruct.nullable)((0, _superstruct.string)())
91
92
  });
92
93
  function assertIsOnTransactionRequestArguments(value) {
93
- (0, _utils.assertStruct)(value, OnTransactionRequestArgumentsStruct, 'Invalid request params');
94
+ (0, _utils.assertStruct)(value, OnTransactionRequestArgumentsStruct, 'Invalid request params', _rpcerrors.rpcErrors.invalidParams);
94
95
  }
95
96
  const baseNameLookupArgs = {
96
97
  chainId: _snapsutils.ChainIdStruct
@@ -108,7 +109,7 @@ const OnNameLookupRequestArgumentsStruct = (0, _superstruct.union)([
108
109
  addressRequestStruct
109
110
  ]);
110
111
  function assertIsOnNameLookupRequestArguments(value) {
111
- (0, _utils.assertStruct)(value, OnNameLookupRequestArgumentsStruct, 'Invalid request params');
112
+ (0, _utils.assertStruct)(value, OnNameLookupRequestArgumentsStruct, 'Invalid request params', _rpcerrors.rpcErrors.invalidParams);
112
113
  }
113
114
  const OkResponseStruct = (0, _superstruct.assign)(_utils.JsonRpcSuccessStruct, (0, _superstruct.object)({
114
115
  result: OkStruct
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","assign","omit","JsonRpcRequestStruct","object","id","optional","JsonRpcIdStruct","string","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","HandlerType","params","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct","domain","OkResponseStruct","JsonRpcSuccessStruct","result","SnapRpcResponse"],"mappings":";;;;;;;;;;;IA0BaA,6BAA6B;eAA7BA;;IAWAC,eAAe;eAAfA;;IASGC,WAAW;eAAXA;;IAUAC,iBAAiB;eAAjBA;;IAMHC,0BAA0B;eAA1BA;;IAIAC,+BAA+B;eAA/BA;;IAKAC,iCAAiC;eAAjCA;;IAMAC,6BAA6B;eAA7BA;;IA+BAC,mCAAmC;eAAnCA;;IAmBGC,qCAAqC;eAArCA;;IAoBHC,kCAAkC;eAAlCA;;IAsBGC,oCAAoC;eAApCA;;;4BAzK2B;uBAQpC;6BAgBA;AAEA,MAAMX,gCAAgCY,IAAAA,mBAAM,EACjDC,IAAAA,iBAAI,EAACC,2BAAoB,EAAE;IAAC;CAAK,GACjCC,IAAAA,mBAAM,EAAC;IACLC,IAAIC,IAAAA,qBAAQ,EAACC,sBAAe;AAC9B;AAOK,MAAMjB,kBAAkBkB,IAAAA,mBAAM;AAS9B,SAASjB,YAAYkB,KAAc;IACxC,OAAOC,IAAAA,eAAE,EAACD,OAAOnB;AACnB;AAQO,SAASE,kBAAkBiB,KAAc;IAC9C,OAAOE,MAAMC,OAAO,CAACH,UAAUA,MAAMI,KAAK,CAACtB;AAC7C;AAEA,MAAMuB,WAAWC,IAAAA,oBAAO,EAAC;AAElB,MAAMtB,6BAA6Ba,IAAAA,qBAAQ,EAChDU,IAAAA,kBAAK,EAAC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;IAEduB,IAAAA,mBAAY,EACVvB,OACAV,oCACA;AAEJ;AAEA,MAAMuC,mBAAmBrC,IAAAA,mBAAM,EAC7BsC,2BAAoB,EACpBnC,IAAAA,mBAAM,EAAC;IACLoC,QAAQ1B;AACV;AAGF,MAAM2B,kBAAkBF,2BAAoB"}
1
+ {"version":3,"sources":["../../../src/common/validation.ts"],"sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport { ChainIdStruct, HandlerType } from '@metamask/snaps-utils';\nimport type { Json, JsonRpcSuccess } from '@metamask/utils';\nimport {\n assertStruct,\n JsonRpcIdStruct,\n JsonRpcRequestStruct,\n JsonRpcSuccessStruct,\n JsonStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n enums,\n is,\n literal,\n nullable,\n object,\n omit,\n optional,\n record,\n string,\n tuple,\n union,\n} from 'superstruct';\n\nexport const JsonRpcRequestWithoutIdStruct = assign(\n omit(JsonRpcRequestStruct, ['id']),\n object({\n id: optional(JsonRpcIdStruct),\n }),\n);\n\nexport type JsonRpcRequestWithoutId = Infer<\n typeof JsonRpcRequestWithoutIdStruct\n>;\n\nexport const EndowmentStruct = string();\nexport type Endowment = Infer<typeof EndowmentStruct>;\n\n/**\n * Check if the given value is an endowment.\n *\n * @param value - The value to check.\n * @returns Whether the value is an endowment.\n */\nexport function isEndowment(value: unknown): value is Endowment {\n return is(value, EndowmentStruct);\n}\n\n/**\n * Check if the given value is an array of endowments.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of endowments.\n */\nexport function isEndowmentsArray(value: unknown): value is Endowment[] {\n return Array.isArray(value) && value.every(isEndowment);\n}\n\nconst OkStruct = literal('OK');\n\nexport const PingRequestArgumentsStruct = optional(\n union([literal(undefined), array()]),\n);\n\nexport const TerminateRequestArgumentsStruct = union([\n literal(undefined),\n array(),\n]);\n\nexport const ExecuteSnapRequestArgumentsStruct = tuple([\n string(),\n string(),\n optional(array(EndowmentStruct)),\n]);\n\nexport const SnapRpcRequestArgumentsStruct = tuple([\n string(),\n enums(Object.values(HandlerType)),\n string(),\n assign(\n JsonRpcRequestWithoutIdStruct,\n object({\n params: optional(record(string(), JsonStruct)),\n }),\n ),\n]);\n\nexport type PingRequestArguments = Infer<typeof PingRequestArgumentsStruct>;\nexport type TerminateRequestArguments = Infer<\n typeof TerminateRequestArgumentsStruct\n>;\n\nexport type ExecuteSnapRequestArguments = Infer<\n typeof ExecuteSnapRequestArgumentsStruct\n>;\n\nexport type SnapRpcRequestArguments = Infer<\n typeof SnapRpcRequestArgumentsStruct\n>;\n\nexport type RequestArguments =\n | PingRequestArguments\n | TerminateRequestArguments\n | ExecuteSnapRequestArguments\n | SnapRpcRequestArguments;\n\nexport const OnTransactionRequestArgumentsStruct = object({\n // TODO: Improve `transaction` type.\n transaction: record(string(), JsonStruct),\n chainId: ChainIdStruct,\n transactionOrigin: nullable(string()),\n});\n\nexport type OnTransactionRequestArguments = Infer<\n typeof OnTransactionRequestArgumentsStruct\n>;\n\n/**\n * Asserts that the given value is a valid {@link OnTransactionRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnTransactionRequestArguments}\n * object.\n */\nexport function assertIsOnTransactionRequestArguments(\n value: unknown,\n): asserts value is OnTransactionRequestArguments {\n assertStruct(\n value,\n OnTransactionRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst baseNameLookupArgs = { chainId: ChainIdStruct };\nconst domainRequestStruct = object({\n ...baseNameLookupArgs,\n address: string(),\n});\nconst addressRequestStruct = object({\n ...baseNameLookupArgs,\n domain: string(),\n});\n\nexport const OnNameLookupRequestArgumentsStruct = union([\n domainRequestStruct,\n addressRequestStruct,\n]);\n\nexport type OnNameLookupRequestArguments = Infer<\n typeof OnNameLookupRequestArgumentsStruct\n>;\n\nexport type PossibleLookupRequestArgs = typeof baseNameLookupArgs & {\n address?: string;\n domain?: string;\n};\n\n/**\n * Asserts that the given value is a valid {@link OnNameLookupRequestArguments}\n * object.\n *\n * @param value - The value to validate.\n * @throws If the value is not a valid {@link OnNameLookupRequestArguments}\n * object.\n */\nexport function assertIsOnNameLookupRequestArguments(\n value: unknown,\n): asserts value is OnNameLookupRequestArguments {\n assertStruct(\n value,\n OnNameLookupRequestArgumentsStruct,\n 'Invalid request params',\n rpcErrors.invalidParams,\n );\n}\n\nconst OkResponseStruct = assign(\n JsonRpcSuccessStruct,\n object({\n result: OkStruct,\n }),\n);\n\nconst SnapRpcResponse = JsonRpcSuccessStruct;\n\nexport type OkResponse = Infer<typeof OkResponseStruct>;\nexport type SnapRpcResponse = Infer<typeof SnapRpcResponse>;\n\nexport type Response = OkResponse | SnapRpcResponse;\n\ntype RequestParams<Params extends unknown[] | undefined> =\n Params extends undefined ? [] : Params;\n\ntype RequestFunction<\n Args extends RequestArguments,\n ResponseType extends JsonRpcSuccess<Json>,\n> = (...args: RequestParams<Args>) => Promise<ResponseType['result']>;\n\nexport type Ping = RequestFunction<PingRequestArguments, OkResponse>;\nexport type Terminate = RequestFunction<TerminateRequestArguments, OkResponse>;\nexport type ExecuteSnap = RequestFunction<\n ExecuteSnapRequestArguments,\n OkResponse\n>;\nexport type SnapRpc = RequestFunction<SnapRpcRequestArguments, SnapRpcResponse>;\n"],"names":["JsonRpcRequestWithoutIdStruct","EndowmentStruct","isEndowment","isEndowmentsArray","PingRequestArgumentsStruct","TerminateRequestArgumentsStruct","ExecuteSnapRequestArgumentsStruct","SnapRpcRequestArgumentsStruct","OnTransactionRequestArgumentsStruct","assertIsOnTransactionRequestArguments","OnNameLookupRequestArgumentsStruct","assertIsOnNameLookupRequestArguments","assign","omit","JsonRpcRequestStruct","object","id","optional","JsonRpcIdStruct","string","value","is","Array","isArray","every","OkStruct","literal","union","undefined","array","tuple","enums","Object","values","HandlerType","params","record","JsonStruct","transaction","chainId","ChainIdStruct","transactionOrigin","nullable","assertStruct","rpcErrors","invalidParams","baseNameLookupArgs","domainRequestStruct","address","addressRequestStruct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C;IACjDX,IAAAA,mBAAM;IACNY,IAAAA,kBAAK,EAACC,OAAOC,MAAM,CAACC,uBAAW;IAC/Bf,IAAAA,mBAAM;IACNP,IAAAA,mBAAM,EACJZ,+BACAe,IAAAA,mBAAM,EAAC;QACLoB,QAAQlB,IAAAA,qBAAQ,EAACmB,IAAAA,mBAAM,EAACjB,IAAAA,mBAAM,KAAIkB,iBAAU;IAC9C;CAEH;AAqBM,MAAM7B,sCAAsCO,IAAAA,mBAAM,EAAC;IACxD,oCAAoC;IACpCuB,aAAaF,IAAAA,mBAAM,EAACjB,IAAAA,mBAAM,KAAIkB,iBAAU;IACxCE,SAASC,yBAAa;IACtBC,mBAAmBC,IAAAA,qBAAQ,EAACvB,IAAAA,mBAAM;AACpC;AAcO,SAASV,sCACdW,KAAc;IAEduB,IAAAA,mBAAY,EACVvB,OACAZ,qCACA,0BACAoC,oBAAS,CAACC,aAAa;AAE3B;AAEA,MAAMC,qBAAqB;IAAEP,SAASC,yBAAa;AAAC;AACpD,MAAMO,sBAAsBhC,IAAAA,mBAAM,EAAC;IACjC,GAAG+B,kBAAkB;IACrBE,SAAS7B,IAAAA,mBAAM;AACjB;AACA,MAAM8B,uBAAuBlC,IAAAA,mBAAM,EAAC;IAClC,GAAG+B,kBAAkB;IACrBI,QAAQ/B,IAAAA,mBAAM;AAChB;AAEO,MAAMT,qCAAqCiB,IAAAA,kBAAK,EAAC;IACtDoB;IACAE;CACD;AAmBM,SAAStC,qCACdS,KAAc;IAEduB,IAAAA,mBAAY,EACVvB,OACAV,oCACA,0BACAkC,oBAAS,CAACC,aAAa;AAE3B;AAEA,MAAMM,mBAAmBvC,IAAAA,mBAAM,EAC7BwC,2BAAoB,EACpBrC,IAAAA,mBAAM,EAAC;IACLsC,QAAQ5B;AACV;AAGF,MAAM6B,kBAAkBF,2BAAoB"}
@@ -1,5 +1,20 @@
1
1
  // eslint-disable-next-line @typescript-eslint/triple-slash-reference, spaced-comment
2
2
  /// <reference path="../../../../node_modules/ses/types.d.ts" />
3
+ function _check_private_redeclaration(obj, privateCollection) {
4
+ if (privateCollection.has(obj)) {
5
+ throw new TypeError("Cannot initialize the same private elements twice on an object");
6
+ }
7
+ }
8
+ function _class_private_method_get(receiver, privateSet, fn) {
9
+ if (!privateSet.has(receiver)) {
10
+ throw new TypeError("attempted to get private field on non-instance");
11
+ }
12
+ return fn;
13
+ }
14
+ function _class_private_method_init(obj, privateSet) {
15
+ _check_private_redeclaration(obj, privateSet);
16
+ privateSet.add(obj);
17
+ }
3
18
  function _define_property(obj, key, value) {
4
19
  if (key in obj) {
5
20
  Object.defineProperty(obj, key, {
@@ -13,23 +28,26 @@ function _define_property(obj, key, value) {
13
28
  }
14
29
  return obj;
15
30
  }
31
+ import { createIdRemapMiddleware } from '@metamask/json-rpc-engine';
16
32
  import { StreamProvider } from '@metamask/providers';
17
- import { SNAP_EXPORT_NAMES, logError, SNAP_EXPORTS } from '@metamask/snaps-utils';
33
+ import { errorCodes, rpcErrors, serializeError } from '@metamask/rpc-errors';
34
+ import { SNAP_EXPORT_NAMES, logError, SNAP_EXPORTS, WrappedSnapError, getErrorData, unwrapError } from '@metamask/snaps-utils';
18
35
  import { isObject, isValidJson, assert, isJsonRpcRequest, hasProperty, getSafeJson } from '@metamask/utils';
19
- import { errorCodes, ethErrors, serializeError } from 'eth-rpc-errors';
20
- import { createIdRemapMiddleware } from 'json-rpc-engine';
21
36
  import { validate } from 'superstruct';
22
37
  import { log } from '../logging';
23
38
  import { getCommandMethodImplementations } from './commands';
24
39
  import { createEndowments } from './endowments';
25
40
  import { addEventListener, removeEventListener } from './globalEvents';
26
41
  import { sortParamKeys } from './sortParams';
27
- import { assertEthereumOutboundRequest, assertSnapOutboundRequest, constructError, sanitizeRequestArguments, proxyStreamProvider, withTeardown } from './utils';
42
+ import { assertEthereumOutboundRequest, assertSnapOutboundRequest, sanitizeRequestArguments, proxyStreamProvider, withTeardown } from './utils';
28
43
  import { ExecuteSnapRequestArgumentsStruct, PingRequestArgumentsStruct, SnapRpcRequestArgumentsStruct, TerminateRequestArgumentsStruct } from './validation';
29
44
  const fallbackError = {
30
45
  code: errorCodes.rpc.internal,
31
46
  message: 'Execution Environment Error'
32
47
  };
48
+ const unhandledError = rpcErrors.internal({
49
+ message: 'Unhandled Snap Error'
50
+ }).serialize();
33
51
  /**
34
52
  * The supported methods in the execution environment. The validator checks the
35
53
  * incoming JSON-RPC request, and the `params` property is used for sorting the
@@ -61,36 +79,40 @@ const fallbackError = {
61
79
  ]
62
80
  }
63
81
  };
82
+ var _write = /*#__PURE__*/ new WeakSet(), _notify = /*#__PURE__*/ new WeakSet(), _respond = /*#__PURE__*/ new WeakSet();
64
83
  export class BaseSnapExecutor {
65
84
  errorHandler(error, data) {
66
- const constructedError = constructError(error);
67
- const serializedError = serializeError(constructedError, {
68
- fallbackError,
85
+ const serializedError = serializeError(error, {
86
+ fallbackError: unhandledError,
69
87
  shouldIncludeStack: false
70
88
  });
71
- // We're setting it this way to avoid sentData.stack = undefined
72
- const sentData = {
73
- ...data,
74
- stack: constructedError?.stack ?? null
75
- };
76
- this.notify({
89
+ const errorData = getErrorData(serializedError);
90
+ _class_private_method_get(this, _notify, notify).call(this, {
77
91
  method: 'UnhandledError',
78
92
  params: {
79
93
  error: {
80
94
  ...serializedError,
81
- data: sentData
95
+ data: {
96
+ ...errorData,
97
+ ...data
98
+ }
82
99
  }
83
100
  }
101
+ }).catch((notifyError)=>{
102
+ logError(notifyError);
84
103
  });
85
104
  }
86
105
  async onCommandRequest(message) {
87
106
  if (!isJsonRpcRequest(message)) {
88
- throw new Error('Command stream received a non-JSON-RPC request.');
107
+ throw rpcErrors.invalidRequest({
108
+ message: 'Command stream received a non-JSON-RPC request.',
109
+ data: message
110
+ });
89
111
  }
90
112
  const { id, method, params } = message;
91
113
  if (!hasProperty(EXECUTION_ENVIRONMENT_METHODS, method)) {
92
- this.respond(id, {
93
- error: ethErrors.rpc.methodNotFound({
114
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
115
+ error: rpcErrors.methodNotFound({
94
116
  data: {
95
117
  method
96
118
  }
@@ -103,8 +125,8 @@ export class BaseSnapExecutor {
103
125
  const paramsAsArray = sortParamKeys(methodObject.params, params);
104
126
  const [error] = validate(paramsAsArray, methodObject.struct);
105
127
  if (error) {
106
- this.respond(id, {
107
- error: ethErrors.rpc.invalidParams({
128
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
129
+ error: rpcErrors.invalidParams({
108
130
  message: `Invalid parameters for method "${method}": ${error.message}.`,
109
131
  data: {
110
132
  method,
@@ -116,45 +138,17 @@ export class BaseSnapExecutor {
116
138
  }
117
139
  try {
118
140
  const result = await this.methods[method](...paramsAsArray);
119
- this.respond(id, {
141
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
120
142
  result
121
143
  });
122
144
  } catch (rpcError) {
123
- this.respond(id, {
145
+ await _class_private_method_get(this, _respond, respond).call(this, id, {
124
146
  error: serializeError(rpcError, {
125
147
  fallbackError
126
148
  })
127
149
  });
128
150
  }
129
151
  }
130
- notify(requestObject) {
131
- if (!isValidJson(requestObject) || !isObject(requestObject)) {
132
- throw new Error('JSON-RPC notifications must be JSON serializable objects');
133
- }
134
- this.commandStream.write({
135
- ...requestObject,
136
- jsonrpc: '2.0'
137
- });
138
- }
139
- respond(id, requestObject) {
140
- if (!isValidJson(requestObject) || !isObject(requestObject)) {
141
- // Instead of throwing, we directly respond with an error.
142
- // This prevents an issue where we wouldn't respond when errors were non-serializable
143
- this.commandStream.write({
144
- error: serializeError(new Error('JSON-RPC responses must be JSON serializable objects.'), {
145
- fallbackError
146
- }),
147
- id,
148
- jsonrpc: '2.0'
149
- });
150
- return;
151
- }
152
- this.commandStream.write({
153
- ...requestObject,
154
- id,
155
- jsonrpc: '2.0'
156
- });
157
- }
158
152
  /**
159
153
  * Attempts to evaluate a snap in SES. Generates APIs for the snap. May throw
160
154
  * on errors.
@@ -223,7 +217,13 @@ export class BaseSnapExecutor {
223
217
  });
224
218
  } catch (error) {
225
219
  this.removeSnap(snapId);
226
- throw new Error(`Error while running snap '${snapId}': ${error.message}`);
220
+ const [cause] = unwrapError(error);
221
+ throw rpcErrors.internal({
222
+ message: `Error while running snap '${snapId}': ${cause.message}`,
223
+ data: {
224
+ cause: cause.serialize()
225
+ }
226
+ });
227
227
  }
228
228
  }
229
229
  /**
@@ -264,16 +264,18 @@ export class BaseSnapExecutor {
264
264
  const request = async (args)=>{
265
265
  const sanitizedArgs = sanitizeRequestArguments(args);
266
266
  assertSnapOutboundRequest(sanitizedArgs);
267
- this.notify({
268
- method: 'OutboundRequest'
269
- });
270
- try {
271
- return await withTeardown(originalRequest(sanitizedArgs), this);
272
- } finally{
273
- this.notify({
274
- method: 'OutboundResponse'
267
+ return await withTeardown((async ()=>{
268
+ await _class_private_method_get(this, _notify, notify).call(this, {
269
+ method: 'OutboundRequest'
275
270
  });
276
- }
271
+ try {
272
+ return await originalRequest(sanitizedArgs);
273
+ } finally{
274
+ await _class_private_method_get(this, _notify, notify).call(this, {
275
+ method: 'OutboundResponse'
276
+ });
277
+ }
278
+ })(), this);
277
279
  };
278
280
  // Proxy target is intentionally set to be an empty object, to ensure
279
281
  // that access to the prototype chain is not possible.
@@ -302,16 +304,18 @@ export class BaseSnapExecutor {
302
304
  const request = async (args)=>{
303
305
  const sanitizedArgs = sanitizeRequestArguments(args);
304
306
  assertEthereumOutboundRequest(sanitizedArgs);
305
- this.notify({
306
- method: 'OutboundRequest'
307
- });
308
- try {
309
- return await withTeardown(originalRequest(sanitizedArgs), this);
310
- } finally{
311
- this.notify({
312
- method: 'OutboundResponse'
307
+ return await withTeardown((async ()=>{
308
+ await _class_private_method_get(this, _notify, notify).call(this, {
309
+ method: 'OutboundRequest'
313
310
  });
314
- }
311
+ try {
312
+ return await originalRequest(sanitizedArgs);
313
+ } finally{
314
+ await _class_private_method_get(this, _notify, notify).call(this, {
315
+ method: 'OutboundResponse'
316
+ });
317
+ }
318
+ })(), this);
315
319
  };
316
320
  const streamProviderProxy = proxyStreamProvider(provider, request);
317
321
  return harden(streamProviderProxy);
@@ -336,11 +340,11 @@ export class BaseSnapExecutor {
336
340
  */ async executeInSnapContext(snapId, executor) {
337
341
  const data = this.snapData.get(snapId);
338
342
  if (data === undefined) {
339
- throw new Error(`Tried to execute in context of unknown snap: "${snapId}".`);
343
+ throw rpcErrors.internal(`Tried to execute in context of unknown snap: "${snapId}".`);
340
344
  }
341
345
  let stop;
342
346
  const stopPromise = new Promise((_, reject)=>stop = ()=>reject(// TODO(rekmarks): Specify / standardize error code for this case.
343
- ethErrors.rpc.internal(`The snap "${snapId}" has been terminated during execution.`)));
347
+ rpcErrors.internal(`The snap "${snapId}" has been terminated during execution.`)));
344
348
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
345
349
  const evaluationData = {
346
350
  stop: stop
@@ -354,6 +358,8 @@ export class BaseSnapExecutor {
354
358
  executor(),
355
359
  stopPromise
356
360
  ]);
361
+ } catch (error) {
362
+ throw new WrappedSnapError(error);
357
363
  } finally{
358
364
  data.runningEvaluations.delete(evaluationData);
359
365
  if (data.runningEvaluations.size === 0) {
@@ -363,6 +369,12 @@ export class BaseSnapExecutor {
363
369
  }
364
370
  }
365
371
  constructor(commandStream, rpcStream){
372
+ // Awaitable function that writes back to the command stream
373
+ // To prevent snap execution from blocking writing we wrap in a promise
374
+ // and await it before continuing execution
375
+ _class_private_method_init(this, _write);
376
+ _class_private_method_init(this, _notify);
377
+ _class_private_method_init(this, _respond);
366
378
  _define_property(this, "snapData", void 0);
367
379
  _define_property(this, "commandStream", void 0);
368
380
  _define_property(this, "rpcStream", void 0);
@@ -385,14 +397,14 @@ export class BaseSnapExecutor {
385
397
  // before the call.
386
398
  const handler = data?.exports[handlerType];
387
399
  const { required } = SNAP_EXPORTS[handlerType];
388
- assert(!required || handler !== undefined, `No ${handlerType} handler exported for snap "${target}`);
400
+ assert(!required || handler !== undefined, `No ${handlerType} handler exported for snap "${target}`, rpcErrors.methodNotSupported);
389
401
  // Certain handlers are not required. If they are not exported, we
390
402
  // return null.
391
403
  if (!handler) {
392
404
  return null;
393
405
  }
394
- // TODO: fix handler args type cast
395
- let result = await this.executeInSnapContext(target, ()=>handler(args));
406
+ let result = await this.executeInSnapContext(target, ()=>// TODO: fix handler args type cast
407
+ handler(args));
396
408
  // The handler might not return anything, but undefined is not valid JSON.
397
409
  if (result === undefined) {
398
410
  result = null;
@@ -401,10 +413,47 @@ export class BaseSnapExecutor {
401
413
  try {
402
414
  return getSafeJson(result);
403
415
  } catch (error) {
404
- throw new TypeError(`Received non-JSON-serializable value: ${error.message.replace(/^Assertion failed: /u, '')}`);
416
+ throw rpcErrors.internal(`Received non-JSON-serializable value: ${error.message.replace(/^Assertion failed: /u, '')}`);
405
417
  }
406
418
  }, this.onTerminate.bind(this));
407
419
  }
408
420
  }
421
+ async function write(chunk) {
422
+ return new Promise((resolve, reject)=>{
423
+ this.commandStream.write(chunk, (error)=>{
424
+ if (error) {
425
+ reject(error);
426
+ return;
427
+ }
428
+ resolve();
429
+ });
430
+ });
431
+ }
432
+ async function notify(requestObject) {
433
+ if (!isValidJson(requestObject) || !isObject(requestObject)) {
434
+ throw rpcErrors.internal('JSON-RPC notifications must be JSON serializable objects');
435
+ }
436
+ await _class_private_method_get(this, _write, write).call(this, {
437
+ ...requestObject,
438
+ jsonrpc: '2.0'
439
+ });
440
+ }
441
+ async function respond(id, requestObject) {
442
+ if (!isValidJson(requestObject) || !isObject(requestObject)) {
443
+ // Instead of throwing, we directly respond with an error.
444
+ // This prevents an issue where we wouldn't respond when errors were non-serializable
445
+ await _class_private_method_get(this, _write, write).call(this, {
446
+ error: serializeError(rpcErrors.internal('JSON-RPC responses must be JSON serializable objects.')),
447
+ id,
448
+ jsonrpc: '2.0'
449
+ });
450
+ return;
451
+ }
452
+ await _class_private_method_get(this, _write, write).call(this, {
453
+ ...requestObject,
454
+ id,
455
+ jsonrpc: '2.0'
456
+ });
457
+ }
409
458
 
410
459
  //# sourceMappingURL=BaseSnapExecutor.js.map