@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.
- package/dist/snaps/SnapController.d.ts +19 -31
- package/dist/snaps/SnapController.js +217 -154
- package/dist/snaps/SnapController.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 +69 -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 +38 -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 +27 -0
- package/dist/snaps/location/npm.js +230 -0
- package/dist/snaps/location/npm.js.map +1 -0
- package/package.json +9 -9
- 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 -85
- 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,21 @@
|
|
|
1
|
+
import { SnapManifest, VirtualFile } from '@metamask/snaps-utils';
|
|
2
|
+
import { SnapLocation } from './location';
|
|
3
|
+
export interface HttpOptions {
|
|
4
|
+
/**
|
|
5
|
+
* @default fetch
|
|
6
|
+
*/
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
fetchOptions?: RequestInit;
|
|
9
|
+
}
|
|
10
|
+
export declare class HttpLocation implements SnapLocation {
|
|
11
|
+
private readonly cache;
|
|
12
|
+
private validatedManifest?;
|
|
13
|
+
private readonly url;
|
|
14
|
+
private readonly fetchFn;
|
|
15
|
+
private readonly fetchOptions?;
|
|
16
|
+
constructor(url: URL, opts?: HttpOptions);
|
|
17
|
+
manifest(): Promise<VirtualFile<SnapManifest>>;
|
|
18
|
+
fetch(path: string): Promise<VirtualFile>;
|
|
19
|
+
get root(): URL;
|
|
20
|
+
private toCanonical;
|
|
21
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.HttpLocation = void 0;
|
|
4
|
+
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
5
|
+
const utils_1 = require("@metamask/utils");
|
|
6
|
+
class HttpLocation {
|
|
7
|
+
constructor(url, opts = {}) {
|
|
8
|
+
var _a;
|
|
9
|
+
// We keep contents separate because then we can use only one Blob in cache,
|
|
10
|
+
// which we convert to Uint8Array when actually returning the file.
|
|
11
|
+
//
|
|
12
|
+
// That avoids deepCloning file contents.
|
|
13
|
+
// I imagine ArrayBuffers are copy-on-write optimized, meaning
|
|
14
|
+
// in most often case we'll only have one file contents in common case.
|
|
15
|
+
this.cache = new Map();
|
|
16
|
+
(0, utils_1.assertStruct)(url.toString(), snaps_utils_1.HttpSnapIdStruct, 'Invalid Snap Id: ');
|
|
17
|
+
this.fetchFn = (_a = opts.fetch) !== null && _a !== void 0 ? _a : globalThis.fetch.bind(globalThis);
|
|
18
|
+
this.fetchOptions = opts.fetchOptions;
|
|
19
|
+
this.url = url;
|
|
20
|
+
}
|
|
21
|
+
async manifest() {
|
|
22
|
+
if (this.validatedManifest) {
|
|
23
|
+
return this.validatedManifest.clone();
|
|
24
|
+
}
|
|
25
|
+
// jest-fetch-mock doesn't handle new URL(), we need to convert .toString()
|
|
26
|
+
const canonicalPath = new URL(snaps_utils_1.NpmSnapFileNames.Manifest, this.url).toString();
|
|
27
|
+
const contents = await (await this.fetchFn(canonicalPath, this.fetchOptions)).text();
|
|
28
|
+
const manifest = JSON.parse(contents);
|
|
29
|
+
const vfile = new snaps_utils_1.VirtualFile({
|
|
30
|
+
value: contents,
|
|
31
|
+
result: (0, snaps_utils_1.createSnapManifest)(manifest),
|
|
32
|
+
path: snaps_utils_1.NpmSnapFileNames.Manifest,
|
|
33
|
+
data: { canonicalPath },
|
|
34
|
+
});
|
|
35
|
+
this.validatedManifest = vfile;
|
|
36
|
+
return this.manifest();
|
|
37
|
+
}
|
|
38
|
+
async fetch(path) {
|
|
39
|
+
const relativePath = (0, snaps_utils_1.normalizeRelative)(path);
|
|
40
|
+
const cached = this.cache.get(relativePath);
|
|
41
|
+
if (cached !== undefined) {
|
|
42
|
+
const { file, contents } = cached;
|
|
43
|
+
const value = new Uint8Array(await contents.arrayBuffer());
|
|
44
|
+
const vfile = file.clone();
|
|
45
|
+
vfile.value = value;
|
|
46
|
+
return vfile;
|
|
47
|
+
}
|
|
48
|
+
const canonicalPath = this.toCanonical(relativePath).toString();
|
|
49
|
+
const response = await this.fetchFn(canonicalPath, this.fetchOptions);
|
|
50
|
+
const vfile = new snaps_utils_1.VirtualFile({
|
|
51
|
+
value: '',
|
|
52
|
+
path: relativePath,
|
|
53
|
+
data: { canonicalPath },
|
|
54
|
+
});
|
|
55
|
+
const blob = await response.blob();
|
|
56
|
+
(0, utils_1.assert)(!this.cache.has(relativePath), 'Corrupted cache, multiple files with same path.');
|
|
57
|
+
this.cache.set(relativePath, { file: vfile, contents: blob });
|
|
58
|
+
return this.fetch(relativePath);
|
|
59
|
+
}
|
|
60
|
+
get root() {
|
|
61
|
+
return new URL(this.url);
|
|
62
|
+
}
|
|
63
|
+
toCanonical(path) {
|
|
64
|
+
(0, utils_1.assert)(!path.startsWith('/'), 'Tried to parse absolute path.');
|
|
65
|
+
return new URL(path, this.url);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
exports.HttpLocation = HttpLocation;
|
|
69
|
+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YAAY,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;QAE9D,OAAO,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAClC,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC3B,CAAC;IAEO,WAAW,CAAC,IAAY;QAC9B,IAAA,cAAM,EAAC,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,+BAA+B,CAAC,CAAC;QAC/D,OAAO,IAAI,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;IACjC,CAAC;CACF;AAzFD,oCAyFC","sourcesContent":["import {\n SnapManifest,\n VirtualFile,\n HttpSnapIdStruct,\n NpmSnapFileNames,\n createSnapManifest,\n normalizeRelative,\n} from '@metamask/snaps-utils';\nimport { assert, assertStruct } from '@metamask/utils';\n\nimport { SnapLocation } from './location';\n\nexport interface HttpOptions {\n /**\n * @default fetch\n */\n fetch?: typeof fetch;\n fetchOptions?: RequestInit;\n}\n\nexport class HttpLocation implements SnapLocation {\n // We keep contents separate because then we can use only one Blob in cache,\n // which we convert to Uint8Array when actually returning the file.\n //\n // That avoids deepCloning file contents.\n // I imagine ArrayBuffers are copy-on-write optimized, meaning\n // in most often case we'll only have one file contents in common case.\n private readonly cache = new Map<\n string,\n { file: VirtualFile; contents: Blob }\n >();\n\n private validatedManifest?: VirtualFile<SnapManifest>;\n\n private readonly url: URL;\n\n private readonly fetchFn: typeof fetch;\n\n private readonly fetchOptions?: RequestInit;\n\n constructor(url: URL, opts: HttpOptions = {}) {\n assertStruct(url.toString(), HttpSnapIdStruct, 'Invalid Snap Id: ');\n this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);\n this.fetchOptions = opts.fetchOptions;\n this.url = url;\n }\n\n async manifest(): Promise<VirtualFile<SnapManifest>> {\n if (this.validatedManifest) {\n return this.validatedManifest.clone();\n }\n\n // jest-fetch-mock doesn't handle new URL(), we need to convert .toString()\n const canonicalPath = new URL(\n NpmSnapFileNames.Manifest,\n this.url,\n ).toString();\n\n const contents = await (\n await this.fetchFn(canonicalPath, this.fetchOptions)\n ).text();\n const manifest = JSON.parse(contents);\n const vfile = new VirtualFile<SnapManifest>({\n value: contents,\n result: createSnapManifest(manifest),\n path: NpmSnapFileNames.Manifest,\n data: { canonicalPath },\n });\n this.validatedManifest = vfile;\n\n return this.manifest();\n }\n\n async fetch(path: string): Promise<VirtualFile> {\n const relativePath = normalizeRelative(path);\n const cached = this.cache.get(relativePath);\n if (cached !== undefined) {\n const { file, contents } = cached;\n const value = new Uint8Array(await contents.arrayBuffer());\n const vfile = file.clone();\n vfile.value = value;\n return vfile;\n }\n\n const canonicalPath = this.toCanonical(relativePath).toString();\n const response = await this.fetchFn(canonicalPath, this.fetchOptions);\n const vfile = new VirtualFile({\n value: '',\n path: relativePath,\n data: { canonicalPath },\n });\n const blob = await response.blob();\n assert(\n !this.cache.has(relativePath),\n 'Corrupted cache, multiple files with same path.',\n );\n this.cache.set(relativePath, { file: vfile, contents: blob });\n\n return this.fetch(relativePath);\n }\n\n get root(): URL {\n return new URL(this.url);\n }\n\n private toCanonical(path: string): URL {\n assert(!path.startsWith('/'), 'Tried to parse absolute path.');\n return new URL(path, this.url);\n }\n}\n"]}
|
|
@@ -14,6 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./location"), exports);
|
|
17
18
|
__exportStar(require("./npm"), exports);
|
|
18
|
-
__exportStar(require("./
|
|
19
|
+
__exportStar(require("./local"), exports);
|
|
20
|
+
__exportStar(require("./http"), exports);
|
|
19
21
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/snaps/location/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,6CAA2B;AAC3B,wCAAsB;AACtB,0CAAwB;AACxB,yCAAuB","sourcesContent":["export * from './location';\nexport * from './npm';\nexport * from './local';\nexport * from './http';\n"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { SnapManifest, VirtualFile } from '@metamask/snaps-utils';
|
|
2
|
+
import { HttpOptions } from './http';
|
|
3
|
+
import { SnapLocation } from './location';
|
|
4
|
+
export declare class LocalLocation implements SnapLocation {
|
|
5
|
+
#private;
|
|
6
|
+
constructor(url: URL, opts?: HttpOptions);
|
|
7
|
+
manifest(): Promise<VirtualFile<SnapManifest>>;
|
|
8
|
+
fetch(path: string): Promise<VirtualFile>;
|
|
9
|
+
get shouldAlwaysReload(): boolean;
|
|
10
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _LocalLocation_http;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.LocalLocation = void 0;
|
|
16
|
+
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
17
|
+
const utils_1 = require("@metamask/utils");
|
|
18
|
+
const http_1 = require("./http");
|
|
19
|
+
class LocalLocation {
|
|
20
|
+
constructor(url, opts = {}) {
|
|
21
|
+
_LocalLocation_http.set(this, void 0);
|
|
22
|
+
(0, utils_1.assertStruct)(url.toString(), snaps_utils_1.LocalSnapIdStruct, 'Invalid Snap Id');
|
|
23
|
+
// TODO(ritave): Write deepMerge() which merges fetchOptions.
|
|
24
|
+
(0, utils_1.assert)(opts.fetchOptions === undefined, 'Currently adding fetch options to local: is unsupported.');
|
|
25
|
+
__classPrivateFieldSet(this, _LocalLocation_http, new http_1.HttpLocation(new URL(url.toString().slice(snaps_utils_1.SnapIdPrefixes.local.length)), Object.assign(Object.assign({}, opts), { fetchOptions: { cache: 'no-cache' } })), "f");
|
|
26
|
+
}
|
|
27
|
+
async manifest() {
|
|
28
|
+
const vfile = await __classPrivateFieldGet(this, _LocalLocation_http, "f").manifest();
|
|
29
|
+
return convertCanonical(vfile);
|
|
30
|
+
}
|
|
31
|
+
async fetch(path) {
|
|
32
|
+
return convertCanonical(await __classPrivateFieldGet(this, _LocalLocation_http, "f").fetch(path));
|
|
33
|
+
}
|
|
34
|
+
get shouldAlwaysReload() {
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
exports.LocalLocation = LocalLocation;
|
|
39
|
+
_LocalLocation_http = new WeakMap();
|
|
40
|
+
/**
|
|
41
|
+
* Converts vfiles with canonical `http:` paths into `local:` paths.
|
|
42
|
+
*
|
|
43
|
+
* @param vfile - The {@link VirtualFile} to convert.
|
|
44
|
+
* @returns The same object with updated `.data.canonicalPath`.
|
|
45
|
+
*/
|
|
46
|
+
function convertCanonical(vfile) {
|
|
47
|
+
(0, utils_1.assert)(vfile.data.canonicalPath !== undefined);
|
|
48
|
+
vfile.data.canonicalPath = `local:${vfile.data.canonicalPath}`;
|
|
49
|
+
return vfile;
|
|
50
|
+
}
|
|
51
|
+
//# sourceMappingURL=local.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"local.js","sourceRoot":"","sources":["../../../src/snaps/location/local.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,uDAK+B;AAC/B,2CAAuD;AAEvD,iCAAmD;AAGnD,MAAa,aAAa;IAGxB,YAAY,GAAQ,EAAE,OAAoB,EAAE;QAF5C,sCAA6B;QAG3B,IAAA,oBAAY,EAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,+BAAiB,EAAE,iBAAiB,CAAC,CAAC;QACnE,6DAA6D;QAC7D,IAAA,cAAM,EACJ,IAAI,CAAC,YAAY,KAAK,SAAS,EAC/B,0DAA0D,CAC3D,CAAC;QAEF,uBAAA,IAAI,uBAAS,IAAI,mBAAY,CAC3B,IAAI,GAAG,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,KAAK,CAAC,4BAAc,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,kCACrD,IAAI,KAAE,YAAY,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,IAC/C,MAAA,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,QAAQ;QACZ,MAAM,KAAK,GAAG,MAAM,uBAAA,IAAI,2BAAM,CAAC,QAAQ,EAAE,CAAC;QAE1C,OAAO,gBAAgB,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,IAAY;QACtB,OAAO,gBAAgB,CAAC,MAAM,uBAAA,IAAI,2BAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IACxD,CAAC;IAED,IAAI,kBAAkB;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AA9BD,sCA8BC;;AAED;;;;;GAKG;AACH,SAAS,gBAAgB,CACvB,KAA0B;IAE1B,IAAA,cAAM,EAAC,KAAK,CAAC,IAAI,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC;IAC/C,KAAK,CAAC,IAAI,CAAC,aAAa,GAAG,SAAS,KAAK,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;IAC/D,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import {\n LocalSnapIdStruct,\n SnapIdPrefixes,\n SnapManifest,\n VirtualFile,\n} from '@metamask/snaps-utils';\nimport { assert, assertStruct } from '@metamask/utils';\n\nimport { HttpLocation, HttpOptions } from './http';\nimport { SnapLocation } from './location';\n\nexport class LocalLocation implements SnapLocation {\n readonly #http: HttpLocation;\n\n constructor(url: URL, opts: HttpOptions = {}) {\n assertStruct(url.toString(), LocalSnapIdStruct, 'Invalid Snap Id');\n // TODO(ritave): Write deepMerge() which merges fetchOptions.\n assert(\n opts.fetchOptions === undefined,\n 'Currently adding fetch options to local: is unsupported.',\n );\n\n this.#http = new HttpLocation(\n new URL(url.toString().slice(SnapIdPrefixes.local.length)),\n { ...opts, fetchOptions: { cache: 'no-cache' } },\n );\n }\n\n async manifest(): Promise<VirtualFile<SnapManifest>> {\n const vfile = await this.#http.manifest();\n\n return convertCanonical(vfile);\n }\n\n async fetch(path: string): Promise<VirtualFile> {\n return convertCanonical(await this.#http.fetch(path));\n }\n\n get shouldAlwaysReload() {\n return true;\n }\n}\n\n/**\n * Converts vfiles with canonical `http:` paths into `local:` paths.\n *\n * @param vfile - The {@link VirtualFile} to convert.\n * @returns The same object with updated `.data.canonicalPath`.\n */\nfunction convertCanonical<Result>(\n vfile: VirtualFile<Result>,\n): VirtualFile<Result> {\n assert(vfile.data.canonicalPath !== undefined);\n vfile.data.canonicalPath = `local:${vfile.data.canonicalPath}`;\n return vfile;\n}\n"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { SnapManifest, VirtualFile } from '@metamask/snaps-utils';
|
|
2
|
+
import { NpmOptions } from './npm';
|
|
3
|
+
declare module '@metamask/snaps-utils' {
|
|
4
|
+
interface DataMap {
|
|
5
|
+
/**
|
|
6
|
+
* Fully qualified, canonical path for the file in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8 } URI format.
|
|
7
|
+
*/
|
|
8
|
+
canonicalPath: string;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
export interface SnapLocation {
|
|
12
|
+
/**
|
|
13
|
+
* All files are relative to the manifest, except the manifest itself.
|
|
14
|
+
*/
|
|
15
|
+
manifest(): Promise<VirtualFile<SnapManifest>>;
|
|
16
|
+
fetch(path: string): Promise<VirtualFile>;
|
|
17
|
+
readonly shouldAlwaysReload?: boolean;
|
|
18
|
+
}
|
|
19
|
+
export declare type DetectSnapLocationOptions = NpmOptions & {
|
|
20
|
+
/**
|
|
21
|
+
* The function used to fetch data.
|
|
22
|
+
*
|
|
23
|
+
* @default globalThis.fetch
|
|
24
|
+
*/
|
|
25
|
+
fetch?: typeof fetch;
|
|
26
|
+
/**
|
|
27
|
+
* @default false
|
|
28
|
+
*/
|
|
29
|
+
allowHttp?: boolean;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Auto-magically detects which SnapLocation object to create based on the provided {@link location}.
|
|
33
|
+
*
|
|
34
|
+
* @param location - A {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8} uri.
|
|
35
|
+
* @param opts - NPM options and feature flags.
|
|
36
|
+
* @returns SnapLocation based on url.
|
|
37
|
+
*/
|
|
38
|
+
export declare function detectSnapLocation(location: string | URL, opts?: DetectSnapLocationOptions): SnapLocation;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.detectSnapLocation = void 0;
|
|
4
|
+
const utils_1 = require("@metamask/utils");
|
|
5
|
+
const http_1 = require("./http");
|
|
6
|
+
const local_1 = require("./local");
|
|
7
|
+
const npm_1 = require("./npm");
|
|
8
|
+
/**
|
|
9
|
+
* Auto-magically detects which SnapLocation object to create based on the provided {@link location}.
|
|
10
|
+
*
|
|
11
|
+
* @param location - A {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8} uri.
|
|
12
|
+
* @param opts - NPM options and feature flags.
|
|
13
|
+
* @returns SnapLocation based on url.
|
|
14
|
+
*/
|
|
15
|
+
function detectSnapLocation(location, opts) {
|
|
16
|
+
var _a;
|
|
17
|
+
const allowHttp = (_a = opts === null || opts === void 0 ? void 0 : opts.allowHttp) !== null && _a !== void 0 ? _a : false;
|
|
18
|
+
const root = new URL(location);
|
|
19
|
+
switch (root.protocol) {
|
|
20
|
+
case 'npm:':
|
|
21
|
+
return new npm_1.NpmLocation(root, opts);
|
|
22
|
+
case 'local:':
|
|
23
|
+
return new local_1.LocalLocation(root, opts);
|
|
24
|
+
case 'http:':
|
|
25
|
+
case 'https:':
|
|
26
|
+
(0, utils_1.assert)(allowHttp, new TypeError('Fetching snaps through http/https is disabled.'));
|
|
27
|
+
return new http_1.HttpLocation(root, opts);
|
|
28
|
+
default:
|
|
29
|
+
throw new TypeError(`Unrecognized "${root.protocol}" snap location protocol.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
exports.detectSnapLocation = detectSnapLocation;
|
|
33
|
+
//# sourceMappingURL=location.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"location.js","sourceRoot":"","sources":["../../../src/snaps/location/location.ts"],"names":[],"mappings":";;;AACA,2CAAyC;AAEzC,iCAAsC;AACtC,mCAAwC;AACxC,+BAAgD;AAkChD;;;;;;GAMG;AACH,SAAgB,kBAAkB,CAChC,QAAsB,EACtB,IAAgC;;IAEhC,MAAM,SAAS,GAAG,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,SAAS,mCAAI,KAAK,CAAC;IAC3C,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC/B,QAAQ,IAAI,CAAC,QAAQ,EAAE;QACrB,KAAK,MAAM;YACT,OAAO,IAAI,iBAAW,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACrC,KAAK,QAAQ;YACX,OAAO,IAAI,qBAAa,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACvC,KAAK,OAAO,CAAC;QACb,KAAK,QAAQ;YACX,IAAA,cAAM,EACJ,SAAS,EACT,IAAI,SAAS,CAAC,gDAAgD,CAAC,CAChE,CAAC;YACF,OAAO,IAAI,mBAAY,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACtC;YACE,MAAM,IAAI,SAAS,CACjB,iBAAiB,IAAI,CAAC,QAAQ,2BAA2B,CAC1D,CAAC;KACL;AACH,CAAC;AAvBD,gDAuBC","sourcesContent":["import { SnapManifest, VirtualFile } from '@metamask/snaps-utils';\nimport { assert } from '@metamask/utils';\n\nimport { HttpLocation } from './http';\nimport { LocalLocation } from './local';\nimport { NpmLocation, NpmOptions } from './npm';\n\ndeclare module '@metamask/snaps-utils' {\n interface DataMap {\n /**\n * Fully qualified, canonical path for the file in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8 } URI format.\n */\n canonicalPath: string;\n }\n}\n\nexport interface SnapLocation {\n /**\n * All files are relative to the manifest, except the manifest itself.\n */\n manifest(): Promise<VirtualFile<SnapManifest>>;\n fetch(path: string): Promise<VirtualFile>;\n\n readonly shouldAlwaysReload?: boolean;\n}\n\nexport type DetectSnapLocationOptions = NpmOptions & {\n /**\n * The function used to fetch data.\n *\n * @default globalThis.fetch\n */\n fetch?: typeof fetch;\n /**\n * @default false\n */\n allowHttp?: boolean;\n};\n\n/**\n * Auto-magically detects which SnapLocation object to create based on the provided {@link location}.\n *\n * @param location - A {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8} uri.\n * @param opts - NPM options and feature flags.\n * @returns SnapLocation based on url.\n */\nexport function detectSnapLocation(\n location: string | URL,\n opts?: DetectSnapLocationOptions,\n): SnapLocation {\n const allowHttp = opts?.allowHttp ?? false;\n const root = new URL(location);\n switch (root.protocol) {\n case 'npm:':\n return new NpmLocation(root, opts);\n case 'local:':\n return new LocalLocation(root, opts);\n case 'http:':\n case 'https:':\n assert(\n allowHttp,\n new TypeError('Fetching snaps through http/https is disabled.'),\n );\n return new HttpLocation(root, opts);\n default:\n throw new TypeError(\n `Unrecognized \"${root.protocol}\" snap location protocol.`,\n );\n }\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { SemVerRange, SnapManifest, VirtualFile } from '@metamask/snaps-utils';
|
|
2
|
+
import { DetectSnapLocationOptions, SnapLocation } from './location';
|
|
3
|
+
export interface NpmOptions {
|
|
4
|
+
/**
|
|
5
|
+
* @default DEFAULT_REQUESTED_SNAP_VERSION
|
|
6
|
+
*/
|
|
7
|
+
versionRange?: SemVerRange;
|
|
8
|
+
/**
|
|
9
|
+
* Whether to allow custom NPM registries outside of {@link DEFAULT_NPM_REGISTRY}.
|
|
10
|
+
*
|
|
11
|
+
* @default false
|
|
12
|
+
*/
|
|
13
|
+
allowCustomRegistries?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export declare class NpmLocation implements SnapLocation {
|
|
16
|
+
#private;
|
|
17
|
+
private readonly meta;
|
|
18
|
+
private validatedManifest?;
|
|
19
|
+
private files?;
|
|
20
|
+
constructor(url: URL, opts?: DetectSnapLocationOptions);
|
|
21
|
+
manifest(): Promise<VirtualFile<SnapManifest>>;
|
|
22
|
+
fetch(path: string): Promise<VirtualFile>;
|
|
23
|
+
get packageName(): string;
|
|
24
|
+
get version(): string;
|
|
25
|
+
get registry(): URL;
|
|
26
|
+
get versionRange(): SemVerRange;
|
|
27
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
3
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
4
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
5
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
6
|
+
};
|
|
7
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
8
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
9
|
+
};
|
|
10
|
+
var _NpmLocation_instances, _NpmLocation_lazyInit;
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.NpmLocation = void 0;
|
|
13
|
+
const snaps_utils_1 = require("@metamask/snaps-utils");
|
|
14
|
+
const utils_1 = require("@metamask/utils");
|
|
15
|
+
const concat_stream_1 = __importDefault(require("concat-stream"));
|
|
16
|
+
const gunzip_maybe_1 = __importDefault(require("gunzip-maybe"));
|
|
17
|
+
const pump_1 = __importDefault(require("pump"));
|
|
18
|
+
const readable_web_to_node_stream_1 = require("readable-web-to-node-stream");
|
|
19
|
+
const tar_stream_1 = require("tar-stream");
|
|
20
|
+
const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org';
|
|
21
|
+
class NpmLocation {
|
|
22
|
+
constructor(url, opts = {}) {
|
|
23
|
+
var _a, _b, _c;
|
|
24
|
+
_NpmLocation_instances.add(this);
|
|
25
|
+
const allowCustomRegistries = (_a = opts.allowCustomRegistries) !== null && _a !== void 0 ? _a : false;
|
|
26
|
+
const fetchFunction = (_b = opts.fetch) !== null && _b !== void 0 ? _b : globalThis.fetch.bind(globalThis);
|
|
27
|
+
const requestedRange = (_c = opts.versionRange) !== null && _c !== void 0 ? _c : snaps_utils_1.DEFAULT_REQUESTED_SNAP_VERSION;
|
|
28
|
+
(0, utils_1.assertStruct)(url.toString(), snaps_utils_1.NpmSnapIdStruct, 'Invalid Snap Id: ');
|
|
29
|
+
let registry;
|
|
30
|
+
if (url.host === '' &&
|
|
31
|
+
url.port === '' &&
|
|
32
|
+
url.username === '' &&
|
|
33
|
+
url.password === '') {
|
|
34
|
+
registry = new URL(DEFAULT_NPM_REGISTRY);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
registry = 'https://';
|
|
38
|
+
if (url.username) {
|
|
39
|
+
registry += url.username;
|
|
40
|
+
if (url.password) {
|
|
41
|
+
registry += `:${url.password}`;
|
|
42
|
+
}
|
|
43
|
+
registry += '@';
|
|
44
|
+
}
|
|
45
|
+
registry += url.host;
|
|
46
|
+
registry = new URL(registry);
|
|
47
|
+
(0, utils_1.assert)(allowCustomRegistries, new TypeError(`Custom NPM registries are disabled, tried to use "${registry.toString()}".`));
|
|
48
|
+
}
|
|
49
|
+
(0, utils_1.assert)(registry.pathname === '/' &&
|
|
50
|
+
registry.search === '' &&
|
|
51
|
+
registry.hash === '');
|
|
52
|
+
(0, utils_1.assert)(url.pathname !== '' && url.pathname !== '/', new TypeError('The package name in NPM location is empty.'));
|
|
53
|
+
let packageName = url.pathname;
|
|
54
|
+
if (packageName.startsWith('/')) {
|
|
55
|
+
packageName = packageName.slice(1);
|
|
56
|
+
}
|
|
57
|
+
this.meta = {
|
|
58
|
+
requestedRange,
|
|
59
|
+
registry,
|
|
60
|
+
packageName,
|
|
61
|
+
fetch: fetchFunction,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
async manifest() {
|
|
65
|
+
if (this.validatedManifest) {
|
|
66
|
+
return this.validatedManifest.clone();
|
|
67
|
+
}
|
|
68
|
+
const vfile = await this.fetch('snap.manifest.json');
|
|
69
|
+
const result = JSON.parse(vfile.toString());
|
|
70
|
+
vfile.result = (0, snaps_utils_1.createSnapManifest)(result);
|
|
71
|
+
this.validatedManifest = vfile;
|
|
72
|
+
return this.manifest();
|
|
73
|
+
}
|
|
74
|
+
async fetch(path) {
|
|
75
|
+
const relativePath = (0, snaps_utils_1.normalizeRelative)(path);
|
|
76
|
+
if (!this.files) {
|
|
77
|
+
await __classPrivateFieldGet(this, _NpmLocation_instances, "m", _NpmLocation_lazyInit).call(this);
|
|
78
|
+
(0, utils_1.assert)(this.files !== undefined);
|
|
79
|
+
}
|
|
80
|
+
const vfile = this.files.get(relativePath);
|
|
81
|
+
(0, utils_1.assert)(vfile !== undefined, new TypeError(`File "${path}" not found in package.`));
|
|
82
|
+
return vfile.clone();
|
|
83
|
+
}
|
|
84
|
+
get packageName() {
|
|
85
|
+
return this.meta.packageName;
|
|
86
|
+
}
|
|
87
|
+
get version() {
|
|
88
|
+
(0, utils_1.assert)(this.meta.version !== undefined, 'Tried to access version without first fetching NPM package.');
|
|
89
|
+
return this.meta.version;
|
|
90
|
+
}
|
|
91
|
+
get registry() {
|
|
92
|
+
return this.meta.registry;
|
|
93
|
+
}
|
|
94
|
+
get versionRange() {
|
|
95
|
+
return this.meta.requestedRange;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
exports.NpmLocation = NpmLocation;
|
|
99
|
+
_NpmLocation_instances = new WeakSet(), _NpmLocation_lazyInit = async function _NpmLocation_lazyInit() {
|
|
100
|
+
(0, utils_1.assert)(this.files === undefined);
|
|
101
|
+
const [tarballResponse, actualVersion] = await fetchNpmTarball(this.meta.packageName, this.meta.requestedRange, this.meta.registry, this.meta.fetch);
|
|
102
|
+
this.meta.version = actualVersion;
|
|
103
|
+
let canonicalBase = 'npm://';
|
|
104
|
+
if (this.meta.registry.username !== '') {
|
|
105
|
+
canonicalBase += this.meta.registry.username;
|
|
106
|
+
if (this.meta.registry.password !== '') {
|
|
107
|
+
canonicalBase += `:${this.meta.registry.password}`;
|
|
108
|
+
}
|
|
109
|
+
canonicalBase += '@';
|
|
110
|
+
}
|
|
111
|
+
canonicalBase += this.meta.registry.host;
|
|
112
|
+
// TODO(ritave): Lazily extract files instead of up-front extracting all of them
|
|
113
|
+
// We would need to replace tar-stream package because it requires immediate consumption of streams.
|
|
114
|
+
await new Promise((resolve, reject) => {
|
|
115
|
+
this.files = new Map();
|
|
116
|
+
(0, pump_1.default)(getNodeStream(tarballResponse),
|
|
117
|
+
// The "gz" in "tgz" stands for "gzip". The tarball needs to be decompressed
|
|
118
|
+
// before we can actually grab any files from it.
|
|
119
|
+
(0, gunzip_maybe_1.default)(), createTarballStream(`${canonicalBase}/${this.meta.packageName}/`, this.files), (error) => {
|
|
120
|
+
error ? reject(error) : resolve();
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* Fetches the tarball (`.tgz` file) of the specified package and version from
|
|
126
|
+
* the public npm registry. Throws an error if fetching fails.
|
|
127
|
+
*
|
|
128
|
+
* @param packageName - The name of the package whose tarball to fetch.
|
|
129
|
+
* @param versionRange - The SemVer range of the package to fetch. The highest
|
|
130
|
+
* version satisfying the range will be fetched.
|
|
131
|
+
* @param registryUrl - The URL of the npm registry to fetch the tarball from.
|
|
132
|
+
* @param fetchFunction - The fetch function to use. Defaults to the global
|
|
133
|
+
* {@link fetch}. Useful for Node.js compatibility.
|
|
134
|
+
* @returns A tuple of the {@link Response} for the package tarball and the
|
|
135
|
+
* actual version of the package.
|
|
136
|
+
*/
|
|
137
|
+
async function fetchNpmTarball(packageName, versionRange, registryUrl, fetchFunction) {
|
|
138
|
+
var _a, _b, _c, _d;
|
|
139
|
+
const packageMetadata = await (await fetchFunction(new URL(packageName, registryUrl).toString())).json();
|
|
140
|
+
if (!(0, utils_1.isObject)(packageMetadata)) {
|
|
141
|
+
throw new Error(`Failed to fetch package "${packageName}" metadata from npm.`);
|
|
142
|
+
}
|
|
143
|
+
const versions = Object.keys((_a = packageMetadata === null || packageMetadata === void 0 ? void 0 : packageMetadata.versions) !== null && _a !== void 0 ? _a : {}).map((version) => {
|
|
144
|
+
(0, snaps_utils_1.assertIsSemVerVersion)(version);
|
|
145
|
+
return version;
|
|
146
|
+
});
|
|
147
|
+
const targetVersion = (0, snaps_utils_1.getTargetVersion)(versions, versionRange);
|
|
148
|
+
if (targetVersion === null) {
|
|
149
|
+
throw new Error(`Failed to find a matching version in npm metadata for package "${packageName}" and requested semver range "${versionRange}".`);
|
|
150
|
+
}
|
|
151
|
+
const tarballUrlString = (_d = (_c = (_b = packageMetadata === null || packageMetadata === void 0 ? void 0 : 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;
|
|
152
|
+
if (!(0, snaps_utils_1.isValidUrl)(tarballUrlString) ||
|
|
153
|
+
!tarballUrlString.toString().endsWith('.tgz')) {
|
|
154
|
+
throw new Error(`Failed to find valid tarball URL in NPM metadata for package "${packageName}".`);
|
|
155
|
+
}
|
|
156
|
+
// Override the tarball hostname/protocol with registryUrl hostname/protocol
|
|
157
|
+
const newRegistryUrl = new URL(registryUrl);
|
|
158
|
+
const newTarballUrl = new URL(tarballUrlString);
|
|
159
|
+
newTarballUrl.hostname = newRegistryUrl.hostname;
|
|
160
|
+
newTarballUrl.protocol = newRegistryUrl.protocol;
|
|
161
|
+
// Perform a raw fetch because we want the Response object itself.
|
|
162
|
+
const tarballResponse = await fetchFunction(newTarballUrl.toString());
|
|
163
|
+
if (!tarballResponse.ok || !tarballResponse.body) {
|
|
164
|
+
throw new Error(`Failed to fetch tarball for package "${packageName}".`);
|
|
165
|
+
}
|
|
166
|
+
return [tarballResponse.body, targetVersion];
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* The paths of files within npm tarballs appear to always be prefixed with
|
|
170
|
+
* "package/".
|
|
171
|
+
*/
|
|
172
|
+
const NPM_TARBALL_PATH_PREFIX = /^package\//u;
|
|
173
|
+
/**
|
|
174
|
+
* Converts a {@link ReadableStream} to a Node.js {@link Readable}
|
|
175
|
+
* stream. Returns the stream directly if it is already a Node.js stream.
|
|
176
|
+
* We can't use the native Web {@link ReadableStream} directly because the
|
|
177
|
+
* other stream libraries we use expect Node.js streams.
|
|
178
|
+
*
|
|
179
|
+
* @param stream - The stream to convert.
|
|
180
|
+
* @returns The given stream as a Node.js Readable stream.
|
|
181
|
+
*/
|
|
182
|
+
function getNodeStream(stream) {
|
|
183
|
+
if (typeof stream.getReader !== 'function') {
|
|
184
|
+
return stream;
|
|
185
|
+
}
|
|
186
|
+
return new readable_web_to_node_stream_1.ReadableWebToNodeStream(stream);
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Creates a `tar-stream` that will get the necessary files from an npm Snap
|
|
190
|
+
* package tarball (`.tgz` file).
|
|
191
|
+
*
|
|
192
|
+
* @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.
|
|
193
|
+
* @param files - An object to write target file contents to.
|
|
194
|
+
* @returns The {@link Writable} tarball extraction stream.
|
|
195
|
+
*/
|
|
196
|
+
function createTarballStream(canonicalBase, files) {
|
|
197
|
+
(0, utils_1.assert)(canonicalBase.endsWith('/'), "Base needs to end with '/' for relative paths to be added as children instead of siblings.");
|
|
198
|
+
(0, utils_1.assert)(canonicalBase.startsWith('npm:'), 'Protocol mismatch, expected "npm:".');
|
|
199
|
+
// `tar-stream` is pretty old-school, so we create it first and then
|
|
200
|
+
// instrument it by adding event listeners.
|
|
201
|
+
const extractStream = (0, tar_stream_1.extract)();
|
|
202
|
+
// "entry" is fired for every discreet entity in the tarball. This includes
|
|
203
|
+
// files and folders.
|
|
204
|
+
extractStream.on('entry', (header, entryStream, next) => {
|
|
205
|
+
const { name: headerName, type: headerType } = header;
|
|
206
|
+
if (headerType === 'file') {
|
|
207
|
+
// The name is a path if the header type is "file".
|
|
208
|
+
const path = headerName.replace(NPM_TARBALL_PATH_PREFIX, '');
|
|
209
|
+
return entryStream.pipe((0, concat_stream_1.default)((data) => {
|
|
210
|
+
const vfile = new snaps_utils_1.VirtualFile({
|
|
211
|
+
value: data,
|
|
212
|
+
path,
|
|
213
|
+
data: {
|
|
214
|
+
canonicalPath: new URL(path, canonicalBase).toString(),
|
|
215
|
+
},
|
|
216
|
+
});
|
|
217
|
+
(0, utils_1.assert)(!files.has(path), 'Malformed tarball, multiple files with the same path.');
|
|
218
|
+
files.set(path, vfile);
|
|
219
|
+
return next();
|
|
220
|
+
}));
|
|
221
|
+
}
|
|
222
|
+
// If we get here, the entry is not a file, and we want to ignore. The entry
|
|
223
|
+
// stream must be drained, or the extractStream will stop reading. This is
|
|
224
|
+
// effectively a no-op for the current entry.
|
|
225
|
+
entryStream.on('end', () => next());
|
|
226
|
+
return entryStream.resume();
|
|
227
|
+
});
|
|
228
|
+
return extractStream;
|
|
229
|
+
}
|
|
230
|
+
//# sourceMappingURL=npm.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"npm.js","sourceRoot":"","sources":["../../../src/snaps/location/npm.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uDAY+B;AAC/B,2CAAiE;AACjE,kEAAmC;AACnC,gEAA8C;AAC9C,gDAAwB;AACxB,6EAAsE;AAEtE,2CAAmD;AAInD,MAAM,oBAAoB,GAAG,4BAA4B,CAAC;AAsB1D,MAAa,WAAW;IAOtB,YAAY,GAAQ,EAAE,OAAkC,EAAE;;;QACxD,MAAM,qBAAqB,GAAG,MAAA,IAAI,CAAC,qBAAqB,mCAAI,KAAK,CAAC;QAClE,MAAM,aAAa,GAAG,MAAA,IAAI,CAAC,KAAK,mCAAI,UAAU,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACtE,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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AC;IAEnC,2EAA2E;IAC3E,qBAAqB;IACrB,aAAa,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,WAAW,EAAE,IAAI,EAAE,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,EAAE,CAAC,CAAC;YAC7D,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 createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n SemVerRange,\n SemVerVersion,\n SnapManifest,\n VirtualFile,\n normalizeRelative,\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 { DetectSnapLocationOptions, 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 * 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: DetectSnapLocationOptions = {}) {\n const allowCustomRegistries = opts.allowCustomRegistries ?? false;\n const fetchFunction = opts.fetch ?? globalThis.fetch.bind(globalThis);\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 vfile.result = createSnapManifest(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 = normalizeRelative(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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/snaps-controllers",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.26.1",
|
|
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.
|
|
35
|
-
"@metamask/base-controller": "^1.
|
|
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.
|
|
38
|
+
"@metamask/permission-controller": "^1.0.1",
|
|
39
39
|
"@metamask/post-message-stream": "^6.0.0",
|
|
40
|
-
"@metamask/rpc-methods": "^0.
|
|
41
|
-
"@metamask/snaps-execution-environments": "^0.
|
|
42
|
-
"@metamask/snaps-types": "^0.
|
|
43
|
-
"@metamask/snaps-utils": "^0.
|
|
44
|
-
"@metamask/subject-metadata-controller": "^1.0.
|
|
40
|
+
"@metamask/rpc-methods": "^0.26.1",
|
|
41
|
+
"@metamask/snaps-execution-environments": "^0.26.1",
|
|
42
|
+
"@metamask/snaps-types": "^0.26.1",
|
|
43
|
+
"@metamask/snaps-utils": "^0.26.1",
|
|
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 +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>;
|