@metamask/snaps-utils 0.36.1-flask.1 → 0.37.1-flask.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/dist/cjs/cronjob.js.map +1 -1
- package/dist/cjs/enum.js.map +1 -1
- package/dist/cjs/eval-worker.js.map +1 -1
- package/dist/cjs/fs.js.map +1 -1
- package/dist/cjs/icon.js.map +1 -1
- package/dist/cjs/json-rpc.js.map +1 -1
- package/dist/cjs/json.js.map +1 -1
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/namespace.js.map +1 -1
- package/dist/cjs/npm.js.map +1 -1
- package/dist/cjs/post-process.js.map +1 -1
- package/dist/cjs/snaps.js.map +1 -1
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/validation.js.map +1 -1
- package/dist/cjs/versions.js.map +1 -1
- package/dist/esm/cronjob.js.map +1 -1
- package/dist/esm/enum.js.map +1 -1
- package/dist/esm/eval-worker.js.map +1 -1
- package/dist/esm/fs.js.map +1 -1
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/icon.js.map +1 -1
- package/dist/esm/json-rpc.js.map +1 -1
- package/dist/esm/json.js.map +1 -1
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/namespace.js.map +1 -1
- package/dist/esm/npm.js.map +1 -1
- package/dist/esm/post-process.js.map +1 -1
- package/dist/esm/snaps.js.map +1 -1
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/validation.js.map +1 -1
- package/dist/esm/versions.js.map +1 -1
- package/dist/types/cronjob.d.ts +1 -1
- package/dist/types/enum.d.ts +1 -1
- package/dist/types/fs.d.ts +2 -2
- package/dist/types/handlers.d.ts +2 -2
- package/dist/types/icon.d.ts +1 -1
- package/dist/types/json-rpc.d.ts +2 -2
- package/dist/types/json.d.ts +1 -1
- package/dist/types/manifest/manifest.d.ts +3 -3
- package/dist/types/manifest/validation.d.ts +3 -3
- package/dist/types/namespace.d.ts +1 -1
- package/dist/types/npm.d.ts +2 -1
- package/dist/types/snaps.d.ts +8 -7
- package/dist/types/types.d.ts +13 -13
- package/dist/types/validation.d.ts +1 -1
- package/dist/types/versions.d.ts +1 -1
- package/package.json +9 -8
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.37.1-flask.1]
|
|
10
|
+
### Changed
|
|
11
|
+
- No changes this release.
|
|
12
|
+
|
|
13
|
+
## [0.37.0-flask.1]
|
|
14
|
+
### Changed
|
|
15
|
+
- No changes this release.
|
|
16
|
+
|
|
9
17
|
## [0.36.1-flask.1]
|
|
10
18
|
### Changed
|
|
11
19
|
- No changes this release.
|
|
@@ -242,7 +250,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
242
250
|
### Added
|
|
243
251
|
- Initial release ([#410](https://github.com/MetaMask/snaps-monorepo/pull/410), [#421](https://github.com/MetaMask/snaps-monorepo/pull/421))
|
|
244
252
|
|
|
245
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/v0.
|
|
253
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/v0.37.1-flask.1...HEAD
|
|
254
|
+
[0.37.1-flask.1]: https://github.com/MetaMask/snaps/compare/v0.37.0-flask.1...v0.37.1-flask.1
|
|
255
|
+
[0.37.0-flask.1]: https://github.com/MetaMask/snaps/compare/v0.36.1-flask.1...v0.37.0-flask.1
|
|
246
256
|
[0.36.1-flask.1]: https://github.com/MetaMask/snaps/compare/v0.36.0-flask.1...v0.36.1-flask.1
|
|
247
257
|
[0.36.0-flask.1]: https://github.com/MetaMask/snaps/compare/v0.35.2-flask.1...v0.36.0-flask.1
|
|
248
258
|
[0.35.2-flask.1]: https://github.com/MetaMask/snaps/compare/v0.35.1-flask.1...v0.35.2-flask.1
|
package/dist/cjs/cronjob.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport {\n array,\n assign,\n coerce,\n create,\n
|
|
1
|
+
{"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n assign,\n coerce,\n create,\n object,\n omit,\n optional,\n partial,\n pick,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["CronjobRpcRequestStruct","CronExpressionStruct","parseCronExpression","CronjobSpecificationStruct","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray","assign","partial","pick","JsonRpcRequestStruct","omit","refine","coerce","string","object","minute","optional","hour","dayOfMonth","month","dayOfWeek","value","parseExpression","expression","ensureStringExpression","create","request","array"],"mappings":";;;;;;;;;;;IAiBaA,uBAAuB;eAAvBA;;IAMAC,oBAAoB;eAApBA;;IAkCGC,mBAAmB;eAAnBA;;IAKHC,0BAA0B;eAA1BA;;IAYGC,sBAAsB;eAAtBA;;IASHC,+BAA+B;eAA/BA;;IAUGC,2BAA2B;eAA3BA;;;uBA7FqB;4BACL;6BAczB;AAEA,MAAMN,0BAA0BO,IAAAA,mBAAM,EAC3CC,IAAAA,oBAAO,EAACC,IAAAA,iBAAI,EAACC,2BAAoB,EAAE;IAAC;IAAM;CAAU,IACpDC,IAAAA,iBAAI,EAACD,2BAAoB,EAAE;IAAC;IAAM;CAAU;AAIvC,MAAMT,uBAAuBW,IAAAA,mBAAM,EACxCC,IAAAA,mBAAM,EACJC,IAAAA,mBAAM,KACNC,IAAAA,mBAAM,EAAC;IACLC,QAAQC,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IACvBI,MAAMD,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IACrBK,YAAYF,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IAC3BM,OAAOH,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IACtBO,WAAWJ,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;AAC5B,IACA,CAACQ,QACC,CAAC,EAAEA,MAAMN,MAAM,IAAI,IAAI,CAAC,EAAEM,MAAMJ,IAAI,IAAI,IAAI,CAAC,EAAEI,MAAMH,UAAU,IAAI,IAAI,CAAC,EACtEG,MAAMF,KAAK,IAAI,IAChB,CAAC,EAAEE,MAAMD,SAAS,IAAI,IAAI,CAAC,GAEhC,kBACA,CAACC;IACC,IAAI;QACFC,IAAAA,2BAAe,EAACD;QAChB,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAWK,SAASpB,oBAAoBsB,UAA2B;IAC7D,MAAMC,yBAAyBC,IAAAA,mBAAM,EAACF,YAAYvB;IAClD,OAAOsB,IAAAA,2BAAe,EAACE;AACzB;AAEO,MAAMtB,6BAA6BY,IAAAA,mBAAM,EAAC;IAC/CS,YAAYvB;IACZ0B,SAAS3B;AACX;AASO,SAASI,uBAAuBkB,KAAc;IACnD,IAAI;QACFI,IAAAA,mBAAM,EAACJ,OAAOnB;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEO,MAAME,kCAAkCuB,IAAAA,kBAAK,EAClDzB;AASK,SAASG,4BAA4BgB,KAAc;IACxD,IAAI;QACFI,IAAAA,mBAAM,EAACJ,OAAOjB;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
|
package/dist/cjs/enum.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/enum.ts"],"sourcesContent":["import type { Struct } from 'superstruct';\nimport { literal } from 'superstruct';\n\n/**\n * Get the enum values as union type. This allows using both the enum string\n * values and the enum itself as values.\n *\n * Note: This only works for string enums.\n *\n * @example\n * ```typescript\n * enum Foo {\n * Bar = 'bar',\n * Baz = 'baz',\n * }\n *\n * type FooValue = EnumToUnion<Foo>;\n * // FooValue is 'bar' | 'baz'\n *\n * const foo: FooValue = Foo.Bar; // Works\n * const foo: FooValue = 'bar'; // Also works\n * ```\n */\nexport type EnumToUnion<Type extends string> = `${Type}`;\n\n/**\n * Superstruct struct for validating an enum value. This allows using both the\n * enum string values and the enum itself as values.\n *\n * @param constant - The enum to validate against.\n * @returns The superstruct struct.\n */\nexport function enumValue<Type extends string>(\n constant: Type,\n): Struct<EnumToUnion<Type>, EnumToUnion<Type>> {\n return literal(constant as EnumToUnion<Type>);\n}\n"],"names":["enumValue","constant","literal"],"mappings":";;;;+BAgCgBA;;;eAAAA;;;6BA/BQ;AA+BjB,SAASA,UACdC,QAAc;IAEd,OAAOC,IAAAA,oBAAO,EAACD;AACjB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport { generateMockEndowments } from './mock';\nimport { HandlerType
|
|
1
|
+
{"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport { generateMockEndowments } from './mock';\nimport type { HandlerType } from './types';\nimport { SNAP_EXPORT_NAMES } from './types';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\n/**\n * Get mock endowments that don't do anything. This is useful for running the\n * eval, for snaps that try to communicate with the extension on initialisation,\n * for example.\n *\n * @returns The mock endowments.\n */\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nnew Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n}).evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"],"names":["lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","getMockEndowments","endowments","generateMockEndowments","window","self","snapFilePath","process","argv","snapModule","exports","Compartment","module","evaluate","readFileSync","invalidExports","Object","keys","filter","snapExport","SNAP_EXPORT_NAMES","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;;;;;QAChD;oBAEsB;sBAEU;uBAEL;AAIlCA,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA;;;;;;CAMC,GACD,SAASC;IACP,MAAMC,aAAaC,IAAAA,4BAAsB;IACzC,OAAO;QACL,GAAGD,UAAU;QACbE,QAAQF;QACRG,MAAMH;IACR;AACF;AAEA,MAAMI,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,IAAIC,YAAY;IACd,GAAGV,mBAAmB;IACtBW,QAAQH;IACRC,SAASD,WAAWC,OAAO;AAC7B,GAAGG,QAAQ,CAACC,IAAAA,gBAAY,EAACR,cAAc;AAEvC,MAAMS,iBAAiBC,OAAOC,IAAI,CAACR,WAAWC,OAAO,EAAEQ,MAAM,CAC3D,CAACC,aAAe,CAACC,wBAAiB,CAACC,QAAQ,CAACF;AAG9C,IAAIJ,eAAeO,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAET,eAAeU,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMnB,QAAQoB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
|
package/dist/cjs/fs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/fs.ts"],"sourcesContent":["import { Json } from '@metamask/utils';\nimport { promises as fs } from 'fs';\nimport os from 'os';\nimport pathUtils from 'path';\n\nimport { parseJson } from './json';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/fs.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { promises as fs } from 'fs';\nimport os from 'os';\nimport pathUtils from 'path';\n\nimport { parseJson } from './json';\nimport type { VirtualFile } from './virtual-file';\nimport { readVirtualFile } from './virtual-file';\n\n/**\n * Checks whether the given path string resolves to an existing directory, and\n * optionally creates the directory if it doesn't exist.\n *\n * @param pathString - The path string to check.\n * @param createDir - Whether to create the directory if it doesn't exist.\n * @returns Whether the given path is an existing directory.\n */\nexport async function isDirectory(\n pathString: string,\n createDir: boolean,\n): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isDirectory();\n } catch (error) {\n if (error.code === 'ENOENT') {\n if (!createDir) {\n return false;\n }\n\n await fs.mkdir(pathString, { recursive: true });\n return true;\n }\n\n return false;\n }\n}\n\n/**\n * Checks whether the given path string resolves to an existing file.\n *\n * @param pathString - The path string to check.\n * @returns Whether the given path is an existing file.\n */\nexport async function isFile(pathString: string): Promise<boolean> {\n try {\n const stats = await fs.stat(pathString);\n return stats.isFile();\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Reads a `.json` file, parses its contents, and returns them.\n *\n * @param pathString - The path to the JSON file.\n * @returns The parsed contents of the JSON file.\n */\nexport async function readJsonFile<Type extends Json = Json>(\n pathString: string,\n): Promise<VirtualFile<Type>> {\n if (!pathString.endsWith('.json')) {\n throw new Error('The specified file must be a \".json\" file.');\n }\n\n let file;\n try {\n file = await readVirtualFile(pathString, 'utf8');\n } catch (error) {\n if (error.code === 'ENOENT') {\n throw new Error(\n `Could not find '${pathString}'. Please ensure that the file exists.`,\n );\n }\n\n throw error;\n }\n file.result = parseJson(file.toString());\n return file as VirtualFile<Type>;\n}\n\n/**\n * Gets the complete out file path from an output file name and parent\n * directory path.\n *\n * @param outDir - The path to the out file's parent directory.\n * @param outFileName - The out file's name.\n * @returns The complete path to the out file.\n */\nexport function getOutfilePath(outDir: string, outFileName: string): string {\n return pathUtils.join(outDir, outFileName || 'bundle.js');\n}\n\n/**\n * Ensures that the outfile name is just a `.js` file name.\n * Throws on validation failure.\n *\n * @param filename - The file name to validate.\n * @returns `true` if validation succeeded.\n * @throws If the file name is invalid.\n */\nexport function validateOutfileName(filename: string): boolean {\n if (\n !filename.endsWith('.js') ||\n filename === '.js' ||\n pathUtils.basename(filename) !== filename\n ) {\n throw new Error(`Invalid outfile name: ${filename}. Must be a .js file`);\n }\n return true;\n}\n\n/**\n * Validates a file path. Throws on validation failure.\n *\n * @param filePath - The file path to validate.\n * @returns `true` if validation succeeded.\n * @throws If the path does not resolve to a file.\n */\nexport async function validateFilePath(filePath: string): Promise<boolean> {\n const exists = await isFile(filePath);\n if (!exists) {\n throw new Error(\n `Invalid params: '${filePath}' is not a file or does not exist.`,\n );\n }\n return true;\n}\n\n/**\n * Validates a directory path. Throws on validation failure.\n *\n * @param dirPath - The directory path to validate.\n * @param createDir - Whether to create the directory if it doesn't exist.\n * @returns `true` if validation succeeded or the directory was created.\n * @throws If the directory does not exist or could not be created.\n */\nexport async function validateDirPath(\n dirPath: string,\n createDir: boolean,\n): Promise<boolean> {\n const exists = await isDirectory(dirPath, createDir);\n if (!exists) {\n throw new Error(\n `Invalid params: '${dirPath}' is not a directory or could not be created.`,\n );\n }\n return true;\n}\n\n/**\n * Creates a temporary file with a given name and content, writes it to disk and calls the provided function.\n * This function handles deletion of the temporary file after usage.\n *\n * @param fileName - The name of the temporary file.\n * @param fileContents - The content of the temporary file.\n * @param fn - The callback function to call when the temporary file has been created.\n */\nexport async function useTemporaryFile(\n fileName: string,\n fileContents: string,\n fn: (path: string) => Promise<unknown>,\n): Promise<void> {\n const filePath = pathUtils.join(os.tmpdir(), fileName);\n await fs.mkdir(pathUtils.dirname(filePath), { recursive: true });\n await fs.writeFile(filePath, fileContents);\n try {\n await fn(filePath);\n } finally {\n if (await isFile(filePath)) {\n await fs.unlink(filePath);\n }\n }\n}\n"],"names":["isDirectory","isFile","readJsonFile","getOutfilePath","validateOutfileName","validateFilePath","validateDirPath","useTemporaryFile","pathString","createDir","stats","fs","stat","error","code","mkdir","recursive","endsWith","Error","file","readVirtualFile","result","parseJson","toString","outDir","outFileName","pathUtils","join","filename","basename","filePath","exists","dirPath","fileName","fileContents","fn","os","tmpdir","dirname","writeFile","unlink"],"mappings":";;;;;;;;;;;IAiBsBA,WAAW;eAAXA;;IA2BAC,MAAM;eAANA;;IAeAC,YAAY;eAAZA;;IA+BNC,cAAc;eAAdA;;IAYAC,mBAAmB;eAAnBA;;IAkBMC,gBAAgB;eAAhBA;;IAkBAC,eAAe;eAAfA;;IAqBAC,gBAAgB;eAAhBA;;;oBA9JS;2DAChB;6DACO;sBAEI;6BAEM;;;;;;AAUzB,eAAeP,YACpBQ,UAAkB,EAClBC,SAAkB;IAElB,IAAI;QACF,MAAMC,QAAQ,MAAMC,YAAE,CAACC,IAAI,CAACJ;QAC5B,OAAOE,MAAMV,WAAW;IAC1B,EAAE,OAAOa,OAAO;QACd,IAAIA,MAAMC,IAAI,KAAK,UAAU;YAC3B,IAAI,CAACL,WAAW;gBACd,OAAO;YACT;YAEA,MAAME,YAAE,CAACI,KAAK,C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,IAAI,CAACsB,QAAQ;QACX,MAAM,IAAIb,MACR,CAAC,iBAAiB,EAAEc,QAAQ,6CAA6C,CAAC;IAE9E;IACA,OAAO;AACT;AAUO,eAAezB,iBACpB0B,QAAgB,EAChBC,YAAoB,EACpBC,EAAsC;IAEtC,MAAML,WAAWJ,aAAS,CAACC,IAAI,CAACS,WAAE,CAACC,MAAM,IAAIJ;IAC7C,MAAMtB,YAAE,CAACI,KAAK,CAACW,aAAS,CAACY,OAAO,CAACR,WAAW;QAAEd,WAAW;IAAK;IAC9D,MAAML,YAAE,CAAC4B,SAAS,CAACT,UAAUI;IAC7B,IAAI;QACF,MAAMC,GAAGL;IACX,SAAU;QACR,IAAI,MAAM7B,OAAO6B,WAAW;YAC1B,MAAMnB,YAAE,CAAC6B,MAAM,CAACV;QAClB;IACF;AACF"}
|
package/dist/cjs/icon.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/icon.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\nimport isSvg from 'is-svg';\n\nimport { VirtualFile } from './virtual-file';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\nexport const assertIsSnapIcon = (icon: VirtualFile) => {\n assert(icon.path.endsWith('.svg'), 'Expected snap icon to end in \".svg\".');\n\n assert(\n Buffer.byteLength(icon.value, 'utf8') <= SVG_MAX_BYTE_SIZE,\n `The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n\n assert(isSvg(icon.toString()), 'Snap icon must be a valid SVG.');\n};\n"],"names":["SVG_MAX_BYTE_SIZE","SVG_MAX_BYTE_SIZE_TEXT","assertIsSnapIcon","Math","floor","icon","assert","path","endsWith","Buffer","byteLength","value","isSvg","toString"],"mappings":";;;;;;;;;;;IAKaA,iBAAiB;eAAjBA;;IACAC,sBAAsB;eAAtBA;;IAIAC,gBAAgB;eAAhBA;;;uBAVU;8DACL;;;;;;AAIX,MAAMF,oBAAoB;AAC1B,MAAMC,yBAAyB,CAAC,EAAEE,KAAKC,KAAK,CACjDJ,oBAAoB,MACpB,EAAE,CAAC;AAEE,MAAME,mBAAmB,CAACG;IAC/BC,IAAAA,aAAM,EAACD,KAAKE,IAAI,CAACC,QAAQ,CAAC,SAAS;IAEnCF,IAAAA,aAAM,EACJG,OAAOC,UAAU,CAACL,KAAKM,KAAK,EAAE,WAAWX,mBACzC,CAAC,mDAAmD,EAAEC,uBAAuB,CAAC,CAAC;IAGjFK,IAAAA,aAAM,EAACM,IAAAA,cAAK,EAACP,KAAKQ,QAAQ,KAAK;AACjC"}
|
|
1
|
+
{"version":3,"sources":["../../src/icon.ts"],"sourcesContent":["import { assert } from '@metamask/utils';\nimport isSvg from 'is-svg';\n\nimport type { VirtualFile } from './virtual-file';\n\nexport const SVG_MAX_BYTE_SIZE = 100_000;\nexport const SVG_MAX_BYTE_SIZE_TEXT = `${Math.floor(\n SVG_MAX_BYTE_SIZE / 1000,\n)}kb`;\n\nexport const assertIsSnapIcon = (icon: VirtualFile) => {\n assert(icon.path.endsWith('.svg'), 'Expected snap icon to end in \".svg\".');\n\n assert(\n Buffer.byteLength(icon.value, 'utf8') <= SVG_MAX_BYTE_SIZE,\n `The specified SVG icon exceeds the maximum size of ${SVG_MAX_BYTE_SIZE_TEXT}.`,\n );\n\n assert(isSvg(icon.toString()), 'Snap icon must be a valid SVG.');\n};\n"],"names":["SVG_MAX_BYTE_SIZE","SVG_MAX_BYTE_SIZE_TEXT","assertIsSnapIcon","Math","floor","icon","assert","path","endsWith","Buffer","byteLength","value","isSvg","toString"],"mappings":";;;;;;;;;;;IAKaA,iBAAiB;eAAjBA;;IACAC,sBAAsB;eAAtBA;;IAIAC,gBAAgB;eAAhBA;;;uBAVU;8DACL;;;;;;AAIX,MAAMF,oBAAoB;AAC1B,MAAMC,yBAAyB,CAAC,EAAEE,KAAKC,KAAK,CACjDJ,oBAAoB,MACpB,EAAE,CAAC;AAEE,MAAME,mBAAmB,CAACG;IAC/BC,IAAAA,aAAM,EAACD,KAAKE,IAAI,CAACC,QAAQ,CAAC,SAAS;IAEnCF,IAAAA,aAAM,EACJG,OAAOC,UAAU,CAACL,KAAKM,KAAK,EAAE,WAAWX,mBACzC,CAAC,mDAAmD,EAAEC,uBAAuB,CAAC,CAAC;IAGjFK,IAAAA,aAAM,EAACM,IAAAA,cAAK,EAACP,KAAKQ,QAAQ,KAAK;AACjC"}
|
package/dist/cjs/json-rpc.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/json-rpc.ts"],"sourcesContent":["import {\n
|
|
1
|
+
{"version":3,"sources":["../../src/json-rpc.ts"],"sourcesContent":["import type {\n Json,\n JsonRpcSuccess,\n AssertionErrorConstructor,\n} from '@metamask/utils';\nimport {\n isJsonRpcFailure,\n isJsonRpcSuccess,\n assertStruct,\n} from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { boolean, object, optional, refine } from 'superstruct';\n\nexport const RpcOriginsStruct = refine(\n object({\n dapps: optional(boolean()),\n snaps: optional(boolean()),\n }),\n 'RPC origins',\n (value) => {\n if (!Object.values(value).some(Boolean)) {\n throw new Error('Must specify at least one JSON-RPC origin');\n }\n\n return true;\n },\n);\n\nexport type RpcOrigins = Infer<typeof RpcOriginsStruct>;\n\n/**\n * Asserts that the given value is a valid {@link RpcOrigins} object.\n *\n * @param value - The value to assert.\n * @param ErrorWrapper - An optional error wrapper to use. Defaults to\n * {@link AssertionError}.\n * @throws If the value is not a valid {@link RpcOrigins} object.\n */\nexport function assertIsRpcOrigins(\n value: unknown,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ErrorWrapper?: AssertionErrorConstructor,\n): asserts value is RpcOrigins {\n assertStruct(\n value,\n RpcOriginsStruct,\n 'Invalid JSON-RPC origins',\n ErrorWrapper,\n );\n}\n\n/**\n * Assert that the given value is a successful JSON-RPC response. If the value\n * is not a success response, an error is thrown. If the value is an JSON-RPC\n * error, the error message is included in the thrown error.\n *\n * @param value - The value to check.\n * @throws If the value is not a JSON-RPC success response.\n */\nexport function assertIsJsonRpcSuccess(\n value: unknown,\n): asserts value is JsonRpcSuccess<Json> {\n if (!isJsonRpcSuccess(value)) {\n if (isJsonRpcFailure(value)) {\n throw new Error(`JSON-RPC request failed: ${value.error.message}`);\n }\n\n throw new Error('Invalid JSON-RPC response.');\n }\n}\n"],"names":["RpcOriginsStruct","assertIsRpcOrigins","assertIsJsonRpcSuccess","refine","object","dapps","optional","boolean","snaps","value","Object","values","some","Boolean","Error","ErrorWrapper","assertStruct","isJsonRpcSuccess","isJsonRpcFailure","error","message"],"mappings":";;;;;;;;;;;IAaaA,gBAAgB;eAAhBA;;IAyBGC,kBAAkB;eAAlBA;;IAqBAC,sBAAsB;eAAtBA;;;uBAlDT;6BAE2C;AAE3C,MAAMF,mBAAmBG,IAAAA,mBAAM,EACpCC,IAAAA,mBAAM,EAAC;IACLC,OAAOC,IAAAA,qBAAQ,EAACC,IAAAA,oBAAO;IACvBC,OAAOF,IAAAA,qBAAQ,EAACC,IAAAA,oBAAO;AACzB,IACA,eACA,CAACE;IACC,IAAI,CAACC,OAAOC,MAAM,CAACF,OAAOG,IAAI,CAACC,UAAU;QACvC,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;AACT;AAaK,SAASb,mBACdQ,KAAc,EACd,gEAAgE;AAChEM,YAAwC;IAExCC,IAAAA,mBAAY,EACVP,OACAT,kBACA,4BACAe;AAEJ;AAUO,SAASb,uBACdO,KAAc;IAEd,IAAI,CAACQ,IAAAA,uBAAgB,EAACR,QAAQ;QAC5B,IAAIS,IAAAA,uBAAgB,EAACT,QAAQ;YAC3B,MAAM,IAAIK,MAAM,CAAC,yBAAyB,EAAEL,MAAMU,KAAK,CAACC,OAAO,CAAC,CAAC;QACnE;QAEA,MAAM,IAAIN,MAAM;IAClB;AACF"}
|
package/dist/cjs/json.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/json.ts"],"sourcesContent":["import {
|
|
1
|
+
{"version":3,"sources":["../../src/json.ts"],"sourcesContent":["import type { Json } from '@metamask/utils';\nimport { getSafeJson } from '@metamask/utils';\n\n// TODO: Upstream this to @metamask/utils\n\n/**\n * Parse JSON safely.\n *\n * Does multiple kinds of validation and strips unwanted properties like\n * `__proto__` and `constructor`.\n *\n * @param json - A JSON string to be parsed.\n * @returns The parsed JSON object.\n * @template Type - The type of the JSON object. The type is not actually\n * checked, but it is used to infer the return type.\n */\nexport function parseJson<Type extends Json = Json>(json: string) {\n return getSafeJson<Type>(JSON.parse(json));\n}\n"],"names":["parseJson","json","getSafeJson","JSON","parse"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;uBAfY;AAerB,SAASA,UAAoCC,IAAY;IAC9D,OAAOC,IAAAA,kBAAW,EAAOC,KAAKC,KAAK,CAACH;AACtC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import { Json, assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport {\n NpmSnapFileNames,\n SnapFiles,\n SnapValidationFailureReason,\n UnvalidatedSnapFiles,\n} from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap icon file: ${error.message}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","svgIcon","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","fs","writeFile","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAiEsBA,aAAa;eAAbA;;IA4INC,WAAW;eAAXA;;IA8CMC,iBAAiB;eAAjBA;;IA0CAC,WAAW;eAAXA;;IAiCNC,mBAAmB;eAAnBA;;IA8BAC,uBAAuB;eAAvBA;;;uBApW8C;sEACxC;oBACS;6DACT;2BAEI;qBACG;qBACG;uBAKzB;uBAMA;6BACsC;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAkCO,eAAed,cACpBe,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB;IAEnB,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAeC,aAAS,CAACC,IAAI,CAACR,UAAUS,uBAAgB,CAACC,QAAQ;IACvE,MAAMC,eAAe,MAAMC,IAAAA,iBAAY,EAACN;IACxC,MAAMO,sBAAsBF,aAAaG,MAAM;IAE/C,MAAMC,cAAc,MAAMH,IAAAA,iBAAY,EACpCL,aAAS,CAACC,IAAI,CAACR,UAAUS,uBAAgB,CAACO,WAAW;IAGvD,MAAMC,YAAkC;QACtCC,UAAUP;QACVQ,aAAaJ;QACbb,YAAY,MAAMf,kBAChBa,UACAa,qBACAX;QAEFkB,SA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B,GAAG,CAAC,EACtKlD,kCAA2B,CAACwB,YAAY;IAE5C;IAEA,IAAI2B,uBAAuBG,wBAAwB;QACjD,MAAM,IAAI/D,uCAAgC,CACxC,CAAC,CAAC,EAAEd,uBAAgB,CAACC,QAAQ,CAAC,wBAAwB,EAAE4E,uBAAuB,uBAAuB,EAAE7E,uBAAgB,CAACO,WAAW,CAAC,oBAAoB,EAAEmE,mBAAmB,GAAG,CAAC,EAClLnD,kCAA2B,CAAC6B,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDuB,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACC,IAAAA,sBAAS,EAACJ,uBAAuBG,qBAClC;QACA,MAAM,IAAIhE,uCAAgC,CACxC,CAAC,CAAC,EAAEd,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HgB,kCAA2B,CAAC8B,kBAAkB;IAElD;IAEA2B,IAAAA,yBAAkB,EAChB;QAAEvE;QAAUhB;QAAYkB;IAAQ,GAChC,CAAC,CAAC,EAAEX,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
|
1
|
+
{"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import 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\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): VirtualFile<SnapManifest> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read Snap icon file: ${error.message}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an npm Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n validateSnapShasum(\n { manifest, sourceCode, svgIcon },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","snapFiles","manifest","packageJson","svgIcon","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","fs","writeFile","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","iconPath","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IA8DsBA,aAAa;eAAbA;;IA4INC,WAAW;eAAXA;;IA8CMC,iBAAiB;eAAjBA;;IA0CAC,WAAW;eAAXA;;IAiCNC,mBAAmB;eAAnBA;;IA8BAC,uBAAuB;eAAvBA;;;uBAhWwC;sEAClC;oBACS;6DACT;2BAEI;qBACG;qBACG;uBAKzB;uBAEuD;6BACjB;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAkCO,eAAed,cACpBe,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB;IAEnB,MAAMC,WAAqB,EAAE;IAC7B,MAAMC,SAAmB,EAAE;IAE3B,IAAIC,UAAU;IAEd,MAAMC,eAAeC,aAAS,CAACC,IAAI,CAACR,UAAUS,uBAAgB,CAACC,QAAQ;IACvE,MAAMC,eAAe,MAAMC,IAAAA,iBAAY,EAACN;IACxC,MAAMO,sBAAsBF,aAAaG,MAAM;IAE/C,MAAMC,cAAc,MAAMH,IAAAA,iBAAY,EACpCL,aAAS,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AgC,CACxC,CAAC,CAAC,EAAEd,uBAAgB,CAACC,QAAQ,CAAC,qBAAqB,EAAE2E,oBAAoB,uBAAuB,EAAE5E,uBAAgB,CAACO,WAAW,CAAC,iBAAiB,EAAEkE,gBAAgB,GAAG,CAAC,EACtKlD,kCAA2B,CAACwB,YAAY;IAE5C;IAEA,IAAI2B,uBAAuBG,wBAAwB;QACjD,MAAM,IAAI/D,uCAAgC,CACxC,CAAC,CAAC,EAAEd,uBAAgB,CAACC,QAAQ,CAAC,wBAAwB,EAAE4E,uBAAuB,uBAAuB,EAAE7E,uBAAgB,CAACO,WAAW,CAAC,oBAAoB,EAAEmE,mBAAmB,GAAG,CAAC,EAClLnD,kCAA2B,CAAC6B,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDuB,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACC,IAAAA,sBAAS,EAACJ,uBAAuBG,qBAClC;QACA,MAAM,IAAIhE,uCAAgC,CACxC,CAAC,CAAC,EAAEd,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HgB,kCAA2B,CAAC8B,kBAAkB;IAElD;IAEA2B,IAAAA,yBAAkB,EAChB;QAAEvE;QAAUhB;QAAYkB;IAAQ,GAChC,CAAC,CAAC,EAAEX,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport {\n array,\n boolean,\n create,\n enums,\n Infer,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n Struct,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { RpcOriginsStruct } from '../json-rpc';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <T extends { path: string[]; curve: string }, S>(\n struct: Struct<T, S>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:long-running': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,\n ),\n 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","PermissionsStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","allowTransactionOrigin","boolean","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","wallet_snap","VersionStruct","description","proposedName","pattern","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IA0CaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,YAAY;eAAZA;;IAeAC,kBAAkB;eAAlBA;;IASAC,oCAAoC;eAApCA;;IAMAC,iBAAiB;eAAjBA;;IAOAC,aAAa;eAAbA;;IAeAC,iBAAiB;eAAjBA;;IAmCAC,kBAAkB;eAAlBA;;IA4CGC,cAAc;eAAdA;;IAUAC,oBAAoB;eAApBA;;IAiBAC,kBAAkB;eAAlBA;;;yBArPwB;uBAMjC;6BAoBA;uBAEiB;yBACwB;yBACgB;yBAC/B;uBACJ;uBACgB;AAE7C,+EAA+E;AAC/E,gCAAgC;AAChC,MAAMC,qBAA+B;IACnCC,0BAAiB;IACjBC,qCAA4B;CAC7B;AAEM,MAAMd,uBAAiC;IAAC;CAAG;AAClD,MAAMe,kBAA8Bf,qBAAqBgB,GAAG,CAAC,CAACC,WAAa;QACzE;QACA;QACA,CAAC,EAAEA,SAAS,CAAC,CAAC;KACf;AAEM,MAAMhB,kBAAkBiB,IAAAA,mBAAM,EACnCC,IAAAA,kBAAK,EAACC,IAAAA,mBAAM,MACZ,eACA,CAAC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AASX,eAAeuB,KAAc;IAC3C,OAAOoD,IAAAA,eAAE,EAACpD,OAAOxB;AACnB;AAQO,SAASE,qBACdsB,KAAc;IAEdqD,IAAAA,mBAAY,EACVrD,OACAxB,oBACA,CAAC,CAAC,EAAE8E,uBAAgB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAAS5E,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAOwD,IAAAA,mBAAM,EAACxD,OAAOxB;AACvB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/manifest/validation.ts"],"sourcesContent":["import { isValidBIP32PathSegment } from '@metamask/key-tree';\nimport {\n assertStruct,\n ChecksumStruct,\n VersionStruct,\n isValidSemVerRange,\n} from '@metamask/utils';\nimport type { Infer, Struct } from 'superstruct';\nimport {\n array,\n boolean,\n create,\n enums,\n integer,\n is,\n literal,\n object,\n optional,\n pattern,\n refine,\n record,\n size,\n string,\n type,\n union,\n} from 'superstruct';\n\nimport { isEqual } from '../array';\nimport { CronjobSpecificationArrayStruct } from '../cronjob';\nimport { SIP_6_MAGIC_VALUE, STATE_ENCRYPTION_MAGIC_VALUE } from '../entropy';\nimport { RpcOriginsStruct } from '../json-rpc';\nimport { SnapIdStruct } from '../snaps';\nimport { NameStruct, NpmSnapFileNames } from '../types';\n\n// BIP-43 purposes that cannot be used for entropy derivation. These are in the\n// string form, ending with `'`.\nconst FORBIDDEN_PURPOSES: string[] = [\n SIP_6_MAGIC_VALUE,\n STATE_ENCRYPTION_MAGIC_VALUE,\n];\n\nexport const FORBIDDEN_COIN_TYPES: number[] = [60];\nconst FORBIDDEN_PATHS: string[][] = FORBIDDEN_COIN_TYPES.map((coinType) => [\n 'm',\n \"44'\",\n `${coinType}'`,\n]);\n\nexport const Bip32PathStruct = refine(\n array(string()),\n 'BIP-32 path',\n (path: string[]) => {\n if (path.length === 0) {\n return 'Path must be a non-empty BIP-32 derivation path array';\n }\n\n if (path[0] !== 'm') {\n return 'Path must start with \"m\".';\n }\n\n if (path.length < 3) {\n return 'Paths must have a length of at least three.';\n }\n\n if (path.slice(1).some((part) => !isValidBIP32PathSegment(part))) {\n return 'Path must be a valid BIP-32 derivation path array.';\n }\n\n if (FORBIDDEN_PURPOSES.includes(path[1])) {\n return `The purpose \"${path[1]}\" is not allowed for entropy derivation.`;\n }\n\n if (\n FORBIDDEN_PATHS.some((forbiddenPath) =>\n isEqual(path.slice(0, forbiddenPath.length), forbiddenPath),\n )\n ) {\n return `The path \"${path.join(\n '/',\n )}\" is not allowed for entropy derivation.`;\n }\n\n return true;\n },\n);\n\nexport const bip32entropy = <\n Type extends { path: string[]; curve: string },\n Schema,\n>(\n struct: Struct<Type, Schema>,\n) =>\n refine(struct, 'BIP-32 entropy', (value) => {\n if (\n value.curve === 'ed25519' &&\n value.path.slice(1).some((part) => !part.endsWith(\"'\"))\n ) {\n return 'Ed25519 does not support unhardened paths.';\n }\n\n return true;\n });\n\n// Used outside @metamask/snap-utils\nexport const Bip32EntropyStruct = bip32entropy(\n type({\n path: Bip32PathStruct,\n curve: enums(['ed25519', 'secp256k1']),\n }),\n);\n\nexport type Bip32Entropy = Infer<typeof Bip32EntropyStruct>;\n\nexport const SnapGetBip32EntropyPermissionsStruct = size(\n array(Bip32EntropyStruct),\n 1,\n Infinity,\n);\n\nexport const SemVerRangeStruct = refine(string(), 'SemVer range', (value) => {\n if (isValidSemVerRange(value)) {\n return true;\n }\n return 'Expected a valid SemVer range.';\n});\n\nexport const SnapIdsStruct = refine(\n record(SnapIdStruct, object({ version: optional(SemVerRangeStruct) })),\n 'SnapIds',\n (value) => {\n if (Object.keys(value).length === 0) {\n return false;\n }\n\n return true;\n },\n);\n\nexport type SnapIds = Infer<typeof SnapIdsStruct>;\n\n/* eslint-disable @typescript-eslint/naming-convention */\nexport const PermissionsStruct = type({\n 'endowment:long-running': optional(object({})),\n 'endowment:network-access': optional(object({})),\n 'endowment:webassembly': optional(object({})),\n 'endowment:transaction-insight': optional(\n object({\n allowTransactionOrigin: optional(boolean()),\n }),\n ),\n 'endowment:cronjob': optional(\n object({ jobs: CronjobSpecificationArrayStruct }),\n ),\n 'endowment:rpc': optional(RpcOriginsStruct),\n snap_dialog: optional(object({})),\n // TODO: Remove\n snap_confirm: optional(object({})),\n snap_manageState: optional(object({})),\n snap_manageAccounts: optional(object({})),\n snap_notify: optional(object({})),\n snap_getBip32Entropy: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip32PublicKey: optional(SnapGetBip32EntropyPermissionsStruct),\n snap_getBip44Entropy: optional(\n size(\n array(object({ coinType: size(integer(), 0, 2 ** 32 - 1) })),\n 1,\n Infinity,\n ),\n ),\n snap_getEntropy: optional(object({})),\n wallet_snap: optional(SnapIdsStruct),\n});\n/* eslint-enable @typescript-eslint/naming-convention */\n\nexport type SnapPermissions = Infer<typeof PermissionsStruct>;\n\nexport const SnapManifestStruct = object({\n version: VersionStruct,\n description: size(string(), 1, 280),\n proposedName: size(\n pattern(\n string(),\n /^(?:[A-Za-z0-9-_]+( [A-Za-z0-9-_]+)*)|(?:(?:@[A-Za-z0-9-*~][A-Za-z0-9-*._~]*\\/)?[A-Za-z0-9-~][A-Za-z0-9-._~]*)$/u,\n ),\n 1,\n 214,\n ),\n repository: optional(\n object({\n type: size(string(), 1, Infinity),\n url: size(string(), 1, Infinity),\n }),\n ),\n source: object({\n shasum: ChecksumStruct,\n location: object({\n npm: object({\n filePath: size(string(), 1, Infinity),\n iconPath: optional(size(string(), 1, Infinity)),\n packageName: NameStruct,\n registry: union([\n literal('https://registry.npmjs.org'),\n literal('https://registry.npmjs.org/'),\n ]),\n }),\n }),\n }),\n initialPermissions: PermissionsStruct,\n manifestVersion: literal('0.1'),\n $schema: optional(string()), // enables JSON-Schema linting in VSC and other IDEs\n});\n\nexport type SnapManifest = Infer<typeof SnapManifestStruct>;\n\n/**\n * Check if the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link SnapManifest} object.\n */\nexport function isSnapManifest(value: unknown): value is SnapManifest {\n return is(value, SnapManifestStruct);\n}\n\n/**\n * Assert that the given value is a valid {@link SnapManifest} object.\n *\n * @param value - The value to check.\n * @throws If the value is not a valid {@link SnapManifest} object.\n */\nexport function assertIsSnapManifest(\n value: unknown,\n): asserts value is SnapManifest {\n assertStruct(\n value,\n SnapManifestStruct,\n `\"${NpmSnapFileNames.Manifest}\" is invalid`,\n );\n}\n\n/**\n * Creates a {@link SnapManifest} object from JSON.\n *\n * @param value - The value to check.\n * @throws If the value cannot be coerced to a {@link SnapManifest} object.\n * @returns The created {@link SnapManifest} object.\n */\nexport function createSnapManifest(value: unknown): SnapManifest {\n // TODO: Add a utility to prefix these errors similar to assertStruct\n return create(value, SnapManifestStruct);\n}\n"],"names":["FORBIDDEN_COIN_TYPES","Bip32PathStruct","bip32entropy","Bip32EntropyStruct","SnapGetBip32EntropyPermissionsStruct","SemVerRangeStruct","SnapIdsStruct","PermissionsStruct","SnapManifestStruct","isSnapManifest","assertIsSnapManifest","createSnapManifest","FORBIDDEN_PURPOSES","SIP_6_MAGIC_VALUE","STATE_ENCRYPTION_MAGIC_VALUE","FORBIDDEN_PATHS","map","coinType","refine","array","string","path","length","slice","some","part","isValidBIP32PathSegment","includes","forbiddenPath","isEqual","join","struct","value","curve","endsWith","type","enums","size","Infinity","isValidSemVerRange","record","SnapIdStruct","object","version","optional","Object","keys","allowTransactionOrigin","boolean","jobs","CronjobSpecificationArrayStruct","RpcOriginsStruct","snap_dialog","snap_confirm","snap_manageState","snap_manageAccounts","snap_notify","snap_getBip32Entropy","snap_getBip32PublicKey","snap_getBip44Entropy","integer","snap_getEntropy","wallet_snap","VersionStruct","description","proposedName","pattern","repository","url","source","shasum","ChecksumStruct","location","npm","filePath","iconPath","packageName","NameStruct","registry","union","literal","initialPermissions","manifestVersion","$schema","is","assertStruct","NpmSnapFileNames","Manifest","create"],"mappings":";;;;;;;;;;;IAyCaA,oBAAoB;eAApBA;;IAOAC,eAAe;eAAfA;;IAsCAC,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AAM,KAAI,GAAGkB;QACxB8B,KAAK/B,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;IACzB;IAEF+B,QAAQ3B,IAAAA,mBAAM,EAAC;QACb4B,QAAQC,qBAAc;QACtBC,UAAU9B,IAAAA,mBAAM,EAAC;YACf+B,KAAK/B,IAAAA,mBAAM,EAAC;gBACVgC,UAAUrC,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBAC5BqC,UAAU/B,IAAAA,qBAAQ,EAACP,IAAAA,iBAAI,EAACjB,IAAAA,mBAAM,KAAI,GAAGkB;gBACrCsC,aAAaC,iBAAU;gBACvBC,UAAUC,IAAAA,kBAAK,EAAC;oBACdC,IAAAA,oBAAO,EAAC;oBACRA,IAAAA,oBAAO,EAAC;iBACT;YACH;QACF;IACF;IACAC,oBAAoB1E;IACpB2E,iBAAiBF,IAAAA,oBAAO,EAAC;IACzBG,SAASvC,IAAAA,qBAAQ,EAACxB,IAAAA,mBAAM;AAC1B;AAUO,SAASX,eAAeuB,KAAc;IAC3C,OAAOoD,IAAAA,eAAE,EAACpD,OAAOxB;AACnB;AAQO,SAASE,qBACdsB,KAAc;IAEdqD,IAAAA,mBAAY,EACVrD,OACAxB,oBACA,CAAC,CAAC,EAAE8E,uBAAgB,CAACC,QAAQ,CAAC,YAAY,CAAC;AAE/C;AASO,SAAS5E,mBAAmBqB,KAAc;IAC/C,qEAAqE;IACrE,OAAOwD,IAAAA,mBAAM,EAACxD,OAAOxB;AACvB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/namespace.ts"],"sourcesContent":["import {\n array,\n
|
|
1
|
+
{"version":3,"sources":["../../src/namespace.ts"],"sourcesContent":["import type { Infer } from 'superstruct';\nimport {\n array,\n is,\n object,\n optional,\n pattern,\n size,\n string,\n} from 'superstruct';\n\nexport const CHAIN_ID_REGEX =\n /^(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})$/u;\n\nexport const ACCOUNT_ID_REGEX =\n /^(?<chainId>(?<namespace>[-a-z0-9]{3,8}):(?<reference>[-a-zA-Z0-9]{1,32})):(?<accountAddress>[a-zA-Z0-9]{1,64})$/u;\n\n/**\n * Parse a chain ID string to an object containing the namespace and reference.\n * This validates the chain ID before parsing it.\n *\n * @param chainId - The chain ID to validate and parse.\n * @returns The parsed chain ID.\n */\nexport function parseChainId(chainId: ChainId): {\n namespace: NamespaceId;\n reference: string;\n} {\n const match = CHAIN_ID_REGEX.exec(chainId);\n if (!match?.groups) {\n throw new Error('Invalid chain ID.');\n }\n\n return {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n };\n}\n\n/**\n * Parse an account ID to an object containing the chain, chain ID and address.\n * This validates the account ID before parsing it.\n *\n * @param accountId - The account ID to validate and parse.\n * @returns The parsed account ID.\n */\nexport function parseAccountId(accountId: AccountId): {\n chain: { namespace: NamespaceId; reference: string };\n chainId: ChainId;\n address: string;\n} {\n const match = ACCOUNT_ID_REGEX.exec(accountId);\n if (!match?.groups) {\n throw new Error('Invalid account ID.');\n }\n\n return {\n address: match.groups.accountAddress,\n chainId: match.groups.chainId as ChainId,\n chain: {\n namespace: match.groups.namespace,\n reference: match.groups.reference,\n },\n };\n}\n\n/**\n * A helper struct for a string with a minimum length of 1 and a maximum length\n * of 40.\n */\nexport const LimitedString = size(string(), 1, 40);\n\n/**\n * A CAIP-2 chain ID, i.e., a human-readable namespace and reference.\n */\nexport const ChainIdStruct = pattern(string(), CHAIN_ID_REGEX);\nexport type ChainId = `${string}:${string}`;\n\nexport const AccountIdStruct = pattern(string(), ACCOUNT_ID_REGEX);\nexport type AccountId = `${ChainId}:${string}`;\n\nexport const AccountIdArrayStruct = array(AccountIdStruct);\n\n/**\n * A chain descriptor.\n */\nexport const ChainStruct = object({\n id: ChainIdStruct,\n name: LimitedString,\n});\nexport type Chain = Infer<typeof ChainStruct>;\n\nexport const NamespaceStruct = object({\n /**\n * A list of supported chains in the namespace.\n */\n chains: array(ChainStruct),\n\n /**\n * A list of supported RPC methods on the namespace, that a DApp can call.\n */\n methods: optional(array(LimitedString)),\n\n /**\n * A list of supported RPC events on the namespace, that a DApp can listen to.\n */\n events: optional(array(LimitedString)),\n});\nexport type Namespace = Infer<typeof NamespaceStruct>;\n\n/**\n * A CAIP-2 namespace, i.e., the first part of a chain ID.\n */\nexport const NamespaceIdStruct = pattern(string(), /^[-a-z0-9]{3,8}$/u);\nexport type NamespaceId = Infer<typeof NamespaceIdStruct>;\n\n/**\n * Check if the given value is a CAIP-2 namespace ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 namespace ID.\n */\nexport function isNamespaceId(value: unknown): value is NamespaceId {\n return is(value, NamespaceIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-2 chain ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-2 chain ID.\n */\nexport function isChainId(value: unknown): value is ChainId {\n return is(value, ChainIdStruct);\n}\n\n/**\n * Check if the given value is a CAIP-10 account ID.\n *\n * @param value - The value to check.\n * @returns Whether the value is a CAIP-10 account ID.\n */\nexport function isAccountId(value: unknown): value is AccountId {\n return is(value, AccountIdStruct);\n}\n\n/**\n * Check if the given value is an array of CAIP-10 account IDs.\n *\n * @param value - The value to check.\n * @returns Whether the value is an array of CAIP-10 account IDs.\n */\nexport function isAccountIdArray(value: unknown): value is AccountId[] {\n return is(value, AccountIdArrayStruct);\n}\n\n/**\n * Check if a value is a {@link Namespace}.\n *\n * @param value - The value to validate.\n * @returns True if the value is a valid {@link Namespace}.\n */\nexport function isNamespace(value: unknown): value is Namespace {\n return is(value, NamespaceStruct);\n}\n"],"names":["CHAIN_ID_REGEX","ACCOUNT_ID_REGEX","parseChainId","parseAccountId","LimitedString","ChainIdStruct","AccountIdStruct","AccountIdArrayStruct","ChainStruct","NamespaceStruct","NamespaceIdStruct","isNamespaceId","isChainId","isAccountId","isAccountIdArray","isNamespace","chainId","match","exec","groups","Error","namespace","reference","accountId","address","accountAddress","chain","size","string","pattern","array","object","id","name","chains","methods","optional","events","value","is"],"mappings":";;;;;;;;;;;IAWaA,cAAc;eAAdA;;IAGAC,gBAAgB;eAAhBA;;IAUGC,YAAY;eAAZA;;IAsBAC,cAAc;eAAdA;;IAwBHC,aAAa;eAAbA;;IAKAC,aAAa;eAAbA;;IAGAC,eAAe;eAAfA;;IAGAC,oBAAoB;eAApBA;;IAKAC,WAAW;eAAXA;;IAMAC,eAAe;eAAfA;;IAqBAC,iBAAiB;eAAjBA;;IASGC,aAAa;eAAbA;;IAUAC,SAAS;eAATA;;IAUAC,WAAW;eAAXA;;IAUAC,gBAAgB;eAAhBA;;IAUAC,WAAW;eAAXA;;;6BAzJT;AAEA,MAAMf,iBACX;AAEK,MAAMC,mBACX;AASK,SAASC,aAAac,OAAgB;IAI3C,MAAMC,QAAQjB,eAAekB,IAAI,CAACF;IAClC,IAAI,CAACC,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLC,WAAWJ,MAAME,MAAM,CAACE,SAAS;QACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;IACnC;AACF;AASO,SAASnB,eAAeoB,SAAoB;IAKjD,MAAMN,QAAQhB,iBAAiBiB,IAAI,CAACK;IACpC,IAAI,CAACN,OAAOE,QAAQ;QAClB,MAAM,IAAIC,MAAM;IAClB;IAEA,OAAO;QACLI,SAASP,MAAME,MAAM,CAACM,cAAc;QACpCT,SAASC,MAAME,MAAM,CAACH,OAAO;QAC7BU,OAAO;YACLL,WAAWJ,MAAME,MAAM,CAACE,SAAS;YACjCC,WAAWL,MAAME,MAAM,CAACG,SAAS;QACnC;IACF;AACF;AAMO,MAAMlB,gBAAgBuB,IAAAA,iBAAI,EAACC,IAAAA,mBAAM,KAAI,GAAG;AAKxC,MAAMvB,gBAAgBwB,IAAAA,oBAAO,EAACD,IAAAA,mBAAM,KAAI5B;AAGxC,MAAMM,kBAAkBuB,IAAAA,oBAAO,EAACD,IAAAA,mBAAM,KAAI3B;AAG1C,MAAMM,uBAAuBuB,IAAAA,kBAAK,EAACxB;AAKnC,MAAME,cAAcuB,IAAAA,mBAAM,EAAC;IAChCC,IAAI3B;IACJ4B,MAAM7B;AACR;AAGO,MAAMK,kBAAkBsB,IAAAA,mBAAM,EAAC;IACpC;;GAEC,GACDG,QAAQJ,IAAAA,kBAAK,EAACtB;IAEd;;GAEC,GACD2B,SAASC,IAAAA,qBAAQ,EAACN,IAAAA,kBAAK,EAAC1B;IAExB;;GAEC,GACDiC,QAAQD,IAAAA,qBAAQ,EAACN,IAAAA,kBAAK,EAAC1B;AACzB;AAMO,MAAMM,oBAAoBmB,IAAAA,oBAAO,EAACD,IAAAA,mBAAM,KAAI;AAS5C,SAASjB,cAAc2B,KAAc;IAC1C,OAAOC,IAAAA,eAAE,EAACD,OAAO5B;AACnB;AAQO,SAASE,UAAU0B,KAAc;IACtC,OAAOC,IAAAA,eAAE,EAACD,OAAOjC;AACnB;AAQO,SAASQ,YAAYyB,KAAc;IACxC,OAAOC,IAAAA,eAAE,EAACD,OAAOhC;AACnB;AAQO,SAASQ,iBAAiBwB,KAAc;IAC7C,OAAOC,IAAAA,eAAE,EAACD,OAAO/B;AACnB;AAQO,SAASQ,YAAYuB,KAAc;IACxC,OAAOC,IAAAA,eAAE,EAACD,OAAO7B;AACnB"}
|
package/dist/cjs/npm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/npm.ts"],"sourcesContent":["import { assertIsSnapIcon } from './icon';\nimport { validateNpmSnapManifest } from './manifest/manifest';\nimport { assertIsSnapManifest } from './manifest/validation';\nimport type { SnapFiles, UnvalidatedSnapFiles } from './types';\nimport { assertIsNpmSnapPackageJson, NpmSnapFileNames } from './types';\n\nexport const EXPECTED_SNAP_FILES = [\n 'manifest',\n 'packageJson',\n 'sourceCode',\n] as const;\n\nexport const SnapFileNameFromKey = {\n manifest: NpmSnapFileNames.Manifest,\n packageJson: NpmSnapFileNames.PackageJson,\n sourceCode: 'source code bundle',\n} as const;\n\n// TODO: Refactor this to be more shared with other validation.\n\n/**\n * Validates the files extracted from an npm Snap package tarball by ensuring\n * that they're non-empty and that the Json files match their respective schemas\n * and the Snaps publishing specification.\n *\n * @param snapFiles - The object containing the expected Snap file contents,\n * if any.\n * @param errorPrefix - The prefix of the error message.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport function validateNpmSnap(\n snapFiles: UnvalidatedSnapFiles,\n errorPrefix?: `${string}: `,\n): SnapFiles {\n EXPECTED_SNAP_FILES.forEach((key) => {\n if (!snapFiles[key]) {\n throw new Error(\n `${errorPrefix ?? ''}Missing file \"${SnapFileNameFromKey[key]}\".`,\n );\n }\n });\n\n // Typecast: We are assured that the required files exist if we get here.\n const { manifest, packageJson, sourceCode, svgIcon } = snapFiles as SnapFiles;\n try {\n assertIsSnapManifest(manifest.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedManifest = manifest;\n\n const { iconPath } = validatedManifest.result.source.location.npm;\n if (iconPath && !svgIcon) {\n throw new Error(`Missing file \"${iconPath}\".`);\n }\n\n try {\n assertIsNpmSnapPackageJson(packageJson.result);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n const validatedPackageJson = packageJson;\n\n validateNpmSnapManifest({\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n });\n\n if (svgIcon) {\n try {\n assertIsSnapIcon(svgIcon);\n } catch (error) {\n throw new Error(`${errorPrefix ?? ''}${error.message}`);\n }\n }\n\n return {\n manifest: validatedManifest,\n packageJson: validatedPackageJson,\n sourceCode,\n svgIcon,\n };\n}\n"],"names":["EXPECTED_SNAP_FILES","SnapFileNameFromKey","validateNpmSnap","manifest","NpmSnapFileNames","Manifest","packageJson","PackageJson","sourceCode","snapFiles","errorPrefix","forEach","key","Error","svgIcon","assertIsSnapManifest","result","error","message","validatedManifest","iconPath","source","location","npm","assertIsNpmSnapPackageJson","validatedPackageJson","validateNpmSnapManifest","assertIsSnapIcon"],"mappings":";;;;;;;;;;;IAMaA,mBAAmB;eAAnBA;;IAMAC,mBAAmB;eAAnBA;;IAkBGC,eAAe;eAAfA;;;sBA9BiB;0BACO;4BACH;uBAEwB;AAEtD,MAAMF,sBAAsB;IACjC;IACA;IACA;CACD;AAEM,MAAMC,sBAAsB;IACjCE,UAAUC,uBAAgB,CAACC,QAAQ;IACnCC,aAAaF,uBAAgB,CAACG,WAAW;IACzCC,YAAY;AACd;AAcO,SAASN,gBACdO,SAA+B,EAC/BC,WAA2B;IAE3BV,oBAAoBW,OAAO,CAAC,CAACC;QAC3B,IAAI,CAACH,SAAS,CAACG,IAAI,EAAE;YACnB,MAAM,IAAIC,MACR,CAAC,EAAEH,eAAe,GAAG,cAAc,EAAET,mBAAmB,CAACW,IAAI,CAAC,EAAE,CAAC;QAErE;IACF;IAEA,yEAAyE;IACzE,MAAM,EAAET,QAAQ,EAAEG,WAAW,EAAEE,UAAU,EAAEM,OAAO,EAAE,GAAGL;IACvD,IAAI;QACFM,IAAAA,gCAAoB,EAACZ,SAASa,MAAM;IACtC,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIJ,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEO,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMC,oBAAoBhB;IAE1B,MAAM,EAAEiB,QAAQ,EAAE,GAAGD,kBAAkBH,MAAM,CAACK,MAAM,CAACC,QAAQ,CAACC,GAAG;IACjE,IAAIH,YAAY,CAACN,SAAS;QACxB,MAAM,IAAID,MAAM,CAAC,cAAc,EAAEO,SAAS,EAAE,CAAC;IAC/C;IAEA,IAAI;QACFI,IAAAA,iCAA0B,EAAClB,YAAYU,MAAM;IAC/C,EAAE,OAAOC,OAAO;QACd,MAAM,IAAIJ,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEO,MAAMC,OAAO,CAAC,CAAC;IACxD;IACA,MAAMO,uBAAuBnB;IAE7BoB,IAAAA,iCAAuB,EAAC;QACtBvB,UAAUgB;QACVb,aAAamB;QACbjB;QACAM;IACF;IAEA,IAAIA,SAAS;QACX,IAAI;YACFa,IAAAA,sBAAgB,EAACb;QACnB,EAAE,OAAOG,OAAO;YACd,MAAM,IAAIJ,MAAM,CAAC,EAAEH,eAAe,GAAG,EAAEO,MAAMC,OAAO,CAAC,CAAC;QACxD;IACF;IAEA,OAAO;QACLf,UAAUgB;QACVb,aAAamB;QACbjB;QACAM;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport { transformSync, Node, Visitor, template, PluginObj } from '@babel/core';\nimport {\n binaryExpression,\n Expression,\n Identifier,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n TemplateElement,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["postProcessBundle","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","templateElement","raw","cooked","evalWrapper","template","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","stringLiteral","lastMatch","suffix","replace","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","templateLiteral","expression","setData","StringLiteral","replacement","acc","binaryExpression","skip","BinaryExpression","errorMessage","operator","isUnaryExpression","right","isUpdateExpression","argument","left","end","start","includes","Error","file","transformSync","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;;;;;;;;;;;;;;;IAqNxCA,iBAAiB;eAAjBA;;;sBApNkD;uBAW3D;IAgDA;UAAKC,kBAAkB;IAAlBA,mBACVC,sBAAmB;GADTD,uBAAAA;AAIZ,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAME,cAAc;AAEpB,4EAA4E;AAC5E,cAAc;AACd,MAAMC,yBAAyBC,IAAAA,sBAAe,EAAC;IAAEC,KAAK;IAAIC,QAAQ;AAAG;AAErE,MAAMC,cAAcC,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAExC,CAAC;AAED,MAAMC,oBAAoBF,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAE9C,CAAC;AAED,MAAME,4BAA4BH,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAEtD,CAAC;AAED;;;;;;;;;;;CAWC,GACD,SAASG,YAAYC,KAAa;IAChC,MAAMC,SAASD,MAAME,KAAK,CAACb;IAC3B,OACEY,MACE,oEAAoE;IACpE,sEAAsE;KACrEE,MAAM,CAAC,CAACC,QAAUA,UAAU,MAAMA,UAAUC;AAEnD;AAEA;;;;;;;;;;CAUC,GACD,SAASC,2BACPN,KAAa;IAEb,6DAA6D;IAC7D,kEAAkE;IAClE,uEAAuE;IACvE,MAAMO,UAA8BC,MAAMC,IAAI,CAACT,MAAMU,QAAQ,CAACrB;IAE9D,IAAIkB,QAAQI,MAAM,GAAG,GAAG;QACtB,MAAMC,SAASL,QAAQM,MAAM,CAC3B,CAAC,CAACC,UAAUC,YAAY,EAAEC,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ClB;YACF;QACF;IACF;IAEA,IAAI;QACF,MAAMW,OAAOC,IAAAA,mBAAa,EAACrE,MAAM;YAC/B,kDAAkD;YAClDsE,YAAY;YAEZC,YAAY;gBACV,sEAAsE;gBACtEC,YAAY;gBAEZ,sEAAsE;gBACtE,wEAAwE;gBACxEC,eAAe,CAACxE;YAClB;YAEA,mEAAmE;YACnE,yEAAyE;YACzEyE,SAAS;YAET,uEAAuE;YACvE,wEAAwE;YACxE,mEAAmE;YACnEtE;YACAD;YAEAwE,SAAS;gBACP,IAAO,CAAA;wBACLpE;wBACAM;oBACF,CAAA;aACD;QACH;QAEA,IAAI,CAACuD,MAAMpE,MAAM;YACf,MAAM,IAAImE,MAAM;QAClB;QAEA,OAAO;YACLnE,MAAMoE,KAAKpE,IAAI;YACfE,WAAWkE,KAAKQ,GAAG;YACnBvE,UAAUzB,MAAMC,IAAI,CAACwB;QACvB;IACF,EAAE,OAAOwE,OAAO;QACd,MAAM,IAAIV,MAAM,CAAC,8BAA8B,EAAEU,MAAMC,OAAO,CAAC,CAAC;IAClE;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/post-process.ts"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-shadow\nimport type { Node, Visitor, PluginObj } from '@babel/core';\nimport { transformSync, template } from '@babel/core';\nimport type { Expression, Identifier, TemplateElement } from '@babel/types';\nimport {\n binaryExpression,\n isUnaryExpression,\n isUpdateExpression,\n stringLiteral,\n templateElement,\n templateLiteral,\n} from '@babel/types';\n\n/**\n * Source map declaration taken from `@babel/core`. Babel doesn't export the\n * type for this, so it's copied from the source code instead here.\n */\nexport type SourceMap = {\n version: number;\n sources: string[];\n names: string[];\n sourceRoot?: string | undefined;\n sourcesContent?: string[] | undefined;\n mappings: string;\n file: string;\n};\n\n/**\n * The post process options.\n *\n * @property stripComments - Whether to strip comments. Defaults to `true`.\n * @property sourceMap - Whether to generate a source map for the modified code.\n * See also `inputSourceMap`.\n * @property inputSourceMap - The source map for the input code. When provided,\n * the source map will be used to generate a source map for the modified code.\n * This ensures that the source map is correct for the modified code, and still\n * points to the original source. If not provided, a new source map will be\n * generated instead.\n */\nexport type PostProcessOptions = {\n stripComments?: boolean;\n sourceMap?: boolean | 'inline';\n inputSourceMap?: SourceMap;\n};\n\n/**\n * The post processed bundle output.\n *\n * @property code - The modified code.\n * @property sourceMap - The source map for the modified code, if the source map\n * option was enabled.\n * @property warnings - Any warnings that occurred during the post-processing.\n */\nexport type PostProcessedBundle = {\n code: string;\n sourceMap?: SourceMap | null;\n warnings: PostProcessWarning[];\n};\n\nexport enum PostProcessWarning {\n UnsafeMathRandom = '`Math.random` was detected in the bundle. This is not a secure source of randomness.',\n}\n\n// The RegEx below consists of multiple groups joined by a boolean OR.\n// Each part consists of two groups which capture a part of each string\n// which needs to be split up, e.g., `<!--` is split into `<!` and `--`.\nconst TOKEN_REGEX = /(<!)(--)|(--)(>)|(import)(\\(.*?\\))/gu;\n\n// An empty template element, i.e., a part of a template literal without any\n// value (\"\").\nconst EMPTY_TEMPLATE_ELEMENT = templateElement({ raw: '', cooked: '' });\n\nconst evalWrapper = template.statement(`\n (1, REF)(ARGS)\n`);\n\nconst objectEvalWrapper = template.statement(`\n (1, OBJECT.REF)\n`);\n\nconst regeneratorRuntimeWrapper = template.statement(`\n var regeneratorRuntime;\n`);\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into an array, in a way that it can be joined\n * together to form the same string, but with the tokens separated into single\n * array elements.\n */\nfunction breakTokens(value: string): string[] {\n const tokens = value.split(TOKEN_REGEX);\n return (\n tokens\n // TODO: The `split` above results in some values being `undefined`.\n // There may be a better solution to avoid having to filter those out.\n .filter((token) => token !== '' && token !== undefined)\n );\n}\n\n/**\n * Breaks up tokens that would otherwise result in SES errors. The tokens are\n * broken up in a non-destructive way where possible. Currently works with:\n * - HTML comment tags `<!--` and `-->`, broken up into `<!`, `--`, and `--`,\n * `>`.\n * - `import(n)` statements, broken up into `import`, `(n)`.\n *\n * @param value - The string value to break up.\n * @returns The string split into a tuple consisting of the new template\n * elements and string literal expressions.\n */\nfunction breakTokensTemplateLiteral(\n value: string,\n): [TemplateElement[], Expression[]] {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore `matchAll` is not available in ES2017, but this code\n // should only be used in environments where the function is supported.\n const matches: RegExpMatchArray[] = Array.from(value.matchAll(TOKEN_REGEX));\n\n if (matches.length > 0) {\n const output = matches.reduce<[TemplateElement[], Expression[]]>(\n ([elements, expressions], rawMatch, index, values) => {\n const [, first, last] = rawMatch.filter((raw) => raw !== undefined);\n\n // Slice the text in front of the match, which does not need to be\n // broken up.\n const prefix = value.slice(\n index === 0\n ? 0\n : (values[index - 1].index as number) + values[index - 1][0].length,\n rawMatch.index,\n );\n\n return [\n [\n ...elements,\n templateElement({\n raw: getRawTemplateValue(prefix),\n cooked: prefix,\n }),\n EMPTY_TEMPLATE_ELEMENT,\n ],\n [...expressions, stringLiteral(first), stringLiteral(last)],\n ];\n },\n [[], []],\n );\n\n // Add the text after the last match to the output.\n const lastMatch = matches[matches.length - 1];\n const suffix = value.slice(\n (lastMatch.index as number) + lastMatch[0].length,\n );\n\n return [\n [\n ...output[0],\n templateElement({ raw: getRawTemplateValue(suffix), cooked: suffix }),\n ],\n output[1],\n ];\n }\n\n // If there are no matches, simply return the original value.\n return [\n [templateElement({ raw: getRawTemplateValue(value), cooked: value })],\n [],\n ];\n}\n\n/**\n * Get a raw template literal value from a cooked value. This adds a backslash\n * before every '`', '\\' and '${' characters.\n *\n * @see https://github.com/babel/babel/issues/9242#issuecomment-532529613\n * @param value - The cooked string to get the raw string for.\n * @returns The value as raw value.\n */\nfunction getRawTemplateValue(value: string) {\n return value.replace(/\\\\|`|\\$\\{/gu, '\\\\$&');\n}\n\n/**\n * Post process code with AST such that it can be evaluated in SES.\n *\n * Currently:\n * - Makes all direct calls to eval indirect.\n * - Handles certain Babel-related edge cases.\n * - Removes the `Buffer` provided by Browserify.\n * - Optionally removes comments.\n * - Breaks up tokens that would otherwise result in SES errors, such as HTML\n * comment tags `<!--` and `-->` and `import(n)` statements.\n *\n * @param code - The code to post process.\n * @param options - The post-process options.\n * @param options.stripComments - Whether to strip comments. Defaults to `true`.\n * @param options.sourceMap - Whether to generate a source map for the modified\n * code. See also `inputSourceMap`.\n * @param options.inputSourceMap - The source map for the input code. When\n * provided, the source map will be used to generate a source map for the\n * modified code. This ensures that the source map is correct for the modified\n * code, and still points to the original source. If not provided, a new source\n * map will be generated instead.\n * @returns An object containing the modified code, and source map, or null if\n * the provided code is null.\n */\nexport function postProcessBundle(\n code: string,\n {\n stripComments = true,\n sourceMap: sourceMaps,\n inputSourceMap,\n }: Partial<PostProcessOptions> = {},\n): PostProcessedBundle {\n const warnings = new Set<PostProcessWarning>();\n\n const pre: PluginObj['pre'] = ({ ast }) => {\n ast.comments?.forEach((comment) => {\n // Break up tokens that could be parsed as HTML comment terminators. The\n // regular expressions below are written strangely so as to avoid the\n // appearance of such tokens in our source code. For reference:\n // https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n comment.value = comment.value\n .replace(new RegExp(`<!${'--'}`, 'gu'), '< !--')\n .replace(new RegExp(`${'--'}>`, 'gu'), '-- >')\n .replace(/import(\\(.*\\))/gu, 'import\\\\$1');\n });\n };\n\n const visitor: Visitor<Node> = {\n FunctionExpression(path) {\n const { node } = path;\n\n // Browserify provides the `Buffer` global as an argument to modules that\n // use it, but this does not work in SES. Since we pass in `Buffer` as an\n // endowment, we can simply remove the argument.\n //\n // Note that this only removes `Buffer` from a wrapped function\n // expression, e.g., `(function (Buffer) { ... })`. Regular functions\n // are not affected.\n //\n // TODO: Since we're working on the AST level, we could check the scope\n // of the function expression, and possibly prevent false positives?\n if (node.type === 'FunctionExpression' && node.extra?.parenthesized) {\n node.params = node.params.filter(\n (param) => !(param.type === 'Identifier' && param.name === 'Buffer'),\n );\n }\n },\n\n CallExpression(path) {\n const { node } = path;\n\n // Replace `eval(foo)` with `(1, eval)(foo)`.\n if (node.callee.type === 'Identifier' && node.callee.name === 'eval') {\n path.replaceWith(\n evalWrapper({\n REF: node.callee,\n ARGS: node.arguments,\n }),\n );\n }\n\n // Detect the use of `Math.random()` and add a warning.\n if (\n node.callee.type === 'MemberExpression' &&\n node.callee.object.type === 'Identifier' &&\n node.callee.object.name === 'Math' &&\n node.callee.property.type === 'Identifier' &&\n node.callee.property.name === 'random'\n ) {\n warnings.add(PostProcessWarning.UnsafeMathRandom);\n }\n },\n\n MemberExpression(path) {\n const { node } = path;\n\n // Replace `object.eval(foo)` with `(1, object.eval)(foo)`.\n if (\n node.property.type === 'Identifier' &&\n node.property.name === 'eval' &&\n // We only apply this to MemberExpressions that are the callee of CallExpression\n path.parent.type === 'CallExpression' &&\n path.parent.callee === node\n ) {\n path.replaceWith(\n objectEvalWrapper({\n OBJECT: node.object,\n REF: node.property,\n }),\n );\n }\n },\n\n Identifier(path) {\n const { node } = path;\n\n // Insert `regeneratorRuntime` global if it's used in the code.\n if (node.name === 'regeneratorRuntime') {\n const program = path.findParent(\n (parent) => parent.node.type === 'Program',\n );\n\n // We know that `program` is a Program node here, but this keeps\n // TypeScript happy.\n if (program?.node.type === 'Program') {\n const body = program.node.body[0];\n\n // This stops it from inserting `regeneratorRuntime` multiple times.\n if (\n body.type === 'VariableDeclaration' &&\n (body.declarations[0].id as Identifier).name ===\n 'regeneratorRuntime'\n ) {\n return;\n }\n\n program?.node.body.unshift(regeneratorRuntimeWrapper());\n }\n }\n },\n\n TemplateLiteral(path) {\n const { node } = path;\n\n // This checks if the template literal was visited before. Without this,\n // it would cause an infinite loop resulting in a stack overflow. We can't\n // skip the path here, because we need to visit the children of the node.\n if (path.getData('visited')) {\n return;\n }\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const [replacementQuasis, replacementExpressions] = node.quasis.reduce<\n [TemplateElement[], Expression[]]\n >(\n ([elements, expressions], quasi, index) => {\n // Note: Template literals have two variants, \"cooked\" and \"raw\". Here\n // we use the cooked version.\n // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw\n const tokens = breakTokensTemplateLiteral(\n quasi.value.cooked as string,\n );\n\n // Only update the node if something changed.\n if (tokens[0].length <= 1) {\n return [\n [...elements, quasi],\n [...expressions, node.expressions[index] as Expression],\n ];\n }\n\n return [\n [...elements, ...tokens[0]],\n [\n ...expressions,\n ...tokens[1],\n node.expressions[index] as Expression,\n ],\n ];\n },\n [[], []],\n );\n\n path.replaceWith(\n templateLiteral(\n replacementQuasis,\n replacementExpressions.filter(\n (expression) => expression !== undefined,\n ),\n ) as Node,\n );\n\n path.setData('visited', true);\n },\n\n StringLiteral(path) {\n const { node } = path;\n\n // Break up tokens that could be parsed as HTML comment terminators, or\n // `import()` statements.\n // For reference:\n // - https://github.com/endojs/endo/blob/70cc86eb400655e922413b99c38818d7b2e79da0/packages/ses/error-codes/SES_HTML_COMMENT_REJECTED.md\n // - https://github.com/MetaMask/snaps-monorepo/issues/505\n const tokens = breakTokens(node.value);\n\n // Only update the node if the string literal was broken up.\n if (tokens.length <= 1) {\n return;\n }\n\n const replacement = tokens\n .slice(1)\n .reduce<Expression>(\n (acc, value) => binaryExpression('+', acc, stringLiteral(value)),\n stringLiteral(tokens[0]),\n );\n\n path.replaceWith(replacement as Node);\n path.skip();\n },\n\n BinaryExpression(path) {\n const { node } = path;\n\n const errorMessage =\n 'Using HTML comments (`<!--` and `-->`) as operators is not allowed. The behaviour of ' +\n 'these comments is ambiguous, and differs per browser and environment. If you want ' +\n 'to use them as operators, break them up into separate characters, i.e., `a-- > b` ' +\n 'and `a < ! --b`.';\n\n if (\n node.operator === '<' &&\n isUnaryExpression(node.right) &&\n isUpdateExpression(node.right.argument) &&\n node.right.argument.operator === '--' &&\n node.left.end &&\n node.right.argument.argument.start\n ) {\n const expression = code.slice(\n node.left.end,\n node.right.argument.argument.start,\n );\n\n if (expression.includes('<!--')) {\n throw new Error(errorMessage);\n }\n }\n\n if (\n node.operator === '>' &&\n isUpdateExpression(node.left) &&\n node.left.operator === '--' &&\n node.left.argument.end &&\n node.right.start\n ) {\n const expression = code.slice(node.left.argument.end, node.right.start);\n\n if (expression.includes('-->')) {\n throw new Error(errorMessage);\n }\n }\n },\n };\n\n try {\n const file = transformSync(code, {\n // Prevent Babel from searching for a config file.\n configFile: false,\n\n parserOpts: {\n // Strict mode isn't enabled by default, so we need to enable it here.\n strictMode: true,\n\n // If this is disabled, the AST does not include any comments. This is\n // useful for performance reasons, and we use it for stripping comments.\n attachComment: !stripComments,\n },\n\n // By default, Babel optimises bundles that exceed 500 KB, but that\n // results in characters which look like HTML comments, which breaks SES.\n compact: false,\n\n // This configures Babel to generate a new source map from the existing\n // source map if specified. If `sourceMap` is `true` but an input source\n // map is not provided, a new source map will be generated instead.\n inputSourceMap,\n sourceMaps,\n\n plugins: [\n () => ({\n pre,\n visitor,\n }),\n ],\n });\n\n if (!file?.code) {\n throw new Error('Bundled code is empty.');\n }\n\n return {\n code: file.code,\n sourceMap: file.map,\n warnings: Array.from(warnings),\n };\n } catch (error) {\n throw new Error(`Failed to post process code:\\n${error.message}`);\n }\n}\n"],"names":["postProcessBundle","PostProcessWarning","UnsafeMathRandom","TOKEN_REGEX","EMPTY_TEMPLATE_ELEMENT","templateElement","raw","cooked","evalWrapper","template","statement","objectEvalWrapper","regeneratorRuntimeWrapper","breakTokens","value","tokens","split","filter","token","undefined","breakTokensTemplateLiteral","matches","Array","from","matchAll","length","output","reduce","elements","expressions","rawMatch","index","values","first","last","prefix","slice","getRawTemplateValue","stringLiteral","lastMatch","suffix","replace","code","stripComments","sourceMap","sourceMaps","inputSourceMap","warnings","Set","pre","ast","comments","forEach","comment","RegExp","visitor","FunctionExpression","path","node","type","extra","parenthesized","params","param","name","CallExpression","callee","replaceWith","REF","ARGS","arguments","object","property","add","MemberExpression","parent","OBJECT","Identifier","program","findParent","body","declarations","id","unshift","TemplateLiteral","getData","replacementQuasis","replacementExpressions","quasis","quasi","templateLiteral","expression","setData","StringLiteral","replacement","acc","binaryExpression","skip","BinaryExpression","errorMessage","operator","isUnaryExpression","right","isUpdateExpression","argument","left","end","start","includes","Error","file","transformSync","configFile","parserOpts","strictMode","attachComment","compact","plugins","map","error","message"],"mappings":"AAAA,wDAAwD;;;;;;;;;;;;;;;IAoNxCA,iBAAiB;eAAjBA;;;sBAlNwB;uBASjC;IAgDA;UAAKC,kBAAkB;IAAlBA,mBACVC,sBAAmB;GADTD,uBAAAA;AAIZ,sEAAsE;AACtE,uEAAuE;AACvE,wEAAwE;AACxE,MAAME,cAAc;AAEpB,4EAA4E;AAC5E,cAAc;AACd,MAAMC,yBAAyBC,IAAAA,sBAAe,EAAC;IAAEC,KAAK;IAAIC,QAAQ;AAAG;AAErE,MAAMC,cAAcC,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAExC,CAAC;AAED,MAAMC,oBAAoBF,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAE9C,CAAC;AAED,MAAME,4BAA4BH,cAAQ,CAACC,SAAS,CAAC,CAAC;;AAEtD,CAAC;AAED;;;;;;;;;;;CAWC,GACD,SAASG,YAAYC,KAAa;IAChC,MAAMC,SAASD,MAAME,KAAK,CAACb;IAC3B,OACEY,MACE,oEAAoE;IACpE,sEAAsE;KACrEE,MAAM,CAAC,CAACC,QAAUA,UAAU,MAAMA,UAAUC;AAEnD;AAEA;;;;;;;;;;CAUC,GACD,SAASC,2BACPN,KAAa;IAEb,6DAA6D;IAC7D,kEAA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