pi-odd-worktree 3.15.1 → 3.16.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 (126) hide show
  1. package/README.md +48 -25
  2. package/extensions/odd-worktree-tools.ts +64 -211
  3. package/lib/shell-api/api.ts +523 -0
  4. package/lib/shell-api/arm.ts +83 -0
  5. package/lib/shell-api/bus.ts +1389 -0
  6. package/lib/shell-api/capture.ts +1340 -0
  7. package/lib/shell-api/card-style-line.ts +112 -0
  8. package/lib/shell-api/card-style-rows.ts +390 -0
  9. package/lib/shell-api/card-style-transform.ts +862 -0
  10. package/lib/shell-api/card-style-wiring.ts +477 -0
  11. package/lib/shell-api/card-styles.ts +153 -0
  12. package/lib/shell-api/config.ts +71 -0
  13. package/lib/shell-api/extension.ts +247 -0
  14. package/lib/shell-api/hook.ts +322 -0
  15. package/lib/shell-api/index.ts +88 -0
  16. package/lib/shell-api/message-design-adoption.ts +549 -0
  17. package/lib/shell-api/message-design-rows.ts +313 -0
  18. package/lib/shell-api/message-design-wiring.ts +369 -0
  19. package/lib/shell-api/message-designs.ts +746 -0
  20. package/lib/shell-api/notices.ts +137 -0
  21. package/lib/shell-api/plugin-lines.ts +877 -0
  22. package/lib/shell-api/presence.ts +258 -0
  23. package/lib/shell-api/repaint.ts +351 -0
  24. package/lib/shell-api/row-labels.ts +146 -0
  25. package/lib/shell-api/row-names.ts +273 -0
  26. package/lib/shell-api/row-origin.ts +144 -0
  27. package/lib/shell-api/rows.ts +591 -0
  28. package/lib/shell-api/section-panel.ts +378 -0
  29. package/lib/shell-api/section-pointer.ts +164 -0
  30. package/lib/shell-api/sections-preview.ts +275 -0
  31. package/lib/shell-api/sections-rows.ts +133 -0
  32. package/lib/shell-api/sidebar-render.ts +705 -0
  33. package/lib/shell-api/sidebar.ts +1126 -0
  34. package/lib/shell-api/store.ts +279 -0
  35. package/lib/shell-api/tool-design-adoption.ts +263 -0
  36. package/lib/shell-api/tool-design-rows.ts +307 -0
  37. package/lib/shell-api/tool-design-wiring.ts +481 -0
  38. package/lib/shell-api/tool-designs.ts +1411 -0
  39. package/lib/shell-api/transform-pipeline.ts +351 -0
  40. package/lib/shell-api/types.ts +803 -0
  41. package/lib/shell-api/visibility.ts +154 -0
  42. package/package.json +3 -2
  43. package/tools/files-bridge.test.js +81 -66
  44. package/tools/fixtures/load-extension.js +40 -18
  45. package/tools/issues-command.test.js +4 -7
  46. package/tools/issues-section.test.js +71 -81
  47. package/tools/odd-rail-wiring.test.js +16 -10
  48. package/tools/package-surface.test.js +42 -13
  49. package/tools/prs-command.test.js +11 -6
  50. package/tools/shell-api/api.test.ts +484 -0
  51. package/tools/shell-api/apply-on-move.test.ts +529 -0
  52. package/tools/shell-api/arm.test.ts +220 -0
  53. package/tools/shell-api/bridge-ready.test.ts +309 -0
  54. package/tools/shell-api/bus.test.ts +194 -0
  55. package/tools/shell-api/button-rows.test.ts +435 -0
  56. package/tools/shell-api/capture.test.ts +583 -0
  57. package/tools/shell-api/card-style-rows.test.ts +493 -0
  58. package/tools/shell-api/card-style-transform.test.ts +379 -0
  59. package/tools/shell-api/card-style-wiring.test.ts +258 -0
  60. package/tools/shell-api/card-styles-e2e.test.ts +502 -0
  61. package/tools/shell-api/card-styles.test.ts +324 -0
  62. package/tools/shell-api/card-transcript-path.test.ts +178 -0
  63. package/tools/shell-api/compatibility-regression.test.mjs +64 -0
  64. package/tools/shell-api/config.test.ts +93 -0
  65. package/tools/shell-api/docs-coverage.test.ts +82 -0
  66. package/tools/shell-api/e2e.test.ts +562 -0
  67. package/tools/shell-api/example-bash-identity.test.ts +372 -0
  68. package/tools/shell-api/example-bash-matrix.test.ts +856 -0
  69. package/tools/shell-api/example-designs.test.ts +737 -0
  70. package/tools/shell-api/example-neon-transform.test.ts +283 -0
  71. package/tools/shell-api/example-plain-style.test.ts +1225 -0
  72. package/tools/shell-api/extension.test.ts +157 -0
  73. package/tools/shell-api/fake-events.ts +58 -0
  74. package/tools/shell-api/fake-host.ts +211 -0
  75. package/tools/shell-api/fake-sidebar.ts +516 -0
  76. package/tools/shell-api/fake-transcript.ts +486 -0
  77. package/tools/shell-api/frame-telemetry.test.ts +317 -0
  78. package/tools/shell-api/hook.test.ts +196 -0
  79. package/tools/shell-api/manifest.test.ts +47 -0
  80. package/tools/shell-api/message-design-adoption.test.ts +611 -0
  81. package/tools/shell-api/message-design-follows.test.ts +361 -0
  82. package/tools/shell-api/message-design-pi-release.test.mjs +157 -0
  83. package/tools/shell-api/message-design-regressions.test.mjs +162 -0
  84. package/tools/shell-api/message-design-rows.test.ts +266 -0
  85. package/tools/shell-api/message-design-wiring.test.ts +362 -0
  86. package/tools/shell-api/message-designs.test.ts +339 -0
  87. package/tools/shell-api/new-category.test.ts +1101 -0
  88. package/tools/shell-api/notices.test.ts +292 -0
  89. package/tools/shell-api/plugin-integration-lines.test.ts +827 -0
  90. package/tools/shell-api/presence.test.ts +396 -0
  91. package/tools/shell-api/rail-part-hits.test.ts +281 -0
  92. package/tools/shell-api/rail-surfaces.test.ts +402 -0
  93. package/tools/shell-api/rail-width.test.ts +406 -0
  94. package/tools/shell-api/regression.test.ts +434 -0
  95. package/tools/shell-api/repaint-api.test.ts +200 -0
  96. package/tools/shell-api/reserved-categories.test.ts +250 -0
  97. package/tools/shell-api/row-labels.test.ts +261 -0
  98. package/tools/shell-api/row-names.test.ts +407 -0
  99. package/tools/shell-api/row-origin.test.ts +395 -0
  100. package/tools/shell-api/row-placement-regression.test.ts +797 -0
  101. package/tools/shell-api/row-placement.test.ts +410 -0
  102. package/tools/shell-api/section-interaction.test.ts +364 -0
  103. package/tools/shell-api/section-panel.test.ts +430 -0
  104. package/tools/shell-api/section-placement-rail.test.ts +390 -0
  105. package/tools/shell-api/section-placement.test.ts +386 -0
  106. package/tools/shell-api/sections-preview.test.ts +312 -0
  107. package/tools/shell-api/sections-rows.test.ts +293 -0
  108. package/tools/shell-api/sidebar-backend.test.ts +477 -0
  109. package/tools/shell-api/sidebar-e2e.test.ts +317 -0
  110. package/tools/shell-api/sidebar-hover.test.ts +276 -0
  111. package/tools/shell-api/sidebar-independent.test.ts +291 -0
  112. package/tools/shell-api/sidebar-render.test.ts +281 -0
  113. package/tools/shell-api/sidebar-sections.test.ts +247 -0
  114. package/tools/shell-api/store.test.ts +192 -0
  115. package/tools/shell-api/surface-repaint-cost.test.ts +520 -0
  116. package/tools/shell-api/tool-design-card-style.test.ts +308 -0
  117. package/tools/shell-api/tool-design-chain.test.ts +471 -0
  118. package/tools/shell-api/tool-design-cost.test.ts +591 -0
  119. package/tools/shell-api/tool-design-rows.test.ts +627 -0
  120. package/tools/shell-api/tool-design-scopes-audit.test.ts +212 -0
  121. package/tools/shell-api/tool-designs.test.ts +2412 -0
  122. package/tools/shell-api/transform-pipeline.test.ts +376 -0
  123. package/tools/shell-api/transforms-bus.test.ts +233 -0
  124. package/tools/shell-api/verifier-width-regressions.test.ts +147 -0
  125. package/tools/shell-api-rpc.test.js +189 -0
  126. package/tools/user-prompt-card.test.js +8 -9
