@metamask/snaps-utils 4.0.0 → 5.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 +17 -1
- package/dist/cjs/cronjob.js +6 -7
- package/dist/cjs/cronjob.js.map +1 -1
- package/dist/cjs/index.browser.js +0 -1
- package/dist/cjs/index.browser.js.map +1 -1
- package/dist/cjs/index.js +0 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/manifest/manifest.js +4 -3
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/structs.js +0 -22
- package/dist/cjs/structs.js.map +1 -1
- package/dist/cjs/ui.js +16 -14
- package/dist/cjs/ui.js.map +1 -1
- package/dist/esm/cronjob.js +8 -9
- package/dist/esm/cronjob.js.map +1 -1
- package/dist/esm/index.browser.js +0 -1
- package/dist/esm/index.browser.js.map +1 -1
- package/dist/esm/index.js +0 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/manifest/manifest.js +5 -3
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/structs.js +1 -48
- package/dist/esm/structs.js.map +1 -1
- package/dist/esm/ui.js +18 -16
- package/dist/esm/ui.js.map +1 -1
- package/dist/types/cronjob.d.ts +15 -15
- package/dist/types/handlers.d.ts +72 -0
- package/dist/types/index.browser.d.ts +0 -1
- package/dist/types/index.d.ts +0 -1
- package/dist/types/localization.d.ts +1 -1
- package/dist/types/manifest/manifest.d.ts +3 -1
- package/dist/types/manifest/validation.d.ts +17 -17
- package/dist/types/structs.d.ts +2 -40
- package/dist/types/ui.d.ts +1 -1
- package/package.json +4 -4
- package/dist/cjs/enum.js +0 -16
- package/dist/cjs/enum.js.map +0 -1
- package/dist/esm/enum.js +0 -12
- package/dist/esm/enum.js.map +0 -1
- package/dist/types/enum.d.ts +0 -10
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n auxiliaryFiles: (await getSnapFiles(basePath, auxiliaryFilePaths)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = await validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = await fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n await validateNpmSnapManifest({\n ...partiallyValidatedFiles,\n manifest,\n });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport async function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): Promise<VirtualFile<SnapManifest>> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = await getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), 'utf8'),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an NPM Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport async function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n await validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["getErrorMessage","assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","writeFileFn","writeFile","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","getSnapFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","auxiliaryFiles","getSnapFiles","localizationFiles","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","selector","snapManifest","paths","Array","isArray","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository"],"mappings":"AAAA,SAASA,eAAe,QAAQ,sBAAsB;AAEtD,SAASC,gBAAgB,EAAEC,MAAM,EAAEC,aAAa,QAAQ,kBAAkB;AAC1E,OAAOC,eAAe,kBAAkB;AACxC,SAASC,YAAYC,EAAE,QAAQ,KAAK;AACpC,OAAOC,eAAe,O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src/manifest/manifest.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n // Intentionally pass null as the encoding here since the files may be binary\n auxiliaryFiles:\n (await getSnapFiles(basePath, auxiliaryFilePaths, null)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = await validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = await fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n await validateNpmSnapManifest({\n ...partiallyValidatedFiles,\n manifest,\n });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport async function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): Promise<VirtualFile<SnapManifest>> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = await getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @param encoding - An optional encoding to pass down to readVirtualFile.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n encoding: BufferEncoding | null = 'utf8',\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), encoding),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an NPM Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport async function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n await validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["getErrorMessage","assertExhaustive","assert","isPlainObject","deepEqual","promises","fs","pathUtils","deepClone","readJsonFile","validateNpmSnap","getSnapChecksum","ProgrammaticallyFixableSnapError","validateSnapShasum","NpmSnapFileNames","SnapValidationFailureReason","readVirtualFile","VirtualFile","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","checkManifest","basePath","writeManifest","sourceCode","writeFileFn","writeFile","warnings","errors","updated","manifestPath","join","Manifest","manifestFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","getSnapFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","getSnapSourceCode","svgIcon","getSnapIcon","auxiliaryFiles","getSnapFiles","localizationFiles","error","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","length","attempts","fixManifest","validateNpmSnapManifest","nextValidationError","Error","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","getWritableManifest","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","undefined","ShasumMismatch","shasum","sourceFilePath","filePath","path","virtualFile","iconPath","selector","snapManifest","paths","Array","isArray","encoding","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository"],"mappings":"AAAA,SAASA,eAAe,QAAQ,sBAAsB;AAEtD,SAASC,gBAAgB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D;IAEA,MAAMnF,mBACJ;QAAEiC;QAAUhB;QAAYuB;QAASE;QAAgBE;IAAkB,GACnE,CAAC,CAAC,EAAE3C,iBAAiBwB,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
package/dist/esm/structs.js
CHANGED
|
@@ -1,55 +1,8 @@
|
|
|
1
1
|
import { isObject } from '@metamask/utils';
|
|
2
2
|
import { bold, green, red } from 'chalk';
|
|
3
3
|
import { resolve } from 'path';
|
|
4
|
-
import { Struct, StructError,
|
|
4
|
+
import { Struct, StructError, create, string, coerce } from 'superstruct';
|
|
5
5
|
import { indent } from './strings';
|
|
6
|
-
/**
|
|
7
|
-
* A wrapper of `superstruct`'s `literal` struct that also defines the name of
|
|
8
|
-
* the struct as the literal value.
|
|
9
|
-
*
|
|
10
|
-
* This is useful for improving the error messages returned by `superstruct`.
|
|
11
|
-
* For example, instead of returning an error like:
|
|
12
|
-
*
|
|
13
|
-
* ```
|
|
14
|
-
* Expected the value to satisfy a union of `literal | literal`, but received: \"baz\"
|
|
15
|
-
* ```
|
|
16
|
-
*
|
|
17
|
-
* This struct will return an error like:
|
|
18
|
-
*
|
|
19
|
-
* ```
|
|
20
|
-
* Expected the value to satisfy a union of `"foo" | "bar"`, but received: \"baz\"
|
|
21
|
-
* ```
|
|
22
|
-
*
|
|
23
|
-
* @param value - The literal value.
|
|
24
|
-
* @returns The `superstruct` struct, which validates that the value is equal
|
|
25
|
-
* to the literal value.
|
|
26
|
-
*/ export function literal(value) {
|
|
27
|
-
return define(JSON.stringify(value), superstructLiteral(value).validator);
|
|
28
|
-
}
|
|
29
|
-
/**
|
|
30
|
-
* A wrapper of `superstruct`'s `union` struct that also defines the schema as
|
|
31
|
-
* the union of the schemas of the structs.
|
|
32
|
-
*
|
|
33
|
-
* This is useful for improving the error messages returned by `superstruct`.
|
|
34
|
-
*
|
|
35
|
-
* @param structs - The structs to union.
|
|
36
|
-
* @param structs."0" - The first struct.
|
|
37
|
-
* @param structs."1" - The remaining structs.
|
|
38
|
-
* @returns The `superstruct` struct, which validates that the value satisfies
|
|
39
|
-
* one of the structs.
|
|
40
|
-
*/ export function union([head, ...tail]) {
|
|
41
|
-
const struct = superstructUnion([
|
|
42
|
-
head,
|
|
43
|
-
...tail
|
|
44
|
-
]);
|
|
45
|
-
return new Struct({
|
|
46
|
-
...struct,
|
|
47
|
-
schema: [
|
|
48
|
-
head,
|
|
49
|
-
...tail
|
|
50
|
-
]
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
6
|
/**
|
|
54
7
|
* A wrapper of `superstruct`'s `string` struct that coerces a value to a string
|
|
55
8
|
* and resolves it relative to the current working directory. This is useful
|
package/dist/esm/structs.js.map
CHANGED
|
@@ -1 +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 * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\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":["isObject","bold","green","red","resolve","Struct","StructError","define","literal","superstructLiteral","union","superstructUnion","create","string","coerce","indent","value","JSON","stringify","validator","head","tail","struct","schema","file","process","cwd","named","name","type","SnapsStructError","constructor","prefix","suffix","failure","failures","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","childStruct","unionNames","replace","formattedFailures"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,kBAAkB;AAC3C,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SACEC,MAAM,EACNC,WAAW,EACXC,MAAM,EACNC,WAAWC,kBAAkB,EAC7BC,SAASC,gBAAgB,EACzBC,MAAM,EACNC,MAAM,EACNC,MAAM,QACD,cAAc;AAGrB,SAASC,MAAM,QAAQ,YAAY;AA6BnC;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,OAAO,SAASP,QAAgDQ,KAAW;IACzE,OAAOT,OACLU,KAAKC,SAAS,CAACF,QACfP,mBAAmBO,OAAOG,SAAS;AAEvC;AAEA;;;;;;;;;;;CAWC,GACD,OAAO,SAAST,MAAwD,CACtEU,M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AWJ,IAAI,CACjE,MACA,gBAAgB,EAAEE,SAAS,CAAC,CAAC;QACjC;QAEA,OAAO,CAAC,EAAEzB,OAAO,EAAEE,QAAQE,OAAO,CAAC,CAAC,CAAC;IACvC;IAEA,IAAIF,QAAQL,IAAI,KAAK,WAAW;QAC9B,yEAAyE;QACzE,0EAA0E;QAC1E,MAAMO,UAAUF,QAAQE,OAAO,CAC5BwB,OAAO,CAAC,wBAAwB,CAAC,kBAAkB,EAAE1D,MAAM,MAAM,GAAG,CAAC,EACrE0D,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,EAAEzD,IAAI,MAAM,CAAC;QAElE,OAAO,CAAC,EAAE6B,OAAO,EAAEI,QAAQ,CAAC,CAAC;IAC/B;IAEA,IAAIF,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAE5B,KACrBiC,QAAQW,IAAI,CAACU,IAAI,CAAC,MAClB,YAAY,EAAEE,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAEzB,OAAO,yBAAyB,EAAE9B,MAC1CgC,QAAQL,IAAI,EACZ,gBAAgB,EAAE4B,SAAS,CAAC,CAAC;AACjC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASpB,sBACdf,MAA4B,EAC5Ba,QAAmB;IAEnB,MAAM0B,oBAAoB1B,SAASiB,GAAG,CAAC,CAAClB,UACtCnB,OAAO,CAAC,EAAE,EAAEyC,wBAAwBlC,QAAQY,SAAS,CAAC;IAGxD,OAAO2B,kBAAkBN,IAAI,CAAC;AAChC"}
|
|
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 } from 'superstruct';\nimport { Struct, StructError, create, string, coerce } from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\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":["isObject","bold","green","red","resolve","Struct","StructError","create","string","coerce","indent","file","value","process","cwd","named","name","struct","type","SnapsStructError","constructor","prefix","suffix","failure","failures","message","getStructErrorMessage","arrayToGenerator","array","item","getError","error","createFromStruct","getStructFromPath","path","reduce","result","key","schema","getUnionStructNames","Array","isArray","map","getStructErrorPrefix","length","join","getStructFailureMessage","received","JSON","stringify","childStruct","unionNames","replace","formattedFailures"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,kBAAkB;AAC3C,SAASC,IAAI,EAAEC,KAAK,EAAEC,GAAG,QAAQ,QAAQ;AACzC,SAASC,OAAO,QAAQ,OAAO;AAE/B,SAASC,MAAM,EAAEC,WAAW,EAAEC,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,cAAc;AAG1E,SAASC,MAAM,QAAQ,YAAY;AA6BnC;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC;IACd,OAAOF,OAAOD,UAAUA,UAAU,CAACI;QACjC,OAAOR,QAAQS,QAAQC,GAAG,IAAIF;IAChC;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASG,MACdC,IAAY,EACZC,MAA4B;IAE5B,OAAO,IAAIZ,OAAO;QAChB,GAAGY,MAAM;QACTC,MAAMF;IACR;AACF;AAEA,OAAO,MAAMG,yBAAuCb;IAClDc,YACEH,MAA4B,EAC5BI,MAAc,EACdC,MAAc,EACdC,OAAoB,EACpBC,QAAkC,CAClC;QACA,KAAK,CAACD,SAASC;QAEf,IAAI,CAACR,IAAI,GAAG;QACZ,IAAI,CAACS,OAAO,GAAG,CAAC,EAAEJ,OAAO,KAAK,EAAEK,sBAAsBT,QAAQ;eACzDO;SACJ,EAAE,EAAEF,SAAS,CAAC,IAAI,EAAEA,OAAO,CAAC,GAAG,GAAG,CAAC;IACtC;AACF;AASA;;;;;;;CAOC,GACD,OAAO,UAAUK,iBACfC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B,oBAAoB7B,SAASkB,GAAG,CAAC,CAACnB,UACtCb,OAAO,CAAC,EAAE,EAAEoC,wBAAwB7B,QAAQM,SAAS,CAAC;IAGxD,OAAO8B,kBAAkBR,IAAI,CAAC;AAChC"}
|
package/dist/esm/ui.js
CHANGED
|
@@ -1,30 +1,32 @@
|
|
|
1
1
|
import { NodeType } from '@metamask/snaps-sdk';
|
|
2
|
-
import { assert, AssertionError
|
|
3
|
-
const
|
|
2
|
+
import { assert, AssertionError } from '@metamask/utils';
|
|
3
|
+
const MARKDOWN_LINK_REGEX = RegExp("\\[(?<name>[^\\]]*)\\]\\((?<url>[^)]+)\\)", "giu");
|
|
4
4
|
const ALLOWED_PROTOCOLS = [
|
|
5
5
|
'https:',
|
|
6
6
|
'mailto:'
|
|
7
7
|
];
|
|
8
8
|
/**
|
|
9
|
-
*
|
|
9
|
+
* Searches for markdown links in a string and checks them against the phishing list.
|
|
10
10
|
*
|
|
11
11
|
* @param text - The text to verify.
|
|
12
12
|
* @param isOnPhishingList - The function that checks the link against the
|
|
13
13
|
* phishing list.
|
|
14
14
|
* @throws If the text contains a link that is not allowed.
|
|
15
15
|
*/ export function validateTextLinks(text, isOnPhishingList) {
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
})
|
|
16
|
+
const matches = String.prototype.matchAll.call(text, MARKDOWN_LINK_REGEX);
|
|
17
|
+
for (const { groups } of matches){
|
|
18
|
+
const link = groups?.url;
|
|
19
|
+
/* This case should never happen with the regex but the TS type allows for undefined */ /* istanbul ignore next */ if (!link) {
|
|
20
|
+
continue;
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
const url = new URL(link);
|
|
24
|
+
assert(ALLOWED_PROTOCOLS.includes(url.protocol), `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`);
|
|
25
|
+
const hostname = url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;
|
|
26
|
+
assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');
|
|
27
|
+
} catch (error) {
|
|
28
|
+
throw new Error(`Invalid URL: ${error instanceof AssertionError ? error.message : 'Unable to parse URL.'}`);
|
|
29
|
+
}
|
|
28
30
|
}
|
|
29
31
|
}
|
|
30
32
|
/**
|
|
@@ -40,7 +42,7 @@ const ALLOWED_PROTOCOLS = [
|
|
|
40
42
|
if (type === NodeType.Panel) {
|
|
41
43
|
component.children.forEach((node)=>validateComponentLinks(node, isOnPhishingList));
|
|
42
44
|
}
|
|
43
|
-
if (
|
|
45
|
+
if (type === NodeType.Text) {
|
|
44
46
|
validateTextLinks(component.value, isOnPhishingList);
|
|
45
47
|
}
|
|
46
48
|
}
|
package/dist/esm/ui.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/ui.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport { assert, AssertionError
|
|
1
|
+
{"version":3,"sources":["../../src/ui.ts"],"sourcesContent":["import type { Component } from '@metamask/snaps-sdk';\nimport { NodeType } from '@metamask/snaps-sdk';\nimport { assert, AssertionError } from '@metamask/utils';\n\nconst MARKDOWN_LINK_REGEX = /\\[(?<name>[^\\]]*)\\]\\((?<url>[^)]+)\\)/giu;\n\nconst ALLOWED_PROTOCOLS = ['https:', 'mailto:'];\n\n/**\n * Searches for markdown links in a string and checks them against the phishing list.\n *\n * @param text - The text to verify.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the text contains a link that is not allowed.\n */\nexport function validateTextLinks(\n text: string,\n isOnPhishingList: (url: string) => boolean,\n) {\n const matches = String.prototype.matchAll.call(text, MARKDOWN_LINK_REGEX);\n\n for (const { groups } of matches) {\n const link = groups?.url;\n\n /* This case should never happen with the regex but the TS type allows for undefined */\n /* istanbul ignore next */\n if (!link) {\n continue;\n }\n\n try {\n const url = new URL(link);\n assert(\n ALLOWED_PROTOCOLS.includes(url.protocol),\n `Protocol must be one of: ${ALLOWED_PROTOCOLS.join(', ')}.`,\n );\n\n const hostname =\n url.protocol === 'mailto:' ? url.pathname.split('@')[1] : url.hostname;\n\n assert(!isOnPhishingList(hostname), 'The specified URL is not allowed.');\n } catch (error) {\n throw new Error(\n `Invalid URL: ${\n error instanceof AssertionError\n ? error.message\n : 'Unable to parse URL.'\n }`,\n );\n }\n }\n}\n\n/**\n * Search for links in UI components and check that the URL they are trying to\n * pass in is not in the phishing list.\n *\n * @param component - The custom UI component.\n * @param isOnPhishingList - The function that checks the link against the\n * phishing list.\n * @throws If the component contains a link that is not allowed.\n */\nexport function validateComponentLinks(\n component: Component,\n isOnPhishingList: (url: string) => boolean,\n) {\n const { type } = component;\n if (type === NodeType.Panel) {\n component.children.forEach((node) =>\n validateComponentLinks(node, isOnPhishingList),\n );\n }\n\n if (type === NodeType.Text) {\n validateTextLinks(component.value, isOnPhishingList);\n }\n}\n"],"names":["NodeType","assert","AssertionError","MARKDOWN_LINK_REGEX","ALLOWED_PROTOCOLS","validateTextLinks","text","isOnPhishingList","matches","String","prototype","matchAll","call","groups","link","url","URL","includes","protocol","join","hostname","pathname","split","error","Error","message","validateComponentLinks","component","type","Panel","children","forEach","node","Text","value"],"mappings":"AACA,SAASA,QAAQ,QAAQ,sBAAsB;AAC/C,SAASC,MAAM,EAAEC,cAAc,QAAQ,kBAAkB;AAEzD,MAAMC,sBAAsB;AAE5B,MAAMC,oBAAoB;IAAC;IAAU;CAAU;AAE/C;;;;;;;CAOC,GACD,OAAO,SAASC,kBACdC,IAAY,EACZC,gBAA0C;IAE1C,MAAMC,UAAUC,OAAOC,SAAS,CAACC,QAAQ,CAACC,IAAI,CAACN,MAAMH;IAErD,KAAK,MAAM,EAAEU,MAAM,EAAE,IAAIL,QAAS;QAChC,MAAMM,OAAOD,QAAQE;QAErB,qFAAqF,GACrF,wBAAwB,GACxB,IAAI,CAACD,MAAM;YACT;QACF;QAEA,IAAI;YACF,MAAMC,MAAM,IAAIC,IAAIF;YACpBb,OACEG,kBAAkBa,QAAQ,CAACF,IAAIG,QAAQ,GACvC,CAAC,yBAAyB,EAAEd,kBAAkBe,IAAI,CAAC,MAAM,CAAC,CAAC;YAG7D,MAAMC,WACJL,IAAIG,QAAQ,KAAK,YAAYH,IAAIM,QAAQ,CAACC,KAAK,CAAC,IAAI,CAAC,EAAE,GAAGP,IAAIK,QAAQ;YAExEnB,OAAO,CAACM,iBAAiBa,WAAW;QACtC,EAAE,OAAOG,OAAO;YACd,MAAM,IAAIC,MACR,CAAC,aAAa,EACZD,iBAAiBrB,iBACbqB,MAAME,OAAO,GACb,uBACL,CAAC;QAEN;IACF;AACF;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASC,uBACdC,SAAoB,EACpBpB,gBAA0C;IAE1C,MAAM,EAAEqB,IAAI,EAAE,GAAGD;IACjB,IAAIC,SAAS5B,SAAS6B,KAAK,EAAE;QAC3BF,UAAUG,QAAQ,CAACC,OAAO,CAAC,CAACC,OAC1BN,uBAAuBM,MAAMzB;IAEjC;IAEA,IAAIqB,SAAS5B,SAASiC,IAAI,EAAE;QAC1B5B,kBAAkBsB,UAAUO,KAAK,EAAE3B;IACrC;AACF"}
|
package/dist/types/cronjob.d.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import type { Infer } from 'superstruct';
|
|
2
2
|
export declare const CronjobRpcRequestStruct: import("superstruct").Struct<{
|
|
3
3
|
method: string;
|
|
4
|
-
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
5
4
|
id?: string | number | null | undefined;
|
|
6
5
|
jsonrpc?: "2.0" | undefined;
|
|
6
|
+
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
7
7
|
}, {
|
|
8
|
-
|
|
8
|
+
jsonrpc: import("superstruct").Struct<"2.0" | undefined, "2.0">;
|
|
9
|
+
id: import("superstruct").Struct<string | number | null | undefined, null>;
|
|
9
10
|
method: import("superstruct").Struct<string, null>;
|
|
10
|
-
|
|
11
|
-
jsonrpc: import("superstruct").Struct<"2.0" | undefined, unknown>;
|
|
11
|
+
params: import("superstruct").Struct<Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined, null>;
|
|
12
12
|
}>;
|
|
13
13
|
export declare type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;
|
|
14
14
|
export declare const CronExpressionStruct: import("superstruct").Struct<string, null>;
|
|
@@ -23,23 +23,23 @@ export declare function parseCronExpression(expression: string | object): import
|
|
|
23
23
|
export declare const CronjobSpecificationStruct: import("superstruct").Struct<{
|
|
24
24
|
request: {
|
|
25
25
|
method: string;
|
|
26
|
-
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
27
26
|
id?: string | number | null | undefined;
|
|
28
27
|
jsonrpc?: "2.0" | undefined;
|
|
28
|
+
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
29
29
|
};
|
|
30
30
|
expression: string;
|
|
31
31
|
}, {
|
|
32
32
|
expression: import("superstruct").Struct<string, null>;
|
|
33
33
|
request: import("superstruct").Struct<{
|
|
34
34
|
method: string;
|
|
35
|
-
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
36
35
|
id?: string | number | null | undefined;
|
|
37
36
|
jsonrpc?: "2.0" | undefined;
|
|
37
|
+
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
38
38
|
}, {
|
|
39
|
-
|
|
39
|
+
jsonrpc: import("superstruct").Struct<"2.0" | undefined, "2.0">;
|
|
40
|
+
id: import("superstruct").Struct<string | number | null | undefined, null>;
|
|
40
41
|
method: import("superstruct").Struct<string, null>;
|
|
41
|
-
|
|
42
|
-
jsonrpc: import("superstruct").Struct<"2.0" | undefined, unknown>;
|
|
42
|
+
params: import("superstruct").Struct<Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined, null>;
|
|
43
43
|
}>;
|
|
44
44
|
}>;
|
|
45
45
|
export declare type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;
|
|
@@ -53,31 +53,31 @@ export declare function isCronjobSpecification(value: unknown): boolean;
|
|
|
53
53
|
export declare const CronjobSpecificationArrayStruct: import("superstruct").Struct<{
|
|
54
54
|
request: {
|
|
55
55
|
method: string;
|
|
56
|
-
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
57
56
|
id?: string | number | null | undefined;
|
|
58
57
|
jsonrpc?: "2.0" | undefined;
|
|
58
|
+
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
59
59
|
};
|
|
60
60
|
expression: string;
|
|
61
61
|
}[], import("superstruct").Struct<{
|
|
62
62
|
request: {
|
|
63
63
|
method: string;
|
|
64
|
-
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
65
64
|
id?: string | number | null | undefined;
|
|
66
65
|
jsonrpc?: "2.0" | undefined;
|
|
66
|
+
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
67
67
|
};
|
|
68
68
|
expression: string;
|
|
69
69
|
}, {
|
|
70
70
|
expression: import("superstruct").Struct<string, null>;
|
|
71
71
|
request: import("superstruct").Struct<{
|
|
72
72
|
method: string;
|
|
73
|
-
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
74
73
|
id?: string | number | null | undefined;
|
|
75
74
|
jsonrpc?: "2.0" | undefined;
|
|
75
|
+
params?: Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined;
|
|
76
76
|
}, {
|
|
77
|
-
|
|
77
|
+
jsonrpc: import("superstruct").Struct<"2.0" | undefined, "2.0">;
|
|
78
|
+
id: import("superstruct").Struct<string | number | null | undefined, null>;
|
|
78
79
|
method: import("superstruct").Struct<string, null>;
|
|
79
|
-
|
|
80
|
-
jsonrpc: import("superstruct").Struct<"2.0" | undefined, unknown>;
|
|
80
|
+
params: import("superstruct").Struct<Record<string, import("@metamask/utils").Json> | import("@metamask/utils").Json[] | undefined, null>;
|
|
81
81
|
}>;
|
|
82
82
|
}>>;
|
|
83
83
|
/**
|
package/dist/types/handlers.d.ts
CHANGED
|
@@ -68,6 +68,24 @@ export declare const OnTransactionResponseStruct: import("superstruct").Struct<{
|
|
|
68
68
|
value: string;
|
|
69
69
|
type: import("@metamask/snaps-sdk").NodeType.Text;
|
|
70
70
|
markdown?: boolean | undefined;
|
|
71
|
+
} | {
|
|
72
|
+
value: string;
|
|
73
|
+
type: import("@metamask/snaps-sdk").NodeType.Address;
|
|
74
|
+
} | {
|
|
75
|
+
value: {
|
|
76
|
+
value: string;
|
|
77
|
+
type: import("@metamask/snaps-sdk").NodeType.Image;
|
|
78
|
+
} | {
|
|
79
|
+
value: string;
|
|
80
|
+
type: import("@metamask/snaps-sdk").NodeType.Text;
|
|
81
|
+
markdown?: boolean | undefined;
|
|
82
|
+
} | {
|
|
83
|
+
value: string;
|
|
84
|
+
type: import("@metamask/snaps-sdk").NodeType.Address;
|
|
85
|
+
};
|
|
86
|
+
type: import("@metamask/snaps-sdk").NodeType.Row;
|
|
87
|
+
label: string;
|
|
88
|
+
variant?: "default" | "warning" | "critical" | undefined;
|
|
71
89
|
};
|
|
72
90
|
severity?: SeverityLevel | undefined;
|
|
73
91
|
} | null, {
|
|
@@ -89,6 +107,24 @@ export declare const OnTransactionResponseStruct: import("superstruct").Struct<{
|
|
|
89
107
|
value: string;
|
|
90
108
|
type: import("@metamask/snaps-sdk").NodeType.Text;
|
|
91
109
|
markdown?: boolean | undefined;
|
|
110
|
+
} | {
|
|
111
|
+
value: string;
|
|
112
|
+
type: import("@metamask/snaps-sdk").NodeType.Address;
|
|
113
|
+
} | {
|
|
114
|
+
value: {
|
|
115
|
+
value: string;
|
|
116
|
+
type: import("@metamask/snaps-sdk").NodeType.Image;
|
|
117
|
+
} | {
|
|
118
|
+
value: string;
|
|
119
|
+
type: import("@metamask/snaps-sdk").NodeType.Text;
|
|
120
|
+
markdown?: boolean | undefined;
|
|
121
|
+
} | {
|
|
122
|
+
value: string;
|
|
123
|
+
type: import("@metamask/snaps-sdk").NodeType.Address;
|
|
124
|
+
};
|
|
125
|
+
type: import("@metamask/snaps-sdk").NodeType.Row;
|
|
126
|
+
label: string;
|
|
127
|
+
variant?: "default" | "warning" | "critical" | undefined;
|
|
92
128
|
}, null>;
|
|
93
129
|
severity: import("superstruct").Struct<SeverityLevel | undefined, SeverityLevel>;
|
|
94
130
|
}>;
|
|
@@ -111,6 +147,24 @@ export declare const OnHomePageResponseStruct: import("superstruct").Struct<{
|
|
|
111
147
|
value: string;
|
|
112
148
|
type: import("@metamask/snaps-sdk").NodeType.Text;
|
|
113
149
|
markdown?: boolean | undefined;
|
|
150
|
+
} | {
|
|
151
|
+
value: string;
|
|
152
|
+
type: import("@metamask/snaps-sdk").NodeType.Address;
|
|
153
|
+
} | {
|
|
154
|
+
value: {
|
|
155
|
+
value: string;
|
|
156
|
+
type: import("@metamask/snaps-sdk").NodeType.Image;
|
|
157
|
+
} | {
|
|
158
|
+
value: string;
|
|
159
|
+
type: import("@metamask/snaps-sdk").NodeType.Text;
|
|
160
|
+
markdown?: boolean | undefined;
|
|
161
|
+
} | {
|
|
162
|
+
value: string;
|
|
163
|
+
type: import("@metamask/snaps-sdk").NodeType.Address;
|
|
164
|
+
};
|
|
165
|
+
type: import("@metamask/snaps-sdk").NodeType.Row;
|
|
166
|
+
label: string;
|
|
167
|
+
variant?: "default" | "warning" | "critical" | undefined;
|
|
114
168
|
};
|
|
115
169
|
}, {
|
|
116
170
|
content: import("superstruct").Struct<import("@metamask/snaps-sdk").Panel | {
|
|
@@ -131,6 +185,24 @@ export declare const OnHomePageResponseStruct: import("superstruct").Struct<{
|
|
|
131
185
|
value: string;
|
|
132
186
|
type: import("@metamask/snaps-sdk").NodeType.Text;
|
|
133
187
|
markdown?: boolean | undefined;
|
|
188
|
+
} | {
|
|
189
|
+
value: string;
|
|
190
|
+
type: import("@metamask/snaps-sdk").NodeType.Address;
|
|
191
|
+
} | {
|
|
192
|
+
value: {
|
|
193
|
+
value: string;
|
|
194
|
+
type: import("@metamask/snaps-sdk").NodeType.Image;
|
|
195
|
+
} | {
|
|
196
|
+
value: string;
|
|
197
|
+
type: import("@metamask/snaps-sdk").NodeType.Text;
|
|
198
|
+
markdown?: boolean | undefined;
|
|
199
|
+
} | {
|
|
200
|
+
value: string;
|
|
201
|
+
type: import("@metamask/snaps-sdk").NodeType.Address;
|
|
202
|
+
};
|
|
203
|
+
type: import("@metamask/snaps-sdk").NodeType.Row;
|
|
204
|
+
label: string;
|
|
205
|
+
variant?: "default" | "warning" | "critical" | undefined;
|
|
134
206
|
}, null>;
|
|
135
207
|
}>;
|
|
136
208
|
/**
|
package/dist/types/index.d.ts
CHANGED
|
@@ -108,9 +108,9 @@ export declare function getLocalizedSnapManifest(snapManifest: SnapManifest, loc
|
|
|
108
108
|
jobs: {
|
|
109
109
|
request: {
|
|
110
110
|
method: string;
|
|
111
|
-
params?: Record<string, import("@metamask/snaps-sdk").Json> | import("@metamask/snaps-sdk").Json[] | undefined;
|
|
112
111
|
id?: string | number | null | undefined;
|
|
113
112
|
jsonrpc?: "2.0" | undefined;
|
|
113
|
+
params?: Record<string, import("@metamask/snaps-sdk").Json> | import("@metamask/snaps-sdk").Json[] | undefined;
|
|
114
114
|
};
|
|
115
115
|
expression: string;
|
|
116
116
|
}[];
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
1
2
|
import type { Json } from '@metamask/utils';
|
|
2
3
|
import { ProgrammaticallyFixableSnapError } from '../snaps';
|
|
3
4
|
import type { SnapFiles } from '../types';
|
|
@@ -80,9 +81,10 @@ export declare function getSnapFilePaths(manifest: Json, selector: (manifest: Pa
|
|
|
80
81
|
*
|
|
81
82
|
* @param basePath - The path to the folder with the manifest files.
|
|
82
83
|
* @param paths - The paths to the files.
|
|
84
|
+
* @param encoding - An optional encoding to pass down to readVirtualFile.
|
|
83
85
|
* @returns A list of auxiliary files and their contents, if any.
|
|
84
86
|
*/
|
|
85
|
-
export declare function getSnapFiles(basePath: string, paths: string[] | undefined): Promise<VirtualFile[] | undefined>;
|
|
87
|
+
export declare function getSnapFiles(basePath: string, paths: string[] | undefined, encoding?: BufferEncoding | null): Promise<VirtualFile[] | undefined>;
|
|
86
88
|
/**
|
|
87
89
|
* Sorts the given manifest in our preferred sort order and removes the
|
|
88
90
|
* `repository` field if it is falsy (it may be `null`).
|