@kubohiroya/turbowarp-plus-editor-project-folder 0.0.0-stage → 0.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.
@@ -0,0 +1,171 @@
1
+ import {equal, isObject, unsupported} from './source.js';
2
+ import type {Json, JsonObject, Project} from './source.js';
3
+ import type {ReloadTarget} from './block-reload.js';
4
+
5
+ /** A block as the VM stores it after `deserializeBlocks`. */
6
+ export type VmBlock = {
7
+ id: string; opcode: string; topLevel: boolean; parent?: string | null; comment?: string;
8
+ fields: Record<string, {name?: string; value: unknown; id?: string | null; variableType?: string}>;
9
+ };
10
+ /** The VM's sb3 `deserializeBlocks`: turns serialized blocks into VM blocks, in place. Results are checked before use. */
11
+ export type DeserializeBlocks = (blocks: Record<string, unknown>) => Record<string, {id: string}>;
12
+
13
+ type Container = ReloadTarget['blocks'] & {
14
+ _blocks: Record<string, VmBlock>;
15
+ _scripts: string[];
16
+ createBlock(block: VmBlock, deferProjectChanged?: boolean): void;
17
+ deleteBlock(id: string): void;
18
+ resetCache(): void;
19
+ };
20
+ export type ScriptReloadTarget = ReloadTarget & {
21
+ blocks: Container;
22
+ comments?: Record<string, unknown>;
23
+ lookupVariableById?(id: string): unknown;
24
+ };
25
+
26
+ /** Replace whole scripts of one target: delete the old top blocks, then create the new scripts' blocks. */
27
+ export type ScriptEdit = {target: string; stage: boolean; remove: string[]; blocks: JsonObject};
28
+
29
+ const reject = (detail = 'Only changes to the scripts of existing targets can be reloaded in place'): never =>
30
+ unsupported(detail);
31
+ // Shadow and menu blocks use these prefixes too. Other prefixes must already appear in the project,
32
+ // so that a reload never needs an extension the VM has not loaded.
33
+ const corePrefixes = new Set(['motion', 'looks', 'sound', 'event', 'control', 'sensing', 'operator', 'data',
34
+ 'procedures', 'argument', 'math', 'text', 'colour']);
35
+ const prefix = (opcode: string) => opcode.split('_', 1)[0];
36
+ const variableFields = new Set(['VARIABLE', 'LIST', 'BROADCAST_OPTION']);
37
+
38
+ // A top-level primitive is stored as an array and is its own script.
39
+ const parentOf = (block: Json): string | null => isObject(block) && typeof block.parent === 'string' ? block.parent : null;
40
+
41
+ function rootsOf(blocks: JsonObject) {
42
+ const roots = new Map<string, string>();
43
+ for (const id of Object.keys(blocks)) {
44
+ let current = id;
45
+ const seen = new Set<string>();
46
+ for (;;) {
47
+ if (seen.has(current)) return reject('Blocks form a cycle');
48
+ seen.add(current);
49
+ const parent = parentOf(blocks[current]);
50
+ if (parent === null) break;
51
+ if (!Object.hasOwn(blocks, parent)) return reject('A block refers to a missing parent');
52
+ current = parent;
53
+ }
54
+ roots.set(id, current);
55
+ }
56
+ return roots;
57
+ }
58
+
59
+ function opcodesOf(blocks: JsonObject, into: Set<string>) {
60
+ for (const block of Object.values(blocks)) {
61
+ if (isObject(block) && typeof block.opcode === 'string') into.add(prefix(block.opcode));
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Plans script replacements for changes that add, remove or reconnect blocks. Every other property of the
67
+ * project and its targets, including comments, must stay the same; otherwise the whole project is reloaded.
68
+ */
69
+ export function planScriptReload(before: Project, after: Project): ScriptEdit[] {
70
+ const {targets: oldTargets, ...oldProject} = before;
71
+ const {targets: newTargets, ...newProject} = after;
72
+ if (oldTargets.length !== newTargets.length || !equal(oldProject, newProject)) return reject();
73
+ const known = new Set(corePrefixes);
74
+ for (const target of oldTargets) if (isObject(target.blocks)) opcodesOf(target.blocks, known);
75
+ const edits: ScriptEdit[] = [];
76
+ for (const [index, oldTarget] of oldTargets.entries()) {
77
+ const {blocks: oldValue, ...oldRest} = oldTarget;
78
+ const {blocks: newValue, ...newRest} = newTargets[index];
79
+ if (!equal(oldRest, newRest)) return reject();
80
+ if (equal(oldValue, newValue)) continue;
81
+ const oldBlocks = isObject(oldValue) ? oldValue : {};
82
+ const newBlocks = isObject(newValue) ? newValue : {};
83
+ const oldRoots = rootsOf(oldBlocks);
84
+ const newRoots = rootsOf(newBlocks);
85
+ const removed = new Set<string>();
86
+ const added = new Set<string>();
87
+ const mark = (id: string) => {
88
+ const oldRoot = oldRoots.get(id);
89
+ const newRoot = newRoots.get(id);
90
+ let grew = false;
91
+ if (oldRoot !== undefined && !removed.has(oldRoot)) {removed.add(oldRoot); grew = true;}
92
+ if (newRoot !== undefined && !added.has(newRoot)) {added.add(newRoot); grew = true;}
93
+ return grew;
94
+ };
95
+ for (const id of new Set([...Object.keys(oldBlocks), ...Object.keys(newBlocks)])) {
96
+ if (!equal(oldBlocks[id], newBlocks[id])) mark(id);
97
+ }
98
+ // A block in a replaced script is replaced with it on both sides, so no script is left half-moved.
99
+ for (let grew = true; grew;) {
100
+ grew = false;
101
+ for (const [id, root] of oldRoots) if (removed.has(root) && mark(id)) grew = true;
102
+ for (const [id, root] of newRoots) if (added.has(root) && mark(id)) grew = true;
103
+ }
104
+ const blocks: JsonObject = {};
105
+ for (const [id, root] of newRoots) if (added.has(root)) blocks[id] = newBlocks[id];
106
+ for (const block of Object.values(blocks)) {
107
+ if (!isObject(block)) continue;
108
+ if (typeof block.opcode !== 'string') return reject('A block has no opcode');
109
+ if (!known.has(prefix(block.opcode))) return reject(`Blocks need an extension the project does not use: ${block.opcode}`);
110
+ }
111
+ edits.push({target: oldTarget.name, stage: oldTarget.isStage, remove: [...removed], blocks});
112
+ }
113
+ return edits;
114
+ }
115
+
116
+ const resolveTarget = (targets: readonly ScriptReloadTarget[], edit: ScriptEdit) => {
117
+ const matching = targets.filter(target => target.isStage === edit.stage &&
118
+ (edit.stage || target.isOriginal && target.getName() === edit.target));
119
+ return matching.length === 1 ? matching[0] : reject();
120
+ };
121
+
122
+ /**
123
+ * Applies planned script replacements. Every edit is checked against the VM before any change. If a change
124
+ * fails part way, every target is restored to its previous blocks.
125
+ */
126
+ export function applyScriptReload(targets: readonly ScriptReloadTarget[], edits: ScriptEdit[], deserialize: DeserializeBlocks) {
127
+ const prepared = edits.map(edit => {
128
+ const target = resolveTarget(targets, edit);
129
+ const container = target.blocks;
130
+ for (const id of edit.remove) {
131
+ const block = container.getBlock(id);
132
+ if (!block || !block.topLevel || !container._scripts.includes(id)) return reject('The editor and the folder differ');
133
+ }
134
+ const created = Object.values(deserialize(JSON.parse(JSON.stringify(edit.blocks)))) as VmBlock[];
135
+ for (const block of created) {
136
+ if (typeof block.id !== 'string' || typeof block.opcode !== 'string') return reject('A block could not be read');
137
+ if (block.comment && !(target.comments && Object.hasOwn(target.comments, block.comment))) {
138
+ return reject('A block refers to a missing comment');
139
+ }
140
+ for (const [name, field] of Object.entries(block.fields ?? {})) {
141
+ if (!variableFields.has(name) && !field.variableType) continue;
142
+ if (typeof field.id !== 'string' || !target.lookupVariableById?.(field.id)) {
143
+ return reject('A block refers to a variable, list or message the project does not have');
144
+ }
145
+ }
146
+ }
147
+ return {target, container, edit, created};
148
+ });
149
+ const saved = prepared.map(({container}) => ({container, blocks: {...container._blocks}, scripts: [...container._scripts],
150
+ tops: new Map(Object.entries(container._blocks).map(([id, block]) => [id, block.topLevel]))}));
151
+ try {
152
+ for (const {container, edit, created} of prepared) {
153
+ for (const id of edit.remove) container.deleteBlock(id);
154
+ for (const block of created) {
155
+ container.createBlock(block, true);
156
+ // createBlock ignores an id that is already present, which would leave the script incomplete.
157
+ if (container._blocks[block.id] !== block) reject('A block id is already in use');
158
+ }
159
+ container.resetCache();
160
+ }
161
+ } catch (error) {
162
+ for (const {container, blocks, scripts, tops} of saved) {
163
+ container._blocks = blocks;
164
+ container._scripts = scripts;
165
+ for (const [id, top] of tops) blocks[id].topLevel = top;
166
+ container.resetCache();
167
+ }
168
+ throw error;
169
+ }
170
+ return prepared.map(({target}) => target);
171
+ }
package/src/session.ts ADDED
@@ -0,0 +1,300 @@
1
+ import {assetKey, assertFolderUnchanged, FolderError, parseProject, projectChanges, projectFile, readFolder, readFolderUpdate} from './source.js';
2
+ import type {Asset, FolderSource, FolderUpdate, Project, Storage} from './source.js';
3
+ import {applyBlockReload, planBlockReload} from './block-reload.js';
4
+ import type {ReloadTarget} from './block-reload.js';
5
+ import {applyScriptReload, planScriptReload} from './script-reload.js';
6
+ import type {DeserializeBlocks, ScriptReloadTarget} from './script-reload.js';
7
+
8
+ export interface FolderVM {
9
+ runtime: {
10
+ storage: Storage;
11
+ targets?: readonly ReloadTarget[];
12
+ getTargetForStage(): object | null;
13
+ on(event: 'PROJECT_LOADED', listener: () => void): void;
14
+ off(event: 'PROJECT_LOADED', listener: () => void): void;
15
+ };
16
+ on(event: 'PROJECT_CHANGED', listener: () => void): void;
17
+ off(event: 'PROJECT_CHANGED', listener: () => void): void;
18
+ quit(): void;
19
+ loadProject(project: string): Promise<unknown>;
20
+ toJSON(target?: string, options?: {allowOptimization: boolean}): string;
21
+ renderer?: {draw(): void};
22
+ }
23
+
24
+ type FileSystemPicker = (options: {id: string; mode: 'readwrite'}) => Promise<FileSystemDirectoryHandle>;
25
+ export type PickerWindow = Window & {showDirectoryPicker?: FileSystemPicker};
26
+
27
+ const storageReaders = new WeakMap<Storage, {assets: Map<string, Asset> | null}>();
28
+ const readerFor = (storage: Storage) => {
29
+ const existing = storageReaders.get(storage);
30
+ if (existing) return existing;
31
+ const reader: {assets: Map<string, Asset> | null} = {assets: null};
32
+ storage.addHelper({load(type, id, format) {
33
+ const asset = reader.assets?.get(assetKey(type, id, format));
34
+ return asset ? Promise.resolve(asset) : null;
35
+ }}, 101);
36
+ storageReaders.set(storage, reader);
37
+ return reader;
38
+ };
39
+
40
+ export interface FolderHost {
41
+ isProjectDirty(): boolean;
42
+ beforeLoad(): void;
43
+ onOpened(title: string): void;
44
+ onSaved(): void;
45
+ blockReload?: {
46
+ isRunning(): boolean;
47
+ subscribe(listener: () => void): () => void;
48
+ onApplied(targets: readonly ReloadTarget[]): void;
49
+ /**
50
+ * The VM's sb3 `deserializeBlocks`. With it, changes that add, remove or reconnect blocks replace the
51
+ * changed scripts in place; without it they need the whole project reloaded.
52
+ */
53
+ deserializeBlocks?: DeserializeBlocks;
54
+ };
55
+ }
56
+
57
+ // `stable` turns true once two scans see the same file version, so consecutive writes settle before auto-apply.
58
+ type Edits = {kind: 'values'; changes: ReturnType<typeof planBlockReload>} |
59
+ {kind: 'scripts'; changes: ReturnType<typeof planScriptReload>};
60
+ type PendingUpdate = {update: FolderUpdate; edits: Edits | null; stable: boolean};
61
+ type Pending = PendingUpdate | 'structure' | 'waiting';
62
+ type Session = {source: FolderSource; baseline: Project; stage: object; pending: Pending | null};
63
+ /**
64
+ * `ready`: the change can be applied in place: values and positions, or with `deserializeBlocks`, whole scripts. `full`: the change needs the whole project reloaded.
65
+ * `waiting`: an external write looks incomplete and is checked again. `dirty`, `running` and `busy` hold the change.
66
+ */
67
+ export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
68
+ /** What the reload command does for the pending change, regardless of whether it may run now. */
69
+ export type ReloadKind = 'partial' | 'full' | null;
70
+ export type OpenResult = 'opened' | 'cancelled';
71
+ export type SaveResult = 'saved' | 'unchanged';
72
+
73
+ export function createFolderSession(vm: FolderVM, host: FolderHost) {
74
+ let current: Session | null = null;
75
+ let busy = false;
76
+ let disposed = false;
77
+ let revision = 0;
78
+ let scanning: Promise<void> | null = null;
79
+ const snapshot = () => parseProject(vm.toJSON(undefined, {allowOptimization: false}));
80
+ const changed = () => {revision++;};
81
+ const loaded = () => {current = null;};
82
+ vm.runtime.on('PROJECT_LOADED', loaded);
83
+ vm.on('PROJECT_CHANGED', changed);
84
+ const active = (session: Session) => {
85
+ if (disposed || current !== session || vm.runtime.getTargetForStage() !== session.stage) {
86
+ throw new FolderError('conflict');
87
+ }
88
+ };
89
+ const dispose = () => {
90
+ disposed = true;
91
+ current = null;
92
+ vm.runtime.off('PROJECT_LOADED', loaded);
93
+ vm.off('PROJECT_CHANGED', changed);
94
+ };
95
+ const openFrom = async (
96
+ getDirectory: () => Promise<FileSystemDirectoryHandle | null>,
97
+ confirmReplace: () => boolean
98
+ ): Promise<OpenResult> => {
99
+ if (disposed || busy) return 'cancelled';
100
+ busy = true;
101
+ const priorStage = vm.runtime.getTargetForStage();
102
+ try {
103
+ const directory = await getDirectory();
104
+ if (!directory || disposed) return 'cancelled';
105
+ const storage = vm.runtime.storage;
106
+ const source = await readFolder(directory, storage);
107
+ if (disposed || vm.runtime.getTargetForStage() !== priorStage) return 'cancelled';
108
+ if (host.isProjectDirty() && !confirmReplace()) return 'cancelled';
109
+ host.beforeLoad();
110
+ current = null;
111
+ const reader = readerFor(storage);
112
+ const assets = source.storageAssets;
113
+ reader.assets = assets;
114
+ let stage: object | null;
115
+ try {
116
+ vm.quit();
117
+ await vm.loadProject(source.projectText);
118
+ stage = vm.runtime.getTargetForStage();
119
+ } finally {
120
+ if (reader.assets === assets) reader.assets = null;
121
+ }
122
+ if (disposed || !stage || vm.runtime.getTargetForStage() !== stage) return 'cancelled';
123
+ host.onOpened(directory.name);
124
+ current = {source, stage, baseline: snapshot(), pending: null};
125
+ vm.renderer?.draw();
126
+ return 'opened';
127
+ } finally {
128
+ busy = false;
129
+ }
130
+ };
131
+ // Value and position edits keep every VM block. Other script changes replace only the changed scripts.
132
+ const planEdits = (before: Project, after: Project): Edits | null => {
133
+ try {
134
+ return {kind: 'values', changes: planBlockReload(before, after)};
135
+ } catch (error) {
136
+ if (!(error instanceof FolderError)) throw error;
137
+ }
138
+ if (!host.blockReload?.deserializeBlocks) return null;
139
+ try {
140
+ return {kind: 'scripts', changes: planScriptReload(before, after)};
141
+ } catch (error) {
142
+ if (!(error instanceof FolderError)) throw error;
143
+ return null;
144
+ }
145
+ };
146
+ const readUpdate = async (session: Session): Promise<Session['pending']> => {
147
+ const previous = typeof session.pending === 'object' ? session.pending : null;
148
+ const update = await readFolderUpdate(session.source, previous?.update ?? null);
149
+ if (!update || typeof update === 'string') return update;
150
+ if (previous?.update === update) return {...previous, stable: true};
151
+ return {update, edits: planEdits(session.source.project, update.project), stable: false};
152
+ };
153
+ const reloadKind = (): ReloadKind => {
154
+ const pending = current?.pending;
155
+ if (!pending || pending === 'waiting') return null;
156
+ return pending === 'structure' || pending.edits === null ? 'full' : 'partial';
157
+ };
158
+ const reloadState = (): ReloadState => {
159
+ const pending = current?.pending;
160
+ if (!pending) return null;
161
+ if (busy) return 'busy';
162
+ if (pending === 'waiting') return 'waiting';
163
+ if (host.isProjectDirty()) return 'dirty';
164
+ if (host.blockReload?.isRunning()) return 'running';
165
+ return reloadKind() === 'full' ? 'full' : 'ready';
166
+ };
167
+ const canApply = () => !host.isProjectDirty() && !host.blockReload?.isRunning();
168
+ return {
169
+ detach() {current = null;},
170
+ get canSave() {return current !== null;},
171
+ get busy() {return busy;},
172
+ get reloadState() {return reloadState();},
173
+ get reloadKind() {return reloadKind();},
174
+ /** A partial change that has stayed the same across two scans and may be applied without asking. */
175
+ get canAutoReload() {
176
+ const pending = current?.pending;
177
+ return reloadState() === 'ready' && typeof pending === 'object' && pending !== null && pending.stable;
178
+ },
179
+ /** True while a change is new or looks incomplete, so a host can look again sooner than its interval. */
180
+ get settling() {
181
+ const pending = current?.pending;
182
+ return pending === 'waiting' || (typeof pending === 'object' && pending !== null && !pending.stable);
183
+ },
184
+ /** Identifies the pending project file version, so a host can attempt an automatic apply only once. */
185
+ get pendingVersion() {
186
+ const pending = current?.pending;
187
+ return typeof pending === 'object' && pending !== null ? pending.update.version : null;
188
+ },
189
+ get directory() {return current?.source.directory ?? null;},
190
+ refresh(): Promise<void> {
191
+ if (disposed || busy || !current || !host.blockReload) return Promise.resolve();
192
+ if (scanning) return scanning;
193
+ const session = current;
194
+ const baseline = session.baseline;
195
+ scanning = readUpdate(session).then(pending => {
196
+ if (current === session && session.baseline === baseline && !busy) session.pending = pending;
197
+ }).finally(() => {scanning = null;});
198
+ return scanning;
199
+ },
200
+ async reload(): Promise<boolean> {
201
+ if (!current || reloadState() !== 'ready' || !host.blockReload) return false;
202
+ const session = current;
203
+ active(session);
204
+ busy = true;
205
+ try {
206
+ const editRevision = revision;
207
+ const pending = await readUpdate(session);
208
+ if (current !== session || disposed || vm.runtime.getTargetForStage() !== session.stage) return false;
209
+ session.pending = pending;
210
+ if (!pending || typeof pending === 'string' || pending.edits === null || editRevision !== revision || !canApply()) {
211
+ return false;
212
+ }
213
+ let targets: readonly ReloadTarget[];
214
+ try {
215
+ const {edits} = pending;
216
+ targets = edits.kind === 'values' ? applyBlockReload(vm.runtime.targets ?? [], edits.changes) :
217
+ applyScriptReload((vm.runtime.targets ?? []) as readonly ScriptReloadTarget[], edits.changes,
218
+ host.blockReload.deserializeBlocks!);
219
+ } catch (error) {
220
+ // After a refused or failed in-place change, offer the whole reload instead of retrying it.
221
+ session.pending = {...pending, edits: null};
222
+ throw error;
223
+ }
224
+ session.baseline = snapshot();
225
+ session.source.project = pending.update.project;
226
+ session.source.files.set(projectFile, pending.update.bytes);
227
+ session.source.versions.set(projectFile, pending.update.version);
228
+ session.pending = null;
229
+ host.blockReload.onApplied(targets);
230
+ return true;
231
+ } finally {
232
+ busy = false;
233
+ }
234
+ },
235
+ /**
236
+ * Reads the open folder again and replaces the project, for changes a partial reload cannot apply. Unsaved
237
+ * edits are discarded only when `confirmReplace` agrees. The VM is left untouched while a project runs.
238
+ */
239
+ reloadAll(confirmReplace: () => boolean): Promise<OpenResult> {
240
+ const session = current;
241
+ if (!session || !session.pending || session.pending === 'waiting' || host.blockReload?.isRunning()) {
242
+ return Promise.resolve('cancelled');
243
+ }
244
+ return openFrom(() => Promise.resolve(current === session ? session.source.directory : null), confirmReplace);
245
+ },
246
+ open(pick: FileSystemPicker, confirmReplace: () => boolean): Promise<OpenResult> {
247
+ return openFrom(async () => {
248
+ try {
249
+ return await pick({id: 'turbowarp-plus-project-folder', mode: 'readwrite'});
250
+ } catch (error) {
251
+ if (error instanceof DOMException && error.name === 'AbortError') return null;
252
+ throw error;
253
+ }
254
+ }, confirmReplace);
255
+ },
256
+ openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean): Promise<OpenResult> {
257
+ return openFrom(() => Promise.resolve(directory), confirmReplace);
258
+ },
259
+ async save(): Promise<SaveResult> {
260
+ if (!current || busy) throw new FolderError('conflict');
261
+ const session = current;
262
+ active(session);
263
+ busy = true;
264
+ try {
265
+ const saveRevision = revision;
266
+ const edited = snapshot();
267
+ const result = projectChanges(session.source.project, session.baseline, edited);
268
+ await assertFolderUnchanged(session.source);
269
+ active(session);
270
+ if (!result) {
271
+ if (revision === saveRevision) host.onSaved();
272
+ return 'unchanged';
273
+ }
274
+ const text = `${JSON.stringify(result, null, 2)}\n`;
275
+ const file = await session.source.directory.getFileHandle(projectFile);
276
+ const options = {mode: 'exclusive'} as FileSystemCreateWritableOptions;
277
+ const writable = await file.createWritable(options);
278
+ try {
279
+ await writable.write(text);
280
+ await assertFolderUnchanged(session.source);
281
+ active(session);
282
+ await writable.close();
283
+ } catch (error) {
284
+ await writable.abort().catch(() => {});
285
+ throw error;
286
+ }
287
+ session.source.project = result;
288
+ session.source.files.set(projectFile, new TextEncoder().encode(text));
289
+ session.source.versions.delete(projectFile);
290
+ session.baseline = edited;
291
+ session.pending = null;
292
+ if (current === session && revision === saveRevision) host.onSaved();
293
+ return 'saved';
294
+ } finally {
295
+ busy = false;
296
+ }
297
+ },
298
+ dispose
299
+ };
300
+ }