@metamask/snaps-controllers 4.0.0 → 5.0.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.
Files changed (163) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/dist/cjs/cronjob/CronjobController.js +3 -3
  3. package/dist/cjs/cronjob/CronjobController.js.map +1 -1
  4. package/dist/cjs/index.js +1 -0
  5. package/dist/cjs/index.js.map +1 -1
  6. package/dist/cjs/interface/SnapInterfaceController.js +166 -0
  7. package/dist/cjs/interface/SnapInterfaceController.js.map +1 -0
  8. package/dist/cjs/interface/index.js +20 -0
  9. package/dist/cjs/interface/index.js.map +1 -0
  10. package/dist/cjs/interface/utils.js +59 -0
  11. package/dist/cjs/interface/utils.js.map +1 -0
  12. package/dist/cjs/services/ProxyPostMessageStream.js +3 -10
  13. package/dist/cjs/services/ProxyPostMessageStream.js.map +1 -1
  14. package/dist/cjs/services/browser.js +1 -0
  15. package/dist/cjs/services/browser.js.map +1 -1
  16. package/dist/cjs/services/index.js +1 -0
  17. package/dist/cjs/services/index.js.map +1 -1
  18. package/dist/cjs/services/node/NodeProcessExecutionService.js +13 -1
  19. package/dist/cjs/services/node/NodeProcessExecutionService.js.map +1 -1
  20. package/dist/cjs/services/node/NodeThreadExecutionService.js +14 -1
  21. package/dist/cjs/services/node/NodeThreadExecutionService.js.map +1 -1
  22. package/dist/cjs/services/offscreen/OffscreenExecutionService.js +36 -99
  23. package/dist/cjs/services/offscreen/OffscreenExecutionService.js.map +1 -1
  24. package/dist/cjs/services/proxy/ProxyExecutionService.js +110 -0
  25. package/dist/cjs/services/proxy/ProxyExecutionService.js.map +1 -0
  26. package/dist/cjs/services/webview/WebViewExecutionService.js +99 -0
  27. package/dist/cjs/services/webview/WebViewExecutionService.js.map +1 -0
  28. package/dist/cjs/services/webview/WebViewMessageStream.js +127 -0
  29. package/dist/cjs/services/webview/WebViewMessageStream.js.map +1 -0
  30. package/dist/cjs/services/webview/index.js +20 -0
  31. package/dist/cjs/services/webview/index.js.map +1 -0
  32. package/dist/cjs/snaps/SnapController.js +303 -138
  33. package/dist/cjs/snaps/SnapController.js.map +1 -1
  34. package/dist/cjs/snaps/constants.js +25 -0
  35. package/dist/cjs/snaps/constants.js.map +1 -0
  36. package/dist/cjs/snaps/index.js +0 -2
  37. package/dist/cjs/snaps/index.js.map +1 -1
  38. package/dist/cjs/snaps/location/npm.js +13 -2
  39. package/dist/cjs/snaps/location/npm.js.map +1 -1
  40. package/dist/cjs/utils.js +32 -0
  41. package/dist/cjs/utils.js.map +1 -1
  42. package/dist/esm/cronjob/CronjobController.js +2 -2
  43. package/dist/esm/cronjob/CronjobController.js.map +1 -1
  44. package/dist/esm/index.js +1 -0
  45. package/dist/esm/index.js.map +1 -1
  46. package/dist/esm/interface/SnapInterfaceController.js +158 -0
  47. package/dist/esm/interface/SnapInterfaceController.js.map +1 -0
  48. package/dist/esm/interface/index.js +3 -0
  49. package/dist/esm/interface/index.js.map +1 -0
  50. package/dist/esm/interface/utils.js +62 -0
  51. package/dist/esm/interface/utils.js.map +1 -0
  52. package/dist/esm/services/ProxyPostMessageStream.js +3 -10
  53. package/dist/esm/services/ProxyPostMessageStream.js.map +1 -1
  54. package/dist/esm/services/browser.js +1 -0
  55. package/dist/esm/services/browser.js.map +1 -1
  56. package/dist/esm/services/index.js +1 -0
  57. package/dist/esm/services/index.js.map +1 -1
  58. package/dist/esm/services/node/NodeProcessExecutionService.js +13 -1
  59. package/dist/esm/services/node/NodeProcessExecutionService.js.map +1 -1
  60. package/dist/esm/services/node/NodeThreadExecutionService.js +14 -1
  61. package/dist/esm/services/node/NodeThreadExecutionService.js.map +1 -1
  62. package/dist/esm/services/offscreen/OffscreenExecutionService.js +36 -99
  63. package/dist/esm/services/offscreen/OffscreenExecutionService.js.map +1 -1
  64. package/dist/esm/services/proxy/ProxyExecutionService.js +100 -0
  65. package/dist/esm/services/proxy/ProxyExecutionService.js.map +1 -0
  66. package/dist/esm/services/webview/WebViewExecutionService.js +89 -0
  67. package/dist/esm/services/webview/WebViewExecutionService.js.map +1 -0
  68. package/dist/esm/services/webview/WebViewMessageStream.js +119 -0
  69. package/dist/esm/services/webview/WebViewMessageStream.js.map +1 -0
  70. package/dist/esm/services/webview/index.js +3 -0
  71. package/dist/esm/services/webview/index.js.map +1 -0
  72. package/dist/esm/snaps/SnapController.js +299 -134
  73. package/dist/esm/snaps/SnapController.js.map +1 -1
  74. package/dist/esm/snaps/constants.js +16 -0
  75. package/dist/esm/snaps/constants.js.map +1 -0
  76. package/dist/esm/snaps/index.js +0 -2
  77. package/dist/esm/snaps/index.js.map +1 -1
  78. package/dist/esm/snaps/location/npm.js +13 -2
  79. package/dist/esm/snaps/location/npm.js.map +1 -1
  80. package/dist/esm/utils.js +37 -0
  81. package/dist/esm/utils.js.map +1 -1
  82. package/dist/types/index.d.ts +1 -0
  83. package/dist/types/interface/SnapInterfaceController.d.ts +85 -0
  84. package/dist/types/interface/index.d.ts +1 -0
  85. package/dist/types/interface/utils.d.ts +36 -0
  86. package/dist/types/services/ProxyPostMessageStream.d.ts +1 -2
  87. package/dist/types/services/browser.d.ts +1 -0
  88. package/dist/types/services/index.d.ts +1 -0
  89. package/dist/types/services/offscreen/OffscreenExecutionService.d.ts +5 -22
  90. package/dist/types/services/proxy/ProxyExecutionService.d.ts +39 -0
  91. package/dist/types/services/webview/WebViewExecutionService.d.ts +20 -0
  92. package/dist/types/services/webview/WebViewMessageStream.d.ts +32 -0
  93. package/dist/types/services/webview/index.d.ts +1 -0
  94. package/dist/types/snaps/SnapController.d.ts +37 -6
  95. package/dist/types/snaps/constants.d.ts +1 -0
  96. package/dist/types/snaps/index.d.ts +0 -2
  97. package/dist/types/utils.d.ts +119 -0
  98. package/package.json +14 -14
  99. package/dist/cjs/snaps/endowments/cronjob.js +0 -100
  100. package/dist/cjs/snaps/endowments/cronjob.js.map +0 -1
  101. package/dist/cjs/snaps/endowments/enum.js +0 -25
  102. package/dist/cjs/snaps/endowments/enum.js.map +0 -1
  103. package/dist/cjs/snaps/endowments/ethereum-provider.js +0 -43
  104. package/dist/cjs/snaps/endowments/ethereum-provider.js.map +0 -1
  105. package/dist/cjs/snaps/endowments/home-page.js +0 -37
  106. package/dist/cjs/snaps/endowments/home-page.js.map +0 -1
  107. package/dist/cjs/snaps/endowments/index.js +0 -99
  108. package/dist/cjs/snaps/endowments/index.js.map +0 -1
  109. package/dist/cjs/snaps/endowments/keyring.js +0 -100
  110. package/dist/cjs/snaps/endowments/keyring.js.map +0 -1
  111. package/dist/cjs/snaps/endowments/lifecycle-hooks.js +0 -37
  112. package/dist/cjs/snaps/endowments/lifecycle-hooks.js.map +0 -1
  113. package/dist/cjs/snaps/endowments/name-lookup.js +0 -106
  114. package/dist/cjs/snaps/endowments/name-lookup.js.map +0 -1
  115. package/dist/cjs/snaps/endowments/network-access.js +0 -44
  116. package/dist/cjs/snaps/endowments/network-access.js.map +0 -1
  117. package/dist/cjs/snaps/endowments/rpc.js +0 -99
  118. package/dist/cjs/snaps/endowments/rpc.js.map +0 -1
  119. package/dist/cjs/snaps/endowments/transaction-insight.js +0 -106
  120. package/dist/cjs/snaps/endowments/transaction-insight.js.map +0 -1
  121. package/dist/cjs/snaps/endowments/web-assembly.js +0 -42
  122. package/dist/cjs/snaps/endowments/web-assembly.js.map +0 -1
  123. package/dist/cjs/snaps/permissions.js +0 -61
  124. package/dist/cjs/snaps/permissions.js.map +0 -1
  125. package/dist/esm/snaps/endowments/cronjob.js +0 -99
  126. package/dist/esm/snaps/endowments/cronjob.js.map +0 -1
  127. package/dist/esm/snaps/endowments/enum.js +0 -15
  128. package/dist/esm/snaps/endowments/enum.js.map +0 -1
  129. package/dist/esm/snaps/endowments/ethereum-provider.js +0 -33
  130. package/dist/esm/snaps/endowments/ethereum-provider.js.map +0 -1
  131. package/dist/esm/snaps/endowments/home-page.js +0 -27
  132. package/dist/esm/snaps/endowments/home-page.js.map +0 -1
  133. package/dist/esm/snaps/endowments/index.js +0 -54
  134. package/dist/esm/snaps/endowments/index.js.map +0 -1
  135. package/dist/esm/snaps/endowments/keyring.js +0 -91
  136. package/dist/esm/snaps/endowments/keyring.js.map +0 -1
  137. package/dist/esm/snaps/endowments/lifecycle-hooks.js +0 -27
  138. package/dist/esm/snaps/endowments/lifecycle-hooks.js.map +0 -1
  139. package/dist/esm/snaps/endowments/name-lookup.js +0 -98
  140. package/dist/esm/snaps/endowments/name-lookup.js.map +0 -1
  141. package/dist/esm/snaps/endowments/network-access.js +0 -34
  142. package/dist/esm/snaps/endowments/network-access.js.map +0 -1
  143. package/dist/esm/snaps/endowments/rpc.js +0 -88
  144. package/dist/esm/snaps/endowments/rpc.js.map +0 -1
  145. package/dist/esm/snaps/endowments/transaction-insight.js +0 -99
  146. package/dist/esm/snaps/endowments/transaction-insight.js.map +0 -1
  147. package/dist/esm/snaps/endowments/web-assembly.js +0 -32
  148. package/dist/esm/snaps/endowments/web-assembly.js.map +0 -1
  149. package/dist/esm/snaps/permissions.js +0 -50
  150. package/dist/esm/snaps/permissions.js.map +0 -1
  151. package/dist/types/snaps/endowments/cronjob.d.ts +0 -51
  152. package/dist/types/snaps/endowments/enum.d.ts +0 -12
  153. package/dist/types/snaps/endowments/ethereum-provider.d.ts +0 -14
  154. package/dist/types/snaps/endowments/home-page.d.ts +0 -15
  155. package/dist/types/snaps/endowments/index.d.ts +0 -115
  156. package/dist/types/snaps/endowments/keyring.d.ts +0 -39
  157. package/dist/types/snaps/endowments/lifecycle-hooks.d.ts +0 -15
  158. package/dist/types/snaps/endowments/name-lookup.d.ts +0 -38
  159. package/dist/types/snaps/endowments/network-access.d.ts +0 -14
  160. package/dist/types/snaps/endowments/rpc.d.ts +0 -38
  161. package/dist/types/snaps/endowments/transaction-insight.d.ts +0 -39
  162. package/dist/types/snaps/endowments/web-assembly.d.ts +0 -14
  163. package/dist/types/snaps/permissions.d.ts +0 -16
