@metamask/snaps-utils 4.0.1 → 5.0.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +18 -1
  2. package/dist/cjs/auxiliary-files.js +3 -3
  3. package/dist/cjs/auxiliary-files.js.map +1 -1
  4. package/dist/cjs/base64.js +44 -0
  5. package/dist/cjs/base64.js.map +1 -0
  6. package/dist/cjs/bytes.js +23 -0
  7. package/dist/cjs/bytes.js.map +1 -0
  8. package/dist/cjs/checksum.js +2 -14
  9. package/dist/cjs/checksum.js.map +1 -1
  10. package/dist/cjs/cronjob.js +6 -7
  11. package/dist/cjs/cronjob.js.map +1 -1
  12. package/dist/cjs/index.browser.js +2 -1
  13. package/dist/cjs/index.browser.js.map +1 -1
  14. package/dist/cjs/index.js +2 -1
  15. package/dist/cjs/index.js.map +1 -1
  16. package/dist/cjs/manifest/manifest.js +4 -3
  17. package/dist/cjs/manifest/manifest.js.map +1 -1
  18. package/dist/cjs/structs.js +0 -22
  19. package/dist/cjs/structs.js.map +1 -1
  20. package/dist/cjs/virtual-file/VirtualFile.js +1 -0
  21. package/dist/cjs/virtual-file/VirtualFile.js.map +1 -1
  22. package/dist/esm/auxiliary-files.js +3 -3
  23. package/dist/esm/auxiliary-files.js.map +1 -1
  24. package/dist/esm/base64.js +36 -0
  25. package/dist/esm/base64.js.map +1 -0
  26. package/dist/esm/bytes.js +18 -0
  27. package/dist/esm/bytes.js.map +1 -0
  28. package/dist/esm/checksum.js +3 -17
  29. package/dist/esm/checksum.js.map +1 -1
  30. package/dist/esm/cronjob.js +8 -9
  31. package/dist/esm/cronjob.js.map +1 -1
  32. package/dist/esm/index.browser.js +2 -1
  33. package/dist/esm/index.browser.js.map +1 -1
  34. package/dist/esm/index.js +2 -1
  35. package/dist/esm/index.js.map +1 -1
  36. package/dist/esm/manifest/manifest.js +5 -3
  37. package/dist/esm/manifest/manifest.js.map +1 -1
  38. package/dist/esm/structs.js +1 -48
  39. package/dist/esm/structs.js.map +1 -1
  40. package/dist/esm/virtual-file/VirtualFile.js +1 -0
  41. package/dist/esm/virtual-file/VirtualFile.js.map +1 -1
  42. package/dist/types/auxiliary-files.d.ts +1 -1
  43. package/dist/types/base64.d.ts +15 -0
  44. package/dist/types/bytes.d.ts +8 -0
  45. package/dist/types/checksum.d.ts +1 -8
  46. package/dist/types/cronjob.d.ts +15 -15
  47. package/dist/types/handlers.d.ts +72 -0
  48. package/dist/types/index.browser.d.ts +2 -1
  49. package/dist/types/index.d.ts +2 -1
  50. package/dist/types/localization.d.ts +1 -1
  51. package/dist/types/manifest/manifest.d.ts +3 -1
  52. package/dist/types/manifest/validation.d.ts +17 -17
  53. package/dist/types/structs.d.ts +2 -40
  54. package/package.json +6 -6
  55. package/dist/cjs/enum.js +0 -16
  56. package/dist/cjs/enum.js.map +0 -1
  57. package/dist/esm/enum.js +0 -12
  58. package/dist/esm/enum.js.map +0 -1
  59. package/dist/types/enum.d.ts +0 -10
