@metamask/snaps-utils 5.2.0 → 6.1.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 (46) hide show
  1. package/CHANGELOG.md +23 -3
  2. package/dist/cjs/caveats.js +6 -0
  3. package/dist/cjs/caveats.js.map +1 -1
  4. package/dist/cjs/eval-worker.js +3 -1
  5. package/dist/cjs/eval-worker.js.map +1 -1
  6. package/dist/cjs/handler-types.js +1 -0
  7. package/dist/cjs/handler-types.js.map +1 -1
  8. package/dist/cjs/handlers.js +74 -3
  9. package/dist/cjs/handlers.js.map +1 -1
  10. package/dist/cjs/icon.js +38 -9
  11. package/dist/cjs/icon.js.map +1 -1
  12. package/dist/cjs/manifest/manifest.js +8 -0
  13. package/dist/cjs/manifest/manifest.js.map +1 -1
  14. package/dist/cjs/manifest/validation.js +50 -14
  15. package/dist/cjs/manifest/validation.js.map +1 -1
  16. package/dist/cjs/post-process.js +1 -1
  17. package/dist/cjs/post-process.js.map +1 -1
  18. package/dist/cjs/structs.js +86 -17
  19. package/dist/cjs/structs.js.map +1 -1
  20. package/dist/esm/caveats.js +6 -0
  21. package/dist/esm/caveats.js.map +1 -1
  22. package/dist/esm/eval-worker.js +3 -1
  23. package/dist/esm/eval-worker.js.map +1 -1
  24. package/dist/esm/handler-types.js +1 -0
  25. package/dist/esm/handler-types.js.map +1 -1
  26. package/dist/esm/handlers.js +45 -4
  27. package/dist/esm/handlers.js.map +1 -1
  28. package/dist/esm/icon.js +43 -3
  29. package/dist/esm/icon.js.map +1 -1
  30. package/dist/esm/manifest/manifest.js +8 -0
  31. package/dist/esm/manifest/manifest.js.map +1 -1
  32. package/dist/esm/manifest/validation.js +38 -16
  33. package/dist/esm/manifest/validation.js.map +1 -1
  34. package/dist/esm/post-process.js +1 -1
  35. package/dist/esm/post-process.js.map +1 -1
  36. package/dist/esm/structs.js +133 -21
  37. package/dist/esm/structs.js.map +1 -1
  38. package/dist/types/caveats.d.ts +9 -1
  39. package/dist/types/handler-types.d.ts +2 -1
  40. package/dist/types/handlers.d.ts +349 -10
  41. package/dist/types/icon.d.ts +16 -1
  42. package/dist/types/localization.d.ts +33 -13
  43. package/dist/types/manifest/validation.d.ts +230 -75
  44. package/dist/types/post-process.d.ts +1 -1
  45. package/dist/types/structs.d.ts +61 -7
  46. package/package.json +5 -6
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { InitialPermissions } from '@metamask/snaps-sdk';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n refine,\n record,\n size,\n string,\n type,\n union,\n intersection,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport type { InferMatching } from '../structs';\nimport { NameStruct, NpmSnapFileNames, uri } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = array(ChainIdStruct);\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:ethereum-provider': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:signature-insight': optional(\n object({\n allowSignatureOrigin: optional(boolean()),\n }),\n ),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:name-lookup': optional(ChainIdsStruct),\n 'endowment:keyring': optional(KeyringOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n snap_getLocale: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = InferMatching<\n typeof PermissionsStruct,\n InitialPermissions\n>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const InitialConnectionsStruct = record(\n intersection([string(), uri()]),\n object({}),\n);\n\nexport type InitialConnections = Infer<typeof InitialConnectionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n locales: optional(SnapAuxilaryFilesStruct),\n }),\n initialConnections: optional(InitialConnectionsStruct),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","InitialConnectionsStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","allowSignatureOrigin","boolean","allowTransactionOrigin","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","KeyringOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","snap_getLocale","wallet_snap","intersection","uri","VersionStruct","description","proposedName","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","files","locales","initialConnections","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA4CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAcAC,cAAc;eAAdA;;IAGAC,iBAAiB;eAAjBA;;IA8CAC,uBAAuB;eAAvBA;;IAEAC,wBAAwB;eAAxBA;;IAOAC,kBAAkB;eAAlBA;;IAwCGC,cAAc;eAAdA;;IAUAC,oBAAoB;eAApBA;;IAiBAC,kBAAkB;eAAlBA;;;yBA5QwB;uBAOjC;6BAmBA;uBAEiB;yBACwB;yBACgB;yBACT;2BACzB;uBACD;uBAEqB;AAElD,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCC,0BAAiB;IACjBC,qCAA4B;CAC7B;AAEM,MAAMjB,uBAAiC;IAAC;CAAG;AAClD,MAAMkB,kBAA8BlB,qBAAqBmB,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAEM,MAAMnB,kBAAkBoB,IAAAA,mBAAM,EACnCC,IAAAA,kBAAK,EAACC,IAAAA,mBAAM,MACZ,eACA,CAACC;IACC,IAAIA,KAAKC,MAAM,KAAK,GAAG;QACrB,OAAO;IACT;IAEA,IAAID,IAAI,CAAC,EAAE,KAAK,KAAK;QACnB,OAAO;IACT;IAEA,I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U1C,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBAC5B0C,UAAUpC,IAAAA,qBAAQ,EAACP,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBACrC2C,aAAaC,iBAAU;gBACvBC,UAAUC,IAAAA,kBAAK,EAAC;oBACdC,IAAAA,oBAAO,EAAC;oBACRA,IAAAA,oBAAO,EAAC;iBACT;YACH;QACF;QACAC,OAAO1C,IAAAA,qBAAQ,EAACtC;QAChBiF,SAAS3C,IAAAA,qBAAQ,EAACtC;IACpB;IACAkF,oBAAoB5C,IAAAA,qBAAQ,EAACrC;IAC7BkF,oBAAoBpF;IACpBqF,iBAAiBL,IAAAA,oBAAO,EAAC;IACzBM,SAAS/C,IAAAA,qBAAQ,EAACxB,IAAAA,mBAAM;AAC1B;AAUO,SAASX,eAAeuB,KAAc;IAC3C,OAAO4D,IAAAA,eAAE,EAAC5D,OAAOxB;AACnB;AAQO,SAASE,qBACdsB,KAAc;IAEd6D,IAAAA,mBAAY,EACV7D,OACAxB,oBACA,CAAC,CAAC,EAAEsF,uBAAgB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAASpF,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAOgE,IAAAA,mBAAM,EAAChE,OAAOxB;AACvB"}
1
+ {"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport type { InitialPermissions } from '@metamask/snaps-sdk';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n inMilliseconds,\n Duration,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n refine,\n record,\n size,\n string,\n type,\n union,\n intersection,\n assign,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { KeyringOriginsStruct, RpcOriginsStruct } from '../json-rpc';\nimport { ChainIdStruct } from '../namespace';\nimport { SnapIdStruct } from '../snaps';\nimport type { InferMatching } from '../structs';\nimport { NameStruct, NpmSnapFileNames, uri } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\nexport const ChainIdsStruct = size(array(ChainIdStruct), 1, Infinity);\n\nexport const LookupMatchersStruct = union([\n object({\n tlds: size(array(string()), 1, Infinity),\n }),\n object({\n schemes: size(array(string()), 1, Infinity),\n }),\n object({\n tlds: size(array(string()), 1, Infinity),\n schemes: size(array(string()), 1, Infinity),\n }),\n]);\n\nexport const MINIMUM_REQUEST_TIMEOUT = inMilliseconds(5, Duration.Second);\nexport const MAXIMUM_REQUEST_TIMEOUT = inMilliseconds(3, Duration.Minute);\n\nexport const MaxRequestTimeStruct = size(\n integer(),\n MINIMUM_REQUEST_TIMEOUT,\n MAXIMUM_REQUEST_TIMEOUT,\n);\n\n// Utility type to union with for all handler structs\nexport const HandlerCaveatsStruct = object({\n maxRequestTime: optional(MaxRequestTimeStruct),\n});\n\nexport type HandlerCaveats = Infer<typeof HandlerCaveatsStruct>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:cronjob': optional(\n assign(\n HandlerCaveatsStruct,\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n ),\n 'endowment:ethereum-provider': optional(object({})),\n 'endowment:keyring': optional(\n assign(HandlerCaveatsStruct, KeyringOriginsStruct),\n ),\n 'endowment:lifecycle-hooks': optional(HandlerCaveatsStruct),\n 'endowment:name-lookup': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n chains: optional(ChainIdsStruct),\n matchers: optional(LookupMatchersStruct),\n }),\n ),\n ),\n 'endowment:network-access': optional(object({})),\n 'endowment:page-home': optional(HandlerCaveatsStruct),\n 'endowment:rpc': optional(RpcOriginsStruct),\n 'endowment:signature-insight': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n allowSignatureOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:transaction-insight': optional(\n assign(\n HandlerCaveatsStruct,\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n ),\n 'endowment:webassembly': optional(object({})),\n snap_dialog: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n snap_getLocale: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = InferMatching<\n typeof PermissionsStruct,\n InitialPermissions\n>;\n\nexport const SnapAuxilaryFilesStruct = array(string());\n\nexport const InitialConnectionsStruct = record(\n intersection([string(), uri()]),\n object({}),\n);\n\nexport type InitialConnections = Infer<typeof InitialConnectionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(string(), 1, 214),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n files: optional(SnapAuxilaryFilesStruct),\n locales: optional(SnapAuxilaryFilesStruct),\n }),\n initialConnections: optional(InitialConnectionsStruct),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","ChainIdsStruct","LookupMatchersStruct","MINIMUM_REQUEST_TIMEOUT","MAXIMUM_REQUEST_TIMEOUT","MaxRequestTimeStruct","HandlerCaveatsStruct","PermissionsStruct","SnapAuxilaryFilesStruct","InitialConnectionsStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","ChainIdStruct","union","tlds","schemes","inMilliseconds","Duration","Second","Minute","integer","maxRequestTime","assign","jobs","CronjobSpecificationArrayStruct","KeyringOriginsStruct","chains","matchers","RpcOriginsStruct","allowSignatureOrigin","boolean","allowTransactionOrigin","snap_dialog","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","snap_getLocale","wallet_snap","intersection","uri","VersionStruct","description","proposedName","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","literal","files","locales","initialConnections","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA+CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAkBAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAcAC,cAAc;eAAdA;;IAEAC,oBAAoB;eAApBA;;IAaAC,uBAAuB;eAAvBA;;IACAC,uBAAuB;eAAvBA;;IAEAC,oBAAoB;eAApBA;;IAOAC,oBAAoB;eAApBA;;IAOAC,iBAAiB;eAAjBA;;IAiEAC,uBAAuB;eAAvBA;;IAEAC,wBAAwB;eAAxBA;;IAOAC,kBAAkB;eAAlBA;;IAwCGC,cAAc;eAAdA;;IAUAC,oBAAoB;eAApBA;;IAiBAC,kBAAkB;eAAlBA;;;yBA/TwB;uBASjC;6BAoBA;uBAEiB;yBACwB;yBACgB;yBACT;2BACzB;uBACD;uBAEqB;AAElD,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCC,0BAAiB;IACjBC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QACLP,MAAME,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;QACxB6C,KAAK9C,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;IACzB;IAEF8C,QAAQ1C,IAAAA,mBAAM,EAAC;QACb2C,QAAQC,qBAAc;QACtBC,UAAU7C,IAAAA,mBAAM,EAAC;YACf8C,KAAK9C,IAAAA,mBAAM,EAAC;gBACV+C,UAAUpD,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBAC5BoD,UAAU9C,IAAAA,qBAAQ,EAACP,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBACrCqD,aAAaC,iBAAU;gBACvBC,UAAU7C,IAAAA,kBAAK,EAAC;oBACd8C,IAAAA,oBAAO,EAAC;oBACRA,IAAAA,oBAAO,EAAC;iBACT;YACH;QACF;QACAC,OAAOnD,IAAAA,qBAAQ,EAACtC;QAChB0F,SAASpD,IAAAA,qBAAQ,EAACtC;IACpB;IACA2F,oBAAoBrD,IAAAA,qBAAQ,EAACrC;IAC7B2F,oBAAoB7F;IACpB8F,iBAAiBL,IAAAA,oBAAO,EAAC;IACzBM,SAASxD,IAAAA,qBAAQ,EAACxB,IAAAA,mBAAM;AAC1B;AAUO,SAASX,eAAeuB,KAAc;IAC3C,OAAOqE,IAAAA,eAAE,EAACrE,OAAOxB;AACnB;AAQO,SAASE,qBACdsB,KAAc;IAEdsE,IAAAA,mBAAY,EACVtE,OACAxB,oBACA,CAAC,CAAC,EAAE+F,uBAAgB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAAS7F,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAOyE,IAAAA,mBAAM,EAACzE,OAAOxB;AACvB"}
@@ -21,7 +21,7 @@ const _core = require("@babel/core");
21
21
  const _types = require("@babel/types");
