@metamask/snaps-utils 0.35.1-flask.1 → 1.0.0-prerelease.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 (252) hide show
  1. package/CHANGELOG.md +5 -46
  2. package/dist/{esm/array.js → array.js} +7 -3
  3. package/dist/array.js.map +1 -0
  4. package/dist/{types/caveats.d.ts → caveats.d.ts} +4 -0
  5. package/dist/caveats.js +35 -0
  6. package/dist/caveats.js.map +1 -0
  7. package/dist/checksum.js +42 -0
  8. package/dist/checksum.js.map +1 -0
  9. package/dist/cronjob.js +71 -0
  10. package/dist/cronjob.js.map +1 -0
  11. package/dist/deep-clone.js +9 -0
  12. package/dist/deep-clone.js.map +1 -0
  13. package/dist/{esm/default-endowments.js → default-endowments.js} +6 -3
  14. package/dist/default-endowments.js.map +1 -0
  15. package/dist/entropy.js +8 -0
  16. package/dist/entropy.js.map +1 -0
  17. package/dist/{cjs/eval-worker.js → eval-worker.js} +21 -22
  18. package/dist/eval-worker.js.map +1 -0
  19. package/dist/eval.js +27 -0
  20. package/dist/eval.js.map +1 -0
  21. package/dist/{esm/fs.js → fs.js} +56 -33
  22. package/dist/fs.js.map +1 -0
  23. package/dist/{types/handlers.d.ts → handlers.d.ts} +42 -5
  24. package/dist/handlers.js +3 -0
  25. package/dist/handlers.js.map +1 -0
  26. package/dist/{types/iframe.d.ts → iframe.d.ts} +2 -3
  27. package/dist/{esm/iframe.js → iframe.js} +18 -16
  28. package/dist/iframe.js.map +1 -0
  29. package/dist/iframe.test.browser.js +15 -0
  30. package/dist/iframe.test.browser.js.map +1 -0
  31. package/dist/{types/index.browser.d.ts → index.browser.d.ts} +1 -2
  32. package/dist/index.browser.js +37 -0
  33. package/dist/index.browser.js.map +1 -0
  34. package/dist/{types/index.d.ts → index.d.ts} +1 -2
  35. package/dist/index.executionenv.js +22 -0
  36. package/dist/index.executionenv.js.map +1 -0
  37. package/dist/index.js +42 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/json-rpc.js +46 -0
  40. package/dist/json-rpc.js.map +1 -0
  41. package/dist/json.d.ts +9 -0
  42. package/dist/json.js +18 -0
  43. package/dist/json.js.map +1 -0
  44. package/dist/{esm/logging.js → logging.js} +14 -6
  45. package/dist/logging.js.map +1 -0
  46. package/dist/manifest/index.browser.js +18 -0
  47. package/dist/manifest/index.browser.js.map +1 -0
  48. package/dist/manifest/index.js +19 -0
  49. package/dist/manifest/index.js.map +1 -0
  50. package/dist/{esm/manifest → manifest}/manifest.js +113 -98
  51. package/dist/manifest/manifest.js.map +1 -0
  52. package/dist/{types/manifest → manifest}/validation.d.ts +73 -31
  53. package/dist/manifest/validation.js +141 -0
  54. package/dist/manifest/validation.js.map +1 -0
  55. package/dist/{esm/mock.js → mock.js} +40 -42
  56. package/dist/mock.js.map +1 -0
  57. package/dist/namespace.d.ts +275 -0
  58. package/dist/namespace.js +225 -0
  59. package/dist/namespace.js.map +1 -0
  60. package/dist/notification.d.ts +66 -0
  61. package/dist/notification.js +58 -0
  62. package/dist/notification.js.map +1 -0
  63. package/dist/{types/npm.d.ts → npm.d.ts} +2 -0
  64. package/dist/npm.js +74 -0
  65. package/dist/npm.js.map +1 -0
  66. package/dist/path.js +21 -0
  67. package/dist/path.js.map +1 -0
  68. package/dist/{esm/post-process.js → post-process.js} +99 -110
  69. package/dist/post-process.js.map +1 -0
  70. package/dist/{types/snaps.d.ts → snaps.d.ts} +2 -9
  71. package/dist/snaps.js +202 -0
  72. package/dist/snaps.js.map +1 -0
  73. package/dist/{types/types.d.ts → types.d.ts} +5 -2
  74. package/dist/types.js +103 -0
  75. package/dist/types.js.map +1 -0
  76. package/dist/{esm/versions.js → versions.js} +18 -15
  77. package/dist/versions.js.map +1 -0
  78. package/dist/{esm/virtual-file → virtual-file}/VirtualFile.js +33 -47
  79. package/dist/virtual-file/VirtualFile.js.map +1 -0
  80. package/dist/virtual-file/index.browser.js +18 -0
  81. package/dist/virtual-file/index.browser.js.map +1 -0
  82. package/dist/virtual-file/index.js +19 -0
  83. package/dist/virtual-file/index.js.map +1 -0
  84. package/dist/virtual-file/toVirtualFile.js +30 -0
  85. package/dist/virtual-file/toVirtualFile.js.map +1 -0
  86. package/package.json +32 -61
  87. package/dist/cjs/array.js +0 -23
  88. package/dist/cjs/array.js.map +0 -1
  89. package/dist/cjs/caveats.js +0 -33
  90. package/dist/cjs/caveats.js.map +0 -1
  91. package/dist/cjs/checksum.js +0 -38
  92. package/dist/cjs/checksum.js.map +0 -1
  93. package/dist/cjs/cronjob.js +0 -84
  94. package/dist/cjs/cronjob.js.map +0 -1
  95. package/dist/cjs/deep-clone.js +0 -22
  96. package/dist/cjs/deep-clone.js.map +0 -1
  97. package/dist/cjs/default-endowments.js +0 -49
  98. package/dist/cjs/default-endowments.js.map +0 -1
  99. package/dist/cjs/entropy.js +0 -23
  100. package/dist/cjs/entropy.js.map +0 -1
  101. package/dist/cjs/enum.js +0 -16
  102. package/dist/cjs/enum.js.map +0 -1
  103. package/dist/cjs/eval-worker.js.map +0 -1
  104. package/dist/cjs/eval.js +0 -29
  105. package/dist/cjs/eval.js.map +0 -1
  106. package/dist/cjs/fs.js +0 -126
  107. package/dist/cjs/fs.js.map +0 -1
  108. package/dist/cjs/handlers.js +0 -6
  109. package/dist/cjs/handlers.js.map +0 -1
  110. package/dist/cjs/icon.js +0 -37
  111. package/dist/cjs/icon.js.map +0 -1
  112. package/dist/cjs/iframe.js +0 -59
  113. package/dist/cjs/iframe.js.map +0 -1
  114. package/dist/cjs/index.browser.js +0 -40
  115. package/dist/cjs/index.browser.js.map +0 -1
  116. package/dist/cjs/index.executionenv.js +0 -24
  117. package/dist/cjs/index.executionenv.js.map +0 -1
  118. package/dist/cjs/index.js +0 -45
  119. package/dist/cjs/index.js.map +0 -1
  120. package/dist/cjs/json-rpc.js +0 -46
  121. package/dist/cjs/json-rpc.js.map +0 -1
  122. package/dist/cjs/json.js +0 -16
  123. package/dist/cjs/json.js.map +0 -1
  124. package/dist/cjs/logging.js +0 -40
  125. package/dist/cjs/logging.js.map +0 -1
  126. package/dist/cjs/manifest/index.browser.js +0 -20
  127. package/dist/cjs/manifest/index.browser.js.map +0 -1
  128. package/dist/cjs/manifest/index.js +0 -21
  129. package/dist/cjs/manifest/index.js.map +0 -1
  130. package/dist/cjs/manifest/manifest.js +0 -239
  131. package/dist/cjs/manifest/manifest.js.map +0 -1
  132. package/dist/cjs/manifest/validation.js +0 -183
  133. package/dist/cjs/manifest/validation.js.map +0 -1
  134. package/dist/cjs/mock.js +0 -128
  135. package/dist/cjs/mock.js.map +0 -1
  136. package/dist/cjs/namespace.js +0 -124
  137. package/dist/cjs/namespace.js.map +0 -1
  138. package/dist/cjs/npm.js +0 -81
  139. package/dist/cjs/npm.js.map +0 -1
  140. package/dist/cjs/path.js +0 -21
  141. package/dist/cjs/path.js.map +0 -1
  142. package/dist/cjs/post-process.js +0 -328
  143. package/dist/cjs/post-process.js.map +0 -1
  144. package/dist/cjs/snaps.js +0 -230
  145. package/dist/cjs/snaps.js.map +0 -1
  146. package/dist/cjs/types.js +0 -117
  147. package/dist/cjs/types.js.map +0 -1
  148. package/dist/cjs/validation.js +0 -22
  149. package/dist/cjs/validation.js.map +0 -1
  150. package/dist/cjs/versions.js +0 -47
  151. package/dist/cjs/versions.js.map +0 -1
  152. package/dist/cjs/virtual-file/VirtualFile.js +0 -85
  153. package/dist/cjs/virtual-file/VirtualFile.js.map +0 -1
  154. package/dist/cjs/virtual-file/index.browser.js +0 -20
  155. package/dist/cjs/virtual-file/index.browser.js.map +0 -1
  156. package/dist/cjs/virtual-file/index.js +0 -21
  157. package/dist/cjs/virtual-file/index.js.map +0 -1
  158. package/dist/cjs/virtual-file/toVirtualFile.js +0 -33
  159. package/dist/cjs/virtual-file/toVirtualFile.js.map +0 -1
  160. package/dist/esm/array.js.map +0 -1
  161. package/dist/esm/caveats.js +0 -23
  162. package/dist/esm/caveats.js.map +0 -1
  163. package/dist/esm/checksum.js +0 -36
  164. package/dist/esm/checksum.js.map +0 -1
  165. package/dist/esm/cronjob.js +0 -66
  166. package/dist/esm/cronjob.js.map +0 -1
  167. package/dist/esm/deep-clone.js +0 -7
  168. package/dist/esm/deep-clone.js.map +0 -1
  169. package/dist/esm/default-endowments.js.map +0 -1
  170. package/dist/esm/entropy.js +0 -6
  171. package/dist/esm/entropy.js.map +0 -1
  172. package/dist/esm/enum.js +0 -12
  173. package/dist/esm/enum.js.map +0 -1
  174. package/dist/esm/eval-worker.js +0 -47
  175. package/dist/esm/eval-worker.js.map +0 -1
  176. package/dist/esm/eval.js +0 -25
  177. package/dist/esm/eval.js.map +0 -1
  178. package/dist/esm/fs.js.map +0 -1
  179. package/dist/esm/handlers.js +0 -3
  180. package/dist/esm/handlers.js.map +0 -1
  181. package/dist/esm/icon.js +0 -11
  182. package/dist/esm/icon.js.map +0 -1
  183. package/dist/esm/iframe.js.map +0 -1
  184. package/dist/esm/index.browser.js +0 -23
  185. package/dist/esm/index.browser.js.map +0 -1
  186. package/dist/esm/index.executionenv.js +0 -7
  187. package/dist/esm/index.executionenv.js.map +0 -1
  188. package/dist/esm/index.js +0 -28
  189. package/dist/esm/index.js.map +0 -1
  190. package/dist/esm/json-rpc.js +0 -39
  191. package/dist/esm/json-rpc.js.map +0 -1
  192. package/dist/esm/json.js +0 -17
  193. package/dist/esm/json.js.map +0 -1
  194. package/dist/esm/logging.js.map +0 -1
  195. package/dist/esm/manifest/index.browser.js +0 -3
  196. package/dist/esm/manifest/index.browser.js.map +0 -1
  197. package/dist/esm/manifest/index.js +0 -4
  198. package/dist/esm/manifest/index.js.map +0 -1
  199. package/dist/esm/manifest/manifest.js.map +0 -1
  200. package/dist/esm/manifest/validation.js +0 -152
  201. package/dist/esm/manifest/validation.js.map +0 -1
  202. package/dist/esm/mock.js.map +0 -1
  203. package/dist/esm/namespace.js +0 -110
  204. package/dist/esm/namespace.js.map +0 -1
  205. package/dist/esm/npm.js +0 -70
  206. package/dist/esm/npm.js.map +0 -1
  207. package/dist/esm/path.js +0 -17
  208. package/dist/esm/path.js.map +0 -1
  209. package/dist/esm/post-process.js.map +0 -1
  210. package/dist/esm/snaps.js +0 -215
  211. package/dist/esm/snaps.js.map +0 -1
  212. package/dist/esm/types.js +0 -85
  213. package/dist/esm/types.js.map +0 -1
  214. package/dist/esm/validation.js +0 -17
  215. package/dist/esm/validation.js.map +0 -1
  216. package/dist/esm/versions.js.map +0 -1
  217. package/dist/esm/virtual-file/VirtualFile.js.map +0 -1
  218. package/dist/esm/virtual-file/index.browser.js +0 -3
  219. package/dist/esm/virtual-file/index.browser.js.map +0 -1
  220. package/dist/esm/virtual-file/index.js +0 -4
  221. package/dist/esm/virtual-file/index.js.map +0 -1
  222. package/dist/esm/virtual-file/toVirtualFile.js +0 -26
  223. package/dist/esm/virtual-file/toVirtualFile.js.map +0 -1
  224. package/dist/types/enum.d.ts +0 -30
  225. package/dist/types/icon.d.ts +0 -4
  226. package/dist/types/json.d.ts +0 -13
  227. package/dist/types/namespace.d.ts +0 -124
  228. package/dist/types/validation.d.ts +0 -8
  229. /package/dist/{types/array.d.ts → array.d.ts} +0 -0
  230. /package/dist/{types/checksum.d.ts → checksum.d.ts} +0 -0
  231. /package/dist/{types/cronjob.d.ts → cronjob.d.ts} +0 -0
  232. /package/dist/{types/deep-clone.d.ts → deep-clone.d.ts} +0 -0
  233. /package/dist/{types/default-endowments.d.ts → default-endowments.d.ts} +0 -0
  234. /package/dist/{types/entropy.d.ts → entropy.d.ts} +0 -0
  235. /package/dist/{types/eval-worker.d.ts → eval-worker.d.ts} +0 -0
  236. /package/dist/{types/eval.d.ts → eval.d.ts} +0 -0
  237. /package/dist/{types/fs.d.ts → fs.d.ts} +0 -0
  238. /package/dist/{types/iframe.test.browser.d.ts → iframe.test.browser.d.ts} +0 -0
  239. /package/dist/{types/index.executionenv.d.ts → index.executionenv.d.ts} +0 -0
  240. /package/dist/{types/json-rpc.d.ts → json-rpc.d.ts} +0 -0
  241. /package/dist/{types/logging.d.ts → logging.d.ts} +0 -0
  242. /package/dist/{types/manifest → manifest}/index.browser.d.ts +0 -0
  243. /package/dist/{types/manifest → manifest}/index.d.ts +0 -0
  244. /package/dist/{types/manifest → manifest}/manifest.d.ts +0 -0
  245. /package/dist/{types/mock.d.ts → mock.d.ts} +0 -0
  246. /package/dist/{types/path.d.ts → path.d.ts} +0 -0
  247. /package/dist/{types/post-process.d.ts → post-process.d.ts} +0 -0
  248. /package/dist/{types/versions.d.ts → versions.d.ts} +0 -0
  249. /package/dist/{types/virtual-file → virtual-file}/VirtualFile.d.ts +0 -0
  250. /package/dist/{types/virtual-file → virtual-file}/index.browser.d.ts +0 -0
  251. /package/dist/{types/virtual-file → virtual-file}/index.d.ts +0 -0
  252. /package/dist/{types/virtual-file → virtual-file}/toVirtualFile.d.ts +0 -0
