@metamask/snaps-utils 3.2.0 → 4.0.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 (89) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/dist/cjs/auxiliary-files.js +6 -19
  3. package/dist/cjs/auxiliary-files.js.map +1 -1
  4. package/dist/cjs/checksum.js +22 -5
  5. package/dist/cjs/checksum.js.map +1 -1
  6. package/dist/cjs/cronjob.js.map +1 -1
  7. package/dist/cjs/enum.js.map +1 -1
  8. package/dist/cjs/errors.js +6 -154
  9. package/dist/cjs/errors.js.map +1 -1
  10. package/dist/cjs/handler-types.js +1 -0
  11. package/dist/cjs/handler-types.js.map +1 -1
  12. package/dist/cjs/handlers.js +17 -11
  13. package/dist/cjs/handlers.js.map +1 -1
  14. package/dist/cjs/index.browser.js +2 -0
  15. package/dist/cjs/index.browser.js.map +1 -1
  16. package/dist/cjs/index.js +2 -7
  17. package/dist/cjs/index.js.map +1 -1
  18. package/dist/cjs/localization.js +113 -0
  19. package/dist/cjs/localization.js.map +1 -0
  20. package/dist/cjs/manifest/manifest.js +33 -19
  21. package/dist/cjs/manifest/manifest.js.map +1 -1
  22. package/dist/cjs/manifest/validation.js +3 -2
  23. package/dist/cjs/manifest/validation.js.map +1 -1
  24. package/dist/cjs/namespace.js +5 -1
  25. package/dist/cjs/namespace.js.map +1 -1
  26. package/dist/cjs/npm.js +18 -5
  27. package/dist/cjs/npm.js.map +1 -1
  28. package/dist/cjs/snaps.js +7 -6
  29. package/dist/cjs/snaps.js.map +1 -1
  30. package/dist/cjs/structs.js.map +1 -1
  31. package/dist/cjs/types.js.map +1 -1
  32. package/dist/cjs/ui.js +51 -0
  33. package/dist/cjs/ui.js.map +1 -0
  34. package/dist/cjs/validation.js +4 -2
  35. package/dist/cjs/validation.js.map +1 -1
  36. package/dist/esm/auxiliary-files.js +1 -6
  37. package/dist/esm/auxiliary-files.js.map +1 -1
  38. package/dist/esm/checksum.js +25 -6
  39. package/dist/esm/checksum.js.map +1 -1
  40. package/dist/esm/cronjob.js +1 -1
  41. package/dist/esm/cronjob.js.map +1 -1
  42. package/dist/esm/enum.js.map +1 -1
  43. package/dist/esm/errors.js +2 -157
  44. package/dist/esm/errors.js.map +1 -1
  45. package/dist/esm/handler-types.js +1 -0
  46. package/dist/esm/handler-types.js.map +1 -1
  47. package/dist/esm/handlers.js +13 -7
  48. package/dist/esm/handlers.js.map +1 -1
  49. package/dist/esm/index.browser.js +2 -0
  50. package/dist/esm/index.browser.js.map +1 -1
  51. package/dist/esm/index.js +2 -1
  52. package/dist/esm/index.js.map +1 -1
  53. package/dist/esm/localization.js +115 -0
  54. package/dist/esm/localization.js.map +1 -0
  55. package/dist/esm/manifest/manifest.js +37 -19
  56. package/dist/esm/manifest/manifest.js.map +1 -1
  57. package/dist/esm/manifest/validation.js +4 -3
  58. package/dist/esm/manifest/validation.js.map +1 -1
  59. package/dist/esm/namespace.js +3 -2
  60. package/dist/esm/namespace.js.map +1 -1
  61. package/dist/esm/npm.js +18 -5
  62. package/dist/esm/npm.js.map +1 -1
  63. package/dist/esm/snaps.js +7 -6
  64. package/dist/esm/snaps.js.map +1 -1
  65. package/dist/esm/structs.js.map +1 -1
  66. package/dist/esm/types.js.map +1 -1
  67. package/dist/esm/ui.js +48 -0
  68. package/dist/esm/ui.js.map +1 -0
  69. package/dist/esm/validation.js +4 -2
  70. package/dist/esm/validation.js.map +1 -1
  71. package/dist/types/auxiliary-files.d.ts +1 -5
  72. package/dist/types/checksum.d.ts +9 -2
  73. package/dist/types/enum.d.ts +1 -21
  74. package/dist/types/errors.d.ts +1 -109
  75. package/dist/types/handler-types.d.ts +2 -1
  76. package/dist/types/handlers.d.ts +73 -152
  77. package/dist/types/index.browser.d.ts +2 -0
  78. package/dist/types/index.d.ts +2 -1
  79. package/dist/types/localization.d.ts +143 -0
  80. package/dist/types/manifest/manifest.d.ts +16 -7
  81. package/dist/types/manifest/validation.d.ts +83 -78
  82. package/dist/types/namespace.d.ts +11 -10
  83. package/dist/types/npm.d.ts +1 -1
  84. package/dist/types/snaps.d.ts +13 -43
  85. package/dist/types/structs.d.ts +23 -0
  86. package/dist/types/types.d.ts +4 -2
  87. package/dist/types/ui.d.ts +20 -0
  88. package/dist/types/validation.d.ts +1 -1
  89. package/package.json +3 -3
package/dist/cjs/npm.js CHANGED
@@ -20,6 +20,7 @@ _export(exports, {
20
20
  }
21
21
  });
22
22
  const _icon = require("./icon");
23
+ const _localization = require("./localization");
23
24
  const _manifest = require("./manifest/manifest");
24
25
  const _validation = require("./manifest/validation");
25
26
  const _types = require("./types");
@@ -33,14 +34,14 @@ const SnapFileNameFromKey = {
33
34
  packageJson: _types.NpmSnapFileNames.PackageJson,
34
35
  sourceCode: 'source code bundle'
35
36
  };