22
22
  var PostProcessWarning;
23
23
  (function(PostProcessWarning) {
24
- PostProcessWarning["UnsafeMathRandom"] = '`Math.random` was detected in the bundle. This is not a secure source of randomness.';
24
+ PostProcessWarning["UnsafeMathRandom"] = '`Math.random` was detected in the Snap bundle. This is not a secure source of randomness, and should not be used in a secure context. Use `crypto.getRandomValues` instead.';
25
25
  })(PostProcessWarning || (PostProcessWarning = {}));
26
26
  // The RegEx below consists of multiple groups joined by a boolean OR.
27
27
  // Each part consists of two groups which capture a part of each string
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["postProcessBundle","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","templateElement","raw","cooked","evalWrapper","template","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","stringLiteral","lastMatch","suffix","replace","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","templateLiteral","expression","setData","StringLiteral","replacement","acc","binaryExpression","skip","BinaryExpression","errorMessage","operator","isUnaryExpression","right","isUpdateExpression","argument","left","end","start","includes","Error","file","transformSync","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;;;;;;;;;;;;;;;IAoNxCA,iBAAiB;eAAjBA;;;sBAlNwB;uBASjC;IAgDA;UAAKC,kBAAkB;IAAlBA,mBACVC,sBAAmB;GADTD,uBAAAA;AAIZ,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAME,cAAc;AAEpB,4EAA4E;AAC5E,cAAc;AACd,MAAMC,yBAAyBC,IAAAA,sBAAe,EAAC;IAAEC,KAAK;IAAIC,QAAQ;AAAG;AAErE,MAAMC,cAAcC,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAExC,CAAC;AAED,MAAMC,oBAAoBF,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAE9C,CAAC;AAED,MAAME,4BAA4BH,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAEtD,CAAC;AAED;;;;;;;;;;;CAWC,GACD,SAASG,YAAYC,KAAa;IAChC,MAAMC,SAASD,MAAME,KAAK,CAACb;IAC3B,OACEY,MACE,oEAAoE;IACpE,sEAAsE;KACrEE,MAAM,CAAC,CAACC,QAAUA,UAAU,MAAMA,UAAUC;AAEnD;AAEA;;;;;;;;;;CAUC,GACD,SAASC,2BACPN,KAAa;IAEb,6DAA6D;IAC7D,kEAAkE;IAClE,uEAAuE;IACvE,MAAMO,UAA8BC,MAAMC,IAAI,CAACT,MAAMU,QAAQ,CAACrB;IAE9D,IAAIkB,QAAQI,MAAM,GAAG,GAAG;QACtB,MAAMC,SAASL,QAAQM,MAAM,CAC3B,CAAC,CAACC,UAAUC,YAAY,EAAEC,UAAUC,OAAOC;YACzC,MAAM,GAAGC,OAAOC,KAAK,GAAGJ,SAASb,MAAM,CAAC,CAACX,MAAQA,QAAQa;YAEzD,kEAAkE;YAClE,aAAa;YACb,MAAMgB,SAASrB,MAAMsB,KAAK,CACxBL,UAAU,IACN,IACA,AAACC,MAAM,CAACD,QAAQ,EAAE,CA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A,mEAAmE;YACnE,yEAAyE;YACzEyE,SAAS;YAET,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnEtE;YACAD;YAEAwE,SAAS;gBACP,IAAO,CAAA;wBACLpE;wBACAM;oBACF,CAAA;aACD;QACH;QAEA,IAAI,CAACuD,MAAMpE,MAAM;YACf,MAAM,IAAImE,MAAM;QAClB;QAEA,OAAO;YACLnE,MAAMoE,KAAKpE,IAAI;YACfE,WAAWkE,KAAKQ,GAAG;YACnBvE,UAAUzB,MAAMC,IAAI,CAACwB;QACvB;IACF,EAAE,OAAOwE,OAAO;QACd,MAAM,IAAIV,MAAM,CAAC,8BAA8B,EAAEU,MAAMC,OAAO,CAAC,CAAC;IAClE;AACF"}
1
+ {"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the Snap bundle. This is not a secure source of randomness, and should not be used in a secure context. Use `crypto.getRandomValues` instead.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["postProcessBundle","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","templateElement","raw","cooked","evalWrapper","template","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","stringLiteral","lastMatch","suffix","replace","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","templateLiteral","expression","setData","StringLiteral","replacement","acc","binaryExpression","skip","BinaryExpression","errorMessage","operator","isUnaryExpression","right","isUpdateExpression","argument","left","end","start","includes","Error","file","transformSync","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;;;;;;;;;;;;;;;IAoNxCA,iBAAiB;eAAjBA;;;sBAlNwB;uBASjC;IAgDA;UAAKC,kBAAkB;IAAlBA,mBACVC,sBAAmB;GADTD,uBAAAA;AAIZ,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAME,cAAc;AAEpB,4EAA4E;AAC5E,cAAc;AACd,MAAMC,yBAAyBC,IAAAA,sBAAe,EAAC;IAAEC,KAAK;IAAIC,QAAQ;AAAG;AAErE,MAAMC,cAAcC,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAExC,CAAC;AAED,MAAMC,oBAAoBF,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAE9C,CAAC;AAED,MAAME,4BAA4BH,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAEtD,CAAC;AAED;;;;;;;;;;;CAWC,GACD,SAASG,YAAYC,KAAa;IAChC,MAAMC,SAASD,MAAME,KAAK,CAACb;IAC3B,OACEY,MACE,oEAAoE;IACpE,sEAAsE;KACrEE,MAAM,CAAC,CAACC,QAAUA,UAAU,MAAMA,UAAUC;AAEnD;AAEA;;;;;;;;;;CAUC,GACD,SAASC,2BACPN,KAAa;IAEb,6DAA6D;IAC7D,kEAAkE;IAClE,uEAAuE;IACvE,MAAMO,UAA8BC,MAAMC,IAAI,CAACT,MAAMU,QAAQ,CAACrB;IAE9D,IAAIkB,QAAQI,MAAM,GAAG,GAAG;QACtB,MAAMC,SAASL,QAAQM,MAAM,CAC3B,CAAC,CAACC,UAAUC,YA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MAAMV;gBAClB;YACF;QACF;IACF;IAEA,IAAI;QACF,MAAMW,OAAOC,IAAAA,mBAAa,EAACrE,MAAM;YAC/B,kDAAkD;YAClDsE,YAAY;YAEZC,YAAY;gBACV,sEAAsE;gBACtEC,YAAY;gBAEZ,sEAAsE;gBACtE,wEAAwE;gBACxEC,eAAe,CAACxE;YAClB;YAEA,mEAAmE;YACnE,yEAAyE;YACzEyE,SAAS;YAET,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnEtE;YACAD;YAEAwE,SAAS;gBACP,IAAO,CAAA;wBACLpE;wBACAM;oBACF,CAAA;aACD;QACH;QAEA,IAAI,CAACuD,MAAMpE,MAAM;YACf,MAAM,IAAImE,MAAM;QAClB;QAEA,OAAO;YACLnE,MAAMoE,KAAKpE,IAAI;YACfE,WAAWkE,KAAKQ,GAAG;YACnBvE,UAAUzB,MAAMC,IAAI,CAACwB;QACvB;IACF,EAAE,OAAOwE,OAAO;QACd,MAAM,IAAIV,MAAM,CAAC,8BAA8B,EAAEU,MAAMC,OAAO,CAAC,CAAC;IAClE;AACF"}
@@ -41,13 +41,36 @@ _export(exports, {
41
41
  },
42
42
  getStructErrorMessage: function() {
43
43
  return getStructErrorMessage;
44
+ },
45
+ validateUnion: function() {
46
+ return validateUnion;
47
+ },
48
+ createUnion: function() {
49
+ return createUnion;
44
50
  }
45
51
  });
