@nodetool-ai/protocol 0.8.13 → 0.8.14

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 (159) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/agent-model-fit.d.ts +35 -0
  3. package/dist/agent-model-fit.d.ts.map +1 -0
  4. package/dist/agent-model-fit.js +62 -0
  5. package/dist/agent-model-fit.js.map +1 -0
  6. package/dist/api-schemas/agent-access.d.ts +40 -0
  7. package/dist/api-schemas/agent-access.d.ts.map +1 -1
  8. package/dist/api-schemas/agent-access.js +24 -1
  9. package/dist/api-schemas/agent-access.js.map +1 -1
  10. package/dist/api-schemas/api-error-code.d.ts +35 -1
  11. package/dist/api-schemas/api-error-code.d.ts.map +1 -1
  12. package/dist/api-schemas/api-error-code.js +34 -0
  13. package/dist/api-schemas/api-error-code.js.map +1 -1
  14. package/dist/api-schemas/assets.d.ts +79 -0
  15. package/dist/api-schemas/assets.d.ts.map +1 -1
  16. package/dist/api-schemas/assets.js +61 -7
  17. package/dist/api-schemas/assets.js.map +1 -1
  18. package/dist/api-schemas/cloud-local.d.ts +194 -0
  19. package/dist/api-schemas/cloud-local.d.ts.map +1 -0
  20. package/dist/api-schemas/cloud-local.js +88 -0
  21. package/dist/api-schemas/cloud-local.js.map +1 -0
  22. package/dist/api-schemas/cloud-transfer-local.d.ts +999 -0
  23. package/dist/api-schemas/cloud-transfer-local.d.ts.map +1 -0
  24. package/dist/api-schemas/cloud-transfer-local.js +189 -0
  25. package/dist/api-schemas/cloud-transfer-local.js.map +1 -0
  26. package/dist/api-schemas/deleted-documents.d.ts +45 -0
  27. package/dist/api-schemas/deleted-documents.d.ts.map +1 -0
  28. package/dist/api-schemas/deleted-documents.js +30 -0
  29. package/dist/api-schemas/deleted-documents.js.map +1 -0
  30. package/dist/api-schemas/document-sharing.d.ts +171 -1
  31. package/dist/api-schemas/document-sharing.d.ts.map +1 -1
  32. package/dist/api-schemas/document-sharing.js +37 -5
  33. package/dist/api-schemas/document-sharing.js.map +1 -1
  34. package/dist/api-schemas/index.d.ts +6 -0
  35. package/dist/api-schemas/index.d.ts.map +1 -1
  36. package/dist/api-schemas/index.js +6 -0
  37. package/dist/api-schemas/index.js.map +1 -1
  38. package/dist/api-schemas/messages.d.ts +30 -0
  39. package/dist/api-schemas/messages.d.ts.map +1 -1
  40. package/dist/api-schemas/messages.js +32 -1
  41. package/dist/api-schemas/messages.js.map +1 -1
  42. package/dist/api-schemas/openverse.d.ts +2 -0
  43. package/dist/api-schemas/openverse.d.ts.map +1 -1
  44. package/dist/api-schemas/projects.d.ts +412 -0
  45. package/dist/api-schemas/projects.d.ts.map +1 -1
  46. package/dist/api-schemas/projects.js +212 -2
  47. package/dist/api-schemas/projects.js.map +1 -1
  48. package/dist/api-schemas/receive.d.ts +95 -0
  49. package/dist/api-schemas/receive.d.ts.map +1 -0
  50. package/dist/api-schemas/receive.js +69 -0
  51. package/dist/api-schemas/receive.js.map +1 -0
  52. package/dist/api-schemas/sdk-execution-v1.d.ts +0 -2
  53. package/dist/api-schemas/sdk-execution-v1.d.ts.map +1 -1
  54. package/dist/api-schemas/settings.d.ts +125 -0
  55. package/dist/api-schemas/settings.d.ts.map +1 -1
  56. package/dist/api-schemas/settings.js +59 -0
  57. package/dist/api-schemas/settings.js.map +1 -1
  58. package/dist/api-schemas/storage.d.ts +96 -0
  59. package/dist/api-schemas/storage.d.ts.map +1 -1
  60. package/dist/api-schemas/storage.js +48 -0
  61. package/dist/api-schemas/storage.js.map +1 -1
  62. package/dist/api-schemas/storyboards.d.ts +55 -0
  63. package/dist/api-schemas/storyboards.d.ts.map +1 -1
  64. package/dist/api-schemas/storyboards.js +55 -8
  65. package/dist/api-schemas/storyboards.js.map +1 -1
  66. package/dist/api-schemas/sync.d.ts +78 -0
  67. package/dist/api-schemas/sync.d.ts.map +1 -0
  68. package/dist/api-schemas/sync.js +78 -0
  69. package/dist/api-schemas/sync.js.map +1 -0
  70. package/dist/api-schemas/timeline-tool-contracts.d.ts +42 -2
  71. package/dist/api-schemas/timeline-tool-contracts.d.ts.map +1 -1
  72. package/dist/api-schemas/timeline-tool-contracts.js +54 -3
  73. package/dist/api-schemas/timeline-tool-contracts.js.map +1 -1
  74. package/dist/api-schemas/timeline-tool-params.d.ts +1 -1
  75. package/dist/api-schemas/timeline-tool-params.d.ts.map +1 -1
  76. package/dist/api-schemas/timeline-tool-params.js +5 -0
  77. package/dist/api-schemas/timeline-tool-params.js.map +1 -1
  78. package/dist/api-schemas/timeline.d.ts +2 -0
  79. package/dist/api-schemas/timeline.d.ts.map +1 -1
  80. package/dist/api-schemas/timeline.js +7 -2
  81. package/dist/api-schemas/timeline.js.map +1 -1
  82. package/dist/api-schemas/transfer.d.ts +890 -0
  83. package/dist/api-schemas/transfer.d.ts.map +1 -0
  84. package/dist/api-schemas/transfer.js +297 -0
  85. package/dist/api-schemas/transfer.js.map +1 -0
  86. package/dist/api-schemas/workflows.d.ts +301 -1
  87. package/dist/api-schemas/workflows.d.ts.map +1 -1
  88. package/dist/api-schemas/workflows.js +110 -8
  89. package/dist/api-schemas/workflows.js.map +1 -1
  90. package/dist/api-schemas/workspace.d.ts +0 -22
  91. package/dist/api-schemas/workspace.d.ts.map +1 -1
  92. package/dist/api-schemas/workspace.js +0 -21
  93. package/dist/api-schemas/workspace.js.map +1 -1
  94. package/dist/api-types.d.ts +83 -24
  95. package/dist/api-types.d.ts.map +1 -1
  96. package/dist/api-types.js +48 -24
  97. package/dist/api-types.js.map +1 -1
  98. package/dist/chat-attachment.d.ts +28 -0
  99. package/dist/chat-attachment.d.ts.map +1 -0
  100. package/dist/chat-attachment.js +101 -0
  101. package/dist/chat-attachment.js.map +1 -0
  102. package/dist/closure.d.ts +33 -0
  103. package/dist/closure.d.ts.map +1 -0
  104. package/dist/closure.js +116 -0
  105. package/dist/closure.js.map +1 -0
  106. package/dist/cloud-profile.d.ts.map +1 -1
  107. package/dist/cloud-profile.js +9 -2
  108. package/dist/cloud-profile.js.map +1 -1
  109. package/dist/creative.d.ts +17 -0
  110. package/dist/creative.d.ts.map +1 -1
  111. package/dist/creative.js.map +1 -1
  112. package/dist/identity-encoding.d.ts +2 -0
  113. package/dist/identity-encoding.d.ts.map +1 -0
  114. package/dist/identity-encoding.js +56 -0
  115. package/dist/identity-encoding.js.map +1 -0
  116. package/dist/index.d.ts +6 -0
  117. package/dist/index.d.ts.map +1 -1
  118. package/dist/index.js +6 -0
  119. package/dist/index.js.map +1 -1
  120. package/dist/messages.d.ts +0 -8
  121. package/dist/messages.d.ts.map +1 -1
  122. package/dist/missing-runtime-package.d.ts +1 -3
  123. package/dist/missing-runtime-package.d.ts.map +1 -1
  124. package/dist/missing-runtime-package.js +1 -3
  125. package/dist/missing-runtime-package.js.map +1 -1
  126. package/dist/processing-messages.schema.json +0 -2
  127. package/dist/project-directories.d.ts +127 -0
  128. package/dist/project-directories.d.ts.map +1 -0
  129. package/dist/project-directories.js +208 -0
  130. package/dist/project-directories.js.map +1 -0
  131. package/dist/run-trace.js +1 -1
  132. package/dist/run-trace.js.map +1 -1
  133. package/dist/runtime-npm-packages.d.ts +3 -13
  134. package/dist/runtime-npm-packages.d.ts.map +1 -1
  135. package/dist/runtime-npm-packages.js +3 -37
  136. package/dist/runtime-npm-packages.js.map +1 -1
  137. package/dist/sandbox-host.d.ts +1 -1
  138. package/dist/sandbox-host.d.ts.map +1 -1
  139. package/dist/sandbox-host.js +1 -50
  140. package/dist/sandbox-host.js.map +1 -1
  141. package/dist/storyboard-markdown.d.ts +154 -0
  142. package/dist/storyboard-markdown.d.ts.map +1 -0
  143. package/dist/storyboard-markdown.js +905 -0
  144. package/dist/storyboard-markdown.js.map +1 -0
  145. package/dist/toolSchemas.d.ts +46 -0
  146. package/dist/toolSchemas.d.ts.map +1 -1
  147. package/dist/toolSchemas.js +87 -3
  148. package/dist/toolSchemas.js.map +1 -1
  149. package/dist/workflow-document-revision.d.ts +1 -1
  150. package/dist/workflow-document-revision.d.ts.map +1 -1
  151. package/dist/workflow-document-revision.js +2 -1
  152. package/dist/workflow-document-revision.js.map +1 -1
  153. package/dist/ws-commands.d.ts +3 -1
  154. package/dist/ws-commands.d.ts.map +1 -1
  155. package/dist/ws-commands.js +2 -0
  156. package/dist/ws-commands.js.map +1 -1
  157. package/package.json +7 -1
  158. package/schema/sdk-v1.execution.schema.json +0 -4
  159. package/schema/sdk-v1.manifest.json +1 -1
