@zeeuw/riff 0.0.0-stage → 0.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +195 -2
  3. package/data/registry-data.js +3 -0
  4. package/data/signatures.js +3 -0
  5. package/docs/clean-room.md +450 -0
  6. package/package.json +69 -4
  7. package/src/audio/clock.js +383 -0
  8. package/src/audio/engine.js +678 -0
  9. package/src/audio/index.js +394 -0
  10. package/src/audio/offline.js +73 -0
  11. package/src/audio/params.js +397 -0
  12. package/src/audio/samples.js +274 -0
  13. package/src/audio/unlock.js +70 -0
  14. package/src/audio/voices.js +44 -0
  15. package/src/combinators.js +150 -0
  16. package/src/compat.js +16 -0
  17. package/src/constructors.js +236 -0
  18. package/src/controls.js +199 -0
  19. package/src/draw.js +252 -0
  20. package/src/euclid.js +57 -0
  21. package/src/evaluate.js +251 -0
  22. package/src/extras/check.js +678 -0
  23. package/src/extras/describe.js +433 -0
  24. package/src/extras/editor.js +369 -0
  25. package/src/extras/index.js +10 -0
  26. package/src/fraction.js +300 -0
  27. package/src/hap.js +64 -0
  28. package/src/helpers.js +68 -0
  29. package/src/index.js +74 -0
  30. package/src/mini/index.js +36 -0
  31. package/src/mini/parser.js +400 -0
  32. package/src/ops.js +293 -0
  33. package/src/outline.js +175 -0
  34. package/src/pattern.js +365 -0
  35. package/src/random.js +344 -0
  36. package/src/register.js +83 -0
  37. package/src/registry.js +52 -0
  38. package/src/samples.js +14 -0
  39. package/src/sampling.js +123 -0
  40. package/src/scope.js +77 -0
  41. package/src/signals.js +76 -0
  42. package/src/stepwise.js +150 -0
  43. package/src/structure.js +636 -0
  44. package/src/time.js +70 -0
  45. package/src/tonal.js +583 -0
  46. package/src/transforms.js +125 -0
  47. package/src/transpile.js +394 -0
  48. package/src/util.js +80 -0
  49. package/src/visuals.js +216 -0
