@kubohiroya/turbowarp-plus-editor-project-folder 0.6.0 → 0.8.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/src/source.ts CHANGED
@@ -5,7 +5,8 @@ type Target = JsonObject & {isStage: boolean; name: string};
5
5
 
6
6
  export const projectFile = 'project.source.json';
7
7
  export const manifestFile = 'sb3-source.json';
8
- const extensionsFile = 'embedded-extensions.json';
8
+ export const extensionsFile = 'embedded-extensions.json';
9
+ const embeddedReference = 'embedded-extension:';
9
10
 
10
11
  export class FolderError extends Error {
11
12
  code: 'conflict' | 'unsupported';
@@ -47,7 +48,7 @@ export function parseProject(text: string): Project {
47
48
  export interface AssetType {name: string}
48
49
  export interface Asset {assetId: string; dataFormat: string; data: Uint8Array}
49
50
  export interface Storage {
50
- AssetType: {Sound: AssetType; ImageVector: AssetType; ImageBitmap: AssetType};
51
+ AssetType: {Sound: AssetType; ImageVector: AssetType; ImageBitmap: AssetType; Font?: AssetType};
51
52
  createAsset(type: AssetType, format: string, data: Uint8Array, id: null, generateId: true): Asset;
52
53
  addHelper(helper: {load(type: AssetType, id: string, format: string): Promise<Asset> | null}, priority: number): void;
53
54
  }
@@ -57,8 +58,14 @@ type FolderFiles = {
57
58
  files: Map<string, Uint8Array>;
58
59
  directory: FileSystemDirectoryHandle;
59
60
  bytes: Map<string, Uint8Array>;
61
+ extensionBytes: Map<string, Uint8Array>;
62
+ };
63
+ export type FolderSource = FolderFiles & {
64
+ project: Project;
65
+ loadText: string;
66
+ storageAssets: Map<string, Asset>;
67
+ embedded: ExtensionManifest;
60
68
  };
61
- export type FolderSource = FolderFiles & {project: Project; projectText: string; storageAssets: Map<string, Asset>};
62
69
 
63
70
  const getFile = async (dir: FileSystemDirectoryHandle, name: string) => (await dir.getFileHandle(name)).getFile();
64
71
  export const fileVersion = (file: File) => `${file.size}:${file.lastModified}`;
@@ -78,10 +85,186 @@ const sameNames = (actual: Set<string>, expected: Iterable<string>) => {
78
85
  return actual.size === expectedNames.size && [...actual].every(name => expectedNames.has(name));
79
86
  };
80
87
 
81
- export const assetTypeFor = (storage: Storage, kind: 'costumes' | 'sounds', format: string) => kind === 'sounds' ?
82
- storage.AssetType.Sound : format === 'svg' ? storage.AssetType.ImageVector : storage.AssetType.ImageBitmap;
88
+ export type AssetKind = 'costumes' | 'sounds' | 'fonts';
89
+
90
+ export const assetTypeFor = (storage: Storage, kind: AssetKind, format: string): AssetType => {
91
+ if (kind === 'fonts') return storage.AssetType.Font ?? unsupported('The editor does not support font assets');
92
+ if (kind === 'sounds') return storage.AssetType.Sound;
93
+ return format === 'svg' ? storage.AssetType.ImageVector : storage.AssetType.ImageBitmap;
94
+ };
83
95
  export const assetKey = (type: AssetType, id: string, format: string) => `${type.name}/${id}.${format}`;
84
96
 
97
+ type DataUrlMetadata = {mediaType: string; parameters: string[]; encoding: 'base64' | 'percent'};
98
+ type EmbeddedExtension = JsonObject & DataUrlMetadata & {id: string; path: string};
99
+ type ExtensionBundle = JsonObject & {id: string; members: string[]};
100
+ type ExtensionManifest = JsonObject & {extensions: EmbeddedExtension[]; extensionBundles?: ExtensionBundle[]};
101
+
102
+ const extensionPath = (id: string) => {
103
+ if (!/^[A-Za-z0-9._-]+$/u.test(id)) return unsupported(`Embedded extension ID cannot be used as a filename: ${id}`);
104
+ return `extensions/${id}.js`;
105
+ };
106
+ const validUrlPart = (part: Json | undefined): part is string => typeof part === 'string' && part.length > 0 && !/[;,\r\n]/u.test(part);
107
+ const extensionURLs = (project: Project) => {
108
+ const urls = project.extensionURLs === undefined ? {} : project.extensionURLs;
109
+ if (!isObject(urls) || Object.values(urls).some(url => typeof url !== 'string')) return unsupported('Invalid extensionURLs');
110
+ return urls as Record<string, string>;
111
+ };
112
+ const apiManifestName = (entry: EmbeddedExtension): string | undefined => {
113
+ if (entry.source === undefined) return;
114
+ if (!isObject(entry.source)) return unsupported(`Invalid source for embedded extension: ${entry.id}`);
115
+ const api = entry.source.apiManifest;
116
+ if (api === undefined) return;
117
+ const name = `${entry.id}.manifest.json`;
118
+ if (!isObject(api) || api.path !== `extensions/${name}`) return unsupported(`Invalid API manifest path: ${entry.id}`);
119
+ return name;
120
+ };
121
+ const extensionNames = (entries: EmbeddedExtension[]) => entries.flatMap(entry => {
122
+ const script = `${entry.id}.js`;
123
+ const api = apiManifestName(entry);
124
+ return api === undefined ? [script] : [script, api];
125
+ });
126
+
127
+ function validateExtensions(project: Project, value: JsonObject): ExtensionManifest {
128
+ if (value.formatVersion !== 1 || !Array.isArray(value.extensions)) return unsupported('Invalid embedded extension manifest');
129
+ const urls = extensionURLs(project);
130
+ const ids = new Set<string>();
131
+ for (const entry of value.extensions) {
132
+ if (!isObject(entry) || typeof entry.id !== 'string' || ids.has(entry.id) ||
133
+ entry.path !== extensionPath(entry.id) || !validUrlPart(entry.mediaType) ||
134
+ !Array.isArray(entry.parameters) || !entry.parameters.every(validUrlPart) ||
135
+ (entry.encoding !== 'base64' && entry.encoding !== 'percent') ||
136
+ !Object.hasOwn(urls, entry.id) || urls[entry.id] !== embeddedReference + entry.path) {
137
+ return unsupported('Invalid embedded extension entry or project reference');
138
+ }
139
+ ids.add(entry.id);
140
+ }
141
+ for (const [id, url] of Object.entries(urls)) {
142
+ if (url.startsWith('data:') || (url.startsWith(embeddedReference) && !ids.has(id))) {
143
+ return unsupported(`Invalid embedded extension reference: ${id}`);
144
+ }
145
+ }
146
+ if (value.extensionBundles !== undefined) {
147
+ if (!Array.isArray(value.extensionBundles)) return unsupported('Invalid extensionBundles');
148
+ const bundleIds = new Set<string>();
149
+ const members = new Set<string>();
150
+ for (const bundle of value.extensionBundles) {
151
+ if (!isObject(bundle) || typeof bundle.id !== 'string' || !/^[a-z0-9]+$/u.test(bundle.id) ||
152
+ ids.has(bundle.id) || bundleIds.has(bundle.id) || typeof bundle.name !== 'string' ||
153
+ !bundle.name.trim() || /[\r\n]/u.test(bundle.name) ||
154
+ !Array.isArray(bundle.members) || bundle.members.length < 2) {
155
+ return unsupported('Invalid extension bundle');
156
+ }
157
+ bundleIds.add(bundle.id);
158
+ for (const member of bundle.members) {
159
+ if (typeof member !== 'string' || !/^[a-z0-9]+$/u.test(member) || !ids.has(member) || members.has(member)) {
160
+ return unsupported(`Invalid member of extension bundle: ${bundle.id}`);
161
+ }
162
+ members.add(member);
163
+ }
164
+ }
165
+ }
166
+ return value as ExtensionManifest;
167
+ }
168
+
169
+ function encodeDataUrl(entry: EmbeddedExtension, bytes: Uint8Array): string {
170
+ const metadata = [entry.mediaType, ...entry.parameters].join(';');
171
+ if (entry.encoding === 'percent') {
172
+ const payload = Array.from(bytes, byte => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`).join('');
173
+ return `data:${metadata},${payload}`;
174
+ }
175
+ let binary = '';
176
+ for (let offset = 0; offset < bytes.length; offset += 8192) {
177
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));
178
+ }
179
+ return `data:${metadata};base64,${btoa(binary)}`;
180
+ }
181
+
182
+ function decodeDataUrl(id: string, url: string): {metadata: DataUrlMetadata; bytes: Uint8Array} {
183
+ const comma = url.indexOf(',');
184
+ if (comma === -1) return unsupported(`Invalid data URL for embedded extension: ${id}`);
185
+ const [type, ...parameters] = url.slice('data:'.length, comma).split(';');
186
+ const mediaType = type || 'text/plain';
187
+ const base64 = parameters.indexOf('base64');
188
+ if (base64 !== -1) parameters.splice(base64, 1);
189
+ const encoding = base64 === -1 ? 'percent' : 'base64';
190
+ if (!validUrlPart(mediaType) || !parameters.every(validUrlPart) || parameters.includes('base64')) {
191
+ return unsupported(`Invalid data URL metadata for embedded extension: ${id}`);
192
+ }
193
+ const payload = url.slice(comma + 1);
194
+ try {
195
+ if (encoding === 'percent') {
196
+ return {metadata: {mediaType, parameters, encoding}, bytes: new TextEncoder().encode(decodeURIComponent(payload))};
197
+ }
198
+ if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(payload)) throw new Error('Invalid base64');
199
+ const binary = atob(payload.replace(/=+$/u, ''));
200
+ return {metadata: {mediaType, parameters, encoding}, bytes: Uint8Array.from(binary, char => char.charCodeAt(0))};
201
+ } catch {
202
+ return unsupported(`Invalid data URL payload for embedded extension: ${id}`);
203
+ }
204
+ }
205
+
206
+ function hasSandboxedNoticeRequirement(bundle: ExtensionBundle, entry: EmbeddedExtension, bytes: Uint8Array): boolean {
207
+ let requirement;
208
+ if (bundle.buildMode === 'module') {
209
+ const source = entry.source;
210
+ if (isObject(source) && isObject(source.module)) requirement = source.module.unsandboxed;
211
+ } else {
212
+ const script = new TextDecoder().decode(bytes);
213
+ requirement = /^\/\/ Unsandboxed: (.+)\r?$/mu.exec(script)?.[1].trim();
214
+ }
215
+ return requirement === 'required' || requirement === 'optional';
216
+ }
217
+
218
+ export function planExtensionSave(source: FolderSource, project: Project) {
219
+ const urls = {...extensionURLs(project)};
220
+ const entries = new Map(source.embedded.extensions.map(entry => [entry.id, entry]));
221
+ const writes = new Map<string, Uint8Array>();
222
+ const sourceRemoved: string[] = [];
223
+ for (const [id, entry] of entries) {
224
+ if (!Object.hasOwn(urls, id) || (!urls[id].startsWith('data:') && urls[id] !== embeddedReference + entry.path)) entries.delete(id);
225
+ }
226
+ for (const [id, url] of Object.entries(urls)) {
227
+ if (!url.startsWith('data:')) continue;
228
+ const path = extensionPath(id);
229
+ const {metadata, bytes} = decodeDataUrl(id, url);
230
+ const name = `${id}.js`;
231
+ const previous = entries.get(id);
232
+ urls[id] = embeddedReference + path;
233
+ if (!previous || !sameBytes(source.extensionBytes.get(name)!, bytes)) {
234
+ const entry: EmbeddedExtension = {...previous, id, path, ...metadata};
235
+ if (entry.source !== undefined) {
236
+ delete entry.source;
237
+ sourceRemoved.push(id);
238
+ }
239
+ entries.set(id, entry);
240
+ writes.set(name, bytes);
241
+ }
242
+ }
243
+ const embedded: ExtensionManifest = {...source.embedded, extensions: [...entries.values()]};
244
+ if (embedded.extensionBundles) {
245
+ embedded.extensionBundles = embedded.extensionBundles.flatMap(bundle => {
246
+ const members = bundle.members.filter(id => entries.has(id) &&
247
+ // Module bundles need a managed npm module for each member.
248
+ !(bundle.buildMode === 'module' && sourceRemoved.includes(id)));
249
+ if (members.length < 2) return [];
250
+ const updated: ExtensionBundle = {...bundle, members};
251
+ const changed = members.length !== bundle.members.length || members.some(id => writes.has(`${id}.js`));
252
+ if (updated.sandboxedNotice !== undefined && changed && !members.some(id => {
253
+ const name = `${id}.js`;
254
+ return hasSandboxedNoticeRequirement(updated, entries.get(id)!, writes.get(name) ?? source.extensionBytes.get(name)!);
255
+ })) {
256
+ delete updated.sandboxedNotice;
257
+ }
258
+ return [updated];
259
+ });
260
+ }
261
+ const result = project.extensionURLs === undefined ? project : {...project, extensionURLs: urls};
262
+ validateExtensions(result, embedded);
263
+ const names = new Set(extensionNames(embedded.extensions));
264
+ return {project: result, embedded, manifestChanged: !equal(embedded, source.embedded), writes, sourceRemoved,
265
+ removed: [...source.extensionBytes.keys()].filter(name => !names.has(name))};
266
+ }
267
+
85
268
  export async function readFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource> {
86
269
  const versions = new Map<string, string>();
87
270
  const readEntry = async (dir: FileSystemDirectoryHandle, name: string, prefix = '') => {
@@ -100,52 +283,38 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
100
283
  manifest.assetsDirectory !== 'assets' || !Array.isArray(manifest.archiveEntries)) {
101
284
  return unsupported('Expected an sb3-toolchain v1 folder');
102
285
  }
103
- if (embedded.formatVersion !== 1 || !Array.isArray(embedded.extensions) || embedded.extensions.length ||
104
- (embedded.extensionBundles !== undefined && (!Array.isArray(embedded.extensionBundles) || embedded.extensionBundles.length)) ||
105
- project.turboWarpPlus !== undefined || project.customFonts !== undefined ||
106
- (project.extensionURLs !== undefined && (!isObject(project.extensionURLs) || Object.keys(project.extensionURLs).length))) {
107
- return unsupported('Custom extensions and fonts are not supported in project folders');
108
- }
109
- const expected = new Set(['project.json']);
110
- const references = new Map<string, {id: string; format: string; type: AssetType; name: string}>();
111
- for (const target of project.targets) {
112
- for (const kind of ['costumes', 'sounds'] as const) {
113
- const entries = target[kind] ?? [];
114
- if (!Array.isArray(entries)) return unsupported('Invalid asset list');
115
- for (const entry of entries) {
116
- if (!isObject(entry) || typeof entry.assetId !== 'string' || !/^[a-f0-9]{32}$/u.test(entry.assetId) ||
117
- typeof entry.dataFormat !== 'string') return unsupported('Invalid asset reference');
118
- const {assetId: id, dataFormat: format} = entry;
119
- const name = `${id}.${format}`;
120
- const type = kind === 'sounds' ?
121
- (/^(wav|mp3)$/u.test(format) ? storage.AssetType.Sound : null) :
122
- (format === 'svg' ? storage.AssetType.ImageVector :
123
- (/^(png|bmp|jpg|jpeg|gif)$/u.test(format) ? storage.AssetType.ImageBitmap : null));
124
- if (!type || entry.md5ext !== name) return unsupported(`Unsupported asset reference: ${name}`);
125
- expected.add(name);
126
- references.set(assetKey(type, id, format), {id, format, type, name});
127
- }
128
- }
129
- }
286
+ if (project.turboWarpPlus !== undefined) return unsupported('Plus extension manifests are not supported in project folders');
287
+ const extensionManifest = validateExtensions(project, embedded);
288
+ const references = projectAssets(project);
289
+ const expected = new Set(['project.json', ...references.keys()]);
130
290
  if (manifest.archiveEntries.length !== expected.size || !sameNames(new Set(manifest.archiveEntries as string[]), expected)) {
131
291
  return unsupported('Asset references and archiveEntries do not match');
132
292
  }
133
293
  expected.delete('project.json');
134
294
  const [assets, extensions] = await Promise.all([directory.getDirectoryHandle('assets'), directory.getDirectoryHandle('extensions')]);
135
- if (!sameNames(await readNames(assets), expected) || (await readNames(extensions)).size) {
295
+ const scripts = extensionNames(extensionManifest.extensions);
296
+ if (!sameNames(await readNames(assets), expected) || !sameNames(await readNames(extensions), scripts)) {
136
297
  return unsupported('Unexpected or missing source files');
137
298
  }
138
299
  const bytes = new Map(await Promise.all([...expected].map(name => readEntry(assets, name, 'assets/'))));
300
+ const extensionBytes = new Map(await Promise.all(scripts.map(name => readEntry(extensions, name, 'extensions/'))));
301
+ const loadText = extensionManifest.extensions.length ? JSON.stringify({...project, extensionURLs: {
302
+ ...extensionURLs(project),
303
+ ...Object.fromEntries(extensionManifest.extensions.map(entry =>
304
+ [entry.id, encodeDataUrl(entry, extensionBytes.get(`${entry.id}.js`)!)]))
305
+ }}) : projectText;
139
306
  const storageAssets = new Map<string, Asset>();
140
- for (const [key, {id, format, type, name}] of references) {
307
+ for (const [name, kind] of references) {
308
+ const [id, format] = name.split('.');
309
+ const type = assetTypeFor(storage, kind, format);
141
310
  const asset = storage.createAsset(type, format, bytes.get(name)!.slice(), null, true);
142
311
  if (asset.assetId !== id) return unsupported(`Asset hash mismatch: ${name}`);
143
- storageAssets.set(key, asset);
312
+ storageAssets.set(assetKey(type, id, format), asset);
144
313
  }
145
- return {versions, files, directory, bytes, project, projectText, storageAssets};
314
+ return {versions, files, directory, bytes, extensionBytes, project, loadText, storageAssets, embedded: extensionManifest};
146
315
  }
147
316
 
148
- const sameBytes = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((value, index) => value === b[index]);
317
+ export const sameBytes = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((value, index) => value === b[index]);
149
318
 
150
319
  export type FolderUpdate = {version: string; bytes: Uint8Array; project: Project};
151
320
  export type DiskChange = FolderUpdate | 'structure' | 'waiting' | null;
@@ -159,10 +328,11 @@ export async function readFolderUpdate(source: FolderSource, previous: FolderUpd
159
328
  directory.getDirectoryHandle('assets'), directory.getDirectoryHandle('extensions'), getFile(directory, projectFile)
160
329
  ]);
161
330
  const [assetNames, extensionNames] = await Promise.all([readNames(assets), readNames(extensions)]);
162
- if (!sameNames(assetNames, source.bytes.keys()) || extensionNames.size) return 'structure';
331
+ if (!sameNames(assetNames, source.bytes.keys()) || !sameNames(extensionNames, source.extensionBytes.keys())) return 'structure';
163
332
  const unchanged = await Promise.all([
164
333
  ...[manifestFile, extensionsFile].map(async name => fileVersion(await getFile(directory, name)) === versions.get(name)),
165
- ...[...assetNames].map(async name => fileVersion(await getFile(assets, name)) === versions.get(`assets/${name}`))
334
+ ...[...assetNames].map(async name => fileVersion(await getFile(assets, name)) === versions.get(`assets/${name}`)),
335
+ ...[...extensionNames].map(async name => fileVersion(await getFile(extensions, name)) === versions.get(`extensions/${name}`))
166
336
  ]);
167
337
  if (unchanged.includes(false)) return 'structure';
168
338
  const version = fileVersion(project);
@@ -174,7 +344,9 @@ export async function readFolderUpdate(source: FolderSource, previous: FolderUpd
174
344
  versions.set(projectFile, version);
175
345
  return null;
176
346
  }
177
- return {version, bytes, project: parseProject(new TextDecoder('utf-8', {fatal: true}).decode(bytes))};
347
+ const updated = parseProject(new TextDecoder('utf-8', {fatal: true}).decode(bytes));
348
+ if (!equal(source.project.extensionURLs, updated.extensionURLs)) return 'structure';
349
+ return {version, bytes, project: updated};
178
350
  } catch (error) {
179
351
  // Well-formed JSON outside the partial scope needs a whole reload. Anything else may be a write in
180
352
  // progress, such as truncated JSON or a file replaced between the probe and the read, and is retried.
@@ -186,12 +358,12 @@ export async function assertFolderUnchanged(source: FolderSource) {
186
358
  try {
187
359
  const assets = await source.directory.getDirectoryHandle('assets');
188
360
  const extensions = await source.directory.getDirectoryHandle('extensions');
189
- if (!sameNames(await readNames(assets), source.bytes.keys()) || (await readNames(extensions)).size) throw new FolderError('conflict');
190
- for (const [name, bytes] of source.files) {
191
- if (!sameBytes(await readBytes(source.directory, name), bytes)) throw new FolderError('conflict');
192
- }
193
- for (const [name, bytes] of source.bytes) {
194
- if (!sameBytes(await readBytes(assets, name), bytes)) throw new FolderError('conflict');
361
+ if (!sameNames(await readNames(assets), source.bytes.keys()) ||
362
+ !sameNames(await readNames(extensions), source.extensionBytes.keys())) throw new FolderError('conflict');
363
+ for (const [directory, files] of [[source.directory, source.files], [assets, source.bytes], [extensions, source.extensionBytes]] as const) {
364
+ for (const [name, bytes] of files) {
365
+ if (!sameBytes(await readBytes(directory, name), bytes)) throw new FolderError('conflict');
366
+ }
195
367
  }
196
368
  } catch (error) {
197
369
  if (error instanceof FolderError || (error instanceof DOMException && ['NotFoundError', 'TypeMismatchError'].includes(error.name))) {
@@ -239,7 +411,7 @@ const applyChanges = (source: Json | undefined, before: Json, after: Json): Json
239
411
 
240
412
  /** The asset files a project refers to, by file name, with the kind of list that refers to each. */
241
413
  export const projectAssets = (project: Project) => {
242
- const names = new Map<string, 'costumes' | 'sounds'>();
414
+ const names = new Map<string, AssetKind>();
243
415
  for (const target of project.targets) {
244
416
  for (const kind of ['costumes', 'sounds'] as const) {
245
417
  const entries = target[kind] ?? [];
@@ -256,10 +428,17 @@ export const projectAssets = (project: Project) => {
256
428
  }
257
429
  }
258
430
  }
431
+ const fonts = project.customFonts ?? [];
432
+ if (!Array.isArray(fonts)) return unsupported('Invalid customFonts list');
433
+ for (const font of fonts) {
434
+ if (!isObject(font) || font.system !== false || font.md5ext === undefined) continue;
435
+ if (typeof font.md5ext !== 'string' || !/^[a-f0-9]{32}\.(ttf|otf|woff2?)$/u.test(font.md5ext)) {
436
+ return unsupported('Invalid font asset reference');
437
+ }
438
+ names.set(font.md5ext, 'fonts');
439
+ }
259
440
  return names;
260
441
  };
261
- const customContent = (project: Project) => project.turboWarpPlus !== undefined || project.customFonts !== undefined ||
262
- (project.extensionURLs !== undefined && (!isObject(project.extensionURLs) || Object.keys(project.extensionURLs).length > 0));
263
442
 
264
443
  /** Runtime ids of the targets, in the order of the project's `targets`, so a renamed sprite stays the same sprite. */
265
444
  export type TargetIdentity = {before: readonly string[]; after: readonly string[]};
@@ -277,7 +456,7 @@ export function projectChanges(source: Project, before: Project, after: Project,
277
456
  return unsupported('The targets could not be identified');
278
457
  }
279
458
  projectAssets(after);
280
- if (customContent(after)) return unsupported('Custom extensions and fonts are not saved to a project folder');
459
+ if (after.turboWarpPlus !== undefined) return unsupported('Plus extension manifests are not saved to a project folder');
281
460
  if (equal(before, after) && equal([...beforeIds], [...afterIds])) return null;
282
461
  const {targets: sourceTargets, ...sourceOther} = source;
283
462
  const {targets: beforeTargets, ...beforeOther} = before;
@@ -299,6 +478,12 @@ export function projectChanges(source: Project, before: Project, after: Project,
299
478
  ordered = targets.map((target, index) => ({target, at: place(index)})).sort((a, b) => a.at - b.at).map(entry => entry.target);
300
479
  }
301
480
  const other = applyChanges(sourceOther, beforeOther, afterOther) as JsonObject;
481
+ if (!equal(before.extensionURLs, after.extensionURLs)) {
482
+ // The VM only serializes the URLs it knows. Apply its edits to those entries.
483
+ const urls = applyChanges(source.extensionURLs, extensionURLs(before), extensionURLs(after)) as JsonObject;
484
+ if (after.extensionURLs === undefined && !Object.keys(urls).length) delete other.extensionURLs;
485
+ else other.extensionURLs = urls;
486
+ }
302
487
  // Keep the folder's key order, with the targets where they were.
303
488
  const result: JsonObject = {};
304
489
  for (const key of Object.keys(source)) {
package/tsconfig.json CHANGED
@@ -5,6 +5,7 @@
5
5
  "module": "NodeNext",
6
6
  "moduleResolution": "NodeNext",
7
7
  "types": [],
8
+ "jsx": "react",
8
9
  "strict": true,
9
10
  "verbatimModuleSyntax": true,
10
11
  "declaration": true,
@@ -12,5 +13,5 @@
12
13
  "rootDir": "src",
13
14
  "outDir": "dist"
14
15
  },
15
- "include": ["src/**/*.ts"]
16
+ "include": ["src/**/*.ts", "src/**/*.tsx"]
16
17
  }
package/vite.config.ts CHANGED
@@ -1,10 +1,20 @@
1
- import {defineConfig} from 'vite';
1
+ import {defineConfig, esmExternalRequirePlugin} from 'vite';
2
2
 
3
3
  export default defineConfig({
4
4
  build: {
5
5
  // The pinned Scratch GUI still parses the library with Webpack 4.
6
6
  target: 'es2017',
7
7
  license: {fileName: 'THIRD_PARTY_NOTICES.md'},
8
- lib: {entry: 'src/index.ts', formats: ['es'], fileName: () => 'index.js'}
8
+ lib: {
9
+ entry: {index: 'src/index.ts', explorer: 'src/explorer.tsx'},
10
+ formats: ['es'],
11
+ fileName: (_format, name) => `${name}.js`
12
+ },
13
+ rolldownOptions: {
14
+ // The explorer renders with the host's React; Headless Tree is bundled.
15
+ plugins: [esmExternalRequirePlugin({external: ['react', 'react-dom']})],
16
+ // Code both entries use; it never imports React.
17
+ output: {chunkFileNames: 'shared-[hash].js'}
18
+ }
9
19
  }
10
20
  });