@metamask/snaps-utils 8.9.1 → 9.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 +41 -1
- package/dist/caveats.cjs +4 -0
- package/dist/caveats.cjs.map +1 -1
- package/dist/caveats.d.cts +5 -1
- package/dist/caveats.d.cts.map +1 -1
- package/dist/caveats.d.mts +5 -1
- package/dist/caveats.d.mts.map +1 -1
- package/dist/caveats.mjs +4 -0
- package/dist/caveats.mjs.map +1 -1
- package/dist/default-endowments.cjs +1 -0
- package/dist/default-endowments.cjs.map +1 -1
- package/dist/default-endowments.d.cts.map +1 -1
- package/dist/default-endowments.d.mts.map +1 -1
- package/dist/default-endowments.mjs +1 -0
- package/dist/default-endowments.mjs.map +1 -1
- package/dist/handler-types.cjs +1 -0
- package/dist/handler-types.cjs.map +1 -1
- package/dist/handler-types.d.cts +2 -1
- package/dist/handler-types.d.cts.map +1 -1
- package/dist/handler-types.d.mts +2 -1
- package/dist/handler-types.d.mts.map +1 -1
- package/dist/handler-types.mjs +1 -0
- package/dist/handler-types.mjs.map +1 -1
- package/dist/handlers.cjs +7 -0
- package/dist/handlers.cjs.map +1 -1
- package/dist/handlers.d.cts +24 -3
- package/dist/handlers.d.cts.map +1 -1
- package/dist/handlers.d.mts +24 -3
- package/dist/handlers.d.mts.map +1 -1
- package/dist/handlers.mjs +7 -0
- package/dist/handlers.mjs.map +1 -1
- package/dist/index.cjs +0 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +0 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +0 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.executionenv.cjs +0 -1
- package/dist/index.executionenv.cjs.map +1 -1
- package/dist/index.executionenv.d.cts +0 -1
- package/dist/index.executionenv.d.cts.map +1 -1
- package/dist/index.executionenv.d.mts +0 -1
- package/dist/index.executionenv.d.mts.map +1 -1
- package/dist/index.executionenv.mjs +0 -1
- package/dist/index.executionenv.mjs.map +1 -1
- package/dist/index.mjs +0 -1
- package/dist/index.mjs.map +1 -1
- package/dist/manifest/validation.cjs +4 -3
- package/dist/manifest/validation.cjs.map +1 -1
- package/dist/manifest/validation.d.cts +3 -0
- package/dist/manifest/validation.d.cts.map +1 -1
- package/dist/manifest/validation.d.mts +3 -0
- package/dist/manifest/validation.d.mts.map +1 -1
- package/dist/manifest/validation.mjs +4 -3
- package/dist/manifest/validation.mjs.map +1 -1
- package/dist/snaps.cjs +1 -12
- package/dist/snaps.cjs.map +1 -1
- package/dist/snaps.d.cts +0 -7
- package/dist/snaps.d.cts.map +1 -1
- package/dist/snaps.d.mts +0 -7
- package/dist/snaps.d.mts.map +1 -1
- package/dist/snaps.mjs +0 -10
- package/dist/snaps.mjs.map +1 -1
- package/package.json +5 -5
- package/dist/namespace.cjs +0 -136
- package/dist/namespace.cjs.map +0 -1
- package/dist/namespace.d.cts +0 -130
- package/dist/namespace.d.cts.map +0 -1
- package/dist/namespace.d.mts +0 -130
- package/dist/namespace.d.mts.map +0 -1
- package/dist/namespace.mjs +0 -126
- package/dist/namespace.mjs.map +0 -1
package/dist/snaps.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAQA,uDAW+B;AAE/B,2CAAiE;AACjE,sCAAqC;AACrC,4FAAyD;AACzD,0FAA2D;AAE3D,2CAA2C;AAC3C,6CAA2C;AAQ3C,uCAA8C;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9B,kHAAkH,CAAC;AAErH,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA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A8B,CAC5C,oBAA6B;IAE7B,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,oBAAoB,CAAC,EAC9B,0CAA0C,CAC3C,CAAC;IAEF,MAAM,EAAE,WAAW,EAAE,oBAAoB,EAAE,GAAG,oBAAoB,CAAC;IAEnE,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,oBAAoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,IAAA,cAAM,EACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO;QACtC,IAAA,gBAAQ,EAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
|
|
1
|
+
{"version":3,"file":"snaps.cjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAQA,uDAW+B;AAE/B,2CAAiE;AACjE,sCAAqC;AACrC,4FAAyD;AACzD,0FAA2D;AAE3D,2CAA2C;AAC3C,6CAA2C;AAQ3C,uCAA8C;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACtH,QAAA,mBAAmB,GAC9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,EAAC,oBAAoB,CAAC,EAC9B,0CAA0C,CAC3C,CAAC;IAEF,MAAM,EAAE,WAAW,EAAE,oBAAoB,EAAE,GAAG,oBAAoB,CAAC;IAEnE,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,oBAAoB,CAAC,EAC9B,wDAAwD,CACzD,CAAC;IAEF,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC;IAEzC,IAAA,cAAM,EACJ,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,EAC9C,yEAAyE,CAC1E,CAAC;IAEF,MAAM,CAAC,MAAM,CAAC,GAAG,OAAO,CAAC;IAEzB,IAAA,cAAM,EACJ,IAAA,gBAAQ,EAAC,MAAM,CAAC;QACd,MAAM,CAAC,IAAI,KAAK,wBAAc,CAAC,OAAO;QACtC,IAAA,gBAAQ,EAAC,MAAM,CAAC,KAAK,CAAC,EACxB,iDAAiD,wBAAc,CAAC,OAAO,UAAU,CAClF,CAAC;AACJ,CAAC;AA9BD,wEA8BC","sourcesContent":["import type {\n Caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
|
package/dist/snaps.d.cts
CHANGED
|
@@ -155,13 +155,6 @@ export declare function isSnapId(value: unknown): value is SnapId;
|
|
|
155
155
|
* @throws If the value is not a valid snap ID.
|
|
156
156
|
*/
|
|
157
157
|
export declare function assertIsValidSnapId(value: unknown): asserts value is SnapId;
|
|
158
|
-
/**
|
|
159
|
-
* Typeguard to ensure a chainId follows the CAIP-2 standard.
|
|
160
|
-
*
|
|
161
|
-
* @param chainId - The chainId being tested.
|
|
162
|
-
* @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.
|
|
163
|
-
*/
|
|
164
|
-
export declare function isCaipChainId(chainId: unknown): chainId is string;
|
|
165
158
|
/**
|
|
166
159
|
* Utility function to check if an origin has permission (and caveat) for a particular snap.
|
|
167
160
|
*
|
package/dist/snaps.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.d.cts","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,oBAAoB,EACrB,wCAAwC;AACzC,OAAO,KAAK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@ export declare function isSnapId(value: unknown): value is SnapId;
|
|
|
155
155
|
* @throws If the value is not a valid snap ID.
|
|
156
156
|
*/
|
|
157
157
|
export declare function assertIsValidSnapId(value: unknown): asserts value is SnapId;
|
|
158
|
-
/**
|
|
159
|
-
* Typeguard to ensure a chainId follows the CAIP-2 standard.
|
|
160
|
-
*
|
|
161
|
-
* @param chainId - The chainId being tested.
|
|
162
|
-
* @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.
|
|
163
|
-
*/
|
|
164
|
-
export declare function isCaipChainId(chainId: unknown): chainId is string;
|
|
165
158
|
/**
|
|
166
159
|
* Utility function to check if an origin has permission (and caveat) for a particular snap.
|
|
167
160
|
*
|
package/dist/snaps.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.d.mts","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,kBAAkB,EAClB,oBAAoB,EACrB,wCAAwC;AACzC,OAAO,KAAK,EAAE,WAAW,EAAE,iCAAiC;AAC5D,OAAO,KAAK,EAAE,MAAM,EAAE,IAAI,IAAI,aAAa,EAAE,4BAA4B;AACzE,OAAO,KAAK,EAAE,MAAM,EAAE,8BAA8B;AAqBpD,OAAO,KAAK,EAAE,gBAAgB,EAAE,2BAAuB;AACvD,OAAO,KAAK,EACV,kBAAkB,EAClB,YAAY,EACZ,eAAe,EAChB,kCAA8B;AAC/B,OAAO,KAAK,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,oBAAgB;AACxE,OAAO,EAAE,cAAc,EAAO,oBAAgB;AAY9C,eAAO,MAAM,mBAAmB,QACoF,CAAC;AAErH,oBAAY,UAAU;IACpB,UAAU,eAAe;IACzB,QAAQ,aAAa;IACrB,OAAO,YAAY;IACnB,OAAO,YAAY;IACnB,OAAO,YAAY;CACpB;AAED,oBAAY,gBAAgB;IAC1B,KAAK,UAAU;IACf,IAAI,SAAS;IACb,KAAK,UAAU;IACf,MAAM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,MAAM,GAAG,cAAc,CAQ5D;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEtD;AAED;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAExD;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,KAAK,IAAI,MAAM,CAE3E;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,WAAW,EAAE,kBAAkB,CAAC,oBAAoB,CAAC,EACrD,MAAM,EAAE,MAAM,WAWf;AAED;;;;;;GAMG;AACH,wBAAgB,8BAA8B,CAC5C,oBAAoB,EAAE,OAAO,GAC5B,OAAO,CAAC,oBAAoB,IAAI,sBAAsB,CA4BxD;AAED,YAAY,EAAE,IAAI,IAAI,aAAa,EAAE,4BAA4B"}
|
package/dist/snaps.mjs
CHANGED
|
@@ -170,16 +170,6 @@ export function isSnapId(value) {
|
|
|
170
170
|
export function assertIsValidSnapId(value) {
|
|
171
171
|
assertStruct(value, SnapIdStruct, 'Invalid snap ID');
|
|
172
172
|
}
|
|
173
|
-
/**
|
|
174
|
-
* Typeguard to ensure a chainId follows the CAIP-2 standard.
|
|
175
|
-
*
|
|
176
|
-
* @param chainId - The chainId being tested.
|
|
177
|
-
* @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.
|
|
178
|
-
*/
|
|
179
|
-
export function isCaipChainId(chainId) {
|
|
180
|
-
return (typeof chainId === 'string' &&
|
|
181
|
-
/^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(chainId));
|
|
182
|
-
}
|
|
183
173
|
/**
|
|
184
174
|
* Utility function to check if an origin has permission (and caveat) for a particular snap.
|
|
185
175
|
*
|
package/dist/snaps.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snaps.mjs","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caveat,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Typeguard to ensure a chainId follows the CAIP-2 standard.\n *\n * @param chainId - The chainId being tested.\n * @returns `true` if the value is a valid CAIP chain id, and `false` otherwise.\n */\nexport function isCaipChainId(chainId: unknown): chainId is string {\n return (\n typeof chainId === 'string' &&\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u.test(\n chainId,\n )\n );\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
|
|
1
|
+
{"version":3,"file":"snaps.mjs","sourceRoot":"","sources":["../src/snaps.ts"],"names":[],"mappings":";;;;;;AAQA,OAAO,EACL,EAAE,EACF,KAAK,EACL,KAAK,EACL,YAAY,EACZ,OAAO,EACP,OAAO,EACP,MAAM,EACN,MAAM,EACN,KAAK,EACL,QAAQ,EACT,8BAA8B;AAE/B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,YAAY,EAAE,wBAAwB;AACjE,OAAO,EAAE,MAAM,EAAE,oBAAoB;AACrC,OAAO,gBAAe,mCAAmC;;AACzD,OAAO,mBAAkB,kCAAkC;;AAE3D,OAAO,EAAE,cAAc,EAAE,sBAAkB;AAC3C,OAAO,EAAE,aAAa,EAAE,uBAAmB;AAQ3C,OAAO,EAAE,cAAc,EAAE,GAAG,EAAE,oBAAgB;AAG9C,+EAA+E;AAC/E,0EAA0E;AAC1E,0EAA0E;AAC1E,4DAA4D;AAC5D,uCAAuC;AACvC,2EAA2E;AAC3E,8EAA8E;AAC9E,qDAAqD;AACrD,mIAAmI;AACnI,MAAM,CAAC,MAAM,mBAAmB,GAC9B,kHAAkH,CAAC;AAErH,MAAM,CAAN,IAAY,UAMX;AAND,WAAY,UAAU;IACpB,uCAAyB,CAAA;IACzB,mCAAqB,CAAA;IACrB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;IACnB,iCAAmB,CAAA;AACrB,CAAC,EANW,UAAU,KAAV,UAAU,QAMrB;AAED,MAAM,CAAN,IAAY,gBAKX;AALD,WAAY,gBAAgB;IAC1B,mCAAe,CAAA;IACf,iCAAa,CAAA;IACb,mCAAe,CAAA;IACf,qCAAiB,CAAA;AACnB,CAAC,EALW,gBAAgB,KAAhB,gBAAgB,QAK3B;AA2GD;;;;;GAKG;AACH,SAAS,wBAAwB,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,\n SubjectPermissions,\n PermissionConstraint,\n} from '@metamask/permission-controller';\nimport type { BlockReason } from '@metamask/snaps-registry';\nimport type { SnapId, Snap as TruncatedSnap } from '@metamask/snaps-sdk';\nimport type { Struct } from '@metamask/superstruct';\nimport {\n is,\n empty,\n enums,\n intersection,\n literal,\n pattern,\n refine,\n string,\n union,\n validate,\n} from '@metamask/superstruct';\nimport type { Json } from '@metamask/utils';\nimport { assert, isObject, assertStruct } from '@metamask/utils';\nimport { base64 } from '@scure/base';\nimport stableStringify from 'fast-json-stable-stringify';\nimport validateNPMPackage from 'validate-npm-package-name';\n\nimport { SnapCaveatType } from './caveats';\nimport { checksumFiles } from './checksum';\nimport type { LocalizationFile } from './localization';\nimport type {\n InitialConnections,\n SnapManifest,\n SnapPermissions,\n} from './manifest/validation';\nimport type { FetchedSnapFiles, SnapsPermissionRequest } from './types';\nimport { SnapIdPrefixes, uri } from './types';\nimport type { VirtualFile } from './virtual-file';\n\n// This RegEx matches valid npm package names (with some exceptions) and space-\n// separated alphanumerical words, optionally with dashes and underscores.\n// The RegEx consists of two parts. The first part matches space-separated\n// words. It is based on the following Stackoverflow answer:\n// https://stackoverflow.com/a/34974982\n// The second part, after the pipe operator, is the same RegEx used for the\n// `name` field of the official package.json JSON Schema, except that we allow\n// mixed-case letters. It was originally copied from:\n// https://github.com/SchemaStore/schemastore/blob/81a16897c1dabfd98c72242a5fd62eb080ff76d8/src/schemas/json/package.json#L132-L138\nexport const PROPOSED_NAME_REGEX =\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u;\n\nexport enum SnapStatus {\n Installing = 'installing',\n Updating = 'updating',\n Running = 'running',\n Stopped = 'stopped',\n Crashed = 'crashed',\n}\n\nexport enum SnapStatusEvents {\n Start = 'START',\n Stop = 'STOP',\n Crash = 'CRASH',\n Update = 'UPDATE',\n}\n\nexport type StatusContext = { snapId: SnapId };\nexport type StatusEvents = { type: SnapStatusEvents };\nexport type StatusStates = {\n value: SnapStatus;\n context: StatusContext;\n};\nexport type Status = StatusStates['value'];\n\nexport type VersionHistory = {\n origin: string;\n version: string;\n // Unix timestamp\n date: number;\n};\n\nexport type SnapAuxilaryFile = {\n path: string;\n // Value here should be stored as base64\n value: string;\n};\n\nexport type PersistedSnap = Snap;\n\n/**\n * A Snap as it exists in {@link SnapController} state.\n */\nexport type Snap = TruncatedSnap & {\n /**\n * The initial connections of the Snap, optional, requested on installation.\n */\n initialConnections?: InitialConnections;\n /**\n * The initial permissions of the Snap, which will be requested when it is\n * installed.\n */\n initialPermissions: SnapPermissions;\n\n /**\n * The source code of the Snap.\n */\n sourceCode: string;\n\n /**\n * The Snap's manifest file.\n */\n manifest: SnapManifest;\n\n /**\n * Information detailing why the snap is blocked.\n */\n blockInformation?: BlockReason;\n\n /**\n * The current status of the Snap, e.g. whether it's running or stopped.\n */\n status: Status;\n\n /**\n * The version history of the Snap.\n * Can be used to derive when the Snap was installed, when it was updated to a certain version and who requested the change.\n */\n versionHistory: VersionHistory[];\n\n /**\n * Static auxiliary files that can be loaded at runtime.\n */\n auxiliaryFiles?: SnapAuxilaryFile[];\n\n /**\n * Localization files which are used to translate the manifest.\n */\n localizationFiles?: LocalizationFile[];\n\n /**\n * Flag to signal whether this snap was preinstalled or not.\n *\n * A lack of specifying this option will be deemed as not preinstalled.\n */\n preinstalled?: boolean;\n\n /**\n * Flag to signal whether this snap is removable or not.\n *\n * A lack of specifying this option will be deemed as removable.\n */\n removable?: boolean;\n\n /**\n * Flag to signal whether this snap should be hidden from the user or not.\n */\n hidden?: boolean;\n\n /**\n * Flag to signal whether this snap should hide the Snap branding like header or avatar in the UI or not.\n */\n hideSnapBranding?: boolean;\n};\n\nexport type TruncatedSnapFields =\n | 'id'\n | 'initialPermissions'\n | 'version'\n | 'enabled'\n | 'blocked';\n\n/**\n * Gets a checksummable manifest by removing the shasum property and reserializing the JSON using a deterministic algorithm.\n *\n * @param manifest - The manifest itself.\n * @returns A virtual file containing the checksummable manifest.\n */\nfunction getChecksummableManifest(\n manifest: VirtualFile<SnapManifest>,\n): VirtualFile {\n const manifestCopy = manifest.clone() as VirtualFile<any>;\n delete manifestCopy.result.source.shasum;\n\n // We use fast-json-stable-stringify to deterministically serialize the JSON\n // This is required before checksumming so we get reproducible checksums across platforms etc\n manifestCopy.value = stableStringify(manifestCopy.result);\n return manifestCopy;\n}\n\n/**\n * Calculates the Base64-encoded SHA-256 digest of all required Snap files.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @returns The Base64-encoded SHA-256 digest of the source code.\n */\nexport async function getSnapChecksum(\n files: FetchedSnapFiles,\n): Promise<string> {\n const { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles } =\n files;\n\n const all = [\n getChecksummableManifest(manifest),\n sourceCode,\n svgIcon,\n ...auxiliaryFiles,\n ...localizationFiles,\n ].filter((file) => file !== undefined);\n\n return base64.encode(await checksumFiles(all as VirtualFile[]));\n}\n\n/**\n * Checks whether the `source.shasum` property of a Snap manifest matches the\n * shasum of the snap.\n *\n * @param files - All required Snap files to be included in the checksum.\n * @param errorMessage - The error message to throw if validation fails.\n */\nexport async function validateSnapShasum(\n files: FetchedSnapFiles,\n errorMessage = 'Invalid Snap manifest: manifest shasum does not match computed shasum.',\n): Promise<void> {\n if (files.manifest.result.source.shasum !== (await getSnapChecksum(files))) {\n throw new Error(errorMessage);\n }\n}\n\nexport const LOCALHOST_HOSTNAMES = ['localhost', '127.0.0.1', '[::1]'] as const;\n\n// Require snap ids to only consist of printable ASCII characters\nexport const BaseSnapIdStruct = pattern(string(), /^[\\x21-\\x7E]*$/u);\n\nconst LocalSnapIdSubUrlStruct = uri({\n protocol: enums(['http:', 'https:']),\n hostname: enums(LOCALHOST_HOSTNAMES),\n hash: empty(string()),\n search: empty(string()),\n});\n\nexport const LocalSnapIdStruct = refine(\n BaseSnapIdStruct,\n 'local Snap Id',\n (value) => {\n if (!value.startsWith(SnapIdPrefixes.local)) {\n return `Expected local snap ID, got \"${value}\".`;\n }\n\n const [error] = validate(\n value.slice(SnapIdPrefixes.local.length),\n LocalSnapIdSubUrlStruct,\n );\n return error ?? true;\n },\n);\nexport const NpmSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: literal(SnapIdPrefixes.npm),\n pathname: refine(string(), 'package name', function* (value) {\n const normalized = value.startsWith('/') ? value.slice(1) : value;\n const { errors, validForNewPackages, warnings } =\n validateNPMPackage(normalized);\n if (!validForNewPackages) {\n if (errors === undefined) {\n assert(warnings !== undefined);\n yield* warnings;\n } else {\n yield* errors;\n }\n }\n return true;\n }),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const HttpSnapIdStruct = intersection([\n BaseSnapIdStruct,\n uri({\n protocol: enums(['http:', 'https:']),\n search: empty(string()),\n hash: empty(string()),\n }),\n]) as unknown as Struct<string, null>;\n\nexport const SnapIdStruct = union([NpmSnapIdStruct, LocalSnapIdStruct]);\n\n/**\n * Extracts the snap prefix from a snap ID.\n *\n * @param snapId - The snap ID to extract the prefix from.\n * @returns The snap prefix from a snap id, e.g. `npm:`.\n */\nexport function getSnapPrefix(snapId: string): SnapIdPrefixes {\n const prefix = Object.values(SnapIdPrefixes).find((possiblePrefix) =>\n snapId.startsWith(possiblePrefix),\n );\n if (prefix !== undefined) {\n return prefix;\n }\n throw new Error(`Invalid or no prefix found for \"${snapId}\"`);\n}\n\n/**\n * Strips snap prefix from a full snap ID.\n *\n * @param snapId - The snap ID to strip.\n * @returns The stripped snap ID.\n */\nexport function stripSnapPrefix(snapId: string): string {\n return snapId.replace(getSnapPrefix(snapId), '');\n}\n\n/**\n * Check if the given value is a valid snap ID. This function is a type guard,\n * and will narrow the type of the value to `SnapId` if it returns `true`.\n *\n * @param value - The value to check.\n * @returns `true` if the value is a valid snap ID, and `false` otherwise.\n */\nexport function isSnapId(value: unknown): value is SnapId {\n return is(value, SnapIdStruct);\n}\n\n/**\n * Assert that the given value is a valid snap ID.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid snap ID.\n */\nexport function assertIsValidSnapId(value: unknown): asserts value is SnapId {\n assertStruct(value, SnapIdStruct, 'Invalid snap ID');\n}\n\n/**\n * Utility function to check if an origin has permission (and caveat) for a particular snap.\n *\n * @param permissions - An origin's permissions object.\n * @param snapId - The id of the snap.\n * @returns A boolean based on if an origin has the specified snap.\n */\nexport function isSnapPermitted(\n permissions: SubjectPermissions<PermissionConstraint>,\n snapId: SnapId,\n) {\n return Boolean(\n (\n (\n (permissions?.wallet_snap?.caveats?.find(\n (caveat) => caveat.type === SnapCaveatType.SnapIds,\n ) ?? {}) as Caveat<string, Json>\n ).value as Record<string, unknown>\n )?.[snapId],\n );\n}\n\n/**\n * Checks whether the passed in requestedPermissions is a valid\n * permission request for a `wallet_snap` permission.\n *\n * @param requestedPermissions - The requested permissions.\n * @throws If the criteria is not met.\n */\nexport function verifyRequestedSnapPermissions(\n requestedPermissions: unknown,\n): asserts requestedPermissions is SnapsPermissionRequest {\n assert(\n isObject(requestedPermissions),\n 'Requested permissions must be an object.',\n );\n\n const { wallet_snap: walletSnapPermission } = requestedPermissions;\n\n assert(\n isObject(walletSnapPermission),\n 'wallet_snap is missing from the requested permissions.',\n );\n\n const { caveats } = walletSnapPermission;\n\n assert(\n Array.isArray(caveats) && caveats.length === 1,\n 'wallet_snap must have a caveat property with a single-item array value.',\n );\n\n const [caveat] = caveats;\n\n assert(\n isObject(caveat) &&\n caveat.type === SnapCaveatType.SnapIds &&\n isObject(caveat.value),\n `The requested permissions do not have a valid ${SnapCaveatType.SnapIds} caveat.`,\n );\n}\n\nexport type { Snap as TruncatedSnap } from '@metamask/snaps-sdk';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-utils",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "9.0.0",
|
|
4
4
|
"description": "A collection of utilities for MetaMask Snaps",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|
|
@@ -79,15 +79,15 @@
|
|
|
79
79
|
"dependencies": {
|
|
80
80
|
"@babel/core": "^7.23.2",
|
|
81
81
|
"@babel/types": "^7.23.0",
|
|
82
|
-
"@metamask/base-controller": "^
|
|
82
|
+
"@metamask/base-controller": "^8.0.0",
|
|
83
83
|
"@metamask/key-tree": "^10.0.2",
|
|
84
|
-
"@metamask/permission-controller": "^11.0.
|
|
84
|
+
"@metamask/permission-controller": "^11.0.6",
|
|
85
85
|
"@metamask/rpc-errors": "^7.0.2",
|
|
86
86
|
"@metamask/slip44": "^4.1.0",
|
|
87
87
|
"@metamask/snaps-registry": "^3.2.3",
|
|
88
|
-
"@metamask/snaps-sdk": "^6.
|
|
88
|
+
"@metamask/snaps-sdk": "^6.18.0",
|
|
89
89
|
"@metamask/superstruct": "^3.1.0",
|
|
90
|
-
"@metamask/utils": "^11.0
|
|
90
|
+
"@metamask/utils": "^11.2.0",
|
|
91
91
|
"@noble/hashes": "^1.3.1",
|
|
92
92
|
"@scure/base": "^1.1.1",
|
|
93
93
|
"chalk": "^4.1.2",
|
package/dist/namespace.cjs
DELETED
|
@@ -1,136 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isNamespace = exports.isAccountIdArray = exports.isAccountId = exports.isChainId = exports.isNamespaceId = exports.NamespaceIdStruct = exports.NamespaceStruct = exports.ChainStruct = exports.AccountAddressStruct = exports.AccountIdArrayStruct = exports.AccountIdStruct = exports.ChainIdStruct = exports.ChainIdStringStruct = exports.LimitedString = exports.parseAccountId = exports.parseChainId = exports.ACCOUNT_ADDRESS_REGEX = exports.ACCOUNT_ID_REGEX = exports.CHAIN_ID_REGEX = void 0;
|
|
4
|
-
const superstruct_1 = require("@metamask/superstruct");
|
|
5
|
-
exports.CHAIN_ID_REGEX = /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;
|
|
6
|
-
exports.ACCOUNT_ID_REGEX = /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
|
|
7
|
-
exports.ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;
|
|
8
|
-
/**
|
|
9
|
-
* Parse a chain ID string to an object containing the namespace and reference.
|
|
10
|
-
* This validates the chain ID before parsing it.
|
|
11
|
-
*
|
|
12
|
-
* @param chainId - The chain ID to validate and parse.
|
|
13
|
-
* @returns The parsed chain ID.
|
|
14
|
-
*/
|
|
15
|
-
function parseChainId(chainId) {
|
|
16
|
-
const match = exports.CHAIN_ID_REGEX.exec(chainId);
|
|
17
|
-
if (!match?.groups) {
|
|
18
|
-
throw new Error('Invalid chain ID.');
|
|
19
|
-
}
|
|
20
|
-
return {
|
|
21
|
-
namespace: match.groups.namespace,
|
|
22
|
-
reference: match.groups.reference,
|
|
23
|
-
};
|
|
24
|
-
}
|
|
25
|
-
exports.parseChainId = parseChainId;
|
|
26
|
-
/**
|
|
27
|
-
* Parse an account ID to an object containing the chain, chain ID and address.
|
|
28
|
-
* This validates the account ID before parsing it.
|
|
29
|
-
*
|
|
30
|
-
* @param accountId - The account ID to validate and parse.
|
|
31
|
-
* @returns The parsed account ID.
|
|
32
|
-
*/
|
|
33
|
-
function parseAccountId(accountId) {
|
|
34
|
-
const match = exports.ACCOUNT_ID_REGEX.exec(accountId);
|
|
35
|
-
if (!match?.groups) {
|
|
36
|
-
throw new Error('Invalid account ID.');
|
|
37
|
-
}
|
|
38
|
-
return {
|
|
39
|
-
address: match.groups.accountAddress,
|
|
40
|
-
chainId: match.groups.chainId,
|
|
41
|
-
chain: {
|
|
42
|
-
namespace: match.groups.namespace,
|
|
43
|
-
reference: match.groups.reference,
|
|
44
|
-
},
|
|
45
|
-
};
|
|
46
|
-
}
|
|
47
|
-
exports.parseAccountId = parseAccountId;
|
|
48
|
-
/**
|
|
49
|
-
* A helper struct for a string with a minimum length of 1 and a maximum length
|
|
50
|
-
* of 40.
|
|
51
|
-
*/
|
|
52
|
-
exports.LimitedString = (0, superstruct_1.size)((0, superstruct_1.string)(), 1, 40);
|
|
53
|
-
exports.ChainIdStringStruct = (0, superstruct_1.define)('Chain ID', (0, superstruct_1.string)().validator);
|
|
54
|
-
/**
|
|
55
|
-
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
|
|
56
|
-
*/
|
|
57
|
-
exports.ChainIdStruct = (0, superstruct_1.pattern)(exports.ChainIdStringStruct, exports.CHAIN_ID_REGEX);
|
|
58
|
-
exports.AccountIdStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.ACCOUNT_ID_REGEX);
|
|
59
|
-
exports.AccountIdArrayStruct = (0, superstruct_1.array)(exports.AccountIdStruct);
|
|
60
|
-
exports.AccountAddressStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), exports.ACCOUNT_ADDRESS_REGEX);
|
|
61
|
-
/**
|
|
62
|
-
* A chain descriptor.
|
|
63
|
-
*/
|
|
64
|
-
exports.ChainStruct = (0, superstruct_1.object)({
|
|
65
|
-
id: exports.ChainIdStruct,
|
|
66
|
-
name: exports.LimitedString,
|
|
67
|
-
});
|
|
68
|
-
exports.NamespaceStruct = (0, superstruct_1.object)({
|
|
69
|
-
/**
|
|
70
|
-
* A list of supported chains in the namespace.
|
|
71
|
-
*/
|
|
72
|
-
chains: (0, superstruct_1.array)(exports.ChainStruct),
|
|
73
|
-
/**
|
|
74
|
-
* A list of supported RPC methods on the namespace, that a DApp can call.
|
|
75
|
-
*/
|
|
76
|
-
methods: (0, superstruct_1.optional)((0, superstruct_1.array)(exports.LimitedString)),
|
|
77
|
-
/**
|
|
78
|
-
* A list of supported RPC events on the namespace, that a DApp can listen to.
|
|
79
|
-
*/
|
|
80
|
-
events: (0, superstruct_1.optional)((0, superstruct_1.array)(exports.LimitedString)),
|
|
81
|
-
});
|
|
82
|
-
/**
|
|
83
|
-
* A CAIP-2 namespace, i.e., the first part of a chain ID.
|
|
84
|
-
*/
|
|
85
|
-
exports.NamespaceIdStruct = (0, superstruct_1.pattern)((0, superstruct_1.string)(), /^[-a-z0-9]{3,8}$/u);
|
|
86
|
-
/**
|
|
87
|
-
* Check if the given value is a CAIP-2 namespace ID.
|
|
88
|
-
*
|
|
89
|
-
* @param value - The value to check.
|
|
90
|
-
* @returns Whether the value is a CAIP-2 namespace ID.
|
|
91
|
-
*/
|
|
92
|
-
function isNamespaceId(value) {
|
|
93
|
-
return (0, superstruct_1.is)(value, exports.NamespaceIdStruct);
|
|
94
|
-
}
|
|
95
|
-
exports.isNamespaceId = isNamespaceId;
|
|
96
|
-
/**
|
|
97
|
-
* Check if the given value is a CAIP-2 chain ID.
|
|
98
|
-
*
|
|
99
|
-
* @param value - The value to check.
|
|
100
|
-
* @returns Whether the value is a CAIP-2 chain ID.
|
|
101
|
-
*/
|
|
102
|
-
function isChainId(value) {
|
|
103
|
-
return (0, superstruct_1.is)(value, exports.ChainIdStruct);
|
|
104
|
-
}
|
|
105
|
-
exports.isChainId = isChainId;
|
|
106
|
-
/**
|
|
107
|
-
* Check if the given value is a CAIP-10 account ID.
|
|
108
|
-
*
|
|
109
|
-
* @param value - The value to check.
|
|
110
|
-
* @returns Whether the value is a CAIP-10 account ID.
|
|
111
|
-
*/
|
|
112
|
-
function isAccountId(value) {
|
|
113
|
-
return (0, superstruct_1.is)(value, exports.AccountIdStruct);
|
|
114
|
-
}
|
|
115
|
-
exports.isAccountId = isAccountId;
|
|
116
|
-
/**
|
|
117
|
-
* Check if the given value is an array of CAIP-10 account IDs.
|
|
118
|
-
*
|
|
119
|
-
* @param value - The value to check.
|
|
120
|
-
* @returns Whether the value is an array of CAIP-10 account IDs.
|
|
121
|
-
*/
|
|
122
|
-
function isAccountIdArray(value) {
|
|
123
|
-
return (0, superstruct_1.is)(value, exports.AccountIdArrayStruct);
|
|
124
|
-
}
|
|
125
|
-
exports.isAccountIdArray = isAccountIdArray;
|
|
126
|
-
/**
|
|
127
|
-
* Check if a value is a {@link Namespace}.
|
|
128
|
-
*
|
|
129
|
-
* @param value - The value to validate.
|
|
130
|
-
* @returns True if the value is a valid {@link Namespace}.
|
|
131
|
-
*/
|
|
132
|
-
function isNamespace(value) {
|
|
133
|
-
return (0, superstruct_1.is)(value, exports.NamespaceStruct);
|
|
134
|
-
}
|
|
135
|
-
exports.isNamespace = isNamespace;
|
|
136
|
-
//# sourceMappingURL=namespace.cjs.map
|
package/dist/namespace.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"namespace.cjs","sourceRoot":"","sources":["../src/namespace.ts"],"names":[],"mappings":";;;AAEA,uDAS+B;AAIlB,QAAA,cAAc,GACzB,kEAAkE,CAAC;AAExD,QAAA,gBAAgB,GAC3B,mHAAmH,CAAC;AAEzG,QAAA,qBAAqB,GAAG,yCAAyC,CAAC;AAE/E;;;;;;GAMG;AACH,SAAgB,YAAY,CAAC,OAAgB;IAI3C,MAAM,KAAK,GAAG,sBAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC3C,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;IACvC,CAAC;IAED,OAAO;QACL,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS;QACjC,SAAS,EAAE,KAAK,CAAC,MAAM,CAAC,SAAS;KAClC,CAAC;AACJ,CAAC;AAbD,oCAaC;AAED;;;;;;GAMG;AACH,SAAgB,cAAc,CAAC,SAAoB;IAKjD,MAAM,KAAK,GAAG,wBAAgB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC/C,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;QACnB,MAAM,IAAI,KAAK,CAAC,qBAAq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BAAa,CAAC,CAAC;CACvC,CAAC,CAAC;AAGH;;GAEG;AACU,QAAA,iBAAiB,GAAG,IAAA,qBAAO,EAAC,IAAA,oBAAM,GAAE,EAAE,mBAAmB,CAAC,CAAC;AAGxE;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,KAAc;IAC1C,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,yBAAiB,CAAC,CAAC;AACtC,CAAC;AAFD,sCAEC;AAED;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,KAAc;IACtC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,qBAAa,CAAC,CAAC;AAClC,CAAC;AAFD,8BAEC;AAED;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,uBAAe,CAAC,CAAC;AACpC,CAAC;AAFD,kCAEC;AAED;;;;;GAKG;AACH,SAAgB,gBAAgB,CAAC,KAAc;IAC7C,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,4BAAoB,CAAC,CAAC;AACzC,CAAC;AAFD,4CAEC;AAED;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,OAAO,IAAA,gBAAE,EAAC,KAAK,EAAE,uBAAe,CAAC,CAAC;AACpC,CAAC;AAFD,kCAEC","sourcesContent":["import type { AccountId, ChainId } from '@metamask/snaps-sdk';\nimport type { Infer } from '@metamask/superstruct';\nimport {\n array,\n define,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from '@metamask/superstruct';\n\nimport type { InferMatching } from './structs';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\nexport const ACCOUNT_ADDRESS_REGEX = /^(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\nexport const ChainIdStringStruct = define<ChainId>(\n 'Chain ID',\n string().validator,\n);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern<ChainId, null>(\n ChainIdStringStruct,\n CHAIN_ID_REGEX,\n);\n\nexport type Caip2ChainId = InferMatching<typeof ChainIdStruct, ChainId>;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\nexport const AccountAddressStruct = pattern(string(), ACCOUNT_ADDRESS_REGEX);\nexport type AccountAddress = Infer<typeof AccountAddressStruct>;\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"]}
|
package/dist/namespace.d.cts
DELETED
|
@@ -1,130 +0,0 @@
|
|
|
1
|
-
import type { AccountId, ChainId } from "@metamask/snaps-sdk";
|
|
2
|
-
import type { Infer } from "@metamask/superstruct";
|
|
3
|
-
import type { InferMatching } from "./structs.cjs";
|
|
4
|
-
export declare const CHAIN_ID_REGEX: RegExp;
|
|
5
|
-
export declare const ACCOUNT_ID_REGEX: RegExp;
|
|
6
|
-
export declare const ACCOUNT_ADDRESS_REGEX: RegExp;
|
|
7
|
-
/**
|
|
8
|
-
* Parse a chain ID string to an object containing the namespace and reference.
|
|
9
|
-
* This validates the chain ID before parsing it.
|
|
10
|
-
*
|
|
11
|
-
* @param chainId - The chain ID to validate and parse.
|
|
12
|
-
* @returns The parsed chain ID.
|
|
13
|
-
*/
|
|
14
|
-
export declare function parseChainId(chainId: ChainId): {
|
|
15
|
-
namespace: NamespaceId;
|
|
16
|
-
reference: string;
|
|
17
|
-
};
|
|
18
|
-
/**
|
|
19
|
-
* Parse an account ID to an object containing the chain, chain ID and address.
|
|
20
|
-
* This validates the account ID before parsing it.
|
|
21
|
-
*
|
|
22
|
-
* @param accountId - The account ID to validate and parse.
|
|
23
|
-
* @returns The parsed account ID.
|
|
24
|
-
*/
|
|
25
|
-
export declare function parseAccountId(accountId: AccountId): {
|
|
26
|
-
chain: {
|
|
27
|
-
namespace: NamespaceId;
|
|
28
|
-
reference: string;
|
|
29
|
-
};
|
|
30
|
-
chainId: ChainId;
|
|
31
|
-
address: string;
|
|
32
|
-
};
|
|
33
|
-
/**
|
|
34
|
-
* A helper struct for a string with a minimum length of 1 and a maximum length
|
|
35
|
-
* of 40.
|
|
36
|
-
*/
|
|
37
|
-
export declare const LimitedString: import("@metamask/superstruct").Struct<string, null>;
|
|
38
|
-
export declare const ChainIdStringStruct: import("@metamask/superstruct").Struct<`${string}:${string}`, null>;
|
|
39
|
-
/**
|
|
40
|
-
* A CAIP-2 chain ID, i.e., a human-readable namespace and reference.
|
|
41
|
-
*/
|
|
42
|
-
export declare const ChainIdStruct: import("@metamask/superstruct").Struct<`${string}:${string}`, null>;
|
|
43
|
-
export type Caip2ChainId = InferMatching<typeof ChainIdStruct, ChainId>;
|
|
44
|
-
export declare const AccountIdStruct: import("@metamask/superstruct").Struct<string, null>;
|
|
45
|
-
export declare const AccountIdArrayStruct: import("@metamask/superstruct").Struct<string[], import("@metamask/superstruct").Struct<string, null>>;
|
|
46
|
-
export declare const AccountAddressStruct: import("@metamask/superstruct").Struct<string, null>;
|
|
47
|
-
export type AccountAddress = Infer<typeof AccountAddressStruct>;
|
|
48
|
-
/**
|
|
49
|
-
* A chain descriptor.
|
|
50
|
-
*/
|
|
51
|
-
export declare const ChainStruct: import("@metamask/superstruct").Struct<{
|
|
52
|
-
id: `${string}:${string}`;
|
|
53
|
-
name: string;
|
|
54
|
-
}, {
|
|
55
|
-
id: import("@metamask/superstruct").Struct<`${string}:${string}`, null>;
|
|
56
|
-
name: import("@metamask/superstruct").Struct<string, null>;
|
|
57
|
-
}>;
|
|
58
|
-
export type Chain = Infer<typeof ChainStruct>;
|
|
59
|
-
export declare const NamespaceStruct: import("@metamask/superstruct").Struct<{
|
|
60
|
-
chains: {
|
|
61
|
-
id: `${string}:${string}`;
|
|
62
|
-
name: string;
|
|
63
|
-
}[];
|
|
64
|
-
methods?: string[] | undefined;
|
|
65
|
-
events?: string[] | undefined;
|
|
66
|
-
}, {
|
|
67
|
-
/**
|
|
68
|
-
* A list of supported chains in the namespace.
|
|
69
|
-
*/
|
|
70
|
-
chains: import("@metamask/superstruct").Struct<{
|
|
71
|
-
id: `${string}:${string}`;
|
|
72
|
-
name: string;
|
|
73
|
-
}[], import("@metamask/superstruct").Struct<{
|
|
74
|
-
id: `${string}:${string}`;
|
|
75
|
-
name: string;
|
|
76
|
-
}, {
|
|
77
|
-
id: import("@metamask/superstruct").Struct<`${string}:${string}`, null>;
|
|
78
|
-
name: import("@metamask/superstruct").Struct<string, null>;
|
|
79
|
-
}>>;
|
|
80
|
-
/**
|
|
81
|
-
* A list of supported RPC methods on the namespace, that a DApp can call.
|
|
82
|
-
*/
|
|
83
|
-
methods: import("@metamask/superstruct").Struct<string[] | undefined, import("@metamask/superstruct").Struct<string, null>>;
|
|
84
|
-
/**
|
|
85
|
-
* A list of supported RPC events on the namespace, that a DApp can listen to.
|
|
86
|
-
*/
|
|
87
|
-
events: import("@metamask/superstruct").Struct<string[] | undefined, import("@metamask/superstruct").Struct<string, null>>;
|
|
88
|
-
}>;
|
|
89
|
-
export type Namespace = Infer<typeof NamespaceStruct>;
|
|
90
|
-
/**
|
|
91
|
-
* A CAIP-2 namespace, i.e., the first part of a chain ID.
|
|
92
|
-
*/
|
|
93
|
-
export declare const NamespaceIdStruct: import("@metamask/superstruct").Struct<string, null>;
|
|
94
|
-
export type NamespaceId = Infer<typeof NamespaceIdStruct>;
|
|
95
|
-
/**
|
|
96
|
-
* Check if the given value is a CAIP-2 namespace ID.
|
|
97
|
-
*
|
|
98
|
-
* @param value - The value to check.
|
|
99
|
-
* @returns Whether the value is a CAIP-2 namespace ID.
|
|
100
|
-
*/
|
|
101
|
-
export declare function isNamespaceId(value: unknown): value is NamespaceId;
|
|
102
|
-
/**
|
|
103
|
-
* Check if the given value is a CAIP-2 chain ID.
|
|
104
|
-
*
|
|
105
|
-
* @param value - The value to check.
|
|
106
|
-
* @returns Whether the value is a CAIP-2 chain ID.
|
|
107
|
-
*/
|
|
108
|
-
export declare function isChainId(value: unknown): value is ChainId;
|
|
109
|
-
/**
|
|
110
|
-
* Check if the given value is a CAIP-10 account ID.
|
|
111
|
-
*
|
|
112
|
-
* @param value - The value to check.
|
|
113
|
-
* @returns Whether the value is a CAIP-10 account ID.
|
|
114
|
-
*/
|
|
115
|
-
export declare function isAccountId(value: unknown): value is AccountId;
|
|
116
|
-
/**
|
|
117
|
-
* Check if the given value is an array of CAIP-10 account IDs.
|
|
118
|
-
*
|
|
119
|
-
* @param value - The value to check.
|
|
120
|
-
* @returns Whether the value is an array of CAIP-10 account IDs.
|
|
121
|
-
*/
|
|
122
|
-
export declare function isAccountIdArray(value: unknown): value is AccountId[];
|
|
123
|
-
/**
|
|
124
|
-
* Check if a value is a {@link Namespace}.
|
|
125
|
-
*
|
|
126
|
-
* @param value - The value to validate.
|
|
127
|
-
* @returns True if the value is a valid {@link Namespace}.
|
|
128
|
-
*/
|
|
129
|
-
export declare function isNamespace(value: unknown): value is Namespace;
|
|
130
|
-
//# sourceMappingURL=namespace.d.cts.map
|
package/dist/namespace.d.cts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"namespace.d.cts","sourceRoot":"","sources":["../src/namespace.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,4BAA4B;AAC9D,OAAO,KAAK,EAAE,KAAK,EAAE,8BAA8B;AAYnD,OAAO,KAAK,EAAE,aAAa,EAAE,sBAAkB;AAE/C,eAAO,MAAM,cAAc,QACyC,CAAC;AAErE,eAAO,MAAM,gBAAgB,QACwF,CAAC;AAEtH,eAAO,MAAM,qBAAqB,QAA4C,CAAC;AAE/E;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG;IAC9C,SAAS,EAAE,WAAW,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB,CAUA;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,SAAS,EAAE,SAAS,GAAG;IACpD,KAAK,EAAE;QAAE,SAAS,EAAE,WAAW,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IACrD,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB,CAcA;AAED;;;GAGG;AACH,eAAO,MAAM,aAAa,sDAAwB,CAAC;AAEnD,eAAO,MAAM,mBAAmB,qEAG/B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,aAAa,qEAGzB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG,aAAa,CAAC,OAAO,aAAa,EAAE,OAAO,CAAC,CAAC;AAExE,eAAO,MAAM,eAAe,sDAAsC,CAAC;AAEnE,eAAO,MAAM,oBAAoB,wGAAyB,CAAC;AAC3D,eAAO,MAAM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