52
+ const _snapssdk = require("@metamask/snaps-sdk");
46
53
  const _utils = require("@metamask/utils");
47
54
  const _chalk = require("chalk");
48
55
  const _path = require("path");
49
56
  const _superstruct = require("superstruct");
50
57
  const _strings = require("./strings");
58
+ /**
59
+ * Colorize a value with a color function. This is useful for colorizing values
60
+ * in error messages. If colorization is disabled, the original value is
61
+ * returned.
62
+ *
63
+ * @param value - The value to colorize.
64
+ * @param colorFunction - The color function to use.
65
+ * @param enabled - Whether to colorize the value.
66
+ * @returns The colorized value, or the original value if colorization is
67
+ * disabled.
68
+ */ function color(value, colorFunction, enabled) {
69
+ if (enabled) {
70
+ return colorFunction(value);
71
+ }
72
+ return value;
73
+ }
51
74
  function file() {
52
75
  return (0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.string)(), (value)=>{
53
76
  return (0, _path.resolve)(process.cwd(), value);
@@ -60,12 +83,12 @@ function named(name, struct) {
60
83
  });
61
84
  }
62
85
  class SnapsStructError extends _superstruct.StructError {
63
- constructor(struct, prefix, suffix, failure, failures){
86
+ constructor(struct, prefix, suffix, failure, failures, colorize = true){
64
87
  super(failure, failures);
65
88
  this.name = 'SnapsStructError';
66
89
  this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
67
90
  ...failures()
68
- ])}${suffix ? `\n\n${suffix}` : ''}`;
91
+ ], colorize)}${suffix ? `\n\n${suffix}` : ''}`;
69
92
  }