@@ -1 +0,0 @@
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":["assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","writeFile","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository"],"mappings":"AAAA,SAAeA,gBAAgB,EAAEC,MAAM,EAAEC,aAAa,QAAQ,kBAAkB;AAChF,OAAOC,eAAe,kBAAkB;AACxC,SAASC,YAAYC,EAAE,QAAQ,KAAK;AACpC,OAAOC,eAAe,OAAO;AAE7B,SAASC,SAAS,QAAQ,gBAAgB;AAC1C,SAASC,YAAY,QAAQ,QAAQ;AACrC,SAASC,eAAe,QAAQ,SAAS;AACzC,SACEC,eAAe,EACfC,gCAAgC,EAChCC,kBAAkB,QACb,WAAW;AAClB,SACEC,gBAAgB,EAEhBC,2BAA2B,QAEtB,WAAW;AAClB,SAASC,eAAe,EAAEC,WAAW,QAAQ,kBAAkB;AAG/D,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAuBA;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,cACpBC,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB;IAEnB,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAe3B,UAAU4B,IAAI,CAACP,UAAUd,iBAAiBsB,QAAQ;IACvE,MAAMC,eAAe,MAAM5B,aAAayB;IACxC,MAAMI,sBAAsBD,aAAaE,MAAM;IAE/C,MAAMC,cAAc,MAAM/B,aACxBF,UAAU4B,IAAI,CAACP,UAAUd,iBAAiB2B,WAAW;IAGvD,MAAMC,YAAkC;QACtCC,UAAUN;QACVO,aAAaJ;QACbV,YAAY,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C;IAEA,IAAIqB,uBAAuBG,wBAAwB;QACjD,MAAM,IAAI7F,iCACR,CAAC,CAAC,EAAEE,iBAAiBsB,QAAQ,CAAC,wBAAwB,EAAEqE,uBAAuB,uBAAuB,EAAE3F,iBAAiB2B,WAAW,CAAC,oBAAoB,EAAE6D,mBAAmB,GAAG,CAAC,EAClLvF,4BAA4BuE,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDiB,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACtG,UAAUmG,uBAAuBG,qBAClC;QACA,MAAM,IAAI9F,iCACR,CAAC,CAAC,EAAEE,iBAAiBsB,QAAQ,CAAC,yCAAyC,EAAEtB,iBAAiB2B,WAAW,CAAC,qBAAqB,CAAC,EAC5H1B,4BAA4BwE,kBAAkB;IAElD;IAEA1E,mBACE;QAAE8B;QAAUb;QAAYgB;IAAQ,GAChC,CAAC,CAAC,EAAEhC,iBAAiBsB,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
@@ -1,152 +0,0 @@
1
- import { isValidBIP32PathSegment } from '@metamask/key-tree';
2
- import { assertStruct, ChecksumStruct, VersionStruct, isValidSemVerRange } from '@metamask/utils';
3
- import { array, boolean, create, enums, integer, is, literal, object, optional, pattern, refine, record, size, string, type, union } from 'superstruct';
4
- import { isEqual } from '../array';
5
- import { CronjobSpecificationArrayStruct } from '../cronjob';
6
- import { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';
7
- import { RpcOriginsStruct } from '../json-rpc';
8
- import { SnapIdStruct } from '../snaps';
9
- import { NameStruct, NpmSnapFileNames } from '../types';
10
- // BIP-43 purposes that cannot be used for entropy derivation. These are in the
11
- // string form, ending with `'`.
12
- const FORBIDDEN_PURPOSES = [
13
- SIP_6_MAGIC_VALUE,
14
- STATE_ENCRYPTION_MAGIC_VALUE
15
- ];
16
- export const FORBIDDEN_COIN_TYPES = [
17
- 60
18
- ];
19
- const FORBIDDEN_PATHS = FORBIDDEN_COIN_TYPES.map((coinType)=>[
20
- 'm',
21
- "44'",
22
- `${coinType}'`
23
- ]);
24
- export const Bip32PathStruct = refine(array(string()), 'BIP-32 path', (path)=>{
25
- if (path.length === 0) {
26
- return 'Path must be a non-empty BIP-32 derivation path array';
27
- }
28
- if (path[0] !== 'm') {
29
- return 'Path must start with "m".';
30
- }
31
- if (path.length < 3) {
32
- return 'Paths must have a length of at least three.';
33
- }
34
- if (path.slice(1).some((part)=>!isValidBIP32PathSegment(part))) {
35
- return 'Path must be a valid BIP-32 derivation path array.';
36
- }
37
- if (FORBIDDEN_PURPOSES.includes(path[1])) {
38
- return `The purpose "${path[1]}" is not allowed for entropy derivation.`;
39
- }
40
- if (FORBIDDEN_PATHS.some((forbiddenPath)=>isEqual(path.slice(0, forbiddenPath.length), forbiddenPath))) {
41
- return `The path "${path.join('/')}" is not allowed for entropy derivation.`;
42
- }
43
- return true;
44
- });
45
- export const bip32entropy = (struct)=>refine(struct, 'BIP-32 entropy', (value)=>{
46
- if (value.curve === 'ed25519' && value.path.slice(1).some((part)=>!part.endsWith("'"))) {
47
- return 'Ed25519 does not support unhardened paths.';
48
- }
49
- return true;
50
- });
51
- // Used outside @metamask/snap-utils
52
- export const Bip32EntropyStruct = bip32entropy(type({
53
- path: Bip32PathStruct,
54
- curve: enums([
55
- 'ed25519',
56
- 'secp256k1'
57
- ])
58
- }));
59
- export const SnapGetBip32EntropyPermissionsStruct = size(array(Bip32EntropyStruct), 1, Infinity);
60
- export const SemVerRangeStruct = refine(string(), 'SemVer range', (value)=>{
61
- if (isValidSemVerRange(value)) {
62
- return true;
63
- }
64
- return 'Expected a valid SemVer range.';
65
- });
66
- export const SnapIdsStruct = refine(record(SnapIdStruct, object({
67
- version: optional(SemVerRangeStruct)
68
- })), 'SnapIds', (value)=>{
69
- if (Object.keys(value).length === 0) {
70
- return false;
71
- }
72
- return true;
73
- });
74
- /* eslint-disable @typescript-eslint/naming-convention */ export const PermissionsStruct = type({
75
- 'endowment:long-running': optional(object({})),
76
- 'endowment:network-access': optional(object({})),
77
- 'endowment:webassembly': optional(object({})),
78
- 'endowment:transaction-insight': optional(object({
79
- allowTransactionOrigin: optional(boolean())
80
- })),
81
- 'endowment:cronjob': optional(object({
82
- jobs: CronjobSpecificationArrayStruct
83
- })),
84
- 'endowment:rpc': optional(RpcOriginsStruct),
85
- snap_dialog: optional(object({})),
86
- // TODO: Remove
87
- snap_confirm: optional(object({})),
88
- snap_manageState: optional(object({})),
89
- snap_manageAccounts: optional(object({})),
90
- snap_notify: optional(object({})),
91
- snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),
92
- snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),
93
- snap_getBip44Entropy: optional(size(array(object({
94
- coinType: size(integer(), 0, 2 ** 32 - 1)
95
- })), 1, Infinity)),
96
- snap_getEntropy: optional(object({})),
97
- wallet_snap: optional(SnapIdsStruct)
98
- });
99
- export const SnapManifestStruct = object({
100
- version: VersionStruct,
101
- description: size(string(), 1, 280),
102
- proposedName: size(pattern(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),
103
- repository: optional(object({
104
- type: size(string(), 1, Infinity),
105
- url: size(string(), 1, Infinity)
106
- })),
107
- source: object({
108
- shasum: ChecksumStruct,
109
- location: object({
110
- npm: object({
111
- filePath: size(string(), 1, Infinity),
112
- iconPath: optional(size(string(), 1, Infinity)),
113
- packageName: NameStruct,
114
- registry: union([
115
- literal('https://registry.npmjs.org'),
116
- literal('https://registry.npmjs.org/')
117
- ])
118
- })
119
- })
120
- }),
121
- initialPermissions: PermissionsStruct,
122
- manifestVersion: literal('0.1'),
123
- $schema: optional(string())
124
- });
125
- /**
126
- * Check if the given value is a valid {@link SnapManifest} object.
127
- *
128
- * @param value - The value to check.
129
- * @returns Whether the value is a valid {@link SnapManifest} object.
130
- */ export function isSnapManifest(value) {
131
- return is(value, SnapManifestStruct);
132
- }
133
- /**
134
- * Assert that the given value is a valid {@link SnapManifest} object.
135
- *
136
- * @param value - The value to check.
137
- * @throws If the value is not a valid {@link SnapManifest} object.
138
- */ export function assertIsSnapManifest(value) {
139
- assertStruct(value, SnapManifestStruct, `"${NpmSnapFileNames.Manifest}" is invalid`);
140
- }
141
- /**
142
- * Creates a {@link SnapManifest} object from JSON.
143
- *
144
- * @param value - The value to check.
145
- * @throws If the value cannot be coerced to a {@link SnapManifest} object.
146
- * @returns The created {@link SnapManifest} object.
147
- */ export function createSnapManifest(value) {
148
- // TODO: Add a utility to prefix these errors similar to assertStruct
149
- return create(value, SnapManifestStruct);
150
- }
151
-
152
- //# sourceMappingURL=validation.js.map
@@ -1 +0,0 @@
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":["isValidBIP32PathSegment","assertStruct","ChecksumStruct","VersionStruct","isValidSemVerRange","array","boolean","create","enums","integer","is","literal","object","optional","pattern","refine","record","size","string","type","union","isEqual","CronjobSpecificationArrayStruct","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","RpcOriginsStruct","SnapIdStruct","NameStruct","NpmSnapFileNames","FORBIDDEN_PURPOSES","FORBIDDEN_COIN_TYPES","FORBIDDEN_PATHS","map","coinType","Bip32PathStruct","path","length","slice","some","part","includes","forbiddenPath","join","bip32entropy","struct","value","curve","endsWith","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","Infinity","SemVerRangeStruct","SnapIdsStruct","version","Object","keys","PermissionsStruct","allowTransactionOrigin","jobs","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","snap_getEntropy","wallet_snap","SnapManifestStruct","description","proposedName","repository","url","source","shasum","location","npm","filePath","iconPath","packageName","registry","initialPermissions","manifestVersion","$schema","isSnapManifest","assertIsSnapManifest","Manifest","createSnapManifest"],"mappings":"AAAA,SAASA,uBAAuB,QAAQ,qBAAqB;AAC7D,SACEC,YAAY,EACZC,cAAc,EACdC,aAAa,EACbC,kBAAkB,QACb,kBAAkB;AACzB,SACEC,KAAK,EACLC,OAAO,EACPC,MAAM,EACNC,KAAK,EAELC,OAAO,EACPC,EAAE,EACFC,OAAO,EACPC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,MAAM,EACNC,MAAM,EACNC,IAAI,EACJC,MAAM,EAENC,IAAI,EACJC,KAAK,QACA,cAAc;AAErB,SAASC,OAAO,QAAQ,WAAW;AACnC,SAASC,+BAA+B,QAAQ,aAAa;AAC7D,SAASC,iBAAiB,EAAEC,4BAA4B,QAAQ,aAAa;AAC7E,SAASC,gBAAgB,QAAQ,cAAc;AAC/C,SAASC,YAAY,QAAQ,WAAW;AACxC,SAASC,UAAU,EAAEC,gBAAgB,QAAQ,WAAW;AAExD,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCN;IACAC;CACD;AAED,OAAO,MAAMM,uBAAiC;IAAC;CAAG,CAAC;AACnD,MAAMC,kBAA8BD,qBAAqBE,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAED,OAAO,MAAMC,kBAAkBnB,OAC7BV,MAAMa,WACN,eACA,CAACiB;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,CAACvC,wBAAwBuC,QAAQ;QAChE,OAAO;IACT;IAEA,IAAIV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GAAGmC,OAAOwB;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASiB,qBACdzC,KAAc;IAEd5C,aACE4C,OACAwB,oBACA,CAAC,CAAC,EAAEzC,iBAAiB2D,QAAQ,CAAC,YAAY,CAAC;AAE/C;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,mBAAmB3C,KAAc;IAC/C,qEAAqE;IACrE,OAAOtC,OAAOsC,OAAOwB;AACvB"}
@@ -1 +0,0 @@
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":["crypto","EventEmitter","DEFAULT_ENDOWMENTS","NETWORK_APIS","ALL_APIS","getMockSnapGlobal","request","getMockEthereumProvider","mockProvider","isConstructor","value","Boolean","prototype","constructor","name","mockFunction","MockClass","handler","construct","Target","args","Proxy","get","_target","_prop","generateMockClass","mockWindow","SubtleCrypto","generateMockEndowment","key","globalValue","globalThis","includes","globalOrMocked","type","isFunction","generateMockEndowments","reduce","acc","cur","snap","ethereum"],"mappings":"AAAA,OAAOA,YAAY,SAAS;AAC5B,OAAOC,kBAAkB,SAAS;AAElC,SAASC,kBAAkB,QAAQ,uBAAuB;AAE1D,MAAMC,eAAe;IAAC;IAAS;IAAW;IAAW;CAAW;AAEhE,OAAO,MAAMC,WAAqB;OAC7BF;OACAC;IACH;CACD,CAAC;AAUF;;;;CAIC,GACD,SAASE;IACP,4DAA4D;IAC5D,OAAO;QAAEC,SAAS,UAAY;IAAK;AACrC;AAEA;;;;CAIC,GACD,SAASC;IACP,MAAMC,eAAe,IAAIP;IACzB,4DAA4D;IAC5DO,aAAaF,OAAO,GAAG,UAAY;IACnC,OAAOE;AACT;AAEA;;;;;CAKC,GACD,OAAO,MAAMC,gBAAgB,CAACC,QAC5BC,QAAQ,OAAOD,OAAOE,WAAWC,aAAaC,SAAS,UAAU;AAEnE;;;;CAIC,GACD,MAAMC,eAAe,IAAM;AAC3B,MAAMC;AAAW;AAEjB,MAAMC,UAAU;IACd,gEAAgE;IAChEC,WAAUC,MAAW,EAAEC,IAAW;QAChC,OAAO,IAAIC,MAAM,IAAIF,UAAUC,OAAOH;IACxC;IACAK,KAAIC,OAAY,EAAEC,KAAU;QAC1B,OAAOT;IACT;AACF;AAEA;;;;;;CAMC,GACD,MAAMU,oBAAoB,CAACf;IACzB,OAAO,IAAIW,MAAMX,OAAOO;AAC1B;AAEA,6EAA6E;AAC7E,oEAAoE;AACpE,MAAMS,aAAsC;IAC1C1B;IACA2B,cAAcX;AAChB;AAEA;;;;;;;CAOC,GACD,MAAMY,wBAAwB,CAACC;IAC7B,MAAMC,cAAc,AAACC,UAAkB,CAACF,IAAI;IAE5C,+CAA+C;IAC/C,IAAIC,eAAe5B,mBAAmB8B,QAAQ,CAACH,MAAM;QACnD,OAAOC;IACT;IAEA,4EAA4E;IAC5E,MAAMG,iBAAiBH,eAAeJ,UAAU,CAACG,IAAI;IAErD,MAAMK,OAAO,OAAOD;IACpB,MAAME,aAAaD,SAAS;IAC5B,IAAIC,cAAc1B,cAAcwB,iBAAiB;QAC/C,OAAOR,kBAAkBQ;IAC3B,OAAO,IAAIE,cAAc,CAACF,gBAAgB;QACxC,qCAAqC;QACrC,OAAOlB;IACT;IACA,OAAOkB;AACT;AAEA;;;;CAIC,GACD,OAAO,MAAMG,yBAAyB;IACpC,OAAOhC,SAASiC,MAAM,CACpB,CAACC,KAAKC,MAAS,CAAA;YAAE,GAAGD,GAAG;YAAE,CAACC,IAAI,EAAEX,sBAAsBW;QAAK,CAAA,GAC3D;QAAEC,MAAMnC;QAAqBoC,UAAUlC;IAA0B;AAErE,EAAE"}
@@ -1,110 +0,0 @@
1
- import { array, is, object, optional, pattern, size, string } from 'superstruct';
2
- export const CHAIN_ID_REGEX = RegExp("^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$", "u");
3
- export 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");
4
- /**
5
- * Parse a chain ID string to an object containing the namespace and reference.
6
- * This validates the chain ID before parsing it.
7
- *
8
- * @param chainId - The chain ID to validate and parse.
9
- * @returns The parsed chain ID.
10
- */ export function parseChainId(chainId) {
11
- const match = CHAIN_ID_REGEX.exec(chainId);
12
- if (!match?.groups) {
13
- throw new Error('Invalid chain ID.');
14
- }
15
- return {
16
- namespace: match.groups.namespace,
17
- reference: match.groups.reference
18
- };
19
- }
20
- /**
21
- * Parse an account ID to an object containing the chain, chain ID and address.
22
- * This validates the account ID before parsing it.
23
- *
24
- * @param accountId - The account ID to validate and parse.
25
- * @returns The parsed account ID.
26
- */ export function parseAccountId(accountId) {
27
- const match = ACCOUNT_ID_REGEX.exec(accountId);
28
- if (!match?.groups) {
29
- throw new Error('Invalid account ID.');
30
- }
31
- return {
32
- address: match.groups.accountAddress,
33
- chainId: match.groups.chainId,
34
- chain: {
35
- namespace: match.groups.namespace,
36
- reference: match.groups.reference
37
- }
38
- };
39
- }
40
- /**
41
- * A helper struct for a string with a minimum length of 1 and a maximum length
42
- * of 40.
43
- */ export const LimitedString = size(string(), 1, 40);
44
- /**
45
- * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
46
- */ export const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);
47
- export const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);
48
- export const AccountIdArrayStruct = array(AccountIdStruct);
49
- /**
50
- * A chain descriptor.
51
- */ export const ChainStruct = object({
52
- id: ChainIdStruct,
53
- name: LimitedString
54
- });
55
- export const NamespaceStruct = object({
56
- /**
57
- * A list of supported chains in the namespace.
58
- */ chains: array(ChainStruct),
59
- /**
60
- * A list of supported RPC methods on the namespace, that a DApp can call.
61
- */ methods: optional(array(LimitedString)),
62
- /**
63
- * A list of supported RPC events on the namespace, that a DApp can listen to.
64
- */ events: optional(array(LimitedString))
65
- });
66
- /**
67
- * A CAIP-2 namespace, i.e., the first part of a chain ID.
68
- */ export const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);
69
- /**
70
- * Check if the given value is a CAIP-2 namespace ID.
71
- *
72
- * @param value - The value to check.
73
- * @returns Whether the value is a CAIP-2 namespace ID.
74
- */ export function isNamespaceId(value) {
75
- return is(value, NamespaceIdStruct);
76
- }
77
- /**
78
- * Check if the given value is a CAIP-2 chain ID.
79
- *
80
- * @param value - The value to check.
81
- * @returns Whether the value is a CAIP-2 chain ID.
82
- */ export function isChainId(value) {
83
- return is(value, ChainIdStruct);
84
- }
85
- /**
86
- * Check if the given value is a CAIP-10 account ID.
87
- *
88
- * @param value - The value to check.
89
- * @returns Whether the value is a CAIP-10 account ID.
90
- */ export function isAccountId(value) {
91
- return is(value, AccountIdStruct);
92
- }
93
- /**
94
- * Check if the given value is an array of CAIP-10 account IDs.
95
- *
96
- * @param value - The value to check.
97
- * @returns Whether the value is an array of CAIP-10 account IDs.
98
- */ export function isAccountIdArray(value) {
99
- return is(value, AccountIdArrayStruct);
100
- }
101
- /**
102
- * Check if a value is a {@link Namespace}.
103
- *
104
- * @param value - The value to validate.
105
- * @returns True if the value is a valid {@link Namespace}.
106
- */ export function isNamespace(value) {
107
- return is(value, NamespaceStruct);
108
- }
109
-
110
- //# sourceMappingURL=namespace.js.map
@@ -1 +0,0 @@
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":["array","is","object","optional","pattern","size","string","CHAIN_ID_REGEX","ACCOUNT_ID_REGEX","parseChainId","chainId","match","exec","groups","Error","namespace","reference","parseAccountId","accountId","address","accountAddress","chain","LimitedString","ChainIdStruct","AccountIdStruct","AccountIdArrayStruct","ChainStruct","id","name","NamespaceStruct","chains","methods","events","NamespaceIdStruct","isNamespaceId","value","isChainId","isAccountId","isAccountIdArray","isNamespace"],"mappings":"AAAA,SACEA,KAAK,EAELC,EAAE,EACFC,MAAM,EACNC,QAAQ,EACRC,OAAO,EACPC,IAAI,EACJC,MAAM,QACD,cAAc;AAErB,OAAO,MAAMC,iBACX,+EAAmE;AAErE,OAAO,MAAMC,mBACX,gIAAoH;AAEtH;;;;;;CAMC,GACD,OAAO,SAASC,aAAaC,OAAgB;IAI3C,MAAMC,QAAQJ,eAAeK,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;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,eAAeC,SAAoB;IAKjD,MAAMP,QAAQH,iBAAiBI,IAAI,CAACM;IACpC,IAAI,CAACP,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLK,SAASR,MAAME,MAAM,CAACO,cAAc;QACpCV,SAASC,MAAME,MAAM,CAACH,OAAO;QAC7BW,OAAO;YACLN,WAAWJ,MAAME,MAAM,CAACE,SAAS;YACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;QACnC;IACF;AACF;AAEA;;;CAGC,GACD,OAAO,MAAMM,gBAAgBjB,KAAKC,UAAU,GAAG,IAAI;AAEnD;;CAEC,GACD,OAAO,MAAMiB,gBAAgBnB,QAAQE,UAAUC,gBAAgB;AAG/D,OAAO,MAAMiB,kBAAkBpB,QAAQE,UAAUE,kBAAkB;AAGnE,OAAO,MAAMiB,uBAAuBzB,MAAMwB,iBAAiB;AAE3D;;CAEC,GACD,OAAO,MAAME,cAAcxB,OAAO;IAChCyB,IAAIJ;IACJK,MAAMN;AACR,GAAG;AAGH,OAAO,MAAMO,kBAAkB3B,OAAO;IACpC;;GAEC,GACD4B,QAAQ9B,MAAM0B;IAEd;;GAEC,GACDK,SAAS5B,SAASH,MAAMsB;IAExB;;GAEC,GACDU,QAAQ7B,SAASH,MAAMsB;AACzB,GAAG;AAGH;;CAEC,GACD,OAAO,MAAMW,oBAAoB7B,QAAQE,UAAU,qBAAqB;AAGxE;;;;;CAKC,GACD,OAAO,SAAS4B,cAAcC,KAAc;IAC1C,OAAOlC,GAAGkC,OAAOF;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASG,UAAUD,KAAc;IACtC,OAAOlC,GAAGkC,OAAOZ;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASc,YAAYF,KAAc;IACxC,OAAOlC,GAAGkC,OAAOX;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASc,iBAAiBH,KAAc;IAC7C,OAAOlC,GAAGkC,OAAOV;AACnB;AAEA;;;;;CAKC,GACD,OAAO,SAASc,YAAYJ,KAAc;IACxC,OAAOlC,GAAGkC,OAAON;AACnB"}
package/dist/esm/npm.js DELETED
@@ -1,70 +0,0 @@
1
- import { assertIsSnapIcon } from './icon';
2
- import { validateNpmSnapManifest } from './manifest/manifest';
3
- import { assertIsSnapManifest } from './manifest/validation';
4
- import { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';
5
- export const EXPECTED_SNAP_FILES = [
6
- 'manifest',
7
- 'packageJson',
8
- 'sourceCode'
9
- ];
10
- export const SnapFileNameFromKey = {
11
- manifest: NpmSnapFileNames.Manifest,
12
- packageJson: NpmSnapFileNames.PackageJson,
13
- sourceCode: 'source code bundle'
14
- };
15
- // TODO: Refactor this to be more shared with other validation.
16
- /**
17
- * Validates the files extracted from an npm Snap package tarball by ensuring
18
- * that they're non-empty and that the Json files match their respective schemas
19
- * and the Snaps publishing specification.
20
- *
21
- * @param snapFiles - The object containing the expected Snap file contents,
22
- * if any.
23
- * @param errorPrefix - The prefix of the error message.
24
- * @returns A tuple of the Snap manifest object and the Snap source code.
25
- */ export function validateNpmSnap(snapFiles, errorPrefix) {
26
- EXPECTED_SNAP_FILES.forEach((key)=>{
27
- if (!snapFiles[key]) {
28
- throw new Error(`${errorPrefix ?? ''}Missing file "${SnapFileNameFromKey[key]}".`);
29
- }
30
- });
31
- // Typecast: We are assured that the required files exist if we get here.
32
- const { manifest, packageJson, sourceCode, svgIcon } = snapFiles;
33
- try {
34
- assertIsSnapManifest(manifest.result);
35
- } catch (error) {
36
- throw new Error(`${errorPrefix ?? ''}${error.message}`);
37
- }
38
- const validatedManifest = manifest;
39
- const { iconPath } = validatedManifest.result.source.location.npm;
40
- if (iconPath && !svgIcon) {
41
- throw new Error(`Missing file "${iconPath}".`);
42
- }
43
- try {
44
- assertIsNpmSnapPackageJson(packageJson.result);
45
- } catch (error) {
46
- throw new Error(`${errorPrefix ?? ''}${error.message}`);
47
- }
48
- const validatedPackageJson = packageJson;
49
- validateNpmSnapManifest({
50
- manifest: validatedManifest,
51
- packageJson: validatedPackageJson,
52
- sourceCode,
53
- svgIcon
54
- });
55
- if (svgIcon) {
56
- try {
57
- assertIsSnapIcon(svgIcon);
58
- } catch (error) {
59
- throw new Error(`${errorPrefix ?? ''}${error.message}`);
60
- }
61
- }
62
- return {
63
- manifest: validatedManifest,
64
- packageJson: validatedPackageJson,
65
- sourceCode,
66
- svgIcon
67
- };
68
- }
69
-
70
- //# sourceMappingURL=npm.js.map
@@ -1 +0,0 @@
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":["assertIsSnapIcon","validateNpmSnapManifest","assertIsSnapManifest","assertIsNpmSnapPackageJson","NpmSnapFileNames","EXPECTED_SNAP_FILES","SnapFileNameFromKey","manifest","Manifest","packageJson","PackageJson","sourceCode","validateNpmSnap","snapFiles","errorPrefix","forEach","key","Error","svgIcon","result","error","message","validatedManifest","iconPath","source","location","npm","validatedPackageJson"],"mappings":"AAAA,SAASA,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,uBAAuB,QAAQ,sBAAsB;AAC9D,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SACEC,0BAA0B,EAC1BC,gBAAgB,QAGX,UAAU;AAEjB,OAAO,MAAMC,sBAAsB;IACjC;IACA;IACA;CACD,CAAU;AAEX,OAAO,MAAMC,sBAAsB;IACjCC,UAAUH,iBAAiBI,QAAQ;IACnCC,aAAaL,iBAAiBM,WAAW;IACzCC,YAAY;AACd,EAAW;AAEX,+DAA+D;AAE/D;;;;;;;;;CASC,GACD,OAAO,SAASC,gBACdC,SAA+B,EAC/BC,WAA2B;IAE3BT,oBAAoBU,OAAO,CAAC,CAACC;QAC3B,IAAI,CAACH,SAAS,CAACG,IAAI,EAAE;YACnB,MAAM,IAAIC,MACR,CAAC,EAAEH,eAAe,GAAG,cAAc,EAAER,mBAAmB,CAACU,IAAI,CAAC,EAAE,CAAC;QAErE;IACF;IAEA,yEAAyE;IACzE,MAAM,EAAET,QAAQ,EAAEE,WAAW,EAAEE,UAAU,EAAEO,OAAO,EAAE,GAAGL;IACvD,IAAI;QACFX,qBAAqBK,SAASY,MAAM;IACtC,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIH,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEM,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMC,oBAAoBf;IAE1B,MAAM,EAAEgB,QAAQ,EAAE,GAAGD,kBAAkBH,MAAM,CAACK,MAAM,CAACC,QAAQ,CAACC,GAAG;IACjE,IAAIH,YAAY,CAACL,SAAS;QACxB,MAAM,IAAID,MAAM,CAAC,cAAc,EAAEM,SAAS,EAAE,CAAC;IAC/C;IAEA,IAAI;QACFpB,2BAA2BM,YAAYU,MAAM;IAC/C,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIH,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEM,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMM,uBAAuBlB;IAE7BR,wBAAwB;QACtBM,UAAUe;QACVb,aAAakB;QACbhB;QACAO;IACF;IAEA,IAAIA,SAAS;QACX,IAAI;YACFlB,iBAAiBkB;QACnB,EAAE,OAAOE,OAAO;YACd,MAAM,IAAIH,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEM,MAAMC,OAAO,CAAC,CAAC;QACxD;IACF;IAEA,OAAO;QACLd,UAAUe;QACVb,aAAakB;QACbhB;QACAO;IACF;AACF"}
package/dist/esm/path.js DELETED
@@ -1,17 +0,0 @@
1
- import { assert } from '@metamask/utils';
2
- /**
3
- * Normalizes relative paths by optionally removing `./` prefix.
4
- *
5
- * @param path - Path to make normalize.
6
- * @returns The same path, with `./` prefix remove.
7
- */ // TODO(ritave): Include NodeJS path polyfill and use path.normalize as well
8
- export function normalizeRelative(path) {
9
- assert(!path.startsWith('/'));
10
- assert(path.search(/:|\/\//u) === -1, `Path "${path}" potentially an URI instead of local relative`);
11
- if (path.startsWith('./')) {
12
- return path.slice(2);
13
- }
14
- return path;
15
- }
16
-
17
- //# sourceMappingURL=path.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/path.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\n\n/**\n * Normalizes relative paths by optionally removing `./` prefix.\n *\n * @param path - Path to make normalize.\n * @returns The same path, with `./` prefix remove.\n */\n// TODO(ritave): Include NodeJS path polyfill and use path.normalize as well\nexport function normalizeRelative(path: string): string {\n assert(!path.startsWith('/'));\n assert(\n path.search(/:|\\/\\//u) === -1,\n `Path \"${path}\" potentially an URI instead of local relative`,\n );\n\n if (path.startsWith('./')) {\n return path.slice(2);\n }\n return path;\n}\n"],"names":["assert","normalizeRelative","path","startsWith","search","slice"],"mappings":"AAAA,SAASA,MAAM,QAAQ,kBAAkB;AAEzC;;;;;CAKC,GACD,4EAA4E;AAC5E,OAAO,SAASC,kBAAkBC,IAAY;IAC5CF,OAAO,CAACE,KAAKC,UAAU,CAAC;IACxBH,OACEE,KAAKE,MAAM,CAAC,eAAe,CAAC,GAC5B,CAAC,MAAM,EAAEF,KAAK,8CAA8C,CAAC;IAG/D,IAAIA,KAAKC,UAAU,CAAC,OAAO;QACzB,OAAOD,KAAKG,KAAK,CAAC;IACpB;IACA,OAAOH;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { transformSync, Node, Visitor, template, PluginObj } from '@babel/core';\nimport {\n binaryExpression,\n Expression,\n Identifier,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n TemplateElement,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["transformSync","template","binaryExpression","isUnaryExpression","isUpdateExpression","stringLiteral","templateElement","templateLiteral","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","raw","cooked","evalWrapper","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","lastMatch","suffix","replace","postProcessBundle","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","expression","setData","StringLiteral","replacement","acc","skip","BinaryExpression","errorMessage","operator","right","argument","left","end","start","includes","Error","file","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;AACxD,SAASA,aAAa,EAAiBC,QAAQ,QAAmB,cAAc;AAChF,SACEC,gBAAgB,EAGhBC,iBAAiB,EACjBC,kBAAkB,EAClBC,aAAa,EAEbC,eAAe,EACfC,eAAe,QACV,eAAe;WAgDf;UAAKC,kBAAkB;IAAlBA,mBACVC,sBAAmB;GADTD,uBAAAA;AAIZ,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAME,cAAc;AAEpB,4EAA4E;AAC5E,cAAc;AACd,MAAMC,yBAAyBL,gBAAgB;IAAEM,KAAK;IAAIC,QAAQ;AAAG;AAErE,MAAMC,cAAcb,SAASc,SAAS,CAAC,CAAC;;AAExC,CAAC;AAED,MAAMC,oBAAoBf,SAASc,SAAS,CAAC,CAAC;;AAE9C,CAAC;AAED,MAAME,4BAA4BhB,SAASc,SAAS,CAAC,CAAC;;AAEtD,CAAC;AAED;;;;;;;;;;;CAWC,GACD,SAASG,YAAYC,KAAa;IAChC,MAAMC,SAASD,MAAME,KAAK,CAACX;IAC3B,OACEU,MACE,oEAAoE;IACpE,sEAAsE;KACrEE,MAAM,CAAC,CAACC,QAAUA,UAAU,MAAMA,UAAUC;AAEnD;AAEA;;;;;;;;;;CAUC,GACD,SAASC,2BACPN,KAAa;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