entangled-worlds-orbiters-shared 2.12.0 → 2.14.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.
@@ -19,10 +19,175 @@ function lerp(a: number, b: number, t: number): number {
19
19
  return a + (b - a) * t;
20
20
  }
21
21
 
22
- /** A single curve keyframe: a time key `t` (seconds or beats) and its value. */
22
+ /**
23
+ * A single curve keyframe: a time key `t` (seconds or beats) and its value. `curve` bends the segment
24
+ * to the next keyframe (see {@link bend}); absent or 0 falls back to the track's `ease`.
25
+ */
23
26
  export interface Keyframe {
24
27
  t: number;
25
28
  value: number;
29
+ curve?: number;
30
+ }
31
+
32
+ /**
33
+ * How a curve moves between keyframes: `line` ramps (bent by each keyframe's `curve`), `step` holds
34
+ * each value until the next keyframe.
35
+ */
36
+ export type CurveShape = 'line' | 'step';
37
+
38
+ /** The range of a keyframe's `curve`: −2 … 2, 0 linear. */
39
+ export const CURVE_BEND_LIMIT = 2;
40
+
41
+ /**
42
+ * The bend of one segment: maps the fraction `u` in [0, 1] through `curve` c. 0 is linear; c > 0 starts
43
+ * slow and ends fast (exponential), c < 0 starts fast (logarithmic). The automation editor and every
44
+ * player read the same function, so what is drawn is what plays.
45
+ */
46
+ export function bend(u: number, curve = 0): number {
47
+ if (!curve) return u;
48
+ return curve > 0 ? Math.pow(u, 1 + curve * 3) : 1 - Math.pow(1 - u, 1 - curve * 3);
49
+ }
50
+
51
+ /**
52
+ * The `curve` that puts a segment's midpoint at `mid`, a share of the way from its first value to its
53
+ * last (0 … 1, exclusive): the inverse of {@link bend} at u = ½, for a bend handle dragged up or down.
54
+ */
55
+ export function curveForMidpoint(mid: number): number {
56
+ const m = Math.max(0.03, Math.min(0.97, mid));
57
+ const c = m <= 0.5 ? (Math.log(m) / Math.log(0.5) - 1) / 3 : -(Math.log(1 - m) / Math.log(0.5) - 1) / 3;
58
+ return Math.max(-CURVE_BEND_LIMIT, Math.min(CURVE_BEND_LIMIT, c));
59
+ }
60
+
61
+ /** What {@link sampleKeyframes} needs besides the keyframes. */
62
+ export interface SampleOptions {
63
+ shape?: CurveShape;
64
+ /** For a segment whose keyframe has no `curve` (default linear). */
65
+ ease?: EaseFn;
66
+ }
67
+
68
+ /**
69
+ * The value of sorted keyframes at time key `key`: held before the first and after the last, ramped
70
+ * (or stepped) between. NaN when there are none: an empty lane writes nothing.
71
+ */
72
+ export function sampleKeyframes(keyframes: readonly Keyframe[], key: number, { shape = 'line', ease = Ease.linear }: SampleOptions = {}): number {
73
+ const kf = keyframes;
74
+ if (!kf.length) return NaN;
75
+ if (key <= kf[0].t) return kf[0].value;
76
+ const last = kf[kf.length - 1];
77
+ if (key >= last.t) return last.value;
78
+ // Binary search: the last keyframe at or before key.
79
+ let lo = 0;
80
+ let hi = kf.length - 1;
81
+ while (hi - lo > 1) {
82
+ const mid = (lo + hi) >> 1;
83
+ if (kf[mid].t <= key) lo = mid; else hi = mid;
84
+ }
85
+ const a = kf[lo];
86
+ const b = kf[lo + 1];
87
+ if (shape === 'step') return a.value;
88
+ const frac = b.t > a.t ? (key - a.t) / (b.t - a.t) : 1;
89
+ return lerp(a.value, b.value, a.curve ? bend(frac, a.curve) : ease(frac));
90
+ }
91
+
92
+ /**
93
+ * A loop over a curve's time key: the curve plays from 0 up to `start + length`, then repeats
94
+ * `start` … `start + length` (a clip's loop). `start` 0 is a curve that loops on its own length.
95
+ */
96
+ export interface CurveLoop {
97
+ start: number;
98
+ length: number;
99
+ }
100
+
101
+ /** The curve's own time key for a running key: before the loop's end as is, then wrapped into the loop. */
102
+ export function loopKey(key: number, loop: CurveLoop | null | undefined): number {
103
+ if (!loop || !(loop.length > 0)) return key;
104
+ const end = loop.start + loop.length;
105
+ if (key < end) return key;
106
+ return loop.start + ((key - end) % loop.length);
107
+ }
108
+
109
+ /** One of the shapes {@link insertShape} draws: points as [u, value, curve?] over one cycle, u in [0, 1). */
110
+ export interface CurveShapeDef {
111
+ id: string;
112
+ label: string;
113
+ points: ReadonlyArray<readonly [number, number, number?]>;
114
+ /** A closing point at the range's end, for shapes that come back to where they started. */
115
+ end?: number;
116
+ }
117
+
118
+ /** The ten shapes of the automation editor's Insert shape menu. */
119
+ export const CURVE_SHAPES: readonly CurveShapeDef[] = [
120
+ { id: 'sine', label: 'Sine', points: [[0, 0.5, -0.2], [0.25, 1, 0.2], [0.5, 0.5, -0.2], [0.75, 0, 0.2]], end: 0.5 },
121
+ { id: 'triangle', label: 'Triangle', points: [[0, 0], [0.5, 1]], end: 0 },
122
+ { id: 'sawDown', label: 'Saw down', points: [[0, 1], [0.999, 0]] },
123
+ { id: 'sawUp', label: 'Saw up', points: [[0, 0], [0.999, 1]] },
124
+ { id: 'square', label: 'Square', points: [[0, 1], [0.5 - 1e-3, 1], [0.5, 0], [0.999, 0]] },
125
+ { id: 'curveUp', label: 'Curve up', points: [[0, 0, 1.2], [0.999, 1]] },
126
+ { id: 'curveDown', label: 'Curve down', points: [[0, 1, -1.2], [0.999, 0]] },
127
+ { id: 'sCurveUp', label: 'S-curve up', points: [[0, 0, 0.8], [0.5, 0.5, -0.8], [0.999, 1]] },
128
+ { id: 'sCurveDown', label: 'S-curve down', points: [[0, 1, 0.8], [0.5, 0.5, -0.8], [0.999, 0]] },
129
+ { id: 'attackDecay', label: 'Attack / decay', points: [[0, 0, -0.6], [0.15, 1, -1], [0.999, 0]] },
130
+ ];
131
+
132
+ const byKey = (a: Keyframe, b: Keyframe) => a.t - b.t;
133
+
134
+ /** The keyframes with every one inside [from, to] replaced by `insert` (sorted). */
135
+ export function replaceRange(keyframes: readonly Keyframe[], from: number, to: number, insert: readonly Keyframe[]): Keyframe[] {
136
+ const eps = 1e-6;
137
+ return keyframes.filter((k) => k.t < from - eps || k.t > to + eps).concat(insert).sort(byKey);
138
+ }
139
+
140
+ /**
141
+ * Draws a shape over [from, to], `cycles` times, replacing only the keyframes inside the range. Null
142
+ * when the shape is unknown or the range is too short to draw (under 1/16 of a key unit).
143
+ */
144
+ export function insertShape(keyframes: readonly Keyframe[], shapeId: string, from: number, to: number, cycles = 1): Keyframe[] | null {
145
+ const def = CURVE_SHAPES.find((s) => s.id === shapeId);
146
+ if (!def || to - from < 0.0625) return null;
147
+ const n = Math.max(1, Math.floor(cycles));
148
+ const len = (to - from) / n;
149
+ const eps = Math.min(1 / 64, len / 8);
150
+ const made: Keyframe[] = [];
151
+ for (let k = 0; k < n; k++) {
152
+ for (const [u, value, curve] of def.points) {
153
+ const t = u >= 0.999 ? from + (k + 1) * len - eps : from + (k + u) * len;
154
+ made.push(curve ? { t, value, curve } : { t, value });
155
+ }
156
+ }
157
+ if (def.end != null) made.push({ t: to, value: def.end });
158
+ return replaceRange(keyframes, from, to, made);
159
+ }
160
+
161
+ /** Freehand draw: one keyframe at the start of the cell [cellStart, cellStart + cellLength), replacing the cell. */
162
+ export function paintCell(keyframes: readonly Keyframe[], cellStart: number, cellLength: number, value: number): Keyframe[] {
163
+ const eps = 1e-6;
164
+ return keyframes
165
+ .filter((k) => k.t < cellStart - eps || k.t >= cellStart + cellLength - eps)
166
+ .concat({ t: cellStart, value })
167
+ .sort(byKey);
168
+ }
169
+
170
+ /**
171
+ * Recording: the keyframes after the time key moved from `prevKey` to `key` while `value` was live.
172
+ * What was recorded over in that span is replaced (a wrap from a loop end back to its start clears both
173
+ * ends of the loop). A new keyframe is written only once `spacing` has passed since `lastWritten` (null: write now),
174
+ * so a recording is one point per grid step, not one per frame.
175
+ */
176
+ export function recordSpan(
177
+ keyframes: readonly Keyframe[],
178
+ prevKey: number,
179
+ key: number,
180
+ value: number,
181
+ { spacing, lastWritten, loop }: { spacing: number; lastWritten: number | null; loop?: CurveLoop | null },
182
+ ): { keyframes: Keyframe[]; written: number | null } {
183
+ const wrapped = key < prevKey;
184
+ const start = loop ? loop.start : 0;
185
+ const end = loop ? loop.start + loop.length : Infinity;
186
+ const over = (t: number) => (wrapped ? (t > prevKey && t < end) || (t >= start && t <= key) : t > prevKey && t <= key);
187
+ const kept = keyframes.filter((k) => !over(k.t));
188
+ const last = lastWritten == null || wrapped ? -Infinity : lastWritten;
189
+ if (key - last < spacing) return { keyframes: kept, written: lastWritten };
190
+ return { keyframes: kept.concat({ t: key, value }).sort(byKey), written: key };
26
191
  }