@@ -0,0 +1,1389 @@
1
+ /**
2
+ * The process-global bus: providers (docs/architecture.md §7, docs/contract.md §1, §5), sidebar
3
+ * sections (the sidebar spec's S1, S2) and transcript transforms (this feature's S1).
4
+ *
5
+ * Pi loads every extension through its own jiti loader with `moduleCache: false`, so module
6
+ * scope is per-copy and cannot hold shared state. The registration lists therefore live on
7
+ * `globalThis` behind a stable `Symbol.for` key, exactly as gentle-shell does for its card
8
+ * style (`lib/shell-card.ts:40-41`). Three providers loaded from three copies of this package
9
+ * see one bus.
10
+ *
11
+ * Sections share this slot rather than taking one of their own: both surfaces are registrations
12
+ * that must be process-global for the same reason, and one slot means one place to read (and to
13
+ * reset) what this process has contributed. `bus()` grows the `sections` list on a slot created
14
+ * by a copy that predates it, so a provider list already in flight is kept. The same holds for
15
+ * `cardStyles` and `transforms`.
16
+ *
17
+ * The key is the bridge's own; it is NOT the hook registry key
18
+ * `Symbol.for("gentle-pi.customize-row-providers")`, which belongs to the host (S4/T5), and it
19
+ * is not the host's rail key `Symbol.for("gentle-pi.experimental-sidebar.state")`.
20
+ *
21
+ * This module is internal. `src/index.ts` re-exports `registerRows` and `snapshotProviders`
22
+ * but never `resetBusForTests`; the section equivalents stay internal until the public surface is
23
+ * decided.
24
+ */
25
+
26
+ import { HOST_CARD_STYLE_VALUES, RESERVED_CARD_STYLE_IDS } from "./card-style-line.ts";
27
+ import { attributeRegistration } from "./plugin-lines.ts";
28
+ import { cardStyleRowLabelText, sectionRowLabelText } from "./row-labels.ts";
29
+ import {
30
+ clearRowNameRejections,
31
+ rejectRowName,
32
+ reservedCategory,
33
+ RESERVED_CATEGORY_RULE,
34
+ } from "./row-names.ts";
35
+ import { RAIL_PARTS } from "./types.ts";
36
+ import type {
37
+ CardStyleRegistration,
38
+ RailPart,
39
+ RowProvider,
40
+ SidebarSection,
41
+ TranscriptTransform,
42
+ } from "./types.ts";
43
+
44
+ /** Re-exported here because a placement decision is the bus's: see `resolveSectionPlacements`. */
45
+ export { RAIL_PARTS };
46
+
47
+ /** Stable process-global slot for the bridge's registration lists. */
48
+ const BUS_KEY = Symbol.for("gentle-shell-bridge.providers");
49
+
50
+ interface BusEntry {
51
+ provider: RowProvider;
52
+ }
53
+
54
+ interface SectionEntry {
55
+ section: SidebarSection;
56
+ }
57
+
58
+ interface CardStyleEntry {
59
+ style: CardStyleRegistration;
60
+ }
61
+
62
+ interface TransformEntry {
63
+ transform: TranscriptTransform;
64
+ }
65
+
66
+ interface BusState {
67
+ /** Providers in subscription order; one entry per live `id`. */
68
+ entries: BusEntry[];
69
+ /** Sections in registration order; one entry per live `id`. Ordering happens in the snapshot. */
70
+ sections: SectionEntry[];
71
+ /** Card styles in registration order; one entry per live `id`. Ordering: `snapshotCardStyles`. */
72
+ cardStyles: CardStyleEntry[];
73
+ /** Transcript transforms in registration order; ordering happens in `snapshotTransforms`. */
74
+ transforms: TransformEntry[];
75
+ /** Sections that asked for a `placement` the bridge cannot honour; one per live `id`. */
76
+ placementRejections: SectionPlacementRejection[];
77
+ /** Row providers that asked for a `placement` the bridge cannot honour; one per live `id`. */
78
+ rowPlacementRejections: RowPlacementRejection[];
79
+ /** The ACTUAL landing each row provider got in the last menu build (S5). */
80
+ rowPlacementLandings: RowPlacementLandingRecord[];
81
+ /** The host's own category names as the last capture observed them (T2 writes this). */
82
+ observedHostCategories?: string[];
83
+ }
84
+
85
+ /** The slot shape on `globalThis`; keeps the cast in one place. */
86
+ function busHost(): Record<symbol, BusState | undefined> {
87
+ // SAFETY: the only writes to this key are the `bus()` creation below, so IF this key holds
88
+ // anything it holds a BusState. A foreign or partial value is not trusted anyway: `bus()`
89
+ // re-checks `entries` and replaces an unusable slot before returning it.
90
+ return globalThis as unknown as Record<symbol, BusState | undefined>;
91
+ }
92
+
93
+ /**
94
+ * Return the process-global bus, creating it on first use. A pre-existing value that is not a
95
+ * usable bus (another library's slot, a partial object across reloads) is replaced rather than
96
+ * trusted.
97
+ */
98
+ function bus(): BusState {
99
+ const host = busHost();
100
+ const existing = host[BUS_KEY];
101
+ if (existing !== undefined && Array.isArray(existing.entries)) {
102
+ // A slot created by a copy of this package (or an earlier load) that predates sections keeps
103
+ // its live providers and gains the section list in place, so two copies always agree.
104
+ if (!Array.isArray(existing.sections)) existing.sections = [];
105
+ // Same for card styles: an older copy's bus gains the list instead of being replaced, so a
106
+ // style registered through one copy is visible to every other (S12, determinism).
107
+ if (!Array.isArray(existing.cardStyles)) existing.cardStyles = [];
108
+ // And for transforms: a copy that predates the pipeline keeps its live registrations and gains
109
+ // the list, so the wrapper another copy installed sees what this copy registered.
110
+ if (!Array.isArray(existing.transforms)) existing.transforms = [];
111
+ // Same for the placement rejections: an older copy's bus gains the list instead of being
112
+ // replaced, so the report of a bad `placement` survives a second package copy registering one.
113
+ if (!Array.isArray(existing.placementRejections)) existing.placementRejections = [];
114
+ // And for the row placement rejections, the same discipline for the row surface.
115
+ if (!Array.isArray(existing.rowPlacementRejections)) existing.rowPlacementRejections = [];
116
+ // The last build's actual landings are diagnostics, not registrations; an older copy gains the
117
+ // list instead of being replaced.
118
+ if (!Array.isArray(existing.rowPlacementLandings)) existing.rowPlacementLandings = [];
119
+ return existing;
120
+ }
121
+ const created: BusState = {
122
+ entries: [],
123
+ sections: [],
124
+ cardStyles: [],
125
+ transforms: [],
126
+ placementRejections: [],
127
+ rowPlacementRejections: [],
128
+ rowPlacementLandings: [],
129
+ };
130
+ host[BUS_KEY] = created;
131
+ return created;
132
+ }
133
+
134
+ /**
135
+ * Register a provider and return a disposer that removes exactly that provider.
136
+ *
137
+ * - Providers keep subscription order.
138
+ * - Registering an existing `id` replaces the previous registration *in place*, so the order
139
+ * is stable and there is still exactly one entry (and one diagnostics entry) for that id.
140
+ * - The disposer removes only the registration it created: after a same-id replacement, the
141
+ * replaced provider's disposer is a no-op instead of removing the replacement, and calling a
142
+ * disposer twice does nothing the second time.
143
+ */
144
+ export function registerRows(provider: RowProvider): () => void {
145
+ // Attribution is a wrapper, not part of the store: the plugin gets ONE INTEGRATIONS line from any
146
+ // number of registrations (`./plugin-lines.ts`, I1), and `registerRowsStored` keeps doing exactly
147
+ // what it did — including throwing a plugin's invalid id back at it.
148
+ return attributeRegistration("rows", provider, undefined, () => {
149
+ assertProviderIdIsFree(provider);
150
+ return registerRowsStored(provider);
151
+ });
152
+ }
153
+
154
+ /**
155
+ * Register one of THIS package's own providers: the same store, the same attribution, without the
156
+ * reservation check below. Internal — `src/index.ts` does not export it, so a plugin cannot reach it.
157
+ */
158
+ export function registerBridgeRows(provider: RowProvider): () => void {
159
+ return attributeRegistration("rows", provider, undefined, () => registerRowsStored(provider));
160
+ }
161
+
162
+ /**
163
+ * The provider ids this package owns. They are the bridge's own plumbing — its effect is the tables
164
+ * in the diagnostics record, and the report filters those exact objects out of `providers`.
165
+ *
166
+ * A plugin that registers one of them is refused, for two reasons that both cost the user something
167
+ * real. The bus answers an id first-come, so a plugin taking `bridge.message-designs` before the
168
+ * bridge does either keeps the bridge's line off the menu until it lets go, or is silently replaced
169
+ * by it — and a plugin that takes the id and gives it back AFTER a design registered leaves the line
170
+ * uninstalled for the rest of the process. Refusing the id at the door is the only answer that cannot
171
+ * strand a switch.
172
+ */
173
+ const RESERVED_ROW_PROVIDER_IDS: ReadonlySet<string> = new Set([
174
+ // The literals of `SECTION_ROWS_PROVIDER_ID`, `CARD_STYLE_ROWS_PROVIDER_ID`,
175
+ // `TOOL_DESIGN_ROWS_PROVIDER_ID` and `MESSAGE_DESIGN_ROWS_PROVIDER_ID`. Spelled here because those
176
+ // modules import THIS one, so importing their constants would close a cycle.
177
+ "bridge.sections",
178
+ "bridge.card-styles",
179
+ "bridge.tool-designs",
180
+ "bridge.message-designs",
181
+ ]);
182
+
183
+ function assertProviderIdIsFree(provider: RowProvider): void {
184
+ if (!RESERVED_ROW_PROVIDER_IDS.has(provider.id)) return;
185
+ throw new Error(
186
+ `gentle-shell-bridge: cannot register row provider ${JSON.stringify(provider.id)}: that id ` +
187
+ "belongs to the bridge's own line, so a plugin using it would take that line off the menu or " +
188
+ "be silently replaced by it. Register your rows under an id of your own, e.g. " +
189
+ '"loon.rows".',
190
+ );
191
+ }
192
+
193
+ /**
194
+ * `Keymaps` is the host's own interaction (S15), not one of its setting pages: its rows capture the
195
+ * next key press, write `keymaps.json` and get a category footer that promises `Enter assign`
196
+ * (`lib/keymaps-customize.ts:49-68`, `lib/visual-customize-view.ts:40`). A plugin row there would be
197
+ * advertised as an assignable binding and could never honour it, so the page is reserved and the
198
+ * provider is refused BEFORE anything is stored.
199
+ *
200
+ * The throw is the refusal: `attributeRegistration` is the boundary every registration already goes
201
+ * through, so the refusal lands in the plugin's INTEGRATIONS line as a rejected registration (the
202
+ * same line, and the same `degraded` state, as an invalid id) and in the diagnostics record. Nothing is
203
+ * stored, so a refused provider can never reach a menu build. A row that carries the reserved
204
+ * category ITSELF is refused per row at build time instead, so its siblings survive (`./rows.ts`).
205
+ */
206
+ function assertRowProviderCategory(provider: RowProvider): void {
207
+ const reserved = reservedCategory(provider.category);
208
+ if (reserved === undefined) return;
209
+ throw new Error(
210
+ `gentle-shell-bridge: cannot register row provider ${JSON.stringify(provider.id)}: its ` +
211
+ `category ${JSON.stringify(String(provider.category))} is the reserved category ` +
212
+ `${JSON.stringify(reserved)}. ${reserved} ${RESERVED_CATEGORY_RULE}. Place the rows in one of ` +
213
+ `the host's other categories, e.g. "Cards".`,
214
+ );
215
+ }
216
+
217
+ function registerRowsStored(provider: RowProvider): () => void {
218
+ assertRowProviderCategory(provider);
219
+ // A row `placement` the bridge cannot honour is reported and IGNORED, never thrown: refusing the
220
+ // whole provider over it would cost the user its rows. It lands at the end, which is the
221
+ // historical default (S5).
222
+ const placementFault = rowPlacementProblem(provider.placement);
223
+ if (placementFault === undefined) clearRowPlacementRejection(provider.id);
224
+ else {
225
+ recordRowPlacementRejection({
226
+ providerId: provider.id,
227
+ value: describeValue(provider.placement),
228
+ reason: placementFault,
229
+ });
230
+ }
231
+ const state = bus();
232
+ const entry: BusEntry = { provider };
233
+ const index = state.entries.findIndex((candidate) => candidate.provider.id === provider.id);
234
+ if (index === -1) state.entries.push(entry);
235
+ else state.entries[index] = entry;
236
+
237
+ let disposed = false;
238
+ return () => {
239
+ if (disposed) return;
240
+ disposed = true;
241
+ const current = state.entries.indexOf(entry);
242
+ if (current !== -1) {
243
+ state.entries.splice(current, 1);
244
+ // The record describes THIS registration, which is gone now; a stale disposer (after a
245
+ // same-id replacement) must not clear the replacement's record instead.
246
+ clearRowPlacementRejection(provider.id);
247
+ }
248
+ };
249
+ }
250
+
251
+ /**
252
+ * An ordered snapshot of the registered providers. The array is a fresh copy, so a fan-out
253
+ * that iterates it sees a stable list even if a provider registers or disposes mid-iteration.
254
+ */
255
+ export function snapshotProviders(): RowProvider[] {
256
+ return bus().entries.map((entry) => entry.provider);
257
+ }
258
+
259
+ /**
260
+ * Test-only seam: empties the process-global bus in place. Deliberately not re-exported from
261
+ * `src/index.ts`, so it is unreachable from the package's public entry.
262
+ */
263
+ export function resetBusForTests(): void {
264
+ const state = bus();
265
+ state.entries.length = 0;
266
+ state.rowPlacementRejections.length = 0;
267
+ state.rowPlacementLandings.length = 0;
268
+ delete state.observedHostCategories;
269
+ }
270
+
271
+ /**
272
+ * Record the host's own category names as the last capture observed them, so the diagnostics record can
273
+ * resolve a row placement against the pages the host really built. The capture backend is the
274
+ * writer (T2); a caller can pass the set in any order, because `resolveRowPlacements` normalizes it.
275
+ */
276
+ export function recordObservedHostCategories(categories: readonly string[]): void {
277
+ bus().observedHostCategories = categories.filter(
278
+ (category): category is string => typeof category === "string",
279
+ );
280
+ }
281
+
282
+ /** The host categories the last capture observed, or `[]` before one (a fresh copy). */
283
+ export function observedHostCategories(): string[] {
284
+ return [...(bus().observedHostCategories ?? [])];
285
+ }
286
+
287
+ /** One row provider's block: where it asked to sit and where it really lands (S1–S3, S5). */
288
+ export interface RowPlacementResolution {
289
+ provider: RowProvider;
290
+ /** The category whose page carries this block. */
291
+ category: string;
292
+ /** What the plugin asked for, as a person reads it: `start`, `end`, `after "loon.news"`. */
293
+ requested: string;
294
+ /** What the block hangs off in its category: `start`, `end`, or `"<provider id>"`. */
295
+ anchor: string;
296
+ /** Why the block is not where it asked to be; absent when the request was honoured. */
297
+ reason?: string;
298
+ }
299
+
300
+ /**
301
+ * A row `placement` the bridge cannot honour, kept verbatim so the author can find it (S5). The
302
+ * provider still registers — a field the bridge can ignore must never cost the whole block — and
303
+ * it is placed at the end, which is what the diagnostics record says next to this record.
304
+ */
305
+ export interface RowPlacementRejection {
306
+ providerId: string;
307
+ /** The value as JSON, exactly as far as a report can show it. Never rewritten. */
308
+ value: string;
309
+ /** One sentence naming the shape that was expected. */
310
+ reason: string;
311
+ }
312
+
313
+ /** Where one provider block REALLY landed in the last menu build (S5), not where it asked to sit. */
314
+ export interface RowPlacementLandingRecord {
315
+ providerId: string;
316
+ /** The row's actual category, which may differ from the provider's declared one. */
317
+ category: string;
318
+ /** The request as a person reads it: `start`, `end`, `after "loon.news"`. */
319
+ requested: string;
320
+ /** The real landing: `start`, `end`, `after "loon.news"`, or `end` after a skipped move. */
321
+ landed: string;
322
+ /** Why it is not where it asked to be; the resolver's exact reason, or why the move was skipped. */
323
+ reason?: string;
324
+ }
325
+
326
+ /** The rule, quoted by every rejection so the message stands on its own. */
327
+ const ROW_PLACEMENT_RULE =
328
+ 'placement must be "start", "end", or { after: "<row provider id>" }';
329
+
330
+ /**
331
+ * What is wrong with one row `placement`, or `undefined` when the bridge can honour it.
332
+ *
333
+ * Checked in a fixed order — the shape, then the `after` string, then its own shape — so the
334
+ * reported reason is deterministic instead of depending on how a bad value was built. One rule for
335
+ * the registration (nothing is thrown) and for the resolver, which must survive a value a
336
+ * registration refused, because a plugin can hand the provider object over and mutate it later.
337
+ */
338
+ function rowPlacementProblem(value: unknown): string | undefined {
339
+ // Absent is the default, `"end"`: a provider that names no placement is conforming, not faulty.
340
+ if (value === undefined) return undefined;
341
+ if (value === "start" || value === "end") return undefined;
342
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
343
+ return `it is ${describeValue(value)}; ${ROW_PLACEMENT_RULE}`;
344
+ }
345
+ const keys = Object.keys(value);
346
+ if (keys.length !== 1 || keys[0] !== "after") {
347
+ return "an object placement carries exactly one field, `after`, naming the id of a registered row provider";
348
+ }
349
+ // SAFETY: the object has exactly the own key `after`, which is what is read here.
350
+ const target = (value as { after: unknown }).after;
351
+ if (typeof target !== "string" || target.trim() === "") {
352
+ return `after is ${describeValue(target)}; after must be a non-empty string naming the id of a registered row provider`;
353
+ }
354
+ return undefined;
355
+ }
356
+
357
+ /** Replace the record for one provider, so a corrected registration stops being reported. */
358
+ function recordRowPlacementRejection(rejection: RowPlacementRejection): void {
359
+ const state = bus();
360
+ const index = state.rowPlacementRejections.findIndex(
361
+ (candidate) => candidate.providerId === rejection.providerId,
362
+ );
363
+ if (index === -1) state.rowPlacementRejections.push(rejection);
364
+ else state.rowPlacementRejections[index] = rejection;
365
+ }
366
+
367
+ function clearRowPlacementRejection(providerId: string): void {
368
+ const rejections = bus().rowPlacementRejections;
369
+ for (let index = rejections.length - 1; index >= 0; index -= 1) {
370
+ if (rejections[index].providerId === providerId) rejections.splice(index, 1);
371
+ }
372
+ }
373
+
374
+ /** Every row `placement` a registration had to refuse, for the diagnostics record. A fresh copy. */
375
+ export function getRowPlacementRejections(): RowPlacementRejection[] {
376
+ return bus().rowPlacementRejections.map((rejection) => ({ ...rejection }));
377
+ }
378
+
379
+ /** Record the ACTUAL landings of one menu build, so the report never repeats a skipped plan (S5). */
380
+ export function recordRowPlacementLandings(
381
+ landings: readonly RowPlacementLandingRecord[],
382
+ ): void {
383
+ bus().rowPlacementLandings = landings.map((landing) => ({ ...landing }));
384
+ }
385
+
386
+ /** The landings of the last menu build. A fresh copy. */
387
+ export function getRowPlacementLandings(): RowPlacementLandingRecord[] {
388
+ return bus().rowPlacementLandings.map((landing) => ({ ...landing }));
389
+ }
390
+
391
+ /** One provider's placement as a phrase: `start`, `end`, `after "loon.news"`. */
392
+ export function requestedRowPlacementText(provider: RowProvider): string {
393
+ const placement = provider.placement;
394
+ if (placement === undefined || placement === "end") return "end";
395
+ if (placement === "start") return "start";
396
+ if (placement !== null && typeof placement === "object" && typeof placement.after === "string") {
397
+ return `after ${JSON.stringify(placement.after)}`;
398
+ }
399
+ return describeValue(placement);
400
+ }
401
+
402
+ /** Where one row landing reads as: `start`, `end`, `after "loon.news"`. */
403
+ export function rowPlacementLandingText(
404
+ landing: Pick<RowPlacementResolution, "anchor">,
405
+ ): string {
406
+ if (landing.anchor === "start" || landing.anchor === "end") return landing.anchor;
407
+ return `after ${landing.anchor}`;
408
+ }
409
+
410
+ /** What one row block hangs off, before the category turns it into a landing. */
411
+ type RowPlacementAnchor =
412
+ | { kind: "start" }
413
+ | { kind: "end" }
414
+ | { kind: "provider"; id: string };
415
+
416
+ /** Group key for one anchor: tagged, because a provider id may itself read `start` or `end`. */
417
+ function rowAnchorKey(anchor: RowPlacementAnchor): string {
418
+ if (anchor.kind === "provider") return `provider:${anchor.id}`;
419
+ return anchor.kind;
420
+ }
421
+
422
+ /** An anchor as a person reads it: `start`, `end`, `"loon.news"`. */
423
+ function rowAnchorText(anchor: RowPlacementAnchor): string {
424
+ if (anchor.kind === "provider") return JSON.stringify(anchor.id);
425
+ return anchor.kind;
426
+ }
427
+
428
+ interface RowDirectPlacement {
429
+ anchor: RowPlacementAnchor;
430
+ reason?: string;
431
+ }
432
+
433
+ /** What one provider asked for, before cycles are broken and categories are resolved. */
434
+ function rowDirectPlacement(
435
+ provider: RowProvider,
436
+ category: string,
437
+ ownIds: ReadonlySet<string>,
438
+ categoriesById: ReadonlyMap<string, ReadonlySet<string>>,
439
+ hostBuilt: boolean,
440
+ ): RowDirectPlacement {
441
+ const placement = provider.placement;
442
+ if (placement === undefined || placement === "end") return { anchor: { kind: "end" } };
443
+ const problem = rowPlacementProblem(placement);
444
+ if (problem !== undefined) {
445
+ return { anchor: { kind: "end" }, reason: `its placement is malformed (${problem})` };
446
+ }
447
+ if (placement === "start") {
448
+ if (!hostBuilt) {
449
+ return {
450
+ anchor: { kind: "end" },
451
+ reason: `the host did not build the category ${JSON.stringify(category)}, so it has no first row to sit before; it landed at the end`,
452
+ };
453
+ }
454
+ return { anchor: { kind: "start" } };
455
+ }
456
+ // SAFETY: `rowPlacementProblem` accepted the value, so it is the `{ after }` shape.
457
+ const target = (placement as { after: string }).after;
458
+ if (!hostBuilt) {
459
+ return {
460
+ anchor: { kind: "end" },
461
+ reason: `the host did not build the category ${JSON.stringify(category)}, so after ${JSON.stringify(target)} cannot be honoured; it landed at the end`,
462
+ };
463
+ }
464
+ if (ownIds.has(target)) return { anchor: { kind: "provider", id: target } };
465
+ const targetCategories = categoriesById.get(target);
466
+ if (targetCategories !== undefined && targetCategories.size > 0) {
467
+ const otherCategory =
468
+ [...targetCategories].sort(compareProviderIds).find((candidate) => candidate !== category) ??
469
+ category;
470
+ return {
471
+ anchor: { kind: "end" },
472
+ reason: `after ${JSON.stringify(target)} is in the category ${JSON.stringify(otherCategory)}, not ${JSON.stringify(category)}`,
473
+ };
474
+ }
475
+ return {
476
+ anchor: { kind: "end" },
477
+ reason: `after ${JSON.stringify(target)} is not a registered row provider id`,
478
+ };
479
+ }
480
+
481
+ /** A provider id compare: UTF-16 code units, never a locale collation (S2). */
482
+ function compareProviderIds(a: string, b: string): number {
483
+ if (a === b) return 0;
484
+ return a < b ? -1 : 1;
485
+ }
486
+
487
+ /** A provider whose `order` is a usable sort key; `NaN`, `Infinity` and a missing value are not. */
488
+ function sortableRowOrder(provider: RowProvider): number | undefined {
489
+ return typeof provider.order === "number" && Number.isFinite(provider.order)
490
+ ? provider.order
491
+ : undefined;
492
+ }
493
+
494
+ /** The S2 order inside one slot: finite `order` first, ascending, then every tie by `id`. */
495
+ function compareRowProviders(a: RowProvider, b: RowProvider): number {
496
+ const orderA = sortableRowOrder(a);
497
+ const orderB = sortableRowOrder(b);
498
+ if (orderA !== undefined && orderB !== undefined) {
499
+ if (orderA !== orderB) return orderA - orderB;
500
+ } else if (orderA !== undefined) {
501
+ return -1;
502
+ } else if (orderB !== undefined) {
503
+ return 1;
504
+ }
505
+ return compareProviderIds(a.id, b.id);
506
+ }
507
+
508
+ /**
509
+ * Every row block's landing, grouped by category and in DRAW order (S1–S3, S5): the answer both the
510
+ * capture backend and the diagnostics record read, so a report and a menu cannot disagree.
511
+ *
512
+ * Pure by construction: it takes the registrations and the host's categories, and nothing else.
513
+ * Where a block goes is decided from those two lists alone, never from the order the plugins loaded
514
+ * in:
515
+ *
516
+ * - within one slot, providers with a finite `order` come first, ascending, then the rest, and ties
517
+ * are broken by `id` compared as UTF-16 code units (S2) — the input order does not matter;
518
+ * - placement is resolved WITHIN the category a block actually belongs to (S4): `categoriesByProvider`
519
+ * lets the capture pass the rows' real categories (`row.category ?? provider.category`), so a
520
+ * provider contributing to two categories is one block in each; `start` is before that category's
521
+ * first row, `end` after its own rows, and every provider id is a slot whose followers draw right
522
+ * after its block, so chains resolve transitively and several providers asking for the same `X`
523
+ * form one block (S3);
524
+ * - a cycle, a provider after itself, an unknown id, an anchor in another category, and `start` or
525
+ * `after` in a category the host did not build all fall back to `"end"` with a reason — never a
526
+ * throw, never a vanished block (S5);
527
+ * - `hostCategories` is a SET: it is deduplicated and sorted by UTF-16 code units, so a caller
528
+ * cannot make the answer depend on how it collected the list.
529
+ */
530
+ export function resolveRowPlacements(
531
+ providers: readonly RowProvider[],
532
+ hostCategories: readonly string[],
533
+ categoriesByProvider?: ReadonlyMap<string, readonly string[]>,
534
+ ): RowPlacementResolution[] {
535
+ const hostBuilt = new Set(
536
+ hostCategories.filter((category): category is string => typeof category === "string"),
537
+ );
538
+ const categoriesById = new Map<string, Set<string>>();
539
+ const categories = new Set<string>(hostBuilt);
540
+ for (const provider of providers) {
541
+ const declared = categoriesByProvider?.get(provider.id) ?? [provider.category];
542
+ const actual = new Set(declared.filter((category) => typeof category === "string"));
543
+ if (actual.size === 0) actual.add(provider.category);
544
+ categoriesById.set(provider.id, actual);
545
+ for (const category of actual) categories.add(category);
546
+ }
547
+
548
+ const out: RowPlacementResolution[] = [];
549
+ // A deterministic category order: the host's pages and the plugin-created ones together, sorted
550
+ // by code unit, so collecting the host set differently cannot reorder the result.
551
+ for (const category of [...categories].sort(compareProviderIds)) {
552
+ const own = providers.filter((provider) => categoriesById.get(provider.id)?.has(category));
553
+ if (own.length === 0) continue;
554
+ const ownIds = new Set(own.map((provider) => provider.id));
555
+ const built = hostBuilt.has(category);
556
+
557
+ const anchors = new Map<string, RowDirectPlacement>();
558
+ for (const provider of own) {
559
+ anchors.set(
560
+ provider.id,
561
+ rowDirectPlacement(provider, category, ownIds, categoriesById, built),
562
+ );
563
+ }
564
+ for (const id of rowCycleMembers(own, anchors)) {
565
+ anchors.set(id, {
566
+ anchor: { kind: "end" },
567
+ reason: "it would sit after itself: a placement cycle falls back to the end",
568
+ });
569
+ }
570
+
571
+ const groups = new Map<string, RowProvider[]>();
572
+ for (const provider of own) {
573
+ const anchor = anchors.get(provider.id)?.anchor ?? { kind: "end" as const };
574
+ const key = rowAnchorKey(anchor);
575
+ const group = groups.get(key);
576
+ if (group === undefined) groups.set(key, [provider]);
577
+ else group.push(provider);
578
+ }
579
+ for (const group of groups.values()) group.sort(compareRowProviders);
580
+
581
+ const visited = new Set<string>();
582
+ const emit = (key: string): void => {
583
+ if (visited.has(key)) return;
584
+ visited.add(key);
585
+ const group = groups.get(key);
586
+ if (group === undefined) return;
587
+ for (const provider of group) {
588
+ const direct = anchors.get(provider.id) ?? { anchor: { kind: "end" as const } };
589
+ out.push({
590
+ provider,
591
+ category,
592
+ requested: requestedRowPlacementText(provider),
593
+ anchor: rowAnchorText(direct.anchor),
594
+ ...(direct.reason === undefined ? {} : { reason: direct.reason }),
595
+ });
596
+ emit(`provider:${provider.id}`);
597
+ }
598
+ };
599
+
600
+ emit("start");
601
+ emit("end");
602
+ // Cycles are gone, so every block was reached above. Emitting any remaining key in a
603
+ // deterministic order keeps a future anchor shape from silently dropping a block.
604
+ for (const key of [...groups.keys()].sort(compareProviderIds)) emit(key);
605
+ }
606
+
607
+ return out;
608
+ }
609
+
610
+ /**
611
+ * The providers that are part of a placement cycle (A after B after A, or A after itself). Every
612
+ * other provider is left alone: a chain that merely LEADS into a cycle is resolved through it
613
+ * after the cycle members have fallen back to the end.
614
+ */
615
+ function rowCycleMembers(
616
+ providers: readonly RowProvider[],
617
+ anchors: ReadonlyMap<string, RowDirectPlacement>,
618
+ ): string[] {
619
+ const settled = new Set<string>();
620
+ const members = new Set<string>();
621
+ for (const provider of providers) {
622
+ const chain: string[] = [];
623
+ let current: string | undefined = provider.id;
624
+ while (current !== undefined && !settled.has(current)) {
625
+ const repeat = chain.indexOf(current);
626
+ if (repeat !== -1) {
627
+ for (const id of chain.slice(repeat)) members.add(id);
628
+ break;
629
+ }
630
+ chain.push(current);
631
+ const anchor: RowPlacementAnchor | undefined = anchors.get(current)?.anchor;
632
+ current = anchor?.kind === "provider" ? anchor.id : undefined;
633
+ }
634
+ for (const id of chain) settled.add(id);
635
+ }
636
+ return [...members];
637
+ }
638
+
639
+ /**
640
+ * Register a sidebar section and return a disposer that removes exactly that section.
641
+ *
642
+ * Same entry discipline as `registerRows`, because a plugin author should not have to learn two:
643
+ *
644
+ * - A second registration with an existing `id` replaces the previous one *in place*, so the
645
+ * section keeps the position its registration earned (ordering is computed in
646
+ * `snapshotSections`, so a replacement that changes `order` moves the section on the next read).
647
+ * - The returned disposer removes only the registration it created: after a same-id replacement the
648
+ * replaced section's disposer is a no-op instead of removing the replacement, and calling a
649
+ * disposer twice does nothing the second time.
650
+ *
651
+ * The disposer removes the section from the rail and from `Sections` together, because both surfaces
652
+ * are built from this one registration.
653
+ */
654
+ /** Ids that collide with `Object.prototype` and therefore cannot be used as a plain-object key. */
655
+ const RESERVED_REGISTRATION_IDS = new Set(["__proto__", "constructor", "prototype"]);
656
+
657
+ /**
658
+ * An id is identity: it keys the ordering, the replacement and the persisted value. A bad id is a
659
+ * plugin bug and is rejected with a clear error BEFORE anything is stored, so a rejected
660
+ * registration can never half-register (B2). One rule for every surface, so a plugin author does
661
+ * not have to learn two.
662
+ */
663
+ function registrationIdProblem(id: unknown): string | undefined {
664
+ if (typeof id !== "string") return "it must be a non-empty string";
665
+ if (id.trim() === "") return "it must be a non-empty string";
666
+ if (RESERVED_REGISTRATION_IDS.has(id)) return "it collides with Object.prototype";
667
+ if (id.includes("\0")) return "it contains a NUL byte";
668
+ return undefined;
669
+ }
670
+
671
+ /** Throws the surface-specific message; `kind` names the thing in both the message and the rule. */
672
+ export function assertRegistrationId(kind: string, id: unknown): asserts id is string {
673
+ const problem = registrationIdProblem(id);
674
+ if (problem === undefined) return;
675
+ throw new Error(
676
+ `gentle-shell-bridge: invalid ${kind} id ${JSON.stringify(id)}: ${problem}. ` +
677
+ `A ${kind} id must be a non-empty string that can be used as a plain object key.`,
678
+ );
679
+ }
680
+
681
+ function assertSectionId(id: unknown): asserts id is string {
682
+ assertRegistrationId("section", id);
683
+ }
684
+
685
+ /**
686
+ * `rowLabel`, when present, is text a human reads in the menu, so an empty one is a plugin bug and
687
+ * is rejected before anything is stored — the same discipline as the id.
688
+ */
689
+ function assertRowLabel(kind: string, id: string, rowLabel: unknown): void {
690
+ if (rowLabel === undefined) return;
691
+ if (typeof rowLabel !== "string" || rowLabel.trim() === "") {
692
+ throw new Error(
693
+ `gentle-shell-bridge: invalid ${kind} rowLabel for ${JSON.stringify(id)}: it must be a ` +
694
+ "non-empty string. It is the text a user reads in the menu; the id stays internal. Omit it " +
695
+ "to let the bridge derive a label from the visible text instead.",
696
+ );
697
+ }
698
+ }
699
+
700
+ export function registerSection(section: SidebarSection): () => void {
701
+ return attributeRegistration("section", section, "section", () => registerSectionStored(section));
702
+ }
703
+
704
+ function registerSectionStored(section: SidebarSection): () => void {
705
+ assertSectionId(section.id);
706
+ assertRowLabel("section", section.id, section.rowLabel);
707
+ // The label is what a user reads, so it obeys the row-name shape before anything is stored (N8):
708
+ // `Music: now playing` is rejected here, reported by the diagnostics record, and never rewritten. A
709
+ // DERIVED label cannot fail this check — derivation applies the same shape (`./row-labels.ts`).
710
+ if (rejectRowName("section", section.id, "row label", sectionRowLabelText(section))) {
711
+ return () => {};
712
+ }
713
+ // The name in force now conforms, so a record left by the name it replaced is no longer true.
714
+ clearRowNameRejections("section", section.id);
715
+ // A `placement` the bridge cannot honour is reported and IGNORED, never thrown: it names where the
716
+ // card goes, and refusing the whole section over it would cost the user their card. It lands at the
717
+ // end, which is the historical default (S5).
718
+ const placementFault = placementProblem(section.placement);
719
+ if (placementFault === undefined) clearPlacementRejection(section.id);
720
+ else {
721
+ recordPlacementRejection({
722
+ sectionId: section.id,
723
+ value: describeValue(section.placement),
724
+ reason: placementFault,
725
+ });
726
+ }
727
+ const state = bus();
728
+ const entry: SectionEntry = { section };
729
+ const index = state.sections.findIndex((candidate) => candidate.section.id === section.id);
730
+ if (index === -1) state.sections.push(entry);
731
+ else state.sections[index] = entry;
732
+
733
+ let disposed = false;
734
+ return () => {
735
+ if (disposed) return;
736
+ disposed = true;
737
+ const current = state.sections.indexOf(entry);
738
+ if (current !== -1) state.sections.splice(current, 1);
739
+ };
740
+ }
741
+
742
+ /** One section's landing: where its block of rows hangs in the rail (S1–S3, S5). */
743
+ export interface SectionPlacementResolution {
744
+ section: SidebarSection;
745
+ /** What the plugin asked for, as a person reads it: `start`, `end`, `after "loon.news"`. */
746
+ requested: string;
747
+ /** The painted rail part whose own rows it draws around. */
748
+ part: RailPart;
749
+ /** `before` draws above that part's own rows, `after` below them. */
750
+ side: "before" | "after";
751
+ /** What the block hangs off: `start`, `end`, a native rail part, or `"<section id>"`. */
752
+ anchor: string;
753
+ /** Why the card is not where it asked to be; absent when the request was honoured. */
754
+ reason?: string;
755
+ }
756
+
757
+ /**
758
+ * A `placement` the bridge cannot honour, kept verbatim so the author can find it (S5). The section
759
+ * still registers — a field the bridge can ignore must never cost the whole card — and it is placed
760
+ * at the end, which is what the diagnostics record says next to this record.
761
+ */
762
+ export interface SectionPlacementRejection {
763
+ sectionId: string;
764
+ /** The value as JSON, exactly as far as a report can show it. Never rewritten. */
765
+ value: string;
766
+ /** One sentence naming the shape that was expected. */
767
+ reason: string;
768
+ }
769
+
770
+ /** The rule, quoted by every rejection so the message stands on its own. */
771
+ const PLACEMENT_RULE =
772
+ 'placement must be "start", "end", or { after: "<section id or native rail part>" }';
773
+
774
+ /**
775
+ * What is wrong with one `placement`, or `undefined` when the bridge can honour it.
776
+ *
777
+ * Checked in a fixed order — the shape, then the `after` string, then its own shape — so the
778
+ * reported reason is deterministic instead of depending on how a bad value was built. One rule for
779
+ * the registration (`./bus.ts` stores nothing) and for the resolver, which must survive a value a
780
+ * registration refused, because a plugin can hand the section object over and mutate it later.
781
+ */
782
+ function placementProblem(value: unknown): string | undefined {
783
+ // Absent is the default, `"end"`: a section that names no placement is conforming, not faulty.
784
+ if (value === undefined) return undefined;
785
+ if (value === "start" || value === "end") return undefined;
786
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
787
+ return `it is ${describeValue(value)}; ${PLACEMENT_RULE}`;
788
+ }
789
+ const keys = Object.keys(value);
790
+ if (keys.length !== 1 || keys[0] !== "after") {
791
+ return 'an object placement carries exactly one field, `after`, naming a section id or one of "todo", "jobs", "agents", "footer"';
792
+ }
793
+ // SAFETY: the object has exactly the own key `after`, which is what is read here.
794
+ const target = (value as { after: unknown }).after;
795
+ if (typeof target !== "string" || target.trim() === "") {
796
+ return `after is ${describeValue(target)}; after must be a non-empty string naming a section id or one of "todo", "jobs", "agents", "footer"`;
797
+ }
798
+ return undefined;
799
+ }
800
+
801
+ /** A value as a short, safe phrase for a message: the JSON when it has one, its type otherwise. */
802
+ function describeValue(value: unknown): string {
803
+ if (value === undefined) return "absent";
804
+ try {
805
+ const json = JSON.stringify(value);
806
+ if (typeof json === "string") return json;
807
+ } catch {
808
+ // A cyclic or otherwise unprintable value falls through to its type.
809
+ }
810
+ return `a ${typeof value}`;
811
+ }
812
+
813
+ /** Replace the record for one section, so a corrected registration stops being reported. */
814
+ function recordPlacementRejection(rejection: SectionPlacementRejection): void {
815
+ const state = bus();
816
+ const index = state.placementRejections.findIndex(
817
+ (candidate) => candidate.sectionId === rejection.sectionId,
818
+ );
819
+ if (index === -1) state.placementRejections.push(rejection);
820
+ else state.placementRejections[index] = rejection;
821
+ }
822
+
823
+ function clearPlacementRejection(sectionId: string): void {
824
+ const rejections = bus().placementRejections;
825
+ for (let index = rejections.length - 1; index >= 0; index -= 1) {
826
+ if (rejections[index].sectionId === sectionId) rejections.splice(index, 1);
827
+ }
828
+ }
829
+
830
+ /** Every `placement` a registration had to refuse, for the diagnostics record. A fresh copy. */
831
+ export function getSectionPlacementRejections(): SectionPlacementRejection[] {
832
+ return bus().placementRejections.map((rejection) => ({ ...rejection }));
833
+ }
834
+
835
+ /** One section's placement as a phrase: `start`, `end`, `after "loon.news"`. */
836
+ export function requestedPlacementText(section: SidebarSection): string {
837
+ const placement = section.placement;
838
+ if (placement === undefined || placement === "end") return "end";
839
+ if (placement === "start") return "start";
840
+ if (placement !== null && typeof placement === "object" && typeof placement.after === "string") {
841
+ return `after ${JSON.stringify(placement.after)}`;
842
+ }
843
+ return describeValue(placement);
844
+ }
845
+
846
+ /** Where one landing reads as: `before todo`, `after footer`. */
847
+ export function placementLandingText(landing: Pick<SectionPlacementResolution, "part" | "side">): string {
848
+ return `${landing.side} ${landing.part}`;
849
+ }
850
+
851
+ /** What a section's rows hang off, before the rail turns it into a part. */
852
+ type PlacementAnchor =
853
+ | { kind: "start" }
854
+ | { kind: "end" }
855
+ | { kind: "part"; part: RailPart }
856
+ | { kind: "section"; id: string };
857
+
858
+ /** Group key for one anchor: tagged, because a section id may itself read `start`, `end` or `todo`. */
859
+ function anchorKey(anchor: PlacementAnchor): string {
860
+ if (anchor.kind === "part") return `part:${anchor.part}`;
861
+ if (anchor.kind === "section") return `section:${anchor.id}`;
862
+ return anchor.kind;
863
+ }
864
+
865
+ /** An anchor as a person reads it: `start`, `end`, `todo`, `"loon.news"`. */
866
+ function anchorText(anchor: PlacementAnchor): string {
867
+ if (anchor.kind === "part") return anchor.part;
868
+ if (anchor.kind === "section") return JSON.stringify(anchor.id);
869
+ return anchor.kind;
870
+ }
871
+
872
+ /** Whether a string names a native rail part. A native part wins over a section that shares the id. */
873
+ function nativePart(value: string): RailPart | undefined {
874
+ return (RAIL_PARTS as readonly string[]).includes(value) ? (value as RailPart) : undefined;
875
+ }
876
+
877
+ interface DirectPlacement {
878
+ anchor: PlacementAnchor;
879
+ reason?: string;
880
+ }
881
+
882
+ /** What one section asked for, before cycles are broken and parts are resolved. */
883
+ function directPlacement(section: SidebarSection, ids: ReadonlySet<string>): DirectPlacement {
884
+ const placement = section.placement;
885
+ if (placement === undefined || placement === "end") return { anchor: { kind: "end" } };
886
+ if (placement === "start") return { anchor: { kind: "start" } };
887
+ const problem = placementProblem(placement);
888
+ if (problem !== undefined) {
889
+ return { anchor: { kind: "end" }, reason: `its placement is malformed (${problem})` };
890
+ }
891
+ // SAFETY: `placementProblem` accepted the value, so it is the `{ after }` shape.
892
+ const target = (placement as { after: string }).after;
893
+ const part = nativePart(target);
894
+ if (part !== undefined) {
895
+ return {
896
+ anchor: { kind: "part", part },
897
+ // A section id is free to be `todo`, so one string can name a section AND a native part. The
898
+ // native part wins, and the report says why instead of leaving the author to guess.
899
+ ...(ids.has(target)
900
+ ? {
901
+ reason: `the native rail part ${JSON.stringify(target)} wins over the section with the same id`,
902
+ }
903
+ : {}),
904
+ };
905
+ }
906
+ if (ids.has(target)) return { anchor: { kind: "section", id: target } };
907
+ return {
908
+ anchor: { kind: "end" },
909
+ reason: `after ${JSON.stringify(target)} is neither a registered section nor a native rail part`,
910
+ };
911
+ }
912
+
913
+ /**
914
+ * Every section's landing, in DRAW order (S1–S3, S5): the answer both the renderer and
915
+ * the diagnostics record read, so a report and a frame cannot disagree.
916
+ *
917
+ * Pure by construction: it takes the registrations and the painted parts, and nothing else. Where a
918
+ * block goes is decided from those two lists alone, never from the order the plugins loaded in:
919
+ *
920
+ * - within one slot, sections with a finite `order` come first, ascending, then the rest, and ties
921
+ * are broken by `id` compared as UTF-16 code units (S2) — the input order does not matter;
922
+ * - `"start"` is one slot, each native part is one slot, `"end"` is one slot, and every section id
923
+ * is one slot: a section asking for `after` X joins X's slot and draws right after X (S3);
924
+ * - a slot is resolved by render, never by registration (S5): an anchor that draws nothing keeps
925
+ * its place, so hiding a section does not move its followers; a native part that is not painted
926
+ * falls forward to the next painted one, ending at `footer`; a cycle, a section after itself, or
927
+ * an anchor nobody registered falls back to `"end"` with a reason. `"end"` itself is the `footer`
928
+ * part, exactly as before this field existed: only `"start"` and a native anchor need to know
929
+ * which parts the host paints.
930
+ *
931
+ * `painted` is the parts the host actually paints this frame, in any order; it is normalized against
932
+ * `RAIL_PARTS`, so a caller cannot make the rail order depend on how it collected the list.
933
+ */
934
+ export function resolveSectionPlacements(
935
+ sections: readonly SidebarSection[],
936
+ painted: readonly RailPart[],
937
+ ): SectionPlacementResolution[] {
938
+ const paintedParts = RAIL_PARTS.filter((part) => painted.includes(part));
939
+ const firstPainted = paintedParts[0];
940
+ const ids = new Set(sections.map((section) => section.id));
941
+
942
+ const anchors = new Map<string, DirectPlacement>();
943
+ for (const section of sections) {
944
+ anchors.set(section.id, directPlacement(section, ids));
945
+ }
946
+
947
+ // A cycle is not a placement: every section IN it falls back to the end. A section leading INTO
948
+ // one resolves through its anchor, which is now the end, so it lands there too and keeps its own
949
+ // request honoured.
950
+ for (const id of cycleMembers(sections, anchors)) {
951
+ anchors.set(id, {
952
+ anchor: { kind: "end" },
953
+ reason: "it would sit after itself: a placement cycle falls back to the end",
954
+ });
955
+ }
956
+
957
+ /**
958
+ * Where one anchor's block lands. A section anchor lands where ITS anchor lands, so a chain of
959
+ * `after` requests resolves transitively; the cycles are already gone, so this terminates.
960
+ */
961
+ const landings = new Map<string, { part: RailPart; side: "before" | "after" }>();
962
+ const landingOf = (anchor: PlacementAnchor): { part: RailPart; side: "before" | "after" } => {
963
+ const key = anchorKey(anchor);
964
+ const known = landings.get(key);
965
+ if (known !== undefined) return known;
966
+ const landing = computeLanding(anchor);
967
+ landings.set(key, landing);
968
+ return landing;
969
+ };
970
+
971
+ const computeLanding = (
972
+ anchor: PlacementAnchor,
973
+ ): { part: RailPart; side: "before" | "after" } => {
974
+ if (anchor.kind === "start") {
975
+ // Before the first painted native part; with nothing painted, after the last one there is.
976
+ return firstPainted === undefined
977
+ ? { part: "footer", side: "after" }
978
+ : { part: firstPainted, side: "before" };
979
+ }
980
+ if (anchor.kind === "end") {
981
+ // After every native section, which IS the footer part: `{ after: "footer" }` and `"end"` are
982
+ // the same placement (S4), and a part that paints no frame draws none of our rows — exactly
983
+ // the rule this surface always had, so a rail whose footer is hidden loses nothing new.
984
+ return { part: "footer", side: "after" };
985
+ }
986
+ if (anchor.kind === "section") {
987
+ const target = anchors.get(anchor.id);
988
+ return target === undefined
989
+ ? { part: "footer", side: "after" }
990
+ : landingOf(target.anchor);
991
+ }
992
+ // A native part: after its own rows when it is painted, otherwise the next painted slot after
993
+ // it, ending at `footer` (S5).
994
+ if (paintedParts.includes(anchor.part)) return { part: anchor.part, side: "after" };
995
+ const at = RAIL_PARTS.indexOf(anchor.part);
996
+ const next = paintedParts.find((part) => RAIL_PARTS.indexOf(part) > at);
997
+ return { part: next ?? "footer", side: "after" };
998
+ };
999
+
1000
+ // The blocks, in the S2 order the input already carries: one list per anchor.
1001
+ const groups = new Map<string, SidebarSection[]>();
1002
+ for (const section of sections) {
1003
+ const anchor = anchors.get(section.id)?.anchor ?? { kind: "end" };
1004
+ const key = anchorKey(anchor);
1005
+ const group = groups.get(key);
1006
+ if (group === undefined) groups.set(key, [section]);
1007
+ else group.push(section);
1008
+ }
1009
+
1010
+ const out: SectionPlacementResolution[] = [];
1011
+ const visited = new Set<string>();
1012
+
1013
+ /**
1014
+ * Why a landing is not the one the request named, when the reason comes from the RENDER (a native
1015
+ * part the host does not paint, or a rail with nothing painted at all) rather than from the shape
1016
+ * of the request itself.
1017
+ */
1018
+ const landingReason = (anchor: PlacementAnchor): string | undefined => {
1019
+ if (anchor.kind === "start" && paintedParts.length === 0) {
1020
+ return "no native rail part is painted, so it landed at the end";
1021
+ }
1022
+ if (anchor.kind === "part" && !paintedParts.includes(anchor.part)) {
1023
+ return `the native rail part ${JSON.stringify(anchor.part)} is not painted; it landed ${placementLandingText(
1024
+ landingOf(anchor),
1025
+ )}`;
1026
+ }
1027
+ return undefined;
1028
+ };
1029
+
1030
+ /** Emit one block and, right after each of its sections, that section's own followers. */
1031
+ const emit = (key: string): void => {
1032
+ if (visited.has(key)) return;
1033
+ visited.add(key);
1034
+ const group = groups.get(key);
1035
+ if (group === undefined) return;
1036
+ for (const section of group) {
1037
+ const direct = anchors.get(section.id) ?? { anchor: { kind: "end" as const } };
1038
+ const landing = landingOf(direct.anchor);
1039
+ const reason = direct.reason ?? landingReason(direct.anchor);
1040
+ out.push({
1041
+ section,
1042
+ requested: requestedPlacementText(section),
1043
+ part: landing.part,
1044
+ side: landing.side,
1045
+ anchor: anchorText(direct.anchor),
1046
+ ...(reason === undefined ? {} : { reason }),
1047
+ });
1048
+ emit(`section:${section.id}`);
1049
+ }
1050
+ };
1051
+
1052
+ emit("start");
1053
+ // Every native part is emitted, painted or not: a block anchored at a part the host does not paint
1054
+ // still exists, and it draws where the landing put it. `RAIL_PARTS` order keeps two blocks that
1055
+ // land on the same rows in one deterministic order, and `end` stays last.
1056
+ for (const part of RAIL_PARTS) emit(`part:${part}`);
1057
+ emit("end");
1058
+
1059
+ return out;
1060
+ }
1061
+
1062
+ /**
1063
+ * The sections that are part of a placement cycle (A after B after A, or A after itself). Every
1064
+ * other section is left alone: a chain that merely LEADS into a cycle is resolved through it after
1065
+ * the cycle members have fallen back to the end.
1066
+ */
1067
+ function cycleMembers(
1068
+ sections: readonly SidebarSection[],
1069
+ anchors: ReadonlyMap<string, DirectPlacement>,
1070
+ ): string[] {
1071
+ const settled = new Set<string>();
1072
+ const members = new Set<string>();
1073
+ for (const section of sections) {
1074
+ const chain: string[] = [];
1075
+ let current: string | undefined = section.id;
1076
+ while (current !== undefined && !settled.has(current)) {
1077
+ const repeat = chain.indexOf(current);
1078
+ if (repeat !== -1) {
1079
+ for (const id of chain.slice(repeat)) members.add(id);
1080
+ break;
1081
+ }
1082
+ chain.push(current);
1083
+ const anchor: PlacementAnchor | undefined = anchors.get(current)?.anchor;
1084
+ current = anchor?.kind === "section" ? anchor.id : undefined;
1085
+ }
1086
+ for (const id of chain) settled.add(id);
1087
+ }
1088
+ return [...members];
1089
+ }
1090
+
1091
+ /** A section id compare: UTF-16 code units, never a locale collation (S2). */
1092
+ function compareSectionIds(a: string, b: string): number {
1093
+ if (a === b) return 0;
1094
+ return a < b ? -1 : 1;
1095
+ }
1096
+
1097
+ /**
1098
+ * The rendering order of every registered section: those with an `order` first, ascending, then the
1099
+ * rest, and every tie broken by `id` compared as UTF-16 code units (S2).
1100
+ *
1101
+ * The registration index is deliberately NOT part of the sort. The same set of registrations has to
1102
+ * draw the same rail in any load order — a user's sidebar must not depend on which plugin Pi
1103
+ * happened to load first — so equal values are resolved by the one key that is identity. Both halves
1104
+ * are computed from the registration list, never from `Map` iteration, and the array is a fresh copy,
1105
+ * so a fan-out that iterates it sees a stable list even if a section registers or disposes
1106
+ * mid-iteration.
1107
+ */
1108
+ export function snapshotSections(): SidebarSection[] {
1109
+ const ordered: Array<{ section: SidebarSection; order: number }> = [];
1110
+ const rest: SidebarSection[] = [];
1111
+
1112
+ for (const entry of bus().sections) {
1113
+ const order = sortableSectionOrder(entry.section);
1114
+ if (order === undefined) rest.push(entry.section);
1115
+ else ordered.push({ section: entry.section, order });
1116
+ }
1117
+
1118
+ ordered.sort((a, b) => a.order - b.order || compareSectionIds(a.section.id, b.section.id));
1119
+ rest.sort((a, b) => compareSectionIds(a.id, b.id));
1120
+ return [...ordered.map((entry) => entry.section), ...rest];
1121
+ }
1122
+
1123
+ /** A section whose `order` is a usable sort key; `NaN`, `Infinity` and a missing value are not. */
1124
+ function sortableSectionOrder(section: SidebarSection): number | undefined {
1125
+ return typeof section.order === "number" && Number.isFinite(section.order)
1126
+ ? section.order
1127
+ : undefined;
1128
+ }
1129
+
1130
+ /**
1131
+ * Test-only seam for the section list only, so a provider test and a section test do not clear
1132
+ * each other's registrations. Like `resetBusForTests`, it is deliberately not re-exported from
1133
+ * `src/index.ts`. The placement rejections go with it: they describe the same registrations.
1134
+ */
1135
+ export function resetSectionsForTests(): void {
1136
+ bus().sections.length = 0;
1137
+ bus().placementRejections.length = 0;
1138
+ }
1139
+
1140
+ /**
1141
+ * A card style's `order`, when it has one that can be sorted on. `NaN`, `Infinity` and a missing
1142
+ * value are not sort keys: a style with one of those keeps its registration position.
1143
+ */
1144
+ function sortableCardStyleOrder(style: CardStyleRegistration): number | undefined {
1145
+ return typeof style.order === "number" && Number.isFinite(style.order) ? style.order : undefined;
1146
+ }
1147
+
1148
+ /** A style's `frame` must be exactly what the transformer calls, or the first render would throw. */
1149
+ function assertCardFrame(id: string, frame: unknown): void {
1150
+ if (frame === null || typeof frame !== "object" || Array.isArray(frame)) {
1151
+ throw new Error(
1152
+ `gentle-shell-bridge: invalid card style ${JSON.stringify(id)}: frame must be an object ` +
1153
+ "with top, line and bottom functions.",
1154
+ );
1155
+ }
1156
+ for (const member of ["top", "line", "bottom"] as const) {
1157
+ if (typeof (frame as Record<string, unknown>)[member] !== "function") {
1158
+ throw new Error(
1159
+ `gentle-shell-bridge: invalid card style ${JSON.stringify(id)}: frame.${member} must be a ` +
1160
+ "function. A style draws chrome and nothing else (S2).",
1161
+ );
1162
+ }
1163
+ }
1164
+ }
1165
+
1166
+ function assertCardStyleLabel(id: string, label: unknown): void {
1167
+ if (typeof label !== "string" || label.trim() === "") {
1168
+ throw new Error(
1169
+ `gentle-shell-bridge: invalid card style ${JSON.stringify(id)}: label must be a non-empty ` +
1170
+ "string. It is the text the user reads on the Card style line, so keep it short.",
1171
+ );
1172
+ }
1173
+ }
1174
+
1175
+ /**
1176
+ * The label is what the user sees, so two styles showing the same text cannot be told apart (S13).
1177
+ *
1178
+ * Rejected before anything is stored: an equal label of another REGISTERED style (the same id
1179
+ * re-registering keeps its own label, because it replaces itself) and any of the host's own values,
1180
+ * which the host renders verbatim on the same line. The comparison is exact — case-sensitive, the
1181
+ * way the host displays the string — so `cute` and `Cute` are two different visible values.
1182
+ */
1183
+ function assertCardStyleLabelIsDistinct(style: CardStyleRegistration): void {
1184
+ if ((HOST_CARD_STYLE_VALUES as readonly string[]).includes(style.label)) {
1185
+ throw new Error(
1186
+ `gentle-shell-bridge: invalid card style label ${JSON.stringify(style.label)} for ` +
1187
+ `${JSON.stringify(style.id)}: it is one of the host's own values ` +
1188
+ `(${HOST_CARD_STYLE_VALUES.join(", ")}), so the Card style line would show it twice. ` +
1189
+ "Pick a distinct label.",
1190
+ );
1191
+ }
1192
+ const clash = snapshotCardStyles().find(
1193
+ (candidate) => candidate.id !== style.id && candidate.label === style.label,
1194
+ );
1195
+ if (clash !== undefined) {
1196
+ throw new Error(
1197
+ `gentle-shell-bridge: invalid card style label ${JSON.stringify(style.label)} for ` +
1198
+ `${JSON.stringify(style.id)}: it is already used by ${JSON.stringify(clash.id)}. Two values ` +
1199
+ "reading the same cannot be told apart on the Card style line. Pick a distinct label.",
1200
+ );
1201
+ }
1202
+ }
1203
+
1204
+ /**
1205
+ * Register a card style and return a disposer that removes exactly that style (S1, S12).
1206
+ *
1207
+ * Same entry discipline as providers and sections, because a plugin author should not have to learn
1208
+ * two:
1209
+ *
1210
+ * - A second registration with an existing `id` replaces the previous one IN PLACE, so the style
1211
+ * keeps the position its registration earned and there is still exactly one value on the line.
1212
+ * Two plugins cannot both own `loon.cute`: the later registration wins.
1213
+ * - The returned disposer removes only the registration it created: after a same-id replacement the
1214
+ * replaced style's disposer is a no-op instead of removing the replacement, and calling a
1215
+ * disposer twice does nothing the second time.
1216
+ * - Validation happens BEFORE anything is stored (id, label, both frames), so a rejected style
1217
+ * never half-registers and never reaches a menu build.
1218
+ */
1219
+ export function registerCardStyle(style: CardStyleRegistration): () => void {
1220
+ return attributeRegistration("card style", style, "card style", () =>
1221
+ registerCardStyleStored(style),
1222
+ );
1223
+ }
1224
+
1225
+ function registerCardStyleStored(style: CardStyleRegistration): () => void {
1226
+ assertRegistrationId("card style", style.id);
1227
+ if (RESERVED_CARD_STYLE_IDS.has(style.id)) {
1228
+ throw new Error(
1229
+ `gentle-shell-bridge: invalid card style id ${JSON.stringify(style.id)}: it is already a ` +
1230
+ "value of the Card style line (the host's own neon/float, or the bridge's native), so the " +
1231
+ "line would show the same value twice. Pick an id of your own, e.g. \"loon.cute\".",
1232
+ );
1233
+ }
1234
+ assertCardStyleLabel(style.id, style.label);
1235
+ assertCardStyleLabelIsDistinct(style);
1236
+ assertRowLabel("card style", style.id, style.rowLabel);
1237
+ // Same rule, same place in the sequence: a row label that breaks the row-name shape is rejected
1238
+ // before the style is stored, and the diagnostics record reports the string and the rule (N8).
1239
+ if (rejectRowName("card style", style.id, "row label", cardStyleRowLabelText(style))) {
1240
+ return () => {};
1241
+ }
1242
+ clearRowNameRejections("card style", style.id);
1243
+ assertCardFrame(style.id, style.frame);
1244
+
1245
+ const state = bus();
1246
+ const entry: CardStyleEntry = { style };
1247
+ const index = state.cardStyles.findIndex((candidate) => candidate.style.id === style.id);
1248
+ if (index === -1) state.cardStyles.push(entry);
1249
+ else state.cardStyles[index] = entry;
1250
+
1251
+ let disposed = false;
1252
+ return () => {
1253
+ if (disposed) return;
1254
+ disposed = true;
1255
+ const current = state.cardStyles.indexOf(entry);
1256
+ if (current !== -1) state.cardStyles.splice(current, 1);
1257
+ };
1258
+ }
1259
+
1260
+ /**
1261
+ * Every registered style, in the order its values appear on the line (S12): styles with an `order`
1262
+ * first, ascending, then those without, in registration order.
1263
+ *
1264
+ * Both halves are computed from the registration list, never from `Map` iteration: the sort is on
1265
+ * explicit keys with the registration index as the tiebreak, so equal `order`s and unordered styles
1266
+ * are deterministic across sessions and across package copies. The array is a fresh copy, so a
1267
+ * caller cannot mutate the registry and a fan-out iterating it sees a stable list even if a style
1268
+ * registers or disposes mid-iteration.
1269
+ */
1270
+ export function snapshotCardStyles(): CardStyleRegistration[] {
1271
+ const ordered: Array<{ style: CardStyleRegistration; order: number; index: number }> = [];
1272
+ const rest: CardStyleRegistration[] = [];
1273
+
1274
+ bus().cardStyles.forEach((entry, index) => {
1275
+ const order = sortableCardStyleOrder(entry.style);
1276
+ if (order === undefined) rest.push(entry.style);
1277
+ else ordered.push({ style: entry.style, order, index });
1278
+ });
1279
+
1280
+ ordered.sort((a, b) => a.order - b.order || a.index - b.index);
1281
+ return [...ordered.map((entry) => entry.style), ...rest];
1282
+ }
1283
+
1284
+ /**
1285
+ * Test-only seam for the card style list only, so a style test and a section test do not clear each
1286
+ * other's registrations. Like `resetBusForTests`, it is deliberately not re-exported from
1287
+ * `src/index.ts`.
1288
+ */
1289
+ export function resetCardStylesForTests(): void {
1290
+ bus().cardStyles.length = 0;
1291
+ }
1292
+
1293
+ /**
1294
+ * A transform's `order`, when it has one that can be sorted on. `NaN`, `Infinity` and a missing
1295
+ * value are not sort keys: a transform with one of those keeps its registration position.
1296
+ */
1297
+ function sortableTransformOrder(transform: TranscriptTransform): number | undefined {
1298
+ return typeof transform.order === "number" && Number.isFinite(transform.order)
1299
+ ? transform.order
1300
+ : undefined;
1301
+ }
1302
+
1303
+ /**
1304
+ * The transform member must be exactly what the pipeline calls, checked before anything is stored:
1305
+ * a registration the first frame would throw on is a plugin bug, not a frame's problem.
1306
+ */
1307
+ function assertTransformFunction(id: string, transform: unknown): void {
1308
+ if (typeof transform !== "function") {
1309
+ throw new Error(
1310
+ `gentle-shell-bridge: invalid transform ${JSON.stringify(id)}: transform must be a function `
1311
+ + `of (lines, ctx) that returns the lines to draw. A transform rewrites rows; the bridge `
1312
+ + `clips them, isolates its throw and records it in the diagnostics record (S1).`,
1313
+ );
1314
+ }
1315
+ }
1316
+
1317
+ /**
1318
+ * Register a transcript transform and return a disposer that removes exactly that transform (S1).
1319
+ *
1320
+ * Same entry discipline as providers, sections and card styles, because a plugin author should not
1321
+ * have to learn two:
1322
+ *
1323
+ * - A second registration with an existing `id` replaces the previous one IN PLACE, so the
1324
+ * transform keeps the position its registration earned (ordering is computed in
1325
+ * `snapshotTransforms`, so a replacement that changes `order` moves the transform on the next
1326
+ * read). Two plugins cannot both own `loon.restyle`: the later registration wins.
1327
+ * - The returned disposer removes only the registration it created: after a same-id replacement the
1328
+ * replaced transform's disposer is a no-op instead of removing the replacement, and calling a
1329
+ * disposer twice does nothing the second time.
1330
+ * - Validation happens BEFORE anything is stored (id, `transform`), so a rejected transform never
1331
+ * half-registers and never reaches a frame.
1332
+ */
1333
+ export function registerTransform(transform: TranscriptTransform): () => void {
1334
+ return attributeRegistration("transform", transform, undefined, () =>
1335
+ registerTransformStored(transform),
1336
+ );
1337
+ }
1338
+
1339
+ function registerTransformStored(transform: TranscriptTransform): () => void {
1340
+ assertRegistrationId("transform", transform.id);
1341
+ assertTransformFunction(transform.id, transform.transform);
1342
+
1343
+ const state = bus();
1344
+ const entry: TransformEntry = { transform };
1345
+ const index = state.transforms.findIndex((candidate) => candidate.transform.id === transform.id);
1346
+ if (index === -1) state.transforms.push(entry);
1347
+ else state.transforms[index] = entry;
1348
+
1349
+ let disposed = false;
1350
+ return () => {
1351
+ if (disposed) return;
1352
+ disposed = true;
1353
+ const current = state.transforms.indexOf(entry);
1354
+ if (current !== -1) state.transforms.splice(current, 1);
1355
+ };
1356
+ }
1357
+
1358
+ /**
1359
+ * Every registered transform, in pipeline order (S2): transforms with an `order` first, ascending,
1360
+ * then those without, in registration order.
1361
+ *
1362
+ * Both halves are computed from the registration list, never from `Map` iteration: the sort is on
1363
+ * explicit keys with the registration index as the tiebreak, so equal `order`s and unordered
1364
+ * transforms are deterministic across sessions and across package copies. The array is a fresh
1365
+ * copy, so a frame iterating it sees a stable list even if a transform registers or disposes
1366
+ * mid-frame.
1367
+ */
1368
+ export function snapshotTransforms(): TranscriptTransform[] {
1369
+ const ordered: Array<{ transform: TranscriptTransform; order: number; index: number }> = [];
1370
+ const rest: TranscriptTransform[] = [];
1371
+
1372
+ bus().transforms.forEach((entry, index) => {
1373
+ const order = sortableTransformOrder(entry.transform);
1374
+ if (order === undefined) rest.push(entry.transform);
1375
+ else ordered.push({ transform: entry.transform, order, index });
1376
+ });
1377
+
1378
+ ordered.sort((a, b) => a.order - b.order || a.index - b.index);
1379
+ return [...ordered.map((entry) => entry.transform), ...rest];
1380
+ }
1381
+
1382
+ /**
1383
+ * Test-only seam for the transform list only, so a transform test and a section test do not clear
1384
+ * each other's registrations. Like `resetBusForTests`, it is deliberately not re-exported from
1385
+ * `src/index.ts`.
1386
+ */
1387
+ export function resetTransformsForTests(): void {
1388
+ bus().transforms.length = 0;
1389
+ }