@zeeuw/riff 0.0.0-stage → 0.1.0-beta.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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -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
package/src/pattern.js ADDED
@@ -0,0 +1,365 @@
1
+ // The Pattern class: a function from a query State to a list of Haps
2
+ // (spec/time.md section 4), plus the core combinator plumbing that every
3
+ // later module builds on (mapping, applicative combination, joins).
4
+ import { fraction } from './fraction.js';
5
+ import { TimeSpan } from './time.js';
6
+ import { Hap, combineContext, EMPTY_CONTEXT } from './hap.js';
7
+
8
+ const NO_CONTROLS = Object.freeze({});
9
+
10
+ // What a query asks for: a span, plus control values from the scheduler.
11
+ export class State {
12
+ constructor(span, controls = NO_CONTROLS) { this.span = span; this.controls = controls; }
13
+ setSpan(span) { return new State(span, this.controls); }
14
+ withSpan(f) { return new State(f(this.span), this.controls); }
15
+ }
16
+
17
+ // onNew(pattern), set only while evaluate() runs user code (call-site tags).
18
+ let onNew = null;
19
+ export const setOnNew = (f) => { const o = onNew; onNew = f; return o; };
20
+
21
+ export class Pattern {
22
+ // query: State -> Hap[]. steps: steps per cycle when known (sequences set
23
+ // it; used by polymeter and the poly operator mode), else undefined.
24
+ constructor(query, steps) {
25
+ this.query = query;
26
+ this._steps = steps;
27
+ // { value, context } when every query answers like pure(value) with that
28
+ // context on each hap (set by pure and mini atoms; lets sequences skip the
29
+ // child query, plan 8.7). Undefined otherwise.
30
+ this._pure = undefined;
31
+ // Set by withValue: the source pattern and the composed value function,
32
+ // so a chain of value maps runs as one pass over the source haps.
33
+ this._mapSrc = undefined;
34
+ if (onNew) onNew(this);
35
+ this._mapFn = undefined;
36
+ this._fastOf = undefined; // { pat, f } when this is fastBy(pat, f)
37
+ }
38
+
39
+ // A query that meets an EmptyQuery (asNumber on a word, S5) answers [].
40
+ queryArc(begin, end, controls = {}) {
41
+ try {
42
+ return this.query(new State(new TimeSpan(begin, end), controls));
43
+ } catch (e) {
44
+ if (e instanceof EmptyQuery) return [];
45
+ throw e;
46
+ }
47
+ }
48
+
49
+ firstCycle() { return this.queryArc(0, 1); }
50
+
51
+ withSteps(steps) { return new Pattern(this.query, steps); }
52
+
53
+ // --- query and hap mapping ---
54
+ splitQueries() {
55
+ return new Pattern((state) => {
56
+ const cycles = state.span.spanCycles();
57
+ if (cycles.length === 1) return this.query(state.setSpan(cycles[0]));
58
+ const out = [];
59
+ for (const span of cycles) for (const h of this.query(state.setSpan(span))) out.push(h);
60
+ return out;
61
+ }, this._steps);
62
+ }
63
+
64
+ withQuerySpan(f) { return new Pattern((state) => this.query(state.withSpan(f)), this._steps); }
65
+ withQueryTime(f) { return this.withQuerySpan((span) => span.withTime(f)); }
66
+ withHaps(f) { return new Pattern((state) => f(this.query(state), state), this._steps); }
67
+ withHap(f) { return this.withHaps((haps) => haps.map(f)); }
68
+ withHapSpan(f) { return this.withHap((h) => h.withSpan(f)); }
69
+ withHapTime(f) { return this.withHap((h) => h.withTime(f)); }
70
+ // Consecutive value maps fuse: p.fmap(g).fmap(f) queries p once and applies
71
+ // f(g(v)) per hap, with no intermediate haps (plan 8.7).
72
+ withValue(f) {
73
+ const src = this._mapSrc ?? this;
74
+ const g = this._mapFn;
75
+ const fn = g === undefined ? f
76
+ : f._assigns !== undefined && g._assigns !== undefined ? assignMap([...g._assigns, ...f._assigns])
77
+ : (v) => f(g(v));
78
+ const out = new Pattern((state) => {
79
+ const haps = src.query(state);
80
+ const res = new Array(haps.length);
81
+ for (let i = 0; i < haps.length; i++) {
82
+ const h = haps[i];
83
+ res[i] = new Hap(h.whole, h.part, fn(h.value), h.context);
84
+ }
85
+ return res;
86
+ }, this._steps);
87
+ out._mapSrc = src;
88
+ out._mapFn = fn;
89
+ return out;
90
+ }
91
+ fmap(f) { return this.withValue(f); }
92
+ withContext(f) { return this.withHap((h) => h.withContext(f)); }
93
+
94
+ filterHaps(pred) { return this.withHaps((haps) => haps.filter(pred)); }
95
+ filterValues(pred) { return this.filterHaps((h) => pred(h.value)); }
96
+ onsetsOnly() { return this.filterHaps((h) => h.hasOnset()); }
97
+ discreteOnly() { return this.filterHaps((h) => h.whole !== null); }
98
+
99
+ // --- applicative combination: values of `this` are functions applied to
100
+ // the other side's values. Locations: right side first, then left. ---
101
+
102
+ // Structure from the left: the right is queried over each left whole.
103
+ appLeft(other) {
104
+ const right = reify(other);
105
+ const pure = right._pure;
106
+ return new Pattern((state) => {
107
+ const out = [];
108
+ for (const lh of this.query(state)) {
109
+ if (pure !== undefined) {
110
+ const part = pureOverlap(lh);
111
+ if (part !== undefined) {
112
+ if (part) out.push(new Hap(lh.whole, part, lh.value(pure.value), combineContext(pure.context, lh.context)));
113
+ continue;
114
+ }
115
+ }
116
+ for (const rh of right.query(state.setSpan(lh.wholeOrPart()))) {
117
+ const part = lh.part.intersect(rh.part);
118
+ if (part) out.push(new Hap(lh.whole, part, lh.value(rh.value), combineContext(rh.context, lh.context)));
119
+ }
120
+ }
121
+ return out;
122
+ }, this._steps);
123
+ }
124
+
125
+ // Structure from the right: the left is queried over each right whole.
126
+ appRight(other) {
127
+ const right = reify(other);
128
+ return new Pattern((state) => {
129
+ const out = [];
130
+ for (const rh of right.query(state)) {
131
+ for (const lh of this.query(state.setSpan(rh.wholeOrPart()))) {
132
+ const part = lh.part.intersect(rh.part);
133
+ if (part) out.push(new Hap(rh.whole, part, lh.value(rh.value), combineContext(rh.context, lh.context)));
134
+ }
135
+ }
136
+ return out;
137
+ }, right._steps);
138
+ }
139
+
140
+ // Structure from both: wholes and parts intersect; analog if either is.
141
+ appBoth(other) {
142
+ const right = reify(other);
143
+ return new Pattern((state) => {
144
+ const out = [];
145
+ const rhs = right.query(state);
146
+ for (const lh of this.query(state)) {
147
+ for (const rh of rhs) {
148
+ const part = lh.part.intersect(rh.part);
149
+ if (!part) continue;
150
+ let whole = null;
151
+ if (lh.whole && rh.whole) {
152
+ whole = lh.whole.intersect(rh.whole);
153
+ if (!whole) continue;
154
+ }
155
+ out.push(new Hap(whole, part, lh.value(rh.value), combineContext(rh.context, lh.context)));
156
+ }
157
+ }
158
+ return out;
159
+ });
160
+ }
161
+
162
+ // --- monadic joins on a pattern of patterns ---
163
+
164
+ // Wholes are the intersection of outer and inner wholes.
165
+ join() {
166
+ return new Pattern((state) => {
167
+ const out = [];
168
+ for (const oh of this.query(state)) {
169
+ for (const ih of reify(oh.value).query(state.setSpan(oh.part))) {
170
+ let whole = null;
171
+ if (oh.whole && ih.whole) {
172
+ whole = oh.whole.intersect(ih.whole);
173
+ if (!whole) continue;
174
+ }
175
+ const part = oh.part.intersect(ih.part);
176
+ if (part) out.push(new Hap(whole, part, ih.value, combineContext(oh.context, ih.context)));
177
+ }
178
+ }
179
+ return out;
180
+ });
181
+ }
182
+
183
+ // Structure from the inner patterns, each queried over the outer hap's part
184
+ // (the patterned-argument rule, spec/functions/README.md).
185
+ innerJoin() {
186
+ return new Pattern((state) => {
187
+ const out = [];
188
+ for (const oh of this.query(state)) {
189
+ for (const ih of reify(oh.value).query(state.setSpan(oh.part))) {
190
+ out.push(new Hap(ih.whole, ih.part, ih.value, combineContext(oh.context, ih.context)));
191
+ }
192
+ }
193
+ return out;
194
+ });
195
+ }
196
+
197
+ // Structure from the outer pattern; the value is the inner value active at
198
+ // the start of the outer whole.
199
+ outerJoin() {
200
+ return new Pattern((state) => {
201
+ const out = [];
202
+ for (const oh of this.query(state)) {
203
+ const span = oh.wholeOrPart();
204
+ for (const ih of reify(oh.value).query(state.setSpan(span))) {
205
+ if (!ih.part.begin.eq(span.begin)) continue;
206
+ out.push(new Hap(oh.whole, oh.part, ih.value, combineContext(oh.context, ih.context)));
207
+ }
208
+ }
209
+ return out;
210
+ }, this._steps);
211
+ }
212
+
213
+ // Cycle 0 of each inner pattern is compressed into its outer hap's whole.
214
+ squeezeJoin() {
215
+ return new Pattern((state) => {
216
+ const out = [];
217
+ for (const oh of this.query(state)) {
218
+ const w = oh.wholeOrPart();
219
+ const len = w.end.sub(w.begin);
220
+ if (len.sign() <= 0) continue;
221
+ // Squeeze the inner cycle the outer whole starts in (fixture
222
+ // ops/squeeze-alt, functions/ply-frac), not always cycle 0.
223
+ const cycle = w.begin.sam();
224
+ const toInner = (x) => cycle.add(x.sub(w.begin).div(len));
225
+ const toOuter = (t) => w.begin.add(t.sub(cycle).mul(len));
226
+ for (const ih of reify(oh.value).query(state.setSpan(oh.part.withTime(toInner)))) {
227
+ const part = ih.part.withTime(toOuter).intersect(oh.part);
228
+ if (!part) continue;
229
+ let whole = null;
230
+ if (ih.whole) {
231
+ whole = ih.whole.withTime(toOuter).intersect(w);
232
+ if (!whole) continue;
233
+ }
234
+ out.push(new Hap(whole, part, ih.value, combineContext(ih.context, oh.context)));
235
+ }
236
+ }
237
+ return out;
238
+ });
239
+ }
240
+
241
+ bind(f) { return this.fmap(f).join(); }
242
+ innerBind(f) { return this.fmap(f).innerJoin(); }
243
+ outerBind(f) { return this.fmap(f).outerJoin(); }
244
+ squeezeBind(f) { return this.fmap(f).squeezeJoin(); }
245
+ }
246
+
247
+ export const isPattern = (x) => x instanceof Pattern;
248
+
249
+ // A left hap against a constant (`_pure`) right side queried over the left
250
+ // whole: when that whole lies within one cycle, the right side has a single hap
251
+ // whose part is the whole itself, so the overlap is part ∩ whole (null when
252
+ // none) and the right query can be skipped. undefined: the whole crosses a
253
+ // cycle boundary, run the real query (plan 8.7).
254
+ export function pureOverlap(lh) {
255
+ const w = lh.wholeOrPart();
256
+ const c = w.begin.compare(w.end);
257
+ if (c < 0 && w.end.gt(w.begin.nextSam())) return undefined;
258
+ if (c < 0 && lh.part === w) return w; // a whole-only hap overlaps itself
259
+ return lh.part.intersect(w);
260
+ }
261
+
262
+ // A value map that copies a control map (a non-map value counts as {}) and
263
+ // sets the [key, value] entries in order. Two in a row fuse into one copy
264
+ // (withValue), which is what a chain like `.s("x").gain(1).lpf(900)` becomes.
265
+ export function assignMap(entries) {
266
+ const fn = (v) => {
267
+ const o = v !== null && typeof v === 'object' && !Array.isArray(v) ? { ...v } : {};
268
+ for (let i = 0; i < entries.length; i++) o[entries[i][0]] = entries[i][1];
269
+ return o;
270
+ };
271
+ fn._assigns = entries;
272
+ return fn;
273
+ }
274
+
275
+ // --- constructors needed by reify ---
276
+
277
+ const nothing = () => [];
278
+ export const silence = new Pattern(nothing, 1);
279
+
280
+ // One hap per cycle touched by the query (spec/time.md 4.4).
281
+ export function pure(value) { return pureWith(value, EMPTY_CONTEXT); }
282
+
283
+ // pure(value).withContext(() => context) in one step (mini-notation atoms).
284
+ export function pureWith(value, context) {
285
+ const pat = new Pattern((state) => {
286
+ const span = state.span;
287
+ if (span.begin.eq(span.end)) {
288
+ const sam = span.begin.sam();
289
+ return [new Hap(new TimeSpan(sam, sam.add(1)), span, value, context)];
290
+ }
291
+ const next = span.begin.nextSam();
292
+ if (span.end.lte(next)) { // within one cycle: one hap, no splitting
293
+ const sam = span.begin.sam();
294
+ const whole = span.begin.eq(sam) && span.end.eq(next) ? span : new TimeSpan(sam, next);
295
+ return [new Hap(whole, span, value, context)];
296
+ }
297
+ return span.spanCycles().map((part) => {
298
+ const sam = part.begin.sam();
299
+ const next = part.begin.nextSam();
300
+ // A whole-cycle part is its own whole (spans are immutable).
301
+ const whole = part.begin.eq(sam) && part.end.eq(next) ? part : new TimeSpan(sam, next);
302
+ return new Hap(whole, part, value, context);
303
+ });
304
+ }, 1);
305
+ pat._pure = { value, context };
306
+ return pat;
307
+ }
308
+
309
+ // Continuous pattern: one analog hap per query, value f(begin) (spec/time.md 6.1).
310
+ // f receives the begin as a Fraction.
311
+ export function signal(f) {
312
+ return new Pattern((state) => [new Hap(null, state.span, f(state.span.begin))]);
313
+ }
314
+
315
+ // --- strings: mini-notation hook. Epic 3 installs the real parser with
316
+ // setStringParser(); until then only a single plain token is understood. ---
317
+
318
+ // Thrown inside a query to make the whole top-level queryArc return no haps
319
+ // (asNumber on a word, S5: Strudel's query aborts there).
320
+ // Invariant: `Pattern#query(state)` is internal and may throw EmptyQuery;
321
+ // every top-level caller (scheduler, draw, visuals, samples preload, check,
322
+ // describe, hosts) queries through `queryArc`, which turns it into [].
323
+ // Combinators must not catch it. test/unit/pattern-invariants.test.js checks
324
+ // both the behaviour and that no module outside pattern.js builds a
325
+ // top-level `query(new State(...))`.
326
+ export class EmptyQuery extends Error {
327
+ constructor() { super('empty query'); this.name = 'EmptyQuery'; }
328
+ }
329
+
330
+ export class NeedsMiniNotation extends Error {
331
+ constructor(s) {
332
+ super(`mini-notation is not available yet: ${JSON.stringify(s)}`);
333
+ this.name = 'NeedsMiniNotation';
334
+ }
335
+ }
336
+
337
+ const TOKEN = /^-?[A-Za-z0-9_#'.:-]*[A-Za-z0-9_#']$/;
338
+ const NUMBER = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
339
+
340
+ function plainToken(s) {
341
+ const t = s.trim();
342
+ if (t === '~') return silence;
343
+ if (!TOKEN.test(t)) throw new NeedsMiniNotation(s);
344
+ const value = (x) => (NUMBER.test(x) ? Number(x) : x);
345
+ // `a:b:c` is the array [a, b, c] (spec/mini.md section 2).
346
+ return pure(t.includes(':') ? t.split(':').map(value) : value(t));
347
+ }
348
+
349
+ let stringParser = plainToken;
350
+ export function setStringParser(fn) { stringParser = fn ?? plainToken; }
351
+ export function getStringParser() { return stringParser === plainToken ? null : stringParser; }
352
+
353
+ // Plain value, string, array or pattern -> pattern. Arrays are sequences.
354
+ export function reify(x) {
355
+ if (x instanceof Pattern) return x;
356
+ if (typeof x === 'string') return stringParser(x);
357
+ if (Array.isArray(x)) return sequenceOf(x);
358
+ return pure(x);
359
+ }
360
+
361
+ // fastcat of the array items, installed by constructors.js (avoids a cycle).
362
+ let sequenceOf = (items) => { throw new Error(`sequences are not loaded (${items.length} items)`); };
363
+ export function setSequenceBuilder(fn) { sequenceOf = fn; }
364
+
365
+