36
- function validateNpmSnap(snapFiles, errorPrefix) {
37
+ async function validateNpmSnap(snapFiles, errorPrefix) {
37
38
  EXPECTED_SNAP_FILES.forEach((key)=>{
38
39
  if (!snapFiles[key]) {
39
40
  throw new Error(`${errorPrefix ?? ''}Missing file "${SnapFileNameFromKey[key]}".`);
40
41
  }
41
42
  });
42
43
  // Typecast: We are assured that the required files exist if we get here.
43
- const { manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles } = snapFiles;
44
+ const { manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } = snapFiles;
44
45
  try {
45
46
  (0, _validation.assertIsSnapManifest)(manifest.result);
46
47
  } catch (error) {
@@ -57,12 +58,13 @@ function validateNpmSnap(snapFiles, errorPrefix) {
57
58
  throw new Error(`${errorPrefix ?? ''}${error.message}`);
58
59
  }
59
60
  const validatedPackageJson = packageJson;
60
- (0, _manifest.validateNpmSnapManifest)({
61
+ await (0, _manifest.validateNpmSnapManifest)({
61
62
  manifest: validatedManifest,
62
63
  packageJson: validatedPackageJson,
63
64
  sourceCode,
64
65
  svgIcon,
65
- auxiliaryFiles
66
+ auxiliaryFiles,
67
+ localizationFiles
66
68
  });
67
69
  if (svgIcon) {
68
70
  try {
@@ -71,12 +73,23 @@ function validateNpmSnap(snapFiles, errorPrefix) {
71
73
  throw new Error(`${errorPrefix ?? ''}${error.message}`);
72
74
  }
73
75
  }
76
+ if (localizationFiles) {
77
+ try {
78
+ // This function validates and returns the localization files. We don't
79
+ // use the return value here, but we do want to validate the files.
80
+ (0, _localization.getValidatedLocalizationFiles)(localizationFiles);
81
+ (0, _localization.validateSnapManifestLocalizations)(manifest.result, localizationFiles.map((file)=>file.result));
82
+ } catch (error) {
83
+ throw new Error(`${errorPrefix ?? ''}${error.message}`);
84
+ }
85
+ }
74
86
  return {
75
87
  manifest: validatedManifest,
76
88
  packageJson: validatedPackageJson,
77
89
  sourceCode,
78
90
  svgIcon,
79
- auxiliaryFiles
91
+ auxiliaryFiles,
92
+ localizationFiles
80
93
  };
81
94
  }
82
95
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles } =\n snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n };\n}\n"],"names":["EXPECTED_SNAP_FILES","SnapFileNameFromKey","validateNpmSnap","manifest","NpmSnapFileNames","Manifest","packageJson","PackageJson","sourceCode","snapFiles","errorPrefix","forEach","key","Error","svgIcon","auxiliaryFiles","assertIsSnapManifest","result","error","message","validatedManifest","iconPath","source","location","npm","assertIsNpmSnapPackageJson","validatedPackageJson","validateNpmSnapManifest","assertIsSnapIcon"],"mappings":";;;;;;;;;;;IAMaA,mBAAmB;eAAnBA;;IAMAC,mBAAmB;eAAnBA;;IAkBGC,eAAe;eAAfA;;;sBA9BiB;0BACO;4BACH;uBAEwB;AAEtD,MAAMF,sBAAsB;IACjC;IACA;IACA;CACD;AAEM,MAAMC,sBAAsB;IACjCE,UAAUC,uBAAgB,CAACC,QAAQ;IACnCC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O;QACLhB,UAAUiB;QACVd,aAAaoB;QACblB;QACAM;QACAC;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport {\n getValidatedLocalizationFiles,\n validateSnapManifestLocalizations,\n} from './localization';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport async function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): Promise<SnapFiles> {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const {\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n } = snapFiles as SnapFiles;\n\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n\n const validatedPackageJson = packageJson;\n await validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n if (localizationFiles) {\n try {\n // This function validates and returns the localization files. We don't\n // use the return value here, but we do want to validate the files.\n getValidatedLocalizationFiles(localizationFiles);\n\n validateSnapManifestLocalizations(\n manifest.result,\n localizationFiles.map((file) => file.result),\n );\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n };\n}\n"],"names":["EXPECTED_SNAP_FILES","SnapFileNameFromKey","validateNpmSnap","manifest","NpmSnapFileNames","Manifest","packageJson","PackageJson","sourceCode","snapFiles","errorPrefix","forEach","key","Error","svgIcon","auxiliaryFiles","localizationFiles","assertIsSnapManifest","result","error","message","validatedManifest","iconPath","source","location","npm","assertIsNpmSnapPackageJson","validatedPackageJson","validateNpmSnapManifest","assertIsSnapIcon","getValidatedLocalizationFiles","validateSnapManifestLocalizations","map","file"],"mappings":";;;;;;;;;;;IAUaA,mBAAmB;eAAnBA;;IAMAC,mBAAmB;eAAnBA;;IAkBSC,eAAe;eAAfA;;;sBAlCW;8BAI1B;0BACiC;4BACH;uBAEwB;AAEtD,MAAMF,sBAAsB;IACjC;IACA;IACA;CACD;AAEM,MAAMC,sBAAsB;IACjCE,UAAUC,uBAAgB,CAACC,QAAQ;IACnCC,aAAaF,uBAAgB,CAACG,WAAW;IACzCC,YAAY;AACd;AAcO,eAAeN,gBACpBO,SAA+B,EAC/BC,WAA2B;IAE3BV,oBAAoBW,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Be,IAAAA,+CAAiC,EAC/B5B,SAASe,MAAM,EACfF,kBAAkBgB,GAAG,CAAC,CAACC,OAASA,KAAKf,MAAM;QAE/C,EAAE,OAAOC,OAAO;YACd,MAAM,IAAIN,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAES,MAAMC,OAAO,CAAC,CAAC;QACxD;IACF;IAEA,OAAO;QACLjB,UAAUkB;QACVf,aAAaqB;QACbnB;QACAM;QACAC;QACAC;IACF;AACF"}
package/dist/cjs/snaps.js CHANGED
@@ -126,18 +126,19 @@ class ProgrammaticallyFixableSnapError extends Error {
126
126
  manifestCopy.value = (0, _fastjsonstablestringify.default)(manifestCopy.result);
127
127
  return manifestCopy;
128
128
  }
129
- function getSnapChecksum(files) {
130
- const { manifest, sourceCode, svgIcon, auxiliaryFiles } = files;
129
+ async function getSnapChecksum(files) {
130
+ const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } = files;
131
131
  const all = [
132
132
  getChecksummableManifest(manifest),
133
133
  sourceCode,
134
134
  svgIcon,
135
- ...auxiliaryFiles
135
+ ...auxiliaryFiles,
136
+ ...localizationFiles
136
137
  ].filter((file)=>file !== undefined);
137
- return _base.base64.encode((0, _checksum.checksumFiles)(all));
138
+ return _base.base64.encode(await (0, _checksum.checksumFiles)(all));
138
139
  }
139
- function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.') {
140
- if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {
140
+ async function validateSnapShasum(files, errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.') {
141
+ if (files.manifest.result.source.shasum !== await getSnapChecksum(files)) {
141
142
  throw new ProgrammaticallyFixableSnapError(errorMessage, _types.SnapValidationFailureReason.ShasumMismatch);
142
143
  }
143
144
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type {\n Json,\n JsonRpcError,\n Opaque,\n SemVerVersion,\n} from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { FetchedSnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult = TruncatedSnap | { error: JsonRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(files: FetchedSnapFiles): string {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles } = files;\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ].filter((file) => file !== undefined);\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["PROPOSED_NAME_REGEX","ProgrammaticallyFixableSnapError","getSnapChecksum","validateSnapShasum","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdStruct","NpmSnapIdStruct","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","stripSnapPrefix","assertIsValidSnapId","isCaipChainId","isSnapPermitted","verifyRequestedSnapPermissions","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","stableStringify","files","sourceCode","svgIcon","auxiliaryFiles","all","filter","file","undefined","base64","encode","checksumFiles","errorMessage","SnapValidationFailureReason","ShasumMismatch","pattern","string","LocalSnapIdSubUrlStruct","uri","protocol","enums","hostname","hash","empty","search","refine","startsWith","SnapIdPrefixes","local","error","validate","slice","length","intersection","literal","npm","pathname","normalized","errors","validForNewPackages","warnings","validateNPMPackage","assert","union","snapId","prefix","Object","values","find","possiblePrefix","replace","assertStruct","chainId","test","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapCaveatType","SnapIds","requestedPermissions","isObject","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;;;;;IA6CaA,mBAAmB;eAAnBA;;IAqIAC,gCAAgC;eAAhCA;;IAiCGC,eAAe;eAAfA;;IAkBAC,kBAAkB;eAAlBA;;IAYHC,mBAAmB;eAAnBA;;IAGAC,gBAAgB;eAAhBA;;IAQAC,iBAAiB;eAAjBA;;IAeAC,eAAe;eAAfA;;IAuBAC,gBAAgB;eAAhBA;;IASAC,YAAY;eAAZA;;IAWGC,aAAa;eAAbA;;IAgBAC,eAAe;eAAfA;;IAUAC,mBAAmB;eAAnBA;;IAYAC,aAAa;eAAbA;;IAgBAC,eAAe;eAAfA;;IAsB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,eAAQ,EAACD,uBACT;IAGF,MAAM,EAAEN,aAAaQ,oBAAoB,EAAE,GAAGF;IAE9CpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACC,uBACT;IAGF,MAAM,EAAEP,OAAO,EAAE,GAAGO;IAEpBtB,IAAAA,aAAM,EACJuB,MAAMC,OAAO,CAACT,YAAYA,QAAQzB,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC0B,OAAO,GAAGD;IAEjBf,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACL,WACPA,OAAOC,IAAI,KAAKC,uBAAc,CAACC,OAAO,IACtCE,IAAAA,eAAQ,EAACL,OAAO3D,KAAK,GACvB,CAAC,8CAA8C,EAAE6D,uBAAc,CAACC,OAAO,CAAC,QAAQ,CAAC;AAErF"}
1
+ {"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"],"names":["PROPOSED_NAME_REGEX","ProgrammaticallyFixableSnapError","getSnapChecksum","validateSnapShasum","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdStruct","NpmSnapIdStruct","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","stripSnapPrefix","assertIsValidSnapId","isCaipChainId","isSnapPermitted","verifyRequestedSnapPermissions","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","stableStringify","files","sourceCode","svgIcon","auxiliaryFiles","localizationFiles","all","filter","file","undefined","base64","encode","checksumFiles","errorMessage","SnapValidationFailureReason","ShasumMismatch","pattern","string","LocalSnapIdSubUrlStruct","uri","protocol","enums","hostname","hash","empty","search","refine","startsWith","SnapIdPrefixes","local","error","validate","slice","length","intersection","literal","npm","pathname","normalized","errors","validForNewPackages","warnings","validateNPMPackage","assert","union","snapId","prefix","Object","values","find","possiblePrefix","replace","assertStruct","chainId","test","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapCaveatType","SnapIds","requestedPermissions","isObject","walletSnapPermission","Array","isArray"],"mappings":";;;;;;;;;;;;;;;;;IA0CaA,mBAAmB;eAAnBA;;IAmGAC,gCAAgC;eAAhCA;;IAiCSC,eAAe;eAAfA;;IAwBAC,kBAAkB;eAAlBA;;IAYTC,mBAAmB;eAAnBA;;IAGAC,gBAAgB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,gBACdgF,WAAqD,EACrDV,MAAc;IAEd,OAAOW,QAEH,AACGD,CAAAA,aAAaE,aAAaC,SAAST,KAClC,CAACU,SAAWA,OAAOC,IAAI,KAAKC,uBAAc,CAACC,OAAO,KAC/C,CAAC,CAAA,EACN/D,KAAK,EACN,CAAC8C,OAAO;AAEf;AASO,SAASrE,+BACduF,oBAA6B;IAE7BpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACD,uBACT;IAGF,MAAM,EAAEN,aAAaQ,oBAAoB,EAAE,GAAGF;IAE9CpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACC,uBACT;IAGF,MAAM,EAAEP,OAAO,EAAE,GAAGO;IAEpBtB,IAAAA,aAAM,EACJuB,MAAMC,OAAO,CAACT,YAAYA,QAAQzB,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC0B,OAAO,GAAGD;IAEjBf,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACL,WACPA,OAAOC,IAAI,KAAKC,uBAAc,CAACC,OAAO,IACtCE,IAAAA,eAAQ,EAACL,OAAO5D,KAAK,GACvB,CAAC,8CAA8C,EAAE8D,uBAAc,CAACC,OAAO,CAAC,QAAQ,CAAC;AAErF"}
@@ -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, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\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 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":["literal","union","file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","value","define","JSON","stringify","superstructLiteral","validator","head","tail","struct","superstructUnion","Struct","schema","coerce","string","resolve","process","cwd","name","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","Array","isArray","map","green","length","bold","join","received","red","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAuCgBA,OAAO;eAAPA;;IAmBAC,KAAK;eAALA;;IAkCAC,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;;;uBA9TS;uBACQ;sBACT;6BAWjB;yBAGgB;AAuBhB,SAASZ,QAAgDa,KAAW;IACzE,OAAOC,IAAAA,mBAAM,EACXC,KAAKC,SAAS,CAACH,QACfI,IAAAA,oBAAkB,EAACJ,OAAOK,SAAS;AAEvC;AAcO,SAASjB,MAAwD,CACtEkB,MACA,GAAGC,KACyB;IAI5B,MAA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,QAAQE,OAAO,CAAC,CAAC,CAAC;IACvC;IAEA,IAAIF,QAAQL,IAAI,KAAK,WAAW;QAC9B,yEAAyE;QACzE,0EAA0E;QAC1E,MAAMO,UAAUF,QAAQE,OAAO,CAC5BqB,OAAO,CAAC,wBAAwB,CAAC,kBAAkB,EAAER,IAAAA,YAAK,EAAC,MAAM,GAAG,CAAC,EACrEQ,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,EAAEH,IAAAA,UAAG,EAAC,MAAM,CAAC;QAElE,OAAO,CAAC,EAAEtB,OAAO,EAAEI,QAAQ,CAAC,CAAC;IAC/B;IAEA,IAAIF,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAEsB,IAAAA,WAAI,EACzBjB,QAAQO,IAAI,CAACW,IAAI,CAAC,MAClB,YAAY,EAAEC,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAErB,OAAO,yBAAyB,EAAEiB,IAAAA,YAAK,EAC/Cf,QAAQL,IAAI,EACZ,gBAAgB,EAAEwB,SAAS,CAAC,CAAC;AACjC;AAUO,SAAS3C,sBACdS,MAA4B,EAC5BgB,QAAmB;IAEnB,MAAMuB,oBAAoBvB,SAASa,GAAG,CAAC,CAACd,UACtCyB,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAElD,wBAAwBU,QAAQe,SAAS,CAAC;IAGxD,OAAOwB,kBAAkBN,IAAI,CAAC;AAChC"}
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, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } 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 `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\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 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":["literal","union","file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","value","define","JSON","stringify","superstructLiteral","validator","head","tail","struct","superstructUnion","Struct","schema","coerce","string","resolve","process","cwd","name","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","Array","isArray","map","green","length","bold","join","received","red","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAkEgBA,OAAO;eAAPA;;IAmBAC,KAAK;eAALA;;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nB,MAAMuB,oBAAoBvB,SAASa,GAAG,CAAC,CAACd,UACtCyB,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAElD,wBAAwBU,QAAQe,SAAS,CAAC;IAGxD,OAAOwB,kBAAkBN,IAAI,CAAC;AAChC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapId = string;\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"],"names":["NameStruct","NpmSnapPackageJsonStruct","isNpmSnapPackageJson","assertIsNpmSnapPackageJson","uri","isValidUrl","WALLET_SNAP_PERMISSION_KEY","NpmSnapFileNames","PackageJson","Manifest","size","pattern","string","type","version","VersionStruct","name","main","optional","Infinity","repository","object","url","value","is","assertStruct","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","opts","refine","union","instance","URL","UrlStruct","assertSuperstruct","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;IA2BaA,UAAU;eAAVA;;IAWAC,wBAAwB;eAAxBA;;IAqBGC,oBAAoB;eAApBA;;IAYAC,0BAA0B;eAA1BA;;IAyFHC,GAAG;eAAHA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BAAQ,EAACC;KAAK,GAAG,OAAO,CAAClB;QAC/C,IAAI;YACF,MAAMD,MAAM,IAAImB,IAAIlB;YAEpB,MAAMmB,YAAY7B,IAAAA,iBAAI,EAACwB;YACvBM,IAAAA,mBAAiB,EAACrB,KAAKoB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEnB,MAAMqB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF;AASK,SAASvC,WACdiB,GAAY,EACZe,OAAwB,CAAC,CAAC;IAE1B,OAAOb,IAAAA,eAAE,EAACF,KAAKlB,IAAIiC;AACrB;AAGO,MAAM/B,6BAA6B"}
1
+ {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports, SnapRpcHookArgs } from './handlers';\nimport type { LocalizationFile } from './localization';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile[];\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n auxiliaryFiles: VirtualFile[];\n localizationFiles: VirtualFile<LocalizationFile>[];\n};\n\n/**\n * A subset of snap files extracted from a fetched snap.\n */\nexport type FetchedSnapFiles = Pick<\n SnapFiles,\n 'manifest' | 'sourceCode' | 'svgIcon' | 'auxiliaryFiles' | 'localizationFiles'\n>;\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"],"names":["NameStruct","NpmSnapPackageJsonStruct","isNpmSnapPackageJson","assertIsNpmSnapPackageJson","uri","isValidUrl","WALLET_SNAP_PERMISSION_KEY","NpmSnapFileNames","PackageJson","Manifest","size","pattern","string","type","version","VersionStruct","name","main","optional","Infinity","repository","object","url","value","is","assertStruct","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","opts","refine","union","instance","URL","UrlStruct","assertSuperstruct","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;IA4BaA,UAAU;eAAVA;;IAWAC,wBAAwB;eAAxBA;;IAqBGC,oBAAoB;eAApBA;;IAYAC,0BAA0B;eAA1BA;;IAyFHC,GAAG;eAAHA;;IAoBGC,UAAU;eAAVA;;IAQHC,0BAA0B;eAA1BA;;;uBA5L+B;6BAcrC;IAQA;UAAKC,gBAAgB;IAAhBA,iBACVC,iBAAc;IADJD,iBAEVE,cAAW;GAFDF,qBAAAA;AAKL,MAAMP,aAAaU,IAAAA,iBAAI,EAC5BC,IAAAA,oBAAO,EACLC,IAAAA,mBAAM,KACN,gEAEF,GACA;AAKK,MAAMX,2BAA2BY,IAAAA,iBAAI,EAAC;IAC3CC,SAASC,oBAAa;IACtBC,MAAMhB;IACNiB,MAAMC,IAAAA,qBAAQ,EAACR,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;IACjCC,YAAYF,IAAAA,qBAAQ,EAClBG,IAAAA,mBAAM,EAAC;QACLR,MAAMH,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;QACxBG,KAAKZ,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;IACzB;AAEJ;AAWO,SAASjB,qBACdqB,KAAc;IAEd,OAAOC,IAAAA,eAAE,EAACD,OAAOtB;AACnB;AAQO,SAASE,2BACdoB,KAAc;IAEdE,IAAAA,mBAAY,EACVF,OACAtB,0BACA,CAAC,CAAC,EAAEM,iBAAiBC,WAAW,CAAC,YAAY,CAAC;AAElD;IAuCO;UAAKkB,cAAc;IAAdA,eACVC,SAAM;IADID,eAEVE,WAAQ;GAFEF,mBAAAA;IAUL;UAAKG,2BAA2B;IAA3BA,4BACVC,kBAAe;IADLD,4BAEVE,qBAAkB;IAFRF,4BAGVG,wBAAqB;IAHXH,4BAIVI,oBAAiB;GAJPJ,gCAAAA;IAQL;UAAKK,iBAAiB;IAAjBA,kBACVC,cAAW;IADDD,kBAEVE,aAAU;GAFAF,sBAAAA;AAwBL,MAAM9B,MAAM,CAACiC,OAAwB,CAAC,CAAC,GAC5CC,IAAAA,mBAAM,EAACC,IAAAA,kBAAK,EAAC;QAAC3B,IAAAA,mBAAM;QAAI4B,IAAAA,qBAAQ,EAACC;KAAK,GAAG,OAAO,CAAClB;QAC/C,IAAI;YACF,MAAMD,MAAM,IAAImB,IAAIlB;YAEpB,MAAMmB,YAAY7B,IAAAA,iBAAI,EAACwB;YACvBM,IAAAA,mBAAiB,EAACrB,KAAKoB;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEnB,MAAMqB,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF;AASK,SAASvC,WACdiB,GAAY,EACZe,OAAwB,CAAC,CAAC;IAE1B,OAAOb,IAAAA,eAAE,EAACF,KAAKlB,IAAIiC;AACrB;AAGO,MAAM/B,6BAA6B"}
package/dist/cjs/ui.js ADDED
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ validateTextLinks: function() {
13
+ return validateTextLinks;
14
+ },
15
+ validateComponentLinks: function() {
16
+ return validateComponentLinks;
17
+ }
18
+ });
19
+ const _snapssdk = require("@metamask/snaps-sdk");
20
+ const _utils = require("@metamask/utils");
21
+ const LINK_REGEX = RegExp("(?<protocol>[a-z]+:\\/?\\/?)(?<host>\\S+?(?:\\.[a-z]+)+)", "giu");
22
+ const ALLOWED_PROTOCOLS = [
23
+ 'https:',
24
+ 'mailto:'
25
+ ];
26
+ function validateTextLinks(text, isOnPhishingList) {
27
+ const links = text.match(LINK_REGEX);
28
+ if (links) {
29
+ links.forEach((link)=>{
30
+ try {
31
+ const url = new URL(link);
32
+ (0, _utils.assert)(ALLOWED_PROTOCOLS.includes(url.protocol), `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`);
33
+ const hostname = url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;
34
+ (0, _utils.assert)(!isOnPhishingList(hostname), 'The specified URL is not allowed.');
35
+ } catch (error) {
36
+ throw new Error(`Invalid URL: ${error instanceof _utils.AssertionError ? error.message : 'Unable to parse URL.'}`);
37
+ }
38
+ });
39
+ }
40
+ }
41
+ function validateComponentLinks(component, isOnPhishingList) {
42
+ const { type } = component;
43
+ if (type === _snapssdk.NodeType.Panel) {
44
+ component.children.forEach((node)=>validateComponentLinks(node, isOnPhishingList));
45
+ }
46
+ if ((0, _utils.hasProperty)(component, 'value') && typeof component.value === 'string') {
47
+ validateTextLinks(component.value, isOnPhishingList);
48
+ }
49
+ }
50
+
51
+ //# sourceMappingURL=ui.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/ui.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport { assert, AssertionError, hasProperty } from '@metamask/utils';\n\nconst LINK_REGEX = /(?<protocol>[a-z]+:\\/?\\/?)(?<host>\\S+?(?:\\.[a-z]+)+)/giu;\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Search for links in a sting and check them against the phishing list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const links = text.match(LINK_REGEX);\n if (links) {\n links.forEach((link) => {\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:'\n ? url.pathname.split('@')[1]\n : url.hostname;\n\n assert(\n !isOnPhishingList(hostname),\n 'The specified URL is not allowed.',\n );\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError\n ? error.message\n : 'Unable to parse URL.'\n }`,\n );\n }\n });\n }\n}\n\n/**\n * Search for links in UI components and check that the URL they are trying to\n * pass in is not in the phishing list.\n *\n * @param component - The custom UI component.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the component contains a link that is not allowed.\n */\nexport function validateComponentLinks(\n component: Component,\n isOnPhishingList: (url: string) => boolean,\n) {\n const { type } = component;\n if (type === NodeType.Panel) {\n component.children.forEach((node) =>\n validateComponentLinks(node, isOnPhishingList),\n );\n }\n\n if (hasProperty(component, 'value') && typeof component.value === 'string') {\n validateTextLinks(component.value, isOnPhishingList);\n }\n}\n"],"names":["validateTextLinks","validateComponentLinks","LINK_REGEX","ALLOWED_PROTOCOLS","text","isOnPhishingList","links","match","forEach","link","url","URL","assert","includes","protocol","join","hostname","pathname","split","error","Error","AssertionError","message","component","type","NodeType","Panel","children","node","hasProperty","value"],"mappings":";;;;;;;;;;;IAegBA,iBAAiB;eAAjBA;;IA6CAC,sBAAsB;eAAtBA;;;0BA3DS;uBAC2B;AAEpD,MAAMC,aAAa;AACnB,MAAMC,oBAAoB;IAAC;IAAU;CAAU;AAUxC,SAASH,kBACdI,IAAY,EACZC,gBAA0C;IAE1C,MAAMC,QAAQF,KAAKG,KAAK,CAACL;IACzB,IAAII,OAAO;QACTA,MAAME,OAAO,CAAC,CAACC;YACb,IAAI;gBACF,MAAMC,MAAM,IAAIC,IAAIF;gBACpBG,IAAAA,aAAM,EACJT,kBAAkBU,QAAQ,CAACH,IAAII,QAAQ,GACvC,CAAC,yBAAyB,EAAEX,kBAAkBY,IAAI,CAAC,MAAM,CAAC,CAAC;gBAG7D,MAAMC,WACJN,IAAII,QAAQ,KAAK,YACbJ,IAAIO,QAAQ,CAACC,KAAK,CAAC,IAAI,CAAC,EAAE,GAC1BR,IAAIM,QAAQ;gBAElBJ,IAAAA,aAAM,EACJ,CAACP,iBAAiBW,WAClB;YAEJ,EAAE,OAAOG,OAAO;gBACd,MAAM,IAAIC,MACR,CAAC,aAAa,EACZD,iBAAiBE,qBAAc,GAC3BF,MAAMG,OAAO,GACb,uBACL,CAAC;YAEN;QACF;IACF;AACF;AAWO,SAASrB,uBACdsB,SAAoB,EACpBlB,gBAA0C;IAE1C,MAAM,EAAEmB,IAAI,EAAE,GAAGD;IACjB,IAAIC,SAASC,kBAAQ,CAACC,KAAK,EAAE;QAC3BH,UAAUI,QAAQ,CAACnB,OAAO,CAAC,CAACoB,OAC1B3B,uBAAuB2B,MAAMvB;IAEjC;IAEA,IAAIwB,IAAAA,kBAAW,EAACN,WAAW,YAAY,OAAOA,UAAUO,KAAK,KAAK,UAAU;QAC1E9B,kBAAkBuB,UAAUO,KAAK,EAAEzB;IACrC;AACF"}
@@ -9,11 +9,13 @@ Object.defineProperty(exports, "validateFetchedSnap", {
9
9
  }
10
10
  });
