@kubohiroya/sb3-toolchain 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +30 -4
  2. package/README.ja.md +17 -1
  3. package/README.md +17 -1
  4. package/dist/archive.d.ts +1 -0
  5. package/dist/archive.js +16 -0
  6. package/dist/archive.js.map +1 -0
  7. package/dist/assert.d.ts +2 -0
  8. package/dist/assert.js +11 -0
  9. package/dist/assert.js.map +1 -0
  10. package/dist/bin.d.ts +1 -0
  11. package/dist/bin.js +12 -0
  12. package/dist/bin.js.map +1 -0
  13. package/dist/build.d.ts +23 -0
  14. package/dist/build.js +111 -0
  15. package/dist/build.js.map +1 -0
  16. package/dist/cli.d.ts +87 -0
  17. package/dist/cli.js +544 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/constants.d.ts +2 -0
  20. package/dist/constants.js +7 -0
  21. package/dist/constants.js.map +1 -0
  22. package/dist/extension-api-manifest.d.ts +65 -0
  23. package/dist/extension-api-manifest.js +231 -0
  24. package/dist/extension-api-manifest.js.map +1 -0
  25. package/dist/extension-bundle-archive.d.ts +36 -0
  26. package/dist/extension-bundle-archive.js +302 -0
  27. package/dist/extension-bundle-archive.js.map +1 -0
  28. package/dist/extension-bundle-configuration.d.ts +55 -0
  29. package/dist/extension-bundle-configuration.js +200 -0
  30. package/dist/extension-bundle-configuration.js.map +1 -0
  31. package/dist/extension-bundle.d.ts +39 -0
  32. package/dist/extension-bundle.js +580 -0
  33. package/dist/extension-bundle.js.map +1 -0
  34. package/dist/extension-dependencies.d.ts +18 -0
  35. package/dist/extension-dependencies.js +59 -0
  36. package/dist/extension-dependencies.js.map +1 -0
  37. package/dist/extension-id-migration.d.ts +83 -0
  38. package/dist/extension-id-migration.js +292 -0
  39. package/dist/extension-id-migration.js.map +1 -0
  40. package/dist/extension-sync.d.ts +111 -0
  41. package/dist/extension-sync.js +463 -0
  42. package/dist/extension-sync.js.map +1 -0
  43. package/dist/import.d.ts +39 -0
  44. package/dist/import.js +244 -0
  45. package/dist/import.js.map +1 -0
  46. package/dist/index.d.ts +31 -0
  47. package/dist/index.js +18 -0
  48. package/dist/npm-extension-source.d.ts +13 -0
  49. package/dist/npm-extension-source.js +63 -0
  50. package/dist/npm-extension-source.js.map +1 -0
  51. package/dist/output-safety.d.ts +29 -0
  52. package/dist/output-safety.js +213 -0
  53. package/dist/output-safety.js.map +1 -0
  54. package/dist/project-asset-additions.d.ts +29 -0
  55. package/dist/project-asset-additions.js +412 -0
  56. package/dist/project-asset-additions.js.map +1 -0
  57. package/dist/release-snapshot.d.ts +75 -0
  58. package/dist/release-snapshot.js +177 -0
  59. package/dist/release-snapshot.js.map +1 -0
  60. package/dist/source.d.ts +41 -0
  61. package/dist/source.js +282 -0
  62. package/dist/source.js.map +1 -0
  63. package/dist/turbowarp-clean-up.d.ts +18 -0
  64. package/dist/turbowarp-clean-up.js +266 -0
  65. package/dist/turbowarp-clean-up.js.map +1 -0
  66. package/dist/types.d.ts +80 -0
  67. package/package.json +31 -20
  68. package/bin/sb3-toolchain.mjs +0 -9
  69. package/src/archive.js +0 -35
  70. package/src/build.js +0 -188
  71. package/src/cli.js +0 -748
  72. package/src/constants.js +0 -4
  73. package/src/extension-api-manifest.js +0 -336
  74. package/src/extension-bundle-archive.js +0 -422
  75. package/src/extension-bundle-configuration.js +0 -265
  76. package/src/extension-bundle.js +0 -695
  77. package/src/extension-dependencies.js +0 -114
  78. package/src/extension-id-migration.js +0 -496
  79. package/src/extension-sync.js +0 -754
  80. package/src/import.js +0 -397
  81. package/src/index.js +0 -75
  82. package/src/npm-extension-source.js +0 -111
  83. package/src/output-safety.js +0 -322
  84. package/src/project-asset-additions.js +0 -560
  85. package/src/release-snapshot.js +0 -247
  86. package/src/source.js +0 -468
  87. package/src/turbowarp-clean-up.js +0 -295
