@nodaro/shared 3.19.0 → 3.20.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.
@@ -0,0 +1,323 @@
1
+ /**
2
+ * A person's review of an Edit Plan, and the ONE rule that makes it win.
3
+ *
4
+ * The planner's output stays on `data.generatedJson`, untouched. A review edit
5
+ * lives beside it on `data.editedEdl` (TA13, decided 2026-10-04), tagged by
6
+ * `kind` and fingerprinted with `basis` — the hash of the plan it was made
7
+ * against. An edit whose basis no longer matches (the plan was re-run) is
8
+ * ignored by construction, so no writer has to remember to clear it for the
9
+ * read to be right. The edit is run-result data (TA14, decided 2026-10-04):
10
+ * `editedEdl` is in `EXECUTION_DATA_KEYS`, so it stays out of undo, presets,
11
+ * templates and exports, and Clear results wipes it.
12
+ *
13
+ * - Tighten: `{v:1, kind:"edl", basis, edl:{segments, dropped}}`. The resolved
14
+ * plan is the planner's EDL with the edit's segments and dropped spans;
15
+ * sources, clock and meta always come from the plan (an edit never stores
16
+ * sources).
17
+ * - Clips: `{v:1, kind:"clips", basis, clips:[{keep, hook?}]}`, index-aligned
18
+ * with the plan's clips, holding decisions only. The list a fan-out reads
19
+ * stays on the PLAN's indices, with `""` at every dropped clip (TA16,
20
+ * decided 2026-10-04), so an edge selector picks the same clips it picked
21
+ * for the preview. `json` holds the kept clips only, so a scalar read (the
22
+ * first item) is the first kept clip. An edited hook travels as `meta.hook`
23
+ * (TA20, decided 2026-10-04: text only).
24
+ * - Chapters have no review: an edit never applies.
25
+ *
26
+ * Every read of an Edit Plan's saved output calls `editPlanSavedOutput`, on
27
+ * both engines; `extractGeneratedJsonAsList` stays generic.
28
+ */
29
+ import { validateEdl, type Edl, type EdlDropped, type EdlSegment, type EdlValidation } from "./edl.js"
30
+
31
+ export const EDITED_EDL_VERSION = 1 as const
32
+
33
+ /** A Tighten plan's review: the kept segments and the dropped spans. */
34
+ export interface EditedEdlCut {
35
+ readonly v: typeof EDITED_EDL_VERSION
36
+ readonly kind: "edl"
37
+ /** `editPlanBasis` of the `generatedJson` this edit was made against. */
38
+ readonly basis: string
39
+ readonly edl: {
40
+ readonly segments: readonly EdlSegment[]
41
+ readonly dropped: readonly EdlDropped[]
42
+ }
43
+ }
44
+
45
+ /** One clip's review decision, at the clip's index in the plan. */
46
+ export interface EditedClipDecision {
47
+ readonly keep: boolean
48
+ /** The clip's hook as the person rewrote it (text only); absent = the plan's. */
49
+ readonly hook?: string
50
+ }
51
+
52
+ /** A clip set's review: one decision per planned clip, index-aligned. */
53
+ export interface EditedClipSet {
54
+ readonly v: typeof EDITED_EDL_VERSION
55
+ readonly kind: "clips"
56
+ /** `editPlanBasis` of the `generatedJson` this edit was made against. */
57
+ readonly basis: string
58
+ readonly clips: readonly EditedClipDecision[]
59
+ }
60
+
61
+ /** What `data.editedEdl` on an Edit Plan holds. */
62
+ export type EditedEdl = EditedEdlCut | EditedClipSet
63
+
64
+ /**
65
+ * How the review edit stood when the plan was resolved:
66
+ * - `none`: there is no edit;
67
+ * - `applied`: the edit was made on this plan and wins;
68
+ * - `stale`: it was made on another plan (a re-run, including one that
69
+ * changed the clip count or the plan's mode) and is ignored;
70
+ * - `invalid`: it is malformed, or, made on this plan, it does not fit its
71
+ * kind or shape; it is ignored.
72
+ */
73
+ export type EditPlanEditStatus = "none" | "applied" | "stale" | "invalid"
74
+
75
+ /** An Edit Plan's output as every reader receives it. */
76
+ export interface EditPlanSavedOutput {
77
+ /** Tighten: the EDL. Clips: the kept clips. Chapters: the chapter set. */
78
+ readonly json: unknown
79
+ /** Clips only: one JSON string per PLANNED clip, `""` where a clip is dropped. */
80
+ readonly listResults?: string[]
81
+ }
82
+
83
+ export interface ResolvedEditPlanOutput extends EditPlanSavedOutput {
84
+ readonly status: EditPlanEditStatus
85
+ }
86
+
87
+ // ─────────────────────────────────────────────────────────────────────────
88
+ // basis: FNV-1a-64 over the key-sorted JSON
89
+ // ─────────────────────────────────────────────────────────────────────────
90
+
91
+ /** JSON text with every object's keys sorted, at every depth. `workflows.nodes`
92
+ * is JSONB, which does not keep key order, so the stored plan can come back
93
+ * with its keys in another order; its canonical text does not. Values follow
94
+ * `JSON.stringify`: an undefined or function value drops its key (and is
95
+ * `null` inside an array), and a non-finite number is `null`. */
96
+ function canonicalJson(value: unknown): string | undefined {
97
+ if (value === null) return "null"
98
+ switch (typeof value) {
99
+ case "string":
100
+ case "boolean":
101
+ return JSON.stringify(value)
102
+ case "number":
103
+ return Number.isFinite(value) ? JSON.stringify(value) : "null"
104
+ case "object": {
105
+ const toJSON = (value as { toJSON?: unknown }).toJSON
106
+ if (typeof toJSON === "function") return canonicalJson((value as { toJSON: () => unknown }).toJSON())
107
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item) ?? "null").join(",")}]`
108
+ const parts: string[] = []
109
+ for (const key of Object.keys(value).sort()) {
110
+ const text = canonicalJson((value as Record<string, unknown>)[key])
111
+ if (text !== undefined) parts.push(`${JSON.stringify(key)}:${text}`)
112
+ }
113
+ return `{${parts.join(",")}}`
114
+ }
115
+ default:
116
+ return undefined
117
+ }
118
+ }
119
+
120
+ /** FNV-1a-64 over the UTF-8 bytes of `text`, as 16 lowercase hex digits. The
121
+ * 64-bit state is two 32-bit halves: the prime is 2^40 + 435, so
122
+ * `h × prime = h × 435 + (h << 40)` (mod 2^64), and every partial product
123
+ * stays an exact double. */
124
+ function fnv1a64(text: string): string {
125
+ let hi = 0xcbf29ce4
126
+ let lo = 0x84222325
127
+ const mix = (byte: number): void => {
128
+ lo = (lo ^ byte) >>> 0
129
+ const loProduct = lo * 435
130
+ const carry = Math.floor(loProduct / 0x1_0000_0000)
131
+ hi = (hi * 435 + carry + ((lo << 8) >>> 0)) >>> 0
132
+ lo = loProduct >>> 0
133
+ }
134
+ for (let i = 0; i < text.length; i++) {
135
+ let code = text.charCodeAt(i)
136
+ // A surrogate pair is one code point; a lone surrogate encodes as U+FFFD,
137
+ // as TextEncoder does.
138
+ if (code >= 0xd800 && code <= 0xdbff) {
139
+ const next = i + 1 < text.length ? text.charCodeAt(i + 1) : 0
140
+ if (next >= 0xdc00 && next <= 0xdfff) {
141
+ code = 0x10000 + ((code - 0xd800) << 10) + (next - 0xdc00)
142
+ i++
143
+ } else code = 0xfffd
144
+ } else if (code >= 0xdc00 && code <= 0xdfff) code = 0xfffd
145
+ if (code < 0x80) mix(code)
146
+ else if (code < 0x800) {
147
+ mix(0xc0 | (code >> 6))
148
+ mix(0x80 | (code & 0x3f))
149
+ } else if (code < 0x10000) {
150
+ mix(0xe0 | (code >> 12))
151
+ mix(0x80 | ((code >> 6) & 0x3f))
152
+ mix(0x80 | (code & 0x3f))
153
+ } else {
154
+ mix(0xf0 | (code >> 18))
155
+ mix(0x80 | ((code >> 12) & 0x3f))
156
+ mix(0x80 | ((code >> 6) & 0x3f))
157
+ mix(0x80 | (code & 0x3f))
158
+ }
159
+ }
160
+ return hi.toString(16).padStart(8, "0") + lo.toString(16).padStart(8, "0")
161
+ }
162
+
163
+ /**
164
+ * The fingerprint of an Edit Plan's stored output (`data.generatedJson`, as
165
+ * unwrapped): FNV-1a-64 of the UTF-8 bytes of its key-sorted JSON, as 16
166
+ * lowercase hex digits. Equal for any key order, so a JSONB round trip keeps
167
+ * it; any change to a value, or to array order, changes it.
168
+ */
169
+ export function editPlanBasis(plan: unknown): string {
170
+ return fnv1a64(canonicalJson(plan) ?? "")
171
+ }
172
+
173
+ // ─────────────────────────────────────────────────────────────────────────
174
+ // The envelope
175
+ // ─────────────────────────────────────────────────────────────────────────
176
+
177
+ type PlanShape = "edl" | "clips" | "other"
178
+
179
+ const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v)
180
+
181
+ function planShape(plan: unknown): PlanShape {
182
+ if (Array.isArray(plan)) return "clips"
183
+ if (isRecord(plan) && Array.isArray(plan.segments)) return "edl"
184
+ return "other"
185
+ }
186
+
187
+ type EnvelopeCheck =
188
+ | { readonly status: "none" }
189
+ | { readonly status: "applied"; readonly edited: EditedEdl }
190
+ | { readonly status: "stale" | "invalid"; readonly issue: string }
191
+
192
+ /** Is `edited` an edit of THIS plan? The envelope (version, basis, kind),
193
+ * then the basis, then the plan's shape and the alignment. The basis comes
194
+ * before the shape and the clip count because a re-run that changes the clip
195
+ * count or the plan's mode is a re-plan (`stale`), not a malformed edit; once
196
+ * the basis matches, a shape or count mismatch really is `invalid`. Never
197
+ * looks inside the cut's segments (that is `validateEdl`'s). */
198
+ function checkEnvelope(edited: unknown, plan: unknown): EnvelopeCheck {
199
+ if (edited === undefined || edited === null) return { status: "none" }
200
+ if (!isRecord(edited)) return { status: "invalid", issue: "editedEdl must be an object" }
201
+ if (edited.v !== EDITED_EDL_VERSION) return { status: "invalid", issue: `editedEdl.v must be ${EDITED_EDL_VERSION}` }
202
+ if (typeof edited.basis !== "string" || edited.basis.length === 0) {
203
+ return { status: "invalid", issue: "editedEdl.basis must be a non-empty string" }
204
+ }
205
+ if (edited.kind !== "edl" && edited.kind !== "clips") {
206
+ return { status: "invalid", issue: `editedEdl.kind must be "edl" or "clips"` }
207
+ }
208
+ if (edited.basis !== editPlanBasis(plan)) {
209
+ return { status: "stale", issue: "editedEdl.basis does not match the plan: the plan changed since this edit was made" }
210
+ }
211
+ const shape = planShape(plan)
212
+ if (edited.kind === "edl") {
213
+ if (shape !== "edl") return { status: "invalid", issue: `an "edl" edit needs a Tighten plan (one EDL); this plan is ${describeShape(shape)}` }
214
+ const edl = edited.edl
215
+ if (!isRecord(edl) || !Array.isArray(edl.segments) || !Array.isArray(edl.dropped)) {
216
+ return { status: "invalid", issue: "editedEdl.edl must hold a segments array and a dropped array" }
217
+ }
218
+ } else if (edited.kind === "clips") {
219
+ if (shape !== "clips") return { status: "invalid", issue: `a "clips" edit needs a clip set; this plan is ${describeShape(shape)}` }
220
+ const clips = edited.clips
221
+ if (!Array.isArray(clips)) return { status: "invalid", issue: "editedEdl.clips must be an array" }
222
+ const planned = (plan as readonly unknown[]).length
223
+ if (clips.length !== planned) {
224
+ return { status: "invalid", issue: `editedEdl.clips holds ${clips.length} decisions; the plan has ${planned} clips` }
225
+ }
226
+ const bad = clips.findIndex(
227
+ (c) => !isRecord(c) || typeof c.keep !== "boolean" || (c.hook !== undefined && typeof c.hook !== "string"),
228
+ )
229
+ if (bad >= 0) return { status: "invalid", issue: `editedEdl.clips[${bad}] must be {keep: boolean, hook?: string}` }
230
+ }
231
+ return { status: "applied", edited: edited as unknown as EditedEdl }
232
+ }
233
+
234
+ function describeShape(shape: PlanShape): string {
235
+ return shape === "edl" ? "a Tighten plan" : shape === "clips" ? "a clip set" : "neither (a chapter list, or no plan)"
236
+ }
237
+
238
+ // ─────────────────────────────────────────────────────────────────────────
239
+ // The resolver
240
+ // ─────────────────────────────────────────────────────────────────────────
241
+
242
+ /** The plan's clip set as one JSON string per clip — today's list output. */
243
+ function plannedList(plan: readonly unknown[]): string[] {
244
+ return plan.map((clip) => (typeof clip === "string" ? clip : JSON.stringify(clip)))
245
+ }
246
+
247
+ function asOutput(plan: unknown): EditPlanSavedOutput {
248
+ return Array.isArray(plan) ? { json: plan, listResults: plannedList(plan) } : { json: plan }
249
+ }
250
+
251
+ /** A clip with the person's hook, never mutating the plan's clip. */
252
+ function withHook(clip: unknown, hook: string | undefined): unknown {
253
+ if (hook === undefined) return clip
254
+ let value = clip
255
+ if (typeof clip === "string") {
256
+ try {
257
+ value = JSON.parse(clip)
258
+ } catch {
259
+ return clip
260
+ }
261
+ }
262
+ if (!isRecord(value)) return clip
263
+ const meta = isRecord(value.meta) ? value.meta : {}
264
+ return { ...value, meta: { ...meta, hook } }
265
+ }
266
+
267
+ /**
268
+ * An Edit Plan's output with the person's review applied: what every edit-plan
269
+ * read hands downstream, on both engines.
270
+ *
271
+ * The edit applies when its shape matches the plan's kind and its `basis` is
272
+ * this plan's. It applies even when the cut it holds is not a well-formed EDL:
273
+ * the render then refuses it with its own issues, where falling back to the
274
+ * planner's cut would silently render what the person removed. A stale or
275
+ * invalid edit is ignored, and the plan is read as planned.
276
+ */
277
+ export function resolveEditPlanOutput(plan: unknown, editedEdl: unknown): ResolvedEditPlanOutput {
278
+ const check = checkEnvelope(editedEdl, plan)
279
+ if (check.status !== "applied") return { status: check.status, ...asOutput(plan) }
280
+ const edited = check.edited
281
+ if (edited.kind === "edl") {
282
+ const json = { ...(plan as Record<string, unknown>), segments: edited.edl.segments, dropped: edited.edl.dropped }
283
+ return { status: "applied", json }
284
+ }
285
+ const rows = (plan as readonly unknown[]).map((clip, i) => {
286
+ const decision = edited.clips[i]!
287
+ return decision.keep ? withHook(clip, decision.hook) : undefined
288
+ })
289
+ return {
290
+ status: "applied",
291
+ json: rows.filter((clip) => clip !== undefined),
292
+ listResults: rows.map((clip) => (clip === undefined ? "" : typeof clip === "string" ? clip : JSON.stringify(clip))),
293
+ }
294
+ }
295
+
296
+ /**
297
+ * An Edit Plan node's SAVED output — the one read every edit-plan reader makes
298
+ * of `data` (a node outside the run, the editor's own read of the canvas).
299
+ * `undefined` when the node holds no plan. With no edit it is exactly the plan:
300
+ * `{json}`, plus `listResults` (one JSON string per clip) for a clip set.
301
+ */
302
+ export function editPlanSavedOutput(data: Readonly<Record<string, unknown>>): EditPlanSavedOutput | undefined {
303
+ const plan = data.generatedJson
304
+ if (plan === undefined) return undefined
305
+ const { status: _status, ...output } = resolveEditPlanOutput(plan, data.editedEdl)
306
+ return output
307
+ }
308
+
309
+ /**
310
+ * Check a review edit before it is saved. The envelope (version, kind), the
311
+ * basis, then the plan's shape and one decision per clip, and, for a Tighten edit,
312
+ * the structural `validateEdl` of the edited cut — the Edit Plan's own
313
+ * "well-formed" rule (TA1 a, decided 2026-10-04); what a given render can draw
314
+ * is the render's rule, not this one. Issues are English, like `validateEdl`'s.
315
+ */
316
+ export function validateEditedEdl(editedEdl: unknown, plan: unknown): EdlValidation {
317
+ const check = checkEnvelope(editedEdl, plan)
318
+ if (check.status === "none") return { ok: false, issues: ["there is no edit"], warnings: [] }
319
+ if (check.status !== "applied") return { ok: false, issues: [check.issue], warnings: [] }
320
+ if (check.edited.kind === "clips") return { ok: true, issues: [], warnings: [] }
321
+ const resolved = resolveEditPlanOutput(plan, editedEdl).json as Edl
322
+ return validateEdl(resolved)
323
+ }
package/src/index.ts CHANGED
@@ -956,6 +956,10 @@ export {
956
956
  type CompetitorAboutPlatform,
957
957
  type CompetitorSchedule,
958
958
  type CompetitorAccounts,
959
+ type CompetitorSearchKind,
960
+ type CompetitorSearch,
961
+ type CompetitorPlatformTally,
962
+ type CompetitorBrandTally,
959
963
  type TrackedCompetitor,
960
964
  type ActionCardKind,
961
965
  type ActionCardPriority,
@@ -1358,6 +1362,8 @@ export {
1358
1362
  DYNAMIC_PRODUCER_TYPES,
1359
1363
  FAN_OUT_EACH_TYPES,
1360
1364
  FAN_OUT_EACH_HANDLES,
1365
+ OWN_LIST_NODE_TYPES,
1366
+ ownsItsList,
1361
1367
  defaultEdgeOutputMode,
1362
1368
  listResultsServeHandle,
1363
1369
  FAN_IN_TARGETS,
@@ -1553,5 +1559,7 @@ export * from "./speaker-layouts.js"
1553
1559
  export * from "./edl-multicam.js"
1554
1560
  export * from "./camera-switch-contract.js"
1555
1561
  export * from "./edit-plan-contract.js"
1562
+ // A person's review of an Edit Plan (`editedEdl`) and the one resolver that applies it.
1563
+ export * from "./edit-plan-review.js"
1556
1564
 
1557
1565
  export { VIDEO_DURATION_AUTO, isAutoVideoDuration } from "./video-duration-auto.js"
@@ -65,6 +65,11 @@ export const EXECUTION_DATA_KEYS: ReadonlySet<string> = new Set([
65
65
  "__pickedTotal",
66
66
  "__restTotal",
67
67
  "generatedJson",
68
+ // Edit Plan: a person's review of the plan (`EditedEdl`, edit-plan-review.ts),
69
+ // kept beside `generatedJson` and fingerprinted against it. Run-result data
70
+ // (TA14, decided 2026-10-04): out of undo, presets, templates and exports,
71
+ // and Clear results wipes it. Persisted — never transient.
72
+ "editedEdl",
68
73
  "subWorkflowProgress",
69
74
  "outputResults",
70
75
  "shots",
@@ -264,6 +264,21 @@ export const FAN_OUT_EACH_HANDLES: Readonly<Record<string, { readonly each: read
264
264
  "camera-switch": { each: ["edl"], primary: "edl" },
265
265
  }
266
266
 
267
+ /**
268
+ * Nodes whose saved list is the list their last run PRODUCED — `__listResults`
269
+ * (Extract Field's JSON value on `generatedJson`) — and never a history in
270
+ * `generatedResults`: Extract Field and JSON Process. No run of either writes
271
+ * one; earlier builds' server runs did (the run's text, the links of a list of
272
+ * links), and both engines' list readers leave it out for these two (decided
273
+ * 2026-10-05). Single source of truth for the backend engine and the editor.
274
+ */
275
+ export const OWN_LIST_NODE_TYPES: ReadonlySet<string> = new Set(["extract-field", "json-process"])
276
+
277
+ /** Whether a node's saved list is its own `__listResults`, never a history. */
278
+ export function ownsItsList(nodeType: string | null | undefined): boolean {
279
+ return typeof nodeType === "string" && OWN_LIST_NODE_TYPES.has(nodeType)
280
+ }
281
+
267
282
  /** The `outputMode` an edge has when none is set on it — the ONE rule both
268
283
  * engines, the credit estimate and the editor read. */
269
284
  export function defaultEdgeOutputMode(