@metamask/snaps-controllers 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,yCAAsC;AAEtC;;;;;;;;;;;;;GAaG;AACH,SAAgB,OAAO,CAGrB,OAAgB,EAAE,OAAgB;IAClC,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CACnC,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QACpB,IAAI,CAAC,CAAC,GAAG,IAAI,OAAO,CAAC,EAAE;YACrB,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;SAClB;QACD,OAAO,GAAG,CAAC;IACb,CAAC,EACD,EAAE,CACuB,CAAC;AAC9B,CAAC;AAbD,0BAaC;AAED;;;;;;;GAOG;AACH,SAAgB,KAAK,CACnB,EAAU,EACV,MAAe;IAEf,OAAO,cAAc,CAAC,IAAI,aAAK,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;AAC/C,CAAC;AALD,sBAKC;AAED;;;;;;;GAOG;AACH,SAAgB,cAAc,CAC5B,KAAY,EACZ,MAAe;IAEf,IAAI,UAAmC,CAAC;IACxC,MAAM,OAAO,GAAQ,IAAI,OAAO,CAAS,CAAC,OAAY,EAAE,MAAM,EAAE,EAAE;QAChE,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE;YACf,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QACrD,CAAC,CAAC,CAAC;QACH,UAAU,GAAG,MAAM,CAAC;IACtB,CAAC,CAAC,CAAC;IAEH,OAAO,CAAC,MAAM,GAAG,GAAG,EAAE;QACpB,IAAI,KAAK,CAAC,MAAM,KAAK,UAAU,EAAE;YAC/B,KAAK,CAAC,MAAM,EAAE,CAAC;YACf,UAAU,CAAC,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC,CAAC;SACvD;IACH,CAAC,CAAC;IACF,OAAO,OAAO,CAAC;AACjB,CAAC;AAnBD,wCAmBC;AAED;;;GAGG;AACU,QAAA,WAAW,GAAG,MAAM,CAC/B,sEAAsE,CACvE,CAAC;AAEF;;;;;;;;;;GAUG;AACI,KAAK,UAAU,WAAW,CAC/B,OAA8B,EAC9B,SAAyB;IAEzB,MAAM,KAAK,GACT,OAAO,SAAS,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,aAAK,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnE,MAAM,YAAY,GAAG,cAAc,CAAC,KAAK,EAAE,mBAAW,CAAC,CAAC;IACxD,IAAI;QACF,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC;KACpD;YAAS;QACR,YAAY,CAAC,MAAM,EAAE,CAAC;KACvB;AACH,CAAC;AAZD,kCAYC","sourcesContent":["import { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * A Promise that delays it's return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue- - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<T> = T extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, T> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<T> = NonNullable<\n {\n [Key in keyof T]: IsLiteral<Key> extends true ? Key : never;\n }[keyof T]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<T> = NonNullable<\n {\n [Key in keyof T]: IsLiteral<Key> extends false ? Key : never;\n }[keyof T]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<A, B> = Omit<A, LiteralKeys<B>> &\n Partial<Pick<A, Extract<keyof A, NonLiteralKeys<B>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template T - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n T extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<T, TargetKey>]: T[Key];\n} & {\n [Key in keyof Omit<T, TargetKey>]: T[Key];\n};\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,2CAAyC;AAEzC,yCAAsC;AAEtC;;;;;;;;;;;;;GAaG;AACH,SAAgB,OAAO,CAGrB,OAAgB,EAAE,OAAgB;IAClC,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,CACnC,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QACpB,IAAI,CAAC,CAAC,GAAG,IAAI,OAAO,CAAC,EAAE;YACrB,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;SAClB;QACD,OAAO,GAAG,CAAC;IACb,CAAC,EACD,EAAE,CACuB,CAAC;AAC9B,CAAC;AAbD,0BAaC;AAED;;;;;;;GAOG;AACH,SAAgB,KAAK,CACnB,EAAU,EACV,MAAe;IAEf,OAAO,cAAc,CAAC,IAAI,aAAK,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC;AAC/C,CAAC;AALD,sBAKC;AAED;;;;;;;GAOG;AACH,SAAgB,cAAc,CAC5B,KAAY,EACZ,MAAe;IAEf,IAAI,UAAmC,CAAC;IACxC,MAAM,OAAO,GAAQ,IAAI,OAAO,CAAS,CAAC,OAAY,EAAE,MAAM,EAAE,EAAE;QAChE,KAAK,CAAC,KAAK,CAAC,GAAG,EAAE;YACf,MAAM,K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C,EAAE;QACzB,OAAO,IAAI,CAAC;KACb;IACD,OAAO,KAAK,IAAI,EAAE,CAAC;AACrB,CAAC;AAXD,wCAWC","sourcesContent":["import { assert } from '@metamask/utils';\n\nimport { Timer } from './snaps/Timer';\n\n/**\n * Takes two objects and does a Set Difference of them.\n * Set Difference is generally defined as follows:\n * ```\n * 𝑥 ∈ A ∖ B ⟺ 𝑥 ∈ A ∧ 𝑥 ∉ B\n * ```\n * Meaning that the returned object contains all properties of A expect those that also\n * appear in B. Notice that properties that appear in B, but not in A, have no effect.\n *\n * @see [Set Difference]{@link https://proofwiki.org/wiki/Definition:Set_Difference}\n * @param objectA - The object on which the difference is being calculated.\n * @param objectB - The object whose properties will be removed from objectA.\n * @returns The objectA without properties from objectB.\n */\nexport function setDiff<\n ObjectA extends Record<any, unknown>,\n ObjectB extends Record<any, unknown>,\n>(objectA: ObjectA, objectB: ObjectB): Diff<ObjectA, ObjectB> {\n return Object.entries(objectA).reduce<Record<any, unknown>>(\n (acc, [key, value]) => {\n if (!(key in objectB)) {\n acc[key] = value;\n }\n return acc;\n },\n {},\n ) as Diff<ObjectA, ObjectB>;\n}\n\n/**\n * A Promise that delays it's return for a given amount of milliseconds.\n *\n * @param ms - Milliseconds to delay the execution for.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delay<Result = void>(\n ms: number,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n return delayWithTimer(new Timer(ms), result);\n}\n\n/**\n * A Promise that delays it's return by using a pausable Timer.\n *\n * @param timer - Timer used to control the delay.\n * @param result - The result to return from the Promise after delay.\n * @returns A promise that is void if no result provided, result otherwise.\n * @template Result - The `result`.\n */\nexport function delayWithTimer<Result = void>(\n timer: Timer,\n result?: Result,\n): Promise<Result> & { cancel: () => void } {\n let rejectFunc: (reason: Error) => void;\n const promise: any = new Promise<Result>((resolve: any, reject) => {\n timer.start(() => {\n result === undefined ? resolve() : resolve(result);\n });\n rejectFunc = reject;\n });\n\n promise.cancel = () => {\n if (timer.status !== 'finished') {\n timer.cancel();\n rejectFunc(new Error('The delay has been canceled.'));\n }\n };\n return promise;\n}\n\n/*\n * We use a Symbol instead of rejecting the promise so that Errors thrown\n * by the main promise will propagate.\n */\nexport const hasTimedOut = Symbol(\n 'Used to check if the requested promise has timeout (see withTimeout)',\n);\n\n/**\n * Executes the given Promise, if the Timer expires before the Promise settles, we return earlier.\n *\n * NOTE:** The given Promise is not cancelled or interrupted, and will continue to execute uninterrupted. We will just discard its result if it does not complete before the timeout.\n *\n * @param promise - The promise that you want to execute.\n * @param timerOrMs - The timer controlling the timeout or a ms value.\n * @returns The resolved `PromiseValue`, or the hasTimedOut symbol if\n * returning early.\n * @template PromiseValue- - The value of the Promise.\n */\nexport async function withTimeout<PromiseValue = void>(\n promise: Promise<PromiseValue>,\n timerOrMs: Timer | number,\n): Promise<PromiseValue | typeof hasTimedOut> {\n const timer =\n typeof timerOrMs === 'number' ? new Timer(timerOrMs) : timerOrMs;\n const delayPromise = delayWithTimer(timer, hasTimedOut);\n try {\n return await Promise.race([promise, delayPromise]);\n } finally {\n delayPromise.cancel();\n }\n}\n\n/**\n * Checks whether the type is composed of literal types\n *\n * @returns @type {true} if whole type is composed of literals, @type {false} if whole type is not literals, @type {boolean} if mixed\n * @example\n * ```\n * type t1 = IsLiteral<1 | 2 | \"asd\" | true>;\n * // t1 = true\n *\n * type t2 = IsLiteral<number | string>;\n * // t2 = false\n *\n * type t3 = IsLiteral<1 | string>;\n * // t3 = boolean\n *\n * const s = Symbol();\n * type t4 = IsLiteral<typeof s>;\n * // t4 = true\n *\n * type t5 = IsLiteral<symbol>\n * // t5 = false;\n * ```\n */\ntype IsLiteral<T> = T extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, T> extends never\n ? true\n : false\n : false;\n\n/**\n * Returns all keys of an object, that are literal, as an union\n *\n * @example\n * ```\n * type t1 = _LiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'b' | 'c'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype LiteralKeys<T> = NonNullable<\n {\n [Key in keyof T]: IsLiteral<Key> extends true ? Key : never;\n }[keyof T]\n>;\n\n/**\n * Returns all keys of an object, that are not literal, as an union\n *\n * @example\n * ```\n * type t1 = _NonLiteralKeys<{a: number, b: 0, c: 'foo', d: string}>\n * // t1 = 'a' | 'd'\n * ```\n * @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}\n */\ntype NonLiteralKeys<T> = NonNullable<\n {\n [Key in keyof T]: IsLiteral<Key> extends false ? Key : never;\n }[keyof T]\n>;\n\n/**\n * A set difference of two objects based on their keys\n *\n * @example\n * ```\n * type t1 = Diff<{a: string, b: string}, {a: number}>\n * // t1 = {b: string};\n * type t2 = Diff<{a: string, 0: string}, Record<string, unknown>>;\n * // t2 = { a?: string, 0: string};\n * type t3 = Diff<{a: string, 0: string, 1: string}, Record<1 | string, unknown>>;\n * // t3 = {a?: string, 0: string}\n * ```\n * @see {@link setDiff} for the main use-case\n */\nexport type Diff<A, B> = Omit<A, LiteralKeys<B>> &\n Partial<Pick<A, Extract<keyof A, NonLiteralKeys<B>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template T - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n T extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<T, TargetKey>]: T[Key];\n} & {\n [Key in keyof Omit<T, TargetKey>]: T[Key];\n};\n\n/**\n * Ensures that a relative path starts with `./` prefix.\n *\n * @param path - Path to make relative.\n * @returns The same path, with optional `./` prefix.\n */\nexport function ensureRelative(path: string): string {\n assert(!path.startsWith('/'));\n assert(\n path.search(/:|\\/\\//u) === -1,\n `Path \"${path}\" potentially an URI instead of local relative`,\n );\n\n if (path.startsWith('./')) {\n return path;\n }\n return `./${path}`;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/snaps-controllers",
3
- "version": "0.25.0",
3
+ "version": "0.26.0",
4
4
  "description": "Controllers for MetaMask Snaps.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -31,17 +31,17 @@
31
31
  "publish:package": "../../scripts/publish-package.sh"
32
32
  },
33
33
  "dependencies": {
34
- "@metamask/approval-controller": "^1.0.0",
35
- "@metamask/base-controller": "^1.0.0",
34
+ "@metamask/approval-controller": "^1.0.1",
35
+ "@metamask/base-controller": "^1.1.1",
36
36
  "@metamask/browser-passworder": "^4.0.2",
37
37
  "@metamask/object-multiplex": "^1.1.0",
38
- "@metamask/permission-controller": "^1.0.0",
38
+ "@metamask/permission-controller": "^1.0.1",
39
39
  "@metamask/post-message-stream": "^6.0.0",
40
- "@metamask/rpc-methods": "^0.25.0",
41
- "@metamask/snaps-execution-environments": "^0.25.0",
42
- "@metamask/snaps-types": "^0.25.0",
43
- "@metamask/snaps-utils": "^0.25.0",
44
- "@metamask/subject-metadata-controller": "^1.0.0",
40
+ "@metamask/rpc-methods": "^0.26.0",
41
+ "@metamask/snaps-execution-environments": "^0.26.0",
42
+ "@metamask/snaps-types": "^0.26.0",
43
+ "@metamask/snaps-utils": "^0.26.0",
44
+ "@metamask/subject-metadata-controller": "^1.0.1",
45
45
  "@metamask/utils": "^3.3.1",
46
46
  "@xstate/fsm": "^2.0.0",
47
47
  "concat-stream": "^2.0.0",
@@ -1,2 +0,0 @@
1
- export * from './npm';
2
- export * from './stream';
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/snaps/utils/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,wCAAsB;AACtB,2CAAyB","sourcesContent":["export * from './npm';\nexport * from './stream';\n"]}
@@ -1,14 +0,0 @@
1
- import { SnapFiles, SemVerRange } from '@metamask/snaps-utils';
2
- export declare const DEFAULT_NPM_REGISTRY = "https://registry.npmjs.org";
3
- /**
4
- * Fetches a Snap from the public npm registry.
5
- *
6
- * @param packageName - The name of the package whose tarball to fetch.
7
- * @param versionRange - The SemVer range of the package to fetch. The highest
8
- * version satisfying the range will be fetched.
9
- * @param registryUrl - The URL of the npm registry to fetch from.
10
- * @param fetchFunction - The fetch function to use. Defaults to the global
11
- * {@link fetch}. Useful for Node.js compatibility.
12
- * @returns A tuple of the Snap manifest object and the Snap source code.
13
- */
14
- export declare function fetchNpmSnap(packageName: string, versionRange: SemVerRange, registryUrl?: string, fetchFunction?: typeof fetch): Promise<SnapFiles>;
@@ -1,85 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.fetchNpmSnap = exports.DEFAULT_NPM_REGISTRY = void 0;
7
- const snaps_utils_1 = require("@metamask/snaps-utils");
8
- const utils_1 = require("@metamask/utils");
9
- const gunzip_maybe_1 = __importDefault(require("gunzip-maybe"));
10
- const pump_1 = __importDefault(require("pump"));
11
- const stream_1 = require("./stream");
12
- exports.DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
13
- /**
14
- * Fetches a Snap from the public npm registry.
15
- *
16
- * @param packageName - The name of the package whose tarball to fetch.
17
- * @param versionRange - The SemVer range of the package to fetch. The highest
18
- * version satisfying the range will be fetched.
19
- * @param registryUrl - The URL of the npm registry to fetch from.
20
- * @param fetchFunction - The fetch function to use. Defaults to the global
21
- * {@link fetch}. Useful for Node.js compatibility.
22
- * @returns A tuple of the Snap manifest object and the Snap source code.
23
- */
24
- async function fetchNpmSnap(packageName, versionRange, registryUrl = exports.DEFAULT_NPM_REGISTRY, fetchFunction = fetch) {
25
- const [tarballResponse, actualVersion] = await fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunction);
26
- // Extract the tarball and get the necessary files from it.
27
- const snapFiles = {};
28
- await new Promise((resolve, reject) => {
29
- (0, pump_1.default)((0, stream_1.getNodeStream)(tarballResponse),
30
- // The "gz" in "tgz" stands for "gzip". The tarball needs to be decompressed
31
- // before we can actually grab any files from it.
32
- (0, gunzip_maybe_1.default)(), (0, stream_1.createTarballExtractionStream)(snapFiles), (error) => {
33
- error ? reject(error) : resolve();
34
- });
35
- });
36
- // At this point, the necessary files will have been added to the snapFiles
37
- // object if they exist.
38
- return (0, snaps_utils_1.validateNpmSnap)(snapFiles, `npm Snap "${packageName}@${actualVersion}" validation error: `);
39
- }
40
- exports.fetchNpmSnap = fetchNpmSnap;
41
- /**
42
- * Fetches the tarball (`.tgz` file) of the specified package and version from
43
- * the public npm registry. Throws an error if fetching fails.
44
- *
45
- * @param packageName - The name of the package whose tarball to fetch.
46
- * @param versionRange - The SemVer range of the package to fetch. The highest
47
- * version satisfying the range will be fetched.
48
- * @param registryUrl - The URL of the npm registry to fetch the tarball from.
49
- * @param fetchFunction - The fetch function to use. Defaults to the global
50
- * {@link fetch}. Useful for Node.js compatibility.
51
- * @returns A tuple of the {@link Response} for the package tarball and the
52
- * actual version of the package.
53
- */
54
- async function fetchNpmTarball(packageName, versionRange, registryUrl = exports.DEFAULT_NPM_REGISTRY, fetchFunction = fetch) {
55
- var _a, _b, _c, _d;
56
- const packageMetadata = await (await fetchFunction(new URL(packageName, registryUrl).toString())).json();
57
- if (!(0, utils_1.isObject)(packageMetadata)) {
58
- throw new Error(`Failed to fetch package "${packageName}" metadata from npm.`);
59
- }
60
- const versions = Object.keys((_a = packageMetadata === null || packageMetadata === void 0 ? void 0 : packageMetadata.versions) !== null && _a !== void 0 ? _a : {}).map((version) => {
61
- (0, snaps_utils_1.assertIsSemVerVersion)(version);
62
- return version;
63
- });
64
- const targetVersion = (0, snaps_utils_1.getTargetVersion)(versions, versionRange);
65
- if (targetVersion === null) {
66
- throw new Error(`Failed to find a matching version in npm metadata for package "${packageName}" and requested semver range "${versionRange}"`);
67
- }
68
- const tarballUrlString = (_d = (_c = (_b = packageMetadata.versions) === null || _b === void 0 ? void 0 : _b[targetVersion]) === null || _c === void 0 ? void 0 : _c.dist) === null || _d === void 0 ? void 0 : _d.tarball;
69
- if (!(0, snaps_utils_1.isValidUrl)(tarballUrlString) || !tarballUrlString.endsWith('.tgz')) {
70
- throw new Error(`Failed to find valid tarball URL in npm metadata for package "${packageName}".`);
71
- }
72
- // Override the tarball hostname/protocol with registryUrl hostname/protocol
73
- const newRegistryUrl = new URL(registryUrl);
74
- const newTarballUrl = new URL(tarballUrlString);
75
- newTarballUrl.hostname = newRegistryUrl.hostname;
76
- newTarballUrl.protocol = newRegistryUrl.protocol;
77
- // Perform a raw fetch because we want the Response object itself.
78
- const tarballResponse = await fetchFunction(newTarballUrl.toString());
79
- if (!tarballResponse.ok) {
80
- throw new Error(`Failed to fetch tarball for package "${packageName}".`);
81
- }
82
- const stream = await tarballResponse.blob().then((blob) => blob.stream());
83
- return [stream, targetVersion];
84
- }
85
- //# sourceMappingURL=npm.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"npm.js","sourceRoot":"","sources":["../../../src/snaps/utils/npm.ts"],"names":[],"mappings":";;;;;;AAAA,uDAS+B;AAC/B,2CAA2C;AAC3C,gEAA8C;AAC9C,gDAAwB;AAExB,qCAAwE;AAE3D,QAAA,oBAAoB,GAAG,4BAA4B,CAAC;AAEjE;;;;;;;;;;GAUG;AACI,KAAK,UAAU,YAAY,CAChC,WAAmB,EACnB,YAAyB,EACzB,WAAW,GAAG,4BAAoB,EAClC,aAAa,GAAG,KAAK;IAErB,MAAM,CAAC,eAAe,EAAE,aAAa,CAAC,GAAG,MAAM,eAAe,CAC5D,WAAW,EACX,YAAY,EACZ,WAAW,EACX,aAAa,CACd,CAAC;IAEF,2DAA2D;IAC3D,MAAM,SAAS,GAAyB,EAAE,CAAC;IAC3C,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC1C,IAAA,cAAI,EACF,IAAA,sBAAa,EAAC,eAAe,CAAC;QAC9B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GAAG,CAC9H,CAAC;KACH;IAED,MAAM,gBAAgB,GAAG,MAAA,MAAA,MAAC,eAAuB,CAAC,QAAQ,0CAAG,aAAa,CAAC,0CACvE,IAAI,0CAAE,OAAO,CAAC;IAElB,IAAI,CAAC,IAAA,wBAAU,EAAC,gBAAgB,CAAC,IAAI,CAAC,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;QACvE,MAAM,IAAI,KAAK,CACb,iEAAiE,WAAW,IAAI,CACjF,CAAC;KACH;IAED,4EAA4E;IAC5E,MAAM,cAAc,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;IAC5C,MAAM,aAAa,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAChD,aAAa,CAAC,QAAQ,GAAG,cAAc,CAAC,QAAQ,CAAC;IACjD,aAAa,CAAC,QAAQ,GAAG,cAAc,CAAC,QAAQ,CAAC;IAEjD,kEAAkE;IAClE,MAAM,eAAe,GAAG,MAAM,aAAa,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC,CAAC;IACtE,IAAI,CAAC,eAAe,CAAC,EAAE,EAAE;QACvB,MAAM,IAAI,KAAK,CAAC,wCAAwC,WAAW,IAAI,CAAC,CAAC;KAC1E;IACD,MAAM,MAAM,GAAG,MAAM,eAAe,CAAC,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAE1E,OAAO,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;AACjC,CAAC","sourcesContent":["import {\n SnapFiles,\n UnvalidatedSnapFiles,\n isValidUrl,\n getTargetVersion,\n validateNpmSnap,\n assertIsSemVerVersion,\n SemVerRange,\n SemVerVersion,\n} from '@metamask/snaps-utils';\nimport { isObject } from '@metamask/utils';\nimport createGunzipStream from 'gunzip-maybe';\nimport pump from 'pump';\n\nimport { createTarballExtractionStream, getNodeStream } from './stream';\n\nexport const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';\n\n/**\n * Fetches a Snap from the public npm registry.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the Snap manifest object and the Snap source code.\n */\nexport async function fetchNpmSnap(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl = DEFAULT_NPM_REGISTRY,\n fetchFunction = fetch,\n): Promise<SnapFiles> {\n const [tarballResponse, actualVersion] = await fetchNpmTarball(\n packageName,\n versionRange,\n registryUrl,\n fetchFunction,\n );\n\n // Extract the tarball and get the necessary files from it.\n const snapFiles: UnvalidatedSnapFiles = {};\n await new Promise<void>((resolve, reject) => {\n pump(\n getNodeStream(tarballResponse),\n // The \"gz\" in \"tgz\" stands for \"gzip\". The tarball needs to be decompressed\n // before we can actually grab any files from it.\n createGunzipStream(),\n createTarballExtractionStream(snapFiles),\n (error) => {\n error ? reject(error) : resolve();\n },\n );\n });\n\n // At this point, the necessary files will have been added to the snapFiles\n // object if they exist.\n return validateNpmSnap(\n snapFiles,\n `npm Snap \"${packageName}@${actualVersion}\" validation error: ` as `${string}: `,\n );\n}\n\n/**\n * Fetches the tarball (`.tgz` file) of the specified package and version from\n * the public npm registry. Throws an error if fetching fails.\n *\n * @param packageName - The name of the package whose tarball to fetch.\n * @param versionRange - The SemVer range of the package to fetch. The highest\n * version satisfying the range will be fetched.\n * @param registryUrl - The URL of the npm registry to fetch the tarball from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns A tuple of the {@link Response} for the package tarball and the\n * actual version of the package.\n */\nasync function fetchNpmTarball(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl = DEFAULT_NPM_REGISTRY,\n fetchFunction = fetch,\n): Promise<[ReadableStream, SemVerVersion]> {\n const packageMetadata = await (\n await fetchFunction(new URL(packageName, registryUrl).toString())\n ).json();\n\n if (!isObject(packageMetadata)) {\n throw new Error(\n `Failed to fetch package \"${packageName}\" metadata from npm.`,\n );\n }\n\n const versions = Object.keys((packageMetadata as any)?.versions ?? {}).map(\n (version) => {\n assertIsSemVerVersion(version);\n return version;\n },\n );\n\n const targetVersion = getTargetVersion(versions, versionRange);\n\n if (targetVersion === null) {\n throw new Error(\n `Failed to find a matching version in npm metadata for package \"${packageName}\" and requested semver range \"${versionRange}\"`,\n );\n }\n\n const tarballUrlString = (packageMetadata as any).versions?.[targetVersion]\n ?.dist?.tarball;\n\n if (!isValidUrl(tarballUrlString) || !tarballUrlString.endsWith('.tgz')) {\n throw new Error(\n `Failed to find valid tarball URL in npm metadata for package \"${packageName}\".`,\n );\n }\n\n // Override the tarball hostname/protocol with registryUrl hostname/protocol\n const newRegistryUrl = new URL(registryUrl);\n const newTarballUrl = new URL(tarballUrlString);\n newTarballUrl.hostname = newRegistryUrl.hostname;\n newTarballUrl.protocol = newRegistryUrl.protocol;\n\n // Perform a raw fetch because we want the Response object itself.\n const tarballResponse = await fetchFunction(newTarballUrl.toString());\n if (!tarballResponse.ok) {\n throw new Error(`Failed to fetch tarball for package \"${packageName}\".`);\n }\n const stream = await tarballResponse.blob().then((blob) => blob.stream());\n\n return [stream, targetVersion];\n}\n"]}
@@ -1,30 +0,0 @@
1
- /// <reference types="node" />
2
- import { UnvalidatedSnapFiles } from '@metamask/snaps-utils';
3
- import { Readable, Writable } from 'stream';
4
- /**
5
- * Strips the leading `./` from a string, or does nothing if no string is
6
- * provided.
7
- *
8
- * @param pathString - The path string to normalize.
9
- * @returns The specified path without a `./` prefix, or `undefined` if no
10
- * string was provided.
11
- */
12
- export declare function stripDotSlash(pathString?: string): string | undefined;
13
- /**
14
- * Converts a {@link ReadableStream} to a Node.js {@link Readable}
15
- * stream. Returns the stream directly if it is already a Node.js stream.
16
- * We can't use the native Web {@link ReadableStream} directly because the
17
- * other stream libraries we use expect Node.js streams.
18
- *
19
- * @param stream - The stream to convert.
20
- * @returns The given stream as a Node.js Readable stream.
21
- */
22
- export declare function getNodeStream(stream: ReadableStream): Readable;
23
- /**
24
- * Creates a `tar-stream` that will get the necessary files from an npm Snap
25
- * package tarball (`.tgz` file).
26
- *
27
- * @param snapFiles - An object to write target file contents to.
28
- * @returns The {@link Writable} tarball extraction stream.
29
- */
30
- export declare function createTarballExtractionStream(snapFiles: UnvalidatedSnapFiles): Writable;
@@ -1,124 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.createTarballExtractionStream = exports.getNodeStream = exports.stripDotSlash = void 0;
7
- const snaps_utils_1 = require("@metamask/snaps-utils");
8
- const utils_1 = require("@metamask/utils");
9
- const concat_stream_1 = __importDefault(require("concat-stream"));
10
- const readable_web_to_node_stream_1 = require("readable-web-to-node-stream");
11
- const tar_stream_1 = require("tar-stream");
12
- // The paths of files within npm tarballs appear to always be prefixed with
13
- // "package/".
14
- const NPM_TARBALL_PATH_PREFIX = /^package\//u;
15
- /**
16
- * Strips the leading `./` from a string, or does nothing if no string is
17
- * provided.
18
- *
19
- * @param pathString - The path string to normalize.
20
- * @returns The specified path without a `./` prefix, or `undefined` if no
21
- * string was provided.
22
- */
23
- function stripDotSlash(pathString) {
24
- return pathString === null || pathString === void 0 ? void 0 : pathString.replace(/^\.\//u, '');
25
- }
26
- exports.stripDotSlash = stripDotSlash;
27
- /**
28
- * Converts a {@link ReadableStream} to a Node.js {@link Readable}
29
- * stream. Returns the stream directly if it is already a Node.js stream.
30
- * We can't use the native Web {@link ReadableStream} directly because the
31
- * other stream libraries we use expect Node.js streams.
32
- *
33
- * @param stream - The stream to convert.
34
- * @returns The given stream as a Node.js Readable stream.
35
- */
36
- function getNodeStream(stream) {
37
- if (typeof stream.getReader !== 'function') {
38
- return stream;
39
- }
40
- return new readable_web_to_node_stream_1.ReadableWebToNodeStream(stream);
41
- }
42
- exports.getNodeStream = getNodeStream;
43
- /**
44
- * Creates a `tar-stream` that will get the necessary files from an npm Snap
45
- * package tarball (`.tgz` file).
46
- *
47
- * @param snapFiles - An object to write target file contents to.
48
- * @returns The {@link Writable} tarball extraction stream.
49
- */
50
- function createTarballExtractionStream(snapFiles) {
51
- // `tar-stream` is pretty old-school, so we create it first and then
52
- // instrument it by adding event listeners.
53
- const extractStream = (0, tar_stream_1.extract)();
54
- // `tar-stream` reads every file in the tarball serially. We already know
55
- // where to look for package.json and the Snap manifest, but we don't know
56
- // where the source code is. Therefore, we cache the contents of each .js
57
- // file in the tarball and pick out the correct one when the stream has ended.
58
- const jsFileCache = new Map();
59
- // "entry" is fired for every discreet entity in the tarball. This includes
60
- // files and folders.
61
- extractStream.on('entry', (header, entryStream, next) => {
62
- const { name: headerName, type: headerType } = header;
63
- if (headerType === 'file') {
64
- // The name is a path if the header type is "file".
65
- const filePath = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');
66
- // Note the use of `concat-stream` since the data for each file may be
67
- // chunked.
68
- if (filePath === snaps_utils_1.NpmSnapFileNames.PackageJson) {
69
- return entryStream.pipe((0, concat_stream_1.default)((data) => {
70
- try {
71
- snapFiles.packageJson = JSON.parse(data.toString());
72
- }
73
- catch (_error) {
74
- return extractStream.destroy(new Error(`Failed to parse "${snaps_utils_1.NpmSnapFileNames.PackageJson}".`));
75
- }
76
- return next();
77
- }));
78
- }
79
- else if (filePath === snaps_utils_1.NpmSnapFileNames.Manifest) {
80
- return entryStream.pipe((0, concat_stream_1.default)((data) => {
81
- try {
82
- snapFiles.manifest = JSON.parse(data.toString());
83
- }
84
- catch (_error) {
85
- return extractStream.destroy(new Error(`Failed to parse "${snaps_utils_1.NpmSnapFileNames.Manifest}".`));
86
- }
87
- return next();
88
- }));
89
- }
90
- else if (/\w+\.(?:js|svg)$/u.test(filePath)) {
91
- return entryStream.pipe((0, concat_stream_1.default)((data) => {
92
- jsFileCache.set(filePath, data);
93
- return next();
94
- }));
95
- }
96
- }
97
- // If we get here, the entry is not a file, and we want to ignore. The entry
98
- // stream must be drained, or the extractStream will stop reading. This is
99
- // effectively a no-op for the current entry.
100
- entryStream.on('end', () => next());
101
- return entryStream.resume();
102
- });
103
- // Once we've read the entire tarball, attempt to grab the bundle file
104
- // contents from the .js file cache.
105
- extractStream.once('finish', () => {
106
- var _a, _b, _c, _d, _e;
107
- if ((0, utils_1.isObject)(snapFiles.manifest)) {
108
- /* istanbul ignore next: optional chaining */
109
- const { filePath: _bundlePath, iconPath: _iconPath } = (_c = (_b = (_a = snapFiles.manifest.source) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.npm) !== null && _c !== void 0 ? _c : {};
110
- const bundlePath = stripDotSlash(_bundlePath);
111
- const iconPath = stripDotSlash(_iconPath);
112
- if (bundlePath) {
113
- snapFiles.sourceCode = (_d = jsFileCache.get(bundlePath)) === null || _d === void 0 ? void 0 : _d.toString('utf8');
114
- }
115
- if (typeof iconPath === 'string' && iconPath.endsWith('.svg')) {
116
- snapFiles.svgIcon = (_e = jsFileCache.get(iconPath)) === null || _e === void 0 ? void 0 : _e.toString('utf8');
117
- }
118
- }
119
- jsFileCache.clear();
120
- });
121
- return extractStream;
122
- }
123
- exports.createTarballExtractionStream = createTarballExtractionStream;
124
- //# sourceMappingURL=stream.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"stream.js","sourceRoot":"","sources":["../../../src/snaps/utils/stream.ts"],"names":[],"mappings":";;;;;;AAAA,uDAI+B;AAC/B,2CAA2C;AAC3C,kEAAmC;AACnC,6EAAsE;AAEtE,2CAAmD;AAEnD,2EAA2E;AAC3E,cAAc;AACd,MAAM,uBAAuB,GAAG,aAAa,CAAC;AAE9C;;;;;;;GAOG;AACH,SAAgB,aAAa,CAAC,UAAmB;IAC/C,OAAO,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,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EAAE,QAAQ,EAAE,SAAS,EAAE,GAClD,MAAA,MAAA,MAAC,SAAS,CAAC,QAA6C,CAAC,MAAM,0CAC3D,QAAQ,0CAAE,GAAG,mCAAI,EAAE,CAAC;YAE1B,MAAM,UAAU,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC9C,MAAM,QAAQ,GAAG,aAAa,CAAC,SAAS,CAAC,CAAC;YAE1C,IAAI,UAAU,EAAE;gBACd,SAAS,CAAC,UAAU,GAAG,MAAA,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,0CAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;aACtE;YAED,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;gBAC7D,SAAS,CAAC,OAAO,GAAG,MAAA,WAAW,CAAC,GAAG,CAAC,QAAQ,CAAC,0CAAE,QAAQ,CAAC,MAAM,CAAC,CAAC;aACjE;SACF;QACD,WAAW,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC,CAAC,CAAC;IAEH,OAAO,aAAa,CAAC;AACvB,CAAC;AA5FD,sEA4FC","sourcesContent":["import {\n SnapManifest,\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n} from '@metamask/snaps-utils';\nimport { isObject } from '@metamask/utils';\nimport concat from 'concat-stream';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\n// The paths of files within npm tarballs appear to always be prefixed with\n// \"package/\".\nconst NPM_TARBALL_PATH_PREFIX = /^package\\//u;\n\n/**\n * Strips the leading `./` from a string, or does nothing if no string is\n * provided.\n *\n * @param pathString - The path string to normalize.\n * @returns The specified path without a `./` prefix, or `undefined` if no\n * string was provided.\n */\nexport function stripDotSlash(pathString?: string): string | undefined {\n return pathString?.replace(/^\\.\\//u, '');\n}\n\n/**\n * Converts a {@link ReadableStream} to a Node.js {@link Readable}\n * stream. Returns the stream directly if it is already a Node.js stream.\n * We can't use the native Web {@link ReadableStream} directly because the\n * other stream libraries we use expect Node.js streams.\n *\n * @param stream - The stream to convert.\n * @returns The given stream as a Node.js Readable stream.\n */\nexport function getNodeStream(stream: ReadableStream): Readable {\n if (typeof stream.getReader !== 'function') {\n return stream as unknown as Readable;\n }\n\n return new ReadableWebToNodeStream(stream);\n}\n\n/**\n * Creates a `tar-stream` that will get the necessary files from an npm Snap\n * package tarball (`.tgz` file).\n *\n * @param snapFiles - An object to write target file contents to.\n * @returns The {@link Writable} tarball extraction stream.\n */\nexport function createTarballExtractionStream(\n snapFiles: UnvalidatedSnapFiles,\n): Writable {\n // `tar-stream` is pretty old-school, so we create it first and then\n // instrument it by adding event listeners.\n const extractStream = tarExtract();\n\n // `tar-stream` reads every file in the tarball serially. We already know\n // where to look for package.json and the Snap manifest, but we don't know\n // where the source code is. Therefore, we cache the contents of each .js\n // file in the tarball and pick out the correct one when the stream has ended.\n const jsFileCache = new Map<string, Buffer>();\n\n // \"entry\" is fired for every discreet entity in the tarball. This includes\n // files and folders.\n extractStream.on('entry', (header, entryStream, next) => {\n const { name: headerName, type: headerType } = header;\n if (headerType === 'file') {\n // The name is a path if the header type is \"file\".\n const filePath = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');\n\n // Note the use of `concat-stream` since the data for each file may be\n // chunked.\n if (filePath === NpmSnapFileNames.PackageJson) {\n return entryStream.pipe(\n concat((data) => {\n try {\n snapFiles.packageJson = JSON.parse(data.toString());\n } catch (_error) {\n return extractStream.destroy(\n new Error(`Failed to parse \"${NpmSnapFileNames.PackageJson}\".`),\n );\n }\n\n return next();\n }),\n );\n } else if (filePath === NpmSnapFileNames.Manifest) {\n return entryStream.pipe(\n concat((data) => {\n try {\n snapFiles.manifest = JSON.parse(data.toString());\n } catch (_error) {\n return extractStream.destroy(\n new Error(`Failed to parse \"${NpmSnapFileNames.Manifest}\".`),\n );\n }\n\n return next();\n }),\n );\n } else if (/\\w+\\.(?:js|svg)$/u.test(filePath)) {\n return entryStream.pipe(\n concat((data) => {\n jsFileCache.set(filePath, data);\n return next();\n }),\n );\n }\n }\n\n // If we get here, the entry is not a file, and we want to ignore. The entry\n // stream must be drained, or the extractStream will stop reading. This is\n // effectively a no-op for the current entry.\n entryStream.on('end', () => next());\n return entryStream.resume();\n });\n\n // Once we've read the entire tarball, attempt to grab the bundle file\n // contents from the .js file cache.\n extractStream.once('finish', () => {\n if (isObject(snapFiles.manifest)) {\n /* istanbul ignore next: optional chaining */\n const { filePath: _bundlePath, iconPath: _iconPath } =\n (snapFiles.manifest as unknown as Partial<SnapManifest>).source\n ?.location?.npm ?? {};\n\n const bundlePath = stripDotSlash(_bundlePath);\n const iconPath = stripDotSlash(_iconPath);\n\n if (bundlePath) {\n snapFiles.sourceCode = jsFileCache.get(bundlePath)?.toString('utf8');\n }\n\n if (typeof iconPath === 'string' && iconPath.endsWith('.svg')) {\n snapFiles.svgIcon = jsFileCache.get(iconPath)?.toString('utf8');\n }\n }\n jsFileCache.clear();\n });\n\n return extractStream;\n}\n"]}