@depths/waves 0.1.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.
package/dist/cli.js ADDED
@@ -0,0 +1,1107 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/cli.ts
32
+ var cli_exports = {};
33
+ __export(cli_exports, {
34
+ main: () => main
35
+ });
36
+ module.exports = __toCommonJS(cli_exports);
37
+ var import_promises2 = __toESM(require("fs/promises"));
38
+ var import_node_path2 = __toESM(require("path"));
39
+
40
+ // src/version.ts
41
+ var __wavesVersion = "0.1.0";
42
+
43
+ // src/utils/json-schema.ts
44
+ var import_zod = require("zod");
45
+ function zodSchemaToJsonSchema(schema) {
46
+ return import_zod.z.toJSONSchema(schema);
47
+ }
48
+
49
+ // src/ir/schema.ts
50
+ var import_zod2 = require("zod");
51
+ var TimingSpecSchema = import_zod2.z.object({
52
+ from: import_zod2.z.number().int().min(0).describe("Start frame (0-indexed)"),
53
+ durationInFrames: import_zod2.z.number().int().positive().describe("Duration in frames")
54
+ });
55
+ var AssetPathSchema = import_zod2.z.string().refine(
56
+ (path3) => path3.startsWith("/") || path3.startsWith("http://") || path3.startsWith("https://"),
57
+ "Asset path must be absolute (starting with /) or a full URL"
58
+ ).describe("Path to asset file, either absolute path or URL");
59
+ var BackgroundSpecSchema = import_zod2.z.discriminatedUnion("type", [
60
+ import_zod2.z.object({
61
+ type: import_zod2.z.literal("color"),
62
+ value: import_zod2.z.string().regex(/^#[0-9A-Fa-f]{6}$/, "Must be valid hex color")
63
+ }),
64
+ import_zod2.z.object({
65
+ type: import_zod2.z.literal("image"),
66
+ value: AssetPathSchema
67
+ }),
68
+ import_zod2.z.object({
69
+ type: import_zod2.z.literal("video"),
70
+ value: AssetPathSchema
71
+ })
72
+ ]);
73
+ var BaseComponentIRSchema = import_zod2.z.object({
74
+ id: import_zod2.z.string().min(1).max(100).describe("Unique component instance ID"),
75
+ type: import_zod2.z.string().min(1).describe("Component type identifier"),
76
+ timing: TimingSpecSchema,
77
+ metadata: import_zod2.z.record(import_zod2.z.string(), import_zod2.z.unknown()).optional().describe("Optional metadata")
78
+ });
79
+ var TextComponentIRSchema = BaseComponentIRSchema.extend({
80
+ type: import_zod2.z.literal("Text"),
81
+ props: import_zod2.z.object({
82
+ content: import_zod2.z.string().min(1).max(1e3),
83
+ fontSize: import_zod2.z.number().int().min(12).max(200).default(48),
84
+ color: import_zod2.z.string().regex(/^#[0-9A-Fa-f]{6}$/).default("#FFFFFF"),
85
+ position: import_zod2.z.enum(["top", "center", "bottom", "left", "right"]).default("center"),
86
+ animation: import_zod2.z.enum(["none", "fade", "slide", "zoom"]).default("fade")
87
+ })
88
+ });
89
+ var AudioComponentIRSchema = BaseComponentIRSchema.extend({
90
+ type: import_zod2.z.literal("Audio"),
91
+ props: import_zod2.z.object({
92
+ src: AssetPathSchema,
93
+ volume: import_zod2.z.number().min(0).max(1).default(1),
94
+ startFrom: import_zod2.z.number().int().min(0).default(0).describe("Start playback from frame N"),
95
+ fadeIn: import_zod2.z.number().int().min(0).default(0).describe("Fade in duration in frames"),
96
+ fadeOut: import_zod2.z.number().int().min(0).default(0).describe("Fade out duration in frames")
97
+ })
98
+ });
99
+ function getComponentIRSchema() {
100
+ return ComponentIRSchema;
101
+ }
102
+ var SceneComponentIRSchema = BaseComponentIRSchema.extend({
103
+ type: import_zod2.z.literal("Scene"),
104
+ props: import_zod2.z.object({
105
+ background: BackgroundSpecSchema
106
+ }),
107
+ children: import_zod2.z.lazy(() => import_zod2.z.array(getComponentIRSchema())).optional()
108
+ });
109
+ var ComponentIRSchema = import_zod2.z.discriminatedUnion("type", [
110
+ SceneComponentIRSchema,
111
+ TextComponentIRSchema,
112
+ AudioComponentIRSchema
113
+ ]);
114
+ var VideoIRSchema = import_zod2.z.object({
115
+ version: import_zod2.z.literal("1.0").describe("IR schema version"),
116
+ video: import_zod2.z.object({
117
+ id: import_zod2.z.string().default("main"),
118
+ width: import_zod2.z.number().int().min(360).max(7680),
119
+ height: import_zod2.z.number().int().min(360).max(4320),
120
+ fps: import_zod2.z.number().int().min(1).max(120).default(30),
121
+ durationInFrames: import_zod2.z.number().int().positive()
122
+ }),
123
+ audio: import_zod2.z.object({
124
+ background: AssetPathSchema.optional(),
125
+ volume: import_zod2.z.number().min(0).max(1).default(0.5)
126
+ }).optional(),
127
+ scenes: import_zod2.z.array(SceneComponentIRSchema).min(1)
128
+ });
129
+
130
+ // src/core/registry.ts
131
+ var ComponentRegistry = class {
132
+ components = /* @__PURE__ */ new Map();
133
+ register(registration) {
134
+ if (this.components.has(registration.type)) {
135
+ throw new Error(`Component type "${registration.type}" is already registered`);
136
+ }
137
+ this.components.set(registration.type, registration);
138
+ }
139
+ get(type) {
140
+ return this.components.get(type);
141
+ }
142
+ getTypes() {
143
+ return Array.from(this.components.keys());
144
+ }
145
+ has(type) {
146
+ return this.components.has(type);
147
+ }
148
+ getJSONSchemaForLLM() {
149
+ const schemas = {};
150
+ for (const [type, registration] of this.components) {
151
+ schemas[type] = {
152
+ schema: zodSchemaToJsonSchema(registration.propsSchema),
153
+ metadata: registration.metadata
154
+ };
155
+ }
156
+ return schemas;
157
+ }
158
+ validateProps(type, props) {
159
+ const registration = this.components.get(type);
160
+ if (!registration) {
161
+ throw new Error(`Unknown component type: ${type}`);
162
+ }
163
+ const result = registration.propsSchema.safeParse(props);
164
+ if (result.success) {
165
+ return { success: true, data: result.data };
166
+ }
167
+ return { success: false, error: result.error };
168
+ }
169
+ };
170
+ var globalRegistry = new ComponentRegistry();
171
+
172
+ // src/components/primitives/Audio.tsx
173
+ var import_remotion = require("remotion");
174
+ var import_zod3 = require("zod");
175
+
176
+ // src/utils/assets.ts
177
+ function isRemoteAssetPath(assetPath) {
178
+ return assetPath.startsWith("http://") || assetPath.startsWith("https://");
179
+ }
180
+ function staticFileInputFromAssetPath(assetPath) {
181
+ if (isRemoteAssetPath(assetPath)) {
182
+ throw new Error("Remote asset paths must not be passed to staticFile()");
183
+ }
184
+ return assetPath.startsWith("/") ? assetPath.slice(1) : assetPath;
185
+ }
186
+
187
+ // src/components/primitives/Audio.tsx
188
+ var import_jsx_runtime = require("react/jsx-runtime");
189
+ var AudioPropsSchema = import_zod3.z.object({
190
+ src: import_zod3.z.string(),
191
+ volume: import_zod3.z.number().min(0).max(1).default(1),
192
+ startFrom: import_zod3.z.number().int().min(0).default(0),
193
+ fadeIn: import_zod3.z.number().int().min(0).default(0),
194
+ fadeOut: import_zod3.z.number().int().min(0).default(0)
195
+ });
196
+ var Audio = ({
197
+ src,
198
+ volume,
199
+ startFrom,
200
+ fadeIn,
201
+ fadeOut,
202
+ __wavesDurationInFrames
203
+ }) => {
204
+ const frame = (0, import_remotion.useCurrentFrame)();
205
+ const durationInFrames = __wavesDurationInFrames ?? Number.POSITIVE_INFINITY;
206
+ const fadeInFactor = fadeIn > 0 ? (0, import_remotion.interpolate)(frame, [0, fadeIn], [0, 1], {
207
+ extrapolateLeft: "clamp",
208
+ extrapolateRight: "clamp"
209
+ }) : 1;
210
+ const fadeOutStart = durationInFrames - fadeOut;
211
+ const fadeOutFactor = fadeOut > 0 ? (0, import_remotion.interpolate)(frame, [fadeOutStart, durationInFrames], [1, 0], {
212
+ extrapolateLeft: "clamp",
213
+ extrapolateRight: "clamp"
214
+ }) : 1;
215
+ const resolvedSrc = isRemoteAssetPath(src) ? src : (0, import_remotion.staticFile)(staticFileInputFromAssetPath(src));
216
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
217
+ import_remotion.Audio,
218
+ {
219
+ src: resolvedSrc,
220
+ trimBefore: startFrom,
221
+ volume: volume * fadeInFactor * fadeOutFactor
222
+ }
223
+ );
224
+ };
225
+ var AudioComponentMetadata = {
226
+ category: "primitive",
227
+ description: "Plays an audio file with optional trimming and fade in/out",
228
+ llmGuidance: "Use for background music or sound effects. Prefer short clips for SFX. Use fadeIn/fadeOut (in frames) for smoother audio starts/ends."
229
+ };
230
+
231
+ // src/components/primitives/Scene.tsx
232
+ var import_remotion2 = require("remotion");
233
+ var import_zod4 = require("zod");
234
+ var import_jsx_runtime2 = require("react/jsx-runtime");
235
+ var ScenePropsSchema = import_zod4.z.object({
236
+ background: BackgroundSpecSchema
237
+ });
238
+ var resolveAsset = (value) => {
239
+ return isRemoteAssetPath(value) ? value : (0, import_remotion2.staticFile)(staticFileInputFromAssetPath(value));
240
+ };
241
+ var Scene = ({ background, children }) => {
242
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_remotion2.AbsoluteFill, { children: [
243
+ background.type === "color" ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_remotion2.AbsoluteFill, { style: { backgroundColor: background.value } }) : background.type === "image" ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
244
+ import_remotion2.Img,
245
+ {
246
+ src: resolveAsset(background.value),
247
+ style: { width: "100%", height: "100%", objectFit: "cover" }
248
+ }
249
+ ) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
250
+ import_remotion2.Video,
251
+ {
252
+ src: resolveAsset(background.value),
253
+ style: { width: "100%", height: "100%", objectFit: "cover" }
254
+ }
255
+ ),
256
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_remotion2.AbsoluteFill, { children })
257
+ ] });
258
+ };
259
+ var SceneComponentMetadata = {
260
+ category: "primitive",
261
+ description: "Scene container with a background and nested children",
262
+ llmGuidance: "Use Scene to define a segment of the video. Scene timings must be sequential with no gaps. Put Text and Audio as children."
263
+ };
264
+
265
+ // src/components/primitives/Text.tsx
266
+ var import_remotion3 = require("remotion");
267
+ var import_zod5 = require("zod");
268
+ var import_jsx_runtime3 = require("react/jsx-runtime");
269
+ var TextPropsSchema = import_zod5.z.object({
270
+ content: import_zod5.z.string(),
271
+ fontSize: import_zod5.z.number().default(48),
272
+ color: import_zod5.z.string().default("#FFFFFF"),
273
+ position: import_zod5.z.enum(["top", "center", "bottom", "left", "right"]).default("center"),
274
+ animation: import_zod5.z.enum(["none", "fade", "slide", "zoom"]).default("fade")
275
+ });
276
+ var getPositionStyles = (position) => {
277
+ const base = {
278
+ display: "flex",
279
+ justifyContent: "center",
280
+ alignItems: "center"
281
+ };
282
+ switch (position) {
283
+ case "top":
284
+ return { ...base, alignItems: "flex-start", paddingTop: 60 };
285
+ case "bottom":
286
+ return { ...base, alignItems: "flex-end", paddingBottom: 60 };
287
+ case "left":
288
+ return { ...base, justifyContent: "flex-start", paddingLeft: 60 };
289
+ case "right":
290
+ return { ...base, justifyContent: "flex-end", paddingRight: 60 };
291
+ default:
292
+ return base;
293
+ }
294
+ };
295
+ var getAnimationStyle = (frame, animation) => {
296
+ const animDuration = 30;
297
+ switch (animation) {
298
+ case "fade": {
299
+ const opacity = (0, import_remotion3.interpolate)(frame, [0, animDuration], [0, 1], {
300
+ extrapolateLeft: "clamp",
301
+ extrapolateRight: "clamp"
302
+ });
303
+ return { opacity };
304
+ }
305
+ case "slide": {
306
+ const translateY = (0, import_remotion3.interpolate)(frame, [0, animDuration], [50, 0], {
307
+ extrapolateLeft: "clamp",
308
+ extrapolateRight: "clamp"
309
+ });
310
+ const opacity = (0, import_remotion3.interpolate)(frame, [0, animDuration], [0, 1], {
311
+ extrapolateLeft: "clamp",
312
+ extrapolateRight: "clamp"
313
+ });
314
+ return { transform: `translateY(${translateY}px)`, opacity };
315
+ }
316
+ case "zoom": {
317
+ const scale = (0, import_remotion3.interpolate)(frame, [0, animDuration], [0.8, 1], {
318
+ extrapolateLeft: "clamp",
319
+ extrapolateRight: "clamp"
320
+ });
321
+ const opacity = (0, import_remotion3.interpolate)(frame, [0, animDuration], [0, 1], {
322
+ extrapolateLeft: "clamp",
323
+ extrapolateRight: "clamp"
324
+ });
325
+ return { transform: `scale(${scale})`, opacity };
326
+ }
327
+ default:
328
+ return {};
329
+ }
330
+ };
331
+ var Text = ({ content, fontSize, color, position, animation }) => {
332
+ const frame = (0, import_remotion3.useCurrentFrame)();
333
+ const positionStyles = getPositionStyles(position);
334
+ const animationStyles = getAnimationStyle(frame, animation);
335
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_remotion3.AbsoluteFill, { style: positionStyles, children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
336
+ "div",
337
+ {
338
+ style: {
339
+ fontSize,
340
+ color,
341
+ fontWeight: 600,
342
+ textAlign: "center",
343
+ ...animationStyles
344
+ },
345
+ children: content
346
+ }
347
+ ) });
348
+ };
349
+ var TextComponentMetadata = {
350
+ category: "primitive",
351
+ description: "Displays animated text with positioning and animation options",
352
+ llmGuidance: 'Use for titles, subtitles, captions. Keep content under 100 characters for readability. Position "center" works best for titles.',
353
+ examples: [
354
+ {
355
+ content: "Welcome to Waves",
356
+ fontSize: 72,
357
+ color: "#FFFFFF",
358
+ position: "center",
359
+ animation: "fade"
360
+ },
361
+ {
362
+ content: "Building the future of video",
363
+ fontSize: 36,
364
+ color: "#CCCCCC",
365
+ position: "bottom",
366
+ animation: "slide"
367
+ }
368
+ ]
369
+ };
370
+
371
+ // src/components/registry.ts
372
+ function registerBuiltInComponents() {
373
+ if (!globalRegistry.has("Scene")) {
374
+ globalRegistry.register({
375
+ type: "Scene",
376
+ component: Scene,
377
+ propsSchema: ScenePropsSchema,
378
+ metadata: SceneComponentMetadata
379
+ });
380
+ }
381
+ if (!globalRegistry.has("Text")) {
382
+ globalRegistry.register({
383
+ type: "Text",
384
+ component: Text,
385
+ propsSchema: TextPropsSchema,
386
+ metadata: TextComponentMetadata
387
+ });
388
+ }
389
+ if (!globalRegistry.has("Audio")) {
390
+ globalRegistry.register({
391
+ type: "Audio",
392
+ component: Audio,
393
+ propsSchema: AudioPropsSchema,
394
+ metadata: AudioComponentMetadata
395
+ });
396
+ }
397
+ }
398
+
399
+ // src/llm/prompt.ts
400
+ var RULES = {
401
+ timing: [
402
+ "All timing is in frames (integers).",
403
+ "Every component has timing: { from, durationInFrames }.",
404
+ "Scenes must be sequential: scene[0].timing.from = 0 and each next scene starts where the previous ends (no gaps/overlaps).",
405
+ "Sum of all scene durations must equal video.durationInFrames.",
406
+ "Child components inside a Scene must fit within the Scene duration."
407
+ ],
408
+ assets: [
409
+ 'Asset paths must be either full URLs (http:// or https://) or absolute public paths starting with "/".',
410
+ 'When using absolute public paths ("/assets/..."), the renderer resolves them relative to the --publicDir passed at render time.'
411
+ ],
412
+ ids: [
413
+ "Every component must have a stable string id.",
414
+ "Ids should be unique within the whole IR."
415
+ ],
416
+ output: [
417
+ "Return only a single JSON object (no markdown fences, no commentary).",
418
+ "The JSON must validate against the provided JSON Schemas.",
419
+ 'Only use component "type" values that exist in schemas.components.'
420
+ ]
421
+ };
422
+ function getSystemPrompt(registeredTypes) {
423
+ const typesLine = registeredTypes.length ? registeredTypes.join(", ") : "(none)";
424
+ return [
425
+ "You generate JSON for @depths/waves Video IR (version 1.0).",
426
+ "",
427
+ "Goal:",
428
+ "- Produce a single JSON object that conforms to the provided Video IR JSON Schema and uses only registered component types.",
429
+ "",
430
+ "Registered component types:",
431
+ `- ${typesLine}`,
432
+ "",
433
+ "Authoring rules:",
434
+ ...RULES.output.map((r) => `- ${r}`),
435
+ ...RULES.timing.map((r) => `- ${r}`),
436
+ ...RULES.assets.map((r) => `- ${r}`),
437
+ ...RULES.ids.map((r) => `- ${r}`),
438
+ "",
439
+ "If you are unsure about an asset, prefer a solid color Scene background and omit optional props to use defaults.",
440
+ ""
441
+ ].join("\n");
442
+ }
443
+ function getPromptPayload(options) {
444
+ registerBuiltInComponents();
445
+ const registry = options?.registry ?? globalRegistry;
446
+ const types = registry.getTypes().sort();
447
+ return {
448
+ package: "@depths/waves",
449
+ version: __wavesVersion,
450
+ irVersion: "1.0",
451
+ systemPrompt: getSystemPrompt(types),
452
+ schemas: {
453
+ videoIR: zodSchemaToJsonSchema(VideoIRSchema),
454
+ components: registry.getJSONSchemaForLLM()
455
+ },
456
+ rules: {
457
+ timing: [...RULES.timing],
458
+ assets: [...RULES.assets],
459
+ ids: [...RULES.ids],
460
+ output: [...RULES.output]
461
+ }
462
+ };
463
+ }
464
+
465
+ // src/core/validator.ts
466
+ var IRValidator = class {
467
+ validateSchema(ir) {
468
+ const result = VideoIRSchema.safeParse(ir);
469
+ if (!result.success) {
470
+ return {
471
+ success: false,
472
+ errors: result.error.issues.map((issue) => ({
473
+ path: issue.path.map((p) => String(p)),
474
+ message: issue.message,
475
+ code: issue.code
476
+ }))
477
+ };
478
+ }
479
+ return { success: true, data: result.data };
480
+ }
481
+ validateSemantics(ir) {
482
+ const errors = [];
483
+ const totalSceneDuration = ir.scenes.reduce((sum, scene) => sum + scene.timing.durationInFrames, 0);
484
+ if (totalSceneDuration !== ir.video.durationInFrames) {
485
+ errors.push({
486
+ path: ["scenes"],
487
+ message: `Sum of scene durations (${totalSceneDuration}) does not match video duration (${ir.video.durationInFrames})`,
488
+ code: "DURATION_MISMATCH"
489
+ });
490
+ }
491
+ let expectedFrame = 0;
492
+ for (const [i, scene] of ir.scenes.entries()) {
493
+ if (scene.timing.from !== expectedFrame) {
494
+ errors.push({
495
+ path: ["scenes", String(i), "timing", "from"],
496
+ message: `Scene ${i} starts at frame ${scene.timing.from}, expected ${expectedFrame}`,
497
+ code: "TIMING_GAP_OR_OVERLAP"
498
+ });
499
+ }
500
+ expectedFrame += scene.timing.durationInFrames;
501
+ }
502
+ for (const [i, scene] of ir.scenes.entries()) {
503
+ if (scene.children && scene.children.length > 0) {
504
+ this.validateComponentTimingRecursive(
505
+ scene.children,
506
+ scene.timing.durationInFrames,
507
+ ["scenes", String(i)],
508
+ errors
509
+ );
510
+ }
511
+ }
512
+ if (errors.length > 0) {
513
+ return { success: false, errors };
514
+ }
515
+ return { success: true };
516
+ }
517
+ validate(ir) {
518
+ const schemaResult = this.validateSchema(ir);
519
+ if (!schemaResult.success) {
520
+ return schemaResult;
521
+ }
522
+ const semanticsResult = this.validateSemantics(schemaResult.data);
523
+ if (!semanticsResult.success) {
524
+ return { success: false, errors: semanticsResult.errors ?? [] };
525
+ }
526
+ return schemaResult;
527
+ }
528
+ validateComponentTimingRecursive(components, parentDuration, pathPrefix, errors) {
529
+ for (const [i, component] of components.entries()) {
530
+ const componentEnd = component.timing.from + component.timing.durationInFrames;
531
+ if (componentEnd > parentDuration) {
532
+ errors.push({
533
+ path: [...pathPrefix, "children", String(i), "timing"],
534
+ message: `Component extends beyond parent duration (${componentEnd} > ${parentDuration})`,
535
+ code: "COMPONENT_EXCEEDS_PARENT"
536
+ });
537
+ }
538
+ if (component.type === "Scene" && component.children && component.children.length > 0) {
539
+ this.validateComponentTimingRecursive(
540
+ component.children,
541
+ component.timing.durationInFrames,
542
+ [...pathPrefix, "children", String(i)],
543
+ errors
544
+ );
545
+ }
546
+ }
547
+ }
548
+ };
549
+
550
+ // src/core/engine.ts
551
+ var import_bundler = require("@remotion/bundler");
552
+ var import_renderer = require("@remotion/renderer");
553
+ var import_promises = __toESM(require("fs/promises"));
554
+ var import_node_path = __toESM(require("path"));
555
+
556
+ // src/utils/errors.ts
557
+ var WavesError = class _WavesError extends Error {
558
+ constructor(message, context) {
559
+ super(message);
560
+ this.context = context;
561
+ this.name = "WavesError";
562
+ Object.setPrototypeOf(this, _WavesError.prototype);
563
+ }
564
+ };
565
+ var WavesRenderError = class _WavesRenderError extends WavesError {
566
+ constructor(message, context) {
567
+ super(message, context);
568
+ this.name = "WavesRenderError";
569
+ Object.setPrototypeOf(this, _WavesRenderError.prototype);
570
+ }
571
+ };
572
+
573
+ // src/core/engine.ts
574
+ var WavesEngine = class {
575
+ constructor(registry, validator) {
576
+ this.registry = registry;
577
+ this.validator = validator;
578
+ }
579
+ async render(ir, options) {
580
+ if (this.registry !== globalRegistry) {
581
+ throw new WavesRenderError("WavesEngine currently requires using globalRegistry", {
582
+ hint: "Use `registerBuiltInComponents()` + `globalRegistry` for both validation and rendering."
583
+ });
584
+ }
585
+ const validationResult = this.validator.validate(ir);
586
+ if (!validationResult.success) {
587
+ throw new WavesRenderError("IR validation failed", { errors: validationResult.errors });
588
+ }
589
+ const validatedIR = validationResult.data;
590
+ const requiredTypes = collectComponentTypes(validatedIR);
591
+ for (const type of requiredTypes) {
592
+ if (!this.registry.has(type)) {
593
+ throw new WavesRenderError("Unknown component type", { type });
594
+ }
595
+ }
596
+ const rootDir = options.rootDir ?? process.cwd();
597
+ const tmpDir = await import_promises.default.mkdtemp(import_node_path.default.join(rootDir, ".waves-tmp-"));
598
+ const entryPoint = import_node_path.default.join(tmpDir, "entry.tsx");
599
+ try {
600
+ await import_promises.default.writeFile(entryPoint, generateEntryPoint(validatedIR, options), "utf-8");
601
+ await import_promises.default.mkdir(import_node_path.default.dirname(options.outputPath), { recursive: true });
602
+ const bundleLocation = await (0, import_bundler.bundle)({
603
+ entryPoint,
604
+ rootDir,
605
+ publicDir: options.publicDir ?? null,
606
+ onProgress: () => void 0
607
+ });
608
+ const compositionId = validatedIR.video.id ?? "main";
609
+ const composition = await (0, import_renderer.selectComposition)({
610
+ serveUrl: bundleLocation,
611
+ id: compositionId,
612
+ inputProps: {}
613
+ });
614
+ await (0, import_renderer.renderMedia)({
615
+ composition,
616
+ serveUrl: bundleLocation,
617
+ codec: options.codec ?? "h264",
618
+ outputLocation: options.outputPath,
619
+ crf: options.crf ?? null,
620
+ concurrency: options.concurrency ?? null,
621
+ overwrite: true
622
+ });
623
+ } catch (error) {
624
+ throw new WavesRenderError("Rendering failed", { originalError: error });
625
+ } finally {
626
+ await import_promises.default.rm(tmpDir, { recursive: true, force: true });
627
+ }
628
+ }
629
+ };
630
+ function collectComponentTypes(ir) {
631
+ const types = /* @__PURE__ */ new Set();
632
+ for (const scene of ir.scenes) {
633
+ walkComponent(scene, types);
634
+ }
635
+ return types;
636
+ }
637
+ function walkComponent(component, types) {
638
+ types.add(component.type);
639
+ const children = component.children;
640
+ if (children) {
641
+ for (const child of children) {
642
+ walkComponent(child, types);
643
+ }
644
+ }
645
+ }
646
+ function generateEntryPoint(ir, options) {
647
+ const compositionId = ir.video.id ?? "main";
648
+ const width = ir.video.width;
649
+ const height = ir.video.height;
650
+ const fps = ir.video.fps ?? 30;
651
+ const durationInFrames = ir.video.durationInFrames;
652
+ const registrationImports = (options.registrationModules ?? []).map((m) => `import ${JSON.stringify(m)};`).join("\n");
653
+ return `import React from 'react';
654
+ import { Composition, registerRoot } from 'remotion';
655
+ import { WavesComposition, globalRegistry, registerBuiltInComponents } from '@depths/waves/remotion';
656
+ ${registrationImports}
657
+
658
+ registerBuiltInComponents();
659
+
660
+ const ir = ${JSON.stringify(ir, null, 2)};
661
+ const compositionId = ${JSON.stringify(compositionId)};
662
+
663
+ const Root = () => {
664
+ return <WavesComposition ir={ir} registry={globalRegistry} />;
665
+ };
666
+
667
+ export const RemotionRoot = () => {
668
+ return (
669
+ <Composition
670
+ id={compositionId}
671
+ component={Root}
672
+ durationInFrames={${durationInFrames}}
673
+ fps={${fps}}
674
+ width={${width}}
675
+ height={${height}}
676
+ />
677
+ );
678
+ };
679
+
680
+ registerRoot(RemotionRoot);
681
+ `;
682
+ }
683
+
684
+ // src/cli.ts
685
+ var EXIT_OK = 0;
686
+ var EXIT_USAGE = 1;
687
+ var EXIT_VALIDATE = 2;
688
+ var EXIT_RENDER = 3;
689
+ var EXIT_IO = 4;
690
+ var EXIT_INTERNAL = 5;
691
+ function parseArgs(argv) {
692
+ const positionals = [];
693
+ const flags = {};
694
+ let command = null;
695
+ for (let i = 0; i < argv.length; i++) {
696
+ const arg = argv[i] ?? "";
697
+ if (!command && !arg.startsWith("-")) {
698
+ command = arg;
699
+ continue;
700
+ }
701
+ if (arg === "--") {
702
+ positionals.push(...argv.slice(i + 1));
703
+ break;
704
+ }
705
+ if (arg.startsWith("--")) {
706
+ const eq = arg.indexOf("=");
707
+ const key = (eq >= 0 ? arg.slice(2, eq) : arg.slice(2)).trim();
708
+ const hasInlineValue = eq >= 0;
709
+ const inlineValue = hasInlineValue ? arg.slice(eq + 1) : void 0;
710
+ const next = argv[i + 1];
711
+ const isBoolean = key === "help" || key === "pretty";
712
+ if (isBoolean) {
713
+ flags[key] = true;
714
+ continue;
715
+ }
716
+ const value = inlineValue ?? (next && !next.startsWith("-") ? (i++, next) : void 0);
717
+ if (value === void 0) {
718
+ flags[key] = true;
719
+ continue;
720
+ }
721
+ const existing = flags[key];
722
+ if (existing === void 0) {
723
+ flags[key] = value;
724
+ } else if (Array.isArray(existing)) {
725
+ existing.push(value);
726
+ } else {
727
+ flags[key] = [String(existing), value];
728
+ }
729
+ continue;
730
+ }
731
+ if (arg === "-h" || arg === "--help") {
732
+ flags.help = true;
733
+ continue;
734
+ }
735
+ if (arg === "-v" || arg === "--version") {
736
+ flags.version = true;
737
+ continue;
738
+ }
739
+ positionals.push(arg);
740
+ }
741
+ return { command, positionals, flags };
742
+ }
743
+ function formatHelp() {
744
+ return `waves v${__wavesVersion}
745
+
746
+ Usage:
747
+ waves <command> [options]
748
+
749
+ Commands:
750
+ prompt Print an agent-ready system prompt + schema payload
751
+ schema Print JSON Schemas for IR/components
752
+ write-ir Write a starter IR JSON file
753
+ validate Validate an IR JSON file
754
+ render Render MP4 from an IR JSON file
755
+
756
+ Options:
757
+ -h, --help Show help
758
+ -v, --version Show version
759
+ `;
760
+ }
761
+ function getFlagString(flags, key) {
762
+ const v = flags[key];
763
+ if (typeof v === "string") return v;
764
+ if (Array.isArray(v)) return String(v[v.length - 1]);
765
+ return void 0;
766
+ }
767
+ function getFlagStrings(flags, key) {
768
+ const v = flags[key];
769
+ if (typeof v === "string") return [v];
770
+ if (Array.isArray(v)) return v.map(String);
771
+ return [];
772
+ }
773
+ async function tryWriteOut(outPath, content) {
774
+ if (!outPath) return null;
775
+ try {
776
+ await import_promises2.default.mkdir(import_node_path2.default.dirname(outPath), { recursive: true });
777
+ await import_promises2.default.writeFile(outPath, content, "utf-8");
778
+ return null;
779
+ } catch (err) {
780
+ return err instanceof Error ? err.message : String(err);
781
+ }
782
+ }
783
+ async function importRegistrationModules(modules) {
784
+ for (const m of modules) {
785
+ await import(m);
786
+ }
787
+ }
788
+ function stringifyJSON(value, pretty) {
789
+ return JSON.stringify(value, null, pretty ? 2 : 0) + "\n";
790
+ }
791
+ function collectComponentTypes2(ir) {
792
+ const types = /* @__PURE__ */ new Set();
793
+ for (const scene of ir.scenes) {
794
+ walkComponent2(scene, types);
795
+ }
796
+ return types;
797
+ }
798
+ function walkComponent2(component, types) {
799
+ types.add(component.type);
800
+ const children = component.children;
801
+ if (children?.length) {
802
+ for (const child of children) {
803
+ walkComponent2(child, types);
804
+ }
805
+ }
806
+ }
807
+ async function main(argv = process.argv.slice(2)) {
808
+ const parsed = parseArgs(argv);
809
+ if (parsed.flags.version) {
810
+ process.stdout.write(`${__wavesVersion}
811
+ `);
812
+ return EXIT_OK;
813
+ }
814
+ if (parsed.flags.help || !parsed.command) {
815
+ process.stdout.write(formatHelp());
816
+ return EXIT_OK;
817
+ }
818
+ if (parsed.command === "help") {
819
+ process.stdout.write(formatHelp());
820
+ return EXIT_OK;
821
+ }
822
+ const outPath = getFlagString(parsed.flags, "out");
823
+ const pretty = Boolean(parsed.flags.pretty);
824
+ const registrationModules = getFlagStrings(parsed.flags, "register");
825
+ try {
826
+ await importRegistrationModules(registrationModules);
827
+ } catch (err) {
828
+ const message = err instanceof Error ? err.message : String(err);
829
+ process.stderr.write(`Failed to import --register module: ${message}
830
+ `);
831
+ return EXIT_USAGE;
832
+ }
833
+ registerBuiltInComponents();
834
+ if (parsed.command === "prompt") {
835
+ const format = (getFlagString(parsed.flags, "format") ?? "text").toLowerCase();
836
+ const maxCharsRaw = getFlagString(parsed.flags, "maxChars");
837
+ const maxChars = maxCharsRaw ? Number(maxCharsRaw) : void 0;
838
+ const payload = getPromptPayload({ registry: globalRegistry });
839
+ if (format === "json") {
840
+ const json = stringifyJSON(payload, pretty);
841
+ const writeErr = await tryWriteOut(outPath, json);
842
+ if (writeErr) {
843
+ process.stderr.write(`Failed to write ${outPath}: ${writeErr}
844
+ `);
845
+ process.stdout.write(json);
846
+ return EXIT_IO;
847
+ }
848
+ process.stdout.write(json);
849
+ if (outPath) process.stderr.write(`Wrote ${outPath}
850
+ `);
851
+ return EXIT_OK;
852
+ }
853
+ if (format === "text") {
854
+ const text = typeof maxChars === "number" && Number.isFinite(maxChars) && maxChars > 0 ? payload.systemPrompt.slice(0, maxChars) : payload.systemPrompt;
855
+ const out = text.endsWith("\n") ? text : `${text}
856
+ `;
857
+ const writeErr = await tryWriteOut(outPath, out);
858
+ if (writeErr) {
859
+ process.stderr.write(`Failed to write ${outPath}: ${writeErr}
860
+ `);
861
+ process.stdout.write(out);
862
+ return EXIT_IO;
863
+ }
864
+ process.stdout.write(out);
865
+ if (outPath) process.stderr.write(`Wrote ${outPath}
866
+ `);
867
+ return EXIT_OK;
868
+ }
869
+ process.stderr.write(`Invalid --format: ${format} (expected "text" or "json")
870
+ `);
871
+ return EXIT_USAGE;
872
+ }
873
+ if (parsed.command === "schema") {
874
+ const kind = (getFlagString(parsed.flags, "kind") ?? "all").toLowerCase();
875
+ let output;
876
+ if (kind === "video-ir") {
877
+ output = zodSchemaToJsonSchema(VideoIRSchema);
878
+ } else if (kind === "components") {
879
+ output = globalRegistry.getJSONSchemaForLLM();
880
+ } else if (kind === "all") {
881
+ output = {
882
+ videoIR: zodSchemaToJsonSchema(VideoIRSchema),
883
+ components: globalRegistry.getJSONSchemaForLLM()
884
+ };
885
+ } else {
886
+ process.stderr.write(`Invalid --kind: ${kind} (expected video-ir|components|all)
887
+ `);
888
+ return EXIT_USAGE;
889
+ }
890
+ const json = stringifyJSON(output, pretty);
891
+ const writeErr = await tryWriteOut(outPath, json);
892
+ if (writeErr) {
893
+ process.stderr.write(`Failed to write ${outPath}: ${writeErr}
894
+ `);
895
+ process.stdout.write(json);
896
+ return EXIT_IO;
897
+ }
898
+ process.stdout.write(json);
899
+ if (outPath) process.stderr.write(`Wrote ${outPath}
900
+ `);
901
+ return EXIT_OK;
902
+ }
903
+ if (parsed.command === "write-ir") {
904
+ const template = (getFlagString(parsed.flags, "template") ?? "minimal").toLowerCase();
905
+ const out = outPath;
906
+ if (!out) {
907
+ process.stderr.write("Missing required --out <path>\n");
908
+ return EXIT_USAGE;
909
+ }
910
+ const ir = template === "basic" ? {
911
+ version: "1.0",
912
+ video: { id: "main", width: 1920, height: 1080, fps: 30, durationInFrames: 90 },
913
+ scenes: [
914
+ {
915
+ id: "scene-1",
916
+ type: "Scene",
917
+ timing: { from: 0, durationInFrames: 90 },
918
+ props: { background: { type: "color", value: "#000000" } },
919
+ children: [
920
+ {
921
+ id: "title",
922
+ type: "Text",
923
+ timing: { from: 0, durationInFrames: 90 },
924
+ props: { content: "Hello Waves", fontSize: 72, animation: "fade" }
925
+ }
926
+ ]
927
+ }
928
+ ]
929
+ } : template === "minimal" ? {
930
+ version: "1.0",
931
+ video: { id: "main", width: 1920, height: 1080, fps: 30, durationInFrames: 60 },
932
+ scenes: [
933
+ {
934
+ id: "scene-1",
935
+ type: "Scene",
936
+ timing: { from: 0, durationInFrames: 60 },
937
+ props: { background: { type: "color", value: "#000000" } }
938
+ }
939
+ ]
940
+ } : null;
941
+ if (!ir) {
942
+ process.stderr.write(`Invalid --template: ${template} (expected minimal|basic)
943
+ `);
944
+ return EXIT_USAGE;
945
+ }
946
+ const schemaCheck = VideoIRSchema.safeParse(ir);
947
+ if (!schemaCheck.success) {
948
+ process.stderr.write("Internal error: generated template does not validate against VideoIRSchema\n");
949
+ return EXIT_INTERNAL;
950
+ }
951
+ const json = stringifyJSON(ir, pretty);
952
+ const writeErr = await tryWriteOut(out, json);
953
+ if (writeErr) {
954
+ process.stderr.write(`Failed to write ${out}: ${writeErr}
955
+ `);
956
+ return EXIT_IO;
957
+ }
958
+ process.stdout.write(json);
959
+ process.stderr.write(`Wrote ${out}
960
+ `);
961
+ return EXIT_OK;
962
+ }
963
+ if (parsed.command === "validate") {
964
+ const inputPath = getFlagString(parsed.flags, "in");
965
+ if (!inputPath) {
966
+ process.stderr.write("Missing required --in <path>\n");
967
+ return EXIT_USAGE;
968
+ }
969
+ const format = (getFlagString(parsed.flags, "format") ?? "text").toLowerCase();
970
+ if (format !== "text" && format !== "json") {
971
+ process.stderr.write(`Invalid --format: ${format} (expected "text" or "json")
972
+ `);
973
+ return EXIT_USAGE;
974
+ }
975
+ let raw;
976
+ try {
977
+ raw = await import_promises2.default.readFile(inputPath, "utf-8");
978
+ } catch (err) {
979
+ const message = err instanceof Error ? err.message : String(err);
980
+ process.stderr.write(`Failed to read ${inputPath}: ${message}
981
+ `);
982
+ return EXIT_IO;
983
+ }
984
+ let json;
985
+ try {
986
+ json = JSON.parse(raw);
987
+ } catch (err) {
988
+ const message = err instanceof Error ? err.message : String(err);
989
+ if (format === "json") {
990
+ process.stdout.write(
991
+ stringifyJSON(
992
+ { success: false, errors: [{ path: ["<file>"], message, code: "INVALID_JSON" }] },
993
+ pretty
994
+ )
995
+ );
996
+ } else {
997
+ process.stderr.write(`Invalid JSON: ${message}
998
+ `);
999
+ }
1000
+ return EXIT_VALIDATE;
1001
+ }
1002
+ const validator = new IRValidator();
1003
+ const result = validator.validate(json);
1004
+ const errors = result.success ? [] : result.errors;
1005
+ if (result.success) {
1006
+ const types = collectComponentTypes2(result.data);
1007
+ const unknownTypes = [...types].filter((t) => !globalRegistry.has(t)).sort();
1008
+ for (const t of unknownTypes) {
1009
+ errors.push({
1010
+ path: ["components", t],
1011
+ message: `Unknown component type: ${t}`,
1012
+ code: "UNKNOWN_COMPONENT_TYPE"
1013
+ });
1014
+ }
1015
+ }
1016
+ const ok = errors.length === 0;
1017
+ if (format === "json") {
1018
+ process.stdout.write(stringifyJSON(ok ? { success: true } : { success: false, errors }, pretty));
1019
+ } else {
1020
+ if (ok) {
1021
+ process.stdout.write("ok\n");
1022
+ } else {
1023
+ process.stderr.write("validation failed\n");
1024
+ for (const e of errors) {
1025
+ process.stderr.write(`- ${e.code} ${e.path.join(".")}: ${e.message}
1026
+ `);
1027
+ }
1028
+ }
1029
+ }
1030
+ return ok ? EXIT_OK : EXIT_VALIDATE;
1031
+ }
1032
+ if (parsed.command === "render") {
1033
+ const inputPath = getFlagString(parsed.flags, "in");
1034
+ const outputPath = outPath;
1035
+ if (!inputPath) {
1036
+ process.stderr.write("Missing required --in <path>\n");
1037
+ return EXIT_USAGE;
1038
+ }
1039
+ if (!outputPath) {
1040
+ process.stderr.write("Missing required --out <path>\n");
1041
+ return EXIT_USAGE;
1042
+ }
1043
+ let raw;
1044
+ try {
1045
+ raw = await import_promises2.default.readFile(inputPath, "utf-8");
1046
+ } catch (err) {
1047
+ const message = err instanceof Error ? err.message : String(err);
1048
+ process.stderr.write(`Failed to read ${inputPath}: ${message}
1049
+ `);
1050
+ return EXIT_IO;
1051
+ }
1052
+ let json;
1053
+ try {
1054
+ json = JSON.parse(raw);
1055
+ } catch (err) {
1056
+ const message = err instanceof Error ? err.message : String(err);
1057
+ process.stderr.write(`Invalid JSON: ${message}
1058
+ `);
1059
+ return EXIT_VALIDATE;
1060
+ }
1061
+ const codec = getFlagString(parsed.flags, "codec");
1062
+ const crfRaw = getFlagString(parsed.flags, "crf");
1063
+ const concurrencyRaw = getFlagString(parsed.flags, "concurrency");
1064
+ const publicDir = getFlagString(parsed.flags, "publicDir");
1065
+ const crf = crfRaw ? Number(crfRaw) : void 0;
1066
+ const concurrency = concurrencyRaw ? /^[0-9]+$/.test(concurrencyRaw) ? Number(concurrencyRaw) : concurrencyRaw : void 0;
1067
+ const engine = new WavesEngine(globalRegistry, new IRValidator());
1068
+ try {
1069
+ const opts = { outputPath, registrationModules };
1070
+ if (publicDir) opts.publicDir = publicDir;
1071
+ if (codec) opts.codec = codec;
1072
+ if (Number.isFinite(crf ?? Number.NaN)) opts.crf = crf;
1073
+ if (concurrency !== void 0) opts.concurrency = concurrency;
1074
+ await engine.render(json, opts);
1075
+ } catch (err) {
1076
+ const message = err instanceof Error ? err.message : String(err);
1077
+ const context = err instanceof WavesRenderError ? err.context : void 0;
1078
+ const payload = context ? stringifyJSON({ error: message, context }, pretty) : null;
1079
+ process.stderr.write(`render failed: ${message}
1080
+ `);
1081
+ if (payload) process.stderr.write(payload);
1082
+ return EXIT_RENDER;
1083
+ }
1084
+ process.stderr.write(`Rendered ${outputPath}
1085
+ `);
1086
+ return EXIT_OK;
1087
+ }
1088
+ process.stderr.write(`Unknown command: ${parsed.command}
1089
+ `);
1090
+ process.stderr.write(`Run: waves --help
1091
+ `);
1092
+ return EXIT_USAGE;
1093
+ }
1094
+ var req = typeof require !== "undefined" ? require : void 0;
1095
+ var isCjsMain = typeof req !== "undefined" && typeof module !== "undefined" && req.main === module;
1096
+ if (isCjsMain) {
1097
+ main().then((code) => process.exit(code)).catch((err) => {
1098
+ const message = err instanceof Error ? err.stack ?? err.message : String(err);
1099
+ process.stderr.write(`${message}
1100
+ `);
1101
+ process.exit(EXIT_INTERNAL);
1102
+ });
1103
+ }
1104
+ // Annotate the CommonJS export names for ESM import in node:
1105
+ 0 && (module.exports = {
1106
+ main
1107
+ });