70
93
  }
71
94
  function* arrayToGenerator(array) {
@@ -73,8 +96,8 @@ function* arrayToGenerator(array) {
73
96
  yield item;
74
97
  }
75
98
  }
76
- function getError({ struct, prefix, suffix = '', error }) {
77
- return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
99
+ function getError({ struct, prefix, suffix = '', error, colorize }) {
100
+ return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()), colorize);
78
101
  }
79
102
  function createFromStruct(value, struct, prefix, suffix = '') {
80
103
  try {
@@ -99,24 +122,24 @@ function getStructFromPath(struct, path) {
99
122
  return result;
100
123
  }, struct);
101
124
  }
102
- function getUnionStructNames(struct) {
125
+ function getUnionStructNames(struct, colorize = true) {
103
126
  if (Array.isArray(struct.schema)) {
104
- return struct.schema.map(({ type })=>(0, _chalk.green)(type));
127
+ return struct.schema.map(({ type })=>color(type, _chalk.green, colorize));
105
128
  }
106
129
  return null;
107
130
  }
108
- function getStructErrorPrefix(failure) {
131
+ function getStructErrorPrefix(failure, colorize = true) {
109
132
  if (failure.type === 'never' || failure.path.length === 0) {
110
133
  return '';
111
134
  }
112
- return `At path: ${(0, _chalk.bold)(failure.path.join('.'))} — `;
135
+ return `At path: ${color(failure.path.join('.'), _chalk.bold, colorize)} — `;
113
136
  }
114
- function getStructFailureMessage(struct, failure) {
115
- const received = (0, _chalk.red)(JSON.stringify(failure.value));
116
- const prefix = getStructErrorPrefix(failure);
137
+ function getStructFailureMessage(struct, failure, colorize = true) {
138
+ const received = color(JSON.stringify(failure.value), _chalk.red, colorize);
139
+ const prefix = getStructErrorPrefix(failure, colorize);
117
140
  if (failure.type === 'union') {
118
141
  const childStruct = getStructFromPath(struct, failure.path);
119
- const unionNames = getUnionStructNames(childStruct);
142
+ const unionNames = getUnionStructNames(childStruct, colorize);
120
143
  if (unionNames) {
121
144
  return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
122
145
  }
@@ -125,17 +148,63 @@ function getStructFailureMessage(struct, failure) {
125
148
  if (failure.type === 'literal') {
126
149
  // Superstruct's failure does not provide information about which literal
127
150
  // value was expected, so we need to parse the message to get the literal.
128
- const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${(0, _chalk.green)('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${(0, _chalk.red)('$1')}`);
151
+ const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${color('$1', _chalk.green, colorize)}\`,`).replace(/, but received: (.+)/u, `, but received: ${color('$1', _chalk.red, colorize)}`);
129
152
  return `${prefix}${message}.`;
130
153
  }
131
154
  if (failure.type === 'never') {
132
- return `Unknown key: ${(0, _chalk.bold)(failure.path.join('.'))}, received: ${received}.`;
155
+ return `Unknown key: ${color(failure.path.join('.'), _chalk.bold, colorize)}, received: ${received}.`;
133
156
  }
134
- return `${prefix}Expected a value of type ${(0, _chalk.green)(failure.type)}, but received: ${received}.`;
157
+ if (failure.refinement === 'size') {
158
+ const message = failure.message.replace(/length between `(\d+)` and `(\d+)`/u, `length between ${color('$1', _chalk.green, colorize)} and ${color('$2', _chalk.green, colorize)},`).replace(/length of `(\d+)`/u, `length of ${color('$1', _chalk.red, colorize)}`).replace(/a array/u, 'an array');
159
+ return `${prefix}${message}.`;
160
+ }
161
+ return `${prefix}Expected a value of type ${color(failure.type, _chalk.green, colorize)}, but received: ${received}.`;
135
162
  }
136
- function getStructErrorMessage(struct, failures) {
137
- const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure)}`));
163
+ function getStructErrorMessage(struct, failures, colorize = true) {
164
+ const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure, colorize)}`));
138
165
  return formattedFailures.join('\n');
139
166
  }
167
+ function validateUnion(value, struct, structKey, coerce = false) {
168
+ (0, _utils.assert)(struct.schema, 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.');
169
+ (0, _utils.assert)(struct.schema.length > 0, 'Expected a non-empty array of structs.');
170
+ const keyUnion = struct.schema.map((innerStruct)=>innerStruct.schema[structKey]);
171
+ const key = (0, _superstruct.type)({
172
+ [structKey]: (0, _snapssdk.union)(keyUnion)
173
+ });
174
+ const [keyError] = (0, _superstruct.validate)(value, key, {
175
+ coerce
176
+ });
177
+ if (keyError) {
178
+ throw new Error(getStructFailureMessage(key, keyError.failures()[0], false));
179
+ }
180
+ // At this point it's guaranteed that the value is an object, so we can safely
181
+ // cast it to a Record.
182
+ const objectValue = value;
183
+ const objectStructs = struct.schema.filter((innerStruct)=>(0, _superstruct.is)(objectValue[structKey], innerStruct.schema[structKey]));
184
+ (0, _utils.assert)(objectStructs.length > 0, 'Expected a struct to match the value.');
185
+ // We need to validate the value against all the object structs that match the
186
+ // struct key, and return the first validated value.
187
+ const validationResults = objectStructs.map((objectStruct)=>(0, _superstruct.validate)(objectValue, objectStruct, {
188
+ coerce
189
+ }));
190
+ const validatedValue = validationResults.find(([error])=>!error);
191
+ if (validatedValue) {
192
+ return validatedValue[1];
193
+ }
194
+ (0, _utils.assert)(validationResults[0][0], 'Expected at least one error.');
195
+ // If there is no validated value, we need to find the error with the least
196
+ // number of failures (with the assumption that it's the most specific error).
197
+ const validationError = validationResults.reduce((error, [innerError])=>{
198
+ (0, _utils.assert)(innerError, 'Expected an error.');
199
+ if (innerError.failures().length < error.failures().length) {
200
+ return innerError;
201
+ }
202
+ return error;
203
+ }, validationResults[0][0]);
204
+ throw new Error(getStructFailureMessage(struct, validationError.failures()[0], false));
205
+ }
206
+ function createUnion(value, struct, structKey) {
207
+ return validateUnion(value, struct, structKey, true);
208
+ }
140
209
 
141
210
  //# sourceMappingURL=structs.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport { Struct, StructError, create, string, coerce } from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","coerce","string","value","resolve","process","cwd","name","struct","Struct","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","schema","Array","isArray","map","green","length","bold","join","received","red","JSON","stringify","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAuDgBA,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAoBAC,mBAAmB;eAAnBA;;IAiBAC,oBAAoB;eAApBA;;IAiBAC,uBAAuB;eAAvBA;;IAiDAC,qBAAqB;eAArBA;;;uBAzRS;uBACQ;sBACT;6BAEoC;yBAGrC;AA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CAAC,wBAAwB,CAAC,kBAAkB,EAAEV,IAAAA,YAAK,EAAC,MAAM,GAAG,CAAC,EACrEU,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,EAAEL,IAAAA,UAAG,EAAC,MAAM,CAAC;QAElE,OAAO,CAAC,EAAEvB,OAAO,EAAEI,QAAQ,CAAC,CAAC;IAC/B;IAEA,IAAIF,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAEuB,IAAAA,WAAI,EACzBlB,QAAQO,IAAI,CAACY,IAAI,CAAC,MAClB,YAAY,EAAEC,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAEtB,OAAO,yBAAyB,EAAEkB,IAAAA,YAAK,EAC/ChB,QAAQL,IAAI,EACZ,gBAAgB,EAAEyB,SAAS,CAAC,CAAC;AACjC;AAUO,SAASnC,sBACdQ,MAA4B,EAC5BQ,QAAmB;IAEnB,MAAM0B,oBAAoB1B,SAASc,GAAG,CAAC,CAACf,UACtC4B,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAE5C,wBAAwBS,QAAQO,SAAS,CAAC;IAGxD,OAAO2B,kBAAkBR,IAAI,CAAC;AAChC"}
1
+ {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { union } from '@metamask/snaps-sdk';\nimport type { NonEmptyArray } from '@metamask/utils';\nimport { assert, isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport {\n is,\n validate,\n type as superstructType,\n Struct,\n StructError,\n create,\n string,\n coerce as superstructCoerce,\n} from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * Colorize a value with a color function. This is useful for colorizing values\n * in error messages. If colorization is disabled, the original value is\n * returned.\n *\n * @param value - The value to colorize.\n * @param colorFunction - The color function to use.\n * @param enabled - Whether to colorize the value.\n * @returns The colorized value, or the original value if colorization is\n * disabled.\n */\nfunction color(\n value: string,\n colorFunction: (value: string) => string,\n enabled: boolean,\n) {\n if (enabled) {\n return colorFunction(value);\n }\n\n return value;\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return superstructCoerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n colorize = true,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(\n struct,\n [...failures()],\n colorize,\n )}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n colorize?: boolean;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @param options.colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n colorize,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(\n struct,\n prefix,\n suffix,\n error,\n () => arrayToGenerator(error.failures()),\n colorize,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n colorize = true,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => color(type, green, colorize));\n }\n\n return null;\n}\n\n/**\n * Get an error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure, colorize = true) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${color(failure.path.join('.'), bold, colorize)} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n colorize = true,\n) {\n const received = color(JSON.stringify(failure.value), red, colorize);\n const prefix = getStructErrorPrefix(failure, colorize);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct, colorize);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(\n /the literal `(.+)`,/u,\n `the value to be \\`${color('$1', green, colorize)}\\`,`,\n )\n .replace(\n /, but received: (.+)/u,\n `, but received: ${color('$1', red, colorize)}`,\n );\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${color(\n failure.path.join('.'),\n bold,\n colorize,\n )}, received: ${received}.`;\n }\n\n if (failure.refinement === 'size') {\n const message = failure.message\n .replace(\n /length between `(\\d+)` and `(\\d+)`/u,\n `length between ${color('$1', green, colorize)} and ${color(\n '$2',\n green,\n colorize,\n )},`,\n )\n .replace(/length of `(\\d+)`/u, `length of ${color('$1', red, colorize)}`)\n .replace(/a array/u, 'an array');\n\n return `${prefix}${message}.`;\n }\n\n return `${prefix}Expected a value of type ${color(\n failure.type,\n green,\n colorize,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @param colorize - Whether to colorize the value. Defaults to `true`.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n colorize = true,\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure, colorize)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n\n/**\n * Validate a union struct, and throw readable errors if the value does not\n * satisfy the struct. This is useful for improving the error messages returned\n * by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @param coerce - Whether to coerce the value to satisfy the struct. Defaults\n * to `false`.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @example\n * const struct = union([\n * object({ type: literal('a'), value: string() }),\n * object({ type: literal('b'), value: number() }),\n * object({ type: literal('c'), value: boolean() }),\n * // ...\n * ]);\n *\n * // At path: type — Expected the value to be one of: \"a\", \"b\", \"c\", but received: \"d\".\n * validateUnion({ type: 'd', value: 'foo' }, struct, 'type');\n *\n * // At path: value — Expected a value of type string, but received: 42.\n * validateUnion({ type: 'a', value: 42 }, struct, 'value');\n */\nexport function validateUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n coerce = false,\n) {\n assert(\n struct.schema,\n 'Expected a struct with a schema. Make sure to use `union` from `@metamask/snaps-sdk`.',\n );\n assert(struct.schema.length > 0, 'Expected a non-empty array of structs.');\n\n const keyUnion = struct.schema.map(\n (innerStruct) => innerStruct.schema[structKey],\n // This is guaranteed to be a non-empty array by the assertion above. We\n // need to cast it since `superstruct` requires a non-empty array of structs\n // for the `union` struct.\n ) as NonEmptyArray<Struct>;\n\n const key = superstructType({\n [structKey]: union(keyUnion),\n });\n\n const [keyError] = validate(value, key, { coerce });\n if (keyError) {\n throw new Error(\n getStructFailureMessage(key, keyError.failures()[0], false),\n );\n }\n\n // At this point it's guaranteed that the value is an object, so we can safely\n // cast it to a Record.\n const objectValue = value as Record<PropertyKey, unknown>;\n const objectStructs = struct.schema.filter((innerStruct) =>\n is(objectValue[structKey], innerStruct.schema[structKey]),\n );\n\n assert(objectStructs.length > 0, 'Expected a struct to match the value.');\n\n // We need to validate the value against all the object structs that match the\n // struct key, and return the first validated value.\n const validationResults = objectStructs.map((objectStruct) =>\n validate(objectValue, objectStruct, { coerce }),\n );\n\n const validatedValue = validationResults.find(([error]) => !error);\n if (validatedValue) {\n return validatedValue[1];\n }\n\n assert(validationResults[0][0], 'Expected at least one error.');\n\n // If there is no validated value, we need to find the error with the least\n // number of failures (with the assumption that it's the most specific error).\n const validationError = validationResults.reduce((error, [innerError]) => {\n assert(innerError, 'Expected an error.');\n if (innerError.failures().length < error.failures().length) {\n return innerError;\n }\n\n return error;\n }, validationResults[0][0]);\n\n throw new Error(\n getStructFailureMessage(struct, validationError.failures()[0], false),\n );\n}\n\n/**\n * Create a value with the coercion logic of a union struct, and throw readable\n * errors if the value does not satisfy the struct. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` union struct to validate the value against.\n * This struct must be a union of object structs, and must have at least one\n * shared key to validate against.\n * @param structKey - The key to validate against. This key must be present in\n * all the object structs in the union struct, and is expected to be a literal\n * value.\n * @returns The validated value.\n * @throws If the value does not satisfy the struct.\n * @see validateUnion\n */\nexport function createUnion<Type, Schema extends readonly Struct<any, any>[]>(\n value: unknown,\n struct: Struct<Type, Schema>,\n structKey: keyof Type,\n) {\n return validateUnion(value, struct, structKey, true);\n}\n"],"names":["file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","validateUnion","createUnion","color","value","colorFunction","enabled","superstructCoerce","string","resolve","process","cwd","name","struct","Struct","type","StructError","constructor","prefix","suffix","failure","failures","colorize","message","array","item","error","create","path","reduce","result","key","isObject","schema","Array","isArray","map","green","length","join","bold","received","JSON","stringify","red","childStruct","unionNames","replace","refinement","formattedFailures","indent","structKey","coerce","assert","keyUnion","innerStruct","superstructType","union","keyError","validate","Error","objectValue","objectStructs","filter","is","validationResults","objectStruct","validatedValue","find","validationError","innerError"],"mappings":";;;;;;;;;;;IAyFgBA,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAoCIC,gBAAgB;eAAhBA;;IAoBDC,QAAQ;eAARA;;IA6BAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAqBAC,mBAAmB;eAAnBA;;IAmBAC,oBAAoB;eAApBA;;IAkBAC,uBAAuB;eAAvBA;;IA6EAC,qBAAqB;eAArBA;;IA0CAC,aAAa;eAAbA;;IAoFAC,WAAW;eAAXA;;;0BApeM;uBAEW;uBACA;sBACT;6BAWjB;yBAGgB;AA6BvB;;;;;;;;;;CAUC,GACD,SAASC,MACPC,KAAa,EACbC,aAAwC,EACxC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AACA;IAC5D,IAAIyC,gBAAgB;QAClB,OAAOA,cAAc,CAAC,EAAE;IAC1B;IAEAd,IAAAA,aAAM,EAACY,iBAAiB,CAAC,EAAE,CAAC,EAAE,EAAE;IAEhC,2EAA2E;IAC3E,8EAA8E;IAC9E,MAAMI,kBAAkBJ,kBAAkBpC,MAAM,CAAC,CAACH,OAAO,CAAC4C,WAAW;QACnEjB,IAAAA,aAAM,EAACiB,YAAY;QACnB,IAAIA,WAAWjD,QAAQ,GAAGiB,MAAM,GAAGZ,MAAML,QAAQ,GAAGiB,MAAM,EAAE;YAC1D,OAAOgC;QACT;QAEA,OAAO5C;IACT,GAAGuC,iBAAiB,CAAC,EAAE,CAAC,EAAE;IAE1B,MAAM,IAAIL,MACR7D,wBAAwBc,QAAQwD,gBAAgBhD,QAAQ,EAAE,CAAC,EAAE,EAAE;AAEnE;AAkBO,SAASnB,YACdE,KAAc,EACdS,MAA4B,EAC5BsC,SAAqB;IAErB,OAAOlD,cAAcG,OAAOS,QAAQsC,WAAW;AACjD"}
@@ -27,6 +27,12 @@ export var SnapCaveatType;
27
27
  SnapCaveatType[/**
28
28
  * Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.
29
29
  */ "ChainIds"] = 'chainIds';
30
+ SnapCaveatType[/**
31
+ * Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.
32
+ */ "LookupMatchers"] = 'lookupMatchers';
33
+ SnapCaveatType[/**
34
+ * Caveat specifying the max request time for a handler endowment.
35
+ */ "MaxRequestTime"] = 'maxRequestTime';
30
36
  })(SnapCaveatType || (SnapCaveatType = {}));
31
37
 
32
38
  //# sourceMappingURL=caveats.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/caveats.ts"],"sourcesContent":["export enum SnapCaveatType {\n /**\n * Permitted derivation paths, used by `snap_getBip32Entropy`.\n */\n PermittedDerivationPaths = 'permittedDerivationPaths',\n\n /**\n * Permitted coin types, used by `snap_getBip44Entropy`.\n */\n PermittedCoinTypes = 'permittedCoinTypes',\n\n /**\n * Caveat specifying a snap cronjob.\n */\n SnapCronjob = 'snapCronjob',\n\n /**\n * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.\n */\n TransactionOrigin = 'transactionOrigin',\n\n /**\n * Caveat specifying access to the signature origin, used by `endowment:signature-insight`.\n */\n SignatureOrigin = 'signatureOrigin',\n\n /**\n * The origins that a Snap can receive JSON-RPC messages from.\n */\n RpcOrigin = 'rpcOrigin',\n\n /**\n * The origins that a Snap can receive keyring messages from.\n */\n KeyringOrigin = 'keyringOrigin',\n\n /**\n * Caveat specifying the snap IDs that can be interacted with.\n */\n SnapIds = 'snapIds',\n\n /**\n * Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.\n */\n ChainIds = 'chainIds',\n}\n"],"names":["SnapCaveatType","PermittedDerivationPaths","PermittedCoinTypes","SnapCronjob","TransactionOrigin","SignatureOrigin","RpcOrigin","KeyringOrigin","SnapIds","ChainIds"],"mappings":"WAAO;UAAKA,cAAc;IAAdA,eACV;;GAEC,GACDC,8BAA2B;IAJjBD,eAMV;;GAEC,GACDE,wBAAqB;IATXF,eAWV;;GAEC,GACDG,iBAAc;IAdJH,eAgBV;;GAEC,GACDI,uBAAoB;IAnBVJ,eAqBV;;GAEC,GACDK,qBAAkB;IAxBRL,eA0BV;;GAEC,GACDM,eAAY;IA7BFN,eA+BV;;GAEC,GACDO,mBAAgB;IAlCNP,eAoCV;;GAEC,GACDQ,aAAU;IAvCAR,eAyCV;;GAEC,GACDS,cAAW;GA5CDT,mBAAAA"}
1
+ {"version":3,"sources":["../../src/caveats.ts"],"sourcesContent":["export enum SnapCaveatType {\n /**\n * Permitted derivation paths, used by `snap_getBip32Entropy`.\n */\n PermittedDerivationPaths = 'permittedDerivationPaths',\n\n /**\n * Permitted coin types, used by `snap_getBip44Entropy`.\n */\n PermittedCoinTypes = 'permittedCoinTypes',\n\n /**\n * Caveat specifying a snap cronjob.\n */\n SnapCronjob = 'snapCronjob',\n\n /**\n * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.\n */\n TransactionOrigin = 'transactionOrigin',\n\n /**\n * Caveat specifying access to the signature origin, used by `endowment:signature-insight`.\n */\n SignatureOrigin = 'signatureOrigin',\n\n /**\n * The origins that a Snap can receive JSON-RPC messages from.\n */\n RpcOrigin = 'rpcOrigin',\n\n /**\n * The origins that a Snap can receive keyring messages from.\n */\n KeyringOrigin = 'keyringOrigin',\n\n /**\n * Caveat specifying the snap IDs that can be interacted with.\n */\n SnapIds = 'snapIds',\n\n /**\n * Caveat specifying the CAIP-2 chain IDs that a snap can service, currently limited to `endowment:name-lookup`.\n */\n ChainIds = 'chainIds',\n\n /**\n * Caveat specifying the input that a name lookup snap can service, currently limited to `endowment:name-lookup`.\n */\n LookupMatchers = 'lookupMatchers',\n\n /**\n * Caveat specifying the max request time for a handler endowment.\n */\n MaxRequestTime = 'maxRequestTime',\n}\n"],"names":["SnapCaveatType","PermittedDerivationPaths","PermittedCoinTypes","SnapCronjob","TransactionOrigin","SignatureOrigin","RpcOrigin","KeyringOrigin","SnapIds","ChainIds","LookupMatchers","MaxRequestTime"],"mappings":"WAAO;UAAKA,cAAc;IAAdA,eACV;;GAEC,GACDC,8BAA2B;IAJjBD,eAMV;;GAEC,GACDE,wBAAqB;IATXF,eAWV;;GAEC,GACDG,iBAAc;IAdJH,eAgBV;;GAEC,GACDI,uBAAoB;IAnBVJ,eAqBV;;GAEC,GACDK,qBAAkB;IAxBRL,eA0BV;;GAEC,GACDM,eAAY;IA7BFN,eA+BV;;GAEC,GACDO,mBAAgB;IAlCNP,eAoCV;;GAEC,GACDQ,aAAU;IAvCAR,eAyCV;;GAEC,GACDS,cAAW;IA5CDT,eA8CV;;GAEC,GACDU,oBAAiB;IAjDPV,eAmDV;;GAEC,GACDW,oBAAiB;GAtDPX,mBAAAA"}
@@ -33,6 +33,8 @@ if (invalidExports.length > 0) {
33
33
  // eslint-disable-next-line no-console
34
34
  console.warn(`Invalid snap exports detected:\n${invalidExports.join('\n')}`);
35
35
  }
36
- setTimeout(()=>process.exit(0), 1000); // Hack to ensure worker exits
36
+ // To ensure the worker exits we explicitly call exit here
37
+ // If we didn't the eval would wait for timers set during Compartment eval
38
+ process.exit(0);
37
39
 
38
40
  //# sourceMappingURL=eval-worker.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handler-types';\nimport { SNAP_EXPORT_NAMES } from './handler-types';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nconst compartment = new Compartment({\n ...generateMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n});\n\n// Mirror BaseSnapExecutor\ncompartment.globalThis.self = compartment.globalThis;\ncompartment.globalThis.global = compartment.globalThis;\ncompartment.globalThis.window = compartment.globalThis;\n\ncompartment.evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"],"names":["readFileSync","SNAP_EXPORT_NAMES","generateMockEndowments","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","snapFilePath","process","argv","snapModule","exports","compartment","Compartment","module","globalThis","self","global","window","evaluate","invalidExports","Object","keys","filter","snapExport","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;AACvD,OAAO,eAAe;AAEtB,SAASA,YAAY,QAAQ,KAAK;AAGlC,SAASC,iBAAiB,QAAQ,kBAAkB;AACpD,SAASC,sBAAsB,QAAQ,SAAS;AAIhDC,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA,MAAMC,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,MAAMC,cAAc,IAAIC,YAAY;IAClC,GAAGd,wBAAwB;IAC3Be,QAAQJ;IACRC,SAASD,WAAWC,OAAO;AAC7B;AAEA,0BAA0B;AAC1BC,YAAYG,UAAU,CAACC,IAAI,GAAGJ,YAAYG,UAAU;AACpDH,YAAYG,UAAU,CAACE,MAAM,GAAGL,YAAYG,UAAU;AACtDH,YAAYG,UAAU,CAACG,MAAM,GAAGN,YAAYG,UAAU;AAEtDH,YAAYO,QAAQ,CAACtB,aAAaU,cAAc;AAEhD,MAAMa,iBAAiBC,OAAOC,IAAI,CAACZ,WAAWC,OAAO,EAAEY,MAAM,CAC3D,CAACC,aAAe,CAAC1B,kBAAkB2B,QAAQ,CAACD;AAG9C,IAAIJ,eAAeM,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAER,eAAeS,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMtB,QAAQuB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
1
+ {"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handler-types';\nimport { SNAP_EXPORT_NAMES } from './handler-types';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nconst compartment = new Compartment({\n ...generateMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n});\n\n// Mirror BaseSnapExecutor\ncompartment.globalThis.self = compartment.globalThis;\ncompartment.globalThis.global = compartment.globalThis;\ncompartment.globalThis.window = compartment.globalThis;\n\ncompartment.evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\n// To ensure the worker exits we explicitly call exit here\n// If we didn't the eval would wait for timers set during Compartment eval\nprocess.exit(0);\n"],"names":["readFileSync","SNAP_EXPORT_NAMES","generateMockEndowments","lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","snapFilePath","process","argv","snapModule","exports","compartment","Compartment","module","globalThis","self","global","window","evaluate","invalidExports","Object","keys","filter","snapExport","includes","length","console","warn","join","exit"],"mappings":"AAAA,uDAAuD;AACvD,OAAO,eAAe;AAEtB,SAASA,YAAY,QAAQ,KAAK;AAGlC,SAASC,iBAAiB,QAAQ,kBAAkB;AACpD,SAASC,sBAAsB,QAAQ,SAAS;AAIhDC,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA,MAAMC,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,MAAMC,cAAc,IAAIC,YAAY;IAClC,GAAGd,wBAAwB;IAC3Be,QAAQJ;IACRC,SAASD,WAAWC,OAAO;AAC7B;AAEA,0BAA0B;AAC1BC,YAAYG,UAAU,CAACC,IAAI,GAAGJ,YAAYG,UAAU;AACpDH,YAAYG,UAAU,CAACE,MAAM,GAAGL,YAAYG,UAAU;AACtDH,YAAYG,UAAU,CAACG,MAAM,GAAGN,YAAYG,UAAU;AAEtDH,YAAYO,QAAQ,CAACtB,aAAaU,cAAc;AAEhD,MAAMa,iBAAiBC,OAAOC,IAAI,CAACZ,WAAWC,OAAO,EAAEY,MAAM,CAC3D,CAACC,aAAe,CAAC1B,kBAAkB2B,QAAQ,CAACD;AAG9C,IAAIJ,eAAeM,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAER,eAAeS,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEA,0DAA0D;AAC1D,0EAA0E;AAC1ErB,QAAQsB,IAAI,CAAC"}
@@ -9,6 +9,7 @@ export var HandlerType;
9
9
  HandlerType["OnNameLookup"] = 'onNameLookup';
10
10
  HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
11
11
  HandlerType["OnHomePage"] = 'onHomePage';
12
+ HandlerType["OnUserInput"] = 'onUserInput';
12
13
  })(HandlerType || (HandlerType = {}));
