@nodaro/shared 3.20.0 → 3.23.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 (86) hide show
  1. package/dist/index.cjs +2287 -195
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +1938 -82
  4. package/dist/index.d.ts +1938 -82
  5. package/dist/index.js +2119 -196
  6. package/dist/index.js.map +1 -1
  7. package/package.json +1 -1
  8. package/src/__tests__/add-captions-plan.test.ts +33 -0
  9. package/src/__tests__/caption-plan-parse.test.ts +23 -0
  10. package/src/__tests__/caption-segment-schema.test.ts +30 -0
  11. package/src/__tests__/collections.test.ts +253 -0
  12. package/src/__tests__/default-tts-provider.test.ts +46 -0
  13. package/src/__tests__/dialogue-capabilities.test.ts +157 -0
  14. package/src/__tests__/edit-plan-review.test.ts +70 -0
  15. package/src/__tests__/edl-clocks.test.ts +97 -0
  16. package/src/__tests__/edl.test.ts +34 -0
  17. package/src/__tests__/execution-outcome.test.ts +44 -0
  18. package/src/__tests__/fan-out-meta.test.ts +23 -0
  19. package/src/__tests__/fan-out-rows.test.ts +36 -0
  20. package/src/__tests__/fan-out-url-item.test.ts +44 -0
  21. package/src/__tests__/fixtures/speaker-tracks.fixtures.json +622 -0
  22. package/src/__tests__/input-field-extra-keys.test.ts +34 -0
  23. package/src/__tests__/list-consumers-fan-in.test.ts +40 -0
  24. package/src/__tests__/model-tree.test.ts +7 -0
  25. package/src/__tests__/node-pass-through.test.ts +23 -0
  26. package/src/__tests__/node-runtime-keys.test.ts +1 -0
  27. package/src/__tests__/picker-restrictions.test.ts +36 -0
  28. package/src/__tests__/preview-gate.test.ts +305 -0
  29. package/src/__tests__/render-basis.test.ts +176 -0
  30. package/src/__tests__/render-nodes.test.ts +73 -0
  31. package/src/__tests__/render-output.test.ts +392 -0
  32. package/src/__tests__/run-continuation.test.ts +32 -0
  33. package/src/__tests__/speaker-tracks.test.ts +474 -0
  34. package/src/__tests__/speech-pricing.test.ts +69 -0
  35. package/src/__tests__/telegram-channel.test.ts +91 -0
  36. package/src/__tests__/tts-capabilities.test.ts +83 -5
  37. package/src/__tests__/tts-neighbour-text.test.ts +19 -0
  38. package/src/__tests__/ugc-call-body.test.ts +38 -0
  39. package/src/__tests__/ugc-run-state.test.ts +68 -0
  40. package/src/__tests__/video-character-refs.test.ts +213 -0
  41. package/src/__tests__/video-overlay-layer-plan.test.ts +94 -0
  42. package/src/add-captions-plan.ts +50 -0
  43. package/src/caption-plan.ts +45 -0
  44. package/src/caption-segment-schema.ts +82 -0
  45. package/src/collections.ts +462 -0
  46. package/src/competitors.ts +77 -0
  47. package/src/credit-estimators/index.ts +9 -0
  48. package/src/credit-estimators/speech.ts +51 -0
  49. package/src/dialogue-capabilities.ts +48 -0
  50. package/src/edit-plan-contract.ts +20 -9
  51. package/src/edit-plan-review.ts +40 -1
  52. package/src/edl.ts +27 -1
  53. package/src/execution-outcome.ts +41 -0
  54. package/src/fan-out-meta.ts +23 -0
  55. package/src/fan-out-rows.ts +74 -5
  56. package/src/gemini-omni-voices.ts +59 -0
  57. package/src/handle-aliases.ts +295 -0
  58. package/src/i18n/camera-motions.pt-BR.ts +14 -14
  59. package/src/i18n/transitions.pt-BR.ts +13 -13
  60. package/src/index.ts +180 -1
  61. package/src/model-catalog.ts +125 -15
  62. package/src/model-constants.ts +37 -4
  63. package/src/model-tree.ts +5 -1
  64. package/src/node-execution-state.ts +13 -0
  65. package/src/node-mappable-fields.ts +7 -1
  66. package/src/node-pass-through.ts +37 -0
  67. package/src/node-runtime-keys.ts +14 -0
  68. package/src/picker-restrictions.ts +49 -0
  69. package/src/presentation-types.ts +26 -2
  70. package/src/presentation-utils.ts +25 -7
  71. package/src/preview-gate.ts +279 -0
  72. package/src/producer-types.ts +58 -0
  73. package/src/render-final.ts +20 -0
  74. package/src/render-nodes.ts +92 -0
  75. package/src/render-output.ts +565 -0
  76. package/src/run-continuation.ts +39 -0
  77. package/src/speaker-tracks.ts +638 -0
  78. package/src/telegram-channel.ts +140 -0
  79. package/src/transcribe-preflight.ts +8 -4
  80. package/src/tts-capabilities.ts +19 -5
  81. package/src/tts-neighbour-text.ts +46 -0
  82. package/src/ugc-call-body.ts +86 -0
  83. package/src/ugc-run-state.ts +64 -0
  84. package/src/video-character-refs.ts +233 -0
  85. package/src/video-overlay.ts +78 -21
  86. package/src/voices.ts +11 -7
