@bendyline/gezel-cli 1.2.7 → 1.2.9

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.
@@ -4,6 +4,10 @@
4
4
  import { basename as basename4, isAbsolute as isAbsolutePath, join as joinPath } from "path";
5
5
  import {
6
6
  GEZEL_VERSION,
7
+ IMAGE_ASPECT_RATIOS,
8
+ IMAGE_QUALITIES,
9
+ ImageAspectRatioSchema,
10
+ ImageQualitySchema,
7
11
  evaluateApiCompat as evaluateApiCompat2,
8
12
  getLogLevel as getLogLevel2,
9
13
  getLogOutput as getLogOutput2,
@@ -67,6 +71,7 @@ import {
67
71
  gezelNamesInUse,
68
72
  pickUnusedGezelName,
69
73
  projectLeadGezelId,
74
+ roleForMatching,
70
75
  setLogLevel,
71
76
  setLogOutput
72
77
  } from "@bendyline/gezel";
@@ -527,7 +532,7 @@ function cliGrantError(error, target) {
527
532
  if (error instanceof GezelSdkError) {
528
533
  if (error.code === "already_connected") {
529
534
  return new CliError(
530
- "Gezel already has a CLI authorization, but this terminal no longer has its token. Revoke \u201CGezel CLI\u201D in Settings \u2192 Connected Apps, then run this command again."
535
+ "Gezel already has a CLI authorization, but this terminal no longer has its token. Revoke \u201CGezel CLI\u201D in Settings \u2192 Integrations, then run this command again."
531
536
  );
532
537
  }
533
538
  if (error.code === "user_denied") {
@@ -545,7 +550,7 @@ function cliGrantError(error, target) {
545
550
  }
546
551
  if (error.code === "grant_already_pending") {
547
552
  return new CliError(
548
- `An earlier Gezel CLI connection request to ${target} is still waiting to be approved, so a new code cannot be issued yet. Approve or dismiss it in Gezel under Settings \u2192 Connected Apps, or wait ${PENDING_GRANT_MINUTES} minutes for it to expire and run this command again.`
553
+ `An earlier Gezel CLI connection request to ${target} is still waiting to be approved, so a new code cannot be issued yet. Approve or dismiss it in Gezel under Settings \u2192 Integrations, or wait ${PENDING_GRANT_MINUTES} minutes for it to expire and run this command again.`
549
554
  );
550
555
  }
551
556
  if (error.code === "daemon_not_running") {
@@ -621,7 +626,7 @@ async function validateCliClient(client, label) {
621
626
  } catch (error) {
622
627
  if (error instanceof GezelApiError && (error.status === 401 || error.status === 403)) {
623
628
  throw new CliError(
624
- `${label} does not have CLI access. Revoke \u201CGezel CLI\u201D in Settings \u2192 Connected Apps and authorize it again.`
629
+ `${label} does not have CLI access. Revoke \u201CGezel CLI\u201D in Settings \u2192 Integrations and authorize it again.`
625
630
  );
626
631
  }
627
632
  throw error;
@@ -731,7 +736,7 @@ async function ensureCliProjectLead(client, projectId) {
731
736
  }
732
737
  const { gezels } = await client.listGezels();
733
738
  let voorman = gezels.find(
734
- (gezel) => gezel.templateId === "voorman" || gezel.role?.trim().toLowerCase() === "voorman"
739
+ (gezel) => gezel.templateId === "voorman" || roleForMatching(gezel.role)?.trim().toLowerCase() === "voorman"
735
740
  );
736
741
  if (!voorman) {
737
742
  const { name, gender } = pickUnusedGezelName(gezelNamesInUse(gezels));
@@ -739,7 +744,7 @@ async function ensureCliProjectLead(client, projectId) {
739
744
  }
740
745
  const updated = await client.updateProject(projectId, { voormanGezelId: voorman.id });
741
746
  if (!updated.voormanGezelId) {
742
- throw new CliError(`project "${updated.name}" has no voorman`);
747
+ throw new CliError(`project "${updated.name}" has no crew lead`);
743
748
  }
744
749
  return updated.voormanGezelId;
745
750
  }
@@ -1828,6 +1833,13 @@ function intOpt(name, v) {
1828
1833
  if (!Number.isInteger(n)) throw new CliError(`--${name} must be an integer (got "${v}").`);
1829
1834
  return n;
1830
1835
  }
1836
+ function enumOpt(name, v, schema) {
1837
+ if (v === void 0) return void 0;
1838
+ const value = schema.options.find((o) => o === v.trim());
1839
+ if (!value)
1840
+ throw new CliError(`--${name} must be one of ${schema.options.join(", ")} (got "${v}").`);
1841
+ return value;
1842
+ }
1831
1843
  function floatOpt(name, v) {
1832
1844
  if (v === void 0) return void 0;
1833
1845
  const n = Number.parseFloat(v);
@@ -1888,6 +1900,111 @@ function assertCatalogOnlyOptions(opts, kind) {
1888
1900
  }
1889
1901
  }
1890
1902
 
1903
+ // src/mcp-command.ts
1904
+ import {
1905
+ HARNESS_AGENT_FILE,
1906
+ HARNESS_CLIENT_IDS,
1907
+ HarnessClientIdSchema,
1908
+ harnessAgentFileLine,
1909
+ harnessPromptInvocation
1910
+ } from "@bendyline/gezel";
1911
+ import { GezelApiError as GezelApiError2, apiErrorMessage } from "@bendyline/gezel-client";
1912
+ var STATE_WORDS = {
1913
+ configured: "set up",
1914
+ "not-configured": "not set up",
1915
+ "update-needed": "needs repair",
1916
+ conflict: "needs attention",
1917
+ unavailable: "unavailable"
1918
+ };
1919
+ function clientId(name) {
1920
+ const parsed = HarnessClientIdSchema.safeParse(name);
1921
+ if (!parsed.success) {
1922
+ throw new CliError(`Unknown app "${name}". Choose one of: ${HARNESS_CLIENT_IDS.join(", ")}.`);
1923
+ }
1924
+ return parsed.data;
1925
+ }
1926
+ function describe(status) {
1927
+ const lines = [`${status.label}: ${STATE_WORDS[status.state]}`];
1928
+ if (status.configPath) lines.push(` settings: ${status.configPath}`);
1929
+ for (const reason of status.reasons) lines.push(` ${reason}`);
1930
+ if (status.state !== "configured" && status.manualCommand) {
1931
+ lines.push(` to set it up yourself: ${status.manualCommand}`);
1932
+ }
1933
+ return lines.join("\n");
1934
+ }
1935
+ async function call(fn) {
1936
+ try {
1937
+ return await fn();
1938
+ } catch (error) {
1939
+ if (error instanceof GezelApiError2) throw new CliError(apiErrorMessage(error));
1940
+ throw error;
1941
+ }
1942
+ }
1943
+ function registerMcpCommands(program2, connect, output = console.log) {
1944
+ const mcp = program2.command("mcp").description(
1945
+ "Give other AI apps Gezel's tools (Claude Code, Codex, Cursor, Claude Desktop, VS Code)"
1946
+ );
1947
+ mcp.command("status").description("Show which apps have Gezel's tools and what they may do").option("--json", "Output the full status as JSON").action(async (options) => {
1948
+ const status = await call(async () => (await connect()).getHarnessTools());
1949
+ if (options.json) {
1950
+ output(JSON.stringify(status));
1951
+ return;
1952
+ }
1953
+ const { config } = status;
1954
+ const lines = [
1955
+ `Gezel's tools in other apps: ${config.enabled ? "on" : "off"} (memories: ${config.memory}, images: ${config.images}, new folders: ${config.newFolders})`,
1956
+ ...status.unavailableReason ? [status.unavailableReason] : [],
1957
+ "",
1958
+ ...status.clients.map(describe)
1959
+ ];
1960
+ if (status.connections.length > 0) {
1961
+ lines.push("", "In use now:");
1962
+ for (const c of status.connections) {
1963
+ lines.push(
1964
+ ` ${c.label}: ${c.projectName ?? "no project"}${c.folder ? ` (${c.folder})` : ""}`
1965
+ );
1966
+ }
1967
+ }
1968
+ output(lines.join("\n"));
1969
+ });
1970
+ mcp.command("install <app>").description(`Set up Gezel's tools in one app: ${HARNESS_CLIENT_IDS.join(", ")}`).option("--project <id>", "Claude Desktop: the Gezel project it works in").option("--profile <id>", "VS Code: the profile to set up").option("--replace", 'Replace a "gezel" entry Gezel did not write (it is kept as a backup)').option("--json", "Output the app status as JSON").action(async (app, options) => {
1971
+ const client = clientId(app);
1972
+ const status = await call(
1973
+ async () => (await connect()).configureHarnessTools(client, {
1974
+ ...options.project ? { projectId: options.project } : {},
1975
+ ...options.profile ? { profileId: options.profile } : {},
1976
+ ...options.replace ? { replaceExisting: true } : {}
1977
+ })
1978
+ );
1979
+ if (options.json) {
1980
+ output(JSON.stringify(status));
1981
+ return;
1982
+ }
1983
+ const lines = [describe(status)];
1984
+ const line = harnessAgentFileLine(client);
1985
+ if (status.state === "configured" && line) {
1986
+ lines.push(
1987
+ "",
1988
+ `${status.label} reaches for its own search first. So it uses Gezel's, add this line near the top of the ${HARNESS_AGENT_FILE[client]} file in a folder you work in (at the end of a long file it gets overlooked):`,
1989
+ "",
1990
+ ` ${line}`
1991
+ );
1992
+ }
1993
+ const triage = harnessPromptInvocation(client, "triage_issues");
1994
+ if (status.state === "configured" && triage) {
1995
+ lines.push(
1996
+ "",
1997
+ `To have ${status.label} check the suspected problems Gezel's night shift found, run ${triage} in a folder Gezel knows.`
1998
+ );
1999
+ }
2000
+ output(lines.join("\n"));
2001
+ });
2002
+ mcp.command("remove <app>").description("Take Gezel's tools out of one app").option("--json", "Output the app status as JSON").action(async (app, options) => {
2003
+ const status = await call(async () => (await connect()).removeHarnessTools(clientId(app)));
2004
+ output(options.json ? JSON.stringify(status) : describe(status));
2005
+ });
2006
+ }
2007
+
1891
2008
  // src/model-choice.ts
1892
2009
  async function installedChatModels(client, engine) {
1893
2010
  const { models } = engine === "mlx" ? await client.listMlxModels() : engine === "ds4" ? await client.listDs4Models() : await client.listLlamaCppModels();
@@ -2124,20 +2241,32 @@ function stderrProgress() {
2124
2241
  // src/tui/gezel-picker.ts
2125
2242
  import {
2126
2243
  getProjectType,
2244
+ legacyRoleKey,
2245
+ plainRoleTitle,
2127
2246
  resolveProjectTypeId
2128
2247
  } from "@bendyline/gezel";
2129
2248
  function roleIdentity(value) {
2130
- return (value ?? "").trim().toLowerCase();
2249
+ const raw = (value ?? "").trim();
2250
+ return (legacyRoleKey(raw) ?? legacyRoleKey(raw.replace(/-/g, " ")) ?? raw).toLowerCase();
2251
+ }
2252
+ function argKeys(values) {
2253
+ return [
2254
+ ...new Set(
2255
+ values.flatMap((value) => [(value ?? "").trim().toLowerCase(), roleIdentity(value)])
2256
+ )
2257
+ ].filter(Boolean);
2131
2258
  }
2132
2259
  function resolveGezelArg(arg, inputs) {
2133
2260
  const query = arg.trim().toLowerCase();
2134
2261
  if (!query) return { kind: "unknown" };
2135
2262
  const { gezels, templates } = inputs;
2136
- const gezelKeys = (g) => [g.id, g.name, g.roleBasedName, g.role].map(roleIdentity).filter(Boolean);
2137
- const templateKeys = (t) => [t.id, t.role, t.name].map(roleIdentity).filter(Boolean);
2138
- const exactGezel = gezels.find((g) => gezelKeys(g).includes(query));
2263
+ const queryRole = roleIdentity(query);
2264
+ const gezelKeys = (g) => argKeys([g.id, g.name, g.roleBasedName, g.role]);
2265
+ const templateKeys = (t) => argKeys([t.id, t.role, t.name]);
2266
+ const exact = (keys) => keys.includes(query) || keys.includes(queryRole);
2267
+ const exactGezel = gezels.find((g) => exact(gezelKeys(g)));
2139
2268
  if (exactGezel) return { kind: "gezel", gezelId: exactGezel.id };
2140
- const exactTemplate = templates.find((t) => templateKeys(t).includes(query));
2269
+ const exactTemplate = templates.find((t) => exact(templateKeys(t)));
2141
2270
  if (exactTemplate) return { kind: "template", templateId: exactTemplate.id };
2142
2271
  const prefixGezels = gezels.filter((g) => gezelKeys(g).some((k) => k.startsWith(query)));
2143
2272
  if (prefixGezels.length === 1) return { kind: "gezel", gezelId: prefixGezels[0].id };
@@ -2147,7 +2276,7 @@ function resolveGezelArg(arg, inputs) {
2147
2276
  const prefixTemplates = templates.filter((t) => templateKeys(t).some((k) => k.startsWith(query)));
2148
2277
  if (prefixTemplates.length === 1) return { kind: "template", templateId: prefixTemplates[0].id };
2149
2278
  if (prefixTemplates.length > 1) {
2150
- return { kind: "ambiguous", labels: prefixTemplates.map((t) => t.name) };
2279
+ return { kind: "ambiguous", labels: prefixTemplates.map((t) => plainRoleTitle(t.name)) };
2151
2280
  }
2152
2281
  return { kind: "unknown" };
2153
2282
  }
@@ -2439,9 +2568,40 @@ var ReplyPrinter = class {
2439
2568
  this.printed = visible;
2440
2569
  }
2441
2570
  };
2571
+ var RunOutput = class {
2572
+ constructor(write) {
2573
+ this.write = write;
2574
+ this.current = this.nextReply();
2575
+ }
2576
+ write;
2577
+ current;
2578
+ printedAny = false;
2579
+ push(chunk) {
2580
+ this.current.push(chunk);
2581
+ }
2582
+ /** One assistant message was saved; later deltas belong to the next one. */
2583
+ complete(committed) {
2584
+ this.current.finish(committed);
2585
+ this.current = this.nextReply();
2586
+ }
2587
+ /** The stream ended. Returns whether anything was printed. */
2588
+ finish() {
2589
+ this.current.finish();
2590
+ return this.printedAny;
2591
+ }
2592
+ nextReply() {
2593
+ let started = false;
2594
+ return new ReplyPrinter((text) => {
2595
+ if (!started && this.printedAny) this.write("\n\n");
2596
+ started = true;
2597
+ this.printedAny = true;
2598
+ this.write(text);
2599
+ });
2600
+ }
2601
+ };
2442
2602
 
2443
2603
  // src/secrets-command.ts
2444
- import { GezelApiError as GezelApiError2 } from "@bendyline/gezel-client";
2604
+ import { GezelApiError as GezelApiError3 } from "@bendyline/gezel-client";
2445
2605
  var credentialFlags = {
2446
2606
  githubToken: "hasGithubToken",
2447
2607
  openaiApiKey: "hasOpenaiApiKey",
@@ -2495,7 +2655,7 @@ async function writeCredential(client, patch) {
2495
2655
  try {
2496
2656
  await client.updateConfig(patch);
2497
2657
  } catch (error) {
2498
- const status = error instanceof GezelApiError2 ? ` (HTTP ${error.status})` : "";
2658
+ const status = error instanceof GezelApiError3 ? ` (HTTP ${error.status})` : "";
2499
2659
  throw new CliError(
2500
2660
  `Could not update the credential${status}. Check the service connection and permissions.`
2501
2661
  );
@@ -2892,6 +3052,7 @@ program.name("gezel").description("Gezel \u2014 assemble a team of AI companions
2892
3052
  );
2893
3053
  var cliGlobals = () => program.opts();
2894
3054
  registerSecretCommands(program, () => connectOwned(cliGlobals()));
3055
+ registerMcpCommands(program, () => connectOwned(cliGlobals()));
2895
3056
  registerSecurityCommands(program, () => connectOwned(cliGlobals()));
2896
3057
  program.hook("preAction", () => {
2897
3058
  const globals = cliGlobals();
@@ -3298,7 +3459,7 @@ program.command("mode [mode]").description("Show or set AI activity (read-only,
3298
3459
  const current = cliEngagementModeOption(updated.aiEngagementMode);
3299
3460
  console.log(`AI mode \u2192 ${current.name} \u2014 ${current.description}`);
3300
3461
  });
3301
- program.command("run [prompt...]").description("Run a prompt through a gezel and print the reply (use - to read stdin)").option("-g, --gezel <ref>", "gezel id or name (default: this project's voorman)").addHelpText(
3462
+ program.command("run [prompt...]").description("Run a prompt through a gezel and print the reply (use - to read stdin)").option("-g, --gezel <ref>", "gezel id or name (default: this project's crew lead)").addHelpText(
3302
3463
  "after",
3303
3464
  `
3304
3465
  Examples:
@@ -3336,9 +3497,8 @@ Replies go to stdout; diagnostics go to stderr.`
3336
3497
  }
3337
3498
  const session = await client.createChatSession({ gezelId, projectId, oneShot: true });
3338
3499
  await client.sendToChatSession(session.id, prompt);
3339
- const reply = new ReplyPrinter((text) => process.stdout.write(text));
3500
+ const reply = new RunOutput((text) => process.stdout.write(text));
3340
3501
  const progress = new RunProgress((text) => process.stderr.write(text));
3341
- let printed = false;
3342
3502
  let errored = false;
3343
3503
  for await (const ev of streamChatEvents({
3344
3504
  url: client.sessionEventsUrl(session.id),
@@ -3352,7 +3512,7 @@ Replies go to stdout; diagnostics go to stderr.`
3352
3512
  reply.push(ev.content);
3353
3513
  } else if (ev.type === "complete") {
3354
3514
  progress.settle();
3355
- printed = reply.finish(ev.message.content);
3515
+ reply.complete(ev.message.content);
3356
3516
  } else if (ev.type === "error") {
3357
3517
  progress.settle();
3358
3518
  console.error(`
@@ -3361,8 +3521,7 @@ ${ev.error}`);
3361
3521
  }
3362
3522
  }
3363
3523
  progress.settle();
3364
- printed = reply.finish() || printed;
3365
- if (printed) process.stdout.write("\n");
3524
+ if (reply.finish()) process.stdout.write("\n");
3366
3525
  if (errored) process.exitCode = 1;
3367
3526
  } finally {
3368
3527
  removeSignalCleanup?.();
@@ -3978,6 +4137,10 @@ appCmd.command("pack <folder>").description("Validate and pack an AI App source
3978
4137
  const { runAppPack } = await loadAppAuthorCommand();
3979
4138
  await runAppPack(folder, opts);
3980
4139
  });
4140
+ appCmd.command("demo <folder>").description("Export an offline page demo with shared components and fonts (no daemon needed)").requiredOption("-o, --out <directory>", "new output directory for the generated demo").action(async (folder, opts) => {
4141
+ const { runAppDemo } = await loadAppAuthorCommand();
4142
+ await runAppDemo(folder, opts);
4143
+ });
3981
4144
  appCmd.command("schemas").description("The JSON Schemas an AI App author codes against, rendered from this build").option("--out <dir>", "write the schema files into a directory").option("--json", "print one combined JSON object").action(async (opts) => {
3982
4145
  const { runAppSchemas } = await loadAppAuthorCommand();
3983
4146
  await runAppSchemas(opts);
@@ -4076,8 +4239,10 @@ ${warning.text}`)
4076
4239
  ].join("\n\n") || "(no task notes)"
4077
4240
  );
4078
4241
  });
4079
- program.command("create-image [prompt...]").description("Generate an image from a prompt (or --file) via the configured image engine").option("-f, --file <path>", "read the prompt from a text file instead of the argument").option("-m, --model <id>", "image model catalog id (default: the engine default)").option("-n, --negative <text>", "negative prompt").option("-W, --width <px>", "width in pixels").option("-H, --height <px>", "height in pixels").option("-s, --steps <n>", "sampler steps (default: the model recommendation)").option("--seed <n>", "seed for reproducible output").option("-p, --project <id>", "project to write the artifact under", "default").option("-o, --output <path>", "write the image here (default: ./<artifact name>)").action(
4242
+ program.command("create-image [prompt...]").description("Generate an image from a prompt (or --file) via the configured image engine").option("-f, --file <path>", "read the prompt from a text file instead of the argument").option("-m, --model <id>", "image model catalog id (default: the engine default)").option("-n, --negative <text>", "negative prompt").option("-W, --width <px>", "width in pixels").option("-H, --height <px>", "height in pixels").option("-a, --aspect <ratio>", `aspect ratio: ${IMAGE_ASPECT_RATIOS.join(", ")}`).option("-q, --quality <tier>", `size tier: ${IMAGE_QUALITIES.join(", ")} (default: standard)`).option("-s, --steps <n>", "sampler steps (default: the model recommendation)").option("--seed <n>", "seed for reproducible output").option("-p, --project <id>", "project to write the artifact under", "default").option("-o, --output <path>", "write the image here (default: ./<artifact name>)").action(
4080
4243
  async (promptParts, opts) => {
4244
+ const aspect = enumOpt("aspect", opts.aspect, ImageAspectRatioSchema);
4245
+ const quality = enumOpt("quality", opts.quality, ImageQualitySchema);
4081
4246
  const prompt = await resolvePromptText(promptParts, opts.file, "prompt");
4082
4247
  const client = await connectOwned(cliGlobals());
4083
4248
  const projectId = opts.project ?? "default";
@@ -4095,6 +4260,8 @@ program.command("create-image [prompt...]").description("Generate an image from
4095
4260
  ...opts.negative ? { negativePrompt: opts.negative } : {},
4096
4261
  ...width !== void 0 ? { width } : {},
4097
4262
  ...height !== void 0 ? { height } : {},
4263
+ ...aspect ? { aspectRatio: aspect } : {},
4264
+ ...quality ? { quality } : {},
4098
4265
  ...steps !== void 0 ? { steps } : {},
4099
4266
  ...seed !== void 0 ? { seed } : {}
4100
4267
  });
@@ -2,13 +2,14 @@
2
2
 
3
3
  // src/handboek-export.ts
4
4
  import { existsSync as existsSync2 } from "fs";
5
- import { cp, mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
6
- import { join as join2, resolve } from "path";
5
+ import { cp, mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
6
+ import { join as join4, resolve } from "path";
7
7
  import { SCORECARD_DATA_ATTRS as SCORECARD_DATA_ATTRS2 } from "@bendyline/gezel";
8
8
  import { CatalogService } from "@bendyline/gezel-catalog";
9
9
  import {
10
10
  OG_CARD_HEIGHT,
11
11
  OG_CARD_WIDTH,
12
+ bundledGildeDataDir,
12
13
  createHandboekEngine,
13
14
  findHandboekContent,
14
15
  ogKicker,
@@ -492,7 +493,7 @@ async function projectTypeDemo(catalog, pt) {
492
493
  const bytes = await catalog.readItemFile("project-type", pt.id, `${prefix}${path}`);
493
494
  if (bytes) files.push({ path, bytes });
494
495
  }
495
- return { projectTypeId: pt.id, entry, files };
496
+ return { projectTypeId: pt.id, entry, files, imports: pt.pages?.imports };
496
497
  }
497
498
  function demoSectionHtml(demo, title) {
498
499
  const src = `demo/${demo.entry.split("/").map(encodeURIComponent).join("/")}`;
@@ -1413,6 +1414,77 @@ var SCORECARD_FILTER_JS = `(function () {
1413
1414
  })();
1414
1415
  `;
1415
1416
 
1417
+ // src/page-demo-export.ts
1418
+ import { createHash as createHash2 } from "crypto";
1419
+ import { readFileSync as readFileSync2 } from "fs";
1420
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
1421
+ import { dirname as dirname2, join as join3, relative as relative2 } from "path";
1422
+ import { fileURLToPath } from "url";
1423
+ import { injectPageDemo, pageDemoBootstrapSource } from "@bendyline/gezel";
1424
+
1425
+ // ../../scripts/project-page-typography.mjs
1426
+ import { readFileSync } from "fs";
1427
+ import { join as join2 } from "path";
1428
+ function buildProjectPageTypography(uiRoot) {
1429
+ const fonts = join2(uiRoot, "src/assets/fonts");
1430
+ const faces = readFileSync(join2(fonts, "ui-fonts.css"), "utf8").replace(
1431
+ /url\("\.\/([a-z0-9-]+\.woff2)"\)/g,
1432
+ (_, name) => `url("data:font/woff2;base64,${readFileSync(join2(fonts, name)).toString("base64")}")`
1433
+ );
1434
+ return [
1435
+ faces,
1436
+ readFileSync(join2(fonts, "typography-tokens.css"), "utf8"),
1437
+ readFileSync(join2(fonts, "page-defaults.css"), "utf8")
1438
+ ].join("\n");
1439
+ }
1440
+
1441
+ // src/page-demo-export.ts
1442
+ function pageDemoAssets() {
1443
+ const sourceMode = import.meta.url.endsWith(".ts");
1444
+ const fonts = fileURLToPath(new URL("../../ui/src/assets/fonts/", import.meta.url));
1445
+ const css = sourceMode ? buildProjectPageTypography(fileURLToPath(new URL("../../ui", import.meta.url))) : readFileSync2(new URL("./page-typography.css", import.meta.url), "utf8");
1446
+ const versioned = (stem, extension, source) => ({
1447
+ path: `${stem}-${createHash2("sha256").update(source).digest("hex").slice(0, 16)}.${extension}`,
1448
+ bytes: Buffer.from(source)
1449
+ });
1450
+ return [
1451
+ versioned("bootstrap", "js", pageDemoBootstrapSource()),
1452
+ versioned("typography", "css", css),
1453
+ ...["LICENSE-HankenGrotesk-OFL-1.1.txt", "LICENSE-PTSerif-OFL-1.1.txt"].map((path) => ({
1454
+ path,
1455
+ bytes: readFileSync2(sourceMode ? join3(fonts, path) : new URL(`./${path}`, import.meta.url))
1456
+ }))
1457
+ ];
1458
+ }
1459
+ async function writePageDemoAssets(directory) {
1460
+ const assets = pageDemoAssets();
1461
+ await mkdir2(directory, { recursive: true });
1462
+ for (const asset of assets) await writeFile2(join3(directory, asset.path), asset.bytes);
1463
+ return assets;
1464
+ }
1465
+ async function writePageDemo(directory, files, config, shared) {
1466
+ const script = shared.assets.find((file) => file.path.endsWith(".js"));
1467
+ const style = shared.assets.find((file) => file.path.endsWith(".css"));
1468
+ for (const file of files) {
1469
+ if (!file.path || file.path.split(/[\\/]/).some((part) => !part || part === "." || part === "..") || /[:\\]/.test(file.path)) {
1470
+ throw new Error(`Unsafe demo asset path: ${file.path}`);
1471
+ }
1472
+ const target = join3(directory, file.path);
1473
+ let bytes = file.bytes;
1474
+ if (/\.html?$/i.test(file.path)) {
1475
+ const url = (name) => relative2(dirname2(target), join3(shared.directory, name)).split(/[\\/]/).map((part) => part === ".." ? part : encodeURIComponent(part)).join("/");
1476
+ bytes = Buffer.from(
1477
+ injectPageDemo(bytes.toString("utf8"), config, {
1478
+ scriptUrl: url(script.path),
1479
+ styleUrl: url(style.path)
1480
+ })
1481
+ );
1482
+ }
1483
+ await mkdir2(dirname2(target), { recursive: true });
1484
+ await writeFile2(target, bytes);
1485
+ }
1486
+ }
1487
+
1416
1488
  // src/handboek-export.ts
1417
1489
  var NAV_INLINE_MAX = 40;
1418
1490
  var SCORECARD_SCRIPT = "scorecard.js";
@@ -1439,7 +1511,7 @@ async function runHandboekExport(opts) {
1439
1511
  "no handboek content tree found \u2014 run from a gezel checkout or install, or set GEZEL_HANDBOEK_DIR"
1440
1512
  );
1441
1513
  }
1442
- const catalog = new CatalogService();
1514
+ const catalog = new CatalogService(void 0, { contentRoot: bundledGildeDataDir });
1443
1515
  const engine = createHandboekEngine({
1444
1516
  catalog,
1445
1517
  device: siteDeviceInfo,
@@ -1449,6 +1521,8 @@ async function runHandboekExport(opts) {
1449
1521
  const site = await buildSiteCatalog(catalog);
1450
1522
  const sitePages = new Map(site.pages.map((p) => [p.entry.id, p]));
1451
1523
  const demos = new Map(site.demos.map((d) => [`project-type/${d.projectTypeId}`, d]));
1524
+ const demoAssetsDirectory = join4(out, "_gezel-demo");
1525
+ const demoAssets = site.demos.length ? await writePageDemoAssets(demoAssetsDirectory) : [];
1452
1526
  const areas = toc.areas.map((a) => ({
1453
1527
  ...a,
1454
1528
  entries: [
@@ -1466,9 +1540,9 @@ async function runHandboekExport(opts) {
1466
1540
  const stem = e.id.split("/").pop();
1467
1541
  if (stem && !byStem.has(stem)) byStem.set(stem, e.id);
1468
1542
  }
1469
- await mkdir2(join2(out, "assets"), { recursive: true });
1470
- await writeFile2(join2(out, "assets", "squisq-player.js"), PLAYER_BUNDLE, "utf8");
1471
- await writeFile2(join2(out, "assets", SCORECARD_SCRIPT), SCORECARD_FILTER_JS, "utf8");
1543
+ await mkdir3(join4(out, "assets"), { recursive: true });
1544
+ await writeFile3(join4(out, "assets", "squisq-player.js"), PLAYER_BUNDLE, "utf8");
1545
+ await writeFile3(join4(out, "assets", SCORECARD_SCRIPT), SCORECARD_FILTER_JS, "utf8");
1472
1546
  const skipped = [];
1473
1547
  let pages = 0;
1474
1548
  const headlines = readOgHeadlines(contentDir);
@@ -1488,7 +1562,13 @@ async function runHandboekExport(opts) {
1488
1562
  continue;
1489
1563
  }
1490
1564
  const depth = entry.id.split("/").length;
1491
- const markdown = rewriteSiteLinks(article.markdown, entry.id, ids, byStem);
1565
+ const markdown = rewriteSiteLinks(
1566
+ article.markdown,
1567
+ entry.id,
1568
+ ids,
1569
+ byStem,
1570
+ (asset) => existsSync2(join4(contentDir, asset))
1571
+ );
1492
1572
  const parsed = parseMarkdown(markdown);
1493
1573
  const demo = demos.get(entry.id);
1494
1574
  const art = entry.id.startsWith("craftbook/") ? site.craftbookArt.get(entry.id.slice("craftbook/".length)) : void 0;
@@ -1500,15 +1580,19 @@ ${sitePage.html}`;
1500
1580
  if (demo) rendered = insertDemoSection(rendered, demoSectionHtml(demo, entry.title));
1501
1581
  if (art) rendered = insertAfterTitle(rendered, craftbookArtHtml(entry.title));
1502
1582
  const { html: body, headings } = withHeadingIds(rendered);
1503
- const dir = join2(out, ...entry.id.split("/"));
1504
- await mkdir2(dir, { recursive: true });
1505
- if (art) await writeFile2(join2(dir, CRAFTBOOK_ART_FILE), art);
1583
+ const dir = join4(out, ...entry.id.split("/"));
1584
+ await mkdir3(dir, { recursive: true });
1585
+ if (art) await writeFile3(join4(dir, CRAFTBOOK_ART_FILE), art);
1506
1586
  if (demo) {
1507
- for (const file of demo.files) {
1508
- const target = join2(dir, "demo", ...file.path.split("/"));
1509
- await mkdir2(join2(target, ".."), { recursive: true });
1510
- await writeFile2(target, file.bytes);
1511
- }
1587
+ await writePageDemo(
1588
+ join4(dir, "demo"),
1589
+ demo.files,
1590
+ { imports: demo.imports },
1591
+ {
1592
+ directory: demoAssetsDirectory,
1593
+ assets: demoAssets
1594
+ }
1595
+ );
1512
1596
  }
1513
1597
  const headline = resolveOgHeadline(entry, headlines);
1514
1598
  if (ogBase) {
@@ -1520,8 +1604,8 @@ ${sitePage.html}`;
1520
1604
  image: ogBase ? `${ogBase}${ogCardPath(entry.id)}` : void 0,
1521
1605
  imageAlt: headline
1522
1606
  } : void 0;
1523
- await writeFile2(
1524
- join2(dir, "index.html"),
1607
+ await writeFile3(
1608
+ join4(dir, "index.html"),
1525
1609
  articlePage({
1526
1610
  entry,
1527
1611
  body,
@@ -1539,8 +1623,8 @@ ${sitePage.html}`;
1539
1623
  articleId: article.id,
1540
1624
  defaultDuration: article.defaultDuration ?? 6
1541
1625
  });
1542
- await writeFile2(
1543
- join2(dir, "watch.html"),
1626
+ await writeFile3(
1627
+ join4(dir, "watch.html"),
1544
1628
  generateExternalHtml(doc, {
1545
1629
  playerScriptPath: `${up(depth)}assets/squisq-player.js`,
1546
1630
  mode: "slideshow",
@@ -1564,13 +1648,13 @@ ${sitePage.html}`;
1564
1648
  headline: "The Gezel Handboek"
1565
1649
  });
1566
1650
  }
1567
- await writeFile2(join2(out, "index.html"), landingPage(areas, css, siteUrl, landingSocial), "utf8");
1651
+ await writeFile3(join4(out, "index.html"), landingPage(areas, css, siteUrl, landingSocial), "utf8");
1568
1652
  pages += 1;
1569
- const assetsSrc = join2(contentDir, "assets");
1653
+ const assetsSrc = join4(contentDir, "assets");
1570
1654
  if (existsSync2(assetsSrc)) {
1571
- await cp(assetsSrc, join2(out, "assets"), { recursive: true });
1655
+ await cp(assetsSrc, join4(out, "assets"), { recursive: true });
1572
1656
  }
1573
- await writeFile2(join2(out, "assets", "handboek.css"), BASELINE_CSS, "utf8");
1657
+ await writeFile3(join4(out, "assets", "handboek.css"), BASELINE_CSS, "utf8");
1574
1658
  const cards = ogBase && opts.ogOut ? await writeOgCards({
1575
1659
  home: opts.home ?? gezelHome(),
1576
1660
  dir: resolve(opts.ogOut),
@@ -1584,18 +1668,19 @@ function normalizeBase(base) {
1584
1668
  if (!trimmed) return void 0;
1585
1669
  return trimmed.endsWith("/") ? trimmed : `${trimmed}/`;
1586
1670
  }
1587
- function rewriteSiteLinks(markdown, pageId, ids, byStem) {
1671
+ function rewriteSiteLinks(markdown, pageId, ids, byStem, hasAsset = () => true) {
1588
1672
  const prefix = up(pageId.split("/").length);
1589
1673
  return markdown.replace(/\]\(([^()\s]+)\)/g, (whole, rawTarget) => {
1590
1674
  if (/^[a-z][a-z0-9+.-]*:/i.test(rawTarget) || rawTarget.startsWith("//") || rawTarget.startsWith("#")) {
1591
1675
  return whole;
1592
1676
  }
1593
1677
  const [path, suffix = ""] = splitLinkSuffix(rawTarget);
1594
- const candidate = path.replace(/\.md$/, "").replace(/^(\.\.?\/)+/, "");
1678
+ const candidate = path.replace(/^(\.\.?\/)+/, "");
1595
1679
  if (candidate.startsWith("assets/")) {
1596
- return `](${prefix}${candidate}${suffix})`;
1680
+ return hasAsset(candidate) ? `](${prefix}${candidate}${suffix})` : `](${PUBLISHED_HANDBOEK}${candidate}${suffix})`;
1597
1681
  }
1598
- const target = ids.has(candidate) ? candidate : byStem.get(candidate.split("/").pop() ?? "");
1682
+ const article = candidate.replace(/\.md$/, "");
1683
+ const target = ids.has(article) ? article : byStem.get(article.split("/").pop() ?? "");
1599
1684
  if (!target) return whole;
1600
1685
  return `](${prefix}${target}/${suffix})`;
1601
1686
  });
@@ -1604,6 +1689,7 @@ function splitLinkSuffix(raw) {
1604
1689
  const idx = raw.search(/[?#]/);
1605
1690
  return idx === -1 ? [raw, ""] : [raw.slice(0, idx), raw.slice(idx)];
1606
1691
  }
1692
+ var PUBLISHED_HANDBOEK = "https://gezel.com/docs/";
1607
1693
  var up = (depth) => "../".repeat(depth);
1608
1694
  var esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
1609
1695
  function extractBody(page) {
@@ -41,6 +41,7 @@ import {
41
41
  gezelNamesInUse,
42
42
  pickUnusedGezelName,
43
43
  projectLeadGezelId,
44
+ roleForMatching,
44
45
  setLogLevel,
45
46
  setLogOutput
46
47
  } from "@bendyline/gezel";