@volter/play 0.5.211 → 0.5.212

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/play-log.ts CHANGED
@@ -1,70 +1,57 @@
1
1
  /**
2
- * THE MODEL PLAY LOG — what a play script says happened, stamped with the run's own clock.
2
+ * THE MODEL PLAY LOG: what a std game's run says happened.
3
3
  *
4
- * The game editor's play log is the receipt of a run (`play-*.jsonl`, `log-format.ts`); this
5
- * is Model Play's. A script calls `play.log(kind, facts)` (`play-script.ts`) on the
6
- * transitions that explain a run — a jump, a landing, a death and its cause, autoplay's
7
- * choice — and an agent reads them back with `cyclotron play-log` or
8
- * `editor.modelPlayLog()` in `eval`. `console.log` cannot do this job: the session's
9
- * console feed keeps warnings and errors only.
4
+ * Each player's page traces its run (std's trace, as the dev server's receiver writes it, `build/runs/<run>/<page>.jsonl`)
5
+ * and the run reads each trace into this log, each entry tagged with its player's slot (`std-game.ts`, `source:
6
+ * 'script'`). Play adds its own lifecycle entries (`source: 'play'`): `play-start`, `running`, `player-joined`,
7
+ * `player-page-loaded`, `player-left`, `view`, `autoplay-on` and `autoplay-off` (each with `by`), `pause`, `resume`,
8
+ * `step` and `speed` (each with the clock std answered), `capture` (its file), `script-error` (with its `phase`) and
9
+ * `play-stop`. An agent reads them back with `cyclotron play-log` or `editor.contributedVerb('model-play-log')` in
10
+ * `eval`: the session's console feed keeps warnings and errors only.
10
11
  *
11
- * Every entry carries `simT` (the seconds of simulation since Play started: the sum of the
12
- * `dt`s the runner has handed to `update`) and `tick` (the number of the update in
13
- * progress; 0 while the script's default export runs), the same two stamps the game
14
- * editor's entries carry. They are the Game panel's clock too: the runner advances both at
15
- * the same call (`play-script.ts`), so they stand still while paused and run at the speed. The
16
- * runner adds its own lifecycle entries (`source: 'play'`): `play-start`, `play-restart` (a
17
- * Restart's fresh run, right after its `play-start`), `script-reload` with its reason,
18
- * `script-error`, `tint-unsupported`, `tint-unknown-object`, `pause`, `resume`, `step` (one per
19
- * stepped update, with its `dt`), `speed` (on a change, and at a start that is not 1×),
20
- * `autoplay-on` and `autoplay-off` (each with `by`: `panel`, `cli`, `takeover`, `script`),
21
- * `autoplay-unavailable` (a script ran its first update without offering a bot),
22
- * `play-stop`.
12
+ * WHEN EACH HAPPENED: a trace entry carries its page's own time, its trace's step (std's trace format 3: `s`, sixty a
13
+ * second of the page's steady clock) as `tick` and that step in seconds as `simT`; Play's own entries carry the run's
14
+ * elapsed seconds since its `play-start` as `simT`, and the newest trace step heard as `tick`. So `--since` reads the
15
+ * run's seconds, a page's from its own start.
23
16
  *
24
- * ONE LOG PER MODEL DOCUMENT, each its document's latest run. Two documents playing at once
25
- * keep separate logs; a read names its document or takes the active Play's (the latest
26
- * started that still plays, else the latest started). Play starting from a fresh copy
27
- * replaces its document's log; a script reload does not, and the log outlives Stop so a
28
- * finished run can be read. The runner writes through the {@link ModelPlayRun} handle Play
29
- * started: once that run has ended its handle writes nothing, so a stale timer of an old
30
- * script cannot reach the next run's log.
17
+ * ONE LOG PER MODEL DOCUMENT, each its document's latest run. A read names its document or takes the active Play's
18
+ * (the latest started that still plays, else the latest started). Each Play replaces its document's log, and the log
19
+ * outlives Stop so a finished run can be read. The run writes through the {@link ModelPlayRun} handle Play started:
20
+ * once that run has ended its handle writes nothing, so a stale timer of an old run cannot reach the next run's log.
31
21
  *
32
- * BOUNDED AND PAGE-LIFETIME. The newest {@link MODEL_PLAY_LOG_CAPACITY} entries of a run are
33
- * kept in a ring (older ones are counted in `dropped`); one entry's facts are kept as JSON of
34
- * at most {@link MODEL_PLAY_LOG_FACTS_CHARS} characters. It is never stored: a reload of the
35
- * page forgets it, as it forgets the game.
22
+ * BOUNDED AND PAGE-LIFETIME. The newest {@link MODEL_PLAY_LOG_CAPACITY} entries of a run are kept in a ring (older
23
+ * ones are counted in `dropped`); one entry's facts are kept as JSON of at most {@link MODEL_PLAY_LOG_FACTS_CHARS}
24
+ * characters. It is never stored: a reload of the page forgets it, as it forgets the run.
36
25
  *
37
- * THE GAME PANEL DRAWS IT LIVE: {@link subscribeModelPlayLog} hears every write, and
38
- * {@link tailModelPlayLog} reads the newest entries of one document without copying the ring.
39
- *
40
- * Logging is a read of the script's own values: it never throws into the script and touches
41
- * neither the clock nor the copy.
26
+ * THE GAME PANEL DRAWS IT LIVE: {@link subscribeModelPlayLog} hears every write, and {@link tailModelPlayLog} reads the
27
+ * newest entries of one document without copying the ring.
42
28
  */
