@metamask/snaps-utils 0.24.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/LICENSE +15 -0
- package/README.md +3 -0
- package/dist/caveats.d.ts +22 -0
- package/dist/caveats.js +27 -0
- package/dist/caveats.js.map +1 -0
- package/dist/cronjob.d.ts +89 -0
- package/dist/cronjob.js +74 -0
- package/dist/cronjob.js.map +1 -0
- package/dist/deep-clone.d.ts +1 -0
- package/dist/deep-clone.js +9 -0
- package/dist/deep-clone.js.map +1 -0
- package/dist/default-endowments.d.ts +4 -0
- package/dist/default-endowments.js +43 -0
- package/dist/default-endowments.js.map +1 -0
- package/dist/eval-worker.d.ts +1 -0
- package/dist/eval-worker.js +32 -0
- package/dist/eval-worker.js.map +1 -0
- package/dist/eval.d.ts +8 -0
- package/dist/eval.js +28 -0
- package/dist/eval.js.map +1 -0
- package/dist/flatMap.d.ts +22 -0
- package/dist/flatMap.js +38 -0
- package/dist/flatMap.js.map +1 -0
- package/dist/fs.d.ts +69 -0
- package/dist/fs.js +144 -0
- package/dist/fs.js.map +1 -0
- package/dist/index.browser.d.ts +13 -0
- package/dist/index.browser.js +30 -0
- package/dist/index.browser.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +36 -0
- package/dist/index.js.map +1 -0
- package/dist/json-rpc.d.ts +10 -0
- package/dist/json-rpc.js +22 -0
- package/dist/json-rpc.js.map +1 -0
- package/dist/manifest/index.browser.d.ts +1 -0
- package/dist/manifest/index.browser.js +18 -0
- package/dist/manifest/index.browser.js.map +1 -0
- package/dist/manifest/index.d.ts +2 -0
- package/dist/manifest/index.js +19 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/manifest/manifest.d.ts +75 -0
- package/dist/manifest/manifest.js +237 -0
- package/dist/manifest/manifest.js.map +1 -0
- package/dist/manifest/validation.d.ts +483 -0
- package/dist/manifest/validation.js +142 -0
- package/dist/manifest/validation.js.map +1 -0
- package/dist/mock.d.ts +14 -0
- package/dist/mock.js +107 -0
- package/dist/mock.js.map +1 -0
- package/dist/namespace.d.ts +275 -0
- package/dist/namespace.js +223 -0
- package/dist/namespace.js.map +1 -0
- package/dist/notification.d.ts +66 -0
- package/dist/notification.js +58 -0
- package/dist/notification.js.map +1 -0
- package/dist/npm.d.ts +20 -0
- package/dist/npm.js +73 -0
- package/dist/npm.js.map +1 -0
- package/dist/object.d.ts +8 -0
- package/dist/object.js +15 -0
- package/dist/object.js.map +1 -0
- package/dist/post-process.d.ts +71 -0
- package/dist/post-process.js +321 -0
- package/dist/post-process.js.map +1 -0
- package/dist/snaps.d.ts +165 -0
- package/dist/snaps.js +123 -0
- package/dist/snaps.js.map +1 -0
- package/dist/types.d.ts +107 -0
- package/dist/types.js +82 -0
- package/dist/types.js.map +1 -0
- package/dist/url.d.ts +7 -0
- package/dist/url.js +19 -0
- package/dist/url.js.map +1 -0
- package/dist/versions.d.ts +44 -0
- package/dist/versions.js +77 -0
- package/dist/versions.js.map +1 -0
- package/package.json +100 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __rest = (this && this.__rest) || function (s, e) {
|
|
3
|
+
var t = {};
|
|
4
|
+
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
|
|
5
|
+
t[p] = s[p];
|
|
6
|
+
if (s != null && typeof Object.getOwnPropertySymbols === "function")
|
|
7
|
+
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
|
|
8
|
+
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
|
|
9
|
+
t[p[i]] = s[p[i]];
|
|
10
|
+
}
|
|
11
|
+
return t;
|
|
12
|
+
};
|
|
13
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.validateNpmSnapManifest = exports.getWritableManifest = exports.getSnapSourceCode = exports.fixManifest = exports.checkManifest = void 0;
|
|
18
|
+
const fs_1 = require("fs");
|
|
19
|
+
const path_1 = __importDefault(require("path"));
|
|
20
|
+
const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
|
|
21
|
+
const deep_clone_1 = require("../deep-clone");
|
|
22
|
+
const fs_2 = require("../fs");
|
|
23
|
+
const npm_1 = require("../npm");
|
|
24
|
+
const snaps_1 = require("../snaps");
|
|
25
|
+
const types_1 = require("../types");
|
|
26
|
+
const MANIFEST_SORT_ORDER = {
|
|
27
|
+
version: 1,
|
|
28
|
+
description: 2,
|
|
29
|
+
proposedName: 3,
|
|
30
|
+
repository: 4,
|
|
31
|
+
source: 5,
|
|
32
|
+
initialPermissions: 6,
|
|
33
|
+
manifestVersion: 7,
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* Validates a snap.manifest.json file. Attempts to fix the manifest and write
|
|
37
|
+
* the fixed version to disk if `writeManifest` is true. Throws if validation
|
|
38
|
+
* fails.
|
|
39
|
+
*
|
|
40
|
+
* @param basePath - The path to the folder with the manifest files.
|
|
41
|
+
* @param writeManifest - Whether to write the fixed manifest to disk.
|
|
42
|
+
* @param sourceCode - The source code of the Snap.
|
|
43
|
+
* @returns Whether the manifest was updated, and an array of warnings that
|
|
44
|
+
* were encountered during processing of the manifest files.
|
|
45
|
+
*/
|
|
46
|
+
async function checkManifest(basePath, writeManifest = true, sourceCode) {
|
|
47
|
+
var _a, _b, _c;
|
|
48
|
+
const warnings = [];
|
|
49
|
+
const errors = [];
|
|
50
|
+
let updated = false;
|
|
51
|
+
const unvalidatedManifest = await (0, fs_2.readSnapJsonFile)(basePath, types_1.NpmSnapFileNames.Manifest);
|
|
52
|
+
const iconPath = unvalidatedManifest && typeof unvalidatedManifest === 'object'
|
|
53
|
+
? /* istanbul ignore next */
|
|
54
|
+
(_c = (_b = (_a = unvalidatedManifest.source) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.npm) === null || _c === void 0 ? void 0 : _c.iconPath
|
|
55
|
+
: /* istanbul ignore next */
|
|
56
|
+
undefined;
|
|
57
|
+
const snapFiles = {
|
|
58
|
+
manifest: unvalidatedManifest,
|
|
59
|
+
packageJson: await (0, fs_2.readSnapJsonFile)(basePath, types_1.NpmSnapFileNames.PackageJson),
|
|
60
|
+
sourceCode: sourceCode !== null && sourceCode !== void 0 ? sourceCode : (await getSnapSourceCode(basePath, unvalidatedManifest)),
|
|
61
|
+
svgIcon: iconPath &&
|
|
62
|
+
(await fs_1.promises.readFile(path_1.default.join(basePath, iconPath), 'utf8')),
|
|
63
|
+
};
|
|
64
|
+
let manifest;
|
|
65
|
+
try {
|
|
66
|
+
({ manifest } = (0, npm_1.validateNpmSnap)(snapFiles));
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (error instanceof snaps_1.ProgrammaticallyFixableSnapError) {
|
|
70
|
+
errors.push(error.message);
|
|
71
|
+
// If we get here, the files at least have the correct shape.
|
|
72
|
+
const partiallyValidatedFiles = snapFiles;
|
|
73
|
+
let isInvalid = true;
|
|
74
|
+
let currentError = error;
|
|
75
|
+
const maxAttempts = Object.keys(types_1.SnapValidationFailureReason).length;
|
|
76
|
+
// Attempt to fix all fixable validation failure reasons. All such reasons
|
|
77
|
+
// are enumerated by the `SnapValidationFailureReason` enum, so we only
|
|
78
|
+
// attempt to fix the manifest the same amount of times as there are
|
|
79
|
+
// reasons in the enum.
|
|
80
|
+
for (let attempts = 1; isInvalid && attempts <= maxAttempts; attempts++) {
|
|
81
|
+
manifest = fixManifest(manifest
|
|
82
|
+
? Object.assign(Object.assign({}, partiallyValidatedFiles), { manifest }) : partiallyValidatedFiles, currentError);
|
|
83
|
+
try {
|
|
84
|
+
validateNpmSnapManifest(Object.assign(Object.assign({}, partiallyValidatedFiles), { manifest }));
|
|
85
|
+
isInvalid = false;
|
|
86
|
+
}
|
|
87
|
+
catch (nextValidationError) {
|
|
88
|
+
currentError = nextValidationError;
|
|
89
|
+
/* istanbul ignore next: this should be impossible */
|
|
90
|
+
if (!(nextValidationError instanceof snaps_1.ProgrammaticallyFixableSnapError) ||
|
|
91
|
+
(attempts === maxAttempts && !isInvalid)) {
|
|
92
|
+
throw new Error(`Internal error: Failed to fix manifest. This is a bug, please report it. Reason:\n${error.message}`);
|
|
93
|
+
}
|
|
94
|
+
errors.push(currentError.message);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
updated = true;
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// TypeScript doesn't see that the 'manifest' variable must be of type
|
|
104
|
+
// SnapManifest at this point, so we cast it.
|
|
105
|
+
const validatedManifest = manifest;
|
|
106
|
+
// Check presence of recommended keys
|
|
107
|
+
const recommendedFields = ['repository'];
|
|
108
|
+
const missingRecommendedFields = recommendedFields.filter((key) => !validatedManifest[key]);
|
|
109
|
+
if (missingRecommendedFields.length > 0) {
|
|
110
|
+
warnings.push(`Missing recommended package.json properties:\n${missingRecommendedFields.reduce((allMissing, currentField) => {
|
|
111
|
+
return `${allMissing}\t${currentField}\n`;
|
|
112
|
+
}, '')}`);
|
|
113
|
+
}
|
|
114
|
+
if (writeManifest) {
|
|
115
|
+
try {
|
|
116
|
+
await fs_1.promises.writeFile(path_1.default.join(basePath, types_1.NpmSnapFileNames.Manifest), `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\n`);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
// Note: This error isn't pushed to the errors array, because it's not an
|
|
120
|
+
// error in the manifest itself.
|
|
121
|
+
throw new Error(`Failed to update snap.manifest.json: ${error.message}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return { manifest: validatedManifest, updated, warnings, errors };
|
|
125
|
+
}
|
|
126
|
+
exports.checkManifest = checkManifest;
|
|
127
|
+
/**
|
|
128
|
+
* Given the relevant Snap files (manifest, `package.json`, and bundle) and a
|
|
129
|
+
* Snap manifest validation error, fixes the fault in the manifest that caused
|
|
130
|
+
* the error.
|
|
131
|
+
*
|
|
132
|
+
* @param snapFiles - The contents of all Snap files.
|
|
133
|
+
* @param error - The {@link ProgrammaticallyFixableSnapError} that was thrown.
|
|
134
|
+
* @returns A copy of the manifest file where the cause of the error is fixed.
|
|
135
|
+
*/
|
|
136
|
+
function fixManifest(snapFiles, error) {
|
|
137
|
+
const { manifest, packageJson, sourceCode } = snapFiles;
|
|
138
|
+
const manifestCopy = (0, deep_clone_1.deepClone)(manifest);
|
|
139
|
+
switch (error.reason) {
|
|
140
|
+
case types_1.SnapValidationFailureReason.NameMismatch:
|
|
141
|
+
manifestCopy.source.location.npm.packageName = packageJson.name;
|
|
142
|
+
break;
|
|
143
|
+
case types_1.SnapValidationFailureReason.VersionMismatch:
|
|
144
|
+
manifestCopy.version = packageJson.version;
|
|
145
|
+
break;
|
|
146
|
+
case types_1.SnapValidationFailureReason.RepositoryMismatch:
|
|
147
|
+
manifestCopy.repository = packageJson.repository
|
|
148
|
+
? (0, deep_clone_1.deepClone)(packageJson.repository)
|
|
149
|
+
: undefined;
|
|
150
|
+
break;
|
|
151
|
+
case types_1.SnapValidationFailureReason.ShasumMismatch:
|
|
152
|
+
manifestCopy.source.shasum = (0, snaps_1.getSnapSourceShasum)(sourceCode);
|
|
153
|
+
break;
|
|
154
|
+
/* istanbul ignore next */
|
|
155
|
+
default: {
|
|
156
|
+
const failureReason = error.reason;
|
|
157
|
+
throw new Error(`Unrecognized validation failure reason: '${failureReason}'`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
return manifestCopy;
|
|
161
|
+
}
|
|
162
|
+
exports.fixManifest = fixManifest;
|
|
163
|
+
/**
|
|
164
|
+
* Given an unvalidated Snap manifest, attempts to extract the location of the
|
|
165
|
+
* bundle source file location and read the file.
|
|
166
|
+
*
|
|
167
|
+
* @param basePath - The path to the folder with the manifest files.
|
|
168
|
+
* @param manifest - The unvalidated Snap manifest file contents.
|
|
169
|
+
* @returns The contents of the bundle file, if any.
|
|
170
|
+
*/
|
|
171
|
+
async function getSnapSourceCode(basePath, manifest) {
|
|
172
|
+
var _a, _b, _c;
|
|
173
|
+
if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {
|
|
174
|
+
const sourceFilePath = (_c = (_b = (_a = manifest.source) === null || _a === void 0 ? void 0 : _a.location) === null || _b === void 0 ? void 0 : _b.npm) === null || _c === void 0 ? void 0 : _c.filePath;
|
|
175
|
+
try {
|
|
176
|
+
return sourceFilePath
|
|
177
|
+
? await fs_1.promises.readFile(path_1.default.join(basePath, sourceFilePath), 'utf8')
|
|
178
|
+
: undefined;
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
throw new Error(`Failed to read Snap bundle file: ${error.message}`);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
exports.getSnapSourceCode = getSnapSourceCode;
|
|
187
|
+
/**
|
|
188
|
+
* Sorts the given manifest in our preferred sort order and removes the
|
|
189
|
+
* `repository` field if it is falsy (it may be `null`).
|
|
190
|
+
*
|
|
191
|
+
* @param manifest - The manifest to sort and modify.
|
|
192
|
+
* @returns The disk-ready manifest.
|
|
193
|
+
*/
|
|
194
|
+
function getWritableManifest(manifest) {
|
|
195
|
+
const { repository } = manifest, remaining = __rest(manifest, ["repository"]);
|
|
196
|
+
const keys = Object.keys(repository ? Object.assign(Object.assign({}, remaining), { repository }) : remaining);
|
|
197
|
+
return keys
|
|
198
|
+
.sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])
|
|
199
|
+
.reduce((result, key) => (Object.assign(Object.assign({}, result), { [key]: manifest[key] })), {});
|
|
200
|
+
}
|
|
201
|
+
exports.getWritableManifest = getWritableManifest;
|
|
202
|
+
/**
|
|
203
|
+
* Validates the fields of an npm Snap manifest that has already passed JSON
|
|
204
|
+
* Schema validation.
|
|
205
|
+
*
|
|
206
|
+
* @param snapFiles - The relevant snap files to validate.
|
|
207
|
+
* @param snapFiles.manifest - The npm Snap manifest to validate.
|
|
208
|
+
* @param snapFiles.packageJson - The npm Snap's `package.json`.
|
|
209
|
+
* @param snapFiles.sourceCode - The Snap's source code.
|
|
210
|
+
* @returns A tuple containing the validated snap manifest, snap source code,
|
|
211
|
+
* and `package.json`.
|
|
212
|
+
*/
|
|
213
|
+
function validateNpmSnapManifest({ manifest, packageJson, sourceCode, }) {
|
|
214
|
+
const packageJsonName = packageJson.name;
|
|
215
|
+
const packageJsonVersion = packageJson.version;
|
|
216
|
+
const packageJsonRepository = packageJson.repository;
|
|
217
|
+
const manifestPackageName = manifest.source.location.npm.packageName;
|
|
218
|
+
const manifestPackageVersion = manifest.version;
|
|
219
|
+
const manifestRepository = manifest.repository;
|
|
220
|
+
if (packageJsonName !== manifestPackageName) {
|
|
221
|
+
throw new snaps_1.ProgrammaticallyFixableSnapError(`"${types_1.NpmSnapFileNames.Manifest}" npm package name ("${manifestPackageName}") does not match the "${types_1.NpmSnapFileNames.PackageJson}" "name" field ("${packageJsonName}").`, types_1.SnapValidationFailureReason.NameMismatch);
|
|
222
|
+
}
|
|
223
|
+
if (packageJsonVersion !== manifestPackageVersion) {
|
|
224
|
+
throw new snaps_1.ProgrammaticallyFixableSnapError(`"${types_1.NpmSnapFileNames.Manifest}" npm package version ("${manifestPackageVersion}") does not match the "${types_1.NpmSnapFileNames.PackageJson}" "version" field ("${packageJsonVersion}").`, types_1.SnapValidationFailureReason.VersionMismatch);
|
|
225
|
+
}
|
|
226
|
+
if (
|
|
227
|
+
// The repository may be `undefined` in package.json but can only be defined
|
|
228
|
+
// or `null` in the Snap manifest due to TS@<4.4 issues.
|
|
229
|
+
(packageJsonRepository || manifestRepository) &&
|
|
230
|
+
!(0, fast_deep_equal_1.default)(packageJsonRepository, manifestRepository)) {
|
|
231
|
+
throw new snaps_1.ProgrammaticallyFixableSnapError(`"${types_1.NpmSnapFileNames.Manifest}" "repository" field does not match the "${types_1.NpmSnapFileNames.PackageJson}" "repository" field.`, types_1.SnapValidationFailureReason.RepositoryMismatch);
|
|
232
|
+
}
|
|
233
|
+
(0, snaps_1.validateSnapShasum)(manifest, sourceCode, `"${types_1.NpmSnapFileNames.Manifest}" "shasum" field does not match computed shasum.`);
|
|
234
|
+
return [manifest, sourceCode, packageJson];
|
|
235
|
+
}
|
|
236
|
+
exports.validateNpmSnapManifest = validateNpmSnapManifest;
|
|
237
|
+
//# sourceMappingURL=manifest.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"manifest.js","sourceRoot":"","sources":["../../src/manifest/manifest.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,2BAAoC;AACpC,gDAA6B;AAG7B,sEAAwC;AACxC,8CAA0C;AAC1C,8BAAyC;AACzC,gCAAyC;AACzC,oCAIkB;AAClB,oCAMkB;AAGlB,MAAM,mBAAmB,GAAuC;IAC9D,OAAO,EAAE,CAAC;IACV,WAAW,EAAE,CAAC;IACd,YAAY,EAAE,CAAC;IACf,UAAU,EAAE,CAAC;IACb,MAAM,EAAE,CAAC;IACT,kBAAkB,EAAE,CAAC;IACrB,eAAe,EAAE,CAAC;CACnB,CAAC;AAuBF;;;;;;;;;;GAUG;AACI,KAAK,UAAU,aAAa,CACjC,QAAgB,EAChB,aAAa,GAAG,IAAI,EACpB,UAAmB;;IAEnB,MAAM,QAAQ,GAAa,EAAE,CAAC;IAC9B,MAAM,MAAM,GAAa,EAAE,CAAC;IAE5B,IAAI,OAAO,GAAG,KAAK,CAAC;IAEpB,MAAM,mBAAmB,GAAG,MAAM,IAAA,qBAAgB,EAChD,QAAQ,EACR,wBAAgB,CAAC,QAAQ,CAC1B,CAAC;IAEF,MAAM,QAAQ,GACZ,mBAAmB,IAAI,OAAO,mBAAmB,KAAK,QAAQ;QAC5D,CAAC,CAAC,0BAA0B;YAC1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CAAC,kBAAkB,CAC/C,CAAC;KACH;IAED,IAAA,0BAAkB,EAChB,QAAQ,EACR,UAAU,EACV,IAAI,wBAAgB,CAAC,QAAQ,kDAAkD,CAChF,CAAC;IACF,OAAO,CAAC,QAAQ,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;AAC7C,CAAC;AA7CD,0DA6CC","sourcesContent":["import { promises as fs } from 'fs';\nimport pathUtils from 'path';\n\nimport { Json } from '@metamask/utils';\nimport deepEqual from 'fast-deep-equal';\nimport { deepClone } from '../deep-clone';\nimport { readSnapJsonFile } from '../fs';\nimport { validateNpmSnap } from '../npm';\nimport {\n getSnapSourceShasum,\n ProgrammaticallyFixableSnapError,\n validateSnapShasum,\n} from '../snaps';\nimport {\n NpmSnapFileNames,\n NpmSnapPackageJson,\n SnapFiles,\n SnapValidationFailureReason,\n UnvalidatedSnapFiles,\n} from '../types';\nimport { SnapManifest } from './validation';\n\nconst MANIFEST_SORT_ORDER: Record<keyof SnapManifest, number> = {\n version: 1,\n description: 2,\n proposedName: 3,\n repository: 4,\n source: 5,\n initialPermissions: 6,\n manifestVersion: 7,\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\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 * @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): Promise<CheckManifestResult> {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n let updated = false;\n\n const unvalidatedManifest = await readSnapJsonFile(\n basePath,\n NpmSnapFileNames.Manifest,\n );\n\n const iconPath =\n unvalidatedManifest && typeof unvalidatedManifest === 'object'\n ? /* istanbul ignore next */\n (unvalidatedManifest as Partial<SnapManifest>).source?.location?.npm\n ?.iconPath\n : /* istanbul ignore next */\n undefined;\n\n const snapFiles: UnvalidatedSnapFiles = {\n manifest: unvalidatedManifest,\n packageJson: await readSnapJsonFile(basePath, NpmSnapFileNames.PackageJson),\n sourceCode:\n sourceCode ?? (await getSnapSourceCode(basePath, unvalidatedManifest)),\n svgIcon:\n iconPath &&\n (await fs.readFile(pathUtils.join(basePath, iconPath), 'utf8')),\n };\n\n let manifest: SnapManifest | undefined;\n try {\n ({ manifest } = 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 = fixManifest(\n manifest\n ? { ...partiallyValidatedFiles, manifest }\n : partiallyValidatedFiles,\n currentError,\n );\n\n try {\n validateNpmSnapManifest({ ...partiallyValidatedFiles, manifest });\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 doesn't see that the 'manifest' variable must be of type\n // SnapManifest at this point, so we cast it.\n const validatedManifest = manifest as SnapManifest;\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 await fs.writeFile(\n pathUtils.join(basePath, NpmSnapFileNames.Manifest),\n `${JSON.stringify(getWritableManifest(validatedManifest), null, 2)}\\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 function fixManifest(\n snapFiles: SnapFiles,\n error: ProgrammaticallyFixableSnapError,\n): SnapManifest {\n const { manifest, packageJson, sourceCode } = snapFiles;\n const manifestCopy = deepClone(manifest);\n\n switch (error.reason) {\n case SnapValidationFailureReason.NameMismatch:\n manifestCopy.source.location.npm.packageName = packageJson.name;\n break;\n\n case SnapValidationFailureReason.VersionMismatch:\n manifestCopy.version = packageJson.version;\n break;\n\n case SnapValidationFailureReason.RepositoryMismatch:\n manifestCopy.repository = packageJson.repository\n ? deepClone(packageJson.repository)\n : undefined;\n break;\n\n case SnapValidationFailureReason.ShasumMismatch:\n manifestCopy.source.shasum = getSnapSourceShasum(sourceCode);\n break;\n\n /* istanbul ignore next */\n default: {\n const failureReason: never = error.reason;\n throw new Error(\n `Unrecognized validation failure reason: '${failureReason}'`,\n );\n }\n }\n\n return manifestCopy;\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 * @returns The contents of the bundle file, if any.\n */\nexport async function getSnapSourceCode(\n basePath: string,\n manifest: Json,\n): Promise<string | undefined> {\n if (manifest && typeof manifest === 'object' && !Array.isArray(manifest)) {\n const sourceFilePath = (manifest as Partial<SnapManifest>).source?.location\n ?.npm?.filePath;\n\n try {\n return sourceFilePath\n ? await fs.readFile(pathUtils.join(basePath, sourceFilePath), 'utf8')\n : undefined;\n } catch (error) {\n throw new Error(`Failed to read Snap bundle file: ${error.message}`);\n }\n }\n\n return undefined;\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 return keys\n .sort((a, b) => MANIFEST_SORT_ORDER[a] - MANIFEST_SORT_ORDER[b])\n .reduce(\n (result, key) => ({\n ...result,\n [key]: manifest[key],\n }),\n {} as SnapManifest,\n );\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 * @returns A tuple containing the validated snap manifest, snap source code,\n * and `package.json`.\n */\nexport function validateNpmSnapManifest({\n manifest,\n packageJson,\n sourceCode,\n}: SnapFiles): [SnapManifest, string, NpmSnapPackageJson] {\n const packageJsonName = packageJson.name;\n const packageJsonVersion = packageJson.version;\n const packageJsonRepository = packageJson.repository;\n\n const manifestPackageName = manifest.source.location.npm.packageName;\n const manifestPackageVersion = manifest.version;\n const manifestRepository = manifest.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 validateSnapShasum(\n manifest,\n sourceCode,\n `\"${NpmSnapFileNames.Manifest}\" \"shasum\" field does not match computed shasum.`,\n );\n return [manifest, sourceCode, packageJson];\n}\n"]}
|