@metamask/snaps-utils 0.34.0-flask.1 → 0.35.0-flask.1

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 (249) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/dist/cjs/array.js +23 -0
  3. package/dist/cjs/array.js.map +1 -0
  4. package/dist/cjs/caveats.js +33 -0
  5. package/dist/cjs/caveats.js.map +1 -0
  6. package/dist/cjs/checksum.js +38 -0
  7. package/dist/cjs/checksum.js.map +1 -0
  8. package/dist/cjs/cronjob.js +84 -0
  9. package/dist/cjs/cronjob.js.map +1 -0
  10. package/dist/cjs/deep-clone.js +22 -0
  11. package/dist/cjs/deep-clone.js.map +1 -0
  12. package/dist/cjs/default-endowments.js +49 -0
  13. package/dist/cjs/default-endowments.js.map +1 -0
  14. package/dist/cjs/entropy.js +23 -0
  15. package/dist/cjs/entropy.js.map +1 -0
  16. package/dist/cjs/enum.js +16 -0
  17. package/dist/cjs/enum.js.map +1 -0
  18. package/dist/{eval-worker.js → cjs/eval-worker.js} +22 -21
  19. package/dist/cjs/eval-worker.js.map +1 -0
  20. package/dist/cjs/eval.js +29 -0
  21. package/dist/cjs/eval.js.map +1 -0
  22. package/dist/cjs/fs.js +126 -0
  23. package/dist/cjs/fs.js.map +1 -0
  24. package/dist/cjs/handlers.js +6 -0
  25. package/dist/cjs/handlers.js.map +1 -0
  26. package/dist/cjs/icon.js +37 -0
  27. package/dist/cjs/icon.js.map +1 -0
  28. package/dist/{iframe.js → cjs/iframe.js} +14 -9
  29. package/dist/cjs/iframe.js.map +1 -0
  30. package/dist/cjs/index.browser.js +40 -0
  31. package/dist/cjs/index.browser.js.map +1 -0
  32. package/dist/cjs/index.executionenv.js +24 -0
  33. package/dist/cjs/index.executionenv.js.map +1 -0
  34. package/dist/cjs/index.js +45 -0
  35. package/dist/cjs/index.js.map +1 -0
  36. package/dist/cjs/json-rpc.js +46 -0
  37. package/dist/cjs/json-rpc.js.map +1 -0
  38. package/dist/cjs/json.js +16 -0
  39. package/dist/cjs/json.js.map +1 -0
  40. package/dist/cjs/logging.js +40 -0
  41. package/dist/cjs/logging.js.map +1 -0
  42. package/dist/cjs/manifest/index.browser.js +20 -0
  43. package/dist/cjs/manifest/index.browser.js.map +1 -0
  44. package/dist/cjs/manifest/index.js +21 -0
  45. package/dist/cjs/manifest/index.js.map +1 -0
  46. package/dist/cjs/manifest/manifest.js +239 -0
  47. package/dist/cjs/manifest/manifest.js.map +1 -0
  48. package/dist/cjs/manifest/validation.js +183 -0
  49. package/dist/cjs/manifest/validation.js.map +1 -0
  50. package/dist/cjs/mock.js +128 -0
  51. package/dist/cjs/mock.js.map +1 -0
  52. package/dist/cjs/namespace.js +124 -0
  53. package/dist/cjs/namespace.js.map +1 -0
  54. package/dist/cjs/npm.js +81 -0
  55. package/dist/cjs/npm.js.map +1 -0
  56. package/dist/cjs/path.js +21 -0
  57. package/dist/cjs/path.js.map +1 -0
  58. package/dist/cjs/post-process.js +328 -0
  59. package/dist/cjs/post-process.js.map +1 -0
  60. package/dist/cjs/snaps.js +230 -0
  61. package/dist/cjs/snaps.js.map +1 -0
  62. package/dist/cjs/types.js +117 -0
  63. package/dist/cjs/types.js.map +1 -0
  64. package/dist/cjs/validation.js +22 -0
  65. package/dist/cjs/validation.js.map +1 -0
  66. package/dist/cjs/versions.js +47 -0
  67. package/dist/cjs/versions.js.map +1 -0
  68. package/dist/cjs/virtual-file/VirtualFile.js +85 -0
  69. package/dist/cjs/virtual-file/VirtualFile.js.map +1 -0
  70. package/dist/cjs/virtual-file/index.browser.js +20 -0
  71. package/dist/cjs/virtual-file/index.browser.js.map +1 -0
  72. package/dist/cjs/virtual-file/index.js +21 -0
  73. package/dist/cjs/virtual-file/index.js.map +1 -0
  74. package/dist/cjs/virtual-file/toVirtualFile.js +33 -0
  75. package/dist/cjs/virtual-file/toVirtualFile.js.map +1 -0
  76. package/dist/esm/array.js +13 -0
  77. package/dist/esm/array.js.map +1 -0
  78. package/dist/esm/caveats.js +23 -0
  79. package/dist/esm/caveats.js.map +1 -0
  80. package/dist/esm/checksum.js +36 -0
  81. package/dist/esm/checksum.js.map +1 -0
  82. package/dist/esm/cronjob.js +66 -0
  83. package/dist/esm/cronjob.js.map +1 -0
  84. package/dist/esm/deep-clone.js +7 -0
  85. package/dist/esm/deep-clone.js.map +1 -0
  86. package/dist/{default-endowments.js → esm/default-endowments.js} +3 -6
  87. package/dist/esm/default-endowments.js.map +1 -0
  88. package/dist/esm/entropy.js +6 -0
  89. package/dist/esm/entropy.js.map +1 -0
  90. package/dist/esm/enum.js +12 -0
  91. package/dist/esm/enum.js.map +1 -0
  92. package/dist/esm/eval-worker.js +47 -0
  93. package/dist/esm/eval-worker.js.map +1 -0
  94. package/dist/esm/eval.js +25 -0
  95. package/dist/esm/eval.js.map +1 -0
  96. package/dist/{fs.js → esm/fs.js} +33 -55
  97. package/dist/esm/fs.js.map +1 -0
  98. package/dist/esm/handlers.js +3 -0
  99. package/dist/esm/handlers.js.map +1 -0
  100. package/dist/esm/icon.js +11 -0
  101. package/dist/esm/icon.js.map +1 -0
  102. package/dist/esm/iframe.js +49 -0
  103. package/dist/esm/iframe.js.map +1 -0
  104. package/dist/esm/index.browser.js +23 -0
  105. package/dist/esm/index.browser.js.map +1 -0
  106. package/dist/esm/index.executionenv.js +7 -0
  107. package/dist/esm/index.executionenv.js.map +1 -0
  108. package/dist/esm/index.js +28 -0
  109. package/dist/esm/index.js.map +1 -0
  110. package/dist/esm/json-rpc.js +39 -0
  111. package/dist/esm/json-rpc.js.map +1 -0
  112. package/dist/esm/json.js +17 -0
  113. package/dist/esm/json.js.map +1 -0
  114. package/dist/{logging.js → esm/logging.js} +6 -14
  115. package/dist/esm/logging.js.map +1 -0
  116. package/dist/esm/manifest/index.browser.js +3 -0
  117. package/dist/esm/manifest/index.browser.js.map +1 -0
  118. package/dist/esm/manifest/index.js +4 -0
  119. package/dist/esm/manifest/index.js.map +1 -0
  120. package/dist/{manifest → esm/manifest}/manifest.js +91 -107
  121. package/dist/esm/manifest/manifest.js.map +1 -0
  122. package/dist/esm/manifest/validation.js +152 -0
  123. package/dist/esm/manifest/validation.js.map +1 -0
  124. package/dist/{mock.js → esm/mock.js} +40 -42
  125. package/dist/esm/mock.js.map +1 -0
  126. package/dist/esm/namespace.js +110 -0
  127. package/dist/esm/namespace.js.map +1 -0
  128. package/dist/{npm.js → esm/npm.js} +23 -30
  129. package/dist/esm/npm.js.map +1 -0
  130. package/dist/esm/path.js +17 -0
  131. package/dist/esm/path.js.map +1 -0
  132. package/dist/{post-process.js → esm/post-process.js} +110 -99
  133. package/dist/esm/post-process.js.map +1 -0
  134. package/dist/esm/snaps.js +215 -0
  135. package/dist/esm/snaps.js.map +1 -0
  136. package/dist/esm/types.js +85 -0
  137. package/dist/esm/types.js.map +1 -0
  138. package/dist/esm/validation.js +17 -0
  139. package/dist/esm/validation.js.map +1 -0
  140. package/dist/{versions.js → esm/versions.js} +15 -18
  141. package/dist/esm/versions.js.map +1 -0
  142. package/dist/{virtual-file → esm/virtual-file}/VirtualFile.js +47 -33
  143. package/dist/esm/virtual-file/VirtualFile.js.map +1 -0
  144. package/dist/esm/virtual-file/index.browser.js +3 -0
  145. package/dist/esm/virtual-file/index.browser.js.map +1 -0
  146. package/dist/esm/virtual-file/index.js +4 -0
  147. package/dist/esm/virtual-file/index.js.map +1 -0
  148. package/dist/esm/virtual-file/toVirtualFile.js +26 -0
  149. package/dist/esm/virtual-file/toVirtualFile.js.map +1 -0
  150. package/dist/types/array.d.ts +10 -0
  151. package/dist/{caveats.d.ts → types/caveats.d.ts} +0 -4
  152. package/dist/types/enum.d.ts +30 -0
  153. package/dist/{handlers.d.ts → types/handlers.d.ts} +1 -38
  154. package/dist/{index.browser.d.ts → types/index.browser.d.ts} +3 -1
  155. package/dist/{index.d.ts → types/index.d.ts} +3 -1
  156. package/dist/types/index.executionenv.d.ts +4 -0
  157. package/dist/types/json.d.ts +13 -0
  158. package/dist/{manifest → types/manifest}/validation.d.ts +6 -69
  159. package/dist/types/namespace.d.ts +124 -0
  160. package/dist/{types.d.ts → types/types.d.ts} +2 -5
  161. package/package.json +52 -25
  162. package/dist/caveats.js +0 -35
  163. package/dist/caveats.js.map +0 -1
  164. package/dist/checksum.js +0 -42
  165. package/dist/checksum.js.map +0 -1
  166. package/dist/cronjob.js +0 -71
  167. package/dist/cronjob.js.map +0 -1
  168. package/dist/deep-clone.js +0 -9
  169. package/dist/deep-clone.js.map +0 -1
  170. package/dist/default-endowments.js.map +0 -1
  171. package/dist/entropy.js +0 -8
  172. package/dist/entropy.js.map +0 -1
  173. package/dist/eval-worker.js.map +0 -1
  174. package/dist/eval.js +0 -27
  175. package/dist/eval.js.map +0 -1
  176. package/dist/fs.js.map +0 -1
  177. package/dist/handlers.js +0 -3
  178. package/dist/handlers.js.map +0 -1
  179. package/dist/icon.js +0 -17
  180. package/dist/icon.js.map +0 -1
  181. package/dist/iframe.js.map +0 -1
  182. package/dist/iframe.test.browser.js +0 -15
  183. package/dist/iframe.test.browser.js.map +0 -1
  184. package/dist/index.browser.js +0 -36
  185. package/dist/index.browser.js.map +0 -1
  186. package/dist/index.js +0 -41
  187. package/dist/index.js.map +0 -1
  188. package/dist/json-rpc.js +0 -46
  189. package/dist/json-rpc.js.map +0 -1
  190. package/dist/logging.js.map +0 -1
  191. package/dist/manifest/index.browser.js +0 -18
  192. package/dist/manifest/index.browser.js.map +0 -1
  193. package/dist/manifest/index.js +0 -19
  194. package/dist/manifest/index.js.map +0 -1
  195. package/dist/manifest/manifest.js.map +0 -1
  196. package/dist/manifest/validation.js +0 -146
  197. package/dist/manifest/validation.js.map +0 -1
  198. package/dist/mock.js.map +0 -1
  199. package/dist/namespace.d.ts +0 -275
  200. package/dist/namespace.js +0 -225
  201. package/dist/namespace.js.map +0 -1
  202. package/dist/notification.d.ts +0 -66
  203. package/dist/notification.js +0 -58
  204. package/dist/notification.js.map +0 -1
  205. package/dist/npm.js.map +0 -1
  206. package/dist/path.js +0 -21
  207. package/dist/path.js.map +0 -1
  208. package/dist/post-process.js.map +0 -1
  209. package/dist/snaps.js +0 -212
  210. package/dist/snaps.js.map +0 -1
  211. package/dist/types.js +0 -103
  212. package/dist/types.js.map +0 -1
  213. package/dist/validation.js +0 -21
  214. package/dist/validation.js.map +0 -1
  215. package/dist/versions.js.map +0 -1
  216. package/dist/virtual-file/VirtualFile.js.map +0 -1
  217. package/dist/virtual-file/index.browser.js +0 -18
  218. package/dist/virtual-file/index.browser.js.map +0 -1
  219. package/dist/virtual-file/index.js +0 -19
  220. package/dist/virtual-file/index.js.map +0 -1
  221. package/dist/virtual-file/toVirtualFile.js +0 -30
  222. package/dist/virtual-file/toVirtualFile.js.map +0 -1
  223. /package/dist/{checksum.d.ts → types/checksum.d.ts} +0 -0
  224. /package/dist/{cronjob.d.ts → types/cronjob.d.ts} +0 -0
  225. /package/dist/{deep-clone.d.ts → types/deep-clone.d.ts} +0 -0
  226. /package/dist/{default-endowments.d.ts → types/default-endowments.d.ts} +0 -0
  227. /package/dist/{entropy.d.ts → types/entropy.d.ts} +0 -0
  228. /package/dist/{eval-worker.d.ts → types/eval-worker.d.ts} +0 -0
  229. /package/dist/{eval.d.ts → types/eval.d.ts} +0 -0
  230. /package/dist/{fs.d.ts → types/fs.d.ts} +0 -0
  231. /package/dist/{icon.d.ts → types/icon.d.ts} +0 -0
  232. /package/dist/{iframe.d.ts → types/iframe.d.ts} +0 -0
  233. /package/dist/{iframe.test.browser.d.ts → types/iframe.test.browser.d.ts} +0 -0
  234. /package/dist/{json-rpc.d.ts → types/json-rpc.d.ts} +0 -0
  235. /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
  236. /package/dist/{manifest → types/manifest}/index.browser.d.ts +0 -0
  237. /package/dist/{manifest → types/manifest}/index.d.ts +0 -0
  238. /package/dist/{manifest → types/manifest}/manifest.d.ts +0 -0
  239. /package/dist/{mock.d.ts → types/mock.d.ts} +0 -0
  240. /package/dist/{npm.d.ts → types/npm.d.ts} +0 -0
  241. /package/dist/{path.d.ts → types/path.d.ts} +0 -0
  242. /package/dist/{post-process.d.ts → types/post-process.d.ts} +0 -0
  243. /package/dist/{snaps.d.ts → types/snaps.d.ts} +0 -0
  244. /package/dist/{validation.d.ts → types/validation.d.ts} +0 -0
  245. /package/dist/{versions.d.ts → types/versions.d.ts} +0 -0
  246. /package/dist/{virtual-file → types/virtual-file}/VirtualFile.d.ts +0 -0
  247. /package/dist/{virtual-file → types/virtual-file}/index.browser.d.ts +0 -0
  248. /package/dist/{virtual-file → types/virtual-file}/index.d.ts +0 -0
  249. /package/dist/{virtual-file → types/virtual-file}/toVirtualFile.d.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import { Json, assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport {\n NpmSnapFileNames,\n SnapFiles,\n SnapValidationFailureReason,\n UnvalidatedSnapFiles,\n} from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap icon file: ${error.message}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","svgIcon","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","fs","writeFile","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAiEsBA,aAAa;eAAbA;;IA4INC,WAAW;eAAXA;;IA8CMC,iBAAiB;eAAjBA;;IA0CAC,WAAW;eAAXA;;IAiCNC,mBAAmB;eAAnBA;;IA8BAC,uBAAuB;eAAvBA;;;uBApW8C;sEACxC;oBACS;6DACT;2BAEI;qBACG;qBACG;uBAKzB;uBAMA;6BACsC;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAkCO,eAAed,cACpBe,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB;IAEnB,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAeC,aAAS,CAACC,IAAI,CAACR,UAAUS,uBAAgB,CAACC,QAAQ;IACvE,MAAMC,eAAe,MAAMC,IAAAA,iBAAY,EAACN;IACxC,MAAMO,sBAAsBF,aAAaG,MAAM;IAE/C,MAAMC,cAAc,MAAMH,IAAAA,iBAAY,EACpCL,aAAS,CAACC,IAAI,CAACR,UAAUS,uBAAgB,CAACO,WAAW;IAGvD,MAAMC,YAAkC;QACtCC,UAAUP;QACVQ,aAAaJ;QACbb,YAAY,MAAMf,kBAChBa,UACAa,qBACAX;QAEFkB,SAAS,MAAMhC,YAAYY,UAAUa;IACvC;IAEA,IAAIK;IACJ,IAAI;QACD,CAAA,EAAEA,QAAQ,EAAE,GAAGG,IAAAA,oBAAe,EAACJ,UAAS;IAC3C,EAAE,OAAOK,OAAO;QACd,IAAIA,iBAAiBC,uCAAgC,EAAE;YACrDnB,OAAOoB,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E7E,uBAAgB,CAACO,WAAW,CAAC,oBAAoB,EAAEmE,mBAAmB,GAAG,CAAC,EAClLnD,kCAA2B,CAAC6B,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDuB,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACC,IAAAA,sBAAS,EAACJ,uBAAuBG,qBAClC;QACA,MAAM,IAAIhE,uCAAgC,CACxC,CAAC,CAAC,EAAEd,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HgB,kCAA2B,CAAC8B,kBAAkB;IAElD;IAEA2B,IAAAA,yBAAkB,EAChB;QAAEvE;QAAUhB;QAAYkB;IAAQ,GAChC,CAAC,CAAC,EAAEX,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
@@ -0,0 +1,183 @@
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
+ FORBIDDEN_COIN_TYPES: function() {
13
+ return FORBIDDEN_COIN_TYPES;
14
+ },
15
+ Bip32PathStruct: function() {
16
+ return Bip32PathStruct;
17
+ },
18
+ bip32entropy: function() {
19
+ return bip32entropy;
20
+ },
21
+ Bip32EntropyStruct: function() {
22
+ return Bip32EntropyStruct;
23
+ },
24
+ SnapGetBip32EntropyPermissionsStruct: function() {
25
+ return SnapGetBip32EntropyPermissionsStruct;
26
+ },
27
+ SemVerRangeStruct: function() {
28
+ return SemVerRangeStruct;
29
+ },
30
+ SnapIdsStruct: function() {
31
+ return SnapIdsStruct;
32
+ },
33
+ PermissionsStruct: function() {
34
+ return PermissionsStruct;
35
+ },
36
+ SnapManifestStruct: function() {
37
+ return SnapManifestStruct;
38
+ },
39
+ isSnapManifest: function() {
40
+ return isSnapManifest;
41
+ },
42
+ assertIsSnapManifest: function() {
43
+ return assertIsSnapManifest;
44
+ },
45
+ createSnapManifest: function() {
46
+ return createSnapManifest;
47
+ }
48
+ });
49
+ const _keytree = require("@metamask/key-tree");
50
+ const _utils = require("@metamask/utils");
51
+ const _superstruct = require("superstruct");
52
+ const _array = require("../array");
53
+ const _cronjob = require("../cronjob");
54
+ const _entropy = require("../entropy");
55
+ const _jsonrpc = require("../json-rpc");
56
+ const _snaps = require("../snaps");
57
+ const _types = require("../types");
58
+ // BIP-43 purposes that cannot be used for entropy derivation. These are in the
59
+ // string form, ending with `'`.
60
+ const FORBIDDEN_PURPOSES = [
61
+ _entropy.SIP_6_MAGIC_VALUE,
62
+ _entropy.STATE_ENCRYPTION_MAGIC_VALUE
63
+ ];
64
+ const FORBIDDEN_COIN_TYPES = [
65
+ 60
66
+ ];
67
+ const FORBIDDEN_PATHS = FORBIDDEN_COIN_TYPES.map((coinType)=>[
68
+ 'm',
69
+ "44'",
70
+ `${coinType}'`
71
+ ]);
72
+ const Bip32PathStruct = (0, _superstruct.refine)((0, _superstruct.array)((0, _superstruct.string)()), 'BIP-32 path', (path)=>{
73
+ if (path.length === 0) {
74
+ return 'Path must be a non-empty BIP-32 derivation path array';
75
+ }
76
+ if (path[0] !== 'm') {
77
+ return 'Path must start with "m".';
78
+ }
79
+ if (path.length < 3) {
80
+ return 'Paths must have a length of at least three.';
81
+ }
82
+ if (path.slice(1).some((part)=>!(0, _keytree.isValidBIP32PathSegment)(part))) {
83
+ return 'Path must be a valid BIP-32 derivation path array.';
84
+ }
85
+ if (FORBIDDEN_PURPOSES.includes(path[1])) {
86
+ return `The purpose "${path[1]}" is not allowed for entropy derivation.`;
87
+ }
88
+ if (FORBIDDEN_PATHS.some((forbiddenPath)=>(0, _array.isEqual)(path.slice(0, forbiddenPath.length), forbiddenPath))) {
89
+ return `The path "${path.join('/')}" is not allowed for entropy derivation.`;
90
+ }
91
+ return true;
92
+ });
93
+ const bip32entropy = (struct)=>(0, _superstruct.refine)(struct, 'BIP-32 entropy', (value)=>{
94
+ if (value.curve === 'ed25519' && value.path.slice(1).some((part)=>!part.endsWith("'"))) {
95
+ return 'Ed25519 does not support unhardened paths.';
96
+ }
97
+ return true;
98
+ });
99
+ const Bip32EntropyStruct = bip32entropy((0, _superstruct.type)({
100
+ path: Bip32PathStruct,
101
+ curve: (0, _superstruct.enums)([
102
+ 'ed25519',
103
+ 'secp256k1'
104
+ ])
105
+ }));
106
+ const SnapGetBip32EntropyPermissionsStruct = (0, _superstruct.size)((0, _superstruct.array)(Bip32EntropyStruct), 1, Infinity);
107
+ const SemVerRangeStruct = (0, _superstruct.refine)((0, _superstruct.string)(), 'SemVer range', (value)=>{
108
+ if ((0, _utils.isValidSemVerRange)(value)) {
109
+ return true;
110
+ }
111
+ return 'Expected a valid SemVer range.';
112
+ });
113
+ const SnapIdsStruct = (0, _superstruct.refine)((0, _superstruct.record)(_snaps.SnapIdStruct, (0, _superstruct.object)({
114
+ version: (0, _superstruct.optional)(SemVerRangeStruct)
115
+ })), 'SnapIds', (value)=>{
116
+ if (Object.keys(value).length === 0) {
117
+ return false;
118
+ }
119
+ return true;
120
+ });
121
+ const PermissionsStruct = (0, _superstruct.type)({
122
+ 'endowment:long-running': (0, _superstruct.optional)((0, _superstruct.object)({})),
123
+ 'endowment:network-access': (0, _superstruct.optional)((0, _superstruct.object)({})),
124
+ 'endowment:webassembly': (0, _superstruct.optional)((0, _superstruct.object)({})),
125
+ 'endowment:transaction-insight': (0, _superstruct.optional)((0, _superstruct.object)({
126
+ allowTransactionOrigin: (0, _superstruct.optional)((0, _superstruct.boolean)())
127
+ })),
128
+ 'endowment:cronjob': (0, _superstruct.optional)((0, _superstruct.object)({
129
+ jobs: _cronjob.CronjobSpecificationArrayStruct
130
+ })),
131
+ 'endowment:rpc': (0, _superstruct.optional)(_jsonrpc.RpcOriginsStruct),
132
+ snap_dialog: (0, _superstruct.optional)((0, _superstruct.object)({})),
133
+ // TODO: Remove
134
+ snap_confirm: (0, _superstruct.optional)((0, _superstruct.object)({})),
135
+ snap_manageState: (0, _superstruct.optional)((0, _superstruct.object)({})),
136
+ snap_manageAccounts: (0, _superstruct.optional)((0, _superstruct.object)({})),
137
+ snap_notify: (0, _superstruct.optional)((0, _superstruct.object)({})),
138
+ snap_getBip32Entropy: (0, _superstruct.optional)(SnapGetBip32EntropyPermissionsStruct),
139
+ snap_getBip32PublicKey: (0, _superstruct.optional)(SnapGetBip32EntropyPermissionsStruct),
140
+ snap_getBip44Entropy: (0, _superstruct.optional)((0, _superstruct.size)((0, _superstruct.array)((0, _superstruct.object)({
141
+ coinType: (0, _superstruct.size)((0, _superstruct.integer)(), 0, 2 ** 32 - 1)
142
+ })), 1, Infinity)),
143
+ snap_getEntropy: (0, _superstruct.optional)((0, _superstruct.object)({})),
144
+ wallet_snap: (0, _superstruct.optional)(SnapIdsStruct)
145
+ });
146
+ const SnapManifestStruct = (0, _superstruct.object)({
147
+ version: _utils.VersionStruct,
148
+ description: (0, _superstruct.size)((0, _superstruct.string)(), 1, 280),
149
+ proposedName: (0, _superstruct.size)((0, _superstruct.pattern)((0, _superstruct.string)(), /^(?:[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), 1, 214),
150
+ repository: (0, _superstruct.optional)((0, _superstruct.object)({
151
+ type: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity),
152
+ url: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)
153
+ })),
154
+ source: (0, _superstruct.object)({
155
+ shasum: _utils.ChecksumStruct,
156
+ location: (0, _superstruct.object)({
157
+ npm: (0, _superstruct.object)({
158
+ filePath: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity),
159
+ iconPath: (0, _superstruct.optional)((0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)),
160
+ packageName: _types.NameStruct,
161
+ registry: (0, _superstruct.union)([
162
+ (0, _superstruct.literal)('https://registry.npmjs.org'),
163
+ (0, _superstruct.literal)('https://registry.npmjs.org/')
164
+ ])
165
+ })
166
+ })
167
+ }),
168
+ initialPermissions: PermissionsStruct,
169
+ manifestVersion: (0, _superstruct.literal)('0.1'),
170
+ $schema: (0, _superstruct.optional)((0, _superstruct.string)())
171
+ });
172
+ function isSnapManifest(value) {
173
+ return (0, _superstruct.is)(value, SnapManifestStruct);
174
+ }
175
+ function assertIsSnapManifest(value) {
176
+ (0, _utils.assertStruct)(value, SnapManifestStruct, `"${_types.NpmSnapFileNames.Manifest}" is invalid`);
177
+ }
178
+ function createSnapManifest(value) {
179
+ // TODO: Add a utility to prefix these errors similar to assertStruct
180
+ return (0, _superstruct.create)(value, SnapManifestStruct);
181
+ }
182
+
183
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport {\n array,\n boolean,\n create,\n enums,\n Infer,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n Struct,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { RpcOriginsStruct } from '../json-rpc';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <T extends { path: string[]; curve: string }, S>(\n struct: Struct<T, S>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:long-running': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\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 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","PermissionsStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","allowTransactionOrigin","boolean","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","wallet_snap","VersionStruct","description","proposedName","pattern","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA0CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAeAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAeAC,iBAAiB;eAAjBA;;IAmCAC,kBAAkB;eAAlBA;;IA4CGC,cAAc;eAAdA;;IAUAC,oBAAoB;eAApBA;;IAiBAC,kBAAkB;eAAlBA;;;yBArPwB;uBAMjC;6BAoBA;uBAEiB;yBACwB;yBACgB;yBAC/B;uBACJ;uBACgB;AAE7C,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCC,0BAAiB;IACjBC,qCAA4B;CAC7B;AAEM,MAAMd,uBAAiC;IAAC;CAAG;AAClD,MAAMe,kBAA8Bf,qBAAqBgB,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAEM,MAAMhB,kBAAkBiB,IAAAA,mBAAM,EACnCC,IAAAA,kBAAK,EAACC,IAAAA,mBAAM,MACZ,eACA,CAACC;IACC,IAAIA,KAAKC,MAAM,KAAK,GAAG;QACrB,OAAO;IACT;IAEA,IAAID,IAAI,CAAC,EAAE,KAAK,KAAK;QACnB,OAAO;IACT;IAEA,IAAIA,KAAKC,MAAM,GAAG,GAAG;QACnB,OAAO;IACT;IAEA,IAAID,KAAKE,KAAK,CAAC,GAAGC,IAAI,CAAC,CAACC,OAAS,CAACC,IAAAA,gCAAuB,EAACD,QAAQ;QAChE,OAAO;IACT;IAEA,IAAIb,mBAAmBe,QAAQ,CAACN,IAAI,CAAC,EAAE,GAAG;QACxC,OAAO,CAAC,aAAa,EAAE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
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
+ ALL_APIS: function() {
13
+ return ALL_APIS;
14
+ },
15
+ isConstructor: function() {
16
+ return isConstructor;
17
+ },
18
+ generateMockEndowments: function() {
19
+ return generateMockEndowments;
20
+ }
21
+ });
22
+ const _crypto = /*#__PURE__*/ _interop_require_default(require("crypto"));
23
+ const _events = /*#__PURE__*/ _interop_require_default(require("events"));
24
+ const _defaultendowments = require("./default-endowments");
25
+ function _interop_require_default(obj) {
26
+ return obj && obj.__esModule ? obj : {
27
+ default: obj
28
+ };
29
+ }
30
+ const NETWORK_APIS = [
31
+ 'fetch',
32
+ 'Request',
33
+ 'Headers',
34
+ 'Response'
35
+ ];
36
+ const ALL_APIS = [
37
+ ..._defaultendowments.DEFAULT_ENDOWMENTS,
38
+ ...NETWORK_APIS,
39
+ 'WebAssembly'
40
+ ];
41
+ /**
42
+ * Get a mock snap API, that always returns `true` for requests.
43
+ *
44
+ * @returns A mocked snap provider.
45
+ */ function getMockSnapGlobal() {
46
+ // eslint-disable-next-line @typescript-eslint/require-await
47
+ return {
48
+ request: async ()=>true
49
+ };
50
+ }
51
+ /**
52
+ * Get a mock Ethereum provider, that always returns `true` for requests.
53
+ *
54
+ * @returns A mocked ethereum provider.
55
+ */ function getMockEthereumProvider() {
56
+ const mockProvider = new _events.default();
57
+ // eslint-disable-next-line @typescript-eslint/require-await
58
+ mockProvider.request = async ()=>true;
59
+ return mockProvider;
60
+ }
61
+ const isConstructor = (value)=>Boolean(typeof value?.prototype?.constructor?.name === 'string');
62
+ /**
63
+ * A function that always returns `true`.
64
+ *
65
+ * @returns `true`.
66
+ */ const mockFunction = ()=>true;
67
+ class MockClass {
68
+ }
69
+ const handler = {
70
+ // eslint-disable-next-line @typescript-eslint/naming-convention
71
+ construct (Target, args) {
72
+ return new Proxy(new Target(...args), handler);
73
+ },
74
+ get (_target, _prop) {
75
+ return mockFunction;
76
+ }
77
+ };
78
+ /**
79
+ * Generate a mock class for a given value. The value is wrapped in a Proxy, and
80
+ * all methods are replaced with a mock function.
81
+ *
82
+ * @param value - The value to mock.
83
+ * @returns A mock class.
84
+ */ const generateMockClass = (value)=>{
85
+ return new Proxy(value, handler);
86
+ };
87
+ // Things not currently auto-mocked because of NodeJS, by adding them here we
88
+ // have types for them and can use that to generate mocks if needed.
89
+ const mockWindow = {
90
+ crypto: _crypto.default,
91
+ SubtleCrypto: MockClass
92
+ };
93
+ /**
94
+ * Generate a mock endowment for a certain class or function on the `globalThis`
95
+ * object.
96
+ *
97
+ * @param key - The key to generate the mock endowment for.
98
+ * @returns A mocked class or function. If the key is part of the default
99
+ * endowments, the original value is returned.
100
+ */ const generateMockEndowment = (key)=>{
101
+ const globalValue = globalThis[key];
102
+ // Default exposed APIs don't need to be mocked
103
+ if (globalValue && _defaultendowments.DEFAULT_ENDOWMENTS.includes(key)) {
104
+ return globalValue;
105
+ }
106
+ // Fall back to mockWindow for certain APIs not exposed in global in Node.JS
107
+ const globalOrMocked = globalValue ?? mockWindow[key];
108
+ const type = typeof globalOrMocked;
109
+ const isFunction = type === 'function';
110
+ if (isFunction && isConstructor(globalOrMocked)) {
111
+ return generateMockClass(globalOrMocked);
112
+ } else if (isFunction || !globalOrMocked) {
113
+ // Fall back to function mock for now
114
+ return mockFunction;
115
+ }
116
+ return globalOrMocked;
117
+ };
118
+ const generateMockEndowments = ()=>{
119
+ return ALL_APIS.reduce((acc, cur)=>({
120
+ ...acc,
121
+ [cur]: generateMockEndowment(cur)
122
+ }), {
123
+ snap: getMockSnapGlobal(),
124
+ ethereum: getMockEthereumProvider()
125
+ });
126
+ };
127
+
128
+ //# sourceMappingURL=mock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/mock.ts"],"sourcesContent":["import crypto from 'crypto';\nimport EventEmitter from 'events';\n\nimport { DEFAULT_ENDOWMENTS } from './default-endowments';\n\nconst NETWORK_APIS = ['fetch', 'Request', 'Headers', 'Response'];\n\nexport const ALL_APIS: string[] = [\n ...DEFAULT_ENDOWMENTS,\n ...NETWORK_APIS,\n 'WebAssembly',\n];\n\ntype MockSnapGlobal = {\n request: () => Promise<any>;\n};\n\ntype MockEthereumProvider = EventEmitter & {\n request: () => Promise<any>;\n};\n\n/**\n * Get a mock snap API, that always returns `true` for requests.\n *\n * @returns A mocked snap provider.\n */\nfunction getMockSnapGlobal(): MockSnapGlobal {\n // eslint-disable-next-line @typescript-eslint/require-await\n return { request: async () => true };\n}\n\n/**\n * Get a mock Ethereum provider, that always returns `true` for requests.\n *\n * @returns A mocked ethereum provider.\n */\nfunction getMockEthereumProvider(): MockEthereumProvider {\n const mockProvider = new EventEmitter() as Partial<MockEthereumProvider>;\n // eslint-disable-next-line @typescript-eslint/require-await\n mockProvider.request = async () => true;\n return mockProvider as MockEthereumProvider;\n}\n\n/**\n * Check if a value is a constructor.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a constructor, or `false` otherwise.\n */\nexport const isConstructor = (value: any) =>\n Boolean(typeof value?.prototype?.constructor?.name === 'string');\n\n/**\n * A function that always returns `true`.\n *\n * @returns `true`.\n */\nconst mockFunction = () => true;\nclass MockClass {}\n\nconst handler = {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n construct(Target: any, args: any[]): any {\n return new Proxy(new Target(...args), handler);\n },\n get(_target: any, _prop: any) {\n return mockFunction;\n },\n};\n\n/**\n * Generate a mock class for a given value. The value is wrapped in a Proxy, and\n * all methods are replaced with a mock function.\n *\n * @param value - The value to mock.\n * @returns A mock class.\n */\nconst generateMockClass = (value: any) => {\n return new Proxy(value, handler);\n};\n\n// Things not currently auto-mocked because of NodeJS, by adding them here we\n// have types for them and can use that to generate mocks if needed.\nconst mockWindow: Record<string, unknown> = {\n crypto,\n SubtleCrypto: MockClass,\n};\n\n/**\n * Generate a mock endowment for a certain class or function on the `globalThis`\n * object.\n *\n * @param key - The key to generate the mock endowment for.\n * @returns A mocked class or function. If the key is part of the default\n * endowments, the original value is returned.\n */\nconst generateMockEndowment = (key: string) => {\n const globalValue = (globalThis as any)[key];\n\n // Default exposed APIs don't need to be mocked\n if (globalValue && DEFAULT_ENDOWMENTS.includes(key)) {\n return globalValue;\n }\n\n // Fall back to mockWindow for certain APIs not exposed in global in Node.JS\n const globalOrMocked = globalValue ?? mockWindow[key];\n\n const type = typeof globalOrMocked;\n const isFunction = type === 'function';\n if (isFunction && isConstructor(globalOrMocked)) {\n return generateMockClass(globalOrMocked);\n } else if (isFunction || !globalOrMocked) {\n // Fall back to function mock for now\n return mockFunction;\n }\n return globalOrMocked;\n};\n\n/**\n * Generate mock endowments for all the APIs as defined in {@link ALL_APIS}.\n *\n * @returns A map of endowments.\n */\nexport const generateMockEndowments = () => {\n return ALL_APIS.reduce<Record<string, any>>(\n (acc, cur) => ({ ...acc, [cur]: generateMockEndowment(cur) }),\n { snap: getMockSnapGlobal(), ethereum: getMockEthereumProvider() },\n );\n};\n"],"names":["ALL_APIS","isConstructor","generateMockEndowments","NETWORK_APIS","DEFAULT_ENDOWMENTS","getMockSnapGlobal","request","getMockEthereumProvider","mockProvider","EventEmitter","value","Boolean","prototype","constructor","name","mockFunction","MockClass","handler","construct","Target","args","Proxy","get","_target","_prop","generateMockClass","mockWindow","crypto","SubtleCrypto","generateMockEndowment","key","globalValue","globalThis","includes","globalOrMocked","type","isFunction","reduce","acc","cur","snap","ethereum"],"mappings":";;;;;;;;;;;IAOaA,QAAQ;eAARA;;IA0CAC,aAAa;eAAbA;;IA0EAC,sBAAsB;eAAtBA;;;+DA3HM;+DACM;mCAEU;;;;;;AAEnC,MAAMC,eAAe;IAAC;IAAS;IAAW;IAAW;CAAW;AAEzD,MAAMH,WAAqB;OAC7BI,qCAAkB;OAClBD;IACH;CACD;AAUD;;;;CAIC,GACD,SAASE;IACP,4DAA4D;IAC5D,OAAO;QAAEC,SAAS,UAAY;IAAK;AACrC;AAEA;;;;CAIC,GACD,SA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AUlC;IAA0B;AAErE"}
@@ -0,0 +1,124 @@
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
+ CHAIN_ID_REGEX: function() {
13
+ return CHAIN_ID_REGEX;
14
+ },
15
+ ACCOUNT_ID_REGEX: function() {
16
+ return ACCOUNT_ID_REGEX;
17
+ },
18
+ parseChainId: function() {
19
+ return parseChainId;
20
+ },
21
+ parseAccountId: function() {
22
+ return parseAccountId;
23
+ },
24
+ LimitedString: function() {
25
+ return LimitedString;
26
+ },
27
+ ChainIdStruct: function() {
28
+ return ChainIdStruct;
29
+ },
30
+ AccountIdStruct: function() {
31
+ return AccountIdStruct;
32
+ },
33
+ AccountIdArrayStruct: function() {
34
+ return AccountIdArrayStruct;
35
+ },
36
+ ChainStruct: function() {
37
+ return ChainStruct;
38
+ },
39
+ NamespaceStruct: function() {
40
+ return NamespaceStruct;
41
+ },
42
+ NamespaceIdStruct: function() {
43
+ return NamespaceIdStruct;
44
+ },
45
+ isNamespaceId: function() {
46
+ return isNamespaceId;
47
+ },
48
+ isChainId: function() {
49
+ return isChainId;
50
+ },
51
+ isAccountId: function() {
52
+ return isAccountId;
53
+ },
54
+ isAccountIdArray: function() {
55
+ return isAccountIdArray;
56
+ },
57
+ isNamespace: function() {
58
+ return isNamespace;
59
+ }
60
+ });
61
+ const _superstruct = require("superstruct");
62
+ const CHAIN_ID_REGEX = RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u");
63
+ const ACCOUNT_ID_REGEX = RegExp("^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$", "u");
64
+ function parseChainId(chainId) {
65
+ const match = CHAIN_ID_REGEX.exec(chainId);
66
+ if (!match?.groups) {
67
+ throw new Error('Invalid chain ID.');
68
+ }
69
+ return {
70
+ namespace: match.groups.namespace,
71
+ reference: match.groups.reference
72
+ };
73
+ }
74
+ function parseAccountId(accountId) {
75
+ const match = ACCOUNT_ID_REGEX.exec(accountId);
76
+ if (!match?.groups) {
77
+ throw new Error('Invalid account ID.');
78
+ }
79
+ return {
80
+ address: match.groups.accountAddress,
81
+ chainId: match.groups.chainId,
82
+ chain: {
83
+ namespace: match.groups.namespace,
84
+ reference: match.groups.reference
85
+ }
86
+ };
87
+ }
88
+ const LimitedString = (0, _superstruct.size)((0, _superstruct.string)(), 1, 40);
89
+ const ChainIdStruct = (0, _superstruct.pattern)((0, _superstruct.string)(), CHAIN_ID_REGEX);
90
+ const AccountIdStruct = (0, _superstruct.pattern)((0, _superstruct.string)(), ACCOUNT_ID_REGEX);
91
+ const AccountIdArrayStruct = (0, _superstruct.array)(AccountIdStruct);
92
+ const ChainStruct = (0, _superstruct.object)({
93
+ id: ChainIdStruct,
94
+ name: LimitedString
95
+ });
96
+ const NamespaceStruct = (0, _superstruct.object)({
97
+ /**
98
+ * A list of supported chains in the namespace.
99
+ */ chains: (0, _superstruct.array)(ChainStruct),
100
+ /**
101
+ * A list of supported RPC methods on the namespace, that a DApp can call.
102
+ */ methods: (0, _superstruct.optional)((0, _superstruct.array)(LimitedString)),
103
+ /**
104
+ * A list of supported RPC events on the namespace, that a DApp can listen to.
105
+ */ events: (0, _superstruct.optional)((0, _superstruct.array)(LimitedString))
106
+ });
107
+ const NamespaceIdStruct = (0, _superstruct.pattern)((0, _superstruct.string)(), /^[-a-z0-9]{3,8}$/u);
108
+ function isNamespaceId(value) {
109
+ return (0, _superstruct.is)(value, NamespaceIdStruct);
110
+ }
111
+ function isChainId(value) {
112
+ return (0, _superstruct.is)(value, ChainIdStruct);
113
+ }
114
+ function isAccountId(value) {
115
+ return (0, _superstruct.is)(value, AccountIdStruct);
116
+ }
117
+ function isAccountIdArray(value) {
118
+ return (0, _superstruct.is)(value, AccountIdArrayStruct);
119
+ }
120
+ function isNamespace(value) {
121
+ return (0, _superstruct.is)(value, NamespaceStruct);
122
+ }
123
+
124
+ //# sourceMappingURL=namespace.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/namespace.ts"],"sourcesContent":["import {\n array,\n Infer,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from 'superstruct';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);\nexport type ChainId = `${string}:${string}`;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\nexport type AccountId = `${ChainId}:${string}`;\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"],"names":["CHAIN_ID_REGEX","ACCOUNT_ID_REGEX","parseChainId","parseAccountId","LimitedString","ChainIdStruct","AccountIdStruct","AccountIdArrayStruct","ChainStruct","NamespaceStruct","NamespaceIdStruct","isNamespaceId","isChainId","isAccountId","isAccountIdArray","isNamespace","chainId","match","exec","groups","Error","namespace","reference","accountId","address","accountAddress","chain","size","string","pattern","array","object","id","name","chains","methods","optional","events","value","is"],"mappings":";;;;;;;;;;;IAWaA,cAAc;eAAdA;;IAGAC,gBAAgB;eAAhBA;;IAUGC,YAAY;eAAZA;;IAsBAC,cAAc;eAAdA;;IAwBHC,aAAa;eAAbA;;IAKAC,aAAa;eAAbA;;IAGAC,eAAe;eAAfA;;IAGAC,oBAAoB;eAApBA;;IAKAC,WAAW;eAAXA;;IAMAC,eAAe;eAAfA;;IAqBAC,iBAAiB;eAAjBA;;IASGC,aAAa;eAAbA;;IAUAC,SAAS;eAATA;;IAUAC,WAAW;eAAXA;;IAUAC,gBAAgB;eAAhBA;;IAUAC,WAAW;eAAXA;;;6BAzJT;AAEA,MAAMf,iBACX;AAEK,MAAMC,mBACX;AASK,SAASC,aAAac,OAAgB;IAI3C,MAAMC,QAAQjB,eAAekB,IAAI,CAACF;IAClC,IAAI,CAACC,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLC,WAAWJ,MAAME,MAAM,CAACE,SAAS;QACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;IACnC;AACF;AASO,SAASnB,eAAeoB,SAAoB;IAKjD,MAAMN,QAAQhB,iBAAiBiB,IAAI,CAACK;IACpC,IAAI,CAACN,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLI,SAASP,MAAME,MAAM,CAACM,cA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
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
+ EXPECTED_SNAP_FILES: function() {
13
+ return EXPECTED_SNAP_FILES;
14
+ },
15
+ SnapFileNameFromKey: function() {
16
+ return SnapFileNameFromKey;
17
+ },
18
+ validateNpmSnap: function() {
19
+ return validateNpmSnap;
20
+ }
21
+ });
22
+ const _icon = require("./icon");
23
+ const _manifest = require("./manifest/manifest");
24
+ const _validation = require("./manifest/validation");
25
+ const _types = require("./types");
26
+ const EXPECTED_SNAP_FILES = [
27
+ 'manifest',
28
+ 'packageJson',
29
+ 'sourceCode'
30
+ ];
31
+ const SnapFileNameFromKey = {
32
+ manifest: _types.NpmSnapFileNames.Manifest,
33
+ packageJson: _types.NpmSnapFileNames.PackageJson,
34
+ sourceCode: 'source code bundle'
35
+ };
36
+ function validateNpmSnap(snapFiles, errorPrefix) {
37
+ EXPECTED_SNAP_FILES.forEach((key)=>{
38
+ if (!snapFiles[key]) {
39
+ throw new Error(`${errorPrefix ?? ''}Missing file "${SnapFileNameFromKey[key]}".`);
40
+ }
41
+ });
42
+ // Typecast: We are assured that the required files exist if we get here.
43
+ const { manifest, packageJson, sourceCode, svgIcon } = snapFiles;
44
+ try {
45
+ (0, _validation.assertIsSnapManifest)(manifest.result);
46
+ } catch (error) {
47
+ throw new Error(`${errorPrefix ?? ''}${error.message}`);
48
+ }
49
+ const validatedManifest = manifest;
50
+ const { iconPath } = validatedManifest.result.source.location.npm;
51
+ if (iconPath && !svgIcon) {
52
+ throw new Error(`Missing file "${iconPath}".`);
53
+ }
54
+ try {
55
+ (0, _types.assertIsNpmSnapPackageJson)(packageJson.result);
56
+ } catch (error) {
57
+ throw new Error(`${errorPrefix ?? ''}${error.message}`);
58
+ }
59
+ const validatedPackageJson = packageJson;
60
+ (0, _manifest.validateNpmSnapManifest)({
61
+ manifest: validatedManifest,
62
+ packageJson: validatedPackageJson,
63
+ sourceCode,
64
+ svgIcon
65
+ });
66
+ if (svgIcon) {
67
+ try {
68
+ (0, _icon.assertIsSnapIcon)(svgIcon);
69
+ } catch (error) {
70
+ throw new Error(`${errorPrefix ?? ''}${error.message}`);
71
+ }
72
+ }
73
+ return {
74
+ manifest: validatedManifest,
75
+ packageJson: validatedPackageJson,
76
+ sourceCode,
77
+ svgIcon
78
+ };
79
+ }
80
+
81
+ //# sourceMappingURL=npm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport {\n assertIsNpmSnapPackageJson,\n NpmSnapFileNames,\n SnapFiles,\n UnvalidatedSnapFiles,\n} 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 } = 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 });\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 };\n}\n"],"names":["EXPECTED_SNAP_FILES","SnapFileNameFromKey","validateNpmSnap","manifest","NpmSnapFileNames","Manifest","packageJson","PackageJson","sourceCode","snapFiles","errorPrefix","forEach","key","Error","svgIcon","assertIsSnapManifest","result","error","message","validatedManifest","iconPath","source","location","npm","assertIsNpmSnapPackageJson","validatedPackageJson","validateNpmSnapManifest","assertIsSnapIcon"],"mappings":";;;;;;;;;;;IAUaA,mBAAmB;eAAnBA;;IAMAC,mBAAmB;eAAnBA;;IAkBGC,eAAe;eAAfA;;;sBAlCiB;0BACO;4BACH;uBAM9B;AAEA,MAAMF,sBAAsB;IACjC;IACA;IACA;CACD;AAEM,MAAMC,sBAAsB;IACjCE,UAAUC,uBAAgB,CAACC,QAAQ;IACnCC,aAAaF,uBAAgB,CAACG,WAAW;IACzCC,YAAY;AACd;AAcO,SAASN,gBACdO,SAA+B,EAC/BC,WAA2B;IAE3BV,oBAAoBW,OAAO,CAAC,CAACC;QAC3B,IAAI,CAACH,SAAS,CAACG,IAAI,EAAE;YACnB,MAAM,IAAIC,MACR,CAAC,EAAEH,eAAe,GAAG,cAAc,EAAET,mBAAmB,CAACW,IAAI,CAAC,EAAE,CAAC;QAErE;IACF;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