43
29
 
44
- /** Entries a run's ring keeps; the oldest beyond this are dropped and counted. */
45
- export const MODEL_PLAY_LOG_CAPACITY = 5000;
46
- /** The longest JSON one entry's facts keep; longer facts are kept truncated, as a string. */
47
- export const MODEL_PLAY_LOG_FACTS_CHARS = 2048;
48
-
30
+ /** One entry of a document's play log (`model-play-log`): read from a player's page's trace, or written by Play. */
49
31
  export interface ModelPlayLogEntry {
50
- /** The entry's place in this run, from 0: a gap in `seq` is entries the ring dropped. */
32
+ /** The entry's place in its run, from 0: a gap in `seq` is entries the bounded log dropped. */
51
33
  readonly seq: number;
52
34
  /** Wall-clock ms. */
53
35
  readonly t: number;
54
- /** Seconds of simulation since Play started, across script reloads. */
36
+ /** When it happened: a trace entry's page time (its step's seconds, and its step), Play's own the run's elapsed
37
+ * seconds (and the newest step heard). */
55
38
  readonly simT: number;
56
- /** The update in progress (the first is 1); 0 before the first. */
57
39
  readonly tick: number;
58
40
  readonly kind: string;
59
- /** `script` for the play script's own entries; `play` for the runner's lifecycle ones. */
41
+ /** `script` for the game's own entries (its pages' traces); `play` for Play's lifecycle ones. */
60
42
  readonly source: 'script' | 'play';
61
43
  readonly facts?: Record<string, unknown>;
62
44
  }
63
45
 
