-
Notifications
You must be signed in to change notification settings - Fork 542
/
location.ts
70 lines (64 loc) · 1.89 KB
/
location.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { SnapManifest, VirtualFile } from '@metamask/snaps-utils';
import { assert } from '@metamask/utils';
import { HttpLocation } from './http';
import { LocalLocation } from './local';
import { NpmLocation, NpmOptions } from './npm';
declare module '@metamask/snaps-utils' {
interface DataMap {
/**
* Fully qualified, canonical path for the file in {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8 } URI format.
*/
canonicalPath: string;
}
}
export interface SnapLocation {
/**
* All files are relative to the manifest, except the manifest itself.
*/
manifest(): Promise<VirtualFile<SnapManifest>>;
fetch(path: string): Promise<VirtualFile>;
readonly shouldAlwaysReload?: boolean;
}
export type DetectSnapLocationOptions = NpmOptions & {
/**
* The function used to fetch data.
*
* @default globalThis.fetch
*/
fetch?: typeof fetch;
/**
* @default false
*/
allowHttp?: boolean;
};
/**
* Auto-magically detects which SnapLocation object to create based on the provided {@link location}.
*
* @param location - A {@link https://github.com/MetaMask/SIPs/blob/main/SIPS/sip-8.md SIP-8} uri.
* @param opts - NPM options and feature flags.
* @returns SnapLocation based on url.
*/
export function detectSnapLocation(
location: string | URL,
opts?: DetectSnapLocationOptions,
): SnapLocation {
const allowHttp = opts?.allowHttp ?? false;
const root = new URL(location);
switch (root.protocol) {
case 'npm:':
return new NpmLocation(root, opts);
case 'local:':
return new LocalLocation(root, opts);
case 'http:':
case 'https:':
assert(
allowHttp,
new TypeError('Fetching snaps through http/https is disabled.'),
);
return new HttpLocation(root, opts);
default:
throw new TypeError(
`Unrecognized "${root.protocol}" snap location protocol.`,
);
}
}