27
192
 
28
193
  export type TimeMode = 'absolute-seconds' | 'beat-locked';
@@ -40,6 +205,10 @@ export interface CurveTrackSpec {
40
205
  timeMode?: TimeMode;
41
206
  projection?: ProjectionLike | null;
42
207
  ease?: EaseFn;
208
+ /** Line (default) or step. */
209
+ shape?: CurveShape;
210
+ /** Loops the curve's time key (a clip loop, or its own length). Absent: plays once, then holds. */
211
+ loop?: CurveLoop | null;
43
212
  outputIntent?: unknown;
44
213
  }
45
214
 
@@ -48,35 +217,37 @@ export class CurveTrack {
48
217
  timeMode: TimeMode;
49
218
  projection: ProjectionLike | null;
50
219
  ease: EaseFn;
220
+ shape: CurveShape;
221
+ loop: CurveLoop | null;
51
222
  outputIntent: unknown;
52
223
 
53
224
  constructor(spec: CurveTrackSpec) {
54
- this.keyframes = spec.keyframes.slice().sort((a, b) => a.t - b.t);
225
+ this.keyframes = spec.keyframes.slice().sort(byKey);
55
226
  this.timeMode = spec.timeMode ?? 'absolute-seconds';
56
227
  this.projection = spec.projection ?? null;
57
228
  this.ease = spec.ease ?? Ease.linear;
229
+ this.shape = spec.shape ?? 'line';
230
+ this.loop = spec.loop ?? null;
58
231
  this.outputIntent = spec.outputIntent ?? null;
59
232
  if (this.timeMode === 'beat-locked' && !this.projection) {
60
233
  throw new Error('beat-locked CurveTrack needs a MusicalProjection');
61
234
  }
62
235
  }
63
236
 
64
- /** The track's own time key for a given clock position. */
237
+ /** The track's own time key for a given clock position (looped when the track loops). */
65
238
  _key(positionSec: number): number {
66
- return this.timeMode === 'beat-locked' ? this.projection!.secondsToBeats(positionSec) : positionSec;
239
+ const key = this.timeMode === 'beat-locked' ? this.projection!.secondsToBeats(positionSec) : positionSec;
240
+ return loopKey(key, this.loop);
67
241
  }
68
242
 
243
+ /** The value at a clock position; NaN for a track with no keyframes. */
69
244
  sample(positionSec: number): number {
70
- const k = this._key(positionSec);
71
- const kf = this.keyframes;
72
- if (k <= kf[0].t) return kf[0].value;
73
- if (k >= kf[kf.length - 1].t) return kf[kf.length - 1].value;
74
- let i = 0;
75
- while (i < kf.length - 1 && kf[i + 1].t <= k) i++;
76
- const a = kf[i];
77
- const b = kf[i + 1];
78
- const frac = (k - a.t) / (b.t - a.t);
79
- return lerp(a.value, b.value, this.ease(frac));
245
+ return this.sampleKey(this._key(positionSec));
246
+ }
247
+
248
+ /** The value at the track's own time key (beats for a beat-locked track), with no loop applied. */
249
+ sampleKey(key: number): number {
250
+ return sampleKeyframes(this.keyframes, key, { shape: this.shape, ease: this.ease });
80
251
  }
81
252
  }