46
+ /** Entries a run's ring keeps; the oldest beyond this are dropped and counted. */
47
+ const MODEL_PLAY_LOG_CAPACITY = 5000;
48
+ /** The longest JSON one entry's facts keep; longer facts are kept truncated, as a string. */
49
+ const MODEL_PLAY_LOG_FACTS_CHARS = 2048;
50
+
64
51
  export interface ModelPlayLogReading {
65
52
  /** The run is still playing; false after Stop, or when nothing has played. */
66
53
  readonly playing: boolean;
67
- /** The model document and play script of the run read; null when nothing has played. */
54
+ /** The model document and what its run ran (the game's dev server command); null when nothing has played. */
68
55
  readonly documentId: string | null;
69
56
  readonly script: string | null;
70
57
  readonly startedAt: number | null;
@@ -84,7 +71,7 @@ export interface ModelPlayLogReading {
84
71
  export interface ModelPlayLogQuery {
85
72
  /** The model document whose log to read; the active Play's when omitted. */
86
73
  readonly documentId?: string;
87
- /** Only entries at or after this simulation time (seconds). */
74
+ /** Only entries at or after this game time (seconds). */
88
75
  readonly since?: number;
89
76
  /** Only entries of this kind. */
90
77
  readonly kind?: string;
@@ -103,17 +90,16 @@ interface Run {
103
90
  readonly kinds: Set<string>;
104
91
  }
105
92
 
106
- /** The runner's door onto its own run's log: inert once the run has ended. */
93
+ /** The run's door onto its own log: inert once the run has ended. */
107
94
  export interface ModelPlayRun {
108
- /** The runner is about to call `update(deltaSeconds)`. */
109
- advance(deltaSeconds: number): void;
110
- append(source: ModelPlayLogEntry['source'], kind: string, facts?: unknown): void;
95
+ /** An entry, stamped with `at` (a trace line's page time) or else the run's elapsed seconds. */
96
+ append(source: ModelPlayLogEntry['source'], kind: string, facts?: unknown, at?: { readonly simT: number; readonly tick: number }): void;
111
97
  /** `play-stop`, then nothing more is written; the entries stay readable. */
112
98
  end(facts?: Record<string, unknown>): void;
113
99
  }
114
100
 
115
101
  // One registry per page, whichever copy of this module a contribution loaded it through: the
116
- // runner writes it from the service, the session verb reads it from the command module.
102
+ // run writes it, the session verb reads it from the command module.
117
103
  const key = Symbol.for('volter.model-play-log');
118
104
  const page = globalThis as typeof globalThis & { [key]?: Map<string, Run> };
119
105
  const runs: Map<string, Run> = page[key] ??= new Map();
@@ -133,29 +119,62 @@ export function subscribeModelPlayLog(listener: () => void): () => void {
133
119
  return () => { listeners.delete(listener); };
134
120
  }
135
121
 
122
+ /** The facts that say what happened, first in an entry's facts: an error's message (std's trace `label`), then its
123
+ * source and where. */
124
+ const MEANING_FIRST = ['label', 'message', 'why', 'text', 'source', 'file', 'line', 'column', 'slot'];
125
+ /** The frames of a stack an entry keeps once its facts are too long. */
126
+ const STACK_FRAMES = 4;
127
+
128
+ /** Facts in the order that keeps their meaning: what happened first, everything else after. */
129
+ function meaningFirst(facts: Record<string, unknown>): Record<string, unknown> {
130
+ const first = MEANING_FIRST.filter((key) => key in facts);
131
+ return Object.fromEntries([...first, ...Object.keys(facts).filter((key) => !first.includes(key))].map((key) => [key, facts[key]]));
132
+ }
133
+
134
+ /** Facts too long to keep whole, shortened where it costs no meaning: the trace's session goes, a URL keeps its path,
135
+ * a stack its first frames, each frame's URL its path. */
136
+ function shortened(facts: Record<string, unknown>): Record<string, unknown> {
137
+ const path = (text: string): string => text.replace(/\bhttps?:\/\/[^/\s)]+/g, '').replace(/\?[^\s):]*/g, '');
138
+ const kept: Record<string, unknown> = {};
139
+ for (const [key, value] of Object.entries(facts)) {
140
+ if (key === 'session') continue;
141
+ kept[key] = typeof value !== 'string' ? value
142
+ : key === 'stack' ? path(value.split('\n').slice(0, STACK_FRAMES + 1).join('\n'))
143
+ : key === 'label' || key === 'message' ? value
144
+ : path(value);
145
+ }
146
+ return kept;
147
+ }
148
+
136
149
  function keptFacts(facts: unknown): Record<string, unknown> | undefined {
137
150
  if (facts === undefined || facts === null) return undefined;
138
151
  let json: string | undefined;
139
- try { json = JSON.stringify(facts); }
152
+ const ordered = typeof facts === 'object' && !Array.isArray(facts) ? meaningFirst(facts as Record<string, unknown>) : facts;
153
+ try { json = JSON.stringify(ordered); }
140
154
  catch (error) { return { unserializable: error instanceof Error ? error.message : String(error) }; }
141
155
  if (json === undefined) return undefined;
156
+ if (json.length > MODEL_PLAY_LOG_FACTS_CHARS && ordered !== facts) json = JSON.stringify(shortened(ordered as Record<string, unknown>));
142
157
  if (json.length > MODEL_PLAY_LOG_FACTS_CHARS) return { truncated: json.slice(0, MODEL_PLAY_LOG_FACTS_CHARS) };
143
158
  // A snapshot, so a script that goes on mutating what it logged does not rewrite history.
144
159
  const value: unknown = JSON.parse(json);
145
160
  return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : { value };
146
161
  }
147
162
 
148
- function append(run: Run, source: ModelPlayLogEntry['source'], kind: string, facts?: unknown): void {
163
+ function append(run: Run, source: ModelPlayLogEntry['source'], kind: string, facts?: unknown, at?: { readonly simT: number; readonly tick: number }): void {
149
164
  try {
150
165
  const kept = keptFacts(facts);
166
+ const t = Date.now();
167
+ const simT = at?.simT ?? (t - run.startedAt) / 1000;
168
+ if (at !== undefined) run.tick = Math.max(run.tick, at.tick);
169
+ run.simT = Math.max(run.simT, (t - run.startedAt) / 1000);
151
170
  const entry: ModelPlayLogEntry = {
152
- seq: run.total, t: Date.now(), simT: run.simT, tick: run.tick, kind: String(kind), source,
171
+ seq: run.total, t, simT, tick: at?.tick ?? run.tick, kind: String(kind), source,
153
172
  ...(kept ? { facts: kept } : {}),
154
173
  };
155
174
  run.ring[run.total % MODEL_PLAY_LOG_CAPACITY] = entry;
156
175
  run.total += 1;
157
176
  run.kinds.add(entry.kind);
158
- } catch { /* A log that cannot be written is not the script's failure. */ }
177
+ } catch { /* A log that cannot be written is not the run's failure. */ }
159
178
  publish();
160
179
  }
161
180
 
@@ -168,12 +187,7 @@ export function beginModelPlayLog(documentId: string, script: string): ModelPlay
168
187
  runs.set(documentId, run);
169
188
  append(run, 'play', 'play-start', { documentId, script });
170
189
  return {
171
- advance(deltaSeconds) {
172
- if (!run.playing) return;
173
- run.tick += 1;
174
- run.simT += deltaSeconds;
175
- },
176
- append(source, kind, facts) { if (run.playing) append(run, source, kind, facts); },
190
+ append(source, kind, facts, at) { if (run.playing) append(run, source, kind, facts, at); },
177
191
  end(facts) {
178
192
  if (!run.playing) return;
179
193
  append(run, 'play', 'play-stop', facts);
@@ -206,7 +220,8 @@ export function readModelPlayLog(query: ModelPlayLogQuery = {}): ModelPlayLogRea
206
220
  }
207
221
  return {
208
222
  playing: run.playing, documentId: run.documentId, script: run.script, startedAt: run.startedAt, documents,
209
- simT: run.simT, tick: run.tick, capacity: MODEL_PLAY_LOG_CAPACITY, total: run.total, dropped, entries,
223
+ simT: run.playing ? Math.max(run.simT, (Date.now() - run.startedAt) / 1000) : run.simT, tick: run.tick,
224
+ capacity: MODEL_PLAY_LOG_CAPACITY, total: run.total, dropped, entries,
210
225
  };
211
226
  }
212
227
 
@@ -0,0 +1,128 @@
1
+ /**
2
+ * STD'S DEVICE CONTROLS, AS PLAY SPEAKS THEM. Every word Play says to a player's page goes through this module, so a
3
+ * change in std's shapes is a change here alone. Each is std's own control (`POST /__std/devices/<id>/control`,
4
+ * std-dev's std-endpoints.ts), reached through play's session route (`../serving/std-dev.ts`), which holds the dev
5
+ * server's token:
6
+ *
7
+ * - `clock`: `{ control: 'clock', action: 'pause' | 'resume' | 'step' | 'speed', frames?, speed? }`, answered with the
8
+ * page's clock, `{ paused, speed, time, frame }` (`time` in seconds; speed one of 0.25, 0.5, 1, 2, 4; a step pauses
9
+ * first, then runs `frames` frames of 1/60 s). It holds the page: a room the game hosts beside it runs on, since
10
+ * Colyseus has no pause for a room.
11
+ * - `inspect`: `{ control: 'inspect' }`, answered with the scene the page last drew and its labelled screen nodes,
12
+ * `{ objects, screen, truncated? }` (at most 2000 objects and 500 nodes, `truncated` saying how many were left out).
13
+ * - `act`: `{ control: 'act', actions, observe? }`, std-driver/2 `Action`s through the page's own input path, answered
14
+ * with the observation (std-driver/2 `Observation`) where `observe` asks for one, else `{ ok: true }`. A refused
15
+ * action fails the whole control, the actions before it already taken.
16
+ *
17
+ * `clock`, `inspect` and `act` need a device of exactly one page (a tab or a frame, as each of Play's players is).
18
+ * Each refusal is std's own answer (HTTP 400, `{ error }`), thrown with its words.
19
+ * - `autoplay` and `manual`: who drives the page, its bot (with its slot and goal) or the person.
20
+ * - `capture`: the page's next frame, written by std's receiver, answered with its file.
21
+ *
22
+ * The session's other routes for a std game (whether the project is one, its dev server, its devices, its pages and
23
+ * their traces, its bot's goals) are asked through {@link askPlay} too.
24
+ */
25
+
26
+ const ROUTE = '/__editor/play/std';
27
+
28
+ /** One of play's std routes, its JSON answer; a refusal thrown with what the route said. */
29
+ export async function askPlay<T>(path: string, init?: RequestInit): Promise<T> {
30
+ const response = await fetch(`${ROUTE}${path}`, init);
31
+ const body = (await response.json()) as T & { error?: string };
32
+ if (!response.ok) throw new Error(body.error ?? `${ROUTE}${path} answered ${response.status}`);
33
+ return body;
34
+ }
35
+
36
+ function control<T>(device: string, said: Record<string, unknown>): Promise<T> {
37
+ return askPlay<T>(`/devices/${encodeURIComponent(device)}/control`, {
38
+ method: 'POST',
39
+ headers: { 'content-type': 'application/json' },
40
+ body: JSON.stringify(said),
41
+ });
42
+ }
43
+
44
+ /** A page's clock as std answers it: held or running, its speed, its game seconds and its frames. */
45
+ export interface StdClock {
46
+ readonly paused: boolean;
47
+ readonly speed: number;
48
+ readonly time: number;
49
+ readonly frame: number;
50
+ }
51
+
52
+ /** What Play asks of a page's clock. */
53
+ export type StdClockAction =
54
+ | { readonly action: 'pause' }
55
+ | { readonly action: 'resume' }
56
+ | { readonly action: 'step'; readonly frames: number }
57
+ | { readonly action: 'speed'; readonly speed: number };
58
+
59
+ /** A page's clock held, released, stepped or set to a speed; its clock after. */
60
+ export function stdClock(device: string, asked: StdClockAction): Promise<StdClock> {
61
+ return control<StdClock>(device, { control: 'clock', ...asked });
62
+ }
63
+
64
+ /** One object of the scene a page last drew, as std's inspect reads it. */
65
+ export interface StdInspectedObject {
66
+ readonly name: string;
67
+ /** three's own `type`. */
68
+ readonly type: string;
69
+ /** Its names from the scene down, joined by `/`. */
70
+ readonly path: string;
71
+ /** Its world position, `[x, y, z]`. */
72
+ readonly position: readonly number[];
73
+ readonly visible: boolean;
74
+ /** Its label: its `userData`'s `role`, `aria-label` and `aria-description`. */
75
+ readonly userData?: { readonly role?: string; readonly 'aria-label'?: string; readonly 'aria-description'?: string };
76
+ }
77
+
78
+ /** The scene a page last drew and its labelled screen nodes, as std bounds them. */
79
+ export interface StdInspection {
80
+ readonly objects: readonly StdInspectedObject[];
81
+ readonly screen: readonly StdScreenNode[];
82
+ /** How many objects and nodes past std's bound were left out, where any were. */
83
+ readonly truncated?: { readonly objects: number; readonly screen: number };
84
+ }
85
+
86
+ /** One labelled node of a page's screen, as std's inspect names it (std-driver/2's `NodeObserved`). */
87
+ export interface StdScreenNode {
88
+ readonly role?: string;
89
+ readonly name?: string;
90
+ readonly [key: string]: unknown;
91
+ }
92
+
93
+ export function stdInspect(device: string): Promise<StdInspection> {
94
+ return control<StdInspection>(device, { control: 'inspect' });
95
+ }
96
+
97
+ /** One std-driver/2 action: a key pressed or let go, or the pointer at a point of the page (0 to 1, x right, y down)
98
+ * with `button` pressed or let go. */
99
+ export type StdAction =
100
+ | { readonly key: { readonly key: string; readonly down: boolean } }
101
+ | { readonly pointer: { readonly x: number; readonly y: number; readonly button?: number; readonly down?: boolean } };
102
+
103
+ /** Actions taken through the page's own input path, as a player's own; the observation after them (std-driver/2's
104
+ * `Observation`) where asked, else `{ ok: true }`. */
105
+ export function stdAct(device: string, actions: readonly StdAction[], observe = false): Promise<unknown> {
106
+ return control(device, { control: 'act', actions, ...(observe ? { observe: true } : {}) });
107
+ }
108
+
109
+ /** Who drives a page: its bot, playing `goal` as the player `slot`, or the person. */
110
+ export function stdDrive(device: string, driver: { readonly slot: string; readonly goal: string } | null): Promise<unknown> {
111
+ return control(device, driver === null ? { control: 'manual' } : { control: 'autoplay', slot: driver.slot, goal: driver.goal });
112
+ }
113
+
114
+ /** A frame std's receiver wrote (`stdCapture`'s file), as the PNG itself. */
115
+ export async function stdCaptured(file: string): Promise<Blob> {
116
+ const name = file.split(/[\\/]/).at(-1) ?? file;
117
+ const response = await fetch(`${ROUTE}/capture?file=${encodeURIComponent(name)}`);
118
+ if (!response.ok) throw new Error(((await response.json()) as { error?: string }).error ?? `${ROUTE}/capture answered ${response.status}`);
119
+ return response.blob();
120
+ }
121
+
122
+ /** The page's next frame, captured by std's receiver; its file. */
123
+ export async function stdCapture(device: string): Promise<string> {
124
+ const { files } = await control<{ files: string[] }>(device, { control: 'capture', id: crypto.randomUUID() });
125
+ const file = files[0];
126
+ if (file === undefined) throw new Error(`std's receiver wrote no capture for ${device}.`);
127
+ return file;
128
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * A STD GAME EXPORTED, AS PLAY ASKS IT (`POST /__editor/play/std/export`, `../serving/std-dev.ts`): to the web (`std
3
+ * build`) or to an engine, made one of the game's targets first where the asker says to add it (`std target add`), as
4
+ * an engine's editor builds for a platform once it is added. One export at a time, the session's per project. Its
5
+ * state (the target, whether it runs, the last line std printed, how it ended, whether the target was added, where the
6
+ * export is) is the open project's, a store the Game panel draws and the `export` verb answers with; each line std
7
+ * prints goes to the editor's console. Another project opened, the state is that project's: none yet.
8
+ */
9
+ import { onProjectChange } from '@volter/sdk/active-project';
10
+ import { editorHost } from '@volter/sdk/host';
11
+ import { askPlay } from './std-controls';
12
+
13
+ /** Where a std game exports: the web, or an engine std ships to. */
14
+ export const EXPORT_TARGETS = ['web', 'roblox', 'unreal'] as const;
15
+ export type ExportTarget = (typeof EXPORT_TARGETS)[number];
16
+ export const isExportTarget = (value: unknown): value is ExportTarget =>
17
+ typeof value === 'string' && (EXPORT_TARGETS as readonly string[]).includes(value);
18
+
19
+ /** Each target's name as a person reads it. */
20
+ export const EXPORT_LABELS: Readonly<Record<ExportTarget, string>> = { web: 'Web', roblox: 'Roblox', unreal: 'Unreal' };
21
+
22
+ /** An export: running, or how it ended. */
23
+ export interface StdExport {
24
+ readonly target: ExportTarget;
25
+ readonly running: boolean;
26
+ /** The last line std printed. */
27
+ readonly line: string | null;
28
+ /** Whether it ended exported; null while it runs. */
29
+ readonly ok: boolean | null;
30
+ /** Whether the engine became a target of the game for it. */
31
+ readonly added: boolean;
32
+ /** Where the export is, from the game's folder, once it ended. */
33
+ readonly out: string | null;
34
+ }
35
+
36
+ let current: StdExport | null = null;
37
+ /** The export's start: only its own answers land, never an earlier start's still running. */
38
+ let started = 0;
39
+ const listeners = new Set<() => void>();
40
+
41
+ onProjectChange(() => {
42
+ current = null;
43
+ started += 1;
44
+ for (const listener of listeners) listener();
45
+ });
46
+
47
+ function publish(next: StdExport): void {
48
+ current = next;
49
+ for (const listener of listeners) listener();
50
+ }
51
+
52
+ /** Whether the Game panel's Export menu is open: its Escape closes it alone, never the game's view as well
53
+ * (`std-game.ts`'s view keys, which hear a key before the menu does). */
54
+ let menuOpen = false;
55
+ export const exportMenuOpen = (): boolean => menuOpen;
56
+ export function setExportMenuOpen(open: boolean): void {
57
+ menuOpen = open;
58
+ }
59
+
60
+ /** The latest export, running or ended; null before any. */
61
+ export const stdExport = (): StdExport | null => current;
62
+
63
+ /** Told each time the export changes. */
64
+ export function onStdExport(listener: () => void): () => void {
65
+ listeners.add(listener);
66
+ return () => listeners.delete(listener);
67
+ }
68
+
69
+ /** The engines the game ships to besides the web (std's targets), as the session reads its packages. */
70
+ export async function stdTargets(): Promise<readonly ExportTarget[]> {
71
+ return (await askPlay<{ targets?: readonly ExportTarget[] }>('')).targets ?? [];
72
+ }
73
+
74
+ /** The game exported to `target`, started, an engine added as the game's target first where `add` says (refused,
75
+ * by the session, for an engine the game doesn't target otherwise); refused while another export runs. Its state as
76
+ * it starts. */
77
+ export function startStdExport(target: ExportTarget, add = false): StdExport {
78
+ if (current?.running === true) throw new Error(`An export to ${EXPORT_LABELS[current.target]} is running: wait for it to end.`);
79
+ started += 1;
80
+ const mine = started;
81
+ publish({ target, running: true, line: null, ok: null, added: false, out: null });
82
+ // (an answer for another project opened since, or an earlier start, is the console's alone)
83
+ const ours = (): boolean => started === mine && current !== null;
84
+ const said = (line: string): void => {
85
+ editorHost().console.log(line, 'export');
86
+ if (ours() && current !== null) publish({ ...current, line });
87
+ };
88
+ const ended = (ok: boolean, added: boolean, out: string | null): void => {
89
+ const label = EXPORT_LABELS[target];
90
+ if (ok) editorHost().console.log(`Exported to ${label}: ${out ?? ''}${added ? ` (${label} added as a target)` : ''}`, 'export');
91
+ else editorHost().console.error(`The export to ${label} failed: ${ours() ? current?.line ?? 'std said nothing' : 'its project was closed'}`, 'export');
92
+ if (ours() && current !== null) publish({ ...current, running: false, ok, added, out });
93
+ };
94
+ void (async () => {
95
+ const response = await fetch('/__editor/play/std/export', {
96
+ method: 'POST',
97
+ headers: { 'content-type': 'application/json' },
98
+ body: JSON.stringify({ target, add }),
99
+ });
100
+ if (!response.ok || response.body === null) {
101
+ said(((await response.json().catch(() => ({}))) as { error?: string }).error ?? `The export answered ${response.status}.`);
102
+ ended(false, false, null);
103
+ return;
104
+ }
105
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
106
+ let rest = '';
107
+ for (;;) {
108
+ const { value, done } = await reader.read();
109
+ if (done) break;
110
+ rest += value;
111
+ for (let at = rest.indexOf('\n'); at >= 0; at = rest.indexOf('\n')) {
112
+ const message = JSON.parse(rest.slice(0, at)) as { line?: string; end?: { ok?: boolean; added?: boolean; out?: string } };
113
+ rest = rest.slice(at + 1);
114
+ if (message.end !== undefined) {
115
+ ended(message.end.ok === true, message.end.added === true, message.end.out ?? null);
116
+ return;
117
+ }
118
+ if (typeof message.line === 'string') said(message.line);
119
+ }
120
+ }
121
+ said('The export ended before it said how.');
122
+ ended(false, false, null);
123
+ })().catch((error: unknown) => {
124
+ said(error instanceof Error ? error.message : String(error));
125
+ ended(false, false, null);
126
+ });
127
+ return current ?? { target, running: true, line: null, ok: null, added: false, out: null };
128
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A STD GAME'S EDITOR, as Play supplies it (`package.json#contributes.volter.projectAdapters`, for a project with
3
+ * `std.json`). A std game carries no editor code: std's design has the editor add nothing to the game (design 8), so
4
+ * the adapter a Cyclotron project would keep in `editor/volter.adapter.ts` is Play's. It is the one a models project
5
+ * gets from `cyclotron create`, Blender's layout, keymap and properties inspector, with the game's Blender files as its
6
+ * documents: every `.blend` under `levels/` and every prefab's under `prefabs/` (std's `prefabs/<name>/<name>.blend`).
7
+ * A game with one level opens it.
8
+ */
9
+ import { defineAdapter } from '@volter/project/adapter/adapter-module';
10
+ import { ModelLayout } from '@volter/editor-blender/layouts';
11
+ import { blenderKeymap } from '@volter/editor-blender/looks';
12
+ // (the game's dev server serves this module, so the SDK's change channel it brings is that server's: it joins the
13
+ // editor's page to the server's file events, which a std game's own modules never import, and the Scene view and
14
+ // Play's remount hear each save's export through it)
15
+ import '@volter/sdk/project-module-changes';
16
+
17
+ export default defineAdapter({
18
+ editor: { Layout: ModelLayout, keymap: blenderKeymap, inspector: 'properties' },
19
+ documents: { find: [{ finder: 'modelsFromBlendFiles', include: ['levels/**/*.blend', 'prefabs/**/*.blend'], defaultIn: 'levels/' }] },
20
+ });