@metamask/snaps-utils 1.0.2 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -223
- package/dist/cjs/array.js +23 -0
- package/dist/cjs/array.js.map +1 -0
- package/dist/cjs/caveats.js +36 -0
- package/dist/cjs/caveats.js.map +1 -0
- package/dist/cjs/checksum.js +38 -0
- package/dist/cjs/checksum.js.map +1 -0
- package/dist/cjs/cronjob.js +84 -0
- package/dist/cjs/cronjob.js.map +1 -0
- package/dist/cjs/deep-clone.js +22 -0
- package/dist/cjs/deep-clone.js.map +1 -0
- package/dist/cjs/default-endowments.js +49 -0
- package/dist/cjs/default-endowments.js.map +1 -0
- package/dist/cjs/entropy.js +23 -0
- package/dist/cjs/entropy.js.map +1 -0
- package/dist/cjs/enum.js +16 -0
- package/dist/cjs/enum.js.map +1 -0
- package/dist/cjs/errors.js +19 -0
- package/dist/cjs/errors.js.map +1 -0
- package/dist/{eval-worker.js → cjs/eval-worker.js} +22 -21
- package/dist/cjs/eval-worker.js.map +1 -0
- package/dist/cjs/eval.js +77 -0
- package/dist/cjs/eval.js.map +1 -0
- package/dist/cjs/fs.js +126 -0
- package/dist/cjs/fs.js.map +1 -0
- package/dist/cjs/handlers.js +80 -0
- package/dist/cjs/handlers.js.map +1 -0
- package/dist/cjs/icon.js +37 -0
- package/dist/cjs/icon.js.map +1 -0
- package/dist/cjs/iframe.js +59 -0
- package/dist/cjs/iframe.js.map +1 -0
- package/dist/cjs/index.browser.js +43 -0
- package/dist/cjs/index.browser.js.map +1 -0
- package/dist/cjs/index.executionenv.js +24 -0
- package/dist/cjs/index.executionenv.js.map +1 -0
- package/dist/cjs/index.js +48 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/json-rpc.js +46 -0
- package/dist/cjs/json-rpc.js.map +1 -0
- package/dist/cjs/json.js +16 -0
- package/dist/cjs/json.js.map +1 -0
- package/dist/cjs/logging.js +40 -0
- package/dist/cjs/logging.js.map +1 -0
- package/dist/cjs/manifest/index.browser.js +20 -0
- package/dist/cjs/manifest/index.browser.js.map +1 -0
- package/dist/cjs/manifest/index.js +21 -0
- package/dist/cjs/manifest/index.js.map +1 -0
- package/dist/cjs/manifest/manifest.js +239 -0
- package/dist/cjs/manifest/manifest.js.map +1 -0
- package/dist/cjs/manifest/validation.js +189 -0
- package/dist/cjs/manifest/validation.js.map +1 -0
- package/dist/cjs/mock.js +128 -0
- package/dist/cjs/mock.js.map +1 -0
- package/dist/cjs/namespace.js +132 -0
- package/dist/cjs/namespace.js.map +1 -0
- package/dist/cjs/npm.js +81 -0
- package/dist/cjs/npm.js.map +1 -0
- package/dist/cjs/path.js +21 -0
- package/dist/cjs/path.js.map +1 -0
- package/dist/cjs/post-process.js +328 -0
- package/dist/cjs/post-process.js.map +1 -0
- package/dist/cjs/snaps.js +230 -0
- package/dist/cjs/snaps.js.map +1 -0
- package/dist/cjs/strings.js +21 -0
- package/dist/cjs/strings.js.map +1 -0
- package/dist/cjs/structs.js +163 -0
- package/dist/cjs/structs.js.map +1 -0
- package/dist/cjs/types.js +109 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/cjs/validation.js +22 -0
- package/dist/cjs/validation.js.map +1 -0
- package/dist/cjs/versions.js +47 -0
- package/dist/cjs/versions.js.map +1 -0
- package/dist/cjs/virtual-file/VirtualFile.js +85 -0
- package/dist/cjs/virtual-file/VirtualFile.js.map +1 -0
- package/dist/cjs/virtual-file/index.browser.js +20 -0
- package/dist/cjs/virtual-file/index.browser.js.map +1 -0
- package/dist/cjs/virtual-file/index.js +21 -0
- package/dist/cjs/virtual-file/index.js.map +1 -0
- package/dist/cjs/virtual-file/toVirtualFile.js +33 -0
- package/dist/cjs/virtual-file/toVirtualFile.js.map +1 -0
- package/dist/{array.js → esm/array.js} +3 -7
- package/dist/esm/array.js.map +1 -0
- package/dist/esm/caveats.js +26 -0
- package/dist/esm/caveats.js.map +1 -0
- package/dist/esm/checksum.js +36 -0
- package/dist/esm/checksum.js.map +1 -0
- package/dist/esm/cronjob.js +66 -0
- package/dist/esm/cronjob.js.map +1 -0
- package/dist/esm/deep-clone.js +7 -0
- package/dist/esm/deep-clone.js.map +1 -0
- package/dist/{default-endowments.js → esm/default-endowments.js} +3 -6
- package/dist/esm/default-endowments.js.map +1 -0
- package/dist/esm/entropy.js +6 -0
- package/dist/esm/entropy.js.map +1 -0
- package/dist/esm/enum.js +12 -0
- package/dist/esm/enum.js.map +1 -0
- package/dist/esm/errors.js +17 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/eval-worker.js +47 -0
- package/dist/esm/eval-worker.js.map +1 -0
- package/dist/esm/eval.js +65 -0
- package/dist/esm/eval.js.map +1 -0
- package/dist/{fs.js → esm/fs.js} +33 -56
- package/dist/esm/fs.js.map +1 -0
- package/dist/esm/handlers.js +59 -0
- package/dist/esm/handlers.js.map +1 -0
- package/dist/esm/icon.js +11 -0
- package/dist/esm/icon.js.map +1 -0
- package/dist/{iframe.js → esm/iframe.js} +16 -18
- package/dist/esm/iframe.js.map +1 -0
- package/dist/esm/index.browser.js +26 -0
- package/dist/esm/index.browser.js.map +1 -0
- package/dist/esm/index.executionenv.js +7 -0
- package/dist/esm/index.executionenv.js.map +1 -0
- package/dist/esm/index.js +31 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/json-rpc.js +39 -0
- package/dist/esm/json-rpc.js.map +1 -0
- package/dist/esm/json.js +17 -0
- package/dist/esm/json.js.map +1 -0
- package/dist/{logging.js → esm/logging.js} +6 -14
- package/dist/esm/logging.js.map +1 -0
- package/dist/esm/manifest/index.browser.js +3 -0
- package/dist/esm/manifest/index.browser.js.map +1 -0
- package/dist/esm/manifest/index.js +4 -0
- package/dist/esm/manifest/index.js.map +1 -0
- package/dist/{manifest → esm/manifest}/manifest.js +101 -115
- package/dist/esm/manifest/manifest.js.map +1 -0
- package/dist/esm/manifest/validation.js +155 -0
- package/dist/esm/manifest/validation.js.map +1 -0
- package/dist/{mock.js → esm/mock.js} +42 -40
- package/dist/esm/mock.js.map +1 -0
- package/dist/esm/namespace.js +112 -0
- package/dist/esm/namespace.js.map +1 -0
- package/dist/esm/npm.js +70 -0
- package/dist/esm/npm.js.map +1 -0
- package/dist/esm/path.js +17 -0
- package/dist/esm/path.js.map +1 -0
- package/dist/{post-process.js → esm/post-process.js} +110 -99
- package/dist/esm/post-process.js.map +1 -0
- package/dist/esm/snaps.js +215 -0
- package/dist/esm/snaps.js.map +1 -0
- package/dist/esm/strings.js +11 -0
- package/dist/esm/strings.js.map +1 -0
- package/dist/esm/structs.js +230 -0
- package/dist/esm/structs.js.map +1 -0
- package/dist/esm/types.js +80 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/validation.js +17 -0
- package/dist/esm/validation.js.map +1 -0
- package/dist/{versions.js → esm/versions.js} +15 -18
- package/dist/esm/versions.js.map +1 -0
- package/dist/{virtual-file → esm/virtual-file}/VirtualFile.js +47 -33
- package/dist/esm/virtual-file/VirtualFile.js.map +1 -0
- package/dist/esm/virtual-file/index.browser.js +3 -0
- package/dist/esm/virtual-file/index.browser.js.map +1 -0
- package/dist/esm/virtual-file/index.js +4 -0
- package/dist/esm/virtual-file/index.js.map +1 -0
- package/dist/esm/virtual-file/toVirtualFile.js +26 -0
- package/dist/esm/virtual-file/toVirtualFile.js.map +1 -0
- package/dist/{caveats.d.ts → types/caveats.d.ts} +5 -5
- package/dist/{cronjob.d.ts → types/cronjob.d.ts} +1 -1
- package/dist/types/enum.d.ts +30 -0
- package/dist/types/errors.d.ts +10 -0
- package/dist/{eval.d.ts → types/eval.d.ts} +9 -1
- package/dist/{fs.d.ts → types/fs.d.ts} +2 -2
- package/dist/types/handlers.d.ts +196 -0
- package/dist/types/icon.d.ts +4 -0
- package/dist/{iframe.d.ts → types/iframe.d.ts} +3 -2
- package/dist/{index.browser.d.ts → types/index.browser.d.ts} +5 -1
- package/dist/{index.d.ts → types/index.d.ts} +5 -1
- package/dist/{json-rpc.d.ts → types/json-rpc.d.ts} +2 -2
- package/dist/types/json.d.ts +13 -0
- package/dist/{manifest → types/manifest}/manifest.d.ts +6 -4
- package/dist/{manifest → types/manifest}/validation.d.ts +40 -76
- package/dist/types/namespace.d.ts +128 -0
- package/dist/{npm.d.ts → types/npm.d.ts} +2 -3
- package/dist/{snaps.d.ts → types/snaps.d.ts} +17 -9
- package/dist/types/strings.d.ts +8 -0
- package/dist/types/structs.d.ts +158 -0
- package/dist/{types.d.ts → types/types.d.ts} +15 -22
- package/dist/types/validation.d.ts +8 -0
- package/dist/{versions.d.ts → types/versions.d.ts} +1 -1
- package/package.json +66 -46
- package/dist/array.js.map +0 -1
- package/dist/caveats.js +0 -35
- package/dist/caveats.js.map +0 -1
- package/dist/checksum.js +0 -42
- package/dist/checksum.js.map +0 -1
- package/dist/cronjob.js +0 -71
- package/dist/cronjob.js.map +0 -1
- package/dist/deep-clone.js +0 -9
- package/dist/deep-clone.js.map +0 -1
- package/dist/default-endowments.js.map +0 -1
- package/dist/entropy.js +0 -8
- package/dist/entropy.js.map +0 -1
- package/dist/eval-worker.js.map +0 -1
- package/dist/eval.js +0 -27
- package/dist/eval.js.map +0 -1
- package/dist/fs.js.map +0 -1
- package/dist/handlers.d.ts +0 -105
- package/dist/handlers.js +0 -3
- package/dist/handlers.js.map +0 -1
- package/dist/iframe.js.map +0 -1
- package/dist/iframe.test.browser.js +0 -15
- package/dist/iframe.test.browser.js.map +0 -1
- package/dist/index.browser.js +0 -37
- package/dist/index.browser.js.map +0 -1
- package/dist/index.executionenv.js +0 -22
- package/dist/index.executionenv.js.map +0 -1
- package/dist/index.js +0 -42
- package/dist/index.js.map +0 -1
- package/dist/json-rpc.js +0 -46
- package/dist/json-rpc.js.map +0 -1
- package/dist/json.d.ts +0 -9
- package/dist/json.js +0 -18
- package/dist/json.js.map +0 -1
- package/dist/logging.js.map +0 -1
- package/dist/manifest/index.browser.js +0 -18
- package/dist/manifest/index.browser.js.map +0 -1
- package/dist/manifest/index.js +0 -19
- package/dist/manifest/index.js.map +0 -1
- package/dist/manifest/manifest.js.map +0 -1
- package/dist/manifest/validation.js +0 -141
- package/dist/manifest/validation.js.map +0 -1
- package/dist/mock.js.map +0 -1
- package/dist/namespace.d.ts +0 -275
- package/dist/namespace.js +0 -225
- package/dist/namespace.js.map +0 -1
- package/dist/notification.d.ts +0 -66
- package/dist/notification.js +0 -58
- package/dist/notification.js.map +0 -1
- package/dist/npm.js +0 -74
- package/dist/npm.js.map +0 -1
- package/dist/path.js +0 -21
- package/dist/path.js.map +0 -1
- package/dist/post-process.js.map +0 -1
- package/dist/snaps.js +0 -202
- package/dist/snaps.js.map +0 -1
- package/dist/types.js +0 -103
- package/dist/types.js.map +0 -1
- package/dist/versions.js.map +0 -1
- package/dist/virtual-file/VirtualFile.js.map +0 -1
- package/dist/virtual-file/index.browser.js +0 -18
- package/dist/virtual-file/index.browser.js.map +0 -1
- package/dist/virtual-file/index.js +0 -19
- package/dist/virtual-file/index.js.map +0 -1
- package/dist/virtual-file/toVirtualFile.js +0 -30
- package/dist/virtual-file/toVirtualFile.js.map +0 -1
- /package/dist/{array.d.ts → types/array.d.ts} +0 -0
- /package/dist/{checksum.d.ts → types/checksum.d.ts} +0 -0
- /package/dist/{deep-clone.d.ts → types/deep-clone.d.ts} +0 -0
- /package/dist/{default-endowments.d.ts → types/default-endowments.d.ts} +0 -0
- /package/dist/{entropy.d.ts → types/entropy.d.ts} +0 -0
- /package/dist/{eval-worker.d.ts → types/eval-worker.d.ts} +0 -0
- /package/dist/{iframe.test.browser.d.ts → types/iframe.test.browser.d.ts} +0 -0
- /package/dist/{index.executionenv.d.ts → types/index.executionenv.d.ts} +0 -0
- /package/dist/{logging.d.ts → types/logging.d.ts} +0 -0
- /package/dist/{manifest → types/manifest}/index.browser.d.ts +0 -0
- /package/dist/{manifest → types/manifest}/index.d.ts +0 -0
- /package/dist/{mock.d.ts → types/mock.d.ts} +0 -0
- /package/dist/{path.d.ts → types/path.d.ts} +0 -0
- /package/dist/{post-process.d.ts → types/post-process.d.ts} +0 -0
- /package/dist/{virtual-file → types/virtual-file}/VirtualFile.d.ts +0 -0
- /package/dist/{virtual-file → types/virtual-file}/index.browser.d.ts +0 -0
- /package/dist/{virtual-file → types/virtual-file}/index.d.ts +0 -0
- /package/dist/{virtual-file → types/virtual-file}/toVirtualFile.d.ts +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/snaps.ts"],"sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { Json, SemVerVersion, Opaque } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport type { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes';\nimport stableStringify from 'fast-json-stable-stringify';\nimport type { Struct } from 'superstruct';\nimport {\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from 'superstruct';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { SnapManifest, SnapPermissions } from './manifest/validation';\nimport type { SnapFiles, SnapId, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, SnapValidationFailureReason, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\n/**\n * wallet_enable / wallet_installSnaps permission typing.\n *\n * @deprecated This type is confusing and not descriptive, people confused it with typing initialPermissions, remove when removing wallet_enable.\n */\nexport type RequestedSnapPermissions = {\n [permission: string]: Record<string, Json>;\n};\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: ValidatedSnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = {\n /**\n * Whether the Snap is enabled, which determines if it can be started.\n */\n enabled: boolean;\n\n /**\n * The ID of the Snap.\n */\n id: ValidatedSnapId;\n\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Whether the Snap is blocked.\n */\n blocked: boolean;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version of the Snap.\n */\n version: SemVerVersion;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n};\n\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":";;;;;;;;;;;;;;;;;IAyCaA,mBAAmB;eAAnBA;;IA4HAC,gCAAgC;eAAhCA;;IAiCGC,e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ACrED;AAGN;AASO,SAAS5E,gBACd8E,WAAqD,EACrDV,MAAc;IAEd,OAAOW,QAEH,AACGD,CAAAA,aAAaE,aAAaC,SAAST,KAClC,CAACU,SAAWA,OAAOC,IAAI,KAAKC,uBAAc,CAACC,OAAO,KAC/C,CAAC,CAAA,EACN7D,KAAK,EACN,CAAC4C,OAAO;AAEf;AASO,SAASnE,+BACdqF,oBAA6B;IAE7BpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACD,uBACT;IAGF,MAAM,EAAEN,aAAaQ,oBAAoB,EAAE,GAAGF;IAE9CpB,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACC,uBACT;IAGF,MAAM,EAAEP,OAAO,EAAE,GAAGO;IAEpBtB,IAAAA,aAAM,EACJuB,MAAMC,OAAO,CAACT,YAAYA,QAAQzB,MAAM,KAAK,GAC7C;IAGF,MAAM,CAAC0B,OAAO,GAAGD;IAEjBf,IAAAA,aAAM,EACJqB,IAAAA,eAAQ,EAACL,WACPA,OAAOC,IAAI,KAAKC,uBAAc,CAACC,OAAO,IACtCE,IAAAA,eAAQ,EAACL,OAAO1D,KAAK,GACvB,CAAC,8CAA8C,EAAE4D,uBAAc,CAACC,OAAO,CAAC,QAAQ,CAAC;AAErF"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Indent a message by adding a number of spaces to the beginning of each line.
|
|
3
|
+
*
|
|
4
|
+
* @param message - The message to indent.
|
|
5
|
+
* @param spaces - The number of spaces to indent by. Defaults to 2.
|
|
6
|
+
* @returns The indented message.
|
|
7
|
+
*/ "use strict";
|
|
8
|
+
Object.defineProperty(exports, "__esModule", {
|
|
9
|
+
value: true
|
|
10
|
+
});
|
|
11
|
+
Object.defineProperty(exports, "indent", {
|
|
12
|
+
enumerable: true,
|
|
13
|
+
get: function() {
|
|
14
|
+
return indent;
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
function indent(message, spaces = 2) {
|
|
18
|
+
return message.replace(/^/gmu, ' '.repeat(spaces));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=strings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/strings.ts"],"sourcesContent":["/**\n * Indent a message by adding a number of spaces to the beginning of each line.\n *\n * @param message - The message to indent.\n * @param spaces - The number of spaces to indent by. Defaults to 2.\n * @returns The indented message.\n */\nexport function indent(message: string, spaces = 2) {\n return message.replace(/^/gmu, ' '.repeat(spaces));\n}\n"],"names":["indent","message","spaces","replace","repeat"],"mappings":"AAAA;;;;;;CAMC;;;;+BACeA;;;eAAAA;;;AAAT,SAASA,OAAOC,OAAe,EAAEC,SAAS,CAAC;IAChD,OAAOD,QAAQE,OAAO,CAAC,QAAQ,IAAIC,MAAM,CAACF;AAC5C"}
|
|
@@ -0,0 +1,163 @@
|
|
|
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
|
+
literal: function() {
|
|
13
|
+
return literal;
|
|
14
|
+
},
|
|
15
|
+
union: function() {
|
|
16
|
+
return union;
|
|
17
|
+
},
|
|
18
|
+
file: function() {
|
|
19
|
+
return file;
|
|
20
|
+
},
|
|
21
|
+
named: function() {
|
|
22
|
+
return named;
|
|
23
|
+
},
|
|
24
|
+
SnapsStructError: function() {
|
|
25
|
+
return SnapsStructError;
|
|
26
|
+
},
|
|
27
|
+
arrayToGenerator: function() {
|
|
28
|
+
return arrayToGenerator;
|
|
29
|
+
},
|
|
30
|
+
getError: function() {
|
|
31
|
+
return getError;
|
|
32
|
+
},
|
|
33
|
+
createFromStruct: function() {
|
|
34
|
+
return createFromStruct;
|
|
35
|
+
},
|
|
36
|
+
getStructFromPath: function() {
|
|
37
|
+
return getStructFromPath;
|
|
38
|
+
},
|
|
39
|
+
getUnionStructNames: function() {
|
|
40
|
+
return getUnionStructNames;
|
|
41
|
+
},
|
|
42
|
+
getStructErrorPrefix: function() {
|
|
43
|
+
return getStructErrorPrefix;
|
|
44
|
+
},
|
|
45
|
+
getStructFailureMessage: function() {
|
|
46
|
+
return getStructFailureMessage;
|
|
47
|
+
},
|
|
48
|
+
getStructErrorMessage: function() {
|
|
49
|
+
return getStructErrorMessage;
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
const _utils = require("@metamask/utils");
|
|
53
|
+
const _chalk = require("chalk");
|
|
54
|
+
const _path = require("path");
|
|
55
|
+
const _superstruct = require("superstruct");
|
|
56
|
+
const _strings = require("./strings");
|
|
57
|
+
function literal(value) {
|
|
58
|
+
return (0, _superstruct.define)(JSON.stringify(value), (0, _superstruct.literal)(value).validator);
|
|
59
|
+
}
|
|
60
|
+
function union([head, ...tail]) {
|
|
61
|
+
const struct = (0, _superstruct.union)([
|
|
62
|
+
head,
|
|
63
|
+
...tail
|
|
64
|
+
]);
|
|
65
|
+
return new _superstruct.Struct({
|
|
66
|
+
...struct,
|
|
67
|
+
schema: [
|
|
68
|
+
head,
|
|
69
|
+
...tail
|
|
70
|
+
]
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
function file() {
|
|
74
|
+
return (0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.string)(), (value)=>{
|
|
75
|
+
return (0, _path.resolve)(process.cwd(), value);
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
function named(name, struct) {
|
|
79
|
+
return new _superstruct.Struct({
|
|
80
|
+
...struct,
|
|
81
|
+
type: name
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
class SnapsStructError extends _superstruct.StructError {
|
|
85
|
+
constructor(struct, prefix, suffix, failure, failures){
|
|
86
|
+
super(failure, failures);
|
|
87
|
+
this.name = 'SnapsStructError';
|
|
88
|
+
this.message = `${prefix}.\n\n${getStructErrorMessage(struct, [
|
|
89
|
+
...failures()
|
|
90
|
+
])}${suffix ? `\n\n${suffix}` : ''}`;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function* arrayToGenerator(array) {
|
|
94
|
+
for (const item of array){
|
|
95
|
+
yield item;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function getError({ struct, prefix, suffix = '', error }) {
|
|
99
|
+
return new SnapsStructError(struct, prefix, suffix, error, ()=>arrayToGenerator(error.failures()));
|
|
100
|
+
}
|
|
101
|
+
function createFromStruct(value, struct, prefix, suffix = '') {
|
|
102
|
+
try {
|
|
103
|
+
return (0, _superstruct.create)(value, struct);
|
|
104
|
+
} catch (error) {
|
|
105
|
+
if (error instanceof _superstruct.StructError) {
|
|
106
|
+
throw getError({
|
|
107
|
+
struct,
|
|
108
|
+
prefix,
|
|
109
|
+
suffix,
|
|
110
|
+
error
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function getStructFromPath(struct, path) {
|
|
117
|
+
return path.reduce((result, key)=>{
|
|
118
|
+
if ((0, _utils.isObject)(struct.schema) && struct.schema[key]) {
|
|
119
|
+
return struct.schema[key];
|
|
120
|
+
}
|
|
121
|
+
return result;
|
|
122
|
+
}, struct);
|
|
123
|
+
}
|
|
124
|
+
function getUnionStructNames(struct) {
|
|
125
|
+
if (Array.isArray(struct.schema)) {
|
|
126
|
+
return struct.schema.map(({ type })=>(0, _chalk.green)(type));
|
|
127
|
+
}
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
function getStructErrorPrefix(failure) {
|
|
131
|
+
if (failure.type === 'never' || failure.path.length === 0) {
|
|
132
|
+
return '';
|
|
133
|
+
}
|
|
134
|
+
return `At path: ${(0, _chalk.bold)(failure.path.join('.'))} — `;
|
|
135
|
+
}
|
|
136
|
+
function getStructFailureMessage(struct, failure) {
|
|
137
|
+
const received = (0, _chalk.red)(JSON.stringify(failure.value));
|
|
138
|
+
const prefix = getStructErrorPrefix(failure);
|
|
139
|
+
if (failure.type === 'union') {
|
|
140
|
+
const childStruct = getStructFromPath(struct, failure.path);
|
|
141
|
+
const unionNames = getUnionStructNames(childStruct);
|
|
142
|
+
if (unionNames) {
|
|
143
|
+
return `${prefix}Expected the value to be one of: ${unionNames.join(', ')}, but received: ${received}.`;
|
|
144
|
+
}
|
|
145
|
+
return `${prefix}${failure.message}.`;
|
|
146
|
+
}
|
|
147
|
+
if (failure.type === 'literal') {
|
|
148
|
+
// Superstruct's failure does not provide information about which literal
|
|
149
|
+
// value was expected, so we need to parse the message to get the literal.
|
|
150
|
+
const message = failure.message.replace(/the literal `(.+)`,/u, `the value to be \`${(0, _chalk.green)('$1')}\`,`).replace(/, but received: (.+)/u, `, but received: ${(0, _chalk.red)('$1')}`);
|
|
151
|
+
return `${prefix}${message}.`;
|
|
152
|
+
}
|
|
153
|
+
if (failure.type === 'never') {
|
|
154
|
+
return `Unknown key: ${(0, _chalk.bold)(failure.path.join('.'))}, received: ${received}.`;
|
|
155
|
+
}
|
|
156
|
+
return `${prefix}Expected a value of type ${(0, _chalk.green)(failure.type)}, but received: ${received}.`;
|
|
157
|
+
}
|
|
158
|
+
function getStructErrorMessage(struct, failures) {
|
|
159
|
+
const formattedFailures = failures.map((failure)=>(0, _strings.indent)(`• ${getStructFailureMessage(struct, failure)}`));
|
|
160
|
+
return formattedFailures.join('\n');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
//# sourceMappingURL=structs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["literal","union","file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","value","define","JSON","stringify","superstructLiteral","validator","head","tail","struct","superstructUnion","Struct","schema","coerce","string","resolve","process","cwd","name","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","Array","isArray","map","green","length","bold","join","received","red","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAuCgBA,OAAO;eAAPA;;IAmBAC,KAAK;eAALA;;IAkCAC,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAoBAC,mBAAmB;eAAnBA;;IAiBAC,oBAAoB;eAApBA;;IAiBAC,uBAAuB;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, "__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
|
+
NameStruct: function() {
|
|
25
|
+
return NameStruct;
|
|
26
|
+
},
|
|
27
|
+
NpmSnapPackageJsonStruct: function() {
|
|
28
|
+
return NpmSnapPackageJsonStruct;
|
|
29
|
+
},
|
|
30
|
+
isNpmSnapPackageJson: function() {
|
|
31
|
+
return isNpmSnapPackageJson;
|
|
32
|
+
},
|
|
33
|
+
assertIsNpmSnapPackageJson: function() {
|
|
34
|
+
return assertIsNpmSnapPackageJson;
|
|
35
|
+
},
|
|
36
|
+
SNAP_EXPORT_NAMES: function() {
|
|
37
|
+
return SNAP_EXPORT_NAMES;
|
|
38
|
+
},
|
|
39
|
+
uri: function() {
|
|
40
|
+
return uri;
|
|
41
|
+
},
|
|
42
|
+
isValidUrl: function() {
|
|
43
|
+
return isValidUrl;
|
|
44
|
+
},
|
|
45
|
+
WALLET_SNAP_PERMISSION_KEY: function() {
|
|
46
|
+
return WALLET_SNAP_PERMISSION_KEY;
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
const _utils = require("@metamask/utils");
|
|
50
|
+
const _superstruct = require("superstruct");
|
|
51
|
+
const _handlers = require("./handlers");
|
|
52
|
+
var NpmSnapFileNames;
|
|
53
|
+
(function(NpmSnapFileNames) {
|
|
54
|
+
NpmSnapFileNames["PackageJson"] = 'package.json';
|
|
55
|
+
NpmSnapFileNames["Manifest"] = 'snap.manifest.json';
|
|
56
|
+
})(NpmSnapFileNames || (NpmSnapFileNames = {}));
|
|
57
|
+
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);
|
|
58
|
+
const NpmSnapPackageJsonStruct = (0, _superstruct.type)({
|
|
59
|
+
version: _utils.VersionStruct,
|
|
60
|
+
name: NameStruct,
|
|
61
|
+
main: (0, _superstruct.optional)((0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)),
|
|
62
|
+
repository: (0, _superstruct.optional)((0, _superstruct.object)({
|
|
63
|
+
type: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity),
|
|
64
|
+
url: (0, _superstruct.size)((0, _superstruct.string)(), 1, Infinity)
|
|
65
|
+
}))
|
|
66
|
+
});
|
|
67
|
+
function isNpmSnapPackageJson(value) {
|
|
68
|
+
return (0, _superstruct.is)(value, NpmSnapPackageJsonStruct);
|
|
69
|
+
}
|
|
70
|
+
function assertIsNpmSnapPackageJson(value) {
|
|
71
|
+
(0, _utils.assertStruct)(value, NpmSnapPackageJsonStruct, `"${NpmSnapFileNames.PackageJson}" is invalid`);
|
|
72
|
+
}
|
|
73
|
+
var SnapIdPrefixes;
|
|
74
|
+
(function(SnapIdPrefixes) {
|
|
75
|
+
SnapIdPrefixes["npm"] = 'npm:';
|
|
76
|
+
SnapIdPrefixes["local"] = 'local:';
|
|
77
|
+
})(SnapIdPrefixes || (SnapIdPrefixes = {}));
|
|
78
|
+
var SnapValidationFailureReason;
|
|
79
|
+
(function(SnapValidationFailureReason) {
|
|
80
|
+
SnapValidationFailureReason["NameMismatch"] = '"name" field mismatch';
|
|
81
|
+
SnapValidationFailureReason["VersionMismatch"] = '"version" field mismatch';
|
|
82
|
+
SnapValidationFailureReason["RepositoryMismatch"] = '"repository" field mismatch';
|
|
83
|
+
SnapValidationFailureReason["ShasumMismatch"] = '"shasum" field mismatch';
|
|
84
|
+
})(SnapValidationFailureReason || (SnapValidationFailureReason = {}));
|
|
85
|
+
var SNAP_STREAM_NAMES;
|
|
86
|
+
(function(SNAP_STREAM_NAMES) {
|
|
87
|
+
SNAP_STREAM_NAMES["JSON_RPC"] = 'jsonRpc';
|
|
88
|
+
SNAP_STREAM_NAMES["COMMAND"] = 'command';
|
|
89
|
+
})(SNAP_STREAM_NAMES || (SNAP_STREAM_NAMES = {}));
|
|
90
|
+
const SNAP_EXPORT_NAMES = Object.values(_handlers.HandlerType);
|
|
91
|
+
const uri = (opts = {})=>(0, _superstruct.refine)((0, _superstruct.union)([
|
|
92
|
+
(0, _superstruct.string)(),
|
|
93
|
+
(0, _superstruct.instance)(URL)
|
|
94
|
+
]), 'uri', (value)=>{
|
|
95
|
+
try {
|
|
96
|
+
const url = new URL(value);
|
|
97
|
+
const UrlStruct = (0, _superstruct.type)(opts);
|
|
98
|
+
(0, _superstruct.assert)(url, UrlStruct);
|
|
99
|
+
return true;
|
|
100
|
+
} catch {
|
|
101
|
+
return `Expected URL, got "${value.toString()}".`;
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
function isValidUrl(url, opts = {}) {
|
|
105
|
+
return (0, _superstruct.is)(url, uri(opts));
|
|
106
|
+
}
|
|
107
|
+
const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';
|
|
108
|
+
|
|
109
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/types.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { assertStruct, VersionStruct } from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n instance,\n is,\n object,\n optional,\n pattern,\n refine,\n size,\n string,\n type,\n union,\n assert as assertSuperstruct,\n} from 'superstruct';\n\nimport type { SnapCaveatType } from './caveats';\nimport type { SnapFunctionExports } from './handlers';\nimport { HandlerType } from './handlers';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport enum NpmSnapFileNames {\n PackageJson = 'package.json',\n Manifest = 'snap.manifest.json',\n}\n\nexport const NameStruct = size(\n pattern(\n string(),\n /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\\/)?[a-z0-9-~][a-z0-9-._~]*$/u,\n ),\n 1,\n 214,\n);\n\n// Note we use `type` instead of `object` here, because the latter does not\n// allow unknown keys.\nexport const NpmSnapPackageJsonStruct = type({\n version: VersionStruct,\n name: NameStruct,\n main: optional(size(string(), 1, Infinity)),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n});\n\nexport type NpmSnapPackageJson = Infer<typeof NpmSnapPackageJsonStruct> &\n Record<string, any>;\n\n/**\n * Check if the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link NpmSnapPackageJson} object.\n */\nexport function isNpmSnapPackageJson(\n value: unknown,\n): value is NpmSnapPackageJson {\n return is(value, NpmSnapPackageJsonStruct);\n}\n\n/**\n * Asserts that the given value is a valid {@link NpmSnapPackageJson} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link NpmSnapPackageJson} object.\n */\nexport function assertIsNpmSnapPackageJson(\n value: unknown,\n): asserts value is NpmSnapPackageJson {\n assertStruct(\n value,\n NpmSnapPackageJsonStruct,\n `\"${NpmSnapFileNames.PackageJson}\" is invalid`,\n );\n}\n\n/**\n * An object for storing parsed but unvalidated Snap file contents.\n */\nexport type UnvalidatedSnapFiles = {\n manifest?: VirtualFile<Json>;\n packageJson?: VirtualFile<Json>;\n sourceCode?: VirtualFile;\n svgIcon?: VirtualFile;\n};\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 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<Type extends string> = {\n protocol?: Struct<Type>;\n hash?: Struct<Type>;\n port?: Struct<Type>;\n hostname?: Struct<Type>;\n pathname?: Struct<Type>;\n search?: Struct<Type>;\n};\n\nexport const uri = (opts: UriOptions<any> = {}) =>\n refine(union([string(), instance(URL)]), 'uri', (value) => {\n try {\n const url = new URL(value);\n\n const UrlStruct = type(opts);\n assertSuperstruct(url, UrlStruct);\n return true;\n } catch {\n return `Expected URL, got \"${value.toString()}\".`;\n }\n });\n\n/**\n * Returns whether a given value is a valid URL.\n *\n * @param url - The value to check.\n * @param opts - Optional constraints for url checking.\n * @returns Whether `url` is valid URL or not.\n */\nexport function isValidUrl(\n url: unknown,\n opts: UriOptions<any> = {},\n): url is string | URL {\n return is(url, uri(opts));\n}\n\n// redefining here to avoid circular dependency\nexport const WALLET_SNAP_PERMISSION_KEY = 'wallet_snap';\n\nexport type SnapsPermissionRequest = {\n [WALLET_SNAP_PERMISSION_KEY]: {\n caveats: [\n {\n type: SnapCaveatType.SnapIds;\n value: Record<string, Json>;\n },\n ];\n };\n};\n"],"names":["NameStruct","NpmSnapPackageJsonStruct","isNpmSnapPackageJson","assertIsNpmSnapPackageJson","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","Object","values","HandlerType","opts","refine","union","instance","URL","UrlStruct","assertSuperstruct","toString"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;IA4BaA,UAAU;eAAVA;;IAWAC,wBAAwB;eAAxBA;;IAqBGC,oBAAoB;eAApBA;;IAYAC,0BAA0B;eAA1BA;;IA6DHC,iBAAiB;eAAjBA;;IA0BAC,GAAG;eAAHA;;IAoBGC,UAAU;eAAVA;;IAQHC,0BAA0B;eAA1BA;;;uBA1L+B;6BAcrC;0BAIqB;IAIrB;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,IAA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AAwB,CAAC,CAAC;IAE1B,OAAOhB,IAAAA,eAAE,EAACF,KAAKlB,IAAIoC;AACrB;AAGO,MAAMlC,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 type { 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 type { Json, SemVerVersion, SemVerRange } from '@metamask/utils';\nimport { VersionRangeStruct } 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":";;;;;;;;;;;IAKaA,8BAA8B;eAA9BA;;IAYGC,gBAAgB;eAAhBA;;IA2BAC,mBAAmB;eAAnBA;;;uBA3CmB;wBACkB;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,IAA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|
@@ -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"}
|