@tdacorp/hyle-sdk 0.17.0 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +261 -42
  2. package/dist/check-routes-bin.js +190 -53
  3. package/dist/{chunk-6VOHFFA5.js → chunk-7T5EEJHK.js} +2 -2
  4. package/dist/chunk-DUPT6XLB.js +57 -0
  5. package/dist/chunk-IW3TUD4G.js +841 -0
  6. package/dist/{chunk-MGSUQBDW.js → chunk-KU7LWK4E.js} +249 -24
  7. package/dist/{chunk-BUJFMR3M.js → chunk-QVYQM5R2.js} +15 -6
  8. package/dist/chunk-SFFBZFEN.js +178 -0
  9. package/dist/chunk-U74B7AUG.js +398 -0
  10. package/dist/chunk-ZIW6FDU2.js +1126 -0
  11. package/dist/client-BGjmEWhN.d.cts +207 -0
  12. package/dist/client-D0LTpr3Y.d.ts +207 -0
  13. package/dist/code-copy.cjs +74 -0
  14. package/dist/code-copy.d.cts +18 -0
  15. package/dist/code-copy.d.ts +18 -0
  16. package/dist/code-copy.js +50 -0
  17. package/dist/comments.cjs +738 -280
  18. package/dist/comments.d.cts +66 -3
  19. package/dist/comments.d.ts +66 -3
  20. package/dist/comments.js +419 -331
  21. package/dist/{diagram-viewer-FJPED4SN.js → diagram-viewer-XY3CG75U.js} +62 -21
  22. package/dist/docs-enhance.cjs +7 -4
  23. package/dist/docs-enhance.d.cts +5 -3
  24. package/dist/docs-enhance.d.ts +5 -3
  25. package/dist/docs-enhance.js +8 -5
  26. package/dist/{embed-DNTZ2UXv.d.ts → embed-CbtsbZs3.d.cts} +5 -3
  27. package/dist/{embed-BmdwA2G9.d.cts → embed-Cf_2ZR5x.d.ts} +5 -3
  28. package/dist/fragment-alias.cjs +51 -0
  29. package/dist/fragment-alias.d.cts +7 -0
  30. package/dist/fragment-alias.d.ts +7 -0
  31. package/dist/fragment-alias.js +27 -0
  32. package/dist/html.cjs +886 -0
  33. package/dist/html.d.cts +20 -0
  34. package/dist/html.d.ts +20 -0
  35. package/dist/html.js +45 -0
  36. package/dist/index.cjs +244 -24
  37. package/dist/index.d.cts +22 -68
  38. package/dist/index.d.ts +22 -68
  39. package/dist/index.js +12 -2
  40. package/dist/{labels-nmukKYgL.d.cts → labels-CrA-iqTN.d.cts} +9 -0
  41. package/dist/{labels-nmukKYgL.d.ts → labels-CrA-iqTN.d.ts} +9 -0
  42. package/dist/mermaid-diagram.cjs +441 -125
  43. package/dist/mermaid-diagram.d.cts +23 -7
  44. package/dist/mermaid-diagram.d.ts +23 -7
  45. package/dist/mermaid-diagram.js +213 -51
  46. package/dist/mermaid-image.cjs +137 -60
  47. package/dist/mermaid-image.d.cts +4 -3
  48. package/dist/mermaid-image.d.ts +4 -3
  49. package/dist/mermaid-image.js +27 -28
  50. package/dist/next.cjs +836 -304
  51. package/dist/next.d.cts +45 -20
  52. package/dist/next.d.ts +45 -20
  53. package/dist/next.js +151 -40
  54. package/dist/print-coordinator.cjs +157 -0
  55. package/dist/print-coordinator.d.cts +27 -0
  56. package/dist/print-coordinator.d.ts +27 -0
  57. package/dist/print-coordinator.js +83 -0
  58. package/dist/react.cjs +603 -240
  59. package/dist/react.d.cts +148 -30
  60. package/dist/react.d.ts +148 -30
  61. package/dist/react.js +26 -4
  62. package/dist/reactions.cjs +653 -0
  63. package/dist/reactions.d.cts +27 -0
  64. package/dist/reactions.d.ts +27 -0
  65. package/dist/reactions.js +364 -0
  66. package/dist/{resolve-euZ4-aC9.d.cts → resolve-BnIv7aB7.d.cts} +2 -2
  67. package/dist/{resolve-Ae7UFjsQ.d.ts → resolve-BysHtZ_i.d.ts} +2 -2
  68. package/dist/revalidation-callback-BQl77tQR.d.cts +75 -0
  69. package/dist/revalidation-callback-BQl77tQR.d.ts +75 -0
  70. package/dist/sanitize-BpY_AdZh.d.cts +23 -0
  71. package/dist/sanitize-BpY_AdZh.d.ts +23 -0
  72. package/dist/styles.css +100 -29
  73. package/dist/toc-spy.cjs +60 -0
  74. package/dist/toc-spy.d.cts +15 -0
  75. package/dist/toc-spy.d.ts +15 -0
  76. package/dist/toc-spy.js +36 -0
  77. package/dist/{types-Czt887Iv.d.cts → types-D09Z072G.d.cts} +57 -2
  78. package/dist/{types-Czt887Iv.d.ts → types-D09Z072G.d.ts} +57 -2
  79. package/dist/use-cache.cjs +89 -13
  80. package/dist/use-cache.d.cts +12 -5
  81. package/dist/use-cache.d.ts +12 -5
  82. package/dist/use-cache.js +8 -8
  83. package/dist/youtube-facade.cjs +50 -0
  84. package/dist/youtube-facade.d.cts +17 -0
  85. package/dist/youtube-facade.d.ts +17 -0
  86. package/dist/youtube-facade.js +26 -0
  87. package/package.json +16 -3
  88. package/dist/chunk-67IOIAVW.js +0 -35
  89. package/dist/chunk-DMK4XQLU.js +0 -1556
  90. package/dist/chunk-PJMJMP66.js +0 -63
  91. package/dist/revalidation-callback-D7Ms_Puz.d.cts +0 -42
  92. package/dist/revalidation-callback-D7Ms_Puz.d.ts +0 -42