@@ -0,0 +1,16 @@
1
+ import { SnapEndowments } from '@metamask/snaps-rpc-methods';
2
+ // These permissions are allowed without being on the allowlist.
3
+ export const ALLOWED_PERMISSIONS = Object.freeze([
4
+ 'snap_dialog',
5
+ 'snap_manageState',
6
+ 'snap_notify',
7
+ 'snap_getLocale',
8
+ SnapEndowments.Cronjob,
9
+ SnapEndowments.HomePage,
10
+ SnapEndowments.LifecycleHooks,
11
+ SnapEndowments.EthereumProvider,
12
+ SnapEndowments.TransactionInsight,
13
+ SnapEndowments.SignatureInsight
14
+ ]);
15
+
16
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/snaps/constants.ts"],"sourcesContent":["import { SnapEndowments } from '@metamask/snaps-rpc-methods';\n\n// These permissions are allowed without being on the allowlist.\nexport const ALLOWED_PERMISSIONS = Object.freeze([\n 'snap_dialog',\n 'snap_manageState',\n 'snap_notify',\n 'snap_getLocale',\n SnapEndowments.Cronjob,\n SnapEndowments.HomePage,\n SnapEndowments.LifecycleHooks,\n SnapEndowments.EthereumProvider,\n SnapEndowments.TransactionInsight,\n SnapEndowments.SignatureInsight,\n]);\n"],"names":["SnapEndowments","ALLOWED_PERMISSIONS","Object","freeze","Cronjob","HomePage","LifecycleHooks","EthereumProvider","TransactionInsight","SignatureInsight"],"mappings":"AAAA,SAASA,cAAc,QAAQ,8BAA8B;AAE7D,gEAAgE;AAChE,OAAO,MAAMC,sBAAsBC,OAAOC,MAAM,CAAC;IAC/C;IACA;IACA;IACA;IACAH,eAAeI,OAAO;IACtBJ,eAAeK,QAAQ;IACvBL,eAAeM,cAAc;IAC7BN,eAAeO,gBAAgB;IAC/BP,eAAeQ,kBAAkB;IACjCR,eAAeS,gBAAgB;CAChC,EAAE"}
@@ -1,8 +1,6 @@
1
1
  export * from './location';
2
2
  export * from './SnapController';
3
- export * from './endowments';
4
3
  export * from './selectors';
5
4
  export * from './registry';
6
- export * from './permissions';
7
5
 