@@ -0,0 +1,474 @@
1
+ import { readFileSync } from "node:fs"
2
+ import { describe, it, expect } from "vitest"
3
+ import {
4
+ SPEAKER_TRACKS_VERSION,
5
+ SPEAKER_TRACK_ATTRIBUTION_METHODS,
6
+ SPEAKER_TRACKS_MAX_BOXES_PER_SOURCE,
7
+ SPEAKER_TRACKS_MAX_BYTES,
8
+ normalizeSpeakerTracks,
9
+ validateSpeakerTracks,
10
+ describeSpeakerTracks,
11
+ normalizeSpeakerTrackSetDescriptor,
12
+ validateSpeakerTrackSetDescriptor,
13
+ edlSpeakerSpace,
14
+ type SpeakerTrackSet,
15
+ } from "../speaker-tracks.js"
16
+ import { normalizeEdl, remapMsThroughEdl, type Edl } from "../edl.js"
17
+ import * as shared from "../index.js"
18
+
19
+ interface Fixture {
20
+ readonly name: string
21
+ readonly edl?: string
22
+ readonly edls?: readonly string[]
23
+ readonly input: unknown
24
+ /** Validate `input` exactly as given, without normalizing it first. */
25
+ readonly validateInput?: boolean
26
+ readonly normalized?: unknown
27
+ readonly validation: { readonly ok: boolean; readonly issues: readonly string[]; readonly warnings: readonly string[] }
28
+ }
29
+ const FIXTURES = JSON.parse(
30
+ readFileSync(new URL("./fixtures/speaker-tracks.fixtures.json", import.meta.url), "utf8"),
31
+ ) as { edls: Record<string, unknown>; cases: Fixture[] }
32
+
33
+ function fixtureEdl(f: Fixture): Edl | Edl[] | undefined {
34
+ if (f.edls) return f.edls.map((k) => normalizeEdl(FIXTURES.edls[k]))
35
+ if (f.edl) return normalizeEdl(FIXTURES.edls[f.edl])
36
+ return undefined
37
+ }
38
+
39
+ // ─────────────────────────────────────────────────────────────────────────
40
+ // A seeded generator (no property-testing dependency): deterministic, so a
41
+ // failure reproduces from its seed.
42
+ // ─────────────────────────────────────────────────────────────────────────
43
+ function rng(seed: number): () => number {
44
+ let s = seed >>> 0
45
+ return () => {
46
+ s = (s + 0x6d2b79f5) >>> 0
47
+ let t = s
48
+ t = Math.imul(t ^ (t >>> 15), t | 1)
49
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
50
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
51
+ }
52
+ }
53
+
54
+ /** Arbitrary, often malformed, input: wrong types, out-of-range numbers,
55
+ * unsorted boxes, fractional ms, extra keys. */
56
+ function garbageSet(r: () => number): unknown {
57
+ const pick = <T,>(xs: readonly T[]): T => xs[Math.floor(r() * xs.length)]
58
+ const anyNum = () => pick([r() * 2 - 0.5, r() * 100000, -r() * 1000, NaN, Infinity, Math.round(r() * 9000) + r()])
59
+ const anyVal = () => pick<unknown>([anyNum(), "1", null, undefined, {}, [], true])
60
+ const box = () =>
61
+ r() < 0.15
62
+ ? anyVal()
63
+ : { ms: r() < 0.9 ? anyNum() : anyVal(), x: anyNum(), y: anyNum(), w: anyNum(), h: anyNum(), ...(r() < 0.5 ? { score: anyNum() } : {}), junk: anyVal() }
64
+ const track = () => ({
65
+ ...(r() < 0.8 ? { id: pick(["a", "b", "", 7, "wide/t1"]) } : {}),
66
+ ...(r() < 0.6 ? { speaker: pick(["Host", "Guest", "", 3]) } : {}),
67
+ ...(r() < 0.6 ? { attribution: pick<unknown>([{ method: pick(["manual", "region", "x", 1]), confidence: anyNum() }, null, "manual"]) } : {}),
68
+ boxes: r() < 0.9 ? Array.from({ length: Math.floor(r() * 6) }, box) : anyVal(),
69
+ })
70
+ const source = () => ({
71
+ sourceId: pick<unknown>(["wide", "camA", "", 5]),
72
+ ...(r() < 0.9 ? { clock: pick(["source", "source", "master"]) } : {}),
73
+ frame: r() < 0.8 ? { w: anyNum(), h: anyNum() } : anyVal(),
74
+ sampledSpans: r() < 0.9 ? Array.from({ length: Math.floor(r() * 4) }, () => ({ startMs: anyNum(), endMs: anyNum() })) : anyVal(),
75
+ tracks: r() < 0.9 ? Array.from({ length: Math.floor(r() * 4) }, track) : anyVal(),
76
+ ...(r() < 0.5 ? { cuts: Array.from({ length: Math.floor(r() * 3) }, anyVal) } : {}),
77
+ })
78
+ if (r() < 0.05) return anyVal()
79
+ return {
80
+ version: pick<unknown>([1, 1, 2, "1"]),
81
+ sampleFps: anyNum(),
82
+ detector: r() < 0.8 ? { id: "example:face-detector", version: anyVal() } : anyVal(),
83
+ sources: r() < 0.9 ? Array.from({ length: Math.floor(r() * 3) }, source) : anyVal(),
84
+ }
85
+ }
86
+
87
+ const round3 = (v: number): number => Math.round(v * 1000) / 1000
88
+
89
+ /** A well-formed set: every box inside a sampled span, strictly increasing,
90
+ * in-frame; tracks never straddle a cut. */
91
+ function validSet(r: () => number): SpeakerTrackSet {
92
+ const sources = (["wide", "camA", "camB"] as const).slice(0, 1 + Math.floor(r() * 3)).map((sourceId) => {
93
+ const spanStart = Math.floor(r() * 5000)
94
+ const spanEnd = spanStart + 2000 + Math.floor(r() * 20000)
95
+ const tracks = Array.from({ length: Math.floor(r() * 3) }, (_, k) => {
96
+ const boxes: { ms: number; x: number; y: number; w: number; h: number; score?: number }[] = []
97
+ let ms = spanStart + Math.floor(r() * 500)
98
+ while (ms < spanEnd && boxes.length < 12) {
99
+ // Rounded, with slack to the frame edge, so a well-formed box never
100
+ // meets the normalizer's fit by a float ulp.
101
+ const w = round3(0.05 + r() * 0.3)
102
+ const h = round3(0.05 + r() * 0.3)
103
+ boxes.push({ ms, x: round3(r() * (1 - w - 0.01)), y: round3(r() * (1 - h - 0.01)), w, h, ...(r() < 0.5 ? { score: round3(r()) } : {}) })
104
+ ms += 500
105
+ }
106
+ return { id: `${sourceId}/t${k + 1}`, ...(r() < 0.5 ? { speaker: "Host" } : {}), boxes }
107
+ })
108
+ return {
109
+ sourceId,
110
+ clock: "source" as const,
111
+ frame: { w: 1920, h: 1080 },
112
+ sampledSpans: [{ startMs: spanStart, endMs: spanEnd }],
113
+ tracks,
114
+ }
115
+ })
116
+ return { version: 1, sampleFps: 2, detector: { id: "example:face-detector" }, sources }
117
+ }
118
+
119
+ const PROPERTY_RUNS = 300
120
+
121
+ // ─────────────────────────────────────────────────────────────────────────
122
+ // The shared fixtures
123
+ // ─────────────────────────────────────────────────────────────────────────
124
+ describe("speaker-tracks fixtures (plain data any implementation must agree on)", () => {
125
+ for (const f of FIXTURES.cases) {
126
+ it(f.name, () => {
127
+ const n = normalizeSpeakerTracks(f.input)
128
+ if (f.normalized !== undefined) expect(n).toEqual(f.normalized)
129
+ const v = validateSpeakerTracks(f.validateInput ? (f.input as SpeakerTrackSet) : n, { edl: fixtureEdl(f) })
130
+ expect(v.issues).toEqual(f.validation.issues)
131
+ expect(v.warnings).toEqual(f.validation.warnings)
132
+ expect(v.ok).toBe(f.validation.ok)
133
+ })
134
+ }
135
+
136
+ it("every fixture's normalized form survives a JSON round trip unchanged", () => {
137
+ for (const f of FIXTURES.cases) {
138
+ const n = normalizeSpeakerTracks(f.input)
139
+ expect(JSON.parse(JSON.stringify(n))).toEqual(n)
140
+ }
141
+ })
142
+ })
143
+
144
+ // ─────────────────────────────────────────────────────────────────────────
145
+ // Properties
146
+ // ─────────────────────────────────────────────────────────────────────────
147
+ describe("normalizeSpeakerTracks — properties", () => {
148
+ it("never throws, and is idempotent, on arbitrary input", () => {
149
+ for (let seed = 1; seed <= PROPERTY_RUNS; seed++) {
150
+ const input = garbageSet(rng(seed))
151
+ const once = normalizeSpeakerTracks(input)
152
+ expect(normalizeSpeakerTracks(once), `seed ${seed}`).toEqual(once)
153
+ expect(normalizeSpeakerTracks(JSON.parse(JSON.stringify(once))), `seed ${seed}`).toEqual(once)
154
+ expect(() => validateSpeakerTracks(once), `seed ${seed}`).not.toThrow()
155
+ }
156
+ })
157
+
158
+ it("cropped, never moved: a box keeps its exact geometry when in frame, and otherwise becomes its visible part", () => {
159
+ const fit = (b: { x: number; y: number; w: number; h: number }) =>
160
+ normalizeSpeakerTracks({
161
+ version: 1, sampleFps: 2, detector: { id: "d" },
162
+ sources: [{ sourceId: "wide", clock: "source", frame: { w: 1920, h: 1080 }, sampledSpans: [{ startMs: 0, endMs: 1000 }], tracks: [{ id: "t", boxes: [{ ms: 0, ...b }] }] }],
163
+ }).sources[0].tracks[0].boxes[0]
164
+ // A left or top overhang is cropped exactly like a right or bottom one.
165
+ expect(fit({ x: -0.1, y: 0.2, w: 0.3, h: 0.2 })).toEqual({ ms: 0, x: 0, y: 0.2, w: -0.1 + 0.3, h: 0.2 })
166
+ expect(fit({ x: 0.2, y: -0.1, w: 0.2, h: 0.3 })).toEqual({ ms: 0, x: 0.2, y: 0, w: 0.2, h: -0.1 + 0.3 })
167
+ expect(fit({ x: 0.8, y: 0.2, w: 0.3, h: 0.2 })).toEqual({ ms: 0, x: 0.8, y: 0.2, w: 1 - 0.8, h: 0.2 })
168
+ // A box entirely outside the frame is no face in it.
169
+ expect(fit({ x: 0.2, y: -0.5, w: 0.2, h: 0.4 })).toBeUndefined()
170
+ expect(fit({ x: 1.2, y: 0.2, w: 0.2, h: 0.2 })).toBeUndefined()
171
+ expect(fit({ x: -0.3, y: 0.2, w: 0.3, h: 0.2 })).toBeUndefined()
172
+
173
+ const axis = (p: number, s: number, op: number, os: number, seed: number) => {
174
+ const lo = Math.max(p, 0)
175
+ const hi = Math.min(p + s, 1)
176
+ expect(op, `seed ${seed}`).toBeCloseTo(lo, 12)
177
+ expect(op + os, `seed ${seed}`).toBeCloseTo(hi, 12)
178
+ // The centre moves only when the box was clipped, and only toward the visible part.
179
+ const c = p + s / 2
180
+ const oc = op + os / 2
181
+ if (p >= 0 && p + s <= 1) expect(oc, `seed ${seed}`).toBe(c)
182
+ else if (p < 0 && p + s <= 1) expect(oc, `seed ${seed}`).toBeGreaterThan(c)
183
+ else if (p >= 0 && p + s > 1) expect(oc, `seed ${seed}`).toBeLessThan(c)
184
+ }
185
+ for (let seed = 1; seed <= PROPERTY_RUNS * 10; seed++) {
186
+ const r = rng(seed)
187
+ const raw = { x: round3(r() * 1.6 - 0.4), y: round3(r() * 1.6 - 0.4), w: round3(0.01 + r() * 0.6), h: round3(0.01 + r() * 0.6) }
188
+ const out = fit(raw)
189
+ const visible = raw.x < 1 && raw.x + raw.w > 0 && raw.y < 1 && raw.y + raw.h > 0
190
+ if (!visible) {
191
+ expect(out, `seed ${seed}`).toBeUndefined()
192
+ continue
193
+ }
194
+ expect(out, `seed ${seed}`).toBeDefined()
195
+ const inFrame = raw.x >= 0 && raw.x + raw.w <= 1 && raw.y >= 0 && raw.y + raw.h <= 1
196
+ if (inFrame) expect(out, `seed ${seed}`).toEqual({ ms: 0, ...raw })
197
+ axis(raw.x, raw.w, out!.x, out!.w, seed)
198
+ axis(raw.y, raw.h, out!.y, out!.h, seed)
199
+ }
200
+ })
201
+
202
+ it("monotonic: every track's boxes come out sorted by time", () => {
203
+ for (let seed = 1; seed <= PROPERTY_RUNS; seed++) {
204
+ for (const s of normalizeSpeakerTracks(garbageSet(rng(seed))).sources) {
205
+ for (const t of s.tracks) {
206
+ for (let i = 1; i < t.boxes.length; i++) expect(t.boxes[i].ms, `seed ${seed}`).toBeGreaterThanOrEqual(t.boxes[i - 1].ms)
207
+ }
208
+ }
209
+ }
210
+ })
211
+
212
+ it("clamped: every box is a finite in-frame region and every score/confidence is 0..1", () => {
213
+ for (let seed = 1; seed <= PROPERTY_RUNS; seed++) {
214
+ for (const s of normalizeSpeakerTracks(garbageSet(rng(seed))).sources) {
215
+ for (const t of s.tracks) {
216
+ if (t.attribution) expect(t.attribution.confidence >= 0 && t.attribution.confidence <= 1, `seed ${seed}`).toBe(true)
217
+ for (const b of t.boxes) {
218
+ for (const v of [b.x, b.y, b.w, b.h]) expect(Number.isFinite(v) && v >= 0 && v <= 1, `seed ${seed}`).toBe(true)
219
+ expect(b.w > 0 && b.h > 0, `seed ${seed}`).toBe(true)
220
+ expect(b.x + b.w <= 1 + 1e-9 && b.y + b.h <= 1 + 1e-9, `seed ${seed}`).toBe(true)
221
+ if (b.score !== undefined) expect(b.score >= 0 && b.score <= 1, `seed ${seed}`).toBe(true)
222
+ }
223
+ }
224
+ }
225
+ }
226
+ })
227
+
228
+ it("ms-only: every time is an integer and is never rescaled (no seconds→ms guessing)", () => {
229
+ for (let seed = 1; seed <= PROPERTY_RUNS; seed++) {
230
+ const n = normalizeSpeakerTracks(garbageSet(rng(seed)))
231
+ for (const s of n.sources) {
232
+ for (const sp of s.sampledSpans) expect(Number.isInteger(sp.startMs) && Number.isInteger(sp.endMs), `seed ${seed}`).toBe(true)
233
+ for (const c of s.cuts ?? []) expect(Number.isInteger(c), `seed ${seed}`).toBe(true)
234
+ for (const t of s.tracks) for (const b of t.boxes) expect(Number.isInteger(b.ms), `seed ${seed}`).toBe(true)
235
+ }
236
+ }
237
+ // A set written in seconds stays in seconds (and then fails validation
238
+ // against its spans) — it is never multiplied by 1000.
239
+ const secs = normalizeSpeakerTracks({
240
+ version: 1, sampleFps: 2, detector: { id: "d" },
241
+ sources: [{ sourceId: "wide", clock: "source", frame: { w: 1920, h: 1080 }, sampledSpans: [{ startMs: 0, endMs: 60 }], tracks: [{ id: "t", boxes: [{ ms: 12, x: 0.1, y: 0.1, w: 0.2, h: 0.2 }] }] }],
242
+ })
243
+ expect(secs.sources[0].tracks[0].boxes[0].ms).toBe(12)
244
+ expect(secs.sources[0].sampledSpans[0]).toEqual({ startMs: 0, endMs: 60 })
245
+ })
246
+
247
+ it("sampled spans come out sorted, positive and non-overlapping; cuts sorted and unique", () => {
248
+ for (let seed = 1; seed <= PROPERTY_RUNS; seed++) {
249
+ for (const s of normalizeSpeakerTracks(garbageSet(rng(seed))).sources) {
250
+ s.sampledSpans.forEach((sp, i) => {
251
+ expect(sp.endMs, `seed ${seed}`).toBeGreaterThan(sp.startMs)
252
+ if (i > 0) expect(sp.startMs, `seed ${seed}`).toBeGreaterThan(s.sampledSpans[i - 1].endMs)
253
+ })
254
+ const cuts = s.cuts ?? []
255
+ for (let i = 1; i < cuts.length; i++) expect(cuts[i], `seed ${seed}`).toBeGreaterThan(cuts[i - 1])
256
+ }
257
+ }
258
+ })
259
+
260
+ it("a generated well-formed set normalizes to itself and validates clean", () => {
261
+ for (let seed = 1; seed <= PROPERTY_RUNS; seed++) {
262
+ const set = validSet(rng(seed))
263
+ const n = normalizeSpeakerTracks(set)
264
+ expect(n, `seed ${seed}`).toEqual(set)
265
+ const v = validateSpeakerTracks(n)
266
+ expect(v.issues, `seed ${seed}`).toEqual([])
267
+ }
268
+ })
269
+ })
270
+
271
+ describe("offset mapping (D19: masterMs = sourceMs + offsetMs) — boxes stay on the source clock", () => {
272
+ it("a box on a source with a ± offset lands at sourceMs + offsetMs on the master clock, and nowhere when that instant was dropped", () => {
273
+ for (let seed = 1; seed <= PROPERTY_RUNS; seed++) {
274
+ const r = rng(seed)
275
+ const offsetMs = Math.round((r() * 2 - 1) * 10000) // − and + offsets
276
+ const inMs = 20000 + Math.floor(r() * 5000)
277
+ const outMs = inMs + 3000 + Math.floor(r() * 5000)
278
+ const edl: Edl = normalizeEdl({
279
+ version: 1,
280
+ clock: "master",
281
+ sources: [{ id: "cam", url: "https://media.example/cam.mp4", kind: "video", offsetMs }],
282
+ segments: [{ id: "s", inMs, outMs, video: "cam", speaker: "Host" }],
283
+ })
284
+ // The producer samples the source-clock span that the segment keeps.
285
+ const spanStart = inMs - offsetMs
286
+ const spanEnd = outMs - offsetMs
287
+ const boxMs = spanStart + Math.floor(r() * (spanEnd - spanStart))
288
+ const set = normalizeSpeakerTracks({
289
+ version: 1, sampleFps: 2, detector: { id: "d" },
290
+ sources: [{ sourceId: "cam", clock: "source", frame: { w: 1920, h: 1080 }, sampledSpans: [{ startMs: spanStart, endMs: spanEnd }],
291
+ tracks: [{ id: "cam/t1", speaker: "Host", boxes: [{ ms: boxMs, x: 0.1, y: 0.1, w: 0.2, h: 0.2 }] }] }],
292
+ })
293
+ const v = validateSpeakerTracks(set, { edl })
294
+ expect(v.issues, `seed ${seed}`).toEqual([])
295
+ // Normalize never applies the offset itself: the box keeps its source ms.
296
+ expect(set.sources[0].tracks[0].boxes[0].ms, `seed ${seed}`).toBe(boxMs)
297
+ expect(remapMsThroughEdl(edl, boxMs, "cam"), `seed ${seed}`).toBe(boxMs + offsetMs - inMs)
298
+ // One ms before the kept span on the source clock is a dropped instant.
299
+ expect(remapMsThroughEdl(edl, spanStart - 1, "cam"), `seed ${seed}`).toBeNull()
300
+ }
301
+ })
302
+ })
303
+
304
+ // ─────────────────────────────────────────────────────────────────────────
305
+ // Size caps
306
+ // ─────────────────────────────────────────────────────────────────────────
307
+ describe("validateSpeakerTracks — the hard size cap", () => {
308
+ const big = (boxes: number): SpeakerTrackSet => ({
309
+ version: 1,
310
+ sampleFps: 2,
311
+ detector: { id: "d" },
312
+ sources: [{
313
+ sourceId: "wide",
314
+ clock: "source",
315
+ frame: { w: 1920, h: 1080 },
316
+ sampledSpans: [{ startMs: 0, endMs: boxes * 500 + 1 }],
317
+ tracks: [{ id: "wide/t1", boxes: Array.from({ length: boxes }, (_, i) => ({ ms: i * 500, x: 0.1, y: 0.1, w: 0.2, h: 0.2 })) }],
318
+ }],
319
+ })
320
+
321
+ it("exports the default caps as named constants", () => {
322
+ expect(SPEAKER_TRACKS_MAX_BOXES_PER_SOURCE).toBeGreaterThan(0)
323
+ expect(SPEAKER_TRACKS_MAX_BYTES).toBeGreaterThan(0)
324
+ // The 180-minute ceiling at 2 samples per second with several faces in frame fits under the per-source cap.
325
+ expect(SPEAKER_TRACKS_MAX_BOXES_PER_SOURCE).toBeGreaterThanOrEqual(180 * 60 * 2 * 3)
326
+ })
327
+
328
+ it("refuses a source with more boxes than the cap", () => {
329
+ const v = validateSpeakerTracks(big(11), { maxBoxesPerSource: 10 })
330
+ expect(v.ok).toBe(false)
331
+ expect(v.issues).toEqual(['source "wide": 11 boxes is over the cap of 10'])
332
+ expect(validateSpeakerTracks(big(10), { maxBoxesPerSource: 10 }).ok).toBe(true)
333
+ })
334
+
335
+ it("bounds the per-box findings: a systematic producer bug yields a short refusal, not one line per box", () => {
336
+ // A clock bug puts every box outside the sampled spans.
337
+ const set = big(50_000)
338
+ const shifted: SpeakerTrackSet = {
339
+ ...set,
340
+ sources: set.sources.map((s) => ({ ...s, sampledSpans: [{ startMs: 100_000_000, endMs: 100_000_001 }] })),
341
+ }
342
+ const v = validateSpeakerTracks(shifted)
343
+ expect(v.ok).toBe(false)
344
+ expect(v.issues.length).toBeLessThanOrEqual(10)
345
+ expect(v.issues.slice(0, 5)).toEqual([0, 1, 2, 3, 4].map((j) => `track "wide/t1" box[${j}]: ms ${j * 500} is outside every sampled span of source "wide"`))
346
+ expect(v.issues[5]).toBe('track "wide/t1": 49995 more boxes outside every sampled span of source "wide"')
347
+ expect(v.issues).toHaveLength(6)
348
+ })
349
+
350
+ it("bounds the whole issue list: many tracks with one bad box each still yield a bounded refusal", () => {
351
+ const tracks = Array.from({ length: 5000 }, (_, i) => ({ id: `wide/t${i}`, boxes: [{ ms: 999_999, x: 0.1, y: 0.1, w: 0.2, h: 0.2 }] }))
352
+ const set: SpeakerTrackSet = {
353
+ version: 1, sampleFps: 2, detector: { id: "d" },
354
+ sources: [{ sourceId: "wide", clock: "source", frame: { w: 1920, h: 1080 }, sampledSpans: [{ startMs: 0, endMs: 1000 }], tracks }],
355
+ }
356
+ const v = validateSpeakerTracks(set)
357
+ expect(v.ok).toBe(false)
358
+ expect(v.issues.length).toBeLessThanOrEqual(101)
359
+ expect(v.issues[0]).toBe('track "wide/t0" box[0]: ms 999999 is outside every sampled span of source "wide"')
360
+ expect(v.issues[v.issues.length - 1]).toMatch(/^\d+ more issues not listed$/)
361
+ const listed = v.issues.length - 1
362
+ expect(v.issues[v.issues.length - 1]).toBe(`${5000 - listed} more issues not listed`)
363
+ })
364
+
365
+ it("refuses a set whose serialized size is over the byte cap (measured, or as given by the caller)", () => {
366
+ const set = big(20)
367
+ const bytes = new TextEncoder().encode(JSON.stringify(set)).length
368
+ expect(validateSpeakerTracks(set, { maxBytes: bytes }).ok).toBe(true)
369
+ expect(validateSpeakerTracks(set, { maxBytes: bytes - 1 }).issues).toEqual([`the track set is ${bytes} bytes, over the cap of ${bytes - 1}`])
370
+ // A caller that already knows the fetched body's length passes it and skips the re-serialization.
371
+ expect(validateSpeakerTracks(set, { maxBytes: 100, serializedBytes: 99 }).ok).toBe(true)
372
+ expect(validateSpeakerTracks(set, { maxBytes: 100, serializedBytes: 101 }).ok).toBe(false)
373
+ })
374
+ })
375
+
376
+ // ─────────────────────────────────────────────────────────────────────────
377
+ // The descriptor (the node's json; the boxes live in the R2 artifact)
378
+ // ─────────────────────────────────────────────────────────────────────────
379
+ const SHA = "a".repeat(64)
380
+
381
+ describe("describeSpeakerTracks — the descriptor projection", () => {
382
+ it("drops every box, keeps every id, speaker, attribution and span, and counts the boxes", () => {
383
+ for (let seed = 1; seed <= PROPERTY_RUNS; seed++) {
384
+ const set = validSet(rng(seed))
385
+ const d = describeSpeakerTracks(set, { url: "https://media.example/tracks.json", sha256: SHA, bytes: 1234 })
386
+ expect(JSON.stringify(d), `seed ${seed}`).not.toContain('"boxes"')
387
+ expect(d.version).toBe(SPEAKER_TRACKS_VERSION)
388
+ expect(d.sampleFps).toBe(set.sampleFps)
389
+ expect(d.url).toBe("https://media.example/tracks.json")
390
+ expect(d.sources.map((s) => s.sourceId)).toEqual(set.sources.map((s) => s.sourceId))
391
+ set.sources.forEach((s, i) => {
392
+ expect(d.sources[i].sampledSpans).toEqual(s.sampledSpans)
393
+ expect(d.sources[i].frame).toEqual(s.frame)
394
+ expect(d.sources[i].tracks.map((t) => [t.id, t.speaker, t.boxCount])).toEqual(s.tracks.map((t) => [t.id, t.speaker, t.boxes.length]))
395
+ })
396
+ expect(normalizeSpeakerTrackSetDescriptor(d), `seed ${seed}`).toEqual(d)
397
+ expect(validateSpeakerTrackSetDescriptor(d).issues, `seed ${seed}`).toEqual([])
398
+ }
399
+ })
400
+
401
+ it("the body a descriptor names is the one whose projection equals it", () => {
402
+ const set = normalizeSpeakerTracks(FIXTURES.cases[0].input)
403
+ const d = describeSpeakerTracks(set, { url: "https://media.example/t.json", sha256: SHA, bytes: 10 })
404
+ expect(describeSpeakerTracks(set, { url: d.url, sha256: d.sha256, bytes: d.bytes })).toEqual(d)
405
+ })
406
+ })
407
+
408
+ describe("validateSpeakerTrackSetDescriptor", () => {
409
+ const base = () => describeSpeakerTracks(normalizeSpeakerTracks(FIXTURES.cases[0].input), { url: "https://media.example/t.json", sha256: SHA, bytes: 4096 })
410
+ const twoHost = normalizeEdl(FIXTURES.edls.twoHost)
411
+
412
+ it("accepts a well-formed descriptor against its EDL", () => {
413
+ expect(validateSpeakerTrackSetDescriptor(base(), { edl: twoHost })).toEqual({ ok: true, issues: [], warnings: [] })
414
+ })
415
+
416
+ it("refuses an empty url, a malformed hash and a non-positive or over-cap byte count", () => {
417
+ const d = normalizeSpeakerTrackSetDescriptor({ ...base(), url: " ", sha256: "ABC", bytes: 0 })
418
+ expect(validateSpeakerTrackSetDescriptor(d).issues).toEqual([
419
+ "url is empty",
420
+ "sha256 must be 64 lowercase hex characters",
421
+ "bytes must be a positive integer",
422
+ ])
423
+ const over = normalizeSpeakerTrackSetDescriptor({ ...base(), bytes: 5000 })
424
+ expect(validateSpeakerTrackSetDescriptor(over, { maxBytes: 4999 }).issues).toEqual(["the track set is 5000 bytes, over the cap of 4999"])
425
+ })
426
+
427
+ it("applies the same structural, EDL and name-space rules as the body", () => {
428
+ const raw = describeSpeakerTracks(normalizeSpeakerTracks(FIXTURES.cases[3].input), { url: "u", sha256: SHA, bytes: 1 })
429
+ const v = validateSpeakerTrackSetDescriptor(raw, { edl: twoHost })
430
+ expect(v.issues).toEqual(validateSpeakerTracks(normalizeSpeakerTracks(FIXTURES.cases[3].input), { edl: twoHost }).issues)
431
+ expect(v.ok).toBe(false)
432
+ })
433
+
434
+ it("refuses a box count over the per-source cap", () => {
435
+ const d = base()
436
+ expect(validateSpeakerTrackSetDescriptor(d, { maxBoxesPerSource: 1 }).issues).toEqual(['source "wide": 4 boxes is over the cap of 1'])
437
+ })
438
+
439
+ it("normalizes a missing or broken boxCount to 0 and never throws on garbage", () => {
440
+ const d = normalizeSpeakerTrackSetDescriptor({ ...base(), sources: [{ sourceId: "wide", clock: "source", frame: { w: 1, h: 1 }, sampledSpans: [], tracks: [{ id: "t", boxCount: -3.5 }, { id: "u" }] }] })
441
+ expect(d.sources[0].tracks.map((t) => t.boxCount)).toEqual([0, 0])
442
+ for (let seed = 1; seed <= PROPERTY_RUNS; seed++) {
443
+ const g = garbageSet(rng(seed))
444
+ const n = normalizeSpeakerTrackSetDescriptor(g)
445
+ expect(normalizeSpeakerTrackSetDescriptor(n), `seed ${seed}`).toEqual(n)
446
+ expect(() => validateSpeakerTrackSetDescriptor(n), `seed ${seed}`).not.toThrow()
447
+ }
448
+ })
449
+ })
450
+
451
+ describe("edlSpeakerSpace — the speakers an edit uses", () => {
452
+ it("is the sorted union of source speakers, segment speakers and slot speakers, across a clip pack", () => {
453
+ expect(edlSpeakerSpace(normalizeEdl(FIXTURES.edls.twoHost))).toEqual(["Guest", "Host"])
454
+ expect(edlSpeakerSpace(normalizeEdl(FIXTURES.edls.rawLabels))).toEqual(["SPEAKER_00", "SPEAKER_01"])
455
+ expect(edlSpeakerSpace([normalizeEdl(FIXTURES.edls.clipOne), normalizeEdl(FIXTURES.edls.clipTwo)])).toEqual(["Guest", "Host"])
456
+ })
457
+
458
+ it("an edit with no speakers has nothing to mismatch: attributed tracks pass", () => {
459
+ const edl = normalizeEdl({ version: 1, clock: "master", sources: [{ id: "wide", url: "u", kind: "video" }], segments: [{ id: "s", inMs: 0, outMs: 1000, video: "wide" }] })
460
+ expect(edlSpeakerSpace(edl)).toEqual([])
461
+ const set = normalizeSpeakerTracks(FIXTURES.cases[3].input)
462
+ expect(validateSpeakerTracks(set, { edl }).ok).toBe(true)
463
+ })
464
+ })
465
+
466
+ describe("public surface", () => {
467
+ it("is exported from the package root", () => {
468
+ expect(shared.normalizeSpeakerTracks).toBe(normalizeSpeakerTracks)
469
+ expect(shared.validateSpeakerTracks).toBe(validateSpeakerTracks)
470
+ expect(shared.describeSpeakerTracks).toBe(describeSpeakerTracks)
471
+ expect(shared.SPEAKER_TRACK_ATTRIBUTION_METHODS).toEqual(["source-map", "region", "mouth-motion", "manual"])
472
+ expect(SPEAKER_TRACK_ATTRIBUTION_METHODS).toBe(shared.SPEAKER_TRACK_ATTRIBUTION_METHODS)
473
+ })
474
+ })
@@ -0,0 +1,69 @@
1
+ import { describe, it, expect } from "vitest"
2
+ import {
3
+ SPEECH_PRICE_UNIT_CHARS,
4
+ SPEECH_FLOOR_UNITS,
5
+ SPEECH_UNIT_CREDIT_SUFFIX,
6
+ speechUnitCreditId,
7
+ speechPriceUnits,
8
+ speechCredits,
9
+ } from "../credit-estimators/speech.js"
10
+ import { TTS_PROVIDERS, TTS_PROVIDER_ALIASES, canonicalTtsProvider } from "../index.js"
11
+
12
+ describe("speech pricing — the unit", () => {
13
+ it("prices per started 100 characters with a minimum of 8 units (decided 2026-10-06)", () => {
14
+ expect(SPEECH_PRICE_UNIT_CHARS).toBe(100)
15
+ expect(SPEECH_FLOOR_UNITS).toBe(8)
16
+ })
17
+
18
+ it.each([
19
+ [0, 8], [1, 8], [100, 8], [800, 8],
20
+ [801, 9], [1000, 10], [1001, 11], [2500, 25], [5000, 50], [10000, 100], [40000, 400],
21
+ ])("%i characters → %i units", (chars, units) => {
22
+ expect(speechPriceUnits(chars)).toBe(units)
23
+ })
24
+
25
+ it("a count that is not a usable number is the floor, never NaN or a throw", () => {
26
+ for (const bad of [Number.NaN, -5, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, -0]) {
27
+ expect(speechPriceUnits(bad), String(bad)).toBe(SPEECH_FLOOR_UNITS)
28
+ }
29
+ })
30
+
31
+ // The worked examples in docs/nodes/ai-audio/text-to-speech.md and
32
+ // text-to-dialogue.md are these rows — change both together.
33
+ it.each([
34
+ // [chars, perUnit, credits]
35
+ [100, 4, 32], [800, 4, 32], [801, 4, 36], [1000, 4, 40], [2500, 4, 100], [5000, 4, 200], [10000, 4, 400],
36
+ [100, 2, 16], [1000, 2, 20], [5000, 2, 100], [40000, 2, 800],
37
+ ])("%i characters at %i per unit → %i credits", (chars, perUnit, credits) => {
38
+ expect(speechCredits(chars, perUnit)).toBe(credits)
39
+ })
40
+
41
+ it("an admin retune moves the floor with it: units × the row, not a second row", () => {
42
+ expect(speechCredits(100, 5)).toBe(40)
43
+ expect(speechCredits(1000, 5)).toBe(50)
44
+ expect(speechCredits(100, 0)).toBe(0) // a free row prices nothing (community has no rows at all)
45
+ })
46
+ })
47
+
48
+ describe("speech pricing — the unit row id", () => {
49
+ it("is the model id plus the suffix, for every text-to-speech model and for dialogue", () => {
50
+ expect(SPEECH_UNIT_CREDIT_SUFFIX).toBe(":per-100-chars")
51
+ for (const id of TTS_PROVIDERS) {
52
+ if (id in TTS_PROVIDER_ALIASES) continue
53
+ expect(speechUnitCreditId(id)).toBe(`${id}:per-100-chars`)
54
+ }
55
+ expect(speechUnitCreditId("elevenlabs-dialogue")).toBe("elevenlabs-dialogue:per-100-chars")
56
+ })
57
+
58
+ it("a legacy alias prices on the row of the model it runs as", () => {
59
+ for (const [alias, target] of Object.entries(TTS_PROVIDER_ALIASES)) {
60
+ expect(speechUnitCreditId(alias)).toBe(speechUnitCreditId(canonicalTtsProvider(target)))
61
+ }
62
+ expect(speechUnitCreditId("elevenlabs")).toBe("elevenlabs-turbo:per-100-chars")
63
+ })
64
+
65
+ it("the suffix sits on a `:` boundary, so a per-service margin on the model id covers its unit id", () => {
66
+ const id = speechUnitCreditId("elevenlabs-v4")
67
+ expect(id.startsWith("elevenlabs-v4:")).toBe(true)
68
+ })
69
+ })
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it } from "vitest"
2
+ import {
3
+ TELEGRAM_FEED_LIMIT_MAX,
4
+ planFeedEmission,
5
+ telegramFeedDigest,
6
+ telegramPostsFrom,
7
+ } from "../telegram-channel.js"
8
+
9
+ const ids = (from: number, to: number) => Array.from({ length: to - from + 1 }, (_, i) => ({ id: from + i }))
10
+
11
+ /** The feed's position after a run — the one rule the route and the editor read. */
12
+ describe("planFeedEmission", () => {
13
+ it("first run: the newest N, and the position jumps to the newest post", () => {
14
+ const plan = planFeedEmission(ids(100, 119), undefined, 5)
15
+ expect(plan.emitted.map((p) => p.id)).toEqual([115, 116, 117, 118, 119])
16
+ expect(plan.latestId).toBe(119)
17
+ })
18
+
19
+ it("a stored position: the OLDEST N above it, and the position is the highest post emitted — a backlog drains N per run", () => {
20
+ // 15 fresh posts above 104, limit 5: the first five, and the position moves to the fifth.
21
+ const plan = planFeedEmission(ids(100, 119), 104, 5)
22
+ expect(plan.emitted.map((p) => p.id)).toEqual([105, 106, 107, 108, 109])
23
+ expect(plan.latestId).toBe(109)
24
+ const next = planFeedEmission(ids(100, 119), plan.latestId, 5)
25
+ expect(next.emitted.map((p) => p.id)).toEqual([110, 111, 112, 113, 114])
26
+ const last = planFeedEmission(ids(100, 119), 114, 5)
27
+ expect(last.emitted.map((p) => p.id)).toEqual([115, 116, 117, 118, 119])
28
+ expect(last.latestId).toBe(119)
29
+ })
30
+
31
+ it("nothing new: nothing emitted and the position stays", () => {
32
+ const plan = planFeedEmission(ids(100, 119), 119, 5)
33
+ expect(plan.emitted).toEqual([])
34
+ expect(plan.latestId).toBe(119)
35
+ const empty = planFeedEmission([], 50, 5)
36
+ expect(empty.emitted).toEqual([])
37
+ expect(empty.latestId).toBe(50)
38
+ })
39
+
40
+ it("a page of posts with nothing to read above the position moves the position past them — the feed never re-reads the same unreadable page", () => {
41
+ // Twenty voice notes (ids 51..70) rendered above position 50, none readable.
42
+ const plan = planFeedEmission([], 50, 5, 70)
43
+ expect(plan.emitted).toEqual([])
44
+ expect(plan.latestId).toBe(70)
45
+ // Readable posts win: the position is the highest EMITTED post, whatever the page went up to.
46
+ const mixed = planFeedEmission(ids(60, 62), 50, 5, 70)
47
+ expect(mixed.emitted.map((p) => p.id)).toEqual([60, 61, 62])
48
+ expect(mixed.latestId).toBe(62)
49
+ // A page max at or below the position changes nothing.
50
+ expect(planFeedEmission([], 50, 5, 50).latestId).toBe(50)
51
+ expect(planFeedEmission([], 50, 5, 40).latestId).toBe(50)
52
+ })
53
+
54
+ it("an empty channel on the first run has no position", () => {
55
+ expect(planFeedEmission([], undefined, 5)).toEqual({ emitted: [], latestId: undefined })
56
+ })
57
+
58
+ it("posts in any order, a repeated post (pinned), and a limit outside the range", () => {
59
+ const shuffled = [{ id: 3 }, { id: 1 }, { id: 2 }, { id: 3 }]
60
+ expect(planFeedEmission(shuffled, undefined, 2).emitted.map((p) => p.id)).toEqual([2, 3])
61
+ expect(planFeedEmission(ids(1, 40), 0, 99).emitted).toHaveLength(TELEGRAM_FEED_LIMIT_MAX)
62
+ expect(planFeedEmission(ids(1, 40), undefined, 0).emitted).toHaveLength(1)
63
+ expect(planFeedEmission(ids(1, 40), undefined, Number.NaN).emitted).toHaveLength(5)
64
+ })
65
+ })
66
+
67
+ describe("telegramFeedDigest", () => {
68
+ it("joins the posts' text oldest first and leaves out a post with no text", () => {
69
+ expect(telegramFeedDigest([{ text: "one" }, { text: " " }, { text: "two" }])).toBe("one\n\n---\n\ntwo")
70
+ expect(telegramFeedDigest([])).toBe("")
71
+ })
72
+ })
73
+
74
+ describe("telegramPostsFrom", () => {
75
+ it("reads a saved list back, normalizing what an older save lacks, and leaves out anything that is not a post", () => {
76
+ const posts = telegramPostsFrom([
77
+ { id: 10, channel: "acme", postUrl: "https://t.me/acme/10", text: "hello", media: [{ type: "photo", url: "https://cdn/p" }], views: "1.2K", date: "2026-10-06T00:00:00Z" },
78
+ { id: 11, text: "no media saved", channel: "acme" },
79
+ { id: "12", text: "string id" },
80
+ "not a post",
81
+ null,
82
+ { id: 13, url: "https://t.me/acme/13", text: "legacy url field", forwardedFrom: { name: "Other", url: "https://t.me/other" } },
83
+ ])
84
+ expect(posts.map((p) => p.id)).toEqual([10, 11, 13])
85
+ expect(posts[0]!.media).toEqual([{ type: "photo", url: "https://cdn/p" }])
86
+ expect(posts[1]).toMatchObject({ postUrl: "https://t.me/acme/11", media: [] })
87
+ expect(posts[2]).toMatchObject({ postUrl: "https://t.me/acme/13", forwardedFrom: { name: "Other", url: "https://t.me/other" } })
88
+ expect(telegramPostsFrom("nope")).toEqual([])
89
+ expect(telegramPostsFrom(undefined)).toEqual([])
90
+ })
91
+ })