13
14
  export const SNAP_EXPORT_NAMES = Object.values(HandlerType);
14
15
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnSignature = 'onSignature',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n OnHomePage = 'onHomePage',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["HandlerType","OnRpcRequest","OnSignature","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","OnHomePage","SNAP_EXPORT_NAMES","Object","values"],"mappings":"WAAO;UAAKA,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,iBAAc;IAFJF,YAGVG,mBAAgB;IAHNH,YAIVI,eAAY;IAJFJ,YAKVK,eAAY;IALFL,YAMVM,cAAW;IANDN,YAOVO,kBAAe;IAPLP,YAQVQ,sBAAmB;IARTR,YASVS,gBAAa;GATHT,gBAAAA;AAoCZ,OAAO,MAAMU,oBAAoBC,OAAOC,MAAM,CAACZ,aAAa"}
1
+ {"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnSignature = 'onSignature',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n OnHomePage = 'onHomePage',\n OnUserInput = 'onUserInput',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["HandlerType","OnRpcRequest","OnSignature","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","OnHomePage","OnUserInput","SNAP_EXPORT_NAMES","Object","values"],"mappings":"WAAO;UAAKA,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,iBAAc;IAFJF,YAGVG,mBAAgB;IAHNH,YAIVI,eAAY;IAJFJ,YAKVK,eAAY;IALFL,YAMVM,cAAW;IANDN,YAOVO,kBAAe;IAPLP,YAQVQ,sBAAmB;IARTR,YASVS,gBAAa;IATHT,YAUVU,iBAAc;GAVJV,gBAAAA;AAqCZ,OAAO,MAAMW,oBAAoBC,OAAOC,MAAM,CAACb,aAAa"}