@canvakit/cli 0.0.0-stage → 0.2.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/LICENSE +105 -0
- package/README.md +103 -2
- package/dist/index.js +1596 -0
- package/dist/index.js.map +1 -0
- package/package.json +66 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1596 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/index.ts
|
|
4
|
+
import { Command, Option } from "commander";
|
|
5
|
+
|
|
6
|
+
// src/commands/design.ts
|
|
7
|
+
import chalk from "chalk";
|
|
8
|
+
import { defaultRegistry } from "@canvakit/showreel";
|
|
9
|
+
|
|
10
|
+
// src/local-fs.ts
|
|
11
|
+
import { promises as fs } from "fs";
|
|
12
|
+
import * as path from "path";
|
|
13
|
+
function createLocalFs(baseDir) {
|
|
14
|
+
const abs = path.resolve(baseDir);
|
|
15
|
+
const resolve11 = (p) => path.resolve(abs, p.replace(/^\/+/, ""));
|
|
16
|
+
return {
|
|
17
|
+
async readFile(p) {
|
|
18
|
+
return fs.readFile(resolve11(p));
|
|
19
|
+
},
|
|
20
|
+
async writeFile(p, contents) {
|
|
21
|
+
const full = resolve11(p);
|
|
22
|
+
await fs.mkdir(path.dirname(full), { recursive: true });
|
|
23
|
+
await fs.writeFile(full, contents);
|
|
24
|
+
},
|
|
25
|
+
async exists(p) {
|
|
26
|
+
try {
|
|
27
|
+
await fs.access(resolve11(p));
|
|
28
|
+
return true;
|
|
29
|
+
} catch {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
async readdir(p, opts) {
|
|
34
|
+
const root = resolve11(p);
|
|
35
|
+
const recursive = opts?.recursive === true;
|
|
36
|
+
let entries;
|
|
37
|
+
try {
|
|
38
|
+
if (recursive) {
|
|
39
|
+
const found = await fs.readdir(root, {
|
|
40
|
+
recursive: true,
|
|
41
|
+
withFileTypes: true
|
|
42
|
+
});
|
|
43
|
+
entries = found.map((e) => ({
|
|
44
|
+
// Node's recursive readdir returns entries where `name` is
|
|
45
|
+
// the leaf and `parentPath` is the containing directory.
|
|
46
|
+
// Canvakit expects names relative to `root`, so reconstruct.
|
|
47
|
+
name: reconstructRelative(
|
|
48
|
+
e.parentPath ?? e.path,
|
|
49
|
+
e.name,
|
|
50
|
+
root
|
|
51
|
+
),
|
|
52
|
+
type: e.isDirectory() ? "directory" : "file"
|
|
53
|
+
}));
|
|
54
|
+
} else {
|
|
55
|
+
const found = await fs.readdir(root, { withFileTypes: true });
|
|
56
|
+
entries = found.map((e) => ({
|
|
57
|
+
name: e.name,
|
|
58
|
+
type: e.isDirectory() ? "directory" : "file"
|
|
59
|
+
}));
|
|
60
|
+
}
|
|
61
|
+
} catch {
|
|
62
|
+
return [];
|
|
63
|
+
}
|
|
64
|
+
return entries;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function reconstructRelative(parent, name, root) {
|
|
69
|
+
const full = path.join(parent, name);
|
|
70
|
+
return path.relative(root, full).split(path.sep).join("/");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/commands/design.ts
|
|
74
|
+
async function runDesignList(options = {}) {
|
|
75
|
+
const cwd = options.cwd ?? process.cwd();
|
|
76
|
+
const fs9 = createLocalFs(cwd);
|
|
77
|
+
const entries = await defaultRegistry.list({ fs: fs9 });
|
|
78
|
+
if (options.json) {
|
|
79
|
+
console.log(JSON.stringify(entries, null, 2));
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
if (entries.length === 0) {
|
|
83
|
+
console.log(chalk.yellow("no design sources found"));
|
|
84
|
+
return 0;
|
|
85
|
+
}
|
|
86
|
+
let currentScheme = null;
|
|
87
|
+
for (const entry of entries) {
|
|
88
|
+
if (entry.scheme !== currentScheme) {
|
|
89
|
+
currentScheme = entry.scheme;
|
|
90
|
+
console.log(chalk.bold(`
|
|
91
|
+
${currentScheme}:`));
|
|
92
|
+
}
|
|
93
|
+
const label = entry.name && entry.name !== entry.ref ? ` ${chalk.dim(entry.name)}` : "";
|
|
94
|
+
console.log(` ${chalk.cyan(entry.ref)}${label}`);
|
|
95
|
+
}
|
|
96
|
+
console.log(chalk.green(`
|
|
97
|
+
ok \u2014 ${entries.length} design source(s)`));
|
|
98
|
+
return 0;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/commands/export.ts
|
|
102
|
+
import { promises as fs3 } from "fs";
|
|
103
|
+
import * as path2 from "path";
|
|
104
|
+
import chalk2 from "chalk";
|
|
105
|
+
import {
|
|
106
|
+
registerTool,
|
|
107
|
+
_clearToolRegistry,
|
|
108
|
+
parseByExtension
|
|
109
|
+
} from "@canvakit/core";
|
|
110
|
+
|
|
111
|
+
// src/photo.ts
|
|
112
|
+
import { promises as fs2 } from "fs";
|
|
113
|
+
import { extname, isAbsolute, resolve as resolve2 } from "path";
|
|
114
|
+
var DATA_URI_RE = /^data:/i;
|
|
115
|
+
var REMOTE_URL_RE = /^https?:\/\//i;
|
|
116
|
+
var PHOTO_MIME_BY_EXT = {
|
|
117
|
+
".png": "image/png",
|
|
118
|
+
".jpg": "image/jpeg",
|
|
119
|
+
".jpeg": "image/jpeg",
|
|
120
|
+
".webp": "image/webp",
|
|
121
|
+
".gif": "image/gif"
|
|
122
|
+
};
|
|
123
|
+
async function readFileAsBase64(absPath) {
|
|
124
|
+
const bytes = await fs2.readFile(absPath);
|
|
125
|
+
return bytes.toString("base64");
|
|
126
|
+
}
|
|
127
|
+
async function resolvePhotoVariable(cwd, absTemplatePath, photo) {
|
|
128
|
+
if (DATA_URI_RE.test(photo) || REMOTE_URL_RE.test(photo)) return photo;
|
|
129
|
+
const ext = extname(photo).toLowerCase();
|
|
130
|
+
const mime = PHOTO_MIME_BY_EXT[ext];
|
|
131
|
+
if (!mime) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
`canvakit export: --photo "${photo}" is not a data-URI/URL and has an unrecognised image extension (expected one of: ${Object.keys(PHOTO_MIME_BY_EXT).join(", ")})`
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
if (isAbsolute(photo)) {
|
|
137
|
+
try {
|
|
138
|
+
const bytes = await readFileAsBase64(photo);
|
|
139
|
+
return `data:${mime};base64,${bytes}`;
|
|
140
|
+
} catch {
|
|
141
|
+
throw new Error(`canvakit export: --photo file not found: "${photo}"`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
const cwdCandidate = resolve2(cwd, photo);
|
|
145
|
+
try {
|
|
146
|
+
const bytes = await readFileAsBase64(cwdCandidate);
|
|
147
|
+
return `data:${mime};base64,${bytes}`;
|
|
148
|
+
} catch {
|
|
149
|
+
}
|
|
150
|
+
const templateDir = resolve2(absTemplatePath, "..");
|
|
151
|
+
const templateCandidate = resolve2(templateDir, photo);
|
|
152
|
+
try {
|
|
153
|
+
const bytes = await readFileAsBase64(templateCandidate);
|
|
154
|
+
return `data:${mime};base64,${bytes}`;
|
|
155
|
+
} catch {
|
|
156
|
+
throw new Error(
|
|
157
|
+
`canvakit export: --photo file not found: "${photo}" \u2014 looked cwd-relative ("${cwdCandidate}") and template-relative ("${templateCandidate}").`
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// src/commands/export.ts
|
|
163
|
+
import { exportCanvas } from "@canvakit/export";
|
|
164
|
+
import { designkitExtension } from "@canvakit/designkit";
|
|
165
|
+
var FONT_MODES = /* @__PURE__ */ new Set(["link", "embed", "none"]);
|
|
166
|
+
var BINARY_FORMATS = /* @__PURE__ */ new Set(["pdf", "png", "html-zip"]);
|
|
167
|
+
var KNOWN_FORMATS = /* @__PURE__ */ new Set([
|
|
168
|
+
"pdf",
|
|
169
|
+
"png",
|
|
170
|
+
"html",
|
|
171
|
+
"html-zip",
|
|
172
|
+
"text"
|
|
173
|
+
]);
|
|
174
|
+
async function runExport(templatePath, options) {
|
|
175
|
+
const cwd = options.cwd ?? process.cwd();
|
|
176
|
+
const absTemplate = path2.resolve(cwd, templatePath);
|
|
177
|
+
let templateRaw;
|
|
178
|
+
try {
|
|
179
|
+
templateRaw = await fs3.readFile(absTemplate, "utf-8");
|
|
180
|
+
} catch (err) {
|
|
181
|
+
console.error(
|
|
182
|
+
chalk2.red(`canvakit export: cannot read template ${absTemplate}:`),
|
|
183
|
+
err instanceof Error ? err.message : err
|
|
184
|
+
);
|
|
185
|
+
return 1;
|
|
186
|
+
}
|
|
187
|
+
_clearToolRegistry();
|
|
188
|
+
if (options.data) {
|
|
189
|
+
const blockRe = /(\n([ \t]*)kind:[ \t]*(["']?)file\3\n\2path:[ \t]*)(["']?)[^"'\n]+\4/;
|
|
190
|
+
const match = templateRaw.match(blockRe);
|
|
191
|
+
if (!match) {
|
|
192
|
+
console.error(
|
|
193
|
+
chalk2.yellow(
|
|
194
|
+
`canvakit export: --data given but no file source \`path:\` found to override`
|
|
195
|
+
)
|
|
196
|
+
);
|
|
197
|
+
} else if (path2.isAbsolute(options.data)) {
|
|
198
|
+
const dataPath = options.data;
|
|
199
|
+
let raw;
|
|
200
|
+
try {
|
|
201
|
+
raw = await fs3.readFile(dataPath, "utf-8");
|
|
202
|
+
} catch (err) {
|
|
203
|
+
console.error(
|
|
204
|
+
chalk2.red(`canvakit export: cannot read --data ${dataPath}:`),
|
|
205
|
+
err instanceof Error ? err.message : err
|
|
206
|
+
);
|
|
207
|
+
return 1;
|
|
208
|
+
}
|
|
209
|
+
const parsed = parseByExtension(dataPath, raw);
|
|
210
|
+
const ref = "cli:data-override";
|
|
211
|
+
registerTool(ref, async () => parsed);
|
|
212
|
+
const indent = match[2];
|
|
213
|
+
templateRaw = templateRaw.replace(
|
|
214
|
+
blockRe,
|
|
215
|
+
`
|
|
216
|
+
${indent}kind: tool
|
|
217
|
+
${indent}ref: "${ref}"`
|
|
218
|
+
);
|
|
219
|
+
} else {
|
|
220
|
+
templateRaw = templateRaw.replace(
|
|
221
|
+
/(\n[ \t]*path:[ \t]*)(["']?)[^"'\n]+\2/,
|
|
222
|
+
`$1"${options.data}"`
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const format = resolveFormat(options.format, options.output);
|
|
227
|
+
if (!KNOWN_FORMATS.has(format)) {
|
|
228
|
+
console.error(
|
|
229
|
+
chalk2.red(
|
|
230
|
+
`canvakit export: unknown --format "${format}" (expected: ${[...KNOWN_FORMATS].join(", ")})`
|
|
231
|
+
)
|
|
232
|
+
);
|
|
233
|
+
return 1;
|
|
234
|
+
}
|
|
235
|
+
if (BINARY_FORMATS.has(format) && !options.output) {
|
|
236
|
+
console.error(
|
|
237
|
+
chalk2.red(`canvakit export: --output is required for --format ${format}`)
|
|
238
|
+
);
|
|
239
|
+
return 1;
|
|
240
|
+
}
|
|
241
|
+
const variables = {};
|
|
242
|
+
for (const pair of options.vars) {
|
|
243
|
+
const eq = pair.indexOf("=");
|
|
244
|
+
if (eq < 0) {
|
|
245
|
+
console.error(
|
|
246
|
+
chalk2.yellow(`skipping malformed --var "${pair}" (expected key=value)`)
|
|
247
|
+
);
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
variables[pair.slice(0, eq)] = parseMaybeJson(pair.slice(eq + 1));
|
|
251
|
+
}
|
|
252
|
+
if (options.photo) {
|
|
253
|
+
try {
|
|
254
|
+
variables.photo = await resolvePhotoVariable(
|
|
255
|
+
cwd,
|
|
256
|
+
absTemplate,
|
|
257
|
+
options.photo
|
|
258
|
+
);
|
|
259
|
+
} catch (err) {
|
|
260
|
+
console.error(chalk2.red(err instanceof Error ? err.message : String(err)));
|
|
261
|
+
return 1;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (options.context) {
|
|
265
|
+
let context;
|
|
266
|
+
try {
|
|
267
|
+
context = JSON.parse(
|
|
268
|
+
await fs3.readFile(path2.resolve(cwd, options.context), "utf-8")
|
|
269
|
+
);
|
|
270
|
+
} catch (err) {
|
|
271
|
+
console.error(
|
|
272
|
+
chalk2.red(
|
|
273
|
+
`canvakit export: cannot read/parse --context ${options.context}:`
|
|
274
|
+
),
|
|
275
|
+
err instanceof Error ? err.message : err
|
|
276
|
+
);
|
|
277
|
+
return 1;
|
|
278
|
+
}
|
|
279
|
+
if (context && typeof context === "object" && !Array.isArray(context)) {
|
|
280
|
+
for (const [ref, value] of Object.entries(
|
|
281
|
+
context
|
|
282
|
+
)) {
|
|
283
|
+
registerTool(ref, async () => value);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (options.fonts && !FONT_MODES.has(options.fonts)) {
|
|
288
|
+
console.error(
|
|
289
|
+
chalk2.red(
|
|
290
|
+
`canvakit export: unknown --fonts "${options.fonts}" (expected: ${[...FONT_MODES].join(", ")})`
|
|
291
|
+
)
|
|
292
|
+
);
|
|
293
|
+
return 1;
|
|
294
|
+
}
|
|
295
|
+
let pdfScale;
|
|
296
|
+
if (format === "pdf") {
|
|
297
|
+
const raw = options.scale ?? variables.density;
|
|
298
|
+
const parsed = typeof raw === "string" ? Number(raw) : raw;
|
|
299
|
+
if (typeof parsed === "number" && Number.isFinite(parsed)) {
|
|
300
|
+
if (parsed < 0.1 || parsed > 2) {
|
|
301
|
+
console.error(
|
|
302
|
+
chalk2.red(
|
|
303
|
+
`canvakit export: scale ${parsed} out of range (must be 0.1-2)`
|
|
304
|
+
)
|
|
305
|
+
);
|
|
306
|
+
return 1;
|
|
307
|
+
}
|
|
308
|
+
pdfScale = parsed;
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
const filesystem = createLocalFs(cwd);
|
|
312
|
+
const extensions = [
|
|
313
|
+
designkitExtension({
|
|
314
|
+
fonts: options.fonts ?? "embed",
|
|
315
|
+
...options.design ? { overrideDesign: options.design } : {}
|
|
316
|
+
})
|
|
317
|
+
];
|
|
318
|
+
const res = await exportCanvas(
|
|
319
|
+
{
|
|
320
|
+
template: templateRaw,
|
|
321
|
+
templatePath: path2.relative(cwd, absTemplate),
|
|
322
|
+
filesystem,
|
|
323
|
+
variables,
|
|
324
|
+
extensions
|
|
325
|
+
},
|
|
326
|
+
{
|
|
327
|
+
format,
|
|
328
|
+
...options.plain ? { medium: "web" } : {},
|
|
329
|
+
...pdfScale != null ? { page: { scale: pdfScale } } : {}
|
|
330
|
+
}
|
|
331
|
+
);
|
|
332
|
+
for (const warning of res.warnings ?? []) {
|
|
333
|
+
console.error(chalk2.yellow(`warning: ${warning}`));
|
|
334
|
+
}
|
|
335
|
+
for (const [name, status] of Object.entries(res.statuses ?? {})) {
|
|
336
|
+
if (status.status === "ok") continue;
|
|
337
|
+
const color = status.status === "missing" ? chalk2.yellow : chalk2.red;
|
|
338
|
+
console.error(color(` [${status.status}] ${name}: ${status.reason}`));
|
|
339
|
+
}
|
|
340
|
+
if (options.output) {
|
|
341
|
+
const outPath = path2.resolve(cwd, options.output);
|
|
342
|
+
await fs3.mkdir(path2.dirname(outPath), { recursive: true });
|
|
343
|
+
await fs3.writeFile(outPath, res.bytes);
|
|
344
|
+
console.error(
|
|
345
|
+
chalk2.green(`wrote ${outPath} (${format}, ${res.bytes.length} bytes)`)
|
|
346
|
+
);
|
|
347
|
+
} else {
|
|
348
|
+
process.stdout.write(res.bytes);
|
|
349
|
+
}
|
|
350
|
+
const hasError = Object.values(res.statuses ?? {}).some(
|
|
351
|
+
(s) => s.status === "error"
|
|
352
|
+
);
|
|
353
|
+
return hasError ? 2 : 0;
|
|
354
|
+
}
|
|
355
|
+
function resolveFormat(format, output) {
|
|
356
|
+
if (format) return format;
|
|
357
|
+
if (output) {
|
|
358
|
+
const ext = path2.extname(output).slice(1).toLowerCase();
|
|
359
|
+
if (ext === "zip") return "html-zip";
|
|
360
|
+
if (ext === "htm" || ext === "html") return "html";
|
|
361
|
+
if (ext === "txt" || ext === "md") return "text";
|
|
362
|
+
if (ext) return ext;
|
|
363
|
+
}
|
|
364
|
+
return "pdf";
|
|
365
|
+
}
|
|
366
|
+
function parseMaybeJson(raw) {
|
|
367
|
+
try {
|
|
368
|
+
return JSON.parse(raw);
|
|
369
|
+
} catch {
|
|
370
|
+
return raw;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// src/commands/install.ts
|
|
375
|
+
import { spawn } from "child_process";
|
|
376
|
+
import * as path3 from "path";
|
|
377
|
+
import { fileURLToPath } from "url";
|
|
378
|
+
import chalk3 from "chalk";
|
|
379
|
+
function canvakitCliPath() {
|
|
380
|
+
return fileURLToPath(import.meta.url);
|
|
381
|
+
}
|
|
382
|
+
var CLIENTS = /* @__PURE__ */ new Set(["claude", "json"]);
|
|
383
|
+
var SCOPES = /* @__PURE__ */ new Set(["local", "project", "user"]);
|
|
384
|
+
async function runInstallMcp(options) {
|
|
385
|
+
const cwd = options.cwd ?? process.cwd();
|
|
386
|
+
const client = options.client ?? "claude";
|
|
387
|
+
const scope = options.scope ?? "project";
|
|
388
|
+
const name = options.name ?? "canvakit";
|
|
389
|
+
const root = path3.resolve(cwd, options.root ?? ".");
|
|
390
|
+
const cli = canvakitCliPath();
|
|
391
|
+
if (!CLIENTS.has(client)) {
|
|
392
|
+
console.error(chalk3.red(`canvakit install mcp: unknown --client "${client}" (expected: ${[...CLIENTS].join(" | ")})`));
|
|
393
|
+
return 1;
|
|
394
|
+
}
|
|
395
|
+
if (!SCOPES.has(scope)) {
|
|
396
|
+
console.error(chalk3.red(`canvakit install mcp: unknown --scope "${scope}" (expected: ${[...SCOPES].join(" | ")})`));
|
|
397
|
+
return 1;
|
|
398
|
+
}
|
|
399
|
+
const stanza = {
|
|
400
|
+
mcpServers: {
|
|
401
|
+
[name]: { type: "stdio", command: "node", args: [cli, "mcp", "--root", root] }
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
if (client === "json") {
|
|
405
|
+
console.log(JSON.stringify(stanza, null, 2));
|
|
406
|
+
return 0;
|
|
407
|
+
}
|
|
408
|
+
const claudeArgs = ["mcp", "add", name, "--scope", scope, "--", "node", cli, "mcp", "--root", root];
|
|
409
|
+
const printable = `claude ${claudeArgs.map((a) => /\s/.test(a) ? JSON.stringify(a) : a).join(" ")}`;
|
|
410
|
+
if (!options.run) {
|
|
411
|
+
console.error(chalk3.cyan(`canvakit install mcp \u2014 register the "${name}" MCP server with Claude Code.`));
|
|
412
|
+
console.error(chalk3.dim("Run this yourself, or re-run with --run to execute it:\n"));
|
|
413
|
+
console.log(printable);
|
|
414
|
+
console.error(chalk3.dim(`
|
|
415
|
+
Other clients: paste this stanza (canvakit install mcp --client json):`));
|
|
416
|
+
console.error(chalk3.dim(JSON.stringify(stanza, null, 2)));
|
|
417
|
+
return 0;
|
|
418
|
+
}
|
|
419
|
+
return await new Promise((resolve11) => {
|
|
420
|
+
const child = spawn("claude", claudeArgs, { cwd, stdio: "inherit" });
|
|
421
|
+
child.on("close", (code) => {
|
|
422
|
+
if (code === 0) {
|
|
423
|
+
console.error(chalk3.green(`\u2713 registered "${name}" (scope: ${scope}, root: ${root})`));
|
|
424
|
+
}
|
|
425
|
+
resolve11(code ?? 1);
|
|
426
|
+
});
|
|
427
|
+
child.on("error", (err) => {
|
|
428
|
+
console.error(
|
|
429
|
+
chalk3.red(`canvakit install mcp: could not run \`claude\`: ${err instanceof Error ? err.message : String(err)}`)
|
|
430
|
+
);
|
|
431
|
+
console.error(chalk3.dim("Is the Claude Code CLI on PATH? Paste this stanza into your .mcp.json instead:"));
|
|
432
|
+
console.error(JSON.stringify(stanza, null, 2));
|
|
433
|
+
resolve11(1);
|
|
434
|
+
});
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// src/commands/init.ts
|
|
439
|
+
import { promises as fs4 } from "fs";
|
|
440
|
+
import * as path4 from "path";
|
|
441
|
+
import chalk4 from "chalk";
|
|
442
|
+
var STARTER = (name) => `---
|
|
443
|
+
template: true
|
|
444
|
+
name: ${name}
|
|
445
|
+
version: 0.1.0
|
|
446
|
+
description: A starter canvakit template.
|
|
447
|
+
variables:
|
|
448
|
+
title: "Hello, canvakit"
|
|
449
|
+
sources:
|
|
450
|
+
note:
|
|
451
|
+
kind: static
|
|
452
|
+
value: "Edit this template and re-run 'canvakit render' to see changes."
|
|
453
|
+
---
|
|
454
|
+
<!doctype html>
|
|
455
|
+
<html>
|
|
456
|
+
<head>
|
|
457
|
+
<meta charset="utf-8" />
|
|
458
|
+
<title>{{title}}</title>
|
|
459
|
+
<style>
|
|
460
|
+
body { font-family: system-ui, sans-serif; padding: 2rem; max-width: 40rem; margin: 0 auto; color: #222; }
|
|
461
|
+
h1 { margin-bottom: 0.25rem; }
|
|
462
|
+
p { line-height: 1.6; color: #555; }
|
|
463
|
+
code { background: #f4f4f4; padding: 0.125rem 0.25rem; border-radius: 3px; }
|
|
464
|
+
</style>
|
|
465
|
+
</head>
|
|
466
|
+
<body>
|
|
467
|
+
<h1>{{title}}</h1>
|
|
468
|
+
<p>{{note}}</p>
|
|
469
|
+
<p>Try adding a <code>kind: file</code> source pointing at a local markdown file, or a <code>kind: query</code> source with a glob pattern.</p>
|
|
470
|
+
<script id="canvas-data" type="application/json">{{{_data}}}</script>
|
|
471
|
+
</body>
|
|
472
|
+
</html>
|
|
473
|
+
`;
|
|
474
|
+
async function runInit(nameArg, options = {}) {
|
|
475
|
+
const cwd = options.cwd ?? process.cwd();
|
|
476
|
+
const name = nameArg ?? options.name ?? path4.basename(cwd).replace(/[^a-z0-9-]/gi, "-");
|
|
477
|
+
const filename = `${name}.canvakit.html`;
|
|
478
|
+
const dest = path4.resolve(cwd, filename);
|
|
479
|
+
const exists = await fs4.access(dest).then(() => true).catch(() => false);
|
|
480
|
+
if (exists) {
|
|
481
|
+
console.error(
|
|
482
|
+
chalk4.red(
|
|
483
|
+
`canvakit init: ${filename} already exists \u2014 choose a different name`
|
|
484
|
+
)
|
|
485
|
+
);
|
|
486
|
+
return 1;
|
|
487
|
+
}
|
|
488
|
+
await fs4.writeFile(dest, STARTER(name));
|
|
489
|
+
console.log(chalk4.green(`created ${filename}`));
|
|
490
|
+
console.log(
|
|
491
|
+
`
|
|
492
|
+
Next:
|
|
493
|
+
canvakit render ${filename}
|
|
494
|
+
canvakit validate ${filename}`
|
|
495
|
+
);
|
|
496
|
+
return 0;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// src/commands/mcp.ts
|
|
500
|
+
import { promises as fs5 } from "fs";
|
|
501
|
+
import * as path5 from "path";
|
|
502
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
503
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
504
|
+
import { z } from "zod";
|
|
505
|
+
import { render, registerTool as registerTool2, _clearToolRegistry as _clearToolRegistry2 } from "@canvakit/core";
|
|
506
|
+
import { exportCanvas as exportCanvas2 } from "@canvakit/export";
|
|
507
|
+
import { generate, refine, fitToPages } from "@canvakit/agent";
|
|
508
|
+
import { createVisionCritic } from "@canvakit/agent/critic-vision";
|
|
509
|
+
import { register as registerCvPlugin } from "@canvakit/plugin-cv";
|
|
510
|
+
import { register as registerSlidesPlugin } from "@canvakit/plugin-slides";
|
|
511
|
+
import { register as registerTemplateDocumentPlugin } from "@canvakit/plugin-template-document";
|
|
512
|
+
async function loadTemplate(root, templatePath, data) {
|
|
513
|
+
const absTemplate = path5.resolve(root, templatePath);
|
|
514
|
+
let raw = await fs5.readFile(absTemplate, "utf-8");
|
|
515
|
+
if (data) {
|
|
516
|
+
const pathRe = /(\n[ \t]*path:[ \t]*)(["']?)[^"'\n]+\2/;
|
|
517
|
+
if (pathRe.test(raw)) raw = raw.replace(pathRe, `$1"${data}"`);
|
|
518
|
+
}
|
|
519
|
+
return { raw, relTemplate: path5.relative(root, absTemplate) };
|
|
520
|
+
}
|
|
521
|
+
function applyContext(context) {
|
|
522
|
+
_clearToolRegistry2();
|
|
523
|
+
if (context) {
|
|
524
|
+
for (const [ref, value] of Object.entries(context)) {
|
|
525
|
+
registerTool2(ref, async () => value);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
function textResult(payload) {
|
|
530
|
+
return {
|
|
531
|
+
content: [
|
|
532
|
+
{ type: "text", text: JSON.stringify(payload, null, 2) }
|
|
533
|
+
]
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
function createCanvakitMcpServer(root) {
|
|
537
|
+
const server = new McpServer({ name: "canvakit", version: "0.1.0" });
|
|
538
|
+
const fsAdapter = createLocalFs(root);
|
|
539
|
+
registerCvPlugin();
|
|
540
|
+
registerSlidesPlugin();
|
|
541
|
+
registerTemplateDocumentPlugin();
|
|
542
|
+
server.tool(
|
|
543
|
+
"render_template",
|
|
544
|
+
"Render a canvakit template to its output (HTML by default). Resolves file/query sources from disk and kind:tool sources from the optional `context` fixtures.",
|
|
545
|
+
{
|
|
546
|
+
template: z.string().describe("Template path (relative to the server root or absolute)."),
|
|
547
|
+
variables: z.record(z.string(), z.unknown()).optional().describe("Overrides for the template's declared variables."),
|
|
548
|
+
context: z.record(z.string(), z.unknown()).optional().describe("Fixtures for kind:tool sources \u2014 ref \u2192 value."),
|
|
549
|
+
data: z.string().optional().describe(
|
|
550
|
+
"Override the first file source's path (e.g. swap language/data set)."
|
|
551
|
+
)
|
|
552
|
+
},
|
|
553
|
+
async ({ template, variables, context, data }) => {
|
|
554
|
+
const { raw, relTemplate } = await loadTemplate(root, template, data);
|
|
555
|
+
applyContext(context);
|
|
556
|
+
const res = await render({
|
|
557
|
+
template: raw,
|
|
558
|
+
templatePath: relTemplate,
|
|
559
|
+
filesystem: fsAdapter,
|
|
560
|
+
variables: variables ?? {}
|
|
561
|
+
});
|
|
562
|
+
return {
|
|
563
|
+
content: [{ type: "text", text: res.body }]
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
);
|
|
567
|
+
server.tool(
|
|
568
|
+
"export_artifact",
|
|
569
|
+
"Render a canvakit template and write an artifact to a file: pdf | png | html | html-zip | text. `plain: true` skips the document cover + table-of-contents assembly (single-pass PDF, A4 geometry kept).",
|
|
570
|
+
{
|
|
571
|
+
template: z.string().describe("Template path (relative to the server root or absolute)."),
|
|
572
|
+
output: z.string().describe(
|
|
573
|
+
"Output file path (relative to the server root or absolute)."
|
|
574
|
+
),
|
|
575
|
+
format: z.enum(["pdf", "png", "html", "html-zip", "text"]).optional().describe(
|
|
576
|
+
"Artifact format. Defaults to the medium's default (pdf for document)."
|
|
577
|
+
),
|
|
578
|
+
plain: z.boolean().optional().describe("Skip the cover + TOC document assembly; keep A4 geometry."),
|
|
579
|
+
variables: z.record(z.string(), z.unknown()).optional(),
|
|
580
|
+
context: z.record(z.string(), z.unknown()).optional(),
|
|
581
|
+
data: z.string().optional().describe(
|
|
582
|
+
"Override the first file source's path (e.g. swap language/data set)."
|
|
583
|
+
)
|
|
584
|
+
},
|
|
585
|
+
async ({ template, output, format, plain, variables, context, data }) => {
|
|
586
|
+
const { raw, relTemplate } = await loadTemplate(root, template, data);
|
|
587
|
+
applyContext(context);
|
|
588
|
+
const res = await exportCanvas2(
|
|
589
|
+
{
|
|
590
|
+
template: raw,
|
|
591
|
+
templatePath: relTemplate,
|
|
592
|
+
filesystem: fsAdapter,
|
|
593
|
+
variables: variables ?? {}
|
|
594
|
+
},
|
|
595
|
+
{
|
|
596
|
+
...format ? { format } : {},
|
|
597
|
+
...plain ? { medium: "web" } : {}
|
|
598
|
+
}
|
|
599
|
+
);
|
|
600
|
+
const outAbs = path5.resolve(root, output);
|
|
601
|
+
await fs5.mkdir(path5.dirname(outAbs), { recursive: true });
|
|
602
|
+
await fs5.writeFile(outAbs, res.bytes);
|
|
603
|
+
return textResult({
|
|
604
|
+
path: outAbs,
|
|
605
|
+
format: res.format,
|
|
606
|
+
bytes: res.bytes.length,
|
|
607
|
+
warnings: res.warnings ?? [],
|
|
608
|
+
statuses: res.statuses ?? {}
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
);
|
|
612
|
+
server.tool(
|
|
613
|
+
"validate_template",
|
|
614
|
+
"Parse a canvakit template and report its identity (name/version), declared sources, and each source's resolution status against disk.",
|
|
615
|
+
{
|
|
616
|
+
template: z.string().describe("Template path (relative to the server root or absolute)."),
|
|
617
|
+
data: z.string().optional().describe("Override the first file source's path before validating.")
|
|
618
|
+
},
|
|
619
|
+
async ({ template, data }) => {
|
|
620
|
+
const { raw, relTemplate } = await loadTemplate(root, template, data);
|
|
621
|
+
applyContext(void 0);
|
|
622
|
+
const res = await render({
|
|
623
|
+
template: raw,
|
|
624
|
+
templatePath: relTemplate,
|
|
625
|
+
filesystem: fsAdapter
|
|
626
|
+
});
|
|
627
|
+
return textResult({
|
|
628
|
+
identity: {
|
|
629
|
+
name: res.frontmatter?.name,
|
|
630
|
+
version: res.frontmatter?.version,
|
|
631
|
+
medium: res.frontmatter?.medium ?? "web",
|
|
632
|
+
design: res.frontmatter?.design
|
|
633
|
+
},
|
|
634
|
+
statuses: res.statuses ?? {},
|
|
635
|
+
warnings: res.warnings ?? []
|
|
636
|
+
});
|
|
637
|
+
}
|
|
638
|
+
);
|
|
639
|
+
server.tool(
|
|
640
|
+
"generate_document",
|
|
641
|
+
'Generate a document via a @canvakit/agent plugin TYPE (e.g. "cv"), resolving it in the plugin registry, validating `input` against that plugin\'s own schema, rendering, and writing the artifact to `output`. `input` is the plugin\'s own I/O shape \u2014 for "cv": { templatePath, dataPath?, design?, fonts?, photo?, variables? } (paths resolve against the server root).',
|
|
642
|
+
{
|
|
643
|
+
type: z.string().describe('Plugin type key, e.g. "cv".'),
|
|
644
|
+
input: z.record(z.string(), z.unknown()).describe(
|
|
645
|
+
"The plugin's own input object (validated against its schema)."
|
|
646
|
+
),
|
|
647
|
+
output: z.string().describe(
|
|
648
|
+
"Output file path (relative to the server root or absolute)."
|
|
649
|
+
)
|
|
650
|
+
},
|
|
651
|
+
async ({ type, input, output }) => {
|
|
652
|
+
try {
|
|
653
|
+
const artifact = await generate(type, input, { ctx: { cwd: root } });
|
|
654
|
+
const outAbs = path5.resolve(root, output);
|
|
655
|
+
await fs5.mkdir(path5.dirname(outAbs), { recursive: true });
|
|
656
|
+
await fs5.writeFile(outAbs, artifact.bytes);
|
|
657
|
+
return textResult({
|
|
658
|
+
path: outAbs,
|
|
659
|
+
type,
|
|
660
|
+
format: artifact.format,
|
|
661
|
+
filename: artifact.filename,
|
|
662
|
+
bytes: artifact.bytes.length
|
|
663
|
+
});
|
|
664
|
+
} catch (err) {
|
|
665
|
+
return textResult({
|
|
666
|
+
error: err instanceof Error ? err.message : String(err)
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
);
|
|
671
|
+
server.tool(
|
|
672
|
+
"refine_document",
|
|
673
|
+
"Improve a generated document. Two modes: `fitPages` (deterministic \u2014 render \u2192 count PDF pages \u2192 shrink the `density` zoom variable \u2192 re-render until it fits N pages; the reliable way to keep a one-pager on one page) and, without it, the agentic vision loop (render \u2192 preview \u2192 LLM critic vs the plugin's rubric \u2192 bounded edit \u2192 re-render; uses the real vision critic when ANTHROPIC_API_KEY is set, else the deterministic StubCritic). Writes the final artifact to `output` + returns the trace.",
|
|
674
|
+
{
|
|
675
|
+
type: z.string().describe('Plugin type key, e.g. "cv".'),
|
|
676
|
+
input: z.record(z.string(), z.unknown()).describe("The plugin's own input object."),
|
|
677
|
+
output: z.string().describe("Output file path for the final artifact."),
|
|
678
|
+
fitPages: z.number().int().positive().optional().describe(
|
|
679
|
+
"Deterministically fit the PDF to at most this many pages by shrinking the `density` variable. E.g. 1 for a one-pager. Skips the vision loop."
|
|
680
|
+
),
|
|
681
|
+
maxRounds: z.number().int().positive().optional().describe("Vision loop: hard cap on critique/edit rounds. Default 5.")
|
|
682
|
+
},
|
|
683
|
+
async ({ type, input, output, fitPages, maxRounds }) => {
|
|
684
|
+
try {
|
|
685
|
+
const outAbs = path5.resolve(root, output);
|
|
686
|
+
await fs5.mkdir(path5.dirname(outAbs), { recursive: true });
|
|
687
|
+
if (fitPages) {
|
|
688
|
+
const res2 = await fitToPages(type, input, {
|
|
689
|
+
ctx: { cwd: root },
|
|
690
|
+
maxPages: fitPages
|
|
691
|
+
});
|
|
692
|
+
await fs5.writeFile(outAbs, res2.artifact.bytes);
|
|
693
|
+
return textResult({
|
|
694
|
+
path: outAbs,
|
|
695
|
+
type,
|
|
696
|
+
mode: "fit",
|
|
697
|
+
format: res2.artifact.format,
|
|
698
|
+
bytes: res2.artifact.bytes.length,
|
|
699
|
+
pages: res2.pages,
|
|
700
|
+
density: res2.density,
|
|
701
|
+
fitted: res2.fitted,
|
|
702
|
+
rounds: res2.rounds
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
const critic = process.env.ANTHROPIC_API_KEY ? createVisionCritic({}) : void 0;
|
|
706
|
+
const res = await refine(type, input, {
|
|
707
|
+
ctx: { cwd: root },
|
|
708
|
+
...maxRounds ? { maxRounds } : {},
|
|
709
|
+
...critic ? { critic } : {}
|
|
710
|
+
});
|
|
711
|
+
await fs5.writeFile(outAbs, res.artifact.bytes);
|
|
712
|
+
return textResult({
|
|
713
|
+
path: outAbs,
|
|
714
|
+
type,
|
|
715
|
+
mode: critic ? "vision" : "stub",
|
|
716
|
+
format: res.artifact.format,
|
|
717
|
+
bytes: res.artifact.bytes.length,
|
|
718
|
+
converged: res.converged,
|
|
719
|
+
rounds: res.rounds
|
|
720
|
+
});
|
|
721
|
+
} catch (err) {
|
|
722
|
+
return textResult({
|
|
723
|
+
error: err instanceof Error ? err.message : String(err)
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
);
|
|
728
|
+
return server;
|
|
729
|
+
}
|
|
730
|
+
async function runMcp(options) {
|
|
731
|
+
const cwd = options.cwd ?? process.cwd();
|
|
732
|
+
const root = path5.resolve(
|
|
733
|
+
cwd,
|
|
734
|
+
options.root ?? process.env.CANVAKIT_MCP_ROOT ?? "."
|
|
735
|
+
);
|
|
736
|
+
const server = createCanvakitMcpServer(root);
|
|
737
|
+
const transport = new StdioServerTransport();
|
|
738
|
+
await server.connect(transport);
|
|
739
|
+
return await new Promise((resolve11) => {
|
|
740
|
+
transport.onclose = () => resolve11(0);
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// src/commands/render.ts
|
|
745
|
+
import { promises as fs6 } from "fs";
|
|
746
|
+
import * as path6 from "path";
|
|
747
|
+
import chalk5 from "chalk";
|
|
748
|
+
import { registerTool as registerTool3, render as render2, _clearToolRegistry as _clearToolRegistry3 } from "@canvakit/core";
|
|
749
|
+
async function runRender(templatePath, options) {
|
|
750
|
+
const cwd = options.cwd ?? process.cwd();
|
|
751
|
+
const absTemplate = path6.resolve(cwd, templatePath);
|
|
752
|
+
let templateRaw;
|
|
753
|
+
try {
|
|
754
|
+
templateRaw = await fs6.readFile(absTemplate, "utf-8");
|
|
755
|
+
} catch (err) {
|
|
756
|
+
console.error(
|
|
757
|
+
chalk5.red(`canvakit render: cannot read template ${absTemplate}:`),
|
|
758
|
+
err instanceof Error ? err.message : err
|
|
759
|
+
);
|
|
760
|
+
return 1;
|
|
761
|
+
}
|
|
762
|
+
const variables = {};
|
|
763
|
+
for (const pair of options.vars) {
|
|
764
|
+
const eq = pair.indexOf("=");
|
|
765
|
+
if (eq < 0) {
|
|
766
|
+
console.error(
|
|
767
|
+
chalk5.yellow(`skipping malformed --var "${pair}" (expected key=value)`)
|
|
768
|
+
);
|
|
769
|
+
continue;
|
|
770
|
+
}
|
|
771
|
+
const key = pair.slice(0, eq);
|
|
772
|
+
const raw = pair.slice(eq + 1);
|
|
773
|
+
variables[key] = parseMaybeJson2(raw);
|
|
774
|
+
}
|
|
775
|
+
_clearToolRegistry3();
|
|
776
|
+
if (options.context) {
|
|
777
|
+
let ctxRaw;
|
|
778
|
+
try {
|
|
779
|
+
ctxRaw = await fs6.readFile(path6.resolve(cwd, options.context), "utf-8");
|
|
780
|
+
} catch (err) {
|
|
781
|
+
console.error(
|
|
782
|
+
chalk5.red(`canvakit render: cannot read --context ${options.context}:`),
|
|
783
|
+
err instanceof Error ? err.message : err
|
|
784
|
+
);
|
|
785
|
+
return 1;
|
|
786
|
+
}
|
|
787
|
+
let context;
|
|
788
|
+
try {
|
|
789
|
+
context = JSON.parse(ctxRaw);
|
|
790
|
+
} catch (err) {
|
|
791
|
+
console.error(
|
|
792
|
+
chalk5.red(`canvakit render: --context is not valid JSON:`),
|
|
793
|
+
err instanceof Error ? err.message : err
|
|
794
|
+
);
|
|
795
|
+
return 1;
|
|
796
|
+
}
|
|
797
|
+
if (context && typeof context === "object" && !Array.isArray(context)) {
|
|
798
|
+
for (const [ref, value] of Object.entries(
|
|
799
|
+
context
|
|
800
|
+
)) {
|
|
801
|
+
registerTool3(ref, async () => value);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
const filesystem = createLocalFs(cwd);
|
|
806
|
+
const result = await render2({
|
|
807
|
+
template: templateRaw,
|
|
808
|
+
templatePath: path6.relative(cwd, absTemplate),
|
|
809
|
+
filesystem,
|
|
810
|
+
variables
|
|
811
|
+
});
|
|
812
|
+
for (const warning of result.warnings) {
|
|
813
|
+
console.error(chalk5.yellow(`warning: ${warning}`));
|
|
814
|
+
}
|
|
815
|
+
for (const [name, status] of Object.entries(result.statuses)) {
|
|
816
|
+
if (status.status === "ok") continue;
|
|
817
|
+
const color = status.status === "missing" ? chalk5.yellow : chalk5.red;
|
|
818
|
+
console.error(color(` [${status.status}] ${name}: ${status.reason}`));
|
|
819
|
+
}
|
|
820
|
+
if (options.output) {
|
|
821
|
+
const outPath = path6.resolve(cwd, options.output);
|
|
822
|
+
await fs6.mkdir(path6.dirname(outPath), { recursive: true });
|
|
823
|
+
await fs6.writeFile(outPath, result.body);
|
|
824
|
+
console.error(chalk5.green(`wrote ${outPath}`));
|
|
825
|
+
} else {
|
|
826
|
+
process.stdout.write(result.body);
|
|
827
|
+
if (!result.body.endsWith("\n")) process.stdout.write("\n");
|
|
828
|
+
}
|
|
829
|
+
const hasError = Object.values(result.statuses).some(
|
|
830
|
+
(s) => s.status === "error"
|
|
831
|
+
);
|
|
832
|
+
return hasError ? 2 : 0;
|
|
833
|
+
}
|
|
834
|
+
function parseMaybeJson2(raw) {
|
|
835
|
+
try {
|
|
836
|
+
return JSON.parse(raw);
|
|
837
|
+
} catch {
|
|
838
|
+
return raw;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
// src/commands/scene.ts
|
|
843
|
+
import { promises as nodeFs } from "fs";
|
|
844
|
+
import * as path7 from "path";
|
|
845
|
+
import chalk6 from "chalk";
|
|
846
|
+
import {
|
|
847
|
+
builtinSceneSource,
|
|
848
|
+
defaultSceneTemplateRegistry,
|
|
849
|
+
resolveSceneTemplate
|
|
850
|
+
} from "@canvakit/showreel";
|
|
851
|
+
async function runSceneList(options = {}) {
|
|
852
|
+
const cwd = options.cwd ?? process.cwd();
|
|
853
|
+
const fs9 = createLocalFs(cwd);
|
|
854
|
+
const entries = await defaultSceneTemplateRegistry.list({ fs: fs9 });
|
|
855
|
+
if (options.json) {
|
|
856
|
+
console.log(JSON.stringify(entries, null, 2));
|
|
857
|
+
return 0;
|
|
858
|
+
}
|
|
859
|
+
if (entries.length === 0) {
|
|
860
|
+
console.log(chalk6.yellow("no scene templates found"));
|
|
861
|
+
return 0;
|
|
862
|
+
}
|
|
863
|
+
let currentScheme = null;
|
|
864
|
+
for (const entry of entries) {
|
|
865
|
+
if (entry.scheme !== currentScheme) {
|
|
866
|
+
currentScheme = entry.scheme;
|
|
867
|
+
console.log(chalk6.bold(`
|
|
868
|
+
${currentScheme}:`));
|
|
869
|
+
}
|
|
870
|
+
console.log(` ${chalk6.cyan(entry.ref)}`);
|
|
871
|
+
}
|
|
872
|
+
console.log(chalk6.green(`
|
|
873
|
+
ok \u2014 ${entries.length} scene template(s)`));
|
|
874
|
+
return 0;
|
|
875
|
+
}
|
|
876
|
+
function resolveWorkspaceDest(cwd, destArg) {
|
|
877
|
+
const segments = destArg.split(/[\\/]+/).filter((segment) => segment.length > 0);
|
|
878
|
+
if (segments.includes("..")) return null;
|
|
879
|
+
const abs = path7.resolve(cwd, destArg);
|
|
880
|
+
const rel = path7.relative(cwd, abs);
|
|
881
|
+
if (rel.startsWith("..") || path7.isAbsolute(rel)) return null;
|
|
882
|
+
return abs;
|
|
883
|
+
}
|
|
884
|
+
async function runSceneInit(builtinId, options = {}) {
|
|
885
|
+
const cwd = options.cwd ?? process.cwd();
|
|
886
|
+
const source = builtinSceneSource(builtinId);
|
|
887
|
+
if (source === null) {
|
|
888
|
+
const fs9 = createLocalFs(cwd);
|
|
889
|
+
const entries = await defaultSceneTemplateRegistry.list({ fs: fs9 });
|
|
890
|
+
const builtins = entries.filter((entry) => entry.scheme === "builtin").map((entry) => entry.ref);
|
|
891
|
+
console.error(
|
|
892
|
+
chalk6.red(
|
|
893
|
+
`canvakit scene init: unknown builtin "${builtinId}" \u2014 available: ${builtins.join(", ")}.`
|
|
894
|
+
)
|
|
895
|
+
);
|
|
896
|
+
return 1;
|
|
897
|
+
}
|
|
898
|
+
const destArg = options.dest ?? path7.join("_scenes", `${builtinId}.md`);
|
|
899
|
+
const dest = resolveWorkspaceDest(cwd, destArg);
|
|
900
|
+
if (dest === null) {
|
|
901
|
+
console.error(
|
|
902
|
+
chalk6.red(`canvakit scene init: dest "${destArg}" escapes the workspace \u2014 refused.`)
|
|
903
|
+
);
|
|
904
|
+
return 1;
|
|
905
|
+
}
|
|
906
|
+
const exists = await nodeFs.access(dest).then(() => true).catch(() => false);
|
|
907
|
+
if (exists && !options.force) {
|
|
908
|
+
console.error(
|
|
909
|
+
chalk6.red(`canvakit scene init: ${destArg} already exists \u2014 pass --force to overwrite.`)
|
|
910
|
+
);
|
|
911
|
+
return 1;
|
|
912
|
+
}
|
|
913
|
+
await nodeFs.mkdir(path7.dirname(dest), { recursive: true });
|
|
914
|
+
await nodeFs.writeFile(dest, source);
|
|
915
|
+
const relRef = path7.relative(cwd, dest).split(path7.sep).join("/");
|
|
916
|
+
console.log(
|
|
917
|
+
chalk6.green(`wrote ${relRef} \u2014 edit it, then reference \`ws:${relRef}\` in your showreel timeline`)
|
|
918
|
+
);
|
|
919
|
+
return 0;
|
|
920
|
+
}
|
|
921
|
+
async function runSceneValidate(pathArg, options = {}) {
|
|
922
|
+
const cwd = options.cwd ?? process.cwd();
|
|
923
|
+
const fs9 = createLocalFs(cwd);
|
|
924
|
+
const template = await resolveSceneTemplate(`ws:${pathArg}`, { fs: fs9 });
|
|
925
|
+
if (template === null) {
|
|
926
|
+
console.error(
|
|
927
|
+
chalk6.red(
|
|
928
|
+
`canvakit scene validate: ${pathArg} is not a valid workspace scene canva (see warnings above).`
|
|
929
|
+
)
|
|
930
|
+
);
|
|
931
|
+
return 1;
|
|
932
|
+
}
|
|
933
|
+
console.log(chalk6.bold("id:"), template.id);
|
|
934
|
+
console.log(
|
|
935
|
+
chalk6.bold("slots:"),
|
|
936
|
+
template.slots.length === 0 ? "(none)" : template.slots.join(", ")
|
|
937
|
+
);
|
|
938
|
+
console.log(chalk6.green(`ok \u2014 valid canva, ${template.slots.length} slot(s)`));
|
|
939
|
+
return 0;
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
// src/commands/showreel.ts
|
|
943
|
+
import { spawnSync } from "child_process";
|
|
944
|
+
import { promises as fs7 } from "fs";
|
|
945
|
+
import * as path8 from "path";
|
|
946
|
+
import { performance } from "perf_hooks";
|
|
947
|
+
import chalk7 from "chalk";
|
|
948
|
+
import {
|
|
949
|
+
validateConfig,
|
|
950
|
+
ShowreelConfigError,
|
|
951
|
+
runShowreelWith,
|
|
952
|
+
runCapture,
|
|
953
|
+
synthesizeAudio,
|
|
954
|
+
assemble,
|
|
955
|
+
renderScenesWith,
|
|
956
|
+
resolveVisualRenderer,
|
|
957
|
+
cachingVisualRenderer,
|
|
958
|
+
measureClip
|
|
959
|
+
} from "@canvakit/showreel";
|
|
960
|
+
import { agenticVisualRenderer } from "@canvakit/showreel-agentic";
|
|
961
|
+
function stripJsonComments(raw) {
|
|
962
|
+
let out = "";
|
|
963
|
+
let inString = false;
|
|
964
|
+
let inLine = false;
|
|
965
|
+
let inBlock = false;
|
|
966
|
+
for (let i = 0; i < raw.length; i++) {
|
|
967
|
+
const c = raw[i];
|
|
968
|
+
const next = raw[i + 1];
|
|
969
|
+
if (inLine) {
|
|
970
|
+
if (c === "\n") {
|
|
971
|
+
inLine = false;
|
|
972
|
+
out += c;
|
|
973
|
+
}
|
|
974
|
+
continue;
|
|
975
|
+
}
|
|
976
|
+
if (inBlock) {
|
|
977
|
+
if (c === "*" && next === "/") {
|
|
978
|
+
inBlock = false;
|
|
979
|
+
i++;
|
|
980
|
+
}
|
|
981
|
+
continue;
|
|
982
|
+
}
|
|
983
|
+
if (inString) {
|
|
984
|
+
out += c;
|
|
985
|
+
if (c === "\\") {
|
|
986
|
+
out += next ?? "";
|
|
987
|
+
i++;
|
|
988
|
+
} else if (c === '"') {
|
|
989
|
+
inString = false;
|
|
990
|
+
}
|
|
991
|
+
continue;
|
|
992
|
+
}
|
|
993
|
+
if (c === '"') {
|
|
994
|
+
inString = true;
|
|
995
|
+
out += c;
|
|
996
|
+
continue;
|
|
997
|
+
}
|
|
998
|
+
if (c === "/" && next === "/") {
|
|
999
|
+
inLine = true;
|
|
1000
|
+
i++;
|
|
1001
|
+
continue;
|
|
1002
|
+
}
|
|
1003
|
+
if (c === "/" && next === "*") {
|
|
1004
|
+
inBlock = true;
|
|
1005
|
+
i++;
|
|
1006
|
+
continue;
|
|
1007
|
+
}
|
|
1008
|
+
out += c;
|
|
1009
|
+
}
|
|
1010
|
+
return out;
|
|
1011
|
+
}
|
|
1012
|
+
async function runShowreel(configPath, opts = {}) {
|
|
1013
|
+
const abs = path8.resolve(process.cwd(), configPath);
|
|
1014
|
+
const configDir = path8.dirname(abs);
|
|
1015
|
+
let raw;
|
|
1016
|
+
try {
|
|
1017
|
+
raw = await fs7.readFile(abs, "utf-8");
|
|
1018
|
+
} catch (err) {
|
|
1019
|
+
console.error(
|
|
1020
|
+
chalk7.red(`canvakit showreel: cannot read ${abs}:`),
|
|
1021
|
+
err instanceof Error ? err.message : err
|
|
1022
|
+
);
|
|
1023
|
+
return 1;
|
|
1024
|
+
}
|
|
1025
|
+
let parsed;
|
|
1026
|
+
try {
|
|
1027
|
+
parsed = JSON.parse(stripJsonComments(raw));
|
|
1028
|
+
} catch (err) {
|
|
1029
|
+
console.error(
|
|
1030
|
+
chalk7.red("canvakit showreel: config is not valid JSON(C):"),
|
|
1031
|
+
err instanceof Error ? err.message : err
|
|
1032
|
+
);
|
|
1033
|
+
return 1;
|
|
1034
|
+
}
|
|
1035
|
+
let config;
|
|
1036
|
+
try {
|
|
1037
|
+
config = validateConfig(parsed);
|
|
1038
|
+
} catch (err) {
|
|
1039
|
+
if (err instanceof ShowreelConfigError) {
|
|
1040
|
+
console.error(chalk7.red(err.message));
|
|
1041
|
+
} else {
|
|
1042
|
+
console.error(
|
|
1043
|
+
chalk7.red("canvakit showreel: validation failed:"),
|
|
1044
|
+
err instanceof Error ? err.message : err
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
return 1;
|
|
1048
|
+
}
|
|
1049
|
+
console.log(chalk7.bold("target:"), config.target.url);
|
|
1050
|
+
if (typeof config.brand === "string") {
|
|
1051
|
+
console.log(chalk7.bold("brand:"), `ref ${config.brand} (resolved via @canvakit/designkit at render time)`);
|
|
1052
|
+
} else {
|
|
1053
|
+
console.log(
|
|
1054
|
+
chalk7.bold("brand:"),
|
|
1055
|
+
config.brand.preset ?? "(no preset)",
|
|
1056
|
+
Object.keys(config.brand.tokens).length ? `+ ${Object.keys(config.brand.tokens).length} token(s)` : ""
|
|
1057
|
+
);
|
|
1058
|
+
}
|
|
1059
|
+
console.log(chalk7.bold("timeline:"), `${config.timeline.length} item(s)`);
|
|
1060
|
+
for (const [i, item] of config.timeline.entries()) {
|
|
1061
|
+
const idx = chalk7.dim(String(i).padStart(2, " "));
|
|
1062
|
+
const kind = item.kind === "scene" ? chalk7.magenta("scene ") : item.kind === "capture" ? chalk7.cyan("capture") : chalk7.yellow("clip ");
|
|
1063
|
+
const detail = item.kind === "scene" ? `template=${item.template} ${item.duration}ms` : item.kind === "capture" ? `${item.steps.length} step(s) fps=${item.record.fps}` : `src=${item.src}${item.trim ? ` trim=[${String(item.trim.startMs ?? 0)}, ${item.trim.endMs === void 0 ? "end" : String(item.trim.endMs)}]` : ""} fit=${item.fit}`;
|
|
1064
|
+
const narration = item.narration ? chalk7.dim(` \u266A "${item.narration}"`) : "";
|
|
1065
|
+
console.log(` ${idx} ${kind} ${chalk7.bold(item.id)} ${detail}${narration}`);
|
|
1066
|
+
}
|
|
1067
|
+
console.log(
|
|
1068
|
+
chalk7.bold("voice:"),
|
|
1069
|
+
`${config.voice.provider} (${config.voice.model})`
|
|
1070
|
+
);
|
|
1071
|
+
console.log(chalk7.bold("music:"), `"${config.music.prompt}" duck=${config.music.duckDb}dB`);
|
|
1072
|
+
console.log(
|
|
1073
|
+
chalk7.bold("output:"),
|
|
1074
|
+
`${config.output.dir}/${config.output.video} + ${config.output.deck} seed=${config.output.seed}`
|
|
1075
|
+
);
|
|
1076
|
+
console.log(
|
|
1077
|
+
chalk7.green(
|
|
1078
|
+
`
|
|
1079
|
+
ok \u2014 config valid, ${config.timeline.length} timeline item(s) planned`
|
|
1080
|
+
)
|
|
1081
|
+
);
|
|
1082
|
+
if (!opts.render) {
|
|
1083
|
+
console.log(chalk7.yellow("note"), "pass --render to run the full pipeline");
|
|
1084
|
+
return 0;
|
|
1085
|
+
}
|
|
1086
|
+
const cacheEnabled = opts.cache ?? true;
|
|
1087
|
+
console.log(
|
|
1088
|
+
chalk7.bold("cache:"),
|
|
1089
|
+
cacheEnabled ? `on \u2014 ${opts.cacheDir ?? ".canvakit/scene-cache"} (--no-cache to disable)` : "off (--no-cache)"
|
|
1090
|
+
);
|
|
1091
|
+
if (opts.renderer !== "html-still") {
|
|
1092
|
+
console.log(
|
|
1093
|
+
chalk7.bold("agent:"),
|
|
1094
|
+
`${opts.adapter ?? "claude-code"}${opts.mode ? `/${opts.mode}` : ""} model=${opts.model ?? "claude-sonnet-5"} effort=${opts.effort ?? "(adapter default)"}`
|
|
1095
|
+
);
|
|
1096
|
+
}
|
|
1097
|
+
try {
|
|
1098
|
+
if (opts.renderer === "html-still") {
|
|
1099
|
+
const artifacts = await runShowreelWith(
|
|
1100
|
+
{
|
|
1101
|
+
runCapture,
|
|
1102
|
+
synthesizeAudio,
|
|
1103
|
+
assemble,
|
|
1104
|
+
measureClip: (item, startOffsetMs) => measureClip(item, startOffsetMs, configDir),
|
|
1105
|
+
renderScenes: (items, brand, startOffsetMs) => renderScenesWith(
|
|
1106
|
+
resolveVisualRenderer({
|
|
1107
|
+
cache: { enabled: cacheEnabled, dir: opts.cacheDir, salt: "html-still:v1" }
|
|
1108
|
+
}),
|
|
1109
|
+
items,
|
|
1110
|
+
brand,
|
|
1111
|
+
startOffsetMs
|
|
1112
|
+
)
|
|
1113
|
+
},
|
|
1114
|
+
config
|
|
1115
|
+
);
|
|
1116
|
+
console.log(chalk7.bold("\nvideoPath:"), artifacts.videoPath);
|
|
1117
|
+
console.log(chalk7.bold("deckPath:"), artifacts.deckPath);
|
|
1118
|
+
return 0;
|
|
1119
|
+
} else {
|
|
1120
|
+
const sceneTimings = [];
|
|
1121
|
+
let capturedInput = null;
|
|
1122
|
+
const artifacts = await runShowreelWith(
|
|
1123
|
+
{
|
|
1124
|
+
runCapture,
|
|
1125
|
+
synthesizeAudio,
|
|
1126
|
+
assemble: async (input) => {
|
|
1127
|
+
capturedInput = input;
|
|
1128
|
+
return assemble(input);
|
|
1129
|
+
},
|
|
1130
|
+
measureClip: (item, startOffsetMs) => measureClip(item, startOffsetMs, configDir),
|
|
1131
|
+
renderScenes: async (items, brand, startOffsetMs) => {
|
|
1132
|
+
const item = items[0];
|
|
1133
|
+
const startedAtMs = performance.now();
|
|
1134
|
+
const result = await renderScenesWith(
|
|
1135
|
+
cachingVisualRenderer(
|
|
1136
|
+
agenticVisualRenderer({
|
|
1137
|
+
maxRounds: 2,
|
|
1138
|
+
...opts.adapter ? { adapter: opts.adapter } : {},
|
|
1139
|
+
...opts.mode ? { mode: opts.mode } : {},
|
|
1140
|
+
...opts.model ? { model: opts.model } : {},
|
|
1141
|
+
...opts.effort ? { effort: opts.effort } : {}
|
|
1142
|
+
}),
|
|
1143
|
+
{
|
|
1144
|
+
enabled: cacheEnabled,
|
|
1145
|
+
dir: opts.cacheDir,
|
|
1146
|
+
// Model/adapter/mode change the produced pixels, so they must
|
|
1147
|
+
// salt the content-addressed cache key — otherwise a kimi
|
|
1148
|
+
// render would be served from a sonnet render's cache entry.
|
|
1149
|
+
salt: `agentic:maxRounds=2:${opts.adapter ?? "claude-code"}:${opts.mode ?? "-"}:${opts.model ?? "claude-sonnet-5"}:v1`
|
|
1150
|
+
}
|
|
1151
|
+
),
|
|
1152
|
+
items,
|
|
1153
|
+
brand,
|
|
1154
|
+
startOffsetMs
|
|
1155
|
+
);
|
|
1156
|
+
if (item) {
|
|
1157
|
+
sceneTimings.push({ id: item.id, startedAtMs, endedAtMs: performance.now() });
|
|
1158
|
+
}
|
|
1159
|
+
return result;
|
|
1160
|
+
}
|
|
1161
|
+
},
|
|
1162
|
+
config
|
|
1163
|
+
);
|
|
1164
|
+
console.log(chalk7.bold("\nvideoPath:"), artifacts.videoPath);
|
|
1165
|
+
console.log(chalk7.bold("deckPath:"), artifacts.deckPath);
|
|
1166
|
+
reportSceneConcurrency(sceneTimings);
|
|
1167
|
+
if (capturedInput) reportSyncAndCapture(capturedInput, artifacts.videoPath);
|
|
1168
|
+
return 0;
|
|
1169
|
+
}
|
|
1170
|
+
} catch (err) {
|
|
1171
|
+
console.error(
|
|
1172
|
+
chalk7.red("canvakit showreel: render failed:"),
|
|
1173
|
+
err instanceof Error ? err.message : err
|
|
1174
|
+
);
|
|
1175
|
+
return 1;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
function reportSceneConcurrency(timings) {
|
|
1179
|
+
if (timings.length < 2) return;
|
|
1180
|
+
console.log(chalk7.bold("\nscene render timing (wall-clock, proves fan-out):"));
|
|
1181
|
+
for (const t of timings) {
|
|
1182
|
+
console.log(
|
|
1183
|
+
` ${t.id}: +${t.startedAtMs.toFixed(0)}ms \u2192 +${t.endedAtMs.toFixed(0)}ms (${(t.endedAtMs - t.startedAtMs).toFixed(0)}ms)`
|
|
1184
|
+
);
|
|
1185
|
+
}
|
|
1186
|
+
for (let i = 0; i < timings.length; i++) {
|
|
1187
|
+
for (let j = i + 1; j < timings.length; j++) {
|
|
1188
|
+
const a = timings[i];
|
|
1189
|
+
const b = timings[j];
|
|
1190
|
+
if (!a || !b) continue;
|
|
1191
|
+
const overlapMs = Math.min(a.endedAtMs, b.endedAtMs) - Math.max(a.startedAtMs, b.startedAtMs);
|
|
1192
|
+
console.log(
|
|
1193
|
+
` overlap(${a.id}, ${b.id}): ${overlapMs.toFixed(0)}ms` + (overlapMs > 0 ? " \u2014 ran concurrently" : " \u2014 ran back-to-back")
|
|
1194
|
+
);
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
var ProbeError = class extends Error {
|
|
1199
|
+
};
|
|
1200
|
+
function ffprobeDurationMs(path10) {
|
|
1201
|
+
const out = spawnSync("ffprobe", [
|
|
1202
|
+
"-v",
|
|
1203
|
+
"error",
|
|
1204
|
+
"-show_entries",
|
|
1205
|
+
"format=duration",
|
|
1206
|
+
"-of",
|
|
1207
|
+
"default=noprint_wrappers=1:nokey=1",
|
|
1208
|
+
path10
|
|
1209
|
+
], { encoding: "utf8" });
|
|
1210
|
+
if (out.error) {
|
|
1211
|
+
throw new ProbeError(`ffprobe not available or failed to start: ${out.error.message}`);
|
|
1212
|
+
}
|
|
1213
|
+
if (out.status !== 0) {
|
|
1214
|
+
throw new ProbeError(
|
|
1215
|
+
`ffprobe exited ${String(out.status)}: ${out.stderr.trim() || "(no stderr)"}`
|
|
1216
|
+
);
|
|
1217
|
+
}
|
|
1218
|
+
const seconds = Number.parseFloat(out.stdout.trim());
|
|
1219
|
+
if (!Number.isFinite(seconds)) {
|
|
1220
|
+
throw new ProbeError(`ffprobe produced unparsable duration output: "${out.stdout.trim()}"`);
|
|
1221
|
+
}
|
|
1222
|
+
return Math.round(seconds * 1e3);
|
|
1223
|
+
}
|
|
1224
|
+
function probeVolumeDb(videoPath, startMs, windowMs) {
|
|
1225
|
+
const out = spawnSync(
|
|
1226
|
+
"ffmpeg",
|
|
1227
|
+
[
|
|
1228
|
+
"-ss",
|
|
1229
|
+
(startMs / 1e3).toFixed(3),
|
|
1230
|
+
"-t",
|
|
1231
|
+
(windowMs / 1e3).toFixed(3),
|
|
1232
|
+
"-i",
|
|
1233
|
+
videoPath,
|
|
1234
|
+
"-af",
|
|
1235
|
+
"volumedetect",
|
|
1236
|
+
"-f",
|
|
1237
|
+
"null",
|
|
1238
|
+
"-"
|
|
1239
|
+
],
|
|
1240
|
+
{ encoding: "utf8" }
|
|
1241
|
+
);
|
|
1242
|
+
if (out.error) {
|
|
1243
|
+
throw new ProbeError(`ffmpeg not available or failed to start: ${out.error.message}`);
|
|
1244
|
+
}
|
|
1245
|
+
if (out.status !== 0) {
|
|
1246
|
+
throw new ProbeError(
|
|
1247
|
+
`ffmpeg exited ${String(out.status)}: ${out.stderr.trim().slice(-500) || "(no stderr)"}`
|
|
1248
|
+
);
|
|
1249
|
+
}
|
|
1250
|
+
const mean = /mean_volume:\s*(-?\d+(?:\.\d+)?) dB/.exec(out.stderr);
|
|
1251
|
+
const max = /max_volume:\s*(-?\d+(?:\.\d+)?) dB/.exec(out.stderr);
|
|
1252
|
+
return {
|
|
1253
|
+
meanDb: mean ? Number.parseFloat(mean[1] ?? "-Infinity") : Number.NEGATIVE_INFINITY,
|
|
1254
|
+
maxDb: max ? Number.parseFloat(max[1] ?? "-Infinity") : Number.NEGATIVE_INFINITY
|
|
1255
|
+
};
|
|
1256
|
+
}
|
|
1257
|
+
function computeMasterTotalMs(measured) {
|
|
1258
|
+
if (measured.length === 0) return null;
|
|
1259
|
+
return Math.max(...measured.map((item) => item.endMs));
|
|
1260
|
+
}
|
|
1261
|
+
function reportSyncAndCapture(input, videoPath) {
|
|
1262
|
+
const measuredById = new Map(input.measured.map((item) => [item.id, item]));
|
|
1263
|
+
if (input.audio.narration.length > 0) {
|
|
1264
|
+
console.log(chalk7.bold("\nsync table (measuredStartMs vs narrationPlacedAtMs):"));
|
|
1265
|
+
for (const clip of input.audio.narration) {
|
|
1266
|
+
const slot = measuredById.get(clip.id);
|
|
1267
|
+
const equal = slot?.startMs === clip.startMs;
|
|
1268
|
+
console.log(
|
|
1269
|
+
` id=${clip.id} measuredStartMs=${String(slot?.startMs)} narrationPlacedAtMs=${String(clip.startMs)} equal=${String(equal)}`
|
|
1270
|
+
);
|
|
1271
|
+
try {
|
|
1272
|
+
const { meanDb, maxDb } = probeVolumeDb(videoPath, clip.startMs, 300);
|
|
1273
|
+
console.log(
|
|
1274
|
+
` non-silence probe @${String(clip.startMs)}ms (300ms window): mean=${meanDb.toFixed(1)}dB max=${maxDb.toFixed(1)}dB ${maxDb > -50 ? "(non-silent)" : "(SILENT \u2014 drift?)"}`
|
|
1275
|
+
);
|
|
1276
|
+
} catch (err) {
|
|
1277
|
+
console.log(
|
|
1278
|
+
` non-silence probe @${String(clip.startMs)}ms: ` + chalk7.yellow(err instanceof Error ? err.message : String(err))
|
|
1279
|
+
);
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
const captureSlots = input.measured.filter((item) => item.kind === "capture");
|
|
1284
|
+
if (captureSlots.length > 0) {
|
|
1285
|
+
console.log(chalk7.bold("\ncapture slot(s):"));
|
|
1286
|
+
for (const slot of captureSlots) {
|
|
1287
|
+
console.log(` id=${slot.id} [${String(slot.startMs)}, ${String(slot.endMs)}]`);
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
console.log(chalk7.bold("\nfinal duration check:"));
|
|
1291
|
+
const masterTotalMs = computeMasterTotalMs(input.measured);
|
|
1292
|
+
if (masterTotalMs === null) {
|
|
1293
|
+
console.log(chalk7.yellow(" no measured items on the master timeline \u2014 nothing to check"));
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
let videoDurationLabel;
|
|
1297
|
+
try {
|
|
1298
|
+
videoDurationLabel = `${String(ffprobeDurationMs(videoPath))}ms`;
|
|
1299
|
+
} catch (err) {
|
|
1300
|
+
videoDurationLabel = chalk7.yellow(
|
|
1301
|
+
`unavailable \u2014 ${err instanceof Error ? err.message : String(err)}`
|
|
1302
|
+
);
|
|
1303
|
+
}
|
|
1304
|
+
console.log(
|
|
1305
|
+
` master-timeline total=${String(masterTotalMs)}ms final mp4 duration=${videoDurationLabel}`
|
|
1306
|
+
);
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// src/commands/validate.ts
|
|
1310
|
+
import { promises as fs8 } from "fs";
|
|
1311
|
+
import * as path9 from "path";
|
|
1312
|
+
import chalk8 from "chalk";
|
|
1313
|
+
import { parseTemplate } from "@canvakit/core";
|
|
1314
|
+
async function runValidate(templatePath, options = {}) {
|
|
1315
|
+
const cwd = options.cwd ?? process.cwd();
|
|
1316
|
+
const absTemplate = path9.resolve(cwd, templatePath);
|
|
1317
|
+
let raw;
|
|
1318
|
+
try {
|
|
1319
|
+
raw = await fs8.readFile(absTemplate, "utf-8");
|
|
1320
|
+
} catch (err) {
|
|
1321
|
+
console.error(
|
|
1322
|
+
chalk8.red(`canvakit validate: cannot read ${absTemplate}:`),
|
|
1323
|
+
err instanceof Error ? err.message : err
|
|
1324
|
+
);
|
|
1325
|
+
return 1;
|
|
1326
|
+
}
|
|
1327
|
+
const { template, warnings } = parseTemplate(raw, templatePath);
|
|
1328
|
+
let failed = false;
|
|
1329
|
+
for (const warning of warnings) {
|
|
1330
|
+
console.log(chalk8.yellow("warn"), warning);
|
|
1331
|
+
}
|
|
1332
|
+
if (!template) {
|
|
1333
|
+
console.error(chalk8.red("error"), "template did not parse");
|
|
1334
|
+
return 1;
|
|
1335
|
+
}
|
|
1336
|
+
const fm = template.frontmatter;
|
|
1337
|
+
console.log(
|
|
1338
|
+
chalk8.bold("identity:"),
|
|
1339
|
+
fm.name ?? chalk8.red("(no name)"),
|
|
1340
|
+
fm.version ?? chalk8.red("(no version)")
|
|
1341
|
+
);
|
|
1342
|
+
if (!fm.name || !fm.version) {
|
|
1343
|
+
console.log(
|
|
1344
|
+
chalk8.yellow("hint"),
|
|
1345
|
+
"gallery templates require frontmatter `name` + `version`"
|
|
1346
|
+
);
|
|
1347
|
+
failed = true;
|
|
1348
|
+
}
|
|
1349
|
+
if (fm.refreshEvery) {
|
|
1350
|
+
console.log(chalk8.bold("refreshEvery:"), fm.refreshEvery);
|
|
1351
|
+
}
|
|
1352
|
+
const sources = fm.sources ?? {};
|
|
1353
|
+
const names = Object.keys(sources);
|
|
1354
|
+
console.log(
|
|
1355
|
+
chalk8.bold("sources:"),
|
|
1356
|
+
names.length === 0 ? "(none)" : `${names.length} declared`
|
|
1357
|
+
);
|
|
1358
|
+
const filesystem = createLocalFs(cwd);
|
|
1359
|
+
for (const [name, source] of Object.entries(sources)) {
|
|
1360
|
+
const label = chalk8.cyan(name);
|
|
1361
|
+
if (source.kind === "tool") {
|
|
1362
|
+
console.log(` ${label} kind=tool ref=${chalk8.magenta(source.ref)}`);
|
|
1363
|
+
} else if (source.kind === "static") {
|
|
1364
|
+
console.log(` ${label} kind=static`);
|
|
1365
|
+
} else if (source.kind === "file") {
|
|
1366
|
+
const reachable = await filesystem.exists(source.path);
|
|
1367
|
+
console.log(
|
|
1368
|
+
` ${label} kind=file path=${source.path} ${reachable ? chalk8.green("ok") : chalk8.yellow("missing on disk")}`
|
|
1369
|
+
);
|
|
1370
|
+
} else if (source.kind === "query") {
|
|
1371
|
+
const patterns = Array.isArray(source.include) ? source.include : [source.include];
|
|
1372
|
+
console.log(` ${label} kind=query include=${patterns.join(", ")}`);
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
const hasHardWarning = warnings.some(
|
|
1376
|
+
(w) => w.includes("validation errors") || w.includes("parse failed") || w.includes("unknown refreshEvery")
|
|
1377
|
+
);
|
|
1378
|
+
if (hasHardWarning) failed = true;
|
|
1379
|
+
if (failed) {
|
|
1380
|
+
console.error(chalk8.red("validation failed"));
|
|
1381
|
+
return 1;
|
|
1382
|
+
}
|
|
1383
|
+
console.error(chalk8.green("ok"));
|
|
1384
|
+
return 0;
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// src/index.ts
|
|
1388
|
+
var program = new Command();
|
|
1389
|
+
program.name("canvakit").description(
|
|
1390
|
+
"Canvakit \u2014 template + data-source binding standard. Render, validate, and scaffold canvakit templates."
|
|
1391
|
+
).version("0.1.0");
|
|
1392
|
+
program.command("render <template>").description(
|
|
1393
|
+
"Render a canvakit template with local filesystem + optional tool fixtures from --context."
|
|
1394
|
+
).option(
|
|
1395
|
+
"-v, --var <key=value>",
|
|
1396
|
+
"set a variable override (repeatable)",
|
|
1397
|
+
(v, acc) => [...acc, v],
|
|
1398
|
+
[]
|
|
1399
|
+
).option(
|
|
1400
|
+
"-c, --context <file>",
|
|
1401
|
+
"JSON file of tool-ref \u2192 value fixtures used to satisfy kind: tool sources"
|
|
1402
|
+
).option(
|
|
1403
|
+
"-o, --output <file>",
|
|
1404
|
+
"write rendered body to file (default: stdout)"
|
|
1405
|
+
).action(
|
|
1406
|
+
async (template, opts) => {
|
|
1407
|
+
const code = await runRender(template, {
|
|
1408
|
+
vars: opts.var,
|
|
1409
|
+
context: opts.context,
|
|
1410
|
+
output: opts.output
|
|
1411
|
+
});
|
|
1412
|
+
process.exit(code);
|
|
1413
|
+
}
|
|
1414
|
+
);
|
|
1415
|
+
program.command("export <template>").description(
|
|
1416
|
+
"Render a canvakit template and write an artifact (pdf / png / html / html-zip / text)."
|
|
1417
|
+
).option(
|
|
1418
|
+
"-o, --output <file>",
|
|
1419
|
+
"write the artifact to this file (required for pdf / png / html-zip)"
|
|
1420
|
+
).option(
|
|
1421
|
+
"-f, --format <format>",
|
|
1422
|
+
"pdf | png | html | html-zip | text (default: inferred from --output, else pdf)"
|
|
1423
|
+
).option(
|
|
1424
|
+
"-v, --var <key=value>",
|
|
1425
|
+
"set a variable override (repeatable)",
|
|
1426
|
+
(v, acc) => [...acc, v],
|
|
1427
|
+
[]
|
|
1428
|
+
).option(
|
|
1429
|
+
"-c, --context <file>",
|
|
1430
|
+
"JSON file of tool-ref \u2192 value fixtures used to satisfy kind: tool sources"
|
|
1431
|
+
).option(
|
|
1432
|
+
"--data <path>",
|
|
1433
|
+
"override the path of the template's first file source (e.g. swap data set / language)"
|
|
1434
|
+
).option(
|
|
1435
|
+
"--plain",
|
|
1436
|
+
"skip the document cover + table-of-contents assembly; keep A4 geometry (single-pass PDF)"
|
|
1437
|
+
).option(
|
|
1438
|
+
"--design <ref>",
|
|
1439
|
+
"force a designkit ref (e.g. dk:atelier | dk:heritage | dk:neon-grid), overriding the template's design: frontmatter"
|
|
1440
|
+
).option(
|
|
1441
|
+
"--fonts <mode>",
|
|
1442
|
+
"designkit font emission: link | embed | none (default: embed \u2014 self-contained PDF)"
|
|
1443
|
+
).option(
|
|
1444
|
+
"--photo <path>",
|
|
1445
|
+
"photo as a data-URI/URL, or a file path (absolute, cwd-relative, or template-relative) to embed as base64"
|
|
1446
|
+
).option(
|
|
1447
|
+
"--scale <factor>",
|
|
1448
|
+
"print-time shrink-to-fit for pdf (0.1-2, default 1) \u2014 the only thing that actually reduces page count; CSS zoom/transform never reach Chrome's print-layout pass. Falls back to a numeric `density` --var/frontmatter value when omitted, so the existing refine-loop convention keeps working."
|
|
1449
|
+
).action(
|
|
1450
|
+
async (template, opts) => {
|
|
1451
|
+
const code = await runExport(template, {
|
|
1452
|
+
vars: opts.var,
|
|
1453
|
+
context: opts.context,
|
|
1454
|
+
output: opts.output,
|
|
1455
|
+
format: opts.format,
|
|
1456
|
+
data: opts.data,
|
|
1457
|
+
plain: opts.plain,
|
|
1458
|
+
design: opts.design,
|
|
1459
|
+
fonts: opts.fonts,
|
|
1460
|
+
photo: opts.photo,
|
|
1461
|
+
scale: opts.scale
|
|
1462
|
+
});
|
|
1463
|
+
process.exit(code);
|
|
1464
|
+
}
|
|
1465
|
+
);
|
|
1466
|
+
program.command("mcp").description(
|
|
1467
|
+
"Serve canvakit as an MCP server over stdio (tools: render_template, export_artifact, validate_template)."
|
|
1468
|
+
).option(
|
|
1469
|
+
"--root <dir>",
|
|
1470
|
+
"base directory for templates + file sources (default: $CANVAKIT_MCP_ROOT or cwd)"
|
|
1471
|
+
).action(async (opts) => {
|
|
1472
|
+
const code = await runMcp({ root: opts.root });
|
|
1473
|
+
process.exit(code);
|
|
1474
|
+
});
|
|
1475
|
+
program.command("validate <template>").description(
|
|
1476
|
+
"Parse a canvakit template, report identity + source kinds, check file/query paths exist."
|
|
1477
|
+
).action(async (template) => {
|
|
1478
|
+
const code = await runValidate(template);
|
|
1479
|
+
process.exit(code);
|
|
1480
|
+
});
|
|
1481
|
+
var install = program.command("install").description(
|
|
1482
|
+
"Register canvakit with a host (MCP server, \u2026) instead of hand-editing config."
|
|
1483
|
+
);
|
|
1484
|
+
install.command("mcp").description(
|
|
1485
|
+
"Register the canvakit MCP server (render / export / validate / generate_document / refine_document) with Claude Code \u2014 or print the stanza for any MCP client. Prints by default; --run executes `claude mcp add`."
|
|
1486
|
+
).option("--client <client>", "claude | json (default claude)").option(
|
|
1487
|
+
"--root <dir>",
|
|
1488
|
+
"canvakit mcp root \u2014 templates + file-sources base dir (default cwd)"
|
|
1489
|
+
).option("--name <name>", "MCP server name (default canvakit)").option(
|
|
1490
|
+
"--scope <scope>",
|
|
1491
|
+
"claude config scope: local | project | user (default project)"
|
|
1492
|
+
).option(
|
|
1493
|
+
"--run",
|
|
1494
|
+
"execute `claude mcp add` instead of only printing it",
|
|
1495
|
+
false
|
|
1496
|
+
).action(
|
|
1497
|
+
async (opts) => {
|
|
1498
|
+
const code = await runInstallMcp({
|
|
1499
|
+
client: opts.client,
|
|
1500
|
+
root: opts.root,
|
|
1501
|
+
name: opts.name,
|
|
1502
|
+
scope: opts.scope,
|
|
1503
|
+
run: opts.run
|
|
1504
|
+
});
|
|
1505
|
+
process.exit(code);
|
|
1506
|
+
}
|
|
1507
|
+
);
|
|
1508
|
+
program.command("init [name]").description("Scaffold a starter canvakit template in the current directory.").action(async (name) => {
|
|
1509
|
+
const code = await runInit(name);
|
|
1510
|
+
process.exit(code);
|
|
1511
|
+
});
|
|
1512
|
+
program.command("showreel <config>").description(
|
|
1513
|
+
"Validate a showreel.config.json(c) and print the planned timeline; with --render, run the full pipeline."
|
|
1514
|
+
).option(
|
|
1515
|
+
"--render",
|
|
1516
|
+
"run the full pipeline (Chrome capture/scenes, ElevenLabs audio, ffmpeg assembly) instead of just validating",
|
|
1517
|
+
false
|
|
1518
|
+
).addOption(
|
|
1519
|
+
new Option(
|
|
1520
|
+
"--renderer <kind>",
|
|
1521
|
+
"scene VisualRenderer for --render: agentic (default \u2014 a real agentproto agent authors/screenshots/critiques/iterates each scene; needs the agentproto daemon) or html-still (cheap, baked templates, no daemon \u2014 the offline fallback)"
|
|
1522
|
+
).choices(["html-still", "agentic"]).default("agentic")
|
|
1523
|
+
).option(
|
|
1524
|
+
"--no-cache",
|
|
1525
|
+
"disable the content-addressed scene render cache (on by default \u2014 re-renders every scene even when nothing changed)"
|
|
1526
|
+
).option(
|
|
1527
|
+
"--cache-dir <dir>",
|
|
1528
|
+
"override the scene render cache directory (default: .canvakit/scene-cache)"
|
|
1529
|
+
).option(
|
|
1530
|
+
"--adapter <slug>",
|
|
1531
|
+
"agentic renderer: agent CLI adapter for the scene-authoring session (default: claude-code; e.g. claude-sdk to route a gateway model)"
|
|
1532
|
+
).option(
|
|
1533
|
+
"--mode <id>",
|
|
1534
|
+
'agentic renderer: adapter mode \u2014 e.g. claude-sdk gateway presets "moonshot"/"openrouter" to drive Kimi/GLM/DeepSeek through an Anthropic-compatible gateway'
|
|
1535
|
+
).option(
|
|
1536
|
+
"--model <id>",
|
|
1537
|
+
"agentic renderer: model id for the scene-authoring session (default: claude-sonnet-5; e.g. moonshotai/kimi-k2 with --adapter claude-sdk --mode openrouter)"
|
|
1538
|
+
).option(
|
|
1539
|
+
"--effort <level>",
|
|
1540
|
+
"agentic renderer: reasoning effort for the scene-authoring session (default: high)"
|
|
1541
|
+
).action(
|
|
1542
|
+
async (config, opts) => {
|
|
1543
|
+
const code = await runShowreel(config, {
|
|
1544
|
+
render: opts.render,
|
|
1545
|
+
renderer: opts.renderer,
|
|
1546
|
+
cache: opts.cache,
|
|
1547
|
+
cacheDir: opts.cacheDir,
|
|
1548
|
+
adapter: opts.adapter,
|
|
1549
|
+
mode: opts.mode,
|
|
1550
|
+
model: opts.model,
|
|
1551
|
+
effort: opts.effort
|
|
1552
|
+
});
|
|
1553
|
+
process.exit(code);
|
|
1554
|
+
}
|
|
1555
|
+
);
|
|
1556
|
+
var design = program.command("design").description(
|
|
1557
|
+
"Inspect design sources available via @canvakit/designkit's DesignSourceRegistry."
|
|
1558
|
+
);
|
|
1559
|
+
design.command("list").description(
|
|
1560
|
+
"List every design source discoverable across schemes that support it (built-in dk: presets + workspace kit:/_design/*.md files), grouped by scheme."
|
|
1561
|
+
).option("--json", "print as JSON", false).action(async (opts) => {
|
|
1562
|
+
const code = await runDesignList({ json: opts.json });
|
|
1563
|
+
process.exit(code);
|
|
1564
|
+
});
|
|
1565
|
+
var scene = program.command("scene").description(
|
|
1566
|
+
"Discover, scaffold, and validate showreel scene canva (builtin + ws:)."
|
|
1567
|
+
);
|
|
1568
|
+
scene.command("list").description(
|
|
1569
|
+
"List every scene template discoverable across schemes (built-in showreel canva + workspace ws:/_scenes/*.md files), grouped by scheme."
|
|
1570
|
+
).option("--json", "print as JSON", false).action(async (opts) => {
|
|
1571
|
+
const code = await runSceneList({ json: opts.json });
|
|
1572
|
+
process.exit(code);
|
|
1573
|
+
});
|
|
1574
|
+
scene.command("init <builtin>").description(
|
|
1575
|
+
"Scaffold a built-in scene canva into an editable workspace file (default: _scenes/<builtin>.md)."
|
|
1576
|
+
).option(
|
|
1577
|
+
"--dest <path>",
|
|
1578
|
+
"workspace-relative destination path (default: _scenes/<builtin>.md)"
|
|
1579
|
+
).option("--force", "overwrite the destination if it already exists", false).action(async (builtin, opts) => {
|
|
1580
|
+
const code = await runSceneInit(builtin, {
|
|
1581
|
+
dest: opts.dest,
|
|
1582
|
+
force: opts.force
|
|
1583
|
+
});
|
|
1584
|
+
process.exit(code);
|
|
1585
|
+
});
|
|
1586
|
+
scene.command("validate <path>").description(
|
|
1587
|
+
"Validate a workspace scene canva (ws:<path>): parse it and report its derived slots."
|
|
1588
|
+
).action(async (path10) => {
|
|
1589
|
+
const code = await runSceneValidate(path10);
|
|
1590
|
+
process.exit(code);
|
|
1591
|
+
});
|
|
1592
|
+
program.parseAsync(process.argv).catch((err) => {
|
|
1593
|
+
console.error(err instanceof Error ? err.message : err);
|
|
1594
|
+
process.exit(1);
|
|
1595
|
+
});
|
|
1596
|
+
//# sourceMappingURL=index.js.map
|