package/CHANGELOG.md CHANGED
@@ -6,6 +6,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [5.0.1]
10
+ ### Changed
11
+ - Improve base64 encoding/decoding speeds ([#1985](https://github.com/MetaMask/snaps/pull/1985))
12
+ - Bump several MetaMask dependencies ([#1989](https://github.com/MetaMask/snaps/pull/1989), [#1993](https://github.com/MetaMask/snaps/pull/1993))
13
+
14
+ ## [5.0.0]
15
+ ### Changed
16
+ - Bump several MetaMask dependencies ([#1964](https://github.com/MetaMask/snaps/pull/1964))
17
+
18
+ ### Removed
19
+ - **BREAKING:** Move `enumValue`, `literal` and `union` to `snaps-sdk` ([#1968](https://github.com/MetaMask/snaps/pull/1968))
20
+
21
+ ### Fixed
22
+ - Fix issues generating checksum with binary auxiliary files ([#1975](https://github.com/MetaMask/snaps/pull/1975))
23
+
9
24
  ## [4.0.1]
10
25
  ### Fixed
11
26
  - Change `validateTextLinks` to only get URL in markdown links ([#1914](https://github.com/MetaMask/snaps/pull/1914))
@@ -107,7 +122,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
107
122
  - The version of the package no longer needs to match the version of all other
108
123
  MetaMask Snaps packages.
109
124
 
110
- [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@4.0.1...HEAD
125
+ [Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.0.1...HEAD
126
+ [5.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@5.0.0...@metamask/snaps-utils@5.0.1
127
+ [5.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@4.0.1...@metamask/snaps-utils@5.0.0
111
128
  [4.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@4.0.0...@metamask/snaps-utils@4.0.1
112
129
  [4.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.3.0...@metamask/snaps-utils@4.0.0
113
130
  [3.3.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.2.0...@metamask/snaps-utils@3.3.0
@@ -10,14 +10,14 @@ Object.defineProperty(exports, "encodeAuxiliaryFile", {
10
10
  });
11
11
  const _snapssdk = require("@metamask/snaps-sdk");
12
12
  const _utils = require("@metamask/utils");
13
- const _base = require("@scure/base");
14
- function encodeAuxiliaryFile(value, encoding) {
13
+ const _base64 = require("./base64");
14
+ async function encodeAuxiliaryFile(value, encoding) {
15
15
  // Input is assumed to be the stored file in base64.
16
16
  if (encoding === _snapssdk.AuxiliaryFileEncoding.Base64) {
17
17
  return value;
18
18
  }
19
19
  // TODO: Use @metamask/utils for this
20
- const decoded = _base.base64.decode(value);
20
+ const decoded = await (0, _base64.decodeBase64)(value);
21
21
  if (encoding === _snapssdk.AuxiliaryFileEncoding.Utf8) {
22
22
  return (0, _utils.bytesToString)(decoded);
23
23
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';\nimport { bytesToHex, bytesToString } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = base64.decode(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n"],"names":["encodeAuxiliaryFile","value","encoding","AuxiliaryFileEncoding","Base64","decoded","base64","decode","Utf8","bytesToString","bytesToHex"],"mappings":";;;;+BAWgBA;;;eAAAA;;;0BAXsB;uBACI;sBACnB;AAShB,SAASA,oBACdC,KAAa,EACbC,QAA+B;IAE/B,oDAAoD;IACpD,IAAIA,aAAaC,+BAAqB,CAACC,MAAM,EAAE;QAC7C,OAAOH;IACT;IAEA,qCAAqC;IACrC,MAAMI,UAAUC,YAAM,CAACC,MAAM,CAACN;IAC9B,IAAIC,aAAaC,+BAAqB,CAACK,IAAI,EAAE;QAC3C,OAAOC,IAAAA,oBAAa,EAACJ;IACvB;IAEA,OAAOK,IAAAA,iBAAU,EAACL;AACpB"}
1
+ {"version":3,"sources":["../../src/auxiliary-files.ts"],"sourcesContent":["import { AuxiliaryFileEncoding } from '@metamask/snaps-sdk';\nimport { bytesToHex, bytesToString } from '@metamask/utils';\n\nimport { decodeBase64 } from './base64';\n\n/**\n * Re-encodes an auxiliary file if needed depending on the requested file encoding.\n *\n * @param value - The base64 value stored for the auxiliary file.\n * @param encoding - The chosen encoding.\n * @returns The file encoded in the requested encoding.\n */\nexport async function encodeAuxiliaryFile(\n value: string,\n encoding: AuxiliaryFileEncoding,\n) {\n // Input is assumed to be the stored file in base64.\n if (encoding === AuxiliaryFileEncoding.Base64) {\n return value;\n }\n\n // TODO: Use @metamask/utils for this\n const decoded = await decodeBase64(value);\n if (encoding === AuxiliaryFileEncoding.Utf8) {\n return bytesToString(decoded);\n }\n\n return bytesToHex(decoded);\n}\n"],"names":["encodeAuxiliaryFile","value","encoding","AuxiliaryFileEncoding","Base64","decoded","decodeBase64","Utf8","bytesToString","bytesToHex"],"mappings":";;;;+BAYsBA;;;eAAAA;;;0BAZgB;uBACI;wBAEb;AAStB,eAAeA,oBACpBC,KAAa,EACbC,QAA+B;IAE/B,oDAAoD;IACpD,IAAIA,aAAaC,+BAAqB,CAACC,MAAM,EAAE;QAC7C,OAAOH;IACT;IAEA,qCAAqC;IACrC,MAAMI,UAAU,MAAMC,IAAAA,oBAAY,EAACL;IACnC,IAAIC,aAAaC,+BAAqB,CAACI,IAAI,EAAE;QAC3C,OAAOC,IAAAA,oBAAa,EAACH;IACvB;IAEA,OAAOI,IAAAA,iBAAU,EAACJ;AACpB"}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ encodeBase64: function() {
13
+ return encodeBase64;
14
+ },
15
+ decodeBase64: function() {
16
+ return decodeBase64;
17
+ }
18
+ });
19
+ const _utils = require("@metamask/utils");
20
+ const _bytes = require("./bytes");
21
+ async function encodeBase64(input) {
22
+ const bytes = (0, _bytes.getBytes)(input);
23
+ // In the browser, FileReader is much faster than bytesToBase64.
24
+ if ('FileReader' in globalThis) {
25
+ return await new Promise((resolve, reject)=>{
26
+ const reader = Object.assign(new FileReader(), {
27
+ onload: ()=>resolve(reader.result.replace('data:application/octet-stream;base64,', '')),
28
+ onerror: ()=>reject(reader.error)
29
+ });
30
+ reader.readAsDataURL(new File([
31
+ bytes
32
+ ], '', {
33
+ type: 'application/octet-stream'
34
+ }));
35
+ });
36
+ }
37
+ return (0, _utils.bytesToBase64)(bytes);
38
+ }
39
+ async function decodeBase64(base64) {
40
+ const response = await fetch(`data:application/octet-stream;base64,${base64}`);
41
+ return new Uint8Array(await response.arrayBuffer());
42
+ }
43
+
44
+ //# sourceMappingURL=base64.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/base64.ts"],"sourcesContent":["import { bytesToBase64 } from '@metamask/utils';\n\nimport { getBytes } from './bytes';\nimport type { VirtualFile } from './virtual-file';\n\n/**\n * Provides fast, asynchronous base64 encoding.\n *\n * @param input - The input value, assumed to be coercable to bytes.\n * @returns A base64 string.\n */\nexport async function encodeBase64(input: Uint8Array | VirtualFile | string) {\n const bytes = getBytes(input);\n // In the browser, FileReader is much faster than bytesToBase64.\n if ('FileReader' in globalThis) {\n return await new Promise((resolve, reject) => {\n const reader = Object.assign(new FileReader(), {\n onload: () =>\n resolve(\n (reader.result as string).replace(\n 'data:application/octet-stream;base64,',\n '',\n ),\n ),\n onerror: () => reject(reader.error),\n });\n reader.readAsDataURL(\n new File([bytes], '', { type: 'application/octet-stream' }),\n );\n });\n }\n return bytesToBase64(bytes);\n}\n\n/**\n * Provides fast, asynchronous base64 decoding.\n *\n * @param base64 - A base64 string.\n * @returns A Uint8Array of bytes.\n */\nexport async function decodeBase64(base64: string) {\n const response = await fetch(\n `data:application/octet-stream;base64,${base64}`,\n );\n return new Uint8Array(await response.arrayBuffer());\n}\n"],"names":["encodeBase64","decodeBase64","input","bytes","getBytes","globalThis","Promise","resolve","reject","reader","Object","assign","FileReader","onload","result","replace","onerror","error","readAsDataURL","File","type","bytesToBase64","base64","response","fetch","Uint8Array","arrayBuffer"],"mappings":";;;;;;;;;;;IAWsBA,YAAY;eAAZA;;IA6BAC,YAAY;eAAZA;;;uBAxCQ;uBAEL;AASlB,eAAeD,aAAaE,KAAwC;IACzE,MAAMC,QAAQC,IAAAA,eAAQ,EAACF;IACvB,gEAAgE;IAChE,IAAI,gBAAgBG,YAAY;QAC9B,OAAO,MAAM,IAAIC,QAAQ,CAACC,SAASC;YACjC,MAAMC,SAASC,OAAOC,MAAM,CAAC,IAAIC,cAAc;gBAC7CC,QAAQ,IACNN,QACE,AAACE,OAAOK,MAAM,CAAYC,OAAO,CAC/B,yCACA;gBAGNC,SAAS,IAAMR,OAAOC,OAAOQ,KAAK;YACpC;YACAR,OAAOS,aAAa,CAClB,IAAIC,KAAK;gBAAChB;aAAM,EAAE,IAAI;gBAAEiB,MAAM;YAA2B;QAE7D;IACF;IACA,OAAOC,IAAAA,oBAAa,EAAClB;AACvB;AAQO,eAAeF,aAAaqB,MAAc;IAC/C,MAAMC,WAAW,MAAMC,MACrB,CAAC,qCAAqC,EAAEF,OAAO,CAAC;IAElD,OAAO,IAAIG,WAAW,MAAMF,SAASG,WAAW;AAClD"}
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "getBytes", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return getBytes;
9
+ }
10
+ });
11
+ const _utils = require("@metamask/utils");
12
+ const _virtualfile = require("./virtual-file");
13
+ function getBytes(bytes) {
14
+ // Unwrap VirtualFiles to extract the content
15
+ // The content is then either a string or Uint8Array
16
+ const unwrapped = bytes instanceof _virtualfile.VirtualFile ? bytes.value : bytes;
17
+ if (typeof unwrapped === 'string') {
18
+ return (0, _utils.stringToBytes)(unwrapped);
19
+ }
20
+ return unwrapped;
21
+ }
22
+
23
+ //# sourceMappingURL=bytes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/bytes.ts"],"sourcesContent":["import { stringToBytes } from '@metamask/utils';\n\nimport { VirtualFile } from './virtual-file';\n\n/**\n * Convert a bytes-like input value to a Uint8Array.\n *\n * @param bytes - A bytes-like value.\n * @returns The input value converted to a Uint8Array if necessary.\n */\nexport function getBytes(bytes: VirtualFile | Uint8Array | string): Uint8Array {\n // Unwrap VirtualFiles to extract the content\n // The content is then either a string or Uint8Array\n const unwrapped = bytes instanceof VirtualFile ? bytes.value : bytes;\n\n if (typeof unwrapped === 'string') {\n return stringToBytes(unwrapped);\n }\n\n return unwrapped;\n}\n"],"names":["getBytes","bytes","unwrapped","VirtualFile","value","stringToBytes"],"mappings":";;;;+BAUgBA;;;eAAAA;;;uBAVc;6BAEF;AAQrB,SAASA,SAASC,KAAwC;IAC/D,6CAA6C;IAC7C,oDAAoD;IACpD,MAAMC,YAAYD,iBAAiBE,wBAAW,GAAGF,MAAMG,KAAK,GAAGH;IAE/D,IAAI,OAAOC,cAAc,UAAU;QACjC,OAAOG,IAAAA,oBAAa,EAACH;IACvB;IAEA,OAAOA;AACT"}
@@ -9,9 +9,6 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
- getChecksumBytes: function() {
13
- return getChecksumBytes;
14
- },
15
12
  checksum: function() {
16
13
  return checksum;
17
14
  },
@@ -21,18 +18,9 @@ _export(exports, {
21
18
  });
22
19
  const _utils = require("@metamask/utils");
23
20
  const _sha256 = require("@noble/hashes/sha256");
24
- const _VirtualFile = require("./virtual-file/VirtualFile");
25
- function getChecksumBytes(bytes) {
26
- // Unwrap VirtualFiles to extract the content
27
- // The content is then either a string or Uint8Array
28
- const unwrapped = bytes instanceof _VirtualFile.VirtualFile ? bytes.value : bytes;
29
- if (typeof unwrapped === 'string') {
30
- return (0, _utils.stringToBytes)(unwrapped);
31
- }
32
- return unwrapped;
33
- }
21
+ const _bytes = require("./bytes");
34
22
  async function checksum(bytes) {
35
- const value = getChecksumBytes(bytes);
23
+ const value = (0, _bytes.getBytes)(bytes);
36
24
  // Use crypto.subtle.digest whenever possible as it is faster.
37
25
  if ('crypto' in globalThis && typeof globalThis.crypto === 'object' && crypto.subtle?.digest) {
38
26
  return new Uint8Array(await crypto.subtle.digest('SHA-256', value));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { assert, concatBytes, stringToBytes } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport { VirtualFile } from './virtual-file/VirtualFile';\n\n/**\n * Convert an input value to a Uint8Array for use in a checksum.\n *\n * @param bytes - A value to use for a checksum calculation.\n * @returns The input value converted to a Uint8Array if necessary.\n */\nexport function getChecksumBytes(\n bytes: VirtualFile | Uint8Array | string,\n): Uint8Array {\n // Unwrap VirtualFiles to extract the content\n // The content is then either a string or Uint8Array\n const unwrapped = bytes instanceof VirtualFile ? bytes.value : bytes;\n\n if (typeof unwrapped === 'string') {\n return stringToBytes(unwrapped);\n }\n\n return unwrapped;\n}\n\n/**\n * Calculates checksum for a single byte array.\n *\n * @param bytes - The byte array to calculate the checksum for.\n * @returns A single sha-256 checksum.\n */\nexport async function checksum(\n bytes: VirtualFile | Uint8Array | string,\n): Promise<Uint8Array> {\n const value = getChecksumBytes(bytes);\n // Use crypto.subtle.digest whenever possible as it is faster.\n if (\n 'crypto' in globalThis &&\n typeof globalThis.crypto === 'object' &&\n crypto.subtle?.digest\n ) {\n return new Uint8Array(await crypto.subtle.digest('SHA-256', value));\n }\n return sha256(value);\n}\n\n/**\n * Calculates checksum over multiple files in a reproducible way.\n *\n * 1. Sort all the files by their paths.\n * 2. Calculate sha-256 checksum of each file separately.\n * 3. Concatenate all the checksums into one buffer and sha-256 that buffer.\n *\n * The sorting of paths is done using {@link https://tc39.es/ecma262/#sec-islessthan UTF-16 Code Units}.\n *\n * @param files - The files over which to calculate the checksum.\n * @returns A single sha-256 checksum.\n */\nexport async function checksumFiles(files: VirtualFile[]) {\n const checksums = await Promise.all(\n [...files]\n .sort((a, b) => {\n assert(a.path !== b.path, 'Tried to sort files with non-unique paths.');\n if (a.path < b.path) {\n return -1;\n }\n return 1;\n })\n .map(async (file) => checksum(file)),\n );\n\n return checksum(concatBytes(checksums));\n}\n"],"names":["getChecksumBytes","checksum","checksumFiles","bytes","unwrapped","VirtualFile","value","stringToBytes","globalThis","crypto","subtle","digest","Uint8Array","sha256","files","checksums","Promise","all","sort","a","b","assert","path","map","file","concatBytes"],"mappings":";;;;;;;;;;;IAWgBA,gBAAgB;eAAhBA;;IAoBMC,QAAQ;eAARA;;IA2BAC,aAAa;eAAbA;;;uBA1D6B;wBAC5B;6BAEK;AAQrB,SAASF,iBACdG,KAAwC;IAExC,6CAA6C;IAC7C,oDAAoD;IACpD,MAAMC,YAAYD,iBAAiBE,wBAAW,GAAGF,MAAMG,KAAK,GAAGH;IAE/D,IAAI,OAAOC,cAAc,UAAU;QACjC,OAAOG,IAAAA,oBAAa,EAACH;IACvB;IAEA,OAAOA;AACT;AAQO,eAAeH,SACpBE,KAAwC;IAExC,MAAMG,QAAQN,iBAAiBG;IAC/B,8DAA8D;IAC9D,IACE,YAAYK,cACZ,OAAOA,WAAWC,MAAM,KAAK,YAC7BA,OAAOC,MAAM,EAAEC,QACf;QACA,OAAO,IAAIC,WAAW,MAAMH,OAAOC,MAAM,CAACC,MAAM,CAAC,WAAWL;IAC9D;IACA,OAAOO,IAAAA,cAAM,EAACP;AAChB;AAcO,eAAeJ,cAAcY,KAAoB;IACtD,MAAMC,YAAY,MAAMC,QAAQC,GAAG,CACjC;WAAIH;KAAM,CACPI,IAAI,CAAC,CAACC,GAAGC;QACRC,IAAAA,aAAM,EAACF,EAAEG,IAAI,KAAKF,EAAEE,IAAI,EAAE;QAC1B,IAAIH,EAAEG,IAAI,GAAGF,EAAEE,IAAI,EAAE;YACnB,OAAO,CAAC;QACV;QACA,OAAO;IACT,GACCC,GAAG,CAAC,OAAOC,OAASvB,SAASuB;IAGlC,OAAOvB,SAASwB,IAAAA,kBAAW,EAACV;AAC9B"}
1
+ {"version":3,"sources":["../../src/checksum.ts"],"sourcesContent":["import { assert, concatBytes } from '@metamask/utils';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport { getBytes } from './bytes';\nimport type { VirtualFile } from './virtual-file/VirtualFile';\n\n/**\n * Calculates checksum for a single byte array.\n *\n * @param bytes - The byte array to calculate the checksum for.\n * @returns A single sha-256 checksum.\n */\nexport async function checksum(\n bytes: VirtualFile | Uint8Array | string,\n): Promise<Uint8Array> {\n const value = getBytes(bytes);\n // Use crypto.subtle.digest whenever possible as it is faster.\n if (\n 'crypto' in globalThis &&\n typeof globalThis.crypto === 'object' &&\n crypto.subtle?.digest\n ) {\n return new Uint8Array(await crypto.subtle.digest('SHA-256', value));\n }\n return sha256(value);\n}\n\n/**\n * Calculates checksum over multiple files in a reproducible way.\n *\n * 1. Sort all the files by their paths.\n * 2. Calculate sha-256 checksum of each file separately.\n * 3. Concatenate all the checksums into one buffer and sha-256 that buffer.\n *\n * The sorting of paths is done using {@link https://tc39.es/ecma262/#sec-islessthan UTF-16 Code Units}.\n *\n * @param files - The files over which to calculate the checksum.\n * @returns A single sha-256 checksum.\n */\nexport async function checksumFiles(files: VirtualFile[]) {\n const checksums = await Promise.all(\n [...files]\n .sort((a, b) => {\n assert(a.path !== b.path, 'Tried to sort files with non-unique paths.');\n if (a.path < b.path) {\n return -1;\n }\n return 1;\n })\n .map(async (file) => checksum(file)),\n );\n\n return checksum(concatBytes(checksums));\n}\n"],"names":["checksum","checksumFiles","bytes","value","getBytes","globalThis","crypto","subtle","digest","Uint8Array","sha256","files","checksums","Promise","all","sort","a","b","assert","path","map","file","concatBytes"],"mappings":";;;;;;;;;;;IAYsBA,QAAQ;eAARA;;IA2BAC,aAAa;eAAbA;;;uBAvCc;wBACb;uBAEE;AASlB,eAAeD,SACpBE,KAAwC;IAExC,MAAMC,QAAQC,IAAAA,eAAQ,EAACF;IACvB,8DAA8D;IAC9D,IACE,YAAYG,cACZ,OAAOA,WAAWC,MAAM,KAAK,YAC7BA,OAAOC,MAAM,EAAEC,QACf;QACA,OAAO,IAAIC,WAAW,MAAMH,OAAOC,MAAM,CAACC,MAAM,CAAC,WAAWL;IAC9D;IACA,OAAOO,IAAAA,cAAM,EAACP;AAChB;AAcO,eAAeF,cAAcU,KAAoB;IACtD,MAAMC,YAAY,MAAMC,QAAQC,GAAG,CACjC;WAAIH;KAAM,CACPI,IAAI,CAAC,CAACC,GAAGC;QACRC,IAAAA,aAAM,EAACF,EAAEG,IAAI,KAAKF,EAAEE,IAAI,EAAE;QAC1B,IAAIH,EAAEG,IAAI,GAAGF,EAAEE,IAAI,EAAE;YACnB,OAAO,CAAC;QACV;QACA,OAAO;IACT,GACCC,GAAG,CAAC,OAAOC,OAASrB,SAASqB;IAGlC,OAAOrB,SAASsB,IAAAA,kBAAW,EAACV;AAC9B"}
@@ -34,13 +34,12 @@ _export(exports, {
34
34
  const _utils = require("@metamask/utils");
35
35
  const _cronparser = require("cron-parser");
36
36
  const _superstruct = require("superstruct");
37
- const CronjobRpcRequestStruct = (0, _superstruct.assign)((0, _superstruct.partial)((0, _superstruct.pick)(_utils.JsonRpcRequestStruct, [
38
- 'id',
39
- 'jsonrpc'
40
- ])), (0, _superstruct.omit)(_utils.JsonRpcRequestStruct, [
41
- 'id',
42
- 'jsonrpc'
43
- ]));
37
+ const CronjobRpcRequestStruct = (0, _superstruct.object)({
38
+ jsonrpc: (0, _superstruct.optional)(_utils.JsonRpcVersionStruct),
39
+ id: (0, _superstruct.optional)(_utils.JsonRpcIdStruct),
40
+ method: (0, _superstruct.string)(),
41
+ params: (0, _superstruct.optional)(_utils.JsonRpcParamsStruct)
42
+ });
44
43
  const CronExpressionStruct = (0, _superstruct.refine)((0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.object)({
45
44
  minute: (0, _superstruct.optional)((0, _superstruct.string)()),
46
45
  hour: (0, _superstruct.optional)((0, _superstruct.string)()),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import { JsonRpcRequestStruct } from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n assign,\n omit,\n partial,\n pick,\n array,\n coerce,\n create,\n object,\n optional,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = assign(\n partial(pick(JsonRpcRequestStruct, ['id', 'jsonrpc'])),\n omit(JsonRpcRequestStruct, ['id', 'jsonrpc']),\n);\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["CronjobRpcRequestStruct","CronExpressionStruct","parseCronExpression","CronjobSpecificationStruct","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray","assign","partial","pick","JsonRpcRequestStruct","omit","refine","coerce","string","object","minute","optional","hour","dayOfMonth","month","dayOfWeek","value","parseExpression","expression","ensureStringExpression","create","request","array"],"mappings":";;;;;;;;;;;IAiBaA,uBAAuB;eAAvBA;;IAMAC,oBAAoB;eAApBA;;IAkCGC,mBAAmB;eAAnBA;;IAKHC,0BAA0B;eAA1BA;;IAYGC,sBAAsB;eAAtBA;;IASHC,+BAA+B;eAA/BA;;IAUGC,2BAA2B;eAA3BA;;;uBA7FqB;4BACL;6BAczB;AAEA,MAAMN,0BAA0BO,IAAAA,mBAAM,EAC3CC,IAAAA,oBAAO,EAACC,IAAAA,iBAAI,EAACC,2BAAoB,EAAE;IAAC;IAAM;CAAU,IACpDC,IAAAA,iBAAI,EAACD,2BAAoB,EAAE;IAAC;IAAM;CAAU;AAIvC,MAAMT,uBAAuBW,IAAAA,mBAAM,EACxCC,IAAAA,mBAAM,EACJC,IAAAA,mBAAM,KACNC,IAAAA,mBAAM,EAAC;IACLC,QAAQC,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IACvBI,MAAMD,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IACrBK,YAAYF,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IAC3BM,OAAOH,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;IACtBO,WAAWJ,IAAAA,qBAAQ,EAACH,IAAAA,mBAAM;AAC5B,IACA,CAACQ,QACC,CAAC,EAAEA,MAAMN,MAAM,IAAI,IAAI,CAAC,EAAEM,MAAMJ,IAAI,IAAI,IAAI,CAAC,EAAEI,MAAMH,UAAU,IAAI,IAAI,CAAC,EACtEG,MAAMF,KAAK,IAAI,IAChB,CAAC,EAAEE,MAAMD,SAAS,IAAI,IAAI,CAAC,GAEhC,kBACA,CAACC;IACC,IAAI;QACFC,IAAAA,2BAAe,EAACD;QAChB,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAWK,SAASpB,oBAAoBsB,UAA2B;IAC7D,MAAMC,yBAAyBC,IAAAA,mBAAM,EAACF,YAAYvB;IAClD,OAAOsB,IAAAA,2BAAe,EAACE;AACzB;AAEO,MAAMtB,6BAA6BY,IAAAA,mBAAM,EAAC;IAC/CS,YAAYvB;IACZ0B,SAAS3B;AACX;AASO,SAASI,uBAAuBkB,KAAc;IACnD,IAAI;QACFI,IAAAA,mBAAM,EAACJ,OAAOnB;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEO,MAAME,kCAAkCuB,IAAAA,kBAAK,EAClDzB;AASK,SAASG,4BAA4BgB,KAAc;IACxD,IAAI;QACFI,IAAAA,mBAAM,EAACJ,OAAOjB;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../src/cronjob.ts"],"sourcesContent":["import {\n JsonRpcIdStruct,\n JsonRpcParamsStruct,\n JsonRpcVersionStruct,\n} from '@metamask/utils';\nimport { parseExpression } from 'cron-parser';\nimport type { Infer } from 'superstruct';\nimport {\n array,\n coerce,\n create,\n object,\n optional,\n refine,\n string,\n} from 'superstruct';\n\nexport const CronjobRpcRequestStruct = object({\n jsonrpc: optional(JsonRpcVersionStruct),\n id: optional(JsonRpcIdStruct),\n method: string(),\n params: optional(JsonRpcParamsStruct),\n});\n\nexport type CronjobRpcRequest = Infer<typeof CronjobRpcRequestStruct>;\n\nexport const CronExpressionStruct = refine(\n coerce(\n string(),\n object({\n minute: optional(string()),\n hour: optional(string()),\n dayOfMonth: optional(string()),\n month: optional(string()),\n dayOfWeek: optional(string()),\n }),\n (value) =>\n `${value.minute ?? '*'} ${value.hour ?? '*'} ${value.dayOfMonth ?? '*'} ${\n value.month ?? '*'\n } ${value.dayOfWeek ?? '*'}`,\n ),\n 'CronExpression',\n (value) => {\n try {\n parseExpression(value);\n return true;\n } catch {\n return false;\n }\n },\n);\n\nexport type CronExpression = Infer<typeof CronExpressionStruct>;\n\n/**\n * Parses a cron expression.\n *\n * @param expression - Expression to parse.\n * @returns A CronExpression class instance.\n */\nexport function parseCronExpression(expression: string | object) {\n const ensureStringExpression = create(expression, CronExpressionStruct);\n return parseExpression(ensureStringExpression);\n}\n\nexport const CronjobSpecificationStruct = object({\n expression: CronExpressionStruct,\n request: CronjobRpcRequestStruct,\n});\nexport type CronjobSpecification = Infer<typeof CronjobSpecificationStruct>;\n\n/**\n * Check if the given value is a {@link CronjobSpecification} object.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid {@link CronjobSpecification} object.\n */\nexport function isCronjobSpecification(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationStruct);\n return true;\n } catch {\n return false;\n }\n}\n\nexport const CronjobSpecificationArrayStruct = array(\n CronjobSpecificationStruct,\n);\n\n/**\n * Check if the given value is an array of {@link CronjobSpecification} objects.\n *\n * @param value - The value to check.\n * @returns Whether the value is a valid array of {@link CronjobSpecification} objects.\n */\nexport function isCronjobSpecificationArray(value: unknown): boolean {\n try {\n create(value, CronjobSpecificationArrayStruct);\n return true;\n } catch {\n return false;\n }\n}\n"],"names":["CronjobRpcRequestStruct","CronExpressionStruct","parseCronExpression","CronjobSpecificationStruct","isCronjobSpecification","CronjobSpecificationArrayStruct","isCronjobSpecificationArray","object","jsonrpc","optional","JsonRpcVersionStruct","id","JsonRpcIdStruct","method","string","params","JsonRpcParamsStruct","refine","coerce","minute","hour","dayOfMonth","month","dayOfWeek","value","parseExpression","expression","ensureStringExpression","create","request","array"],"mappings":";;;;;;;;;;;IAiBaA,uBAAuB;eAAvBA;;IASAC,oBAAoB;eAApBA;;IAkCGC,mBAAmB;eAAnBA;;IAKHC,0BAA0B;eAA1BA;;IAYGC,sBAAsB;eAAtBA;;IASHC,+BAA+B;eAA/BA;;IAUGC,2BAA2B;eAA3BA;;;uBA5FT;4BACyB;6BAUzB;AAEA,MAAMN,0BAA0BO,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B,IAAAA,kBAAK,EAClD3B;AASK,SAASG,4BAA4BkB,KAAc;IACxD,IAAI;QACFI,IAAAA,mBAAM,EAACJ,OAAOnB;QACd,OAAO;IACT,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
@@ -4,13 +4,14 @@ Object.defineProperty(exports, "__esModule", {
4
4
  });
5
5
  _export_star(require("./array"), exports);
6
6
  _export_star(require("./auxiliary-files"), exports);
7
+ _export_star(require("./base64"), exports);
8
+ _export_star(require("./bytes"), exports);
7
9
  _export_star(require("./caveats"), exports);
8
10
  _export_star(require("./checksum"), exports);
9
11
  _export_star(require("./cronjob"), exports);
10
12
  _export_star(require("./deep-clone"), exports);
11
13
  _export_star(require("./default-endowments"), exports);
12
14
  _export_star(require("./entropy"), exports);
13
- _export_star(require("./enum"), exports);
14
15
  _export_star(require("./errors"), exports);
15
16
  _export_star(require("./handlers"), exports);
16
17
  _export_star(require("./handler-types"), exports);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './errors';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
1
+ {"version":3,"sources":["../../src/index.browser.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './base64';\nexport * from './bytes';\nexport * from './caveats';\nexport * from './checksum';\nexport * from './cronjob';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './errors';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest/index.browser';\nexport * from './namespace';\nexport * from './path';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file/index.browser';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
package/dist/cjs/index.js CHANGED
@@ -4,13 +4,14 @@ Object.defineProperty(exports, "__esModule", {
4
4
  });
5
5
  _export_star(require("./array"), exports);
6
6
  _export_star(require("./auxiliary-files"), exports);
7
+ _export_star(require("./base64"), exports);
8
+ _export_star(require("./bytes"), exports);
7
9
  _export_star(require("./caveats"), exports);
8
10
  _export_star(require("./cronjob"), exports);
9
11
  _export_star(require("./checksum"), exports);
10
12
  _export_star(require("./deep-clone"), exports);
11
13
  _export_star(require("./default-endowments"), exports);
12
14
  _export_star(require("./entropy"), exports);
13
- _export_star(require("./enum"), exports);
14
15
  _export_star(require("./eval"), exports);
15
16
  _export_star(require("./errors"), exports);
16
17
  _export_star(require("./fs"), exports);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './enum';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
1
+ {"version":3,"sources":["../../src/index.ts"],"sourcesContent":["export * from './array';\nexport * from './auxiliary-files';\nexport * from './base64';\nexport * from './bytes';\nexport * from './caveats';\nexport * from './cronjob';\nexport * from './checksum';\nexport * from './deep-clone';\nexport * from './default-endowments';\nexport * from './entropy';\nexport * from './eval';\nexport * from './errors';\nexport * from './fs';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './iframe';\nexport * from './json';\nexport * from './json-rpc';\nexport * from './localization';\nexport * from './logging';\nexport * from './manifest';\nexport * from './mock';\nexport * from './namespace';\nexport * from './npm';\nexport * from './path';\nexport * from './post-process';\nexport * from './snaps';\nexport * from './strings';\nexport * from './structs';\nexport * from './types';\nexport * from './ui';\nexport * from './validation';\nexport * from './versions';\nexport * from './virtual-file';\n"],"names":[],"mappings":";;;;qBAAc;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA;qBACA"}
@@ -75,7 +75,8 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
75
75
  packageJson: packageFile,
76
76
  sourceCode: await getSnapSourceCode(basePath, unvalidatedManifest, sourceCode),
77
77
  svgIcon: await getSnapIcon(basePath, unvalidatedManifest),
78
- auxiliaryFiles: await getSnapFiles(basePath, auxiliaryFilePaths) ?? [],
78
+ // Intentionally pass null as the encoding here since the files may be binary
79
+ auxiliaryFiles: await getSnapFiles(basePath, auxiliaryFilePaths, null) ?? [],
79
80
  localizationFiles: await getSnapFiles(basePath, localizationFilePaths) ?? []
80
81
  };
81
82
  let manifest;
@@ -221,12 +222,12 @@ function getSnapFilePaths(manifest, selector) {
221
222
  }
222
223
  return paths;
223
224
  }
224
- async function getSnapFiles(basePath, paths) {
225
+ async function getSnapFiles(basePath, paths, encoding = 'utf8') {
225
226
  if (!paths) {
226
227
  return undefined;
227
228
  }
228
229
  try {
229
- return await Promise.all(paths.map(async (filePath)=>(0, _virtualfile.readVirtualFile)(_path.default.join(basePath, filePath), 'utf8')));
230
+ return await Promise.all(paths.map(async (filePath)=>(0, _virtualfile.readVirtualFile)(_path.default.join(basePath, filePath), encoding)));
230
231
  } catch (error) {
231
232
  throw new Error(`Failed to read snap files: ${(0, _snapssdk.getErrorMessage)(error)}`);
232
233
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n auxiliaryFiles: (await getSnapFiles(basePath, auxiliaryFilePaths)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = await validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = await fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n await validateNpmSnapManifest({\n ...partiallyValidatedFiles,\n manifest,\n });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport async function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): Promise<VirtualFile<SnapManifest>> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = await getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), 'utf8'),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an NPM Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport async function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n await validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getSnapFilePaths","getSnapFiles","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","writeFileFn","fs","writeFile","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","svgIcon","auxiliaryFiles","localizationFiles","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","getErrorMessage","iconPath","selector","snapManifest","paths","Array","isArray","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAkEsBA,aAAa;eAAbA;;IA6JAC,WAAW;eAAXA;;IA8CAC,iBAAiB;eAAjBA;;IA4CAC,WAAW;eAAXA;;IAiCNC,gBAAgB;eAAhBA;;IA0BMC,YAAY;eAAZA;;IA0BNC,mBAAmB;eAAnBA;;IAgCMC,uBAAuB;eAAvBA;;;0BA9aU;uBAEwB;sEAClC;oBACS;6DACT;2BAEI;qBACG;qBACG;uBAKzB;uBAEuD;6BACjB;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;IACRC,oBAAoB;IACpBC,iBAAiB;AACnB;AAqCO,eAAehB,cACpBiB,QAAgB,EAChBC,gBAAgB,IAAI,EACpBC,UAAmB,EACnBC,cAAiCC,YAAE,CAACC,SAAS;IAE7C,MAAMC,WAAqB,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AC,qBAAqB,EAAEwF,oBAAoB,uBAAuB,EAAEzF,uBAAgB,CAACO,WAAW,CAAC,iBAAiB,EAAE+E,gBAAgB,GAAG,CAAC,EACtKzD,kCAA2B,CAACsB,YAAY;IAE5C;IAEA,IAAIoC,uBAAuBG,wBAAwB;QACjD,MAAM,IAAItE,uCAAgC,CACxC,CAAC,CAAC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,wBAAwB,EAAEyF,uBAAuB,uBAAuB,EAAE1F,uBAAgB,CAACO,WAAW,CAAC,oBAAoB,EAAEgF,mBAAmB,GAAG,CAAC,EAClL1D,kCAA2B,CAAC2B,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDgC,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACC,IAAAA,sBAAS,EAACJ,uBAAuBG,qBAClC;QACA,MAAM,IAAIvE,uCAAgC,CACxC,CAAC,CAAC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HsB,kCAA2B,CAAC4B,kBAAkB;IAElD;IAEA,MAAMoC,IAAAA,yBAAkB,EACtB;QAAEpF;QAAUnB;QAAYyB;QAASC;QAAgBC;IAAkB,GACnE,CAAC,CAAC,EAAEjB,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
1
+ {"version":3,"sources":["../../../src/manifest/manifest.ts"],"sourcesContent":["import { getErrorMessage } from '@metamask/snaps-sdk';\nimport type { Json } from '@metamask/utils';\nimport { assertExhaustive, assert, isPlainObject } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { deepClone } from '../deep-clone';\nimport { readJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapChecksum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport type { SnapFiles, UnvalidatedSnapFiles } from '../types';\nimport { NpmSnapFileNames, SnapValidationFailureReason } from '../types';\nimport { readVirtualFile, VirtualFile } from '../virtual-file';\nimport type { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n $schema: 1,\n version: 2,\n description: 3,\n proposedName: 4,\n repository: 5,\n source: 6,\n initialPermissions: 7,\n manifestVersion: 8,\n};\n\n/**\n * The result from the `checkManifest` function.\n *\n * @property manifest - The fixed manifest object.\n * @property updated - Whether the manifest was updated.\n * @property warnings - An array of warnings that were encountered during\n * processing of the manifest files. These warnings are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n * @property errors - An array of errors that were encountered during\n * processing of the manifest files. These errors are not logged to the\n * console automatically, so depending on the environment the function is called\n * in, a different method for logging can be used.\n */\nexport type CheckManifestResult = {\n manifest: SnapManifest;\n updated?: boolean;\n warnings: string[];\n errors: string[];\n};\n\nexport type WriteFileFunction = (path: string, data: string) => Promise<void>;\n\n/**\n * Validates a snap.manifest.json file. Attempts to fix the manifest and write\n * the fixed version to disk if `writeManifest` is true. Throws if validation\n * fails.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param writeManifest - Whether to write the fixed manifest to disk.\n * @param sourceCode - The source code of the Snap.\n * @param writeFileFn - The function to use to write the manifest to disk.\n * @returns Whether the manifest was updated, and an array of warnings that\n * were encountered during processing of the manifest files.\n */\nexport async function checkManifest(\n basePath: string,\n writeManifest = true,\n sourceCode?: string,\n writeFileFn: WriteFileFunction = fs.writeFile,\n): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const manifestPath = pathUtils.join(basePath, NpmSnapFileNames.Manifest);\n const manifestFile = await readJsonFile(manifestPath);\n const unvalidatedManifest = manifestFile.result;\n\n const packageFile = await readJsonFile(\n pathUtils.join(basePath, NpmSnapFileNames.PackageJson),\n );\n\n const auxiliaryFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.files,\n );\n\n const localizationFilePaths = getSnapFilePaths(\n unvalidatedManifest,\n (manifest) => manifest?.source?.locales,\n );\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: manifestFile,\n packageJson: packageFile,\n sourceCode: await getSnapSourceCode(\n basePath,\n unvalidatedManifest,\n sourceCode,\n ),\n svgIcon: await getSnapIcon(basePath, unvalidatedManifest),\n // Intentionally pass null as the encoding here since the files may be binary\n auxiliaryFiles:\n (await getSnapFiles(basePath, auxiliaryFilePaths, null)) ?? [],\n localizationFiles:\n (await getSnapFiles(basePath, localizationFilePaths)) ?? [],\n };\n\n let manifest: VirtualFile<SnapManifest> | undefined;\n try {\n ({ manifest } = await validateNpmSnap(snapFiles));\n } catch (error) {\n if (error instanceof ProgrammaticallyFixableSnapError) {\n errors.push(error.message);\n\n // If we get here, the files at least have the correct shape.\n const partiallyValidatedFiles = snapFiles as SnapFiles;\n\n let isInvalid = true;\n let currentError = error;\n const maxAttempts = Object.keys(SnapValidationFailureReason).length;\n\n // Attempt to fix all fixable validation failure reasons. All such reasons\n // are enumerated by the `SnapValidationFailureReason` enum, so we only\n // attempt to fix the manifest the same amount of times as there are\n // reasons in the enum.\n for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {\n manifest = await fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n await validateNpmSnapManifest({\n ...partiallyValidatedFiles,\n manifest,\n });\n\n isInvalid = false;\n } catch (nextValidationError) {\n currentError = nextValidationError;\n /* istanbul ignore next: this should be impossible */\n if (\n !(\n nextValidationError instanceof ProgrammaticallyFixableSnapError\n ) ||\n (attempts === maxAttempts && !isInvalid)\n ) {\n throw new Error(\n `Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\\n${error.message}`,\n );\n }\n\n errors.push(currentError.message);\n }\n }\n\n updated = true;\n } else {\n throw error;\n }\n }\n\n // TypeScript assumes `manifest` can still be undefined, that is not the case.\n // But we assert to keep TypeScript happy.\n assert(manifest);\n\n const validatedManifest = manifest.result;\n\n // Check presence of recommended keys\n const recommendedFields = ['repository'] as const;\n\n const missingRecommendedFields = recommendedFields.filter(\n (key) => !validatedManifest[key],\n );\n\n if (missingRecommendedFields.length > 0) {\n warnings.push(\n `Missing recommended package.json properties:\\n${missingRecommendedFields.reduce(\n (allMissing, currentField) => {\n return `${allMissing}\\t${currentField}\\n`;\n },\n '',\n )}`,\n );\n }\n\n if (writeManifest) {\n try {\n const newManifest = `${JSON.stringify(\n getWritableManifest(validatedManifest),\n null,\n 2,\n )}\\n`;\n\n if (updated || newManifest !== manifestFile.value) {\n await writeFileFn(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n newManifest,\n );\n }\n } catch (error) {\n // Note: This error isn't pushed to the errors array, because it's not an\n // error in the manifest itself.\n throw new Error(`Failed to update snap.manifest.json: ${error.message}`);\n }\n }\n\n return { manifest: validatedManifest, updated, warnings, errors };\n}\n\n/**\n * Given the relevant Snap files (manifest, `package.json`, and bundle) and a\n * Snap manifest validation error, fixes the fault in the manifest that caused\n * the error.\n *\n * @param snapFiles - The contents of all Snap files.\n * @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.\n * @returns A copy of the manifest file where the cause of the error is fixed.\n */\nexport async function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): Promise<VirtualFile<SnapManifest>> {\n const { manifest, packageJson } = snapFiles;\n const clonedFile = manifest.clone();\n const manifestCopy = clonedFile.result;\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.result.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.result.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.result.repository\n ? deepClone(packageJson.result.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = await getSnapChecksum(snapFiles);\n break;\n\n /* istanbul ignore next */\n default:\n assertExhaustive(error.reason);\n }\n\n clonedFile.result = manifestCopy;\n clonedFile.value = JSON.stringify(manifestCopy);\n return clonedFile;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * bundle source file location and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param sourceCode - Override source code for plugins.\n * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n sourceCode?: string,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n if (!sourceFilePath) {\n return undefined;\n }\n\n if (sourceCode) {\n return new VirtualFile({\n path: pathUtils.join(basePath, sourceFilePath),\n value: sourceCode,\n });\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, sourceFilePath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(\n `Failed to read snap bundle file: ${getErrorMessage(error)}`,\n );\n }\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the location of the\n * icon and read the file.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param manifest - The unvalidated Snap manifest file contents.\n * @returns The contents of the icon, if any.\n */\nexport async function getSnapIcon(\n basePath: string,\n manifest: Json,\n): Promise<VirtualFile | undefined> {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const iconPath = (manifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath;\n\n if (!iconPath) {\n return undefined;\n }\n\n try {\n const virtualFile = await readVirtualFile(\n pathUtils.join(basePath, iconPath),\n 'utf8',\n );\n return virtualFile;\n } catch (error) {\n throw new Error(`Failed to read snap icon file: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Get an array of paths from an unvalidated Snap manifest.\n *\n * @param manifest - The unvalidated Snap manifest file contents.\n * @param selector - A function that returns the paths to the files.\n * @returns The paths to the files, if any.\n */\nexport function getSnapFilePaths(\n manifest: Json,\n selector: (manifest: Partial<SnapManifest>) => string[] | undefined,\n) {\n if (!isPlainObject(manifest)) {\n return undefined;\n }\n\n const snapManifest = manifest as Partial<SnapManifest>;\n const paths = selector(snapManifest);\n\n if (!Array.isArray(paths)) {\n return undefined;\n }\n\n return paths;\n}\n\n/**\n * Given an unvalidated Snap manifest, attempts to extract the files with the\n * given paths and read them.\n *\n * @param basePath - The path to the folder with the manifest files.\n * @param paths - The paths to the files.\n * @param encoding - An optional encoding to pass down to readVirtualFile.\n * @returns A list of auxiliary files and their contents, if any.\n */\nexport async function getSnapFiles(\n basePath: string,\n paths: string[] | undefined,\n encoding: BufferEncoding | null = 'utf8',\n): Promise<VirtualFile[] | undefined> {\n if (!paths) {\n return undefined;\n }\n\n try {\n return await Promise.all(\n paths.map(async (filePath) =>\n readVirtualFile(pathUtils.join(basePath, filePath), encoding),\n ),\n );\n } catch (error) {\n throw new Error(`Failed to read snap files: ${getErrorMessage(error)}`);\n }\n}\n\n/**\n * Sorts the given manifest in our preferred sort order and removes the\n * `repository` field if it is falsy (it may be `null`).\n *\n * @param manifest - The manifest to sort and modify.\n * @returns The disk-ready manifest.\n */\nexport function getWritableManifest(manifest: SnapManifest): SnapManifest {\n const { repository, ...remaining } = manifest;\n\n const keys = Object.keys(\n repository ? { ...remaining, repository } : remaining,\n ) as (keyof SnapManifest)[];\n\n const writableManifest = keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce<Partial<SnapManifest>>(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {},\n );\n\n return writableManifest as SnapManifest;\n}\n\n/**\n * Validates the fields of an NPM Snap manifest that has already passed JSON\n * Schema validation.\n *\n * @param snapFiles - The relevant snap files to validate.\n * @param snapFiles.manifest - The npm Snap manifest to validate.\n * @param snapFiles.packageJson - The npm Snap's `package.json`.\n * @param snapFiles.sourceCode - The Snap's source code.\n * @param snapFiles.svgIcon - The Snap's optional icon.\n * @param snapFiles.auxiliaryFiles - Any auxiliary files required by the snap at runtime.\n * @param snapFiles.localizationFiles - The Snap's localization files.\n */\nexport async function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n svgIcon,\n auxiliaryFiles,\n localizationFiles,\n}: SnapFiles) {\n const packageJsonName = packageJson.result.name;\n const packageJsonVersion = packageJson.result.version;\n const packageJsonRepository = packageJson.result.repository;\n\n const manifestPackageName = manifest.result.source.location.npm.packageName;\n const manifestPackageVersion = manifest.result.version;\n const manifestRepository = manifest.result.repository;\n\n if (packageJsonName !== manifestPackageName) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package name (\"${manifestPackageName}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"name\" field (\"${packageJsonName}\").`,\n SnapValidationFailureReason.NameMismatch,\n );\n }\n\n if (packageJsonVersion !== manifestPackageVersion) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" npm package version (\"${manifestPackageVersion}\") does not match the \"${NpmSnapFileNames.PackageJson}\" \"version\" field (\"${packageJsonVersion}\").`,\n SnapValidationFailureReason.VersionMismatch,\n );\n }\n\n if (\n // The repository may be `undefined` in package.json but can only be defined\n // or `null` in the Snap manifest due to TS@<4.4 issues.\n (packageJsonRepository || manifestRepository) &&\n !deepEqual(packageJsonRepository, manifestRepository)\n ) {\n throw new ProgrammaticallyFixableSnapError(\n `\"${NpmSnapFileNames.Manifest}\" \"repository\" field does not match the \"${NpmSnapFileNames.PackageJson}\" \"repository\" field.`,\n SnapValidationFailureReason.RepositoryMismatch,\n );\n }\n\n await validateSnapShasum(\n { manifest, sourceCode, svgIcon, auxiliaryFiles, localizationFiles },\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n}\n"],"names":["checkManifest","fixManifest","getSnapSourceCode","getSnapIcon","getSnapFilePaths","getSnapFiles","getWritableManifest","validateNpmSnapManifest","MANIFEST_SORT_ORDER","$schema","version","description","proposedName","repository","source","initialPermissions","manifestVersion","basePath","writeManifest","sourceCode","writeFileFn","fs","writeFile","warnings","errors","updated","manifestPath","pathUtils","join","NpmSnapFileNames","Manifest","manifestFile","readJsonFile","unvalidatedManifest","result","packageFile","PackageJson","auxiliaryFilePaths","manifest","files","localizationFilePaths","locales","snapFiles","packageJson","svgIcon","auxiliaryFiles","localizationFiles","validateNpmSnap","error","ProgrammaticallyFixableSnapError","push","message","partiallyValidatedFiles","isInvalid","currentError","maxAttempts","Object","keys","SnapValidationFailureReason","length","attempts","nextValidationError","Error","assert","validatedManifest","recommendedFields","missingRecommendedFields","filter","key","reduce","allMissing","currentField","newManifest","JSON","stringify","value","clonedFile","clone","manifestCopy","reason","NameMismatch","location","npm","packageName","name","VersionMismatch","RepositoryMismatch","deepClone","undefined","ShasumMismatch","shasum","getSnapChecksum","assertExhaustive","isPlainObject","sourceFilePath","filePath","VirtualFile","path","virtualFile","readVirtualFile","getErrorMessage","iconPath","selector","snapManifest","paths","Array","isArray","encoding","Promise","all","map","remaining","writableManifest","sort","a","b","packageJsonName","packageJsonVersion","packageJsonRepository","manifestPackageName","manifestPackageVersion","manifestRepository","deepEqual","validateSnapShasum"],"mappings":";;;;;;;;;;;IAkEsBA,aAAa;eAAbA;;IA+JAC,WAAW;eAAXA;;IA8CAC,iBAAiB;eAAjBA;;IA4CAC,WAAW;eAAXA;;IAiCNC,gBAAgB;eAAhBA;;IA2BMC,YAAY;eAAZA;;IA2BNC,mBAAmB;eAAnBA;;IAgCMC,uBAAuB;eAAvBA;;;0BAlbU;uBAEwB;sEAClC;oBACS;6DACT;2BAEI;qBACG;qBACG;uBAKzB;uBAEuD;6BACjB;;;;;;AAG7C,MAAMC,sBAA0D;IAC9DC,SAAS;IACTC,SAAS;IACTC,aAAa;IACbC,cAAc;IACdC,YAAY;IACZC,QAAQ;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yBlF,SAASJ,MAAM,CAACxB,OAAO;IACtD,MAAM+G,qBAAqBnF,SAASJ,MAAM,CAACrB,UAAU;IAErD,IAAIuG,oBAAoBG,qBAAqB;QAC3C,MAAM,IAAItE,uCAAgC,CACxC,CAAC,CAAC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,qBAAqB,EAAEyF,oBAAoB,uBAAuB,EAAE1F,uBAAgB,CAACO,WAAW,CAAC,iBAAiB,EAAEgF,gBAAgB,GAAG,CAAC,EACtK1D,kCAA2B,CAACsB,YAAY;IAE5C;IAEA,IAAIqC,uBAAuBG,wBAAwB;QACjD,MAAM,IAAIvE,uCAAgC,CACxC,CAAC,CAAC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,wBAAwB,EAAE0F,uBAAuB,uBAAuB,EAAE3F,uBAAgB,CAACO,WAAW,CAAC,oBAAoB,EAAEiF,mBAAmB,GAAG,CAAC,EAClL3D,kCAA2B,CAAC2B,eAAe;IAE/C;IAEA,IAGE,AAFA,4EAA4E;IAC5E,wDAAwD;IACvDiC,CAAAA,yBAAyBG,kBAAiB,KAC3C,CAACC,IAAAA,sBAAS,EAACJ,uBAAuBG,qBAClC;QACA,MAAM,IAAIxE,uCAAgC,CACxC,CAAC,CAAC,EAAEpB,uBAAgB,CAACC,QAAQ,CAAC,yCAAyC,EAAED,uBAAgB,CAACO,WAAW,CAAC,qBAAqB,CAAC,EAC5HsB,kCAA2B,CAAC4B,kBAAkB;IAElD;IAEA,MAAMqC,IAAAA,yBAAkB,EACtB;QAAErF;QAAUnB;QAAYyB;QAASC;QAAgBC;IAAkB,GACnE,CAAC,CAAC,EAAEjB,uBAAgB,CAACC,QAAQ,CAAC,gDAAgD,CAAC;AAEnF"}
@@ -9,12 +9,6 @@ function _export(target, all) {
9
9
  });
10
10
  }
11
11
  _export(exports, {
12
- literal: function() {
13
- return literal;
14
- },
15
- union: function() {
16
- return union;
17
- },
18
12
  file: function() {
19
13
  return file;
20
14
  },
@@ -54,22 +48,6 @@ const _chalk = require("chalk");
54
48
  const _path = require("path");
55
49
  const _superstruct = require("superstruct");
56
50
  const _strings = require("./strings");
57
- function literal(value) {
58
- return (0, _superstruct.define)(JSON.stringify(value), (0, _superstruct.literal)(value).validator);
59
- }
60
- function union([head, ...tail]) {
61
- const struct = (0, _superstruct.union)([
62
- head,
63
- ...tail
64
- ]);
65
- return new _superstruct.Struct({
66
- ...struct,
67
- schema: [
68
- head,
69
- ...tail
70
- ]
71
- });
72
- }
73
51
  function file() {
74
52
  return (0, _superstruct.coerce)((0, _superstruct.string)(), (0, _superstruct.string)(), (value)=>{
75
53
  return (0, _path.resolve)(process.cwd(), value);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure, Infer } from 'superstruct';\nimport {\n Struct,\n StructError,\n define,\n literal as superstructLiteral,\n union as superstructUnion,\n create,\n string,\n coerce,\n} from 'superstruct';\nimport type { AnyStruct, InferStructTuple } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * A wrapper of `superstruct`'s `literal` struct that also defines the name of\n * the struct as the literal value.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n * For example, instead of returning an error like:\n *\n * ```\n * Expected the value to satisfy a union of `literal | literal`, but received: \\\"baz\\\"\n * ```\n *\n * This struct will return an error like:\n *\n * ```\n * Expected the value to satisfy a union of `\"foo\" | \"bar\"`, but received: \\\"baz\\\"\n * ```\n *\n * @param value - The literal value.\n * @returns The `superstruct` struct, which validates that the value is equal\n * to the literal value.\n */\nexport function literal<Type extends string | number | boolean>(value: Type) {\n return define<Type>(\n JSON.stringify(value),\n superstructLiteral(value).validator,\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `union` struct that also defines the schema as\n * the union of the schemas of the structs.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param structs - The structs to union.\n * @param structs.\"0\" - The first struct.\n * @param structs.\"1\" - The remaining structs.\n * @returns The `superstruct` struct, which validates that the value satisfies\n * one of the structs.\n */\nexport function union<Head extends AnyStruct, Tail extends AnyStruct[]>([\n head,\n ...tail\n]: [head: Head, ...tail: Tail]): Struct<\n Infer<Head> | InferStructTuple<Tail>[number],\n [head: Head, ...tail: Tail]\n> {\n const struct = superstructUnion([head, ...tail]);\n\n return new Struct({\n ...struct,\n schema: [head, ...tail],\n });\n}\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["literal","union","file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","value","define","JSON","stringify","superstructLiteral","validator","head","tail","struct","superstructUnion","Struct","schema","coerce","string","resolve","process","cwd","name","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","Array","isArray","map","green","length","bold","join","received","red","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAkEgBA,OAAO;eAAPA;;IAmBAC,KAAK;eAALA;;IAkCAC,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAoBAC,mBAAmB;eAAnBA;;IAiBAC,oBAAoB;eAApBA;;IAiBAC,uBAAuB;eAAvBA;;IAiDAC,qBAAqB;eAArBA;;;uBAzVS;uBACQ;sBACT;6BAWjB;yBAGgB;AAkDhB,SAASZ,QAAgDa,KAAW;IACzE,OAAOC,IAAAA,mBAAM,EACXC,KAAKC,SAAS,CAACH,QACfI,IAAAA,oBAAkB,EAACJ,OAAOK,SAAS;AAEvC;AAcO,SAASjB,MAAwD,CACtEkB,M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O,CAAC,EAAErB,OAAO,EAAEE,QAAQE,OAAO,CAAC,CAAC,CAAC;IACvC;IAEA,IAAIF,QAAQL,IAAI,KAAK,WAAW;QAC9B,yEAAyE;QACzE,0EAA0E;QAC1E,MAAMO,UAAUF,QAAQE,OAAO,CAC5BqB,OAAO,CAAC,wBAAwB,CAAC,kBAAkB,EAAER,IAAAA,YAAK,EAAC,MAAM,GAAG,CAAC,EACrEQ,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,EAAEH,IAAAA,UAAG,EAAC,MAAM,CAAC;QAElE,OAAO,CAAC,EAAEtB,OAAO,EAAEI,QAAQ,CAAC,CAAC;IAC/B;IAEA,IAAIF,QAAQL,IAAI,KAAK,SAAS;QAC5B,OAAO,CAAC,aAAa,EAAEsB,IAAAA,WAAI,EACzBjB,QAAQO,IAAI,CAACW,IAAI,CAAC,MAClB,YAAY,EAAEC,SAAS,CAAC,CAAC;IAC7B;IAEA,OAAO,CAAC,EAAErB,OAAO,yBAAyB,EAAEiB,IAAAA,YAAK,EAC/Cf,QAAQL,IAAI,EACZ,gBAAgB,EAAEwB,SAAS,CAAC,CAAC;AACjC;AAUO,SAAS3C,sBACdS,MAA4B,EAC5BgB,QAAmB;IAEnB,MAAMuB,oBAAoBvB,SAASa,GAAG,CAAC,CAACd,UACtCyB,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAElD,wBAAwBU,QAAQe,SAAS,CAAC;IAGxD,OAAOwB,kBAAkBN,IAAI,CAAC;AAChC"}
1
+ {"version":3,"sources":["../../src/structs.ts"],"sourcesContent":["import { isObject } from '@metamask/utils';\nimport { bold, green, red } from 'chalk';\nimport { resolve } from 'path';\nimport type { Failure } from 'superstruct';\nimport { Struct, StructError, create, string, coerce } from 'superstruct';\nimport type { AnyStruct } from 'superstruct/dist/utils';\n\nimport { indent } from './strings';\n\n/**\n * Infer a struct type, only if it matches the specified type. This is useful\n * for defining types and structs that are related to each other in separate\n * files.\n *\n * @example\n * ```typescript\n * // In file A\n * export type GetFileArgs = {\n * path: string;\n * encoding?: EnumToUnion<AuxiliaryFileEncoding>;\n * };\n *\n * // In file B\n * export const GetFileArgsStruct = object(...);\n *\n * // If the type and struct are in the same file, this will return the type.\n * // Otherwise, it will return `never`.\n * export type GetFileArgs =\n * InferMatching<typeof GetFileArgsStruct, GetFileArgs>;\n * ```\n */\nexport type InferMatching<\n StructType extends Struct<any, any>,\n Type,\n> = StructType['TYPE'] extends Type ? Type : never;\n\n/**\n * A wrapper of `superstruct`'s `string` struct that coerces a value to a string\n * and resolves it relative to the current working directory. This is useful\n * for specifying file paths in a configuration file, as it allows the user to\n * use both relative and absolute paths.\n *\n * @returns The `superstruct` struct, which validates that the value is a\n * string, and resolves it relative to the current working directory.\n * @example\n * ```ts\n * const config = struct({\n * file: file(),\n * // ...\n * });\n *\n * const value = create({ file: 'path/to/file' }, config);\n * console.log(value.file); // /process/cwd/path/to/file\n * ```\n */\nexport function file() {\n return coerce(string(), string(), (value) => {\n return resolve(process.cwd(), value);\n });\n}\n\n/**\n * Define a struct, and also define the name of the struct as the given name.\n *\n * This is useful for improving the error messages returned by `superstruct`.\n *\n * @param name - The name of the struct.\n * @param struct - The struct.\n * @returns The struct.\n */\nexport function named<Type, Schema>(\n name: string,\n struct: Struct<Type, Schema>,\n) {\n return new Struct({\n ...struct,\n type: name,\n });\n}\n\nexport class SnapsStructError<Type, Schema> extends StructError {\n constructor(\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix: string,\n failure: StructError,\n failures: () => Generator<Failure>,\n ) {\n super(failure, failures);\n\n this.name = 'SnapsStructError';\n this.message = `${prefix}.\\n\\n${getStructErrorMessage(struct, [\n ...failures(),\n ])}${suffix ? `\\n\\n${suffix}` : ''}`;\n }\n}\n\ntype GetErrorOptions<Type, Schema> = {\n struct: Struct<Type, Schema>;\n prefix: string;\n suffix?: string;\n error: StructError;\n};\n\n/**\n * Converts an array to a generator function that yields the items in the\n * array.\n *\n * @param array - The array.\n * @returns A generator function.\n * @yields The items in the array.\n */\nexport function* arrayToGenerator<Type>(\n array: Type[],\n): Generator<Type, void, undefined> {\n for (const item of array) {\n yield item;\n }\n}\n\n/**\n * Returns a `SnapsStructError` with the given prefix and suffix.\n *\n * @param options - The options.\n * @param options.struct - The struct that caused the error.\n * @param options.prefix - The prefix to add to the error message.\n * @param options.suffix - The suffix to add to the error message. Defaults to\n * an empty string.\n * @param options.error - The `superstruct` error to wrap.\n * @returns The `SnapsStructError`.\n */\nexport function getError<Type, Schema>({\n struct,\n prefix,\n suffix = '',\n error,\n}: GetErrorOptions<Type, Schema>) {\n return new SnapsStructError(struct, prefix, suffix, error, () =>\n arrayToGenerator(error.failures()),\n );\n}\n\n/**\n * A wrapper of `superstruct`'s `create` function that throws a\n * `SnapsStructError` instead of a `StructError`. This is useful for improving\n * the error messages returned by `superstruct`.\n *\n * @param value - The value to validate.\n * @param struct - The `superstruct` struct to validate the value against.\n * @param prefix - The prefix to add to the error message.\n * @param suffix - The suffix to add to the error message. Defaults to an empty\n * string.\n * @returns The validated value.\n */\nexport function createFromStruct<Type, Schema>(\n value: unknown,\n struct: Struct<Type, Schema>,\n prefix: string,\n suffix = '',\n) {\n try {\n return create(value, struct);\n } catch (error) {\n if (error instanceof StructError) {\n throw getError({ struct, prefix, suffix, error });\n }\n\n throw error;\n }\n}\n\n/**\n * Get a struct from a failure path.\n *\n * @param struct - The struct.\n * @param path - The failure path.\n * @returns The struct at the failure path.\n */\nexport function getStructFromPath<Type, Schema>(\n struct: Struct<Type, Schema>,\n path: string[],\n) {\n return path.reduce<AnyStruct>((result, key) => {\n if (isObject(struct.schema) && struct.schema[key]) {\n return struct.schema[key] as AnyStruct;\n }\n\n return result;\n }, struct);\n}\n\n/**\n * Get the union struct names from a struct.\n *\n * @param struct - The struct.\n * @returns The union struct names, or `null` if the struct is not a union\n * struct.\n */\nexport function getUnionStructNames<Type, Schema>(\n struct: Struct<Type, Schema>,\n) {\n if (Array.isArray(struct.schema)) {\n return struct.schema.map(({ type }) => green(type));\n }\n\n return null;\n}\n\n/**\n * Get a error prefix from a `superstruct` failure. This is useful for\n * formatting the error message returned by `superstruct`.\n *\n * @param failure - The `superstruct` failure.\n * @returns The error prefix.\n */\nexport function getStructErrorPrefix(failure: Failure) {\n if (failure.type === 'never' || failure.path.length === 0) {\n return '';\n }\n\n return `At path: ${bold(failure.path.join('.'))} — `;\n}\n\n/**\n * Get a string describing the failure. This is similar to the `message`\n * property of `superstruct`'s `Failure` type, but formats the value in a more\n * readable way.\n *\n * @param struct - The struct that caused the failure.\n * @param failure - The `superstruct` failure.\n * @returns A string describing the failure.\n */\nexport function getStructFailureMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failure: Failure,\n) {\n const received = red(JSON.stringify(failure.value));\n const prefix = getStructErrorPrefix(failure);\n\n if (failure.type === 'union') {\n const childStruct = getStructFromPath(struct, failure.path);\n const unionNames = getUnionStructNames(childStruct);\n\n if (unionNames) {\n return `${prefix}Expected the value to be one of: ${unionNames.join(\n ', ',\n )}, but received: ${received}.`;\n }\n\n return `${prefix}${failure.message}.`;\n }\n\n if (failure.type === 'literal') {\n // Superstruct's failure does not provide information about which literal\n // value was expected, so we need to parse the message to get the literal.\n const message = failure.message\n .replace(/the literal `(.+)`,/u, `the value to be \\`${green('$1')}\\`,`)\n .replace(/, but received: (.+)/u, `, but received: ${red('$1')}`);\n\n return `${prefix}${message}.`;\n }\n\n if (failure.type === 'never') {\n return `Unknown key: ${bold(\n failure.path.join('.'),\n )}, received: ${received}.`;\n }\n\n return `${prefix}Expected a value of type ${green(\n failure.type,\n )}, but received: ${received}.`;\n}\n\n/**\n * Get a string describing the errors. This formats all the errors in a\n * human-readable way.\n *\n * @param struct - The struct that caused the failures.\n * @param failures - The `superstruct` failures.\n * @returns A string describing the errors.\n */\nexport function getStructErrorMessage<Type, Schema>(\n struct: Struct<Type, Schema>,\n failures: Failure[],\n) {\n const formattedFailures = failures.map((failure) =>\n indent(`• ${getStructFailureMessage(struct, failure)}`),\n );\n\n return formattedFailures.join('\\n');\n}\n"],"names":["file","named","SnapsStructError","arrayToGenerator","getError","createFromStruct","getStructFromPath","getUnionStructNames","getStructErrorPrefix","getStructFailureMessage","getStructErrorMessage","coerce","string","value","resolve","process","cwd","name","struct","Struct","type","StructError","constructor","prefix","suffix","failure","failures","message","array","item","error","create","path","reduce","result","key","isObject","schema","Array","isArray","map","green","length","bold","join","received","red","JSON","stringify","childStruct","unionNames","replace","formattedFailures","indent"],"mappings":";;;;;;;;;;;IAuDgBA,IAAI;eAAJA;;IAeAC,KAAK;eAALA;;IAUHC,gBAAgB;eAAhBA;;IAgCIC,gBAAgB;eAAhBA;;IAmBDC,QAAQ;eAARA;;IAuBAC,gBAAgB;eAAhBA;;IAwBAC,iBAAiB;eAAjBA;;IAoBAC,mBAAmB;eAAnBA;;IAiBAC,oBAAoB;eAApBA;;IAiBAC,uBAAuB;eAAvBA;;IAiDAC,qBAAqB;eAArBA;;;uBAzRS;uBACQ;sBACT;6BAEoC;yBAGrC;AAgDhB,SAASV;IACd,OAAOW,IAAAA,mBAAM,EAACC,IAAAA,mBAAM,KAAIA,IAAAA,mBAAM,KAAI,CAACC;QACjC,OAAOC,IAAAA,aAAO,EAACC,QAAQC,GAAG,IAAIH;IAChC;AACF;AAWO,SAASZ,MACdgB,IAAY,EACZC,MAA4B;IAE5B,OAAO,IAAIC,mBAAM,CAAC;QAChB,GAAGD,MAAM;QACTE,MAAMH;IACR;AACF;AAEO,MAAMf,yBAAuCmB,wBAAW;IAC7DC,YACEJ,MAA4B,EAC5BK,MAAc,EACdC,MAAc,EACdC,OAAoB,EACpBC,QAAkC,CAClC;QACA,KAAK,CAACD,SAASC;QAEf,IAAI,CAACT,IAAI,GAAG;QACZ,IAAI,CAACU,OAAO,GAAG,CAAC,EAAEJ,OAAO,KAAK,EAAEb,sBAAsBQ,QAAQ;eACzDQ;SACJ,EAAE,EAAEF,SAAS,CAAC,IAAI,EAAEA,OAAO,CAAC,GAAG,GAAG,CAAC;IACtC;AACF;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ACf,UACtC4B,IAAAA,eAAM,EAAC,CAAC,EAAE,EAAE5C,wBAAwBS,QAAQO,SAAS,CAAC;IAGxD,OAAO2B,kBAAkBR,IAAI,CAAC;AAChC"}
@@ -40,6 +40,7 @@ class VirtualFile {
40
40
  } else if (this.value instanceof Uint8Array && encoding === 'hex') {
41
41
  return (0, _utils.bytesToHex)(this.value);
42
42
  } else if (this.value instanceof Uint8Array && encoding === 'base64') {
43
+ // For large files, this is quite slow, instead use `encodeBase64()`
43
44
  // TODO: Use @metamask/utils for this
44
45
  return _base.base64.encode(this.value);
45
46
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/virtual-file/VirtualFile.ts"],"sourcesContent":["// TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review\n// TODO(ritave): Streaming vfile contents similar to vinyl maybe?\n// TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile\n// similar to unified instead of throwing \"ProgrammaticallyFixableErrors\".\n//\n// Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.\n// https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because\n// we're calculating checksums based on original path.\nimport { assert, bytesToHex } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\nimport { deepClone } from '../deep-clone';\n\n/**\n * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.\n *\n * This type can be augmented to register custom `data` types.\n *\n * @example\n * declare module '@metamask/snaps-utils' {\n * interface DataMap {\n * // `file.data.name` is typed as `string`\n * name: string\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface\nexport interface DataMap {}\n\nexport type Value = string | Uint8Array;\nexport type Compatible<Result = unknown> =\n | string\n | Uint8Array\n | Options<Result>;\nexport type Data = Record<string, unknown> & Partial<DataMap>;\nexport type Options<Result = unknown> = {\n value: Value;\n path?: string;\n data?: Data;\n result?: Result;\n};\n\nexport class VirtualFile<Result = unknown> {\n constructor(value?: Compatible<Result>) {\n let options: Options | undefined;\n if (typeof value === 'string' || value instanceof Uint8Array) {\n options = { value };\n } else {\n options = value;\n }\n\n this.value = options?.value ?? '';\n // This situations happens when there's no .result used,\n // we expect the file to have default generic in that situation:\n // VirtualFile<unknown> which will handle undefined properly\n //\n // While not 100% type safe, it'll be way less frustrating to work with.\n // The alternative would be to have VirtualFile.result be Result | undefined\n // and that would result in needing to branch out and check in all situations.\n //\n // In short, optimizing for most common use case.\n this.result = options?.result ?? (undefined as any);\n this.data = options?.data ?? {};\n this.path = options?.path ?? '/';\n }\n\n value: Value;\n\n result: Result;\n\n data: Data;\n\n path: string;\n\n toString(encoding?: string) {\n if (typeof this.value === 'string') {\n assert(encoding === undefined, 'Tried to encode string.');\n return this.value;\n } else if (this.value instanceof Uint8Array && encoding === 'hex') {\n return bytesToHex(this.value);\n } else if (this.value instanceof Uint8Array && encoding === 'base64') {\n // TODO: Use @metamask/utils for this\n return base64.encode(this.value);\n }\n const decoder = new TextDecoder(encoding);\n return decoder.decode(this.value);\n }\n\n clone() {\n const vfile = new VirtualFile<Result>();\n if (typeof this.value === 'string') {\n vfile.value = this.value;\n } else {\n // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array\n vfile.value = this.value.slice(0);\n }\n vfile.result = deepClone(this.result);\n vfile.data = deepClone(this.data);\n vfile.path = this.path;\n return vfile;\n }\n}\n"],"names":["VirtualFile","toString","encoding","value","assert","undefined","Uint8Array","bytesToHex","base64","encode","decoder","TextDecoder","decode","clone","vfile","slice","result","deepClone","data","path","constructor","options"],"mappings":"AAAA,0HAA0H;AAC1H,iEAAiE;AACjE,2FAA2F;AAC3F,wFAAwF;AACxF,EAAE;AACF,oHAAoH;AACpH,qGAAqG;AACrG,sDAAsD;;;;;+BAmCzCA;;;eAAAA;;;uBAlCsB;sBACZ;2BAEG;;;;;;;;;;;;;;AA+BnB,MAAMA;IAgCXC,SAASC,QAAiB,EAAE;QAC1B,IAAI,OAAO,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AA4D;QAC5D,EAAE;QACF,wEAAwE;QACxE,4EAA4E;QAC5E,8EAA8E;QAC9E,EAAE;QACF,iDAAiD;QACjD,IAAI,CAACa,MAAM,GAAGK,SAASL,UAAWX;QAClC,IAAI,CAACa,IAAI,GAAGG,SAASH,QAAQ,CAAC;QAC9B,IAAI,CAACC,IAAI,GAAGE,SAASF,QAAQ;IAC/B;AAqCF"}
1
+ {"version":3,"sources":["../../../src/virtual-file/VirtualFile.ts"],"sourcesContent":["// TODO(ritave): Move into separate package @metamask/vfile / @metamask/utils + @metamask/to-vfile when passes code review\n// TODO(ritave): Streaming vfile contents similar to vinyl maybe?\n// TODO(ritave): Move fixing manifest in cli and bundler plugins to write messages to vfile\n// similar to unified instead of throwing \"ProgrammaticallyFixableErrors\".\n//\n// Using https://github.com/vfile/vfile would be helpful, but they only support ESM and we need to support CommonJS.\n// https://github.com/gulpjs/vinyl is also good, but they normalize paths, which we can't do, because\n// we're calculating checksums based on original path.\nimport { assert, bytesToHex } from '@metamask/utils';\nimport { base64 } from '@scure/base';\n\nimport { deepClone } from '../deep-clone';\n\n/**\n * This map registers the type of the {@link VirtualFile.data} key of a {@link VirtualFile}.\n *\n * This type can be augmented to register custom `data` types.\n *\n * @example\n * declare module '@metamask/snaps-utils' {\n * interface DataMap {\n * // `file.data.name` is typed as `string`\n * name: string\n * }\n * }\n */\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions, @typescript-eslint/no-empty-interface\nexport interface DataMap {}\n\nexport type Value = string | Uint8Array;\nexport type Compatible<Result = unknown> =\n | string\n | Uint8Array\n | Options<Result>;\nexport type Data = Record<string, unknown> & Partial<DataMap>;\nexport type Options<Result = unknown> = {\n value: Value;\n path?: string;\n data?: Data;\n result?: Result;\n};\n\nexport class VirtualFile<Result = unknown> {\n constructor(value?: Compatible<Result>) {\n let options: Options | undefined;\n if (typeof value === 'string' || value instanceof Uint8Array) {\n options = { value };\n } else {\n options = value;\n }\n\n this.value = options?.value ?? '';\n // This situations happens when there's no .result used,\n // we expect the file to have default generic in that situation:\n // VirtualFile<unknown> which will handle undefined properly\n //\n // While not 100% type safe, it'll be way less frustrating to work with.\n // The alternative would be to have VirtualFile.result be Result | undefined\n // and that would result in needing to branch out and check in all situations.\n //\n // In short, optimizing for most common use case.\n this.result = options?.result ?? (undefined as any);\n this.data = options?.data ?? {};\n this.path = options?.path ?? '/';\n }\n\n value: Value;\n\n result: Result;\n\n data: Data;\n\n path: string;\n\n toString(encoding?: string) {\n if (typeof this.value === 'string') {\n assert(encoding === undefined, 'Tried to encode string.');\n return this.value;\n } else if (this.value instanceof Uint8Array && encoding === 'hex') {\n return bytesToHex(this.value);\n } else if (this.value instanceof Uint8Array && encoding === 'base64') {\n // For large files, this is quite slow, instead use `encodeBase64()`\n // TODO: Use @metamask/utils for this\n return base64.encode(this.value);\n }\n const decoder = new TextDecoder(encoding);\n return decoder.decode(this.value);\n }\n\n clone() {\n const vfile = new VirtualFile<Result>();\n if (typeof this.value === 'string') {\n vfile.value = this.value;\n } else {\n // deep-clone doesn't clone Buffer properly, even if it's a sub-class of Uint8Array\n vfile.value = this.value.slice(0);\n }\n vfile.result = deepClone(this.result);\n vfile.data = deepClone(this.data);\n vfile.path = this.path;\n return vfile;\n }\n}\n"],"names":["VirtualFile","toString","encoding","value","assert","undefined","Uint8Array","bytesToHex","base64","encode","decoder","TextDecoder","decode","clone","vfile","slice","result","deepClone","data","path","constructor","options"],"mappings":"AAAA,0HAA0H;AAC1H,iEAAiE;AACjE,2FAA2F;AAC3F,wFAAwF;AACxF,EAAE;AACF,oHAAoH;AACpH,qGAAqG;AACrG,sDAAsD;;;;;+BAmCzCA;;;eAAAA;;;uBAlCsB;sBACZ;2BAEG;;;;;;;;;;;;;;AA+BnB,MAAMA;IAgCXC,SAASC,QAAiB,EAAE;QAC1B,IAAI,OAAO,IAAI,CAACC,KAAK,KAAK,UAAU;YAClCC,IAAAA,aAAM,EAACF,aAAaG,WAAW;YAC/B,OAAO,IAAI,CAACF,KAA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