saturndocs 0.1.2 → 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.
Files changed (50) hide show
  1. package/dist/{auth-FRCFGNYT.js → auth-DUYYFNEZ.js} +4 -4
  2. package/dist/{brokenLinks-TTOBP4P7.js → brokenLinks-E364XYH3.js} +1 -1
  3. package/dist/{chunk-SABK3R2P.js → chunk-2RZEC3VH.js} +132 -136
  4. package/dist/{chunk-KGJESHJC.js → chunk-2YTD2XNI.js} +1 -1
  5. package/dist/{chunk-QLFODLVN.js → chunk-4J33CCAC.js} +18 -15
  6. package/dist/{chunk-STCCGFKC.js → chunk-4ORVQCHY.js} +1 -1
  7. package/dist/chunk-56U46JVN.js +28 -0
  8. package/dist/chunk-6JGAA5TF.js +86 -0
  9. package/dist/{chunk-GYRVGWDM.js → chunk-ADZOBRZE.js} +88 -6
  10. package/dist/chunk-D3CLXV7D.js +131 -0
  11. package/dist/{chunk-5KX4ZK5E.js → chunk-DBMFJXKP.js} +11 -5
  12. package/dist/chunk-EB7RWFQA.js +3821 -0
  13. package/dist/{chunk-R3X2DPFF.js → chunk-FGKHDJOC.js} +133 -4
  14. package/dist/{chunk-3V753MRI.js → chunk-GGGL4O7Z.js} +2 -2
  15. package/dist/{chunk-OZWTXMO3.js → chunk-GLI3OUYL.js} +57 -4
  16. package/dist/{chunk-3P2OFTXR.js → chunk-K5YY6NSF.js} +2 -2
  17. package/dist/{chunk-TKISMN3P.js → chunk-KOJJUISB.js} +2 -2
  18. package/dist/chunk-O72DR5FK.js +152 -0
  19. package/dist/{chunk-U7PKMSB3.js → chunk-QF2ADHQZ.js} +4 -4
  20. package/dist/{chunk-S45UWCML.js → chunk-SVDVBZPA.js} +9 -9
  21. package/dist/{chunk-CMNX5DLQ.js → chunk-W3GKH5DY.js} +2 -2
  22. package/dist/{chunk-N7QPZMLP.js → chunk-WBI4EI3D.js} +1 -1
  23. package/dist/{chunk-OEAEX5YW.js → chunk-WHNL6UYJ.js} +8 -2
  24. package/dist/chunk-WUPP3THV.js +87 -0
  25. package/dist/chunk-YSFP37B7.js +76 -0
  26. package/dist/{chunk-XO4CUC7V.js → chunk-Z5CBPJ2L.js} +3 -3
  27. package/dist/cli.js +3 -3
  28. package/dist/coverage-EBWULNQQ.js +15 -0
  29. package/dist/deploy-QUVLOGII.js +13 -0
  30. package/dist/dist-XISZDQTR.js +120 -0
  31. package/dist/index.d.ts +35 -2
  32. package/dist/index.js +66 -38
  33. package/dist/{init-7T5TEPBH.js → init-PI4VTG7V.js} +2 -2
  34. package/dist/lint-SXBP37G3.js +13 -0
  35. package/dist/{manage-MKH27U3B.js → manage-OB6DQK3Q.js} +2 -2
  36. package/dist/nav-R4OORY2G.js +14 -0
  37. package/dist/{openapiCheck-KGBQJTIQ.js → openapiCheck-X2QQGETY.js} +6 -6
  38. package/dist/{pages-HIPXRLSY.js → pages-MKFZAVGI.js} +5 -5
  39. package/dist/{read-DMSJUEDA.js → read-VECMKHBW.js} +4 -4
  40. package/dist/{read-ZEVUZNNB.js → read-WWOMA67R.js} +4 -4
  41. package/dist/requests-A7WC3B4M.js +13 -0
  42. package/dist/{schema-XJUEZSIW.js → schema-NKOXZHQH.js} +3 -3
  43. package/dist/{sites-I4WI2MPG.js → sites-XMMGWPY2.js} +4 -4
  44. package/dist/{status-7R3NOI5H.js → status-SYIUUSSU.js} +4 -4
  45. package/dist/{suggestions-4WFQ3APX.js → suggestions-GX5CQK26.js} +4 -4
  46. package/dist/{validate-VXL4PL42.js → validate-D4I3DY2W.js} +5 -3
  47. package/package.json +6 -5
  48. package/dist/chunk-I6U4V7B4.js +0 -1552
  49. package/dist/deploy-QU7DCKWU.js +0 -11
  50. package/dist/requests-H5MIGBIS.js +0 -13