8
6
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/snaps/index.ts"],"sourcesContent":["export * from './location';\nexport * from './SnapController';\nexport * from './endowments';\nexport * from './selectors';\nexport * from './registry';\nexport * from './permissions';\n"],"names":[],"mappings":"AAAA,cAAc,aAAa;AAC3B,cAAc,mBAAmB;AACjC,cAAc,eAAe;AAC7B,cAAc,cAAc;AAC5B,cAAc,aAAa;AAC3B,cAAc,gBAAgB"}
1
+ {"version":3,"sources":["../../../src/snaps/index.ts"],"sourcesContent":["export * from './location';\nexport * from './SnapController';\nexport * from './selectors';\nexport * from './registry';\n"],"names":[],"mappings":"AAAA,cAAc,aAAa;AAC3B,cAAc,mBAAmB;AACjC,cAAc,cAAc;AAC5B,cAAc,aAAa"}
@@ -192,11 +192,22 @@ export class NpmLocation extends BaseNpmLocation {
192
192
  assert(tarballSize <= TARBALL_SIZE_SAFETY_LIMIT, 'Snap tarball exceeds size limit');
193
193
  return new Promise((resolve, reject)=>{
194
194
  const files = new Map();
195
+ const tarballStream = createTarballStream(getNpmCanonicalBasePath(this.meta.registry, this.meta.packageName), files);
196
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
197
+ const body = tarballResponse.body;
195
198
  // The "gz" in "tgz" stands for "gzip". The tarball needs to be decompressed
196
199
  // before we can actually grab any files from it.
197
200
  // To prevent recursion-based zip bombs, we should not allow recursion here.
198
- pipeline(// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
199
- getNodeStream(tarballResponse.body), createGunzip(), createTarballStream(getNpmCanonicalBasePath(this.meta.registry, this.meta.packageName), files), (error)=>{
201
+ // If native decompression stream is available we use that, otherwise fallback to zlib.
202
+ if ('pipeThrough' in body && 'DecompressionStream' in globalThis) {
203
+ const decompressionStream = new DecompressionStream('gzip');
204
+ const decompressedStream = body.pipeThrough(decompressionStream);
205
+ pipeline(getNodeStream(decompressedStream), tarballStream, (error)=>{
206
+ error ? reject(error) : resolve(files);
207
+ });
208
+ return;
209
+ }
210
+ pipeline(getNodeStream(body), createGunzip(), tarballStream, (error)=>{
200
211
  error ? reject(error) : resolve(files);
201
212
  });
202
213
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/snaps/location/npm.ts"],"sourcesContent":["import type { SnapManifest } from '@metamask/snaps-utils';\nimport {\n createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n VirtualFile,\n normalizeRelative,\n parseJson,\n} from '@metamask/snaps-utils';\nimport type { SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerVersion,\n assertStruct,\n isObject,\n isValidSemVerVersion,\n} from '@metamask/utils';\nimport { createGunzip } from 'browserify-zlib';\nimport concat from 'concat-stream';\nimport getNpmTarballUrl from 'get-npm-tarball-url';\nimport { pipeline } from 'readable-stream';\nimport type { Readable, Writable } from 'readable-stream';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport type { DetectSnapLocationOptions, SnapLocation } from './location';\n\nexport const DEFAULT_NPM_REGISTRY = new URL('https://registry.npmjs.org');\n\ninterface NpmMeta {\n registry: URL;\n packageName: string;\n requestedRange: SemVerRange;\n version?: string;\n fetch: typeof fetch;\n resolveVersion: (range: SemVerRange) => Promise<SemVerRange>;\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\n// Base class for NPM implementation, useful for extending with custom NPM fetching logic\nexport abstract class BaseNpmLocation implements SnapLocation {\n protected readonly meta: NpmMeta;\n\n #validatedManifest?: VirtualFile<SnapManifest>;\n\n #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 const defaultResolve = async (range: SemVerRange) => range;\n const resolveVersion = opts.resolveVersion ?? defaultResolve;\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 = 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 resolveVersion,\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 = parseJson(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 resolvedVersion = await this.meta.resolveVersion(\n this.meta.requestedRange,\n );\n\n const { tarballURL, targetVersion } = await resolveNpmVersion(\n this.meta.packageName,\n resolvedVersion,\n this.meta.registry,\n this.meta.fetch,\n );\n\n if (!isValidUrl(tarballURL) || !tarballURL.toString().endsWith('.tgz')) {\n throw new Error(\n `Failed to find valid tarball URL in NPM metadata for package \"${this.meta.packageName}\".`,\n );\n }\n\n // Override the tarball hostname/protocol with registryUrl hostname/protocol\n const newTarballUrl = new URL(tarballURL);\n newTarballUrl.hostname = this.meta.registry.hostname;\n newTarballUrl.protocol = this.meta.registry.protocol;\n\n const files = await this.fetchNpmTarball(newTarballUrl);\n\n this.#files = files;\n this.meta.version = targetVersion;\n }\n\n /**\n * Fetches and unpacks the tarball (`.tgz` file) from the specified URL.\n *\n * @param tarballUrl - The tarball URL to fetch and unpack.\n * @returns A the files for the package tarball.\n * @throws If fetching the tarball fails.\n */\n abstract fetchNpmTarball(tarballUrl: URL): Promise<Map<string, VirtualFile>>;\n}\n\n// Safety limit for tarballs, 250 MB in bytes\nexport const TARBALL_SIZE_SAFETY_LIMIT = 262144000;\n\n// Main NPM implementation, contains a browser tarball fetching implementation.\nexport class NpmLocation extends BaseNpmLocation {\n /**\n * Fetches and unpacks the tarball (`.tgz` file) from the specified URL.\n *\n * @param tarballUrl - The tarball URL to fetch and unpack.\n * @returns A the files for the package tarball.\n * @throws If fetching the tarball fails.\n */\n async fetchNpmTarball(\n tarballUrl: URL,\n ): Promise<Map<string, VirtualFile<unknown>>> {\n // Perform a raw fetch because we want the Response object itself.\n const tarballResponse = await this.meta.fetch(tarballUrl.toString());\n if (!tarballResponse.ok || !tarballResponse.body) {\n throw new Error(\n `Failed to fetch tarball for package \"${this.meta.packageName}\".`,\n );\n }\n\n // We assume that NPM is a good actor and provides us with a valid `content-length` header.\n const tarballSizeString = tarballResponse.headers.get('content-length');\n assert(tarballSizeString, 'Snap tarball has invalid content-length');\n const tarballSize = parseInt(tarballSizeString, 10);\n assert(\n tarballSize <= TARBALL_SIZE_SAFETY_LIMIT,\n 'Snap tarball exceeds size limit',\n );\n return new Promise((resolve, reject) => {\n const files = new Map();\n\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 // To prevent recursion-based zip bombs, we should not allow recursion here.\n pipeline(\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n getNodeStream(tarballResponse.body!),\n createGunzip(),\n createTarballStream(\n getNpmCanonicalBasePath(this.meta.registry, this.meta.packageName),\n files,\n ),\n (error: unknown) => {\n error ? reject(error) : resolve(files);\n },\n );\n });\n }\n}\n\n// Incomplete type\nexport type PartialNpmMetadata = {\n versions: Record<string, { dist: { tarball: string } }>;\n};\n\n/**\n * Fetches the NPM metadata of the specified package from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param registryUrl - The URL of the npm registry to fetch the metadata from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns The NPM metadata object.\n * @throws If fetching the metadata fails.\n */\nexport async function fetchNpmMetadata(\n packageName: string,\n registryUrl: URL,\n fetchFunction: typeof fetch,\n): Promise<PartialNpmMetadata> {\n const packageResponse = await fetchFunction(\n new URL(packageName, registryUrl).toString(),\n {\n headers: {\n // Corgi format is slightly smaller: https://github.com/npm/pacote/blob/main/lib/registry.js#L71\n accept: isNPM(registryUrl)\n ? 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*'\n : 'application/json',\n },\n },\n );\n if (!packageResponse.ok) {\n throw new Error(\n `Failed to fetch NPM registry entry. Status code: ${packageResponse.status}.`,\n );\n }\n const packageMetadata = await packageResponse.json();\n\n if (!isObject(packageMetadata)) {\n throw new Error(\n `Failed to fetch package \"${packageName}\" metadata from npm.`,\n );\n }\n\n return packageMetadata as PartialNpmMetadata;\n}\n\n/**\n * Gets the canonical base path for an NPM snap.\n *\n * @param registryUrl - A registry URL.\n * @param packageName - A package name.\n * @returns The canonical base path.\n */\nexport function getNpmCanonicalBasePath(registryUrl: URL, packageName: string) {\n let canonicalBase = 'npm://';\n if (registryUrl.username !== '') {\n canonicalBase += registryUrl.username;\n if (registryUrl.password !== '') {\n canonicalBase += `:${registryUrl.password}`;\n }\n canonicalBase += '@';\n }\n return `${canonicalBase}${registryUrl.host}/${packageName}/`;\n}\n\n/**\n * Determine if a registry URL is NPM.\n *\n * @param registryUrl - A registry url.\n * @returns True if the registry is the NPM registry, otherwise false.\n */\nfunction isNPM(registryUrl: URL) {\n return registryUrl.toString() === DEFAULT_NPM_REGISTRY.toString();\n}\n\n/**\n * Resolves a version range to a version using the NPM registry.\n *\n * Unless the version range is already a version, then the NPM registry is skipped.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param versionRange - The version range of the package.\n * @param registryUrl - The URL of the npm registry to fetch the metadata from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns An object containing the resolved version and a URL for its tarball.\n * @throws If fetching the metadata fails.\n */\nasync function resolveNpmVersion(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl: URL,\n fetchFunction: typeof fetch,\n): Promise<{ tarballURL: string; targetVersion: SemVerVersion }> {\n // If the version range is already a static version we don't need to look for the metadata.\n if (isNPM(registryUrl) && isValidSemVerVersion(versionRange)) {\n return {\n tarballURL: getNpmTarballUrl(packageName, versionRange),\n targetVersion: versionRange,\n };\n }\n\n const packageMetadata = await fetchNpmMetadata(\n packageName,\n registryUrl,\n fetchFunction,\n );\n\n const versions = Object.keys(packageMetadata?.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 tarballURL = packageMetadata?.versions?.[targetVersion]?.dist?.tarball;\n\n return { tarballURL, 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 let totalSize = 0;\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({ encoding: 'uint8array' }, (data) => {\n try {\n totalSize += data.byteLength;\n // To prevent zip bombs, we set a safety limit for the total size of tarballs.\n assert(\n totalSize < TARBALL_SIZE_SAFETY_LIMIT,\n `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`,\n );\n const vfile = new VirtualFile({\n value: data,\n path,\n data: {\n canonicalPath: new URL(path, canonicalBase).toString(),\n },\n });\n // We disallow files having identical paths as it may confuse our checksum calculations.\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 } catch (error) {\n return extractStream.destroy(error);\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 return extractStream;\n}\n"],"names":["createSnapManifest","DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","isValidUrl","NpmSnapIdStruct","VirtualFile","normalizeRelative","parseJson","assert","assertIsSemVerVersion","assertStruct","isObject","isValidSemVerVersion","createGunzip","concat","getNpmTarballUrl","pipeline","ReadableWebToNodeStream","extract","tarExtract","DEFAULT_NPM_REGISTRY","URL","BaseNpmLocation","manifest","validatedManifest","clone","vfile","fetch","result","toString","path","relativePath","files","lazyInit","undefined","get","TypeError","packageName","meta","version","registry","versionRange","requestedRange","constructor","url","opts","allowCustomRegistries","fetchFunction","globalThis","bind","defaultResolve","range","resolveVersion","host","port","username","password","pathname","search","hash","startsWith","slice","resolvedVersion","tarballURL","targetVersion","resolveNpmVersion","endsWith","Error","newTarballUrl","hostname","protocol","fetchNpmTarball","TARBALL_SIZE_SAFETY_LIMIT","NpmLocation","tarballUrl","tarballResponse","ok","body","tarballSizeString","headers","tarballSize","parseInt","Promise","resolve","reject","Map","getNodeStream","createTarballStream","getNpmCanonicalBasePath","error","fetchNpmMetadata","registryUrl","packageResponse","accept","isNPM","status","packageMetadata","json","canonicalBase","versions","Object","keys","map","dist","tarball","NPM_TARBALL_PATH_PREFIX","stream","getReader","extractStream","totalSize","on","header","entryStream","next","name","headerName","type","headerType","replace","pipe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,8BAA8B,EAAEA,0BAA0B,OAAO,CAAC;oBAErE,MAAM9C,QAAQ,IAAIrB,YAAY;wBAC5BsH,OAAOF;wBACP3F;wBACA2F,MAAM;4BACJG,eAAe,IAAIvG,IAAIS,MAAMoE,eAAerE,QAAQ;wBACtD;oBACF;oBACA,wFAAwF;oBACxFrB,OACE,CAACwB,MAAM6F,GAAG,CAAC/F,OACX;oBAEFE,MAAM8F,GAAG,CAAChG,MAAMJ;oBAChB,OAAOuF;gBACT,EAAE,OAAOxB,OAAO;oBACd,OAAOmB,cAAcmB,OAAO,CAACtC;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7CuB,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYgB,MAAM;IAC3B;IACA,OAAOpB;AACT"}
1
+ {"version":3,"sources":["../../../../src/snaps/location/npm.ts"],"sourcesContent":["import type { SnapManifest } from '@metamask/snaps-utils';\nimport {\n createSnapManifest,\n DEFAULT_REQUESTED_SNAP_VERSION,\n getTargetVersion,\n isValidUrl,\n NpmSnapIdStruct,\n VirtualFile,\n normalizeRelative,\n parseJson,\n} from '@metamask/snaps-utils';\nimport type { SemVerRange, SemVerVersion } from '@metamask/utils';\nimport {\n assert,\n assertIsSemVerVersion,\n assertStruct,\n isObject,\n isValidSemVerVersion,\n} from '@metamask/utils';\nimport { createGunzip } from 'browserify-zlib';\nimport concat from 'concat-stream';\nimport getNpmTarballUrl from 'get-npm-tarball-url';\nimport { pipeline } from 'readable-stream';\nimport type { Readable, Writable } from 'readable-stream';\nimport { ReadableWebToNodeStream } from 'readable-web-to-node-stream';\nimport { extract as tarExtract } from 'tar-stream';\n\nimport type { DetectSnapLocationOptions, SnapLocation } from './location';\n\nexport const DEFAULT_NPM_REGISTRY = new URL('https://registry.npmjs.org');\n\ninterface NpmMeta {\n registry: URL;\n packageName: string;\n requestedRange: SemVerRange;\n version?: string;\n fetch: typeof fetch;\n resolveVersion: (range: SemVerRange) => Promise<SemVerRange>;\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\n// Base class for NPM implementation, useful for extending with custom NPM fetching logic\nexport abstract class BaseNpmLocation implements SnapLocation {\n protected readonly meta: NpmMeta;\n\n #validatedManifest?: VirtualFile<SnapManifest>;\n\n #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 const defaultResolve = async (range: SemVerRange) => range;\n const resolveVersion = opts.resolveVersion ?? defaultResolve;\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 = 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 resolveVersion,\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 = parseJson(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 resolvedVersion = await this.meta.resolveVersion(\n this.meta.requestedRange,\n );\n\n const { tarballURL, targetVersion } = await resolveNpmVersion(\n this.meta.packageName,\n resolvedVersion,\n this.meta.registry,\n this.meta.fetch,\n );\n\n if (!isValidUrl(tarballURL) || !tarballURL.toString().endsWith('.tgz')) {\n throw new Error(\n `Failed to find valid tarball URL in NPM metadata for package \"${this.meta.packageName}\".`,\n );\n }\n\n // Override the tarball hostname/protocol with registryUrl hostname/protocol\n const newTarballUrl = new URL(tarballURL);\n newTarballUrl.hostname = this.meta.registry.hostname;\n newTarballUrl.protocol = this.meta.registry.protocol;\n\n const files = await this.fetchNpmTarball(newTarballUrl);\n\n this.#files = files;\n this.meta.version = targetVersion;\n }\n\n /**\n * Fetches and unpacks the tarball (`.tgz` file) from the specified URL.\n *\n * @param tarballUrl - The tarball URL to fetch and unpack.\n * @returns A the files for the package tarball.\n * @throws If fetching the tarball fails.\n */\n abstract fetchNpmTarball(tarballUrl: URL): Promise<Map<string, VirtualFile>>;\n}\n\n// Safety limit for tarballs, 250 MB in bytes\nexport const TARBALL_SIZE_SAFETY_LIMIT = 262144000;\n\n// Main NPM implementation, contains a browser tarball fetching implementation.\nexport class NpmLocation extends BaseNpmLocation {\n /**\n * Fetches and unpacks the tarball (`.tgz` file) from the specified URL.\n *\n * @param tarballUrl - The tarball URL to fetch and unpack.\n * @returns A the files for the package tarball.\n * @throws If fetching the tarball fails.\n */\n async fetchNpmTarball(\n tarballUrl: URL,\n ): Promise<Map<string, VirtualFile<unknown>>> {\n // Perform a raw fetch because we want the Response object itself.\n const tarballResponse = await this.meta.fetch(tarballUrl.toString());\n if (!tarballResponse.ok || !tarballResponse.body) {\n throw new Error(\n `Failed to fetch tarball for package \"${this.meta.packageName}\".`,\n );\n }\n\n // We assume that NPM is a good actor and provides us with a valid `content-length` header.\n const tarballSizeString = tarballResponse.headers.get('content-length');\n assert(tarballSizeString, 'Snap tarball has invalid content-length');\n const tarballSize = parseInt(tarballSizeString, 10);\n assert(\n tarballSize <= TARBALL_SIZE_SAFETY_LIMIT,\n 'Snap tarball exceeds size limit',\n );\n return new Promise((resolve, reject) => {\n const files = new Map();\n\n const tarballStream = createTarballStream(\n getNpmCanonicalBasePath(this.meta.registry, this.meta.packageName),\n files,\n );\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const body = tarballResponse.body!;\n\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 // To prevent recursion-based zip bombs, we should not allow recursion here.\n\n // If native decompression stream is available we use that, otherwise fallback to zlib.\n if ('pipeThrough' in body && 'DecompressionStream' in globalThis) {\n const decompressionStream = new DecompressionStream('gzip');\n const decompressedStream = body.pipeThrough(decompressionStream);\n\n pipeline(\n getNodeStream(decompressedStream),\n tarballStream,\n (error: unknown) => {\n error ? reject(error) : resolve(files);\n },\n );\n return;\n }\n\n pipeline(\n getNodeStream(body),\n createGunzip(),\n tarballStream,\n (error: unknown) => {\n error ? reject(error) : resolve(files);\n },\n );\n });\n }\n}\n\n// Incomplete type\nexport type PartialNpmMetadata = {\n versions: Record<string, { dist: { tarball: string } }>;\n};\n\n/**\n * Fetches the NPM metadata of the specified package from\n * the public npm registry.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param registryUrl - The URL of the npm registry to fetch the metadata from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns The NPM metadata object.\n * @throws If fetching the metadata fails.\n */\nexport async function fetchNpmMetadata(\n packageName: string,\n registryUrl: URL,\n fetchFunction: typeof fetch,\n): Promise<PartialNpmMetadata> {\n const packageResponse = await fetchFunction(\n new URL(packageName, registryUrl).toString(),\n {\n headers: {\n // Corgi format is slightly smaller: https://github.com/npm/pacote/blob/main/lib/registry.js#L71\n accept: isNPM(registryUrl)\n ? 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*'\n : 'application/json',\n },\n },\n );\n if (!packageResponse.ok) {\n throw new Error(\n `Failed to fetch NPM registry entry. Status code: ${packageResponse.status}.`,\n );\n }\n const packageMetadata = await packageResponse.json();\n\n if (!isObject(packageMetadata)) {\n throw new Error(\n `Failed to fetch package \"${packageName}\" metadata from npm.`,\n );\n }\n\n return packageMetadata as PartialNpmMetadata;\n}\n\n/**\n * Gets the canonical base path for an NPM snap.\n *\n * @param registryUrl - A registry URL.\n * @param packageName - A package name.\n * @returns The canonical base path.\n */\nexport function getNpmCanonicalBasePath(registryUrl: URL, packageName: string) {\n let canonicalBase = 'npm://';\n if (registryUrl.username !== '') {\n canonicalBase += registryUrl.username;\n if (registryUrl.password !== '') {\n canonicalBase += `:${registryUrl.password}`;\n }\n canonicalBase += '@';\n }\n return `${canonicalBase}${registryUrl.host}/${packageName}/`;\n}\n\n/**\n * Determine if a registry URL is NPM.\n *\n * @param registryUrl - A registry url.\n * @returns True if the registry is the NPM registry, otherwise false.\n */\nfunction isNPM(registryUrl: URL) {\n return registryUrl.toString() === DEFAULT_NPM_REGISTRY.toString();\n}\n\n/**\n * Resolves a version range to a version using the NPM registry.\n *\n * Unless the version range is already a version, then the NPM registry is skipped.\n *\n * @param packageName - The name of the package whose metadata to fetch.\n * @param versionRange - The version range of the package.\n * @param registryUrl - The URL of the npm registry to fetch the metadata from.\n * @param fetchFunction - The fetch function to use. Defaults to the global\n * {@link fetch}. Useful for Node.js compatibility.\n * @returns An object containing the resolved version and a URL for its tarball.\n * @throws If fetching the metadata fails.\n */\nasync function resolveNpmVersion(\n packageName: string,\n versionRange: SemVerRange,\n registryUrl: URL,\n fetchFunction: typeof fetch,\n): Promise<{ tarballURL: string; targetVersion: SemVerVersion }> {\n // If the version range is already a static version we don't need to look for the metadata.\n if (isNPM(registryUrl) && isValidSemVerVersion(versionRange)) {\n return {\n tarballURL: getNpmTarballUrl(packageName, versionRange),\n targetVersion: versionRange,\n };\n }\n\n const packageMetadata = await fetchNpmMetadata(\n packageName,\n registryUrl,\n fetchFunction,\n );\n\n const versions = Object.keys(packageMetadata?.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 tarballURL = packageMetadata?.versions?.[targetVersion]?.dist?.tarball;\n\n return { tarballURL, 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 let totalSize = 0;\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({ encoding: 'uint8array' }, (data) => {\n try {\n totalSize += data.byteLength;\n // To prevent zip bombs, we set a safety limit for the total size of tarballs.\n assert(\n totalSize < TARBALL_SIZE_SAFETY_LIMIT,\n `Snap tarball exceeds limit of ${TARBALL_SIZE_SAFETY_LIMIT} bytes.`,\n );\n const vfile = new VirtualFile({\n value: data,\n path,\n data: {\n canonicalPath: new URL(path, canonicalBase).toString(),\n },\n });\n // We disallow files having identical paths as it may confuse our checksum calculations.\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 } catch (error) {\n return extractStream.destroy(error);\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 return extractStream;\n}\n"],"names":["createSnapManifest","DEFAULT_REQUESTED_SNAP_VERSION","getTargetVersion","isValidUrl","NpmSnapIdStruct","VirtualFile","normalizeRelative","parseJson","assert","assertIsSemVerVersion","assertStruct","isObject","isValidSemVerVersion","createGunzip","concat","getNpmTarballUrl","pipeline","ReadableWebToNodeStream","extract","tarExtract","DEFAULT_NPM_REGISTRY","URL","BaseNpmLocation","manifest","validatedManifest","clone","vfile","fetch","result","toString","path","relativePath","files","lazyInit","undefined","get","TypeError","packageName","meta","version","registry","versionRange","requestedRange","constructor","url","opts","allowCustomRegistries","fetchFunction","globalThis","bind","defaultResolve","range","resolveVersion","host","port","username","password","pathname","search","hash","startsWith","slice","resolvedVersion","tarballURL","targetVersion","resolveNpmVersion","endsWith","Error","newTarballUrl","hostname","protocol","fetchNpmTarball","TARBALL_SIZE_SAFETY_LIMIT","NpmLocation","tarballUrl","tarballResponse","ok","body","tarballSizeString","headers","tarballSize","parseInt","Promise","resolve","reject","Map","tarballStream","createTarballStream","getNpmCanonicalBasePath","decompressionStream","DecompressionStream","decompressedStream","pipeThrough","getNodeStream","error","fetchNpmMetadata","registryUrl","packageResponse","accept","isNPM","status","packageMetadata","json","canonicalBase","versions","Object","keys","map","dist","tarball","NPM_TARBALL_PATH_PREFIX","stream","getReader","extractStream","totalSize","on","header","entryStream","next","name","headerName","type","headerType","replace","pipe","encoding","data","byteLength","value","canonicalPath","has","set","destroy","resume"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SACEA,kBAAkB,EAClBC,8BAA8B,EAC9BC,gBAAgB,EAChBC,UAAU,EACVC,eAAe,EACfC,WAAW,EACXC,iBAAiB,EACjBC,SAAS,QACJ,wBAAwB;AAE/B,SACEC,MAAM,EACNC,qBAAqB,EACrBC,YAAY,EACZC,QAAQ,EACRC,oBAAoB,QACf,kBAAkB;AACzB,SAASC,YAAY,QAAQ,kBAAkB;AAC/C,OAAOC,YAAY,gBAAgB;AACnC,OAAOC,sBAAsB,sBAAsB;AAC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AAIS,MAAMyE,eAAe1E,QAAQ;wBACtD;oBACF;oBACA,wFAAwF;oBACxFrB,OACE,CAACwB,MAAMkG,GAAG,CAACpG,OACX;oBAEFE,MAAMmG,GAAG,CAACrG,MAAMJ;oBAChB,OAAO4F;gBACT,EAAE,OAAOxB,OAAO;oBACd,OAAOmB,cAAcmB,OAAO,CAACtC;gBAC/B;YACF;QAEJ;QAEA,4EAA4E;QAC5E,0EAA0E;QAC1E,6CAA6C;QAC7CuB,YAAYF,EAAE,CAAC,OAAO,IAAMG;QAC5B,OAAOD,YAAYgB,MAAM;IAC3B;IACA,OAAOpB;AACT"}
package/dist/esm/utils.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { getErrorMessage } from '@metamask/snaps-sdk';
2
+ import { encodeBase64, getValidatedLocalizationFiles, validateFetchedSnap } from '@metamask/snaps-utils';
1
3
  import { Timer } from './snaps/Timer';
2
4
  /**
3
5
  * Takes two objects and does a Set Difference of them.
@@ -91,5 +93,40 @@ import { Timer } from './snaps/Timer';
91
93
  }
92
94
  return await Promise.all(files.map(async (filePath)=>location.fetch(filePath)));
93
95
  }
96
+ /**
97
+ * Fetch the Snap manifest, source code, and any other files from the given
98
+ * location.
99
+ *
100
+ * @param snapId - The ID of the Snap to fetch.
101
+ * @param location - The location of the Snap.
102
+ * @returns The Snap files and location.
103
+ * @throws If the Snap files are invalid, or if the Snap could not be fetched.
104
+ */ export async function fetchSnap(snapId, location) {
105
+ try {
106
+ const manifest = await location.manifest();
107
+ const sourceCode = await location.fetch(manifest.result.source.location.npm.filePath);
108
+ const { iconPath } = manifest.result.source.location.npm;
109
+ const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;
110
+ const auxiliaryFiles = await getSnapFiles(location, manifest.result.source.files);
111
+ await Promise.all(auxiliaryFiles.map(async (file)=>{
112
+ // This should still be safe
113
+ // eslint-disable-next-line require-atomic-updates
114
+ file.data.base64 = await encodeBase64(file);
115
+ }));
116
+ const localizationFiles = await getSnapFiles(location, manifest.result.source.locales);
117
+ const validatedLocalizationFiles = getValidatedLocalizationFiles(localizationFiles);
118
+ const files = {
119
+ manifest,
120
+ sourceCode,
121
+ svgIcon,
122
+ auxiliaryFiles,
123
+ localizationFiles: validatedLocalizationFiles
124
+ };
125
+ await validateFetchedSnap(files);
126
+ return files;
127
+ } catch (error) {
128
+ throw new Error(`Failed to fetch snap "${snapId}": ${getErrorMessage(error)}.`);
129
+ }
130
+ }
94
131
 
95
132
  //# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type { SnapLocation } from './snaps';\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 its 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<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> 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<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\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<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\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<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n"],"names":["Timer","setDiff","objectA","objectB","Object","entries","reduce","acc","key","value","delay","ms","result","delayWithTimer","timer","rejectFunc","promise","Promise","resolve","reject","start","undefined","cancel","status","Error","hasTimedOut","Symbol","withTimeout","timerOrMs","delayPromise","race","getSnapFiles","location","files","length","all","map","filePath","fetch"],"mappings":"AACA,SAASA,KAAK,QAAQ,gBAAgB;AAEtC;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,QAGdC,OAAgB,EAAEC,OAAgB;IAClC,OAAOC,OAAOC,OAAO,CAACH,SAASI,MAAM,CACnC,CAACC,KAAK,CAACC,KAAKC,MAAM;QAChB,IAAI,CAAED,CAAAA,OAAOL,OAAM,GAAI;YACrBI,GAAG,CAACC,IAAI,GAAGC;QACb;QACA,OAAOF;IACT,GACA,CAAC;AAEL;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,MACdC,EAAU,EACVC,MAAe;IAEf,OAAOC,eAAe,IAAIb,MAAMW,KAAKC;AACvC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,eACdC,KAAY,EACZF,MAAe;IAEf,IAAIG;IACJ,MAAMC,UAAe,IAAIC,QAAgB,CAACC,SAAcC;QACtDL,MAAMM,KAAK,CAAC;YACVR,WAAWS,YAAYH,YAAYA,QAAQN;QAC7C;QACAG,aAAaI;IACf;IAEAH,QAAQM,MAAM,GAAG;QACf,IAAIR,MAAMS,MAAM,KAAK,YAAY;YAC/BT,MAAMQ,MAAM;YACZP,WAAW,IAAIS,MAAM;QACvB;IACF;IACA,OAAOR;AACT;AAEA;;;CAGC,GACD,OAAO,MAAMS,cAAcC,OACzB,wEACA;AAEF;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,YACpBX,OAA8B,EAC9BY,SAAyB;IAEzB,MAAMd,QACJ,OAAOc,cAAc,WAAW,IAAI5B,MAAM4B,aAAaA;IACzD,MAAMC,eAAehB,eAAeC,OAAOW;IAC3C,IAAI;QACF,OAAO,MAAMR,QAAQa,IAAI,CAAC;YAACd;YAASa;SAAa;IACnD,SAAU;QACRA,aAAaP,MAAM;IACrB;AACF;AA+FA;;;;;;CAMC,GACD,OAAO,eAAeS,aACpBC,QAAsB,EACtBC,KAA4B;IAE5B,IAAI,CAACA,SAASA,MAAMC,MAAM,KAAK,GAAG;QAChC,OAAO,EAAE;IACX;IAEA,OAAO,MAAMjB,QAAQkB,GAAG,CACtBF,MAAMG,GAAG,CAAC,OAAOC,WAAaL,SAASM,KAAK,CAACD;AAEjD"}
1
+ {"version":3,"sources":["../../src/utils.ts"],"sourcesContent":["import type { SnapId } from '@metamask/snaps-sdk';\nimport { getErrorMessage } from '@metamask/snaps-sdk';\nimport {\n encodeBase64,\n getValidatedLocalizationFiles,\n validateFetchedSnap,\n} from '@metamask/snaps-utils';\n\nimport type { SnapLocation } from './snaps';\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 its 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<Type> = Type extends string | number | boolean | symbol\n ? Extract<string | number | boolean | symbol, Type> 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<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends true ? Key : never;\n }[keyof Type]\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<Type> = NonNullable<\n {\n [Key in keyof Type]: IsLiteral<Key> extends false ? Key : never;\n }[keyof Type]\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<First, Second> = Omit<First, LiteralKeys<Second>> &\n Partial<Pick<First, Extract<keyof First, NonLiteralKeys<Second>>>>;\n\n/**\n * Makes every specified property of the specified object type mutable.\n *\n * @template Type - The object whose readonly properties to make mutable.\n * @template TargetKey - The property key(s) to make mutable.\n */\nexport type Mutable<\n Type extends Record<string, unknown>,\n TargetKey extends string,\n> = {\n -readonly [Key in keyof Pick<Type, TargetKey>]: Type[Key];\n} & {\n [Key in keyof Omit<Type, TargetKey>]: Type[Key];\n};\n\n/**\n * Get all files in a Snap from an array of file paths.\n *\n * @param location - The location of the Snap.\n * @param files - The array of file paths.\n * @returns The array of files as {@link VirtualFile}s.\n */\nexport async function getSnapFiles(\n location: SnapLocation,\n files?: string[] | undefined,\n) {\n if (!files || files.length === 0) {\n return [];\n }\n\n return await Promise.all(\n files.map(async (filePath) => location.fetch(filePath)),\n );\n}\n\n/**\n * Fetch the Snap manifest, source code, and any other files from the given\n * location.\n *\n * @param snapId - The ID of the Snap to fetch.\n * @param location - The location of the Snap.\n * @returns The Snap files and location.\n * @throws If the Snap files are invalid, or if the Snap could not be fetched.\n */\nexport async function fetchSnap(snapId: SnapId, location: SnapLocation) {\n try {\n const manifest = await location.manifest();\n const sourceCode = await location.fetch(\n manifest.result.source.location.npm.filePath,\n );\n const { iconPath } = manifest.result.source.location.npm;\n const svgIcon = iconPath ? await location.fetch(iconPath) : undefined;\n\n const auxiliaryFiles = await getSnapFiles(\n location,\n manifest.result.source.files,\n );\n\n await Promise.all(\n auxiliaryFiles.map(async (file) => {\n // This should still be safe\n // eslint-disable-next-line require-atomic-updates\n file.data.base64 = await encodeBase64(file);\n }),\n );\n\n const localizationFiles = await getSnapFiles(\n location,\n manifest.result.source.locales,\n );\n\n const validatedLocalizationFiles =\n getValidatedLocalizationFiles(localizationFiles);\n\n const files = {\n manifest,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles: validatedLocalizationFiles,\n };\n\n await validateFetchedSnap(files);\n\n return files;\n } catch (error) {\n throw new Error(\n `Failed to fetch snap \"${snapId}\": ${getErrorMessage(error)}.`,\n );\n }\n}\n"],"names":["getErrorMessage","encodeBase64","getValidatedLocalizationFiles","validateFetchedSnap","Timer","setDiff","objectA","objectB","Object","entries","reduce","acc","key","value","delay","ms","result","delayWithTimer","timer","rejectFunc","promise","Promise","resolve","reject","start","undefined","cancel","status","Error","hasTimedOut","Symbol","withTimeout","timerOrMs","delayPromise","race","getSnapFiles","location","files","length","all","map","filePath","fetch","fetchSnap","snapId","manifest","sourceCode","source","npm","iconPath","svgIcon","auxiliaryFiles","file","data","base64","localizationFiles","locales","validatedLocalizationFiles","error"],"mappings":"AACA,SAASA,eAAe,QAAQ,sBAAsB;AACtD,SACEC,YAAY,EACZC,6BAA6B,EAC7BC,mBAAmB,QACd,wBAAwB;AAG/B,SAASC,KAAK,QAAQ,gBAAgB;AAEtC;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,QAGdC,OAAgB,EAAEC,OAAgB;IAClC,OAAOC,OAAOC,OAAO,CAACH,SAASI,MAAM,CACnC,CAACC,KAAK,CAACC,KAAKC,MAAM;QAChB,IAAI,CAAED,CAAAA,OAAOL,OAAM,GAAI;YACrBI,GAAG,CAACC,IAAI,GAAGC;QACb;QACA,OAAOF;IACT,GACA,CAAC;AAEL;AAEA;;;;;;;CAOC,GACD,OAAO,SAASG,MACdC,EAAU,EACVC,MAAe;IAEf,OAAOC,eAAe,IAAIb,MAAMW,KAAKC;AACvC;AAEA;;;;;;;CAOC,GACD,OAAO,SAASC,eACdC,KAAY,EACZF,MAAe;IAEf,IAAIG;IACJ,MAAMC,UAAe,IAAIC,QAAgB,CAACC,SAAcC;QACtDL,MAAMM,KAAK,CAAC;YACVR,WAAWS,YAAYH,YAAYA,QAAQN;QAC7C;QACAG,aAAaI;IACf;I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,CAAC,OAAOY;YACxB,4BAA4B;YAC5B,kDAAkD;YAClDA,KAAKC,IAAI,CAACC,MAAM,GAAG,MAAMrD,aAAamD;QACxC;QAGF,MAAMG,oBAAoB,MAAMpB,aAC9BC,UACAS,SAAS7B,MAAM,CAAC+B,MAAM,CAACS,OAAO;QAGhC,MAAMC,6BACJvD,8BAA8BqD;QAEhC,MAAMlB,QAAQ;YACZQ;YACAC;YACAI;YACAC;YACAI,mBAAmBE;QACrB;QAEA,MAAMtD,oBAAoBkC;QAE1B,OAAOA;IACT,EAAE,OAAOqB,OAAO;QACd,MAAM,IAAI9B,MACR,CAAC,sBAAsB,EAAEgB,OAAO,GAAG,EAAE5C,gBAAgB0D,OAAO,CAAC,CAAC;IAElE;AACF"}
@@ -3,3 +3,4 @@ export * from './services';
3
3
  export * from './snaps';
4
4
  export * from './utils';
5
5
  export * from './cronjob';
6
+ export * from './interface';
@@ -0,0 +1,85 @@
1
+ import type { RestrictedControllerMessenger } from '@metamask/base-controller';
2
+ import { BaseController } from '@metamask/base-controller';
3
+ import type { MaybeUpdateState, TestOrigin } from '@metamask/phishing-controller';
4
+ import type { Component, InterfaceState, SnapId } from '@metamask/snaps-sdk';
5
+ declare const controllerName = "SnapInterfaceController";
6
+ export declare type CreateInterface = {
7
+ type: `${typeof controllerName}:createInterface`;
8
+ handler: SnapInterfaceController['createInterface'];
9
+ };
10
+ export declare type GetInterface = {
11
+ type: `${typeof controllerName}:getInterface`;
12
+ handler: SnapInterfaceController['getInterface'];
13
+ };
14
+ export declare type UpdateInterface = {
15
+ type: `${typeof controllerName}:updateInterface`;
16
+ handler: SnapInterfaceController['updateInterface'];
17
+ };
18
+ export declare type DeleteInterface = {
19
+ type: `${typeof controllerName}:deleteInterface`;
20
+ handler: SnapInterfaceController['deleteInterface'];
21
+ };
22
+ export declare type UpdateInterfaceState = {
23
+ type: `${typeof controllerName}:updateInterfaceState`;
24
+ handler: SnapInterfaceController['updateInterfaceState'];
25
+ };
26
+ export declare type SnapInterfaceControllerAllowedActions = TestOrigin | MaybeUpdateState;
27
+ export declare type SnapInterfaceControllerActions = CreateInterface | GetInterface | UpdateInterface | DeleteInterface | UpdateInterfaceState;
28
+ export declare type SnapInterfaceControllerMessenger = RestrictedControllerMessenger<typeof controllerName, SnapInterfaceControllerActions | SnapInterfaceControllerAllowedActions, never, SnapInterfaceControllerAllowedActions['type'], never>;
29
+ export declare type StoredInterface = {
30
+ snapId: SnapId;
31
+ content: Component;
32
+ state: InterfaceState;
33
+ };
34
+ export declare type SnapInterfaceControllerState = {
35
+ interfaces: Record<string, StoredInterface>;
36
+ };
37
+ export declare type SnapInterfaceControllerArgs = {
38
+ messenger: SnapInterfaceControllerMessenger;
39
+ state?: SnapInterfaceControllerState;
40
+ };
41
+ /**
42
+ * Use this controller to manage snaps UI interfaces using RPC method hooks.
43
+ */
44
+ export declare class SnapInterfaceController extends BaseController<typeof controllerName, SnapInterfaceControllerState, SnapInterfaceControllerMessenger> {
45
+ #private;
46
+ constructor({ messenger, state }: SnapInterfaceControllerArgs);
47
+ /**
48
+ * Create an interface in the controller state with the associated data.
49
+ *
50
+ * @param snapId - The snap id that created the interface.
51
+ * @param content - The interface content.
52
+ * @returns The newly interface id.
53
+ */
54
+ createInterface(snapId: SnapId, content: Component): Promise<string>;
55
+ /**
56
+ * Get the data of a given interface id.
57
+ *
58
+ * @param snapId - The snap id requesting the interface data.
59
+ * @param id - The interface id.
60
+ * @returns The interface state.
61
+ */
62
+ getInterface(snapId: SnapId, id: string): StoredInterface;
63
+ /**
64
+ * Update the interface with the given content.
65
+ *
66
+ * @param snapId - The snap id requesting the update.
67
+ * @param id - The interface id.
68
+ * @param content - The new content.
69
+ */
70
+ updateInterface(snapId: SnapId, id: string, content: Component): Promise<void>;
71
+ /**
72
+ * Delete an interface from state.
73
+ *
74
+ * @param id - The interface id.
75
+ */
76
+ deleteInterface(id: string): void;
77
+ /**
78
+ * Update the interface state.
79
+ *
80
+ * @param id - The interface id.
81
+ * @param state - The new state.
82
+ */
83
+ updateInterfaceState(id: string, state: InterfaceState): void;
84
+ }
85
+ export {};
@@ -0,0 +1 @@
1
+ export * from './SnapInterfaceController';
@@ -0,0 +1,36 @@
1
+ import type { Component, Input, InterfaceState } from '@metamask/snaps-sdk';
2
+ /**
3
+ * Construct the state for a stray input (not enclosed in a form).
4
+ *
5
+ * @param state - The interface state.
6
+ * @param component - The Input component.
7
+ * @returns The input state.
8
+ */
9
+ export declare const constructInputState: (state: InterfaceState, component: Input) => string | Record<string, string | null> | null;
10
+ /**
11
+ * Construct the state for a form input.
12
+ *
13
+ * Sets the state to either the specified component value, the previous value from the old state or null.
14
+ *
15
+ * @param state - The interface state.
16
+ * @param component - The Input component.
17
+ * @param form - The parent form name of the input.
18
+ * @returns The input state.
19
+ */
20
+ export declare const constructFormInputState: (state: InterfaceState, component: Input, form: string) => string | null;
21
+ /**
22
+ * Assert that the component name is unique in state.
23
+ *
24
+ * @param state - The interface state to verify against.
25
+ * @param name - The component name to verify.
26
+ */
27
+ export declare const assertNameIsUnique: (state: InterfaceState, name: string) => void;
28
+ /**
29
+ * Construct the interface state for a given component tree while preserving values for matching stateful components in the old state.
30
+ *
31
+ * @param oldState - The previous state.
32
+ * @param component - The UI component to construct state from.
33
+ * @param newState - The state that is being constructed.
34
+ * @returns The interface state of the passed component.
35
+ */
36
+ export declare const constructState: (oldState: InterfaceState, component: Component, newState?: InterfaceState) => InterfaceState;
@@ -22,9 +22,8 @@ export declare class ProxyPostMessageStream extends BasePostMessageStream {
22
22
  * @param args - The constructor arguments.
23
23
  * @param args.stream - The underlying stream to use for communication.
24
24
  * @param args.jobId - The ID of the job this stream is associated with.
25
- * @param args.extra - Extra data to include in the post message.
26
25
  */
27
- constructor({ stream, jobId, extra }: ProxyPostMessageStreamArgs);
26
+ constructor({ stream, jobId }: ProxyPostMessageStreamArgs);
28
27
  /**
29
28
  * Write data to the underlying stream. This wraps the data in an object with
30
29
  * the job ID.
@@ -3,4 +3,5 @@ export * from './ExecutionService';
3
3
  export * from './ProxyPostMessageStream';
4
4
  export * from './iframe';
5
5
  export * from './offscreen';
6
+ export * from './webview';
6
7
  export { WebWorkerExecutionService } from './webworker';
@@ -4,4 +4,5 @@ export * from './ProxyPostMessageStream';
4
4
  export * from './iframe';
5
5
  export * from './node';
6
6
  export * from './offscreen';
7
+ export * from './webview';
7
8
  export { WebWorkerExecutionService } from './webworker';
@@ -1,14 +1,11 @@
1
- import type { ExecutionServiceArgs, Job } from '../AbstractExecutionService';
2
- import { AbstractExecutionService } from '../AbstractExecutionService';
3
- import { ProxyPostMessageStream } from '../ProxyPostMessageStream';
1
+ import type { ExecutionServiceArgs } from '../AbstractExecutionService';
2
+ import { ProxyExecutionService } from '../proxy/ProxyExecutionService';
4
3
  declare type OffscreenExecutionEnvironmentServiceArgs = {
5
4
  documentUrl: URL;
6
- frameUrl: URL;
7
5
  } & ExecutionServiceArgs;
8
- export declare class OffscreenExecutionService extends AbstractExecutionService<string> {
6
+ export declare class OffscreenExecutionService extends ProxyExecutionService {
9
7
  #private;
10
8
  readonly documentUrl: URL;
11
- readonly frameUrl: URL;
12
9
  /**
13
10
  * Create a new offscreen execution service.
14
11
  *
@@ -16,20 +13,12 @@ export declare class OffscreenExecutionService extends AbstractExecutionService<
16
13
  * @param args.documentUrl - The URL of the offscreen document to use as the
17
14
  * execution environment. This must be a URL relative to the location where
18
15
  * this is called. This cannot be a public (http(s)) URL.
19
- * @param args.frameUrl - The URL of the iframe to load inside the offscreen
20
- * document.
21
16
  * @param args.messenger - The messenger to use for communication with the
22
17
  * `SnapController`.
23
18
  * @param args.setupSnapProvider - The function to use to set up the snap
24
19
  * provider.
25
20
  */
26
- constructor({ documentUrl, frameUrl, messenger, setupSnapProvider, }: OffscreenExecutionEnvironmentServiceArgs);
27
- /**
28
- * Send a termination command to the offscreen document.
29
- *
30
- * @param job - The job to terminate.
31
- */
32
- protected terminateJob(job: Job<string>): Promise<void>;
21
+ constructor({ documentUrl, messenger, setupSnapProvider, }: OffscreenExecutionEnvironmentServiceArgs);
33
22
  /**
34
23
  * Create a new stream for the specified job. This wraps the runtime stream
35
24
  * in a stream specific to the job.
@@ -38,13 +27,7 @@ export declare class OffscreenExecutionService extends AbstractExecutionService<
38
27
  */
39
28
  protected initEnvStream(jobId: string): Promise<{
40
29
  worker: string;
41
- stream: ProxyPostMessageStream;
30
+ stream: import("..").ProxyPostMessageStream;
42
31
  }>;
43
- /**
44
- * Creates the offscreen document to be used as the execution environment.
45
- *
46
- * If the document already exists, this does nothing.
47
- */
48
- private createDocument;
49
32
  }
50
33
  export {};
@@ -0,0 +1,39 @@
1
+ import type { BasePostMessageStream } from '@metamask/post-message-stream';
2
+ import type { ExecutionServiceArgs, Job } from '../AbstractExecutionService';
3
+ import { AbstractExecutionService } from '../AbstractExecutionService';
4
+ import { ProxyPostMessageStream } from '../ProxyPostMessageStream';
5
+ declare type ProxyExecutionEnvironmentServiceArgs = {
6
+ stream: BasePostMessageStream;
7
+ } & ExecutionServiceArgs;
8
+ export declare class ProxyExecutionService extends AbstractExecutionService<string> {
9
+ #private;
10
+ /**
11
+ * Create a new proxy execution service.
12
+ *
13
+ * @param args - The constructor arguments.
14
+ * @param args.messenger - The messenger to use for communication with the
15
+ * `SnapController`.
16
+ * @param args.setupSnapProvider - The function to use to set up the snap
17
+ * provider.
18
+ * @param args.stream - The stream to use for communicating with the proxy
19
+ * executor.
20
+ */
21
+ constructor({ stream, messenger, setupSnapProvider, }: ProxyExecutionEnvironmentServiceArgs);
22
+ /**
23
+ * Send a termination command to the proxy stream.
24
+ *
25
+ * @param job - The job to terminate.
26
+ */
27
+ protected terminateJob(job: Job<string>): Promise<void>;
28
+ /**
29
+ * Create a new stream for the specified job. This wraps the root stream
30
+ * in a stream specific to the job.
31
+ *
32
+ * @param jobId - The job ID.
33
+ */
34
+ protected initEnvStream(jobId: string): Promise<{
35
+ worker: string;
36
+ stream: ProxyPostMessageStream;
37
+ }>;
38
+ }
39
+ export {};
@@ -0,0 +1,20 @@
1
+ import type { ExecutionServiceArgs } from '../AbstractExecutionService';
2
+ import { ProxyExecutionService } from '../proxy/ProxyExecutionService';
3
+ import type { WebViewInterface } from './WebViewMessageStream';
4
+ export declare type WebViewExecutionServiceArgs = ExecutionServiceArgs & {
5
+ getWebView: () => Promise<WebViewInterface>;
6
+ };
7
+ export declare class WebViewExecutionService extends ProxyExecutionService {
8
+ #private;
9
+ constructor({ messenger, setupSnapProvider, getWebView, }: WebViewExecutionServiceArgs);
10
+ /**
11
+ * Create a new stream for the specified job. This wraps the runtime stream
12
+ * in a stream specific to the job.
13
+ *
14
+ * @param jobId - The job ID.
15
+ */
16
+ protected initEnvStream(jobId: string): Promise<{
17
+ worker: string;
18
+ stream: import("..").ProxyPostMessageStream;
19
+ }>;
20
+ }
@@ -0,0 +1,32 @@
1
+ import type { PostMessageEvent } from '@metamask/post-message-stream';
2
+ import { BasePostMessageStream } from '@metamask/post-message-stream';
3
+ export declare type WebViewInterface = {
4
+ injectJavaScript(js: string): void;
5
+ registerMessageListener(listener: (event: PostMessageEvent) => void): void;
6
+ unregisterMessageListener(listener: (event: PostMessageEvent) => void): void;
7
+ };
8
+ declare type WebViewStreamArgs = {
9
+ name: string;
10
+ target: string;
11
+ getWebView: () => Promise<WebViewInterface>;
12
+ };
13
+ /**
14
+ * A special postMessage stream used to interface with a WebView.
15
+ */
16
+ export declare class WebViewMessageStream extends BasePostMessageStream {
17
+ #private;
18
+ /**
19
+ * Creates a stream for communicating with other streams inside a WebView.
20
+ *
21
+ * @param args - Options bag.
22
+ * @param args.name - The name of the stream. Used to differentiate between
23
+ * multiple streams sharing the same window object.
24
+ * @param args.target - The name of the stream to exchange messages with.
25
+ * @param args.getWebView - A asynchronous getter for the webview.
26
+ */
27
+ constructor({ name, target, getWebView }: WebViewStreamArgs);
28
+ protected _postMessage(data: unknown): void;
29
+ private _onMessage;
30
+ _destroy(): void;
31
+ }
32
+ export {};
@@ -0,0 +1 @@
1
+ export * from './WebViewExecutionService';