@metamask/snaps-controllers 0.25.0 → 0.26.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.
@@ -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,4EAA4E;QAC5E,iDAAiD;QACjD,IAAA,sBAAkB,GAAE,EACpB,IAAA,sCAA6B,EAAC,SAAS,CAAC,EACxC,CAAC,KAAK,EAAE,EAAE;YACR,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,CAAC;QACpC,CAAC,CACF,CAAC;IACJ,CAAC,CAAC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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,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AAC3C,CAAC;AAFD,sCAEC;AAED;;;;;;;;GAQG;AACH,SAAgB,aAAa,CAAC,MAAsB;IAClD,IAAI,OAAO,MAAM,CAAC,SAAS,KAAK,UAAU,EAAE;QAC1C,OAAO,MAA6B,CAAC;KACtC;IAED,OAAO,IAAI,qDAAuB,CAAC,MAAM,CAAC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E1C,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"]}