@marver-design/marver 0.29.0 → 0.30.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 (76) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +2 -1
  3. package/dist/{anchor-check-DhlpKl2K.mjs → anchor-check-c52IDkiQ.mjs} +1 -1
  4. package/dist/{build-CWbrb2bl.mjs → build-C3mUtjEn.mjs} +5 -4
  5. package/dist/cli.mjs +5 -5
  6. package/dist/{daemon-Sc_z8gT6.mjs → daemon-B0Wi1OQ3.mjs} +5 -3
  7. package/dist/{dev-DWBKQhxf.mjs → dev-5dlxoW28.mjs} +8 -8
  8. package/dist/{perf-Denssrko.mjs → perf-6MOTHxay.mjs} +710 -99
  9. package/dist/perf-BCxAo0IS.mjs +1743 -0
  10. package/dist/{plugin-DqoZB-D6.mjs → plugin-CXRoMA8g.mjs} +898 -539
  11. package/dist/{poster-CrsjqhY4.mjs → poster-CYmCa00B.mjs} +1 -1
  12. package/dist/{publish-bakes-DW-NDgU2.mjs → publish-bakes-C_2ZtHou.mjs} +2 -2
  13. package/dist/{recover-GtJ9UDAB.mjs → recover-XD8iXJOj.mjs} +1 -1
  14. package/dist/{shot-T04Ixrvq.mjs → shot-CRRGgxru.mjs} +3 -3
  15. package/docs/app.md +194 -0
  16. package/docs/performance.md +98 -18
  17. package/package.json +1 -1
  18. package/src/client/frame-host/bridge.js +17 -8
  19. package/src/client/frame-host/inplace.ts +124 -0
  20. package/src/client/frame-host/inspect.d.ts +1 -0
  21. package/src/client/frame-host/inspect.js +13 -4
  22. package/src/client/frame-host/main.tsx +12 -3
  23. package/src/client/frame-host/messages.ts +85 -0
  24. package/src/client/frame-host/signals.d.ts +15 -0
  25. package/src/client/frame-host/signals.js +219 -0
  26. package/src/client/recorder-level.ts +41 -0
  27. package/src/client/shell/App.tsx +158 -88
  28. package/src/client/shell/BoardList.tsx +103 -48
  29. package/src/client/shell/Comments.tsx +66 -42
  30. package/src/client/shell/ContextMenu.tsx +3 -2
  31. package/src/client/shell/JamSurface.tsx +116 -71
  32. package/src/client/shell/LockedApp.tsx +19 -3
  33. package/src/client/shell/Play.tsx +94 -58
  34. package/src/client/shell/StatusPicker.tsx +19 -9
  35. package/src/client/shell/Toolbar.tsx +15 -7
  36. package/src/client/shell/api.ts +18 -4
  37. package/src/client/shell/app-bridge.ts +12 -6
  38. package/src/client/shell/app-perf.ts +31 -1
  39. package/src/client/shell/canvas/Canvas.tsx +17 -6
  40. package/src/client/shell/canvas/FrameNode.tsx +25 -12
  41. package/src/client/shell/canvas/Sticky.tsx +4 -2
  42. package/src/client/shell/canvas/ctl.ts +2 -0
  43. package/src/client/shell/canvas/ready-watch.ts +4 -0
  44. package/src/client/shell/canvas/sleep.ts +2 -0
  45. package/src/client/shell/canvas/updates.ts +13 -6
  46. package/src/client/shell/commands.ts +765 -0
  47. package/src/client/shell/comments-store.ts +42 -27
  48. package/src/client/shell/goto.ts +11 -6
  49. package/src/client/shell/jam-keys.ts +141 -75
  50. package/src/client/shell/jam-lane.tsx +19 -12
  51. package/src/client/shell/jam-panel.tsx +61 -48
  52. package/src/client/shell/jam-session.tsx +41 -37
  53. package/src/client/shell/jam-state.ts +9 -1
  54. package/src/client/shell/jam-surface-parts.tsx +8 -6
  55. package/src/client/shell/jam-ui.tsx +9 -6
  56. package/src/client/shell/jam-voice.ts +4 -2
  57. package/src/client/shell/main.tsx +7 -1
  58. package/src/client/shell/marks-ui.tsx +11 -0
  59. package/src/client/shell/perf.ts +51 -5
  60. package/src/client/shell/recorder-core.ts +4 -1
  61. package/src/client/shell/recorder-hmr.ts +36 -0
  62. package/src/client/shell/recorder-reloads.ts +264 -0
  63. package/src/client/shell/recorder-seams.ts +116 -0
  64. package/src/client/shell/recorder-self.ts +73 -0
  65. package/src/client/shell/recorder-signals-core.ts +139 -0
  66. package/src/client/shell/recorder-signals.ts +485 -0
  67. package/src/client/shell/recorder.ts +115 -41
  68. package/src/client/shell/store.ts +56 -22
  69. package/src/client/shell/whiteout-probes.ts +3 -1
  70. package/src/client/stage/main.tsx +10 -5
  71. package/src/shared/app-api.ts +28 -6
  72. package/src/shared/app-perf.ts +99 -6
  73. package/src/shared/app-report.ts +586 -0
  74. package/src/shared/perf-records.ts +445 -0
  75. package/src/shared/perf-run.ts +6 -2
  76. package/dist/perf-jam-CLkERSHo.mjs +0 -642
