@metamask/snaps-utils 0.34.1-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 +21 -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 +46 -21
  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/snaps.ts"],"sourcesContent":["import {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport { BlockReason } from '@metamask/snaps-registry';\nimport {\n assert,\n Json,\n SemVerVersion,\n isObject,\n Opaque,\n assertStruct,\n} from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n Struct,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport { SnapManifest, SnapPermissions } from './manifest/validation';\nimport {\n SnapFiles,\n SnapId,\n SnapIdPrefixes,\n SnapsPermissionRequest,\n SnapValidationFailureReason,\n uri,\n} from './types';\nimport { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap & {\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n};\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * A {@link Snap} object with the fields that are relevant to an external\n * caller.\n */\nexport type TruncatedSnap = Pick<Snap, TruncatedSnapFields>;\n\nexport type ProcessSnapResult =\n | TruncatedSnap\n | { error: SerializedEthereumRpcError };\n\nexport type InstallSnapsResult = Record<SnapId, ProcessSnapResult>;\n\n/**\n * An error indicating that a Snap validation failure is programmatically\n * fixable during development.\n */\nexport class ProgrammaticallyFixableSnapError extends Error {\n reason: SnapValidationFailureReason;\n\n constructor(message: string, reason: SnapValidationFailureReason) {\n super(message);\n this.reason = reason;\n }\n}\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport function getSnapChecksum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): string {\n const { manifest, sourceCode, svgIcon } = files;\n const all = [getChecksummableManifest(manifest), sourceCode, svgIcon].filter(\n (file) => file !== undefined,\n );\n return base64.encode(checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport function validateSnapShasum(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): void {\n if (files.manifest.result.source.shasum !== getSnapChecksum(files)) {\n throw new ProgrammaticallyFixableSnapError(\n errorMessage,\n SnapValidationFailureReason.ShasumMismatch,\n );\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\nexport type ValidatedSnapId = Opaque<string, typeof snapIdSymbol>;\ndeclare const snapIdSymbol: unique symbol;\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(\n value: unknown,\n): asserts value is ValidatedSnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n"],"names":["PROPOSED_NAME_REGEX","ProgrammaticallyFixableSnapError","getSnapChecksum","validateSnapShasum","LOCALHOST_HOSTNAMES","BaseSnapIdStruct","LocalSnapIdStruct","NpmSnapIdStruct","HttpSnapIdStruct","SnapIdStruct","getSnapPrefix","stripSnapPrefix","assertIsValidSnapId","isCaipChainId","isSnapPermitted","verifyRequestedSnapPermissions","SnapStatus","Installing","Updating","Running","Stopped","Crashed","SnapStatusEvents","Start","Stop","Crash","Update","Error","constructor","message","reason","getChecksummableManifest","manifest","manifestCopy","clone","result","source","shasum","value","stableStringify","files","sourceCode","svgIcon","all","filter","file","undefined","base64","encode","checksumFiles","errorMessage","SnapValidationFailureReason","ShasumMismatch","pattern","string","LocalSnapIdSubUrlStruct","uri","protocol","enums","hostname","hash","empty","search","refine","startsWith","SnapIdPrefixes","local","error","validate","slice","length","intersection","literal","npm","pathname","normalized","errors","validForNewPackages","warnings","validateNPMPackage","assert","union","snapId","prefix","Object","values","find","possiblePrefix","replace","assertStruct","chainId","test","permissions","Boolean","wallet_snap","caveats","caveat","type","SnapCaveatType","SnapIds","requestedPermissions","isObject","walletSnapPermission","Array","isArray"],"mappings":"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"}
@@ -0,0 +1,117 @@
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
+ NpmSnapFileNames: function() {
13
+ return NpmSnapFileNames;
14
+ },
15
+ SnapIdPrefixes: function() {
16
+ return SnapIdPrefixes;
17
+ },
18
+ SnapValidationFailureReason: function() {
19
+ return SnapValidationFailureReason;
20
+ },
21
+ SNAP_STREAM_NAMES: function() {
22
+ return SNAP_STREAM_NAMES;
23
+ },
24
+ HandlerType: function() {
25
+ return HandlerType;
26
+ },
27
+ NameStruct: function() {
28
+ return NameStruct;
29
+ },
30
+ NpmSnapPackageJsonStruct: function() {
31
+ return NpmSnapPackageJsonStruct;
32
+ },
33
+ isNpmSnapPackageJson: function() {
34
+ return isNpmSnapPackageJson;
35
+ },
36
+ assertIsNpmSnapPackageJson: function() {
37
+ return assertIsNpmSnapPackageJson;
38
+ },
39
+ SNAP_EXPORT_NAMES: function() {
40
+ return SNAP_EXPORT_NAMES;
41
+ },
42
+ uri: function() {
43
+ return uri;
44
+ },
45
+ isValidUrl: function() {
46
+ return isValidUrl;
47
+ },
48
+ WALLET_SNAP_PERMISSION_KEY: function() {
49
+ return WALLET_SNAP_PERMISSION_KEY;
50
+ }
51
+ });
52
+ const _utils = require("@metamask/utils");
53
+ const _superstruct = require("superstruct");
54
+ var NpmSnapFileNames;
55
+ (function(NpmSnapFileNames) {
56
+ NpmSnapFileNames["PackageJson"] = 'package.json';
57
+ NpmSnapFileNames["Manifest"] = 'snap.manifest.json';
58
+ })(NpmSnapFileNames || (NpmSnapFileNames = {}));
59
+ const NameStruct = (0, _superstruct.size)((0, _superstruct.pattern)((0, _superstruct.string)(), /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/u), 1, 214);
60
+ const NpmSnapPackageJsonStruct = (0, _superstruct.type)({
61
+ version: _utils.VersionStruct,
62
+ name: NameStruct,
63
+ main: (0, _superstruct.optional)((0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)),
64
+ repository: (0, _superstruct.optional)((0, _superstruct.object)({
65
+ type: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity),
66
+ url: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)
67
+ }))
68
+ });
69
+ function isNpmSnapPackageJson(value) {
70
+ return (0, _superstruct.is)(value, NpmSnapPackageJsonStruct);
71
+ }
72
+ function assertIsNpmSnapPackageJson(value) {
73
+ (0, _utils.assertStruct)(value, NpmSnapPackageJsonStruct, `"${NpmSnapFileNames.PackageJson}" is invalid`);
74
+ }
75
+ var SnapIdPrefixes;
76
+ (function(SnapIdPrefixes) {
77
+ SnapIdPrefixes["npm"] = 'npm:';
78
+ SnapIdPrefixes["local"] = 'local:';
79
+ })(SnapIdPrefixes || (SnapIdPrefixes = {}));
80
+ var SnapValidationFailureReason;
81
+ (function(SnapValidationFailureReason) {
82
+ SnapValidationFailureReason["NameMismatch"] = '"name" field mismatch';
83
+ SnapValidationFailureReason["VersionMismatch"] = '"version" field mismatch';
84
+ SnapValidationFailureReason["RepositoryMismatch"] = '"repository" field mismatch';
85
+ SnapValidationFailureReason["ShasumMismatch"] = '"shasum" field mismatch';
86
+ })(SnapValidationFailureReason || (SnapValidationFailureReason = {}));
87
+ var SNAP_STREAM_NAMES;
88
+ (function(SNAP_STREAM_NAMES) {
89
+ SNAP_STREAM_NAMES["JSON_RPC"] = 'jsonRpc';
90
+ SNAP_STREAM_NAMES["COMMAND"] = 'command';
91
+ })(SNAP_STREAM_NAMES || (SNAP_STREAM_NAMES = {}));
92
+ var HandlerType;
93
+ (function(HandlerType) {
94
+ HandlerType["OnRpcRequest"] = 'onRpcRequest';
95
+ HandlerType["OnTransaction"] = 'onTransaction';
96
+ HandlerType["OnCronjob"] = 'onCronjob';
97
+ })(HandlerType || (HandlerType = {}));
98
+ const SNAP_EXPORT_NAMES = Object.values(HandlerType);
99
+ const uri = (opts = {})=>(0, _superstruct.refine)((0, _superstruct.union)([
100
+ (0, _superstruct.string)(),
101
+ (0, _superstruct.instance)(URL)
102
+ ]), 'uri', (value)=>{
103
+ try {
104
+ const url = new URL(value);
105
+ const UrlStruct = (0, _superstruct.type)(opts);
106
+ (0, _superstruct.assert)(url, UrlStruct);
107
+ return true;
108
+ } catch {
109
+ return `Expected URL, got "${value.toString()}".`;
110
+ }
111
+ });
112
+ function isValidUrl(url, opts = {}) {
113
+ return (0, _superstruct.is)(url, uri(opts));
114
+ }
115
+ const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';
116
+
117
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import { assertStruct, Json, VersionStruct } from '@metamask/utils';\nimport {\n Infer,\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n Struct,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport { SnapCaveatType } from './caveats';\nimport { SnapFunctionExports } from './handlers';\nimport { SnapManifest } from './manifest';\nimport { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n};\n\n/**\n * An object for storing the contents of Snap files that have passed JSON\n * Schema validation, or are non-empty if they are strings.\n */\nexport type SnapFiles = {\n manifest: VirtualFile<SnapManifest>;\n packageJson: VirtualFile<NpmSnapPackageJson>;\n sourceCode: VirtualFile;\n svgIcon?: VirtualFile;\n};\n\n/**\n * The possible prefixes for snap ids.\n */\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SnapIdPrefixes {\n npm = 'npm:',\n local = 'local:',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapId = string;\n\n/**\n * Snap validation failure reason codes that are programmatically fixable\n * if validation occurs during development.\n */\nexport enum SnapValidationFailureReason {\n NameMismatch = '\"name\" field mismatch',\n VersionMismatch = '\"version\" field mismatch',\n RepositoryMismatch = '\"repository\" field mismatch',\n ShasumMismatch = '\"shasum\" field mismatch',\n}\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport enum SNAP_STREAM_NAMES {\n JSON_RPC = 'jsonRpc',\n COMMAND = 'command',\n}\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n}\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\n// The snap is the callee\nexport type SnapRpcHook = (options: SnapRpcHookArgs) => Promise<unknown>;\n\ntype ObjectParameters<\n Type extends Record<string, (...args: any[]) => unknown>,\n> = Parameters<Type[keyof Type]>;\n\nexport type SnapExportsParameters = ObjectParameters<SnapFunctionExports>;\n\ntype UriOptions<T extends string> = {\n protocol?: Struct<T>;\n hash?: Struct<T>;\n port?: Struct<T>;\n hostname?: Struct<T>;\n pathname?: Struct<T>;\n search?: Struct<T>;\n};\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"],"names":["NameStruct","NpmSnapPackageJsonStruct","isNpmSnapPackageJson","assertIsNpmSnapPackageJson","SNAP_EXPORT_NAMES","uri","isValidUrl","WALLET_SNAP_PERMISSION_KEY","NpmSnapFileNames","PackageJson","Manifest","size","pattern","string","type","version","VersionStruct","name","main","optional","Infinity","repository","object","url","value","is","assertStruct","SnapIdPrefixes","npm","local","SnapValidationFailureReason","NameMismatch","VersionMismatch","RepositoryMismatch","ShasumMismatch","SNAP_STREAM_NAMES","JSON_RPC","COMMAND","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","Object","values","opts","refine","union","instance","URL","UrlStruct","assertSuperstruct","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;IA2BaA,UAAU;eAAVA;;IAWAC,wBAAwB;eAAxBA;;IAqBGC,oBAAoB;eAApBA;;IAYAC,0BAA0B;eAA1BA;;IAmEHC,iBAAiB;eAAjBA;;IAyBAC,GAAG;eAAHA;;IAoBGC,UAAU;eAAVA;;IAQHC,0BAA0B;eAA1BA;;;uBA/LqC;6BAe3C;IAOA;UAAKC,gBAAgB;IAAhBA,iBACVC,iBAAc;IADJD,iBAEVE,cAAW;GAFDF,qBAAAA;AAKL,MAAMR,aAAaW,IAAAA,iBAAI,EAC5BC,IAAAA,oBAAO,EACLC,IAAAA,mBAAM,KACN,gEAEF,GACA;AAKK,MAAMZ,2BAA2Ba,IAAAA,iBAAI,EAAC;IAC3CC,SAASC,oBAAa;IACtBC,MAAMjB;IACNkB,MAAMC,IAAAA,qBAAQ,EAACR,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;IACjCC,YAAYF,IAAAA,qBAAQ,EAClBG,IAAAA,mBAAM,EAAC;QACLR,MAAMH,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;QACxBG,KAAKZ,IAAAA,iBAAI,EAACE,IAAAA,mBAAM,KAAI,GAAGO;IACzB;AAEJ;AAWO,SAASlB,qBACdsB,KAAc;IAEd,OAAOC,IAAAA,eAAE,EAACD,OAAOvB;AACnB;AAQO,SAASE,2BACdqB,KAAc;IAEdE,IAAAA,mBAAY,EACVF,OACAvB,0BACA,CAAC,CAAC,EAAEO,iBAAiBC,WAAW,CAAC,YAAY,CAAC;AAElD;IA2BO;UAAKkB,cAAc;IAAdA,eACVC,SAAM;IADID,eAEVE,WAAQ;GAFEF,mBAAAA;IAYL;UAAKG,2BAA2B;IAA3BA,4BACVC,kBAAe;IADLD,4BAEVE,qBAAkB;IAFRF,4BAGVG,wBAAqB;IAHXH,4BAIVI,oBAAiB;GAJPJ,gCAAAA;IAQL;UAAKK,iBAAiB;IAAjBA,kBACVC,cAAW;IADDD,kBAEVE,aAAU;GAFAF,sBAAAA;IAML;UAAKG,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;GAHFH,gBAAAA;AAML,MAAMlC,oBAAoBsC,OAAOC,MAAM,CAACL;AAyBxC,MAAMjC,MAAM,CAACuC,OAAwB,CAAC,CAAC,GAC5CC,IAAAA,mBAAM,EAACC,IAAAA,kBAAK,EAAC;QAACjC,IAAAA,mBAAM;QAAIkC,IAAAA,qBAAQ,EAACC;KAAK,GAAG,OAAO,CAACxB;QAC/C,IAAI;YACF,MAAMD,MAAM,IAAIyB,IAAIxB;YAEpB,MAAMyB,YAAYnC,IAAAA,iBAAI,EAAC8B;YACvBM,IAAAA,mBAAiB,EAAC3B,KAAK0B;YACvB,OAAO;QACT,EAAE,OAAM;YACN,OAAO,CAAC,mBAAmB,EAAEzB,MAAM2B,QAAQ,GAAG,EAAE,CAAC;QACnD;IACF;AASK,SAAS7C,WACdiB,GAAY,EACZqB,OAAwB,CAAC,CAAC;IAE1B,OAAOnB,IAAAA,eAAE,EAACF,KAAKlB,IAAIuC;AACrB;AAGO,MAAMrC,6BAA6B"}
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "validateFetchedSnap", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return validateFetchedSnap;
9
+ }
10
+ });
11
+ const _icon = require("./icon");
12
+ const _validation = require("./manifest/validation");
13
+ const _snaps = require("./snaps");
14
+ function validateFetchedSnap(files) {
15
+ (0, _validation.assertIsSnapManifest)(files.manifest.result);
16
+ (0, _snaps.validateSnapShasum)(files);
17
+ if (files.svgIcon) {
18
+ (0, _icon.assertIsSnapIcon)(files.svgIcon);
19
+ }
20
+ }
21
+
22
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/validation.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport { validateSnapShasum } from './snaps';\nimport { SnapFiles } from './types';\n\n/**\n * Validates the files contained in a fetched snap.\n *\n * @param files - All potentially included files in a fetched snap.\n * @throws If any of the files are considered invalid.\n */\nexport function validateFetchedSnap(\n files: Pick<SnapFiles, 'manifest' | 'sourceCode' | 'svgIcon'>,\n): void {\n assertIsSnapManifest(files.manifest.result);\n validateSnapShasum(files);\n\n if (files.svgIcon) {\n assertIsSnapIcon(files.svgIcon);\n }\n}\n"],"names":["validateFetchedSnap","files","assertIsSnapManifest","manifest","result","validateSnapShasum","svgIcon","assertIsSnapIcon"],"mappings":";;;;+BAWgBA;;;eAAAA;;;sBAXiB;4BACI;uBACF;AAS5B,SAASA,oBACdC,KAA6D;IAE7DC,IAAAA,gCAAoB,EAACD,MAAME,QAAQ,CAACC,MAAM;IAC1CC,IAAAA,yBAAkB,EAACJ;IAEnB,IAAIA,MAAMK,OAAO,EAAE;QACjBC,IAAAA,sBAAgB,EAACN,MAAMK,OAAO;IAChC;AACF"}
@@ -0,0 +1,47 @@
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
+ DEFAULT_REQUESTED_SNAP_VERSION: function() {
13
+ return DEFAULT_REQUESTED_SNAP_VERSION;
14
+ },
15
+ getTargetVersion: function() {
16
+ return getTargetVersion;
17
+ },
18
+ resolveVersionRange: function() {
19
+ return resolveVersionRange;
20
+ }
21
+ });
22
+ const _utils = require("@metamask/utils");
23
+ const _semver = require("semver");
24
+ const _superstruct = require("superstruct");
25
+ const DEFAULT_REQUESTED_SNAP_VERSION = '*';
26
+ function getTargetVersion(versions, versionRange) {
27
+ const maxSatisfyingNonPreRelease = (0, _semver.maxSatisfying)(versions, versionRange);
28
+ // By default don't use pre-release versions
29
+ if (maxSatisfyingNonPreRelease) {
30
+ return maxSatisfyingNonPreRelease;
31
+ }
32
+ // If no satisfying release version is found by default, try pre-release versions
33
+ return (0, _semver.maxSatisfying)(versions, versionRange, {
34
+ includePrerelease: true
35
+ });
36
+ }
37
+ function resolveVersionRange(version) {
38
+ if (version === undefined || version === 'latest') {
39
+ return [
40
+ undefined,
41
+ DEFAULT_REQUESTED_SNAP_VERSION
42
+ ];
43
+ }
44
+ return (0, _superstruct.validate)(version, _utils.VersionRangeStruct);
45
+ }
46
+
47
+ //# sourceMappingURL=versions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/versions.ts"],"sourcesContent":["import {\n Json,\n SemVerVersion,\n SemVerRange,\n VersionRangeStruct,\n} from '@metamask/utils';\nimport { maxSatisfying as maxSatisfyingSemver } from 'semver';\nimport { validate } from 'superstruct';\n\nexport const DEFAULT_REQUESTED_SNAP_VERSION = '*' as SemVerRange;\n\n/**\n * Return the highest version in the list that satisfies the range, or `null` if\n * none of them do. For the satisfaction check, pre-release versions will only\n * be checked if no satisfactory non-prerelease version is found first.\n *\n * @param versions - The list of version to check.\n * @param versionRange - The SemVer version range to check against.\n * @returns The highest version in the list that satisfies the range,\n * or `null` if none of them do.\n */\nexport function getTargetVersion(\n versions: SemVerVersion[],\n versionRange: SemVerRange,\n): SemVerVersion | null {\n const maxSatisfyingNonPreRelease = maxSatisfyingSemver(\n versions,\n versionRange,\n );\n\n // By default don't use pre-release versions\n if (maxSatisfyingNonPreRelease) {\n return maxSatisfyingNonPreRelease;\n }\n\n // If no satisfying release version is found by default, try pre-release versions\n return maxSatisfyingSemver(versions, versionRange, {\n includePrerelease: true,\n });\n}\n\n/**\n * Parse a version received by some subject attempting to access a snap.\n *\n * @param version - The received version value.\n * @returns `*` if the version is `undefined` or `latest\", otherwise returns\n * the specified version.\n */\nexport function resolveVersionRange(\n version?: Json,\n): [error: undefined, range: SemVerRange] | [error: Error, range: undefined] {\n if (version === undefined || version === 'latest') {\n return [undefined, DEFAULT_REQUESTED_SNAP_VERSION];\n }\n return validate(version, VersionRangeStruct);\n}\n"],"names":["DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","resolveVersionRange","versions","versionRange","maxSatisfyingNonPreRelease","maxSatisfyingSemver","includePrerelease","version","undefined","validate","VersionRangeStruct"],"mappings":";;;;;;;;;;;IASaA,8BAA8B;eAA9BA;;IAYGC,gBAAgB;eAAhBA;;IA2BAC,mBAAmB;eAAnBA;;;uBA3CT;wBAC8C;6BAC5B;AAElB,MAAMF,iCAAiC;AAYvC,SAASC,iBACdE,QAAyB,EACzBC,YAAyB;IAEzB,MAAMC,6BAA6BC,IAAAA,qBAAmB,EACpDH,UACAC;IAGF,4CAA4C;IAC5C,IAAIC,4BAA4B;QAC9B,OAAOA;IACT;IAEA,iFAAiF;IACjF,OAAOC,IAAAA,qBAAmB,EAACH,UAAUC,cAAc;QACjDG,mBAAmB;IACrB;AACF;AASO,SAASL,oBACdM,OAAc;IAEd,IAAIA,YAAYC,aAAaD,YAAY,UAAU;QACjD,OAAO;YAACC;YAAWT;SAA+B;IACpD;IACA,OAAOU,IAAAA,qBAAQ,EAACF,SAASG,yBAAkB;AAC7C"}
@@ -0,0 +1,85 @@
1
+ // TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review
2
+ // TODO(ritave): Streaming vfile contents similar to vinyl maybe?
3
+ // TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile
4
+ // similar to unified instead of throwing "ProgrammaticallyFixableErrors".
5
+ //
6
+ // Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.
7
+ // https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because
8
+ // we're calculating checksums based on original path.
9
+ "use strict";
10
+ Object.defineProperty(exports, "__esModule", {
11
+ value: true
12
+ });
13
+ Object.defineProperty(exports, "VirtualFile", {
14
+ enumerable: true,
15
+ get: function() {
16
+ return VirtualFile;
17
+ }
18
+ });
19
+ const _utils = require("@metamask/utils");
20
+ const _deepclone = require("../deep-clone");
21
+ function _define_property(obj, key, value) {
22
+ if (key in obj) {
23
+ Object.defineProperty(obj, key, {
24
+ value: value,
25
+ enumerable: true,
26
+ configurable: true,
27
+ writable: true
28
+ });
29
+ } else {
30
+ obj[key] = value;
31
+ }
32
+ return obj;
33
+ }
34
+ class VirtualFile {
35
+ toString(encoding) {
36
+ if (typeof this.value === 'string') {
37
+ (0, _utils.assert)(encoding === undefined, 'Tried to encode string.');
38
+ return this.value;
39
+ }
40
+ const decoder = new TextDecoder(encoding);
41
+ return decoder.decode(this.value);
42
+ }
43
+ clone() {
44
+ const vfile = new VirtualFile();
45
+ if (typeof this.value === 'string') {
46
+ vfile.value = this.value;
47
+ } else {
48
+ // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array
49
+ vfile.value = this.value.slice(0);
50
+ }
51
+ vfile.result = (0, _deepclone.deepClone)(this.result);
52
+ vfile.data = (0, _deepclone.deepClone)(this.data);
53
+ vfile.path = this.path;
54
+ return vfile;
55
+ }
56
+ constructor(value){
57
+ _define_property(this, "value", void 0);
58
+ _define_property(this, "result", void 0);
59
+ _define_property(this, "data", void 0);
60
+ _define_property(this, "path", void 0);
61
+ let options;
62
+ if (typeof value === 'string' || value instanceof Uint8Array) {
63
+ options = {
64
+ value
65
+ };
66
+ } else {
67
+ options = value;
68
+ }
69
+ this.value = options?.value ?? '';
70
+ // This situations happens when there's no .result used,
71
+ // we expect the file to have default generic in that situation:
72
+ // VirtualFile<unknown> which will handle undefined properly
73
+ //
74
+ // While not 100% type safe, it'll be way less frustrating to work with.
75
+ // The alternative would be to have VirtualFile.result be Result | undefined
76
+ // and that would result in needing to branch out and check in all situations.
77
+ //
78
+ // In short, optimizing for most common use case.
79
+ this.result = options?.result ?? undefined;
80
+ this.data = options?.data ?? {};
81
+ this.path = options?.path ?? '/';
82
+ }
83
+ }
84
+
85
+ //# sourceMappingURL=VirtualFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/virtual-file/VirtualFile.ts"],"sourcesContent":["// TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review\n// TODO(ritave): Streaming vfile contents similar to vinyl maybe?\n// TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile\n// similar to unified instead of throwing \"ProgrammaticallyFixableErrors\".\n//\n// Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.\n// https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because\n// we're calculating checksums based on original path.\nimport { assert } from '@metamask/utils';\n\nimport { deepClone } from '../deep-clone';\n\n/**\n * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.\n *\n * This type can be augmented to register custom `data` types.\n *\n * @example\n * declare module '@metamask/snaps-utils' {\n * interface DataMap {\n * // `file.data.name` is typed as `string`\n * name: string\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface\nexport interface DataMap {}\n\nexport type Value = string | Uint8Array;\nexport type Compatible<Result = unknown> =\n | string\n | Uint8Array\n | Options<Result>;\nexport type Data = Record<string, unknown> & Partial<DataMap>;\nexport type Options<Result = unknown> = {\n value: Value;\n path?: string;\n data?: Data;\n result?: Result;\n};\n\nexport class VirtualFile<Result = unknown> {\n constructor(value?: Compatible<Result>) {\n let options: Options | undefined;\n if (typeof value === 'string' || value instanceof Uint8Array) {\n options = { value };\n } else {\n options = value;\n }\n\n this.value = options?.value ?? '';\n // This situations happens when there's no .result used,\n // we expect the file to have default generic in that situation:\n // VirtualFile<unknown> which will handle undefined properly\n //\n // While not 100% type safe, it'll be way less frustrating to work with.\n // The alternative would be to have VirtualFile.result be Result | undefined\n // and that would result in needing to branch out and check in all situations.\n //\n // In short, optimizing for most common use case.\n this.result = options?.result ?? (undefined as any);\n this.data = options?.data ?? {};\n this.path = options?.path ?? '/';\n }\n\n value: Value;\n\n result: Result;\n\n data: Data;\n\n path: string;\n\n toString(encoding?: string) {\n if (typeof this.value === 'string') {\n assert(encoding === undefined, 'Tried to encode string.');\n return this.value;\n }\n const decoder = new TextDecoder(encoding);\n return decoder.decode(this.value);\n }\n\n clone() {\n const vfile = new VirtualFile<Result>();\n if (typeof this.value === 'string') {\n vfile.value = this.value;\n } else {\n // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array\n vfile.value = this.value.slice(0);\n }\n vfile.result = deepClone(this.result);\n vfile.data = deepClone(this.data);\n vfile.path = this.path;\n return vfile;\n }\n}\n"],"names":["VirtualFile","toString","encoding","value","assert","undefined","decoder","TextDecoder","decode","clone","vfile","slice","result","deepClone","data","path","constructor","options","Uint8Array"],"mappings":"AAAA,0HAA0H;AAC1H,iEAAiE;AACjE,2FAA2F;AAC3F,wFAAwF;AACxF,EAAE;AACF,oHAAoH;AACpH,qGAAqG;AACrG,sDAAsD;;;;;+BAkCzCA;;;eAAAA;;;uBAjCU;2BAEG;;;;;;;;;;;;;;AA+BnB,MAAMA;IAgCXC,SAASC,QAAiB,EAAE;QAC1B,IAAI,OAAO,IAAI,CAACC,KAAK,KAAK,UAAU;YAClCC,IAAAA,aAAM,EAACF,aAAaG,WAAW;YAC/B,OAAO,IAAI,CAACF,KAAK;QACnB;QACA,MAAMG,UAAU,IAAIC,YAAYL;QAChC,OAAOI,QAAQE,MAAM,CAAC,IAAI,CAACL,KAAK;IAClC;IAEAM,QAAQ;QACN,MAAMC,QAAQ,IAAIV;QAClB,IAAI,OAAO,IAAI,CAACG,KAAK,KAAK,UAAU;YAClCO,MAAMP,KAAK,GAAG,IAAI,CAACA,KAAK;QAC1B,OAAO;YACL,mFAAmF;YACnFO,MAAMP,KAAK,GAAG,IAAI,CAACA,KAAK,CAACQ,KAAK,CAAC;QACjC;QACAD,MAAME,MAAM,GAAGC,IAAAA,oBAAS,EAAC,IAAI,CAACD,MAAM;QACpCF,MAAMI,IAAI,GAAGD,IAAAA,oBAAS,EAAC,IAAI,CAACC,IAAI;QAChCJ,MAAMK,IAAI,GAAG,IAAI,CAACA,IAAI;QACtB,OAAOL;IACT;IApDAM,YAAYb,KAA0B,CAAE;QAuBxCA,uBAAAA,SAAAA,KAAAA;QAEAS,uBAAAA,UAAAA,KAAAA;QAEAE,uBAAAA,QAAAA,KAAAA;QAEAC,uBAAAA,QAAAA,KAAAA;QA5BE,IAAIE;QACJ,IAAI,OAAOd,UAAU,YAAYA,iBAAiBe,YAAY;YAC5DD,UAAU;gBAAEd;YAAM;QACpB,OAAO;YACLc,UAAUd;QACZ;QAEA,IAAI,CAACA,KAAK,GAAGc,SAASd,SAAS;QAC/B,wDAAwD;QACxD,gEAAgE;QAChE,4DAA4D;QAC5D,EAAE;QACF,wEAAwE;QACxE,4EAA4E;QAC5E,8EAA8E;QAC9E,EAAE;QACF,iDAAiD;QACjD,IAAI,CAACS,MAAM,GAAGK,SAASL,UAAWP;QAClC,IAAI,CAACS,IAAI,GAAGG,SAASH,QAAQ,CAAC;QAC9B,IAAI,CAACC,IAAI,GAAGE,SAASF,QAAQ;IAC/B;AAgCF"}
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ _export_star(require("./VirtualFile"), exports);
6
+ function _export_star(from, to) {
7
+ Object.keys(from).forEach(function(k) {
8
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
9
+ Object.defineProperty(to, k, {
10
+ enumerable: true,
11
+ get: function() {
12
+ return from[k];
13
+ }
14
+ });
15
+ }
16
+ });
17
+ return from;
18
+ }
19
+
20
+ //# sourceMappingURL=index.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/virtual-file/index.browser.ts"],"sourcesContent":["export * from './VirtualFile';\n"],"names":[],"mappings":";;;;qBAAc"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ _export_star(require("./toVirtualFile"), exports);
6
+ _export_star(require("./VirtualFile"), exports);
7
+ function _export_star(from, to) {
8
+ Object.keys(from).forEach(function(k) {
9
+ if (k !== "default" && !Object.prototype.hasOwnProperty.call(to, k)) {
10
+ Object.defineProperty(to, k, {
11
+ enumerable: true,
12
+ get: function() {
13
+ return from[k];
14
+ }
15
+ });
16
+ }
17
+ });
18
+ return from;
19
+ }
20
+
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/virtual-file/index.ts"],"sourcesContent":["export * from './toVirtualFile';\nexport * from './VirtualFile';\n"],"names":[],"mappings":";;;;qBAAc;qBACA"}
@@ -0,0 +1,33 @@
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
+ readVirtualFile: function() {
13
+ return readVirtualFile;
14
+ },
15
+ writeVirtualFile: function() {
16
+ return writeVirtualFile;
17
+ }
18
+ });
19
+ const _fs = require("fs");
20
+ const _VirtualFile = require("./VirtualFile");
21
+ async function readVirtualFile(path, encoding = null) {
22
+ return new _VirtualFile.VirtualFile({
23
+ path,
24
+ value: await _fs.promises.readFile(path, {
25
+ encoding
26
+ })
27
+ });
28
+ }
29
+ async function writeVirtualFile(vfile, options) {
30
+ return _fs.promises.writeFile(vfile.path, vfile.value, options);
31
+ }
32
+
33
+ //# sourceMappingURL=toVirtualFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/virtual-file/toVirtualFile.ts"],"sourcesContent":["import { promises as fsPromises } from 'fs';\n\nimport { VirtualFile } from './VirtualFile';\n\n/**\n * Reads a file from filesystem and creates a vfile.\n *\n * @param path - Filesystem path to load the contents from.\n * @param encoding - Optional encoding to pass down to fs.readFile.\n * @returns Promise returning VFile with loaded file contents.\n */\nexport async function readVirtualFile(\n path: string,\n encoding: BufferEncoding | null = null,\n) {\n return new VirtualFile({\n path,\n value: await fsPromises.readFile(path, { encoding }),\n });\n}\n\ntype WriteVFileOptions = Exclude<\n Parameters<typeof fsPromises['writeFile']>[2],\n undefined\n>;\n\n/**\n * Writes vfile to filesystem.\n *\n * @param vfile - The vfile to write.\n * @param options - Options to pass down to fs.writeFile.\n */\nexport async function writeVirtualFile(\n vfile: VirtualFile,\n options?: WriteVFileOptions,\n) {\n return fsPromises.writeFile(vfile.path, vfile.value, options);\n}\n"],"names":["readVirtualFile","writeVirtualFile","path","encoding","VirtualFile","value","fsPromises","readFile","vfile","options","writeFile"],"mappings":";;;;;;;;;;;IAWsBA,eAAe;eAAfA;;IAqBAC,gBAAgB;eAAhBA;;;oBAhCiB;6BAEX;AASrB,eAAeD,gBACpBE,IAAY,EACZC,WAAkC,IAAI;IAEtC,OAAO,IAAIC,wBAAW,CAAC;QACrBF;QACAG,OAAO,MAAMC,YAAU,CAACC,QAAQ,CAACL,MAAM;YAAEC;QAAS;IACpD;AACF;AAaO,eAAeF,iBACpBO,KAAkB,EAClBC,OAA2B;IAE3B,OAAOH,YAAU,CAACI,SAAS,CAACF,MAAMN,IAAI,EAAEM,MAAMH,KAAK,EAAEI;AACvD"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Checks if array `a` is equal to array `b`. Note that this does not do a deep
3
+ * equality check. It only checks if the arrays are the same length and if each
4
+ * element in `a` is equal to (`===`) the corresponding element in `b`.
5
+ *
6
+ * @param a - The first array to compare.
7
+ * @param b - The second array to compare.
8
+ * @returns `true` if the arrays are equal, `false` otherwise.
9
+ */ export function isEqual(a, b) {
10
+ return a.length === b.length && a.every((value, index)=>value === b[index]);
11
+ }
12
+
13
+ //# sourceMappingURL=array.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/array.ts"],"sourcesContent":["/**\n * Checks if array `a` is equal to array `b`. Note that this does not do a deep\n * equality check. It only checks if the arrays are the same length and if each\n * element in `a` is equal to (`===`) the corresponding element in `b`.\n *\n * @param a - The first array to compare.\n * @param b - The second array to compare.\n * @returns `true` if the arrays are equal, `false` otherwise.\n */\nexport function isEqual(a: unknown[], b: unknown[]): boolean {\n return a.length === b.length && a.every((value, index) => value === b[index]);\n}\n"],"names":["isEqual","a","b","length","every","value","index"],"mappings":"AAAA;;;;;;;;CAQC,GACD,OAAO,SAASA,QAAQC,CAAY,EAAEC,CAAY;IAChD,OAAOD,EAAEE,MAAM,KAAKD,EAAEC,MAAM,IAAIF,EAAEG,KAAK,CAAC,CAACC,OAAOC,QAAUD,UAAUH,CAAC,CAACI,MAAM;AAC9E"}
@@ -0,0 +1,23 @@
1
+ export var SnapCaveatType;
2
+ (function(SnapCaveatType) {
3
+ SnapCaveatType[/**
4
+ * Permitted derivation paths, used by `snap_getBip32Entropy`.
5
+ */ "PermittedDerivationPaths"] = 'permittedDerivationPaths';
6
+ SnapCaveatType[/**
7
+ * Permitted coin types, used by `snap_getBip44Entropy`.
8
+ */ "PermittedCoinTypes"] = 'permittedCoinTypes';
9
+ SnapCaveatType[/**
10
+ * Caveat specifying a snap cronjob.
11
+ */ "SnapCronjob"] = 'snapCronjob';
12
+ SnapCaveatType[/**
13
+ * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.
14
+ */ "TransactionOrigin"] = 'transactionOrigin';
15
+ SnapCaveatType[/**
16
+ * The origins that a Snap can receive JSON-RPC messages from.
17
+ */ "RpcOrigin"] = 'rpcOrigin';
18
+ SnapCaveatType[/**
19
+ * Caveat specifying the snap IDs that can be interacted with.
20
+ */ "SnapIds"] = 'snapIds';
21
+ })(SnapCaveatType || (SnapCaveatType = {}));
22
+
23
+ //# sourceMappingURL=caveats.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/caveats.ts"],"sourcesContent":["export enum SnapCaveatType {\n /**\n * Permitted derivation paths, used by `snap_getBip32Entropy`.\n */\n PermittedDerivationPaths = 'permittedDerivationPaths',\n\n /**\n * Permitted coin types, used by `snap_getBip44Entropy`.\n */\n PermittedCoinTypes = 'permittedCoinTypes',\n\n /**\n * Caveat specifying a snap cronjob.\n */\n SnapCronjob = 'snapCronjob',\n\n /**\n * Caveat specifying access to the transaction origin, used by `endowment:transaction-insight`.\n */\n TransactionOrigin = 'transactionOrigin',\n\n /**\n * The origins that a Snap can receive JSON-RPC messages from.\n */\n RpcOrigin = 'rpcOrigin',\n\n /**\n * Caveat specifying the snap IDs that can be interacted with.\n */\n SnapIds = 'snapIds',\n}\n"],"names":["SnapCaveatType","PermittedDerivationPaths","PermittedCoinTypes","SnapCronjob","TransactionOrigin","RpcOrigin","SnapIds"],"mappings":"WAAO;UAAKA,cAAc;IAAdA,eACV;;GAEC,GACDC,8BAA2B;IAJjBD,eAMV;;GAEC,GACDE,wBAAqB;IATXF,eAWV;;GAEC,GACDG,iBAAc;IAdJH,eAgBV;;GAEC,GACDI,uBAAoB;IAnBVJ,eAqBV;;GAEC,GACDK,eAAY;IAxBFL,eA0BV;;GAEC,GACDM,aAAU;GA7BAN,mBAAAA"}
@@ -0,0 +1,36 @@
1
+ import { assert, concatBytes } from '@metamask/utils';
2
+ import { sha256 } from '@noble/hashes/sha256';
3
+ import { VirtualFile } from './virtual-file/VirtualFile';
4
+ /**
5
+ * Calculates checksum for a single byte array.
6
+ *
7
+ * @param bytes - The byte array to calculate the checksum for.
8
+ * @returns A single sha-256 checksum.
9
+ */ export function checksum(bytes) {
10
+ const value = bytes instanceof VirtualFile ? bytes.value : bytes;
11
+ return sha256(value);
12
+ }
13
+ /**
14
+ * Calculates checksum over multiple files in a reproducible way.
15
+ *
16
+ * 1. Sort all the files by their paths.
17
+ * 2. Calculate sha-256 checksum of each file separately.
18
+ * 3. Concatenate all the checksums into one buffer and sha-256 that buffer.
19
+ *
20
+ * The sorting of paths is done using {@link https://tc39.es/ecma262/#sec-islessthan UTF-16 Code Units}.
21
+ *
22
+ * @param files - The files over which to calculate the checksum.
23
+ * @returns A single sha-256 checksum.
24
+ */ export function checksumFiles(files) {
25
+ return checksum(concatBytes([
26
+ ...files
27
+ ].sort((a, b)=>{
28
+ assert(a.path !== b.path, 'Tried to sort files with non-unique paths.');
29
+ if (a.path < b.path) {
30
+ return -1;
31
+ }
32
+ return 1;
33
+ }).map((file)=>checksum(file))));
34
+ }
35
+
36
+ //# sourceMappingURL=checksum.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { assert, concatBytes } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport { VirtualFile } from './virtual-file/VirtualFile';\n\n/**\n * Calculates checksum for a single byte array.\n *\n * @param bytes - The byte array to calculate the checksum for.\n * @returns A single sha-256 checksum.\n */\nexport function checksum(bytes: VirtualFile | Uint8Array | string): Uint8Array {\n const value = bytes instanceof VirtualFile ? bytes.value : bytes;\n return sha256(value);\n}\n\n/**\n * Calculates checksum over multiple files in a reproducible way.\n *\n * 1. Sort all the files by their paths.\n * 2. Calculate sha-256 checksum of each file separately.\n * 3. Concatenate all the checksums into one buffer and sha-256 that buffer.\n *\n * The sorting of paths is done using {@link https://tc39.es/ecma262/#sec-islessthan UTF-16 Code Units}.\n *\n * @param files - The files over which to calculate the checksum.\n * @returns A single sha-256 checksum.\n */\nexport function checksumFiles(files: VirtualFile[]) {\n return checksum(\n concatBytes(\n [...files]\n .sort((a, b) => {\n assert(\n a.path !== b.path,\n 'Tried to sort files with non-unique paths.',\n );\n if (a.path < b.path) {\n return -1;\n }\n return 1;\n })\n .map((file) => checksum(file)),\n ),\n );\n}\n"],"names":["assert","concatBytes","sha256","VirtualFile","checksum","bytes","value","checksumFiles","files","sort","a","b","path","map","file"],"mappings":"AAAA,SAASA,MAAM,EAAEC,WAAW,QAAQ,kBAAkB;AACtD,SAASC,MAAM,QAAQ,uBAAuB;AAE9C,SAASC,WAAW,QAAQ,6BAA6B;AAEzD;;;;;CAKC,GACD,OAAO,SAASC,SAASC,KAAwC;IAC/D,MAAMC,QAAQD,iBAAiBF,cAAcE,MAAMC,KAAK,GAAGD;IAC3D,OAAOH,OAAOI;AAChB;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAASC,cAAcC,KAAoB;IAChD,OAAOJ,SACLH,YACE;WAAIO;KAAM,CACPC,IAAI,CAAC,CAACC,GAAGC;QACRX,OACEU,EAAEE,IAAI,KAAKD,EAAEC,IAAI,EACjB;QAEF,IAAIF,EAAEE,IAAI,GAAGD,EAAEC,IAAI,EAAE;YACnB,OAAO,CAAC;QACV;QACA,OAAO;IACT,GACCC,GAAG,CAAC,CAACC,OAASV,SAASU;AAGhC"}
@@ -0,0 +1,66 @@
1
+ import { JsonRpcRequestStruct } from '@metamask/utils';
2
+ import { parseExpression } from 'cron-parser';
3
+ import { array, assign, coerce, create, object, omit, optional, partial, pick, refine, string } from 'superstruct';
4
+ export const CronjobRpcRequestStruct = assign(partial(pick(JsonRpcRequestStruct, [
5
+ 'id',
6
+ 'jsonrpc'
7
+ ])), omit(JsonRpcRequestStruct, [
8
+ 'id',
9
+ 'jsonrpc'
10
+ ]));
11
+ export const CronExpressionStruct = refine(coerce(string(), object({
12
+ minute: optional(string()),
13
+ hour: optional(string()),
14
+ dayOfMonth: optional(string()),
15
+ month: optional(string()),
16
+ dayOfWeek: optional(string())
17
+ }), (value)=>`${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${value.month ?? '*'} ${value.dayOfWeek ?? '*'}`), 'CronExpression', (value)=>{
18
+ try {
19
+ parseExpression(value);
20
+ return true;
21
+ } catch {
22
+ return false;
23
+ }
24
+ });
25
+ /**
26
+ * Parses a cron expression.
27
+ *
28
+ * @param expression - Expression to parse.
29
+ * @returns A CronExpression class instance.
30
+ */ export function parseCronExpression(expression) {
31
+ const ensureStringExpression = create(expression, CronExpressionStruct);
32
+ return parseExpression(ensureStringExpression);
33
+ }
34
+ export const CronjobSpecificationStruct = object({
35
+ expression: CronExpressionStruct,
36
+ request: CronjobRpcRequestStruct
37
+ });
38
+ /**
39
+ * Check if the given value is a {@link CronjobSpecification} object.
40
+ *
41
+ * @param value - The value to check.
42
+ * @returns Whether the value is a valid {@link CronjobSpecification} object.
43
+ */ export function isCronjobSpecification(value) {
44
+ try {
45
+ create(value, CronjobSpecificationStruct);
46
+ return true;
47
+ } catch {
48
+ return false;
49
+ }
50
+ }
51
+ export const CronjobSpecificationArrayStruct = array(CronjobSpecificationStruct);
52
+ /**
53
+ * Check if the given value is an array of {@link CronjobSpecification} objects.
54
+ *
55
+ * @param value - The value to check.
56
+ * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.
57
+ */ export function isCronjobSpecificationArray(value) {
58
+ try {
59
+ create(value, CronjobSpecificationArrayStruct);
60
+ return true;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ //# sourceMappingURL=cronjob.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport {\n array,\n assign,\n coerce,\n create,\n Infer,\n object,\n omit,\n optional,\n partial,\n pick,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["JsonRpcRequestStruct","parseExpression","array","assign","coerce","create","object","omit","optional","partial","pick","refine","string","CronjobRpcRequestStruct","CronExpressionStruct","minute","hour","dayOfMonth","month","dayOfWeek","value","parseCronExpression","expression","ensureStringExpression","CronjobSpecificationStruct","request","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray"],"mappings":"AAAA,SAASA,oBAAoB,QAAQ,kBAAkB;AACvD,SAASC,eAAe,QAAQ,cAAc;AAC9C,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,MAAM,EAENC,MAAM,EACNC,IAAI,EACJC,QAAQ,EACRC,OAAO,EACPC,IAAI,EACJC,MAAM,EACNC,MAAM,QACD,cAAc;AAErB,OAAO,MAAMC,0BAA0BV,OACrCM,QAAQC,KAAKV,sBAAsB;IAAC;IAAM;CAAU,IACpDO,KAAKP,sBAAsB;IAAC;IAAM;CAAU,GAC5C;AAGF,OAAO,MAAMc,uBAAuBH,OAClCP,OACEQ,UACAN,OAAO;IACLS,QAAQP,SAASI;IACjBI,MAAMR,SAASI;IACfK,YAAYT,SAASI;IACrBM,OAAOV,SAASI;IAChBO,WAAWX,SAASI;AACtB,IACA,CAACQ,QACC,CAAC,EAAEA,MAAML,MAAM,IAAI,IAAI,CAAC,EAAEK,MAAMJ,IAAI,IAAI,IAAI,CAAC,EAAEI,MAAMH,UAAU,IAAI,IAAI,CAAC,EACtEG,MAAMF,KAAK,IAAI,IAChB,CAAC,EAAEE,MAAMD,SAAS,IAAI,IAAI,CAAC,GAEhC,kBACA,CAACC;IACC,IAAI;QACFnB,gBAAgBmB;QAChB,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF,GACA;AAIF;;;;;CAKC,GACD,OAAO,SAASC,oBAAoBC,UAA2B;IAC7D,MAAMC,yBAAyBlB,OAAOiB,YAAYR;IAClD,OAAOb,gBAAgBsB;AACzB;AAEA,OAAO,MAAMC,6BAA6BlB,OAAO;IAC/CgB,YAAYR;IACZW,SAASZ;AACX,GAAG;AAGH;;;;;CAKC,GACD,OAAO,SAASa,uBAAuBN,KAAc;IACnD,IAAI;QACFf,OAAOe,OAAOI;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA,OAAO,MAAMG,kCAAkCzB,MAC7CsB,4BACA;AAEF;;;;;CAKC,GACD,OAAO,SAASI,4BAA4BR,KAAc;IACxD,IAAI;QACFf,OAAOe,OAAOO;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
@@ -0,0 +1,7 @@
1
+ import rfdc from 'rfdc';
2
+ export const deepClone = rfdc({
3
+ proto: false,
4
+ circles: false
5
+ });
6
+
7
+ //# sourceMappingURL=deep-clone.js.map