@metamask/snaps-controllers 0.24.1 → 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/cronjob/CronjobController.d.ts +3 -2
- package/dist/cronjob/CronjobController.js +37 -23
- package/dist/cronjob/CronjobController.js.map +1 -1
- package/dist/fsm.js +1 -1
- package/dist/fsm.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/dist/multichain/MultiChainController.d.ts +3 -1
- package/dist/multichain/MultiChainController.js +8 -8
- package/dist/multichain/MultiChainController.js.map +1 -1
- package/dist/multichain/middleware.d.ts +1 -1
- package/dist/multichain/middleware.js +2 -2
- package/dist/multichain/middleware.js.map +1 -1
- package/dist/services/AbstractExecutionService.d.ts +3 -3
- package/dist/services/AbstractExecutionService.js +13 -12
- package/dist/services/AbstractExecutionService.js.map +1 -1
- package/dist/services/ExecutionService.d.ts +1 -1
- package/dist/services/ExecutionService.js.map +1 -1
- package/dist/services/iframe/IframeExecutionService.js +1 -1
- package/dist/services/iframe/IframeExecutionService.js.map +1 -1
- package/dist/services/iframe/test/server.js +6 -6
- package/dist/services/iframe/test/server.js.map +1 -1
- package/dist/services/node/NodeProcessExecutionService.d.ts +1 -1
- package/dist/services/node/NodeProcessExecutionService.js +2 -2
- package/dist/services/node/NodeProcessExecutionService.js.map +1 -1
- package/dist/services/node/NodeThreadExecutionService.d.ts +2 -2
- package/dist/services/node/NodeThreadExecutionService.js +5 -4
- package/dist/services/node/NodeThreadExecutionService.js.map +1 -1
- package/dist/snaps/SnapController.d.ts +37 -47
- package/dist/snaps/SnapController.js +306 -228
- package/dist/snaps/SnapController.js.map +1 -1
- package/dist/snaps/endowments/cronjob.d.ts +2 -2
- package/dist/snaps/endowments/cronjob.js +3 -3
- package/dist/snaps/endowments/cronjob.js.map +1 -1
- package/dist/snaps/endowments/enum.d.ts +2 -1
- package/dist/snaps/endowments/enum.js +1 -0
- package/dist/snaps/endowments/enum.js.map +1 -1
- package/dist/snaps/endowments/ethereum-provider.d.ts +1 -1
- package/dist/snaps/endowments/ethereum-provider.js +2 -2
- package/dist/snaps/endowments/ethereum-provider.js.map +1 -1
- package/dist/snaps/endowments/index.d.ts +33 -19
- package/dist/snaps/endowments/index.js +16 -4
- package/dist/snaps/endowments/index.js.map +1 -1
- package/dist/snaps/endowments/keyring.d.ts +1 -1
- package/dist/snaps/endowments/keyring.js +2 -2
- package/dist/snaps/endowments/keyring.js.map +1 -1
- package/dist/snaps/endowments/long-running.d.ts +1 -1
- package/dist/snaps/endowments/long-running.js +2 -2
- package/dist/snaps/endowments/long-running.js.map +1 -1
- package/dist/snaps/endowments/network-access.d.ts +1 -1
- package/dist/snaps/endowments/network-access.js +2 -2
- package/dist/snaps/endowments/network-access.js.map +1 -1
- package/dist/snaps/endowments/rpc.d.ts +35 -0
- package/dist/snaps/endowments/rpc.js +91 -0
- package/dist/snaps/endowments/rpc.js.map +1 -0
- package/dist/snaps/endowments/transaction-insight.d.ts +3 -3
- package/dist/snaps/endowments/transaction-insight.js +3 -3
- package/dist/snaps/endowments/transaction-insight.js.map +1 -1
- package/dist/snaps/index.d.ts +0 -1
- package/dist/snaps/index.js +0 -1
- package/dist/snaps/index.js.map +1 -1
- package/dist/snaps/location/http.d.ts +21 -0
- package/dist/snaps/location/http.js +71 -0
- package/dist/snaps/location/http.js.map +1 -0
- package/dist/snaps/location/index.d.ts +4 -0
- package/dist/snaps/{utils → location}/index.js +3 -1
- package/dist/snaps/location/index.js.map +1 -0
- package/dist/snaps/location/local.d.ts +10 -0
- package/dist/snaps/location/local.js +51 -0
- package/dist/snaps/location/local.js.map +1 -0
- package/dist/snaps/location/location.d.ts +32 -0
- package/dist/snaps/location/location.js +33 -0
- package/dist/snaps/location/location.js.map +1 -0
- package/dist/snaps/location/npm.d.ts +33 -0
- package/dist/snaps/location/npm.js +232 -0
- package/dist/snaps/location/npm.js.map +1 -0
- package/dist/utils.d.ts +10 -3
- package/dist/utils.js +17 -1
- package/dist/utils.js.map +1 -1
- package/package.json +25 -20
- package/dist/snaps/utils/index.d.ts +0 -2
- package/dist/snaps/utils/index.js.map +0 -1
- package/dist/snaps/utils/npm.d.ts +0 -14
- package/dist/snaps/utils/npm.js +0 -81
- package/dist/snaps/utils/npm.js.map +0 -1
- package/dist/snaps/utils/stream.d.ts +0 -30
- package/dist/snaps/utils/stream.js +0 -124
- package/dist/snaps/utils/stream.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../../../src/snaps/location/npm.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uDAW+B;AAC/B,2CAAiE;AACjE,kEAAmC;AACnC,gEAA8C;AAC9C,gDAAwB;AACxB,6EAAsE;AAEtE,2CAAmD;AAEnD,uCAA6C;AAG7C,MAAM,oBAAoB,GAAG,4BAA4B,CAAC;AA4B1D,MAAa,WAAW;IAOtB,YAAY,GAAQ,EAAE,OAAmB,EAAE;;;QACzC,MAAM,qBAAqB,GAAG,MAAA,IAAI,CAAC,qBAAqB,mCAAI,KAAK,CAAC;QAClE,MAAM,aAAa,GAAG,MAAA,IAAI,CAAC,KAAK,mCAAI,UAAU,CAAC,KAAK,CAAC;QACrD,MAAM,cAAc,GAAG,MAAA,IAAI,CAAC,YAAY,mCAAI,4CAA8B,CAAC;QAE3E,IAAA,oBAAY,EAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,6BAAe,EAAE,mBAAmB,CAAC,CAAC;QAEnE,IAAI,QAAsB,CAAC;QAC3B,IACE,GAAG,CAAC,IAAI,KAAK,EAAE;YACf,GAAG,CAAC,IAAI,KAAK,EAAE;YACf,GAAG,CAAC,QAAQ,KAAK,EAAE;YACnB,GAAG,CAAC,QAAQ,KAAK,EAAE,EACnB;YACA,QAAQ,GAAG,IAAI,GAAG,CAAC,oBAAoB,CAAC,CAAC;SAC1C;aAAM;YACL,QAAQ,GAAG,UAAU,CAAC;YACtB,IAA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EAAE;QACtD,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;QACtD,IAAI,UAAU,KAAK,MAAM,EAAE;YACzB,mDAAmD;YACnD,MAAM,IAAI,GAAG,UAAU,CAAC,OAAO,CAAC,uBAAuB,EAAE,IAAI,CAAC,CAAC;YAC/D,OAAO,WAAW,CAAC,IAAI,CACrB,IAAA,uBAAM,EAAC,CAAC,IAAI,EAAE,EAAE;gBACd,MAAM,KAAK,GAAG,IAAI,yBAAW,CAAC;oBAC5B,KAAK,EAAE,IAAI;oBACX,IAAI;oBACJ,IAAI,EAAE;wBACJ,aAAa,EAAE,IAAI,GAAG,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC,QAAQ,EAAE;qBACvD;iBACF,CAAC,CAAC;gBACH,IAAA,cAAM,EACJ,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAChB,uDAAuD,CACxD,CAAC;gBACF,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;gBACvB,OAAO,IAAI,EAAE,CAAC;YAChB,CAAC,CAAC,CACH,CAAC;SACH;QAED,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7C,WAAW,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC;QACpC,OAAO,WAAW,CAAC,MAAM,EAAE,CAAC;IAC9B,CAAC,CAAC,CAAC;IACH,OAAO,aAAa,CAAC;AACvB,CAAC","sourcesContent":["import {\n assertIsSemVerVersion,\n assertIsSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n SemVerRange,\n SemVerVersion,\n SnapManifest,\n VirtualFile,\n} from '@metamask/snaps-utils';\nimport { assert, assertStruct, isObject } from '@metamask/utils';\nimport concat from 'concat-stream';\nimport createGunzipStream from 'gunzip-maybe';\nimport pump from 'pump';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { Readable, Writable } from 'stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport { ensureRelative } from '../../utils';\nimport { SnapLocation } from './location';\n\nconst DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';\n\ninterface NpmMeta {\n registry: URL;\n packageName: string;\n requestedRange: SemVerRange;\n version?: string;\n fetch: typeof fetch;\n}\nexport interface NpmOptions {\n /**\n * @default DEFAULT_REQUESTED_SNAP_VERSION\n */\n versionRange?: SemVerRange;\n /**\n * The function used to fetch data.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * Whether to allow custom NPM registries outside of {@link DEFAULT_NPM_REGISTRY}.\n *\n * @default false\n */\n allowCustomRegistries?: boolean;\n}\n\nexport class NpmLocation implements SnapLocation {\n private readonly meta: NpmMeta;\n\n private validatedManifest?: VirtualFile<SnapManifest>;\n\n private files?: Map<string, VirtualFile>;\n\n constructor(url: URL, opts: NpmOptions = {}) {\n const allowCustomRegistries = opts.allowCustomRegistries ?? false;\n const fetchFunction = opts.fetch ?? globalThis.fetch;\n const requestedRange = opts.versionRange ?? DEFAULT_REQUESTED_SNAP_VERSION;\n\n assertStruct(url.toString(), NpmSnapIdStruct, 'Invalid Snap Id: ');\n\n let registry: string | URL;\n if (\n url.host === '' &&\n url.port === '' &&\n url.username === '' &&\n url.password === ''\n ) {\n registry = new URL(DEFAULT_NPM_REGISTRY);\n } else {\n registry = 'https://';\n if (url.username) {\n registry += url.username;\n if (url.password) {\n registry += `:${url.password}`;\n }\n registry += '@';\n }\n registry += url.host;\n registry = new URL(registry);\n assert(\n allowCustomRegistries,\n new TypeError(\n `Custom NPM registries are disabled, tried to use \"${registry.toString()}\".`,\n ),\n );\n }\n\n assert(\n registry.pathname === '/' &&\n registry.search === '' &&\n registry.hash === '',\n );\n\n assert(\n url.pathname !== '' && url.pathname !== '/',\n new TypeError('The package name in NPM location is empty.'),\n );\n let packageName = url.pathname;\n if (packageName.startsWith('/')) {\n packageName = packageName.slice(1);\n }\n\n this.meta = {\n requestedRange,\n registry,\n packageName,\n fetch: fetchFunction,\n };\n }\n\n async manifest(): Promise<VirtualFile<SnapManifest>> {\n if (this.validatedManifest) {\n return this.validatedManifest.clone();\n }\n\n const vfile = await this.fetch('./snap.manifest.json');\n const result = JSON.parse(vfile.toString());\n assertIsSnapManifest(result);\n vfile.result = result;\n this.validatedManifest = vfile as VirtualFile<SnapManifest>;\n\n return this.manifest();\n }\n\n async fetch(path: string): Promise<VirtualFile> {\n const relativePath = ensureRelative(path);\n if (!this.files) {\n await this.#lazyInit();\n assert(this.files !== undefined);\n }\n const vfile = this.files.get(relativePath);\n assert(\n vfile !== undefined,\n new TypeError(`File \"${path}\" not found in package.`),\n );\n return vfile.clone();\n }\n\n get packageName(): string {\n return this.meta.packageName;\n }\n\n get version(): string {\n assert(\n this.meta.version !== undefined,\n 'Tried to access version without first fetching NPM package.',\n );\n return this.meta.version;\n }\n\n get registry(): URL {\n return this.meta.registry;\n }\n\n get versionRange(): SemVerRange {\n return this.meta.requestedRange;\n }\n\n async #lazyInit() {\n assert(this.files === undefined);\n const [tarballResponse, actualVersion] = await fetchNpmTarball(\n this.meta.packageName,\n this.meta.requestedRange,\n this.meta.registry,\n this.meta.fetch,\n );\n this.meta.version = actualVersion;\n\n let canonicalBase = 'npm://';\n if (this.meta.registry.username !== '') {\n canonicalBase += this.meta.registry.username;\n if (this.meta.registry.password !== '') {\n canonicalBase += `:${this.meta.registry.password}`;\n }\n canonicalBase += '@';\n }\n canonicalBase += this.meta.registry.host;\n\n // TODO(ritave): Lazily extract files instead of up-front extracting all of them\n // We would need to replace tar-stream package because it requires immediate consumption of streams.\n await new Promise<void>((resolve, reject) => {\n this.files = new Map();\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 createTarballStream(\n `${canonicalBase}/${this.meta.packageName}/`,\n this.files,\n ),\n (error) => {\n error ? reject(error) : resolve();\n },\n );\n });\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: URL | string,\n fetchFunction: typeof 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 (\n !isValidUrl(tarballUrlString) ||\n !tarballUrlString.toString().endsWith('.tgz')\n ) {\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 || !tarballResponse.body) {\n throw new Error(`Failed to fetch tarball for package \"${packageName}\".`);\n }\n return [tarballResponse.body, targetVersion];\n}\n\n/**\n * The paths of files within npm tarballs appear to always be prefixed with\n * \"package/\".\n */\nconst NPM_TARBALL_PATH_PREFIX = /^package\\//u;\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 */\nfunction 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 canonicalBase - A base URI as specified in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8}. Starting with 'npm:'. Will be used for canonicalPath vfile argument.\n * @param files - An object to write target file contents to.\n * @returns The {@link Writable} tarball extraction stream.\n */\nfunction createTarballStream(\n canonicalBase: string,\n files: Map<string, VirtualFile>,\n): Writable {\n assert(\n canonicalBase.endsWith('/'),\n \"Base needs to end with '/' for relative paths to be added as children instead of siblings.\",\n );\n\n assert(\n canonicalBase.startsWith('npm:'),\n 'Protocol mismatch, expected \"npm:\".',\n );\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 // \"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 path = headerName.replace(NPM_TARBALL_PATH_PREFIX, './');\n return entryStream.pipe(\n concat((data) => {\n const vfile = new VirtualFile({\n value: data,\n path,\n data: {\n canonicalPath: new URL(path, canonicalBase).toString(),\n },\n });\n assert(\n !files.has(path),\n 'Malformed tarball, multiple files with the same path.',\n );\n files.set(path, vfile);\n return next();\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 return extractStream;\n}\n"]}
|
package/dist/utils.d.ts
CHANGED
|
@@ -83,7 +83,7 @@ declare type IsLiteral<T> = T extends string | number | boolean | symbol ? Extra
|
|
|
83
83
|
* ```
|
|
84
84
|
* @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}
|
|
85
85
|
*/
|
|
86
|
-
declare type
|
|
86
|
+
declare type LiteralKeys<T> = NonNullable<{
|
|
87
87
|
[Key in keyof T]: IsLiteral<Key> extends true ? Key : never;
|
|
88
88
|
}[keyof T]>;
|
|
89
89
|
/**
|
|
@@ -96,7 +96,7 @@ declare type _LiteralKeys<T> = NonNullable<{
|
|
|
96
96
|
* ```
|
|
97
97
|
* @see [Literal types]{@link https://www.typescriptlang.org/docs/handbook/literal-types.html}
|
|
98
98
|
*/
|
|
99
|
-
declare type
|
|
99
|
+
declare type NonLiteralKeys<T> = NonNullable<{
|
|
100
100
|
[Key in keyof T]: IsLiteral<Key> extends false ? Key : never;
|
|
101
101
|
}[keyof T]>;
|
|
102
102
|
/**
|
|
@@ -113,7 +113,7 @@ declare type _NonLiteralKeys<T> = NonNullable<{
|
|
|
113
113
|
* ```
|
|
114
114
|
* @see {@link setDiff} for the main use-case
|
|
115
115
|
*/
|
|
116
|
-
export declare type Diff<A, B> = Omit<A,
|
|
116
|
+
export declare type Diff<A, B> = Omit<A, LiteralKeys<B>> & Partial<Pick<A, Extract<keyof A, NonLiteralKeys<B>>>>;
|
|
117
117
|
/**
|
|
118
118
|
* Makes every specified property of the specified object type mutable.
|
|
119
119
|
*
|
|
@@ -125,4 +125,11 @@ export declare type Mutable<T extends Record<string, unknown>, TargetKey extends
|
|
|
125
125
|
} & {
|
|
126
126
|
[Key in keyof Omit<T, TargetKey>]: T[Key];
|
|
127
127
|
};
|
|
128
|
+
/**
|
|
129
|
+
* Ensures that a relative path starts with `./` prefix.
|
|
130
|
+
*
|
|
131
|
+
* @param path - Path to make relative.
|
|
132
|
+
* @returns The same path, with optional `./` prefix.
|
|
133
|
+
*/
|
|
134
|
+
export declare function ensureRelative(path: string): string;
|
|
128
135
|
export {};
|
package/dist/utils.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.withTimeout = exports.hasTimedOut = exports.delayWithTimer = exports.delay = exports.setDiff = void 0;
|
|
3
|
+
exports.ensureRelative = exports.withTimeout = exports.hasTimedOut = exports.delayWithTimer = exports.delay = exports.setDiff = void 0;
|
|
4
|
+
const utils_1 = require("@metamask/utils");
|
|
4
5
|
const Timer_1 = require("./snaps/Timer");
|
|
5
6
|
/**
|
|
6
7
|
* Takes two objects and does a Set Difference of them.
|
|
@@ -89,4 +90,19 @@ async function withTimeout(promise, timerOrMs) {
|
|
|
89
90
|
}
|
|
90
91
|
}
|
|
91
92
|
exports.withTimeout = withTimeout;
|
|
93
|
+
/**
|
|
94
|
+
* Ensures that a relative path starts with `./` prefix.
|
|
95
|
+
*
|
|
96
|
+
* @param path - Path to make relative.
|
|
97
|
+
* @returns The same path, with optional `./` prefix.
|
|
98
|
+
*/
|
|
99
|
+
function ensureRelative(path) {
|
|
100
|
+
(0, utils_1.assert)(!path.startsWith('/'));
|
|
101
|
+
(0, utils_1.assert)(path.search(/:|\/\//u) === -1, `Path "${path}" potentially an URI instead of local relative`);
|
|
102
|
+
if (path.startsWith('./')) {
|
|
103
|
+
return path;
|
|
104
|
+
}
|
|
105
|
+
return `./${path}`;
|
|
106
|
+
}
|
|
107
|
+
exports.ensureRelative = ensureRelative;
|
|
92
108
|
//# sourceMappingURL=utils.js.map
|
package/dist/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1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;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
|
|
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,K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AC,CAAC;IAC9B,IAAA,cAAM,EACJ,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,EAC7B,SAAS,IAAI,gDAAgD,CAC9D,CAAC;IAEF,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,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.
|
|
3
|
+
"version": "0.26.0",
|
|
4
4
|
"description": "Controllers for MetaMask Snaps.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -31,14 +31,17 @@
|
|
|
31
31
|
"publish:package": "../../scripts/publish-package.sh"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@metamask/
|
|
35
|
-
"@metamask/
|
|
34
|
+
"@metamask/approval-controller": "^1.0.1",
|
|
35
|
+
"@metamask/base-controller": "^1.1.1",
|
|
36
|
+
"@metamask/browser-passworder": "^4.0.2",
|
|
36
37
|
"@metamask/object-multiplex": "^1.1.0",
|
|
38
|
+
"@metamask/permission-controller": "^1.0.1",
|
|
37
39
|
"@metamask/post-message-stream": "^6.0.0",
|
|
38
|
-
"@metamask/rpc-methods": "^0.
|
|
39
|
-
"@metamask/snaps-execution-environments": "^0.
|
|
40
|
-
"@metamask/snaps-types": "^0.
|
|
41
|
-
"@metamask/snaps-utils": "^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",
|
|
42
45
|
"@metamask/utils": "^3.3.1",
|
|
43
46
|
"@xstate/fsm": "^2.0.0",
|
|
44
47
|
"concat-stream": "^2.0.0",
|
|
@@ -55,11 +58,11 @@
|
|
|
55
58
|
},
|
|
56
59
|
"devDependencies": {
|
|
57
60
|
"@lavamoat/allow-scripts": "^2.0.3",
|
|
58
|
-
"@metamask/auto-changelog": "^
|
|
59
|
-
"@metamask/eslint-config": "^
|
|
60
|
-
"@metamask/eslint-config-jest": "^
|
|
61
|
-
"@metamask/eslint-config-nodejs": "^
|
|
62
|
-
"@metamask/eslint-config-typescript": "^
|
|
61
|
+
"@metamask/auto-changelog": "^3.1.0",
|
|
62
|
+
"@metamask/eslint-config": "^11.0.0",
|
|
63
|
+
"@metamask/eslint-config-jest": "^11.0.0",
|
|
64
|
+
"@metamask/eslint-config-nodejs": "^11.0.1",
|
|
65
|
+
"@metamask/eslint-config-typescript": "^11.0.0",
|
|
63
66
|
"@metamask/template-snap": "^0.7.0",
|
|
64
67
|
"@peculiar/webcrypto": "^1.3.3",
|
|
65
68
|
"@types/concat-stream": "^2.0.0",
|
|
@@ -68,26 +71,28 @@
|
|
|
68
71
|
"@types/pump": "^1.1.1",
|
|
69
72
|
"@types/readable-stream": "^2.3.9",
|
|
70
73
|
"@types/tar-stream": "^2.2.2",
|
|
74
|
+
"@typescript-eslint/eslint-plugin": "^5.42.1",
|
|
75
|
+
"@typescript-eslint/parser": "^5.42.1",
|
|
71
76
|
"deepmerge": "^4.2.2",
|
|
72
|
-
"eslint": "^
|
|
73
|
-
"eslint-config-prettier": "^8.
|
|
74
|
-
"eslint-plugin-import": "^2.
|
|
75
|
-
"eslint-plugin-jest": "^
|
|
76
|
-
"eslint-plugin-jsdoc": "^
|
|
77
|
+
"eslint": "^8.27.0",
|
|
78
|
+
"eslint-config-prettier": "^8.5.0",
|
|
79
|
+
"eslint-plugin-import": "^2.26.0",
|
|
80
|
+
"eslint-plugin-jest": "^27.1.5",
|
|
81
|
+
"eslint-plugin-jsdoc": "^39.6.2",
|
|
77
82
|
"eslint-plugin-node": "^11.1.0",
|
|
78
|
-
"eslint-plugin-prettier": "^
|
|
83
|
+
"eslint-plugin-prettier": "^4.2.1",
|
|
79
84
|
"jest": "^29.0.2",
|
|
80
85
|
"jest-environment-jsdom": "^29.0.2",
|
|
81
86
|
"jest-fetch-mock": "^3.0.3",
|
|
82
87
|
"jest-it-up": "^2.0.0",
|
|
83
88
|
"jsdom": "^19.0.0",
|
|
84
89
|
"mkdirp": "^1.0.4",
|
|
85
|
-
"prettier": "^2.
|
|
90
|
+
"prettier": "^2.7.1",
|
|
86
91
|
"prettier-plugin-packagejson": "^2.2.11",
|
|
87
92
|
"rimraf": "^3.0.2",
|
|
88
93
|
"serve-handler": "^6.1.5",
|
|
89
94
|
"ts-jest": "^29.0.0",
|
|
90
|
-
"typescript": "
|
|
95
|
+
"typescript": "~4.8.4"
|
|
91
96
|
},
|
|
92
97
|
"engines": {
|
|
93
98
|
"node": ">=16.0.0"
|
|
@@ -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 } 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: string, registryUrl?: string, fetchFunction?: typeof fetch): Promise<SnapFiles>;
|
package/dist/snaps/utils/npm.js
DELETED
|
@@ -1,81 +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 utils_1 = require("@metamask/utils");
|
|
8
|
-
const pump_1 = __importDefault(require("pump"));
|
|
9
|
-
const gunzip_maybe_1 = __importDefault(require("gunzip-maybe"));
|
|
10
|
-
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
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 targetVersion = (0, snaps_utils_1.getTargetVersion)(Object.keys((_a = packageMetadata === null || packageMetadata === void 0 ? void 0 : packageMetadata.versions) !== null && _a !== void 0 ? _a : {}), versionRange);
|
|
61
|
-
if (targetVersion === null) {
|
|
62
|
-
throw new Error(`Failed to find a matching version in npm metadata for package "${packageName}" and requested semver range "${versionRange}"`);
|
|
63
|
-
}
|
|
64
|
-
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;
|
|
65
|
-
if (!(0, snaps_utils_1.isValidUrl)(tarballUrlString) || !tarballUrlString.endsWith('.tgz')) {
|
|
66
|
-
throw new Error(`Failed to find valid tarball URL in npm metadata for package "${packageName}".`);
|
|
67
|
-
}
|
|
68
|
-
// Override the tarball hostname/protocol with registryUrl hostname/protocol
|
|
69
|
-
const newRegistryUrl = new URL(registryUrl);
|
|
70
|
-
const newTarballUrl = new URL(tarballUrlString);
|
|
71
|
-
newTarballUrl.hostname = newRegistryUrl.hostname;
|
|
72
|
-
newTarballUrl.protocol = newRegistryUrl.protocol;
|
|
73
|
-
// Perform a raw fetch because we want the Response object itself.
|
|
74
|
-
const tarballResponse = await fetchFunction(newTarballUrl.toString());
|
|
75
|
-
if (!tarballResponse.ok) {
|
|
76
|
-
throw new Error(`Failed to fetch tarball for package "${packageName}".`);
|
|
77
|
-
}
|
|
78
|
-
const stream = await tarballResponse.blob().then((blob) => blob.stream());
|
|
79
|
-
return [stream, targetVersion];
|
|
80
|
-
}
|
|
81
|
-
//# sourceMappingURL=npm.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../../../src/snaps/utils/npm.ts"],"names":[],"mappings":";;;;;;AAAA,2CAA2C;AAC3C,gDAAwB;AACxB,gEAA8C;AAC9C,uDAM+B;AAE/B,qCAAwE;AAE3D,QAAA,oBAAoB,GAAG,4BAA4B,CAAC;AAEjE;;;;;;;;;;GAUG;AACI,KAAK,UAAU,YAAY,CAChC,WAAmB,EACnB,YAAoB,EACpB,WAAW,GAAG,4BAAoB,EAClC,aAAa,GAA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,mCAAI,EAAE,CAAC,EACrD,YAAY,CACb,CAAC;IAEF,IAAI,aAAa,KAAK,IAAI,EAAE;QAC1B,MAAM,IAAI,KAAK,CACb,kEAAkE,WAAW,iCAAiC,YAAY,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 { isObject } from '@metamask/utils';\nimport pump from 'pump';\nimport createGunzipStream from 'gunzip-maybe';\nimport {\n SnapFiles,\n UnvalidatedSnapFiles,\n isValidUrl,\n getTargetVersion,\n validateNpmSnap,\n} from '@metamask/snaps-utils';\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: string,\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: `,\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: string,\n registryUrl = DEFAULT_NPM_REGISTRY,\n fetchFunction = fetch,\n): Promise<[ReadableStream, string]> {\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 targetVersion = getTargetVersion(\n Object.keys((packageMetadata as any)?.versions ?? {}),\n versionRange,\n );\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 { Readable, Writable } from 'stream';
|
|
3
|
-
import { UnvalidatedSnapFiles } from '@metamask/snaps-utils';
|
|
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 readable_web_to_node_stream_1 = require("readable-web-to-node-stream");
|
|
8
|
-
const tar_stream_1 = require("tar-stream");
|
|
9
|
-
const concat_stream_1 = __importDefault(require("concat-stream"));
|
|
10
|
-
const utils_1 = require("@metamask/utils");
|
|
11
|
-
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
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":";;;;;;AACA,6EAAsE;AACtE,2CAAmD;AACnD,kEAAmC;AACnC,2CAA2C;AAC3C,uDAI+B;AAE/B,2EAA2E;AAC3E,cAAc;AACd,MAAM,uBAAuB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AE;;QAChC,IAAI,IAAA,gBAAQ,EAAC,SAAS,CAAC,QAAQ,CAAC,EAAE;YAChC,6CAA6C;YAC7C,MAAM,EAAE,QAAQ,EAAE,WAAW,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 { Readable, Writable } from 'stream';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { extract as tarExtract } from 'tar-stream';\nimport concat from 'concat-stream';\nimport { isObject } from '@metamask/utils';\nimport {\n SnapManifest,\n NpmSnapFileNames,\n UnvalidatedSnapFiles,\n} from '@metamask/snaps-utils';\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"]}
|