@@ -0,0 +1,905 @@
1
+ /**
2
+ * A storyboard document written as Markdown, and read back.
3
+ *
4
+ * The Markdown is a view of {@link StoryboardDocumentSchema}. Every line maps
5
+ * to a key the schema already has, and references use the encodings NodeTool
6
+ * already stores:
7
+ *
8
+ * ```
9
+ * # Title {#screenplay-id} screenplay.title, screenplay.id
10
+ * Text under the title document.brief
11
+ * - **Style:** … document.style (board fields: BOARD_FIELDS)
12
+ * # Act I (Exposition) {#act-id} screenplay.acts[]; text under it is the objective
13
+ * ## Slugline {#scene-id} screenplay.scenes[], with the act above as act_id
14
+ * - **Lighting:** … scene.lighting
15
+ * ### Slug {#shot-id} a shot: slug, id; index is its position
16
+ * ![Still](asset://<id>.png) shot.keyframe (a video file: shot.clip)
17
+ * Text under a shot shot.action
18
+ * - **Motion:** … shot.motion (shot fields: SHOT_FIELDS)
19
+ * [Nova](entity://<id>) an entity mention: the id joins shot.entity_ids
20
+ * [Shot 4](#<shot-id>) a shot reference, used by transitions and continuities
21
+ * ```
22
+ *
23
+ * `{#id}` is the Pandoc heading attribute. It is the join key with the stored
24
+ * document: what the text does not show (takes, render records, status,
25
+ * models, script links) is kept from `base` by id. Shot numbers are computed.
26
+ *
27
+ * Pure and dependency-free, so the web editor and the server read the text the
28
+ * same way. The native editor uses a C++ port,
29
+ * native/storyboard/src/StoryboardMarkdown.cpp. Its oracle test runs both on
30
+ * the same boards and fails on any difference, so change them together.
31
+ */
32
+ import { isNumber, isRecord, isString } from "./predicates.js";
33
+ export const STORYBOARD_MARKDOWN_ID = "[A-Za-z0-9._~-]+";
34
+ const ID = STORYBOARD_MARKDOWN_ID;
35
+ const ENTITY_LINK = new RegExp(`\\[([^\\]\\n]+)\\]\\(entity://(${ID})\\)|(?<![\\w(])entity://(${ID})`, "g");
36
+ const SHOT_LINK = new RegExp(`\\[([^\\]\\n]*)\\]\\(#(${ID})\\)`, "g");
37
+ const IMAGE = /^\s*!\[([^\]\n]*)\]\(([^)\s]+)\)\s*$/;
38
+ const VIDEO_EXT = /\.(mp4|webm|mov|m4v|mkv)$/i;
39
+ /** A media reference names a video file: its path, without query or fragment, ends in a video extension. */
40
+ const isVideoUri = (uri) => VIDEO_EXT.test(uri.split(/[?#]/, 1)[0]);
41
+ /** Field labels, the first label of each key being the one written out. */
42
+ const SHOT_FIELDS = [
43
+ ["Action", "action"], ["Framing", "camera.framing"], ["Lens", "camera.lens"], ["Angle", "camera.angle"],
44
+ ["Camera movement", "camera.movement"], ["Rig", "camera.equipment"], ["Camera presets", "camera.preset_ids"],
45
+ ["Motion", "motion"], ["End", "end_state"], ["Sound", "sound"], ["Dialogue", "dialogue"], ["Narration", "narration"],
46
+ ["Duration", "duration_seconds"], ["Render", "render_mode"], ["Location", "location_id"], ["Cast", "entity_ids"],
47
+ ["Look", "look_preset_ids"], ["Transition", "transition"], ["Continuity", "continuity"], ["Notes", "notes"]
48
+ ];
49
+ const SHOT_ALIASES = {
50
+ "initial phase": "action", "initial frame": "action", "camera move": "camera.movement", equipment: "camera.equipment",
51
+ movement: "motion", "end state": "end_state", "final phase": "end_state", "end frame": "end_state", voiceover: "narration",
52
+ vo: "narration", mode: "render_mode", "render mode": "render_mode", entities: "entity_ids", characters: "entity_ids",
53
+ references: "entity_ids", "look presets": "look_preset_ids", note: "notes"
54
+ };
55
+ const BOARD_FIELDS = [
56
+ ["Logline", "logline"], ["Brief", "brief"], ["Style", "style"], ["Aspect ratio", "aspectRatio"], ["Genre", "genre"],
57
+ ["Cast", "entityIds"], ["Look", "look_preset_ids"], ["Music", "music_prompt"], ["Narration", "narration"],
58
+ ["Motion design", "motion_direction"]
59
+ ];
60
+ const BOARD_ALIASES = {
61
+ "style bible": "style", aspect: "aspectRatio", "music prompt": "music_prompt", score: "music_prompt", entities: "entityIds", concept: "brief"
62
+ };
63
+ const ACT_FIELDS = [["Objective", "objective"]];
64
+ const SCENE_FIELDS = [["Lighting", "lighting"]];
65
+ const labelTable = (list, aliases = {}) => {
66
+ const byLabel = new Map();
67
+ for (const [label, key] of list)
68
+ byLabel.set(label.toLowerCase(), key);
69
+ for (const [label, key] of Object.entries(aliases))
70
+ byLabel.set(label, key);
71
+ return byLabel;
72
+ };
73
+ const FIELDS = {
74
+ board: labelTable(BOARD_FIELDS, BOARD_ALIASES),
75
+ act: labelTable(ACT_FIELDS),
76
+ scene: labelTable(SCENE_FIELDS),
77
+ shot: labelTable(SHOT_FIELDS, SHOT_ALIASES)
78
+ };
79
+ const KNOWN_LABELS = new Set(Object.values(FIELDS).flatMap((table) => [...table.keys()]));
80
+ /** Shot keys the Markdown owns. Every other key of a stored shot is kept as it was. */
81
+ const SHOT_TEXT_KEYS = new Set(["slug", "action", "motion", "end_state", "sound", "dialogue", "narration", "notes", "duration_seconds",
82
+ "render_mode", "location_id", "entity_ids", "look_preset_ids", "keyframe", "clip", "scene_id", "index", "id", "type", "camera"]);
83
+ const CAMERA_TEXT_KEYS = ["framing", "lens", "angle", "movement", "equipment", "preset_ids"];
84
+ const RENDER_MODES = new Set(["keyframe", "direct", "reference"]);
85
+ /** Fields written once per line: each line is one transition or continuity. */
86
+ const REPEATED = new Set(["transition", "continuity"]);
87
+ /* ── small helpers ───────────────────────────────────────────────────── */
88
+ const isRec = (value) => isRecord(value);
89
+ const str = (value) => (isString(value) ? value : undefined);
90
+ const strList = (value) => (Array.isArray(value) ? value.filter(isString) : []);
91
+ const recList = (value) => (Array.isArray(value) ? value.filter(isRec) : []);
92
+ const clone = (value) => (value === undefined ? value : JSON.parse(JSON.stringify(value)));
93
+ const isEmptyValue = (value) => value === "" || (Array.isArray(value) && value.length === 0) || (isRec(value) && Object.keys(value).length === 0);
94
+ const sameSet = (a, b) => a.length === b.length && a.every((x) => b.includes(x));
95
+ const defaultId = () => globalThis.crypto.randomUUID().replace(/-/g, "");
96
+ const assetIdOf = (uri) => /^asset:\/\/([^./?#]+)/.exec(uri)?.[1] ?? null;
97
+ const refUri = (ref) => {
98
+ if (!isRec(ref))
99
+ return "";
100
+ const uri = str(ref.uri);
101
+ if (uri)
102
+ return uri;
103
+ const assetId = str(ref.asset_id);
104
+ return assetId ? `asset://${assetId}` : "";
105
+ };
106
+ const sameRef = (ref, uri) => isRec(ref) && (refUri(ref) === uri || (!!str(ref.asset_id) && assetIdOf(uri) === ref.asset_id));
107
+ const splitIds = (raw) => raw.split(/[,\s]+/).filter(Boolean);
108
+ /** Keep the stored order when the set of ids did not change. */
109
+ const keepOrder = (ids, stored) => {
110
+ const before = strList(stored);
111
+ return Array.isArray(stored) && sameSet(before, ids) ? before : ids;
112
+ };
113
+ /** The last `{#id}` in a text, wherever it is: text typed after it must not detach an object from its id. */
114
+ function findAnchor(text) {
115
+ let found = null;
116
+ for (const m of text.matchAll(new RegExp(`\\s*\\{#(${ID})\\}`, "g"))) {
117
+ found = { index: m.index, length: m[0].length, id: m[1], text: m[0] };
118
+ }
119
+ return found;
120
+ }
121
+ const withoutAnchor = (text, anchor) => anchor ? text.slice(0, anchor.index) + text.slice(anchor.index + anchor.length) : text;
122
+ export function matchStoryboardHeading(text) {
123
+ const m = /^(\s*(#{1,6})\s+)/.exec(text);
124
+ if (!m)
125
+ return null;
126
+ const rest = text.slice(m[1].length);
127
+ const anchor = findAnchor(rest);
128
+ const body = withoutAnchor(rest, anchor);
129
+ const level = m[2].length;
130
+ // A typed shot number is ignored: numbers are computed.
131
+ const prefix = level >= 3 ? (/^(\d+\s*[.)]\s*)/.exec(body)?.[1] ?? "") : "";
132
+ return {
133
+ mark: m[1],
134
+ level,
135
+ prefix,
136
+ body: body.slice(prefix.length),
137
+ bodyStart: m[1].length + prefix.length,
138
+ anchor: anchor ? { id: anchor.id, start: m[1].length + anchor.index, text: anchor.text } : null
139
+ };
140
+ }
141
+ export function matchStoryboardField(text) {
142
+ // Each pattern matches the syntax only; the value is the rest of the line.
143
+ let m = /^(\s*(?:[-*•]\s+)?\*\*)([^*:\n]{1,40}?)(:\*\*|\*\*\s*:)(\s*)/.exec(text);
144
+ if (!m) {
145
+ m = /^(\s*(?:[-*•]\s+)?)([A-Za-z][A-Za-z /]{0,30}?)(:)(\s*)/.exec(text);
146
+ // "Note: …" in prose stays prose unless the label is one the grammar knows.
147
+ if (!m || !KNOWN_LABELS.has(m[2].trim().toLowerCase()))
148
+ return null;
149
+ }
150
+ return { pre: m[1], label: m[2], post: m[3], gap: m[4], body: text.slice(m[0].length), bodyStart: m[0].length };
151
+ }
152
+ const matchImage = (text) => {
153
+ const m = IMAGE.exec(text);
154
+ return m ? { uri: m[2], video: isVideoUri(m[2]) || /^clip\b/i.test(m[1].trim()) } : null;
155
+ };
156
+ /** Entity mentions in a value, and the value with each mention written as its name. */
157
+ export function readEntityMentions(value, entities) {
158
+ const ids = [];
159
+ const text = value.replace(ENTITY_LINK, (_match, label, linked, bare) => {
160
+ const id = linked ?? bare ?? "";
161
+ if (!ids.includes(id))
162
+ ids.push(id);
163
+ return label ?? entities?.get(id)?.name ?? `entity://${id}`;
164
+ });
165
+ return { text, ids };
166
+ }
167
+ const readShotLinks = (value) => [...value.matchAll(SHOT_LINK)].map((m) => ({ id: m[2], index: m.index, length: m[0].length }));
168
+ const stripShotLinks = (value) => value.replace(SHOT_LINK, "").replace(/\s{2,}/g, " ").trim();
169
+ /** Split one line into styled runs. The run texts always add up to the line. */
170
+ export function tokenizeStoryboardLine(text, entities) {
171
+ const out = [];
172
+ const push = (kind, s, entityKind) => {
173
+ if (!s)
174
+ return;
175
+ const last = out[out.length - 1];
176
+ if (last && last.kind === kind && last.entityKind === entityKind && kind !== "entity" && kind !== "shotref")
177
+ last.text += s;
178
+ else
179
+ out.push(entityKind ? { kind, text: s, entityKind } : { kind, text: s });
180
+ };
181
+ const inline = (s) => {
182
+ const re = new RegExp(`(\\*\\*)(?=\\S)([^*]+?)(\\*\\*)|(\\*)(?=\\S)([^*\\n]+?)(\\*)|\\[([^\\]\\n]+)\\]\\((entity://(${ID}))\\)|(?<![\\w(])(entity://(${ID}))|\\[([^\\]\\n]*)\\]\\((#${ID})\\)`, "g");
183
+ let at = 0;
184
+ for (const m of s.matchAll(re)) {
185
+ push("text", s.slice(at, m.index));
186
+ if (m[1]) {
187
+ push("syntax", m[1]);
188
+ push("bold", m[2]);
189
+ push("syntax", m[3]);
190
+ }
191
+ else if (m[4]) {
192
+ push("syntax", m[4]);
193
+ push("italic", m[5]);
194
+ push("syntax", m[6]);
195
+ }
196
+ else if (m[7]) {
197
+ push("hidden", "[");
198
+ push("entity", m[7], entities?.get(m[9])?.kind ?? "missing");
199
+ push("hidden", `](${m[8]})`);
200
+ }
201
+ else if (m[10]) {
202
+ push("entity", m[10], entities?.get(m[11])?.kind ?? "missing");
203
+ }
204
+ else {
205
+ push("hidden", "[");
206
+ push("shotref", m[12]);
207
+ push("hidden", `](${m[13]})`);
208
+ }
209
+ at = m.index + m[0].length;
210
+ }
211
+ push("text", s.slice(at));
212
+ };
213
+ const heading = matchStoryboardHeading(text);
214
+ if (heading) {
215
+ push("syntax", heading.mark + heading.prefix);
216
+ const rest = text.slice(heading.bodyStart);
217
+ if (heading.anchor) {
218
+ const at = heading.anchor.start - heading.bodyStart;
219
+ inline(rest.slice(0, at));
220
+ push("id", heading.anchor.text);
221
+ inline(rest.slice(at + heading.anchor.text.length));
222
+ }
223
+ else
224
+ inline(rest);
225
+ }
226
+ else if (matchImage(text)) {
227
+ push("syntax", text);
228
+ }
229
+ else {
230
+ const field = matchStoryboardField(text);
231
+ if (field) {
232
+ push("syntax", field.pre);
233
+ push("label", field.label);
234
+ push("syntax", field.post);
235
+ push("text", field.gap);
236
+ const anchor = findAnchor(field.body);
237
+ if (anchor) {
238
+ inline(field.body.slice(0, anchor.index));
239
+ push("id", anchor.text);
240
+ inline(field.body.slice(anchor.index + anchor.length));
241
+ }
242
+ else
243
+ inline(field.body);
244
+ }
245
+ else {
246
+ const bullet = /^\s*[-*•]\s+/.exec(text);
247
+ if (bullet) {
248
+ push("syntax", bullet[0]);
249
+ inline(text.slice(bullet[0].length));
250
+ }
251
+ else
252
+ inline(text);
253
+ }
254
+ }
255
+ return out.map((t) => t.text).join("") === text ? out : text ? [{ kind: "text", text }] : [];
256
+ }
257
+ /**
258
+ * Read a storyboard document out of its Markdown.
259
+ *
260
+ * Returns the document, what each line became, the warnings, and the headings
261
+ * that need an id written into them. The result validates against
262
+ * `storyboardDocument` for any input text.
263
+ */
264
+ export function parseStoryboardMarkdown(markdown, options = {}) {
265
+ const base = (options.base ?? null);
266
+ const entities = options.entities;
267
+ const newId = options.generateId ?? defaultId;
268
+ const lines = isString(markdown) ? markdown.replace(/\n$/, "").split("\n") : [...markdown];
269
+ const baseScreenplay = isRec(base?.screenplay) ? base.screenplay : null;
270
+ const baseShotList = recList(base?.shots).length ? recList(base?.shots) : recList(baseScreenplay?.shots);
271
+ const baseShots = new Map(baseShotList.map((s) => [str(s.id) ?? "", s]));
272
+ const baseScenes = new Map(recList(baseScreenplay?.scenes).map((s) => [str(s.id) ?? "", s]));
273
+ const baseActs = new Map(recList(baseScreenplay?.acts).map((a) => [str(a.id) ?? "", a]));
274
+ const baseMotion = isRec(baseScreenplay?.motion_design) ? baseScreenplay.motion_design : null;
275
+ const baseTransitions = recList(baseMotion?.transitions);
276
+ const baseContinuities = new Map(recList(baseMotion?.continuities).map((c) => [str(c.id) ?? "", c]));
277
+ const board = { title: null, titleId: null, fields: {}, brief: [] };
278
+ const acts = [];
279
+ const scenes = [];
280
+ const shots = [];
281
+ const info = [];
282
+ const warnings = [];
283
+ const missingIds = [];
284
+ const seen = new Set();
285
+ let holder = { type: "board", name: "Board" };
286
+ let act = null;
287
+ let scene = null;
288
+ let field = null;
289
+ let afterBlank = false;
290
+ let fieldsStarted = false;
291
+ let lastField = null;
292
+ const note = (line, code, message, params = {}) => {
293
+ const warning = { line, code, params, message };
294
+ warnings.push(warning);
295
+ return warning;
296
+ };
297
+ const warn = (m, code, message, params = {}) => {
298
+ m.warning = note(m.line, code, message, params);
299
+ };
300
+ const claimId = (m, heading) => {
301
+ let id = heading.anchor?.id;
302
+ if (!id || seen.has(id)) {
303
+ id = newId();
304
+ missingIds.push({ line: m.line, id, replace: heading.anchor ? { start: heading.anchor.start, text: heading.anchor.text } : null });
305
+ }
306
+ seen.add(id);
307
+ return id;
308
+ };
309
+ const appendParagraph = (list, text) => {
310
+ if (afterBlank || !list.length)
311
+ list.push(text);
312
+ else
313
+ list[list.length - 1] += "\n" + text;
314
+ };
315
+ lines.forEach((text, line) => {
316
+ const m = { line, role: "text", bodyStart: 0 };
317
+ info.push(m);
318
+ if (!text.trim()) {
319
+ m.role = "blank";
320
+ field = null;
321
+ afterBlank = true;
322
+ return;
323
+ }
324
+ const heading = matchStoryboardHeading(text);
325
+ if (heading) {
326
+ field = null;
327
+ afterBlank = false;
328
+ fieldsStarted = false;
329
+ lastField = null;
330
+ Object.assign(m, { bodyStart: heading.bodyStart, bodyEnd: heading.anchor ? heading.anchor.start : text.length, syntaxWidth: heading.mark.trim().length + heading.prefix.length });
331
+ const body = heading.body.trim();
332
+ if (heading.level === 1 && board.title === null && !acts.length && !scenes.length && !shots.length) {
333
+ board.title = body;
334
+ board.titleId = claimId(m, heading);
335
+ holder = { type: "board", name: "Board" };
336
+ Object.assign(m, { role: "title", group: "title", scope: "Board · title" });
337
+ }
338
+ else if (heading.level === 1) {
339
+ act = { id: claimId(m, heading), title: body, objective: [] };
340
+ acts.push(act);
341
+ scene = null;
342
+ holder = { type: "act", act, name: `Act ${acts.length}` };
343
+ Object.assign(m, { role: "act", group: `act:${act.id}:title`, scope: `Act ${acts.length} · title` });
344
+ }
345
+ else if (heading.level === 2) {
346
+ scene = { id: claimId(m, heading), slugline: body, act: act?.id ?? null };
347
+ scenes.push(scene);
348
+ holder = { type: "scene", scene, name: `Scene ${scenes.length}` };
349
+ Object.assign(m, { role: "scene", group: `scene:${scene.id}:slugline`, scope: `Scene ${scenes.length} · slugline` });
350
+ }
351
+ else {
352
+ const shot = { id: claimId(m, heading), slug: body, action: [], notes: [], fields: {}, repeated: {}, keyframe: null, clip: null, scene: scene?.id ?? null, line };
353
+ shots.push(shot);
354
+ holder = { type: "shot", shot, name: `Shot ${shots.length}` };
355
+ Object.assign(m, { role: "shot", group: `shot:${shot.id}:slug`, scope: `Shot ${shots.length} · title`, shotNumber: shots.length, shotId: shot.id });
356
+ }
357
+ return;
358
+ }
359
+ const image = matchImage(text);
360
+ if (image) {
361
+ field = null;
362
+ afterBlank = false;
363
+ m.bodyStart = text.length;
364
+ m.media = image.uri;
365
+ if (holder.type !== "shot") {
366
+ m.role = "stray";
367
+ warn(m, "media_outside_shot", "An image belongs to a shot: put it under a ### shot heading.");
368
+ return;
369
+ }
370
+ const slot = image.video ? "clip" : "keyframe";
371
+ if (holder.shot[slot])
372
+ warn(m, "second_media", `A shot has one selected ${image.video ? "clip" : "still"}. This one is not used.`, { media: image.video ? "clip" : "still" });
373
+ else
374
+ holder.shot[slot] = image.uri;
375
+ Object.assign(m, { role: image.video ? "clip" : "still", scope: `${holder.name} · ${image.video ? "clip" : "still"}` });
376
+ return;
377
+ }
378
+ const f = matchStoryboardField(text);
379
+ if (f) {
380
+ const label = f.label.trim();
381
+ const key = FIELDS[holder.type].get(label.toLowerCase());
382
+ afterBlank = false;
383
+ fieldsStarted = true;
384
+ Object.assign(m, { role: "field", bodyStart: f.bodyStart, scope: `${holder.name} · ${label}` });
385
+ lastField = m;
386
+ const body = f.body.trim();
387
+ if (!key) {
388
+ m.key = "unknown";
389
+ if (holder.type === "shot") {
390
+ holder.shot.notes.push(`${label}: ${body}`);
391
+ field = { kind: "list", list: holder.shot.notes };
392
+ warn(m, "unknown_shot_field", `"${label}" is not a storyboard field. It is saved in the shot's notes.`, { label });
393
+ }
394
+ else {
395
+ field = { kind: "lost" };
396
+ warn(m, "unknown_field", `"${label}" is not a field of ${holder.type === "board" ? "the board" : `a ${holder.type}`}. It is not saved.`, { label, holder: holder.type });
397
+ }
398
+ return;
399
+ }
400
+ m.key = key;
401
+ const owner = holder.type === "board" ? "board" : holder.type === "act" ? `act:${holder.act.id}` : holder.type === "scene" ? `scene:${holder.scene.id}` : `shot:${holder.shot.id}`;
402
+ m.group = `${owner}:${key}`;
403
+ if (holder.type === "shot" && (key === "action" || key === "notes")) {
404
+ const list = key === "action" ? holder.shot.action : holder.shot.notes;
405
+ list.push(body);
406
+ field = { kind: "list", list };
407
+ return;
408
+ }
409
+ if (holder.type === "board" && key === "brief") {
410
+ board.brief.push(body);
411
+ field = { kind: "list", list: board.brief };
412
+ return;
413
+ }
414
+ if (holder.type === "act") {
415
+ holder.act.objective.push(body);
416
+ field = { kind: "list", list: holder.act.objective };
417
+ return;
418
+ }
419
+ if (holder.type === "scene") {
420
+ holder.scene.lighting = (holder.scene.lighting ? holder.scene.lighting + "\n" : "") + body;
421
+ field = { kind: "scene", scene: holder.scene };
422
+ return;
423
+ }
424
+ const into = holder.type === "board" ? board.fields : holder.shot.fields;
425
+ if (holder.type === "shot" && REPEATED.has(key)) {
426
+ const list = (holder.shot.repeated[key] ??= []);
427
+ list.push(body);
428
+ field = { kind: "repeated", list };
429
+ return;
430
+ }
431
+ into[key] = (into[key] ? into[key] + "\n" : "") + body;
432
+ field = { kind: "value", into, key };
433
+ return;
434
+ }
435
+ // Plain text continues the field above it, or is the main text of its object.
436
+ const open = field;
437
+ if (open && !afterBlank) {
438
+ const t = text.trim();
439
+ if (open.kind === "list" || open.kind === "repeated")
440
+ open.list[open.list.length - 1] += "\n" + t;
441
+ else if (open.kind === "value")
442
+ open.into[open.key] += "\n" + t;
443
+ else if (open.kind === "scene")
444
+ open.scene.lighting += "\n" + t;
445
+ const above = lastField;
446
+ Object.assign(m, { role: "cont", scope: above?.scope, key: above?.key, group: above?.group });
447
+ return;
448
+ }
449
+ field = null;
450
+ const t = text.trim();
451
+ if (holder.type === "shot") {
452
+ if (!fieldsStarted) {
453
+ appendParagraph(holder.shot.action, t);
454
+ Object.assign(m, { key: "action", scope: `${holder.name} · action`, group: `shot:${holder.shot.id}:action` });
455
+ }
456
+ else {
457
+ appendParagraph(holder.shot.notes, t);
458
+ Object.assign(m, { key: "notes", scope: `${holder.name} · notes`, group: `shot:${holder.shot.id}:notes` });
459
+ }
460
+ }
461
+ else if (holder.type === "board") {
462
+ appendParagraph(board.brief, t);
463
+ Object.assign(m, { key: "brief", scope: "Board · brief", group: "board:brief" });
464
+ }
465
+ else if (holder.type === "act") {
466
+ appendParagraph(holder.act.objective, t);
467
+ Object.assign(m, { key: "objective", scope: `${holder.name} · objective`, group: `act:${holder.act.id}:objective` });
468
+ }
469
+ else {
470
+ m.role = "stray";
471
+ warn(m, "text_in_scene", "A scene has a slugline and lighting only. Put this text under a shot, or label it \"Lighting:\".");
472
+ }
473
+ afterBlank = false;
474
+ });
475
+ /* — shots — */
476
+ const order = new Map(shots.map((s, i) => [s.id, i]));
477
+ const outShots = shots.map((p, index) => {
478
+ const stored = baseShots.get(p.id);
479
+ const shot = {};
480
+ if (stored)
481
+ for (const [k, v] of Object.entries(stored))
482
+ if (!SHOT_TEXT_KEYS.has(k))
483
+ shot[k] = clone(v);
484
+ shot.type = "shot";
485
+ shot.id = p.id;
486
+ shot.index = index;
487
+ // "" and [] round-trip through an absent line.
488
+ const keep = (key, value) => {
489
+ if (value !== undefined && value !== "")
490
+ shot[key] = value;
491
+ else if (stored && key in stored && isEmptyValue(stored[key]))
492
+ shot[key] = clone(stored[key]);
493
+ };
494
+ const mentions = [];
495
+ const prose = (raw) => {
496
+ if (raw === undefined)
497
+ return undefined;
498
+ const read = readEntityMentions(raw, entities);
499
+ for (const id of read.ids)
500
+ if (!mentions.includes(id))
501
+ mentions.push(id);
502
+ return read.text;
503
+ };
504
+ keep("slug", prose(p.slug) || undefined);
505
+ shot.action = prose(p.action.join("\n\n")) ?? "";
506
+ for (const key of ["motion", "end_state", "sound", "dialogue", "narration"])
507
+ keep(key, prose(p.fields[key]));
508
+ keep("notes", prose(p.notes.length ? p.notes.join("\n\n") : undefined));
509
+ const storedCamera = isRec(stored?.camera) ? stored.camera : null;
510
+ const camera = storedCamera ? Object.fromEntries(Object.entries(storedCamera).filter(([k]) => !CAMERA_TEXT_KEYS.includes(k))) : {};
511
+ for (const k of CAMERA_TEXT_KEYS) {
512
+ const raw = p.fields[`camera.${k}`];
513
+ if (raw !== undefined && raw.trim())
514
+ camera[k] = k === "preset_ids" ? splitIds(raw) : raw;
515
+ else if (storedCamera && k in storedCamera && isEmptyValue(storedCamera[k]))
516
+ camera[k] = clone(storedCamera[k]);
517
+ }
518
+ if (Object.keys(camera).length || (stored && "camera" in stored))
519
+ shot.camera = camera;
520
+ const duration = p.fields.duration_seconds;
521
+ if (duration !== undefined) {
522
+ const seconds = parseFloat(duration.replace(",", "."));
523
+ if (Number.isFinite(seconds)) {
524
+ shot.duration_seconds = seconds;
525
+ if (stored?.duration_seconds !== seconds)
526
+ shot.duration_source = "manual";
527
+ }
528
+ else
529
+ note(p.line, "bad_duration", `Shot ${index + 1}: the duration "${duration}" is not a number of seconds.`, { shot: index + 1, value: duration });
530
+ }
531
+ const render = p.fields.render_mode?.trim().toLowerCase();
532
+ if (render !== undefined) {
533
+ if (RENDER_MODES.has(render))
534
+ shot.render_mode = render;
535
+ else
536
+ note(p.line, "bad_render", `Shot ${index + 1}: render is keyframe, direct or reference.`, { shot: index + 1 });
537
+ }
538
+ const look = p.fields.look_preset_ids;
539
+ keep("look_preset_ids", look !== undefined && look.trim() ? splitIds(look) : undefined);
540
+ const location = p.fields.location_id;
541
+ if (location !== undefined) {
542
+ const id = readEntityMentions(location, entities).ids[0];
543
+ if (id)
544
+ shot.location_id = id;
545
+ else if (/^none$/i.test(location.trim()))
546
+ shot.location_id = null;
547
+ }
548
+ else if (stored && "location_id" in stored && (stored.location_id === null || stored.location_id === ""))
549
+ shot.location_id = stored.location_id;
550
+ const castField = p.fields.entity_ids;
551
+ const cast = castField === undefined ? null : /^none$/i.test(castField.trim()) ? [] : readEntityMentions(castField, entities).ids;
552
+ if (mentions.length || cast) {
553
+ const ids = [...(cast ?? [])];
554
+ for (const id of mentions)
555
+ if (!ids.includes(id))
556
+ ids.push(id);
557
+ shot.entity_ids = keepOrder(ids, stored?.entity_ids);
558
+ }
559
+ else if (stored && Array.isArray(stored.entity_ids) && stored.entity_ids.length === 0)
560
+ shot.entity_ids = [];
561
+ // The selected still and clip. A file not among the takes becomes a take as well.
562
+ for (const [slot, versions, type] of [["keyframe", "keyframe_versions", "image"], ["clip", "clip_versions", "video"]]) {
563
+ const uri = p[slot];
564
+ if (uri) {
565
+ const found = sameRef(stored?.[slot], uri) ? stored?.[slot] : recList(stored?.[versions]).find((v) => sameRef(v, uri));
566
+ const ref = found ? clone(found) : { type, uri, asset_id: assetIdOf(uri) };
567
+ shot[slot] = ref;
568
+ if (!found)
569
+ shot[versions] = [...recList(shot[versions]), clone(ref)];
570
+ }
571
+ else if (stored && slot in stored)
572
+ shot[slot] = null;
573
+ }
574
+ if (p.scene)
575
+ shot.scene_id = p.scene;
576
+ // What normalizeStoryboardShot gives a new shot.
577
+ if (!isString(shot.status))
578
+ shot.status = "planned";
579
+ return shot;
580
+ });
581
+ /* — transitions and continuities, written on the shot they start from — */
582
+ const transitions = [];
583
+ const continuities = [];
584
+ shots.forEach((p, i) => {
585
+ for (const raw of p.repeated.transition ?? []) {
586
+ const links = readShotLinks(raw);
587
+ const to = links[0] && order.has(links[0].id) ? links[0].id : shots[i + 1]?.id;
588
+ if (!to) {
589
+ note(p.line, "no_next_shot", `Shot ${i + 1}: a transition leads to the next shot, and there is none.`, { shot: i + 1 });
590
+ continue;
591
+ }
592
+ const direction = stripShotLinks(raw);
593
+ const stored = baseTransitions.find((t) => t.from_shot_id === p.id && t.to_shot_id === to);
594
+ const transition = stored ? clone(stored) : {};
595
+ transition.from_shot_id = p.id;
596
+ transition.to_shot_id = to;
597
+ if (direction)
598
+ transition.direction = direction;
599
+ else if (!(stored && isEmptyValue(stored.direction)))
600
+ delete transition.direction;
601
+ transitions.push(transition);
602
+ }
603
+ for (const raw of p.repeated.continuity ?? []) {
604
+ const anchor = findAnchor(raw);
605
+ const body = withoutAnchor(raw, anchor);
606
+ const links = readShotLinks(body);
607
+ let ids = [p.id];
608
+ const until = links[0] && /^\s*until\s*\[/i.test(body) ? order.get(links[0].id) : undefined;
609
+ if (until !== undefined)
610
+ ids = shots.slice(i, until + 1).map((s) => s.id);
611
+ else
612
+ for (const l of links)
613
+ if (order.has(l.id) && !ids.includes(l.id))
614
+ ids.push(l.id);
615
+ const direction = stripShotLinks(body.replace(/^\s*(until|with)\s+/i, "")).replace(/^[—–:-]\s*/, "");
616
+ const id = anchor?.id ?? `${p.id}-continuity-${continuities.length + 1}`;
617
+ const stored = baseContinuities.get(id);
618
+ const continuity = stored ? clone(stored) : {};
619
+ Object.assign(continuity, { id, shot_ids: keepOrder(ids, stored?.shot_ids), direction });
620
+ continuities.push(continuity);
621
+ }
622
+ });
623
+ /* — the document — */
624
+ const F = board.fields;
625
+ const read = (key) => (F[key] !== undefined ? readEntityMentions(F[key], entities).text : undefined);
626
+ const doc = base ? clone(base) : { setupStage: "done", directorModel: null, imageModel: null, videoModel: null };
627
+ doc.brief = board.brief.join("\n\n");
628
+ doc.style = read("style") ?? "";
629
+ doc.aspectRatio = read("aspectRatio")?.trim() || str(base?.aspectRatio) || "16:9";
630
+ // Keys the schema defaults are left out when the stored board left them out.
631
+ const genre = read("genre")?.trim();
632
+ if (genre || !base || "genre" in base)
633
+ doc.genre = genre ?? "";
634
+ if (F.entityIds !== undefined)
635
+ doc.entityIds = keepOrder(readEntityMentions(F.entityIds, entities).ids, base?.entityIds);
636
+ else if (!base || "entityIds" in base)
637
+ doc.entityIds = [];
638
+ const look = F.look_preset_ids !== undefined ? splitIds(F.look_preset_ids) : [];
639
+ if (look.length)
640
+ doc.look_preset_ids = look;
641
+ else if (base && "look_preset_ids" in base && isEmptyValue(base.look_preset_ids))
642
+ doc.look_preset_ids = clone(base.look_preset_ids);
643
+ else
644
+ delete doc.look_preset_ids;
645
+ doc.shots = outShots;
646
+ const wantsScreenplay = baseScreenplay || board.title !== null || acts.length || scenes.length || F.logline || F.music_prompt || F.narration || F.motion_direction;
647
+ if (!wantsScreenplay)
648
+ doc.screenplay = null;
649
+ else {
650
+ const sp = baseScreenplay ? clone(baseScreenplay) : {};
651
+ sp.type = "screenplay";
652
+ sp.id = board.titleId ?? str(baseScreenplay?.id) ?? newId();
653
+ sp.title = board.title ?? "";
654
+ const optional = (key, value) => {
655
+ if (value)
656
+ sp[key] = value;
657
+ else if (baseScreenplay && key in baseScreenplay && isEmptyValue(baseScreenplay[key]))
658
+ sp[key] = clone(baseScreenplay[key]);
659
+ else
660
+ delete sp[key];
661
+ };
662
+ optional("logline", read("logline"));
663
+ optional("music_prompt", read("music_prompt"));
664
+ optional("narration", read("narration"));
665
+ // The screenplay keeps copies of board values. A copy that matched the board keeps matching it.
666
+ for (const [spKey, docKey] of [["brief", "brief"], ["style_bible", "style"], ["aspect_ratio", "aspectRatio"], ["genre", "genre"], ["entity_ids", "entityIds"]]) {
667
+ if (base && baseScreenplay && spKey in baseScreenplay && JSON.stringify(baseScreenplay[spKey]) === JSON.stringify(base[docKey]))
668
+ sp[spKey] = clone(doc[docKey]);
669
+ }
670
+ const ordered = (list, stored) => {
671
+ const storedOrder = [...stored.keys()];
672
+ return sameSet(storedOrder, list.map((x) => x.id)) ? storedOrder.map((id) => list.find((x) => x.id === id)) : list;
673
+ };
674
+ if (acts.length || (baseScreenplay && "acts" in baseScreenplay)) {
675
+ sp.acts = ordered(acts, baseActs).map((a) => {
676
+ const stored = baseActs.get(a.id);
677
+ const out = stored ? clone(stored) : {};
678
+ Object.assign(out, { type: "act", id: a.id, title: a.title });
679
+ const objective = readEntityMentions(a.objective.join("\n\n"), entities).text;
680
+ if (objective)
681
+ out.objective = objective;
682
+ else if (!(stored && isEmptyValue(stored.objective)))
683
+ delete out.objective;
684
+ return out;
685
+ });
686
+ }
687
+ if (scenes.length || (baseScreenplay && "scenes" in baseScreenplay)) {
688
+ sp.scenes = ordered(scenes, baseScenes).map((s) => {
689
+ const stored = baseScenes.get(s.id);
690
+ const out = stored ? clone(stored) : {};
691
+ Object.assign(out, { type: "scene", id: s.id, slugline: s.slugline });
692
+ const lighting = s.lighting !== undefined ? readEntityMentions(s.lighting, entities).text : undefined;
693
+ if (lighting)
694
+ out.lighting = lighting;
695
+ else if (!(stored && isEmptyValue(stored.lighting)))
696
+ delete out.lighting;
697
+ if (s.act)
698
+ out.act_id = s.act;
699
+ else
700
+ delete out.act_id;
701
+ return out;
702
+ });
703
+ }
704
+ const motion = baseMotion ? clone(baseMotion) : {};
705
+ const direction = read("motion_direction");
706
+ if (direction)
707
+ motion.direction = direction;
708
+ else if (!(baseMotion && isEmptyValue(baseMotion.direction)))
709
+ delete motion.direction;
710
+ if (transitions.length || (baseMotion && "transitions" in baseMotion))
711
+ motion.transitions = transitions;
712
+ else
713
+ delete motion.transitions;
714
+ if (continuities.length || (baseMotion && "continuities" in baseMotion))
715
+ motion.continuities = continuities;
716
+ else
717
+ delete motion.continuities;
718
+ if (Object.keys(motion).length || (baseScreenplay && "motion_design" in baseScreenplay))
719
+ sp.motion_design = motion;
720
+ else
721
+ delete sp.motion_design;
722
+ sp.shots = outShots;
723
+ doc.screenplay = sp;
724
+ }
725
+ for (const m of info) {
726
+ if (m.role !== "shot" || m.shotNumber === undefined)
727
+ continue;
728
+ const shot = outShots[m.shotNumber - 1];
729
+ m.status = str(shot.status);
730
+ if (!str(shot.action)?.trim())
731
+ warn(m, "missing_action", `Shot ${m.shotNumber} has no action yet. Write the visual to render under its heading.`, { shot: m.shotNumber });
732
+ }
733
+ // SAFETY: built key by key from the schema's own keys, starting from the
734
+ // stored document; the round-trip and schema tests pin the shape.
735
+ return { document: doc, lines: info, warnings, missingIds, shotOrder: shots.map((s) => s.id) };
736
+ }
737
+ /* ── document → Markdown ─────────────────────────────────────────────── */
738
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
739
+ /** Write the first mention of each entity in a value as a link. */
740
+ function linkNames(value, ids, entities, linked) {
741
+ let out = value;
742
+ for (const id of ids) {
743
+ const name = entities?.get(id)?.name.trim();
744
+ if (linked.has(id) || !name)
745
+ continue;
746
+ const at = out.toLowerCase().search(new RegExp(`(?<![\\w\\[])${escapeRe(name.toLowerCase())}(?![\\w\\]])`));
747
+ if (at < 0)
748
+ continue;
749
+ const before = out.slice(0, at);
750
+ // Never inside an existing link.
751
+ if ((before.match(/\[/g) ?? []).length > (before.match(/\]/g) ?? []).length)
752
+ continue;
753
+ out = `${before}[${out.slice(at, at + name.length)}](entity://${id})${out.slice(at + name.length)}`;
754
+ linked.add(id);
755
+ }
756
+ return out;
757
+ }
758
+ /** Write a storyboard document as Markdown. */
759
+ export function storyboardToMarkdown(document, options = {}) {
760
+ const doc = document;
761
+ const entities = options.entities;
762
+ const sp = isRec(doc.screenplay) ? doc.screenplay : null;
763
+ const shots = recList(doc.shots).length ? recList(doc.shots) : recList(sp?.shots);
764
+ const L = [];
765
+ const paragraphs = (value) => value.trim().split(/\n\n+/).flatMap((p, i) => (i ? ["", ...p.split("\n")] : p.split("\n")));
766
+ const writeField = (label, value) => {
767
+ const text = isString(value) ? value.trim() : "";
768
+ if (text)
769
+ text.split("\n").forEach((line, i) => L.push(i ? line : `- **${label}:** ${line}`));
770
+ };
771
+ const mention = (id) => `[${entities?.get(id)?.name || id}](entity://${id})`;
772
+ if (sp)
773
+ L.push(`# ${str(sp.title) ? `${str(sp.title)} ` : ""}{#${str(sp.id) ?? ""}}`);
774
+ const brief = str(doc.brief)?.trim();
775
+ if (brief)
776
+ L.push(...(L.length ? [""] : []), ...paragraphs(brief));
777
+ const meta = [];
778
+ const metaLine = (label, value) => { const v = isString(value) ? value.trim() : ""; if (v)
779
+ meta.push([label, v]); };
780
+ metaLine("Logline", sp?.logline);
781
+ metaLine("Style", doc.style);
782
+ metaLine("Aspect ratio", doc.aspectRatio);
783
+ metaLine("Genre", doc.genre);
784
+ metaLine("Cast", strList(doc.entityIds).map(mention).join(", "));
785
+ metaLine("Look", strList(doc.look_preset_ids).join(", "));
786
+ metaLine("Music", sp?.music_prompt);
787
+ metaLine("Narration", sp?.narration);
788
+ metaLine("Motion design", isRec(sp?.motion_design) ? sp.motion_design.direction : undefined);
789
+ if (meta.length) {
790
+ if (L.length)
791
+ L.push("");
792
+ for (const [label, value] of meta)
793
+ writeField(label, value);
794
+ }
795
+ const acts = new Map(recList(sp?.acts).map((a) => [str(a.id) ?? "", a]));
796
+ const scenes = new Map(recList(sp?.scenes).map((s) => [str(s.id) ?? "", s]));
797
+ const number = new Map(shots.map((s, i) => [str(s.id) ?? "", i + 1]));
798
+ const link = (id) => `[Shot ${number.get(id)}](#${id})`;
799
+ const motion = isRec(sp?.motion_design) ? sp.motion_design : null;
800
+ const transitions = recList(motion?.transitions);
801
+ const continuities = recList(motion?.continuities);
802
+ const firstShotOf = (c) => strList(c.shot_ids).slice().sort((a, b) => (number.get(a) ?? 1e9) - (number.get(b) ?? 1e9))[0];
803
+ const writtenActs = new Set();
804
+ const writtenScenes = new Set();
805
+ const writeAct = (a) => {
806
+ L.push("", `# ${str(a.title) ? `${str(a.title)} ` : ""}{#${str(a.id)}}`);
807
+ const objective = str(a.objective)?.trim();
808
+ if (objective)
809
+ L.push(...paragraphs(objective));
810
+ writtenActs.add(str(a.id) ?? "");
811
+ };
812
+ const writeScene = (s) => {
813
+ L.push("", `## ${str(s.slugline) ? `${str(s.slugline)} ` : ""}{#${str(s.id)}}`);
814
+ writeField("Lighting", s.lighting);
815
+ writtenScenes.add(str(s.id) ?? "");
816
+ };
817
+ let previousScene;
818
+ let previousAct;
819
+ shots.forEach((s, i) => {
820
+ const id = str(s.id) ?? "";
821
+ const sceneId = str(s.scene_id);
822
+ const sc = sceneId ? scenes.get(sceneId) : undefined;
823
+ if (sc && sceneId !== previousScene) {
824
+ const actId = str(sc.act_id);
825
+ const a = actId ? acts.get(actId) : undefined;
826
+ if (a && actId !== previousAct && !writtenActs.has(actId ?? ""))
827
+ writeAct(a);
828
+ if (a)
829
+ previousAct = actId;
830
+ writeScene(sc);
831
+ previousScene = sceneId;
832
+ }
833
+ L.push("", `### ${str(s.slug) ? `${str(s.slug)} ` : ""}{#${id}}`);
834
+ const still = refUri(s.keyframe), clip = refUri(s.clip);
835
+ if (still)
836
+ L.push(`![Still](${still})`);
837
+ if (clip)
838
+ L.push(`![Clip](${clip})`);
839
+ const ids = strList(s.entity_ids);
840
+ const linked = new Set();
841
+ const prose = (v) => (isString(v) && v ? linkNames(v, ids, entities, linked) : undefined);
842
+ const action = prose(str(s.action)?.trim());
843
+ if (still || clip)
844
+ L.push("");
845
+ if (action)
846
+ L.push(...paragraphs(action));
847
+ const fields = [];
848
+ const add = (label, value) => { if (isString(value) && value.trim() !== "")
849
+ fields.push([label, value]); };
850
+ const camera = isRec(s.camera) ? s.camera : {};
851
+ add("Framing", camera.framing);
852
+ add("Lens", camera.lens);
853
+ add("Angle", camera.angle);
854
+ add("Camera movement", camera.movement);
855
+ add("Rig", camera.equipment);
856
+ add("Camera presets", strList(camera.preset_ids).join(", "));
857
+ add("Motion", prose(s.motion));
858
+ add("End", prose(s.end_state));
859
+ add("Sound", prose(s.sound));
860
+ add("Dialogue", prose(s.dialogue));
861
+ add("Narration", prose(s.narration));
862
+ if (isNumber(s.duration_seconds))
863
+ add("Duration", `${s.duration_seconds}s`);
864
+ add("Render", s.render_mode);
865
+ if (str(s.location_id))
866
+ add("Location", mention(str(s.location_id) ?? ""));
867
+ add("Cast", ids.filter((e) => !linked.has(e)).map(mention).join(", "));
868
+ add("Look", strList(s.look_preset_ids).join(", "));
869
+ for (const t of transitions.filter((t) => t.from_shot_id === id && number.has(str(t.to_shot_id) ?? ""))) {
870
+ const to = str(t.to_shot_id) ?? "";
871
+ const value = `${str(shots[i + 1]?.id) === to ? "" : `${link(to)} `}${str(t.direction) ?? ""}`.trim();
872
+ fields.push(["Transition", value]);
873
+ }
874
+ for (const c of continuities.filter((c) => firstShotOf(c) === id)) {
875
+ const rest = strList(c.shot_ids).filter((x) => x !== id && number.has(x)).sort((a, b) => (number.get(a) ?? 0) - (number.get(b) ?? 0));
876
+ const contiguous = rest.length > 0 && rest.every((x, j) => number.get(x) === i + 2 + j);
877
+ const span = !rest.length ? "" : contiguous ? `until ${link(rest[rest.length - 1])} — ` : `with ${rest.map(link).join(" ")} — `;
878
+ fields.push(["Continuity", `${span}${str(c.direction) ?? ""} {#${str(c.id)}}`]);
879
+ }
880
+ add("Notes", prose(s.notes));
881
+ if (fields.length) {
882
+ L.push("");
883
+ for (const [label, value] of fields) {
884
+ if (!value.trim())
885
+ L.push(`- **${label}:**`);
886
+ else
887
+ writeField(label, value);
888
+ }
889
+ }
890
+ });
891
+ // Acts and scenes no shot is in yet are kept at the end, so they survive a round trip.
892
+ for (const sc of scenes.values()) {
893
+ if (writtenScenes.has(str(sc.id) ?? ""))
894
+ continue;
895
+ const a = str(sc.act_id) ? acts.get(str(sc.act_id) ?? "") : undefined;
896
+ if (a && !writtenActs.has(str(a.id) ?? ""))
897
+ writeAct(a);
898
+ writeScene(sc);
899
+ }
900
+ for (const a of acts.values())
901
+ if (!writtenActs.has(str(a.id) ?? ""))
902
+ writeAct(a);
903
+ return L.join("\n") + "\n";
904
+ }
905
+ //# sourceMappingURL=storyboard-markdown.js.map