package/src/import.js DELETED
@@ -1,397 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- import {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';
4
- import path from 'node:path';
5
- import process from 'node:process';
6
-
7
- import {strFromU8, unzipSync} from 'fflate';
8
-
9
- import {validateArchiveEntryName} from './archive.js';
10
- import {validateManagedExtensionApiManifest} from './extension-api-manifest.js';
11
- import {validateManagedExtensionContents} from './extension-dependencies.js';
12
- import {
13
- assertNoInterruptedRollback,
14
- assertRecognizedOutputDirectory,
15
- compareDirectories,
16
- inspectGitOutputState,
17
- pathExists,
18
- replaceDirectoryTransactionally,
19
- validateOutputDirectoryPath,
20
- } from './output-safety.js';
21
- import {sourceFormatVersion} from './source.js';
22
-
23
- export {validateOutputDirectoryPath} from './output-safety.js';
24
-
25
- function assert(condition, message) {
26
- if (!condition) {
27
- throw new Error(message);
28
- }
29
- }
30
-
31
- function summarizeGitChanges(gitState) {
32
- const entries = [
33
- ...gitState.statusEntries,
34
- ...gitState.untrackedContent.map((entry) => `not tracked: ${entry}`),
35
- ];
36
- const visibleEntries = entries.slice(0, 8).join(', ');
37
- const remainder = entries.length > 8 ? `, and ${entries.length - 8} more` : '';
38
- return `${visibleEntries}${remainder}`;
39
- }
40
-
41
- async function authorizeOutputReplacement({
42
- candidateDirectory,
43
- confirmReplace,
44
- discardLocalChanges,
45
- outputDirectory,
46
- yes,
47
- }) {
48
- await assertNoInterruptedRollback(outputDirectory);
49
- if (!(await pathExists(outputDirectory))) {
50
- return {action: 'create', comparison: null, gitState: null};
51
- }
52
-
53
- await assertRecognizedOutputDirectory(outputDirectory, sourceFormatVersion);
54
- const comparison = await compareDirectories(outputDirectory, candidateDirectory);
55
- if (comparison.identical) {
56
- return {action: 'unchanged', comparison, gitState: null};
57
- }
58
-
59
- const gitState = await inspectGitOutputState(outputDirectory, comparison.existingFilePaths);
60
- assert(
61
- gitState.managed,
62
- `Existing output differs from the SB3 candidate but is not tracked by Git: ${outputDirectory}. ` +
63
- 'Import to a new output directory instead of replacing unrecoverable content.',
64
- );
65
- assert(
66
- gitState.clean || discardLocalChanges,
67
- `Existing output differs from the SB3 candidate and has uncommitted Git changes: ` +
68
- `${summarizeGitChanges(gitState)}. Commit or stash them first, or explicitly use ` +
69
- '--discard-local-changes.',
70
- );
71
-
72
- const context = {
73
- comparison,
74
- discardLocalChanges,
75
- gitState,
76
- outputDirectory,
77
- };
78
- if (yes) {
79
- return {action: 'replace', ...context};
80
- }
81
- assert(
82
- typeof confirmReplace === 'function',
83
- `Output directory already exists: ${outputDirectory}. ` +
84
- 'Refusing to replace differing content without interactive confirmation or --yes.',
85
- );
86
- assert(
87
- await confirmReplace(context),
88
- 'SB3 import cancelled; the existing output was not changed.',
89
- );
90
- return {action: 'replace', ...context};
91
- }
92
-
93
- async function revalidateOutputReplacement({
94
- candidateDirectory,
95
- decision,
96
- discardLocalChanges,
97
- outputDirectory,
98
- }) {
99
- const latestComparison = await compareDirectories(outputDirectory, candidateDirectory);
100
- assert(
101
- latestComparison.existingFingerprint === decision.comparison.existingFingerprint &&
102
- latestComparison.candidateFingerprint === decision.comparison.candidateFingerprint,
103
- 'Output or candidate content changed during SB3 import; refusing to replace it.',
104
- );
105
- const latestGitState = await inspectGitOutputState(
106
- outputDirectory,
107
- latestComparison.existingFilePaths,
108
- );
109
- assert(
110
- latestGitState.managed,
111
- 'Output stopped being Git-managed during SB3 import; refusing to replace it.',
112
- );
113
- assert(
114
- latestGitState.fingerprint === decision.gitState.fingerprint,
115
- 'Git state changed during SB3 import; refusing to replace the output.',
116
- );
117
- assert(
118
- latestGitState.clean || discardLocalChanges,
119
- 'Output gained uncommitted Git changes during SB3 import; refusing to replace it.',
120
- );
121
- }
122
-
123
- function extensionSourcePath(extensionId) {
124
- assert(
125
- /^[A-Za-z0-9._-]+$/u.test(extensionId),
126
- `Embedded extension ID cannot be used as a filename: ${JSON.stringify(extensionId)}`,
127
- );
128
- return `extensions/${extensionId}.js`;
129
- }
130
-
131
- async function readExistingExtensionSources(outputDirectory) {
132
- if (!(await pathExists(outputDirectory))) {
133
- return new Map();
134
- }
135
-
136
- const manifestPath = path.join(outputDirectory, 'embedded-extensions.json');
137
- if (!(await pathExists(manifestPath))) {
138
- return new Map();
139
- }
140
-
141
- let manifest;
142
- try {
143
- manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
144
- } catch (error) {
145
- throw new Error(`Existing embedded extension manifest is not valid JSON: ${manifestPath}`, {
146
- cause: error,
147
- });
148
- }
149
- assert(
150
- manifest &&
151
- typeof manifest === 'object' &&
152
- !Array.isArray(manifest) &&
153
- Array.isArray(manifest.extensions),
154
- `Existing embedded extension manifest is invalid: ${manifestPath}`,
155
- );
156
-
157
- const sources = new Map();
158
- for (const extension of manifest.extensions) {
159
- if (
160
- !extension ||
161
- typeof extension !== 'object' ||
162
- typeof extension.id !== 'string' ||
163
- typeof extension.path !== 'string' ||
164
- extension.source === undefined
165
- ) {
166
- continue;
167
- }
168
- sources.set(`${extension.id}\u0000${extension.path}`, extension.source);
169
- }
170
- return sources;
171
- }
172
-
173
- export function decodeExtensionDataUrl(dataUrl) {
174
- assert(
175
- typeof dataUrl === 'string' && dataUrl.startsWith('data:'),
176
- 'Embedded extension URL must be a data URL.',
177
- );
178
- const commaIndex = dataUrl.indexOf(',');
179
- assert(commaIndex >= 0, 'Embedded extension data URL has no payload separator.');
180
-
181
- const metadata = dataUrl.slice('data:'.length, commaIndex).split(';');
182
- const mediaType = metadata.shift() || 'text/plain';
183
- const base64Index = metadata.indexOf('base64');
184
- const encoding = base64Index >= 0 ? 'base64' : 'percent';
185
- if (base64Index >= 0) {
186
- metadata.splice(base64Index, 1);
187
- }
188
-
189
- const payload = dataUrl.slice(commaIndex + 1);
190
- let source;
191
- if (encoding === 'base64') {
192
- assert(
193
- /^[A-Za-z0-9+/]*={0,2}$/u.test(payload),
194
- 'Embedded extension data URL contains invalid base64.',
195
- );
196
- const unpaddedPayload = payload.replace(/=+$/u, '');
197
- assert(
198
- unpaddedPayload.length % 4 !== 1,
199
- 'Embedded extension data URL contains invalid base64.',
200
- );
201
- source = Buffer.from(
202
- unpaddedPayload.padEnd(Math.ceil(unpaddedPayload.length / 4) * 4, '='),
203
- 'base64',
204
- );
205
- } else {
206
- try {
207
- source = Buffer.from(decodeURIComponent(payload), 'utf8');
208
- } catch {
209
- throw new Error('Embedded extension data URL contains invalid percent encoding.');
210
- }
211
- }
212
-
213
- return {
214
- encoding,
215
- mediaType,
216
- parameters: metadata,
217
- source,
218
- };
219
- }
220
-
221
- export async function importSb3({
222
- inputPath,
223
- outputDirectory,
224
- protectedRoot = process.cwd(),
225
- discardLocalChanges = false,
226
- yes = false,
227
- confirmReplace,
228
- }) {
229
- assert(typeof inputPath === 'string', 'Input SB3 path is required.');
230
- assert(typeof outputDirectory === 'string', 'SB3 source output directory is required.');
231
- const resolvedInputPath = path.resolve(inputPath);
232
- const resolvedOutputDirectory = validateOutputDirectoryPath(outputDirectory, protectedRoot);
233
-
234
- const archive = unzipSync(new Uint8Array(await readFile(resolvedInputPath)));
235
- const archiveEntries = Object.entries(archive);
236
- assert(archiveEntries.length > 0, 'SB3 archive is empty.');
237
- for (const [entryName] of archiveEntries) {
238
- validateArchiveEntryName(entryName);
239
- }
240
-
241
- const projectEntry = archive['project.json'];
242
- assert(projectEntry, 'SB3 archive does not contain project.json.');
243
-
244
- let project;
245
- let decision;
246
- let rollbackCleanupWarning = null;
247
- try {
248
- project = JSON.parse(strFromU8(projectEntry));
249
- } catch (error) {
250
- throw new Error(`SB3 project.json is invalid JSON: ${error.message}`, {cause: error});
251
- }
252
- assert(
253
- project && typeof project === 'object' && !Array.isArray(project),
254
- 'SB3 project.json must contain a JSON object.',
255
- );
256
-
257
- const extensionUrls = project.extensionURLs ?? {};
258
- assert(
259
- extensionUrls && typeof extensionUrls === 'object' && !Array.isArray(extensionUrls),
260
- 'SB3 project.json extensionURLs must be an object when present.',
261
- );
262
-
263
- const existingExtensionSources = await readExistingExtensionSources(resolvedOutputDirectory);
264
- const embeddedExtensions = [];
265
- const decodedExtensionSources = [];
266
- for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {
267
- if (typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:')) {
268
- continue;
269
- }
270
- const sourcePath = extensionSourcePath(extensionId);
271
- const decoded = decodeExtensionDataUrl(extensionUrl);
272
- extensionUrls[extensionId] = `embedded-extension:${sourcePath}`;
273
- const extension = {
274
- id: extensionId,
275
- path: sourcePath,
276
- mediaType: decoded.mediaType,
277
- parameters: decoded.parameters,
278
- encoding: decoded.encoding,
279
- };
280
- const existingSource = existingExtensionSources.get(`${extensionId}\u0000${sourcePath}`);
281
- let existingApiManifestContents = null;
282
- if (existingSource !== undefined) {
283
- extension.source = structuredClone(existingSource);
284
- validateManagedExtensionContents(extension, decoded.source);
285
- if (extension.source.apiManifest) {
286
- existingApiManifestContents = await readFile(
287
- path.join(resolvedOutputDirectory, extension.source.apiManifest.path),
288
- );
289
- validateManagedExtensionApiManifest(extension, existingApiManifestContents);
290
- }
291
- }
292
- embeddedExtensions.push(extension);
293
- decodedExtensionSources.push({path: sourcePath, source: decoded.source});
294
- if (existingApiManifestContents) {
295
- decodedExtensionSources.push({
296
- path: extension.source.apiManifest.path,
297
- source: existingApiManifestContents,
298
- });
299
- }
300
- }
301
-
302
- const outputParent = path.dirname(resolvedOutputDirectory);
303
- await mkdir(outputParent, {recursive: true});
304
- const temporaryDirectory = await mkdtemp(
305
- path.join(outputParent, `.${path.basename(resolvedOutputDirectory)}.import-`),
306
- );
307
-
308
- try {
309
- const assetsDirectory = path.join(temporaryDirectory, 'assets');
310
- await mkdir(assetsDirectory, {recursive: true});
311
- await mkdir(path.join(temporaryDirectory, 'extensions'), {recursive: true});
312
-
313
- for (const [entryName, contents] of archiveEntries) {
314
- if (entryName === 'project.json' || entryName.endsWith('/')) {
315
- continue;
316
- }
317
- const assetPath = path.resolve(assetsDirectory, entryName);
318
- assert(
319
- assetPath.startsWith(`${assetsDirectory}${path.sep}`),
320
- `SB3 archive entry escapes the assets directory: ${JSON.stringify(entryName)}`,
321
- );
322
- await mkdir(path.dirname(assetPath), {recursive: true});
323
- await writeFile(assetPath, contents);
324
- }
325
-
326
- for (const extension of decodedExtensionSources) {
327
- await writeFile(path.join(temporaryDirectory, extension.path), extension.source);
328
- }
329
-
330
- const sourceManifest = {
331
- formatVersion: sourceFormatVersion,
332
- project: 'project.source.json',
333
- embeddedExtensions: 'embedded-extensions.json',
334
- assetsDirectory: 'assets',
335
- archiveEntries: archiveEntries.map(([entryName]) => entryName),
336
- };
337
- await Promise.all([
338
- writeFile(
339
- path.join(temporaryDirectory, 'project.source.json'),
340
- `${JSON.stringify(project, null, 2)}\n`,
341
- ),
342
- writeFile(
343
- path.join(temporaryDirectory, 'embedded-extensions.json'),
344
- `${JSON.stringify({formatVersion: sourceFormatVersion, extensions: embeddedExtensions}, null, 2)}\n`,
345
- ),
346
- writeFile(
347
- path.join(temporaryDirectory, 'sb3-source.json'),
348
- `${JSON.stringify(sourceManifest, null, 2)}\n`,
349
- ),
350
- ]);
351
- decision = await authorizeOutputReplacement({
352
- candidateDirectory: temporaryDirectory,
353
- confirmReplace,
354
- discardLocalChanges,
355
- outputDirectory: resolvedOutputDirectory,
356
- yes,
357
- });
358
- if (decision.action === 'unchanged') {
359
- await rm(temporaryDirectory, {recursive: true, force: true});
360
- } else {
361
- if (decision.action === 'replace') {
362
- await revalidateOutputReplacement({
363
- candidateDirectory: temporaryDirectory,
364
- decision,
365
- discardLocalChanges,
366
- outputDirectory: resolvedOutputDirectory,
367
- });
368
- }
369
- ({rollbackCleanupWarning} = await replaceDirectoryTransactionally(
370
- temporaryDirectory,
371
- resolvedOutputDirectory,
372
- ));
373
- }
374
- } catch (error) {
375
- await rm(temporaryDirectory, {recursive: true, force: true});
376
- throw error;
377
- }
378
-
379
- return {
380
- archiveEntryCount: archiveEntries.length,
381
- assetCount: archiveEntries.filter(
382
- ([entryName]) => entryName !== 'project.json' && !entryName.endsWith('/'),
383
- ).length,
384
- embeddedExtensionCount: embeddedExtensions.length,
385
- changed: decision.action !== 'unchanged',
386
- differenceCounts: decision.comparison
387
- ? {
388
- added: decision.comparison.differences.added.length,
389
- modified: decision.comparison.differences.modified.length,
390
- removed: decision.comparison.differences.removed.length,
391
- }
392
- : null,
393
- inputPath: resolvedInputPath,
394
- outputDirectory: resolvedOutputDirectory,
395
- rollbackCleanupWarning,
396
- };
397
- }
package/src/index.js DELETED
@@ -1,75 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- export {validateArchiveEntryName} from './archive.js';
4
- export {buildSb3} from './build.js';
5
- export {packageName, packageVersion} from './constants.js';
6
- export {
7
- extensionHeaderId,
8
- extensionHeaderMetadata,
9
- extensionIntegrity,
10
- validateExtensionSourceMetadata,
11
- validateManagedExtensionContents,
12
- } from './extension-dependencies.js';
13
- export {
14
- compareExtensionApiManifests,
15
- defaultExtensionApiManifestSizeLimit,
16
- extensionApiManifestFormatVersion,
17
- extensionApiManifestIntegrity,
18
- extensionApiManifestLocalPath,
19
- formatExtensionApiCompatibilityChanges,
20
- parseExtensionApiManifest,
21
- validateExtensionApiManifestSourceMetadata,
22
- validateManagedExtensionApiManifest,
23
- } from './extension-api-manifest.js';
24
- export {
25
- bundleExtensions,
26
- planExtensionBundle,
27
- planExtensionUnbundle,
28
- unbundleExtensions,
29
- } from './extension-bundle-configuration.js';
30
- export {planBundledSb3Unbundle, unbundleSb3} from './extension-bundle-archive.js';
31
- export {
32
- buildExtensionBundles,
33
- createStaticExtensionBundle,
34
- extensionBundleRecoveryMarker,
35
- validateExtensionBundleConfigurations,
36
- } from './extension-bundle.js';
37
- export {
38
- migrateExtensionId,
39
- planExtensionIdMigration,
40
- validateNewExtensionId,
41
- } from './extension-id-migration.js';
42
- export {
43
- defaultExtensionArtifactSizeLimit,
44
- extensionStatus,
45
- syncExtensions,
46
- updateExtensions,
47
- } from './extension-sync.js';
48
- export {decodeExtensionDataUrl, importSb3} from './import.js';
49
- export {
50
- compareDirectories,
51
- inspectGitOutputState,
52
- validateOutputDirectoryPath,
53
- } from './output-safety.js';
54
- export {
55
- createDeterministicSb3,
56
- fixedZipTimestamp,
57
- sourceFormatVersion,
58
- validateSb3Source,
59
- } from './source.js';
60
- export {
61
- applyProjectAssetAdditions,
62
- projectAssetAdditionsFormatVersion,
63
- } from './project-asset-additions.js';
64
- export {
65
- assertSb3ReleaseSnapshotMetadata,
66
- computeReleaseSourceIdentity,
67
- createSb3ReleaseSnapshot,
68
- createSb3ReleaseSnapshotMetadata,
69
- freezeSb3ReleaseSnapshot,
70
- readSb3ReleaseSnapshotMetadata,
71
- recordPublishedSb3ReleaseSnapshot,
72
- verifySb3ReleaseSnapshot,
73
- writeSb3ReleaseCandidate,
74
- } from './release-snapshot.js';
75
- export {cleanUpTurboWarpBlocks, turboWarpCleanUpLayout} from './turbowarp-clean-up.js';
@@ -1,111 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- import {lstat, readFile, realpath} from 'node:fs/promises';
4
- import path from 'node:path';
5
-
6
- import {validateExtensionApiManifestSourceMetadata} from './extension-api-manifest.js';
7
- import {extensionHeaderId, validateExtensionSourceMetadata} from './extension-dependencies.js';
8
-
9
- function assert(condition, message) {
10
- if (!condition) throw new Error(message);
11
- }
12
-
13
- function packageSegments(packageName) {
14
- return packageName.startsWith('@') ? packageName.split('/') : [packageName];
15
- }
16
-
17
- async function findPackageDirectory(sourceDirectory, packageName) {
18
- let current = path.resolve(sourceDirectory);
19
- while (true) {
20
- const candidate = path.join(current, 'node_modules', ...packageSegments(packageName));
21
- try {
22
- await lstat(path.join(candidate, 'package.json'));
23
- return candidate;
24
- } catch (error) {
25
- if (error?.code !== 'ENOENT' && error?.code !== 'ENOTDIR') throw error;
26
- }
27
- const parent = path.dirname(current);
28
- if (parent === current) break;
29
- current = parent;
30
- }
31
- throw new Error(
32
- `Installed npm package was not found for managed extension: ${packageName}. Run the project's package manager install command.`,
33
- );
34
- }
35
-
36
- async function readPackageArtifact(packageDirectory, artifact, maximumBytes, description) {
37
- const [resolvedPackageDirectory, resolvedArtifact] = await Promise.all([
38
- realpath(packageDirectory),
39
- realpath(path.join(packageDirectory, ...artifact.split('/'))),
40
- ]);
41
- const relativeArtifact = path.relative(resolvedPackageDirectory, resolvedArtifact);
42
- assert(
43
- relativeArtifact !== '' &&
44
- relativeArtifact !== '..' &&
45
- !relativeArtifact.startsWith(`..${path.sep}`) &&
46
- !path.isAbsolute(relativeArtifact),
47
- `${description} resolves outside its npm package: ${artifact}`,
48
- );
49
- const stats = await lstat(resolvedArtifact);
50
- assert(stats.isFile(), `${description} must be a regular file: ${artifact}`);
51
- assert(stats.size <= maximumBytes, `${description} exceeds the ${maximumBytes}-byte limit.`);
52
- return readFile(resolvedArtifact);
53
- }
54
-
55
- export async function readNpmExtensionSource(
56
- extension,
57
- sourceDirectory,
58
- {allowVersionMismatch = false, maximumArtifactBytes, maximumManifestBytes},
59
- ) {
60
- const source = validateExtensionSourceMetadata(extension);
61
- assert(source?.provider === 'npm', `Extension is not managed by npm: ${extension.id}`);
62
- const packageDirectory = await findPackageDirectory(sourceDirectory, source.package);
63
- let packageManifest;
64
- try {
65
- packageManifest = JSON.parse(
66
- await readFile(path.join(packageDirectory, 'package.json'), 'utf8'),
67
- );
68
- } catch (error) {
69
- throw new Error(`Invalid package.json for npm extension ${extension.id}: ${error.message}`, {
70
- cause: error,
71
- });
72
- }
73
- assert(
74
- packageManifest?.name === source.package,
75
- `npm package name mismatch for extension ${extension.id}: expected ${source.package}, got ${packageManifest?.name ?? '(missing)'}`,
76
- );
77
- assert(
78
- typeof packageManifest.version === 'string' &&
79
- /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(
80
- packageManifest.version,
81
- ),
82
- `npm package has an invalid semantic version for extension ${extension.id}: ${packageManifest?.version ?? '(missing)'}`,
83
- );
84
- if (!allowVersionMismatch) {
85
- assert(
86
- packageManifest.version === source.version,
87
- `npm package version mismatch for extension ${extension.id}: expected ${source.version}, got ${packageManifest?.version ?? '(missing)'}`,
88
- );
89
- }
90
- const contents = await readPackageArtifact(
91
- packageDirectory,
92
- source.artifact,
93
- maximumArtifactBytes,
94
- `npm extension artifact for ${extension.id}`,
95
- );
96
- const actualId = extensionHeaderId(contents);
97
- assert(
98
- actualId === extension.id,
99
- `npm extension header ID mismatch for ${extension.id}: expected ${extension.id}, got ${actualId ?? '(missing)'}`,
100
- );
101
- const apiMetadata = validateExtensionApiManifestSourceMetadata(extension);
102
- const apiManifestContents = apiMetadata
103
- ? await readPackageArtifact(
104
- packageDirectory,
105
- apiMetadata.artifact,
106
- maximumManifestBytes,
107
- `npm extension API manifest for ${extension.id}`,
108
- )
109
- : null;
110
- return {apiManifestContents, contents, packageDirectory, version: packageManifest.version};
111
- }