@kairotic/app 0.0.0-stage → 0.2.1

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 (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,271 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · input
3
+ ;; Sound from outside, and sound back into messages and pictures.
4
+ ;;
5
+ ;; adc~ [channel …] audio input (the microphone or the sound card): one outlet per channel
6
+ ;; written after it (adc~ 1 by default). Asks for the microphone at ▶.
7
+ ;; snapshot~ [ms] [rms|peak|db]
8
+ ;; a signal as numbers, every ms (50 by default): its value, or its level
9
+ ;; (rms, peak, or rms in dB). Sends only what changed.
10
+ ;; scope~ [ms] [zoom] an oscilloscope in the patch: the last ms (20) of the signal, steady on a
11
+ ;; rising zero crossing; drag up/down to zoom, sideways for the time.
12
+ ;;
13
+ ;; The audio nodes cannot send messages: they report what they find to their own box (api/report!),
14
+ ;; which receives it on inlet :audio and decides what to send, show and keep, in its pure :receive.
15
+ ;; The loops over samples run in an AudioWorklet (api/tap): the page only handles small arrays.
16
+
17
+ (ns kairotic.input
18
+ (:require [clojure.string :as str]
19
+ [kairotic.components :as comp]
20
+ [kairotic.api :as api]))
21
+
22
+ ;; ───────── the microphone: one stream for every adc~ ─────────
23
+
24
+ (defn adc-channels
25
+ "The input channels of an adc~ (1-based): its numbers, or 1."
26
+ [b] (let [cs (filterv (fn [x] (and (number? x) (>= x 1))) (:args b))] (if (seq cs) (mapv js/Math.floor cs) [1])))
27
+
28
+ (def max-channels 32)
29
+
30
+ ;; {:ac :p (Promise of {:stream :source :split :have}) :users n :closing timeout}
31
+ (defonce mic (atom nil))
32
+
33
+ (defn constraints
34
+ "What is asked of the microphone: its sound as it is (no echo cancellation, noise suppression or
35
+ automatic gain, which are made for speech and change music), with as many channels as it has."
36
+ [n]
37
+ (clj->js {:audio {:channelCount {:ideal (max 2 n)}
38
+ :echoCancellation false :noiseSuppression false :autoGainControl false}}))
39
+
40
+ (defn close! [m]
41
+ (.then (:p m)
42
+ (fn [{:keys [stream source split]}]
43
+ (try (.disconnect source) (.disconnect split) (catch :default _ nil))
44
+ (doseq [t (array-seq (.getTracks stream))] (.stop t)))
45
+ (fn [_] nil)))
46
+
47
+ (defn open!
48
+ "Promise of the shared input ({:stream :source :split :have}) in AudioContext ac, opened the first
49
+ time an adc~ asks (asking for the microphone) and shared by every adc~ after."
50
+ [ac n]
51
+ (let [m @mic]
52
+ (if (and m (identical? (:ac m) ac))
53
+ (do (when-let [t (:closing m)] (js/clearTimeout t))
54
+ (swap! mic (fn [m] (-> m (update :users inc) (dissoc :closing))))
55
+ (:p m))
56
+ (let [md (.-mediaDevices js/navigator)
57
+ p (if-not (and md (.-getUserMedia md))
58
+ (js/Promise.reject (js/Error. "this page cannot use a microphone (it needs https or localhost)"))
59
+ (.then (.getUserMedia md (constraints n))
60
+ (fn [stream]
61
+ (let [source (.createMediaStreamSource ac stream)
62
+ split (.createChannelSplitter ac max-channels)
63
+ track (first (array-seq (.getAudioTracks stream)))
64
+ have (when track (.-channelCount (.getSettings track)))]
65
+ (.connect source split)
66
+ {:stream stream :source source :split split :have have}))))]
67
+ (when m (close! m))
68
+ ;; a refusal is not kept: the next ▶ asks again
69
+ (.catch p (fn [_] (when (identical? (:p @mic) p) (reset! mic nil))))
70
+ (reset! mic {:ac ac :p p :users 1})
71
+ p))))
72
+
73
+ (defn release!
74
+ "An adc~ no longer listens. When none does, the microphone is closed a moment later (an adc~ rebuilt
75
+ because its text changed takes it again in between, without asking)."
76
+ []
77
+ (when-let [m @mic]
78
+ (if (> (:users m) 1)
79
+ (swap! mic update :users dec)
80
+ (swap! mic assoc :users 0
81
+ :closing (js/setTimeout (fn [] (let [m @mic]
82
+ (when (and m (zero? (:users m)))
83
+ (reset! mic nil)
84
+ (close! m))))
85
+ 2000)))))
86
+
87
+ (defn report-error [e] {:error (str "adc~: " (or (.-message e) e))})
88
+
89
+ (comp/define! "adc~"
90
+ {:doc "Audio input (the microphone or the sound card): one outlet per input channel, the ones written after it (adc~ 1 by default; adc~ 1 2 for stereo). At ▶ it asks for the microphone, and takes its sound as it is, without the echo cancellation, noise suppression and automatic gain made for speech. Every adc~ shares one stream."
91
+ :usage "adc~ [channel …]"
92
+ :license "MPL-2.0"
93
+ :io (fn [b] [0 (count (adc-channels b))]) :dynamic-io true
94
+ :receive (fn [{:keys [inlet value]}]
95
+ (if (and (= inlet :audio) (map? value) (:error value))
96
+ {:effects [[:print (:error value)]]}
97
+ {}))
98
+ :audio {:create (fn [ac b _]
99
+ (let [cs (adc-channels b)
100
+ outs (vec (for [_ cs] (.createGain ac)))
101
+ alive (atom true)
102
+ node {:outs outs :alive alive :outlets (vec (for [g outs] [g 0]))}]
103
+ (-> (open! ac (apply max cs))
104
+ (.then (fn [{:keys [split have]}]
105
+ (when @alive
106
+ (doseq [[c g] (map vector cs outs) :when (<= c max-channels)]
107
+ (.connect split g (dec c)))
108
+ (when-let [missing (seq (filter (fn [c] (and (number? have) (> c have))) cs))]
109
+ (api/report! (:id b) {:error (str "adc~: the input has " have " channel"
110
+ (when (not= 1 have) "s") ": channel "
111
+ (str/join " " missing) " is silent")}
112
+ nil)))))
113
+ (.catch (fn [e] (when @alive (api/report! (:id b) (report-error e) nil)))))
114
+ node))
115
+ :key (fn [b] (adc-channels b))
116
+ :dispose (fn [node]
117
+ (reset! (:alive node) false)
118
+ (doseq [g (:outs node)] (try (.disconnect g) (catch :default _ nil)))
119
+ (release!))}})
120
+
121
+ ;; ───────── snapshot~: a signal as numbers ─────────
122
+
123
+ (def snapshot-modes #{:rms :peak :db})
124
+
125
+ (defn snapshot-value
126
+ "The number a snapshot~ sends for a block [last rms peak] of the tap."
127
+ [mode [last rms peak]]
128
+ (case mode
129
+ :rms rms
130
+ :peak peak
131
+ :db (comp/nice (api/db rms))
132
+ last))
133
+
134
+ (defn level-unit
135
+ "Where a value of a snapshot~ stands on its bar (0…1): levels as they are, dB from -60 to 0."
136
+ [mode v]
137
+ (when (number? v)
138
+ (case mode
139
+ (:rms :peak) (comp/clamp v 0 1)
140
+ :db (comp/clamp (/ (+ v 60) 60) 0 1)
141
+ nil)))
142
+
143
+ (defn snapshot-ms [x] (comp/clamp (or (comp/num-of x) 50) 5 10000))
144
+
145
+ (comp/define! "snapshot~"
146
+ {:doc "A signal as numbers: every ms (50 by default) its last value, or with a word its level over that time — rms, peak, or db (the rms in decibels). It sends only what changed, so a constant signal sends once. A number on the left changes ms; a bang sends the last value again. With adc~ it is a level meter; with phasor~, an envelope or faust~ it brings a signal back into the messages."
147
+ :usage "snapshot~ [ms] [rms|peak|db]"
148
+ :license "MPL-2.0"
149
+ :io [1 1]
150
+ :size [104 30]
151
+ :args [[:ms 50] [:mode nil]]
152
+ :receive (fn [{:keys [inlet value state args]}]
153
+ (let [mode (snapshot-modes (:mode args))]
154
+ (cond
155
+ (= inlet :audio)
156
+ (let [block (first value)
157
+ v (when block (snapshot-value mode (vec (array-seq block))))]
158
+ (if (and (number? v) (not= v state))
159
+ {:state v :show v :out [[0 v]]}
160
+ {}))
161
+ (= value :bang) (if (number? state) {:out [[0 state]] :show state} {})
162
+ (comp/num-of value) {:effects [[:ms (snapshot-ms value)]]}
163
+ :else {})))
164
+ :derive (fn [{:keys [shown args]}]
165
+ (let [mode (snapshot-modes (:mode args)) u (level-unit mode shown)]
166
+ {:label (str (if (number? shown) (comp/nice shown) "–") (when (= mode :db) " dB"))
167
+ :bar (if u (* 96 u) 0)
168
+ :tag (if mode (name mode) "value")}))
169
+ :view [[:rect {:x 2 :y 2 :w 100 :h 26 :r 3 :stroke :grid :fill :bg}]
170
+ [:rect {:x 4 :y 22 :w :$bar :h 4 :r 1 :stroke nil :fill :accent}]
171
+ [:text {:x 6 :y 16 :size 11} :$label]
172
+ [:text {:x 98 :y 16 :anchor :end :size 8 :fill :soft} :$tag]]
173
+ :audio {:create (fn [ac b _]
174
+ (let [in (.createGain ac)
175
+ args (comp/args-for (comp/lookup "snapshot~") (:text b))
176
+ hop (fn [ms] (js/Math.max 16 (js/Math.round (* (.-sampleRate ac) (/ ms 1000)))))
177
+ ms (snapshot-ms (:ms args))
178
+ node {:in in :hop hop :tap (atom nil) :alive (atom true) :inlets [[in 0]] :outlets []}]
179
+ (-> (api/tap ac {:mode :summary :size (hop ms) :hop (hop ms)}
180
+ (fn [data at & _] (when @(:alive node) (api/report! (:id b) data at))))
181
+ (.then (fn [w] (if @(:alive node) (do (.connect in w) (reset! (:tap node) w))
182
+ (try (.disconnect w) (catch :default _ nil)))))
183
+ (.catch (fn [e] (js/console.error "snapshot~" e))))
184
+ node))
185
+ :update (fn [node b _]
186
+ (when-let [w @(:tap node)]
187
+ (let [h ((:hop node) (snapshot-ms (:ms (comp/args-for (comp/lookup "snapshot~") (:text b)))))]
188
+ (api/retap w {:size h :hop h}))))
189
+ :effects {:ms (fn [node ms _]
190
+ (when-let [w @(:tap node)] (let [h ((:hop node) ms)] (api/retap w {:size h :hop h}))))}
191
+ :dispose (fn [node]
192
+ (reset! (:alive node) false)
193
+ (api/untap @(:tap node))
194
+ (try (.disconnect (:in node)) (catch :default _ nil)))}})
195
+
196
+ ;; ───────── scope~: an oscilloscope ─────────
197
+
198
+ (def scope-w 168)
199
+ (def scope-h 84)
200
+ (def scope-columns 160) ; one [min max] pair per pixel of the trace (x from 4 to 164)
201
+
202
+ (defn scope-ms [x] (comp/clamp (or (comp/num-of x) 20) 1 2000))
203
+ (defn scope-zoom [x] (comp/clamp (or (comp/num-of x) 1) 0.125 64))
204
+
205
+ (defn trace-points
206
+ "The polyline of a trace: columns pairs [min max] (a Float32Array or a seq) as points from x 4 to 164,
207
+ around the middle line, `zoom` times taller (clipped to the box)."
208
+ [col zoom]
209
+ (let [xs (vec (array-seq col)) k (quot (count xs) 2)
210
+ mid (/ scope-h 2) half (- mid 6)
211
+ y (fn [v] (comp/clamp (- mid (* v zoom half)) 4 (- scope-h 4)))]
212
+ (when (pos? k)
213
+ (vec (for [i (range k) j [0 1]]
214
+ [(+ 4 (* (- scope-w 8) (/ i (max 1 (dec k))))) (y (nth xs (+ (* 2 i) j)))])))))
215
+
216
+ (defn scope-view [m]
217
+ (let [{:keys [ms zoom]} (merge (:args m) (when (map? (:state m)) (:state m)))]
218
+ {:ms (scope-ms ms) :zoom (scope-zoom zoom)}))
219
+
220
+ (comp/define! "scope~"
221
+ {:doc "An oscilloscope in the patch: the last ms (20 by default) of the signal on its left, drawn from a rising zero crossing so a periodic wave stands still. zoom makes it taller. Drag up or down over it to zoom (⇧ finer) and sideways to change the time; on release both stay in the box text. A number on the left changes ms."
222
+ :usage "scope~ [ms] [zoom]"
223
+ :license "MPL-2.0"
224
+ :io [1 0]
225
+ :size [168 84]
226
+ :args [[:ms 20] [:zoom 1]]
227
+ :persist (fn [{:keys [ms zoom]}] {:ms (comp/nice ms) :zoom (comp/nice zoom)})
228
+ :receive (fn [{:keys [inlet value] :as m}]
229
+ (let [{:keys [ms zoom] :as v} (scope-view m)]
230
+ (cond
231
+ (= inlet :audio) {:show (assoc v :pts (trace-points (first value) zoom))}
232
+ (and (map? value) (contains? value :zoom))
233
+ (let [nv {:ms (scope-ms (:ms value)) :zoom (scope-zoom (:zoom value))}]
234
+ {:state nv :effects [[:ms (:ms nv)]]})
235
+ (comp/num-of value) (let [nv (assoc v :ms (scope-ms value))] {:state nv :effects [[:ms (:ms nv)]]})
236
+ :else {})))
237
+ ;; from what it showed on press (or its text): not from its state, which the drag itself changes
238
+ :gesture (fn [{:keys [start dx dy fine] :as m}]
239
+ (let [{:keys [ms zoom]} (if (and (map? start) (:ms start)) start (scope-view (dissoc m :state)))
240
+ k (if fine 4 1)]
241
+ {:ms (scope-ms (* ms (js/Math.pow 2 (/ dx (* 40 k)))))
242
+ :zoom (scope-zoom (* zoom (js/Math.pow 2 (/ (- dy) (* 40 k)))))}))
243
+ :derive (fn [{:keys [shown] :as m}]
244
+ (let [{:keys [ms zoom]} (scope-view m)]
245
+ {:pts (when (map? shown) (:pts shown))
246
+ :label (str (comp/nice ms) " ms" (when (not= zoom 1) (str " · ×" (comp/nice zoom))))}))
247
+ :view [[:rect {:x 2 :y 2 :w 164 :h 80 :r 4 :stroke :grid :fill :bg}]
248
+ [:line {:x1 4 :y1 42 :x2 164 :y2 42 :stroke :grid}]
249
+ [:path {:points :$pts :stroke :accent :weight 1}]
250
+ [:text {:x 162 :y 78 :anchor :end :size 8 :fill :soft} :$label]]
251
+ :audio {:create (fn [ac b _]
252
+ (let [in (.createGain ac)
253
+ sr (.-sampleRate ac)
254
+ samples (fn [ms] (js/Math.max 32 (js/Math.round (* sr (/ ms 1000)))))
255
+ ms (scope-ms (:ms (comp/args-for (comp/lookup "scope~") (:text b))))
256
+ node {:in in :samples samples :tap (atom nil) :alive (atom true) :inlets [[in 0]] :outlets []}]
257
+ ;; about 30 pictures a second
258
+ (-> (api/tap ac {:mode :trace :size (samples ms) :hop (js/Math.round (/ sr 30)) :columns scope-columns}
259
+ (fn [data at & _] (when @(:alive node) (api/report! (:id b) data at))))
260
+ (.then (fn [w] (if @(:alive node) (do (.connect in w) (reset! (:tap node) w))
261
+ (try (.disconnect w) (catch :default _ nil)))))
262
+ (.catch (fn [e] (js/console.error "scope~" e))))
263
+ node))
264
+ :update (fn [node b _]
265
+ (when-let [w @(:tap node)]
266
+ (api/retap w {:size ((:samples node) (scope-ms (:ms (comp/args-for (comp/lookup "scope~") (:text b)))))})))
267
+ :effects {:ms (fn [node ms _] (when-let [w @(:tap node)] (api/retap w {:size ((:samples node) ms)})))}
268
+ :dispose (fn [node]
269
+ (reset! (:alive node) false)
270
+ (api/untap @(:tap node))
271
+ (try (.disconnect (:in node)) (catch :default _ nil)))}})
@@ -0,0 +1,138 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+ // Kairotic · a work as a file (discussion #149): the zip container and the sound files of a .kairotic.
3
+ // Plain JavaScript, no dependency: a zip of stored and deflated entries (deflate with the browser's
4
+ // CompressionStream, where there is one), read back the same way; and sounds as 32-bit float WAV, so the
5
+ // samples come back exactly as they were kept (their hash is their key in this browser).
6
+
7
+ const enc = new TextEncoder();
8
+ const dec = new TextDecoder();
9
+
10
+ // ───── CRC-32 (the zip's) ─────
11
+ const table = (() => {
12
+ const t = new Uint32Array(256);
13
+ for (let n = 0; n < 256; n++) {
14
+ let c = n;
15
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
16
+ t[n] = c >>> 0;
17
+ }
18
+ return t;
19
+ })();
20
+ function crc32(bytes) {
21
+ let c = 0xffffffff;
22
+ for (let i = 0; i < bytes.length; i++) c = table[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
23
+ return (c ^ 0xffffffff) >>> 0;
24
+ }
25
+
26
+ async function through(bytes, stream) {
27
+ const out = await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer();
28
+ return new Uint8Array(out);
29
+ }
30
+ const canDeflate = () => typeof CompressionStream !== "undefined";
31
+
32
+ // ───── zip ─────
33
+ // files: [{name, data: Uint8Array | string, deflate?: boolean}] → Promise<Uint8Array>
34
+ async function zip(files) {
35
+ const entries = [];
36
+ for (const f of files) {
37
+ const data = typeof f.data === "string" ? enc.encode(f.data) : f.data;
38
+ const name = enc.encode(f.name);
39
+ let body = data, method = 0;
40
+ if (f.deflate !== false && canDeflate() && data.length > 64) {
41
+ const z = await through(data, new CompressionStream("deflate-raw"));
42
+ if (z.length < data.length) { body = z; method = 8; }
43
+ }
44
+ entries.push({ name, data, body, method, crc: crc32(data) });
45
+ }
46
+ const parts = [];
47
+ const central = [];
48
+ let offset = 0;
49
+ const u16 = (v, a, i) => a.setUint16(i, v, true);
50
+ const u32 = (v, a, i) => a.setUint32(i, v >>> 0, true);
51
+ for (const e of entries) {
52
+ const h = new DataView(new ArrayBuffer(30));
53
+ u32(0x04034b50, h, 0); u16(20, h, 4); u16(0x0800, h, 6); u16(e.method, h, 8); u16(0, h, 10); u16(0x21, h, 12);
54
+ u32(e.crc, h, 14); u32(e.body.length, h, 18); u32(e.data.length, h, 22); u16(e.name.length, h, 26); u16(0, h, 28);
55
+ parts.push(new Uint8Array(h.buffer), e.name, e.body);
56
+ const c = new DataView(new ArrayBuffer(46));
57
+ u32(0x02014b50, c, 0); u16(20, c, 4); u16(20, c, 6); u16(0x0800, c, 8); u16(e.method, c, 10); u16(0, c, 12); u16(0x21, c, 14);
58
+ u32(e.crc, c, 16); u32(e.body.length, c, 20); u32(e.data.length, c, 24); u16(e.name.length, c, 28);
59
+ u16(0, c, 30); u16(0, c, 32); u16(0, c, 34); u16(0, c, 36); u32(0, c, 38); u32(offset, c, 42);
60
+ central.push(new Uint8Array(c.buffer), e.name);
61
+ offset += 30 + e.name.length + e.body.length;
62
+ }
63
+ const size = central.reduce((s, p) => s + p.length, 0);
64
+ const end = new DataView(new ArrayBuffer(22));
65
+ u32(0x06054b50, end, 0); u16(0, end, 4); u16(0, end, 6); u16(entries.length, end, 8); u16(entries.length, end, 10);
66
+ u32(size, end, 12); u32(offset, end, 16); u16(0, end, 20);
67
+ return new Uint8Array(await new Blob([...parts, ...central, new Uint8Array(end.buffer)]).arrayBuffer());
68
+ }
69
+
70
+ // bytes → Promise<[{name, data: Uint8Array}]> (stored and deflated entries; the CRC is checked)
71
+ async function unzip(bytes) {
72
+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
73
+ let e = bytes.length - 22;
74
+ while (e >= 0 && v.getUint32(e, true) !== 0x06054b50) e--;
75
+ if (e < 0) throw new Error("not a zip file");
76
+ const n = v.getUint16(e + 10, true);
77
+ let p = v.getUint32(e + 16, true);
78
+ const files = [];
79
+ for (let i = 0; i < n; i++) {
80
+ if (v.getUint32(p, true) !== 0x02014b50) throw new Error("a broken zip file");
81
+ const method = v.getUint16(p + 10, true), crc = v.getUint32(p + 16, true);
82
+ const csize = v.getUint32(p + 20, true), size = v.getUint32(p + 24, true);
83
+ const nlen = v.getUint16(p + 28, true), xlen = v.getUint16(p + 30, true), clen = v.getUint16(p + 32, true);
84
+ const local = v.getUint32(p + 42, true);
85
+ const name = dec.decode(bytes.subarray(p + 46, p + 46 + nlen));
86
+ const start = local + 30 + v.getUint16(local + 26, true) + v.getUint16(local + 28, true);
87
+ const body = bytes.subarray(start, start + csize);
88
+ let data;
89
+ if (method === 0) data = body.slice();
90
+ else if (method === 8) {
91
+ if (typeof DecompressionStream === "undefined") throw new Error("this browser cannot read deflated zip entries");
92
+ data = await through(body, new DecompressionStream("deflate-raw"));
93
+ } else throw new Error("zip method " + method + " is not supported (" + name + ")");
94
+ if (data.length !== size || crc32(data) !== crc) throw new Error("a damaged entry in the file: " + name);
95
+ files.push({ name, data });
96
+ p += 46 + nlen + xlen + clen;
97
+ }
98
+ return files;
99
+ }
100
+
101
+ // ───── sounds: 32-bit float WAV ─────
102
+ // (sample rate, [Float32Array per channel]) → Uint8Array
103
+ function wav(sr, chans) {
104
+ const nc = chans.length, frames = nc ? chans[0].length : 0, bytes = frames * nc * 4;
105
+ const b = new ArrayBuffer(44 + bytes), v = new DataView(b);
106
+ const s = (i, t) => { for (let k = 0; k < t.length; k++) v.setUint8(i + k, t.charCodeAt(k)); };
107
+ s(0, "RIFF"); v.setUint32(4, 36 + bytes, true); s(8, "WAVE");
108
+ s(12, "fmt "); v.setUint32(16, 16, true); v.setUint16(20, 3, true); v.setUint16(22, nc, true);
109
+ v.setUint32(24, sr, true); v.setUint32(28, sr * nc * 4, true); v.setUint16(32, nc * 4, true); v.setUint16(34, 32, true);
110
+ s(36, "data"); v.setUint32(40, bytes, true);
111
+ const out = new Float32Array(b, 44, frames * nc);
112
+ for (let i = 0; i < frames; i++) for (let c = 0; c < nc; c++) out[i * nc + c] = chans[c][i];
113
+ return new Uint8Array(b);
114
+ }
115
+
116
+ // Uint8Array of a float WAV written above → {sr, chans}
117
+ function unwav(bytes) {
118
+ const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
119
+ const tag = (i) => String.fromCharCode(v.getUint8(i), v.getUint8(i + 1), v.getUint8(i + 2), v.getUint8(i + 3));
120
+ if (tag(0) !== "RIFF" || tag(8) !== "WAVE") throw new Error("not a WAV file");
121
+ let p = 12, fmt = null, data = null;
122
+ while (p + 8 <= bytes.length) {
123
+ const id = tag(p), len = v.getUint32(p + 4, true);
124
+ if (id === "fmt ") fmt = { format: v.getUint16(p + 8, true), nc: v.getUint16(p + 10, true), sr: v.getUint32(p + 12, true), bits: v.getUint16(p + 22, true) };
125
+ if (id === "data") data = { at: p + 8, len };
126
+ p += 8 + len + (len % 2);
127
+ }
128
+ if (!fmt || !data || fmt.format !== 3 || fmt.bits !== 32) throw new Error("a sound of a .kairotic is a 32-bit float WAV");
129
+ const frames = Math.floor(data.len / (4 * fmt.nc));
130
+ const chans = Array.from({ length: fmt.nc }, () => new Float32Array(frames));
131
+ for (let i = 0; i < frames; i++)
132
+ for (let c = 0; c < fmt.nc; c++) chans[c][i] = v.getFloat32(data.at + (i * fmt.nc + c) * 4, true);
133
+ return { sr: fmt.sr, chans };
134
+ }
135
+
136
+ const text = (bytes) => dec.decode(bytes);
137
+
138
+ export default { zip, unzip, wav, unwav, text, crc32 };
@@ -0,0 +1,214 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · library
3
+ ;; Components that do not come from the core. Three levels, with the same format:
4
+ ;; 1. in the work: a `component` box whose source is the definition; it travels with the work and its history
5
+ ;; 2. shared: this space's library (the artifact's database), to use in other works
6
+ ;; 3. published: an npm package served by jsDelivr, pinned by version
7
+ ;; Whatever is used from 2 and 3 is copied into a `component` box of the work: so every work is complete,
8
+ ;; works offline and sounds the same even if the library changes later.
9
+ ;;
10
+ ;; Format of a published component (an .mjs module):
11
+ ;; export default { class: "drift", version: "1.0.0", author: "…", license: "MPL-2.0", doc: "…",
12
+ ;; source: `{:class "drift" :io [1 1] :receive (fn [m] …)}` };
13
+ ;;
14
+ ;; A package (Study 14) is several components published together, and travels as ONE component box:
15
+ ;; export default { package: "@kairotic/synth", version: "0.1.0", api: 1, license: "MPL-2.0",
16
+ ;; components: [{class: "adsr~", doc: "…", source: "…"}, …] };
17
+ ;; and its box holds {:package "@kairotic/synth" :version "0.1.0" :api 1 :components [<source> …]}.
18
+ ;; Writing a class that a known package defines (see `packages`) brings that package into the work.
19
+
20
+ (ns kairotic.library
21
+ (:require [clojure.string :as str]
22
+ [kairotic.api :as api]
23
+ [kairotic.components :as comp]
24
+ [kairotic.code :as code]))
25
+
26
+ (def template
27
+ "{:class \"echo-msg\"
28
+ :doc \"Returns what it receives (change it to anything).\"
29
+ :io [1 1]
30
+ :receive (fn [{:keys [inlet value state args at]}]
31
+ ;; return {:out [[outlet value]] :state … :later [[at inlet value]]}
32
+ {:out [[0 value]]})}")
33
+
34
+ (declare validate)
35
+
36
+ (defn validate-package
37
+ "nil if a package map is valid; otherwise, the reason."
38
+ [m]
39
+ (cond
40
+ (not (string? (:package m))) "a package has :package \"@scope/name\""
41
+ (not (sequential? (:components m))) "a package has :components [definition …]"
42
+ (and (:api m) (> (:api m) api/version)) (str (:package m) " needs the Kairotic API " (:api m) " (this one is " api/version ")")
43
+ :else (some (fn [c] (when-let [r (validate c)] (str (or (:class c) "a component") ": " r))) (:components m))))
44
+
45
+ (defn package? [m] (and (map? m) (contains? m :package)))
46
+
47
+ (defn definitions
48
+ "The component definitions in what a component box evaluates to: one, or those of a package
49
+ (each marked with :package and :version)."
50
+ [m]
51
+ (if (package? m)
52
+ (for [c (:components m)] (assoc c :package (:package m) :version (:version m)))
53
+ [m]))
54
+
55
+ (defn validate
56
+ "nil if the definition is valid; otherwise, the reason."
57
+ [m]
58
+ (cond
59
+ (package? m) (validate-package m)
60
+ (not (map? m)) "a component's source is a map {:class … :receive …}"
61
+ (not (and (string? (:class m)) (re-matches #"[^\s()\[\]{}\"]+" (:class m)))) "missing :class (one word, e.g. \"fifth\")"
62
+ (= :core (:origin (comp/lookup (:class m)))) (str "«" (:class m) "» is a core class; use another name")
63
+ (not (or (fn? (:receive m)) (map? (:audio m)) (map? (:patch m)))) "missing :receive (fn [m] …), :audio or :patch"
64
+ (and (contains? m :tasks) (not (and (map? (:tasks m)) (every? keyword? (keys (:tasks m))) (every? fn? (vals (:tasks m))))))
65
+ ":tasks is a map {:name (fn [x box] promise)}"
66
+ (and (contains? m :tasks) (not (fn? (:receive m)))) "a component with :tasks needs a :receive to ask for them and get what they find"
67
+ (some #{:print :keep :tree-edit :tree-set :canvas-edit :presets :sample} (keys (:tasks m)))
68
+ "a task cannot be called :print, :keep or another effect of the page"
69
+ (and (contains? m :patch) (not (and (map? (:patch m)) (map? (:boxes (:patch m))))))
70
+ ":patch is a patch {:boxes {…} :lines […]}"
71
+ (and (contains? m :io) (not (or (fn? (:io m)) (and (vector? (:io m)) (= 2 (count (:io m))) (every? number? (:io m))))))
72
+ ":io is [inlets outlets] or a function"
73
+ :else nil))
74
+
75
+ ;; the language of component boxes: ClojureScript that evaluates to a definition map
76
+ (code/register-language! "component"
77
+ (fn [source]
78
+ (js/Promise.
79
+ (fn [res rej]
80
+ (if-not (code/allowed? source)
81
+ (rej (js/Error. "not run: this work is shared; (trust-scripts true) to evaluate its components"))
82
+ (try
83
+ (let [m (js/scittle.core.eval_string (str "(do " source "\n)"))]
84
+ (if-let [reason (validate m)]
85
+ (rej (js/Error. reason))
86
+ (if (package? m)
87
+ (res {:value m
88
+ :info {:class (:package m)
89
+ :summary (str (:package m) " " (:version m) " · "
90
+ (str/join ", " (map :class (:components m))))}})
91
+ (let [io (:io m)]
92
+ (res {:value m
93
+ :info {:class (:class m)
94
+ :summary (str "defines «" (:class m) "»"
95
+ (when (vector? io) (str " · " (first io) " in · " (second io) " out")))}})))))
96
+ (catch :default e (rej e))))))))
97
+
98
+ (comp/define! "component"
99
+ {:doc "Defines a box class inside the work: its source is a map {:class :doc :io :receive …} with the same contract as any component."
100
+ :usage "component"
101
+ :display :code :language "component" :model code/model :template template
102
+ :io [0 0]})
103
+
104
+ ;; ───────── the registry follows the work's definitions ─────────
105
+
106
+ (defonce work-classes (atom {})) ; class → [box-id definition]
107
+
108
+ (defn box-num [k] (let [m (re-matches #"b(\d+)" (name k))] (if m (js/parseInt (second m) 10) 1e9)))
109
+
110
+ (defn sync!
111
+ "Registers the classes defined by the patch's component boxes (the lowest-numbered one wins if two
112
+ define the same) and removes those no longer there. Returns true if the registry changed."
113
+ [patch]
114
+ (let [defs (for [[id b] (sort-by (fn [[k _]] (box-num k)) (:boxes patch))
115
+ :when (= "component" (comp/klass (:text b)))
116
+ :let [r (code/compiled "component" (get-in b [:data :source]))]
117
+ :when (= :ok (:status r))
118
+ m (definitions (:value r))]
119
+ [(:class m) [id m]])
120
+ fresh (reduce (fn [acc [c v]] (if (contains? acc c) acc (assoc acc c v))) {} defs)
121
+ before @work-classes]
122
+ (when (not= fresh before)
123
+ (doseq [[c _] before :when (not (contains? fresh c))]
124
+ (when (= :work (:origin (comp/lookup c))) (swap! comp/registry dissoc c)))
125
+ (doseq [[c [id m]] fresh :when (not= (get before c) [id m])]
126
+ (when-not (= :core (:origin (comp/lookup c)))
127
+ (comp/define! c (merge (dissoc m :class) {:origin :work :from id}))))
128
+ (reset! work-classes fresh)
129
+ true)))
130
+
131
+ ;; ───────── import ─────────
132
+
133
+ (defn url-of
134
+ "npm:package@version/path → jsDelivr; a relative path is a file of this page."
135
+ [s]
136
+ (let [s (str/trim (str s))]
137
+ (cond
138
+ (str/starts-with? s "npm:") (str "https://cdn.jsdelivr.net/npm/" (subs s 4))
139
+ :else s)))
140
+
141
+ (defn header [{cls :class :keys [version author license]} origin]
142
+ (str ";; " cls (when version (str " " version)) (when author (str " · " author))
143
+ (when (seq license) (str " · license " license)) "\n;; imported from " origin "\n"))
144
+
145
+ (defn import-module
146
+ "Promise of the component published at `origin`: {:class :version :author :doc :source}, or of the
147
+ package: {:package :version :api :components [{:class :source …}]}."
148
+ [origin]
149
+ (-> ((.-kairoticImport js/window) (url-of origin))
150
+ (.then (fn [obj]
151
+ (let [m (js->clj obj :keywordize-keys true)]
152
+ (when-not (and (map? m) (or (string? (:source m))
153
+ (and (string? (:package m)) (sequential? (:components m)))))
154
+ (throw (js/Error. "that module does not export a component {class, source, …} nor a package {package, components, …}")))
155
+ m)))))
156
+
157
+ (defn package-source
158
+ "The source of the component box that carries a package: one map with every component's source."
159
+ [{:keys [package version api license components]} origin]
160
+ (str ";; " package " " version (when (seq license) (str " · license " license)) "\n"
161
+ ";; imported from " origin "\n"
162
+ "{:package " (pr-str package) " :version " (pr-str version) (when api (str " :api " api)) "\n"
163
+ " :components\n ["
164
+ (str/join "\n\n " (map (fn [c] (str/trim (:source c))) components))
165
+ "]}\n"))
166
+
167
+ ;; ───────── official packages ─────────
168
+ ;; Where each official package is, and which classes it defines: writing one of these classes in a
169
+ ;; work that does not have it brings the package into the work (pinned to this version). Until a
170
+ ;; version is on npm, the page serves its own copy (:local).
171
+
172
+ (def packages
173
+ {"@kairotic/synth" {:version "0.3.0" :classes #{"adsr~" "synth~" "gendy~"} :local "kairotic/packages/synth.mjs"}
174
+ "@kairotic/spatial" {:version "0.1.1" :classes #{"pan~" "space~"} :local "kairotic/packages/spatial.mjs"}
175
+ "@kairotic/controls" {:version "0.2.3" :classes #{"knob" "keyboard" "scale"} :local "kairotic/packages/controls.mjs"}
176
+ "@kairotic/analysis" {:version "0.7.5" :classes #{"features~" "pitch~" "onset~" "chroma~" "spectrum~" "transcribe" "monitor" "form~" "realize~"}
177
+ :local "kairotic/packages/analysis.mjs"}
178
+ "@kairotic/theory" {:version "0.11.0" :classes #{"pcclock" "fourier" "tonnetz" "comes" "cancrizans" "euclid"} :local "kairotic/packages/theory.mjs"}
179
+ "@kairotic/data" {:version "0.1.4" :classes #{"fetch" "edn"} :local "kairotic/packages/data.mjs"}
180
+ "@kairotic/patterns" {:version "0.2.1" :classes #{"pbind" "pattern" "player" "render"} :local "kairotic/packages/patterns.mjs"}
181
+ "@kairotic/spectral" {:version "0.1.2" :classes #{"shift~"} :local "kairotic/packages/spectral.mjs"}
182
+ "@kairotic/io" {:version "0.2.4" :classes #{"midiin" "midiout" "oscin" "oscout" "motion" "gamepad" "serial" "control"}
183
+ :local "kairotic/packages/io.mjs"}
184
+ "@kairotic/net" {:version "0.1.3" :classes #{"share" "shared" "pulse"} :local "kairotic/packages/net.mjs"}})
185
+
186
+ ;; Official packages that carry modules for the page itself rather than box classes (nothing to bring into
187
+ ;; a work): where their files are, npm first at the pinned version, then the page's own copy.
188
+ (def module-packages
189
+ {"@kairotic/faust-units" {:version "0.1.5" :local "kairotic/packages/faust-units/"}})
190
+
191
+ (defn module-origins
192
+ "Where file `f` of a module package is, in order: npm (pinned version), then the page's own copy."
193
+ [pkg-name f]
194
+ (let [{:keys [version local]} (get module-packages pkg-name)]
195
+ [(str "npm:" pkg-name "@" version "/dist/" f) (str local f)]))
196
+
197
+ (defn package-of
198
+ "The official package that defines class k: [name info], or nil."
199
+ [k]
200
+ (first (filter (fn [[_ p]] (contains? (:classes p) k)) packages)))
201
+
202
+ (defn package-origins
203
+ "Where to look for a package, in order: npm (pinned version), then the page's own copy."
204
+ [pkg-name]
205
+ (let [{:keys [version local]} (get packages pkg-name)]
206
+ (cond-> [(str "npm:" pkg-name "@" version "/dist/index.mjs")] local (conj local))))
207
+
208
+ (defn import-package
209
+ "Promise of [package origin]: the first of its origins that answers."
210
+ [pkg-name]
211
+ (reduce (fn [p origin]
212
+ (.catch p (fn [_] (.then (import-module origin) (fn [m] [m origin])))))
213
+ (js/Promise.reject (js/Error. "no origin"))
214
+ (package-origins pkg-name)))
@@ -0,0 +1,41 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · links that carry a patch (Study 22)
3
+ ;; A link (?code=…, ?src=…) and a patch Claude makes (Study 23) carry the patch as code. That code is
4
+ ;; read as data (EDN: reading evaluates nothing) and only the calls a patch is made of go through, with
5
+ ;; literal arguments, so a link cannot run code in the page. What goes through is written again and
6
+ ;; evaluated by the page as gestures.
7
+
8
+ (ns kairotic.links
9
+ (:require [clojure.string :as str]
10
+ [clojure.edn :as edn]))
11
+
12
+ (def calls
13
+ "The calls a patch is made of."
14
+ '#{box connect present view resize code stroke axis grid-x grid-y tuning tree! presets! sample! inside layer mark project})
15
+
16
+ (defn literal?
17
+ "Plain data all the way down: numbers, strings, keywords, booleans, nil, vectors, maps, sets."
18
+ [x]
19
+ (cond (or (symbol? x) (seq? x)) false
20
+ (map? x) (every? (fn [[k v]] (and (literal? k) (literal? v))) x)
21
+ (coll? x) (every? literal? x)
22
+ :else true))
23
+
24
+ (defn call?
25
+ "Whether a form is a patch call with literal arguments (`inside` holds patch calls)."
26
+ [f]
27
+ (and (seq? f) (contains? calls (first f))
28
+ (if (= 'inside (first f))
29
+ (and (keyword? (second f)) (every? call? (drop 2 f)))
30
+ (every? literal? (rest f)))))
31
+
32
+ (defn read-code
33
+ "The code of a link, read as data and written again with only the calls a patch is made of. Throws if
34
+ anything else is in it."
35
+ [src]
36
+ (let [forms (edn/read-string (str "[" src "\n]"))
37
+ bad (first (remove call? forms))]
38
+ (when bad
39
+ (throw (js/Error. (str "a link can only make a patch; it cannot run "
40
+ (let [t (pr-str bad)] (if (> (count t) 60) (str (subs t 0 60) "…") t))))))
41
+ (str/join "\n" (map pr-str forms))))