@@ -6,9 +6,15 @@ import { join } from "path";
6
6
  var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
7
7
  var ASSET_RESERVED_PATH = "/api/hyle/*";
8
8
  var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
9
- var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
9
+ var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg|woff2";
10
10
  var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
11
- var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
11
+ var THEME_FONT = new RegExp(`^/assets/${UUID}\\.woff2$`);
12
+ var PREVIEW_TOKEN_SOURCE = "hyle_pv_[A-Za-z0-9_-]{43}";
13
+ var PREVIEW_TOKEN = new RegExp(`^${PREVIEW_TOKEN_SOURCE}$`);
14
+ var PREVIEW_HEADER = "cp-preview";
15
+ var PREVIEW_PARAM = "hyle_preview";
16
+ var PREVIEW_QUERY_SOURCE = `\\?${PREVIEW_PARAM}=${PREVIEW_TOKEN_SOURCE}`;
17
+ var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)(${PREVIEW_QUERY_SOURCE})?$`, "i");
12
18
 
13
19
  // src/errors.ts
14
20
  var Cp1ClientError = class extends Error {
@@ -26,7 +32,43 @@ var Cp1ClientError = class extends Error {
26
32
  }
27
33
  };
28
34
 
35
+ // src/preview.ts
36
+ var ASSET_PATH = /^\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?:\.[a-z0-9]+)?(?= |$)/i;
37
+ var ASSET_PROPERTIES = ["src", "dataLight", "dataDark"];
38
+ var MAX_DEPTH = 200;
39
+ function mapNode(node, mark, depth) {
40
+ if (typeof node !== "object" || node === null || depth > MAX_DEPTH) return node;
41
+ const { properties, children } = node;
42
+ const marked = properties && Object.fromEntries(ASSET_PROPERTIES.filter((name) => name in properties).map((name) => [name, mark(properties[name])]));
43
+ return {
44
+ ...node,
45
+ ...properties ? { properties: { ...properties, ...marked } } : {},
46
+ ...Array.isArray(children) ? { children: children.map((child) => mapNode(child, mark, depth + 1)) } : {}
47
+ };
48
+ }
49
+ function withPreviewAssets(article, token) {
50
+ const mark = (value) => typeof value === "string" ? value.replace(ASSET_PATH, (path) => `${path}?${PREVIEW_PARAM}=${token}`) : value;
51
+ const { publication, content } = article;
52
+ return {
53
+ ...article,
54
+ publication: publication.cover ? { ...publication, cover: { path: String(mark(publication.cover.path)) } } : publication,
55
+ content: content.format === "hast" ? { ...content, tree: mapNode(content.tree, mark, 0) } : content
56
+ };
57
+ }
58
+
29
59
  // src/client.ts
60
+ var RENDERER_VERSION = "4";
61
+ function applyCredential(headers, credential, method, url) {
62
+ if (!credential.auth) {
63
+ headers.set("authorization", `Bearer ${credential.token}`);
64
+ return void 0;
65
+ }
66
+ const { workspaceId } = credential;
67
+ return credential.auth({ method, url }).then((extra) => {
68
+ for (const [name, value] of Object.entries(extra)) headers.set(name, value);
69
+ headers.set("cp-workspace", workspaceId);
70
+ });
71
+ }
30
72
  var DEFAULT_TIMEOUT_MS = 1e4;
31
73
  var DEFAULT_MAX_RESPONSE_BYTES = 5 * 1024 * 1024;
32
74
  var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
@@ -68,14 +110,16 @@ function checkBaseUrl(baseUrl, allowInsecureHttp) {
68
110
  }
69
111
  function createHyleClient(options) {
70
112
  checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
71
- if (!options.token) throw new TypeError("token is required");
113
+ if (!options.auth && !options.token) throw new TypeError("token is required");
72
114
  const base = options.baseUrl.replace(/\/+$/, "");
73
115
  const fetchImpl = options.fetch ?? fetch;
74
116
  async function get(pathname, query, init) {
75
117
  const url = new URL(`${base}${pathname}`);
76
118
  url.search = query.toString();
77
119
  const headers = new Headers(init?.headers);
78
- headers.set("authorization", `Bearer ${options.token}`);
120
+ headers.set("cp-renderer-version", RENDERER_VERSION);
121
+ const applied = applyCredential(headers, options, "GET", url.toString());
122
+ if (applied) await applied;
79
123
  const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
80
124
  const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
81
125
  const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
@@ -115,41 +159,71 @@ function createHyleClient(options) {
115
159
  if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
116
160
  throw failure(reply);
117
161
  }
162
+ async function pushPosts(opts) {
163
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(opts.section)) throw new TypeError("section must be a section slug");
164
+ const query = new URLSearchParams();
165
+ if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
166
+ const reply = await get(`/cp1/read/sections/${opts.section}/posts`, query, opts.init);
167
+ const data = reply.parsed?.data;
168
+ if (data?.cp === 1 && data.kind === "push_posts" && Array.isArray(data.posts) && typeof data.complete === "boolean") return data;
169
+ throw failure(reply);
170
+ }
171
+ async function preview(token) {
172
+ if (typeof token !== "string" || !PREVIEW_TOKEN.test(token)) return { kind: "notfound" };
173
+ const reply = await get("/cp1/read/_preview", new URLSearchParams(), { headers: { [PREVIEW_HEADER]: token }, cache: "no-store" });
174
+ if (reply.status === 404 && reply.parsed?.error?.code === "NOT_FOUND") return { kind: "notfound" };
175
+ const data = reply.parsed?.data;
176
+ if (data?.cp === 1 && data.kind === "disabled") return { kind: "disabled" };
177
+ const article = data?.article;
178
+ if (data?.cp !== 1 || data.kind !== "preview" || typeof data.expires_at !== "string" || article?.kind !== "article" || article.content?.format !== "hast" || !article.publication) throw failure(reply);
179
+ return { kind: "preview", expires_at: data.expires_at, article: withPreviewAssets(article, token) };
180
+ }
118
181
  async function asset(file, opts = {}) {
119
182
  if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
120
- const headers = new Headers({ authorization: `Bearer ${options.token}` });
183
+ const { previewToken } = opts;
184
+ if (previewToken !== void 0 && !PREVIEW_TOKEN.test(previewToken)) throw new TypeError("previewToken is not a preview token");
185
+ const url = `${base}/cp1/read/assets/${file}`;
186
+ const headers = new Headers();
187
+ const applied = applyCredential(headers, options, "GET", url);
188
+ if (applied) await applied;
121
189
  for (const name of ["range", "if-range", "if-none-match"]) {
122
190
  const value = opts.headers?.[name];
123
191
  if (value) headers.set(name, value);
124
192
  }
125
- return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
193
+ if (previewToken !== void 0) headers.set(PREVIEW_HEADER, previewToken);
194
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS), ...previewToken === void 0 ? {} : { cache: "no-store" } });
126
195
  }
127
- return { resolve, mounts, asset };
196
+ async function theme(opts = {}) {
197
+ const url = `${base}/cp1/read/theme.css`;
198
+ const headers = new Headers();
199
+ const applied = applyCredential(headers, options, "GET", url);
200
+ if (applied) await applied;
201
+ return fetchImpl(url, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
202
+ }
203
+ return { resolve, mounts, pushPosts, preview, asset, theme };
128
204
  }
129
205
 
130
206
  // src/host-sync.ts
131
207
  var CONTROL_TOKEN_PREFIX = "hyle_tc_";
132
208
  var DEFAULT_TIMEOUT_MS2 = 1e4;
133
209
  var MAX_RESPONSE_BYTES = 1024 * 1024;
134
- var PATH = "/cp1/control/workspace/host-reserved-paths";
135
- async function syncHostReserved(input) {
210
+ async function put(input, path, body, read) {
136
211
  checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
137
- if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
212
+ if (input.token !== void 0 && !input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
138
213
  throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
139
214
  }
140
215
  const fetchImpl = input.fetch ?? fetch;
141
- const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
216
+ const url = `${input.baseUrl.replace(/\/+$/, "")}${path}`;
217
+ const headers = new Headers({ "content-type": "application/json", "idempotency-key": `sync-${crypto.randomUUID()}` });
218
+ await applyCredential(headers, input.auth ? { auth: input.auth, workspaceId: input.workspaceId } : { token: input.token }, "PUT", url);
219
+ headers.set("cp-workspace", input.workspaceId);
220
+ const res = await fetchImpl(url, {
142
221
  method: "PUT",
143
222
  // redirect "error": the bearer token must never follow a redirect to another host.
144
223
  redirect: "error",
145
224
  signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
146
- headers: {
147
- authorization: `Bearer ${input.token}`,
148
- "content-type": "application/json",
149
- "cp-workspace": input.workspaceId,
150
- "idempotency-key": `sync-${crypto.randomUUID()}`
151
- },
152
- body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
225
+ headers,
226
+ body: JSON.stringify(body)
153
227
  });
154
228
  const text = await readCapped(res, MAX_RESPONSE_BYTES);
155
229
  let parsed;
@@ -158,14 +232,24 @@ async function syncHostReserved(input) {
158
232
  } catch {
159
233
  parsed = void 0;
160
234
  }
161
- const data = parsed?.data;
162
- const conflicts = data?.conflicts;
163
- if (res.ok && data && Array.isArray(data.paths) && typeof data.changed === "boolean" && typeof data.synced_at === "string" && typeof conflicts?.total === "number" && Array.isArray(conflicts.offenders)) {
164
- return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
165
- }
235
+ const result = res.ok && parsed?.data ? read(parsed.data) : void 0;
236
+ if (result !== void 0) return result;
166
237
  const err = parsed?.error;
167
238
  throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
168
239
  }
240
+ function syncHostReserved(input) {
241
+ return put(input, "/cp1/control/workspace/host-reserved-paths", { paths: input.paths, host: input.host, build_id: input.buildId }, (data) => {
242
+ const conflicts = data.conflicts;
243
+ if (!Array.isArray(data.paths) || typeof data.changed !== "boolean" || typeof data.synced_at !== "string" || typeof conflicts?.total !== "number" || !Array.isArray(conflicts.offenders)) return void 0;
244
+ return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
245
+ });
246
+ }
247
+ function syncCodeTheme(input) {
248
+ return put(input, "/cp1/control/workspace/code-theme", { theme: input.theme, host: input.host, build_id: input.buildId }, ({ changed, cssChanged, hash, ignored }) => {
249
+ if (typeof changed !== "boolean" || typeof cssChanged !== "boolean" || hash !== null && typeof hash !== "string" || !Array.isArray(ignored)) return void 0;
250
+ return { changed, cssChanged, hash, ignored: ignored.map(String) };
251
+ });
252
+ }
169
253
 
170
254
  // src/next/paths.ts
171
255
  function normalizeBasePath(basePath) {
@@ -396,7 +480,7 @@ async function listPublicationPaths(options) {
396
480
 
397
481
  // src/check-routes-cli.ts
398
482
  var USAGE = `hyle-sdk-check-routes [--next-dir .next] [--base-url URL] [--json] [--print-reserved]