11
11
  const _icon = require("./icon");
12
+ const _localization = require("./localization");
12
13
  const _validation = require("./manifest/validation");
13
14
  const _snaps = require("./snaps");
14
- function validateFetchedSnap(files) {
15
+ async function validateFetchedSnap(files) {
15
16
  (0, _validation.assertIsSnapManifest)(files.manifest.result);
16
- (0, _snaps.validateSnapShasum)(files);
17
+ await (0, _snaps.validateSnapShasum)(files);
18
+ (0, _localization.validateSnapManifestLocalizations)(files.manifest.result, files.localizationFiles.map((file)=>file.result));
17
19
  if (files.svgIcon) {
18
20
  (0, _icon.assertIsSnapIcon)(files.svgIcon);
19
21
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { FetchedSnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport function validateFetchedSnap(files: FetchedSnapFiles): void {\n assertIsSnapManifest(files.manifest.result);\n validateSnapShasum(files);\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["validateFetchedSnap","files","assertIsSnapManifest","manifest","result","validateSnapShasum","svgIcon","assertIsSnapIcon"],"mappings":";;;;+BAWgBA;;;eAAAA;;;sBAXiB;4BACI;uBACF;AAS5B,SAASA,oBAAoBC,KAAuB;IACzDC,IAAAA,gCAAoB,EAACD,MAAME,QAAQ,CAACC,MAAM;IAC1CC,IAAAA,yBAAkB,EAACJ;IAEnB,IAAIA,MAAMK,OAAO,EAAE;QACjBC,IAAAA,sBAAgB,EAACN,MAAMK,OAAO;IAChC;AACF"}
1
+ {"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateSnapManifestLocalizations } from './localization';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport type { FetchedSnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport async function validateFetchedSnap(\n files: FetchedSnapFiles,\n): Promise<void> {\n assertIsSnapManifest(files.manifest.result);\n await validateSnapShasum(files);\n validateSnapManifestLocalizations(\n files.manifest.result,\n files.localizationFiles.map((file) => file.result),\n );\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["validateFetchedSnap","files","assertIsSnapManifest","manifest","result","validateSnapShasum","validateSnapManifestLocalizations","localizationFiles","map","file","svgIcon","assertIsSnapIcon"],"mappings":";;;;+BAYsBA;;;eAAAA;;;sBAZW;8BACiB;4BACb;uBACF;AAS5B,eAAeA,oBACpBC,KAAuB;IAEvBC,IAAAA,gCAAoB,EAACD,MAAME,QAAQ,CAACC,MAAM;IAC1C,MAAMC,IAAAA,yBAAkB,EAACJ;IACzBK,IAAAA,+CAAiC,EAC/BL,MAAME,QAAQ,CAACC,MAAM,EACrBH,MAAMM,iBAAiB,CAACC,GAAG,CAAC,CAACC,OAASA,KAAKL,MAAM;IAGnD,IAAIH,MAAMS,OAAO,EAAE;QACjBC,IAAAA,sBAAgB,EAACV,MAAMS,OAAO;IAChC;AACF"}
@@ -1,11 +1,6 @@
1
+ import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';
1
2
  import { bytesToHex, bytesToString } from '@metamask/utils';
2
3
  import { base64 } from '@scure/base';
3
- export var AuxiliaryFileEncoding;
4
- (function(AuxiliaryFileEncoding) {
5
- AuxiliaryFileEncoding["Base64"] = 'base64';
6
- AuxiliaryFileEncoding["Hex"] = 'hex';
7
- AuxiliaryFileEncoding["Utf8"] = 'utf8';
8
- })(AuxiliaryFileEncoding || (AuxiliaryFileEncoding = {}));
9
4
  /**
10
5
  * Re-encodes an auxiliary file if needed depending on the requested file encoding.
11
6
  *
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import { bytesToHex, bytesToString } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\nexport enum AuxiliaryFileEncoding {\n Base64 = 'base64',\n Hex = 'hex',\n Utf8 = 'utf8',\n}\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = base64.decode(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n"],"names":["bytesToHex","bytesToString","base64","AuxiliaryFileEncoding","Base64","Hex","Utf8","encodeAuxiliaryFile","value","encoding","decoded","decode"],"mappings":"AAAA,SAASA,UAAU,EAAEC,aAAa,QAAQ,kBAAkB;AAC5D,SAASC,MAAM,QAAQ,cAAc;WAE9B;UAAKC,qBAAqB;IAArBA,sBACVC,YAAS;IADCD,sBAEVE,SAAM;IAFIF,sBAGVG,UAAO;GAHGH,0BAAAA;AAMZ;;;;;;CAMC,GACD,OAAO,SAASI,oBACdC,KAAa,EACbC,QAA+B;IAE/B,oDAAoD;IACpD,IAAIA,aAAaN,sBAAsBC,MAAM,EAAE;QAC7C,OAAOI;IACT;IAEA,qCAAqC;IACrC,MAAME,UAAUR,OAAOS,MAAM,CAACH;IAC9B,IAAIC,aAAaN,sBAAsBG,IAAI,EAAE;QAC3C,OAAOL,cAAcS;IACvB;IAEA,OAAOV,WAAWU;AACpB"}
1
+ {"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';\nimport { bytesToHex, bytesToString } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = base64.decode(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n"],"names":["AuxiliaryFileEncoding","bytesToHex","bytesToString","base64","encodeAuxiliaryFile","value","encoding","Base64","decoded","decode","Utf8"],"mappings":"AAAA,SAASA,qBAAqB,QAAQ,sBAAsB;AAC5D,SAASC,UAAU,EAAEC,aAAa,QAAQ,kBAAkB;AAC5D,SAASC,MAAM,QAAQ,cAAc;AAErC;;;;;;CAMC,GACD,OAAO,SAASC,oBACdC,KAAa,EACbC,QAA+B;IAE/B,oDAAoD;IACpD,IAAIA,aAAaN,sBAAsBO,MAAM,EAAE;QAC7C,OAAOF;IACT;IAEA,qCAAqC;IACrC,MAAMG,UAAUL,OAAOM,MAAM,CAACJ;IAC9B,IAAIC,aAAaN,sBAAsBU,IAAI,EAAE;QAC3C,OAAOR,cAAcM;IACvB;IAEA,OAAOP,WAAWO;AACpB"}
@@ -1,13 +1,31 @@
1
- import { assert, concatBytes } from '@metamask/utils';
1
+ import { assert, concatBytes, stringToBytes } from '@metamask/utils';
2
2
  import { sha256 } from '@noble/hashes/sha256';
3
3
  import { VirtualFile } from './virtual-file/VirtualFile';
4
+ /**
5
+ * Convert an input value to a Uint8Array for use in a checksum.
6
+ *
7
+ * @param bytes - A value to use for a checksum calculation.
8
+ * @returns The input value converted to a Uint8Array if necessary.
9
+ */ export function getChecksumBytes(bytes) {
10
+ // Unwrap VirtualFiles to extract the content
11
+ // The content is then either a string or Uint8Array
12
+ const unwrapped = bytes instanceof VirtualFile ? bytes.value : bytes;
13
+ if (typeof unwrapped === 'string') {
14
+ return stringToBytes(unwrapped);
15
+ }
16
+ return unwrapped;
17
+ }
4
18
  /**
5
19
  * Calculates checksum for a single byte array.
6
20
  *
7
21
  * @param bytes - The byte array to calculate the checksum for.
8
22
  * @returns A single sha-256 checksum.
9
- */ export function checksum(bytes) {
10
- const value = bytes instanceof VirtualFile ? bytes.value : bytes;
23
+ */ export async function checksum(bytes) {
24
+ const value = getChecksumBytes(bytes);
25
+ // Use crypto.subtle.digest whenever possible as it is faster.
26
+ if ('crypto' in globalThis && typeof globalThis.crypto === 'object' && crypto.subtle?.digest) {
27
+ return new Uint8Array(await crypto.subtle.digest('SHA-256', value));
28
+ }
11
29
  return sha256(value);
12
30
  }
13
31
  /**
@@ -21,8 +39,8 @@ import { VirtualFile } from './virtual-file/VirtualFile';
21
39
  *
22
40
  * @param files - The files over which to calculate the checksum.
23
41
  * @returns A single sha-256 checksum.
24
- */ export function checksumFiles(files) {
25
- return checksum(concatBytes([
42
+ */ export async function checksumFiles(files) {
43
+ const checksums = await Promise.all([
26
44
  ...files
27
45
  ].sort((a, b)=>{
28
46
  assert(a.path !== b.path, 'Tried to sort files with non-unique paths.');
@@ -30,7 +48,8 @@ import { VirtualFile } from './virtual-file/VirtualFile';
30
48
  return -1;
31
49
  }
32
50
  return 1;
33
- }).map((file)=>checksum(file))));
51
+ }).map(async (file)=>checksum(file)));
52
+ return checksum(concatBytes(checksums));
34
53
  }
35
54
 
36
55
  //# sourceMappingURL=checksum.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { assert, concatBytes } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport { VirtualFile } from './virtual-file/VirtualFile';\n\n/**\n * Calculates checksum for a single byte array.\n *\n * @param bytes - The byte array to calculate the checksum for.\n * @returns A single sha-256 checksum.\n */\nexport function checksum(bytes: VirtualFile | Uint8Array | string): Uint8Array {\n const value = bytes instanceof VirtualFile ? bytes.value : bytes;\n return sha256(value);\n}\n\n/**\n * Calculates checksum over multiple files in a reproducible way.\n *\n * 1. Sort all the files by their paths.\n * 2. Calculate sha-256 checksum of each file separately.\n * 3. Concatenate all the checksums into one buffer and sha-256 that buffer.\n *\n * The sorting of paths is done using {@link https://tc39.es/ecma262/#sec-islessthan UTF-16 Code Units}.\n *\n * @param files - The files over which to calculate the checksum.\n * @returns A single sha-256 checksum.\n */\nexport function checksumFiles(files: VirtualFile[]) {\n return checksum(\n concatBytes(\n [...files]\n .sort((a, b) => {\n assert(\n a.path !== b.path,\n 'Tried to sort files with non-unique paths.',\n );\n if (a.path < b.path) {\n return -1;\n }\n return 1;\n })\n .map((file) => checksum(file)),\n ),\n );\n}\n"],"names":["assert","concatBytes","sha256","VirtualFile","checksum","bytes","value","checksumFiles","files","sort","a","b","path","map","file"],"mappings":"AAAA,SAASA,MAAM,EAAEC,WAAW,QAAQ,kBAAkB;AACtD,SAASC,MAAM,QAAQ,uBAAuB;AAE9C,SAASC,WAAW,QAAQ,6BAA6B;AAEzD;;;;;CAKC,GACD,OAAO,SAASC,SAASC,KAAwC;IAC/D,MAAMC,QAAQD,iBAAiBF,cAAcE,MAAMC,KAAK,GAAGD;IAC3D,OAAOH,OAAOI;AAChB;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,cAAcC,KAAoB;IAChD,OAAOJ,SACLH,YACE;WAAIO;KAAM,CACPC,IAAI,CAAC,CAACC,GAAGC;QACRX,OACEU,EAAEE,IAAI,KAAKD,EAAEC,IAAI,EACjB;QAEF,IAAIF,EAAEE,IAAI,GAAGD,EAAEC,IAAI,EAAE;YACnB,OAAO,CAAC;QACV;QACA,OAAO;IACT,GACCC,GAAG,CAAC,CAACC,OAASV,SAASU;AAGhC"}
1
+ {"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { assert, concatBytes, stringToBytes } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport { VirtualFile } from './virtual-file/VirtualFile';\n\n/**\n * Convert an input value to a Uint8Array for use in a checksum.\n *\n * @param bytes - A value to use for a checksum calculation.\n * @returns The input value converted to a Uint8Array if necessary.\n */\nexport function getChecksumBytes(\n bytes: VirtualFile | Uint8Array | string,\n): Uint8Array {\n // Unwrap VirtualFiles to extract the content\n // The content is then either a string or Uint8Array\n const unwrapped = bytes instanceof VirtualFile ? bytes.value : bytes;\n\n if (typeof unwrapped === 'string') {\n return stringToBytes(unwrapped);\n }\n\n return unwrapped;\n}\n\n/**\n * Calculates checksum for a single byte array.\n *\n * @param bytes - The byte array to calculate the checksum for.\n * @returns A single sha-256 checksum.\n */\nexport async function checksum(\n bytes: VirtualFile | Uint8Array | string,\n): Promise<Uint8Array> {\n const value = getChecksumBytes(bytes);\n // Use crypto.subtle.digest whenever possible as it is faster.\n if (\n 'crypto' in globalThis &&\n typeof globalThis.crypto === 'object' &&\n crypto.subtle?.digest\n ) {\n return new Uint8Array(await crypto.subtle.digest('SHA-256', value));\n }\n return sha256(value);\n}\n\n/**\n * Calculates checksum over multiple files in a reproducible way.\n *\n * 1. Sort all the files by their paths.\n * 2. Calculate sha-256 checksum of each file separately.\n * 3. Concatenate all the checksums into one buffer and sha-256 that buffer.\n *\n * The sorting of paths is done using {@link https://tc39.es/ecma262/#sec-islessthan UTF-16 Code Units}.\n *\n * @param files - The files over which to calculate the checksum.\n * @returns A single sha-256 checksum.\n */\nexport async function checksumFiles(files: VirtualFile[]) {\n const checksums = await Promise.all(\n [...files]\n .sort((a, b) => {\n assert(a.path !== b.path, 'Tried to sort files with non-unique paths.');\n if (a.path < b.path) {\n return -1;\n }\n return 1;\n })\n .map(async (file) => checksum(file)),\n );\n\n return checksum(concatBytes(checksums));\n}\n"],"names":["assert","concatBytes","stringToBytes","sha256","VirtualFile","getChecksumBytes","bytes","unwrapped","value","checksum","globalThis","crypto","subtle","digest","Uint8Array","checksumFiles","files","checksums","Promise","all","sort","a","b","path","map","file"],"mappings":"AAAA,SAASA,MAAM,EAAEC,WAAW,EAAEC,aAAa,QAAQ,kBAAkB;AACrE,SAASC,MAAM,QAAQ,uBAAuB;AAE9C,SAASC,WAAW,QAAQ,6BAA6B;AAEzD;;;;;CAKC,GACD,OAAO,SAASC,iBACdC,KAAwC;IAExC,6CAA6C;IAC7C,oDAAoD;IACpD,MAAMC,YAAYD,iBAAiBF,cAAcE,MAAME,KAAK,GAAGF;IAE/D,IAAI,OAAOC,cAAc,UAAU;QACjC,OAAOL,cAAcK;IACvB;IAEA,OAAOA;AACT;AAEA;;;;;CAKC,GACD,OAAO,eAAeE,SACpBH,KAAwC;IAExC,MAAME,QAAQH,iBAAiBC;IAC/B,8DAA8D;IAC9D,IACE,YAAYI,cACZ,OAAOA,WAAWC,MAAM,KAAK,YAC7BA,OAAOC,MAAM,EAAEC,QACf;QACA,OAAO,IAAIC,WAAW,MAAMH,OAAOC,MAAM,CAACC,MAAM,CAAC,WAAWL;IAC9D;IACA,OAAOL,OAAOK;AAChB;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeO,cAAcC,KAAoB;IACtD,MAAMC,YAAY,MAAMC,QAAQC,GAAG,CACjC;WAAIH;KAAM,CACPI,IAAI,CAAC,CAACC,GAAGC;QACRtB,OAAOqB,EAAEE,IAAI,KAAKD,EAAEC,IAAI,EAAE;QAC1B,IAAIF,EAAEE,IAAI,GAAGD,EAAEC,IAAI,EAAE;YACnB,OAAO,CAAC;QACV;QACA,OAAO;IACT,GACCC,GAAG,CAAC,OAAOC,OAAShB,SAASgB;IAGlC,OAAOhB,SAASR,YAAYgB;AAC9B"}
@@ -1,6 +1,6 @@
1
1
  import { JsonRpcRequestStruct } from '@metamask/utils';
2
2
  import { parseExpression } from 'cron-parser';
3
- import { array, assign, coerce, create, object, omit, optional, partial, pick, refine, string } from 'superstruct';
3
+ import { assign, omit, partial, pick, array, coerce, create, object, optional, refine, string } from 'superstruct';
4
4
  export const CronjobRpcRequestStruct = assign(partial(pick(JsonRpcRequestStruct, [
5
5
  'id',
6
6
  'jsonrpc'
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n coerce,\n create,\n object,\n omit,\n optional,\n partial,\n pick,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["JsonRpcRequestStruct","parseExpression","array","assign","coerce","create","object","omit","optional","partial","pick","refine","string","CronjobRpcRequestStruct","CronExpressionStruct","minute","hour","dayOfMonth","month","dayOfWeek","value","parseCronExpression","expression","ensureStringExpression","CronjobSpecificationStruct","request","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,kBAAkB;AACvD,SAASC,eAAe,QAAQ,cAAc;AAE9C,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,MAAM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ronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n assign,\n omit,\n partial,\n pick,\n array,\n coerce,\n create,\n object,\n optional,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["JsonRpcRequestStruct","parseExpression","assign","omit","partial","pick","array","coerce","create","object","optional","refine","string","CronjobRpcRequestStruct","CronExpressionStruct","minute","hour","dayOfMonth","month","dayOfWeek","value","parseCronExpression","expression","ensureStringExpression","CronjobSpecificationStruct","request","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,kBAAkB;AACvD,SAASC,eAAe,QAAQ,cAAc;AAE9C,SACEC,MAAM,EACNC,IAAI,EACJC,OAAO,EACPC,IAAI,EACJC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,MAAM,EACNC,QAAQ,EACRC,MAAM,EACNC,MAAM,QACD,cAAc;AAErB,OAAO,MAAMC,0BAA0BX,OACrCE,QAAQC,KAAKL,sBAAsB;IAAC;IAAM;CAAU,IACpDG,KAAKH,sBAAsB;IAAC;IAAM;CAAU,GAC5C;AAGF,OAAO,MAAMc,uBAAuBH,OAClCJ,OACEK,UACAH,OAAO;IACLM,QAAQL,SAASE;IACjBI,MAAMN,SAASE;IACfK,YAAYP,SAASE;IACrBM,OAAOR,SAASE;IAChBO,WAAWT,SAASE;AACtB,IACA,CAACQ,QACC,CAAC,EAAEA,MAAML,MAAM,IAAI,IAAI,CAAC,EAAEK,MAAMJ,IAAI,IAAI,IAAI,CAAC,EAAEI,MAAMH,UAAU,IAAI,IAAI,CAAC,EACtEG,MAAMF,KAAK,IAAI,IAChB,CAAC,EAAEE,MAAMD,SAAS,IAAI,IAAI,CAAC,GAEhC,kBACA,CAACC;IACC,IAAI;QACFnB,gBAAgBmB;QAChB,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF,GACA;AAIF;;;;;CAKC,GACD,OAAO,SAASC,oBAAoBC,UAA2B;IAC7D,MAAMC,yBAAyBf,OAAOc,YAAYR;IAClD,OAAOb,gBAAgBsB;AACzB;AAEA,OAAO,MAAMC,6BAA6Bf,OAAO;IAC/Ca,YAAYR;IACZW,SAASZ;AACX,GAAG;AAGH;;;;;CAKC,GACD,OAAO,SAASa,uBAAuBN,KAAc;IACnD,IAAI;QACFZ,OAAOY,OAAOI;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,OAAO,MAAMG,kCAAkCrB,MAC7CkB,4BACA;AAEF;;;;;CAKC,GACD,OAAO,SAASI,4BAA4BR,KAAc;IACxD,IAAI;QACFZ,OAAOY,OAAOO;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\n\nimport { literal } from './structs';\n\n/**\n * Get the enum values as union type. This allows using both the enum string\n * values and the enum itself as values.\n *\n * Note: This only works for string enums.\n *\n * @example\n * ```typescript\n * enum Foo {\n * Bar = 'bar',\n * Baz = 'baz',\n * }\n *\n * type FooValue = EnumToUnion<Foo>;\n * // FooValue is 'bar' | 'baz'\n *\n * const foo: FooValue = Foo.Bar; // Works\n * const foo: FooValue = 'bar'; // Also works\n * ```\n */\nexport type EnumToUnion<Type extends string> = `${Type}`;\n\n/**\n * Superstruct struct for validating an enum value. This allows using both the\n * enum string values and the enum itself as values.\n *\n * @param constant - The enum to validate against.\n * @returns The superstruct struct.\n */\nexport function enumValue<Type extends string>(\n constant: Type,\n): Struct<EnumToUnion<Type>, null> {\n return literal(constant as EnumToUnion<Type>);\n}\n"],"names":["literal","enumValue","constant"],"mappings":"AAEA,SAASA,OAAO,QAAQ,YAAY;AAwBpC;;;;;;CAMC,GACD,OAAO,SAASC,UACdC,QAAc;IAEd,OAAOF,QAAQE;AACjB"}
1
+ {"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import type { EnumToUnion } from '@metamask/snaps-sdk';\nimport type { Struct } from 'superstruct';\n\nimport { literal } from './structs';\n\n/**\n * Superstruct struct for validating an enum value. This allows using both the\n * enum string values and the enum itself as values.\n *\n * @param constant - The enum to validate against.\n * @returns The superstruct struct.\n */\nexport function enumValue<Type extends string>(\n constant: Type,\n): Struct<EnumToUnion<Type>, null> {\n return literal(constant as EnumToUnion<Type>);\n}\n"],"names":["literal","enumValue","constant"],"mappings":"AAGA,SAASA,OAAO,QAAQ,YAAY;AAEpC;;;;;;CAMC,GACD,OAAO,SAASC,UACdC,QAAc;IAEd,OAAOF,QAAQE;AACjB"}