@writedocs/generator 0.1.0 → 0.2.1

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.
@@ -0,0 +1,1004 @@
1
+ // O schema do writedocs.json, e nada alem disso.
2
+ //
3
+ // Este arquivo era as primeiras 875 linhas do config.ts (que continua
4
+ // reexportando tudo daqui, entao nada que importa de './config.js' mudou). A
5
+ // separacao existe por um motivo concreto: o config.ts importa node:fs,
6
+ // node:path e gray-matter no topo pras funcoes que leem o disco, e o
7
+ // package.json passou a exportar './config-schema' pra que a plataforma
8
+ // (writedocs-application) possa importar o schema DE VERDADE - o mesmo que o
9
+ // build usa - em vez de manter uma copia que diverge em algumas semanas. Um
10
+ // Worker da Cloudflare nao consegue importar um modulo que traz node:fs junto.
11
+ //
12
+ // Por isso a unica dependencia aqui e o zod. Nada neste arquivo pode passar a
13
+ // tocar o sistema de arquivos: se precisar de fs/path, o lugar e o config.ts.
14
+ //
15
+ // ESTE arquivo e a fonte de verdade, mas NAO e o que o pacote publica: o script
16
+ // `prepare` (package.json) transpila ele pra ./config-schema.js, e e o `.js` que
17
+ // o `exports` e o bin/writedocs.js apontam. Sem isso o `writedocs validate`
18
+ // quebra pra quem instala o pacote - o Node recusa type stripping sob
19
+ // node_modules. Editou aqui, rode `npm run build:schema` (ou qualquer
20
+ // `npm install`) antes de testar o caminho da CLI ou da plataforma.
21
+ //
22
+ // (`zod` e nao `astro/zod`: as duas especificacoes resolvem pra mesma instalacao
23
+ // - node_modules/zod 4.4.3, que e o que astro@7.2.2 tambem pede via `^4.3.6` -
24
+ // entao a troca nao muda comportamento nenhum, so tira o astro do caminho de
25
+ // quem importa isto de fora do gerador.)
26
+ import { z } from 'zod';
27
+
28
+ // ---------------------------------------------------------------------
29
+ // Pages & groups - the leaf content any container ultimately bottoms out
30
+ // at. A group can nest other groups arbitrarily deep, and can optionally
31
+ // link its own label to a page (`page`) independent of expanding or
32
+ // collapsing its children - see NavTree.astro for how that renders.
33
+ // ---------------------------------------------------------------------
34
+
35
+ const navPageSchema = z.string();
36
+
37
+ // A group ordinarily lists its own children by hand (`pages`), but can
38
+ // instead auto-generate them from an OpenAPI spec via `openapi: { src,
39
+ // path }` - resolved by loadDocsConfig() (via expandOpenApiInNavigation()
40
+ // below, reading the manifest generate-api-pages.js writes for this exact
41
+ // group) into a real `{ group, pages }` node - one sub-group per tag -
42
+ // before anything else in this file ever sees it, so
43
+ // resolveSections()/flattenNav()/buildNavTree()/etc. only ever need to
44
+ // understand the ordinary pages-array shape. `.strict()` on both variants
45
+ // is load-bearing (see withChildren()'s own comment on this pattern
46
+ // below): without it, a group written with both `pages` and `openapi` at
47
+ // once would silently have one dropped instead of rejected.
48
+ const navGroupPagesSchema: z.ZodType<{ group: string; page?: string; pages: NavItem[] }> = z.lazy(() =>
49
+ z
50
+ .object({
51
+ group: z.string(),
52
+ page: z.string().optional(),
53
+ pages: z.array(navItemSchema),
54
+ })
55
+ .strict()
56
+ );
57
+
58
+ const navGroupOpenApiSchema = z.object({
59
+ group: z.string(),
60
+ openapi: z
61
+ .object({
62
+ // Path to an OpenAPI 3.x spec, relative to the content directory
63
+ // (alongside writedocs.json) - same convention the old top-level
64
+ // `openapi` field used. See generate-api-pages.js (the pre-Astro
65
+ // build/dev step that actually parses this and writes the
66
+ // manifest/operation JSON this group's pages are expanded from).
67
+ src: z.string(),
68
+ // Base URL path every page generated from this spec is namespaced
69
+ // under, e.g. "/api" -> pages served at /api/<tag>/<operation>/.
70
+ // Also doubles as this spec's own unique key under
71
+ // writedocsTempDir()'s openapi/<path>/ directory (manifest.json + operations/*.json),
72
+ // so two openapi groups in the same writedocs.json must use different
73
+ // `path` values - generate-api-pages.js throws a clear error if
74
+ // they collide.
75
+ path: z.string(),
76
+ })
77
+ .strict(),
78
+ }).strict();
79
+
80
+ export type GroupNavItem =
81
+ | { group: string; page?: string; pages: NavItem[] }
82
+ | { group: string; openapi: { src: string; path: string } };
83
+
84
+ const navGroupSchema: z.ZodType<GroupNavItem> = z.union([navGroupPagesSchema, navGroupOpenApiSchema]);
85
+
86
+ // A bare external link sitting directly in a `pages` array, alongside
87
+ // page slugs and groups - e.g. a "Support" link to an external help
88
+ // desk shown right in the sidebar, rather than only reachable via
89
+ // navigation.global.dropdowns. Discriminated from navGroupSchema by
90
+ // its required `label`/`href` keys (vs `group`/`pages`/`openapi`), so a
91
+ // plain (non-strict at the union level) schema is enough for Zod to pick
92
+ // the right branch; `.strict()` here still catches a typo'd extra key.
93
+ const navLinkSchema = z.object({ label: z.string(), href: z.string() }).strict();
94
+
95
+ const navItemSchema: z.ZodType<NavItem> = z.lazy(() =>
96
+ z.union([navPageSchema, navGroupSchema, navLinkSchema])
97
+ );
98
+
99
+ export type NavItem = string | GroupNavItem | { label: string; href: string };
100
+
101
+ // ---------------------------------------------------------------------
102
+ // Containers: tabs, versions, languages, dropdowns, products.
103
+ //
104
+ // This schema is modeled directly on Mintlify's writedocs.json
105
+ // (https://mintlify.com/writedocs.json / mintlify.com/docs/organize/navigation):
106
+ // all five container kinds are structurally identical except for their
107
+ // own identifying field. Each owns *exactly one* of {pages, tabs,
108
+ // versions, languages, dropdowns, products} as its content, or is a bare
109
+ // external `href` link with no content of its own. That symmetry is what
110
+ // lets any of them nest inside any other - a tab can contain versions, a
111
+ // version can contain languages, a language can contain tabs, and so on,
112
+ // bottoming out at a `pages` array. `withChildren()` is the single place
113
+ // that shape is defined, instead of hand-writing the union five times.
114
+ // ---------------------------------------------------------------------
115
+
116
+ export type NavChildren =
117
+ | { pages: NavItem[] }
118
+ | { tabs: TabItem[] }
119
+ | { versions: VersionItem[] }
120
+ | { languages: LanguageItem[] }
121
+ | { dropdowns: DropdownItem[] }
122
+ | { products: ProductItem[] }
123
+ | { href: string };
124
+
125
+ export type TabItem = { tab: string; icon?: string } & NavChildren;
126
+ export type VersionItem = { version: string; label?: string; tag?: string; default?: boolean } & NavChildren;
127
+ export type LanguageItem = { language: string; label?: string } & NavChildren;
128
+ export type DropdownItem = { dropdown: string; icon?: string } & NavChildren;
129
+ export type ProductItem = { product: string; icon?: string; description?: string } & NavChildren;
130
+
131
+ // `.strict()` on every variant is load-bearing, not decoration: Zod
132
+ // objects silently strip unrecognized keys by default, so without it a
133
+ // node written with two children fields at once (e.g. both `pages` and
134
+ // `versions`) would just have the second one dropped instead of
135
+ // rejected - defeating the entire "exactly one child kind per level"
136
+ // rule this schema exists to enforce (mirroring Mintlify's own "a tab
137
+ // cannot contain both anchors and groups at the same level").
138
+ function withChildren<Base extends z.ZodRawShape>(base: Base) {
139
+ return z.union([
140
+ z.object({ ...base, pages: z.array(navItemSchema) }).strict(),
141
+ z.object({ ...base, tabs: z.array(tabSchema).min(1) }).strict(),
142
+ z.object({ ...base, versions: z.array(versionSchema).min(1) }).strict(),
143
+ z.object({ ...base, languages: z.array(languageSchema).min(1) }).strict(),
144
+ z.object({ ...base, dropdowns: z.array(dropdownSchema).min(1) }).strict(),
145
+ z.object({ ...base, products: z.array(productSchema).min(1) }).strict(),
146
+ z.object({ ...base, href: z.string() }).strict(),
147
+ ]);
148
+ }
149
+
150
+ // Each of these five is defined via z.lazy() because withChildren()
151
+ // references all five by name (mutual recursion) - safe because none of
152
+ // them are actually *called* until a real writedocs.json is parsed, by which
153
+ // point every const below has been assigned. The same pattern already
154
+ // used for navItemSchema/navGroupSchema above.
155
+ const tabSchema: z.ZodType<TabItem> = z.lazy(() =>
156
+ withChildren({ tab: z.string(), icon: z.string().optional() })
157
+ );
158
+
159
+ const versionSchema: z.ZodType<VersionItem> = z.lazy(() =>
160
+ withChildren({
161
+ version: z.string(),
162
+ label: z.string().optional(),
163
+ tag: z.string().optional(),
164
+ default: z.boolean().optional(),
165
+ })
166
+ );
167
+
168
+ const languageSchema: z.ZodType<LanguageItem> = z.lazy(() =>
169
+ withChildren({ language: z.string(), label: z.string().optional() })
170
+ );
171
+
172
+ const dropdownSchema: z.ZodType<DropdownItem> = z.lazy(() =>
173
+ withChildren({ dropdown: z.string(), icon: z.string().optional() })
174
+ );
175
+
176
+ const productSchema: z.ZodType<ProductItem> = z.lazy(() =>
177
+ withChildren({ product: z.string(), icon: z.string().optional(), description: z.string().optional() })
178
+ );
179
+
180
+ // ---------------------------------------------------------------------
181
+ // Root navigation: a flat array (shorthand for one implicit section - the
182
+ // common case) or an object choosing exactly one primary organizational
183
+ // pattern, per Mintlify's convention ("choose one primary organizational
184
+ // pattern at the root level of your navigation").
185
+ //
186
+ // `global.dropdowns` is the one exception to "exactly one pattern": it's
187
+ // not a primary pattern, it's a persistent set of topbar dropdown
188
+ // triggers that render on every page regardless of which tab/version/
189
+ // language/product is active - equivalent to Mintlify's
190
+ // `navigation.global.anchors`. This replaces the earlier `{tabs,
191
+ // dropdowns}` shape (both present at once), which doesn't generalize
192
+ // once versions/languages/products are also root-level choices.
193
+ // ---------------------------------------------------------------------
194
+
195
+ export type NavigationConfig =
196
+ | NavItem[]
197
+ | { global?: { dropdowns: DropdownItem[] }; tabs: TabItem[] }
198
+ | { global?: { dropdowns: DropdownItem[] }; versions: VersionItem[] }
199
+ | { global?: { dropdowns: DropdownItem[] }; languages: LanguageItem[] }
200
+ | { global?: { dropdowns: DropdownItem[] }; dropdowns: DropdownItem[] }
201
+ | { global?: { dropdowns: DropdownItem[] }; products: ProductItem[] };
202
+
203
+ const globalSchema = z.object({ dropdowns: z.array(dropdownSchema).min(1) });
204
+
205
+ const navigationSchema = z.union([
206
+ z.array(navItemSchema),
207
+ z.object({ global: globalSchema.optional(), tabs: z.array(tabSchema).min(1) }).strict(),
208
+ z.object({ global: globalSchema.optional(), versions: z.array(versionSchema).min(1) }).strict(),
209
+ z.object({ global: globalSchema.optional(), languages: z.array(languageSchema).min(1) }).strict(),
210
+ z.object({ global: globalSchema.optional(), dropdowns: z.array(dropdownSchema).min(1) }).strict(),
211
+ z.object({ global: globalSchema.optional(), products: z.array(productSchema).min(1) }).strict(),
212
+ ]) as z.ZodType<NavigationConfig>;
213
+
214
+ const DEFAULT_PRIMARY = '#6366f1';
215
+
216
+ // A logo is either one path used for both color modes, or a
217
+ // { light, dark, label } object - each image shown only while that mode
218
+ // is active (see BaseLayout.astro's .wd-logo-light/.wd-logo-dark CSS).
219
+ // The topbar shows *only* the image by default - no site name text next
220
+ // to it, since a real logo asset usually already is a wordmark. `label`
221
+ // is the opt-in way to add text back next to the image (e.g. a product
222
+ // name alongside a symbol-only mark); it only exists on the object form,
223
+ // since a single shared image path is just as easy to bake the label
224
+ // into directly.
225
+ //
226
+ // `light`/`dark` are themselves optional (unlike the string form, which
227
+ // is inherently "both"): a site with no logo *images* at all can still
228
+ // set `styles.logo: { label: "..." }` to override the topbar's fallback
229
+ // text without providing any image - see BaseLayout.astro's
230
+ // hasLogoImage/logoLabel/brandLabel derivation, where an object with
231
+ // only `label` set already resolves correctly (brandLabel = logoLabel,
232
+ // same as if an image were also present) without needing any change
233
+ // there; only this schema needed loosening; light/dark were previously
234
+ // both required whenever the object form was used at all.
235
+ //
236
+ // Standalone const (rather than inlined into stylesSchema.logo below) so
237
+ // footer.logo further down can share the exact same union instead of an
238
+ // independently-written copy - see footerSchema's own comment on why a
239
+ // footer logo needs this at all.
240
+ const logoSchema = z.union([
241
+ z.string(),
242
+ z.object({ light: z.string().optional(), dark: z.string().optional(), label: z.string().optional() }).strict(),
243
+ ]);
244
+
245
+ // Same {light, dark}-with-fallback shape applies to `colors.dark`: any
246
+ // of primary/text left unset there falls back to the light-mode value
247
+ // already given above, so a site only has to specify what actually
248
+ // differs in dark mode. There used to be a `background`/`dark.background`
249
+ // pair here too, doing effectively the same job as `background.colors`
250
+ // further down (see that field's own comment) - two writedocs.json fields
251
+ // both named "background" that visually looked interchangeable but
252
+ // weren't quite (one drove --wd-background site-wide, the other only
253
+ // the <body> canvas), which was confusing to author against and easy to
254
+ // half-configure by setting only one. Removed in favor of `background`
255
+ // alone being the single place to set any background color - see that
256
+ // field's comment for what it now covers.
257
+ // One side of `styles.navbar` (light or dark) - either a bare background
258
+ // color (the original shape) or `{ background, accent? }` once a site
259
+ // wants its own accent color (the active-tab fill / hover underline)
260
+ // inside the navbar specifically, independent of the sitewide
261
+ // `styles.colors.primary`. Deliberately does NOT carry a text/icon color
262
+ // field at all - see `navbar`'s own comment below (stylesSchema) for why
263
+ // that's resolved automatically instead of being configurable. Kept as a
264
+ // standalone const rather than inlined so `light`/`dark` share the exact
265
+ // same union rather than two independently-written (and possibly
266
+ // drifting) copies of it.
267
+ const navbarColorValueSchema = z.union([
268
+ z.string(),
269
+ z
270
+ .object({
271
+ background: z.string(),
272
+ accent: z.string().optional(),
273
+ })
274
+ .strict(),
275
+ ]);
276
+
277
+ // One font declaration - almost exactly Mintlify's own `fonts` shape (see
278
+ // docs/dev/docs/site-config.mdx's own "Fonts" section for the research this
279
+ // was based on): a bare Google Fonts family name (`family` alone - Google
280
+ // Fonts loads it automatically, see googleFontsHref() below), or a local/
281
+ // externally-hosted font file (`source` + `format` together; `source` is
282
+ // either a project-relative path like the other five asset-fallback fields
283
+ // this schema already has - see collectConfiguredAssetPaths() - or a full
284
+ // https:// URL to an externally-hosted font). `weight` does two things at
285
+ // once, both driven by BaseLayout.astro: it narrows which file actually
286
+ // loads (folded into the Google Fonts URL's `:wght@` axis, or the
287
+ // generated `@font-face` rule's own `font-weight` descriptor for a
288
+ // `source` font - see googleFontsHref()/fontFaceRule() below), *and* it's
289
+ // applied as a real CSS `font-weight` on h1-h6 (for `heading`) or `body`
290
+ // (for `body`) - see BaseLayout's own `wdFontWeightHeading`/
291
+ // `wdFontWeightBody`. Both halves matter: loading only the 400-weight file
292
+ // while leaving h1-h6 at the browser's UA-default `font-weight: bold`
293
+ // faux-bolds that file back to looking bold anyway, with no visible
294
+ // change from configuring a lighter weight at all - the bug this second
295
+ // half fixes (caught from real user-reported behavior, not anticipated
296
+ // up front). Left unset anywhere in `styles.fonts` renders no font-weight
297
+ // rule at all, keeping today's plain browser-default bold headings/normal
298
+ // body text unchanged for a site that hasn't touched this field.
299
+ const fontVariantSchema = z
300
+ .object({
301
+ family: z.string(),
302
+ weight: z.number().optional(),
303
+ source: z.string().optional(),
304
+ format: z.enum(['woff', 'woff2']).optional(),
305
+ })
306
+ .strict();
307
+
308
+ export type FontVariant = z.infer<typeof fontVariantSchema>;
309
+
310
+ // The top-level shape adds `heading`/`body`: each independently optional,
311
+ // each falling back to the top-level family/weight/source/format when
312
+ // unset (see resolveFonts() below) - so a site can set one font for
313
+ // everything (`fonts.family` alone), or split headings and body text
314
+ // without needing to repeat itself for whichever side isn't changing.
315
+ const fontsSchema = z
316
+ .object({
317
+ family: z.string(),
318
+ weight: z.number().optional(),
319
+ source: z.string().optional(),
320
+ format: z.enum(['woff', 'woff2']).optional(),
321
+ heading: fontVariantSchema.optional(),
322
+ body: fontVariantSchema.optional(),
323
+ })
324
+ .strict();
325
+
326
+ export type FontsConfig = z.infer<typeof fontsSchema>;
327
+
328
+ const stylesSchema = z
329
+ .object({
330
+ colors: z
331
+ .object({
332
+ primary: z.string().default(DEFAULT_PRIMARY),
333
+ text: z.string().optional(),
334
+ dark: z
335
+ .object({
336
+ primary: z.string().optional(),
337
+ text: z.string().optional(),
338
+ })
339
+ .optional(),
340
+ })
341
+ .default({ primary: DEFAULT_PRIMARY }),
342
+ logo: logoSchema.optional(),
343
+ favicon: z.string().optional(),
344
+ // No default value here (unlike `colors.primary`'s DEFAULT_PRIMARY) -
345
+ // resolveFonts() below is where "Inter" actually gets applied as the
346
+ // site-wide default whenever this field is left unset entirely, so
347
+ // that fallback lives in one place alongside the rest of the
348
+ // resolution logic rather than being duplicated as a schema default
349
+ // *and* a resolver fallback.
350
+ fonts: fontsSchema.optional(),
351
+ // The Shiki theme *name* (not a full theme object/JSON - see
352
+ // https://shiki.style/themes for the built-in list) each fenced
353
+ // (```) MDX code block, and the API playground's request/response
354
+ // snippets, use in light/dark mode - read out of writedocs.json by both
355
+ // astro.config.mjs (Shiki's dual-theme markdown config) and
356
+ // ApiReferencePanel.astro (its own separate <Code/> usages, which
357
+ // don't inherit markdown.shikiConfig) via resolveCodeblockTheme()
358
+ // below, the single source of truth for the 'github-light'/
359
+ // 'github-dark' fallback. Left per-key optional (not defaulted in
360
+ // the schema itself) so a site can override just one side (e.g.
361
+ // only `dark`) and still get the ordinary default for the other.
362
+ codeblocks: z
363
+ .object({
364
+ light: z.string().optional(),
365
+ dark: z.string().optional(),
366
+ // Maps a fenced (```) block's own language tag to whichever real
367
+ // Shiki grammar actually highlights it, before that tag ever
368
+ // reaches Shiki - see resolveCodeblockLangAlias() below for the
369
+ // one built-in entry (mdx -> jsx) this ships with by default and
370
+ // why. A site can add its own entries for any other language tag
371
+ // that either doesn't tokenize well under its own grammar, or
372
+ // that a site wants to write under a shorter/friendlier fence tag
373
+ // than Shiki's own bundled id (e.g. `groovy: 'java'` for a close-
374
+ // enough approximation Shiki doesn't ship a dedicated grammar for
375
+ // at all) - merged with, not replacing, the built-in default, so
376
+ // adding one of a site's own doesn't require re-declaring mdx.
377
+ langAlias: z.record(z.string(), z.string()).optional(),
378
+ })
379
+ .strict()
380
+ .optional(),
381
+ // The topbar's own background, independent of `background` below (the
382
+ // page's) - a site may want its navbar to stand out (a dark or
383
+ // brand-colored bar over a light page) rather than blend into the
384
+ // page, which is the default when this is left unset. Same {light,
385
+ // dark} shape (and same per-key-optional, not defaulted here) as
386
+ // `codeblocks` right above, rather than nested under `colors` - it's a
387
+ // topbar-specific override, not a third general-purpose page color, so
388
+ // it reads more like "one more themed surface" alongside codeblocks
389
+ // than a sibling of primary/text. BaseLayout.astro's own
390
+ // lightNavbarBg/darkNavbarBg resolution is what falls each side back
391
+ // to the page background when unset.
392
+ //
393
+ // Each side (`light`/`dark`) is either a bare string - just the
394
+ // background color, exactly the original shape, kept for backwards
395
+ // compatibility - or `{ background, accent? }`, for when a site also
396
+ // wants the navbar's own active-tab-fill/hover-underline color to
397
+ // differ from the sitewide `styles.colors.primary` (`accent`'s only
398
+ // job - see BaseLayout.astro's lightNavbarAccent). Deliberately no
399
+ // text/icon color field here at all: BaseLayout.astro always resolves
400
+ // the navbar's plain text/icon color itself, picking black or white by
401
+ // contrast against whatever `background` resolves to
402
+ // (contrastTextColor() below) the moment this field is configured at
403
+ // all (string or object) - never a value read from writedocs.json. A
404
+ // manually-set text color is a legibility footgun a site author can
405
+ // get wrong (or drift out of sync after later changing `background`
406
+ // without remembering to update it too) in a way "compute it
407
+ // correctly, every time" simply can't - there's no legitimate reason
408
+ // to want *illegible* navbar text, unlike `accent`, which is a real
409
+ // aesthetic choice. Real bug this fixes: a site setting `navbar.light`
410
+ // to the same value as `colors.primary` (a plausible thing to reach
411
+ // for - "brand-colored navbar") made every topbar label/icon/link
412
+ // render in the default near-black text color against that same
413
+ // saturated background, all but unreadable - and an earlier version of
414
+ // this feature that let a writedocs.json-supplied color double as the text
415
+ // color reintroduced the identical bug one level down, just requiring
416
+ // one more (still guessable-wrong) field to trigger it.
417
+ navbar: z
418
+ .object({
419
+ light: navbarColorValueSchema.optional(),
420
+ dark: navbarColorValueSchema.optional(),
421
+ })
422
+ .strict()
423
+ .optional(),
424
+ // The single place to configure any background color: `colors` is a
425
+ // solid color (falls back to '#ffffff'/'#0b1120' when unset - see
426
+ // BaseLayout.astro's lightBackground/darkBackground resolution), and
427
+ // `images` layers an image on top of it (or is the whole background
428
+ // by itself, if `colors` is left at its default). This one pair now
429
+ // drives everything background-related site-wide - --wd-background
430
+ // (dropdowns/modals/kbd chips/footer/topbar-fallback/etc., see every
431
+ // `var(--wd-background)` call site) *and* the <body> canvas behind the
432
+ // main/toc columns - rather than the two being independently
433
+ // configurable fields that happened to look alike but didn't affect
434
+ // the same things (see this schema's own comment on `colors.dark`
435
+ // above for why that split was removed). Both are per-mode optional,
436
+ // same "only specify what differs" pattern as codeblocks/navbar above.
437
+ // The topbar and footer still get their own explicit opaque
438
+ // background (topbar.css/footer.css) specifically so an `images`
439
+ // background doesn't show through them; see those files' own
440
+ // comments. The sidebar column has no background of its own (base.css)
441
+ // and lets it show through, same as the main/toc columns.
442
+ background: z
443
+ .object({
444
+ colors: z
445
+ .object({
446
+ light: z.string().optional(),
447
+ dark: z.string().optional(),
448
+ })
449
+ .strict()
450
+ .optional(),
451
+ images: z
452
+ .object({
453
+ light: z.string().optional(),
454
+ dark: z.string().optional(),
455
+ })
456
+ .strict()
457
+ .optional(),
458
+ })
459
+ .strict()
460
+ .optional(),
461
+ })
462
+ .default({ colors: { primary: DEFAULT_PRIMARY } });
463
+
464
+ // `href` is always required - a link with nowhere to go isn't a link.
465
+ // `label`/`icon` are each individually optional, but not both at once
466
+ // (enforced by the .refine() below, same shape as scriptEntrySchema's own
467
+ // exactly-one-of check above) - a link needs *something* visible to render,
468
+ // whichever of the two, and can have both (icon rendered to the left of the
469
+ // label - see TopBar.astro/SiteFooter.astro, the two renderers of this
470
+ // shape). An icon-only link (no label) is the common case for something
471
+ // like a bare GitHub mark in the topbar; label-only (no icon) is every
472
+ // plain text link this already supported before `icon` existed - both
473
+ // still need to keep working unchanged, hence neither field being outright
474
+ // required on its own.
475
+ const topbarLinkSchema = z
476
+ .object({
477
+ label: z.string().optional(),
478
+ href: z.string(),
479
+ // Same string shape as every other writedocs.json `icon` field (a plain
480
+ // Lucide name, or the explicit "collection:icon-name" form for
481
+ // anything else - see resolveIcon()/AppIcon.astro) - not documented
482
+ // again here since that convention is already established elsewhere
483
+ // in this file (tabs/switchers/socials all take the identical shape).
484
+ icon: z.string().optional(),
485
+ })
486
+ .strict()
487
+ .refine((link) => Boolean(link.label) || Boolean(link.icon), {
488
+ message: 'Each topbar.links/footer column link needs a "label", an "icon", or both - a link with neither has nothing to render.',
489
+ });
490
+
491
+ // One column of the footer (BaseLayout.astro's <footer class="wd-footer">) -
492
+ // an optional heading (e.g. "Resources", "Community") plus a list of links,
493
+ // reusing the exact same {label, icon, href} shape as topbar.links above (a
494
+ // footer link is the same thing rendered in a different place, no reason
495
+ // for a second, identical-but-differently-named schema). `title` is
496
+ // optional so a single-column footer with no heading (just a bare list of
497
+ // links) is valid too.
498
+ const footerColumnSchema = z
499
+ .object({
500
+ title: z.string().optional(),
501
+ links: z.array(topbarLinkSchema).default([]),
502
+ })
503
+ .strict();
504
+
505
+ // Off by default (empty `columns`, same convention as `topbar` above - a
506
+ // footer with nothing configured just doesn't render at all, see
507
+ // BaseLayout.astro's `hasFooterContent` check) rather than `.optional()`
508
+ // like contextMenu: unlike that field, an empty/default footer has no
509
+ // build-output or routing implications to gate, it's purely visual, so
510
+ // there's no reason to distinguish "unset" from "set to nothing" the way
511
+ // contextMenu needs to.
512
+ // Same {light, dark, label} union as `styles.logo` (via the shared
513
+ // logoSchema above) - unset by default, in which case the footer just
514
+ // shows the sitewide `styles.logo` (BaseLayout.astro's existing
515
+ // logoLight/logoDark/logoLabel, already threaded into SiteFooter as-is).
516
+ // Set here, it replaces that entirely rather than filling in only the
517
+ // missing side of it - a footer.logo with only `dark` set shows *just*
518
+ // the dark-mode image, not styles.logo's light image plus this dark one -
519
+ // the same all-or-nothing-relative-to-styles.logo resolution BaseLayout.astro
520
+ // already applies.
521
+ const footerSchema = z
522
+ .object({
523
+ columns: z.array(footerColumnSchema).default([]),
524
+ logo: logoSchema.optional(),
525
+ })
526
+ .strict()
527
+ .default({ columns: [] });
528
+
529
+ export type FooterColumn = z.infer<typeof footerColumnSchema>;
530
+ export type FooterConfig = z.infer<typeof footerSchema>;
531
+
532
+ // Shared by both writedocs.json's top-level `seo` (site-wide defaults) and a
533
+ // page's own frontmatter `seo` (per-page overrides) - see
534
+ // content.config.ts's docsSchema, which imports this exact schema rather
535
+ // than redeclaring the same shape a second time. mergeSeo() below is what
536
+ // actually combines the two, field by field, at render time.
537
+ export const seoFieldsSchema = z
538
+ .object({
539
+ // Open Graph / Twitter card image - a relative path (resolved against
540
+ // `domain` below into an absolute URL, since most social crawlers
541
+ // require one) or an already-absolute https:// URL.
542
+ ogImage: z.string().optional(),
543
+ // og:type - "website" for most pages, "article" for blog-post-shaped
544
+ // content, etc. Defaults to "website" if never set anywhere.
545
+ ogType: z.string().optional(),
546
+ twitterCard: z.enum(['summary', 'summary_large_image']).optional(),
547
+ keywords: z.array(z.string()).optional(),
548
+ // Renders <meta name="robots" content="noindex, nofollow" /> and
549
+ // (see astro.config.mjs's sitemap `filter`) excludes the page from
550
+ // sitemap.xml entirely - both driven off this one flag, since listing
551
+ // a page in the sitemap while also telling crawlers not to index it
552
+ // would be self-contradictory.
553
+ noindex: z.boolean().optional(),
554
+ })
555
+ .strict();
556
+
557
+ export type SeoFields = z.infer<typeof seoFieldsSchema>;
558
+
559
+ /** Field-by-field merge of a page's own `seo` frontmatter over writedocs.json's
560
+ * site-wide `seo` defaults - a page only overrides the specific fields it
561
+ * sets, falling back to the site default for everything else, rather than
562
+ * a page's (possibly partial) `seo` object replacing the site's wholesale. */
563
+ export function mergeSeo(site: SeoFields, page?: SeoFields): SeoFields {
564
+ if (!page) return site;
565
+ return {
566
+ ogImage: page.ogImage ?? site.ogImage,
567
+ ogType: page.ogType ?? site.ogType,
568
+ twitterCard: page.twitterCard ?? site.twitterCard,
569
+ keywords: page.keywords ?? site.keywords,
570
+ noindex: page.noindex ?? site.noindex,
571
+ };
572
+ }
573
+
574
+ // Controls for the OpenAPI API playground's "Try it" modal - separate
575
+ // from a group's own `openapi: { src, path }` field (which spec to use,
576
+ // and where) since this is about how a *request* it sends behaves, not
577
+ // about the spec itself.
578
+ const apiSchema = z
579
+ .object({
580
+ // Whether the Try-it modal's Send button routes its request through
581
+ // writedocs' own CORS proxy (https://proxy.writechoice.io/) rather
582
+ // than calling the API directly from the browser. Almost no
583
+ // real-world API sends back Access-Control-Allow-Origin headers
584
+ // permitting an arbitrary docs site's origin, so a direct browser
585
+ // fetch() from the Try-it modal fails for most real APIs without
586
+ // this - see PROXY_BASE_URL in ApiReferencePanel.astro for the
587
+ // actual request-forwarding logic. Defaults to enabled; a site can
588
+ // set this to `false` to always call the API directly instead (the
589
+ // API is already CORS-permissive, same-origin in some deployments,
590
+ // or the site owner doesn't want requests routed through a third
591
+ // party at all).
592
+ proxy: z.boolean().default(true),
593
+ })
594
+ .strict()
595
+ .default({ proxy: true });
596
+
597
+ // The "Copy page" dropdown shown next to a page's title - copy the raw
598
+ // Markdown to the clipboard, open the raw Markdown in a new tab, or
599
+ // deep-link into an AI assistant with a prompt pointing at it. Opt-in:
600
+ // undefined (the field simply absent from writedocs.json) means the feature
601
+ // is off entirely - no menu rendered, no .md routes generated at build
602
+ // time either (see [...slug].md.ts) - rather than defaulting to on,
603
+ // since it changes both the UI and the build output. Once a site does
604
+ // write a `contextMenu` key (even `{}`), copying/viewing-as-Markdown are
605
+ // always included (they need nothing but the page's own content); only
606
+ // `openIn` (the AI-assistant deep-links, which need an absolute URL to
607
+ // point the assistant at) is independently configurable.
608
+ const contextMenuSchema = z
609
+ .object({
610
+ openIn: z.array(z.enum(['chatgpt', 'claude', 'perplexity'])).default(['chatgpt', 'claude', 'perplexity']),
611
+ })
612
+ .strict();
613
+
614
+ export type ContextMenuConfig = z.infer<typeof contextMenuSchema>;
615
+
616
+ // One entry in writedocs.json's `redirects` array - wired almost directly into
617
+ // Astro's own `redirects` config option (astro.config.mjs), which is what
618
+ // actually generates the redirect pages. `permanent` is deliberately not
619
+ // part of this schema: with no server/adapter (this project always builds
620
+ // `output: 'static'` with none installed), Astro's own docs say a static
621
+ // redirect "does not support status codes" at all - it's always a client-
622
+ // side `<meta http-equiv="refresh">` page, full stop. Accepting a
623
+ // `permanent` field here that silently did nothing would be worse than
624
+ // not offering it.
625
+ const redirectSchema = z
626
+ .object({
627
+ source: z.string(),
628
+ destination: z.string(),
629
+ })
630
+ .strict();
631
+
632
+ export type RedirectConfig = z.infer<typeof redirectSchema>;
633
+
634
+ // A site-wide banner rendered above the topbar on every page (except
635
+ // `mode: blank`, which drops all site chrome including this - see
636
+ // BaseLayout.astro). Optional/undefined by default, same convention as
637
+ // `contextMenu` above - a site with no banner configured gets no banner
638
+ // markup at all, not an empty one.
639
+ const bannerSchema = z
640
+ .object({
641
+ content: z.string(),
642
+ // Persisted via localStorage once dismissed (see BaseLayout.astro's
643
+ // initBanner()) - a static site has no server-side session to track
644
+ // this against, so "dismissed" only ever means "dismissed in this
645
+ // browser". A banner without `dismissible` reappears on every visit,
646
+ // appropriate for something that should stay visible until the site
647
+ // author removes it from writedocs.json themselves (e.g. "this version is
648
+ // deprecated"), not something a reader can permanently clear.
649
+ dismissible: z.boolean().default(false),
650
+ type: z.enum(['info', 'warning', 'critical']).default('info'),
651
+ })
652
+ .strict();
653
+
654
+ export type BannerConfig = z.infer<typeof bannerSchema>;
655
+
656
+ // Content for the custom 404 page (src/pages/404.astro) - Astro's own
657
+ // file-based convention (a static build emits this as 404.html at the
658
+ // site root; most static hosts pick it up automatically for unmatched
659
+ // routes). Both fields are optional with hardcoded fallbacks in 404.astro
660
+ // itself, so a site doesn't have to set either to get a reasonably
661
+ // branded 404 page (still rendered inside the normal BaseLayout/topbar
662
+ // chrome, just with placeholder content).
663
+ const notFoundSchema = z
664
+ .object({
665
+ title: z.string().optional(),
666
+ description: z.string().optional(),
667
+ })
668
+ .strict()
669
+ .default({});
670
+
671
+ export type NotFoundConfig = z.infer<typeof notFoundSchema>;
672
+
673
+ // One <script> tag to inject - exactly one of `src` (an external/local
674
+ // file, rendered as `<script src="...">`) or `content` (inline JS,
675
+ // rendered via `<script is:inline set:html="...">`) has to be set, not
676
+ // both and not neither - enforced by the `.refine()` below rather than
677
+ // leaving both optional and silently rendering an empty tag if a site
678
+ // author gets this wrong.
679
+ const scriptEntrySchema = z
680
+ .object({
681
+ src: z.string().optional(),
682
+ content: z.string().optional(),
683
+ })
684
+ .strict()
685
+ .refine((v) => (v.src ? !v.content : !!v.content), {
686
+ message: 'Each scripts.head/scripts.body entry needs exactly one of "src" or "content", not both or neither.',
687
+ });
688
+
689
+ export type ScriptEntry = z.infer<typeof scriptEntrySchema>;
690
+
691
+ // Raw third-party script injection - analytics snippets, chat widgets,
692
+ // anything that needs a real <script> tag writedocs.json's own structured
693
+ // fields (styles, integrations-style config, ...) don't have a dedicated
694
+ // slot for yet. `head` renders right before </head>; `body` renders right
695
+ // before </body> (after everything else has already loaded/hydrated -
696
+ // see BaseLayout.astro), matching where a third-party script's own
697
+ // install instructions usually say to put it.
698
+ const scriptsSchema = z
699
+ .object({
700
+ head: z.array(scriptEntrySchema).default([]),
701
+ body: z.array(scriptEntrySchema).default([]),
702
+ })
703
+ .strict()
704
+ .default({ head: [], body: [] });
705
+
706
+ export type ScriptsConfig = z.infer<typeof scriptsSchema>;
707
+
708
+ // writedocs.json's `integrations` - a curated, high-value subset of analytics
709
+ // providers, each getting its own minimal config object (just the id(s)
710
+ // it actually needs) rather than requiring a site author to hand-write
711
+ // the provider's own install snippet through the generic `scripts` field
712
+ // above. This is deliberately its own thing, not built as sugar over
713
+ // `scripts` the way the roadmap once implied it might be - most of these
714
+ // providers' real snippets need `defer`/`async`/`data-*` attributes
715
+ // ScriptEntry's plain `{ src?, content? }` shape has no way to express,
716
+ // so BaseLayout.astro renders each provider with its own bespoke markup
717
+ // instead of generating a ScriptEntry array to feed through the generic
718
+ // renderer. Every snippet shape below was sourced from that provider's
719
+ // own current official docs (fetched directly, not recalled from
720
+ // training data) while building this feature - see
721
+ // docs/dev/docs/integrations.mdx for links and dates.
722
+ //
723
+ // Every provider field is optional and independent - a site can turn on
724
+ // any subset (including all of them at once, for a migration period) or
725
+ // none. No "the" analytics field; a site picks whichever provider(s) it
726
+ // actually uses.
727
+
728
+ const ga4IntegrationSchema = z
729
+ .object({
730
+ // A GA4 "Measurement ID", always shaped like "G-XXXXXXXXXX" - not
731
+ // validated against that shape here, since Google could change the
732
+ // prefix/length without this schema needing to track it.
733
+ measurementId: z.string(),
734
+ })
735
+ .strict();
736
+
737
+ const googleTagManagerIntegrationSchema = z
738
+ .object({
739
+ // A GTM container id, shaped like "GTM-XXXXXXX".
740
+ containerId: z.string(),
741
+ })
742
+ .strict();
743
+
744
+ const plausibleIntegrationSchema = z
745
+ .object({
746
+ domain: z.string(),
747
+ // Plausible's own hosted script URL by default - override for a
748
+ // self-hosted instance, a reverse-proxy path (Plausible's own
749
+ // documented way to dodge ad-blockers), or one of Plausible's
750
+ // documented script *extensions* (e.g.
751
+ // "https://plausible.io/js/script.hash.outbound-links.js").
752
+ src: z.string().default('https://plausible.io/js/script.js'),
753
+ })
754
+ .strict();
755
+
756
+ const fathomIntegrationSchema = z
757
+ .object({
758
+ // Fathom's own short "Site ID", not a full URL or measurement id.
759
+ siteId: z.string(),
760
+ })
761
+ .strict();
762
+
763
+ const posthogIntegrationSchema = z
764
+ .object({
765
+ // PostHog calls this a "project API key" (starts with "phc_") in its
766
+ // own docs - `apiKey` here rather than that exact name, matching this
767
+ // schema's own plainer naming convention for the equivalent id on
768
+ // every other provider above.
769
+ apiKey: z.string(),
770
+ // PostHog is region-sharded (US/EU) with no single universal default
771
+ // - "https://us.i.posthog.com" is PostHog's own default for a new
772
+ // project, but a site on their EU cloud (or a self-hosted instance)
773
+ // must override this to the host shown in their own project
774
+ // settings, or events silently go nowhere.
775
+ apiHost: z.string().default('https://us.i.posthog.com'),
776
+ })
777
+ .strict();
778
+
779
+ const umamiIntegrationSchema = z
780
+ .object({
781
+ websiteId: z.string(),
782
+ // Unlike Plausible/PostHog, Umami has no single hosted default that
783
+ // works for most users - it's commonly self-hosted, and even Umami
784
+ // Cloud users get a per-region script URL. Defaults to Umami Cloud's
785
+ // own documented script URL, which only happens to be correct for a
786
+ // Cloud user on that specific region; anyone self-hosting (the more
787
+ // common case for this particular provider) must override it to
788
+ // their own instance's own /script.js path.
789
+ src: z.string().default('https://cloud.umami.is/script.js'),
790
+ })
791
+ .strict();
792
+
793
+ // AI chat over the site's own docs content, via a third-party provider
794
+ // (DocsBot, currently the only one wired up) rather than a self-hosted
795
+ // RAG pipeline - see the roadmap's own "AI chat over docs content" line
796
+ // in docs/dev/docs/roadmap.mdx, which this fulfills via integration
797
+ // rather than by building the retrieval/generation stack in-house.
798
+ // Deliberately named `askAi` here, not `docsbot` - this is the
799
+ // writedocs.json-facing, provider-neutral name for the feature (matching
800
+ // the "Ask AI" label this kind of button/widget is conventionally
801
+ // given in docs sites generally), independent of which vendor happens
802
+ // to sit behind it today. `id` matches DocsBot's own embed config
803
+ // field name exactly (`DocsBotAI.init({ id: 'teamId/botId' })`) - it's
804
+ // a single opaque "teamId/botId" string DocsBot treats as one value,
805
+ // not two separate ids, so this schema doesn't split it either.
806
+ const askAiIntegrationSchema = z
807
+ .object({
808
+ id: z.string(),
809
+ })
810
+ .strict();
811
+
812
+ const integrationsSchema = z
813
+ .object({
814
+ ga4: ga4IntegrationSchema.optional(),
815
+ googleTagManager: googleTagManagerIntegrationSchema.optional(),
816
+ plausible: plausibleIntegrationSchema.optional(),
817
+ fathom: fathomIntegrationSchema.optional(),
818
+ posthog: posthogIntegrationSchema.optional(),
819
+ umami: umamiIntegrationSchema.optional(),
820
+ askAi: askAiIntegrationSchema.optional(),
821
+ })
822
+ .strict()
823
+ .default({});
824
+
825
+ export type IntegrationsConfig = z.infer<typeof integrationsSchema>;
826
+
827
+ export const docsConfigSchema = z.object({
828
+ name: z.string(),
829
+ description: z.string().optional(),
830
+ styles: stylesSchema,
831
+ navigation: navigationSchema,
832
+ // Platform name -> profile/page URL (e.g. `{ "github": "https://
833
+ // github.com/...", "twitter": "https://twitter.com/..." }`), free-form
834
+ // rather than an enum of known platforms - the key doubles as the icon
835
+ // reference BaseLayout.astro's footer resolves via resolveIcon() below
836
+ // (bare `"github"` -> `lucide:github`; use an explicit
837
+ // `"simple-icons:whatever"` key instead when the bare lucide name isn't
838
+ // right for a given platform). Rendered as a row of icon links in the
839
+ // footer - see hasFooterContent/`.wd-footer-socials` in BaseLayout.astro.
840
+ socials: z.record(z.string(), z.string()).default({}),
841
+ topbar: z
842
+ .object({ links: z.array(topbarLinkSchema).default([]) })
843
+ .default({ links: [] }),
844
+ // Columns of links below the page content - see footerSchema/
845
+ // footerColumnSchema above. Renders alongside `socials` above (as a row
846
+ // of icon links) in the same <footer> - see BaseLayout.astro.
847
+ footer: footerSchema,
848
+ api: apiSchema,
849
+ // The site's own deployed domain, e.g. "docs.example.com" or
850
+ // "https://docs.example.com" (the scheme is optional - resolveSiteUrl()
851
+ // below normalizes either form to a full https:// origin). Powers three
852
+ // things that all need an absolute origin to work: sitemap.xml
853
+ // generation (astro.config.mjs only registers @astrojs/sitemap when this
854
+ // is set - a sitemap of relative URLs isn't meaningful), the canonical
855
+ // <link> and og:url/twitter meta tags (BaseLayout.astro), and resolving
856
+ // a relative `seo.ogImage` into an absolute URL for social crawlers.
857
+ // Left optional and simply skipped (with a log message, not an error) at
858
+ // every one of those call sites when unset - most fixtures/local builds
859
+ // have no real deployed domain yet.
860
+ domain: z.string().optional(),
861
+ // Site-wide meta tag defaults - see seoFieldsSchema above. A page's own
862
+ // frontmatter `seo` (content.config.ts's docsSchema) overrides these
863
+ // field by field via mergeSeo(), rather than needing to repeat every
864
+ // field on every page.
865
+ seo: seoFieldsSchema.default({}),
866
+ // The "Copy page" dropdown - see contextMenuSchema above. Absent by
867
+ // default (no menu, no .md routes).
868
+ contextMenu: contextMenuSchema.optional(),
869
+ // See redirectSchema above. Wired directly into Astro's own `redirects`
870
+ // config option in astro.config.mjs.
871
+ redirects: z.array(redirectSchema).default([]),
872
+ // Site-wide `[[key]]` substitution values, applied to page prose text
873
+ // at build time (see the remarkSubstituteVariables plugin wired into
874
+ // astro.config.mjs) - e.g. `{ "productName": "Acme" }` lets every page
875
+ // write `[[productName]]` once instead of hardcoding it everywhere.
876
+ // Double square brackets, not the more familiar `{{key}}` - MDX
877
+ // reserves single curly braces for embedded JS expressions, so
878
+ // `{{productName}}` in an .mdx file parses as a JS object-literal
879
+ // expression (`{productName}`, shorthand syntax) rather than literal
880
+ // text, and throws `ReferenceError: productName is not defined` at
881
+ // render time - see remarkSubstituteVariables' own comment in
882
+ // mdx-substitute-variables.js for the full explanation. Deliberately a
883
+ // flat string map, not typed values - this is text substitution into
884
+ // prose, not a templating language.
885
+ variables: z.record(z.string(), z.string()).default({}),
886
+ // See bannerSchema above. Absent by default (no banner rendered).
887
+ banner: bannerSchema.optional(),
888
+ // See notFoundSchema above.
889
+ notFound: notFoundSchema,
890
+ // See scriptsSchema above.
891
+ scripts: scriptsSchema,
892
+ // See integrationsSchema above.
893
+ integrations: integrationsSchema,
894
+ });
895
+
896
+ export type DocsConfig = z.infer<typeof docsConfigSchema>;
897
+
898
+ // ---------------------------------------------------------------------
899
+ // Ponto de entrada unico de validacao
900
+ //
901
+ // Existe pra que o gerador (`writedocs validate` e o `loadDocsConfig` que o
902
+ // build usa) e a plataforma validem pelo MESMO codigo, com as MESMAS palavras -
903
+ // o criterio de aceite do WD-066 e do WD-062. Se cada lado formatasse os erros
904
+ // por conta propria, o cliente veria a plataforma aceitar um writedocs.json que
905
+ // o build depois recusa, que e exatamente a classe de bug que a E11 existe pra
906
+ // impedir.
907
+ //
908
+ // Recebe TEXTO CRU, e faz o JSON.parse por conta propria, por tres motivos:
909
+ // 1. um JSON sintaticamente quebrado passa a ser um resultado de validacao
910
+ // como qualquer outro, em vez de uma excecao solta do runtime;
911
+ // 2. linha/coluna so existem no texto - e o WD-063 precisa reportar linha;
912
+ // 3. do lado da plataforma, importProjectConfig ja tem os bytes crus em maos
913
+ // antes de parsear, entao encaixa sem ginastica nenhuma.
914
+ //
915
+ // IMPORTANTE, e deliberado: as mensagens aqui sao as do Zod, VERBATIM. Melhorar
916
+ // a linguagem delas e o WD-063, que precisa deste comportamento como ponto de
917
+ // partida pra medir a melhora. Nada aqui reescreve, traduz ou embeleza mensagem.
918
+ // ---------------------------------------------------------------------
919
+
920
+ /** Um problema encontrado na configuracao. `path` e o caminho do campo em
921
+ * notacao de ponto (`navigation.tabs.0.label`), ou `(root)` quando o problema e
922
+ * do documento inteiro - o mesmo texto que a mensagem de erro do build ja
923
+ * imprime hoje. `line`/`column` so vem quando da pra saber (hoje: erro de JSON;
924
+ * no WD-063, tambem para erros de schema). */
925
+ export type ValidationIssue = {
926
+ path: string;
927
+ message: string;
928
+ /** Codigo do Zod (`invalid_type`, `unrecognized_keys`, ...) ou `invalid_json`. */
929
+ code?: string;
930
+ line?: number;
931
+ column?: number;
932
+ };
933
+
934
+ /** Sucesso carrega os dados ja validados (com os defaults do schema aplicados);
935
+ * falha carrega os problemas e diz de que tipo ela foi. `parseError` so aparece
936
+ * quando o JSON nao pode nem ser parseado, e existe para o chamador que quiser
937
+ * relancar exatamente o erro original (e o que o loadDocsConfig faz, pra nao
938
+ * mudar uma virgula do que o `writedocs build` ja imprime hoje). */
939
+ export type ValidationResult =
940
+ | { ok: true; data: DocsConfig; issues: ValidationIssue[] }
941
+ | {
942
+ ok: false;
943
+ data: null;
944
+ kind: 'invalid_json' | 'schema';
945
+ issues: ValidationIssue[];
946
+ parseError?: SyntaxError;
947
+ };
948
+
949
+ /** "at position 22 (line 1 column 23)" -> { line: 1, column: 23 }.
950
+ * O formato da mensagem de erro do JSON.parse e do V8, nao do padrao, entao
951
+ * isto e melhor-esforco: se a mensagem nao trouxer posicao, devolve null e o
952
+ * problema simplesmente fica sem linha. */
953
+ function positionFromJsonError(message: string, rawText: string): { line: number; column: number } | null {
954
+ const comLinha = message.match(/line (\d+) column (\d+)/);
955
+ if (comLinha) return { line: Number(comLinha[1]), column: Number(comLinha[2]) };
956
+ const comPosicao = message.match(/position (\d+)/);
957
+ if (comPosicao) {
958
+ const pos = Math.min(Number(comPosicao[1]), rawText.length);
959
+ const antes = rawText.slice(0, pos);
960
+ const line = antes.split('\n').length;
961
+ return { line, column: pos - antes.lastIndexOf('\n') };
962
+ }
963
+ return null;
964
+ }
965
+
966
+ /** O corpo da mensagem de erro, uma linha por problema - exatamente o formato
967
+ * que o `writedocs build` imprime desde sempre (` - campo: mensagem`). Fica
968
+ * aqui, e nao em cada chamador, pra que CLI e plataforma nao possam divergir. */
969
+ export function formatValidationIssues(issues: ValidationIssue[]): string {
970
+ return issues.map((i) => ` - ${i.path}: ${i.message}`).join('\n');
971
+ }
972
+
973
+ export function validateDocsConfig(rawText: string): ValidationResult {
974
+ let raw: unknown;
975
+ try {
976
+ raw = JSON.parse(rawText);
977
+ } catch (err) {
978
+ const parseError = err as SyntaxError;
979
+ const posicao = positionFromJsonError(parseError.message, rawText);
980
+ return {
981
+ ok: false,
982
+ data: null,
983
+ kind: 'invalid_json',
984
+ parseError,
985
+ issues: [{ path: '(root)', message: parseError.message, code: 'invalid_json', ...(posicao ?? {}) }],
986
+ };
987
+ }
988
+
989
+ const result = docsConfigSchema.safeParse(raw);
990
+ if (!result.success) {
991
+ return {
992
+ ok: false,
993
+ data: null,
994
+ kind: 'schema',
995
+ issues: result.error.issues.map((i) => ({
996
+ path: i.path.join('.') || '(root)',
997
+ message: i.message,
998
+ code: i.code,
999
+ })),
1000
+ };
1001
+ }
1002
+
1003
+ return { ok: true, data: result.data, issues: [] };
1004
+ }