399
- [--sync [--strict] [--no-check] [--host ID] [--build-id ID] [--allow-empty] [--allow-non-production]]
483
+ [--sync [--theme] [--strict] [--no-check] [--host ID] [--build-id ID] [--allow-empty] [--allow-non-production]]
400
484
  [--locales en,fr,es --default-locale en --locale-prefix as-needed|always|never] [--hyle-param hyle]
401
485
 
402
486
  Run after \`next build\`. Reads the build's route manifests and hyle's read-only endpoints (mounts, and the published pages of each mount).
@@ -404,17 +488,20 @@ Credentials: HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN. The tok
404
488
  (a) hyle pages a host static route shadows, (b) host dynamic routes that match hyle URLs, (c) mounts that are host static routes.
405
489
  --print-reserved print the host's routes in hyle's "Reserved paths" format and exit.
406
490
  --sync report that list to hyle (ADR 0016) so nobody maintains it by hand, then run the check. Needs HYLE_CONTROL_TOKEN
407
- (a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write), read from the environment only.
491
+ (a hyle_tc_ control credential with hyle.workspace.sync_host; the read token cannot write), read from the environment only.
408
492
  A failed sync only warns, so it never fails a deploy, unless --strict (exit 3). Skipped on a non-production Vercel
409
493
  build (VERCEL_ENV) unless --allow-non-production. --no-check syncs without the collision check. The host id comes
410
494
  from --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL; the build id from <next-dir>/BUILD_ID or --build-id.
411
495
  An empty list is refused unless --allow-empty.
496
+ --theme with --sync: also send ./hyle.theme.json as the workspace's code theme (ADR 0036), with the same
497
+ credential and the same failure, preview and --strict rules. The file replaces the code theme.
412
498
  Exit: 0 no collision, 1 collision (a) or (c), 2 cannot run, 3 sync failed under --strict.`;
