@metamask/snaps-utils 3.1.0 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -1
- package/dist/cjs/eval-worker.js +2 -2
- package/dist/cjs/eval-worker.js.map +1 -1
- package/dist/cjs/handler-types.js +32 -0
- package/dist/cjs/handler-types.js.map +1 -0
- package/dist/cjs/handlers.js +37 -27
- package/dist/cjs/handlers.js.map +1 -1
- package/dist/cjs/index.browser.js +2 -0
- package/dist/cjs/index.browser.js.map +1 -1
- package/dist/cjs/index.executionenv.js +1 -0
- package/dist/cjs/index.executionenv.js.map +1 -1
- package/dist/cjs/index.js +2 -0
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/localization.js +113 -0
- package/dist/cjs/localization.js.map +1 -0
- package/dist/cjs/manifest/manifest.js +23 -9
- package/dist/cjs/manifest/manifest.js.map +1 -1
- package/dist/cjs/manifest/validation.js +3 -2
- package/dist/cjs/manifest/validation.js.map +1 -1
- package/dist/cjs/npm.js +16 -3
- package/dist/cjs/npm.js.map +1 -1
- package/dist/cjs/snaps.js.map +1 -1
- package/dist/cjs/types.js +0 -5
- package/dist/cjs/types.js.map +1 -1
- package/dist/cjs/validation.js +2 -0
- package/dist/cjs/validation.js.map +1 -1
- package/dist/esm/eval-worker.js +1 -1
- package/dist/esm/eval-worker.js.map +1 -1
- package/dist/esm/handler-types.js +14 -0
- package/dist/esm/handler-types.js.map +1 -0
- package/dist/esm/handlers.js +17 -10
- package/dist/esm/handlers.js.map +1 -1
- package/dist/esm/index.browser.js +2 -0
- package/dist/esm/index.browser.js.map +1 -1
- package/dist/esm/index.executionenv.js +1 -0
- package/dist/esm/index.executionenv.js.map +1 -1
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/localization.js +115 -0
- package/dist/esm/localization.js.map +1 -0
- package/dist/esm/manifest/manifest.js +30 -12
- package/dist/esm/manifest/manifest.js.map +1 -1
- package/dist/esm/manifest/validation.js +4 -3
- package/dist/esm/manifest/validation.js.map +1 -1
- package/dist/esm/npm.js +16 -3
- package/dist/esm/npm.js.map +1 -1
- package/dist/esm/snaps.js.map +1 -1
- package/dist/esm/types.js +0 -2
- package/dist/esm/types.js.map +1 -1
- package/dist/esm/validation.js +2 -0
- package/dist/esm/validation.js.map +1 -1
- package/dist/types/handler-types.d.ts +32 -0
- package/dist/types/handlers.d.ts +95 -36
- package/dist/types/index.browser.d.ts +2 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/index.executionenv.d.ts +1 -0
- package/dist/types/localization.d.ts +143 -0
- package/dist/types/manifest/manifest.d.ts +15 -6
- package/dist/types/manifest/validation.d.ts +5 -2
- package/dist/types/snaps.d.ts +5 -0
- package/dist/types/types.d.ts +6 -10
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [3.3.0]
|
|
10
|
+
### Added
|
|
11
|
+
- Add manifest localization functionality ([#1889](https://github.com/MetaMask/snaps/pull/1889))
|
|
12
|
+
- Add `OnHomePage` export ([#1896](https://github.com/MetaMask/snaps/pull/1896))
|
|
13
|
+
|
|
14
|
+
## [3.2.0]
|
|
15
|
+
### Added
|
|
16
|
+
- Add support for links in custom UI and notifications ([#1814](https://github.com/MetaMask/snaps/pull/1814))
|
|
17
|
+
|
|
9
18
|
## [3.1.0]
|
|
10
19
|
### Added
|
|
11
20
|
- Add static file API ([#1836](https://github.com/MetaMask/snaps/pull/1836), [#1858](https://github.com/MetaMask/snaps/pull/1858))
|
|
@@ -67,7 +76,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
67
76
|
- The version of the package no longer needs to match the version of all other
|
|
68
77
|
MetaMask Snaps packages.
|
|
69
78
|
|
|
70
|
-
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.
|
|
79
|
+
[Unreleased]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.3.0...HEAD
|
|
80
|
+
[3.3.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.2.0...@metamask/snaps-utils@3.3.0
|
|
81
|
+
[3.2.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.1.0...@metamask/snaps-utils@3.2.0
|
|
71
82
|
[3.1.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@3.0.0...@metamask/snaps-utils@3.1.0
|
|
72
83
|
[3.0.0]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@2.0.1...@metamask/snaps-utils@3.0.0
|
|
73
84
|
[2.0.1]: https://github.com/MetaMask/snaps/compare/@metamask/snaps-utils@2.0.0...@metamask/snaps-utils@2.0.1
|
package/dist/cjs/eval-worker.js
CHANGED
|
@@ -5,8 +5,8 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
});
|
|
6
6
|
require("ses/lockdown");
|
|
7
7
|
const _fs = require("fs");
|
|
8
|
+
const _handlertypes = require("./handler-types");
|
|
8
9
|
const _mock = require("./mock");
|
|
9
|
-
const _types = require("./types");
|
|
10
10
|
lockdown({
|
|
11
11
|
consoleTaming: 'unsafe',
|
|
12
12
|
errorTaming: 'unsafe',
|
|
@@ -41,7 +41,7 @@ new Compartment({
|
|
|
41
41
|
module: snapModule,
|
|
42
42
|
exports: snapModule.exports
|
|
43
43
|
}).evaluate((0, _fs.readFileSync)(snapFilePath, 'utf8'));
|
|
44
|
-
const invalidExports = Object.keys(snapModule.exports).filter((snapExport)=>!
|
|
44
|
+
const invalidExports = Object.keys(snapModule.exports).filter((snapExport)=>!_handlertypes.SNAP_EXPORT_NAMES.includes(snapExport));
|
|
45
45
|
if (invalidExports.length > 0) {
|
|
46
46
|
// eslint-disable-next-line no-console
|
|
47
47
|
console.warn(`Invalid snap exports detected:\n${invalidExports.join('\n')}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './
|
|
1
|
+
{"version":3,"sources":["../../src/eval-worker.ts"],"sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'ses/lockdown';\n\nimport { readFileSync } from 'fs';\n\nimport type { HandlerType } from './handler-types';\nimport { SNAP_EXPORT_NAMES } from './handler-types';\nimport { generateMockEndowments } from './mock';\n\ndeclare let lockdown: any, Compartment: any;\n\nlockdown({\n consoleTaming: 'unsafe',\n errorTaming: 'unsafe',\n mathTaming: 'unsafe',\n dateTaming: 'unsafe',\n overrideTaming: 'severe',\n\n // We disable domain taming, because it does not work in certain cases when\n // running tests. This is unlikely to be a problem in production, because\n // Node.js domains are deprecated.\n domainTaming: 'unsafe',\n});\n\n/**\n * Get mock endowments that don't do anything. This is useful for running the\n * eval, for snaps that try to communicate with the extension on initialisation,\n * for example.\n *\n * @returns The mock endowments.\n */\nfunction getMockEndowments() {\n const endowments = generateMockEndowments();\n return {\n ...endowments,\n window: endowments,\n self: endowments,\n };\n}\n\nconst snapFilePath = process.argv[2];\n\nconst snapModule: { exports?: any } = { exports: {} };\n\nnew Compartment({\n ...getMockEndowments(),\n module: snapModule,\n exports: snapModule.exports,\n}).evaluate(readFileSync(snapFilePath, 'utf8'));\n\nconst invalidExports = Object.keys(snapModule.exports).filter(\n (snapExport) => !SNAP_EXPORT_NAMES.includes(snapExport as HandlerType),\n);\n\nif (invalidExports.length > 0) {\n // eslint-disable-next-line no-console\n console.warn(`Invalid snap exports detected:\\n${invalidExports.join('\\n')}`);\n}\n\nsetTimeout(() => process.exit(0), 1000); // Hack to ensure worker exits\n"],"names":["lockdown","consoleTaming","errorTaming","mathTaming","dateTaming","overrideTaming","domainTaming","getMockEndowments","endowments","generateMockEndowments","window","self","snapFilePath","process","argv","snapModule","exports","Compartment","module","evaluate","readFileSync","invalidExports","Object","keys","filter","snapExport","SNAP_EXPORT_NAMES","includes","length","console","warn","join","setTimeout","exit"],"mappings":"AAAA,uDAAuD;;;;;QAChD;oBAEsB;8BAGK;sBACK;AAIvCA,SAAS;IACPC,eAAe;IACfC,aAAa;IACbC,YAAY;IACZC,YAAY;IACZC,gBAAgB;IAEhB,2EAA2E;IAC3E,yEAAyE;IACzE,kCAAkC;IAClCC,cAAc;AAChB;AAEA;;;;;;CAMC,GACD,SAASC;IACP,MAAMC,aAAaC,IAAAA,4BAAsB;IACzC,OAAO;QACL,GAAGD,UAAU;QACbE,QAAQF;QACRG,MAAMH;IACR;AACF;AAEA,MAAMI,eAAeC,QAAQC,IAAI,CAAC,EAAE;AAEpC,MAAMC,aAAgC;IAAEC,SAAS,CAAC;AAAE;AAEpD,IAAIC,YAAY;IACd,GAAGV,mBAAmB;IACtBW,QAAQH;IACRC,SAASD,WAAWC,OAAO;AAC7B,GAAGG,QAAQ,CAACC,IAAAA,gBAAY,EAACR,cAAc;AAEvC,MAAMS,iBAAiBC,OAAOC,IAAI,CAACR,WAAWC,OAAO,EAAEQ,MAAM,CAC3D,CAACC,aAAe,CAACC,+BAAiB,CAACC,QAAQ,CAACF;AAG9C,IAAIJ,eAAeO,MAAM,GAAG,GAAG;IAC7B,sCAAsC;IACtCC,QAAQC,IAAI,CAAC,CAAC,gCAAgC,EAAET,eAAeU,IAAI,CAAC,MAAM,CAAC;AAC7E;AAEAC,WAAW,IAAMnB,QAAQoB,IAAI,CAAC,IAAI,OAAO,8BAA8B"}
|
|
@@ -0,0 +1,32 @@
|
|
|
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
|
+
HandlerType: function() {
|
|
13
|
+
return HandlerType;
|
|
14
|
+
},
|
|
15
|
+
SNAP_EXPORT_NAMES: function() {
|
|
16
|
+
return SNAP_EXPORT_NAMES;
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
var HandlerType;
|
|
20
|
+
(function(HandlerType) {
|
|
21
|
+
HandlerType["OnRpcRequest"] = 'onRpcRequest';
|
|
22
|
+
HandlerType["OnTransaction"] = 'onTransaction';
|
|
23
|
+
HandlerType["OnCronjob"] = 'onCronjob';
|
|
24
|
+
HandlerType["OnInstall"] = 'onInstall';
|
|
25
|
+
HandlerType["OnUpdate"] = 'onUpdate';
|
|
26
|
+
HandlerType["OnNameLookup"] = 'onNameLookup';
|
|
27
|
+
HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
|
|
28
|
+
HandlerType["OnHomePage"] = 'onHomePage';
|
|
29
|
+
})(HandlerType || (HandlerType = {}));
|
|
30
|
+
const SNAP_EXPORT_NAMES = Object.values(HandlerType);
|
|
31
|
+
|
|
32
|
+
//# sourceMappingURL=handler-types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/handler-types.ts"],"sourcesContent":["export enum HandlerType {\n OnRpcRequest = 'onRpcRequest',\n OnTransaction = 'onTransaction',\n OnCronjob = 'onCronjob',\n OnInstall = 'onInstall',\n OnUpdate = 'onUpdate',\n OnNameLookup = 'onNameLookup',\n OnKeyringRequest = 'onKeyringRequest',\n OnHomePage = 'onHomePage',\n}\n\nexport type SnapHandler = {\n /**\n * The type of handler.\n */\n type: HandlerType;\n\n /**\n * Whether the handler is required, i.e., whether the request will fail if the\n * handler is called, but the snap does not export it.\n *\n * This is primarily used for the lifecycle handlers, which are optional.\n */\n required: boolean;\n\n /**\n * Validate the given snap export. This should return a type guard for the\n * handler type.\n *\n * @param snapExport - The export to validate.\n * @returns Whether the export is valid.\n */\n validator: (snapExport: unknown) => boolean;\n};\n\nexport const SNAP_EXPORT_NAMES = Object.values(HandlerType);\n"],"names":["SNAP_EXPORT_NAMES","HandlerType","OnRpcRequest","OnTransaction","OnCronjob","OnInstall","OnUpdate","OnNameLookup","OnKeyringRequest","OnHomePage","Object","values"],"mappings":";;;;;;;;;;;;;;IAmCaA,iBAAiB;eAAjBA;;;IAnCN;UAAKC,WAAW;IAAXA,YACVC,kBAAe;IADLD,YAEVE,mBAAgB;IAFNF,YAGVG,eAAY;IAHFH,YAIVI,eAAY;IAJFJ,YAKVK,cAAW;IALDL,YAMVM,kBAAe;IANLN,YAOVO,sBAAmB;IAPTP,YAQVQ,gBAAa;GARHR,gBAAAA;AAmCL,MAAMD,oBAAoBU,OAAOC,MAAM,CAACV"}
|
package/dist/cjs/handlers.js
CHANGED
|
@@ -9,71 +9,74 @@ function _export(target, all) {
|
|
|
9
9
|
});
|
|
10
10
|
}
|
|
11
11
|
_export(exports, {
|
|
12
|
-
HandlerType: function() {
|
|
13
|
-
return HandlerType;
|
|
14
|
-
},
|
|
15
12
|
SeverityLevel: function() {
|
|
16
13
|
return SeverityLevel;
|
|
17
14
|
},
|
|
18
15
|
SNAP_EXPORTS: function() {
|
|
19
16
|
return SNAP_EXPORTS;
|
|
17
|
+
},
|
|
18
|
+
OnTransactionResponseStruct: function() {
|
|
19
|
+
return OnTransactionResponseStruct;
|
|
20
|
+
},
|
|
21
|
+
OnHomePageResponseStruct: function() {
|
|
22
|
+
return OnHomePageResponseStruct;
|
|
20
23
|
}
|
|
21
24
|
});
|
|
22
|
-
|
|
23
|
-
(
|
|
24
|
-
|
|
25
|
-
HandlerType["OnTransaction"] = 'onTransaction';
|
|
26
|
-
HandlerType["OnCronjob"] = 'onCronjob';
|
|
27
|
-
HandlerType["OnInstall"] = 'onInstall';
|
|
28
|
-
HandlerType["OnUpdate"] = 'onUpdate';
|
|
29
|
-
HandlerType["OnNameLookup"] = 'onNameLookup';
|
|
30
|
-
HandlerType["OnKeyringRequest"] = 'onKeyringRequest';
|
|
31
|
-
})(HandlerType || (HandlerType = {}));
|
|
25
|
+
const _snapsui = require("@metamask/snaps-ui");
|
|
26
|
+
const _superstruct = require("superstruct");
|
|
27
|
+
const _handlertypes = require("./handler-types");
|
|
32
28
|
const SNAP_EXPORTS = {
|
|
33
|
-
[HandlerType.OnRpcRequest]: {
|
|
34
|
-
type: HandlerType.OnRpcRequest,
|
|
29
|
+
[_handlertypes.HandlerType.OnRpcRequest]: {
|
|
30
|
+
type: _handlertypes.HandlerType.OnRpcRequest,
|
|
35
31
|
required: true,
|
|
36
32
|
validator: (snapExport)=>{
|
|
37
33
|
return typeof snapExport === 'function';
|
|
38
34
|
}
|
|
39
35
|
},
|
|
40
|
-
[HandlerType.OnTransaction]: {
|
|
41
|
-
type: HandlerType.OnTransaction,
|
|
36
|
+
[_handlertypes.HandlerType.OnTransaction]: {
|
|
37
|
+
type: _handlertypes.HandlerType.OnTransaction,
|
|
42
38
|
required: true,
|
|
43
39
|
validator: (snapExport)=>{
|
|
44
40
|
return typeof snapExport === 'function';
|
|
45
41
|
}
|
|
46
42
|
},
|
|
47
|
-
[HandlerType.OnCronjob]: {
|
|
48
|
-
type: HandlerType.OnCronjob,
|
|
43
|
+
[_handlertypes.HandlerType.OnCronjob]: {
|
|
44
|
+
type: _handlertypes.HandlerType.OnCronjob,
|
|
49
45
|
required: true,
|
|
50
46
|
validator: (snapExport)=>{
|
|
51
47
|
return typeof snapExport === 'function';
|
|
52
48
|
}
|
|
53
49
|
},
|
|
54
|
-
[HandlerType.OnNameLookup]: {
|
|
55
|
-
type: HandlerType.OnNameLookup,
|
|
50
|
+
[_handlertypes.HandlerType.OnNameLookup]: {
|
|
51
|
+
type: _handlertypes.HandlerType.OnNameLookup,
|
|
56
52
|
required: true,
|
|
57
53
|
validator: (snapExport)=>{
|
|
58
54
|
return typeof snapExport === 'function';
|
|
59
55
|
}
|
|
60
56
|
},
|
|
61
|
-
[HandlerType.OnInstall]: {
|
|
62
|
-
type: HandlerType.OnInstall,
|
|
57
|
+
[_handlertypes.HandlerType.OnInstall]: {
|
|
58
|
+
type: _handlertypes.HandlerType.OnInstall,
|
|
63
59
|
required: false,
|
|
64
60
|
validator: (snapExport)=>{
|
|
65
61
|
return typeof snapExport === 'function';
|
|
66
62
|
}
|
|
67
63
|
},
|
|
68
|
-
[HandlerType.OnUpdate]: {
|
|
69
|
-
type: HandlerType.OnUpdate,
|
|
64
|
+
[_handlertypes.HandlerType.OnUpdate]: {
|
|
65
|
+
type: _handlertypes.HandlerType.OnUpdate,
|
|
70
66
|
required: false,
|
|
71
67
|
validator: (snapExport)=>{
|
|
72
68
|
return typeof snapExport === 'function';
|
|
73
69
|
}
|
|
74
70
|
},
|
|
75
|
-
[HandlerType.OnKeyringRequest]: {
|
|
76
|
-
type: HandlerType.OnKeyringRequest,
|
|
71
|
+
[_handlertypes.HandlerType.OnKeyringRequest]: {
|
|
72
|
+
type: _handlertypes.HandlerType.OnKeyringRequest,
|
|
73
|
+
required: true,
|
|
74
|
+
validator: (snapExport)=>{
|
|
75
|
+
return typeof snapExport === 'function';
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
[_handlertypes.HandlerType.OnHomePage]: {
|
|
79
|
+
type: _handlertypes.HandlerType.OnHomePage,
|
|
77
80
|
required: true,
|
|
78
81
|
validator: (snapExport)=>{
|
|
79
82
|
return typeof snapExport === 'function';
|
|
@@ -84,5 +87,12 @@ var SeverityLevel;
|
|
|
84
87
|
(function(SeverityLevel) {
|
|
85
88
|
SeverityLevel["Critical"] = 'critical';
|
|
86
89
|
})(SeverityLevel || (SeverityLevel = {}));
|
|
90
|
+
const OnTransactionResponseStruct = (0, _superstruct.object)({
|
|
91
|
+
content: _snapsui.ComponentStruct,
|
|
92
|
+
severity: (0, _superstruct.optional)((0, _superstruct.literal)(SeverityLevel.Critical))
|
|
93
|
+
});
|
|
94
|
+
const OnHomePageResponseStruct = (0, _superstruct.object)({
|
|
95
|
+
content: _snapsui.ComponentStruct
|
|
96
|
+
});
|
|
87
97
|
|
|
88
98
|
//# sourceMappingURL=handlers.js.map
|
package/dist/cjs/handlers.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"sources":["../../src/handlers.ts"],"sourcesContent":["import { ComponentStruct } from '@metamask/snaps-ui';\nimport type { Json, JsonRpcParams, JsonRpcRequest } from '@metamask/utils';\nimport type { Infer } from 'superstruct';\nimport { literal, object, optional } from 'superstruct';\n\nimport type { SnapHandler } from './handler-types';\nimport { HandlerType } from './handler-types';\nimport type { AccountAddress, Caip2ChainId } from './namespace';\n\nexport type SnapRpcHookArgs = {\n origin: string;\n handler: HandlerType;\n request: Record<string, unknown>;\n};\n\nexport const SNAP_EXPORTS = {\n [HandlerType.OnRpcRequest]: {\n type: HandlerType.OnRpcRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnRpcRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnTransaction]: {\n type: HandlerType.OnTransaction,\n required: true,\n validator: (snapExport: unknown): snapExport is OnTransactionHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnCronjob]: {\n type: HandlerType.OnCronjob,\n required: true,\n validator: (snapExport: unknown): snapExport is OnCronjobHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnNameLookup]: {\n type: HandlerType.OnNameLookup,\n required: true,\n validator: (snapExport: unknown): snapExport is OnNameLookupHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnInstall]: {\n type: HandlerType.OnInstall,\n required: false,\n validator: (snapExport: unknown): snapExport is OnInstallHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnUpdate]: {\n type: HandlerType.OnUpdate,\n required: false,\n validator: (snapExport: unknown): snapExport is OnUpdateHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnKeyringRequest]: {\n type: HandlerType.OnKeyringRequest,\n required: true,\n validator: (snapExport: unknown): snapExport is OnKeyringRequestHandler => {\n return typeof snapExport === 'function';\n },\n },\n [HandlerType.OnHomePage]: {\n type: HandlerType.OnHomePage,\n required: true,\n validator: (snapExport: unknown): snapExport is OnHomePageHandler => {\n return typeof snapExport === 'function';\n },\n },\n} as const;\n\n/**\n * The `onRpcRequest` handler. This is called whenever a JSON-RPC request is\n * made to the snap.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of another\n * snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n * @returns The JSON-RPC response. This must be a JSON-serializable value.\n */\nexport type OnRpcRequestHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n }) => Promise<unknown>;\n\n/**\n * Enum used to specify the severity level of content being returned from a transaction insight.\n */\nexport enum SeverityLevel {\n Critical = 'critical',\n}\n\nexport const OnTransactionResponseStruct = object({\n content: ComponentStruct,\n severity: optional(literal(SeverityLevel.Critical)),\n});\n\n/**\n * The response from a snap's `onTransaction` handler.\n *\n * @property content - A custom UI component, that will be shown in MetaMask. Can be created using `@metamask/snaps-ui`.\n *\n * If the snap has no insights about the transaction, this should be `null`.\n */\nexport type OnTransactionResponse = Infer<typeof OnTransactionResponseStruct>;\n\n/**\n * The `onTransaction` handler. This is called whenever a transaction is\n * submitted to the snap. It can return insights about the transaction, which\n * will be displayed to the user.\n *\n * @param args - The request arguments.\n * @param args.transaction - The transaction object.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.transactionOrigin - The origin of the transaction. This is the\n * URL of the dapp that submitted the transaction.\n * @returns Insights about the transaction. See {@link OnTransactionResponse}.\n */\n// TODO: Improve type.\nexport type OnTransactionHandler = (args: {\n transaction: { [key: string]: Json };\n chainId: string;\n transactionOrigin?: string;\n}) => Promise<OnTransactionResponse>;\n\n/**\n * The `onCronjob` handler. This is called on a regular interval, as defined by\n * the snap's manifest.\n *\n * @param args - The request arguments.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnCronjobHandler<Params extends JsonRpcParams = JsonRpcParams> =\n (args: { request: JsonRpcRequest<Params> }) => Promise<unknown>;\n\n/**\n * A handler that can be used for the lifecycle hooks.\n */\nexport type LifecycleEventHandler = (args: {\n request: JsonRpcRequest;\n}) => Promise<unknown>;\n\n/**\n * The `onInstall` handler. This is called after the snap is installed.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnInstallHandler = LifecycleEventHandler;\n\n/**\n * The `onUpdate` handler. This is called after the snap is updated.\n *\n * This type is an alias for {@link LifecycleEventHandler}.\n */\nexport type OnUpdateHandler = LifecycleEventHandler;\n\n/**\n * The `onKeyringRequest` handler. This is called by the MetaMask client for\n * privileged keyring actions.\n *\n * @param args - The request arguments.\n * @param args.origin - The origin of the request. This can be the ID of\n * another snap, or the URL of a dapp.\n * @param args.request - The JSON-RPC request sent to the snap.\n */\nexport type OnKeyringRequestHandler<\n Params extends JsonRpcParams = JsonRpcParams,\n> = (args: {\n origin: string;\n request: JsonRpcRequest<Params>;\n}) => Promise<unknown>;\n\nexport type OnHomePageHandler = () => Promise<OnHomePageResponse>;\n\nexport const OnHomePageResponseStruct = object({\n content: ComponentStruct,\n});\n\nexport type OnHomePageResponse = Infer<typeof OnHomePageResponseStruct>;\n\n/**\n * Utility type for getting the handler function type from a handler type.\n */\nexport type HandlerFunction<Type extends SnapHandler> =\n Type['validator'] extends (snapExport: unknown) => snapExport is infer Handler\n ? Handler\n : never;\n\n/**\n * The response from a snap's `onNameLookup` handler.\n *\n * @property resolvedAddress - The resolved address for a given domain.\n * @property resolvedDomain - The resolved domain for a given address.\n *\n *\n * If the snap has no resolved address/domain from its lookup, this should be `null`.\n */\nexport type OnNameLookupResponse =\n | {\n resolvedAddress: AccountAddress;\n resolvedDomain?: never;\n }\n | { resolvedDomain: string; resolvedAddress?: never }\n | null;\n\nexport type OnNameLookupArgs = {\n chainId: Caip2ChainId;\n} & ({ domain: string; address?: never } | { address: string; domain?: never });\n\n/**\n * The `onNameLookup` handler. This is called whenever content is entered\n * into the send to field for sending assets to an EOA address.\n *\n * @param args - The request arguments.\n * @param args.domain - The human-readable address that is to be resolved.\n * @param args.chainId - The CAIP-2 chain ID of the network the transaction is\n * being submitted to.\n * @param args.address - The address that is to be resolved.\n * @returns Resolved address/domain from the lookup. See {@link OnNameLookupResponse}.\n */\nexport type OnNameLookupHandler = (\n args: OnNameLookupArgs,\n) => Promise<OnNameLookupResponse>;\n\n/**\n * All the function-based handlers that a snap can implement.\n */\nexport type SnapFunctionExports = {\n [Key in keyof typeof SNAP_EXPORTS]?: HandlerFunction<\n (typeof SNAP_EXPORTS)[Key]\n >;\n};\n\n/**\n * All handlers that a snap can implement.\n */\nexport type SnapExports = SnapFunctionExports;\n"],"names":["SNAP_EXPORTS","OnTransactionResponseStruct","OnHomePageResponseStruct","HandlerType","OnRpcRequest","type","required","validator","snapExport","OnTransaction","OnCronjob","OnNameLookup","OnInstall","OnUpdate","OnKeyringRequest","OnHomePage","SeverityLevel","Critical","object","content","ComponentStruct","severity","optional","literal"],"mappings":";;;;;;;;;;;;;;IAeaA,YAAY;eAAZA;;IAkFAC,2BAA2B;eAA3BA;;IAmFAC,wBAAwB;eAAxBA;;;yBApLmB;6BAGU;8BAGd;AASrB,MAAMF,eAAe;IAC1B,CAACG,yBAAW,CAACC,YAAY,CAAC,EAAE;QAC1BC,MAAMF,yBAAW,CAACC,YAAY;QAC9BE,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACM,aAAa,CAAC,EAAE;QAC3BJ,MAAMF,yBAAW,CAACM,aAAa;QAC/BH,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACO,SAAS,CAAC,EAAE;QACvBL,MAAMF,yBAAW,CAACO,SAAS;QAC3BJ,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACQ,YAAY,CAAC,EAAE;QAC1BN,MAAMF,yBAAW,CAACQ,YAAY;QAC9BL,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACS,SAAS,CAAC,EAAE;QACvBP,MAAMF,yBAAW,CAACS,SAAS;QAC3BN,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACU,QAAQ,CAAC,EAAE;QACtBR,MAAMF,yBAAW,CAACU,QAAQ;QAC1BP,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACW,gBAAgB,CAAC,EAAE;QAC9BT,MAAMF,yBAAW,CAACW,gBAAgB;QAClCR,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;IACA,CAACL,yBAAW,CAACY,UAAU,CAAC,EAAE;QACxBV,MAAMF,yBAAW,CAACY,UAAU;QAC5BT,UAAU;QACVC,WAAW,CAACC;YACV,OAAO,OAAOA,eAAe;QAC/B;IACF;AACF;IAqBO;UAAKQ,aAAa;IAAbA,cACVC,cAAW;GADDD,kBAAAA;AAIL,MAAMf,8BAA8BiB,IAAAA,mBAAM,EAAC;IAChDC,SAASC,wBAAe;IACxBC,UAAUC,IAAAA,qBAAQ,EAACC,IAAAA,oBAAO,EAACP,cAAcC,QAAQ;AACnD;AAgFO,MAAMf,2BAA2BgB,IAAAA,mBAAM,EAAC;IAC7CC,SAASC,wBAAe;AAC1B"}
|
|
@@ -13,9 +13,11 @@ _export_star(require("./entropy"), exports);
|
|
|
13
13
|
_export_star(require("./enum"), exports);
|
|
14
14
|
_export_star(require("./errors"), exports);
|
|
15
15
|
_export_star(require("./handlers"), exports);
|
|
16
|
+
_export_star(require("./handler-types"), exports);
|
|
16
17
|
_export_star(require("./iframe"), exports);
|
|
17
18
|
_export_star(require("./json"), exports);
|
|
18
19
|
_export_star(require("./json-rpc"), exports);
|
|
20
|
+
_export_star(require("./localization"), exports);
|
|
19
21
|
_export_star(require("./logging"), exports);
|
|
20
22
|
_export_star(require("./manifest/index.browser"), exports);
|
|
21
23
|
_export_star(require("./namespace"), 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 './iframe';\nexport * from './json';\nexport * from './json-rpc';\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 './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"}
|
|
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 './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"}
|
|
@@ -5,6 +5,7 @@ Object.defineProperty(exports, "__esModule", {
|
|
|
5
5
|
});
|
|
6
6
|
_export_star(require("./errors"), exports);
|
|
7
7
|
_export_star(require("./handlers"), exports);
|
|
8
|
+
_export_star(require("./handler-types"), exports);
|
|
8
9
|
_export_star(require("./logging"), exports);
|
|
9
10
|
_export_star(require("./namespace"), exports);
|
|
10
11
|
_export_star(require("./types"), exports);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/index.executionenv.ts"],"sourcesContent":["// Special entrypoint for execution environments for bundle sizing reasons\nexport * from './errors';\nexport * from './handlers';\nexport * from './logging';\nexport * from './namespace';\nexport * from './types';\n"],"names":[],"mappings":"AAAA,0EAA0E;;;;;qBAC5D;qBACA;qBACA;qBACA;qBACA"}
|
|
1
|
+
{"version":3,"sources":["../../src/index.executionenv.ts"],"sourcesContent":["// Special entrypoint for execution environments for bundle sizing reasons\nexport * from './errors';\nexport * from './handlers';\nexport * from './handler-types';\nexport * from './logging';\nexport * from './namespace';\nexport * from './types';\n"],"names":[],"mappings":"AAAA,0EAA0E;;;;;qBAC5D;qBACA;qBACA;qBACA;qBACA;qBACA"}
|
package/dist/cjs/index.js
CHANGED
|
@@ -15,9 +15,11 @@ _export_star(require("./eval"), exports);
|
|
|
15
15
|
_export_star(require("./errors"), exports);
|
|
16
16
|
_export_star(require("./fs"), exports);
|
|
17
17
|
_export_star(require("./handlers"), exports);
|
|
18
|
+
_export_star(require("./handler-types"), exports);
|
|
18
19
|
_export_star(require("./iframe"), exports);
|
|
19
20
|
_export_star(require("./json"), exports);
|
|
20
21
|
_export_star(require("./json-rpc"), exports);
|
|
22
|
+
_export_star(require("./localization"), exports);
|
|
21
23
|
_export_star(require("./logging"), exports);
|
|
22
24
|
_export_star(require("./manifest"), exports);
|
|
23
25
|
_export_star(require("./mock"), exports);
|
package/dist/cjs/index.js.map
CHANGED
|
@@ -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 './iframe';\nexport * from './json';\nexport * from './json-rpc';\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 './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"}
|
|
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 './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"}
|
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+
LOCALIZABLE_FIELDS: function() {
|
|
13
|
+
return LOCALIZABLE_FIELDS;
|
|
14
|
+
},
|
|
15
|
+
LocalizationFileStruct: function() {
|
|
16
|
+
return LocalizationFileStruct;
|
|
17
|
+
},
|
|
18
|
+
getValidatedLocalizationFiles: function() {
|
|
19
|
+
return getValidatedLocalizationFiles;
|
|
20
|
+
},
|
|
21
|
+
getLocalizationFile: function() {
|
|
22
|
+
return getLocalizationFile;
|
|
23
|
+
},
|
|
24
|
+
TRANSLATION_REGEX: function() {
|
|
25
|
+
return TRANSLATION_REGEX;
|
|
26
|
+
},
|
|
27
|
+
translate: function() {
|
|
28
|
+
return translate;
|
|
29
|
+
},
|
|
30
|
+
getLocalizedSnapManifest: function() {
|
|
31
|
+
return getLocalizedSnapManifest;
|
|
32
|
+
},
|
|
33
|
+
validateSnapManifestLocalizations: function() {
|
|
34
|
+
return validateSnapManifestLocalizations;
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
const _superstruct = require("superstruct");
|
|
38
|
+
const _errors = require("./errors");
|
|
39
|
+
const _json = require("./json");
|
|
40
|
+
const LOCALIZABLE_FIELDS = [
|
|
41
|
+
'description',
|
|
42
|
+
'proposedName'
|
|
43
|
+
];
|
|
44
|
+
const LocalizationFileStruct = (0, _superstruct.object)({
|
|
45
|
+
locale: (0, _superstruct.string)(),
|
|
46
|
+
messages: (0, _superstruct.record)((0, _superstruct.string)(), (0, _superstruct.object)({
|
|
47
|
+
message: (0, _superstruct.string)(),
|
|
48
|
+
description: (0, _superstruct.optional)((0, _superstruct.string)())
|
|
49
|
+
}))
|
|
50
|
+
});
|
|
51
|
+
function getValidatedLocalizationFiles(localizationFiles) {
|
|
52
|
+
for (const file of localizationFiles){
|
|
53
|
+
try {
|
|
54
|
+
file.result = (0, _superstruct.create)((0, _json.parseJson)(file.toString()), LocalizationFileStruct);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (error instanceof _superstruct.StructError) {
|
|
57
|
+
throw new Error(`Failed to validate localization file "${file.path}": ${error.message}.`);
|
|
58
|
+
}
|
|
59
|
+
if (error instanceof SyntaxError) {
|
|
60
|
+
throw new Error(`Failed to parse localization file "${file.path}" as JSON.`);
|
|
61
|
+
}
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return localizationFiles;
|
|
66
|
+
}
|
|
67
|
+
function getLocalizationFile(locale, localizationFiles) {
|
|
68
|
+
const file = localizationFiles.find((localizationFile)=>localizationFile.locale === locale);
|
|
69
|
+
if (!file) {
|
|
70
|
+
return localizationFiles.find((localizationFile)=>localizationFile.locale === 'en');
|
|
71
|
+
}
|
|
72
|
+
return file;
|
|
73
|
+
}
|
|
74
|
+
const TRANSLATION_REGEX = /\{\{\s?([a-zA-Z0-9-_\s]+)\s?\}\}/gu;
|
|
75
|
+
function translate(value, file) {
|
|
76
|
+
const matches = value.matchAll(TRANSLATION_REGEX);
|
|
77
|
+
const array = Array.from(matches);
|
|
78
|
+
return array.reduce((result, [match, key])=>{
|
|
79
|
+
if (!file) {
|
|
80
|
+
throw new Error(`Failed to translate "${value}": No localization file found.`);
|
|
81
|
+
}
|
|
82
|
+
const translation = file.messages[key.trim()];
|
|
83
|
+
if (!translation) {
|
|
84
|
+
throw new Error(`Failed to translate "${value}": No translation found for "${key.trim()}" in "${file.locale}" file.`);
|
|
85
|
+
}
|
|
86
|
+
return result.replace(match, translation.message);
|
|
87
|
+
}, value);
|
|
88
|
+
}
|
|
89
|
+
function getLocalizedSnapManifest(snapManifest, locale, localizationFiles) {
|
|
90
|
+
const file = getLocalizationFile(locale, localizationFiles);
|
|
91
|
+
return LOCALIZABLE_FIELDS.reduce((manifest, field)=>{
|
|
92
|
+
const translation = translate(manifest[field], file);
|
|
93
|
+
return {
|
|
94
|
+
...manifest,
|
|
95
|
+
[field]: translation
|
|
96
|
+
};
|
|
97
|
+
}, snapManifest);
|
|
98
|
+
}
|
|
99
|
+
function validateSnapManifestLocalizations(snapManifest, localizationFiles) {
|
|
100
|
+
try {
|
|
101
|
+
// `translate` throws if the manifest cannot be localized, so we just attempt
|
|
102
|
+
// to translate the manifest using all localization files.
|
|
103
|
+
localizationFiles.filter((file)=>file.locale !== 'en').forEach((file)=>{
|
|
104
|
+
getLocalizedSnapManifest(snapManifest, file.locale, localizationFiles);
|
|
105
|
+
});
|
|
106
|
+
// The manifest must be localizable in English.
|
|
107
|
+
getLocalizedSnapManifest(snapManifest, 'en', localizationFiles);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw new Error(`Failed to localize Snap manifest: ${(0, _errors.getErrorMessage)(error)}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=localization.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/localization.ts"],"sourcesContent":["import type { Infer } from 'superstruct';\nimport {\n create,\n object,\n optional,\n record,\n string,\n StructError,\n} from 'superstruct';\n\nimport { getErrorMessage } from './errors';\nimport { parseJson } from './json';\nimport type { SnapManifest } from './manifest';\nimport type { VirtualFile } from './virtual-file';\n\nexport const LOCALIZABLE_FIELDS = ['description', 'proposedName'] as const;\n\nexport const LocalizationFileStruct = object({\n locale: string(),\n messages: record(\n string(),\n object({\n message: string(),\n description: optional(string()),\n }),\n ),\n});\n\nexport type LocalizationFile = Infer<typeof LocalizationFileStruct>;\n\n/**\n * Validate a list of localization files.\n *\n * @param localizationFiles - The localization files to validate.\n * @returns The validated localization files.\n * @throws If any of the files are considered invalid.\n */\nexport function getValidatedLocalizationFiles(\n localizationFiles: VirtualFile[],\n): VirtualFile<LocalizationFile>[] {\n for (const file of localizationFiles) {\n try {\n file.result = create(parseJson(file.toString()), LocalizationFileStruct);\n } catch (error) {\n if (error instanceof StructError) {\n throw new Error(\n `Failed to validate localization file \"${file.path}\": ${error.message}.`,\n );\n }\n\n if (error instanceof SyntaxError) {\n throw new Error(\n `Failed to parse localization file \"${file.path}\" as JSON.`,\n );\n }\n\n throw error;\n }\n }\n\n return localizationFiles as VirtualFile<LocalizationFile>[];\n}\n\n/**\n * Get the localization file for a given locale. If the locale is not found,\n * the English localization file will be returned.\n *\n * @param locale - The locale to use.\n * @param localizationFiles - The localization files to use.\n * @returns The localization file, or `undefined` if no localization file was\n * found.\n */\nexport function getLocalizationFile(\n locale: string,\n localizationFiles: LocalizationFile[],\n) {\n const file = localizationFiles.find(\n (localizationFile) => localizationFile.locale === locale,\n );\n\n if (!file) {\n return localizationFiles.find(\n (localizationFile) => localizationFile.locale === 'en',\n );\n }\n\n return file;\n}\n\nexport const TRANSLATION_REGEX = /\\{\\{\\s?([a-zA-Z0-9-_\\s]+)\\s?\\}\\}/gu;\n\n/**\n * Translate a string using a localization file. This will replace all instances\n * of `{{key}}` with the localized version of `key`.\n *\n * @param value - The string to translate.\n * @param file - The localization file to use, or `undefined` if no localization\n * file was found.\n * @returns The translated string.\n * @throws If the string contains a key that is not present in the localization\n * file, or if no localization file was found.\n */\nexport function translate(value: string, file: LocalizationFile | undefined) {\n const matches = value.matchAll(TRANSLATION_REGEX);\n const array = Array.from(matches);\n\n return array.reduce<string>((result, [match, key]) => {\n if (!file) {\n throw new Error(\n `Failed to translate \"${value}\": No localization file found.`,\n );\n }\n\n const translation = file.messages[key.trim()];\n if (!translation) {\n throw new Error(\n `Failed to translate \"${value}\": No translation found for \"${key.trim()}\" in \"${\n file.locale\n }\" file.`,\n );\n }\n\n return result.replace(match, translation.message);\n }, value);\n}\n\n/**\n * Get the localized Snap manifest for a given locale. This will replace all\n * localized strings in the manifest with the localized version.\n *\n * @param snapManifest - The Snap manifest to localize.\n * @param locale - The locale to use.\n * @param localizationFiles - The localization files to use.\n * @returns The localized Snap manifest.\n */\nexport function getLocalizedSnapManifest(\n snapManifest: SnapManifest,\n locale: string,\n localizationFiles: LocalizationFile[],\n) {\n const file = getLocalizationFile(locale, localizationFiles);\n\n return LOCALIZABLE_FIELDS.reduce((manifest, field) => {\n const translation = translate(manifest[field], file);\n return {\n ...manifest,\n [field]: translation,\n };\n }, snapManifest);\n}\n\n/**\n * Validate the localization files for a Snap manifest.\n *\n * @param snapManifest - The Snap manifest to validate.\n * @param localizationFiles - The localization files to validate.\n * @throws If the manifest cannot be localized.\n */\nexport function validateSnapManifestLocalizations(\n snapManifest: SnapManifest,\n localizationFiles: LocalizationFile[],\n) {\n try {\n // `translate` throws if the manifest cannot be localized, so we just attempt\n // to translate the manifest using all localization files.\n localizationFiles\n .filter((file) => file.locale !== 'en')\n .forEach((file) => {\n getLocalizedSnapManifest(snapManifest, file.locale, localizationFiles);\n });\n\n // The manifest must be localizable in English.\n getLocalizedSnapManifest(snapManifest, 'en', localizationFiles);\n } catch (error) {\n throw new Error(\n `Failed to localize Snap manifest: ${getErrorMessage(error)}`,\n );\n }\n}\n"],"names":["LOCALIZABLE_FIELDS","LocalizationFileStruct","getValidatedLocalizationFiles","getLocalizationFile","TRANSLATION_REGEX","translate","getLocalizedSnapManifest","validateSnapManifestLocalizations","object","locale","string","messages","record","message","description","optional","localizationFiles","file","result","create","parseJson","toString","error","StructError","Error","path","SyntaxError","find","localizationFile","value","matches","matchAll","array","Array","from","reduce","match","key","translation","trim","replace","snapManifest","manifest","field","filter","forEach","getErrorMessage"],"mappings":"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"}
|
|
@@ -21,8 +21,11 @@ _export(exports, {
|
|
|
21
21
|
getSnapIcon: function() {
|
|
22
22
|
return getSnapIcon;
|
|
23
23
|
},
|
|
24
|
-
|
|
25
|
-
return
|
|
24
|
+
getSnapFilePaths: function() {
|
|
25
|
+
return getSnapFilePaths;
|
|
26
|
+
},
|
|
27
|
+
getSnapFiles: function() {
|
|
28
|
+
return getSnapFiles;
|
|
26
29
|
},
|
|
27
30
|
getWritableManifest: function() {
|
|
28
31
|
return getWritableManifest;
|
|
@@ -65,12 +68,15 @@ async function checkManifest(basePath, writeManifest = true, sourceCode, writeFi
|
|
|
65
68
|
const manifestFile = await (0, _fs1.readJsonFile)(manifestPath);
|
|
66
69
|
const unvalidatedManifest = manifestFile.result;
|
|
67
70
|
const packageFile = await (0, _fs1.readJsonFile)(_path.default.join(basePath, _types.NpmSnapFileNames.PackageJson));
|
|
71
|
+
const auxiliaryFilePaths = getSnapFilePaths(unvalidatedManifest, (manifest)=>manifest?.source?.files);
|
|
72
|
+
const localizationFilePaths = getSnapFilePaths(unvalidatedManifest, (manifest)=>manifest?.source?.locales);
|
|
68
73
|
const snapFiles = {
|
|
69
74
|
manifest: manifestFile,
|
|
70
75
|
packageJson: packageFile,
|
|
71
76
|
sourceCode: await getSnapSourceCode(basePath, unvalidatedManifest, sourceCode),
|
|
72
77
|
svgIcon: await getSnapIcon(basePath, unvalidatedManifest),
|
|
73
|
-
auxiliaryFiles: await
|
|
78
|
+
auxiliaryFiles: await getSnapFiles(basePath, auxiliaryFilePaths) ?? [],
|
|
79
|
+
localizationFiles: await getSnapFiles(basePath, localizationFilePaths) ?? []
|
|
74
80
|
};
|
|
75
81
|
let manifest;
|
|
76
82
|
try {
|
|
@@ -204,16 +210,23 @@ async function getSnapIcon(basePath, manifest) {
|
|
|
204
210
|
throw new Error(`Failed to read snap icon file: ${(0, _errors.getErrorMessage)(error)}`);
|
|
205
211
|
}
|
|
206
212
|
}
|
|
207
|
-
|
|
213
|
+
function getSnapFilePaths(manifest, selector) {
|
|
208
214
|
if (!(0, _utils.isPlainObject)(manifest)) {
|
|
209
215
|
return undefined;
|
|
210
216
|
}
|
|
211
|
-
const
|
|
212
|
-
|
|
217
|
+
const snapManifest = manifest;
|
|
218
|
+
const paths = selector(snapManifest);
|
|
219
|
+
if (!Array.isArray(paths)) {
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
return paths;
|
|
223
|
+
}
|
|
224
|
+
async function getSnapFiles(basePath, paths) {
|
|
225
|
+
if (!paths) {
|
|
213
226
|
return undefined;
|
|
214
227
|
}
|
|
215
228
|
try {
|
|
216
|
-
return await Promise.all(
|
|
229
|
+
return await Promise.all(paths.map(async (filePath)=>(0, _virtualfile.readVirtualFile)(_path.default.join(basePath, filePath), 'utf8')));
|
|
217
230
|
} catch (error) {
|
|
218
231
|
throw new Error(`Failed to read snap files: ${(0, _errors.getErrorMessage)(error)}`);
|
|
219
232
|
}
|
|
@@ -230,7 +243,7 @@ function getWritableManifest(manifest) {
|
|
|
230
243
|
}), {});
|
|
231
244
|
return writableManifest;
|
|
232
245
|
}
|
|
233
|
-
function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles }) {
|
|
246
|
+
function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, auxiliaryFiles, localizationFiles }) {
|
|
234
247
|
const packageJsonName = packageJson.result.name;
|
|
235
248
|
const packageJsonVersion = packageJson.result.version;
|
|
236
249
|
const packageJsonRepository = packageJson.result.repository;
|
|
@@ -252,7 +265,8 @@ function validateNpmSnapManifest({ manifest, packageJson, sourceCode, svgIcon, a
|
|
|
252
265
|
manifest,
|
|
253
266
|
sourceCode,
|
|
254
267
|
svgIcon,
|
|
255
|
-
auxiliaryFiles
|
|
268
|
+
auxiliaryFiles,
|
|
269
|
+
localizationFiles
|
|
256
270
|
}, `"${_types.NpmSnapFileNames.Manifest}" "shasum" field does not match computed shasum.`);
|
|
257
271
|
}
|
|
258
272
|
|