@@ -0,0 +1,3821 @@
1
+ import {
2
+ parseOpenApi
3
+ } from "./chunk-SVDVBZPA.js";
4
+ import {
5
+ BuildRuleError,
6
+ assertGroupCapacity,
7
+ knownGroups,
8
+ navigationGroups,
9
+ normalizedRedirectPath,
10
+ openApiPublicationCollision,
11
+ parseDocsConfig,
12
+ parseModelsConfig,
13
+ reservedPageClash,
14
+ resolveRootRedirectDestination,
15
+ themeCssProblems,
16
+ ungatedOpenApiSpecPaths
17
+ } from "./chunk-FGKHDJOC.js";
18
+
19
+ // ../ui-tokens/dist/index.js
20
+ import {
21
+ converter,
22
+ formatCss,
23
+ formatHex,
24
+ clampChroma,
25
+ parse,
26
+ wcagContrast
27
+ } from "culori";
28
+ var toOklab = converter("oklab");
29
+ var ThemeError = class extends Error {
30
+ problems;
31
+ constructor(problems) {
32
+ super(`Invalid theme:
33
+ ${problems.map((problem) => ` - ${problem}`).join("\n")}`);
34
+ this.name = "ThemeError";
35
+ this.problems = [...problems];
36
+ }
37
+ };
38
+ var RAMP_STEPS = [
39
+ "50",
40
+ "100",
41
+ "200",
42
+ "300",
43
+ "400",
44
+ "500",
45
+ "600",
46
+ "700",
47
+ "800",
48
+ "900",
49
+ "950"
50
+ ];
51
+ var LIGHTNESS = {
52
+ "50": 0.971,
53
+ "100": 0.936,
54
+ "200": 0.885,
55
+ "300": 0.808,
56
+ "400": 0.716,
57
+ "500": 0.637,
58
+ "600": 0.564,
59
+ "700": 0.487,
60
+ "800": 0.41,
61
+ "900": 0.343,
62
+ "950": 0.256
63
+ };
64
+ var CHROMA_ENVELOPE = {
65
+ "50": 0.09,
66
+ "100": 0.16,
67
+ "200": 0.32,
68
+ "300": 0.52,
69
+ "400": 0.78,
70
+ "500": 1,
71
+ "600": 0.97,
72
+ "700": 0.86,
73
+ "800": 0.72,
74
+ "900": 0.58,
75
+ "950": 0.45
76
+ };
77
+ var GRAY_CHROMA = {
78
+ "50": 4e-3,
79
+ "100": 5e-3,
80
+ "200": 6e-3,
81
+ "300": 7e-3,
82
+ "400": 8e-3,
83
+ "500": 9e-3,
84
+ "600": 0.01,
85
+ "700": 0.011,
86
+ "800": 0.012,
87
+ "900": 0.013,
88
+ "950": 0.014
89
+ };
90
+ var toOklch = converter("oklch");
91
+ var THEME_PRESETS = ["default", "minimal", "soft", "bold"];
92
+ var RADIUS_SCALES = ["none", "small", "medium", "large"];
93
+ var ACCENT_STRENGTHS = ["subtle", "medium", "strong"];
94
+ function round(n, places) {
95
+ const f = 10 ** places;
96
+ return Math.round(n * f) / f;
97
+ }
98
+ function oklchString(l, c, h) {
99
+ const raw = { mode: "oklch", l, c, h };
100
+ const inGamut = clampChroma(raw, "oklch", "rgb");
101
+ const rounded = {
102
+ mode: "oklch",
103
+ l: round(inGamut.l, 4),
104
+ c: round(inGamut.c, 4),
105
+ h: round(inGamut.h ?? 0, 2)
106
+ };
107
+ return formatCss(rounded);
108
+ }
109
+ function parseInput(input) {
110
+ const parsed = toOklch(input);
111
+ if (!parsed) {
112
+ throw new Error(
113
+ `deriveTokens: could not parse color input ${JSON.stringify(input)}`
114
+ );
115
+ }
116
+ return parsed;
117
+ }
118
+ function deriveTokens(primary, options = {}) {
119
+ const base = parseInput(primary);
120
+ const hue = base.h ?? 0;
121
+ const presetName = includes(THEME_PRESETS, options.theme) ? options.theme : "default";
122
+ const chromaMax = PRESET_DEFAULTS[presetName].chromaMax;
123
+ const inputChroma = base.c;
124
+ const peakChroma = inputChroma <= 1e-3 ? 0 : Math.min(Math.max(inputChroma, 0.11), chromaMax);
125
+ const primaryRamp = {};
126
+ const grayRamp = {};
127
+ for (const step of RAMP_STEPS) {
128
+ const l = LIGHTNESS[step];
129
+ primaryRamp[step] = oklchString(l, peakChroma * CHROMA_ENVELOPE[step], hue);
130
+ grayRamp[step] = oklchString(
131
+ l,
132
+ peakChroma === 0 ? 0 : GRAY_CHROMA[step],
133
+ hue
134
+ );
135
+ }
136
+ return { primary: primaryRamp, gray: grayRamp };
137
+ }
138
+ function contrastColor(bg) {
139
+ const white = "#ffffff";
140
+ const near = "#0b0b0d";
141
+ return wcagContrast(bg, white) >= wcagContrast(bg, near) ? white : near;
142
+ }
143
+ function cssBlock(selector, lines) {
144
+ const body = lines.map((l) => ` ${l}`).join("\n");
145
+ return `${selector} {
146
+ ${body}
147
+ }`;
148
+ }
149
+ function themeBlock(theme, lines) {
150
+ return cssBlock(`[data-theme='${theme}']`, lines);
151
+ }
152
+ function presetThemeBlock(preset, theme, lines) {
153
+ return cssBlock(`[data-gs-preset='${preset}'][data-theme='${theme}']`, lines);
154
+ }
155
+ var CALLOUT_HUES = {
156
+ info: { h: 252, c: 0.15 },
157
+ tip: { h: 150, c: 0.15 },
158
+ warning: { h: 74, c: 0.15 },
159
+ check: { h: 195, c: 0.12 },
160
+ danger: { h: 27, c: 0.16 }
161
+ };
162
+ var PRESET_DEFAULTS = {
163
+ default: {
164
+ theme: "default",
165
+ radius: "medium",
166
+ accentStrength: "medium",
167
+ shadow: "soft",
168
+ surfaceTintLight: 0,
169
+ surfaceTintDark: 0,
170
+ heroGlowLight: 3,
171
+ heroGlowDark: 5,
172
+ chromaMax: 0.18
173
+ },
174
+ minimal: {
175
+ theme: "minimal",
176
+ radius: "small",
177
+ accentStrength: "subtle",
178
+ shadow: "none",
179
+ surfaceTintLight: 0,
180
+ surfaceTintDark: 0,
181
+ heroGlowLight: 2,
182
+ heroGlowDark: 3,
183
+ chromaMax: 0.18
184
+ },
185
+ soft: {
186
+ theme: "soft",
187
+ radius: "large",
188
+ accentStrength: "medium",
189
+ shadow: "soft-large",
190
+ surfaceTintLight: 2,
191
+ surfaceTintDark: 4,
192
+ heroGlowLight: 4,
193
+ heroGlowDark: 6,
194
+ chromaMax: 0.18
195
+ },
196
+ bold: {
197
+ theme: "bold",
198
+ radius: "medium",
199
+ accentStrength: "strong",
200
+ shadow: "strong",
201
+ surfaceTintLight: 3,
202
+ surfaceTintDark: 6,
203
+ heroGlowLight: 6,
204
+ heroGlowDark: 8,
205
+ chromaMax: 0.2
206
+ }
207
+ };
208
+ var RADIUS_VALUES = {
209
+ none: { sm: "0px", md: "0px", lg: "0px", xl: "0px" },
210
+ small: { sm: "2px", md: "4px", lg: "6px", xl: "8px" },
211
+ medium: { sm: "6px", md: "10px", lg: "14px", xl: "20px" },
212
+ large: { sm: "10px", md: "14px", lg: "20px", xl: "28px" }
213
+ };
214
+ function includes(values, value) {
215
+ return typeof value === "string" && values.includes(value);
216
+ }
217
+ function resolvePreset(options) {
218
+ const name = includes(THEME_PRESETS, options.theme) ? options.theme : "default";
219
+ const base = PRESET_DEFAULTS[name];
220
+ return {
221
+ ...base,
222
+ radius: includes(RADIUS_SCALES, options.styling?.radius) ? options.styling.radius : base.radius,
223
+ accentStrength: includes(ACCENT_STRENGTHS, options.styling?.accentStrength) ? options.styling.accentStrength : base.accentStrength
224
+ };
225
+ }
226
+ function cssInputColor(input, fallback) {
227
+ if (input === void 0) return fallback;
228
+ const parsed = parseInput(input);
229
+ return formatCss(clampChroma(parsed, "oklch", "rgb"));
230
+ }
231
+ function seededLinkColor(input, fallback, mode, chromaMax) {
232
+ if (input === void 0) return fallback;
233
+ const parsed = parseInput(input);
234
+ const step = mode === "light" ? "700" : "300";
235
+ const lightness = mode === "light" ? Math.min(parsed.l, LIGHTNESS[step]) : Math.max(parsed.l, LIGHTNESS[step]);
236
+ const chroma = Math.min(parsed.c, chromaMax) * CHROMA_ENVELOPE[step];
237
+ return oklchString(lightness, chroma, parsed.h ?? 0);
238
+ }
239
+ function mix(color, amount, base) {
240
+ if (amount <= 0) return base;
241
+ return `color-mix(in oklab, ${color} ${amount}%, ${base})`;
242
+ }
243
+ function radiusScaleVars(scale) {
244
+ const r = RADIUS_VALUES[scale];
245
+ return [
246
+ `--gs-radius-sm: ${r.sm};`,
247
+ `--gs-radius: ${r.md};`,
248
+ `--gs-radius-lg: ${r.lg};`,
249
+ `--gs-radius-xl: ${r.xl};`
250
+ ];
251
+ }
252
+ function radiusVars(scale) {
253
+ return [
254
+ ...radiusScaleVars(scale),
255
+ `--gs-radius-full: 9999px;`
256
+ ];
257
+ }
258
+ function shadowVars(mode, shadow) {
259
+ if (shadow === "none") {
260
+ return [
261
+ `--gs-shadow-card: none;`,
262
+ `--gs-shadow-card-hover: none;`,
263
+ `--gs-shadow-overlay: none;`
264
+ ];
265
+ }
266
+ if (mode === "dark") {
267
+ const values = shadow === "soft" ? {
268
+ card: "0 1px 2px rgb(0 0 0 / 0.5), 0 8px 24px rgb(0 0 0 / 0.35)",
269
+ hover: "0 2px 4px rgb(0 0 0 / 0.55), 0 12px 32px rgb(0 0 0 / 0.4)",
270
+ overlay: "0 8px 24px rgb(0 0 0 / 0.5), 0 32px 72px rgb(0 0 0 / 0.45)"
271
+ } : shadow === "soft-large" ? {
272
+ card: "0 2px 4px rgb(0 0 0 / 0.5), 0 12px 32px rgb(0 0 0 / 0.38)",
273
+ hover: "0 3px 6px rgb(0 0 0 / 0.55), 0 18px 42px rgb(0 0 0 / 0.42)",
274
+ overlay: "0 10px 28px rgb(0 0 0 / 0.52), 0 40px 88px rgb(0 0 0 / 0.48)"
275
+ } : {
276
+ card: "0 2px 5px rgb(0 0 0 / 0.58), 0 16px 38px rgb(0 0 0 / 0.44)",
277
+ hover: "0 4px 8px rgb(0 0 0 / 0.62), 0 22px 52px rgb(0 0 0 / 0.5)",
278
+ overlay: "0 12px 32px rgb(0 0 0 / 0.6), 0 48px 96px rgb(0 0 0 / 0.54)"
279
+ };
280
+ return [
281
+ `--gs-shadow-card: ${values.card};`,
282
+ `--gs-shadow-card-hover: ${values.hover};`,
283
+ `--gs-shadow-overlay: ${values.overlay};`
284
+ ];
285
+ }
286
+ return [
287
+ `--gs-shadow-card: 0 1px 2px rgb(0 0 0 / 0.04), 0 4px 12px -2px rgb(0 0 0 / 0.06);`,
288
+ `--gs-shadow-card-hover: var(--gs-shadow-card);`,
289
+ `--gs-shadow-overlay: 0 4px 12px rgb(0 0 0 / 0.06), 0 24px 48px -12px rgb(0 0 0 / 0.18);`
290
+ ];
291
+ }
292
+ function chromePresetValues(mode, preset, primary, primaryRamp, primaryContrast, surfaceRaised, border, text) {
293
+ const tint = preset.accentStrength === "subtle" ? 7 : preset.accentStrength === "medium" ? 12 : 100;
294
+ const activeText = mode === "light" ? primaryRamp["700"] : primaryRamp["300"];
295
+ const headerBorderWidth = preset.accentStrength === "strong" ? "2px" : "1px";
296
+ return {
297
+ accentStrength: `${tint}%`,
298
+ headerBorder: preset.accentStrength === "strong" ? primary : border,
299
+ headerBorderWidth,
300
+ navActiveBg: "transparent",
301
+ navActiveText: activeText,
302
+ searchBg: mix(text, mode === "light" ? 2 : 4, surfaceRaised),
303
+ searchKbdBg: mix(text, mode === "light" ? 5 : 9, surfaceRaised),
304
+ buttonSecondaryBg: mix(text, mode === "light" ? 2 : 4, surfaceRaised)
305
+ };
306
+ }
307
+ function chromePresetVars(mode, preset, primary, primaryRamp, primaryContrast, surfaceRaised, border, text) {
308
+ const v = chromePresetValues(
309
+ mode,
310
+ preset,
311
+ primary,
312
+ primaryRamp,
313
+ primaryContrast,
314
+ surfaceRaised,
315
+ border,
316
+ text
317
+ );
318
+ return [
319
+ `--gs-accent-strength: ${v.accentStrength};`,
320
+ `--gs-header-border: ${v.headerBorder};`,
321
+ `--gs-header-border-width: ${v.headerBorderWidth};`,
322
+ `--gs-nav-active-bg: ${v.navActiveBg};`,
323
+ `--gs-nav-active-text: ${v.navActiveText};`,
324
+ `--gs-search-bg: ${v.searchBg};`,
325
+ `--gs-search-kbd-bg: ${v.searchKbdBg};`,
326
+ `--gs-button-secondary-bg: ${v.buttonSecondaryBg};`
327
+ ];
328
+ }
329
+ function chromeStableVars(mode, primary, primaryRamp, surface, border, text, secondary, faint) {
330
+ const hoverAmount = mode === "light" ? 5 : 8;
331
+ const branded = mode === "light" ? primaryRamp["700"] : primaryRamp["300"];
332
+ return [
333
+ `--gs-header-bg: color-mix(in oklab, ${surface} 78%, transparent);`,
334
+ `--gs-sidebar-bg: ${mix(primary, mode === "light" ? 1 : 2, surface)};`,
335
+ `--gs-nav-hover-bg: ${mix(text, hoverAmount, "transparent")};`,
336
+ `--gs-nav-hover-text: ${text};`,
337
+ `--gs-nav-active-border: transparent;`,
338
+ `--gs-search-border: ${border};`,
339
+ `--gs-search-text: ${secondary};`,
340
+ `--gs-toc-active: ${branded};`,
341
+ `--gs-toc-text: ${faint};`,
342
+ `--gs-focus-ring: ${primary};`,
343
+ `--gs-button-primary-bg: ${branded};`,
344
+ `--gs-button-primary-text: ${contrastColor(branded)};`,
345
+ `--gs-button-secondary-text: ${text};`
346
+ ];
347
+ }
348
+ function methodVars(mode) {
349
+ const colors = mode === "light" ? {
350
+ get: normalizedColor("#15803d"),
351
+ post: normalizedColor("#2563eb"),
352
+ put: normalizedColor("#b45309"),
353
+ patch: normalizedColor("#b45309"),
354
+ delete: normalizedColor("#c52222"),
355
+ other: "#57606a"
356
+ } : {
357
+ get: normalizedColor("#22c55e"),
358
+ post: normalizedColor("#60a5fa"),
359
+ put: normalizedColor("#fbbf24"),
360
+ patch: normalizedColor("#fbbf24"),
361
+ delete: normalizedColor("#f87171"),
362
+ other: "#9ca3af"
363
+ };
364
+ const vars = Object.entries(colors).flatMap(([method, color]) => [
365
+ `--gs-method-${method}: ${color};`,
366
+ ...["get", "post", "put", "patch", "delete"].includes(method) ? [`--gs-method-${method}-bg: ${mix(color, 12, "transparent")};`] : [],
367
+ `--gs-method-${method}-contrast: ${contrastColor(color)};`
368
+ ]);
369
+ for (const alias of ["head", "options", "trace"]) {
370
+ vars.push(`--gs-method-${alias}: ${colors.other};`);
371
+ vars.push(`--gs-method-${alias}-contrast: ${contrastColor(colors.other)};`);
372
+ }
373
+ return vars;
374
+ }
375
+ function tokensToCss(tokens, options = {}) {
376
+ const p = tokens.primary;
377
+ const g = tokens.gray;
378
+ const preset = resolvePreset(options);
379
+ const hue = toOklch(p["500"])?.h ?? 0;
380
+ const darkBg = oklchString(0.17, 9e-3, hue);
381
+ const darkSurfaceUi = oklchString(0.21, 9e-3, hue);
382
+ const darkRaised = oklchString(0.225, 0.013, hue);
383
+ const darkOverlay = oklchString(0.26, 0.014, hue);
384
+ const darkBorder = oklchString(0.33, 0.012, hue);
385
+ const lightCodeBg = oklchString(0.985, 3e-3, hue);
386
+ const lightCodeTitleBg = oklchString(0.966, 4e-3, hue);
387
+ const darkCodeBg = oklchString(0.195, 0.011, hue);
388
+ const apiPanelKey = oklchString(0.78, 0.11, 255);
389
+ const lightApiPanelString = normalizedColor("#f6ad55");
390
+ const darkApiPanelString = normalizedColor("#fdba74");
391
+ const apiPanelNumber = oklchString(0.82, 0.13, 75);
392
+ const apiPanelPunctuation = oklchString(0.76, 0.08, 300);
393
+ const rampVars = (ramp) => RAMP_STEPS.map((s) => `--gs-primary-${s}: ${ramp[s]};`);
394
+ const calloutVars = (mode) => {
395
+ const noteHue = CALLOUT_HUES.info;
396
+ const out = mode === "light" ? [
397
+ `--gs-callout-note: ${g["500"]};`,
398
+ `--gs-callout-note-surface: ${g["100"]};`,
399
+ `--gs-callout-note-link: ${oklchString(0.45, noteHue.c, noteHue.h)};`
400
+ ] : [
401
+ `--gs-callout-note: ${g["400"]};`,
402
+ `--gs-callout-note-surface: ${oklchString(0.21, 6e-3, hue)};`,
403
+ `--gs-callout-note-link: ${oklchString(0.82, noteHue.c, noteHue.h)};`
404
+ ];
405
+ for (const [name, { h, c }] of Object.entries(CALLOUT_HUES)) {
406
+ if (mode === "light") {
407
+ out.push(`--gs-callout-${name}: ${oklchString(0.55, c, h)};`);
408
+ out.push(`--gs-callout-${name}-surface: ${oklchString(0.966, c * 0.5, h)};`);
409
+ out.push(`--gs-callout-${name}-link: ${oklchString(0.45, c, h)};`);
410
+ } else {
411
+ out.push(`--gs-callout-${name}: ${oklchString(0.72, c, h)};`);
412
+ out.push(`--gs-callout-${name}-surface: ${oklchString(0.225, c * 0.35, h)};`);
413
+ out.push(`--gs-callout-${name}-link: ${oklchString(0.82, c, h)};`);
414
+ }
415
+ }
416
+ return out;
417
+ };
418
+ const lightPrimary = cssInputColor(options.colors?.light, p["600"]);
419
+ const lightLink = seededLinkColor(options.colors?.light, p["700"], "light", preset.chromaMax);
420
+ const lightSurface = g["50"];
421
+ const lightBorder = g["200"];
422
+ const lightText = g["900"];
423
+ const lightSecondary = g["600"];
424
+ const lightFaint = g["500"];
425
+ const lightPrimaryContrast = contrastColor(lightPrimary);
426
+ const successLight = "#15803d";
427
+ const dangerLight = "#b42318";
428
+ const lightPresetVars = (currentPreset, includeRadiusFull = false) => {
429
+ const raised = mix(p["500"], currentPreset.surfaceTintLight, "#ffffff");
430
+ const overlay = mix(p["500"], Math.max(0, currentPreset.surfaceTintLight - 1), "#ffffff");
431
+ return [
432
+ ...includeRadiusFull ? radiusVars(currentPreset.radius) : radiusScaleVars(currentPreset.radius),
433
+ ...shadowVars("light", currentPreset.shadow),
434
+ `--gs-surface-raised: ${raised};`,
435
+ `--gs-surface-overlay: ${overlay};`,
436
+ ...chromePresetVars(
437
+ "light",
438
+ currentPreset,
439
+ lightPrimary,
440
+ p,
441
+ lightPrimaryContrast,
442
+ raised,
443
+ lightBorder,
444
+ lightText
445
+ ),
446
+ `--gs-hero-glow: radial-gradient(circle at 50% 12%, ${mix(p["500"], currentPreset.heroGlowLight, "transparent")} 0, transparent 58%);`
447
+ ];
448
+ };
449
+ const light = [
450
+ ...rampVars(p),
451
+ ...lightPresetVars(preset, true),
452
+ `--gs-font-display: var(--gs-font-display-custom, var(--gs-font-heading, var(--gs-font-sans)));`,
453
+ `--gs-color-primary: ${lightPrimary};`,
454
+ `--gs-color-primary-contrast: ${lightPrimaryContrast};`,
455
+ // A darker ramp step for links/accent text so inline links clear WCAG AA on
456
+ // the light surface (the accent fill color itself does not).
457
+ `--gs-color-link: ${lightLink};`,
458
+ `--gs-color-success: ${successLight};`,
459
+ `--gs-color-success-contrast: ${contrastColor(successLight)};`,
460
+ `--gs-surface: ${lightSurface};`,
461
+ `--gs-surface-ui: ${lightSurface};`,
462
+ `--gs-border: ${lightBorder};`,
463
+ `--gs-text: ${lightText};`,
464
+ `--gs-text-secondary: ${lightSecondary};`,
465
+ `--gs-text-muted: ${lightSecondary};`,
466
+ `--gs-text-faint: ${lightFaint};`,
467
+ `--gs-color-danger: ${dangerLight};`,
468
+ `--gs-color-danger-contrast: ${contrastColor(dangerLight)};`,
469
+ `--gs-code-bg: ${lightCodeBg};`,
470
+ `--gs-code-title-bg: ${lightCodeTitleBg};`,
471
+ `--gs-api-panel-bg: ${darkCodeBg};`,
472
+ `--gs-api-panel-border: ${darkBorder};`,
473
+ `--gs-api-panel-text: ${g["50"]};`,
474
+ `--gs-api-panel-muted: ${g["400"]};`,
475
+ `--gs-api-panel-key: ${apiPanelKey};`,
476
+ `--gs-api-panel-string: ${lightApiPanelString};`,
477
+ `--gs-api-panel-number: ${apiPanelNumber};`,
478
+ `--gs-api-panel-punctuation: ${apiPanelPunctuation};`,
479
+ ...chromeStableVars(
480
+ "light",
481
+ lightPrimary,
482
+ p,
483
+ lightSurface,
484
+ lightBorder,
485
+ lightText,
486
+ lightSecondary,
487
+ lightFaint
488
+ ),
489
+ ...methodVars("light"),
490
+ ...calloutVars("light")
491
+ ];
492
+ const darkPrimary = cssInputColor(options.colors?.dark, p["400"]);
493
+ const darkLink = seededLinkColor(options.colors?.dark, p["300"], "dark", preset.chromaMax);
494
+ const darkSurface = darkBg;
495
+ const darkText = g["50"];
496
+ const darkSecondary = g["400"];
497
+ const darkFaint = g["500"];
498
+ const darkPrimaryContrast = contrastColor(darkPrimary);
499
+ const successDark = "#22c55e";
500
+ const dangerDark = "#f28b82";
501
+ const darkPresetVars = (currentPreset, includeRadiusFull = false) => {
502
+ const raised = mix(p["500"], currentPreset.surfaceTintDark, darkRaised);
503
+ const overlay = mix(p["500"], Math.max(0, currentPreset.surfaceTintDark - 1), darkOverlay);
504
+ return [
505
+ ...includeRadiusFull ? radiusVars(currentPreset.radius) : radiusScaleVars(currentPreset.radius),
506
+ ...shadowVars("dark", currentPreset.shadow),
507
+ `--gs-surface-raised: ${raised};`,
508
+ `--gs-surface-overlay: ${overlay};`,
509
+ ...chromePresetVars(
510
+ "dark",
511
+ currentPreset,
512
+ darkPrimary,
513
+ p,
514
+ darkPrimaryContrast,
515
+ raised,
516
+ darkBorder,
517
+ darkText
518
+ ),
519
+ `--gs-hero-glow: radial-gradient(circle at 50% 12%, ${mix(p["500"], currentPreset.heroGlowDark, "transparent")} 0, transparent 60%);`
520
+ ];
521
+ };
522
+ const dark = [
523
+ ...rampVars(p),
524
+ ...darkPresetVars(preset, true),
525
+ `--gs-font-display: var(--gs-font-display-custom, var(--gs-font-heading, var(--gs-font-sans)));`,
526
+ `--gs-color-primary: ${darkPrimary};`,
527
+ `--gs-color-primary-contrast: ${darkPrimaryContrast};`,
528
+ `--gs-color-link: ${darkLink};`,
529
+ `--gs-color-success: ${successDark};`,
530
+ `--gs-color-success-contrast: ${contrastColor(successDark)};`,
531
+ `--gs-surface: ${darkSurface};`,
532
+ `--gs-surface-ui: ${darkSurfaceUi};`,
533
+ `--gs-border: ${darkBorder};`,
534
+ `--gs-text: ${darkText};`,
535
+ `--gs-text-secondary: ${darkSecondary};`,
536
+ `--gs-text-muted: ${darkSecondary};`,
537
+ `--gs-text-faint: ${darkFaint};`,
538
+ `--gs-color-danger: ${dangerDark};`,
539
+ `--gs-color-danger-contrast: ${contrastColor(dangerDark)};`,
540
+ `--gs-code-bg: ${darkCodeBg};`,
541
+ `--gs-code-title-bg: ${darkRaised};`,
542
+ `--gs-api-panel-bg: ${darkCodeBg};`,
543
+ `--gs-api-panel-border: ${darkBorder};`,
544
+ `--gs-api-panel-text: ${g["50"]};`,
545
+ `--gs-api-panel-muted: ${g["400"]};`,
546
+ `--gs-api-panel-key: ${apiPanelKey};`,
547
+ `--gs-api-panel-string: ${darkApiPanelString};`,
548
+ `--gs-api-panel-number: ${apiPanelNumber};`,
549
+ `--gs-api-panel-punctuation: ${apiPanelPunctuation};`,
550
+ ...chromeStableVars(
551
+ "dark",
552
+ darkPrimary,
553
+ p,
554
+ darkSurface,
555
+ darkBorder,
556
+ darkText,
557
+ darkSecondary,
558
+ darkFaint
559
+ ),
560
+ ...methodVars("dark"),
561
+ ...calloutVars("dark")
562
+ ];
563
+ const presetBlocks = THEME_PRESETS.flatMap((presetName) => {
564
+ const resolved = resolvePreset({ ...options, theme: presetName });
565
+ return [
566
+ presetThemeBlock(presetName, "light", lightPresetVars(resolved)),
567
+ presetThemeBlock(presetName, "dark", darkPresetVars(resolved))
568
+ ];
569
+ });
570
+ return `${[
571
+ themeBlock("light", light),
572
+ themeBlock("dark", dark),
573
+ ...presetBlocks
574
+ ].join("\n\n")}
575
+ `;
576
+ }
577
+ var TOKEN_NAMES = Object.freeze([
578
+ "gs-accent-strength",
579
+ "gs-api-panel-bg",
580
+ "gs-api-panel-border",
581
+ "gs-api-panel-key",
582
+ "gs-api-panel-muted",
583
+ "gs-api-panel-number",
584
+ "gs-api-panel-punctuation",
585
+ "gs-api-panel-string",
586
+ "gs-api-panel-text",
587
+ "gs-border",
588
+ "gs-button-primary-bg",
589
+ "gs-button-primary-text",
590
+ "gs-button-secondary-bg",
591
+ "gs-button-secondary-text",
592
+ "gs-callout-check",
593
+ "gs-callout-check-link",
594
+ "gs-callout-check-surface",
595
+ "gs-callout-danger",
596
+ "gs-callout-danger-link",
597
+ "gs-callout-danger-surface",
598
+ "gs-callout-info",
599
+ "gs-callout-info-link",
600
+ "gs-callout-info-surface",
601
+ "gs-callout-note",
602
+ "gs-callout-note-link",
603
+ "gs-callout-note-surface",
604
+ "gs-callout-tip",
605
+ "gs-callout-tip-link",
606
+ "gs-callout-tip-surface",
607
+ "gs-callout-warning",
608
+ "gs-callout-warning-link",
609
+ "gs-callout-warning-surface",
610
+ "gs-code-bg",
611
+ "gs-code-title-bg",
612
+ "gs-color-danger",
613
+ "gs-color-danger-contrast",
614
+ "gs-color-link",
615
+ "gs-color-primary",
616
+ "gs-color-primary-contrast",
617
+ "gs-color-success",
618
+ "gs-color-success-contrast",
619
+ "gs-focus-ring",
620
+ "gs-font-display",
621
+ "gs-header-bg",
622
+ "gs-header-border",
623
+ "gs-header-border-width",
624
+ "gs-hero-glow",
625
+ "gs-method-delete",
626
+ "gs-method-delete-bg",
627
+ "gs-method-delete-contrast",
628
+ "gs-method-get",
629
+ "gs-method-get-bg",
630
+ "gs-method-get-contrast",
631
+ "gs-method-head",
632
+ "gs-method-head-contrast",
633
+ "gs-method-options",
634
+ "gs-method-options-contrast",
635
+ "gs-method-other",
636
+ "gs-method-other-contrast",
637
+ "gs-method-patch",
638
+ "gs-method-patch-bg",
639
+ "gs-method-patch-contrast",
640
+ "gs-method-post",
641
+ "gs-method-post-bg",
642
+ "gs-method-post-contrast",
643
+ "gs-method-put",
644
+ "gs-method-put-bg",
645
+ "gs-method-put-contrast",
646
+ "gs-method-trace",
647
+ "gs-method-trace-contrast",
648
+ "gs-nav-active-bg",
649
+ "gs-nav-active-border",
650
+ "gs-nav-active-text",
651
+ "gs-nav-hover-bg",
652
+ "gs-nav-hover-text",
653
+ "gs-primary-100",
654
+ "gs-primary-200",
655
+ "gs-primary-300",
656
+ "gs-primary-400",
657
+ "gs-primary-50",
658
+ "gs-primary-500",
659
+ "gs-primary-600",
660
+ "gs-primary-700",
661
+ "gs-primary-800",
662
+ "gs-primary-900",
663
+ "gs-primary-950",
664
+ "gs-radius",
665
+ "gs-radius-full",
666
+ "gs-radius-lg",
667
+ "gs-radius-sm",
668
+ "gs-radius-xl",
669
+ "gs-search-bg",
670
+ "gs-search-border",
671
+ "gs-search-kbd-bg",
672
+ "gs-search-text",
673
+ "gs-shadow-card",
674
+ "gs-shadow-card-hover",
675
+ "gs-shadow-overlay",
676
+ "gs-sidebar-bg",
677
+ "gs-surface",
678
+ "gs-surface-ui",
679
+ "gs-surface-overlay",
680
+ "gs-surface-raised",
681
+ "gs-text",
682
+ "gs-text-faint",
683
+ "gs-text-muted",
684
+ "gs-text-secondary",
685
+ "gs-toc-active",
686
+ "gs-toc-text"
687
+ ]);
688
+ var TOKEN_NAME_SET = new Set(TOKEN_NAMES);
689
+ var SHADOW_NAMES = ["none", "soft", "soft-large", "strong"];
690
+ function modeTokenRecord(css, mode) {
691
+ const selector = `[data-theme='${mode}']`;
692
+ const start = css.indexOf(`${selector} {`);
693
+ const end = css.indexOf("\n}", start);
694
+ if (start === -1 || end === -1) {
695
+ throw new Error(`tokensToCss did not emit ${selector}`);
696
+ }
697
+ const block = css.slice(start, end + 2);
698
+ return Object.fromEntries(
699
+ [...block.matchAll(/\s--(gs-[^:]+):\s*([^;]+);/g)].map((match) => [
700
+ match[1],
701
+ match[2].trim()
702
+ ])
703
+ );
704
+ }
705
+ function legacyThemeRecords(preset, colors, styling) {
706
+ const css = tokensToCss(deriveTokens(colors.primary, { theme: preset }), {
707
+ theme: preset,
708
+ colors: { light: colors.light, dark: colors.dark },
709
+ styling
710
+ });
711
+ return {
712
+ light: modeTokenRecord(css, "light"),
713
+ dark: modeTokenRecord(css, "dark")
714
+ };
715
+ }
716
+ function normalizedColor(input) {
717
+ return formatCss(clampChroma(parseInput(input), "oklch", "rgb"));
718
+ }
719
+ function seededAccentRecord(mode, seed, preset, styling) {
720
+ const css = tokensToCss(deriveTokens(seed, { theme: preset }), {
721
+ theme: preset,
722
+ colors: mode === "light" ? { light: seed } : { dark: seed },
723
+ styling
724
+ });
725
+ return modeTokenRecord(css, mode);
726
+ }
727
+ function boundedNeutralColor(lightness, anchor, chromaFraction) {
728
+ return oklchString(
729
+ Math.min(1, Math.max(0, lightness)),
730
+ Math.min(anchor.c * chromaFraction, 0.04),
731
+ anchor.h ?? 0
732
+ );
733
+ }
734
+ function interpolateColor(from, to, amount) {
735
+ const fromHue = from.h ?? to.h ?? 0;
736
+ const toHue = to.h ?? from.h ?? 0;
737
+ let hueDelta = toHue - fromHue;
738
+ if (hueDelta > 180) hueDelta -= 360;
739
+ if (hueDelta < -180) hueDelta += 360;
740
+ return oklchString(
741
+ Math.min(1, Math.max(0, from.l + (to.l - from.l) * amount)),
742
+ Math.max(0, from.c + (to.c - from.c) * amount),
743
+ fromHue + hueDelta * amount
744
+ );
745
+ }
746
+ function applyNeutralSeeds(record, baseRecord, mode, backgroundSeed, surfaceSeed, textSeed) {
747
+ if (!backgroundSeed && !surfaceSeed && !textSeed) return;
748
+ const originalBackground = parseInput(baseRecord["gs-surface"]);
749
+ const background = backgroundSeed ? parseInput(backgroundSeed) : originalBackground;
750
+ const backgroundValue = backgroundSeed ? normalizedColor(backgroundSeed) : baseRecord["gs-surface"];
751
+ const designedSurfaceLightness = mode === "light" ? Math.min(1, background.l + 0.029) : Math.min(1, background.l + 0.055);
752
+ const surface = surfaceSeed ? parseInput(surfaceSeed) : parseInput(boundedNeutralColor(designedSurfaceLightness, background, 0.7));
753
+ const surfaceValue = surfaceSeed ? normalizedColor(surfaceSeed) : boundedNeutralColor(designedSurfaceLightness, background, 0.7);
754
+ const overlayValue = interpolateColor(background, surface, 1.6);
755
+ const surfaceUiValue = mode === "light" ? backgroundValue : interpolateColor(background, surface, 0.73);
756
+ const codeValue = interpolateColor(background, surface, mode === "light" ? 0.48 : 0.45);
757
+ const codeTitleValue = mode === "light" ? interpolateColor(background, surface, -0.17) : surfaceValue;
758
+ const borderLightness = mode === "light" ? background.l - 0.086 : background.l + 0.16;
759
+ const borderValue = boundedNeutralColor(borderLightness, background, 1);
760
+ if (backgroundSeed) record["gs-surface"] = backgroundValue;
761
+ if (backgroundSeed || surfaceSeed) {
762
+ record["gs-surface-ui"] = surfaceUiValue;
763
+ record["gs-surface-raised"] = surfaceValue;
764
+ record["gs-surface-overlay"] = overlayValue;
765
+ record["gs-code-bg"] = codeValue;
766
+ record["gs-code-title-bg"] = codeTitleValue;
767
+ record["gs-callout-note-surface"] = surfaceUiValue;
768
+ record["gs-border"] = borderValue;
769
+ record["gs-search-border"] = borderValue;
770
+ if (mode === "dark") {
771
+ record["gs-api-panel-bg"] = codeValue;
772
+ record["gs-api-panel-border"] = borderValue;
773
+ }
774
+ if (record["gs-header-border-width"] !== "2px") {
775
+ record["gs-header-border"] = borderValue;
776
+ }
777
+ }
778
+ const requestedTextValue = textSeed ? normalizedColor(textSeed) : baseRecord["gs-text"];
779
+ if (backgroundSeed || textSeed) {
780
+ const textTarget = wcagContrast(
781
+ baseRecord["gs-text"],
782
+ baseRecord["gs-surface"]
783
+ );
784
+ const textValue = wcagContrast(requestedTextValue, backgroundValue) >= textTarget ? requestedTextValue : nearestAccessible(requestedTextValue, backgroundValue, textTarget);
785
+ const text = parseInput(textValue);
786
+ const mutedFraction = mode === "light" ? 0.352 : 0.318;
787
+ const faintFraction = mode === "light" ? 0.468 : 0.417;
788
+ const rawMuted = interpolateColor(text, background, mutedFraction);
789
+ const rawFaint = interpolateColor(text, background, faintFraction);
790
+ const mutedTarget = wcagContrast(
791
+ baseRecord["gs-text-muted"],
792
+ baseRecord["gs-surface"]
793
+ );
794
+ const faintTarget = wcagContrast(
795
+ baseRecord["gs-text-faint"],
796
+ baseRecord["gs-surface"]
797
+ );
798
+ const muted = wcagContrast(rawMuted, backgroundValue) >= mutedTarget ? rawMuted : nearestAccessible(rawMuted, backgroundValue, mutedTarget);
799
+ const faint = wcagContrast(rawFaint, backgroundValue) >= faintTarget ? rawFaint : nearestAccessible(rawFaint, backgroundValue, faintTarget);
800
+ record["gs-text"] = textValue;
801
+ record["gs-text-secondary"] = muted;
802
+ record["gs-text-muted"] = muted;
803
+ record["gs-text-faint"] = faint;
804
+ record["gs-nav-hover-text"] = textValue;
805
+ record["gs-button-secondary-text"] = textValue;
806
+ record["gs-search-text"] = muted;
807
+ record["gs-toc-text"] = faint;
808
+ }
809
+ if (backgroundSeed || surfaceSeed || textSeed) {
810
+ const primary = record["gs-color-primary"];
811
+ const textValueNow = record["gs-text"];
812
+ const raisedValue = record["gs-surface-raised"];
813
+ record["gs-header-bg"] = `color-mix(in oklab, ${backgroundValue} 78%, transparent)`;
814
+ record["gs-sidebar-bg"] = mix(primary, mode === "light" ? 1 : 2, backgroundValue);
815
+ record["gs-nav-hover-bg"] = mix(textValueNow, mode === "light" ? 5 : 8, "transparent");
816
+ record["gs-search-bg"] = mix(textValueNow, mode === "light" ? 2 : 4, raisedValue);
817
+ record["gs-search-kbd-bg"] = mix(textValueNow, mode === "light" ? 5 : 9, raisedValue);
818
+ record["gs-button-secondary-bg"] = mix(textValueNow, mode === "light" ? 2 : 4, raisedValue);
819
+ }
820
+ }
821
+ function applyShadowOverride(record, mode, shadow) {
822
+ if (!shadow) return;
823
+ for (const declaration of shadowVars(mode, shadow)) {
824
+ const match = /^--(gs-[^:]+):\s*(.*);$/.exec(declaration);
825
+ if (match) record[match[1]] = match[2];
826
+ }
827
+ }
828
+ function validateThemeInput(theme, colors) {
829
+ const problems = [];
830
+ let input;
831
+ let preset = "default";
832
+ if (typeof theme === "string") {
833
+ if (includes(THEME_PRESETS, theme)) preset = theme;
834
+ else problems.push(`unknown theme preset ${JSON.stringify(theme)}`);
835
+ } else if (theme !== void 0) {
836
+ if (theme === null || Array.isArray(theme) || typeof theme !== "object") {
837
+ problems.push("theme must be a preset name or theme object");
838
+ } else {
839
+ input = theme;
840
+ if (input.base === void 0) preset = "default";
841
+ else if (includes(THEME_PRESETS, input.base)) preset = input.base;
842
+ else problems.push(`unknown theme base ${JSON.stringify(input.base)}`);
843
+ if (input.radius !== void 0 && !includes(RADIUS_SCALES, input.radius)) {
844
+ problems.push(`unknown radius scale ${JSON.stringify(input.radius)}`);
845
+ }
846
+ if (input.accentStrength !== void 0 && !includes(ACCENT_STRENGTHS, input.accentStrength)) {
847
+ problems.push(`unknown accent strength ${JSON.stringify(input.accentStrength)}`);
848
+ }
849
+ if (input.shadow !== void 0 && !includes(SHADOW_NAMES, input.shadow)) {
850
+ problems.push(`unknown shadow ${JSON.stringify(input.shadow)}`);
851
+ }
852
+ }
853
+ }
854
+ const colorEntries = [
855
+ ["colors.primary", colors?.primary],
856
+ ["colors.light", colors?.light],
857
+ ["colors.dark", colors?.dark]
858
+ ];
859
+ for (const seedName of ["background", "surface", "text", "accent"]) {
860
+ for (const mode of ["light", "dark"]) {
861
+ colorEntries.push([
862
+ `seeds.${seedName}.${mode}`,
863
+ input?.seeds?.[seedName]?.[mode]
864
+ ]);
865
+ }
866
+ }
867
+ for (const [label, value] of colorEntries) {
868
+ if (value === void 0) continue;
869
+ if (typeof value !== "string" || !toOklch(value)) {
870
+ problems.push(`${label}: could not parse color ${JSON.stringify(value)}`);
871
+ }
872
+ }
873
+ for (const mode of ["light", "dark"]) {
874
+ for (const key of Object.keys(input?.tokens?.[mode] ?? {})) {
875
+ if (!TOKEN_NAME_SET.has(key)) {
876
+ problems.push(`tokens.${mode}.${key}: unknown token name`);
877
+ }
878
+ }
879
+ }
880
+ if (problems.length > 0) throw new ThemeError(problems);
881
+ return { preset, input };
882
+ }
883
+ function resolveTheme(theme, colors, configStyling) {
884
+ const { preset, input } = validateThemeInput(theme, colors);
885
+ const styling = {
886
+ radius: input?.radius ?? configStyling?.radius,
887
+ accentStrength: input?.accentStrength ?? configStyling?.accentStrength
888
+ };
889
+ const base = legacyThemeRecords(preset, colors, styling);
890
+ const resolved = {
891
+ light: { ...base.light },
892
+ dark: { ...base.dark }
893
+ };
894
+ for (const mode of ["light", "dark"]) {
895
+ const accentSeed = input?.seeds?.accent?.[mode];
896
+ if (accentSeed) {
897
+ resolved[mode] = seededAccentRecord(mode, accentSeed, preset, styling);
898
+ }
899
+ const modeBase = accentSeed ? { ...resolved[mode] } : base[mode];
900
+ applyNeutralSeeds(
901
+ resolved[mode],
902
+ modeBase,
903
+ mode,
904
+ input?.seeds?.background?.[mode],
905
+ input?.seeds?.surface?.[mode],
906
+ input?.seeds?.text?.[mode]
907
+ );
908
+ applyShadowOverride(resolved[mode], mode, input?.shadow);
909
+ enforceTextFloors(resolved[mode]);
910
+ if (input?.seeds?.background?.[mode] || input?.seeds?.surface?.[mode] || input?.seeds?.text?.[mode]) {
911
+ syncChromeTextAliases(resolved[mode]);
912
+ }
913
+ enforceGeneratedComponentFloors(resolved[mode]);
914
+ Object.assign(resolved[mode], input?.tokens?.[mode]);
915
+ }
916
+ if (input?.seeds?.background?.dark || input?.seeds?.surface?.dark) {
917
+ if (input?.tokens?.light?.["gs-api-panel-bg"] === void 0) {
918
+ resolved.light["gs-api-panel-bg"] = resolved.dark["gs-api-panel-bg"];
919
+ }
920
+ if (input?.tokens?.light?.["gs-api-panel-border"] === void 0) {
921
+ resolved.light["gs-api-panel-border"] = resolved.dark["gs-api-panel-border"];
922
+ }
923
+ }
924
+ return resolved;
925
+ }
926
+ var TEXT_FLOOR_ROLES = ["gs-text", "gs-text-secondary", "gs-text-muted", "gs-text-faint"];
927
+ var TEXT_FLOOR_SURFACES = [
928
+ { name: "gs-bg" },
929
+ { name: "gs-surface" },
930
+ { name: "gs-surface-raised" },
931
+ { name: "gs-surface-overlay" },
932
+ { name: "gs-sidebar-bg" },
933
+ { name: "gs-nav-hover-bg", backdrop: "gs-sidebar-bg" },
934
+ { name: "gs-search-bg" },
935
+ { name: "gs-search-kbd-bg" },
936
+ { name: "gs-button-secondary-bg" },
937
+ { name: "gs-code-bg" },
938
+ { name: "gs-code-title-bg" }
939
+ ];
940
+ function splitTopLevelArgs(value) {
941
+ const parts = [];
942
+ let depth = 0;
943
+ let current = "";
944
+ for (const char of value) {
945
+ if (char === "(") depth += 1;
946
+ if (char === ")") depth -= 1;
947
+ if (char === "," && depth === 0) {
948
+ parts.push(current.trim());
949
+ current = "";
950
+ } else {
951
+ current += char;
952
+ }
953
+ }
954
+ if (current.trim()) parts.push(current.trim());
955
+ return parts;
956
+ }
957
+ function flattenTokenColor(value, tokens) {
958
+ if (!value) return null;
959
+ const trimmed = value.trim();
960
+ const varRef = trimmed.match(/^var\(--([a-z0-9-]+)\)$/i);
961
+ const varName = varRef?.[1];
962
+ if (varName !== void 0) return flattenTokenColor(tokens[varName], tokens);
963
+ const mixBody = trimmed.match(/^color-mix\(in\s+oklab\s*,([\s\S]*)\)$/i)?.[1];
964
+ if (mixBody !== void 0) {
965
+ const parts = splitTopLevelArgs(mixBody);
966
+ const [partA, partB] = parts;
967
+ if (parts.length !== 2 || partA === void 0 || partB === void 0) return null;
968
+ const parseStop = (part) => {
969
+ const weightMatch = part.match(/^([\s\S]*?)\s+([\d.]+)%$/);
970
+ const body = weightMatch?.[1] ?? part;
971
+ const weightText = weightMatch?.[2];
972
+ return {
973
+ color: flattenTokenColor(body, tokens),
974
+ weight: weightText === void 0 ? void 0 : Number(weightText) / 100
975
+ };
976
+ };
977
+ const stopA = parseStop(partA);
978
+ const stopB = parseStop(partB);
979
+ if (!stopA.color || !stopB.color) return null;
980
+ const w0 = stopA.weight ?? (stopB.weight === void 0 ? 0.5 : 1 - stopB.weight);
981
+ const w1 = stopB.weight ?? 1 - w0;
982
+ const total = w0 + w1;
983
+ const pairs = [
984
+ { color: stopA.color, weight: w0 / total },
985
+ { color: stopB.color, weight: w1 / total }
986
+ ];
987
+ const alpha = pairs.reduce((sum, pair) => sum + pair.color.alpha * pair.weight, 0);
988
+ const channel = (name) => alpha === 0 ? 0 : pairs.reduce((sum, pair) => sum + pair.color[name] * pair.color.alpha * pair.weight, 0) / alpha;
989
+ return { l: channel("l"), a: channel("a"), b: channel("b"), alpha };
990
+ }
991
+ if (trimmed.toLowerCase() === "transparent") return { l: 0, a: 0, b: 0, alpha: 0 };
992
+ const parsed = parse(trimmed);
993
+ const converted = parsed ? toOklab(parsed) : void 0;
994
+ if (!converted) return null;
995
+ return { l: converted.l, a: converted.a, b: converted.b, alpha: converted.alpha ?? 1 };
996
+ }
997
+ function flatToHex(color, backdrop) {
998
+ let out = color;
999
+ if (color.alpha < 1) {
1000
+ const back = backdrop ?? { l: 1, a: 0, b: 0, alpha: 1 };
1001
+ const alpha = color.alpha + back.alpha * (1 - color.alpha);
1002
+ const channel = (name) => alpha === 0 ? 0 : (color[name] * color.alpha + back[name] * back.alpha * (1 - color.alpha)) / alpha;
1003
+ out = { l: channel("l"), a: channel("a"), b: channel("b"), alpha };
1004
+ }
1005
+ return formatHex({ mode: "oklab", l: out.l, a: out.a, b: out.b });
1006
+ }
1007
+ function enforceTextFloors(tokens) {
1008
+ const surfaceHexes = [];
1009
+ for (const surface of TEXT_FLOOR_SURFACES) {
1010
+ const flat = flattenTokenColor(tokens[surface.name], tokens);
1011
+ if (!flat) continue;
1012
+ const backdrop = surface.backdrop ? flattenTokenColor(tokens[surface.backdrop], tokens) : null;
1013
+ surfaceHexes.push(flatToHex(flat, backdrop));
1014
+ }
1015
+ for (const role of TEXT_FLOOR_ROLES) {
1016
+ const raw = tokens[role];
1017
+ if (!raw || raw.includes("var(")) continue;
1018
+ let value = raw;
1019
+ for (let pass = 0; pass < 2; pass++) {
1020
+ for (const surfaceHex of surfaceHexes) {
1021
+ if (wcagContrast(value, surfaceHex) < 4.5) {
1022
+ value = nearestAccessible(value, surfaceHex, 4.5);
1023
+ }
1024
+ }
1025
+ }
1026
+ if (value !== raw) tokens[role] = value;
1027
+ }
1028
+ }
1029
+ function syncChromeTextAliases(tokens) {
1030
+ tokens["gs-search-text"] = tokens["gs-text-secondary"];
1031
+ tokens["gs-toc-text"] = tokens["gs-text-faint"];
1032
+ }
1033
+ function enforceGeneratedComponentFloors(tokens) {
1034
+ const foregroundName = "gs-search-text";
1035
+ const backgroundName = "gs-search-bg";
1036
+ const foreground = flattenTokenColor(tokens[foregroundName], tokens);
1037
+ const background = flattenTokenColor(tokens[backgroundName], tokens);
1038
+ const surface = flattenTokenColor(tokens["gs-surface"], tokens);
1039
+ if (!foreground || !background || !surface) return;
1040
+ const backgroundHex = flatToHex(background, surface);
1041
+ const opaqueBackground = flattenTokenColor(backgroundHex, tokens);
1042
+ if (!opaqueBackground) return;
1043
+ const foregroundHex = flatToHex(foreground, opaqueBackground);
1044
+ if (wcagContrast(foregroundHex, backgroundHex) < 4.5) {
1045
+ tokens[foregroundName] = nearestAccessible(
1046
+ foregroundHex,
1047
+ backgroundHex,
1048
+ 4.5
1049
+ );
1050
+ }
1051
+ }
1052
+ function accessibleAtLightness(color, lightness) {
1053
+ return formatHex(
1054
+ clampChroma(
1055
+ { ...color, l: Math.min(1, Math.max(0, lightness)) },
1056
+ "oklch",
1057
+ "rgb"
1058
+ )
1059
+ );
1060
+ }
1061
+ function nearestAccessible(fg, bg, ratio) {
1062
+ const foreground = toOklch(fg);
1063
+ const background = toOklch(bg);
1064
+ const problems = [];
1065
+ if (!foreground) problems.push(`foreground: could not parse color ${JSON.stringify(fg)}`);
1066
+ if (!background) problems.push(`background: could not parse color ${JSON.stringify(bg)}`);
1067
+ if (!Number.isFinite(ratio) || ratio < 1 || ratio > 21) {
1068
+ problems.push(`ratio must be between 1 and 21; received ${JSON.stringify(ratio)}`);
1069
+ }
1070
+ if (problems.length > 0) throw new ThemeError(problems);
1071
+ const original = accessibleAtLightness(foreground, foreground.l);
1072
+ if (wcagContrast(original, bg) >= ratio) return original;
1073
+ const candidates = [];
1074
+ const darker = accessibleAtLightness(foreground, 0);
1075
+ if (wcagContrast(darker, bg) >= ratio) {
1076
+ let low = 0;
1077
+ let high = foreground.l;
1078
+ for (let index = 0; index < 32; index++) {
1079
+ const mid = (low + high) / 2;
1080
+ if (wcagContrast(accessibleAtLightness(foreground, mid), bg) >= ratio) low = mid;
1081
+ else high = mid;
1082
+ }
1083
+ const color = accessibleAtLightness(foreground, low);
1084
+ candidates.push({ color, delta: foreground.l - low });
1085
+ }
1086
+ const lighter = accessibleAtLightness(foreground, 1);
1087
+ if (wcagContrast(lighter, bg) >= ratio) {
1088
+ let low = foreground.l;
1089
+ let high = 1;
1090
+ for (let index = 0; index < 32; index++) {
1091
+ const mid = (low + high) / 2;
1092
+ if (wcagContrast(accessibleAtLightness(foreground, mid), bg) >= ratio) high = mid;
1093
+ else low = mid;
1094
+ }
1095
+ const color = accessibleAtLightness(foreground, high);
1096
+ candidates.push({ color, delta: high - foreground.l });
1097
+ }
1098
+ candidates.sort((left, right) => left.delta - right.delta);
1099
+ if (candidates[0]) return candidates[0].color;
1100
+ throw new ThemeError([
1101
+ `no lightness adjustment of ${JSON.stringify(fg)} reaches ${ratio}:1 against ${JSON.stringify(bg)}`
1102
+ ]);
1103
+ }
1104
+
1105
+ // ../source-abi/dist/index.js
1106
+ import { parse as parse2, parseDocument } from "yaml";
1107
+ import { unified } from "unified";
1108
+ import remarkGfm from "remark-gfm";
1109
+ import remarkMdx from "remark-mdx";
1110
+ import remarkParse from "remark-parse";
1111
+ import { z } from "zod";
1112
+ var SOURCE_ABI_VERSION = 3;
1113
+ var SOURCE_LIMITS = Object.freeze({
1114
+ maxFileBytes: 26214400,
1115
+ maxTotalBytes: 209715200,
1116
+ maxFileCount: 5e3,
1117
+ maxPageCount: 2e3,
1118
+ maxPathDepth: 12,
1119
+ maxPathBytes: 512,
1120
+ maxSegmentBytes: 255,
1121
+ maxDocsJsonBytes: 1048576,
1122
+ maxModelsTomlBytes: 65536,
1123
+ maxOpenApiBytes: 4194304,
1124
+ maxFrontmatterBytes: 65536,
1125
+ maxThemeCssBytes: 262144
1126
+ });
1127
+ var SOURCE_ALLOWED_ROOTS = Object.freeze([
1128
+ "docs.json",
1129
+ "models.toml",
1130
+ "pages/**",
1131
+ "public/**",
1132
+ "openapi/**"
1133
+ ]);
1134
+ var SOURCE_ALLOWED_EXTENSIONS = Object.freeze({
1135
+ root: Object.freeze([".json", ".toml"]),
1136
+ pages: Object.freeze([".md", ".mdx"]),
1137
+ openapi: Object.freeze([".json", ".yaml", ".yml"]),
1138
+ public: Object.freeze([
1139
+ ".css",
1140
+ ".png",
1141
+ ".jpg",
1142
+ ".jpeg",
1143
+ ".gif",
1144
+ ".webp",
1145
+ ".avif",
1146
+ ".svg",
1147
+ ".ico",
1148
+ ".woff",
1149
+ ".woff2",
1150
+ ".ttf",
1151
+ ".otf",
1152
+ ".eot",
1153
+ ".mp4",
1154
+ ".webm",
1155
+ ".mp3",
1156
+ ".wav",
1157
+ ".ogg",
1158
+ ".oga",
1159
+ ".ogv",
1160
+ ".pdf",
1161
+ ".txt",
1162
+ ".csv"
1163
+ ])
1164
+ });
1165
+ var RESERVED_URL_PREFIXES = Object.freeze([
1166
+ "/api",
1167
+ "/api/*",
1168
+ "/auth",
1169
+ "/auth/*",
1170
+ "/mcp",
1171
+ "/ask",
1172
+ "/runtime",
1173
+ "/runtime/*"
1174
+ ]);
1175
+ var REJECTED_GENERATED_ROOTS = Object.freeze([
1176
+ "dist",
1177
+ "pagefind",
1178
+ "_astro",
1179
+ "worker/generated",
1180
+ "node_modules",
1181
+ ".git"
1182
+ ]);
1183
+ var REJECTED_GENERATED_FILENAMES = Object.freeze([
1184
+ "llms.txt",
1185
+ "llms-full.txt",
1186
+ "robots.txt",
1187
+ "sitemap*",
1188
+ "*auth-manifest*.json"
1189
+ ]);
1190
+ var SOURCE_MEDIA_TYPES = Object.freeze({
1191
+ ".avif": "image/avif",
1192
+ ".csv": "text/csv",
1193
+ ".css": "text/css",
1194
+ ".eot": "application/vnd.ms-fontobject",
1195
+ ".gif": "image/gif",
1196
+ ".ico": "image/x-icon",
1197
+ ".jpeg": "image/jpeg",
1198
+ ".jpg": "image/jpeg",
1199
+ ".json": "application/json",
1200
+ ".md": "text/markdown",
1201
+ ".mdx": "text/mdx",
1202
+ ".mp3": "audio/mpeg",
1203
+ ".mp4": "video/mp4",
1204
+ ".oga": "audio/ogg",
1205
+ ".ogg": "audio/ogg",
1206
+ ".ogv": "video/ogg",
1207
+ ".otf": "font/otf",
1208
+ ".pdf": "application/pdf",
1209
+ ".png": "image/png",
1210
+ ".svg": "image/svg+xml",
1211
+ ".toml": "application/toml",
1212
+ ".ttf": "font/ttf",
1213
+ ".txt": "text/plain",
1214
+ ".wav": "audio/wav",
1215
+ ".webm": "video/webm",
1216
+ ".webp": "image/webp",
1217
+ ".woff": "font/woff",
1218
+ ".woff2": "font/woff2",
1219
+ ".yaml": "application/yaml",
1220
+ ".yml": "application/yaml"
1221
+ });
1222
+ var textEncoder = new TextEncoder();
1223
+ var WINDOWS_DEVICE_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
1224
+ var ASCII_SOURCE_PATH = /^[A-Za-z0-9._/-]+$/;
1225
+ var ASCII_SOURCE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
1226
+ var PAGE_EXTENSIONS = new Set(SOURCE_ALLOWED_EXTENSIONS.pages);
1227
+ var PUBLIC_EXTENSIONS = new Set(SOURCE_ALLOWED_EXTENSIONS.public);
1228
+ var OPENAPI_EXTENSIONS = new Set(SOURCE_ALLOWED_EXTENSIONS.openapi);
1229
+ function sourceExtension(path) {
1230
+ const filename = path.slice(path.lastIndexOf("/") + 1);
1231
+ const dot = filename.lastIndexOf(".");
1232
+ return dot <= 0 ? null : filename.slice(dot).toLowerCase();
1233
+ }
1234
+ function inspectSourcePath(raw) {
1235
+ const normalized = raw;
1236
+ const segments = normalized.split("/");
1237
+ const tooDeep = segments.length > SOURCE_LIMITS.maxPathDepth;
1238
+ const tooLong = textEncoder.encode(normalized).byteLength > SOURCE_LIMITS.maxPathBytes;
1239
+ const segmentTooLong = segments.some(
1240
+ (segment) => textEncoder.encode(segment).byteLength > SOURCE_LIMITS.maxSegmentBytes
1241
+ );
1242
+ let syntaxValid = normalized.length > 0;
1243
+ if (normalized.startsWith("/") || normalized.endsWith("/") || !ASCII_SOURCE_PATH.test(normalized)) {
1244
+ syntaxValid = false;
1245
+ }
1246
+ for (const segment of segments) {
1247
+ if (segment.length === 0 || !ASCII_SOURCE_SEGMENT.test(segment) || segment === "." || segment === ".." || WINDOWS_DEVICE_NAME.test(segment) || segment.endsWith(".")) {
1248
+ syntaxValid = false;
1249
+ }
1250
+ }
1251
+ return { normalized, segments, syntaxValid, tooDeep, tooLong, segmentTooLong };
1252
+ }
1253
+ function isKnownSourceRoot(path) {
1254
+ if (path === "docs.json" || path === "models.toml") return true;
1255
+ return path.startsWith("pages/") || path.startsWith("public/") || path.startsWith("openapi/");
1256
+ }
1257
+ function isAllowedSourceLocation(path) {
1258
+ const extension = sourceExtension(path);
1259
+ if (path === "docs.json") return extension === ".json";
1260
+ if (path === "models.toml") return extension === ".toml";
1261
+ if (path.startsWith("pages/")) {
1262
+ return extension !== null && PAGE_EXTENSIONS.has(extension);
1263
+ }
1264
+ if (path.startsWith("public/")) {
1265
+ if (extension === ".css") return path === "public/theme.css";
1266
+ return extension !== null && PUBLIC_EXTENSIONS.has(extension);
1267
+ }
1268
+ if (path.startsWith("openapi/")) {
1269
+ return extension !== null && OPENAPI_EXTENSIONS.has(extension);
1270
+ }
1271
+ return false;
1272
+ }
1273
+ function isStaticallyGeneratedArtifact(path) {
1274
+ const lower = path.toLowerCase();
1275
+ const filename = lower.slice(lower.lastIndexOf("/") + 1);
1276
+ if (lower === "dist" || lower.startsWith("dist/") || lower === "pagefind" || lower.startsWith("pagefind/") || lower === "_astro" || lower.startsWith("_astro/") || lower === "node_modules" || lower.startsWith("node_modules/") || lower === ".git" || lower.startsWith(".git/") || lower === "worker/generated" || lower.startsWith("worker/generated/")) {
1277
+ return true;
1278
+ }
1279
+ return filename === "llms.txt" || filename === "llms-full.txt" || filename === "robots.txt" || filename.startsWith("sitemap") || filename.endsWith(".json") && filename.includes("auth-manifest");
1280
+ }
1281
+ function canonicalizeSourcePath(raw) {
1282
+ const inspected = inspectSourcePath(raw);
1283
+ if (!inspected.syntaxValid || inspected.tooDeep || inspected.tooLong || inspected.segmentTooLong || !isAllowedSourceLocation(inspected.normalized) || isStaticallyGeneratedArtifact(inspected.normalized)) {
1284
+ return null;
1285
+ }
1286
+ return inspected.normalized;
1287
+ }
1288
+ function detectSourceMediaType(path) {
1289
+ const extension = sourceExtension(path);
1290
+ if (extension === null) return null;
1291
+ return SOURCE_MEDIA_TYPES[extension] ?? null;
1292
+ }
1293
+ function unicodeCaseFold(value) {
1294
+ return value.toLowerCase();
1295
+ }
1296
+ var textEncoder2 = new TextEncoder();
1297
+ var BLOB_PATTERN = /^sha256\/[0-9a-f]{64}$/;
1298
+ var GIT_COMMIT_PATTERN = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
1299
+ var ASCII_PATTERN = /^[\x00-\x7f]*$/;
1300
+ var REVISION_DOMAIN = "saturndocs-source-revision-v1\n";
1301
+ function hex(bytes) {
1302
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
1303
+ }
1304
+ async function sha256(bytes) {
1305
+ const copy = new Uint8Array(bytes.byteLength);
1306
+ copy.set(bytes);
1307
+ const digest = await crypto.subtle.digest("SHA-256", copy.buffer);
1308
+ return hex(digest);
1309
+ }
1310
+ async function blobId(bytes) {
1311
+ return `sha256/${await sha256(bytes)}`;
1312
+ }
1313
+ function compareCodePoints(left, right) {
1314
+ const leftPoints = Array.from(left, (point) => point.codePointAt(0));
1315
+ const rightPoints = Array.from(right, (point) => point.codePointAt(0));
1316
+ const count = Math.min(leftPoints.length, rightPoints.length);
1317
+ for (let index = 0; index < count; index += 1) {
1318
+ const difference = leftPoints[index] - rightPoints[index];
1319
+ if (difference !== 0) return difference;
1320
+ }
1321
+ return leftPoints.length - rightPoints.length;
1322
+ }
1323
+ function canonicalJsonString(value) {
1324
+ if (!ASCII_PATTERN.test(value)) {
1325
+ throw new TypeError("canonical revision strings must be ASCII");
1326
+ }
1327
+ let result = '"';
1328
+ for (let index = 0; index < value.length; index += 1) {
1329
+ const code = value.charCodeAt(index);
1330
+ if (code === 34) result += '\\"';
1331
+ else if (code === 92) result += "\\\\";
1332
+ else if (code === 8) result += "\\b";
1333
+ else if (code === 12) result += "\\f";
1334
+ else if (code === 10) result += "\\n";
1335
+ else if (code === 13) result += "\\r";
1336
+ else if (code === 9) result += "\\t";
1337
+ else if (code <= 31) result += `\\u00${code.toString(16).padStart(2, "0")}`;
1338
+ else result += value[index];
1339
+ }
1340
+ return `${result}"`;
1341
+ }
1342
+ function canonicalJson(value) {
1343
+ if (value === null || typeof value === "boolean" || typeof value === "string") {
1344
+ return typeof value === "string" ? canonicalJsonString(value) : JSON.stringify(value);
1345
+ }
1346
+ if (typeof value === "number") {
1347
+ if (!Number.isSafeInteger(value)) {
1348
+ throw new TypeError("canonical revision numbers must be safe integers");
1349
+ }
1350
+ return String(value);
1351
+ }
1352
+ if (Array.isArray(value)) {
1353
+ return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
1354
+ }
1355
+ if (typeof value === "object") {
1356
+ const record = value;
1357
+ const keys = Object.keys(record).filter((key) => record[key] !== void 0).sort(compareCodePoints);
1358
+ return `{${keys.map((key) => `${canonicalJsonString(key)}:${canonicalJson(record[key])}`).join(",")}}`;
1359
+ }
1360
+ throw new TypeError("canonical revision JSON contains an unsupported value");
1361
+ }
1362
+ function validatedManifestValue(manifest) {
1363
+ if (manifest.sourceAbiVersion !== SOURCE_ABI_VERSION) {
1364
+ throw new TypeError(`sourceAbiVersion must be ${SOURCE_ABI_VERSION}`);
1365
+ }
1366
+ if (manifest.sourceOfTruth !== "bundle" && manifest.sourceOfTruth !== "git") {
1367
+ throw new TypeError('sourceOfTruth must be "bundle" or "git"');
1368
+ }
1369
+ const entries = {};
1370
+ for (const path of Object.keys(manifest.entries).sort(compareCodePoints)) {
1371
+ if (canonicalizeSourcePath(path) !== path) {
1372
+ throw new TypeError(`revision entry path is not canonical: ${path}`);
1373
+ }
1374
+ const entry = manifest.entries[path];
1375
+ if (!BLOB_PATTERN.test(entry.blob)) {
1376
+ throw new TypeError(`revision entry blob is invalid: ${path}`);
1377
+ }
1378
+ if (!Number.isSafeInteger(entry.size) || entry.size < 0) {
1379
+ throw new TypeError(`revision entry size is invalid: ${path}`);
1380
+ }
1381
+ const mediaType = detectSourceMediaType(path);
1382
+ if (mediaType === null || !ASCII_PATTERN.test(mediaType)) {
1383
+ throw new TypeError(`revision entry mediaType cannot be derived: ${path}`);
1384
+ }
1385
+ entries[path] = {
1386
+ blob: entry.blob,
1387
+ mediaType,
1388
+ size: entry.size
1389
+ };
1390
+ }
1391
+ const value = {
1392
+ entries,
1393
+ sourceAbiVersion: SOURCE_ABI_VERSION,
1394
+ sourceOfTruth: manifest.sourceOfTruth
1395
+ };
1396
+ return value;
1397
+ }
1398
+ function canonicalizeRevisionManifest(manifest) {
1399
+ return canonicalJson(validatedManifestValue(manifest));
1400
+ }
1401
+ async function revisionId(manifest) {
1402
+ const canonical = canonicalizeRevisionManifest(manifest);
1403
+ const digest = await sha256(textEncoder2.encode(`${REVISION_DOMAIN}${canonical}`));
1404
+ return `srev1:${digest}`;
1405
+ }
1406
+ var SourceAbiError = class extends Error {
1407
+ code;
1408
+ path;
1409
+ constructor(code, path, message) {
1410
+ super(message);
1411
+ this.name = "SourceAbiError";
1412
+ this.code = code;
1413
+ this.path = path;
1414
+ }
1415
+ };
1416
+ function applyChangeSet(base, changeSet) {
1417
+ if (base.sourceOfTruth === "git") {
1418
+ throw new SourceAbiError(
1419
+ "git_base_immutable",
1420
+ "",
1421
+ "change sets cannot edit a git-mode source revision"
1422
+ );
1423
+ }
1424
+ const entries = {};
1425
+ for (const [path, entry] of Object.entries(base.entries)) {
1426
+ entries[path] = { ...entry };
1427
+ }
1428
+ for (const operation of changeSet.ops) {
1429
+ if (canonicalizeSourcePath(operation.path) !== operation.path) {
1430
+ throw new SourceAbiError(
1431
+ "non_canonical_path",
1432
+ operation.path,
1433
+ `change-set path is not canonical: ${operation.path}`
1434
+ );
1435
+ }
1436
+ if (operation.op === "put") {
1437
+ entries[operation.path] = { ...operation.entry };
1438
+ continue;
1439
+ }
1440
+ if (!(operation.path in entries)) {
1441
+ throw new SourceAbiError(
1442
+ "delete_missing",
1443
+ operation.path,
1444
+ `cannot delete missing source path: ${operation.path}`
1445
+ );
1446
+ }
1447
+ delete entries[operation.path];
1448
+ }
1449
+ return {
1450
+ sourceAbiVersion: base.sourceAbiVersion,
1451
+ sourceOfTruth: base.sourceOfTruth,
1452
+ entries
1453
+ };
1454
+ }
1455
+ function compareCodePoints2(left, right) {
1456
+ const leftPoints = Array.from(left, (point) => point.codePointAt(0));
1457
+ const rightPoints = Array.from(right, (point) => point.codePointAt(0));
1458
+ const count = Math.min(leftPoints.length, rightPoints.length);
1459
+ for (let index = 0; index < count; index += 1) {
1460
+ const difference = leftPoints[index] - rightPoints[index];
1461
+ if (difference !== 0) return difference;
1462
+ }
1463
+ return leftPoints.length - rightPoints.length;
1464
+ }
1465
+ function sortViolations(violations) {
1466
+ return violations.sort((left, right) => {
1467
+ if (left.path === null && right.path !== null) return -1;
1468
+ if (left.path !== null && right.path === null) return 1;
1469
+ const pathOrder = compareCodePoints2(left.path ?? "", right.path ?? "");
1470
+ if (pathOrder !== 0) return pathOrder;
1471
+ const codeOrder = compareCodePoints2(left.code, right.code);
1472
+ if (codeOrder !== 0) return codeOrder;
1473
+ return compareCodePoints2(left.message, right.message);
1474
+ });
1475
+ }
1476
+ function isRootSpecificTypeInvalid(path) {
1477
+ return (path.startsWith("pages/") || path.startsWith("public/") || path.startsWith("openapi/") || path === "docs.json" || path === "models.toml") && !isAllowedSourceLocation(path);
1478
+ }
1479
+ function isReservedRoute(path) {
1480
+ return RESERVED_URL_PREFIXES.some((pattern) => {
1481
+ if (pattern.endsWith("/*")) {
1482
+ return path.startsWith(pattern.slice(0, -1));
1483
+ }
1484
+ return path === pattern;
1485
+ });
1486
+ }
1487
+ function servedRoute(path) {
1488
+ if (path.startsWith("pages/")) {
1489
+ const extension = sourceExtension(path);
1490
+ if (extension !== ".md" && extension !== ".mdx") return null;
1491
+ const logical = path.slice("pages/".length, -extension.length);
1492
+ return logical === "index" ? "/" : `/${logical}`;
1493
+ }
1494
+ if (path.startsWith("public/")) {
1495
+ return `/${path.slice("public/".length)}`;
1496
+ }
1497
+ return null;
1498
+ }
1499
+ function pageTwinPaths(paths) {
1500
+ const pages = /* @__PURE__ */ new Set();
1501
+ for (const path of paths) {
1502
+ if (!path.startsWith("pages/")) continue;
1503
+ const extension = sourceExtension(path);
1504
+ if (extension === ".md" || extension === ".mdx") {
1505
+ pages.add(path.slice("pages/".length, -extension.length));
1506
+ }
1507
+ }
1508
+ const twins = /* @__PURE__ */ new Set();
1509
+ for (const path of paths) {
1510
+ if (path.startsWith("pages/") || sourceExtension(path) !== ".md") continue;
1511
+ if (pages.has(path.slice(0, -3))) twins.add(path);
1512
+ }
1513
+ return twins;
1514
+ }
1515
+ function validateBundleStructure(files) {
1516
+ const violations = [];
1517
+ const inspected = files.map((file) => ({ file, path: inspectSourcePath(file.path) }));
1518
+ const normalizedPaths = inspected.filter((item) => item.path.syntaxValid).map((item) => item.path.normalized);
1519
+ const generatedTwins = pageTwinPaths(normalizedPaths);
1520
+ if (files.length > SOURCE_LIMITS.maxFileCount) {
1521
+ violations.push({
1522
+ path: null,
1523
+ code: "too_many_files",
1524
+ severity: "error",
1525
+ message: `bundle has ${files.length} files; maximum is ${SOURCE_LIMITS.maxFileCount}`
1526
+ });
1527
+ }
1528
+ let totalSize = 0;
1529
+ let pageCount = 0;
1530
+ let hasDocsJson = false;
1531
+ for (const { file, path } of inspected) {
1532
+ const sizeValid = Number.isSafeInteger(file.size) && file.size >= 0;
1533
+ totalSize += sizeValid ? file.size : 0;
1534
+ const displayPath = path.syntaxValid ? path.normalized : file.path;
1535
+ if (!sizeValid) {
1536
+ violations.push({
1537
+ path: displayPath,
1538
+ code: "invalid_size",
1539
+ severity: "error",
1540
+ message: "source file size must be a non-negative safe integer"
1541
+ });
1542
+ }
1543
+ if (!path.syntaxValid || path.tooLong || path.segmentTooLong) {
1544
+ violations.push({
1545
+ path: displayPath,
1546
+ code: "invalid_path",
1547
+ severity: "error",
1548
+ message: "source path is not a valid canonical logical path"
1549
+ });
1550
+ }
1551
+ if (path.tooDeep) {
1552
+ violations.push({
1553
+ path: displayPath,
1554
+ code: "path_too_deep",
1555
+ severity: "error",
1556
+ message: `source path has ${path.segments.length} segments; maximum is ${SOURCE_LIMITS.maxPathDepth}`
1557
+ });
1558
+ }
1559
+ if (sizeValid && file.size > SOURCE_LIMITS.maxFileBytes) {
1560
+ violations.push({
1561
+ path: displayPath,
1562
+ code: "file_too_large",
1563
+ severity: "error",
1564
+ message: `source file is ${file.size} bytes; maximum is ${SOURCE_LIMITS.maxFileBytes}`
1565
+ });
1566
+ }
1567
+ if (sizeValid && path.syntaxValid && path.normalized === "public/theme.css" && file.size > SOURCE_LIMITS.maxThemeCssBytes) {
1568
+ violations.push({
1569
+ path: path.normalized,
1570
+ code: "theme_css_too_large",
1571
+ severity: "error",
1572
+ message: `public/theme.css is ${file.size} bytes; maximum is ${SOURCE_LIMITS.maxThemeCssBytes}`
1573
+ });
1574
+ }
1575
+ if (!path.syntaxValid) continue;
1576
+ const normalized = path.normalized;
1577
+ if (normalized === "docs.json" && !path.tooLong && !path.segmentTooLong && isAllowedSourceLocation(normalized) && !isStaticallyGeneratedArtifact(normalized)) {
1578
+ hasDocsJson = true;
1579
+ }
1580
+ const mediaType = detectSourceMediaType(normalized);
1581
+ if (mediaType === null || isRootSpecificTypeInvalid(normalized)) {
1582
+ violations.push({
1583
+ path: normalized,
1584
+ code: "inadmissible_type",
1585
+ severity: "error",
1586
+ message: "file extension is not admissible at this source location"
1587
+ });
1588
+ }
1589
+ if (!isKnownSourceRoot(normalized)) {
1590
+ violations.push({
1591
+ path: normalized,
1592
+ code: "unknown_root",
1593
+ severity: "error",
1594
+ message: "source path is not under an allowed source root"
1595
+ });
1596
+ }
1597
+ if (isStaticallyGeneratedArtifact(normalized) || generatedTwins.has(normalized)) {
1598
+ violations.push({
1599
+ path: normalized,
1600
+ code: "generated_artifact",
1601
+ severity: "error",
1602
+ message: "build-generated output is not admissible as source"
1603
+ });
1604
+ }
1605
+ if (sourceExtension(normalized) === ".svg") {
1606
+ violations.push({
1607
+ path: normalized,
1608
+ code: "active_content",
1609
+ severity: "warning",
1610
+ message: "SVG is active content and requires release-layer policy"
1611
+ });
1612
+ }
1613
+ const route = servedRoute(normalized);
1614
+ if (route !== null && isReservedRoute(route)) {
1615
+ violations.push({
1616
+ path: normalized,
1617
+ code: "reserved_route",
1618
+ severity: "error",
1619
+ message: `source path would claim reserved route ${route}`
1620
+ });
1621
+ }
1622
+ const extension = sourceExtension(normalized);
1623
+ if (normalized.startsWith("pages/") && (extension === ".md" || extension === ".mdx")) {
1624
+ pageCount += 1;
1625
+ }
1626
+ }
1627
+ if (!hasDocsJson) {
1628
+ violations.push({
1629
+ path: null,
1630
+ code: "missing_docs_json",
1631
+ severity: "error",
1632
+ message: "bundle must contain an admissible docs.json entry"
1633
+ });
1634
+ }
1635
+ if (totalSize > SOURCE_LIMITS.maxTotalBytes) {
1636
+ violations.push({
1637
+ path: null,
1638
+ code: "bundle_too_large",
1639
+ severity: "error",
1640
+ message: `bundle is ${totalSize} bytes; maximum is ${SOURCE_LIMITS.maxTotalBytes}`
1641
+ });
1642
+ }
1643
+ if (pageCount > SOURCE_LIMITS.maxPageCount) {
1644
+ violations.push({
1645
+ path: null,
1646
+ code: "too_many_pages",
1647
+ severity: "error",
1648
+ message: `bundle has ${pageCount} page files; maximum is ${SOURCE_LIMITS.maxPageCount}`
1649
+ });
1650
+ }
1651
+ const caseGroups = /* @__PURE__ */ new Map();
1652
+ for (const path of normalizedPaths) {
1653
+ const folded = unicodeCaseFold(path);
1654
+ const group = caseGroups.get(folded) ?? [];
1655
+ group.push(path);
1656
+ caseGroups.set(folded, group);
1657
+ }
1658
+ for (const group of caseGroups.values()) {
1659
+ const paths = [...group].sort(compareCodePoints2);
1660
+ for (let index = 1; index < paths.length; index += 1) {
1661
+ violations.push({
1662
+ path: paths[index],
1663
+ code: "case_collision",
1664
+ severity: "error",
1665
+ message: `source path collides case-insensitively with ${paths[0]}`
1666
+ });
1667
+ }
1668
+ }
1669
+ const pageKinds = /* @__PURE__ */ new Map();
1670
+ for (const path of normalizedPaths) {
1671
+ if (!path.startsWith("pages/")) continue;
1672
+ const extension = sourceExtension(path);
1673
+ if (extension !== ".md" && extension !== ".mdx") continue;
1674
+ const logical = path.slice(0, -extension.length);
1675
+ const kind = pageKinds.get(logical) ?? {};
1676
+ if (extension === ".md") kind.md = path;
1677
+ else kind.mdx = path;
1678
+ pageKinds.set(logical, kind);
1679
+ }
1680
+ for (const kind of pageKinds.values()) {
1681
+ if (kind.md && kind.mdx) {
1682
+ violations.push({
1683
+ path: kind.mdx,
1684
+ code: "md_mdx_collision",
1685
+ severity: "error",
1686
+ message: `logical page resolves to both ${kind.md} and ${kind.mdx}`
1687
+ });
1688
+ }
1689
+ }
1690
+ return sortViolations(violations);
1691
+ }
1692
+ var themeCssDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
1693
+ function addViolation(violations, path, code, message) {
1694
+ violations.push({ path, code, severity: "error", message });
1695
+ }
1696
+ function errorMessage(error) {
1697
+ return error instanceof Error ? error.message : String(error);
1698
+ }
1699
+ function buildRequirementPages(config, groupsByPath) {
1700
+ return navigationGroups(config).flatMap(
1701
+ (group) => group.pages.map((docId) => {
1702
+ const mdx = `pages/${docId}.mdx`;
1703
+ const md = `pages/${docId}.md`;
1704
+ const path = groupsByPath.has(md) && !groupsByPath.has(mdx) ? md : mdx;
1705
+ return { docId, path, url: docId === "index" ? "/" : `/${docId}`, groups: groupsByPath.get(path) ?? [] };
1706
+ })
1707
+ );
1708
+ }
1709
+ function validateRedirects(input, violations) {
1710
+ const knownPaths = /* @__PURE__ */ new Set([
1711
+ ...input.pages.map((page) => page.url),
1712
+ ...[...input.operationSlugsBySpec.values()].flatMap((slugs) => slugs.map((slug) => `/api-reference/${slug}`))
1713
+ ]);
1714
+ const specCount = new Set(navigationGroups(input.config).flatMap((group) => group.openapi ?? [])).size;
1715
+ const allSpecsRead = input.operationSlugsBySpec.size === specCount;
1716
+ try {
1717
+ resolveRootRedirectDestination(input.config.redirects ?? [], knownPaths);
1718
+ } catch (error) {
1719
+ if (!(error instanceof BuildRuleError)) throw error;
1720
+ switch (error.code) {
1721
+ case "redirect_cycle":
1722
+ addViolation(violations, "docs.json", "redirect_cycle", error.message);
1723
+ break;
1724
+ case "root_redirect_to_ask":
1725
+ addViolation(violations, "docs.json", "root_redirect_to_ask", error.message);
1726
+ break;
1727
+ case "root_redirect_unknown_page":
1728
+ if (allSpecsRead) addViolation(violations, "docs.json", "root_redirect_unknown_page", error.message);
1729
+ break;
1730
+ }
1731
+ }
1732
+ }
1733
+ function validateOpenApiNames(input, violations) {
1734
+ if (input.config.agents?.openapi === false) return;
1735
+ const groupsByDocId = new Map(input.pages.map((page) => [page.docId, page.groups]));
1736
+ const specGroups = navigationGroups(input.config).flatMap(
1737
+ (group) => group.openapi ? [{ openapi: group.openapi, pages: group.pages }] : []
1738
+ );
1739
+ const collision = openApiPublicationCollision(
1740
+ ungatedOpenApiSpecPaths(specGroups, (docId) => groupsByDocId.get(docId) ?? [])
1741
+ );
1742
+ if (collision) {
1743
+ addViolation(
1744
+ violations,
1745
+ "docs.json",
1746
+ "openapi_name_collision",
1747
+ `OpenAPI files ${collision.first} and ${collision.second} both publish as /api-reference/${collision.name}.openapi.json; rename one file.`
1748
+ );
1749
+ }
1750
+ }
1751
+ function validateReaderGroups(input, violations) {
1752
+ const groups = knownGroups(input);
1753
+ try {
1754
+ assertGroupCapacity(groups);
1755
+ } catch (error) {
1756
+ addViolation(violations, "docs.json", "too_many_reader_groups", errorMessage(error));
1757
+ }
1758
+ const clash = reservedPageClash(input.pages.map((page) => page.docId), groups.length > 0);
1759
+ if (clash) {
1760
+ const path = input.pages.find((page) => page.docId === clash.docId)?.path ?? `pages/${clash.docId}.mdx`;
1761
+ addViolation(
1762
+ violations,
1763
+ path,
1764
+ "reserved_page_path",
1765
+ `Page "${clash.docId}" occupies ${clash.reserved}/, the path the build reserves for reader-group navigation.`
1766
+ );
1767
+ }
1768
+ }
1769
+ function validateRootPage(input, violations) {
1770
+ if ("versions" in input.config.navigation) return;
1771
+ if ((input.config.redirects ?? []).some((redirect) => normalizedRedirectPath(redirect.source) === "/")) return;
1772
+ if (input.pages.some((page) => page.docId === "index" || page.groups.length === 0)) return;
1773
+ addViolation(
1774
+ violations,
1775
+ "docs.json",
1776
+ "missing_root_page",
1777
+ "docs.json has no redirect for /, there is no pages/index page, and every navigation page has reader groups, so the build has no page to serve at the site address."
1778
+ );
1779
+ }
1780
+ function validateTheme(input, violations) {
1781
+ try {
1782
+ resolveTheme(input.config.theme, input.config.colors, input.config.styling);
1783
+ } catch (error) {
1784
+ const message = error instanceof ThemeError ? `docs.json theme settings are invalid: ${error.problems.join("; ")}.` : errorMessage(error);
1785
+ addViolation(violations, "docs.json", "invalid_theme", message);
1786
+ }
1787
+ if (input.themeCss === null) return;
1788
+ const problems = themeCssProblems(themeCssDecoder.decode(input.themeCss));
1789
+ if (problems.length > 0) addViolation(violations, "public/theme.css", "incompatible_theme_css", problems.join(" "));
1790
+ }
1791
+ function validateBuildRequirements(input, violations) {
1792
+ validateRedirects(input, violations);
1793
+ validateRootPage(input, violations);
1794
+ validateOpenApiNames(input, violations);
1795
+ validateReaderGroups(input, violations);
1796
+ validateTheme(input, violations);
1797
+ }
1798
+ var STRING = "string";
1799
+ var BOOLEAN = "boolean";
1800
+ var HREF = "href";
1801
+ var SRC = "src";
1802
+ var CALLOUT_ATTRIBUTES = { title: STRING, icon: STRING };
1803
+ var COMPONENTS = {
1804
+ Accordion: {
1805
+ attributes: { title: STRING, icon: STRING, defaultOpen: BOOLEAN },
1806
+ required: ["title"]
1807
+ },
1808
+ AccordionGroup: { attributes: {} },
1809
+ AppPreview: {
1810
+ attributes: {
1811
+ url: STRING,
1812
+ query: STRING,
1813
+ tool: STRING,
1814
+ response: STRING,
1815
+ entities: STRING,
1816
+ relationships: STRING
1817
+ },
1818
+ required: ["query", "tool", "response", "entities", "relationships"]
1819
+ },
1820
+ BrandAsset: {
1821
+ attributes: {
1822
+ title: STRING,
1823
+ src: SRC,
1824
+ alt: STRING,
1825
+ surface: ["light", "dark", "neutral"],
1826
+ background: "color",
1827
+ description: STRING,
1828
+ downloadLabel: STRING
1829
+ },
1830
+ required: ["title", "src", "alt"],
1831
+ empty: true
1832
+ },
1833
+ Callout: {
1834
+ attributes: {
1835
+ type: ["note", "info", "tip", "warning", "check", "danger"],
1836
+ title: STRING,
1837
+ icon: STRING
1838
+ }
1839
+ },
1840
+ Card: { attributes: { title: STRING, icon: STRING, href: HREF } },
1841
+ CardGroup: { attributes: { cols: "cols" } },
1842
+ Check: { attributes: CALLOUT_ATTRIBUTES },
1843
+ CodeGroup: { attributes: { label: STRING } },
1844
+ Columns: { attributes: { cols: "cols" } },
1845
+ ColorSwatch: {
1846
+ attributes: { name: STRING, value: "color", usage: STRING },
1847
+ required: ["name", "value"],
1848
+ empty: true
1849
+ },
1850
+ CommandStep: {
1851
+ attributes: { number: STRING, title: STRING, command: STRING },
1852
+ required: ["number", "title", "command"],
1853
+ empty: true
1854
+ },
1855
+ CommandTimeline: { attributes: {} },
1856
+ Danger: { attributes: CALLOUT_ATTRIBUTES },
1857
+ DomainCard: {
1858
+ attributes: { name: STRING, emoji: STRING, domain: STRING, entities: STRING },
1859
+ required: ["name", "emoji", "domain", "entities"],
1860
+ empty: true
1861
+ },
1862
+ DomainCarousel: { attributes: {} },
1863
+ Expandable: {
1864
+ attributes: { title: STRING, defaultOpen: BOOLEAN },
1865
+ required: ["title"]
1866
+ },
1867
+ FooterColumn: { attributes: { title: STRING }, required: ["title"] },
1868
+ Frame: { attributes: { caption: STRING, surface: ["default", "light", "dark"] } },
1869
+ FrameworkCard: {
1870
+ attributes: { title: STRING, support: ["Full Streaming", "Tool Events"] },
1871
+ required: ["title", "support"]
1872
+ },
1873
+ FrameworkGrid: { attributes: {} },
1874
+ Icon: {
1875
+ attributes: { icon: STRING, size: "iconSize" },
1876
+ required: ["icon"],
1877
+ empty: true
1878
+ },
1879
+ Info: { attributes: CALLOUT_ATTRIBUTES },
1880
+ LandingCta: {
1881
+ attributes: {
1882
+ title: STRING,
1883
+ description: STRING,
1884
+ primaryLabel: STRING,
1885
+ primaryHref: HREF,
1886
+ secondaryLabel: STRING,
1887
+ secondaryHref: HREF
1888
+ },
1889
+ required: ["title"]
1890
+ },
1891
+ LandingFooter: {
1892
+ attributes: { name: STRING, logo: SRC, description: STRING },
1893
+ required: ["name"]
1894
+ },
1895
+ LandingHero: {
1896
+ attributes: {
1897
+ title: STRING,
1898
+ description: STRING,
1899
+ eyebrow: STRING,
1900
+ primaryLabel: STRING,
1901
+ primaryHref: HREF,
1902
+ secondaryLabel: STRING,
1903
+ secondaryHref: HREF,
1904
+ align: ["left", "center"],
1905
+ visualMode: ["static", "sequence"],
1906
+ terminalLabel: STRING,
1907
+ previewLabel: STRING
1908
+ },
1909
+ required: ["title"]
1910
+ },
1911
+ LandingSection: {
1912
+ attributes: {
1913
+ title: STRING,
1914
+ description: STRING,
1915
+ eyebrow: STRING,
1916
+ align: ["left", "center"],
1917
+ tone: ["default", "muted", "accent"]
1918
+ },
1919
+ required: ["title"]
1920
+ },
1921
+ MemorySequence: { attributes: {} },
1922
+ MemoryStage: {
1923
+ attributes: {
1924
+ stage: ["short", "long", "reasoning", "connected"],
1925
+ badge: STRING,
1926
+ title: STRING,
1927
+ description: STRING
1928
+ },
1929
+ required: ["stage", "badge", "title", "description"],
1930
+ empty: true
1931
+ },
1932
+ Note: { attributes: CALLOUT_ATTRIBUTES },
1933
+ ParamField: {
1934
+ attributes: {
1935
+ path: STRING,
1936
+ name: STRING,
1937
+ query: STRING,
1938
+ body: STRING,
1939
+ type: STRING,
1940
+ required: BOOLEAN,
1941
+ default: "default"
1942
+ }
1943
+ },
1944
+ PortalCard: {
1945
+ attributes: { title: STRING, icon: STRING, href: HREF, description: STRING },
1946
+ required: ["title", "href"]
1947
+ },
1948
+ ResponseField: {
1949
+ attributes: { name: STRING, type: STRING, required: BOOLEAN },
1950
+ required: ["name"]
1951
+ },
1952
+ Stat: {
1953
+ attributes: {
1954
+ label: STRING,
1955
+ value: "numberOrString",
1956
+ caption: STRING,
1957
+ title: STRING,
1958
+ accent: BOOLEAN,
1959
+ bare: BOOLEAN
1960
+ },
1961
+ required: ["label", "value"]
1962
+ },
1963
+ Step: { attributes: { title: STRING } },
1964
+ Steps: { attributes: {} },
1965
+ Tab: { attributes: { title: STRING }, required: ["title"] },
1966
+ Tabs: { attributes: { label: STRING } },
1967
+ TerminalWindow: { attributes: { title: STRING, command: STRING, variant: ["default", "showcase", "compact"] } },
1968
+ Tip: { attributes: CALLOUT_ATTRIBUTES },
1969
+ TypeSpecimen: {
1970
+ attributes: {
1971
+ family: STRING,
1972
+ role: STRING,
1973
+ weights: STRING,
1974
+ sample: STRING,
1975
+ variant: ["body", "heading", "mono"]
1976
+ },
1977
+ required: ["family", "role", "weights", "sample", "variant"],
1978
+ empty: true
1979
+ },
1980
+ UsageExample: {
1981
+ attributes: { verdict: ["do", "dont"], title: STRING },
1982
+ required: ["verdict", "title"]
1983
+ },
1984
+ Video: {
1985
+ attributes: {
1986
+ src: SRC,
1987
+ title: STRING,
1988
+ summary: STRING,
1989
+ caption: STRING,
1990
+ poster: SRC,
1991
+ kind: ["auto", "video", "iframe"]
1992
+ },
1993
+ required: ["src", "title"]
1994
+ },
1995
+ Warning: { attributes: CALLOUT_ATTRIBUTES }
1996
+ };
1997
+ var NATIVE_ELEMENTS = {
1998
+ img: {
1999
+ attributes: { src: SRC, alt: STRING, width: "dimension", height: "dimension" },
2000
+ required: ["src"],
2001
+ empty: true
2002
+ },
2003
+ kbd: { attributes: {} }
2004
+ };
2005
+ var STANDARD_NODES = /* @__PURE__ */ new Set([
2006
+ "blockquote",
2007
+ "break",
2008
+ "code",
2009
+ "definition",
2010
+ "delete",
2011
+ "emphasis",
2012
+ "heading",
2013
+ "image",
2014
+ "imageReference",
2015
+ "inlineCode",
2016
+ "link",
2017
+ "linkReference",
2018
+ "list",
2019
+ "listItem",
2020
+ "paragraph",
2021
+ "root",
2022
+ "strong",
2023
+ "table",
2024
+ "tableCell",
2025
+ "tableRow",
2026
+ "text",
2027
+ "thematicBreak"
2028
+ ]);
2029
+ var markdownParser = unified().use(remarkParse).use(remarkGfm);
2030
+ var mdxParser = unified().use(remarkParse).use(remarkMdx).use(remarkGfm);
2031
+ function issue(message) {
2032
+ return { code: "inadmissible_page_content", message };
2033
+ }
2034
+ function expressionValue(attribute) {
2035
+ return attribute.value && typeof attribute.value === "object" ? attribute.value.value : null;
2036
+ }
2037
+ function directBoolean(attribute) {
2038
+ if (attribute.value === null) return true;
2039
+ const value = expressionValue(attribute);
2040
+ return value === "true" || value === "false";
2041
+ }
2042
+ function directNumber(attribute) {
2043
+ const value = expressionValue(attribute);
2044
+ if (value === null || !/^(?:0|[1-9]\d*)(?:\.\d+)?$/.test(value)) return null;
2045
+ const number = Number(value);
2046
+ return Number.isFinite(number) ? number : null;
2047
+ }
2048
+ function safeUrl(raw, context) {
2049
+ if (raw.length === 0 || raw.trim() !== raw || /[\u0000-\u001f\u007f]/.test(raw) || /\s/u.test(raw) || raw.includes("\\") || raw.startsWith("//")) {
2050
+ return false;
2051
+ }
2052
+ if (raw.startsWith("/") || raw.startsWith("./") || raw.startsWith("../") || raw.startsWith("#") || raw.startsWith("?")) {
2053
+ return true;
2054
+ }
2055
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(raw)?.[1]?.toLowerCase();
2056
+ if (scheme !== void 0) {
2057
+ return scheme === "http" || scheme === "https" || context === "href" && scheme === "mailto";
2058
+ }
2059
+ return !raw.includes(":");
2060
+ }
2061
+ function validAttribute(attribute, kind) {
2062
+ if (attribute.type !== "mdxJsxAttribute") return false;
2063
+ if (kind === "boolean") return directBoolean(attribute);
2064
+ if (kind === "color") {
2065
+ return typeof attribute.value === "string" && /^#[0-9A-Fa-f]{6}$/.test(attribute.value);
2066
+ }
2067
+ if (kind === "cols") {
2068
+ const value = directNumber(attribute);
2069
+ return value !== null && Number.isInteger(value) && value >= 1 && value <= 6;
2070
+ }
2071
+ if (kind === "default") {
2072
+ return typeof attribute.value === "string" || directBoolean(attribute) || directNumber(attribute) !== null;
2073
+ }
2074
+ if (kind === "numberOrString") {
2075
+ return typeof attribute.value === "string" || directNumber(attribute) !== null;
2076
+ }
2077
+ if (kind === "dimension") {
2078
+ if (typeof attribute.value === "string") return /^(?:0|[1-9]\d*)$/.test(attribute.value);
2079
+ const value = directNumber(attribute);
2080
+ return value !== null && Number.isInteger(value) && value >= 0;
2081
+ }
2082
+ if (kind === "iconSize") {
2083
+ if (typeof attribute.value === "string") {
2084
+ const match = /^(0|(?:0|[1-9]\d*)(?:\.\d+)?)(px|rem|em)?$/.exec(attribute.value);
2085
+ return match !== null && Number(match[1]) <= 512;
2086
+ }
2087
+ const value = directNumber(attribute);
2088
+ return value !== null && value >= 0 && value <= 512;
2089
+ }
2090
+ if (kind === "href" || kind === "src") {
2091
+ return typeof attribute.value === "string" && safeUrl(attribute.value, kind);
2092
+ }
2093
+ if (kind === "string") return typeof attribute.value === "string";
2094
+ return typeof attribute.value === "string" && kind.includes(attribute.value);
2095
+ }
2096
+ function validateElement(node) {
2097
+ if (node.name === null || node.name === void 0) return issue("MDX fragments are not admissible");
2098
+ const policy = COMPONENTS[node.name] ?? NATIVE_ELEMENTS[node.name];
2099
+ if (policy === void 0) return issue(`element ${node.name} is not admissible`);
2100
+ const seen = /* @__PURE__ */ new Set();
2101
+ for (const attribute of node.attributes ?? []) {
2102
+ if (attribute.type !== "mdxJsxAttribute" || attribute.name === void 0) {
2103
+ return issue(`spread attributes are not admissible on ${node.name}`);
2104
+ }
2105
+ if (seen.has(attribute.name)) return issue(`duplicate attribute ${attribute.name} on ${node.name}`);
2106
+ seen.add(attribute.name);
2107
+ const kind = policy.attributes[attribute.name];
2108
+ if (kind === void 0) return issue(`attribute ${attribute.name} is not admissible on ${node.name}`);
2109
+ if (!validAttribute(attribute, kind)) {
2110
+ return issue(`attribute ${attribute.name} has an inadmissible value on ${node.name}`);
2111
+ }
2112
+ }
2113
+ for (const required of policy.required ?? []) {
2114
+ if (!seen.has(required)) return issue(`attribute ${required} is required on ${node.name}`);
2115
+ }
2116
+ if (policy.empty && (node.children?.length ?? 0) > 0) return issue(`${node.name} must not have children`);
2117
+ return null;
2118
+ }
2119
+ function validatePageSource(path, source, policy = {}) {
2120
+ let tree;
2121
+ try {
2122
+ tree = (path.toLowerCase().endsWith(".mdx") ? mdxParser : markdownParser).parse(source);
2123
+ } catch (error) {
2124
+ return {
2125
+ code: "invalid_page_syntax",
2126
+ message: error instanceof Error ? error.message : String(error)
2127
+ };
2128
+ }
2129
+ const definitions = /* @__PURE__ */ new Map();
2130
+ const collectDefinitions = (node) => {
2131
+ if (node.type === "definition" && node.identifier !== void 0 && node.url !== void 0) {
2132
+ definitions.set(node.identifier, node.url);
2133
+ }
2134
+ for (const child of node.children ?? []) collectDefinitions(child);
2135
+ };
2136
+ collectDefinitions(tree);
2137
+ const visit = (node) => {
2138
+ if (node.type === "heading" && node.depth === 1 && policy.allowLevelOneHeading === false) {
2139
+ return {
2140
+ code: "page_heading_conflict",
2141
+ message: "standard documentation pages receive their level-one heading from frontmatter title; remove the authored level-one heading or set pageHeader: false when the page owns its title"
2142
+ };
2143
+ }
2144
+ if (node.type === "mdxjsEsm") return issue("ESM is not admissible in page source");
2145
+ if (node.type === "mdxFlowExpression" || node.type === "mdxTextExpression") {
2146
+ return issue("MDX expressions are not admissible in page content");
2147
+ }
2148
+ if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") {
2149
+ const elementIssue = validateElement(node);
2150
+ if (elementIssue !== null) return elementIssue;
2151
+ } else if (node.type === "html") {
2152
+ return issue("raw HTML is not admissible in page source");
2153
+ } else if (!STANDARD_NODES.has(node.type)) {
2154
+ return issue(`syntax node ${node.type} is not admissible`);
2155
+ }
2156
+ if ((node.type === "link" || node.type === "definition") && node.url !== void 0) {
2157
+ if (!safeUrl(node.url, "href")) return issue(`URL scheme is not admissible: ${node.url}`);
2158
+ }
2159
+ if (node.type === "image" && node.url !== void 0 && !safeUrl(node.url, "src")) {
2160
+ return issue(`image URL scheme is not admissible: ${node.url}`);
2161
+ }
2162
+ if (node.type === "linkReference" && node.identifier !== void 0) {
2163
+ const url = definitions.get(node.identifier);
2164
+ if (url !== void 0 && !safeUrl(url, "href")) return issue(`URL scheme is not admissible: ${url}`);
2165
+ }
2166
+ if (node.type === "imageReference" && node.identifier !== void 0) {
2167
+ const url = definitions.get(node.identifier);
2168
+ if (url !== void 0 && !safeUrl(url, "src")) return issue(`image URL scheme is not admissible: ${url}`);
2169
+ }
2170
+ for (const child of node.children ?? []) {
2171
+ const childIssue = visit(child);
2172
+ if (childIssue !== null) return childIssue;
2173
+ }
2174
+ return null;
2175
+ };
2176
+ return visit(tree);
2177
+ }
2178
+ function pageSourceComponents() {
2179
+ return Object.entries(COMPONENTS).map(([name, policy]) => ({
2180
+ name,
2181
+ attributes: Object.fromEntries(
2182
+ Object.entries(policy.attributes).map(([attribute, kind]) => [
2183
+ attribute,
2184
+ typeof kind === "string" ? kind : [...kind]
2185
+ ])
2186
+ ),
2187
+ required: [...policy.required ?? []],
2188
+ empty: policy.empty === true
2189
+ }));
2190
+ }
2191
+ var RUNBOOK_MIN_STEPS = 3;
2192
+ var RUNBOOK_MAX_STEPS = 8;
2193
+ var RUNBOOK_MAX_STEP_WORDS = 40;
2194
+ var RUNBOOK_TARGETS = ["code", "workspace"];
2195
+ var RUNBOOK_KEYS = ["goal", "prerequisites", "steps", "expected", "verify", "target"];
2196
+ var RUNBOOK_KEY_SET = new Set(RUNBOOK_KEYS);
2197
+ var LINE_BREAK = /[\r\n]/;
2198
+ var CONTROL_CHARACTER = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
2199
+ function isRecord(value) {
2200
+ return value !== null && typeof value === "object" && !Array.isArray(value);
2201
+ }
2202
+ function filledString(value) {
2203
+ return typeof value === "string" && value.trim().length > 0;
2204
+ }
2205
+ function wordCount(value) {
2206
+ return value.trim().split(/\s+/).length;
2207
+ }
2208
+ function proseProblems(value, field) {
2209
+ const problems = [];
2210
+ if (LINE_BREAK.test(value)) {
2211
+ problems.push(
2212
+ `runbook.${field} must not contain a line break. Move long context into the page body.`
2213
+ );
2214
+ }
2215
+ if (CONTROL_CHARACTER.test(value)) {
2216
+ problems.push(`runbook.${field} must not contain a control character.`);
2217
+ }
2218
+ return problems;
2219
+ }
2220
+ function stringListProblems(value, field) {
2221
+ if (!Array.isArray(value)) return [`runbook.${field} must be a list of strings.`];
2222
+ return value.flatMap(
2223
+ (entry, index) => filledString(entry) ? [] : [`runbook.${field}[${index}] must be a non-empty string.`]
2224
+ );
2225
+ }
2226
+ function runbookProblems(value) {
2227
+ if (!isRecord(value)) return ["runbook must be an object with goal, steps, expected, and verify."];
2228
+ const problems = [];
2229
+ for (const key of Object.keys(value)) {
2230
+ if (!RUNBOOK_KEY_SET.has(key)) {
2231
+ problems.push(
2232
+ `runbook.${key} is not a runbook field. Allowed fields: ${RUNBOOK_KEYS.join(", ")}.`
2233
+ );
2234
+ }
2235
+ }
2236
+ for (const field of ["goal", "expected", "verify"]) {
2237
+ const entry = value[field];
2238
+ if (!filledString(entry)) {
2239
+ problems.push(`runbook.${field} is required and must be a non-empty string.`);
2240
+ continue;
2241
+ }
2242
+ problems.push(...proseProblems(entry, field));
2243
+ }
2244
+ if (value["prerequisites"] !== void 0) {
2245
+ const listProblems = stringListProblems(value["prerequisites"], "prerequisites");
2246
+ problems.push(...listProblems);
2247
+ if (listProblems.length === 0) {
2248
+ for (const [index, entry] of value["prerequisites"].entries()) {
2249
+ problems.push(...proseProblems(entry, `prerequisites[${index}]`));
2250
+ }
2251
+ }
2252
+ }
2253
+ if (value["steps"] === void 0) {
2254
+ problems.push("runbook.steps is required and must be a list of strings.");
2255
+ } else {
2256
+ const listProblems = stringListProblems(value["steps"], "steps");
2257
+ problems.push(...listProblems);
2258
+ if (listProblems.length === 0) {
2259
+ const steps = value["steps"];
2260
+ if (steps.length < RUNBOOK_MIN_STEPS || steps.length > RUNBOOK_MAX_STEPS) {
2261
+ problems.push(
2262
+ `runbook.steps must hold ${RUNBOOK_MIN_STEPS} to ${RUNBOOK_MAX_STEPS} steps, not ${steps.length}. Move long context into the page body.`
2263
+ );
2264
+ }
2265
+ for (const [index, step] of steps.entries()) {
2266
+ problems.push(...proseProblems(step, `steps[${index}]`));
2267
+ if (wordCount(step) > RUNBOOK_MAX_STEP_WORDS) {
2268
+ problems.push(
2269
+ `runbook.steps[${index}] is ${wordCount(step)} words. A step may hold at most ${RUNBOOK_MAX_STEP_WORDS} words.`
2270
+ );
2271
+ }
2272
+ }
2273
+ }
2274
+ }
2275
+ const target = value["target"];
2276
+ if (target !== void 0 && !RUNBOOK_TARGETS.includes(target)) {
2277
+ problems.push(`runbook.target must be ${RUNBOOK_TARGETS.join(" or ")}.`);
2278
+ }
2279
+ return problems;
2280
+ }
2281
+ var fatalUtf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
2282
+ var boundedUtf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
2283
+ var textEncoder3 = new TextEncoder();
2284
+ function errorMessage2(error) {
2285
+ return error instanceof Error ? error.message : String(error);
2286
+ }
2287
+ function addViolation2(violations, path, code, message, severity = "error") {
2288
+ violations.push({ path, code, severity, message });
2289
+ }
2290
+ function decodeUtf8(bytes, path, violations, maxBytes) {
2291
+ if (maxBytes !== void 0 && bytes.byteLength > maxBytes) {
2292
+ addViolation2(
2293
+ violations,
2294
+ path,
2295
+ "semantic_input_too_large",
2296
+ `${path} exceeds ${maxBytes} bytes`
2297
+ );
2298
+ return null;
2299
+ }
2300
+ try {
2301
+ const source = fatalUtf8Decoder.decode(bytes);
2302
+ if (source.startsWith("\uFEFF")) {
2303
+ addViolation2(violations, path, "invalid_utf8", `${path} must not begin with a UTF-8 BOM`);
2304
+ return null;
2305
+ }
2306
+ return source;
2307
+ } catch (error) {
2308
+ addViolation2(
2309
+ violations,
2310
+ path,
2311
+ "invalid_utf8",
2312
+ `${path} is not valid UTF-8: ${errorMessage2(error)}`
2313
+ );
2314
+ return null;
2315
+ }
2316
+ }
2317
+ function readSemanticFile(input, path, violations) {
2318
+ try {
2319
+ const bytes = input.readFile(path);
2320
+ return bytes === null ? { present: false, bytes: null } : { present: true, bytes };
2321
+ } catch (error) {
2322
+ addViolation2(violations, path, "read_error", errorMessage2(error));
2323
+ return { present: true, bytes: null };
2324
+ }
2325
+ }
2326
+ async function readSemanticFileAsync(input, path, violations) {
2327
+ try {
2328
+ const bytes = await input.readFile(path);
2329
+ return bytes === null ? { present: false, bytes: null } : { present: true, bytes };
2330
+ } catch (error) {
2331
+ addViolation2(violations, path, "read_error", errorMessage2(error));
2332
+ return { present: true, bytes: null };
2333
+ }
2334
+ }
2335
+ function parseDocsJson(bytes, violations) {
2336
+ const source = decodeUtf8(bytes, "docs.json", violations, SOURCE_LIMITS.maxDocsJsonBytes);
2337
+ if (source === null) return null;
2338
+ try {
2339
+ const document = parseDocument(source, { schema: "json", uniqueKeys: true });
2340
+ if (document.errors.length > 0) throw document.errors[0];
2341
+ } catch (error) {
2342
+ addViolation2(
2343
+ violations,
2344
+ "docs.json",
2345
+ "invalid_docs_json",
2346
+ `docs.json has duplicate keys or invalid JSON structure: ${errorMessage2(error)}`
2347
+ );
2348
+ return null;
2349
+ }
2350
+ let parsed;
2351
+ try {
2352
+ parsed = JSON.parse(source);
2353
+ } catch (error) {
2354
+ addViolation2(
2355
+ violations,
2356
+ "docs.json",
2357
+ "invalid_docs_json",
2358
+ `docs.json is not valid JSON: ${errorMessage2(error)}`
2359
+ );
2360
+ return null;
2361
+ }
2362
+ let config;
2363
+ try {
2364
+ config = parseDocsConfig(parsed);
2365
+ } catch (error) {
2366
+ addViolation2(violations, "docs.json", "invalid_docs_json", errorMessage2(error));
2367
+ return null;
2368
+ }
2369
+ if (config.siteUrl !== void 0) {
2370
+ addViolation2(violations, "docs.json", "deprecated_site_url", "siteUrl is ignored: the dashboard sets the site address", "warning");
2371
+ }
2372
+ return config;
2373
+ }
2374
+ var ADMISSIBLE_FRONTMATTER_KEYS = ["title", "description", "pageLayout", "groups", "pagefind", "noindex", "public", "pageHeader", "runbook"];
2375
+ function frontmatterPolicy(bytes) {
2376
+ let openingLength = 0;
2377
+ if (bytes[0] === 45 && bytes[1] === 45 && bytes[2] === 45) {
2378
+ let index = 3;
2379
+ while (bytes[index] === 32 || bytes[index] === 9) index += 1;
2380
+ if (bytes[index] === 10) openingLength = index + 1;
2381
+ else if (bytes[index] === 13 && bytes[index + 1] === 10) openingLength = index + 2;
2382
+ else if (index < bytes.byteLength) throw new Error("frontmatter opening marker is malformed");
2383
+ }
2384
+ if (openingLength === 0) {
2385
+ return {
2386
+ grouped: false,
2387
+ groups: [],
2388
+ pagefindFalse: false,
2389
+ pageLayout: "docs",
2390
+ pageHeader: true,
2391
+ bodyOffset: 0
2392
+ };
2393
+ }
2394
+ const searchEnd = Math.min(
2395
+ bytes.byteLength,
2396
+ openingLength + SOURCE_LIMITS.maxFrontmatterBytes
2397
+ );
2398
+ const bounded = boundedUtf8Decoder.decode(bytes.subarray(openingLength, searchEnd));
2399
+ const closing = /(?:^|\r?\n)---[\t ]*(?:\r?\n|$)/.exec(bounded);
2400
+ if (!closing) {
2401
+ throw new Error(
2402
+ `frontmatter closing marker was not found within ${SOURCE_LIMITS.maxFrontmatterBytes} bytes`
2403
+ );
2404
+ }
2405
+ const block = bounded.slice(0, closing.index);
2406
+ if (textEncoder3.encode(block).byteLength > SOURCE_LIMITS.maxFrontmatterBytes) {
2407
+ throw new Error(`frontmatter exceeds ${SOURCE_LIMITS.maxFrontmatterBytes} bytes`);
2408
+ }
2409
+ const bodyOffset = openingLength + textEncoder3.encode(bounded.slice(0, closing.index + closing[0].length)).byteLength;
2410
+ const parsed = parse2(block, {
2411
+ maxAliasCount: 0,
2412
+ schema: "core",
2413
+ uniqueKeys: true
2414
+ });
2415
+ if (parsed === null || parsed === void 0) {
2416
+ return {
2417
+ grouped: false,
2418
+ groups: [],
2419
+ pagefindFalse: false,
2420
+ pageLayout: "docs",
2421
+ pageHeader: true,
2422
+ bodyOffset
2423
+ };
2424
+ }
2425
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
2426
+ throw new Error("frontmatter must be a top-level YAML mapping");
2427
+ }
2428
+ const record = parsed;
2429
+ const allowed = new Set(ADMISSIBLE_FRONTMATTER_KEYS);
2430
+ for (const key of Object.keys(record)) {
2431
+ if (!allowed.has(key)) throw new Error(`frontmatter key is not admissible: ${key}`);
2432
+ }
2433
+ for (const key of ["title", "description"]) {
2434
+ if (record[key] !== void 0 && typeof record[key] !== "string") {
2435
+ throw new Error(`frontmatter ${key} must be a string`);
2436
+ }
2437
+ }
2438
+ if (record["pageLayout"] !== void 0 && !["docs", "landing"].includes(String(record["pageLayout"]))) {
2439
+ throw new Error("frontmatter pageLayout must be docs or landing");
2440
+ }
2441
+ if (record["groups"] !== void 0 && (!Array.isArray(record["groups"]) || record["groups"].some((group) => typeof group !== "string"))) {
2442
+ throw new Error("frontmatter groups must be an array of strings");
2443
+ }
2444
+ for (const key of ["pagefind", "noindex", "public", "pageHeader"]) {
2445
+ if (record[key] !== void 0 && typeof record[key] !== "boolean") {
2446
+ throw new Error(`frontmatter ${key} must be a boolean`);
2447
+ }
2448
+ }
2449
+ if (record["runbook"] !== void 0) {
2450
+ const problems = runbookProblems(record["runbook"]);
2451
+ if (problems.length > 0) {
2452
+ throw new Error(`frontmatter runbook is invalid: ${problems.join(" ")}`);
2453
+ }
2454
+ }
2455
+ return {
2456
+ grouped: Array.isArray(record["groups"]) && record["groups"].length > 0,
2457
+ groups: Array.isArray(record["groups"]) ? record["groups"] : [],
2458
+ pagefindFalse: record["pagefind"] === false,
2459
+ pageLayout: record["pageLayout"] === "landing" ? "landing" : "docs",
2460
+ pageHeader: record["pageHeader"] !== false,
2461
+ bodyOffset
2462
+ };
2463
+ }
2464
+ function pageCandidates(entry) {
2465
+ const mdx = `pages/${entry}.mdx`;
2466
+ const md = `pages/${entry}.md`;
2467
+ if (canonicalizeSourcePath(mdx) !== mdx || canonicalizeSourcePath(md) !== md) return null;
2468
+ return { mdx, md };
2469
+ }
2470
+ function isRecord2(value) {
2471
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2472
+ }
2473
+ function hasExternalRef(value, seen = /* @__PURE__ */ new Set()) {
2474
+ if (typeof value !== "object" || value === null) return false;
2475
+ if (seen.has(value)) return false;
2476
+ seen.add(value);
2477
+ if (Array.isArray(value)) return value.some((item) => hasExternalRef(item, seen));
2478
+ for (const [key, child] of Object.entries(value)) {
2479
+ if (key === "$ref" && typeof child === "string") {
2480
+ const hash = child.indexOf("#");
2481
+ const filePart = hash === -1 ? child : child.slice(0, hash);
2482
+ if (filePart.length > 0) return true;
2483
+ }
2484
+ if (hasExternalRef(child, seen)) return true;
2485
+ }
2486
+ return false;
2487
+ }
2488
+ function validateOpenApiDocument(source) {
2489
+ const document = parse2(source, {
2490
+ maxAliasCount: 0,
2491
+ schema: "core",
2492
+ uniqueKeys: true
2493
+ });
2494
+ if (!isRecord2(document)) throw new Error("OpenAPI document must be an object");
2495
+ const isOpenApi3 = typeof document["openapi"] === "string" && /^3\./.test(document["openapi"]);
2496
+ const isSwagger2 = document["swagger"] === "2.0";
2497
+ if (!isOpenApi3 && !isSwagger2) {
2498
+ throw new Error("document must declare top-level openapi 3.x or swagger 2.0");
2499
+ }
2500
+ if (hasExternalRef(document)) {
2501
+ throw new Error(`external OpenAPI $ref values are not admissible in source ABI v${SOURCE_ABI_VERSION}`);
2502
+ }
2503
+ return parseOpenApi(source);
2504
+ }
2505
+ function prepareSemanticValidation(input) {
2506
+ const violations = [];
2507
+ const config = parseDocsJson(input.docsJson, violations);
2508
+ if (config === null) return { config, pagePaths: [], pagePathSet: /* @__PURE__ */ new Set(), violations };
2509
+ if (input.modelsToml !== void 0) {
2510
+ const source = decodeUtf8(
2511
+ input.modelsToml,
2512
+ "models.toml",
2513
+ violations,
2514
+ SOURCE_LIMITS.maxModelsTomlBytes
2515
+ );
2516
+ if (source !== null) {
2517
+ try {
2518
+ parseModelsConfig(source);
2519
+ } catch (error) {
2520
+ addViolation2(violations, "models.toml", "invalid_models_toml", errorMessage2(error));
2521
+ }
2522
+ }
2523
+ }
2524
+ const pagePaths = [...input.pagePaths].sort();
2525
+ const pagePathSet = /* @__PURE__ */ new Set();
2526
+ for (const path of pagePaths) {
2527
+ const extension = sourceExtension(path);
2528
+ if (pagePathSet.has(path) || !path.startsWith("pages/") || canonicalizeSourcePath(path) !== path || extension !== ".md" && extension !== ".mdx") {
2529
+ addViolation2(
2530
+ violations,
2531
+ path,
2532
+ "inadmissible_page_content",
2533
+ `page path is not a unique canonical page source path: ${path}`
2534
+ );
2535
+ continue;
2536
+ }
2537
+ pagePathSet.add(path);
2538
+ }
2539
+ return { config, pagePaths, pagePathSet, violations };
2540
+ }
2541
+ function validatePageBytes(path, bytes, violations) {
2542
+ const source = decodeUtf8(bytes, path, violations);
2543
+ if (source === null) return [];
2544
+ try {
2545
+ const policy = frontmatterPolicy(bytes);
2546
+ if (policy.grouped && !policy.pagefindFalse) {
2547
+ addViolation2(
2548
+ violations,
2549
+ path,
2550
+ "pagefind_required",
2551
+ "grouped pages must set pagefind: false"
2552
+ );
2553
+ }
2554
+ const body = fatalUtf8Decoder.decode(bytes.subarray(policy.bodyOffset));
2555
+ const pageIssue = validatePageSource(path, body, {
2556
+ allowLevelOneHeading: policy.pageLayout === "landing" || !policy.pageHeader
2557
+ });
2558
+ if (pageIssue !== null) addViolation2(violations, path, pageIssue.code, pageIssue.message);
2559
+ return policy.groups;
2560
+ } catch (error) {
2561
+ addViolation2(violations, path, "invalid_frontmatter", errorMessage2(error));
2562
+ return [];
2563
+ }
2564
+ }
2565
+ function validateNavigation(config, prepared) {
2566
+ const { pagePaths, pagePathSet, violations } = prepared;
2567
+ const pages = new Set(navigationGroups(config).flatMap((group) => group.pages));
2568
+ const referencedPagePaths = /* @__PURE__ */ new Set();
2569
+ for (const entry of pages) {
2570
+ const candidates = pageCandidates(entry);
2571
+ if (!candidates) {
2572
+ addViolation2(
2573
+ violations,
2574
+ "docs.json",
2575
+ "invalid_navigation_path",
2576
+ `navigation page is not a canonical source path: ${entry}`
2577
+ );
2578
+ continue;
2579
+ }
2580
+ const hasMdx = pagePathSet.has(candidates.mdx);
2581
+ const hasMd = pagePathSet.has(candidates.md);
2582
+ if (hasMdx) referencedPagePaths.add(candidates.mdx);
2583
+ if (hasMd) referencedPagePaths.add(candidates.md);
2584
+ if (hasMdx && hasMd) {
2585
+ addViolation2(
2586
+ violations,
2587
+ candidates.mdx,
2588
+ "md_mdx_collision",
2589
+ `navigation page resolves to both ${candidates.mdx} and ${candidates.md}`
2590
+ );
2591
+ continue;
2592
+ }
2593
+ if (!hasMdx && !hasMd) {
2594
+ addViolation2(
2595
+ violations,
2596
+ candidates.mdx,
2597
+ "missing_page",
2598
+ `navigation page ${entry} has no .mdx or .md source file`
2599
+ );
2600
+ }
2601
+ }
2602
+ for (const path of pagePaths) {
2603
+ if (!referencedPagePaths.has(path)) {
2604
+ addViolation2(
2605
+ violations,
2606
+ path,
2607
+ "unreferenced_page",
2608
+ `page source is not referenced by docs.json navigation: ${path}`
2609
+ );
2610
+ }
2611
+ }
2612
+ }
2613
+ function openApiPaths(config, violations) {
2614
+ const valid = [];
2615
+ const paths = new Set(
2616
+ navigationGroups(config).map((group) => group.openapi).filter((path) => path !== void 0)
2617
+ );
2618
+ for (const path of paths) {
2619
+ const extension = sourceExtension(path);
2620
+ if (!path.startsWith("openapi/") || canonicalizeSourcePath(path) !== path || extension !== ".json" && extension !== ".yaml" && extension !== ".yml") {
2621
+ addViolation2(
2622
+ violations,
2623
+ "docs.json",
2624
+ "invalid_openapi_path",
2625
+ `OpenAPI path must be a canonical openapi/** path: ${path}`
2626
+ );
2627
+ } else {
2628
+ valid.push(path);
2629
+ }
2630
+ }
2631
+ return valid;
2632
+ }
2633
+ function validateOpenApiBytes(path, bytes, violations) {
2634
+ const source = decodeUtf8(bytes, path, violations, SOURCE_LIMITS.maxOpenApiBytes);
2635
+ if (source === null) return null;
2636
+ try {
2637
+ return validateOpenApiDocument(source).operations.map((operation) => operation.slug);
2638
+ } catch (error) {
2639
+ addViolation2(violations, path, "invalid_openapi", errorMessage2(error));
2640
+ return null;
2641
+ }
2642
+ }
2643
+ function validateBundleSemantics(input) {
2644
+ const prepared = prepareSemanticValidation(input);
2645
+ if (!prepared.config) return sortViolations(prepared.violations);
2646
+ const groupsByPath = /* @__PURE__ */ new Map();
2647
+ for (const path of prepared.pagePaths) {
2648
+ if (!prepared.pagePathSet.has(path)) continue;
2649
+ const read = readSemanticFile(input, path, prepared.violations);
2650
+ if (!read.present) {
2651
+ addViolation2(prepared.violations, path, "read_error", "listed page source is missing");
2652
+ continue;
2653
+ }
2654
+ if (read.bytes === null) continue;
2655
+ groupsByPath.set(path, validatePageBytes(path, read.bytes, prepared.violations));
2656
+ }
2657
+ validateNavigation(prepared.config, prepared);
2658
+ const operationSlugsBySpec = /* @__PURE__ */ new Map();
2659
+ for (const path of openApiPaths(prepared.config, prepared.violations)) {
2660
+ const read = readSemanticFile(input, path, prepared.violations);
2661
+ if (!read.present) {
2662
+ addViolation2(prepared.violations, path, "missing_openapi", "referenced OpenAPI file is missing");
2663
+ continue;
2664
+ }
2665
+ if (read.bytes === null) continue;
2666
+ const slugs = validateOpenApiBytes(path, read.bytes, prepared.violations);
2667
+ if (slugs !== null) operationSlugsBySpec.set(path, slugs);
2668
+ }
2669
+ validateBuildRequirements({
2670
+ config: prepared.config,
2671
+ pages: buildRequirementPages(prepared.config, groupsByPath),
2672
+ operationSlugsBySpec,
2673
+ themeCss: readSemanticFile(input, "public/theme.css", prepared.violations).bytes
2674
+ }, prepared.violations);
2675
+ return sortViolations(prepared.violations);
2676
+ }
2677
+ async function validateBundleSemanticsAsync(input) {
2678
+ const prepared = prepareSemanticValidation(input);
2679
+ if (!prepared.config) return sortViolations(prepared.violations);
2680
+ const groupsByPath = /* @__PURE__ */ new Map();
2681
+ for (const path of prepared.pagePaths) {
2682
+ if (!prepared.pagePathSet.has(path)) continue;
2683
+ const read = await readSemanticFileAsync(input, path, prepared.violations);
2684
+ if (!read.present) {
2685
+ addViolation2(prepared.violations, path, "read_error", "listed page source is missing");
2686
+ continue;
2687
+ }
2688
+ if (read.bytes !== null) groupsByPath.set(path, validatePageBytes(path, read.bytes, prepared.violations));
2689
+ }
2690
+ validateNavigation(prepared.config, prepared);
2691
+ const operationSlugsBySpec = /* @__PURE__ */ new Map();
2692
+ for (const path of openApiPaths(prepared.config, prepared.violations)) {
2693
+ const read = await readSemanticFileAsync(input, path, prepared.violations);
2694
+ if (!read.present) {
2695
+ addViolation2(prepared.violations, path, "missing_openapi", "referenced OpenAPI file is missing");
2696
+ continue;
2697
+ }
2698
+ const slugs = read.bytes === null ? null : validateOpenApiBytes(path, read.bytes, prepared.violations);
2699
+ if (slugs !== null) operationSlugsBySpec.set(path, slugs);
2700
+ }
2701
+ validateBuildRequirements({
2702
+ config: prepared.config,
2703
+ pages: buildRequirementPages(prepared.config, groupsByPath),
2704
+ operationSlugsBySpec,
2705
+ themeCss: (await readSemanticFileAsync(input, "public/theme.css", prepared.violations)).bytes
2706
+ }, prepared.violations);
2707
+ return sortViolations(prepared.violations);
2708
+ }
2709
+ var MIB = 1048576;
2710
+ var KIB = 1024;
2711
+ var VIOLATION_GUIDANCE = Object.freeze({
2712
+ archive_rejected: {
2713
+ requirement: `The source archive could not be read safely. The whole repository, not only the docs folder, must hold only regular files and folders: no symbolic links, hard links, or device files. The docs folder must also stay within ${SOURCE_LIMITS.maxFileCount} files and ${SOURCE_LIMITS.maxTotalBytes / MIB} MiB. Exclude a link you need to keep with export-ignore in .gitattributes.`,
2714
+ example: "tools/current export-ignore (a line in .gitattributes at the repository root)"
2715
+ },
2716
+ build_failed: {
2717
+ requirement: "The documentation build stopped on this error after the source passed validation. Fix the file or setting the message names, then push the change again."
2718
+ },
2719
+ incompatible_theme_css: {
2720
+ requirement: "public/theme.css must not reference #gs-ask-ai, .gs-ai-panel or data-astro-transition-persist, must not combine gs-ask, width and !important on one line, and must not set position: fixed on .gs-header.",
2721
+ example: ".gs-header { position: sticky; } (not position: fixed)"
2722
+ },
2723
+ invalid_git_commit: {
2724
+ requirement: "The build must name a full commit SHA. Build the latest commit again; if this repeats, contact SaturnDocs support."
2725
+ },
2726
+ too_many_files: {
2727
+ requirement: `The docs folder can hold at most ${SOURCE_LIMITS.maxFileCount} files. Remove files the site does not serve.`
2728
+ },
2729
+ invalid_size: {
2730
+ requirement: "Every source file must have a readable size. Commit the file again; if this repeats, contact SaturnDocs support."
2731
+ },
2732
+ invalid_path: {
2733
+ requirement: `File and folder names may use only letters, digits, dots, hyphens, and underscores, must start with a letter or digit, and must not end with a dot. A path can be at most ${SOURCE_LIMITS.maxPathBytes} bytes.`,
2734
+ example: "pages/getting-started.mdx (not pages/Getting Started.mdx)"
2735
+ },
2736
+ path_too_deep: {
2737
+ requirement: `A path can be at most ${SOURCE_LIMITS.maxPathDepth} folders deep. Move the file to a shallower folder.`
2738
+ },
2739
+ file_too_large: {
2740
+ requirement: `Each file can be at most ${SOURCE_LIMITS.maxFileBytes / MIB} MiB. Compress the file or host it elsewhere and link to it.`
2741
+ },
2742
+ theme_css_too_large: {
2743
+ requirement: `public/theme.css can be at most ${SOURCE_LIMITS.maxThemeCssBytes / KIB} KiB. Remove unused rules.`
2744
+ },
2745
+ inadmissible_type: {
2746
+ requirement: "This file type is not allowed in this folder. Pages are .md or .mdx under pages/, API specs are .json, .yaml, or .yml under openapi/, and images, fonts, media, and CSS go under public/.",
2747
+ example: "public/logo.png (not pages/logo.png)"
2748
+ },
2749
+ unknown_root: {
2750
+ requirement: "Only docs.json, models.toml, and the pages/, public/, and openapi/ folders are read. Move the file into one of those folders or delete it.",
2751
+ example: "pages/guides/install.mdx (not guides/install.mdx)"
2752
+ },
2753
+ generated_artifact: {
2754
+ requirement: "Build output is not source. Delete generated folders and files (dist/, pagefind/, _astro/, node_modules/, sitemap files, llms.txt, robots.txt) from the docs folder, and a .md copy that duplicates a page."
2755
+ },
2756
+ active_content: {
2757
+ requirement: "SVG files can run scripts, so they are served with a restrictive policy. This is a warning; it does not block the build by itself."
2758
+ },
2759
+ reserved_page_path: {
2760
+ requirement: "When any page has reader groups, no page may be named gs-nav-variants or __gs-variants, or have a path that starts with gs-nav-variants/ or __gs-variants/, because the build reserves them.",
2761
+ example: "pages/guides/variants.mdx (not pages/gs-nav-variants/overview.mdx)"
2762
+ },
2763
+ reserved_route: {
2764
+ requirement: "The platform owns /api, /auth, /mcp, /ask, and /runtime. Rename the page or file so its address does not start with one of them.",
2765
+ example: "pages/reference/api.mdx (not pages/api.mdx)"
2766
+ },
2767
+ missing_docs_json: {
2768
+ requirement: "The docs folder must contain docs.json at its top level. Check the configured docs path points at the folder that holds it.",
2769
+ example: '{\n "name": "Acme Docs",\n "navigation": { "groups": [{ "group": "Guides", "pages": ["index"] }] }\n}'
2770
+ },
2771
+ bundle_too_large: {
2772
+ requirement: `All files together can be at most ${SOURCE_LIMITS.maxTotalBytes / MIB} MiB. Remove or compress large media.`
2773
+ },
2774
+ too_many_pages: {
2775
+ requirement: `A site can have at most ${SOURCE_LIMITS.maxPageCount} pages.`
2776
+ },
2777
+ case_collision: {
2778
+ requirement: "Two paths differ only in upper and lower case. Rename or delete one so every path is unique ignoring case."
2779
+ },
2780
+ md_mdx_collision: {
2781
+ requirement: "A page can exist as .md or .mdx, not both. Delete one of the two files."
2782
+ },
2783
+ openapi_name_collision: {
2784
+ requirement: "Each published OpenAPI file needs a file name that is unique without its extension, because agents fetch it by that name: openapi/x.yaml and openapi/y/x.json collide.",
2785
+ example: "openapi/billing.yaml and openapi/users.yaml (not openapi/v1/spec.yaml and openapi/v2/spec.json)"
2786
+ },
2787
+ redirect_cycle: {
2788
+ requirement: "Redirects in docs.json must not lead back to a path they started from.",
2789
+ example: '"redirects": [{ "source": "/old", "destination": "/guide" }]'
2790
+ },
2791
+ root_redirect_to_ask: {
2792
+ requirement: "The redirect for / must not end at /ask, the assistant page.",
2793
+ example: '"redirects": [{ "source": "/", "destination": "/quickstart" }]'
2794
+ },
2795
+ root_redirect_unknown_page: {
2796
+ requirement: "The redirect for / must end at a page in the navigation or an API reference operation.",
2797
+ example: '"redirects": [{ "source": "/", "destination": "/quickstart" }]'
2798
+ },
2799
+ semantic_input_too_large: {
2800
+ requirement: `The file is larger than its type allows: docs.json ${SOURCE_LIMITS.maxDocsJsonBytes / MIB} MiB, models.toml ${SOURCE_LIMITS.maxModelsTomlBytes / KIB} KiB, OpenAPI specs ${SOURCE_LIMITS.maxOpenApiBytes / MIB} MiB.`
2801
+ },
2802
+ invalid_utf8: {
2803
+ requirement: "Text files must be saved as UTF-8 without a byte-order mark. Re-save the file as UTF-8 in your editor."
2804
+ },
2805
+ read_error: {
2806
+ requirement: "The file could not be read during validation. Build the latest commit again; if this repeats, contact SaturnDocs support."
2807
+ },
2808
+ deprecated_site_url: {
2809
+ requirement: "The site address comes from the domains set in the dashboard. Remove siteUrl from docs.json; the build ignores it."
2810
+ },
2811
+ invalid_docs_json: {
2812
+ requirement: "docs.json must be valid JSON with no duplicate keys and must match the docs.json schema. The message names the field that failed.",
2813
+ example: '{\n "name": "Acme Docs",\n "navigation": { "groups": [{ "group": "Guides", "pages": ["index", "quickstart"] }] }\n}'
2814
+ },
2815
+ invalid_models_toml: {
2816
+ requirement: "models.toml must be valid TOML that matches the model configuration schema. The message names the field that failed."
2817
+ },
2818
+ inadmissible_page_content: {
2819
+ requirement: "Pages may use Markdown and the supported components only. Remove imports, exports, {expressions}, and unsupported tags or attributes.",
2820
+ example: '<img src="/diagram.png" alt="Request flow" /> (not {diagram} or import Diagram from "./diagram")'
2821
+ },
2822
+ invalid_page_syntax: {
2823
+ requirement: "The page is not valid Markdown or MDX. Check the line the message names for an unclosed tag, brace, or code fence."
2824
+ },
2825
+ page_heading_conflict: {
2826
+ requirement: "A standard page gets its top heading from the frontmatter title. Remove the # heading, or set pageHeader: false if the page writes its own.",
2827
+ example: "---\ntitle: Quickstart\n---\n\n## Install"
2828
+ },
2829
+ pagefind_required: {
2830
+ requirement: "A page restricted to reader groups must be left out of search, so its text never appears in results for other readers.",
2831
+ example: "---\ntitle: Internal runbook\ngroups: [staff]\npagefind: false\n---"
2832
+ },
2833
+ invalid_frontmatter: {
2834
+ requirement: "Frontmatter must be a YAML block between --- lines using only title, description, pageLayout, groups, pagefind, noindex, public, pageHeader, and runbook.",
2835
+ example: "---\ntitle: Quickstart\ndescription: Install and run your first build.\n---"
2836
+ },
2837
+ invalid_navigation_path: {
2838
+ requirement: "Navigation entries in docs.json name a page by its path under pages/, without the extension or a leading slash.",
2839
+ example: '"pages": ["guides/install"] (not "/pages/guides/install.mdx")'
2840
+ },
2841
+ invalid_theme: {
2842
+ requirement: "The theme settings in docs.json must use a known theme, radius, accent strength and shadow, valid colors in colors and in the theme seed colors, and only known token names.",
2843
+ example: '"colors": { "primary": "#2563eb" }'
2844
+ },
2845
+ missing_page: {
2846
+ requirement: "docs.json navigation lists a page that has no file. Add the file, or remove or correct the entry in docs.json.",
2847
+ example: '"pages": ["quickstart"] needs pages/quickstart.mdx or pages/quickstart.md'
2848
+ },
2849
+ missing_root_page: {
2850
+ requirement: "Readers who open the site address need a page: add pages/index.mdx, add a redirect for /, or keep at least one page without reader groups.",
2851
+ example: '"redirects": [{ "source": "/", "destination": "/quickstart" }]'
2852
+ },
2853
+ too_many_reader_groups: {
2854
+ requirement: "Pages can use at most 4 different reader groups across the site.",
2855
+ example: "groups: [staff] (reuse an existing group instead of adding a fifth)"
2856
+ },
2857
+ unreferenced_page: {
2858
+ requirement: "Every page file must be listed in docs.json navigation. Add the page to a group, or delete the file.",
2859
+ example: '{ "group": "Guides", "pages": ["quickstart", "guides/install"] }'
2860
+ },
2861
+ invalid_openapi_path: {
2862
+ requirement: "A group's openapi value must point at a .json, .yaml, or .yml file under openapi/.",
2863
+ example: '{ "group": "API", "openapi": "openapi/api.yaml", "pages": [] }'
2864
+ },
2865
+ invalid_openapi: {
2866
+ requirement: "The spec must be OpenAPI 3.x or Swagger 2.0 in one file. References to other files ($ref: other.yaml#/...) are not supported; inline them.",
2867
+ example: '$ref: "#/components/schemas/User" (not $ref: "schemas.yaml#/User")'
2868
+ },
2869
+ missing_openapi: {
2870
+ requirement: "docs.json points a group at an OpenAPI file that does not exist. Add the file or correct the path."
2871
+ }
2872
+ });
2873
+ function violationGuidance(code) {
2874
+ return Object.hasOwn(VIOLATION_GUIDANCE, code) ? VIOLATION_GUIDANCE[code] : null;
2875
+ }
2876
+ var SELF_CONTRADICTING_COUNT = "self_contradicting_count";
2877
+ var INCONSISTENT_VALUE_LIST = "inconsistent_value_list";
2878
+ var COUNT_WORDS = /* @__PURE__ */ new Map([
2879
+ ["one", 1],
2880
+ ["two", 2],
2881
+ ["three", 3],
2882
+ ["four", 4],
2883
+ ["five", 5],
2884
+ ["six", 6],
2885
+ ["seven", 7],
2886
+ ["eight", 8],
2887
+ ["nine", 9],
2888
+ ["ten", 10],
2889
+ ["eleven", 11],
2890
+ ["twelve", 12]
2891
+ ]);
2892
+ var MAX_ENUMERATED_COUNT = 20;
2893
+ var MAX_LINES_TO_LIST = 3;
2894
+ var MAX_FINDINGS = 10;
2895
+ function blankNonProse(text) {
2896
+ const lines = text.split("\n");
2897
+ const out = new Array(lines.length).fill("");
2898
+ let index = 0;
2899
+ if (lines.length > 0 && /^---\s*$/.test(lines[0])) {
2900
+ let end = -1;
2901
+ for (let scan = 1; scan < lines.length; scan += 1) {
2902
+ if (/^(?:---|\.\.\.)\s*$/.test(lines[scan])) {
2903
+ end = scan;
2904
+ break;
2905
+ }
2906
+ }
2907
+ if (end !== -1) index = end + 1;
2908
+ }
2909
+ let fence = null;
2910
+ let inComment = false;
2911
+ for (; index < lines.length; index += 1) {
2912
+ const raw = lines[index];
2913
+ if (fence !== null) {
2914
+ if (new RegExp(`^\\s{0,3}${fence}{3,}\\s*$`).test(raw)) fence = null;
2915
+ continue;
2916
+ }
2917
+ const opening = /^\s{0,3}(`{3,}|~{3,})/.exec(raw);
2918
+ if (opening !== null && !inComment) {
2919
+ fence = opening[1][0] === "`" ? "`" : "~";
2920
+ continue;
2921
+ }
2922
+ let line = raw;
2923
+ if (inComment) {
2924
+ const close = line.indexOf("-->");
2925
+ if (close === -1) continue;
2926
+ line = " ".repeat(close + 3) + line.slice(close + 3);
2927
+ inComment = false;
2928
+ }
2929
+ line = line.replace(/<!--[\s\S]*?-->/g, (match) => " ".repeat(match.length));
2930
+ const open = line.indexOf("<!--");
2931
+ if (open !== -1) {
2932
+ line = line.slice(0, open) + " ".repeat(line.length - open);
2933
+ inComment = true;
2934
+ }
2935
+ line = line.replace(/(`+)(?:[^`]|(?!\1)`)*?\1/g, (match) => " ".repeat(match.length));
2936
+ out[index] = line;
2937
+ }
2938
+ return out;
2939
+ }
2940
+ function headingsOf(lines) {
2941
+ const headings = [];
2942
+ for (let index = 0; index < lines.length; index += 1) {
2943
+ const match = /^\s{0,3}(#{1,6})\s+(.+?)\s*#*\s*$/.exec(lines[index]);
2944
+ if (match !== null) headings.push({ index, level: match[1].length, text: match[2] });
2945
+ }
2946
+ return headings;
2947
+ }
2948
+ var listItem = (line) => {
2949
+ const match = /^(\s*)(?:[-*+]|\d{1,3}[.)])\s+\S/.exec(line);
2950
+ return match === null || match[1].length > 3 ? null : { indent: match[1].length };
2951
+ };
2952
+ function countListItems(lines, from, until) {
2953
+ let start = -1;
2954
+ for (let index = from; index < Math.min(until, from + MAX_LINES_TO_LIST + 1); index += 1) {
2955
+ if (listItem(lines[index]) !== null) {
2956
+ start = index;
2957
+ break;
2958
+ }
2959
+ }
2960
+ if (start === -1) return 0;
2961
+ const base = listItem(lines[start]).indent;
2962
+ let items = 0;
2963
+ for (let index = start; index < until; index += 1) {
2964
+ const line = lines[index];
2965
+ if (line.trim() === "") continue;
2966
+ const item = listItem(line);
2967
+ if (item !== null) {
2968
+ if (item.indent < base) break;
2969
+ if (item.indent === base) items += 1;
2970
+ continue;
2971
+ }
2972
+ if (/^\s{0,3}#{1,6}\s/.test(line) || !/^\s/.test(line)) break;
2973
+ }
2974
+ return items;
2975
+ }
2976
+ function countChildHeadings(headings, at) {
2977
+ const parent = headings[at].level;
2978
+ const children = [];
2979
+ for (let index = at + 1; index < headings.length; index += 1) {
2980
+ const heading = headings[index];
2981
+ if (heading.level <= parent) break;
2982
+ children.push(heading.level);
2983
+ }
2984
+ if (children.length === 0) return 0;
2985
+ const level = Math.min(...children);
2986
+ return children.filter((child) => child === level).length;
2987
+ }
2988
+ var singular = (noun) => noun.replace(/(?:ies|es|s)$/, (suffix) => suffix === "ies" ? "y" : "");
2989
+ function sectionEnd(headings, at, lineCount) {
2990
+ const level = headings[at].level;
2991
+ for (let index = at + 1; index < headings.length; index += 1) {
2992
+ if (headings[index].level <= level) return headings[index].index;
2993
+ }
2994
+ return lineCount;
2995
+ }
2996
+ function enumeratedCount(page, from, noun, afterNoun) {
2997
+ const { lines, headings, hidden } = page;
2998
+ const stem = singular(noun.toLowerCase());
2999
+ if (stem.length < 3) return null;
3000
+ const named = new RegExp(`\\b${stem}(?:s|es)?\\b`, "i");
3001
+ const next = headings.find((heading) => heading.index > from);
3002
+ if (next !== void 0 && named.test(next.text) && !hidden.slice(from + 1, next.index).some(Boolean)) {
3003
+ const index = headings.indexOf(next);
3004
+ const children = countChildHeadings(headings, index);
3005
+ if (children > 0) return { count: children, where: `under "${next.text}"` };
3006
+ const items2 = countListItems(lines, next.index + 1, sectionEnd(headings, index, lines.length));
3007
+ return items2 > 0 ? { count: items2, where: `under "${next.text}"` } : null;
3008
+ }
3009
+ if (!/^[^:]{0,12}:\s*$/.test(afterNoun)) return null;
3010
+ const items = countListItems(lines, from + 1, lines.length);
3011
+ return items > 0 ? { count: items, where: "in the list it introduces" } : null;
3012
+ }
3013
+ var COUNT_CLAIM = /\b(\d{1,2}|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)\s+(?:[a-z][a-z-]{2,15}\s+)?([a-z][a-z-]{2,20}(?:s|es|ies))\b/gi;
3014
+ var NON_COUNTABLE = /* @__PURE__ */ new Set(["times", "ways", "cases", "reasons", "others", "seconds", "minutes", "hours", "days", "weeks", "months", "years", "bytes", "kilobytes", "megabytes", "characters", "requests", "users", "lines", "percent", "levels"]);
3015
+ function countRules(path, page) {
3016
+ const findings = [];
3017
+ const seen = /* @__PURE__ */ new Set();
3018
+ for (let index = 0; index < page.lines.length; index += 1) {
3019
+ const line = page.lines[index];
3020
+ if (/^\s{0,3}#{1,6}\s/.test(line)) continue;
3021
+ COUNT_CLAIM.lastIndex = 0;
3022
+ let match;
3023
+ while ((match = COUNT_CLAIM.exec(line)) !== null) {
3024
+ if (/[A-Za-z0-9._-]/.test(line.slice(Math.max(0, match.index - 1), match.index))) continue;
3025
+ const word = match[1].toLowerCase();
3026
+ const claimed = COUNT_WORDS.get(word) ?? Number.parseInt(word, 10);
3027
+ const noun = match[2];
3028
+ if (!Number.isFinite(claimed) || claimed < 1 || claimed > MAX_ENUMERATED_COUNT) continue;
3029
+ const key = noun.toLowerCase();
3030
+ if (NON_COUNTABLE.has(key) || seen.has(key)) continue;
3031
+ const enumerated = enumeratedCount(page, index, noun, line.slice(match.index + match[0].length));
3032
+ if (enumerated === null || enumerated.count === claimed) continue;
3033
+ seen.add(key);
3034
+ findings.push({
3035
+ severity: "error",
3036
+ line: index + 1,
3037
+ rule: SELF_CONTRADICTING_COUNT,
3038
+ message: `${path} line ${index + 1} says "${match[1]} ${noun}", but the page documents ${enumerated.count} ${enumerated.where}.`
3039
+ });
3040
+ }
3041
+ }
3042
+ return findings;
3043
+ }
3044
+ var VALUE_LIST = /\b[a-z0-9][a-z0-9._-]{0,23}(?:, (?:(?:and|or) )?[a-z0-9][a-z0-9._-]{0,23}){2,}\b/g;
3045
+ var valueShaped = (member) => member.length <= 4 || /[0-9._-]/.test(member);
3046
+ function valueListsOf(lines) {
3047
+ const lists = [];
3048
+ for (let index = 0; index < lines.length; index += 1) {
3049
+ VALUE_LIST.lastIndex = 0;
3050
+ let match;
3051
+ while ((match = VALUE_LIST.exec(lines[index])) !== null) {
3052
+ const members = new Set(match[0].split(", ").map((part) => part.replace(/^(?:and|or) /, "")));
3053
+ if (members.size >= 3 && [...members].every(valueShaped) && ![...members].every((member) => /^[0-9]+$/.test(member))) lists.push({ line: index + 1, text: match[0].trim(), members });
3054
+ }
3055
+ }
3056
+ return lists;
3057
+ }
3058
+ var intersectionSize = (a, b) => {
3059
+ let size = 0;
3060
+ for (const member of a) if (b.has(member)) size += 1;
3061
+ return size;
3062
+ };
3063
+ function valueListRules(path, lines) {
3064
+ const lists = valueListsOf(lines);
3065
+ for (let a = 0; a < lists.length; a += 1) {
3066
+ for (let b = a + 1; b < lists.length; b += 1) {
3067
+ const first = lists[a];
3068
+ const second = lists[b];
3069
+ const shared = intersectionSize(first.members, second.members);
3070
+ const differing = first.members.size + second.members.size - 2 * shared;
3071
+ if (differing === 0 || differing > 2) continue;
3072
+ if (shared < 2 || shared < Math.min(first.members.size, second.members.size) - 1) continue;
3073
+ const extra = [...second.members].filter((member) => !first.members.has(member)).concat([...first.members].filter((member) => !second.members.has(member)));
3074
+ return [{
3075
+ severity: "error",
3076
+ line: second.line,
3077
+ rule: INCONSISTENT_VALUE_LIST,
3078
+ message: `${path} lists "${first.text}" at line ${first.line} and "${second.text}" at line ${second.line}; they differ on ${extra.join(", ")}.`
3079
+ }];
3080
+ }
3081
+ }
3082
+ return [];
3083
+ }
3084
+ function lintContent(path, text) {
3085
+ const lines = blankNonProse(text);
3086
+ const hidden = text.split("\n").map((original, index) => original.trim() !== "" && lines[index].trim() === "");
3087
+ const page = { lines, headings: headingsOf(lines), hidden };
3088
+ const findings = [...countRules(path, page), ...valueListRules(path, lines)];
3089
+ findings.sort((left, right) => left.line - right.line);
3090
+ return findings.slice(0, MAX_FINDINGS);
3091
+ }
3092
+ var MAX_DIFF_LINES = 1200;
3093
+ function keptLines(before, after) {
3094
+ const width = after.length + 1;
3095
+ const table = new Uint32Array((before.length + 1) * width);
3096
+ for (let i2 = before.length - 1; i2 >= 0; i2 -= 1) {
3097
+ for (let j2 = after.length - 1; j2 >= 0; j2 -= 1) {
3098
+ table[i2 * width + j2] = before[i2] === after[j2] ? table[(i2 + 1) * width + j2 + 1] + 1 : Math.max(table[(i2 + 1) * width + j2], table[i2 * width + j2 + 1]);
3099
+ }
3100
+ }
3101
+ const kept = /* @__PURE__ */ new Set();
3102
+ let i = 0;
3103
+ let j = 0;
3104
+ while (i < before.length && j < after.length) {
3105
+ if (before[i] === after[j]) {
3106
+ kept.add(j);
3107
+ i += 1;
3108
+ j += 1;
3109
+ continue;
3110
+ }
3111
+ if (table[(i + 1) * width + j] >= table[i * width + j + 1]) i += 1;
3112
+ else j += 1;
3113
+ }
3114
+ return kept;
3115
+ }
3116
+ function changedLineIndexes(previous, proposed) {
3117
+ const before = previous.split("\n");
3118
+ const after = proposed.split("\n");
3119
+ let head = 0;
3120
+ while (head < before.length && head < after.length && before[head] === after[head]) head += 1;
3121
+ let tail = 0;
3122
+ while (tail < before.length - head && tail < after.length - head && before[before.length - 1 - tail] === after[after.length - 1 - tail]) tail += 1;
3123
+ const midBefore = before.slice(head, before.length - tail);
3124
+ const midAfter = after.slice(head, after.length - tail);
3125
+ if (midAfter.length === 0) return [];
3126
+ const kept = midBefore.length === 0 || midBefore.length > MAX_DIFF_LINES || midAfter.length > MAX_DIFF_LINES ? /* @__PURE__ */ new Set() : keptLines(midBefore, midAfter);
3127
+ const changed = [];
3128
+ for (let index = 0; index < midAfter.length; index += 1) if (!kept.has(index)) changed.push(head + index);
3129
+ return changed;
3130
+ }
3131
+ var MAX_TOKENS_PER_PAGE = 40;
3132
+ var FLAG = /^--[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
3133
+ var ENV = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;
3134
+ var KEY = /^[a-z][a-zA-Z0-9_-]*(?:\.[a-z][a-zA-Z0-9_-]*)+$/;
3135
+ var VALUE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,23}$/;
3136
+ var COMMON_ENV = /* @__PURE__ */ new Set([
3137
+ "NODE_ENV",
3138
+ "NODE_OPTIONS",
3139
+ "HTTP_PROXY",
3140
+ "HTTPS_PROXY",
3141
+ "NO_PROXY",
3142
+ "ALL_PROXY",
3143
+ "NO_COLOR",
3144
+ "FORCE_COLOR",
3145
+ "XDG_CONFIG_HOME",
3146
+ "XDG_DATA_HOME",
3147
+ "XDG_CACHE_HOME",
3148
+ "XDG_STATE_HOME",
3149
+ "LC_ALL",
3150
+ "GITHUB_TOKEN",
3151
+ "GH_TOKEN",
3152
+ "GITHUB_ACTIONS",
3153
+ "GITHUB_WORKSPACE",
3154
+ "GITHUB_OUTPUT",
3155
+ "GITHUB_ENV",
3156
+ "RUNNER_TEMP",
3157
+ "JAVA_HOME",
3158
+ "AWS_REGION",
3159
+ "AWS_PROFILE",
3160
+ "AWS_ACCESS_KEY_ID",
3161
+ "AWS_SECRET_ACCESS_KEY",
3162
+ "SSL_CERT_FILE",
3163
+ "NODE_EXTRA_CA_CERTS"
3164
+ ]);
3165
+ var THIRD_PARTY_COMMANDS = /* @__PURE__ */ new Set([
3166
+ "npm",
3167
+ "npx",
3168
+ "pnpm",
3169
+ "yarn",
3170
+ "bun",
3171
+ "bunx",
3172
+ "node",
3173
+ "deno",
3174
+ "git",
3175
+ "gh",
3176
+ "docker",
3177
+ "docker-compose",
3178
+ "podman",
3179
+ "kubectl",
3180
+ "helm",
3181
+ "curl",
3182
+ "wget",
3183
+ "brew",
3184
+ "apt",
3185
+ "apt-get",
3186
+ "yum",
3187
+ "dnf",
3188
+ "pip",
3189
+ "pip3",
3190
+ "pipx",
3191
+ "python",
3192
+ "python3",
3193
+ "go",
3194
+ "cargo",
3195
+ "rustup",
3196
+ "make",
3197
+ "cmake",
3198
+ "ssh",
3199
+ "scp",
3200
+ "rsync",
3201
+ "tar",
3202
+ "unzip",
3203
+ "chmod",
3204
+ "chown",
3205
+ "mkdir",
3206
+ "cp",
3207
+ "mv",
3208
+ "rm",
3209
+ "ls",
3210
+ "cat",
3211
+ "echo",
3212
+ "grep",
3213
+ "sed",
3214
+ "awk",
3215
+ "find",
3216
+ "source",
3217
+ "cd",
3218
+ "wrangler",
3219
+ "terraform",
3220
+ "aws",
3221
+ "gcloud",
3222
+ "az",
3223
+ "openssl",
3224
+ "tsc",
3225
+ "vite",
3226
+ "vitest",
3227
+ "jest",
3228
+ "eslint",
3229
+ "prettier",
3230
+ "corepack"
3231
+ ]);
3232
+ var NOT_KEY_SUFFIXES = /* @__PURE__ */ new Set([
3233
+ "md",
3234
+ "mdx",
3235
+ "json",
3236
+ "jsonc",
3237
+ "yaml",
3238
+ "yml",
3239
+ "toml",
3240
+ "ts",
3241
+ "tsx",
3242
+ "js",
3243
+ "jsx",
3244
+ "mjs",
3245
+ "cjs",
3246
+ "css",
3247
+ "scss",
3248
+ "html",
3249
+ "txt",
3250
+ "sh",
3251
+ "py",
3252
+ "rb",
3253
+ "go",
3254
+ "rs",
3255
+ "lock",
3256
+ "env",
3257
+ "xml",
3258
+ "csv",
3259
+ "png",
3260
+ "jpg",
3261
+ "jpeg",
3262
+ "svg",
3263
+ "gif",
3264
+ "ico",
3265
+ "pdf",
3266
+ "zip",
3267
+ "gz",
3268
+ "tgz",
3269
+ "log",
3270
+ "ini",
3271
+ "cfg",
3272
+ "conf",
3273
+ "com",
3274
+ "org",
3275
+ "net",
3276
+ "io",
3277
+ "dev",
3278
+ "app",
3279
+ "ai",
3280
+ "co",
3281
+ "edu",
3282
+ "gov",
3283
+ "xyz",
3284
+ "cloud",
3285
+ "local",
3286
+ "test",
3287
+ "example"
3288
+ ]);
3289
+ var NOT_KEY_ROOTS = /* @__PURE__ */ new Set([
3290
+ "process",
3291
+ "console",
3292
+ "window",
3293
+ "document",
3294
+ "globalthis",
3295
+ "math",
3296
+ "json",
3297
+ "os",
3298
+ "path",
3299
+ "fs",
3300
+ "npm",
3301
+ "import",
3302
+ "module",
3303
+ "exports",
3304
+ "require",
3305
+ "self",
3306
+ "this",
3307
+ "navigator",
3308
+ "location",
3309
+ "crypto",
3310
+ "buffer",
3311
+ "object",
3312
+ "array",
3313
+ "string",
3314
+ "number",
3315
+ "promise",
3316
+ "e",
3317
+ "i"
3318
+ ]);
3319
+ var VALUE_LIST_CUE = /\b(?:one of|any of|either|values?|accepts?|allowed|valid|choices?|possible|supported|supports)\b/i;
3320
+ var CODE_SPAN = /(`+)((?:[^`]|(?!\1)`)*?)\1/g;
3321
+ var SPAN_LIST = /`[^`\s]{1,24}`(?:(?:,\s*(?:(?:and|or)\s+)?|\s+(?:and|or)\s+)`[^`\s]{1,24}`)+/g;
3322
+ var ENV_IN_CODE = [
3323
+ /\$\{?([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)\b/g,
3324
+ /\benv\.([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)\b/g,
3325
+ /\b(?:env|environ)(?:\.get\(|\[)\s*["']([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)["']/g,
3326
+ /\bgetenv\(\s*["']([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)["']/gi
3327
+ ];
3328
+ function emitEnv(name, emit) {
3329
+ if (ENV.test(name) && !COMMON_ENV.has(name)) emit(name, "env");
3330
+ }
3331
+ function commandTokens(line, emit) {
3332
+ const trimmed = line.trim().replace(/^(?:\$|>)\s+/, "");
3333
+ if (trimmed === "" || trimmed.startsWith("#") || trimmed.startsWith("//")) return;
3334
+ const segment = trimmed.split(/\s*(?:\|\||&&|\||;)\s*/)[0] ?? "";
3335
+ const words = segment.split(/\s+/).filter((word) => word !== "");
3336
+ let index = 0;
3337
+ if (words[index] === "sudo") index += 1;
3338
+ if (words[index] === "export") index += 1;
3339
+ for (; index < words.length; index += 1) {
3340
+ const assignment = /^([A-Z][A-Z0-9_]*)=/.exec(words[index]);
3341
+ if (assignment === null) break;
3342
+ emitEnv(assignment[1], emit);
3343
+ }
3344
+ const command = words[index]?.split("/").pop() ?? "";
3345
+ if (THIRD_PARTY_COMMANDS.has(command)) return;
3346
+ for (const word of words.slice(index)) {
3347
+ const flag = word.split("=")[0].replace(/[,.;:)\]]+$/, "");
3348
+ if (FLAG.test(flag)) emit(flag, "flag");
3349
+ }
3350
+ }
3351
+ function envTokens(code, emit) {
3352
+ for (const pattern of ENV_IN_CODE) {
3353
+ pattern.lastIndex = 0;
3354
+ let match;
3355
+ while ((match = pattern.exec(code)) !== null) emitEnv(match[1], emit);
3356
+ }
3357
+ }
3358
+ function fenceTokens(line, emit) {
3359
+ commandTokens(line, emit);
3360
+ envTokens(line, emit);
3361
+ }
3362
+ function keyShaped(span) {
3363
+ if (!KEY.test(span)) return false;
3364
+ const segments = span.split(".");
3365
+ return !NOT_KEY_SUFFIXES.has(segments.at(-1).toLowerCase()) && !NOT_KEY_ROOTS.has(segments[0].toLowerCase());
3366
+ }
3367
+ function proseTokens(line, emit) {
3368
+ CODE_SPAN.lastIndex = 0;
3369
+ let match;
3370
+ while ((match = CODE_SPAN.exec(line)) !== null) {
3371
+ const span = match[2].trim();
3372
+ if (span.startsWith("--")) {
3373
+ const flag = span.split(/[\s=]/)[0];
3374
+ if (FLAG.test(flag)) emit(flag, "flag");
3375
+ } else if (/\s/.test(span)) {
3376
+ commandTokens(span, emit);
3377
+ } else if (ENV.test(span.replace(/^\$/, ""))) {
3378
+ emitEnv(span.replace(/^\$/, ""), emit);
3379
+ } else if (keyShaped(span)) {
3380
+ emit(span, "key");
3381
+ } else {
3382
+ envTokens(span, emit);
3383
+ }
3384
+ }
3385
+ SPAN_LIST.lastIndex = 0;
3386
+ let list;
3387
+ while ((list = SPAN_LIST.exec(line)) !== null) {
3388
+ if (!VALUE_LIST_CUE.test(line.slice(Math.max(0, list.index - 40), list.index))) continue;
3389
+ for (const member of list[0].matchAll(/`([^`]+)`/g)) {
3390
+ const value = member[1];
3391
+ if (VALUE.test(value) && !FLAG.test(value) && !ENV.test(value)) emit(value, "value");
3392
+ }
3393
+ }
3394
+ }
3395
+ function lineKinds(lines) {
3396
+ const kinds = new Array(lines.length).fill("prose");
3397
+ let index = 0;
3398
+ if (lines.length > 0 && /^---\s*$/.test(lines[0])) {
3399
+ for (let scan = 1; scan < lines.length; scan += 1) {
3400
+ if (/^(?:---|\.\.\.)\s*$/.test(lines[scan])) {
3401
+ for (let skip = 0; skip <= scan; skip += 1) kinds[skip] = "skip";
3402
+ index = scan + 1;
3403
+ break;
3404
+ }
3405
+ }
3406
+ }
3407
+ let fence = null;
3408
+ for (; index < lines.length; index += 1) {
3409
+ const line = lines[index];
3410
+ if (fence !== null) {
3411
+ if (new RegExp(`^\\s{0,3}${fence}{3,}\\s*$`).test(line)) {
3412
+ fence = null;
3413
+ kinds[index] = "skip";
3414
+ } else {
3415
+ kinds[index] = "fence";
3416
+ }
3417
+ continue;
3418
+ }
3419
+ const opening = /^\s{0,3}(`{3,}|~{3,})/.exec(line);
3420
+ if (opening !== null) {
3421
+ fence = opening[1][0] === "`" ? "`" : "~";
3422
+ kinds[index] = "skip";
3423
+ }
3424
+ }
3425
+ return kinds;
3426
+ }
3427
+ function extractClaimTokens(pages) {
3428
+ const tokens = [];
3429
+ for (const page of pages) {
3430
+ const lines = page.proposed.split("\n");
3431
+ const kinds = lineKinds(lines);
3432
+ const changed = page.previous === null ? lines.map((_, index) => index) : changedLineIndexes(page.previous, page.proposed);
3433
+ const seen = /* @__PURE__ */ new Set();
3434
+ for (const index of changed) {
3435
+ if (seen.size >= MAX_TOKENS_PER_PAGE) break;
3436
+ const emit = (name, kind) => {
3437
+ if (seen.has(name) || seen.size >= MAX_TOKENS_PER_PAGE) return;
3438
+ seen.add(name);
3439
+ tokens.push({ path: page.path, line: index + 1, name, kind });
3440
+ };
3441
+ if (kinds[index] === "fence") fenceTokens(lines[index], emit);
3442
+ else if (kinds[index] === "prose") proseTokens(lines[index], emit);
3443
+ }
3444
+ }
3445
+ return tokens;
3446
+ }
3447
+ var WORD_CHAR = /[a-z0-9_]/;
3448
+ function hasWholeToken(haystack, needle) {
3449
+ if (needle === "") return false;
3450
+ let from = 0;
3451
+ for (; ; ) {
3452
+ const at = haystack.indexOf(needle, from);
3453
+ if (at === -1) return false;
3454
+ const before = at === 0 ? "" : haystack[at - 1];
3455
+ const after = haystack[at + needle.length] ?? "";
3456
+ if (!WORD_CHAR.test(before) && !WORD_CHAR.test(after)) return true;
3457
+ from = at + 1;
3458
+ }
3459
+ }
3460
+ function flagSpellings(flag) {
3461
+ const names = [flag.slice(2)];
3462
+ if (names[0].startsWith("no-")) names.push(names[0].slice(3));
3463
+ return [flag, ...names.flatMap((name) => [name, name.replace(/-/g, ""), name.replace(/-/g, "_")])];
3464
+ }
3465
+ function grounded(token, evidence) {
3466
+ const name = token.name.toLowerCase();
3467
+ switch (token.kind) {
3468
+ case "flag":
3469
+ return flagSpellings(name).some((spelling) => hasWholeToken(evidence, spelling));
3470
+ case "key":
3471
+ return hasWholeToken(evidence, name) || name.split(".").every((segment) => hasWholeToken(evidence, segment));
3472
+ default:
3473
+ return hasWholeToken(evidence, name);
3474
+ }
3475
+ }
3476
+ function groundTokens(tokens, evidence) {
3477
+ if (tokens.length === 0) return [];
3478
+ const text = evidence.join("\n").toLowerCase();
3479
+ return tokens.filter((token) => !grounded(token, text));
3480
+ }
3481
+ var KNOWN_PITFALL_CODE = "known_pitfall";
3482
+ var KNOWN_PITFALLS = [
3483
+ {
3484
+ id: "orbit-language-ja",
3485
+ wrong: "\\bja\\b",
3486
+ correct: "The orbit CLI accepts exactly four language codes -- en, es, fr, de. Read the enum in the source before listing one; an unlisted code makes the CLI print `Unsupported language`.",
3487
+ context: { mentions: ["orbit", "language"] },
3488
+ source: "#248",
3489
+ verified_by: "orbit-language-ja: a page listing only the four supported codes is clear"
3490
+ },
3491
+ {
3492
+ id: "orbit-farewell-period",
3493
+ wrong: '"greeting"\\s*:\\s*"Goodbye[^"]*\\."',
3494
+ correct: "orbit renders a greeting as `${word}, ${name}!`, so a farewell in an example output ends in `!`, never a period.",
3495
+ context: { mentions: ["orbit"] },
3496
+ source: "#248",
3497
+ verified_by: "orbit-farewell-period: an example output ending in an exclamation mark is clear"
3498
+ },
3499
+ {
3500
+ id: "method-style-fetch-impl",
3501
+ wrong: "\\.fetchImpl\\s*\\(",
3502
+ correct: "Call an injected `fetchImpl` as a bare function -- `fetchImpl(request)` -- never `object.fetchImpl(request)`. workerd throws on the method-style call; Node does not, so the mistake survives every local test.",
3503
+ context: { mentions: ["saturndocs"] },
3504
+ source: "AGENTS.md",
3505
+ verified_by: "method-style-fetch-impl: a bare fetchImpl call is clear"
3506
+ },
3507
+ {
3508
+ id: "workers-dev-service-url",
3509
+ wrong: "[A-Za-z0-9-]+\\.workers\\.dev",
3510
+ correct: "A SaturnDocs Worker reaches another through a service binding or a routed hostname. Cloudflare answers a `*.workers.dev` URL with a bare 404 (error 1042).",
3511
+ context: { mentions: ["saturndocs", "worker"] },
3512
+ source: "AGENTS.md",
3513
+ verified_by: "workers-dev-service-url: a service binding is clear"
3514
+ },
3515
+ {
3516
+ id: "connected-callback-mount",
3517
+ wrong: "connectedCallback",
3518
+ correct: "Mount renderer components on `astro:page-load`, not `connectedCallback`, or they stay unmounted after a client-side navigation.",
3519
+ context: { mentions: ["saturndocs"] },
3520
+ source: "AGENTS.md",
3521
+ verified_by: "connected-callback-mount: mounting on astro:page-load is clear"
3522
+ }
3523
+ ];
3524
+ var compiled = /* @__PURE__ */ new WeakMap();
3525
+ function compile(entry) {
3526
+ const cached = compiled.get(entry);
3527
+ if (cached !== void 0) return cached;
3528
+ const built = {
3529
+ entry,
3530
+ wrong: new RegExp(entry.wrong),
3531
+ paths: entry.context.paths === void 0 ? null : entry.context.paths.map(globToRegExp),
3532
+ mentions: entry.context.mentions === void 0 ? null : entry.context.mentions.map((mention) => mention.toLowerCase())
3533
+ };
3534
+ compiled.set(entry, built);
3535
+ return built;
3536
+ }
3537
+ function globToRegExp(glob) {
3538
+ let pattern = "";
3539
+ for (let index = 0; index < glob.length; index += 1) {
3540
+ const character = glob[index];
3541
+ if (character === "*") {
3542
+ if (glob[index + 1] === "*") {
3543
+ pattern += ".*";
3544
+ index += 1;
3545
+ continue;
3546
+ }
3547
+ pattern += "[^/]*";
3548
+ continue;
3549
+ }
3550
+ pattern += character.replace(/[.+?^${}()|[\]\\]/, "\\$&");
3551
+ }
3552
+ return new RegExp(`^${pattern}$`);
3553
+ }
3554
+ function inContext(entry, page, lowered) {
3555
+ if (entry.paths !== null && !entry.paths.some((pattern) => pattern.test(page.path))) return false;
3556
+ if (entry.mentions !== null && !entry.mentions.every((mention) => lowered.includes(mention))) return false;
3557
+ return true;
3558
+ }
3559
+ function checkPitfalls(pages, catalog = KNOWN_PITFALLS) {
3560
+ const entries = catalog.map(compile);
3561
+ const violations = [];
3562
+ for (const page of pages) {
3563
+ const lowered = page.content.toLowerCase();
3564
+ for (const entry of entries) {
3565
+ if (!inContext(entry, page, lowered)) continue;
3566
+ if (!entry.wrong.test(page.content)) continue;
3567
+ violations.push({
3568
+ path: page.path,
3569
+ code: KNOWN_PITFALL_CODE,
3570
+ severity: "warning",
3571
+ message: `Known pitfall ${entry.entry.id} (${entry.entry.source}) in ${page.path}: ${entry.entry.correct}`
3572
+ });
3573
+ }
3574
+ }
3575
+ return violations;
3576
+ }
3577
+ var encoder = new TextEncoder();
3578
+ var TAR_BLOCK_SIZE = 512;
3579
+ var TAR_TRAILER_SIZE = 1024;
3580
+ function tarPadding(size) {
3581
+ return (TAR_BLOCK_SIZE - size % TAR_BLOCK_SIZE) % TAR_BLOCK_SIZE;
3582
+ }
3583
+ function writeText(target, offset, length, value) {
3584
+ target.set(encoder.encode(value).subarray(0, length), offset);
3585
+ }
3586
+ function octal(value, length) {
3587
+ return `${value.toString(8).padStart(length - 1, "0")}\0`;
3588
+ }
3589
+ function tarHeader(name, size, options = {}) {
3590
+ const header = new Uint8Array(TAR_BLOCK_SIZE);
3591
+ writeText(header, 0, 100, name);
3592
+ writeText(header, 100, 8, octal(options.mode ?? 420, 8));
3593
+ writeText(header, 108, 8, octal(0, 8));
3594
+ writeText(header, 116, 8, octal(0, 8));
3595
+ writeText(header, 124, 12, octal(size, 12));
3596
+ writeText(header, 136, 12, octal(0, 12));
3597
+ header.fill(32, 148, 156);
3598
+ header[156] = (options.type ?? "0").charCodeAt(0);
3599
+ writeText(header, 257, 6, "ustar\0");
3600
+ writeText(header, 263, 2, "00");
3601
+ const checksum = header.reduce((sum, byte) => sum + byte, 0);
3602
+ writeText(header, 148, 8, `${checksum.toString(8).padStart(6, "0")}\0 `);
3603
+ return header;
3604
+ }
3605
+ function paxRecord(key, value) {
3606
+ let length = encoder.encode(`${key}=${value}
3607
+ `).byteLength + 3;
3608
+ for (; ; ) {
3609
+ const record = encoder.encode(`${length} ${key}=${value}
3610
+ `);
3611
+ if (record.byteLength === length) return record;
3612
+ length = record.byteLength;
3613
+ }
3614
+ }
3615
+ var MARKDOWN_LINK = /\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g;
3616
+ var REFERENCE_DEFINITION = /^\s*\[[^\]]+\]:\s*(\S+)/gm;
3617
+ var JSX_HREF = /\bhref\s*=\s*"([^"]+)"/g;
3618
+ function isCheckable(href) {
3619
+ if (href === "" || href.startsWith("#")) return false;
3620
+ if (/^[a-z][a-z0-9+.-]*:/i.test(href)) return false;
3621
+ if (href.startsWith("//")) return false;
3622
+ if (href.startsWith("{")) return false;
3623
+ const withoutFragment = href.split("#")[0] ?? "";
3624
+ if (withoutFragment === "") return false;
3625
+ return !/\.[a-z0-9]{1,8}$/i.test(withoutFragment);
3626
+ }
3627
+ function resolveHref(href, fromDocId) {
3628
+ const target = (href.split("#")[0] ?? "").split("?")[0] ?? "";
3629
+ if (target === "") return null;
3630
+ const segments = target.startsWith("/") ? target.slice(1).split("/") : [...fromDocId.split("/").slice(0, -1), ...target.split("/")];
3631
+ const resolved = [];
3632
+ for (const segment of segments) {
3633
+ if (segment === "" || segment === ".") continue;
3634
+ if (segment === "..") {
3635
+ resolved.pop();
3636
+ continue;
3637
+ }
3638
+ resolved.push(segment);
3639
+ }
3640
+ return resolved.length === 0 ? null : resolved.join("/");
3641
+ }
3642
+ function extractLinks(source) {
3643
+ const hrefs = [];
3644
+ for (const pattern of [MARKDOWN_LINK, REFERENCE_DEFINITION, JSX_HREF]) {
3645
+ pattern.lastIndex = 0;
3646
+ for (const match of source.matchAll(pattern)) {
3647
+ const href = match[1];
3648
+ if (href !== void 0) hrefs.push(href.trim());
3649
+ }
3650
+ }
3651
+ return hrefs;
3652
+ }
3653
+ function findUnresolvedLinks(pages, knownDocIds) {
3654
+ const misses = [];
3655
+ for (const page of pages) {
3656
+ for (const href of extractLinks(page.source)) {
3657
+ if (!isCheckable(href)) continue;
3658
+ const target = resolveHref(href, page.docId);
3659
+ if (target !== null && knownDocIds.has(target)) continue;
3660
+ misses.push({ path: page.path, href });
3661
+ }
3662
+ }
3663
+ return misses;
3664
+ }
3665
+ var PRODUCT_KINDS = ["cli", "library", "http-api", "web-app", "infrastructure", "other"];
3666
+ var PAGE_PATH = /^pages\/(?:[A-Za-z0-9._-]+\/)*[A-Za-z0-9._-]+\.(?:md|mdx)$/;
3667
+ var INDEX_PATHS = ["pages/index.md", "pages/index.mdx"];
3668
+ var nonEmpty = z.string().trim().min(1);
3669
+ var PageSchema = z.object({
3670
+ path: z.string(),
3671
+ title: nonEmpty,
3672
+ group: nonEmpty,
3673
+ purpose: nonEmpty,
3674
+ sources: z.array(z.string()),
3675
+ sections: z.array(nonEmpty)
3676
+ });
3677
+ var OutlineSchema = z.object({
3678
+ product: z.object({ name: nonEmpty, kind: z.enum(PRODUCT_KINDS), summary: nonEmpty }),
3679
+ readers: z.array(z.string()),
3680
+ pages: z.array(PageSchema).min(1)
3681
+ }).superRefine((outline, ctx) => {
3682
+ const seen = /* @__PURE__ */ new Set();
3683
+ outline.pages.forEach((page, index) => {
3684
+ const at = ["pages", index, "path"];
3685
+ if (!PAGE_PATH.test(page.path) || canonicalizeSourcePath(page.path) !== page.path) {
3686
+ ctx.addIssue({ code: "custom", path: at, message: `must be a pages/ .md or .mdx path that the content contract accepts (got "${page.path}")` });
3687
+ }
3688
+ if (seen.has(page.path)) {
3689
+ ctx.addIssue({ code: "custom", path: at, message: `duplicate path; paths must be unique ("${page.path}")` });
3690
+ }
3691
+ seen.add(page.path);
3692
+ });
3693
+ const first = outline.pages[0];
3694
+ if (first && !INDEX_PATHS.includes(first.path)) {
3695
+ ctx.addIssue({ code: "custom", path: ["pages", 0, "path"], message: "the first page must be pages/index.md or pages/index.mdx" });
3696
+ }
3697
+ });
3698
+ var formatPath = (path) => path.reduce((out, key) => typeof key === "number" ? `${out}[${key}]` : out ? `${out}.${String(key)}` : String(key), "");
3699
+ function parseOutline(value) {
3700
+ const result = OutlineSchema.safeParse(value);
3701
+ if (result.success) return result.data;
3702
+ throw new Error(
3703
+ result.error.issues.map((issue2) => `${formatPath(issue2.path) || "outline"}: ${issue2.message}`).join("; ")
3704
+ );
3705
+ }
3706
+ function outlineJsonSchema() {
3707
+ return z.toJSONSchema(OutlineSchema);
3708
+ }
3709
+ function outlineDocId(path) {
3710
+ return path.replace(/^pages\//, "").replace(/\.mdx?$/i, "");
3711
+ }
3712
+ function navigationFromOutline(outline) {
3713
+ const groups = /* @__PURE__ */ new Map();
3714
+ for (const page of outline.pages) {
3715
+ const docs = groups.get(page.group) ?? [];
3716
+ docs.push(outlineDocId(page.path));
3717
+ groups.set(page.group, docs);
3718
+ }
3719
+ return [...groups].map(([group, pages]) => ({ group, pages }));
3720
+ }
3721
+ function normalizeHeading(text) {
3722
+ return text.toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim();
3723
+ }
3724
+ function outlineCoverage(outline, pages) {
3725
+ const byPath = new Map(pages.map((page) => [page.path, page.content]));
3726
+ const planned = new Set(outline.pages.map((page) => page.path));
3727
+ const missing_pages = [];
3728
+ const missing_sections = [];
3729
+ for (const entry of outline.pages) {
3730
+ const content = byPath.get(entry.path);
3731
+ if (content === void 0) {
3732
+ missing_pages.push(entry.path);
3733
+ continue;
3734
+ }
3735
+ const rawLines = content.split(/\r?\n/);
3736
+ const present = new Set(
3737
+ headingsOf(blankNonProse(content)).filter((h) => h.level >= 2).map((h) => normalizeHeading((rawLines[h.index] ?? "").replace(/^\s{0,3}#{1,6}\s+/, "").replace(/\s*#*\s*$/, "")))
3738
+ );
3739
+ for (const section of entry.sections) {
3740
+ if (!present.has(normalizeHeading(section))) missing_sections.push({ path: entry.path, section });
3741
+ }
3742
+ }
3743
+ const unplanned_pages = pages.filter((page) => !planned.has(page.path)).map((page) => page.path);
3744
+ return {
3745
+ complete: missing_pages.length === 0 && unplanned_pages.length === 0 && missing_sections.length === 0,
3746
+ missing_pages,
3747
+ unplanned_pages,
3748
+ missing_sections
3749
+ };
3750
+ }
3751
+ function contentContract() {
3752
+ return {
3753
+ abi_version: SOURCE_ABI_VERSION,
3754
+ roots: SOURCE_ALLOWED_ROOTS,
3755
+ extensions: SOURCE_ALLOWED_EXTENSIONS,
3756
+ limits: SOURCE_LIMITS,
3757
+ frontmatter: { keys: [...ADMISSIBLE_FRONTMATTER_KEYS], page_layouts: ["docs", "landing"] },
3758
+ components: pageSourceComponents(),
3759
+ outline_schema: outlineJsonSchema()
3760
+ };
3761
+ }
3762
+
3763
+ export {
3764
+ SOURCE_ABI_VERSION,
3765
+ SOURCE_LIMITS,
3766
+ SOURCE_ALLOWED_ROOTS,
3767
+ SOURCE_ALLOWED_EXTENSIONS,
3768
+ RESERVED_URL_PREFIXES,
3769
+ REJECTED_GENERATED_ROOTS,
3770
+ REJECTED_GENERATED_FILENAMES,
3771
+ SOURCE_MEDIA_TYPES,
3772
+ canonicalizeSourcePath,
3773
+ detectSourceMediaType,
3774
+ GIT_COMMIT_PATTERN,
3775
+ blobId,
3776
+ canonicalizeRevisionManifest,
3777
+ revisionId,
3778
+ SourceAbiError,
3779
+ applyChangeSet,
3780
+ validateBundleStructure,
3781
+ validatePageSource,
3782
+ pageSourceComponents,
3783
+ RUNBOOK_MIN_STEPS,
3784
+ RUNBOOK_MAX_STEPS,
3785
+ RUNBOOK_MAX_STEP_WORDS,
3786
+ RUNBOOK_TARGETS,
3787
+ runbookProblems,
3788
+ ADMISSIBLE_FRONTMATTER_KEYS,
3789
+ validateBundleSemantics,
3790
+ validateBundleSemanticsAsync,
3791
+ VIOLATION_GUIDANCE,
3792
+ violationGuidance,
3793
+ SELF_CONTRADICTING_COUNT,
3794
+ INCONSISTENT_VALUE_LIST,
3795
+ blankNonProse,
3796
+ headingsOf,
3797
+ lintContent,
3798
+ changedLineIndexes,
3799
+ extractClaimTokens,
3800
+ groundTokens,
3801
+ KNOWN_PITFALL_CODE,
3802
+ KNOWN_PITFALLS,
3803
+ checkPitfalls,
3804
+ TAR_BLOCK_SIZE,
3805
+ TAR_TRAILER_SIZE,
3806
+ tarPadding,
3807
+ tarHeader,
3808
+ paxRecord,
3809
+ resolveHref,
3810
+ extractLinks,
3811
+ findUnresolvedLinks,
3812
+ PRODUCT_KINDS,
3813
+ OutlineSchema,
3814
+ parseOutline,
3815
+ outlineJsonSchema,
3816
+ outlineDocId,
3817
+ navigationFromOutline,
3818
+ normalizeHeading,
3819
+ outlineCoverage,
3820
+ contentContract
3821
+ };