82
253
 
@@ -0,0 +1,171 @@
1
+ /**
2
+ * A head made ready for play mode: its programs composed, compiled, shrunk, sized and stamped.
3
+ *
4
+ * Play mode downloads finished programs: no compiler in the page, no first-build wait on a phone.
5
+ * This is the step that makes them, once, when an Orbiter is released. It runs where a compiler and
6
+ * the shrink step exist (a server, a build, a test), never in a listener's browser, so both arrive
7
+ * as tools rather than imports: this file stays pure.
8
+ *
9
+ * For one head (`voiceProgram.ts`, `buildHeadPrograms`):
10
+ *
11
+ * 1. **Compose** its programs: the note modules as one, the instrument as another; the instrument
12
+ * alone when nothing sits in front of it.
13
+ * 2. **Compile** each with the app's own options.
14
+ * 3. **Shrink** each (the same step the module build uses: the same program, a quarter smaller).
15
+ * 4. **Size** each: past the heavy line its largest function is one Safari may never optimise. The
16
+ * export still goes through; the author is told.
17
+ * 5. **Stamp** the export with what it was built from and the runtime it expects.
18
+ *
19
+ * A released Orbiter keeps its sound: an export stays valid when a module's source changes later
20
+ * (the stamp says what it was built from). Play mode refuses it only when the runtime it expects is
21
+ * no longer the app's, and then plays as it would have without one.
22
+ */
23
+ import { buildHeadPrograms, HEAD_PROGRAM_NAME, type VoiceSlot } from './voiceProgram.js';
24
+ import { HEAVY_FUNCTION_BYTES, largestFunction } from './wasmSize.js';
25
+
26
+ /** One item of Faust's UI tree: a group (with `items`) or a control. */
27
+ export interface FaustUiItem {
28
+ type: string;
29
+ label: string;
30
+ address?: string;
31
+ init?: number;
32
+ min?: number;
33
+ max?: number;
34
+ step?: number;
35
+ items?: FaustUiItem[];
36
+ [field: string]: unknown;
37
+ }
38
+
39
+ /** Faust's metadata for a compiled DSP (its JSON): the UI tree, inputs, outputs, declares. */
40
+ export interface FaustDspMeta {
41
+ name: string;
42
+ inputs: number;
43
+ outputs: number;
44
+ compile_options: string;
45
+ ui: FaustUiItem[];
46
+ meta?: Array<Record<string, string>>;
47
+ [field: string]: unknown;
48
+ }
49
+
50
+ /** A compiled program as it is stored and downloaded: its wasm and the description of its controls. */
51
+ export interface CompiledProgram {
52
+ /** Faust's sha key; the `registerProcessor` name. */
53
+ processorName: string;
54
+ dspName: string;
55
+ dspMeta: FaustDspMeta;
56
+ /** Fully-qualified control addresses, in Faust's order. */
57
+ paramAddresses: string[];
58
+ wasmBase64: string;
59
+ /** 4 for a single-precision build, 8 for -double. */
60
+ sampleSize: 4 | 8;
61
+ }
62
+
63
+ /** Every control address in the DSP's UI tree, in Faust's own order. */
64
+ export function collectParamAddresses(ui: FaustUiItem[] | null | undefined): string[] {
65
+ const out: string[] = [];
66
+ const walk = (items: FaustUiItem[]) => items.forEach((item) => {
67
+ if (item.items) walk(item.items);
68
+ else if (item.address) out.push(item.address);
69
+ });
70
+ walk(ui ?? []);
71
+ return out;
72
+ }
73
+
74
+ /** What an export was built from, and what it needs to play. */
75
+ export interface HeadExportStamp {
76
+ /** The runtime contract the programs were built for: the app's, as its recipes file names it. */
77
+ runtime: number;
78
+ /** The FAUST compiler's version, and its options. */
79
+ faust: string;
80
+ options: string;
81
+ /** The shrink step's version. */
82
+ shrink: string;
83
+ /** The fingerprint of the recipes file: every `.dsp` source and library the compiler could read. */
84
+ sources: string;
85
+ }
86
+
87
+ /** The compiler and the shrink step, handed in by whoever runs the export. */
88
+ export interface HeadExportTools {
89
+ /** Compile `source` under `name` with the sources and libraries mounted: FAUST's factory. */
90
+ compile(name: string, source: string): Promise<{ code: Uint8Array; json: string; shaKey: string }>;
91
+ /** The same program, smaller. */
92
+ shrink(wasm: Uint8Array): Uint8Array;
93
+ /**
94
+ * A program already filed under this key, if there is one: it is taken as it is, never compiled
95
+ * again (an instrument's program is the same file for every Orbiter that plays it).
96
+ */
97
+ find?(key: string): Promise<CompiledProgram | null>;
98
+ stamp: HeadExportStamp;
99
+ }
100
+
101
+ /** One finished program of a head. */
102
+ export interface ExportedProgram {
103
+ /** What it is filed under: its shape. */
104
+ key: string;
105
+ artifact: CompiledProgram;
106
+ /** Its largest function, in bytes, and whether that is past the heavy line. */
107
+ largestFunction: number;
108
+ heavy: boolean;
109
+ }
110
+
111
+ export interface HeadExport {
112
+ /** Null when nothing sits in front of the instrument. */
113
+ notes: ExportedProgram | null;
114
+ instrument: ExportedProgram;
115
+ stamp: HeadExportStamp;
116
+ }
117
+
118
+ function base64(bytes: Uint8Array): string {
119
+ let binary = '';
120
+ // In pieces: one call with every byte as an argument overflows the stack on a large program.
121
+ for (let at = 0; at < bytes.length; at += 0x8000) binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000));
122
+ return btoa(binary);
123
+ }
124
+
125
+ function bytes(text: string): Uint8Array {
126
+ const binary = atob(text);
127
+ const out = new Uint8Array(binary.length);
128
+ for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
129
+ return out;
130
+ }
131
+
132
+ async function exportProgram(key: string, source: string, tools: HeadExportTools): Promise<ExportedProgram> {
133
+ const filed = await tools.find?.(key);
134
+ if (filed) {
135
+ const size = largestFunction(bytes(filed.wasmBase64));
136
+ return { key, artifact: filed, largestFunction: size, heavy: size > HEAVY_FUNCTION_BYTES };
137
+ }
138
+ const factory = await tools.compile(HEAD_PROGRAM_NAME, source);
139
+ const wasm = tools.shrink(factory.code);
140
+ const dspMeta: FaustDspMeta = JSON.parse(factory.json);
141
+ const size = largestFunction(wasm);
142
+ return {
143
+ key,
144
+ artifact: {
145
+ processorName: factory.shaKey,
146
+ dspName: HEAD_PROGRAM_NAME,
147
+ dspMeta,
148
+ paramAddresses: collectParamAddresses(dspMeta.ui),
149
+ wasmBase64: base64(wasm),
150
+ sampleSize: dspMeta.compile_options.includes('-double') ? 8 : 4,
151
+ },
152
+ largestFunction: size,
153
+ heavy: size > HEAVY_FUNCTION_BYTES,
154
+ };
155
+ }
156
+
157
+ /**
158
+ * `slots`: the head's note modules in rack order, then its instrument, each with what it does with
159
+ * notes. Throws when a program does not compile: the caller saves the release without programs, and
160
+ * play mode plays as it does without them.
161
+ */
162
+ export async function exportHead(slots: readonly VoiceSlot[], tools: HeadExportTools): Promise<HeadExport> {
163
+ const programs = buildHeadPrograms(slots);
164
+ // One after the other: one libfaust compiles one program at a time.
165
+ const notes = programs.notes ? await exportProgram(programs.notes.key, programs.notes.source, tools) : null;
166
+ const instrument = await exportProgram(programs.instrument.key, programs.instrument.source, tools);
167
+ if (notes && notes.artifact.dspMeta.outputs !== instrument.artifact.dspMeta.inputs) {
168
+ throw new Error(`[headExport] the note modules put out ${notes.artifact.dspMeta.outputs} signals; the instrument takes ${instrument.artifact.dspMeta.inputs}`);
169
+ }
170
+ return { notes, instrument, stamp: tools.stamp };
171
+ }
@@ -0,0 +1,7 @@
1
+ // Composing a rack's note head into FAUST programs, and making them ready for play mode: shared by
2
+ // the app that plays them and the server step that compiles them at release, so the source, its key
3
+ // and its file name are the same on both sides. Pure: the compiler and the shrink tool are handed in.
4
+ export * from './voiceProgram.js';
5
+ export * from './wasmSize.js';
6
+ export * from './headExport.js';
7
+ export * from './recipes.js';
@@ -0,0 +1,136 @@
1
+ /**
2
+ * The recipes file: everything one build of the app compiles its programs from, in one file named by
3
+ * a fingerprint of its content.
4
+ *
5
+ * The app publishes it beside its compiler; the release step fetches it by the fingerprint the author's
6
+ * page sends, checks the content against the name, and compiles from exactly that. The sources stay
7
+ * where they are authored: nothing else has to hold a copy of them in step.
8
+ *
9
+ * The fingerprint covers all of it (the sources, the libraries, the compiler's version and options,
10
+ * the runtime contract), so two builds that would compile a different program never share a name.
11
+ */
12
+ import { MAX_NOTE_LANES, type SlotNotes, type VoiceSlot } from './voiceProgram.js';
13
+
14
+ export interface Recipes {
15
+ /** `.dsp` file name → FAUST source. */
16
+ sources: Readonly<Record<string, string>>;
17
+ /** Library file name → FAUST source, mounted beside the standard ones. */
18
+ libraries: Readonly<Record<string, string>>;
19
+ /** The compiler: the version of the package that carries libfaust. */
20
+ faust: string;
21
+ /** The compiler's options. */
22
+ options: string;
23
+ /** The runtime contract a program compiled from these plays under. */
24
+ runtime: number;
25
+ }
26
+
27
+ const FINGERPRINT = /^[0-9a-f]{16}$/;
28
+
29
+ export const isRecipesFingerprint = (value: unknown): value is string => typeof value === 'string' && FINGERPRINT.test(value);
30
+
31
+ /** The file a fingerprint names, as the app publishes it. */
32
+ export const recipesFileName = (fingerprint: string): string => `sources-${fingerprint}.json`;
33
+
34
+ async function shortHash(parts: unknown): Promise<string> {
35
+ const text = new TextEncoder().encode(JSON.stringify(parts));
36
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', text));
37
+ return Array.from(digest.subarray(0, 8), (byte) => byte.toString(16).padStart(2, '0')).join('');
38
+ }
39
+
40
+ /** A hash of everything a compile reads and is told (SHA-256, its first 16 hex digits). */
41
+ export function recipesFingerprint(recipes: Recipes): Promise<string> {
42
+ const sorted = (files: Readonly<Record<string, string>>) => Object.keys(files).sort().map((file) => [file, files[file]]);
43
+ return shortHash([sorted(recipes.sources), sorted(recipes.libraries), recipes.faust, recipes.options, recipes.runtime]);
44
+ }
45
+
46
+ const isTextMap = (value: unknown): value is Record<string, string> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
47
+ && Object.values(value as object).every((text) => typeof text === 'string');
48
+
49
+ /** A downloaded recipes file, if it reads as one; anything else is null. */
50
+ export function readRecipes(value: unknown): Recipes | null {
51
+ const recipes = value as Recipes | null;
52
+ if (!recipes || typeof recipes !== 'object') return null;
53
+ if (!isTextMap(recipes.sources) || !isTextMap(recipes.libraries) || !Object.keys(recipes.sources).length) return null;
54
+ if (typeof recipes.faust !== 'string' || typeof recipes.options !== 'string' || !Number.isInteger(recipes.runtime)) return null;
55
+ return { sources: recipes.sources, libraries: recipes.libraries, faust: recipes.faust, options: recipes.options, runtime: recipes.runtime };
56
+ }
57
+
58
+ /**
59
+ * How this package composes a program from a shape. Raise it when the same shape would compose to
60
+ * different text: a test keeps a fingerprint of the composed text beside it and fails until then.
61
+ */
62
+ export const COMPOSER_VERSION = 1;
63
+
64
+ /**
65
+ * Where a build's compiled programs are filed: the recipes, the shrink step and the composer
66
+ * together. A file under it is never replaced, so a release keeps the programs it was given.
67
+ */
68
+ export function programsNamespace(fingerprint: string, shrink: string): Promise<string> {
69
+ return shortHash([fingerprint, shrink, COMPOSER_VERSION]);
70
+ }
71
+
72
+ /** The most World dimensions an Orbiter has: a head each. */
73
+ export const MAX_HEADS = 3;
74
+ /** The most note modules in front of an instrument: a generator and the MIDI effects. */
75
+ export const MAX_HEAD_NOTE_MODULES = 12;
76
+ /** The largest program constant an instrument takes. */
77
+ const MAX_CONSTANT = 64;
78
+
79
+ const whole = (value: unknown, most: number): value is number => Number.isInteger(value) && (value as number) >= 1 && (value as number) <= most;
80
+
81
+ /**
82
+ * A head's shape as a client sent it, checked before anything is composed from it: the note modules
83
+ * in rack order, then the instrument. Every file must be one of the recipes', every count a whole
84
+ * number inside the rack's limits. Returns the shape with nothing else on it; throws with the reason.
85
+ */
86
+ export function readHeadShape(value: unknown, sources: Readonly<Record<string, string>>): VoiceSlot[] {
87
+ if (!Array.isArray(value) || value.length < 1 || value.length > MAX_HEAD_NOTE_MODULES + 1) throw new Error('a head is 1 to 13 modules');
88
+ return value.map((slot, index): VoiceSlot => {
89
+ const file = (slot as VoiceSlot | null)?.dspFileName;
90
+ const notes = (slot as VoiceSlot | null)?.notes as SlotNotes | undefined;
91
+ if (typeof file !== 'string' || !Object.hasOwn(sources, file)) throw new Error(`module ${index}: no such source`);
92
+ const last = index === value.length - 1;
93
+ if (last) {
94
+ if (notes?.kind !== 'instrument' || !whole(notes.polyphony, MAX_NOTE_LANES)) throw new Error(`module ${index}: a head ends with an instrument of 1 to ${MAX_NOTE_LANES} voices`);
95
+ const constants = notes.constants ?? {};
96
+ if (typeof constants !== 'object' || Array.isArray(constants)) throw new Error(`module ${index}: constants`);
97
+ const entries = Object.entries(constants);
98
+ if (entries.length > 8 || entries.some(([name, n]) => !/^[A-Z][A-Z0-9_]{0,23}$/.test(name) || !whole(n, MAX_CONSTANT))) throw new Error(`module ${index}: constants`);
99
+ return { dspFileName: file, notes: { kind: 'instrument', polyphony: notes.polyphony, ...(entries.length ? { constants: Object.fromEntries(entries) } : {}) } };
100
+ }
101
+ if ((notes?.kind !== 'generator' && notes?.kind !== 'midi') || !whole(notes.lanesPerLane, MAX_NOTE_LANES)) throw new Error(`module ${index}: a note module with 1 to ${MAX_NOTE_LANES} lanes per lane`);
102
+ return { dspFileName: file, notes: { kind: notes.kind, lanesPerLane: notes.lanesPerLane } };
103
+ });
104
+ }
105
+
106
+ /** One head's programs on a release: their keys, and whether the author was told it is heavy. */
107
+ export interface ReleasedHead {
108
+ /** Null when nothing sits in front of the instrument. */
109
+ notes: string | null;
110
+ instrument: string;
111
+ heavy?: boolean;
112
+ }
113
+
114
+ /** What a release carries of its programs: written by the server at release, never by a client. */
115
+ export interface ReleasedPrograms {
116
+ /** The runtime contract the programs were built for. */
117
+ runtime: number;
118
+ /** Where they are filed (`programsNamespace`): what they were built from and with. */
119
+ sources: string;
120
+ /** By World dimension id. */
121
+ heads: Record<string, ReleasedHead>;
122
+ }
123
+
124
+ const isHead = (head: unknown): head is ReleasedHead => {
125
+ const h = head as ReleasedHead | null;
126
+ return Boolean(h && typeof h === 'object' && typeof h.instrument === 'string' && (h.notes === null || typeof h.notes === 'string'));
127
+ };
128
+
129
+ /** A release's programs, if what it carries reads as them; anything else is no programs. */
130
+ export function readReleasedPrograms(value: unknown): ReleasedPrograms | null {
131
+ const programs = value as ReleasedPrograms | null;
132
+ if (!programs || typeof programs !== 'object' || !Number.isInteger(programs.runtime) || typeof programs.sources !== 'string') return null;
133
+ if (!/^[a-z0-9]+$/i.test(programs.sources) || !programs.heads || typeof programs.heads !== 'object') return null;
134
+ const heads = Object.fromEntries(Object.entries(programs.heads).filter(([, head]) => isHead(head)));
135
+ return Object.keys(heads).length ? { runtime: programs.runtime, sources: programs.sources, heads } : null;
136
+ }