@@ -0,0 +1,251 @@
1
+ // evaluate() (plan 3.3, spec/integration.md 2-3, spec/transpile.md 2-4):
2
+ // transpile user code, run it as the body of an AsyncFunction whose
3
+ // parameters are the public API (nothing is written to globalThis), collect
4
+ // `.p()` registrations, and return the resulting pattern.
5
+ import { addScope, scopeEntries } from './scope.js';
6
+ import { Pattern, pure, silence, isPattern, setStringParser, getStringParser, setOnNew } from './pattern.js';
7
+ import { stack } from './constructors.js';
8
+ import { miniAt } from './mini/index.js';
9
+ import { seedLayer } from './random.js';
10
+ import { transpile, MINI_FN, CALL_FN } from './transpile.js';
11
+ import { lineCol } from './util.js';
12
+
13
+ const AsyncFunction = (async () => {}).constructor;
14
+ const IDENT = /^[A-Za-z_$][\w$]*$/;
15
+ const RESERVED = new Set(('break case catch class const continue debugger default delete do else enum export ' +
16
+ 'extends false finally for function if import in instanceof new null return super switch this throw true ' +
17
+ 'try typeof var void while with yield let static implements package protected interface private public ' +
18
+ 'await arguments eval').split(' '));
19
+
20
+ // --- call-site tags (spec/diagnostics.md): cur = the call entered last ---
21
+ let cur = null;
22
+ const NONE = Object.freeze([]);
23
+
24
+ // `text at line:col: msg` and the span (1-based) of call [from, to) of `code`.
25
+ export function callMessage(code, from, to, msg) {
26
+ const a = lineCol(code, from);
27
+ const b = lineCol(code, to);
28
+ let text = code.slice(from, to).replace(/\s+/g, ' ');
29
+ if (text.length > 40) text = `${text.slice(0, 39)}…`;
30
+ return { message: `${text} at ${a.line}:${a.column + 1}: ${msg}`, line: a.line, column: a.column + 1, endLine: b.line, endColumn: b.column + 1 };
31
+ }
32
+
33
+ // explain(err, run?) sets err.call = { name, from, to }: the call entered last
34
+ // (unless user code threw), or with `run` (a failed query, re-run) the
35
+ // innermost call whose patterns threw.
36
+ function explainer(code, spans, tagged) {
37
+ return (err, run) => {
38
+ if (!err || typeof err !== 'object' || err.call !== undefined) return err?.call ?? null;
39
+ let id = null;
40
+ if (run) {
41
+ const hits = new Map();
42
+ const qs = [];
43
+ for (let i = 0; i < tagged.length; i += 2) {
44
+ const p = tagged[i];
45
+ const q = p.query;
46
+ const c = tagged[i + 1];
47
+ qs.push(q);
48
+ p.query = function (st) { try { return q.call(this, st); } catch (e) { if (!hits.has(e)) hits.set(e, c); throw e; } };
49
+ }
50
+ try { run(); } catch (e) { id = hits.get(e) ?? null; } finally { for (let i = 0; i < tagged.length; i += 2) tagged[i].query = qs[i / 2]; }
51
+ } else if (!/^\s*at .*<anonymous>:\d/.test(String(err.stack).split('\n').find((l) => /^\s*at /.test(l)) ?? '')) id = cur;
52
+ const s = spans?.[id];
53
+ err.call = s ? { name: /^[\w$]+/.exec(code.slice(s[0]))[0], from: s[0], to: s[1] } : null;
54
+ return err.call;
55
+ };
56
+ }
57
+
58
+ // --- `.p(id)`: register a pattern in the evaluation that is running ---
59
+ let registrations = null;
60
+
61
+ Object.defineProperty(Pattern.prototype, 'p', {
62
+ value: function p(id) {
63
+ if (!registrations) return this;
64
+ const key = String(id);
65
+ const muted = typeof id === 'string' && id.startsWith('_');
66
+ if (key === '$' || key === '_$') registrations.push({ key: null, pattern: this, muted });
67
+ else {
68
+ const at = registrations.findIndex((r) => r.key === key);
69
+ if (at >= 0) registrations[at] = { key, pattern: this, muted };
70
+ else registrations.push({ key, pattern: this, muted });
71
+ }
72
+ return this;
73
+ },
74
+ writable: true, configurable: true,
75
+ });
76
+
77
+ // As a pattern method, `hush()` is silence (spec/integration.md 3).
78
+ Object.defineProperty(Pattern.prototype, 'hush', {
79
+ value: function hush() { return silence; },
80
+ writable: true, configurable: true,
81
+ });
82
+
83
+ export function describe(v) {
84
+ if (v === undefined) return 'undefined';
85
+ if (v === null) return 'null';
86
+ if (typeof v === 'function') return 'a function';
87
+ if (typeof v === 'string') return `the string ${JSON.stringify(v.length > 40 ? `${v.slice(0, 40)}…` : v)}`;
88
+ if (typeof v === 'object') return `an object (${v.constructor?.name ?? 'Object'})`;
89
+ return `the ${typeof v} ${String(v)}`;
90
+ }
91
+
92
+ // Plan 8.12 (improvements 7): a hint after the real type of a non-pattern value.
93
+ function noPatternHint(v) {
94
+ if (typeof v === 'function') return 'did you forget to call a function?';
95
+ if (v === undefined) return 'the last statement returns nothing (samples(), setcps() or a declaration): end with a pattern such as s("bd sd"), or play layers with $:';
96
+ return 'end the program with a pattern such as s("bd sd"), or play layers with $:';
97
+ }
98
+
99
+ // The names user code sees: registered functions and the public names
100
+ // (src/scope.js), the REPL's own functions, then caller-supplied names
101
+ // (highest priority).
102
+ function buildScope(own, extra) {
103
+ const scope = scopeEntries();
104
+ Object.assign(scope, own, extra);
105
+ for (const k of Object.keys(scope)) if (!IDENT.test(k) || RESERVED.has(k)) delete scope[k];
106
+ return scope;
107
+ }
108
+
109
+ // createRepl(options) -> { evaluate, hush, state, options, setSliderValue }
110
+ // options.scope: extra names for user code; options.onError(err); options.log;
111
+ // options.onPattern(pattern) after a successful evaluation, options.onHush(),
112
+ // options.onCps(cps) when user code calls setcps/setcpm.
113
+ // One REPL owns its state, so several can live on one page.
114
+ export function createRepl(replOptions = {}) {
115
+ const state = {
116
+ pattern: null, playing: false, cps: 0.5,
117
+ widgets: [], miniLocations: [], evalError: null, playError: null, code: '',
118
+ };
119
+ const sliderValues = new Map();
120
+
121
+ // Slider value as a pattern: one hap per cycle with the slider's current
122
+ // value. Each evaluation starts from the value written in the code (the UI
123
+ // rewrites the code when the slider moves); setSliderValue changes the cell
124
+ // of the latest evaluation.
125
+ function sliderWithID(id, value = 0) {
126
+ const cell = { value };
127
+ sliderValues.set(id, cell);
128
+ return new Pattern((st) => pure(cell.value).query(st), 1);
129
+ }
130
+ let explain = () => null;
131
+ const own = {
132
+ [MINI_FN]: (v, o) => { cur = null; return miniAt(v, o); },
133
+ [CALL_FN]: (id) => { cur = id; return NONE; },
134
+ sliderWithID,
135
+ slider: (value = 0) => pure(value),
136
+ setcps: (cps) => { state.cps = Number(cps); replOptions.onCps?.(state.cps); return silence; },
137
+ setcpm: (cpm) => { state.cps = Number(cpm) / 60; replOptions.onCps?.(state.cps); return silence; },
138
+ hush: () => hush(),
139
+ };
140
+
141
+ function hush() {
142
+ state.playing = false;
143
+ replOptions.onHush?.();
144
+ return silence;
145
+ }
146
+
147
+ // evaluate(code, options) -> Promise<Pattern | undefined>
148
+ // options.scope: extra names; options.throwOnError: reject instead of
149
+ // resolving undefined (spec/integration.md 2 resolves undefined);
150
+ // options.quantize ('cycle' | 'bar' | cycles) and options.crossfade (s):
151
+ // when the new pattern takes over (plan 8.5), passed to onPattern.
152
+ // onPattern(pattern, meta) gets meta { code, layers?, quantize, crossfade };
153
+ // layers ({ name, pattern, key, nth }) are the played `$:`/`.p()` layers.
154
+ async function evaluate(code, options = {}) {
155
+ replOptions.onEvaluate?.();
156
+ const prevRegs = registrations;
157
+ const regs = [];
158
+ try {
159
+ if (String(code ?? '').trim() === '') throw new Error('no code to evaluate');
160
+ let t;
161
+ try {
162
+ t = transpile(code, { ...options, calls: true });
163
+ } catch (e) {
164
+ // Keep the oracle's wording first (fixture stmt-const-last), then say what it means.
165
+ if (/without body expression/.test(e?.message ?? '') && !e.hint) {
166
+ e.hint = 'the program ends with a declaration, so it returns no pattern: end with a pattern expression, or play layers with $:';
167
+ e.message = `${e.message}: ${e.hint}`;
168
+ }
169
+ throw e;
170
+ }
171
+ let pattern;
172
+ let layers;
173
+ if (t.empty) pattern = silence;
174
+ else {
175
+ const scope = buildScope(own, { ...replOptions.scope, ...options.scope });
176
+ const names = Object.keys(scope);
177
+ const fn = new AsyncFunction(...names, `{${t.output}\n}`);
178
+ registrations = regs;
179
+ // Plain JS strings in user code stay plain values (spec/transpile.md:
180
+ // single quotes, tagged templates, `"a" + "b"`); only transpiled
181
+ // double-quoted/backtick strings are mini-notation.
182
+ const prevParser = getStringParser();
183
+ setStringParser(pure);
184
+ const tagged = [];
185
+ explain = explainer(String(code), t.calls, tagged);
186
+ cur = null;
187
+ const prevNew = setOnNew((p) => { if (cur !== null) tagged.push(p, cur); });
188
+ let value;
189
+ try {
190
+ value = await fn(...names.map((n) => scope[n]));
191
+ } catch (e) {
192
+ explain(e);
193
+ throw e;
194
+ } finally {
195
+ registrations = prevRegs;
196
+ setStringParser(prevParser);
197
+ setOnNew(prevNew);
198
+ }
199
+ if (regs.length > 0) {
200
+ // key: the label (null for `$:`); nth: which `$:` it is, muted included.
201
+ // Layer ids for 'riff' random mode (plan 8.9): the label, or `$<k>` for the k-th `$:`.
202
+ let anon = 0;
203
+ layers = regs.map((r) => {
204
+ const nth = r.key === null ? anon++ : 0;
205
+ const id = r.key ?? '$' + nth;
206
+ return { name: r.key ?? '$', pattern: seedLayer(r.pattern, id), key: r.key, nth, muted: r.muted };
207
+ }).filter((r) => !r.muted);
208
+ pattern = stack(...layers.map((r) => r.pattern));
209
+ }
210
+ else if (isPattern(value)) pattern = value;
211
+ else {
212
+ const hint = noPatternHint(value);
213
+ throw Object.assign(new Error(`the program's value is ${describe(value)}, not a pattern (${hint})`), { hint });
214
+ }
215
+ }
216
+ Object.assign(state, {
217
+ pattern, playing: true, widgets: t.widgets, miniLocations: t.miniLocations, evalError: null, playError: null, code: String(code),
218
+ });
219
+ replOptions.onPattern?.(pattern, { code: String(code), layers, quantize: options.quantize, crossfade: options.crossfade, explain });
220
+ return pattern;
221
+ } catch (err) {
222
+ state.evalError = err;
223
+ if (err instanceof Error) {
224
+ const c = err.call && callMessage(String(code), err.call.from, err.call.to, err.message);
225
+ err.diagnostic = {
226
+ code: err.reason !== undefined ? 'mini-syntax' : err.name === 'SyntaxError' ? 'syntax' : err.hint ? 'no-pattern' : 'runtime',
227
+ severity: 'error', message: err.message, line: err.line, column: err.column + 1 || undefined, hint: err.hint, ...c,
228
+ };
229
+ }
230
+ if (options.throwOnError) throw err;
231
+ (replOptions.onError ?? options.onError ?? ((e) => (replOptions.log ?? console.error)(`[riff] ${e?.message ?? e}`)))(err);
232
+ return undefined;
233
+ }
234
+ }
235
+
236
+ // options: the hooks (onPattern, onHush, onCps, onError); the audio layer
237
+ // sets them on the default REPL (src/audio/index.js).
238
+ return {
239
+ evaluate, hush, state, options: replOptions, explain: (e, run) => explain(e, run),
240
+ setSliderValue: (id, v) => { const c = sliderValues.get(id); if (c) c.value = v; else sliderValues.set(id, { value: v }); },
241
+ sliderValues,
242
+ };
243
+ }
244
+
245
+ // The default REPL behind the package-level evaluate() and hush().
246
+ export const repl = createRepl();
247
+ export const evaluate = (code, options) => repl.evaluate(code, options);
248
+ export const hush = () => repl.hush();
249
+
250
+ // Names for user code (src/scope.js).
251
+ addScope({ createRepl, evaluate, hush, repl });