@@ -0,0 +1,264 @@
1
+ /**
2
+ * The edit's way to the frames, from the shell (spec 30 R1, R2): the reload Outbox (#16: `shell-boot`, `ready`,
3
+ * `settled`, `invalidated`/`invalidated-nodes`, `inplace`, `watchdog`, each with `page` and `seq`, batched to
4
+ * `POST perf/reload` under #7), the navigation tokens frozen at `startReload` (#14), the in-place reports
5
+ * (`sh:inplace`, #15), the board writes' `x-mv-page`/`x-mv-cmds` headers (#18, `perfSeams.requestHeaders`) and the
6
+ * watchdog's lines (#20). Owner: the edits stream.
7
+ *
8
+ * recorder.ts calls `startReloads()` once, at the full level only, after the page recorder is on. Until then every hook
9
+ * here does nothing, and a reload line goes as 0.29's did (store.ts `reloadHooks`). It subscribes through
10
+ * recorder-seams.ts and never imports recorder.ts.
11
+ */
12
+ import { encodeCmds, RELOAD_BOUNDS, RELOAD_OUTBOX, WRITER_HEADERS, type HeldBy } from '../../shared/perf-records.ts'
13
+ import { WATCH_MAX_MS } from '../../shared/app-api.ts'
14
+ import { SH } from '../frame-host/messages.ts'
15
+ import { api, isStopped, resumed } from './api.ts'
16
+ import { watchWindow } from './app-perf.ts'
17
+ import { bootOf, iframeOf } from './canvas/frame-registry.ts'
18
+ import { isAsleep } from './canvas/sleep.ts'
19
+ import { heldBy } from './canvas/updates.ts'
20
+ import { cmdsForWrite } from './commands.ts'
21
+ import { PERF_RUN } from './perf-run.ts'
22
+ import { bound, fitWithin, Outbox, type PerfRecord } from './recorder-core.ts'
23
+ import { PAGE_ID, perfSeams } from './recorder-seams.ts'
24
+ import { logReload, reloadHooks, reloadLine, useStore } from './store.ts'
25
+
26
+ let on = false
27
+ const nodeOf = (key: string) => useStore.getState().nodes.find((n) => n.key === key)
28
+ /** Never in the way (#5), and nothing until started. */
29
+ const guard = <A extends unknown[]>(fn: (...a: A) => void) => (...a: A): void => { if (!on) return; try { fn(...a) } catch { /* never in the way */ } }
30
+ const chunk = <T>(list: readonly T[], n: number): T[][] => Array.from({ length: Math.ceil(list.length / n) }, (_, i) => list.slice(i * n, (i + 1) * n))
31
+
32
+ // ---- #14: attribution frozen per navigation ---------------------------------------------------------------------
33
+
34
+ /** A node's revisions waiting for a navigation: all of them go with the next one (coalesced). `asleep`: as the first of
35
+ * them arrived - going stale wakes a node (FrameNode's sleep effect), so by its `startReload` it is always awake. */
36
+ interface Pending { revisions: string[]; arrivedAt: number; asleep: boolean; heldBy?: HeldBy }
37
+ /** One navigation of a node, frozen as it starts: what arrives after this belongs to the next. */
38
+ interface NavToken extends Pending { nav: number; startedAt: number; release: () => void }
39
+
40
+ const pending = new Map<string, Pending>()
41
+ const tokens = new Map<string, NavToken>()
42
+ /** each live document's id -> the node's navigation when it booted: a document is told by itself, not by the node's nav
43
+ * now (a job may have moved it on, its document not there yet) */
44
+ const docNav = new Map<string, number>()
45
+
46
+ // #38: `reload`, an on-screen job's `startReload` to its ready. One window however many jobs run; a job that never comes
47
+ // to its ready (the watchdog gave up, the node left) lets go at the app's own end for a window.
48
+ let watching = 0
49
+ function holdWatch(): () => void {
50
+ if (watching++ === 0) watchWindow('reload', true)
51
+ let held = true
52
+ const t = setTimeout(() => release(), WATCH_MAX_MS)
53
+ const release = () => {
54
+ if (!held) return
55
+ held = false
56
+ clearTimeout(t)
57
+ if (--watching === 0) watchWindow('reload', false)
58
+ }
59
+ return release
60
+ }
61
+
62
+ /** #13: counted over the board's nodes - one frame may have several, or none. */
63
+ function invalidated(frames: ReadonlySet<string>, revision: string): void {
64
+ const s = useStore.getState()
65
+ const nodes = s.nodes.filter((n) => frames.has(n.frame))
66
+ const now = performance.now()
67
+ const held: Partial<Record<HeldBy, number>> = {}
68
+ let asleep = 0, awake = 0
69
+ for (const n of nodes) {
70
+ const why = heldBy(n, s)
71
+ if (why) held[why] = (held[why] ?? 0) + 1
72
+ if (isAsleep(n.key)) asleep++
73
+ else if (!n.missing) awake++
74
+ if (n.missing) continue // it never goes stale: no navigation will carry this for it
75
+ const p = pending.get(n.key)
76
+ if (!p) pending.set(n.key, { revisions: [revision], arrivedAt: now, asleep: isAsleep(n.key) })
77
+ else if (!p.revisions.includes(revision)) {
78
+ p.revisions.push(revision)
79
+ if (p.revisions.length > RELOAD_BOUNDS.idsPerLine) p.revisions.shift()
80
+ }
81
+ }
82
+ const shown = new Set(nodes.map((n) => n.frame))
83
+ const parts = chunk(nodes.map((n) => n.key), RELOAD_BOUNDS.idsPerLine)
84
+ logReload({ kind: 'invalidated', revision, asked: frames.size, offBoard: [...frames].filter((f) => !shown.has(f)).length, onBoard: nodes.length, awake, asleep, held, ...(parts.length ? { parts: parts.length } : {}) })
85
+ parts.forEach((p, i) => logReload({ kind: 'invalidated-nodes', revision, part: i + 1, parts: parts.length, nodes: p }))
86
+ // a node gone from the board keeps nothing here: no ready will come for it
87
+ const keys = new Set(s.nodes.map((n) => n.key))
88
+ for (const k of pending.keys()) if (!keys.has(k)) pending.delete(k)
89
+ for (const [k, t] of tokens) if (!keys.has(k)) { t.release(); tokens.delete(k) }
90
+ }
91
+
92
+ /** The first reason the queue refused a node, for the navigation that will carry its revisions. */
93
+ function held(key: string, why: HeldBy): void {
94
+ const p = pending.get(key)
95
+ if (p) p.heldBy ??= why
96
+ }
97
+
98
+ /** `startReload`: this navigation's token. A revision arriving from here on is the next navigation's. */
99
+ function started(key: string, nav: number): void {
100
+ const p = pending.get(key)
101
+ pending.delete(key)
102
+ tokens.get(key)?.release()
103
+ tokens.set(key, { revisions: p?.revisions ?? [], arrivedAt: p?.arrivedAt ?? performance.now(), asleep: p?.asleep ?? isAsleep(key), heldBy: p?.heldBy, nav, startedAt: performance.now(), release: holdWatch() })
104
+ }
105
+
106
+ /**
107
+ * sh:ready, from the live document (App.tsx's `fromLiveDocument`), before `setStatus` pumps the next job and `setShown`
108
+ * moves its wait: the token of the navigation this document belongs to, as the `ready` line's fields. A document with no
109
+ * token - a first load, a reload by hand, a self reload - has none.
110
+ */
111
+ export function takeNavToken(key: string, data: { boot?: unknown }): Record<string, unknown> | undefined {
112
+ if (!on) return undefined
113
+ try {
114
+ const n = nodeOf(key)
115
+ if (!n) return undefined
116
+ const boot = typeof data.boot === 'string' ? data.boot : ''
117
+ const nav = docNav.get(boot) ?? n.nav ?? 0
118
+ docNav.delete(boot)
119
+ // what setShown decides next: a document that already shows a revision that waited needs no navigation for it
120
+ queueMicrotask(() => { if (!nodeOf(key)?.stale) pending.delete(key) })
121
+ const t = tokens.get(key)
122
+ if (!t || t.nav !== nav) return undefined
123
+ tokens.delete(key)
124
+ t.release()
125
+ return { revisions: t.revisions, queuedMs: Math.round(t.startedAt - t.arrivedAt), bootMs: Math.round(performance.now() - t.startedAt), ...(t.heldBy ? { heldBy: t.heldBy } : {}), ...(t.asleep ? { asleep: true } : {}) }
126
+ } catch { return undefined }
127
+ }
128
+
129
+ // ---- messages from the documents --------------------------------------------------------------------------------
130
+
131
+ function onFrameMessage(key: string, data: Record<string, unknown>): void {
132
+ if (data.type === 'sh:boot' && typeof data.boot === 'string') {
133
+ const n = nodeOf(key)
134
+ if (!n) return
135
+ docNav.set(data.boot, n.nav ?? 0)
136
+ if (docNav.size > 1_024) docNav.delete(docNav.keys().next().value!)
137
+ } else if (data.type === SH.inplace) {
138
+ // #15: from the document there now; what it saw, no more
139
+ if (typeof data.boot !== 'string' || data.boot !== bootOf(iframeOf(key))) return
140
+ const n = nodeOf(key)
141
+ if (!n) return
142
+ logReload({ kind: 'inplace', node: key, frame: n.frame, hmrTs: data.hmrTs, fetched: true, applyMs: data.applyMs, nextObservedCommitMs: data.nextObservedCommitMs, applied: data.applied === false ? false : 'unknown', ...(data.noAfterUpdate === true ? { noAfterUpdate: true } : {}) })
143
+ }
144
+ }
145
+
146
+ /** #20: the watchdog's silence, before it acts. */
147
+ export const watchdogLine = guard((key: string, action: 'retry' | 'gave-up') => {
148
+ const n = nodeOf(key)
149
+ if (n) logReload({ kind: 'watchdog', node: key, frame: n.frame, nav: n.nav ?? 0, action })
150
+ })
151
+
152
+ // ---- #18: a board write names its page and its commands ----------------------------------------------------------
153
+
154
+ const BOARD_WRITE = /\/api\/(boards\/[^?#]+)/
155
+ const NOT_A_BOARD = new Set(['pin', 'status', 'rename', 'reorder'])
156
+ function writeHeaders(url: string, init: RequestInit): Record<string, string> | undefined {
157
+ if (!init.method || init.method === 'GET') return undefined
158
+ const route = BOARD_WRITE.exec(url)?.[1]
159
+ if (!route) return undefined
160
+ // the board, when the path names it - a body is never read (#4)
161
+ const name = route.slice('boards/'.length)
162
+ return { [WRITER_HEADERS.page]: PAGE_ID, [WRITER_HEADERS.cmds]: encodeCmds(cmdsForWrite(NOT_A_BOARD.has(name) ? '' : decodeURIComponent(name), route)) }
163
+ }
164
+
165
+ // ---- #16, #7: the reload Outbox ----------------------------------------------------------------------------------
166
+
167
+ const outbox = new Outbox(RELOAD_OUTBOX.max, RELOAD_OUTBOX.bytes)
168
+ let inFlight: PerfRecord[] = []
169
+ let sendTimer: ReturnType<typeof setTimeout> | undefined
170
+ let sending = false
171
+
172
+ const csrf = () => /(?:^|;\s*)mv_c=([\w-]+)/.exec(document.cookie)?.[1] ?? ''
173
+ const post = (records: PerfRecord[], keepalive = false) => api('perf/reload', {
174
+ method: 'POST',
175
+ headers: { 'content-type': 'application/json', 'x-mv-c': csrf() },
176
+ body: JSON.stringify({ records }),
177
+ ...(keepalive ? { keepalive: true } : {}),
178
+ })
179
+ const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))
180
+ const armSend = () => { if (!sending && sendTimer === undefined && outbox.size) sendTimer = setTimeout(() => { sendTimer = undefined; void send() }, RELOAD_OUTBOX.sendMs) }
181
+ /** The `dropped` line that says how many went, when any did (the count starts over): R13's, a line like the others. */
182
+ const droppedNow = (more = 0): PerfRecord[] => {
183
+ const n = outbox.dropped + more
184
+ outbox.dropped = 0
185
+ return n ? [reloadLine({ kind: 'dropped', n }) as PerfRecord] : []
186
+ }
187
+
188
+ /** As the page recorder's `send` (recorder.ts), under #7: a network failure or a server error is tried twice more, 2 s
189
+ * apart - the server answers only after its append returned, 503 when it failed; a 403 primes the request cookie once;
190
+ * any other refusal is final. What never lands is counted. */
191
+ async function send(): Promise<void> {
192
+ clearTimeout(sendTimer)
193
+ sendTimer = undefined
194
+ if (!on || sending || !outbox.size) return
195
+ // a headless run's documents are not this log's (its barrier refuses the route)
196
+ if (PERF_RUN) { outbox.takeAll(); outbox.dropped = 0; return }
197
+ sending = true
198
+ let batch: PerfRecord[] = []
199
+ let ok = false
200
+ try {
201
+ batch = [...droppedNow(), ...outbox.takeAll()]
202
+ inFlight = batch
203
+ for (let attempt = 0; attempt < 3 && !ok; attempt++) {
204
+ if (attempt) await wait(RELOAD_OUTBOX.sendMs)
205
+ try {
206
+ let r = await post(batch)
207
+ if (r.status === 403) { await api('work').catch(() => {}); r = await post(batch) }
208
+ if (r.ok) ok = true
209
+ else if (r.status < 500 || isStopped(r)) break
210
+ } catch { /* the network: again */ }
211
+ }
212
+ } catch { /* never in the way: what it held is counted below */ }
213
+ if (!ok) outbox.dropped += batch.reduce((n, r) => n + (r.kind === 'dropped' ? (r.n as number) : 1), 0)
214
+ inFlight = []
215
+ sending = false
216
+ armSend()
217
+ }
218
+
219
+ /** The page is going (recorder.ts, after its own last records, only when no capture holds the allowance): this log's
220
+ * share of the keepalive, what does not fit counted in the last line that does. */
221
+ function leave(): void {
222
+ clearTimeout(sendTimer)
223
+ sendTimer = undefined
224
+ if (PERF_RUN) return
225
+ const all = [...inFlight, ...outbox.takeAll()]
226
+ if (!all.length && !outbox.dropped) return
227
+ const { fit, lost } = fitWithin([], all, RELOAD_OUTBOX.keepaliveBytes)
228
+ try { void post([...fit, ...droppedNow(lost)], true).catch(() => {}) } catch { /* going anyway */ }
229
+ }
230
+
231
+ /** The page that left this tab for good, in the tab's own storage until the next page there names it (#48). A page writes
232
+ * it only as it ends: a duplicated tab copies this storage from a live page, which has written nothing, so a copy can
233
+ * never say its original ended. A crash writes nothing either: the app's `gone`, or nothing at all. */
234
+ const LEFT_TAB = 'mv-page-left'
235
+ /** A line, as `logReload` built it. `shell-boot` adds what only the page knows (#16). */
236
+ function take(line: Record<string, unknown>): void {
237
+ if (line.kind === 'shell-boot') {
238
+ const nav = (performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined)?.type
239
+ if (nav) line.nav = bound(nav, 16)
240
+ if (resumed) line.resumed = true
241
+ try {
242
+ const prev = sessionStorage.getItem(LEFT_TAB)
243
+ if (prev) { line.prev = prev; sessionStorage.removeItem(LEFT_TAB) }
244
+ } catch { /* storage off: no evidence, and the reader says so */ }
245
+ }
246
+ outbox.push(line as PerfRecord)
247
+ armSend()
248
+ }
249
+
250
+ /** recorder.ts `startRecorder`, at the full level: the reload Outbox and its listeners. */
251
+ export function startReloads(): void {
252
+ if (on) return
253
+ on = true
254
+ reloadHooks.line = guard(take)
255
+ reloadHooks.invalidated = guard(invalidated)
256
+ reloadHooks.started = guard(started)
257
+ reloadHooks.held = guard(held)
258
+ perfSeams.requestHeaders = (url, init) => { try { return writeHeaders(url, init) } catch { return undefined } }
259
+ // kept for back and forward (`persisted`), this page may yet come back: it has not ended
260
+ addEventListener('pagehide', (e) => { if (!e.persisted) { try { sessionStorage.setItem(LEFT_TAB, PAGE_ID) } catch { /* storage off */ } } })
261
+ perfSeams.frameMessage.on(guard(onFrameMessage))
262
+ perfSeams.leaving.on(guard(leave))
263
+ document.addEventListener('visibilitychange', guard(() => { if (document.visibilityState === 'hidden') void send() }))
264
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The page recorder's seams (spec 30): what the shared shell files call and the spec 30 streams fill, so each stream's
3
+ * work stays in its own module. Dependency-free (recorder-core.ts and types only): store.ts, api.ts, App.tsx, Play.tsx
4
+ * and every stream module import it without a cycle - recorder.ts imports store.ts, so a stream module that store.ts
5
+ * or api.ts reaches must never import recorder.ts at its top level for a value it reads at load.
6
+ *
7
+ * Two shapes, as store.ts's `recorderHooks`: a settable function where one owner answers (a header, a transition id),
8
+ * and a tap (listeners, each run in a try, never in the way) where several streams listen to one point. Every tap is
9
+ * silent until a stream subscribes, and the streams subscribe only from their starters (recorder.ts `startRecorder`,
10
+ * never under the `core` level), so a published canvas, a `core` run and a page without the recorder pay one call.
11
+ *
12
+ * FROZEN before the spec 30 streams split. Who fills what (.r30-contracts.md has the whole map):
13
+ * - `record`, `load`, `leaving`: recorder.ts (the page recorder writes through `record`; its loads' phases and its
14
+ * `pagehide` are told to whoever listens - commands' `board-open`, app-store's `watch load`, edits' reload Outbox);
15
+ * - `requestHeaders`: edits (#18: a board write's `x-mv-page` and `x-mv-cmds`, from commands.ts `cmdsForWrite`);
16
+ * - `answered`: signals (#31: `api` errors), commands (#49: a write's or a call's answer ends its commands);
17
+ * - `frameMessage`, `stageMessage`: signals (acks with `t`, `sh:mode-applied`, `sh:dropped`, `sh:renders`,
18
+ * `sh:console`, `sh:resource-error`), edits (`sh:inplace`), commands (`sh:stage-shown` ends play commands);
19
+ * - `transition`: signals (#21: the `t` FrameNode and Play send with `sh:set-theme`, `sh:laser` and `sh:pick`);
20
+ * - `selfCost`: app-store (#58: `self` records' `hookMs`), charged by every stream through `hooked()`.
21
+ */
22
+ import { newId } from './recorder-core.ts'
23
+ import { busyWait, SLOW_HOOK, SLOW_HOOK_MS } from '../recorder-level.ts'
24
+ import type { LoadTrigger, PageKind, SelfHook } from '../../shared/perf-records.ts'
25
+ import type { LoadCause } from './store.ts'
26
+
27
+ /** This document, in every record (and, in the app, in its hello: the app's records about this tab carry it). */
28
+ export const PAGE_ID = newId()
29
+
30
+ let seq = 0
31
+ /** The page's one record order (spec 30 #7, #16): page records and reload lines share it, so `(page, seq)` names one
32
+ * record of this page whichever file it lands in. */
33
+ export const nextSeq = (): number => seq++
34
+
35
+ type Listener<A extends unknown[]> = (...a: A) => void
36
+ /** Listeners at one point: each runs in a try - a stream's hook never stands in the way, nor stops another's (#5). */
37
+ export interface Tap<A extends unknown[]> {
38
+ on(fn: Listener<A>): () => void
39
+ emit(...a: A): void
40
+ readonly size: number
41
+ }
42
+ export function tap<A extends unknown[]>(): Tap<A> {
43
+ const fns = new Set<Listener<A>>()
44
+ return {
45
+ on(fn) { fns.add(fn); return () => { fns.delete(fn) } },
46
+ emit(...a) { if (fns.size) for (const fn of [...fns]) { try { fn(...a) } catch { /* never in the way */ } } },
47
+ get size() { return fns.size },
48
+ }
49
+ }
50
+
51
+ /** A request mvFetch sent and how it ended: `status` the HTTP status, 0 the network, `timeout` its abort signal's
52
+ * timeout. `headers` as sent (the board write's `x-mv-cmds` among them). Never a body. */
53
+ export interface Answered { url: string; init: RequestInit; headers: Record<string, string> | undefined; status: number | 'timeout'; ms: number }
54
+
55
+ /** Why a load or a request ended unsettled (the server's `CUT_REASONS`). */
56
+ export type CutReason = 'switch' | 'reload' | 'hidden' | 'timeout' | 'superseded' | 'error' | 'edited' | 'unsaved'
57
+ /**
58
+ * A load's way, as the page recorder sees it (its records carry the same ids). `request`: asked for (#38's `load`
59
+ * window opens here); `visible`: the cohort chosen (`assumed` when no fit landed); `commit` (`late`: a request already
60
+ * cut mounted all the same); `settled`; `cut` (`request`: before it committed). `visible-ready` - the cohort's frames
61
+ * all ready (#49's step) - is the commands stream's to emit, from progress() (recorder.ts).
62
+ */
63
+ export type LoadPhase =
64
+ | { phase: 'request'; load: string; board: string; cause: LoadCause; trigger?: LoadTrigger }
65
+ | { phase: 'visible'; load: string; nodes: number; assumed?: true }
66
+ | { phase: 'visible-ready'; load: string }
67
+ | { phase: 'commit'; load: string; late?: true }
68
+ | { phase: 'settled'; load: string }
69
+ | { phase: 'cut'; load: string; reason: CutReason; request?: true }
70
+
71
+ /** The transitions whose id a message to a document carries (#21, #26). */
72
+ export type TransitionKind = 'theme' | 'mode'
73
+
74
+ export const perfSeams = {
75
+ /** recorder.ts sets it: true while the page records (dev, not published, a workspace) */
76
+ on: false,
77
+ /** recorder.ts sets it: a record of `kind` into page.jsonl, through the page's envelope (`page`, `seq`, `ts`) and
78
+ * outbox; `load` the load that owns the geometry unless given. Nothing while the page does not record */
79
+ record: (_kind: PageKind, _body: Record<string, unknown>, _load?: string): void => {},
80
+ /** recorder.ts: each load's phases */
81
+ load: tap<[p: LoadPhase]>(),
82
+ /** recorder.ts, at `pagehide`, after the page's own last records went (#7's order: Jam's captures, page records
83
+ * 16 KB, then reload lines 8 KB) - never while a capture holds the keepalive allowance */
84
+ leaving: tap<[]>(),
85
+ /** mvFetch (api.ts), before it sends a request this page's canvas will answer: headers to add, or undefined */
86
+ requestHeaders: (_url: string, _init: RequestInit): Record<string, string> | undefined => undefined,
87
+ /** mvFetch (api.ts): every request that got an answer or failed - `perf/*` included; a listener skips what it must */
88
+ answered: tap<[a: Answered]>(),
89
+ /** App.tsx: every `sh:*` message from a registered frame, before the shell handles it (a listener checks the
90
+ * document itself - `fromLiveDocument` - and never consumes the message) */
91
+ frameMessage: tap<[node: string, data: Record<string, unknown>]>(),
92
+ /** Play.tsx: every message from the play stage's live iframe, before the shell handles it */
93
+ stageMessage: tap<[data: Record<string, unknown>]>(),
94
+ /** FrameNode.tsx and Play.tsx, as they post a theme or a mode to a document: the transition it belongs to, or none */
95
+ transition: (_kind: TransitionKind): string | undefined => undefined,
96
+ /** app-store (#58): a hook's own time, by hook - `hooked()` charges it */
97
+ selfCost: (_hook: SelfHook, _ms: number): void => {},
98
+ }
99
+
100
+ let hookDepth = 0
101
+ /** Is a measured hook running? (`self` counts a record written inside one as that hook's.) */
102
+ export const insideHook = (): boolean => hookDepth > 0
103
+
104
+ /** A stream's hook, as recorder.ts's `guard`: nothing while the page does not record, never in the way - and its time
105
+ * charged to `hook` in `self` (#58) when it is one of the measured hooks. `?mvslowhook=<hook>` adds the cost run's
106
+ * injected wait here (recorder-level.ts, test only). */
107
+ export function hooked<A extends unknown[]>(hook: SelfHook | null, fn: (...a: A) => void): (...a: A) => void {
108
+ return (...a) => {
109
+ if (!perfSeams.on) return
110
+ const t0 = hook ? performance.now() : 0
111
+ if (hook) hookDepth++
112
+ if (hook && hook === SLOW_HOOK) busyWait(SLOW_HOOK_MS)
113
+ try { fn(...a) } catch { /* never in the way */ }
114
+ if (hook) { hookDepth--; try { perfSeams.selfCost(hook, performance.now() - t0) } catch { /* the same */ } }
115
+ }
116
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The recorder's own cost (spec 30 R15 #58): every 5 minutes in which it recorded anything, a `self` record - `cpuMs`,
3
+ * `hookMs` by hook (charged through recorder-seams.ts `hooked()`, which calls `perfSeams.selfCost`), `records`,
4
+ * `bytes`, `dropped`. Also the page's `load` white-out window (R8 #38): from a load's request to its settled or cut,
5
+ * asked of the Mac app through app-perf.ts `watchWindow`. Owner: the app-store stream.
6
+ *
7
+ * recorder.ts calls `startSelf()` once, at the full level only, after the page recorder is on; under `core` nothing here
8
+ * runs and `selfCounts.on` stays false. `cpuMs` is what the recorder's code took on this thread as far as it can tell:
9
+ * the measured hooks and `rec()` outside them. `performance.now()` is coarse in a page (100 µs), so a figure is a sum
10
+ * of coarse readings, right on average and never to the microsecond.
11
+ */
12
+ import { SELF_MS, type SelfBody, type SelfHook } from '../../shared/perf-records.ts'
13
+ import { SLOW_HOOK, SLOW_HOOK_MS, busyWait } from '../recorder-level.ts'
14
+ import { watchWindow } from './app-perf.ts'
15
+ import { insideHook, perfSeams, type LoadPhase } from './recorder-seams.ts'
16
+
17
+ /** What recorder.ts's `rec()` and `send()` add to, read here; `on` keeps them silent under `core`. */
18
+ export const selfCounts = {
19
+ on: false,
20
+ records: 0,
21
+ bytes: 0,
22
+ dropped: 0,
23
+ /** `rec()` outside any hook (a hook's own time holds the records it writes) */
24
+ recMs: 0,
25
+ /** recorder.ts `rec()`, as it returns */
26
+ record(ms: number): void { this.records++; if (!insideHook()) this.recMs += ms },
27
+ }
28
+ let hookMs: Partial<Record<SelfHook, number>> = {}
29
+
30
+ const tenth = (n: number) => Math.round(n * 10) / 10
31
+
32
+ /** The period's record, when it recorded anything; the counts start over either way. */
33
+ export function writeSelf(): void {
34
+ if (selfCounts.records > 0) {
35
+ const hooks = Object.entries(hookMs).reduce((n, [, v]) => n + (v ?? 0), 0)
36
+ const body: SelfBody = {
37
+ cpuMs: tenth(hooks + selfCounts.recMs),
38
+ hookMs: Object.fromEntries(Object.entries(hookMs).map(([k, v]) => [k, tenth(v ?? 0)])),
39
+ records: selfCounts.records,
40
+ bytes: selfCounts.bytes,
41
+ dropped: selfCounts.dropped,
42
+ }
43
+ perfSeams.record('self', body as unknown as Record<string, unknown>)
44
+ }
45
+ selfCounts.records = 0
46
+ selfCounts.bytes = 0
47
+ selfCounts.dropped = 0
48
+ selfCounts.recMs = 0
49
+ hookMs = {}
50
+ }
51
+
52
+ /** #38: one window per load, open from its request until it settled or was cut. */
53
+ function loadWindows(): void {
54
+ const open = new Set<string>()
55
+ perfSeams.load.on((p: LoadPhase) => {
56
+ if (p.phase === 'request') { open.add(p.load); watchWindow('load', true); return }
57
+ if ((p.phase === 'settled' || p.phase === 'cut') && open.delete(p.load)) watchWindow('load', false)
58
+ })
59
+ }
60
+
61
+ /** recorder.ts `startRecorder`, at the full level. */
62
+ export function startSelf(): void {
63
+ selfCounts.on = true
64
+ perfSeams.selfCost = (hook, ms) => { hookMs[hook] = (hookMs[hook] ?? 0) + ms }
65
+ loadWindows()
66
+ setInterval(writeSelf, SELF_MS)
67
+ // #58's test-only switch (`?mvslowhook=console`): the console's way through this page costs 5 ms more, so the cost
68
+ // run must fail. `hooked('console', ...)` waits too (recorder-seams.ts); this holds for any console.error of the shell.
69
+ if (SLOW_HOOK === 'console') {
70
+ const was = console.error
71
+ console.error = (...a: unknown[]) => { busyWait(SLOW_HOOK_MS); was.apply(console, a) }
72
+ }
73
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The pure parts of the page's signals (spec 30 R5, R6), kept apart from the browser-coupled module so they can be
3
+ * unit-tested (recorder-core.ts's precedent): a request's route without its names, a gesture's three longest Long
4
+ * Animation Frames and what they ran, a minute's heaviest re-render rows and warning nodes, a source's rate, the
5
+ * nodes a view shows. No imports but types and constants.
6
+ */
7
+ import { LOAF, RENDERS, WARNINGS, type Loaf, type RenderRow } from '../../shared/perf-records.ts'
8
+
9
+ // ---- #31: a request's route -----------------------------------------------------------------------------------------
10
+
11
+ /** The routes the dev server answers whose every segment is a fixed word: said as they are. */
12
+ const FIXED = new Set([
13
+ 'policy', 'boards', 'boards/status', 'boards/pin', 'boards/rename', 'boards/reorder', 'boards.rights', 'scenes/rename',
14
+ 'sizes', 'folders', 'membership', 'shot', 'shots', 'anchor', 'bakes', 'poster', 'me', 'profile', 'marks', 'marks/seen',
15
+ 'work', 'seen', 'update', 'sync', 'request-access', 'invite-info', 'auth/signin', 'auth/claim', 'hello',
16
+ 'jam/queue', 'jam/card', 'jam/audio-ticket', 'jam/voice', 'jam/session', 'jam/run', 'jam/prefs', 'jam/capture-open',
17
+ 'jam/record', 'jam/capture', 'jam/picture', 'jam/picture/live',
18
+ ])
19
+ /** Everything after the first segment that is not a fixed word is a name or an id. */
20
+ const WORD = /^[a-z][a-z-]*$/
21
+ /**
22
+ * #31: a request's route, ids and names replaced (`boards/:board`), never a query. Under the API: its path after
23
+ * `/api/`, a known route as it is, `boards/<x>` and `comments/<x>` by what `<x>` is, anything else its first word and
24
+ * `:id` for the rest. Elsewhere: the first segment, the rest `:path` - `design/manifest.json` is the one fixed name.
25
+ */
26
+ export function normRoute(url: string): string {
27
+ const path = url.replace(/^[a-z]+:\/\/[^/]+/i, '').split(/[?#]/)[0]
28
+ const api = /(?:^|\/)api\/(.*)$/.exec(path)
29
+ if (api) {
30
+ const rel = api[1].replace(/\/+$/, '')
31
+ if (FIXED.has(rel)) return rel
32
+ const segs = rel.split('/')
33
+ if (segs[0] === 'boards' && segs.length === 2) return 'boards/:board'
34
+ if (segs[0] === 'comments' && segs.length === 2) return 'comments/:board'
35
+ return segs.map((s, i) => (i === 0 && WORD.test(s) ? s : ':id')).join('/')
36
+ }
37
+ const rel = path.replace(/^\/+/, '')
38
+ if (rel === 'design/manifest.json') return rel
39
+ const segs = rel.split('/').filter(Boolean)
40
+ return segs.length ? `${WORD.test(segs[0]) ? segs[0] : ':path'}${segs.length > 1 ? '/:path' : ''}` : '/'
41
+ }
42
+
43
+ // ---- #35: a gesture's Long Animation Frames ----------------------------------------------------------------------
44
+
45
+ /** What this module reads of a `PerformanceScriptTiming`. */
46
+ export interface LoafScript { duration: number; sourceURL?: string; sourceFunctionName?: string; invoker?: string; windowAttribution?: string; window?: unknown }
47
+ /** What this module reads of a `long-animation-frame` entry; a `longtask` entry (Safari, Firefox) has `duration` alone. */
48
+ export interface LoafEntry { startTime?: number; duration: number; blockingDuration?: number; scripts?: readonly LoafScript[] }
49
+
50
+ /** A URL's path, no query, no host; '' when it is not one. */
51
+ export function urlPath(raw: string | undefined): string {
52
+ if (!raw) return ''
53
+ try { return new URL(raw, 'http://x').pathname } catch { return '' }
54
+ }
55
+ /** Keep the `kept` longest as they arrive (a heavy gesture has many, and an entry holds its scripts' windows). */
56
+ export function keepLongest(top: LoafEntry[], e: LoafEntry, kept: number = LOAF.kept): void {
57
+ top.push(e)
58
+ top.sort((a, b) => b.duration - a.duration)
59
+ if (top.length > kept) top.length = kept
60
+ }
61
+ /**
62
+ * #35: the longest frames, longest first: `ms`, `blockMs`, and the longest script's `src` (a URL path, no query),
63
+ * `frame` (what `frameOf` makes of its path and its window: a frame's module path names the frame), `fn` (64
64
+ * characters), `invoker` (no query, 64 characters), `ms` and `where` (`windowAttribution`). A `longtask` entry: `ms` alone.
65
+ */
66
+ export function pickLoafs(entries: readonly LoafEntry[], frameOf: (src: string, win: unknown) => string | undefined, kept: number = LOAF.kept): Loaf[] {
67
+ return [...entries].sort((a, b) => b.duration - a.duration).slice(0, kept).map((e) => {
68
+ const out: Loaf = { ms: Math.round(e.duration) }
69
+ if (typeof e.blockingDuration === 'number') out.blockMs = Math.round(e.blockingDuration)
70
+ const s = e.scripts?.length ? e.scripts.reduce((a, b) => (b.duration > a.duration ? b : a)) : undefined
71
+ if (s) {
72
+ const src = urlPath(s.sourceURL)
73
+ const frame = frameOf(src, s.window)
74
+ out.script = {
75
+ ms: Math.round(s.duration),
76
+ ...(src ? { src } : {}),
77
+ ...(frame ? { frame } : {}),
78
+ ...(s.sourceFunctionName ? { fn: s.sourceFunctionName.slice(0, LOAF.fn) } : {}),
79
+ ...(s.invoker ? { invoker: s.invoker.replace(/[?#].*$/, '').slice(0, LOAF.fn) } : {}),
80
+ ...(s.windowAttribution ? { where: s.windowAttribution } : {}),
81
+ }
82
+ }
83
+ return out
84
+ })
85
+ }
86
+
87
+ // ---- #36, #28: a minute's rows -------------------------------------------------------------------------------------
88
+
89
+ /** One minute's accumulating row (`who`, `frame`). */
90
+ export function addRow(rows: Map<string, RenderRow>, who: string, frame: string | undefined, r: { commits: number; ms: number; maxMs: number; inGesture: number }): void {
91
+ const cur = rows.get(who)
92
+ if (!cur) { rows.set(who, { who, ...(frame ? { frame } : {}), commits: r.commits, ms: r.ms, maxMs: r.maxMs, inGesture: r.inGesture }); return }
93
+ cur.commits += r.commits; cur.ms += r.ms; cur.inGesture += r.inGesture
94
+ if (r.maxMs > cur.maxMs) cur.maxMs = r.maxMs
95
+ if (frame) cur.frame = frame
96
+ }
97
+ /** #36: the `max` heaviest rows by `ms`, the rest folded into one `others` row that says how many it holds. */
98
+ export function foldRows(rows: Iterable<RenderRow>, max: number = RENDERS.rows): RenderRow[] {
99
+ const tenth = (x: number) => Math.round(x * 10) / 10
100
+ const all = [...rows].sort((a, b) => b.ms - a.ms).map((r) => ({ ...r, ms: tenth(r.ms), maxMs: tenth(r.maxMs) }))
101
+ if (all.length <= max) return all
102
+ const rest = all.slice(max)
103
+ const others: RenderRow = { who: 'others', commits: 0, ms: 0, maxMs: 0, inGesture: 0, rows: rest.length }
104
+ for (const r of rest) { others.commits += r.commits; others.ms += r.ms; others.inGesture += r.inGesture; if (r.maxMs > others.maxMs) others.maxMs = r.maxMs }
105
+ others.ms = tenth(others.ms)
106
+ return [...all.slice(0, max), others]
107
+ }
108
+ /** #28: the minute's total, and the `top` nodes with most. */
109
+ export function topWarnings(by: ReadonlyMap<string, number>, top: number = WARNINGS.top): { n: number; top: { node: string; n: number }[] } {
110
+ let n = 0
111
+ for (const c of by.values()) n += c
112
+ return { n, top: [...by].sort((a, b) => b[1] - a[1]).slice(0, top).map(([node, c]) => ({ node, n: c })) }
113
+ }
114
+
115
+ // ---- rates, percentiles, what a view shows --------------------------------------------------------------------------
116
+
117
+ /** At most `perSecond` in each wall second (the rule the frames' budget keeps). */
118
+ export function createRate(perSecond: number, now: () => number = () => performance.now()): () => boolean {
119
+ let sec = NaN, inSec = 0
120
+ return () => {
121
+ const s = Math.floor(now() / 1000)
122
+ if (s !== sec) { sec = s; inSec = 0 }
123
+ if (inSec >= perSecond) return false
124
+ inSec++
125
+ return true
126
+ }
127
+ }
128
+ /** The nearest-rank median of `xs` (cli/perf.ts `spread`'s rule), undefined with none. */
129
+ export function p50(xs: readonly number[]): number | undefined {
130
+ if (!xs.length) return undefined
131
+ const v = [...xs].sort((a, b) => a - b)
132
+ return v[Math.min(v.length - 1, Math.ceil(0.5 * v.length) - 1)]
133
+ }
134
+ /** A node's title bar is part of its box (FrameNode). */
135
+ const HEADER = 28
136
+ /** recorder.ts `cohortIn`: the nodes a view shows. */
137
+ export function nodesIn<N extends { key: string; x: number; y: number; w: number; h: number }>(nodes: readonly N[], v: { x: number; y: number; w: number; h: number }): N[] {
138
+ return nodes.filter((n) => n.x < v.x + v.w && n.x + n.w > v.x && n.y < v.y + v.h && n.y + n.h + HEADER > v.y)
139
+ }