413
499
  var FLAGS = /* @__PURE__ */ new Set(["--next-dir", "--base-url", "--locales", "--default-locale", "--locale-prefix", "--hyle-param", "--host", "--build-id"]);
414
- var BOOLEAN = /* @__PURE__ */ new Set(["--json", "--print-reserved", "--help", "--sync", "--strict", "--no-check", "--allow-empty", "--allow-non-production"]);
500
+ var BOOLEAN = /* @__PURE__ */ new Set(["--json", "--print-reserved", "--help", "--sync", "--theme", "--strict", "--no-check", "--allow-empty", "--allow-non-production"]);
415
501
  var CANNOT_RUN = 2;
416
502
  var SYNC_FAILED = 3;
417
503
  var MAX_SYNCED_PATHS = 512;
504
+ var THEME_FILE = "hyle.theme.json";
418
505
  function parseArgs(argv) {
419
506
  const args = /* @__PURE__ */ new Map();
420
507
  for (let i = 0; i < argv.length; i++) {
@@ -427,35 +514,36 @@ function parseArgs(argv) {
427
514
  }
428
515
  var readJson = (file) => JSON.parse(readFileSync(file, "utf8"));
429
516
  var SAFE_ID = /[^A-Za-z0-9._-]/g;
430
- async function syncStep(args, io, ctx) {
431
- const fail = (reason) => (io.err(`sync: ${printable(reason)}`), { status: "failed", reason });
432
- const vercelEnv = io.env.VERCEL_ENV;
433
- if (vercelEnv !== void 0 && vercelEnv !== "production" && !args.has("--allow-non-production")) {
434
- io.err(`sync: skipped, this is a ${printable(vercelEnv)} build (a preview must not replace production's list; --allow-non-production overrides)`);
435
- return { status: "skipped" };
436
- }
437
- const { baseUrl, mounts } = ctx.plan;
517
+ function failed(io, step, reason) {
518
+ io.err(`${step}: ${printable(reason)}`);
519
+ return { status: "failed", reason };
520
+ }
521
+ var errorText = (error) => error instanceof Error ? `${error.name}: ${error.message}` : "unknown error";
522
+ function syncTarget(args, io, nextDir, { baseUrl, mounts, mountsError }) {
438
523
  const token = io.env.HYLE_CONTROL_TOKEN;
439
- if (!token) return fail("set HYLE_CONTROL_TOKEN (a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write)");
440
- if (!baseUrl || !mounts) return fail(ctx.plan.mountsError ?? "set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN so the workspace can be found");
524
+ if (!token) return "set HYLE_CONTROL_TOKEN (a hyle_tc_ control credential with hyle.workspace.sync_host; the read token cannot write)";
525
+ if (!baseUrl || !mounts) return mountsError ?? "set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN so the workspace can be found";
441
526
  const host = (args.get("--host") ?? io.env.HYLE_HOST_ID ?? io.env.VERCEL_PROJECT_PRODUCTION_URL)?.replace(SAFE_ID, "-").slice(0, 128);
442
- if (!host) return fail("name this host with --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL");
527
+ if (!host) return "name this host with --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL";
443
528
  let buildId = args.get("--build-id") ?? io.env.VERCEL_GIT_COMMIT_SHA;
444
529
  try {
445
- buildId = readFileSync(join(ctx.nextDir, "BUILD_ID"), "utf8").trim();
530
+ buildId = readFileSync(join(nextDir, "BUILD_ID"), "utf8").trim();
446
531
  } catch {
447
532
  }
448
533
  buildId = buildId?.replace(SAFE_ID, "-").slice(0, 128);
449
- if (!buildId) return fail("no build id: <next-dir>/BUILD_ID is missing; pass --build-id");
450
- const rootMount = mounts.prefixes.includes("/");
451
- const fromHost = reservedFor(ctx.hostRoutes, { ...ctx.locale ? { locale: ctx.locale } : {}, mounts: mounts.prefixes, hyleParam: ctx.hyleParam }).filter((p) => !(rootMount && p === "/"));
534
+ if (!buildId) return "no build id: <next-dir>/BUILD_ID is missing; pass --build-id";
535
+ return { baseUrl, token, workspaceId: mounts.workspaceId, host, buildId, ...io.fetch ? { fetch: io.fetch } : {} };
536
+ }
537
+ async function pathsStep(args, io, target, ctx) {
538
+ const rootMount = ctx.prefixes.includes("/");
539
+ const fromHost = reservedFor(ctx.hostRoutes, { ...ctx.locale ? { locale: ctx.locale } : {}, mounts: ctx.prefixes, hyleParam: ctx.hyleParam }).filter((p) => !(rootMount && p === "/"));
452
540
  const reserved = [.../* @__PURE__ */ new Set([...fromHost, ...SDK_OWN_RESERVED])].sort();
453
- if (fromHost.length === 0 && !args.has("--allow-empty")) return fail("the build has no reservable routes; refusing to replace hyle's list with an empty one (--allow-empty overrides)");
454
- if (reserved.length > MAX_SYNCED_PATHS) return fail(`${reserved.length} reserved paths exceed hyle's limit of ${MAX_SYNCED_PATHS}`);
541
+ if (fromHost.length === 0 && !args.has("--allow-empty")) return failed(io, "sync", "the build has no reservable routes; refusing to replace hyle's list with an empty one (--allow-empty overrides)");
542
+ if (reserved.length > MAX_SYNCED_PATHS) return failed(io, "sync", `${reserved.length} reserved paths exceed hyle's limit of ${MAX_SYNCED_PATHS}`);
455
543
  try {
456
- const result = await syncHostReserved({ baseUrl, token, workspaceId: mounts.workspaceId, paths: reserved, host, buildId, ...io.fetch ? { fetch: io.fetch } : {} });
544
+ const result = await syncHostReserved({ ...target, paths: reserved });
457
545
  if (!args.has("--json")) {
458
- io.out(`sync: ${result.paths.length} reserved paths ${result.changed ? "updated" : "unchanged"} in hyle (host ${printable(host)}, build ${printable(buildId)})`);
546
+ io.out(`sync: ${result.paths.length} reserved paths ${result.changed ? "updated" : "unchanged"} in hyle (host ${printable(target.host)}, build ${printable(target.buildId)})`);
459
547
  if (result.conflicts.total > 0) {
460
548
  io.out(`sync: ${result.conflicts.total} published hyle URL(s) are on paths this host owns (hyle unpublished nothing):`);
461
549
  for (const path of result.conflicts.offenders) io.out(` ${printable(path)}`);
@@ -463,13 +551,62 @@ async function syncStep(args, io, ctx) {
463
551
  }
464
552
  return { status: "ok", result };
465
553
  } catch (error) {
466
- return fail(error instanceof Error ? `${error.name}: ${error.message}` : "unknown error");
554
+ return failed(io, "sync", errorText(error));
555
+ }
556
+ }
557
+ function refusalLines(error) {
558
+ const details = error instanceof Cp1ClientError ? error.details : void 0;
559
+ if (details?.reason !== "theme_refused" || typeof details.keys !== "string") return void 0;
560
+ const messages = typeof details.messages === "string" ? details.messages.split("\n") : [];
561
+ return details.keys.split("\n").map((key, i) => ` ${printable(key) || "(the file)"}: ${printable(messages[i] ?? "not accepted")}`);
562
+ }
563
+ async function themeStep(args, io, target) {
564
+ const dir = io.cwd ?? process.cwd();
565
+ let text;
566
+ try {
567
+ text = readFileSync(join(dir, THEME_FILE), "utf8");
568
+ } catch {
569
+ return failed(io, "theme", `no ${THEME_FILE} in ${dir} (or it cannot be read); run this where the file is`);
570
+ }
571
+ let theme;
572
+ try {
573
+ theme = JSON.parse(text);
574
+ } catch (error) {
575
+ return failed(io, "theme", `${THEME_FILE} is not valid JSON: ${error instanceof Error ? error.message : "unknown error"}`);
576
+ }
577
+ try {
578
+ const result = await syncCodeTheme({ ...target, theme });
579
+ if (result.ignored.length > 0) io.err(`theme: hyle ignored unknown keys: ${printable(result.ignored.join(", "))}`);
580
+ if (!args.has("--json")) io.out(`theme: ${THEME_FILE} synced, the stylesheet ${result.cssChanged ? "changed" : "is unchanged"} (host ${printable(target.host)}, build ${printable(target.buildId)})`);
581
+ return { status: "ok", result };
582
+ } catch (error) {
583
+ const lines = refusalLines(error);
584
+ if (lines) {
585
+ const reason = `hyle refused ${THEME_FILE}, so the theme was not changed:`;
586
+ io.err([`theme: ${reason}`, ...lines].join("\n"));
587
+ return { status: "failed", reason: [reason, ...lines].join("\n") };
588
+ }
589
+ const hint = error instanceof Cp1ClientError && error.status === 404 ? " (does the credential hold hyle.workspace.sync_host on this workspace, and does this hyle have themes?)" : "";
590
+ return failed(io, "theme", `${errorText(error)}${hint}`);
591
+ }
592
+ }
593
+ async function syncSteps(args, io, ctx) {
594
+ const wantsTheme = args.has("--theme");
595
+ const vercelEnv = io.env.VERCEL_ENV;
596
+ if (vercelEnv !== void 0 && vercelEnv !== "production" && !args.has("--allow-non-production")) {
597
+ io.err(`sync: skipped, this is a ${printable(vercelEnv)} build (a preview must not replace what production synced; --allow-non-production overrides)`);
598
+ return { sync: { status: "skipped" }, ...wantsTheme ? { theme: { status: "skipped" } } : {} };
467
599
  }
600
+ const target = syncTarget(args, io, ctx.nextDir, ctx.plan);
601
+ if (typeof target === "string") return { sync: failed(io, "sync", target), ...wantsTheme ? { theme: failed(io, "theme", target) } : {} };
602
+ const sync = await pathsStep(args, io, target, ctx);
603
+ return { sync, ...wantsTheme ? { theme: await themeStep(args, io, target) } : {} };
468
604
  }
469
605
  async function runCli(argv, io) {
470
606
  try {
471
607
  const args = parseArgs(argv);
472
608
  if (args.has("--help")) return io.out(USAGE), 0;
609
+ if (args.has("--theme") && !args.has("--sync")) throw new Error("--theme needs --sync");
473
610
  const nextDir = args.get("--next-dir") ?? ".next";
474
611
  const hyleParam = args.get("--hyle-param") ?? "hyle";
475
612
  let locale;
@@ -511,12 +648,13 @@ async function runCli(argv, io) {
511
648
  }
512
649
  const prefixes = mounts?.mounts.map((m) => m.prefix);
513
650
  const strict = args.has("--strict");
514
- let sync;
651
+ let synced;
652
+ const exitAfterSync = () => strict && (synced?.sync.status === "failed" || synced?.theme?.status === "failed") ? SYNC_FAILED : 0;
515
653
  if (args.has("--sync")) {
516
- sync = await syncStep(args, io, { nextDir, hostRoutes, locale, hyleParam, plan: { baseUrl, mounts: mounts?.kind === "mounts" && prefixes ? { workspaceId: mounts.workspace_id, prefixes } : void 0, ...mountsError instanceof Error ? { mountsError: `${mountsError.name}: ${mountsError.message}` } : {} } });
654
+ synced = await syncSteps(args, io, { nextDir, hostRoutes, locale, hyleParam, prefixes: prefixes ?? [], plan: { baseUrl, mounts: mounts?.kind === "mounts" ? { workspaceId: mounts.workspace_id } : void 0, ...mountsError instanceof Error ? { mountsError: errorText(mountsError) } : {} } });
517
655
  if (args.has("--no-check")) {
518
- if (args.has("--json")) io.out(JSON.stringify({ sync }));
519
- return sync.status === "failed" && strict ? SYNC_FAILED : 0;
656
+ if (args.has("--json")) io.out(JSON.stringify(synced));
657
+ return exitAfterSync();
520
658
  }
521
659
  }
522
660
  if (args.has("--print-reserved")) {
@@ -542,9 +680,8 @@ async function runCli(argv, io) {
542
680
  }
543
681
  }
544
682
  const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths: [...hylePaths], hyleParam, ...locale ? { locale } : {} });
545
- io.out(args.has("--json") ? JSON.stringify(sync ? { ...report, sync } : report, null, 2) : formatReport(report));
546
- if (!report.ok) return 1;
547
- return sync?.status === "failed" && strict ? SYNC_FAILED : 0;
683
+ io.out(args.has("--json") ? JSON.stringify({ ...report, ...synced }, null, 2) : formatReport(report));
684
+ return report.ok ? exitAfterSync() : 1;
548
685
  } catch (error) {
549
686
  io.err(`CANNOT RUN: ${error instanceof Error ? printable(`${error.name}: ${error.message}`) : "unknown error"}`);
550
687
  return CANNOT_RUN;
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  createHyleClient,
3
3
  isValidCacheTag
4
- } from "./chunk-MGSUQBDW.js";
4
+ } from "./chunk-KU7LWK4E.js";
5
5
 
6
6
  // src/next/resolve.ts
7
- var DEFAULT_REVALIDATE = 300;
7
+ var DEFAULT_REVALIDATE = 86400;
8
8
  var MAX_TAGS = 64;
9
9
  function workspaceTags(workspaceId, sections = []) {
10
10
  const workspaceTag = `hyle:1:ws:${workspaceId}`;
@@ -0,0 +1,57 @@
1
+ // src/asset-path.ts
2
+ var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
3
+ var ASSET_RESERVED_PATH = "/api/hyle/*";
4
+ var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
5
+ var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg|woff2";
6
+ var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
7
+ var THEME_FILE = /^theme-([0-9a-f]{16})-([0-9a-f]{64})\.css$/;
8
+ var THEME_FONT = new RegExp(`^/assets/${UUID}\\.woff2$`);
9
+ function themeStylesheetHref({ scope, hash }) {
10
+ const file = `theme-${scope}-${hash}.css`;
11
+ return THEME_FILE.test(file) ? `${ASSET_ROUTE_PREFIX}/${file}` : void 0;
12
+ }
13
+ function themeFontHrefs(preload) {
14
+ return preload.flatMap((src) => typeof src === "string" && THEME_FONT.test(src) ? [hostAssetSrc(src)] : []);
15
+ }
16
+ var PREVIEW_TOKEN_SOURCE = "hyle_pv_[A-Za-z0-9_-]{43}";
17
+ var PREVIEW_TOKEN = new RegExp(`^${PREVIEW_TOKEN_SOURCE}$`);
18
+ var PREVIEW_HEADER = "cp-preview";
19
+ var PREVIEW_PARAM = "hyle_preview";
20
+ var PREVIEW_QUERY_SOURCE = `\\?${PREVIEW_PARAM}=${PREVIEW_TOKEN_SOURCE}`;
21
+ var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)(${PREVIEW_QUERY_SOURCE})?$`, "i");
22
+ function hostAssetSrc(src) {
23
+ const [, file, query = ""] = HYLE_ASSET_URL.exec(src) ?? [];
24
+ return file ? `${ASSET_ROUTE_PREFIX}/${file.toLowerCase()}${query}` : src;
25
+ }
26
+ function hostAssetHtml(html) {
27
+ return html.replace(new RegExp(`(\\ssrc=")(/assets/${UUID}(?:\\.(?:${EXTENSIONS}))?)(")`, "gi"), (_m, open, url, close) => `${open}${hostAssetSrc(url)}${close}`);
28
+ }
29
+ var ASSET_CONTENT_TYPES = /* @__PURE__ */ new Set([
30
+ "image/png",
31
+ "image/jpeg",
32
+ "image/gif",
33
+ "image/webp",
34
+ "image/svg+xml",
35
+ "application/pdf",
36
+ "video/mp4",
37
+ "video/webm",
38
+ "audio/mpeg",
39
+ "audio/ogg",
40
+ "font/woff2"
41
+ ]);
42
+
43
+ export {
44
+ ASSET_ROUTE_PREFIX,
45
+ ASSET_RESERVED_PATH,
46
+ ASSET_FILE,
47
+ THEME_FILE,
48
+ themeStylesheetHref,
49
+ themeFontHrefs,
50
+ PREVIEW_TOKEN,
51
+ PREVIEW_HEADER,
52
+ PREVIEW_PARAM,
53
+ PREVIEW_QUERY_SOURCE,
54
+ hostAssetSrc,
55
+ hostAssetHtml,
56
+ ASSET_CONTENT_TYPES
57
+ };