@writedocs/generator 0.13.4 → 0.13.5

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 (86) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +356 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +203 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +268 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +507 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +69 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +203 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +408 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.ts +2509 -2509
  48. package/src/lib/config.ts +1316 -1316
  49. package/src/lib/consent.js +108 -108
  50. package/src/lib/content-store-reload-integration.js +101 -101
  51. package/src/lib/icon-data-dev.js +53 -53
  52. package/src/lib/image-size.js +152 -152
  53. package/src/lib/json-schema-descriptions.js +228 -228
  54. package/src/lib/link-check.js +544 -544
  55. package/src/lib/llms-index.ts +90 -90
  56. package/src/lib/mcp-dev-integration.js +65 -65
  57. package/src/lib/mcp-index.ts +102 -102
  58. package/src/lib/mintlify-convert.js +605 -605
  59. package/src/lib/moved-api-pages.js +49 -49
  60. package/src/lib/og-cards.js +33 -33
  61. package/src/lib/og-image.js +235 -235
  62. package/src/lib/openapi-dev-status.js +80 -80
  63. package/src/lib/openapi-reload-integration.js +193 -193
  64. package/src/lib/pages.js +312 -312
  65. package/src/lib/project-files-integration.js +116 -116
  66. package/src/lib/project-files.js +137 -137
  67. package/src/lib/rehype-base-path.js +62 -62
  68. package/src/lib/rehype-image-loading.js +71 -71
  69. package/src/lib/robots-txt.js +21 -21
  70. package/src/lib/search-scope.js +44 -44
  71. package/src/lib/selector-placement.js +50 -50
  72. package/src/lib/seo-tags.js +155 -155
  73. package/src/lib/shiki-code-block.js +7 -1
  74. package/src/lib/site-base.ts +27 -27
  75. package/src/lib/styles-asset-integration.js +291 -291
  76. package/src/lib/wdignore-cases.json +195 -195
  77. package/src/lib/wdignore.js +177 -177
  78. package/src/pages/404.astro +63 -63
  79. package/src/pages/[...slug].astro +1762 -1608
  80. package/src/pages/[...slug].md.ts +93 -93
  81. package/src/pages/llms-full.txt.ts +88 -88
  82. package/src/pages/og/[...slug].png.ts +63 -63
  83. package/src/scripts/mobile-menu.ts +80 -80
  84. package/src/scripts/search.ts +245 -245
  85. package/src/scripts/sidebar-scroll.ts +61 -61
  86. package/src/styles/global.css +40 -40
@@ -1,2509 +1,2509 @@
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, fixado no package.json, dentro do `^4.3.6` que o astro
24
- // tambem pede; o scripts/package-files.test.js garante uma copia so - entao a
25
- // troca nao muda comportamento nenhum, so tira o astro do caminho de quem
26
- // importa isto de fora do gerador.)
27
- import { z } from 'zod';
28
- // WD-063: `parseTree` + `findNodeAtLocation` traduzem o caminho de um erro
29
- // (`navigation.products.0.product`) para o offset dele no TEXTO, que e o que
30
- // vira linha. E o parser de JSON do VS Code: zero dependencias, nada de `node:`,
31
- // entao continua bundlavel pro Worker da plataforma. Escrever o scanner a mao
32
- // foi tentado e deu errado (perdia todo caminho aninhado, que e justamente o que
33
- // importa aqui) - nao repita.
34
- // WD-315 (07c): e o `visit`, a mesma leitura sem montar a arvore - ver
35
- // localizarCaminhos.
36
- import { findNodeAtLocation, parseTree, visit } from 'jsonc-parser';
37
- // The form of `basePath`. Plain JS with no `node:` import, like this file.
38
- import { BASE_PATH_FIELD_PATTERN } from './base-path.js';
39
-
40
- // ---------------------------------------------------------------------
41
- // Pages & groups - the leaf content any container ultimately bottoms out
42
- // at. A group can nest other groups arbitrarily deep, and can optionally
43
- // link its own label to a page (`page`) independent of expanding or
44
- // collapsing its children - see NavTree.astro for how that renders.
45
- // ---------------------------------------------------------------------
46
-
47
- const navPageSchema = z.string();
48
-
49
- // A group ordinarily lists its own children by hand (`pages`), but can
50
- // instead auto-generate them from an OpenAPI spec via `openapi: { src,
51
- // path }` - resolved by loadDocsConfig() (via expandOpenApiInNavigation()
52
- // below, reading the manifest generate-api-pages.js writes for this exact
53
- // group) into a real `{ group, pages }` node - one sub-group per tag -
54
- // before anything else in this file ever sees it, so
55
- // resolveSections()/flattenNav()/buildNavTree()/etc. only ever need to
56
- // understand the ordinary pages-array shape. `.strict()` on both variants
57
- // is load-bearing (see withChildren()'s own comment on this pattern
58
- // below): without it, a group written with both `pages` and `openapi` at
59
- // once would silently have one dropped instead of rejected.
60
- const navGroupPagesSchema: z.ZodType<{ group: string; page?: string; pages: NavItem[] }> = z.lazy(() =>
61
- z
62
- .object({
63
- group: z.string(),
64
- page: z.string().optional(),
65
- pages: z.array(navItemSchema),
66
- })
67
- .strict()
68
- );
69
-
70
- const navGroupOpenApiSchema = z.object({
71
- group: z.string(),
72
- openapi: z
73
- .object({
74
- // Path to an OpenAPI 3.x spec, relative to the content directory
75
- // (alongside writedocs.json) - same convention the old top-level
76
- // `openapi` field used. See generate-api-pages.js (the pre-Astro
77
- // build/dev step that actually parses this and writes the
78
- // manifest/operation JSON this group's pages are expanded from).
79
- src: z.string(),
80
- // Base URL path every page generated from this spec is namespaced
81
- // under, e.g. "/api" -> pages served at /api/<tag>/<operation>/.
82
- // Also doubles as this spec's own unique key under
83
- // writedocsTempDir()'s openapi/<path>/ directory (manifest.json + operations/*.json),
84
- // so two openapi groups in the same writedocs.json must use different
85
- // `path` values - generate-api-pages.js throws a clear error if
86
- // they collide.
87
- path: z.string(),
88
- })
89
- .strict(),
90
- }).strict();
91
-
92
- export type GroupNavItem =
93
- | { group: string; page?: string; pages: NavItem[] }
94
- | { group: string; openapi: { src: string; path: string } };
95
-
96
- const navGroupSchema: z.ZodType<GroupNavItem> = z.union([navGroupPagesSchema, navGroupOpenApiSchema]);
97
-
98
- // A bare external link sitting directly in a `pages` array, alongside
99
- // page slugs and groups - e.g. a "Support" link to an external help
100
- // desk shown right in the sidebar, rather than only reachable via
101
- // navigation.global.dropdowns. Discriminated from navGroupSchema by
102
- // its required `label`/`href` keys (vs `group`/`pages`/`openapi`), so a
103
- // plain (non-strict at the union level) schema is enough for Zod to pick
104
- // the right branch; `.strict()` here still catches a typo'd extra key.
105
- const navLinkSchema = z.object({ label: z.string(), href: z.string() }).strict();
106
-
107
- const navItemSchema: z.ZodType<NavItem> = z.lazy(() =>
108
- z.union([navPageSchema, navGroupSchema, navLinkSchema])
109
- );
110
-
111
- export type NavItem = string | GroupNavItem | { label: string; href: string };
112
-
113
- // ---------------------------------------------------------------------
114
- // Containers: tabs, versions, languages, dropdowns, products.
115
- //
116
- // This schema is modeled directly on Mintlify's writedocs.json
117
- // (https://mintlify.com/writedocs.json / mintlify.com/docs/organize/navigation):
118
- // all five container kinds are structurally identical except for their
119
- // own identifying field. Each owns *exactly one* of {pages, tabs,
120
- // versions, languages, dropdowns, products} as its content, or is a bare
121
- // external `href` link with no content of its own. That symmetry is what
122
- // lets any of them nest inside any other - a tab can contain versions, a
123
- // version can contain languages, a language can contain tabs, and so on,
124
- // bottoming out at a `pages` array. `withChildren()` is the single place
125
- // that shape is defined, instead of hand-writing the union five times.
126
- // ---------------------------------------------------------------------
127
-
128
- export type NavChildren =
129
- | { pages: NavItem[] }
130
- | { tabs: TabItem[] }
131
- | { versions: VersionItem[] }
132
- | { languages: LanguageItem[] }
133
- | { dropdowns: DropdownItem[] }
134
- | { products: ProductItem[] }
135
- | { href: string };
136
-
137
- /** Any navigation item can be hidden: reachable only by its address - no
138
- * switcher, tab or menu lists it, and its pages search only among
139
- * themselves (plus the public ones, with `searchPublic`). See
140
- * lib/hidden-sections.js.
141
- * And any can have a `page` of its own: where choosing the item leads, in
142
- * place of its first page - an overview of what's in it. In a sidebar too,
143
- * it opens there; otherwise it opens inside the item (resolveLandings() in
144
- * lib/config.ts). */
145
- export type Hideable = { hidden?: boolean; searchPublic?: boolean; page?: string };
146
-
147
- export type TabItem = { tab: string; icon?: string } & Hideable & NavChildren;
148
- export type VersionItem = { version: string; label?: string; tag?: string; default?: boolean } & Hideable & NavChildren;
149
- export type LanguageItem = { language: string; label?: string } & Hideable & NavChildren;
150
- export type DropdownItem = { dropdown: string; icon?: string } & Hideable & NavChildren;
151
- export type ProductItem = { product: string; icon?: string; description?: string } & Hideable & NavChildren;
152
-
153
- // `.strict()` on every variant is load-bearing, not decoration: Zod
154
- // objects silently strip unrecognized keys by default, so without it a
155
- // node written with two children fields at once (e.g. both `pages` and
156
- // `versions`) would just have the second one dropped instead of
157
- // rejected - defeating the entire "exactly one child kind per level"
158
- // rule this schema exists to enforce (mirroring Mintlify's own "a tab
159
- // cannot contain both anchors and groups at the same level").
160
- function withChildren<Base extends z.ZodRawShape>(ownFields: Base) {
161
- const base = { ...ownFields, hidden: z.boolean().optional(), searchPublic: z.boolean().optional(), page: z.string().optional() };
162
- return z.union([
163
- z.object({ ...base, pages: z.array(navItemSchema) }).strict(),
164
- z.object({ ...base, tabs: z.array(tabSchema).min(1) }).strict(),
165
- z.object({ ...base, versions: z.array(versionSchema).min(1) }).strict(),
166
- z.object({ ...base, languages: z.array(languageSchema).min(1) }).strict(),
167
- z.object({ ...base, dropdowns: z.array(dropdownSchema).min(1) }).strict(),
168
- z.object({ ...base, products: z.array(productSchema).min(1) }).strict(),
169
- z.object({ ...base, href: z.string() }).strict(),
170
- ]);
171
- }
172
-
173
- // Each of these five is defined via z.lazy() because withChildren()
174
- // references all five by name (mutual recursion) - safe because none of
175
- // them are actually *called* until a real writedocs.json is parsed, by which
176
- // point every const below has been assigned. The same pattern already
177
- // used for navItemSchema/navGroupSchema above.
178
- const tabSchema: z.ZodType<TabItem> = z.lazy(() =>
179
- withChildren({ tab: z.string(), icon: z.string().optional() })
180
- );
181
-
182
- const versionSchema: z.ZodType<VersionItem> = z.lazy(() =>
183
- withChildren({
184
- version: z.string(),
185
- label: z.string().optional(),
186
- tag: z.string().optional(),
187
- default: z.boolean().optional(),
188
- })
189
- );
190
-
191
- const languageSchema: z.ZodType<LanguageItem> = z.lazy(() =>
192
- withChildren({ language: z.string(), label: z.string().optional() })
193
- );
194
-
195
- const dropdownSchema: z.ZodType<DropdownItem> = z.lazy(() =>
196
- withChildren({ dropdown: z.string(), icon: z.string().optional() })
197
- );
198
-
199
- const productSchema: z.ZodType<ProductItem> = z.lazy(() =>
200
- withChildren({ product: z.string(), icon: z.string().optional(), description: z.string().optional() })
201
- );
202
-
203
- // ---------------------------------------------------------------------
204
- // Root navigation: a flat array (shorthand for one implicit section - the
205
- // common case) or an object choosing exactly one primary organizational
206
- // pattern, per Mintlify's convention ("choose one primary organizational
207
- // pattern at the root level of your navigation").
208
- //
209
- // `global.dropdowns` is the one exception to "exactly one pattern": it's
210
- // not a primary pattern, it's a persistent set of topbar dropdown
211
- // triggers that render on every page regardless of which tab/version/
212
- // language/product is active - equivalent to Mintlify's
213
- // `navigation.global.anchors`. This replaces the earlier `{tabs,
214
- // dropdowns}` shape (both present at once), which doesn't generalize
215
- // once versions/languages/products are also root-level choices.
216
- // ---------------------------------------------------------------------
217
-
218
- export type NavigationConfig =
219
- | NavItem[]
220
- | { global?: { dropdowns: DropdownItem[] }; tabs: TabItem[] }
221
- | { global?: { dropdowns: DropdownItem[] }; versions: VersionItem[] }
222
- | { global?: { dropdowns: DropdownItem[] }; languages: LanguageItem[] }
223
- | { global?: { dropdowns: DropdownItem[] }; dropdowns: DropdownItem[] }
224
- | { global?: { dropdowns: DropdownItem[] }; products: ProductItem[] };
225
-
226
- /** Levels of tabs a page can sit under - one row of the top bar each. */
227
- export const MAX_TAB_LEVELS = 2;
228
- /** Levels of dropdowns in a tab's menu - the menu, and a flyout beside an
229
- * entry for the dropdowns inside it (lib/selector-placement.js). */
230
- export const MAX_TAB_MENU_LEVELS = 2;
231
-
232
- const globalSchema = z.object({ dropdowns: z.array(dropdownSchema).min(1) });
233
-
234
- const navigationSchema = z.union([
235
- z.array(navItemSchema),
236
- z.object({ global: globalSchema.optional(), tabs: z.array(tabSchema).min(1) }).strict(),
237
- z.object({ global: globalSchema.optional(), versions: z.array(versionSchema).min(1) }).strict(),
238
- z.object({ global: globalSchema.optional(), languages: z.array(languageSchema).min(1) }).strict(),
239
- z.object({ global: globalSchema.optional(), dropdowns: z.array(dropdownSchema).min(1) }).strict(),
240
- z.object({ global: globalSchema.optional(), products: z.array(productSchema).min(1) }).strict(),
241
- ]).superRefine((navigation, ctx) => {
242
- // Every page under a language is in that language - a second `languages`
243
- // inside it would make a page two languages at once. And tabs take a row
244
- // of the top bar per level: two levels at most (TopBar.astro).
245
- const CONTAINERS = ['tabs', 'versions', 'languages', 'dropdowns', 'products'] as const;
246
- // `menu`: the dropdown levels in a tab's menu down to `node` - 0 outside
247
- // one, 1 for a dropdown right inside a tab, 2 for a dropdown inside that.
248
- const walk = (node: unknown, path: (string | number)[], language: string | null, tabs: string[], menu = 0) => {
249
- if (!node || typeof node !== 'object' || Array.isArray(node)) return;
250
- const own = node as Record<string, unknown>;
251
- for (const key of CONTAINERS) {
252
- const items = own[key];
253
- if (!Array.isArray(items)) continue;
254
- if (key === 'languages' && language !== null) {
255
- ctx.addIssue({
256
- code: 'custom',
257
- path: [...path, key],
258
- message: `The language "${language}" contains another "languages" list. A page can only be in one language - put the languages at one level, and the rest (tabs, versions, ...) inside each of them.`,
259
- });
260
- continue;
261
- }
262
- if (key === 'tabs' && tabs.length >= MAX_TAB_LEVELS) {
263
- ctx.addIssue({
264
- code: 'custom',
265
- path: [...path, key],
266
- message: `Tabs go at most ${MAX_TAB_LEVELS} levels deep, and these are a third level (inside "${tabs.join('" > "')}"). Each level of tabs is a row in the top bar - use a dropdown or groups for this level instead.`,
267
- });
268
- continue;
269
- }
270
- // Dropdowns right inside a tab are its menu; dropdowns inside one of
271
- // those, a flyout beside its entry. Any other level of dropdowns starts
272
- // its own count.
273
- const menuLevel = key !== 'dropdowns' ? 0 : 'tab' in own ? 1 : 'dropdown' in own && menu > 0 ? menu + 1 : 0;
274
- if (menuLevel > MAX_TAB_MENU_LEVELS) {
275
- ctx.addIssue({
276
- code: 'custom',
277
- path: [...path, key],
278
- message: `A tab's menu goes ${MAX_TAB_MENU_LEVELS} levels deep at most - its dropdowns, and the dropdowns inside each of them - and these are a third level (inside "${String(own.dropdown)}"). Use products or groups for this level instead.`,
279
- });
280
- continue;
281
- }
282
- items.forEach((item, i) => {
283
- const own = item as { hidden?: unknown; searchPublic?: unknown; page?: unknown; href?: unknown };
284
- if (own?.page !== undefined && own.href !== undefined) {
285
- ctx.addIssue({
286
- code: 'custom',
287
- path: [...path, key, i, 'page'],
288
- message: 'An item with `href` is a link, so it has no page of its own - remove `page`, or `href`.',
289
- });
290
- }
291
- if (own?.searchPublic === true && own.hidden !== true) {
292
- ctx.addIssue({
293
- code: 'custom',
294
- path: [...path, key, i, 'searchPublic'],
295
- message: '`searchPublic` only applies to a hidden item - add "hidden": true, or remove `searchPublic`.',
296
- });
297
- }
298
- const inner = key === 'languages' ? String((item as { language?: unknown })?.language ?? '') : language;
299
- const tab = (item as { tab?: unknown })?.tab;
300
- walk(item, [...path, key, i], inner, key === 'tabs' ? [...tabs, String(tab ?? '')] : tabs, menuLevel);
301
- });
302
- }
303
- };
304
- walk(navigation, [], null, []);
305
- }) as z.ZodType<NavigationConfig>;
306
-
307
- const DEFAULT_PRIMARY = '#6366f1';
308
-
309
- // A logo is either one path used for both color modes, or a
310
- // { light, dark, label } object - each image shown only while that mode
311
- // is active (see BaseLayout.astro's .wd-logo-light/.wd-logo-dark CSS).
312
- // The topbar shows *only* the image by default - no site name text next
313
- // to it, since a real logo asset usually already is a wordmark. `label`
314
- // is the opt-in way to add text back next to the image (e.g. a product
315
- // name alongside a symbol-only mark); it only exists on the object form,
316
- // since a single shared image path is just as easy to bake the label
317
- // into directly.
318
- //
319
- // `light`/`dark` are themselves optional (unlike the string form, which
320
- // is inherently "both"): a site with no logo *images* at all can still
321
- // set `styles.logo: { label: "..." }` to override the topbar's fallback
322
- // text without providing any image - see BaseLayout.astro's
323
- // hasLogoImage/logoLabel/brandLabel derivation, where an object with
324
- // only `label` set already resolves correctly (brandLabel = logoLabel,
325
- // same as if an image were also present) without needing any change
326
- // there; only this schema needed loosening; light/dark were previously
327
- // both required whenever the object form was used at all.
328
- //
329
- // Standalone const (rather than inlined into stylesSchema.logo below) so
330
- // footer.logo further down can share the exact same union instead of an
331
- // independently-written copy - see footerSchema's own comment on why a
332
- // footer logo needs this at all.
333
- const logoSchema = z.union([
334
- z.string(),
335
- z.object({ light: z.string().optional(), dark: z.string().optional(), label: z.string().optional() }).strict(),
336
- ]);
337
-
338
- // Same {light, dark}-with-fallback shape applies to `colors.dark`: any
339
- // of primary/text left unset there falls back to the light-mode value
340
- // already given above, so a site only has to specify what actually
341
- // differs in dark mode. There used to be a `background`/`dark.background`
342
- // pair here too, doing effectively the same job as `background.colors`
343
- // further down (see that field's own comment) - two writedocs.json fields
344
- // both named "background" that visually looked interchangeable but
345
- // weren't quite (one drove --wd-background site-wide, the other only
346
- // the <body> canvas), which was confusing to author against and easy to
347
- // half-configure by setting only one. Removed in favor of `background`
348
- // alone being the single place to set any background color - see that
349
- // field's comment for what it now covers.
350
- // One side of `styles.navbar` (light or dark) - either a bare background
351
- // color (the original shape) or `{ background, accent? }` once a site
352
- // wants its own accent color (the active tab's underline)
353
- // inside the navbar specifically, independent of the sitewide
354
- // `styles.colors.primary`. Deliberately does NOT carry a text/icon color
355
- // field at all - see `navbar`'s own comment below (stylesSchema) for why
356
- // that's resolved automatically instead of being configurable. Kept as a
357
- // standalone const rather than inlined so `light`/`dark` share the exact
358
- // same union rather than two independently-written (and possibly
359
- // drifting) copies of it.
360
- const navbarColorValueSchema = z.union([
361
- z.string(),
362
- z
363
- .object({
364
- background: z.string(),
365
- accent: z.string().optional(),
366
- })
367
- .strict(),
368
- ]);
369
-
370
- // One font declaration - almost exactly Mintlify's own `fonts` shape (see
371
- // docs/dev/docs/site-config.mdx's own "Fonts" section for the research this
372
- // was based on): a bare Google Fonts family name (`family` alone - Google
373
- // Fonts loads it automatically, see googleFontsHref() below), or a local/
374
- // externally-hosted font file (`source` + `format` together; `source` is
375
- // either a project-relative path like the other five asset-fallback fields
376
- // this schema already has - see collectConfiguredAssetPaths() - or a full
377
- // https:// URL to an externally-hosted font). `weight` does two things at
378
- // once, both driven by BaseLayout.astro: it narrows which file actually
379
- // loads (folded into the Google Fonts URL's `:wght@` axis, or the
380
- // generated `@font-face` rule's own `font-weight` descriptor for a
381
- // `source` font - see googleFontsHref()/fontFaceRule() below), *and* it's
382
- // applied as a real CSS `font-weight` on h1-h6 (for `heading`) or `body`
383
- // (for `body`) - see BaseLayout's own `wdFontWeightHeading`/
384
- // `wdFontWeightBody`. Both halves matter: loading only the 400-weight file
385
- // while leaving h1-h6 at the browser's UA-default `font-weight: bold`
386
- // faux-bolds that file back to looking bold anyway, with no visible
387
- // change from configuring a lighter weight at all - the bug this second
388
- // half fixes (caught from real user-reported behavior, not anticipated
389
- // up front). Left unset anywhere in `styles.fonts` renders no font-weight
390
- // rule at all, keeping today's plain browser-default bold headings/normal
391
- // body text unchanged for a site that hasn't touched this field.
392
- const fontVariantSchema = z
393
- .object({
394
- family: z.string(),
395
- weight: z.number().optional(),
396
- source: z.string().optional(),
397
- format: z.enum(['woff', 'woff2']).optional(),
398
- })
399
- .strict();
400
-
401
- export type FontVariant = z.infer<typeof fontVariantSchema>;
402
-
403
- // The top-level shape adds `heading`/`body`: each independently optional,
404
- // each falling back to the top-level family/weight/source/format when
405
- // unset (see resolveFonts() below) - so a site can set one font for
406
- // everything (`fonts.family` alone), or split headings and body text
407
- // without needing to repeat itself for whichever side isn't changing.
408
- const fontsSchema = z
409
- .object({
410
- family: z.string(),
411
- weight: z.number().optional(),
412
- source: z.string().optional(),
413
- format: z.enum(['woff', 'woff2']).optional(),
414
- heading: fontVariantSchema.optional(),
415
- body: fontVariantSchema.optional(),
416
- })
417
- .strict();
418
-
419
- export type FontsConfig = z.infer<typeof fontsSchema>;
420
-
421
- const stylesSchema = z
422
- .object({
423
- colors: z
424
- .object({
425
- primary: z.string().default(DEFAULT_PRIMARY),
426
- text: z.string().optional(),
427
- dark: z
428
- .object({
429
- primary: z.string().optional(),
430
- text: z.string().optional(),
431
- })
432
- .optional(),
433
- })
434
- .default({ primary: DEFAULT_PRIMARY }),
435
- logo: logoSchema.optional(),
436
- favicon: z.string().optional(),
437
- // No default value here (unlike `colors.primary`'s DEFAULT_PRIMARY) -
438
- // resolveFonts() below is where "Inter" actually gets applied as the
439
- // site-wide default whenever this field is left unset entirely, so
440
- // that fallback lives in one place alongside the rest of the
441
- // resolution logic rather than being duplicated as a schema default
442
- // *and* a resolver fallback.
443
- fonts: fontsSchema.optional(),
444
- // The Shiki theme *name* (not a full theme object/JSON - see
445
- // https://shiki.style/themes for the built-in list) each fenced
446
- // (```) MDX code block, and the API playground's request/response
447
- // snippets, use in light/dark mode - read out of writedocs.json by both
448
- // astro.config.mjs (Shiki's dual-theme markdown config) and
449
- // ApiReferencePanel.astro (its own separate <Code/> usages, which
450
- // don't inherit markdown.shikiConfig) via resolveCodeblockTheme()
451
- // below, the single source of truth for the 'github-light'/
452
- // 'github-dark' fallback. Left per-key optional (not defaulted in
453
- // the schema itself) so a site can override just one side (e.g.
454
- // only `dark`) and still get the ordinary default for the other.
455
- codeblocks: z
456
- .object({
457
- light: z.string().optional(),
458
- dark: z.string().optional(),
459
- // Maps a fenced (```) block's own language tag to whichever real
460
- // Shiki grammar actually highlights it, before that tag ever
461
- // reaches Shiki - see resolveCodeblockLangAlias() below for the
462
- // one built-in entry (mdx -> jsx) this ships with by default and
463
- // why. A site can add its own entries for any other language tag
464
- // that either doesn't tokenize well under its own grammar, or
465
- // that a site wants to write under a shorter/friendlier fence tag
466
- // than Shiki's own bundled id (e.g. `groovy: 'java'` for a close-
467
- // enough approximation Shiki doesn't ship a dedicated grammar for
468
- // at all) - merged with, not replacing, the built-in default, so
469
- // adding one of a site's own doesn't require re-declaring mdx.
470
- langAlias: z.record(z.string(), z.string()).optional(),
471
- })
472
- .strict()
473
- .optional(),
474
- // The topbar's own background, independent of `background` below (the
475
- // page's) - a site may want its navbar to stand out (a dark or
476
- // brand-colored bar over a light page) rather than blend into the
477
- // page, which is the default when this is left unset. Same {light,
478
- // dark} shape (and same per-key-optional, not defaulted here) as
479
- // `codeblocks` right above, rather than nested under `colors` - it's a
480
- // topbar-specific override, not a third general-purpose page color, so
481
- // it reads more like "one more themed surface" alongside codeblocks
482
- // than a sibling of primary/text. BaseLayout.astro's own
483
- // lightNavbarBg/darkNavbarBg resolution is what falls each side back
484
- // to the page background when unset.
485
- //
486
- // Each side (`light`/`dark`) is either a bare string - just the
487
- // background color, exactly the original shape, kept for backwards
488
- // compatibility - or `{ background, accent? }`, for when a site also
489
- // wants the navbar's own active-tab underline color to
490
- // differ from the sitewide `styles.colors.primary` (`accent`'s only
491
- // job - see BaseLayout.astro's lightNavbarAccent). Deliberately no
492
- // text/icon color field here at all: BaseLayout.astro always resolves
493
- // the navbar's plain text/icon color itself, picking black or white by
494
- // contrast against whatever `background` resolves to
495
- // (contrastTextColor() below) the moment this field is configured at
496
- // all (string or object) - never a value read from writedocs.json. A
497
- // manually-set text color is a legibility footgun a site author can
498
- // get wrong (or drift out of sync after later changing `background`
499
- // without remembering to update it too) in a way "compute it
500
- // correctly, every time" simply can't - there's no legitimate reason
501
- // to want *illegible* navbar text, unlike `accent`, which is a real
502
- // aesthetic choice. Real bug this fixes: a site setting `navbar.light`
503
- // to the same value as `colors.primary` (a plausible thing to reach
504
- // for - "brand-colored navbar") made every topbar label/icon/link
505
- // render in the default near-black text color against that same
506
- // saturated background, all but unreadable - and an earlier version of
507
- // this feature that let a writedocs.json-supplied color double as the text
508
- // color reintroduced the identical bug one level down, just requiring
509
- // one more (still guessable-wrong) field to trigger it.
510
- navbar: z
511
- .object({
512
- light: navbarColorValueSchema.optional(),
513
- dark: navbarColorValueSchema.optional(),
514
- })
515
- .strict()
516
- .optional(),
517
- // The single place to configure any background color: `colors` is a
518
- // solid color (falls back to '#ffffff'/'#0b1120' when unset - see
519
- // BaseLayout.astro's lightBackground/darkBackground resolution), and
520
- // `images` layers an image on top of it (or is the whole background
521
- // by itself, if `colors` is left at its default). This one pair now
522
- // drives everything background-related site-wide - --wd-background
523
- // (dropdowns/modals/kbd chips/footer/topbar-fallback/etc., see every
524
- // `var(--wd-background)` call site) *and* the <body> canvas behind the
525
- // main/toc columns - rather than the two being independently
526
- // configurable fields that happened to look alike but didn't affect
527
- // the same things (see this schema's own comment on `colors.dark`
528
- // above for why that split was removed). Both are per-mode optional,
529
- // same "only specify what differs" pattern as codeblocks/navbar above.
530
- // The topbar and footer still get their own explicit opaque
531
- // background (topbar.css/footer.css) specifically so an `images`
532
- // background doesn't show through them; see those files' own
533
- // comments. The sidebar column has no background of its own (base.css)
534
- // and lets it show through, same as the main/toc columns.
535
- background: z
536
- .object({
537
- colors: z
538
- .object({
539
- light: z.string().optional(),
540
- dark: z.string().optional(),
541
- })
542
- .strict()
543
- .optional(),
544
- images: z
545
- .object({
546
- light: z.string().optional(),
547
- dark: z.string().optional(),
548
- })
549
- .strict()
550
- .optional(),
551
- })
552
- .strict()
553
- .optional(),
554
- })
555
- .default({ colors: { primary: DEFAULT_PRIMARY } });
556
-
557
- // `href` is always required - a link with nowhere to go isn't a link.
558
- // `label`/`icon` are each individually optional, but not both at once
559
- // (enforced by the .refine() below, same shape as scriptEntrySchema's own
560
- // exactly-one-of check above) - a link needs *something* visible to render,
561
- // whichever of the two, and can have both (icon rendered to the left of the
562
- // label - see TopBar.astro/SiteFooter.astro, the two renderers of this
563
- // shape). An icon-only link (no label) is the common case for something
564
- // like a bare GitHub mark in the topbar; label-only (no icon) is every
565
- // plain text link this already supported before `icon` existed - both
566
- // still need to keep working unchanged, hence neither field being outright
567
- // required on its own.
568
- const topbarLinkSchema = z
569
- .object({
570
- label: z.string().optional(),
571
- href: z.string(),
572
- // Same string shape as every other writedocs.json `icon` field (a plain
573
- // Lucide name, or the explicit "collection:icon-name" form for
574
- // anything else - see resolveIcon()/AppIcon.astro) - not documented
575
- // again here since that convention is already established elsewhere
576
- // in this file (tabs/switchers/socials all take the identical shape).
577
- icon: z.string().optional(),
578
- })
579
- .strict()
580
- .refine((link) => Boolean(link.label) || Boolean(link.icon), {
581
- message: 'Each topbar.links/footer column link needs a "label", an "icon", or both - a link with neither has nothing to render.',
582
- });
583
-
584
- // One column of the footer (BaseLayout.astro's <footer class="wd-footer">) -
585
- // an optional heading (e.g. "Resources", "Community") plus a list of links,
586
- // reusing the exact same {label, icon, href} shape as topbar.links above (a
587
- // footer link is the same thing rendered in a different place, no reason
588
- // for a second, identical-but-differently-named schema). `title` is
589
- // optional so a single-column footer with no heading (just a bare list of
590
- // links) is valid too.
591
- const footerColumnSchema = z
592
- .object({
593
- title: z.string().optional(),
594
- links: z.array(topbarLinkSchema).default([]),
595
- })
596
- .strict();
597
-
598
- // Off by default (empty `columns`, same convention as `topbar` above - a
599
- // footer with nothing configured just doesn't render at all, see
600
- // BaseLayout.astro's `hasFooterContent` check) rather than `.optional()`
601
- // like contextMenu: unlike that field, an empty/default footer has no
602
- // build-output or routing implications to gate, it's purely visual, so
603
- // there's no reason to distinguish "unset" from "set to nothing" the way
604
- // contextMenu needs to.
605
- // Same {light, dark, label} union as `styles.logo` (via the shared
606
- // logoSchema above) - unset by default, in which case the footer just
607
- // shows the sitewide `styles.logo` (BaseLayout.astro's existing
608
- // logoLight/logoDark/logoLabel, already threaded into SiteFooter as-is).
609
- // Set here, it replaces that entirely rather than filling in only the
610
- // missing side of it - a footer.logo with only `dark` set shows *just*
611
- // the dark-mode image, not styles.logo's light image plus this dark one -
612
- // the same all-or-nothing-relative-to-styles.logo resolution BaseLayout.astro
613
- // already applies.
614
- const footerSchema = z
615
- .object({
616
- columns: z.array(footerColumnSchema).default([]),
617
- logo: logoSchema.optional(),
618
- })
619
- .strict()
620
- .default({ columns: [] });
621
-
622
- export type FooterColumn = z.infer<typeof footerColumnSchema>;
623
- export type FooterConfig = z.infer<typeof footerSchema>;
624
-
625
- // Shared by both writedocs.json's top-level `seo` (site-wide defaults) and a
626
- // page's own frontmatter `seo` (per-page overrides) - see
627
- // content.config.ts's docsSchema, which imports this exact schema rather
628
- // than redeclaring the same shape a second time. mergeSeo() below is what
629
- // actually combines the two, field by field, at render time.
630
- export const seoFieldsSchema = z
631
- .object({
632
- // Open Graph / Twitter card image - a relative path (resolved against
633
- // `domain` below into an absolute URL, since most social crawlers
634
- // require one) or an already-absolute https:// URL.
635
- ogImage: z.string().optional(),
636
- // og:type - "website" for most pages, "article" for blog-post-shaped
637
- // content, etc. Defaults to "website" if never set anywhere.
638
- ogType: z.string().optional(),
639
- twitterCard: z.enum(['summary', 'summary_large_image']).optional(),
640
- keywords: z.array(z.string()).optional(),
641
- // Renders <meta name="robots" content="noindex, nofollow" /> and
642
- // (see astro.config.mjs's sitemap `filter`) excludes the page from
643
- // sitemap.xml entirely - both driven off this one flag, since listing
644
- // a page in the sitemap while also telling crawlers not to index it
645
- // would be self-contradictory.
646
- noindex: z.boolean().optional(),
647
- // The whole <meta name="robots"> value, for anything `noindex` (always
648
- // "noindex, nofollow") doesn't say - "noindex, follow", "max-snippet:50".
649
- // Wins over `noindex`; a value with "noindex" keeps the page out of
650
- // sitemap.xml and llms.txt the same way (isNoindex(), lib/seo-tags.js).
651
- robots: z.string().optional(),
652
- // Any other <meta> tag, name -> content: "google-site-verification",
653
- // "twitter:site", "og:locale"... One with the name of a tag writedocs
654
- // writes itself ("og:image", "twitter:image", "description") replaces
655
- // it. Open Graph names become <meta property>, the rest <meta name> -
656
- // see seoHead() in lib/seo-tags.js. A page's own are merged over the
657
- // site's, name by name.
658
- metatags: z.record(z.string(), z.string()).optional(),
659
- })
660
- .strict();
661
-
662
- // A page's own `seo`: everything above, plus what only makes sense for one
663
- // page - the site has no single title, description or canonical address.
664
- export const pageSeoFieldsSchema = seoFieldsSchema
665
- .extend({
666
- // The <title> and og:title/twitter:title, exactly as written - no site
667
- // name is added. The page's <h1> and sidebar entry keep `title`.
668
- title: z.string().optional(),
669
- // The <meta name="description"> and og/twitter descriptions, when they
670
- // should differ from the `description` shown under the page's title.
671
- description: z.string().optional(),
672
- // The page's canonical URL, when it isn't its own address: a full URL,
673
- // or a path on the site's domain. A page whose canonical is another
674
- // address is left out of sitemap.xml.
675
- canonical: z.string().optional(),
676
- // The page's own structured data (schema.org JSON-LD): one block, or a
677
- // list of them, written into the page after the ones writedocs
678
- // generates (lib/json-ld.js). Any shape - it is the author's to get right.
679
- jsonLd: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]).optional(),
680
- })
681
- .strict();
682
-
683
- // writedocs.json's `seo`: the shared fields, plus what describes the site
684
- // as a whole.
685
- export const siteSeoFieldsSchema = seoFieldsSchema
686
- .extend({
687
- // The link preview picture generated for every page that has no
688
- // `ogImage` (lib/og-image.js). On unless this is `false`: drawing one
689
- // takes ~25 ms a page, which a site with thousands of pages may prefer
690
- // to save. Site-wide only - a page opts out by setting its own `ogImage`.
691
- generatedOgImage: z.boolean().optional(),
692
- // Who publishes the site - an Organization block in the home page's
693
- // structured data, and the `publisher` of every page (lib/json-ld.js).
694
- // Not derived from `name`: a site is called "Acme Docs", the
695
- // organization "Acme".
696
- organization: z
697
- .object({
698
- name: z.string(),
699
- // The organization's own site. Default: this site's address.
700
- url: z.string().optional(),
701
- // A path in the project or a full URL. Default: the site's logo.
702
- logo: z.string().optional(),
703
- // Its profiles elsewhere. Default: the URLs in `socials`.
704
- sameAs: z.array(z.string()).optional(),
705
- })
706
- .strict()
707
- .optional(),
708
- })
709
- .strict();
710
-
711
- export type SiteSeoFields = z.infer<typeof siteSeoFieldsSchema>;
712
- export type SeoFields = z.infer<typeof pageSeoFieldsSchema>;
713
-
714
- /** Field-by-field merge of a page's own `seo` frontmatter over writedocs.json's
715
- * site-wide `seo` defaults - a page only overrides the specific fields it
716
- * sets, falling back to the site default for everything else, rather than
717
- * a page's (possibly partial) `seo` object replacing the site's wholesale. */
718
- export function mergeSeo(site: SeoFields, page: SeoFields = {}): SeoFields {
719
- // `robots` and `noindex` say the same thing two ways, so they're taken
720
- // together: a page that sets either one decides for itself, and the
721
- // site's value of the other doesn't leak into it. `noindex` then follows
722
- // `robots` when there is one, so everything that reads `noindex` (the
723
- // sitemap, llms.txt, the MCP index) agrees with the tag on the page.
724
- const pageDecides = page.robots !== undefined || page.noindex !== undefined;
725
- const robots = pageDecides ? page.robots : site.robots;
726
- const noindex = robots !== undefined ? /\bnoindex\b|\bnone\b/i.test(robots) : pageDecides ? page.noindex : site.noindex;
727
- const metatags = site.metatags || page.metatags ? { ...site.metatags, ...page.metatags } : undefined;
728
- return {
729
- ogImage: page.ogImage ?? site.ogImage,
730
- ogType: page.ogType ?? site.ogType,
731
- twitterCard: page.twitterCard ?? site.twitterCard,
732
- keywords: page.keywords ?? site.keywords,
733
- noindex,
734
- robots,
735
- metatags,
736
- title: page.title,
737
- description: page.description,
738
- canonical: page.canonical,
739
- jsonLd: page.jsonLd,
740
- };
741
- }
742
-
743
- const MINTLIFY_MODE_ALIASES: Record<string, string> = { center: 'frame', assistant: 'default' };
744
-
745
- /** A page's own frontmatter - the `pages` and `generatedDocs` content
746
- * collections' schema (content.config.ts), and what `writedocs validate`
747
- * checks every page against. */
748
- export const pageFrontmatterSchema = z.object({
749
- title: z.string(),
750
- description: z.string().optional(),
751
- // Overrides the URL this page is served at, independent of where the
752
- // file actually lives - writedocs.json's `pages` arrays always keep
753
- // referencing the file's own path regardless. This is Astro's own
754
- // glob()-loader convention (a `slug` frontmatter field becomes
755
- // `entry.id` verbatim - see generateIdDefault in
756
- // astro/dist/content/loaders/glob.js), not writedocs-specific
757
- // behavior; declaring it here just brings it into the schema (and
758
- // its docs) rather than leaving it an undocumented Astro feature.
759
- // See fileIdForEntry() in lib/config.ts for how routes/links still
760
- // resolve a page by its file id once this diverges from `entry.id`.
761
- // Leading/trailing slashes are fine either way ("/", "/guides/x",
762
- // "guides/x" and "guides/x/" all mean the same thing) - see
763
- // normalizeEntryId() in lib/config.ts, which is what actually
764
- // strips them before this value is ever used as a route or href.
765
- slug: z.string().optional(),
766
- // Marks this page as an OpenAPI operation reference: "METHOD /path"
767
- // matching an operation in the owning group's OpenAPI spec, e.g.
768
- // "GET /pets/{petId}" - [...slug].astro renders <ApiPlayground /> for
769
- // any page with this field set, below the page's own MDX body (if
770
- // any). Sites don't write this by hand for most pages; it's either
771
- // set on a generated stub in the `generatedDocs` collection below (see
772
- // generate-api-pages.js) or hand-authored to "eject" one specific
773
- // operation into a real file (in `docs`) with custom prose - either
774
- // way, the value is always exactly the same "METHOD /path" key
775
- // generate-api-pages.js uses to look up the operation's full resolved
776
- // schema/examples at render time.
777
- openapi: z.string().optional(),
778
- // Controls how much of the site's own chrome (topbar, sidebar, table of
779
- // contents) wraps this page - see BaseLayout.astro/[...slug].astro for
780
- // what each value actually removes:
781
- // default - the normal three-column reading layout (all chrome).
782
- // wide - drops the table of contents; the article itself also
783
- // renders wider, for content that wants the extra room
784
- // (wide tables, side-by-side images).
785
- // frame - drops the sidebar and table of contents, but keeps the
786
- // topbar and the article's own normal presentation
787
- // ("frame" as in: still inside the site's outer frame).
788
- // custom - drops the sidebar and table of contents, the
789
- // auto-rendered <h1>, and prev/next nav, and skips the
790
- // article's own prose width/padding too - a blank canvas
791
- // for a hand-built landing/home page made entirely of
792
- // components - but keeps the topbar, so the page still
793
- // has site branding/nav/search/theme-toggle available.
794
- // blank - everything 'custom' drops, plus the topbar too: no site
795
- // chrome at all, just <slot />. For a page that wants to
796
- // look nothing like the rest of the site (an auth screen,
797
- // a print-style page).
798
- //
799
- // Two Mintlify values are accepted so a migrated page doesn't fail the
800
- // build (see MINTLIFY_MODE_ALIASES above): `center` is the same layout
801
- // as our `frame`, and `assistant` (a full-page Mintlify AI chat, which
802
- // writedocs doesn't have) falls back to `default`. Mintlify's own
803
- // `frame` means something else (a canvas that keeps the sidebar) - it's
804
- // left as our `frame`; see docs/dev/docs/mintlify-compat.mdx.
805
- mode: z
806
- .preprocess(
807
- (value) => (typeof value === 'string' && value in MINTLIFY_MODE_ALIASES ? MINTLIFY_MODE_ALIASES[value] : value),
808
- z.enum(['default', 'wide', 'frame', 'custom', 'blank']),
809
- )
810
- .default('default'),
811
- // Per-page meta tag overrides - same shape as writedocs.json's top-level
812
- // `seo` (see seoFieldsSchema in lib/config.ts, the single source of
813
- // truth for this shape). A page only needs to set the specific fields
814
- // it wants to override; mergeSeo() falls back to the site-wide default
815
- // for anything left unset. See BaseLayout.astro for where this and the
816
- // site-wide seo actually get merged and rendered.
817
- seo: pageSeoFieldsSchema.optional(),
818
- // Mintlify's spelling of `seo.noindex` - a top-level `noindex: true`.
819
- // Folded into `seo` by the transform below, so everything downstream
820
- // (the robots meta tag, sitemap.xml, llms.txt) keeps reading
821
- // `seo.noindex` only.
822
- noindex: z.boolean().optional(),
823
- // Mintlify's spellings of `seo.robots` and `seo.canonical`, folded into
824
- // `seo` the same way.
825
- robots: z.string().optional(),
826
- canonical: z.string().optional(),
827
- // Mintlify's short navigation label - used for the sidebar and the
828
- // topbar dropdown menus in place of `title` ([...slug].astro's
829
- // navTitleForSlug). The page's own <h1> and prev/next links keep `title`.
830
- sidebarTitle: z.string().optional(),
831
- // Mintlify's spellings of `seo.keywords`, `seo.ogImage`, `seo.ogType`
832
- // and `seo.twitterCard`, folded into `seo` below like `noindex`.
833
- keywords: z.array(z.string()).optional(),
834
- 'og:image': z.string().optional(),
835
- 'og:type': z.string().optional(),
836
- 'twitter:card': z.enum(['summary', 'summary_large_image']).optional(),
837
- // Mintlify's sidebar/page-chrome fields - see NavTree.astro and
838
- // [...slug].astro for where each is used:
839
- // icon - shown before the page's label in the sidebar.
840
- // tag - a short label after it (e.g. "NEW").
841
- // deprecated - a "Deprecated" label in the sidebar and next
842
- // to the page's <h1>.
843
- // hidden - left out of the sidebar, dropdowns and
844
- // prev/next, but still built and reachable by
845
- // URL. Also noindexed, as on Mintlify.
846
- // url - an external link: the page's sidebar entry
847
- // links straight to it, and the page's own URL
848
- // redirects there.
849
- // hideFooterPagination - no prev/next links on this page.
850
- // hideApiMarker - no HTTP method badge on this page's sidebar
851
- // entry.
852
- icon: z.string().optional(),
853
- tag: z.string().optional(),
854
- deprecated: z.boolean().optional(),
855
- hidden: z.boolean().optional(),
856
- url: z.string().optional(),
857
- hideFooterPagination: z.boolean().optional(),
858
- hideApiMarker: z.boolean().optional(),
859
- }).transform(
860
- ({ noindex, robots, canonical, keywords, 'og:image': ogImage, 'og:type': ogType, 'twitter:card': twitterCard, ...data }) => {
861
- // Top-level Mintlify keys fill in `seo` only where the page's own `seo`
862
- // doesn't already set that field - an explicit `seo` value always wins.
863
- // A `hidden` page is noindexed unless it says otherwise.
864
- const seo = { ...data.seo };
865
- // `robots` says whether the page is indexed, so with one - the page's
866
- // own, or the top-level spelling - `noindex` follows it, and a `hidden`
867
- // page's automatic noindex doesn't apply.
868
- const pageRobots = seo.robots ?? robots;
869
- const fromMintlify = {
870
- robots,
871
- canonical,
872
- noindex: pageRobots !== undefined ? undefined : (noindex ?? (data.hidden ? true : undefined)),
873
- keywords,
874
- ogImage,
875
- ogType,
876
- twitterCard,
877
- };
878
- let changed = false;
879
- for (const [key, value] of Object.entries(fromMintlify)) {
880
- if (value === undefined || seo[key as keyof typeof seo] !== undefined) continue;
881
- (seo as Record<string, unknown>)[key] = value;
882
- changed = true;
883
- }
884
- if (pageRobots !== undefined) {
885
- seo.noindex = /\bnoindex\b|\bnone\b/i.test(pageRobots);
886
- changed = true;
887
- }
888
- return changed ? { ...data, seo } : data;
889
- },
890
- );
891
-
892
- // Controls for the OpenAPI API playground's "Try it" modal - separate
893
- // from a group's own `openapi: { src, path }` field (which spec to use,
894
- // and where) since this is about how a *request* it sends behaves, not
895
- // about the spec itself.
896
- const apiSchema = z
897
- .object({
898
- // Whether a Try-it request the browser blocks is retried through
899
- // writedocs' own CORS proxy (https://proxy.writechoice.io/). The
900
- // request always goes to the API directly first, so a reader's key
901
- // reaches the proxy only when the API itself refuses browser calls.
902
- // Almost no real-world API sends back Access-Control-Allow-Origin
903
- // headers permitting an arbitrary docs site's origin, so the direct
904
- // call fails for most real APIs - see the send handler and
905
- // PROXY_BASE_URL in ApiReferencePanel.astro. Defaults to enabled; a
906
- // site can set this to `false` to never involve a third party.
907
- proxy: z.boolean().default(true),
908
- })
909
- .strict()
910
- .default({ proxy: true });
911
-
912
- // The "Copy page" menu shown next to a page's title - copy the page's
913
- // Markdown, view it, or open it in an AI assistant - and the .md copy of
914
- // every page it relies on ([...slug].md.ts). On by default, with every
915
- // option, like the MCP server. writedocs.json narrows or turns it off:
916
- //
917
- // (absent) or true every option
918
- // ["copy", "claude"] only these, in the menu's own order
919
- // (copy, view, chatgpt, claude, perplexity,
920
- // mcp, cursor, vscode - the last three connect
921
- // AI tools to the site's MCP server, and are
922
- // left out when `mcp` is false)
923
- // false (or []) no menu, and no .md routes
924
- // { "openIn": [...] } the earlier form: copy and view, plus these
925
- // assistants - still accepted
926
- //
927
- // Read it through contextMenuOptions() below - never test the raw value for
928
- // truthiness: absent now means on.
929
- export const CONTEXT_MENU_OPTIONS = ['copy', 'view', 'chatgpt', 'claude', 'perplexity', 'mcp', 'cursor', 'vscode'] as const;
930
- export type ContextMenuOption = (typeof CONTEXT_MENU_OPTIONS)[number];
931
- const ASSISTANT_OPTIONS = ['chatgpt', 'claude', 'perplexity'] as const;
932
- /** The options that point at the site's MCP server - see `mcp` below. */
933
- export const MCP_MENU_OPTIONS = ['mcp', 'cursor', 'vscode'] as const;
934
-
935
- const contextMenuSchema = z.union([
936
- z.boolean(),
937
- z.array(z.enum(CONTEXT_MENU_OPTIONS)),
938
- z
939
- .object({
940
- openIn: z.array(z.enum(ASSISTANT_OPTIONS)).optional(),
941
- })
942
- .strict(),
943
- ]);
944
-
945
- export type ContextMenuConfig = z.infer<typeof contextMenuSchema>;
946
-
947
- /** The menu options a writedocs.json `contextMenu` value turns on, in menu
948
- * order - [] when the menu is off. Takes the raw value too (link-check.js
949
- * reads writedocs.json without the schema), so absent means every option.
950
- * With `mcp: false` (no MCP server), the MCP options are left out. */
951
- export function contextMenuOptions(value: unknown, { mcp = true }: { mcp?: boolean } = {}): ContextMenuOption[] {
952
- const available = CONTEXT_MENU_OPTIONS.filter((option) => mcp || !(MCP_MENU_OPTIONS as readonly string[]).includes(option));
953
- if (value === false) return [];
954
- if (value === undefined || value === null || value === true) return [...available];
955
- if (Array.isArray(value)) return available.filter((option) => value.includes(option));
956
- if (typeof value === 'object') {
957
- const openIn = (value as { openIn?: unknown }).openIn;
958
- const assistants = Array.isArray(openIn) ? openIn : [...ASSISTANT_OPTIONS];
959
- return CONTEXT_MENU_OPTIONS.filter((option) => option === 'copy' || option === 'view' || assistants.includes(option));
960
- }
961
- return [];
962
- }
963
-
964
- // One entry in writedocs.json's `redirects` array - wired almost directly into
965
- // Astro's own `redirects` config option (astro.config.mjs), which is what
966
- // actually generates the redirect pages. `permanent` is deliberately not
967
- // part of this schema: with no server/adapter (this project always builds
968
- // `output: 'static'` with none installed), Astro's own docs say a static
969
- // redirect "does not support status codes" at all - it's always a client-
970
- // side `<meta http-equiv="refresh">` page, full stop. Accepting a
971
- // `permanent` field here that silently did nothing would be worse than
972
- // not offering it.
973
- const redirectSchema = z
974
- .object({
975
- source: z.string(),
976
- destination: z.string(),
977
- })
978
- .strict();
979
-
980
- export type RedirectConfig = z.infer<typeof redirectSchema>;
981
-
982
- // A site-wide banner rendered above the topbar on every page (except
983
- // `mode: blank`, which drops all site chrome including this - see
984
- // BaseLayout.astro). Optional/undefined by default, same convention as
985
- // `contextMenu` above - a site with no banner configured gets no banner
986
- // markup at all, not an empty one.
987
- const bannerSchema = z
988
- .object({
989
- content: z.string(),
990
- // Persisted via localStorage once dismissed (see BaseLayout.astro's
991
- // initBanner()) - a static site has no server-side session to track
992
- // this against, so "dismissed" only ever means "dismissed in this
993
- // browser". A banner without `dismissible` reappears on every visit,
994
- // appropriate for something that should stay visible until the site
995
- // author removes it from writedocs.json themselves (e.g. "this version is
996
- // deprecated"), not something a reader can permanently clear.
997
- dismissible: z.boolean().default(false),
998
- type: z.enum(['info', 'warning', 'critical']).default('info'),
999
- })
1000
- .strict();
1001
-
1002
- export type BannerConfig = z.infer<typeof bannerSchema>;
1003
-
1004
- // Content for the custom 404 page (src/pages/404.astro) - Astro's own
1005
- // file-based convention (a static build emits this as 404.html at the
1006
- // site root; most static hosts pick it up automatically for unmatched
1007
- // routes). Both fields are optional with hardcoded fallbacks in 404.astro
1008
- // itself, so a site doesn't have to set either to get a reasonably
1009
- // branded 404 page (still rendered inside the normal BaseLayout/topbar
1010
- // chrome, just with placeholder content).
1011
- const notFoundSchema = z
1012
- .object({
1013
- title: z.string().optional(),
1014
- description: z.string().optional(),
1015
- })
1016
- .strict()
1017
- .default({});
1018
-
1019
- export type NotFoundConfig = z.infer<typeof notFoundSchema>;
1020
-
1021
- // One <script> tag to inject - exactly one of `src` (an external/local
1022
- // file, rendered as `<script src="...">`) or `content` (inline JS,
1023
- // rendered via `<script is:inline set:html="...">`) has to be set, not
1024
- // both and not neither - enforced by the `.refine()` below rather than
1025
- // leaving both optional and silently rendering an empty tag if a site
1026
- // author gets this wrong.
1027
- const scriptEntrySchema = z
1028
- .object({
1029
- src: z.string().optional(),
1030
- content: z.string().optional(),
1031
- // With `integrations.consent` on, a script marked `true` loads only
1032
- // once the reader accepts, like the analytics integrations. Without the
1033
- // banner it loads as any other script.
1034
- consent: z.boolean().optional(),
1035
- })
1036
- .strict()
1037
- .refine((v) => (v.src ? !v.content : !!v.content), {
1038
- message: 'Each scripts.head/scripts.body entry needs exactly one of "src" or "content", not both or neither.',
1039
- });
1040
-
1041
- export type ScriptEntry = z.infer<typeof scriptEntrySchema>;
1042
-
1043
- // Raw third-party script injection - analytics snippets, chat widgets,
1044
- // anything that needs a real <script> tag writedocs.json's own structured
1045
- // fields (styles, integrations-style config, ...) don't have a dedicated
1046
- // slot for yet. `head` renders right before </head>; `body` renders right
1047
- // before </body> (after everything else has already loaded/hydrated -
1048
- // see BaseLayout.astro), matching where a third-party script's own
1049
- // install instructions usually say to put it.
1050
- const scriptsSchema = z
1051
- .object({
1052
- head: z.array(scriptEntrySchema).default([]),
1053
- body: z.array(scriptEntrySchema).default([]),
1054
- })
1055
- .strict()
1056
- .default({ head: [], body: [] });
1057
-
1058
- export type ScriptsConfig = z.infer<typeof scriptsSchema>;
1059
-
1060
- // writedocs.json's `integrations` - a curated, high-value subset of analytics
1061
- // providers, each getting its own minimal config object (just the id(s)
1062
- // it actually needs) rather than requiring a site author to hand-write
1063
- // the provider's own install snippet through the generic `scripts` field
1064
- // above. This is deliberately its own thing, not built as sugar over
1065
- // `scripts` the way the roadmap once implied it might be - most of these
1066
- // providers' real snippets need `defer`/`async`/`data-*` attributes
1067
- // ScriptEntry's plain `{ src?, content? }` shape has no way to express,
1068
- // so BaseLayout.astro renders each provider with its own bespoke markup
1069
- // instead of generating a ScriptEntry array to feed through the generic
1070
- // renderer. Every snippet shape below was sourced from that provider's
1071
- // own current official docs (fetched directly, not recalled from
1072
- // training data) while building this feature - see
1073
- // docs/dev/docs/integrations.mdx for links and dates.
1074
- //
1075
- // Every provider field is optional and independent - a site can turn on
1076
- // any subset (including all of them at once, for a migration period) or
1077
- // none. No "the" analytics field; a site picks whichever provider(s) it
1078
- // actually uses.
1079
-
1080
- const ga4IntegrationSchema = z
1081
- .object({
1082
- // A GA4 "Measurement ID", always shaped like "G-XXXXXXXXXX" - not
1083
- // validated against that shape here, since Google could change the
1084
- // prefix/length without this schema needing to track it.
1085
- measurementId: z.string(),
1086
- })
1087
- .strict();
1088
-
1089
- const googleTagManagerIntegrationSchema = z
1090
- .object({
1091
- // A GTM container id, shaped like "GTM-XXXXXXX".
1092
- containerId: z.string(),
1093
- })
1094
- .strict();
1095
-
1096
- const plausibleIntegrationSchema = z
1097
- .object({
1098
- domain: z.string(),
1099
- // Plausible's own hosted script URL by default - override for a
1100
- // self-hosted instance, a reverse-proxy path (Plausible's own
1101
- // documented way to dodge ad-blockers), or one of Plausible's
1102
- // documented script *extensions* (e.g.
1103
- // "https://plausible.io/js/script.hash.outbound-links.js").
1104
- src: z.string().default('https://plausible.io/js/script.js'),
1105
- })
1106
- .strict();
1107
-
1108
- const fathomIntegrationSchema = z
1109
- .object({
1110
- // Fathom's own short "Site ID", not a full URL or measurement id.
1111
- siteId: z.string(),
1112
- })
1113
- .strict();
1114
-
1115
- const posthogIntegrationSchema = z
1116
- .object({
1117
- // PostHog calls this a "project API key" (starts with "phc_") in its
1118
- // own docs - `apiKey` here rather than that exact name, matching this
1119
- // schema's own plainer naming convention for the equivalent id on
1120
- // every other provider above.
1121
- apiKey: z.string(),
1122
- // PostHog is region-sharded (US/EU) with no single universal default
1123
- // - "https://us.i.posthog.com" is PostHog's own default for a new
1124
- // project, but a site on their EU cloud (or a self-hosted instance)
1125
- // must override this to the host shown in their own project
1126
- // settings, or events silently go nowhere.
1127
- apiHost: z.string().default('https://us.i.posthog.com'),
1128
- })
1129
- .strict();
1130
-
1131
- const umamiIntegrationSchema = z
1132
- .object({
1133
- websiteId: z.string(),
1134
- // Unlike Plausible/PostHog, Umami has no single hosted default that
1135
- // works for most users - it's commonly self-hosted, and even Umami
1136
- // Cloud users get a per-region script URL. Defaults to Umami Cloud's
1137
- // own documented script URL, which only happens to be correct for a
1138
- // Cloud user on that specific region; anyone self-hosting (the more
1139
- // common case for this particular provider) must override it to
1140
- // their own instance's own /script.js path.
1141
- src: z.string().default('https://cloud.umami.is/script.js'),
1142
- })
1143
- .strict();
1144
-
1145
- // AI chat over the site's own docs content, via a third-party provider
1146
- // (DocsBot, currently the only one wired up) rather than a self-hosted
1147
- // RAG pipeline - see the roadmap's own "AI chat over docs content" line
1148
- // in docs/dev/docs/roadmap.mdx, which this fulfills via integration
1149
- // rather than by building the retrieval/generation stack in-house.
1150
- // Deliberately named `askAi` here, not `docsbot` - this is the
1151
- // writedocs.json-facing, provider-neutral name for the feature (matching
1152
- // the "Ask AI" label this kind of button/widget is conventionally
1153
- // given in docs sites generally), independent of which vendor happens
1154
- // to sit behind it today. `id` matches DocsBot's own embed config
1155
- // field name exactly (`DocsBotAI.init({ id: 'teamId/botId' })`) - it's
1156
- // a single opaque "teamId/botId" string DocsBot treats as one value,
1157
- // not two separate ids, so this schema doesn't split it either.
1158
- const askAiIntegrationSchema = z
1159
- .object({
1160
- id: z.string(),
1161
- })
1162
- .strict();
1163
-
1164
- // A consent banner for the analytics integrations above: with it, none of
1165
- // their scripts load until the reader accepts (see lib/consent.js and
1166
- // ConsentBanner.astro). `true` uses the default texts; an object changes
1167
- // them. The reader's answer is kept in the browser's localStorage.
1168
- const consentSchema = z.union([
1169
- z.boolean(),
1170
- z
1171
- .object({
1172
- message: z.string().optional(),
1173
- acceptLabel: z.string().optional(),
1174
- declineLabel: z.string().optional(),
1175
- // A link after the message - a privacy or cookie policy.
1176
- policyUrl: z.string().optional(),
1177
- policyLabel: z.string().optional(),
1178
- })
1179
- .strict(),
1180
- ]);
1181
-
1182
- const integrationsSchema = z
1183
- .object({
1184
- ga4: ga4IntegrationSchema.optional(),
1185
- googleTagManager: googleTagManagerIntegrationSchema.optional(),
1186
- plausible: plausibleIntegrationSchema.optional(),
1187
- fathom: fathomIntegrationSchema.optional(),
1188
- posthog: posthogIntegrationSchema.optional(),
1189
- umami: umamiIntegrationSchema.optional(),
1190
- askAi: askAiIntegrationSchema.optional(),
1191
- consent: consentSchema.optional(),
1192
- })
1193
- .strict()
1194
- .default({});
1195
-
1196
- export type IntegrationsConfig = z.infer<typeof integrationsSchema>;
1197
-
1198
- export const docsConfigSchema = z.object({
1199
- name: z.string(),
1200
- description: z.string().optional(),
1201
- styles: stylesSchema,
1202
- navigation: navigationSchema,
1203
- // Platform name -> profile/page URL (e.g. `{ "github": "https://
1204
- // github.com/...", "twitter": "https://twitter.com/..." }`), free-form
1205
- // rather than an enum of known platforms - the key doubles as the icon
1206
- // reference BaseLayout.astro's footer resolves via resolveIcon() below
1207
- // (bare `"github"` -> `lucide:github`; use an explicit
1208
- // `"simple-icons:whatever"` key instead when the bare lucide name isn't
1209
- // right for a given platform). Rendered as a row of icon links in the
1210
- // footer - see hasFooterContent/`.wd-footer-socials` in BaseLayout.astro.
1211
- socials: z.record(z.string(), z.string()).default({}),
1212
- topbar: z
1213
- .object({ links: z.array(topbarLinkSchema).default([]) })
1214
- .default({ links: [] }),
1215
- // Columns of links below the page content - see footerSchema/
1216
- // footerColumnSchema above. Renders alongside `socials` above (as a row
1217
- // of icon links) in the same <footer> - see BaseLayout.astro.
1218
- footer: footerSchema,
1219
- api: apiSchema,
1220
- // The site's own deployed domain, e.g. "docs.example.com" or
1221
- // "https://docs.example.com" (the scheme is optional - resolveSiteUrl()
1222
- // below normalizes either form to a full https:// origin). Powers three
1223
- // things that all need an absolute origin to work: sitemap.xml
1224
- // generation (astro.config.mjs only registers @astrojs/sitemap when this
1225
- // is set - a sitemap of relative URLs isn't meaningful), the canonical
1226
- // <link> and og:url/twitter meta tags (BaseLayout.astro), and resolving
1227
- // a relative `seo.ogImage` into an absolute URL for social crawlers.
1228
- // Left optional and simply skipped (with a log message, not an error) at
1229
- // every one of those call sites when unset - most fixtures/local builds
1230
- // have no real deployed domain yet.
1231
- domain: z.string().optional(),
1232
- // The path the site is served under on `domain`, like "/docs" for
1233
- // empresa.com/docs (usually behind the customer's own proxy). Every
1234
- // address the site makes starts with it, and the build writes the site to
1235
- // dist/<basePath>/ - see src/lib/base-path.js. Absent, "" or "/": the site
1236
- // at the root, exactly as without the field.
1237
- basePath: z
1238
- .string()
1239
- .regex(BASE_PATH_FIELD_PATTERN, {
1240
- message:
1241
- '"basePath" must be a path like "/docs" or "/help/docs": it starts with "/", has no "/" at the end, and each part has only lowercase letters, digits, "-" and "_".',
1242
- })
1243
- .optional(),
1244
- // Site-wide meta tag defaults - see seoFieldsSchema above. A page's own
1245
- // frontmatter `seo` (content.config.ts's docsSchema) overrides these
1246
- // field by field via mergeSeo(), rather than needing to repeat every
1247
- // field on every page.
1248
- seo: siteSeoFieldsSchema.default({}),
1249
- // The "Copy page" menu - see contextMenuSchema above. Absent means on,
1250
- // with every option; read it through contextMenuOptions().
1251
- contextMenu: contextMenuSchema.optional(),
1252
- // The site's MCP server - an AI tool connects to `/mcp` and searches and
1253
- // reads the docs. On by default: `writedocs build` writes the page index
1254
- // (mcp-index.json) and a Cloudflare-ready `_worker.js` into dist/ (see
1255
- // src/cli/write-mcp-files.js). `false` leaves all of it out.
1256
- mcp: z.boolean().default(true),
1257
- // See redirectSchema above. Wired directly into Astro's own `redirects`
1258
- // config option in astro.config.mjs.
1259
- redirects: z.array(redirectSchema).default([]),
1260
- // Site-wide `[[key]]` substitution values, applied to page prose text
1261
- // at build time (see the remarkSubstituteVariables plugin wired into
1262
- // astro.config.mjs) - e.g. `{ "productName": "Acme" }` lets every page
1263
- // write `[[productName]]` once instead of hardcoding it everywhere.
1264
- // Double square brackets, not the more familiar `{{key}}` - MDX
1265
- // reserves single curly braces for embedded JS expressions, so
1266
- // `{{productName}}` in an .mdx file parses as a JS object-literal
1267
- // expression (`{productName}`, shorthand syntax) rather than literal
1268
- // text, and throws `ReferenceError: productName is not defined` at
1269
- // render time - see remarkSubstituteVariables' own comment in
1270
- // mdx-substitute-variables.js for the full explanation. Deliberately a
1271
- // flat string map, not typed values - this is text substitution into
1272
- // prose, not a templating language.
1273
- variables: z.record(z.string(), z.string()).default({}),
1274
- // See bannerSchema above. Absent by default (no banner rendered).
1275
- banner: bannerSchema.optional(),
1276
- // See notFoundSchema above.
1277
- notFound: notFoundSchema,
1278
- // See scriptsSchema above.
1279
- scripts: scriptsSchema,
1280
- // See integrationsSchema above.
1281
- integrations: integrationsSchema,
1282
- });
1283
-
1284
- export type DocsConfig = z.infer<typeof docsConfigSchema>;
1285
-
1286
- // ---------------------------------------------------------------------
1287
- // Ponto de entrada unico de validacao
1288
- //
1289
- // Existe pra que o gerador (`writedocs validate` e o `loadDocsConfig` que o
1290
- // build usa) e a plataforma validem pelo MESMO codigo, com as MESMAS palavras -
1291
- // o criterio de aceite do WD-066 e do WD-062. Se cada lado formatasse os erros
1292
- // por conta propria, o cliente veria a plataforma aceitar um writedocs.json que
1293
- // o build depois recusa, que e exatamente a classe de bug que a E11 existe pra
1294
- // impedir.
1295
- //
1296
- // Recebe TEXTO CRU, e faz o JSON.parse por conta propria, por tres motivos:
1297
- // 1. um JSON sintaticamente quebrado passa a ser um resultado de validacao
1298
- // como qualquer outro, em vez de uma excecao solta do runtime;
1299
- // 2. linha/coluna so existem no texto - e o WD-063 precisa reportar linha;
1300
- // 3. do lado da plataforma, importProjectConfig ja tem os bytes crus em maos
1301
- // antes de parsear, entao encaixa sem ginastica nenhuma.
1302
- //
1303
- // IMPORTANTE, e deliberado: as mensagens aqui sao as do Zod, VERBATIM. Melhorar
1304
- // a linguagem delas e o WD-063, que precisa deste comportamento como ponto de
1305
- // partida pra medir a melhora. Nada aqui reescreve, traduz ou embeleza mensagem.
1306
- //
1307
- // WD-315 - O TETO. O validateDocsConfig() devolve no maximo os primeiros
1308
- // VALIDATION_ISSUE_LIMIT problemas, na ordem de sempre, e o total deles em
1309
- // `issuesTotal`; o unknownRootKeyWarnings() faz o mesmo com os avisos. So os
1310
- // que voltam sao localizados (linha/coluna) e humanizados - o resto e contado
1311
- // e nada mais. O motivo: um writedocs.json de ~11 MB (o porte do maior
1312
- // docs.json de cliente que ja vimos) com uma pagina errada em cada uma das 66
1313
- // mil levava 169 s e ~1,2 GB so pra localizar os erros, e a plataforma valida
1314
- // por esta mesma funcao dentro de um Worker de 128 MB. Ninguem le 66 mil
1315
- // erros; quase sempre e o mesmo engano repetido, e os 100 primeiros mostram
1316
- // qual. Ate o teto, o resultado e exatamente o de antes do teto: a mesma
1317
- // lista, as mesmas mensagens e linhas (provado na rodada gerador/07 com o
1318
- // corpus da plataforma). O numero e exportado pra que a plataforma grave o
1319
- // mesmo tanto que o gerador mostra.
1320
- //
1321
- // WD-315 (07c) - PARAR CEDO. O teto cortava o custo de localizar, mas o Zod
1322
- // ainda produzia todos os erros antes: 100 mil itens errados em 0,2 MB pediam
1323
- // ~270 MB so no safeParse. Agora a validacao para de trabalhar depois de
1324
- // VALIDATION_ISSUE_LIMIT + 1 erros - ver a secao "PARAR CEDO" mais abaixo, que
1325
- // diz como, e por que isso nao muda nada ate o teto. Acima dele, o
1326
- // `issuesTotal` deixa de ser exato: vira "pelo menos" (VALIDATION_ISSUE_LIMIT +
1327
- // 1), com `issuesTruncated: true`. Para a lista inteira, `{ all: true }` (o
1328
- // `writedocs validate --all`) valida tudo, sem parar, como antes.
1329
- // ---------------------------------------------------------------------
1330
-
1331
- /** WD-315: quantos problemas o validateDocsConfig() (e o
1332
- * unknownRootKeyWarnings()) devolve, no maximo - os primeiros, na ordem de
1333
- * sempre. O total vem em `issuesTotal`. */
1334
- export const VALIDATION_ISSUE_LIMIT = 100;
1335
-
1336
- /** `all: true` - a lista inteira, sem teto e sem parar (o `writedocs validate
1337
- * --all`). Custa o que a validacao custava antes do WD-315: so pra quem pediu,
1338
- * na propria maquina. */
1339
- export type ValidationOptions = { all?: boolean };
1340
-
1341
- /** Um problema encontrado na configuracao. `path` e o caminho do campo em
1342
- * notacao de ponto (`navigation.tabs.0.label`), ou `(root)` quando o problema e
1343
- * do documento inteiro - o mesmo texto que a mensagem de erro do build ja
1344
- * imprime hoje. `line`/`column` so vem quando da pra saber (hoje: erro de JSON;
1345
- * no WD-063, tambem para erros de schema). */
1346
- export type ValidationIssue = {
1347
- path: string;
1348
- message: string;
1349
- /** Codigo do Zod (`invalid_type`, `unrecognized_keys`, ...) ou `invalid_json`. */
1350
- code?: string;
1351
- line?: number;
1352
- column?: number;
1353
- /** WD-063: a mesma coisa que `message`, dita para gente. ADICIONAL, nunca
1354
- * substituto - `message` continua sendo o texto do Zod verbatim, que e o que
1355
- * o `writedocs build` imprime e o que o WD-062 grava em `validation_issues`.
1356
- * Quem exibe escolhe qual dos dois mostrar. */
1357
- humanMessage?: string;
1358
- /** O que fazer a respeito, quando da pra dizer algo concreto. */
1359
- suggestion?: string;
1360
- /** Chave ESTAVEL de documentacao (`config.styles`), nunca uma URL: uma URL
1361
- * cravada num pacote npm fica quebrada em toda instalacao ate a proxima
1362
- * release, e o mesmo erro e exibido pela CLI e pelo dashboard, que podem
1363
- * querer destinos diferentes. O mapa chave -> URL mora do lado de quem
1364
- * renderiza. */
1365
- docKey?: string;
1366
- };
1367
-
1368
- /** Sucesso carrega os dados ja validados (com os defaults do schema aplicados);
1369
- * falha carrega os problemas e diz de que tipo ela foi. `parseError` so aparece
1370
- * quando o JSON nao pode nem ser parseado, e existe para o chamador que quiser
1371
- * relancar exatamente o erro original (e o que o loadDocsConfig faz, pra nao
1372
- * mudar uma virgula do que o `writedocs build` ja imprime hoje).
1373
- *
1374
- * `issues` traz no maximo VALIDATION_ISSUE_LIMIT problemas. `issuesTotal`:
1375
- * quantos ha ao todo (0 num config valido, 1 num JSON quebrado) quando
1376
- * `issuesTruncated` e false; quando e true, a validacao parou depois do teto, e
1377
- * `issuesTotal` e so um minimo (VALIDATION_ISSUE_LIMIT + 1). Com `{ all: true }`
1378
- * nao ha teto: `issues` traz todos, e `issuesTruncated` e sempre false. */
1379
- export type ValidationResult =
1380
- | { ok: true; data: DocsConfig; issues: ValidationIssue[]; issuesTotal: number; issuesTruncated: boolean }
1381
- | {
1382
- ok: false;
1383
- data: null;
1384
- kind: 'invalid_json' | 'schema';
1385
- issues: ValidationIssue[];
1386
- issuesTotal: number;
1387
- issuesTruncated: boolean;
1388
- parseError?: SyntaxError;
1389
- };
1390
-
1391
- /** "at position 22 (line 1 column 23)" -> { line: 1, column: 23 }.
1392
- * O formato da mensagem de erro do JSON.parse e do V8, nao do padrao, entao
1393
- * isto e melhor-esforco: se a mensagem nao trouxer posicao, devolve null e o
1394
- * problema simplesmente fica sem linha. */
1395
- function positionFromJsonError(message: string, rawText: string): { line: number; column: number } | null {
1396
- const comLinha = message.match(/line (\d+) column (\d+)/);
1397
- if (comLinha) return { line: Number(comLinha[1]), column: Number(comLinha[2]) };
1398
- const comPosicao = message.match(/position (\d+)/);
1399
- if (comPosicao) {
1400
- const pos = Math.min(Number(comPosicao[1]), rawText.length);
1401
- const antes = rawText.slice(0, pos);
1402
- const line = antes.split('\n').length;
1403
- return { line, column: pos - antes.lastIndexOf('\n') };
1404
- }
1405
- return null;
1406
- }
1407
-
1408
- /** O corpo da mensagem de erro, uma linha por problema - exatamente o formato
1409
- * que o `writedocs build` imprime desde sempre (` - campo: mensagem`). Fica
1410
- * aqui, e nao em cada chamador, pra que CLI e plataforma nao possam divergir.
1411
- *
1412
- * NAO mudou no WD-063, de proposito: continua imprimindo `message` (o texto do
1413
- * Zod). O que melhorou foi o CONTEUDO dos issues - a uniao desembrulhada faz o
1414
- * `path` apontar pro campo real em vez de parar em `navigation`. Quem quiser a
1415
- * versao com frase humana e linha usa formatValidationIssuesDetailed.
1416
- *
1417
- * `total` e `truncated` (o `issuesTotal` e o `issuesTruncated` do resultado):
1418
- * quando ha mais problemas do que os listados, uma ultima linha diz quantos
1419
- * ficaram de fora, ou que ha mais (WD-315). */
1420
- export function formatValidationIssues(
1421
- issues: ValidationIssue[],
1422
- { total, truncated }: { total?: number; truncated?: boolean } = {}
1423
- ): string {
1424
- const linhas = issues.map((i) => ` - ${i.path}: ${i.message}`);
1425
- const resto = moreIssuesLine(issues.length, total, truncated);
1426
- if (resto) linhas.push(` ${resto}`);
1427
- return linhas.join('\n');
1428
- }
1429
-
1430
- /** A linha do que ficou de fora, ou null quando nada ficou. Uma frase so pros
1431
- * dois formatadores (e pra plataforma, se ela quiser), como o resto das
1432
- * palavras deste modulo:
1433
- * - `truncated` (a validacao parou no teto): "...and more - run "writedocs
1434
- * validate --all" for the full list." - o quanto mais nao se sabe;
1435
- * - um total exato maior que a lista (os avisos, sempre exatos): "...and 50
1436
- * more - only the first 100 are listed.". */
1437
- export function moreIssuesLine(listados: number, total: number | undefined, truncated = false): string | null {
1438
- if (truncated) return '...and more - run "writedocs validate --all" for the full list.';
1439
- if (total === undefined || total <= listados) return null;
1440
- return `...and ${total - listados} more - only the first ${listados} are listed.`;
1441
- }
1442
-
1443
- /** A versao longa, para quem tem uma tela inteira (a CLI hoje, o dashboard do
1444
- * WD-065 se quiser): caminho, linha, frase humana, sugestao, e a mensagem do
1445
- * Zod por ultimo, entre parenteses, pra quem precisa do texto exato.
1446
- *
1447
- * Mora aqui pelo mesmo motivo que a irma curta: se cada consumidor montasse a
1448
- * sua, a CLI e a plataforma divergiriam na primeira mudanca - que e exatamente
1449
- * o que o AC do WD-066 proibe. `fileName` so entra na referencia de linha.
1450
- * `total`/`truncated`: como no formatValidationIssues, a linha do que ficou de
1451
- * fora. */
1452
- export function formatValidationIssuesDetailed(
1453
- issues: ValidationIssue[],
1454
- { fileName = 'writedocs.json', total, truncated }: { fileName?: string; total?: number; truncated?: boolean } = {}
1455
- ): string {
1456
- const resto = moreIssuesLine(issues.length, total, truncated);
1457
- return issues
1458
- .map((i) => {
1459
- const temCampo = i.path !== '(root)';
1460
- const local = i.line ? `${fileName}:${i.line}` : i.path;
1461
- const linhas = [` ${local}${i.line && temCampo ? ` (${i.path})` : ''}`];
1462
- linhas.push(` ${i.humanMessage ?? i.message}`);
1463
- if (i.suggestion) linhas.push(` ${i.suggestion}`);
1464
- if (i.humanMessage && i.message !== i.humanMessage) linhas.push(` (${i.message})`);
1465
- return linhas.join('\n');
1466
- })
1467
- .concat(resto ? [` ${resto}`] : [])
1468
- .join('\n\n');
1469
- }
1470
-
1471
- // ---------------------------------------------------------------------
1472
- // WD-063 — do issue do Zod para "onde esta o erro, e o que fazer"
1473
- //
1474
- // Tres transformacoes, nesta ordem:
1475
- // 1. desembrulhar `invalid_union` (senao todo erro dentro da navigation vira
1476
- // `navigation: "Invalid input"`, que e inutil num arquivo de 10 KB);
1477
- // 2. achar a linha no texto, pelo caminho ja desembrulhado;
1478
- // 3. escrever a frase humana, a sugestao e a docKey - POR CODIGO do Zod, nao
1479
- // por campo: um mapa por campo teria 17 entradas so na raiz e centenas no
1480
- // total, e envelheceria a cada campo novo do schema.
1481
- // ---------------------------------------------------------------------
1482
-
1483
- /** Chaves que a raiz aceita sem ser campo do schema, e que por isso NAO devem
1484
- * gerar aviso de chave desconhecida. Deliberadamente minuscula: a raiz nao e
1485
- * `.strict()` justamente pra nao quebrar configs existentes, e `$schema` foi um
1486
- * dos argumentos dessa decisao - avisar sobre ele contradiria o que o protegeu.
1487
- * Se esta lista passar de dois ou tres nomes, o problema e outro e a raiz
1488
- * precisa de outra conversa. */
1489
- export const ROOT_ALLOWED_EXTRA_KEYS: readonly string[] = Object.freeze(['$schema']);
1490
-
1491
- type IssueCru = {
1492
- code?: string;
1493
- path?: (string | number)[];
1494
- message: string;
1495
- expected?: string;
1496
- values?: unknown[];
1497
- keys?: string[];
1498
- minimum?: number;
1499
- maximum?: number;
1500
- origin?: string;
1501
- format?: string;
1502
- errors?: unknown[];
1503
- unionErrors?: unknown[];
1504
- /** WD-315 (07c): este issue nao e um erro, e o resumo de uma lista validada
1505
- * "contando sem guardar" - ver a secao PARAR CEDO. */
1506
- wdLista?: ResumoDeLista;
1507
- };
1508
-
1509
- type IssuePlano = IssueCru & { caminho: (string | number)[] };
1510
-
1511
- function issuesDoRamo(ramo: unknown): IssueCru[] {
1512
- if (Array.isArray(ramo)) return ramo as IssueCru[];
1513
- const comIssues = ramo as { issues?: IssueCru[] };
1514
- return comIssues?.issues ?? [];
1515
- }
1516
-
1517
- /** Os ramos de um `invalid_union`, ou null se o issue nao for uma uniao com
1518
- * ramos (uniao sem `errors` fica como esta - ver humanizar). */
1519
- function ramosDaUniao(issue: IssueCru): unknown[] | null {
1520
- const ramos = issue.code === 'invalid_union' ? issue.errors ?? issue.unionErrors : null;
1521
- return Array.isArray(ramos) && ramos.length > 0 ? ramos : null;
1522
- }
1523
-
1524
- /** O que a pontuacao de um ramo (melhorRamo) precisa saber do plano ACHATADO
1525
- * dele: quantos issues o plano tem (`n`) e a maior profundidade efetiva entre
1526
- * eles (`maior`: o comprimento do caminho relativo ao ramo, +1 para
1527
- * `unrecognized_keys`; -Infinity num plano vazio). */
1528
- type Resumo = { n: number; maior: number };
1529
-
1530
- /** O resumo de um ramo, memoizado por identidade do ramo.
1531
- *
1532
- * A memoizacao nao e otimizacao, e o que torna o achatamento viavel. Pontuar um
1533
- * ramo exige desembrulhar as unioes DENTRO dele, e cada uma dessas tem os seus
1534
- * proprios ramos - sem cache, a pontuacao visita o mesmo sub-ramo uma vez por
1535
- * caminho que leva ate ele, o que e exponencial na profundidade do aninhamento.
1536
- * Medido com grupos aninhados e um erro no fundo: 3,7 ms com 4 niveis, 281 ms
1537
- * com 8, 69 SEGUNDOS com 12. Com o cache, os mesmos casos ficam em 0,2 ms,
1538
- * porque cada no da arvore de erro do Zod e resumido uma vez so.
1539
- *
1540
- * Se alguem remover este cache por parecer supérfluo, o `writedocs validate`
1541
- * passa a travar em configs profundas. Nao remova.
1542
- *
1543
- * WD-315, tres mudancas:
1544
- * - o cache guardava o plano achatado inteiro de cada ramo de cada uniao, so
1545
- * pra contar os issues e medir a profundidade - com 66 mil erros, a mesma
1546
- * memoria que o Zod gasta pra produzi-los, de novo. O resumo e a mesma conta
1547
- * sem montar o plano: n e a soma, e a profundidade o maximo, sobre os issues
1548
- * do ramo, descendo pelo ramo escolhido de cada uniao dentro dele;
1549
- * - era um WeakMap do modulo, e agora e um Map por chamada do
1550
- * validateDocsConfig() (`resumos`), que some com ela. No Node 22 um WeakMap
1551
- * com milhoes de chaves fica lento demais: 3 milhoes de chaves levam 10,8 s
1552
- * num WeakMap e 0,8 s num Map (no Node 24, 0,9 s), e um writedocs.json de 2 MB
1553
- * com um milhao de erros passava de 45 s so nisso;
1554
- * - so entra no cache o ramo que tem uniao dentro, que e o que pode ser
1555
- * revisitado. Um ramo sem uniao e recontado (uma passada pelos issues dele),
1556
- * e o cache fica do tamanho das unioes aninhadas, nao do numero de erros. */
1557
- function resumoDoRamo(ramo: unknown, resumos: Map<object, Resumo>): Resumo {
1558
- const memoizavel = typeof ramo === 'object' && ramo !== null;
1559
- if (memoizavel) {
1560
- const memoizado = resumos.get(ramo);
1561
- if (memoizado) return memoizado;
1562
- }
1563
- let n = 0;
1564
- let maior = -Infinity;
1565
- let temUniao = false;
1566
- for (const issue of issuesDoRamo(ramo)) {
1567
- const passos = issue.path?.length ?? 0;
1568
- // WD-315 (07c): uma lista resumida conta com o que os itens dela dariam.
1569
- const lista = issue.wdLista;
1570
- if (lista) {
1571
- temUniao = true;
1572
- n += lista.n;
1573
- if (lista.n > 0 && passos + lista.maior > maior) maior = passos + lista.maior;
1574
- continue;
1575
- }
1576
- const ramos = ramosDaUniao(issue);
1577
- if (ramos) {
1578
- temUniao = true;
1579
- const escolhido = resumoDoRamo(melhorRamo(ramos, resumos), resumos);
1580
- n += escolhido.n;
1581
- if (escolhido.n > 0 && passos + escolhido.maior > maior) maior = passos + escolhido.maior;
1582
- } else {
1583
- n += 1;
1584
- const p = passos + (issue.code === 'unrecognized_keys' ? 1 : 0);
1585
- if (p > maior) maior = p;
1586
- }
1587
- }
1588
- const resumo = { n, maior };
1589
- if (memoizavel && temUniao) resumos.set(ramo, resumo);
1590
- return resumo;
1591
- }
1592
-
1593
- /** Escolhe qual ramo de uma uniao o cliente PROVAVELMENTE quis.
1594
- *
1595
- * Criterio: caminho mais fundo primeiro; empate resolvido por menos issues. A
1596
- * intuicao e a do Gabriel na spec - o ramo certo e o que nao reclama da chave
1597
- * que o cliente usou -, e a profundidade importa porque um ramo que chegou
1598
- * fundo antes de falhar (`products.0.product`) reconheceu a forma, enquanto um
1599
- * que falha na raiz (`expected array, received object`) so recusou o shape.
1600
- *
1601
- * DUAS CORRECOES sobre a primeira versao (WD-063), as duas medidas contra o
1602
- * `00-kitchen-sink` real - ver o relato de revisao 43:
1603
- *
1604
- * 1. PONTUA O RAMO ACHATADO, nao a lista crua. Um ramo que e ele proprio uma
1605
- * uniao aparece como UM issue (`invalid_union`) no caminho vazio - ou seja,
1606
- * com a MENOR contagem e a MENOR profundidade possiveis, sem que isso diga
1607
- * nada sobre o quanto ele reconheceu. Era o caso mais comum que existe: um
1608
- * item de `pages` e `string | grupo | link`, e o grupo e outra uniao, entao
1609
- * todo erro estrutural dentro de um grupo empatava com o ramo `string` e
1610
- * perdia pela ordem de declaracao. O cliente que escrevia
1611
- * `{ "group": "G", "pages": 42 }` recebia "expected string, received
1612
- * object" - conselho errado, nao so inutil. Achatando primeiro, o mesmo caso
1613
- * vira `pages.0.pages: expected array, received number`. (Desde o WD-315 o
1614
- * plano achatado nao e montado: resumoDoRamo faz a mesma conta.)
1615
- *
1616
- * 2. PROFUNDIDADE EFETIVA: `unrecognized_keys` reporta no caminho do PAI, com a
1617
- * chave ofensora em `keys`, entao a profundidade dele sai subestimada em 1.
1618
- * Sem a correcao, um ramo que identificou a chave errada perde para um que
1619
- * so exigiu um campo ausente. (`validateDocsConfig` ja fazia a mesma conta
1620
- * para achar a LINHA; aqui ela entra tambem na pontuacao.)
1621
- *
1622
- * Medido sobre as 60 folhas da `navigation` do `00-kitchen-sink`, trocando o
1623
- * tipo de cada uma: a versao anterior apontava o campo exato em 42/60 e PARAVA
1624
- * RASO em 18/60 (sempre os mesmos 18: os que ficam sob um `pages`); esta aponta
1625
- * 60/60 para valor escalar errado e nunca para raso. Para um objeto vazio ou
1626
- * parcial no lugar de uma pagina, as duas ficam tecnicamente empatadas (41
1627
- * contra 42): a anterior diz "expected string", esta lista os campos que
1628
- * faltam para ser um grupo. E o custo aceito desta versao, e substitui o antigo
1629
- * (`tabs` e `products` escritos juntos, que agora sai como
1630
- * `Unrecognized key: "products"`).
1631
- *
1632
- * EMPATE TOTAL (mesma profundidade E mesmo numero de issues): vence o ramo
1633
- * declarado primeiro no schema - a varredura so troca de ramo diante de um
1634
- * ESTRITAMENTE melhor (era um `sort` estavel e o [0], que da o mesmo; quem
1635
- * trocar o `>`/`<` por `>=`/`<=` faz o desempate virar o ultimo). Duas razoes
1636
- * para "o primeiro" em vez de "todos os empatados":
1637
- * - um engano do cliente tem que virar UMA mensagem. Emitir os 5 ramos
1638
- * empatados de um `"navigation": {}` produz cinco exigencias que se
1639
- * contradizem ("tabs e obrigatorio", "versions e obrigatorio", ...);
1640
- * - determinismo: a mesma config sempre da a mesma mensagem. Um palpite
1641
- * instavel seria pior que um palpite ruim.
1642
- * E nada se perde no palpite errado: `message` continua sendo o texto do Zod. */
1643
- function melhorRamo(ramos: unknown[], resumos: Map<object, Resumo>): unknown {
1644
- let melhor = ramos[0];
1645
- const primeiro = resumoDoRamo(melhor, resumos);
1646
- let profundidade = Math.max(0, primeiro.maior);
1647
- let n = primeiro.n;
1648
- for (let i = 1; i < ramos.length; i++) {
1649
- const resumo = resumoDoRamo(ramos[i], resumos);
1650
- const p = Math.max(0, resumo.maior);
1651
- if (p > profundidade || (p === profundidade && resumo.n < n)) {
1652
- melhor = ramos[i];
1653
- profundidade = p;
1654
- n = resumo.n;
1655
- }
1656
- }
1657
- return melhor;
1658
- }
1659
-
1660
- /** Desembrulha `invalid_union` recursivamente - o ramo escolhido normalmente e
1661
- * outra uniao (cada produto da navigation e, por sua vez, uma uniao de formas),
1662
- * entao para so quando chega num erro concreto. Sem recursao, o
1663
- * `navigation.products.0` para em "Invalid input" de novo, um nivel abaixo.
1664
- *
1665
- * WD-315: um gerador, que entrega cada erro concreto (o issue e o caminho
1666
- * inteiro dele) na ordem de sempre, em vez de montar a lista: quem chama guarda
1667
- * os primeiros VALIDATION_ISSUE_LIMIT e so conta o resto. Montada, a lista de
1668
- * um writedocs.json com um milhao de erros (2 MB) era mais memoria do que o
1669
- * proprio Zod gasta. (E sem `push(...lista)`: o spread virava argumentos de
1670
- * chamada e estourava a pilha com ~150 mil issues numa uniao.) `resumos`: o
1671
- * cache da pontuacao (resumoDoRamo), um por chamada do validateDocsConfig().
1672
- *
1673
- * WD-315 (07c): uma lista resumida (`wdLista`) e revalidada aqui, item a item,
1674
- * so quando o fluxo chega nela - e so ate quem consome parar de pedir. */
1675
- function* desembrulharUnioes(
1676
- issues: IssueCru[],
1677
- resumos: Map<object, Resumo>,
1678
- prefixo: (string | number)[] = []
1679
- ): Generator<[IssueCru, (string | number)[]]> {
1680
- for (const issue of issues) {
1681
- const caminho = [...prefixo, ...(issue.path ?? [])];
1682
- if (issue.wdLista) {
1683
- yield* itensDaLista(issue.wdLista, resumos, caminho);
1684
- continue;
1685
- }
1686
- const ramos = ramosDaUniao(issue);
1687
- if (ramos) yield* desembrulharUnioes(issuesDoRamo(melhorRamo(ramos, resumos)), resumos, caminho);
1688
- else yield [issue, caminho];
1689
- }
1690
- }
1691
-
1692
- const LISTAS_DE_CONTAINER = ['tabs', 'versions', 'languages', 'dropdowns', 'products'] as const;
1693
- const ITENS_DE_CONTAINER: Record<string, { lista: string; nome: string }> = {
1694
- tab: { lista: 'tabs', nome: 'A tab' },
1695
- version: { lista: 'versions', nome: 'A version' },
1696
- language: { lista: 'languages', nome: 'A language' },
1697
- dropdown: { lista: 'dropdowns', nome: 'A dropdown' },
1698
- product: { lista: 'products', nome: 'A product' },
1699
- };
1700
-
1701
- /** Um container (`{ "tabs": [...] }`, ou um item como `{ "tab": "API", ... }`)
1702
- * dentro de uma lista de paginas - o `pages` de um grupo, de uma tab etc., ou
1703
- * a `navigation` em forma de lista. O Zod tenta os tres formatos de item
1704
- * (pagina, grupo, link) e reclama de cada um: "group is required", "pages is
1705
- * required", "tabs is not an option" - tres erros, nenhum dizendo o que houve.
1706
- * Aqui eles viram UM, no item, dizendo onde o container pode ficar.
1707
- *
1708
- * Um gerador, como o desembrulharUnioes que o alimenta (WD-315): entrega cada
1709
- * issue final na ordem, e so guarda as chaves dos containers ja vistos. */
1710
- function* containersEmPaginas(issues: Iterable<[IssueCru, (string | number)[]]>, raiz: unknown): Generator<IssuePlano> {
1711
- const vistos = new Set<string>();
1712
- for (const [issue, caminho] of issues) {
1713
- const achado = containerEmPaginas(caminho, raiz);
1714
- if (!achado) {
1715
- yield { ...issue, caminho };
1716
- continue;
1717
- }
1718
- const chave = achado.caminho.join('.');
1719
- if (vistos.has(chave)) continue;
1720
- vistos.add(chave);
1721
- yield { ...issue, code: 'custom', caminho: achado.caminho, message: achado.mensagem, keys: undefined };
1722
- }
1723
- }
1724
-
1725
- function containerEmPaginas(caminho: (string | number)[], raiz: unknown): { caminho: (string | number)[]; mensagem: string } | null {
1726
- for (let k = 1; k < caminho.length; k++) {
1727
- if (typeof caminho[k] !== 'number') continue;
1728
- const naRaiz = k === 1 && caminho[0] === 'navigation';
1729
- if (!naRaiz && caminho[k - 1] !== 'pages') continue;
1730
- const item = valorEm(raiz, caminho.slice(0, k + 1));
1731
- if (!item || typeof item !== 'object' || Array.isArray(item) || 'group' in item) continue;
1732
- const lugar = naRaiz ? 'the navigation list' : 'a "pages" list';
1733
- const rotulo = (texto: string) => (naRaiz ? 'The navigation list' : 'A "pages" list') + ` holds pages, groups and links only. ${texto}`;
1734
- const lista = LISTAS_DE_CONTAINER.find((l) => l in item);
1735
- if (lista) {
1736
- return {
1737
- caminho: caminho.slice(0, k + 1),
1738
- mensagem: `"${lista}" can't go inside ${lugar}. ` + rotulo(
1739
- naRaiz
1740
- ? `To use ${lista}, make "navigation" an object: "navigation": { "${lista}": [ ... ] }, with the groups inside each of them.`
1741
- : `Put "${lista}" on "navigation" itself, or on a tab, version, language, dropdown or product in place of its "pages".`
1742
- ),
1743
- };
1744
- }
1745
- const tipo = Object.keys(ITENS_DE_CONTAINER).find((t) => t in item);
1746
- if (tipo) {
1747
- const { lista: dela, nome } = ITENS_DE_CONTAINER[tipo];
1748
- const nomeDoItem = (item as Record<string, unknown>)[tipo];
1749
- return {
1750
- caminho: caminho.slice(0, k + 1),
1751
- mensagem: `${nome}${typeof nomeDoItem === 'string' ? ` ("${nomeDoItem}")` : ''} can't go inside ${lugar}. ` + rotulo(
1752
- naRaiz ? `${nome} goes in a "${dela}" list: "navigation": { "${dela}": [ ... ] }.` : `${nome} goes in a "${dela}" list.`
1753
- ),
1754
- };
1755
- }
1756
- }
1757
- return null;
1758
- }
1759
-
1760
- // ---------------------------------------------------------------------
1761
- // WD-315 (07c) - PARAR CEDO
1762
- //
1763
- // O Zod nao tem "pare no N-esimo erro": o safeParse produz todos, e o custo e
1764
- // por erro (~2 KB cada; 100 mil itens errados em 0,2 MB pediam ~270 MB). Por
1765
- // isso, durante o validateDocsConfig() sem `all`, as listas (z.array) e os
1766
- // registros (z.record) do schema sao validados por estas funcoes em vez das do
1767
- // Zod, item a item, e param de trabalhar depois de VALIDATION_ISSUE_LIMIT + 1
1768
- // itens errados. Fora dessa chamada (o `all`, ou o docsConfigSchema.safeParse()
1769
- // de qualquer outro lugar) o Zod valida como sempre - nada no schema muda, e o
1770
- // writedocs.schema.json, que sai dele, tambem nao.
1771
- //
1772
- // O PROBLEMA de parar: o desembrulho das unioes (WD-063) escolhe o ramo pela
1773
- // profundidade e, no empate, pelo NUMERO de erros do ramo inteiro. Parar no
1774
- // meio de uma lista pode mudar a escolha - e o erro mostrado. Um contador por
1775
- // chamada, parando toda lista, mudava a saida mesmo abaixo de 100 erros: numa
1776
- // tab com `pages` E `versions` (60 itens errados em cada), os erros contados no
1777
- // ramo descartado gastavam o limite e o resto do arquivo deixava de ser
1778
- // validado. Por isso tres modos, decididos pelo objeto em volta da lista:
1779
- //
1780
- // - PARAR (o normal): a lista para quando o limite acaba. So e seguro porque,
1781
- // num objeto com no maximo UMA das CHAVES_DE_RAMO, o ramo que desce numa
1782
- // lista com um item errado vence sempre pela profundidade (>= 2, contra no
1783
- // maximo 1 dos outros ramos, que so reclamam da chave que falta ou que
1784
- // sobra) - entao contar menos erros nele nao muda escolha nenhuma, e todo
1785
- // item errado contado vira pelo menos um erro na saida, ANTES do ponto onde
1786
- // a validacao parou. Conferido uniao por uniao do schema: navigation, os
1787
- // itens de tabs/versions/languages/dropdowns/products, os itens de `pages`
1788
- // (pagina, grupo, link) e o contextMenu. O `global` da navigation e
1789
- // compartilhado por todas as opcoes, e o Zod (o memoizer dele) valida o
1790
- // mesmo objeto uma vez so por chamada, entao ele sai igual em todas.
1791
- // - CONTAR (um objeto "disputado", com duas ou mais CHAVES_DE_RAMO - uma tab
1792
- // com `pages` e `versions`, um grupo com `pages` e `openapi`, a navigation
1793
- // com `global` e `tabs`): ai a escolha depende da contagem inteira, entao a
1794
- // lista e validada ate o fim - mas sem guardar os erros. Cada item errado
1795
- // vira so o resumo que o resumoDoRamo precisaria dele, e a lista devolve um
1796
- // unico "issue" de resumo (`wdLista`). Quando o fluxo de saida chega nele,
1797
- // itensDaLista revalida os itens, um a um, so ate quem consome parar.
1798
- // Memoria pequena; o tempo continua proporcional a lista.
1799
- // - PULAR (um container dentro de uma lista de paginas, que o
1800
- // containersEmPaginas resume num erro so): nada dentro dele aparece na
1801
- // saida, entao as listas de dentro nao sao validadas.
1802
- //
1803
- // O modo de uma lista e o do objeto disputado ou recolhido mais externo em
1804
- // volta dela (`regioes`). Dentro de uma regiao, um item errado nao conta pro
1805
- // limite - so os das listas em PARAR contam, e so os "folha" (um item que erra
1806
- // porque uma lista de dentro errou ja foi contado la).
1807
- //
1808
- // Prova (rodada gerador/07c): o corpus da plataforma e os casos das rodadas 06
1809
- // e 07 saem iguais ate 100 erros, e com os mesmos 100 primeiros acima disso; e
1810
- // scripts/validation-stop.test.js compara, em centenas de configs montadas de
1811
- // proposito (as disputadas inclusive), o resultado com o de `{ all: true }`.
1812
- // ---------------------------------------------------------------------
1813
-
1814
- /** O resumo de uma lista validada no modo CONTAR: o que os itens errados dela
1815
- * dariam ao resumoDoRamo (n e a maior profundidade, ja com o indice do item),
1816
- * e o que itensDaLista precisa pra revalida-los. */
1817
- type ResumoDeLista = { n: number; maior: number; entrada: unknown[]; elemento: { safeParse: (v: unknown) => { success: boolean; error?: { issues: unknown[] } } } };
1818
-
1819
- type Regiao = 'contar' | 'pular';
1820
-
1821
- /** O estado de UMA chamada do validateDocsConfig() sem `all`; null fora dela, e
1822
- * entao as listas validam pelo Zod, como sempre. `contados`: itens errados nas
1823
- * listas em PARAR; `esgotado`: passou de VALIDATION_ISSUE_LIMIT. */
1824
- let corte: { contados: number; esgotado: boolean; regioes: Regiao[] } | null = null;
1825
-
1826
- /** As chaves que escolhem o ramo de uma uniao com listas: o filho de um
1827
- * container (withChildren), o `openapi` de um grupo, o `global` da navigation. */
1828
- const CHAVES_DE_RAMO = ['pages', 'tabs', 'versions', 'languages', 'dropdowns', 'products', 'href', 'openapi', 'global'];
1829
-
1830
- function disputado(objeto: object): boolean {
1831
- let achadas = 0;
1832
- for (const chave of CHAVES_DE_RAMO) if (chave in objeto && ++achadas >= 2) return true;
1833
- return false;
1834
- }
1835
-
1836
- /** O mesmo teste do containerEmPaginas: um objeto numa lista de paginas que
1837
- * nao e grupo e tem cara de container vira um erro so. */
1838
- function recolhido(objeto: object): boolean {
1839
- return !('group' in objeto) && (LISTAS_DE_CONTAINER.some((l) => l in objeto) || Object.keys(ITENS_DE_CONTAINER).some((t) => t in objeto));
1840
- }
1841
-
1842
- type Payload = { value: unknown; issues: IssueCru[]; aborted?: boolean };
1843
- type Interno = { _zod: { def: any; parse: Function; run: Function; innerType?: unknown } };
1844
- type ComCorte = (original: Function, schema: Interno, payload: Payload, ctx: unknown) => Payload;
1845
-
1846
- function ehObjeto(v: unknown): v is Record<string, unknown> {
1847
- return v !== null && typeof v === 'object' && !Array.isArray(v);
1848
- }
1849
-
1850
- /** Troca o `parse` (e o `run`, quando o Zod o copiou do `parse`) de um schema
1851
- * por um que, fora de uma chamada com corte, so repassa. Por acessores, e nao
1852
- * por atribuicao: o memoizer do Zod troca o `parse` de volta pelo original na
1853
- * primeira validacao de um schema nao recursivo, e o setter guarda essa troca
1854
- * como o novo original em vez de perder o embrulho. */
1855
- function embrulhar(schema: Interno, comCorte: ComCorte) {
1856
- const zod = schema._zod;
1857
- let original = zod.parse;
1858
- const runEhParse = zod.run === original;
1859
- const embrulhado = (payload: Payload, ctx: unknown) => (corte ? comCorte(original, schema, payload, ctx) : original(payload, ctx));
1860
- Object.defineProperty(zod, 'parse', { configurable: true, enumerable: true, get: () => embrulhado, set: (v) => { original = v; } });
1861
- if (runEhParse) Object.defineProperty(zod, 'run', { configurable: true, enumerable: true, get: () => embrulhado, set: () => {} });
1862
- }
1863
-
1864
- /** Percorre o schema uma vez, ao carregar o modulo, e embrulha cada lista,
1865
- * cada registro e cada objeto que e opcao de uma uniao (direto ou por um
1866
- * z.lazy) - so nesses a escolha de ramo existe, e so eles abrem uma regiao. A
1867
- * raiz, por exemplo, nao: chaves desconhecidas nela nao sao validadas.
1868
- * `membros`: os objetos que validam itens de uma lista de paginas (grupo, grupo
1869
- * de openapi, link) - os unicos que podem ser um container recolhido. */
1870
- function instalarCorte(raiz: unknown, membros: Set<unknown>) {
1871
- const todos: Interno[] = [];
1872
- const opcoes = new Set<unknown>();
1873
- const vistos = new Set<unknown>();
1874
- const pendentes = [raiz];
1875
- const resolver = (schema: Interno): unknown => (schema?._zod?.def?.type === 'lazy' ? schema._zod.innerType : schema);
1876
- while (pendentes.length) {
1877
- const schema = pendentes.pop() as Interno;
1878
- if (!schema || typeof schema !== 'object' || !schema._zod || vistos.has(schema)) continue;
1879
- vistos.add(schema);
1880
- todos.push(schema);
1881
- const def = schema._zod.def;
1882
- if (def.type === 'array') pendentes.push(def.element);
1883
- else if (def.type === 'record') pendentes.push(def.keyType, def.valueType);
1884
- else if (def.type === 'object') {
1885
- pendentes.push(...Object.values(def.shape as object));
1886
- if (def.catchall) pendentes.push(def.catchall);
1887
- } else if (def.type === 'union') {
1888
- for (const opcao of def.options) opcoes.add(resolver(opcao));
1889
- pendentes.push(...def.options);
1890
- } else if (def.type === 'lazy') pendentes.push(schema._zod.innerType);
1891
- else if (def.type === 'pipe') pendentes.push(def.in, def.out);
1892
- else if (def.innerType) pendentes.push(def.innerType);
1893
- }
1894
- for (const schema of todos) {
1895
- const tipo = schema._zod.def.type;
1896
- if (tipo === 'array') embrulhar(schema, listaComCorte);
1897
- else if (tipo === 'record') embrulhar(schema, registroComCorte);
1898
- else if (tipo === 'object' && opcoes.has(schema)) embrulhar(schema, objetoComCorte(membros.has(schema)));
1899
- }
1900
- }
1901
-
1902
- /** Uma opcao de uniao abre a regiao do seu modo (a mais externa vale pra tudo
1903
- * dentro dela). */
1904
- function objetoComCorte(membro: boolean): ComCorte {
1905
- return (original, _schema, payload, ctx) => {
1906
- const estado = corte!;
1907
- const valor = payload.value;
1908
- if (estado.regioes.length > 0 || !ehObjeto(valor)) return original(payload, ctx);
1909
- const regiao: Regiao | null = disputado(valor) ? 'contar' : membro && recolhido(valor) ? 'pular' : null;
1910
- if (!regiao) return original(payload, ctx);
1911
- estado.regioes.push(regiao);
1912
- try {
1913
- return original(payload, ctx);
1914
- } finally {
1915
- estado.regioes.pop();
1916
- }
1917
- };
1918
- }
1919
-
1920
- /** Roda o schema de um item como o Zod roda (sincrono: nada neste schema e
1921
- * assincrono). */
1922
- function rodar(schema: Interno, valor: unknown, ctx: unknown): Payload {
1923
- const resultado = schema._zod.run({ value: valor, issues: [] }, ctx);
1924
- if (resultado instanceof Promise) throw new Error('[writedocs] async validation is not supported');
1925
- return resultado;
1926
- }
1927
-
1928
- function abortou(resultado: Payload): boolean {
1929
- return resultado.aborted === true || resultado.issues.some((issue) => (issue as { continue?: boolean }).continue !== true);
1930
- }
1931
-
1932
- /** O z.array: o laco do Zod (o valor de cada item, os erros com o indice na
1933
- * frente), nos tres modos. Sem corte (lista sem erro, ou que nao chegou ao
1934
- * limite), o resultado e o do Zod, item por item. */
1935
- const listaComCorte: ComCorte = (original, schema, payload, ctx) => {
1936
- const entrada = payload.value;
1937
- if (!Array.isArray(entrada)) return original(payload, ctx);
1938
- const estado = corte!;
1939
- const elemento = schema._zod.def.element as Interno;
1940
- const valor = new Array(entrada.length);
1941
- payload.value = valor;
1942
- const regiao = estado.regioes[estado.regioes.length - 1];
1943
- if (regiao === 'pular') {
1944
- for (let i = 0; i < entrada.length; i++) valor[i] = entrada[i];
1945
- return payload;
1946
- }
1947
- if (regiao === 'contar') {
1948
- let n = 0;
1949
- let maior = -Infinity;
1950
- let algumErrado = false;
1951
- let algumAborta = false;
1952
- for (let i = 0; i < entrada.length; i++) {
1953
- const resultado = rodar(elemento, entrada[i], ctx);
1954
- valor[i] = resultado.value;
1955
- if (resultado.issues.length === 0) continue;
1956
- algumErrado = true;
1957
- if (abortou(resultado)) algumAborta = true;
1958
- // Um Map so deste item: o resumo dele nao serve pra mais nada.
1959
- const resumo = resumoDoRamo(resultado.issues, new Map());
1960
- n += resumo.n;
1961
- if (resumo.n > 0 && 1 + resumo.maior > maior) maior = 1 + resumo.maior;
1962
- }
1963
- // `continue` diz se o resultado "aborta", e as unioes do Zod decidem por
1964
- // isso: o resumo aborta exatamente quando algum dos erros resumidos abortaria.
1965
- if (algumErrado) {
1966
- payload.issues.push({
1967
- code: 'custom',
1968
- message: 'writedocs: list summary',
1969
- path: [],
1970
- continue: !algumAborta,
1971
- wdLista: { n, maior, entrada, elemento: elemento as unknown as ResumoDeLista['elemento'] },
1972
- } as IssueCru);
1973
- }
1974
- return payload;
1975
- }
1976
- for (let i = 0; i < entrada.length; i++) {
1977
- if (estado.esgotado) {
1978
- valor[i] = entrada[i];
1979
- continue;
1980
- }
1981
- const antes = estado.contados;
1982
- const resultado = rodar(elemento, entrada[i], ctx);
1983
- valor[i] = resultado.value;
1984
- if (resultado.issues.length === 0) continue;
1985
- for (const issue of resultado.issues) {
1986
- (issue.path ??= []).unshift(i);
1987
- payload.issues.push(issue);
1988
- }
1989
- // So o item "folha" conta: se uma lista de dentro dele ja contou, o erro
1990
- // dele e o dela.
1991
- if (estado.contados === antes && ++estado.contados > VALIDATION_ISSUE_LIMIT) estado.esgotado = true;
1992
- }
1993
- return payload;
1994
- };
1995
-
1996
- /** O z.record de chave texto (socials, variables, metatags, langAlias): o laco
1997
- * do Zod, no modo PARAR. Qualquer outro (chave com regra, ou dentro de uma
1998
- * regiao) fica com o do Zod - nenhum registro do schema mora numa regiao. */
1999
- const registroComCorte: ComCorte = (original, schema, payload, ctx) => {
2000
- const entrada = payload.value;
2001
- const estado = corte!;
2002
- const def = schema._zod.def;
2003
- const chaveTexto = def.keyType?._zod?.def?.type === 'string' && !(def.keyType._zod.def.checks?.length > 0);
2004
- if (estado.regioes.length > 0 || !ehObjeto(entrada) || !chaveTexto || Object.getPrototypeOf(entrada) !== Object.prototype) {
2005
- return original(payload, ctx);
2006
- }
2007
- const valor: Record<string, unknown> = {};
2008
- payload.value = valor;
2009
- for (const chave of Object.keys(entrada)) {
2010
- if (chave === '__proto__') continue;
2011
- if (estado.esgotado) {
2012
- valor[chave] = entrada[chave];
2013
- continue;
2014
- }
2015
- const antes = estado.contados;
2016
- const resultado = rodar(def.valueType, entrada[chave], ctx);
2017
- valor[chave] = resultado.value;
2018
- if (resultado.issues.length === 0) continue;
2019
- for (const issue of resultado.issues) {
2020
- (issue.path ??= []).unshift(chave);
2021
- payload.issues.push(issue);
2022
- }
2023
- if (estado.contados === antes && ++estado.contados > VALIDATION_ISSUE_LIMIT) estado.esgotado = true;
2024
- }
2025
- return payload;
2026
- };
2027
-
2028
- /** Os erros de uma lista resumida (modo CONTAR), na ordem, revalidando um item
2029
- * por vez - dentro de uma regiao CONTAR, como na primeira passada. */
2030
- function* itensDaLista(lista: ResumoDeLista, resumos: Map<object, Resumo>, caminho: (string | number)[]): Generator<[IssueCru, (string | number)[]]> {
2031
- for (let i = 0; i < lista.entrada.length; i++) {
2032
- corte?.regioes.push('contar');
2033
- let resultado;
2034
- try {
2035
- resultado = lista.elemento.safeParse(lista.entrada[i]);
2036
- } finally {
2037
- corte?.regioes.pop();
2038
- }
2039
- if (resultado.success) continue;
2040
- yield* desembrulharUnioes(resultado.error!.issues as IssueCru[], resumos, [...caminho, i]);
2041
- }
2042
- }
2043
-
2044
- instalarCorte(
2045
- docsConfigSchema,
2046
- new Set([(navGroupPagesSchema as unknown as Interno)._zod.innerType, navGroupOpenApiSchema, navLinkSchema])
2047
- );
2048
-
2049
- /** Linha e coluna de varios caminhos numa passada so pelo texto (o `visit` do
2050
- * jsonc-parser), sem montar a arvore: com um milhao de valores, o parseTree
2051
- * sozinho passava de 64 MB. A mesma resposta do criarLocalizador (parseTree +
2052
- * findNodeAtLocation), inclusive com chave repetida num objeto, onde vale a
2053
- * primeira; o que nao leva a nenhum caminho pedido e pulado sem callbacks. */
2054
- function localizarCaminhos(rawText: string, caminhos: (string | number)[][]): (caminho: (string | number)[]) => { line: number; column: number } | null {
2055
- rawText = semBom(rawText);
2056
- type No = { filhos: Map<string | number, No>; alvo: boolean; offset?: number };
2057
- const raiz: No = { filhos: new Map(), alvo: false };
2058
- for (const caminho of caminhos) {
2059
- if (caminho.length === 0) continue;
2060
- let no = raiz;
2061
- for (const passo of caminho) {
2062
- let filho = no.filhos.get(passo);
2063
- if (!filho) no.filhos.set(passo, (filho = { filhos: new Map(), alvo: false }));
2064
- no = filho;
2065
- }
2066
- no.alvo = true;
2067
- }
2068
- type Quadro = { no: No | null; lista: boolean; indice: number; chave: string; vistas: Set<string> };
2069
- const pilha: Quadro[] = [];
2070
- const comecoDeValor = (offset: number): No | null => {
2071
- const topo = pilha[pilha.length - 1];
2072
- if (!topo) return raiz;
2073
- if (!topo.no) return null;
2074
- let filho: No | null;
2075
- if (topo.lista) filho = topo.no.filhos.get(topo.indice++) ?? null;
2076
- else {
2077
- filho = topo.no.filhos.get(topo.chave) ?? null;
2078
- // Chave repetida: o findNodeAtLocation desce pela primeira.
2079
- if (filho) {
2080
- if (topo.vistas.has(topo.chave)) filho = null;
2081
- else topo.vistas.add(topo.chave);
2082
- }
2083
- }
2084
- if (filho?.alvo && filho.offset === undefined) filho.offset = offset;
2085
- return filho;
2086
- };
2087
- const abrir = (lista: boolean) => (offset: number) => {
2088
- const no = comecoDeValor(offset);
2089
- pilha.push({ no, lista, indice: 0, chave: '', vistas: new Set() });
2090
- return no !== null && no.filhos.size > 0 ? undefined : false;
2091
- };
2092
- if (raiz.filhos.size > 0) {
2093
- visit(rawText, {
2094
- onObjectBegin: abrir(false),
2095
- onArrayBegin: abrir(true),
2096
- onObjectEnd: () => void pilha.pop(),
2097
- onArrayEnd: () => void pilha.pop(),
2098
- onObjectProperty: (chave: string) => {
2099
- pilha[pilha.length - 1].chave = chave;
2100
- },
2101
- onLiteralValue: (_valor: unknown, offset: number) => void comecoDeValor(offset),
2102
- });
2103
- }
2104
- let inicios: number[] | undefined;
2105
- return (caminho) => {
2106
- if (caminho.length === 0) return null;
2107
- let no: No | undefined = raiz;
2108
- for (const passo of caminho) {
2109
- no = no.filhos.get(passo);
2110
- if (!no) return null;
2111
- }
2112
- if (no.offset === undefined) return null;
2113
- inicios ??= iniciosDeLinha(rawText);
2114
- return linhaEColuna(inicios, no.offset);
2115
- };
2116
- }
2117
-
2118
- /** Exported for `writedocs validate`'s content pass (lib/content-check.js),
2119
- * which reports writedocs.json problems of its own - navigation entries
2120
- * with no page, unknown icons - with the same line numbers as the schema
2121
- * errors. Same function as criarLocalizador below. */
2122
- export function createJsonLocator(rawText: string): (path: (string | number)[]) => { line: number; column: number } | null {
2123
- return criarLocalizador(rawText);
2124
- }
2125
-
2126
- /** Parseia o texto UMA vez e devolve "caminho -> linha/coluna". Devolve null
2127
- * quando o no nao existe no texto (campo obrigatorio ausente e o caso comum):
2128
- * `line` ausente e melhor que `line` inventada.
2129
- *
2130
- * WD-315: o custo de cada busca tem que independer do tamanho do texto. A
2131
- * versao anterior fazia `rawText.slice(0, offset).split('\n')` POR BUSCA - com
2132
- * 66 mil erros num texto de 11 MB, 169 s e ~1,2 GB. Agora a arvore e os inicios
2133
- * de linha sao calculados uma vez, na primeira busca (um config sem nada pra
2134
- * localizar nao paga nenhum dos dois), e cada offset vira linha por busca
2135
- * binaria. A linha e a coluna sao exatamente as de antes: a linha conta so
2136
- * '\n' (um `\r\n` e um '\n' com o '\r' no fim da linha anterior), e a coluna e
2137
- * em unidades UTF-16, como o offset do jsonc-parser - um emoji conta 2. */
2138
- function criarLocalizador(rawText: string): (caminho: (string | number)[]) => { line: number; column: number } | null {
2139
- rawText = semBom(rawText);
2140
- let arvore: ReturnType<typeof parseTree> | undefined | null = null;
2141
- let inicios: number[] | undefined;
2142
- return (caminho) => {
2143
- if (caminho.length === 0) return null;
2144
- if (arvore === null) {
2145
- try {
2146
- arvore = parseTree(rawText);
2147
- } catch {
2148
- arvore = undefined;
2149
- }
2150
- }
2151
- if (!arvore) return null;
2152
- const no = findNodeAtLocation(arvore, caminho);
2153
- if (!no) return null;
2154
- inicios ??= iniciosDeLinha(rawText);
2155
- return linhaEColuna(inicios, no.offset);
2156
- };
2157
- }
2158
-
2159
- /** Os offsets em que cada linha comeca: 0, e o seguinte a cada '\n'. */
2160
- function iniciosDeLinha(texto: string): number[] {
2161
- const inicios = [0];
2162
- for (let i = texto.indexOf('\n'); i !== -1; i = texto.indexOf('\n', i + 1)) inicios.push(i + 1);
2163
- return inicios;
2164
- }
2165
-
2166
- /** A linha do offset e o ultimo inicio <= offset (busca binaria); a coluna
2167
- * conta a partir de 1 nesse inicio. */
2168
- function linhaEColuna(inicios: number[], offset: number): { line: number; column: number } {
2169
- let baixo = 0;
2170
- let alto = inicios.length - 1;
2171
- while (baixo < alto) {
2172
- const meio = (baixo + alto + 1) >> 1;
2173
- if (inicios[meio] <= offset) baixo = meio;
2174
- else alto = meio - 1;
2175
- }
2176
- return { line: baixo + 1, column: offset - inicios[baixo] + 1 };
2177
- }
2178
-
2179
- /** `styles.primaryColor` -> `config.styles`. Primeiro segmento so, com fallback
2180
- * pra `config`: o conjunto tem que ficar pequeno e estavel, porque vira
2181
- * superficie publica no instante em que alguem mapear chave -> URL. */
2182
- function docKeyDoCaminho(caminho: (string | number)[]): string {
2183
- const primeiro = caminho[0];
2184
- return typeof primeiro === 'string' && primeiro ? `config.${primeiro}` : 'config';
2185
- }
2186
-
2187
- const ARTIGO_POR_TIPO: Record<string, string> = {
2188
- string: 'a piece of text',
2189
- number: 'a number',
2190
- boolean: 'true or false',
2191
- array: 'a list',
2192
- object: 'an object',
2193
- null: 'null',
2194
- };
2195
-
2196
- const COMO_ESCREVER: Record<string, string> = {
2197
- string: 'Write the value in double quotes, like "Core Platform".',
2198
- number: 'Write the value as a bare number, like 3 - no quotes.',
2199
- boolean: 'Write true or false - no quotes.',
2200
- array: 'Write the value as a list in square brackets: [ ... ].',
2201
- object: 'Write the value as an object in curly braces: { ... }.',
2202
- };
2203
-
2204
- /** O tipo que o cliente REALMENTE escreveu, lido do JSON ja parseado em vez de
2205
- * extraido da mensagem do Zod por regex - o Zod v4 nao carrega `received` como
2206
- * propriedade, so dentro do texto, e depender do texto quebra na primeira vez
2207
- * que ele mudar de forma. */
2208
- function tipoReal(valor: unknown): string {
2209
- if (valor === undefined) return 'missing';
2210
- if (valor === null) return 'null';
2211
- if (Array.isArray(valor)) return 'array';
2212
- return typeof valor;
2213
- }
2214
-
2215
- function valorEm(raiz: unknown, caminho: (string | number)[]): unknown {
2216
- let atual: unknown = raiz;
2217
- for (const passo of caminho) {
2218
- if (atual === null || typeof atual !== 'object') return undefined;
2219
- atual = (atual as Record<string | number, unknown>)[passo];
2220
- }
2221
- return atual;
2222
- }
2223
-
2224
- function comoCampo(caminho: (string | number)[]): string {
2225
- return caminho.length > 0 ? `"${caminho.join('.')}"` : 'writedocs.json';
2226
- }
2227
-
2228
- /** A frase de chave desconhecida, num lugar so.
2229
- *
2230
- * Decisao 6: chave desconhecida em sub-objeto strict e ERRO e na raiz e AVISO -
2231
- * a assimetria de SEVERIDADE e intencional e fica. A de VOCABULARIO nao: os
2232
- * dois caminhos chamam esta funcao, entao os dois dizem exatamente a mesma
2233
- * coisa, e so quem chama decide o peso. */
2234
- function fraseChaveDesconhecida(chaves: string[], dentroDe: (string | number)[]) {
2235
- const onde = dentroDe.length > 0 ? ` inside "${dentroDe.join('.')}"` : '';
2236
- const lista = chaves.map((k) => `"${k}"`).join(', ');
2237
- return {
2238
- humanMessage:
2239
- chaves.length === 1
2240
- ? `${lista} is not a writedocs.json option${onde}.`
2241
- : `${lista} are not writedocs.json options${onde}.`,
2242
- suggestion: 'Remove it, or check the spelling - options are case-sensitive.',
2243
- };
2244
- }
2245
-
2246
- /** A frase humana + a sugestao, escolhidas pelo CODIGO do Zod. `raiz` e o JSON
2247
- * ja parseado, usado so pra saber o que o cliente escreveu de fato. */
2248
- function humanizar(issue: IssuePlano, raiz: unknown): { humanMessage?: string; suggestion?: string } {
2249
- const campo = comoCampo(issue.caminho);
2250
- switch (issue.code) {
2251
- case 'invalid_type': {
2252
- const esperado = issue.expected ?? 'a different type';
2253
- const recebido = tipoReal(valorEm(raiz, issue.caminho));
2254
- if (recebido === 'missing') {
2255
- return {
2256
- humanMessage: `${campo} is required, but writedocs.json does not set it.`,
2257
- suggestion: `Add ${campo} with ${ARTIGO_POR_TIPO[esperado] ?? `a ${esperado}`} as its value.`,
2258
- };
2259
- }
2260
- return {
2261
- humanMessage: `${campo} must be ${ARTIGO_POR_TIPO[esperado] ?? `a ${esperado}`}, but writedocs.json has ${ARTIGO_POR_TIPO[recebido] ?? `a ${recebido}`}.`,
2262
- suggestion: COMO_ESCREVER[esperado],
2263
- };
2264
- }
2265
- case 'unrecognized_keys': {
2266
- // O Zod agrega as chaves sobrando numa mensagem so, com o `path` no PAI.
2267
- const chaves = issue.keys ?? [];
2268
- if (chaves.length === 0) return {};
2269
- return fraseChaveDesconhecida(chaves, issue.caminho);
2270
- }
2271
- case 'invalid_value': {
2272
- const opcoes = (issue.values ?? []).map((v) => JSON.stringify(v)).join(', ');
2273
- return {
2274
- humanMessage: `${campo} must be one of: ${opcoes}.`,
2275
- suggestion: 'Replace the value with one of the options above.',
2276
- };
2277
- }
2278
- case 'too_small': {
2279
- const unidade = issue.origin === 'array' ? 'item' : 'character';
2280
- const minimo = issue.minimum ?? 1;
2281
- return {
2282
- humanMessage: `${campo} needs at least ${minimo} ${unidade}${minimo === 1 ? '' : 's'}.`,
2283
- suggestion: issue.origin === 'array' ? 'Add an entry, or remove the field entirely.' : undefined,
2284
- };
2285
- }
2286
- case 'too_big': {
2287
- const unidade = issue.origin === 'array' ? 'item' : 'character';
2288
- const maximo = issue.maximum ?? 0;
2289
- return { humanMessage: `${campo} allows at most ${maximo} ${unidade}${maximo === 1 ? '' : 's'}.` };
2290
- }
2291
- case 'invalid_format':
2292
- // A field with a pattern of its own (`basePath`) says what's wrong in
2293
- // its own words.
2294
- if (issue.format === 'regex' && issue.message) return { humanMessage: issue.message };
2295
- return {
2296
- humanMessage: `${campo} is not a valid ${issue.format ?? 'value'}.`,
2297
- suggestion: 'Check the format against the documentation for this field.',
2298
- };
2299
- case 'invalid_union':
2300
- // So chega aqui se o desembrulho nao achou ramo nenhum (uniao sem
2301
- // `errors`). Raro, mas melhor dizer o que aconteceu do que "Invalid input".
2302
- return {
2303
- humanMessage: `${campo} does not match any of the shapes writedocs.json accepts here.`,
2304
- suggestion: 'Check the documentation for the shapes this field accepts.',
2305
- };
2306
- case 'custom':
2307
- // As mensagens de `.refine()` deste schema ja sao frases escritas pra
2308
- // gente ("Each scripts.head/scripts.body entry needs exactly one of..."),
2309
- // entao reescrever seria piorar. Repassa como frase humana pra que quem
2310
- // exibe so `humanMessage` nao fique sem nada.
2311
- return { humanMessage: issue.message };
2312
- default:
2313
- return {};
2314
- }
2315
- }
2316
-
2317
- /** Avisos de chave desconhecida na RAIZ.
2318
- *
2319
- * A raiz nao e `.strict()` (decidido no E11-desenho-geral: tornar strict
2320
- * quebraria configs existentes), entao o Zod descarta a chave em silencio e
2321
- * nao ha issue nenhum. Quem quiser avisar chama isto. Mora aqui, e nao na
2322
- * plataforma, pelo motivo de sempre: era o unico texto escrito pela plataforma,
2323
- * e enquanto ele viver la os dois lados podem divergir.
2324
- *
2325
- * Severidade e de quem chama - isto so descreve o problema. `validateDocsConfig`
2326
- * deliberadamente NAO chama: um config valido continua saindo com `issues: []`,
2327
- * porque a plataforma repassa `issues` como `errors` e um aviso ali viraria
2328
- * erro.
2329
- *
2330
- * WD-315: no maximo os primeiros VALIDATION_ISSUE_LIMIT avisos, na ordem das
2331
- * chaves no texto. O total sai do unknownRootKeyWarnings() logo abaixo. */
2332
- export function unknownRootKeyIssues(rawText: string): ValidationIssue[] {
2333
- return unknownRootKeyWarnings(rawText).issues;
2334
- }
2335
-
2336
- /** O mesmo que unknownRootKeyIssues(), com o total (`issuesTotal`), como o
2337
- * validateDocsConfig(). Uma funcao a parte, e nao outro retorno daquela, pra
2338
- * que quem ja chama unknownRootKeyIssues() continue recebendo uma lista. O
2339
- * total e sempre exato (contar chaves nao custa); `{ all: true }` devolve
2340
- * todos os avisos. */
2341
- export function unknownRootKeyWarnings(
2342
- rawText: string,
2343
- { all = false }: ValidationOptions = {}
2344
- ): { issues: ValidationIssue[]; issuesTotal: number } {
2345
- rawText = semBom(rawText);
2346
- let raiz: unknown;
2347
- try {
2348
- raiz = JSON.parse(rawText);
2349
- } catch {
2350
- return { issues: [], issuesTotal: 0 };
2351
- }
2352
- if (raiz === null || typeof raiz !== 'object' || Array.isArray(raiz)) return { issues: [], issuesTotal: 0 };
2353
- const conhecidas = new Set([...Object.keys(docsConfigSchema.shape), ...ROOT_ALLOWED_EXTRA_KEYS]);
2354
- const desconhecidas = Object.keys(raiz as Record<string, unknown>).filter((chave) => !conhecidas.has(chave));
2355
- const listadas = all ? desconhecidas : desconhecidas.slice(0, VALIDATION_ISSUE_LIMIT);
2356
- const localizar = localizarCaminhos(rawText, listadas.map((chave) => [chave]));
2357
- const issues = listadas
2358
- .map((chave) => {
2359
- const frase = fraseChaveDesconhecida([chave], []);
2360
- return {
2361
- path: chave,
2362
- // O mesmo formato singular da mensagem `unrecognized_keys` do Zod, pra
2363
- // que aviso e erro sejam indistinguiveis por quem so le `message`.
2364
- message: `Unrecognized key: "${chave}"`,
2365
- code: 'unrecognized_keys',
2366
- ...(localizar([chave]) ?? {}),
2367
- ...frase,
2368
- // `config`, e NAO `config.<chave>`: a chave aqui e o que o cliente
2369
- // digitou errado, e derivar a docKey dela faria cada erro de digitacao
2370
- // inventar uma chave nova. O conjunto de docKeys tem que ser fechado -
2371
- // `config` mais um por campo do schema, nada alem disso -, senao quem
2372
- // mapeia chave -> URL do outro lado nao tem lista pra mapear.
2373
- docKey: 'config',
2374
- };
2375
- });
2376
- return { issues, issuesTotal: desconhecidas.length };
2377
- }
2378
-
2379
- /** Texto sem o BOM do UTF-8 no inicio. Editores do Windows (Bloco de Notas, o
2380
- * `Out-File` do PowerShell 5.1) gravam um, e o JSON.parse o rejeita com uma
2381
- * mensagem que culpa virgulas e colchetes. Copia local, e nao import de
2382
- * lib/config-file.js: este modulo so importa zod e jsonc-parser (ver o topo). */
2383
- function semBom(texto: string): string {
2384
- return texto.charCodeAt(0) === 0xfeff ? texto.slice(1) : texto;
2385
- }
2386
-
2387
- export function validateDocsConfig(rawText: string, { all = false }: ValidationOptions = {}): ValidationResult {
2388
- rawText = semBom(rawText);
2389
- let raw: unknown;
2390
- try {
2391
- raw = JSON.parse(rawText);
2392
- } catch (err) {
2393
- const parseError = err as SyntaxError;
2394
- const posicao = positionFromJsonError(parseError.message, rawText);
2395
- return {
2396
- ok: false,
2397
- data: null,
2398
- kind: 'invalid_json',
2399
- parseError,
2400
- issues: [
2401
- {
2402
- path: '(root)',
2403
- message: parseError.message,
2404
- code: 'invalid_json',
2405
- ...(posicao ?? {}),
2406
- humanMessage: 'writedocs.json is not valid JSON, so none of it could be checked.',
2407
- suggestion: posicao
2408
- ? `Look at line ${posicao.line} - a missing comma, an extra trailing comma, or an unclosed bracket is the usual cause.`
2409
- : 'A missing comma, an extra trailing comma, or an unclosed bracket is the usual cause.',
2410
- docKey: 'config',
2411
- },
2412
- ],
2413
- issuesTotal: 1,
2414
- issuesTruncated: false,
2415
- };
2416
- }
2417
-
2418
- if (all) return validarTudo(rawText, raw);
2419
-
2420
- // A validacao com corte (a secao PARAR CEDO): o `corte` vive ate o fluxo de
2421
- // saida ser consumido, porque as listas resumidas sao revalidadas nele.
2422
- corte = { contados: 0, esgotado: false, regioes: [] };
2423
- try {
2424
- const result = docsConfigSchema.safeParse(raw);
2425
- if (result.success) return { ok: true, data: result.data, issues: [], issuesTotal: 0, issuesTruncated: false };
2426
- // A lista, na ordem - o desembrulho e o containersEmPaginas mudam quantos sao
2427
- // e em que ordem -, ate o VALIDATION_ISSUE_LIMIT-esimo e mais um, que so diz
2428
- // que ha mais. Os primeiros sao localizados e humanizados.
2429
- const primeiros: IssuePlano[] = [];
2430
- let truncado = false;
2431
- const resumos = new Map<object, Resumo>();
2432
- for (const issue of containersEmPaginas(desembrulharUnioes(result.error.issues as IssueCru[], resumos), raw)) {
2433
- if (primeiros.length === VALIDATION_ISSUE_LIMIT) {
2434
- truncado = true;
2435
- break;
2436
- }
2437
- primeiros.push(issue);
2438
- }
2439
- // Se a validacao parou, ela parou depois de VALIDATION_ISSUE_LIMIT + 1 itens
2440
- // errados, e cada um e pelo menos um erro antes do ponto onde ela parou -
2441
- // entao o fluxo tem que ter passado do teto. Se nao passou, a conta da secao
2442
- // PARAR CEDO falhou em algum caso: entao vale a validacao inteira, que e
2443
- // sempre certa, mesmo que cara.
2444
- if (corte.esgotado && !truncado) {
2445
- corte = null;
2446
- recaidas++;
2447
- return limitar(validarTudo(rawText, raw));
2448
- }
2449
- return {
2450
- ok: false,
2451
- data: null,
2452
- kind: 'schema',
2453
- issues: localizarEHumanizar(primeiros, rawText, raw, localizarCaminhos),
2454
- issuesTotal: truncado ? VALIDATION_ISSUE_LIMIT + 1 : primeiros.length,
2455
- issuesTruncated: truncado,
2456
- };
2457
- } finally {
2458
- corte = null;
2459
- }
2460
- }
2461
-
2462
- /** Quantas vezes, desde que o modulo carregou, a validacao com corte caiu na
2463
- * validacao inteira (o `if` acima). Deve ser sempre 0: o resultado sai certo
2464
- * mesmo assim, mas sem a economia - e um erro na secao PARAR CEDO. Exportado
2465
- * pros testes (scripts/validation-stop.test.js), que exigem 0. */
2466
- let recaidas = 0;
2467
- export function stopFallbacks(): number {
2468
- return recaidas;
2469
- }
2470
-
2471
- /** `{ all: true }`: o Zod inteiro, sem corte, e a lista inteira - o que o
2472
- * validateDocsConfig() fazia antes do WD-315. */
2473
- function validarTudo(rawText: string, raw: unknown): ValidationResult {
2474
- const result = docsConfigSchema.safeParse(raw);
2475
- if (result.success) return { ok: true, data: result.data, issues: [], issuesTotal: 0, issuesTruncated: false };
2476
- const todos = [...containersEmPaginas(desembrulharUnioes(result.error.issues as IssueCru[], new Map()), raw)];
2477
- const issues = localizarEHumanizar(todos, rawText, raw, (texto) => criarLocalizador(texto));
2478
- return { ok: false, data: null, kind: 'schema', issues, issuesTotal: issues.length, issuesTruncated: false };
2479
- }
2480
-
2481
- /** O resultado de validarTudo() cortado no teto, como o normal o daria. */
2482
- function limitar(resultado: ValidationResult): ValidationResult {
2483
- if (resultado.issues.length <= VALIDATION_ISSUE_LIMIT) return resultado;
2484
- return { ...resultado, issues: resultado.issues.slice(0, VALIDATION_ISSUE_LIMIT), issuesTotal: VALIDATION_ISSUE_LIMIT + 1, issuesTruncated: true };
2485
- }
2486
-
2487
- /** Do issue desembrulhado para o ValidationIssue: a linha, a frase humana, a
2488
- * docKey. `criar` recebe o texto e os caminhos que serao procurados. */
2489
- function localizarEHumanizar(
2490
- lista: IssuePlano[],
2491
- rawText: string,
2492
- raw: unknown,
2493
- criar: (texto: string, caminhos: (string | number)[][]) => (caminho: (string | number)[]) => { line: number; column: number } | null
2494
- ): ValidationIssue[] {
2495
- // Para chave desconhecida o `path` do Zod aponta pro PAI (`footer`), e a
2496
- // chave ofensora vem em `keys`. Para a LINHA vale a pena descer ate ela
2497
- // (`footer.banana`), que e onde o cliente precisa olhar; o `path` fica
2498
- // como o Zod deu, pra nao mudar o que a plataforma ja grava.
2499
- const alvos = lista.map((i) => (i.code === 'unrecognized_keys' && i.keys?.length ? [...i.caminho, i.keys[0]] : i.caminho));
2500
- const localizar = criar(rawText, [...alvos, ...lista.map((i) => i.caminho)]);
2501
- return lista.map((i, k) => ({
2502
- path: i.caminho.join('.') || '(root)',
2503
- message: i.message,
2504
- code: i.code,
2505
- ...(localizar(alvos[k]) ?? localizar(i.caminho) ?? {}),
2506
- ...humanizar(i, raw),
2507
- docKey: docKeyDoCaminho(i.caminho),
2508
- }));
2509
- }
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, fixado no package.json, dentro do `^4.3.6` que o astro
24
+ // tambem pede; o scripts/package-files.test.js garante uma copia so - entao a
25
+ // troca nao muda comportamento nenhum, so tira o astro do caminho de quem
26
+ // importa isto de fora do gerador.)
27
+ import { z } from 'zod';
28
+ // WD-063: `parseTree` + `findNodeAtLocation` traduzem o caminho de um erro
29
+ // (`navigation.products.0.product`) para o offset dele no TEXTO, que e o que
30
+ // vira linha. E o parser de JSON do VS Code: zero dependencias, nada de `node:`,
31
+ // entao continua bundlavel pro Worker da plataforma. Escrever o scanner a mao
32
+ // foi tentado e deu errado (perdia todo caminho aninhado, que e justamente o que
33
+ // importa aqui) - nao repita.
34
+ // WD-315 (07c): e o `visit`, a mesma leitura sem montar a arvore - ver
35
+ // localizarCaminhos.
36
+ import { findNodeAtLocation, parseTree, visit } from 'jsonc-parser';
37
+ // The form of `basePath`. Plain JS with no `node:` import, like this file.
38
+ import { BASE_PATH_FIELD_PATTERN } from './base-path.js';
39
+
40
+ // ---------------------------------------------------------------------
41
+ // Pages & groups - the leaf content any container ultimately bottoms out
42
+ // at. A group can nest other groups arbitrarily deep, and can optionally
43
+ // link its own label to a page (`page`) independent of expanding or
44
+ // collapsing its children - see NavTree.astro for how that renders.
45
+ // ---------------------------------------------------------------------
46
+
47
+ const navPageSchema = z.string();
48
+
49
+ // A group ordinarily lists its own children by hand (`pages`), but can
50
+ // instead auto-generate them from an OpenAPI spec via `openapi: { src,
51
+ // path }` - resolved by loadDocsConfig() (via expandOpenApiInNavigation()
52
+ // below, reading the manifest generate-api-pages.js writes for this exact
53
+ // group) into a real `{ group, pages }` node - one sub-group per tag -
54
+ // before anything else in this file ever sees it, so
55
+ // resolveSections()/flattenNav()/buildNavTree()/etc. only ever need to
56
+ // understand the ordinary pages-array shape. `.strict()` on both variants
57
+ // is load-bearing (see withChildren()'s own comment on this pattern
58
+ // below): without it, a group written with both `pages` and `openapi` at
59
+ // once would silently have one dropped instead of rejected.
60
+ const navGroupPagesSchema: z.ZodType<{ group: string; page?: string; pages: NavItem[] }> = z.lazy(() =>
61
+ z
62
+ .object({
63
+ group: z.string(),
64
+ page: z.string().optional(),
65
+ pages: z.array(navItemSchema),
66
+ })
67
+ .strict()
68
+ );
69
+
70
+ const navGroupOpenApiSchema = z.object({
71
+ group: z.string(),
72
+ openapi: z
73
+ .object({
74
+ // Path to an OpenAPI 3.x spec, relative to the content directory
75
+ // (alongside writedocs.json) - same convention the old top-level
76
+ // `openapi` field used. See generate-api-pages.js (the pre-Astro
77
+ // build/dev step that actually parses this and writes the
78
+ // manifest/operation JSON this group's pages are expanded from).
79
+ src: z.string(),
80
+ // Base URL path every page generated from this spec is namespaced
81
+ // under, e.g. "/api" -> pages served at /api/<tag>/<operation>/.
82
+ // Also doubles as this spec's own unique key under
83
+ // writedocsTempDir()'s openapi/<path>/ directory (manifest.json + operations/*.json),
84
+ // so two openapi groups in the same writedocs.json must use different
85
+ // `path` values - generate-api-pages.js throws a clear error if
86
+ // they collide.
87
+ path: z.string(),
88
+ })
89
+ .strict(),
90
+ }).strict();
91
+
92
+ export type GroupNavItem =
93
+ | { group: string; page?: string; pages: NavItem[] }
94
+ | { group: string; openapi: { src: string; path: string } };
95
+
96
+ const navGroupSchema: z.ZodType<GroupNavItem> = z.union([navGroupPagesSchema, navGroupOpenApiSchema]);
97
+
98
+ // A bare external link sitting directly in a `pages` array, alongside
99
+ // page slugs and groups - e.g. a "Support" link to an external help
100
+ // desk shown right in the sidebar, rather than only reachable via
101
+ // navigation.global.dropdowns. Discriminated from navGroupSchema by
102
+ // its required `label`/`href` keys (vs `group`/`pages`/`openapi`), so a
103
+ // plain (non-strict at the union level) schema is enough for Zod to pick
104
+ // the right branch; `.strict()` here still catches a typo'd extra key.
105
+ const navLinkSchema = z.object({ label: z.string(), href: z.string() }).strict();
106
+
107
+ const navItemSchema: z.ZodType<NavItem> = z.lazy(() =>
108
+ z.union([navPageSchema, navGroupSchema, navLinkSchema])
109
+ );
110
+
111
+ export type NavItem = string | GroupNavItem | { label: string; href: string };
112
+
113
+ // ---------------------------------------------------------------------
114
+ // Containers: tabs, versions, languages, dropdowns, products.
115
+ //
116
+ // This schema is modeled directly on Mintlify's writedocs.json
117
+ // (https://mintlify.com/writedocs.json / mintlify.com/docs/organize/navigation):
118
+ // all five container kinds are structurally identical except for their
119
+ // own identifying field. Each owns *exactly one* of {pages, tabs,
120
+ // versions, languages, dropdowns, products} as its content, or is a bare
121
+ // external `href` link with no content of its own. That symmetry is what
122
+ // lets any of them nest inside any other - a tab can contain versions, a
123
+ // version can contain languages, a language can contain tabs, and so on,
124
+ // bottoming out at a `pages` array. `withChildren()` is the single place
125
+ // that shape is defined, instead of hand-writing the union five times.
126
+ // ---------------------------------------------------------------------
127
+
128
+ export type NavChildren =
129
+ | { pages: NavItem[] }
130
+ | { tabs: TabItem[] }
131
+ | { versions: VersionItem[] }
132
+ | { languages: LanguageItem[] }
133
+ | { dropdowns: DropdownItem[] }
134
+ | { products: ProductItem[] }
135
+ | { href: string };
136
+
137
+ /** Any navigation item can be hidden: reachable only by its address - no
138
+ * switcher, tab or menu lists it, and its pages search only among
139
+ * themselves (plus the public ones, with `searchPublic`). See
140
+ * lib/hidden-sections.js.
141
+ * And any can have a `page` of its own: where choosing the item leads, in
142
+ * place of its first page - an overview of what's in it. In a sidebar too,
143
+ * it opens there; otherwise it opens inside the item (resolveLandings() in
144
+ * lib/config.ts). */
145
+ export type Hideable = { hidden?: boolean; searchPublic?: boolean; page?: string };
146
+
147
+ export type TabItem = { tab: string; icon?: string } & Hideable & NavChildren;
148
+ export type VersionItem = { version: string; label?: string; tag?: string; default?: boolean } & Hideable & NavChildren;
149
+ export type LanguageItem = { language: string; label?: string } & Hideable & NavChildren;
150
+ export type DropdownItem = { dropdown: string; icon?: string } & Hideable & NavChildren;
151
+ export type ProductItem = { product: string; icon?: string; description?: string } & Hideable & NavChildren;
152
+
153
+ // `.strict()` on every variant is load-bearing, not decoration: Zod
154
+ // objects silently strip unrecognized keys by default, so without it a
155
+ // node written with two children fields at once (e.g. both `pages` and
156
+ // `versions`) would just have the second one dropped instead of
157
+ // rejected - defeating the entire "exactly one child kind per level"
158
+ // rule this schema exists to enforce (mirroring Mintlify's own "a tab
159
+ // cannot contain both anchors and groups at the same level").
160
+ function withChildren<Base extends z.ZodRawShape>(ownFields: Base) {
161
+ const base = { ...ownFields, hidden: z.boolean().optional(), searchPublic: z.boolean().optional(), page: z.string().optional() };
162
+ return z.union([
163
+ z.object({ ...base, pages: z.array(navItemSchema) }).strict(),
164
+ z.object({ ...base, tabs: z.array(tabSchema).min(1) }).strict(),
165
+ z.object({ ...base, versions: z.array(versionSchema).min(1) }).strict(),
166
+ z.object({ ...base, languages: z.array(languageSchema).min(1) }).strict(),
167
+ z.object({ ...base, dropdowns: z.array(dropdownSchema).min(1) }).strict(),
168
+ z.object({ ...base, products: z.array(productSchema).min(1) }).strict(),
169
+ z.object({ ...base, href: z.string() }).strict(),
170
+ ]);
171
+ }
172
+
173
+ // Each of these five is defined via z.lazy() because withChildren()
174
+ // references all five by name (mutual recursion) - safe because none of
175
+ // them are actually *called* until a real writedocs.json is parsed, by which
176
+ // point every const below has been assigned. The same pattern already
177
+ // used for navItemSchema/navGroupSchema above.
178
+ const tabSchema: z.ZodType<TabItem> = z.lazy(() =>
179
+ withChildren({ tab: z.string(), icon: z.string().optional() })
180
+ );
181
+
182
+ const versionSchema: z.ZodType<VersionItem> = z.lazy(() =>
183
+ withChildren({
184
+ version: z.string(),
185
+ label: z.string().optional(),
186
+ tag: z.string().optional(),
187
+ default: z.boolean().optional(),
188
+ })
189
+ );
190
+
191
+ const languageSchema: z.ZodType<LanguageItem> = z.lazy(() =>
192
+ withChildren({ language: z.string(), label: z.string().optional() })
193
+ );
194
+
195
+ const dropdownSchema: z.ZodType<DropdownItem> = z.lazy(() =>
196
+ withChildren({ dropdown: z.string(), icon: z.string().optional() })
197
+ );
198
+
199
+ const productSchema: z.ZodType<ProductItem> = z.lazy(() =>
200
+ withChildren({ product: z.string(), icon: z.string().optional(), description: z.string().optional() })
201
+ );
202
+
203
+ // ---------------------------------------------------------------------
204
+ // Root navigation: a flat array (shorthand for one implicit section - the
205
+ // common case) or an object choosing exactly one primary organizational
206
+ // pattern, per Mintlify's convention ("choose one primary organizational
207
+ // pattern at the root level of your navigation").
208
+ //
209
+ // `global.dropdowns` is the one exception to "exactly one pattern": it's
210
+ // not a primary pattern, it's a persistent set of topbar dropdown
211
+ // triggers that render on every page regardless of which tab/version/
212
+ // language/product is active - equivalent to Mintlify's
213
+ // `navigation.global.anchors`. This replaces the earlier `{tabs,
214
+ // dropdowns}` shape (both present at once), which doesn't generalize
215
+ // once versions/languages/products are also root-level choices.
216
+ // ---------------------------------------------------------------------
217
+
218
+ export type NavigationConfig =
219
+ | NavItem[]
220
+ | { global?: { dropdowns: DropdownItem[] }; tabs: TabItem[] }
221
+ | { global?: { dropdowns: DropdownItem[] }; versions: VersionItem[] }
222
+ | { global?: { dropdowns: DropdownItem[] }; languages: LanguageItem[] }
223
+ | { global?: { dropdowns: DropdownItem[] }; dropdowns: DropdownItem[] }
224
+ | { global?: { dropdowns: DropdownItem[] }; products: ProductItem[] };
225
+
226
+ /** Levels of tabs a page can sit under - one row of the top bar each. */
227
+ export const MAX_TAB_LEVELS = 2;
228
+ /** Levels of dropdowns in a tab's menu - the menu, and a flyout beside an
229
+ * entry for the dropdowns inside it (lib/selector-placement.js). */
230
+ export const MAX_TAB_MENU_LEVELS = 2;
231
+
232
+ const globalSchema = z.object({ dropdowns: z.array(dropdownSchema).min(1) });
233
+
234
+ const navigationSchema = z.union([
235
+ z.array(navItemSchema),
236
+ z.object({ global: globalSchema.optional(), tabs: z.array(tabSchema).min(1) }).strict(),
237
+ z.object({ global: globalSchema.optional(), versions: z.array(versionSchema).min(1) }).strict(),
238
+ z.object({ global: globalSchema.optional(), languages: z.array(languageSchema).min(1) }).strict(),
239
+ z.object({ global: globalSchema.optional(), dropdowns: z.array(dropdownSchema).min(1) }).strict(),
240
+ z.object({ global: globalSchema.optional(), products: z.array(productSchema).min(1) }).strict(),
241
+ ]).superRefine((navigation, ctx) => {
242
+ // Every page under a language is in that language - a second `languages`
243
+ // inside it would make a page two languages at once. And tabs take a row
244
+ // of the top bar per level: two levels at most (TopBar.astro).
245
+ const CONTAINERS = ['tabs', 'versions', 'languages', 'dropdowns', 'products'] as const;
246
+ // `menu`: the dropdown levels in a tab's menu down to `node` - 0 outside
247
+ // one, 1 for a dropdown right inside a tab, 2 for a dropdown inside that.
248
+ const walk = (node: unknown, path: (string | number)[], language: string | null, tabs: string[], menu = 0) => {
249
+ if (!node || typeof node !== 'object' || Array.isArray(node)) return;
250
+ const own = node as Record<string, unknown>;
251
+ for (const key of CONTAINERS) {
252
+ const items = own[key];
253
+ if (!Array.isArray(items)) continue;
254
+ if (key === 'languages' && language !== null) {
255
+ ctx.addIssue({
256
+ code: 'custom',
257
+ path: [...path, key],
258
+ message: `The language "${language}" contains another "languages" list. A page can only be in one language - put the languages at one level, and the rest (tabs, versions, ...) inside each of them.`,
259
+ });
260
+ continue;
261
+ }
262
+ if (key === 'tabs' && tabs.length >= MAX_TAB_LEVELS) {
263
+ ctx.addIssue({
264
+ code: 'custom',
265
+ path: [...path, key],
266
+ message: `Tabs go at most ${MAX_TAB_LEVELS} levels deep, and these are a third level (inside "${tabs.join('" > "')}"). Each level of tabs is a row in the top bar - use a dropdown or groups for this level instead.`,
267
+ });
268
+ continue;
269
+ }
270
+ // Dropdowns right inside a tab are its menu; dropdowns inside one of
271
+ // those, a flyout beside its entry. Any other level of dropdowns starts
272
+ // its own count.
273
+ const menuLevel = key !== 'dropdowns' ? 0 : 'tab' in own ? 1 : 'dropdown' in own && menu > 0 ? menu + 1 : 0;
274
+ if (menuLevel > MAX_TAB_MENU_LEVELS) {
275
+ ctx.addIssue({
276
+ code: 'custom',
277
+ path: [...path, key],
278
+ message: `A tab's menu goes ${MAX_TAB_MENU_LEVELS} levels deep at most - its dropdowns, and the dropdowns inside each of them - and these are a third level (inside "${String(own.dropdown)}"). Use products or groups for this level instead.`,
279
+ });
280
+ continue;
281
+ }
282
+ items.forEach((item, i) => {
283
+ const own = item as { hidden?: unknown; searchPublic?: unknown; page?: unknown; href?: unknown };
284
+ if (own?.page !== undefined && own.href !== undefined) {
285
+ ctx.addIssue({
286
+ code: 'custom',
287
+ path: [...path, key, i, 'page'],
288
+ message: 'An item with `href` is a link, so it has no page of its own - remove `page`, or `href`.',
289
+ });
290
+ }
291
+ if (own?.searchPublic === true && own.hidden !== true) {
292
+ ctx.addIssue({
293
+ code: 'custom',
294
+ path: [...path, key, i, 'searchPublic'],
295
+ message: '`searchPublic` only applies to a hidden item - add "hidden": true, or remove `searchPublic`.',
296
+ });
297
+ }
298
+ const inner = key === 'languages' ? String((item as { language?: unknown })?.language ?? '') : language;
299
+ const tab = (item as { tab?: unknown })?.tab;
300
+ walk(item, [...path, key, i], inner, key === 'tabs' ? [...tabs, String(tab ?? '')] : tabs, menuLevel);
301
+ });
302
+ }
303
+ };
304
+ walk(navigation, [], null, []);
305
+ }) as z.ZodType<NavigationConfig>;
306
+
307
+ const DEFAULT_PRIMARY = '#6366f1';
308
+
309
+ // A logo is either one path used for both color modes, or a
310
+ // { light, dark, label } object - each image shown only while that mode
311
+ // is active (see BaseLayout.astro's .wd-logo-light/.wd-logo-dark CSS).
312
+ // The topbar shows *only* the image by default - no site name text next
313
+ // to it, since a real logo asset usually already is a wordmark. `label`
314
+ // is the opt-in way to add text back next to the image (e.g. a product
315
+ // name alongside a symbol-only mark); it only exists on the object form,
316
+ // since a single shared image path is just as easy to bake the label
317
+ // into directly.
318
+ //
319
+ // `light`/`dark` are themselves optional (unlike the string form, which
320
+ // is inherently "both"): a site with no logo *images* at all can still
321
+ // set `styles.logo: { label: "..." }` to override the topbar's fallback
322
+ // text without providing any image - see BaseLayout.astro's
323
+ // hasLogoImage/logoLabel/brandLabel derivation, where an object with
324
+ // only `label` set already resolves correctly (brandLabel = logoLabel,
325
+ // same as if an image were also present) without needing any change
326
+ // there; only this schema needed loosening; light/dark were previously
327
+ // both required whenever the object form was used at all.
328
+ //
329
+ // Standalone const (rather than inlined into stylesSchema.logo below) so
330
+ // footer.logo further down can share the exact same union instead of an
331
+ // independently-written copy - see footerSchema's own comment on why a
332
+ // footer logo needs this at all.
333
+ const logoSchema = z.union([
334
+ z.string(),
335
+ z.object({ light: z.string().optional(), dark: z.string().optional(), label: z.string().optional() }).strict(),
336
+ ]);
337
+
338
+ // Same {light, dark}-with-fallback shape applies to `colors.dark`: any
339
+ // of primary/text left unset there falls back to the light-mode value
340
+ // already given above, so a site only has to specify what actually
341
+ // differs in dark mode. There used to be a `background`/`dark.background`
342
+ // pair here too, doing effectively the same job as `background.colors`
343
+ // further down (see that field's own comment) - two writedocs.json fields
344
+ // both named "background" that visually looked interchangeable but
345
+ // weren't quite (one drove --wd-background site-wide, the other only
346
+ // the <body> canvas), which was confusing to author against and easy to
347
+ // half-configure by setting only one. Removed in favor of `background`
348
+ // alone being the single place to set any background color - see that
349
+ // field's comment for what it now covers.
350
+ // One side of `styles.navbar` (light or dark) - either a bare background
351
+ // color (the original shape) or `{ background, accent? }` once a site
352
+ // wants its own accent color (the active tab's underline)
353
+ // inside the navbar specifically, independent of the sitewide
354
+ // `styles.colors.primary`. Deliberately does NOT carry a text/icon color
355
+ // field at all - see `navbar`'s own comment below (stylesSchema) for why
356
+ // that's resolved automatically instead of being configurable. Kept as a
357
+ // standalone const rather than inlined so `light`/`dark` share the exact
358
+ // same union rather than two independently-written (and possibly
359
+ // drifting) copies of it.
360
+ const navbarColorValueSchema = z.union([
361
+ z.string(),
362
+ z
363
+ .object({
364
+ background: z.string(),
365
+ accent: z.string().optional(),
366
+ })
367
+ .strict(),
368
+ ]);
369
+
370
+ // One font declaration - almost exactly Mintlify's own `fonts` shape (see
371
+ // docs/dev/docs/site-config.mdx's own "Fonts" section for the research this
372
+ // was based on): a bare Google Fonts family name (`family` alone - Google
373
+ // Fonts loads it automatically, see googleFontsHref() below), or a local/
374
+ // externally-hosted font file (`source` + `format` together; `source` is
375
+ // either a project-relative path like the other five asset-fallback fields
376
+ // this schema already has - see collectConfiguredAssetPaths() - or a full
377
+ // https:// URL to an externally-hosted font). `weight` does two things at
378
+ // once, both driven by BaseLayout.astro: it narrows which file actually
379
+ // loads (folded into the Google Fonts URL's `:wght@` axis, or the
380
+ // generated `@font-face` rule's own `font-weight` descriptor for a
381
+ // `source` font - see googleFontsHref()/fontFaceRule() below), *and* it's
382
+ // applied as a real CSS `font-weight` on h1-h6 (for `heading`) or `body`
383
+ // (for `body`) - see BaseLayout's own `wdFontWeightHeading`/
384
+ // `wdFontWeightBody`. Both halves matter: loading only the 400-weight file
385
+ // while leaving h1-h6 at the browser's UA-default `font-weight: bold`
386
+ // faux-bolds that file back to looking bold anyway, with no visible
387
+ // change from configuring a lighter weight at all - the bug this second
388
+ // half fixes (caught from real user-reported behavior, not anticipated
389
+ // up front). Left unset anywhere in `styles.fonts` renders no font-weight
390
+ // rule at all, keeping today's plain browser-default bold headings/normal
391
+ // body text unchanged for a site that hasn't touched this field.
392
+ const fontVariantSchema = z
393
+ .object({
394
+ family: z.string(),
395
+ weight: z.number().optional(),
396
+ source: z.string().optional(),
397
+ format: z.enum(['woff', 'woff2']).optional(),
398
+ })
399
+ .strict();
400
+
401
+ export type FontVariant = z.infer<typeof fontVariantSchema>;
402
+
403
+ // The top-level shape adds `heading`/`body`: each independently optional,
404
+ // each falling back to the top-level family/weight/source/format when
405
+ // unset (see resolveFonts() below) - so a site can set one font for
406
+ // everything (`fonts.family` alone), or split headings and body text
407
+ // without needing to repeat itself for whichever side isn't changing.
408
+ const fontsSchema = z
409
+ .object({
410
+ family: z.string(),
411
+ weight: z.number().optional(),
412
+ source: z.string().optional(),
413
+ format: z.enum(['woff', 'woff2']).optional(),
414
+ heading: fontVariantSchema.optional(),
415
+ body: fontVariantSchema.optional(),
416
+ })
417
+ .strict();
418
+
419
+ export type FontsConfig = z.infer<typeof fontsSchema>;
420
+
421
+ const stylesSchema = z
422
+ .object({
423
+ colors: z
424
+ .object({
425
+ primary: z.string().default(DEFAULT_PRIMARY),
426
+ text: z.string().optional(),
427
+ dark: z
428
+ .object({
429
+ primary: z.string().optional(),
430
+ text: z.string().optional(),
431
+ })
432
+ .optional(),
433
+ })
434
+ .default({ primary: DEFAULT_PRIMARY }),
435
+ logo: logoSchema.optional(),
436
+ favicon: z.string().optional(),
437
+ // No default value here (unlike `colors.primary`'s DEFAULT_PRIMARY) -
438
+ // resolveFonts() below is where "Inter" actually gets applied as the
439
+ // site-wide default whenever this field is left unset entirely, so
440
+ // that fallback lives in one place alongside the rest of the
441
+ // resolution logic rather than being duplicated as a schema default
442
+ // *and* a resolver fallback.
443
+ fonts: fontsSchema.optional(),
444
+ // The Shiki theme *name* (not a full theme object/JSON - see
445
+ // https://shiki.style/themes for the built-in list) each fenced
446
+ // (```) MDX code block, and the API playground's request/response
447
+ // snippets, use in light/dark mode - read out of writedocs.json by both
448
+ // astro.config.mjs (Shiki's dual-theme markdown config) and
449
+ // ApiReferencePanel.astro (its own separate <Code/> usages, which
450
+ // don't inherit markdown.shikiConfig) via resolveCodeblockTheme()
451
+ // below, the single source of truth for the 'github-light'/
452
+ // 'github-dark' fallback. Left per-key optional (not defaulted in
453
+ // the schema itself) so a site can override just one side (e.g.
454
+ // only `dark`) and still get the ordinary default for the other.
455
+ codeblocks: z
456
+ .object({
457
+ light: z.string().optional(),
458
+ dark: z.string().optional(),
459
+ // Maps a fenced (```) block's own language tag to whichever real
460
+ // Shiki grammar actually highlights it, before that tag ever
461
+ // reaches Shiki - see resolveCodeblockLangAlias() below for the
462
+ // one built-in entry (mdx -> jsx) this ships with by default and
463
+ // why. A site can add its own entries for any other language tag
464
+ // that either doesn't tokenize well under its own grammar, or
465
+ // that a site wants to write under a shorter/friendlier fence tag
466
+ // than Shiki's own bundled id (e.g. `groovy: 'java'` for a close-
467
+ // enough approximation Shiki doesn't ship a dedicated grammar for
468
+ // at all) - merged with, not replacing, the built-in default, so
469
+ // adding one of a site's own doesn't require re-declaring mdx.
470
+ langAlias: z.record(z.string(), z.string()).optional(),
471
+ })
472
+ .strict()
473
+ .optional(),
474
+ // The topbar's own background, independent of `background` below (the
475
+ // page's) - a site may want its navbar to stand out (a dark or
476
+ // brand-colored bar over a light page) rather than blend into the
477
+ // page, which is the default when this is left unset. Same {light,
478
+ // dark} shape (and same per-key-optional, not defaulted here) as
479
+ // `codeblocks` right above, rather than nested under `colors` - it's a
480
+ // topbar-specific override, not a third general-purpose page color, so
481
+ // it reads more like "one more themed surface" alongside codeblocks
482
+ // than a sibling of primary/text. BaseLayout.astro's own
483
+ // lightNavbarBg/darkNavbarBg resolution is what falls each side back
484
+ // to the page background when unset.
485
+ //
486
+ // Each side (`light`/`dark`) is either a bare string - just the
487
+ // background color, exactly the original shape, kept for backwards
488
+ // compatibility - or `{ background, accent? }`, for when a site also
489
+ // wants the navbar's own active-tab underline color to
490
+ // differ from the sitewide `styles.colors.primary` (`accent`'s only
491
+ // job - see BaseLayout.astro's lightNavbarAccent). Deliberately no
492
+ // text/icon color field here at all: BaseLayout.astro always resolves
493
+ // the navbar's plain text/icon color itself, picking black or white by
494
+ // contrast against whatever `background` resolves to
495
+ // (contrastTextColor() below) the moment this field is configured at
496
+ // all (string or object) - never a value read from writedocs.json. A
497
+ // manually-set text color is a legibility footgun a site author can
498
+ // get wrong (or drift out of sync after later changing `background`
499
+ // without remembering to update it too) in a way "compute it
500
+ // correctly, every time" simply can't - there's no legitimate reason
501
+ // to want *illegible* navbar text, unlike `accent`, which is a real
502
+ // aesthetic choice. Real bug this fixes: a site setting `navbar.light`
503
+ // to the same value as `colors.primary` (a plausible thing to reach
504
+ // for - "brand-colored navbar") made every topbar label/icon/link
505
+ // render in the default near-black text color against that same
506
+ // saturated background, all but unreadable - and an earlier version of
507
+ // this feature that let a writedocs.json-supplied color double as the text
508
+ // color reintroduced the identical bug one level down, just requiring
509
+ // one more (still guessable-wrong) field to trigger it.
510
+ navbar: z
511
+ .object({
512
+ light: navbarColorValueSchema.optional(),
513
+ dark: navbarColorValueSchema.optional(),
514
+ })
515
+ .strict()
516
+ .optional(),
517
+ // The single place to configure any background color: `colors` is a
518
+ // solid color (falls back to '#ffffff'/'#0b1120' when unset - see
519
+ // BaseLayout.astro's lightBackground/darkBackground resolution), and
520
+ // `images` layers an image on top of it (or is the whole background
521
+ // by itself, if `colors` is left at its default). This one pair now
522
+ // drives everything background-related site-wide - --wd-background
523
+ // (dropdowns/modals/kbd chips/footer/topbar-fallback/etc., see every
524
+ // `var(--wd-background)` call site) *and* the <body> canvas behind the
525
+ // main/toc columns - rather than the two being independently
526
+ // configurable fields that happened to look alike but didn't affect
527
+ // the same things (see this schema's own comment on `colors.dark`
528
+ // above for why that split was removed). Both are per-mode optional,
529
+ // same "only specify what differs" pattern as codeblocks/navbar above.
530
+ // The topbar and footer still get their own explicit opaque
531
+ // background (topbar.css/footer.css) specifically so an `images`
532
+ // background doesn't show through them; see those files' own
533
+ // comments. The sidebar column has no background of its own (base.css)
534
+ // and lets it show through, same as the main/toc columns.
535
+ background: z
536
+ .object({
537
+ colors: z
538
+ .object({
539
+ light: z.string().optional(),
540
+ dark: z.string().optional(),
541
+ })
542
+ .strict()
543
+ .optional(),
544
+ images: z
545
+ .object({
546
+ light: z.string().optional(),
547
+ dark: z.string().optional(),
548
+ })
549
+ .strict()
550
+ .optional(),
551
+ })
552
+ .strict()
553
+ .optional(),
554
+ })
555
+ .default({ colors: { primary: DEFAULT_PRIMARY } });
556
+
557
+ // `href` is always required - a link with nowhere to go isn't a link.
558
+ // `label`/`icon` are each individually optional, but not both at once
559
+ // (enforced by the .refine() below, same shape as scriptEntrySchema's own
560
+ // exactly-one-of check above) - a link needs *something* visible to render,
561
+ // whichever of the two, and can have both (icon rendered to the left of the
562
+ // label - see TopBar.astro/SiteFooter.astro, the two renderers of this
563
+ // shape). An icon-only link (no label) is the common case for something
564
+ // like a bare GitHub mark in the topbar; label-only (no icon) is every
565
+ // plain text link this already supported before `icon` existed - both
566
+ // still need to keep working unchanged, hence neither field being outright
567
+ // required on its own.
568
+ const topbarLinkSchema = z
569
+ .object({
570
+ label: z.string().optional(),
571
+ href: z.string(),
572
+ // Same string shape as every other writedocs.json `icon` field (a plain
573
+ // Lucide name, or the explicit "collection:icon-name" form for
574
+ // anything else - see resolveIcon()/AppIcon.astro) - not documented
575
+ // again here since that convention is already established elsewhere
576
+ // in this file (tabs/switchers/socials all take the identical shape).
577
+ icon: z.string().optional(),
578
+ })
579
+ .strict()
580
+ .refine((link) => Boolean(link.label) || Boolean(link.icon), {
581
+ message: 'Each topbar.links/footer column link needs a "label", an "icon", or both - a link with neither has nothing to render.',
582
+ });
583
+
584
+ // One column of the footer (BaseLayout.astro's <footer class="wd-footer">) -
585
+ // an optional heading (e.g. "Resources", "Community") plus a list of links,
586
+ // reusing the exact same {label, icon, href} shape as topbar.links above (a
587
+ // footer link is the same thing rendered in a different place, no reason
588
+ // for a second, identical-but-differently-named schema). `title` is
589
+ // optional so a single-column footer with no heading (just a bare list of
590
+ // links) is valid too.
591
+ const footerColumnSchema = z
592
+ .object({
593
+ title: z.string().optional(),
594
+ links: z.array(topbarLinkSchema).default([]),
595
+ })
596
+ .strict();
597
+
598
+ // Off by default (empty `columns`, same convention as `topbar` above - a
599
+ // footer with nothing configured just doesn't render at all, see
600
+ // BaseLayout.astro's `hasFooterContent` check) rather than `.optional()`
601
+ // like contextMenu: unlike that field, an empty/default footer has no
602
+ // build-output or routing implications to gate, it's purely visual, so
603
+ // there's no reason to distinguish "unset" from "set to nothing" the way
604
+ // contextMenu needs to.
605
+ // Same {light, dark, label} union as `styles.logo` (via the shared
606
+ // logoSchema above) - unset by default, in which case the footer just
607
+ // shows the sitewide `styles.logo` (BaseLayout.astro's existing
608
+ // logoLight/logoDark/logoLabel, already threaded into SiteFooter as-is).
609
+ // Set here, it replaces that entirely rather than filling in only the
610
+ // missing side of it - a footer.logo with only `dark` set shows *just*
611
+ // the dark-mode image, not styles.logo's light image plus this dark one -
612
+ // the same all-or-nothing-relative-to-styles.logo resolution BaseLayout.astro
613
+ // already applies.
614
+ const footerSchema = z
615
+ .object({
616
+ columns: z.array(footerColumnSchema).default([]),
617
+ logo: logoSchema.optional(),
618
+ })
619
+ .strict()
620
+ .default({ columns: [] });
621
+
622
+ export type FooterColumn = z.infer<typeof footerColumnSchema>;
623
+ export type FooterConfig = z.infer<typeof footerSchema>;
624
+
625
+ // Shared by both writedocs.json's top-level `seo` (site-wide defaults) and a
626
+ // page's own frontmatter `seo` (per-page overrides) - see
627
+ // content.config.ts's docsSchema, which imports this exact schema rather
628
+ // than redeclaring the same shape a second time. mergeSeo() below is what
629
+ // actually combines the two, field by field, at render time.
630
+ export const seoFieldsSchema = z
631
+ .object({
632
+ // Open Graph / Twitter card image - a relative path (resolved against
633
+ // `domain` below into an absolute URL, since most social crawlers
634
+ // require one) or an already-absolute https:// URL.
635
+ ogImage: z.string().optional(),
636
+ // og:type - "website" for most pages, "article" for blog-post-shaped
637
+ // content, etc. Defaults to "website" if never set anywhere.
638
+ ogType: z.string().optional(),
639
+ twitterCard: z.enum(['summary', 'summary_large_image']).optional(),
640
+ keywords: z.array(z.string()).optional(),
641
+ // Renders <meta name="robots" content="noindex, nofollow" /> and
642
+ // (see astro.config.mjs's sitemap `filter`) excludes the page from
643
+ // sitemap.xml entirely - both driven off this one flag, since listing
644
+ // a page in the sitemap while also telling crawlers not to index it
645
+ // would be self-contradictory.
646
+ noindex: z.boolean().optional(),
647
+ // The whole <meta name="robots"> value, for anything `noindex` (always
648
+ // "noindex, nofollow") doesn't say - "noindex, follow", "max-snippet:50".
649
+ // Wins over `noindex`; a value with "noindex" keeps the page out of
650
+ // sitemap.xml and llms.txt the same way (isNoindex(), lib/seo-tags.js).
651
+ robots: z.string().optional(),
652
+ // Any other <meta> tag, name -> content: "google-site-verification",
653
+ // "twitter:site", "og:locale"... One with the name of a tag writedocs
654
+ // writes itself ("og:image", "twitter:image", "description") replaces
655
+ // it. Open Graph names become <meta property>, the rest <meta name> -
656
+ // see seoHead() in lib/seo-tags.js. A page's own are merged over the
657
+ // site's, name by name.
658
+ metatags: z.record(z.string(), z.string()).optional(),
659
+ })
660
+ .strict();
661
+
662
+ // A page's own `seo`: everything above, plus what only makes sense for one
663
+ // page - the site has no single title, description or canonical address.
664
+ export const pageSeoFieldsSchema = seoFieldsSchema
665
+ .extend({
666
+ // The <title> and og:title/twitter:title, exactly as written - no site
667
+ // name is added. The page's <h1> and sidebar entry keep `title`.
668
+ title: z.string().optional(),
669
+ // The <meta name="description"> and og/twitter descriptions, when they
670
+ // should differ from the `description` shown under the page's title.
671
+ description: z.string().optional(),
672
+ // The page's canonical URL, when it isn't its own address: a full URL,
673
+ // or a path on the site's domain. A page whose canonical is another
674
+ // address is left out of sitemap.xml.
675
+ canonical: z.string().optional(),
676
+ // The page's own structured data (schema.org JSON-LD): one block, or a
677
+ // list of them, written into the page after the ones writedocs
678
+ // generates (lib/json-ld.js). Any shape - it is the author's to get right.
679
+ jsonLd: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]).optional(),
680
+ })
681
+ .strict();
682
+
683
+ // writedocs.json's `seo`: the shared fields, plus what describes the site
684
+ // as a whole.
685
+ export const siteSeoFieldsSchema = seoFieldsSchema
686
+ .extend({
687
+ // The link preview picture generated for every page that has no
688
+ // `ogImage` (lib/og-image.js). On unless this is `false`: drawing one
689
+ // takes ~25 ms a page, which a site with thousands of pages may prefer
690
+ // to save. Site-wide only - a page opts out by setting its own `ogImage`.
691
+ generatedOgImage: z.boolean().optional(),
692
+ // Who publishes the site - an Organization block in the home page's
693
+ // structured data, and the `publisher` of every page (lib/json-ld.js).
694
+ // Not derived from `name`: a site is called "Acme Docs", the
695
+ // organization "Acme".
696
+ organization: z
697
+ .object({
698
+ name: z.string(),
699
+ // The organization's own site. Default: this site's address.
700
+ url: z.string().optional(),
701
+ // A path in the project or a full URL. Default: the site's logo.
702
+ logo: z.string().optional(),
703
+ // Its profiles elsewhere. Default: the URLs in `socials`.
704
+ sameAs: z.array(z.string()).optional(),
705
+ })
706
+ .strict()
707
+ .optional(),
708
+ })
709
+ .strict();
710
+
711
+ export type SiteSeoFields = z.infer<typeof siteSeoFieldsSchema>;
712
+ export type SeoFields = z.infer<typeof pageSeoFieldsSchema>;
713
+
714
+ /** Field-by-field merge of a page's own `seo` frontmatter over writedocs.json's
715
+ * site-wide `seo` defaults - a page only overrides the specific fields it
716
+ * sets, falling back to the site default for everything else, rather than
717
+ * a page's (possibly partial) `seo` object replacing the site's wholesale. */
718
+ export function mergeSeo(site: SeoFields, page: SeoFields = {}): SeoFields {
719
+ // `robots` and `noindex` say the same thing two ways, so they're taken
720
+ // together: a page that sets either one decides for itself, and the
721
+ // site's value of the other doesn't leak into it. `noindex` then follows
722
+ // `robots` when there is one, so everything that reads `noindex` (the
723
+ // sitemap, llms.txt, the MCP index) agrees with the tag on the page.
724
+ const pageDecides = page.robots !== undefined || page.noindex !== undefined;
725
+ const robots = pageDecides ? page.robots : site.robots;
726
+ const noindex = robots !== undefined ? /\bnoindex\b|\bnone\b/i.test(robots) : pageDecides ? page.noindex : site.noindex;
727
+ const metatags = site.metatags || page.metatags ? { ...site.metatags, ...page.metatags } : undefined;
728
+ return {
729
+ ogImage: page.ogImage ?? site.ogImage,
730
+ ogType: page.ogType ?? site.ogType,
731
+ twitterCard: page.twitterCard ?? site.twitterCard,
732
+ keywords: page.keywords ?? site.keywords,
733
+ noindex,
734
+ robots,
735
+ metatags,
736
+ title: page.title,
737
+ description: page.description,
738
+ canonical: page.canonical,
739
+ jsonLd: page.jsonLd,
740
+ };
741
+ }
742
+
743
+ const MINTLIFY_MODE_ALIASES: Record<string, string> = { center: 'frame', assistant: 'default' };
744
+
745
+ /** A page's own frontmatter - the `pages` and `generatedDocs` content
746
+ * collections' schema (content.config.ts), and what `writedocs validate`
747
+ * checks every page against. */
748
+ export const pageFrontmatterSchema = z.object({
749
+ title: z.string(),
750
+ description: z.string().optional(),
751
+ // Overrides the URL this page is served at, independent of where the
752
+ // file actually lives - writedocs.json's `pages` arrays always keep
753
+ // referencing the file's own path regardless. This is Astro's own
754
+ // glob()-loader convention (a `slug` frontmatter field becomes
755
+ // `entry.id` verbatim - see generateIdDefault in
756
+ // astro/dist/content/loaders/glob.js), not writedocs-specific
757
+ // behavior; declaring it here just brings it into the schema (and
758
+ // its docs) rather than leaving it an undocumented Astro feature.
759
+ // See fileIdForEntry() in lib/config.ts for how routes/links still
760
+ // resolve a page by its file id once this diverges from `entry.id`.
761
+ // Leading/trailing slashes are fine either way ("/", "/guides/x",
762
+ // "guides/x" and "guides/x/" all mean the same thing) - see
763
+ // normalizeEntryId() in lib/config.ts, which is what actually
764
+ // strips them before this value is ever used as a route or href.
765
+ slug: z.string().optional(),
766
+ // Marks this page as an OpenAPI operation reference: "METHOD /path"
767
+ // matching an operation in the owning group's OpenAPI spec, e.g.
768
+ // "GET /pets/{petId}" - [...slug].astro renders <ApiPlayground /> for
769
+ // any page with this field set, below the page's own MDX body (if
770
+ // any). Sites don't write this by hand for most pages; it's either
771
+ // set on a generated stub in the `generatedDocs` collection below (see
772
+ // generate-api-pages.js) or hand-authored to "eject" one specific
773
+ // operation into a real file (in `docs`) with custom prose - either
774
+ // way, the value is always exactly the same "METHOD /path" key
775
+ // generate-api-pages.js uses to look up the operation's full resolved
776
+ // schema/examples at render time.
777
+ openapi: z.string().optional(),
778
+ // Controls how much of the site's own chrome (topbar, sidebar, table of
779
+ // contents) wraps this page - see BaseLayout.astro/[...slug].astro for
780
+ // what each value actually removes:
781
+ // default - the normal three-column reading layout (all chrome).
782
+ // wide - drops the table of contents; the article itself also
783
+ // renders wider, for content that wants the extra room
784
+ // (wide tables, side-by-side images).
785
+ // frame - drops the sidebar and table of contents, but keeps the
786
+ // topbar and the article's own normal presentation
787
+ // ("frame" as in: still inside the site's outer frame).
788
+ // custom - drops the sidebar and table of contents, the
789
+ // auto-rendered <h1>, and prev/next nav, and skips the
790
+ // article's own prose width/padding too - a blank canvas
791
+ // for a hand-built landing/home page made entirely of
792
+ // components - but keeps the topbar, so the page still
793
+ // has site branding/nav/search/theme-toggle available.
794
+ // blank - everything 'custom' drops, plus the topbar too: no site
795
+ // chrome at all, just <slot />. For a page that wants to
796
+ // look nothing like the rest of the site (an auth screen,
797
+ // a print-style page).
798
+ //
799
+ // Two Mintlify values are accepted so a migrated page doesn't fail the
800
+ // build (see MINTLIFY_MODE_ALIASES above): `center` is the same layout
801
+ // as our `frame`, and `assistant` (a full-page Mintlify AI chat, which
802
+ // writedocs doesn't have) falls back to `default`. Mintlify's own
803
+ // `frame` means something else (a canvas that keeps the sidebar) - it's
804
+ // left as our `frame`; see docs/dev/docs/mintlify-compat.mdx.
805
+ mode: z
806
+ .preprocess(
807
+ (value) => (typeof value === 'string' && value in MINTLIFY_MODE_ALIASES ? MINTLIFY_MODE_ALIASES[value] : value),
808
+ z.enum(['default', 'wide', 'frame', 'custom', 'blank']),
809
+ )
810
+ .default('default'),
811
+ // Per-page meta tag overrides - same shape as writedocs.json's top-level
812
+ // `seo` (see seoFieldsSchema in lib/config.ts, the single source of
813
+ // truth for this shape). A page only needs to set the specific fields
814
+ // it wants to override; mergeSeo() falls back to the site-wide default
815
+ // for anything left unset. See BaseLayout.astro for where this and the
816
+ // site-wide seo actually get merged and rendered.
817
+ seo: pageSeoFieldsSchema.optional(),
818
+ // Mintlify's spelling of `seo.noindex` - a top-level `noindex: true`.
819
+ // Folded into `seo` by the transform below, so everything downstream
820
+ // (the robots meta tag, sitemap.xml, llms.txt) keeps reading
821
+ // `seo.noindex` only.
822
+ noindex: z.boolean().optional(),
823
+ // Mintlify's spellings of `seo.robots` and `seo.canonical`, folded into
824
+ // `seo` the same way.
825
+ robots: z.string().optional(),
826
+ canonical: z.string().optional(),
827
+ // Mintlify's short navigation label - used for the sidebar and the
828
+ // topbar dropdown menus in place of `title` ([...slug].astro's
829
+ // navTitleForSlug). The page's own <h1> and prev/next links keep `title`.
830
+ sidebarTitle: z.string().optional(),
831
+ // Mintlify's spellings of `seo.keywords`, `seo.ogImage`, `seo.ogType`
832
+ // and `seo.twitterCard`, folded into `seo` below like `noindex`.
833
+ keywords: z.array(z.string()).optional(),
834
+ 'og:image': z.string().optional(),
835
+ 'og:type': z.string().optional(),
836
+ 'twitter:card': z.enum(['summary', 'summary_large_image']).optional(),
837
+ // Mintlify's sidebar/page-chrome fields - see NavTree.astro and
838
+ // [...slug].astro for where each is used:
839
+ // icon - shown before the page's label in the sidebar.
840
+ // tag - a short label after it (e.g. "NEW").
841
+ // deprecated - a "Deprecated" label in the sidebar and next
842
+ // to the page's <h1>.
843
+ // hidden - left out of the sidebar, dropdowns and
844
+ // prev/next, but still built and reachable by
845
+ // URL. Also noindexed, as on Mintlify.
846
+ // url - an external link: the page's sidebar entry
847
+ // links straight to it, and the page's own URL
848
+ // redirects there.
849
+ // hideFooterPagination - no prev/next links on this page.
850
+ // hideApiMarker - no HTTP method badge on this page's sidebar
851
+ // entry.
852
+ icon: z.string().optional(),
853
+ tag: z.string().optional(),
854
+ deprecated: z.boolean().optional(),
855
+ hidden: z.boolean().optional(),
856
+ url: z.string().optional(),
857
+ hideFooterPagination: z.boolean().optional(),
858
+ hideApiMarker: z.boolean().optional(),
859
+ }).transform(
860
+ ({ noindex, robots, canonical, keywords, 'og:image': ogImage, 'og:type': ogType, 'twitter:card': twitterCard, ...data }) => {
861
+ // Top-level Mintlify keys fill in `seo` only where the page's own `seo`
862
+ // doesn't already set that field - an explicit `seo` value always wins.
863
+ // A `hidden` page is noindexed unless it says otherwise.
864
+ const seo = { ...data.seo };
865
+ // `robots` says whether the page is indexed, so with one - the page's
866
+ // own, or the top-level spelling - `noindex` follows it, and a `hidden`
867
+ // page's automatic noindex doesn't apply.
868
+ const pageRobots = seo.robots ?? robots;
869
+ const fromMintlify = {
870
+ robots,
871
+ canonical,
872
+ noindex: pageRobots !== undefined ? undefined : (noindex ?? (data.hidden ? true : undefined)),
873
+ keywords,
874
+ ogImage,
875
+ ogType,
876
+ twitterCard,
877
+ };
878
+ let changed = false;
879
+ for (const [key, value] of Object.entries(fromMintlify)) {
880
+ if (value === undefined || seo[key as keyof typeof seo] !== undefined) continue;
881
+ (seo as Record<string, unknown>)[key] = value;
882
+ changed = true;
883
+ }
884
+ if (pageRobots !== undefined) {
885
+ seo.noindex = /\bnoindex\b|\bnone\b/i.test(pageRobots);
886
+ changed = true;
887
+ }
888
+ return changed ? { ...data, seo } : data;
889
+ },
890
+ );
891
+
892
+ // Controls for the OpenAPI API playground's "Try it" modal - separate
893
+ // from a group's own `openapi: { src, path }` field (which spec to use,
894
+ // and where) since this is about how a *request* it sends behaves, not
895
+ // about the spec itself.
896
+ const apiSchema = z
897
+ .object({
898
+ // Whether a Try-it request the browser blocks is retried through
899
+ // writedocs' own CORS proxy (https://proxy.writechoice.io/). The
900
+ // request always goes to the API directly first, so a reader's key
901
+ // reaches the proxy only when the API itself refuses browser calls.
902
+ // Almost no real-world API sends back Access-Control-Allow-Origin
903
+ // headers permitting an arbitrary docs site's origin, so the direct
904
+ // call fails for most real APIs - see the send handler and
905
+ // PROXY_BASE_URL in ApiReferencePanel.astro. Defaults to enabled; a
906
+ // site can set this to `false` to never involve a third party.
907
+ proxy: z.boolean().default(true),
908
+ })
909
+ .strict()
910
+ .default({ proxy: true });
911
+
912
+ // The "Copy page" menu shown next to a page's title - copy the page's
913
+ // Markdown, view it, or open it in an AI assistant - and the .md copy of
914
+ // every page it relies on ([...slug].md.ts). On by default, with every
915
+ // option, like the MCP server. writedocs.json narrows or turns it off:
916
+ //
917
+ // (absent) or true every option
918
+ // ["copy", "claude"] only these, in the menu's own order
919
+ // (copy, view, chatgpt, claude, perplexity,
920
+ // mcp, cursor, vscode - the last three connect
921
+ // AI tools to the site's MCP server, and are
922
+ // left out when `mcp` is false)
923
+ // false (or []) no menu, and no .md routes
924
+ // { "openIn": [...] } the earlier form: copy and view, plus these
925
+ // assistants - still accepted
926
+ //
927
+ // Read it through contextMenuOptions() below - never test the raw value for
928
+ // truthiness: absent now means on.
929
+ export const CONTEXT_MENU_OPTIONS = ['copy', 'view', 'chatgpt', 'claude', 'perplexity', 'mcp', 'cursor', 'vscode'] as const;
930
+ export type ContextMenuOption = (typeof CONTEXT_MENU_OPTIONS)[number];
931
+ const ASSISTANT_OPTIONS = ['chatgpt', 'claude', 'perplexity'] as const;
932
+ /** The options that point at the site's MCP server - see `mcp` below. */
933
+ export const MCP_MENU_OPTIONS = ['mcp', 'cursor', 'vscode'] as const;
934
+
935
+ const contextMenuSchema = z.union([
936
+ z.boolean(),
937
+ z.array(z.enum(CONTEXT_MENU_OPTIONS)),
938
+ z
939
+ .object({
940
+ openIn: z.array(z.enum(ASSISTANT_OPTIONS)).optional(),
941
+ })
942
+ .strict(),
943
+ ]);
944
+
945
+ export type ContextMenuConfig = z.infer<typeof contextMenuSchema>;
946
+
947
+ /** The menu options a writedocs.json `contextMenu` value turns on, in menu
948
+ * order - [] when the menu is off. Takes the raw value too (link-check.js
949
+ * reads writedocs.json without the schema), so absent means every option.
950
+ * With `mcp: false` (no MCP server), the MCP options are left out. */
951
+ export function contextMenuOptions(value: unknown, { mcp = true }: { mcp?: boolean } = {}): ContextMenuOption[] {
952
+ const available = CONTEXT_MENU_OPTIONS.filter((option) => mcp || !(MCP_MENU_OPTIONS as readonly string[]).includes(option));
953
+ if (value === false) return [];
954
+ if (value === undefined || value === null || value === true) return [...available];
955
+ if (Array.isArray(value)) return available.filter((option) => value.includes(option));
956
+ if (typeof value === 'object') {
957
+ const openIn = (value as { openIn?: unknown }).openIn;
958
+ const assistants = Array.isArray(openIn) ? openIn : [...ASSISTANT_OPTIONS];
959
+ return CONTEXT_MENU_OPTIONS.filter((option) => option === 'copy' || option === 'view' || assistants.includes(option));
960
+ }
961
+ return [];
962
+ }
963
+
964
+ // One entry in writedocs.json's `redirects` array - wired almost directly into
965
+ // Astro's own `redirects` config option (astro.config.mjs), which is what
966
+ // actually generates the redirect pages. `permanent` is deliberately not
967
+ // part of this schema: with no server/adapter (this project always builds
968
+ // `output: 'static'` with none installed), Astro's own docs say a static
969
+ // redirect "does not support status codes" at all - it's always a client-
970
+ // side `<meta http-equiv="refresh">` page, full stop. Accepting a
971
+ // `permanent` field here that silently did nothing would be worse than
972
+ // not offering it.
973
+ const redirectSchema = z
974
+ .object({
975
+ source: z.string(),
976
+ destination: z.string(),
977
+ })
978
+ .strict();
979
+
980
+ export type RedirectConfig = z.infer<typeof redirectSchema>;
981
+
982
+ // A site-wide banner rendered above the topbar on every page (except
983
+ // `mode: blank`, which drops all site chrome including this - see
984
+ // BaseLayout.astro). Optional/undefined by default, same convention as
985
+ // `contextMenu` above - a site with no banner configured gets no banner
986
+ // markup at all, not an empty one.
987
+ const bannerSchema = z
988
+ .object({
989
+ content: z.string(),
990
+ // Persisted via localStorage once dismissed (see BaseLayout.astro's
991
+ // initBanner()) - a static site has no server-side session to track
992
+ // this against, so "dismissed" only ever means "dismissed in this
993
+ // browser". A banner without `dismissible` reappears on every visit,
994
+ // appropriate for something that should stay visible until the site
995
+ // author removes it from writedocs.json themselves (e.g. "this version is
996
+ // deprecated"), not something a reader can permanently clear.
997
+ dismissible: z.boolean().default(false),
998
+ type: z.enum(['info', 'warning', 'critical']).default('info'),
999
+ })
1000
+ .strict();
1001
+
1002
+ export type BannerConfig = z.infer<typeof bannerSchema>;
1003
+
1004
+ // Content for the custom 404 page (src/pages/404.astro) - Astro's own
1005
+ // file-based convention (a static build emits this as 404.html at the
1006
+ // site root; most static hosts pick it up automatically for unmatched
1007
+ // routes). Both fields are optional with hardcoded fallbacks in 404.astro
1008
+ // itself, so a site doesn't have to set either to get a reasonably
1009
+ // branded 404 page (still rendered inside the normal BaseLayout/topbar
1010
+ // chrome, just with placeholder content).
1011
+ const notFoundSchema = z
1012
+ .object({
1013
+ title: z.string().optional(),
1014
+ description: z.string().optional(),
1015
+ })
1016
+ .strict()
1017
+ .default({});
1018
+
1019
+ export type NotFoundConfig = z.infer<typeof notFoundSchema>;
1020
+
1021
+ // One <script> tag to inject - exactly one of `src` (an external/local
1022
+ // file, rendered as `<script src="...">`) or `content` (inline JS,
1023
+ // rendered via `<script is:inline set:html="...">`) has to be set, not
1024
+ // both and not neither - enforced by the `.refine()` below rather than
1025
+ // leaving both optional and silently rendering an empty tag if a site
1026
+ // author gets this wrong.
1027
+ const scriptEntrySchema = z
1028
+ .object({
1029
+ src: z.string().optional(),
1030
+ content: z.string().optional(),
1031
+ // With `integrations.consent` on, a script marked `true` loads only
1032
+ // once the reader accepts, like the analytics integrations. Without the
1033
+ // banner it loads as any other script.
1034
+ consent: z.boolean().optional(),
1035
+ })
1036
+ .strict()
1037
+ .refine((v) => (v.src ? !v.content : !!v.content), {
1038
+ message: 'Each scripts.head/scripts.body entry needs exactly one of "src" or "content", not both or neither.',
1039
+ });
1040
+
1041
+ export type ScriptEntry = z.infer<typeof scriptEntrySchema>;
1042
+
1043
+ // Raw third-party script injection - analytics snippets, chat widgets,
1044
+ // anything that needs a real <script> tag writedocs.json's own structured
1045
+ // fields (styles, integrations-style config, ...) don't have a dedicated
1046
+ // slot for yet. `head` renders right before </head>; `body` renders right
1047
+ // before </body> (after everything else has already loaded/hydrated -
1048
+ // see BaseLayout.astro), matching where a third-party script's own
1049
+ // install instructions usually say to put it.
1050
+ const scriptsSchema = z
1051
+ .object({
1052
+ head: z.array(scriptEntrySchema).default([]),
1053
+ body: z.array(scriptEntrySchema).default([]),
1054
+ })
1055
+ .strict()
1056
+ .default({ head: [], body: [] });
1057
+
1058
+ export type ScriptsConfig = z.infer<typeof scriptsSchema>;
1059
+
1060
+ // writedocs.json's `integrations` - a curated, high-value subset of analytics
1061
+ // providers, each getting its own minimal config object (just the id(s)
1062
+ // it actually needs) rather than requiring a site author to hand-write
1063
+ // the provider's own install snippet through the generic `scripts` field
1064
+ // above. This is deliberately its own thing, not built as sugar over
1065
+ // `scripts` the way the roadmap once implied it might be - most of these
1066
+ // providers' real snippets need `defer`/`async`/`data-*` attributes
1067
+ // ScriptEntry's plain `{ src?, content? }` shape has no way to express,
1068
+ // so BaseLayout.astro renders each provider with its own bespoke markup
1069
+ // instead of generating a ScriptEntry array to feed through the generic
1070
+ // renderer. Every snippet shape below was sourced from that provider's
1071
+ // own current official docs (fetched directly, not recalled from
1072
+ // training data) while building this feature - see
1073
+ // docs/dev/docs/integrations.mdx for links and dates.
1074
+ //
1075
+ // Every provider field is optional and independent - a site can turn on
1076
+ // any subset (including all of them at once, for a migration period) or
1077
+ // none. No "the" analytics field; a site picks whichever provider(s) it
1078
+ // actually uses.
1079
+
1080
+ const ga4IntegrationSchema = z
1081
+ .object({
1082
+ // A GA4 "Measurement ID", always shaped like "G-XXXXXXXXXX" - not
1083
+ // validated against that shape here, since Google could change the
1084
+ // prefix/length without this schema needing to track it.
1085
+ measurementId: z.string(),
1086
+ })
1087
+ .strict();
1088
+
1089
+ const googleTagManagerIntegrationSchema = z
1090
+ .object({
1091
+ // A GTM container id, shaped like "GTM-XXXXXXX".
1092
+ containerId: z.string(),
1093
+ })
1094
+ .strict();
1095
+
1096
+ const plausibleIntegrationSchema = z
1097
+ .object({
1098
+ domain: z.string(),
1099
+ // Plausible's own hosted script URL by default - override for a
1100
+ // self-hosted instance, a reverse-proxy path (Plausible's own
1101
+ // documented way to dodge ad-blockers), or one of Plausible's
1102
+ // documented script *extensions* (e.g.
1103
+ // "https://plausible.io/js/script.hash.outbound-links.js").
1104
+ src: z.string().default('https://plausible.io/js/script.js'),
1105
+ })
1106
+ .strict();
1107
+
1108
+ const fathomIntegrationSchema = z
1109
+ .object({
1110
+ // Fathom's own short "Site ID", not a full URL or measurement id.
1111
+ siteId: z.string(),
1112
+ })
1113
+ .strict();
1114
+
1115
+ const posthogIntegrationSchema = z
1116
+ .object({
1117
+ // PostHog calls this a "project API key" (starts with "phc_") in its
1118
+ // own docs - `apiKey` here rather than that exact name, matching this
1119
+ // schema's own plainer naming convention for the equivalent id on
1120
+ // every other provider above.
1121
+ apiKey: z.string(),
1122
+ // PostHog is region-sharded (US/EU) with no single universal default
1123
+ // - "https://us.i.posthog.com" is PostHog's own default for a new
1124
+ // project, but a site on their EU cloud (or a self-hosted instance)
1125
+ // must override this to the host shown in their own project
1126
+ // settings, or events silently go nowhere.
1127
+ apiHost: z.string().default('https://us.i.posthog.com'),
1128
+ })
1129
+ .strict();
1130
+
1131
+ const umamiIntegrationSchema = z
1132
+ .object({
1133
+ websiteId: z.string(),
1134
+ // Unlike Plausible/PostHog, Umami has no single hosted default that
1135
+ // works for most users - it's commonly self-hosted, and even Umami
1136
+ // Cloud users get a per-region script URL. Defaults to Umami Cloud's
1137
+ // own documented script URL, which only happens to be correct for a
1138
+ // Cloud user on that specific region; anyone self-hosting (the more
1139
+ // common case for this particular provider) must override it to
1140
+ // their own instance's own /script.js path.
1141
+ src: z.string().default('https://cloud.umami.is/script.js'),
1142
+ })
1143
+ .strict();
1144
+
1145
+ // AI chat over the site's own docs content, via a third-party provider
1146
+ // (DocsBot, currently the only one wired up) rather than a self-hosted
1147
+ // RAG pipeline - see the roadmap's own "AI chat over docs content" line
1148
+ // in docs/dev/docs/roadmap.mdx, which this fulfills via integration
1149
+ // rather than by building the retrieval/generation stack in-house.
1150
+ // Deliberately named `askAi` here, not `docsbot` - this is the
1151
+ // writedocs.json-facing, provider-neutral name for the feature (matching
1152
+ // the "Ask AI" label this kind of button/widget is conventionally
1153
+ // given in docs sites generally), independent of which vendor happens
1154
+ // to sit behind it today. `id` matches DocsBot's own embed config
1155
+ // field name exactly (`DocsBotAI.init({ id: 'teamId/botId' })`) - it's
1156
+ // a single opaque "teamId/botId" string DocsBot treats as one value,
1157
+ // not two separate ids, so this schema doesn't split it either.
1158
+ const askAiIntegrationSchema = z
1159
+ .object({
1160
+ id: z.string(),
1161
+ })
1162
+ .strict();
1163
+
1164
+ // A consent banner for the analytics integrations above: with it, none of
1165
+ // their scripts load until the reader accepts (see lib/consent.js and
1166
+ // ConsentBanner.astro). `true` uses the default texts; an object changes
1167
+ // them. The reader's answer is kept in the browser's localStorage.
1168
+ const consentSchema = z.union([
1169
+ z.boolean(),
1170
+ z
1171
+ .object({
1172
+ message: z.string().optional(),
1173
+ acceptLabel: z.string().optional(),
1174
+ declineLabel: z.string().optional(),
1175
+ // A link after the message - a privacy or cookie policy.
1176
+ policyUrl: z.string().optional(),
1177
+ policyLabel: z.string().optional(),
1178
+ })
1179
+ .strict(),
1180
+ ]);
1181
+
1182
+ const integrationsSchema = z
1183
+ .object({
1184
+ ga4: ga4IntegrationSchema.optional(),
1185
+ googleTagManager: googleTagManagerIntegrationSchema.optional(),
1186
+ plausible: plausibleIntegrationSchema.optional(),
1187
+ fathom: fathomIntegrationSchema.optional(),
1188
+ posthog: posthogIntegrationSchema.optional(),
1189
+ umami: umamiIntegrationSchema.optional(),
1190
+ askAi: askAiIntegrationSchema.optional(),
1191
+ consent: consentSchema.optional(),
1192
+ })
1193
+ .strict()
1194
+ .default({});
1195
+
1196
+ export type IntegrationsConfig = z.infer<typeof integrationsSchema>;
1197
+
1198
+ export const docsConfigSchema = z.object({
1199
+ name: z.string(),
1200
+ description: z.string().optional(),
1201
+ styles: stylesSchema,
1202
+ navigation: navigationSchema,
1203
+ // Platform name -> profile/page URL (e.g. `{ "github": "https://
1204
+ // github.com/...", "twitter": "https://twitter.com/..." }`), free-form
1205
+ // rather than an enum of known platforms - the key doubles as the icon
1206
+ // reference BaseLayout.astro's footer resolves via resolveIcon() below
1207
+ // (bare `"github"` -> `lucide:github`; use an explicit
1208
+ // `"simple-icons:whatever"` key instead when the bare lucide name isn't
1209
+ // right for a given platform). Rendered as a row of icon links in the
1210
+ // footer - see hasFooterContent/`.wd-footer-socials` in BaseLayout.astro.
1211
+ socials: z.record(z.string(), z.string()).default({}),
1212
+ topbar: z
1213
+ .object({ links: z.array(topbarLinkSchema).default([]) })
1214
+ .default({ links: [] }),
1215
+ // Columns of links below the page content - see footerSchema/
1216
+ // footerColumnSchema above. Renders alongside `socials` above (as a row
1217
+ // of icon links) in the same <footer> - see BaseLayout.astro.
1218
+ footer: footerSchema,
1219
+ api: apiSchema,
1220
+ // The site's own deployed domain, e.g. "docs.example.com" or
1221
+ // "https://docs.example.com" (the scheme is optional - resolveSiteUrl()
1222
+ // below normalizes either form to a full https:// origin). Powers three
1223
+ // things that all need an absolute origin to work: sitemap.xml
1224
+ // generation (astro.config.mjs only registers @astrojs/sitemap when this
1225
+ // is set - a sitemap of relative URLs isn't meaningful), the canonical
1226
+ // <link> and og:url/twitter meta tags (BaseLayout.astro), and resolving
1227
+ // a relative `seo.ogImage` into an absolute URL for social crawlers.
1228
+ // Left optional and simply skipped (with a log message, not an error) at
1229
+ // every one of those call sites when unset - most fixtures/local builds
1230
+ // have no real deployed domain yet.
1231
+ domain: z.string().optional(),
1232
+ // The path the site is served under on `domain`, like "/docs" for
1233
+ // empresa.com/docs (usually behind the customer's own proxy). Every
1234
+ // address the site makes starts with it, and the build writes the site to
1235
+ // dist/<basePath>/ - see src/lib/base-path.js. Absent, "" or "/": the site
1236
+ // at the root, exactly as without the field.
1237
+ basePath: z
1238
+ .string()
1239
+ .regex(BASE_PATH_FIELD_PATTERN, {
1240
+ message:
1241
+ '"basePath" must be a path like "/docs" or "/help/docs": it starts with "/", has no "/" at the end, and each part has only lowercase letters, digits, "-" and "_".',
1242
+ })
1243
+ .optional(),
1244
+ // Site-wide meta tag defaults - see seoFieldsSchema above. A page's own
1245
+ // frontmatter `seo` (content.config.ts's docsSchema) overrides these
1246
+ // field by field via mergeSeo(), rather than needing to repeat every
1247
+ // field on every page.
1248
+ seo: siteSeoFieldsSchema.default({}),
1249
+ // The "Copy page" menu - see contextMenuSchema above. Absent means on,
1250
+ // with every option; read it through contextMenuOptions().
1251
+ contextMenu: contextMenuSchema.optional(),
1252
+ // The site's MCP server - an AI tool connects to `/mcp` and searches and
1253
+ // reads the docs. On by default: `writedocs build` writes the page index
1254
+ // (mcp-index.json) and a Cloudflare-ready `_worker.js` into dist/ (see
1255
+ // src/cli/write-mcp-files.js). `false` leaves all of it out.
1256
+ mcp: z.boolean().default(true),
1257
+ // See redirectSchema above. Wired directly into Astro's own `redirects`
1258
+ // config option in astro.config.mjs.
1259
+ redirects: z.array(redirectSchema).default([]),
1260
+ // Site-wide `[[key]]` substitution values, applied to page prose text
1261
+ // at build time (see the remarkSubstituteVariables plugin wired into
1262
+ // astro.config.mjs) - e.g. `{ "productName": "Acme" }` lets every page
1263
+ // write `[[productName]]` once instead of hardcoding it everywhere.
1264
+ // Double square brackets, not the more familiar `{{key}}` - MDX
1265
+ // reserves single curly braces for embedded JS expressions, so
1266
+ // `{{productName}}` in an .mdx file parses as a JS object-literal
1267
+ // expression (`{productName}`, shorthand syntax) rather than literal
1268
+ // text, and throws `ReferenceError: productName is not defined` at
1269
+ // render time - see remarkSubstituteVariables' own comment in
1270
+ // mdx-substitute-variables.js for the full explanation. Deliberately a
1271
+ // flat string map, not typed values - this is text substitution into
1272
+ // prose, not a templating language.
1273
+ variables: z.record(z.string(), z.string()).default({}),
1274
+ // See bannerSchema above. Absent by default (no banner rendered).
1275
+ banner: bannerSchema.optional(),
1276
+ // See notFoundSchema above.
1277
+ notFound: notFoundSchema,
1278
+ // See scriptsSchema above.
1279
+ scripts: scriptsSchema,
1280
+ // See integrationsSchema above.
1281
+ integrations: integrationsSchema,
1282
+ });
1283
+
1284
+ export type DocsConfig = z.infer<typeof docsConfigSchema>;
1285
+
1286
+ // ---------------------------------------------------------------------
1287
+ // Ponto de entrada unico de validacao
1288
+ //
1289
+ // Existe pra que o gerador (`writedocs validate` e o `loadDocsConfig` que o
1290
+ // build usa) e a plataforma validem pelo MESMO codigo, com as MESMAS palavras -
1291
+ // o criterio de aceite do WD-066 e do WD-062. Se cada lado formatasse os erros
1292
+ // por conta propria, o cliente veria a plataforma aceitar um writedocs.json que
1293
+ // o build depois recusa, que e exatamente a classe de bug que a E11 existe pra
1294
+ // impedir.
1295
+ //
1296
+ // Recebe TEXTO CRU, e faz o JSON.parse por conta propria, por tres motivos:
1297
+ // 1. um JSON sintaticamente quebrado passa a ser um resultado de validacao
1298
+ // como qualquer outro, em vez de uma excecao solta do runtime;
1299
+ // 2. linha/coluna so existem no texto - e o WD-063 precisa reportar linha;
1300
+ // 3. do lado da plataforma, importProjectConfig ja tem os bytes crus em maos
1301
+ // antes de parsear, entao encaixa sem ginastica nenhuma.
1302
+ //
1303
+ // IMPORTANTE, e deliberado: as mensagens aqui sao as do Zod, VERBATIM. Melhorar
1304
+ // a linguagem delas e o WD-063, que precisa deste comportamento como ponto de
1305
+ // partida pra medir a melhora. Nada aqui reescreve, traduz ou embeleza mensagem.
1306
+ //
1307
+ // WD-315 - O TETO. O validateDocsConfig() devolve no maximo os primeiros
1308
+ // VALIDATION_ISSUE_LIMIT problemas, na ordem de sempre, e o total deles em
1309
+ // `issuesTotal`; o unknownRootKeyWarnings() faz o mesmo com os avisos. So os
1310
+ // que voltam sao localizados (linha/coluna) e humanizados - o resto e contado
1311
+ // e nada mais. O motivo: um writedocs.json de ~11 MB (o porte do maior
1312
+ // docs.json de cliente que ja vimos) com uma pagina errada em cada uma das 66
1313
+ // mil levava 169 s e ~1,2 GB so pra localizar os erros, e a plataforma valida
1314
+ // por esta mesma funcao dentro de um Worker de 128 MB. Ninguem le 66 mil
1315
+ // erros; quase sempre e o mesmo engano repetido, e os 100 primeiros mostram
1316
+ // qual. Ate o teto, o resultado e exatamente o de antes do teto: a mesma
1317
+ // lista, as mesmas mensagens e linhas (provado na rodada gerador/07 com o
1318
+ // corpus da plataforma). O numero e exportado pra que a plataforma grave o
1319
+ // mesmo tanto que o gerador mostra.
1320
+ //
1321
+ // WD-315 (07c) - PARAR CEDO. O teto cortava o custo de localizar, mas o Zod
1322
+ // ainda produzia todos os erros antes: 100 mil itens errados em 0,2 MB pediam
1323
+ // ~270 MB so no safeParse. Agora a validacao para de trabalhar depois de
1324
+ // VALIDATION_ISSUE_LIMIT + 1 erros - ver a secao "PARAR CEDO" mais abaixo, que
1325
+ // diz como, e por que isso nao muda nada ate o teto. Acima dele, o
1326
+ // `issuesTotal` deixa de ser exato: vira "pelo menos" (VALIDATION_ISSUE_LIMIT +
1327
+ // 1), com `issuesTruncated: true`. Para a lista inteira, `{ all: true }` (o
1328
+ // `writedocs validate --all`) valida tudo, sem parar, como antes.
1329
+ // ---------------------------------------------------------------------
1330
+
1331
+ /** WD-315: quantos problemas o validateDocsConfig() (e o
1332
+ * unknownRootKeyWarnings()) devolve, no maximo - os primeiros, na ordem de
1333
+ * sempre. O total vem em `issuesTotal`. */
1334
+ export const VALIDATION_ISSUE_LIMIT = 100;
1335
+
1336
+ /** `all: true` - a lista inteira, sem teto e sem parar (o `writedocs validate
1337
+ * --all`). Custa o que a validacao custava antes do WD-315: so pra quem pediu,
1338
+ * na propria maquina. */
1339
+ export type ValidationOptions = { all?: boolean };
1340
+
1341
+ /** Um problema encontrado na configuracao. `path` e o caminho do campo em
1342
+ * notacao de ponto (`navigation.tabs.0.label`), ou `(root)` quando o problema e
1343
+ * do documento inteiro - o mesmo texto que a mensagem de erro do build ja
1344
+ * imprime hoje. `line`/`column` so vem quando da pra saber (hoje: erro de JSON;
1345
+ * no WD-063, tambem para erros de schema). */
1346
+ export type ValidationIssue = {
1347
+ path: string;
1348
+ message: string;
1349
+ /** Codigo do Zod (`invalid_type`, `unrecognized_keys`, ...) ou `invalid_json`. */
1350
+ code?: string;
1351
+ line?: number;
1352
+ column?: number;
1353
+ /** WD-063: a mesma coisa que `message`, dita para gente. ADICIONAL, nunca
1354
+ * substituto - `message` continua sendo o texto do Zod verbatim, que e o que
1355
+ * o `writedocs build` imprime e o que o WD-062 grava em `validation_issues`.
1356
+ * Quem exibe escolhe qual dos dois mostrar. */
1357
+ humanMessage?: string;
1358
+ /** O que fazer a respeito, quando da pra dizer algo concreto. */
1359
+ suggestion?: string;
1360
+ /** Chave ESTAVEL de documentacao (`config.styles`), nunca uma URL: uma URL
1361
+ * cravada num pacote npm fica quebrada em toda instalacao ate a proxima
1362
+ * release, e o mesmo erro e exibido pela CLI e pelo dashboard, que podem
1363
+ * querer destinos diferentes. O mapa chave -> URL mora do lado de quem
1364
+ * renderiza. */
1365
+ docKey?: string;
1366
+ };
1367
+
1368
+ /** Sucesso carrega os dados ja validados (com os defaults do schema aplicados);
1369
+ * falha carrega os problemas e diz de que tipo ela foi. `parseError` so aparece
1370
+ * quando o JSON nao pode nem ser parseado, e existe para o chamador que quiser
1371
+ * relancar exatamente o erro original (e o que o loadDocsConfig faz, pra nao
1372
+ * mudar uma virgula do que o `writedocs build` ja imprime hoje).
1373
+ *
1374
+ * `issues` traz no maximo VALIDATION_ISSUE_LIMIT problemas. `issuesTotal`:
1375
+ * quantos ha ao todo (0 num config valido, 1 num JSON quebrado) quando
1376
+ * `issuesTruncated` e false; quando e true, a validacao parou depois do teto, e
1377
+ * `issuesTotal` e so um minimo (VALIDATION_ISSUE_LIMIT + 1). Com `{ all: true }`
1378
+ * nao ha teto: `issues` traz todos, e `issuesTruncated` e sempre false. */
1379
+ export type ValidationResult =
1380
+ | { ok: true; data: DocsConfig; issues: ValidationIssue[]; issuesTotal: number; issuesTruncated: boolean }
1381
+ | {
1382
+ ok: false;
1383
+ data: null;
1384
+ kind: 'invalid_json' | 'schema';
1385
+ issues: ValidationIssue[];
1386
+ issuesTotal: number;
1387
+ issuesTruncated: boolean;
1388
+ parseError?: SyntaxError;
1389
+ };
1390
+
1391
+ /** "at position 22 (line 1 column 23)" -> { line: 1, column: 23 }.
1392
+ * O formato da mensagem de erro do JSON.parse e do V8, nao do padrao, entao
1393
+ * isto e melhor-esforco: se a mensagem nao trouxer posicao, devolve null e o
1394
+ * problema simplesmente fica sem linha. */
1395
+ function positionFromJsonError(message: string, rawText: string): { line: number; column: number } | null {
1396
+ const comLinha = message.match(/line (\d+) column (\d+)/);
1397
+ if (comLinha) return { line: Number(comLinha[1]), column: Number(comLinha[2]) };
1398
+ const comPosicao = message.match(/position (\d+)/);
1399
+ if (comPosicao) {
1400
+ const pos = Math.min(Number(comPosicao[1]), rawText.length);
1401
+ const antes = rawText.slice(0, pos);
1402
+ const line = antes.split('\n').length;
1403
+ return { line, column: pos - antes.lastIndexOf('\n') };
1404
+ }
1405
+ return null;
1406
+ }
1407
+
1408
+ /** O corpo da mensagem de erro, uma linha por problema - exatamente o formato
1409
+ * que o `writedocs build` imprime desde sempre (` - campo: mensagem`). Fica
1410
+ * aqui, e nao em cada chamador, pra que CLI e plataforma nao possam divergir.
1411
+ *
1412
+ * NAO mudou no WD-063, de proposito: continua imprimindo `message` (o texto do
1413
+ * Zod). O que melhorou foi o CONTEUDO dos issues - a uniao desembrulhada faz o
1414
+ * `path` apontar pro campo real em vez de parar em `navigation`. Quem quiser a
1415
+ * versao com frase humana e linha usa formatValidationIssuesDetailed.
1416
+ *
1417
+ * `total` e `truncated` (o `issuesTotal` e o `issuesTruncated` do resultado):
1418
+ * quando ha mais problemas do que os listados, uma ultima linha diz quantos
1419
+ * ficaram de fora, ou que ha mais (WD-315). */
1420
+ export function formatValidationIssues(
1421
+ issues: ValidationIssue[],
1422
+ { total, truncated }: { total?: number; truncated?: boolean } = {}
1423
+ ): string {
1424
+ const linhas = issues.map((i) => ` - ${i.path}: ${i.message}`);
1425
+ const resto = moreIssuesLine(issues.length, total, truncated);
1426
+ if (resto) linhas.push(` ${resto}`);
1427
+ return linhas.join('\n');
1428
+ }
1429
+
1430
+ /** A linha do que ficou de fora, ou null quando nada ficou. Uma frase so pros
1431
+ * dois formatadores (e pra plataforma, se ela quiser), como o resto das
1432
+ * palavras deste modulo:
1433
+ * - `truncated` (a validacao parou no teto): "...and more - run "writedocs
1434
+ * validate --all" for the full list." - o quanto mais nao se sabe;
1435
+ * - um total exato maior que a lista (os avisos, sempre exatos): "...and 50
1436
+ * more - only the first 100 are listed.". */
1437
+ export function moreIssuesLine(listados: number, total: number | undefined, truncated = false): string | null {
1438
+ if (truncated) return '...and more - run "writedocs validate --all" for the full list.';
1439
+ if (total === undefined || total <= listados) return null;
1440
+ return `...and ${total - listados} more - only the first ${listados} are listed.`;
1441
+ }
1442
+
1443
+ /** A versao longa, para quem tem uma tela inteira (a CLI hoje, o dashboard do
1444
+ * WD-065 se quiser): caminho, linha, frase humana, sugestao, e a mensagem do
1445
+ * Zod por ultimo, entre parenteses, pra quem precisa do texto exato.
1446
+ *
1447
+ * Mora aqui pelo mesmo motivo que a irma curta: se cada consumidor montasse a
1448
+ * sua, a CLI e a plataforma divergiriam na primeira mudanca - que e exatamente
1449
+ * o que o AC do WD-066 proibe. `fileName` so entra na referencia de linha.
1450
+ * `total`/`truncated`: como no formatValidationIssues, a linha do que ficou de
1451
+ * fora. */
1452
+ export function formatValidationIssuesDetailed(
1453
+ issues: ValidationIssue[],
1454
+ { fileName = 'writedocs.json', total, truncated }: { fileName?: string; total?: number; truncated?: boolean } = {}
1455
+ ): string {
1456
+ const resto = moreIssuesLine(issues.length, total, truncated);
1457
+ return issues
1458
+ .map((i) => {
1459
+ const temCampo = i.path !== '(root)';
1460
+ const local = i.line ? `${fileName}:${i.line}` : i.path;
1461
+ const linhas = [` ${local}${i.line && temCampo ? ` (${i.path})` : ''}`];
1462
+ linhas.push(` ${i.humanMessage ?? i.message}`);
1463
+ if (i.suggestion) linhas.push(` ${i.suggestion}`);
1464
+ if (i.humanMessage && i.message !== i.humanMessage) linhas.push(` (${i.message})`);
1465
+ return linhas.join('\n');
1466
+ })
1467
+ .concat(resto ? [` ${resto}`] : [])
1468
+ .join('\n\n');
1469
+ }
1470
+
1471
+ // ---------------------------------------------------------------------
1472
+ // WD-063 — do issue do Zod para "onde esta o erro, e o que fazer"
1473
+ //
1474
+ // Tres transformacoes, nesta ordem:
1475
+ // 1. desembrulhar `invalid_union` (senao todo erro dentro da navigation vira
1476
+ // `navigation: "Invalid input"`, que e inutil num arquivo de 10 KB);
1477
+ // 2. achar a linha no texto, pelo caminho ja desembrulhado;
1478
+ // 3. escrever a frase humana, a sugestao e a docKey - POR CODIGO do Zod, nao
1479
+ // por campo: um mapa por campo teria 17 entradas so na raiz e centenas no
1480
+ // total, e envelheceria a cada campo novo do schema.
1481
+ // ---------------------------------------------------------------------
1482
+
1483
+ /** Chaves que a raiz aceita sem ser campo do schema, e que por isso NAO devem
1484
+ * gerar aviso de chave desconhecida. Deliberadamente minuscula: a raiz nao e
1485
+ * `.strict()` justamente pra nao quebrar configs existentes, e `$schema` foi um
1486
+ * dos argumentos dessa decisao - avisar sobre ele contradiria o que o protegeu.
1487
+ * Se esta lista passar de dois ou tres nomes, o problema e outro e a raiz
1488
+ * precisa de outra conversa. */
1489
+ export const ROOT_ALLOWED_EXTRA_KEYS: readonly string[] = Object.freeze(['$schema']);
1490
+
1491
+ type IssueCru = {
1492
+ code?: string;
1493
+ path?: (string | number)[];
1494
+ message: string;
1495
+ expected?: string;
1496
+ values?: unknown[];
1497
+ keys?: string[];
1498
+ minimum?: number;
1499
+ maximum?: number;
1500
+ origin?: string;
1501
+ format?: string;
1502
+ errors?: unknown[];
1503
+ unionErrors?: unknown[];
1504
+ /** WD-315 (07c): este issue nao e um erro, e o resumo de uma lista validada
1505
+ * "contando sem guardar" - ver a secao PARAR CEDO. */
1506
+ wdLista?: ResumoDeLista;
1507
+ };
1508
+
1509
+ type IssuePlano = IssueCru & { caminho: (string | number)[] };
1510
+
1511
+ function issuesDoRamo(ramo: unknown): IssueCru[] {
1512
+ if (Array.isArray(ramo)) return ramo as IssueCru[];
1513
+ const comIssues = ramo as { issues?: IssueCru[] };
1514
+ return comIssues?.issues ?? [];
1515
+ }
1516
+
1517
+ /** Os ramos de um `invalid_union`, ou null se o issue nao for uma uniao com
1518
+ * ramos (uniao sem `errors` fica como esta - ver humanizar). */
1519
+ function ramosDaUniao(issue: IssueCru): unknown[] | null {
1520
+ const ramos = issue.code === 'invalid_union' ? issue.errors ?? issue.unionErrors : null;
1521
+ return Array.isArray(ramos) && ramos.length > 0 ? ramos : null;
1522
+ }
1523
+
1524
+ /** O que a pontuacao de um ramo (melhorRamo) precisa saber do plano ACHATADO
1525
+ * dele: quantos issues o plano tem (`n`) e a maior profundidade efetiva entre
1526
+ * eles (`maior`: o comprimento do caminho relativo ao ramo, +1 para
1527
+ * `unrecognized_keys`; -Infinity num plano vazio). */
1528
+ type Resumo = { n: number; maior: number };
1529
+
1530
+ /** O resumo de um ramo, memoizado por identidade do ramo.
1531
+ *
1532
+ * A memoizacao nao e otimizacao, e o que torna o achatamento viavel. Pontuar um
1533
+ * ramo exige desembrulhar as unioes DENTRO dele, e cada uma dessas tem os seus
1534
+ * proprios ramos - sem cache, a pontuacao visita o mesmo sub-ramo uma vez por
1535
+ * caminho que leva ate ele, o que e exponencial na profundidade do aninhamento.
1536
+ * Medido com grupos aninhados e um erro no fundo: 3,7 ms com 4 niveis, 281 ms
1537
+ * com 8, 69 SEGUNDOS com 12. Com o cache, os mesmos casos ficam em 0,2 ms,
1538
+ * porque cada no da arvore de erro do Zod e resumido uma vez so.
1539
+ *
1540
+ * Se alguem remover este cache por parecer supérfluo, o `writedocs validate`
1541
+ * passa a travar em configs profundas. Nao remova.
1542
+ *
1543
+ * WD-315, tres mudancas:
1544
+ * - o cache guardava o plano achatado inteiro de cada ramo de cada uniao, so
1545
+ * pra contar os issues e medir a profundidade - com 66 mil erros, a mesma
1546
+ * memoria que o Zod gasta pra produzi-los, de novo. O resumo e a mesma conta
1547
+ * sem montar o plano: n e a soma, e a profundidade o maximo, sobre os issues
1548
+ * do ramo, descendo pelo ramo escolhido de cada uniao dentro dele;
1549
+ * - era um WeakMap do modulo, e agora e um Map por chamada do
1550
+ * validateDocsConfig() (`resumos`), que some com ela. No Node 22 um WeakMap
1551
+ * com milhoes de chaves fica lento demais: 3 milhoes de chaves levam 10,8 s
1552
+ * num WeakMap e 0,8 s num Map (no Node 24, 0,9 s), e um writedocs.json de 2 MB
1553
+ * com um milhao de erros passava de 45 s so nisso;
1554
+ * - so entra no cache o ramo que tem uniao dentro, que e o que pode ser
1555
+ * revisitado. Um ramo sem uniao e recontado (uma passada pelos issues dele),
1556
+ * e o cache fica do tamanho das unioes aninhadas, nao do numero de erros. */
1557
+ function resumoDoRamo(ramo: unknown, resumos: Map<object, Resumo>): Resumo {
1558
+ const memoizavel = typeof ramo === 'object' && ramo !== null;
1559
+ if (memoizavel) {
1560
+ const memoizado = resumos.get(ramo);
1561
+ if (memoizado) return memoizado;
1562
+ }
1563
+ let n = 0;
1564
+ let maior = -Infinity;
1565
+ let temUniao = false;
1566
+ for (const issue of issuesDoRamo(ramo)) {
1567
+ const passos = issue.path?.length ?? 0;
1568
+ // WD-315 (07c): uma lista resumida conta com o que os itens dela dariam.
1569
+ const lista = issue.wdLista;
1570
+ if (lista) {
1571
+ temUniao = true;
1572
+ n += lista.n;
1573
+ if (lista.n > 0 && passos + lista.maior > maior) maior = passos + lista.maior;
1574
+ continue;
1575
+ }
1576
+ const ramos = ramosDaUniao(issue);
1577
+ if (ramos) {
1578
+ temUniao = true;
1579
+ const escolhido = resumoDoRamo(melhorRamo(ramos, resumos), resumos);
1580
+ n += escolhido.n;
1581
+ if (escolhido.n > 0 && passos + escolhido.maior > maior) maior = passos + escolhido.maior;
1582
+ } else {
1583
+ n += 1;
1584
+ const p = passos + (issue.code === 'unrecognized_keys' ? 1 : 0);
1585
+ if (p > maior) maior = p;
1586
+ }
1587
+ }
1588
+ const resumo = { n, maior };
1589
+ if (memoizavel && temUniao) resumos.set(ramo, resumo);
1590
+ return resumo;
1591
+ }
1592
+
1593
+ /** Escolhe qual ramo de uma uniao o cliente PROVAVELMENTE quis.
1594
+ *
1595
+ * Criterio: caminho mais fundo primeiro; empate resolvido por menos issues. A
1596
+ * intuicao e a do Gabriel na spec - o ramo certo e o que nao reclama da chave
1597
+ * que o cliente usou -, e a profundidade importa porque um ramo que chegou
1598
+ * fundo antes de falhar (`products.0.product`) reconheceu a forma, enquanto um
1599
+ * que falha na raiz (`expected array, received object`) so recusou o shape.
1600
+ *
1601
+ * DUAS CORRECOES sobre a primeira versao (WD-063), as duas medidas contra o
1602
+ * `00-kitchen-sink` real - ver o relato de revisao 43:
1603
+ *
1604
+ * 1. PONTUA O RAMO ACHATADO, nao a lista crua. Um ramo que e ele proprio uma
1605
+ * uniao aparece como UM issue (`invalid_union`) no caminho vazio - ou seja,
1606
+ * com a MENOR contagem e a MENOR profundidade possiveis, sem que isso diga
1607
+ * nada sobre o quanto ele reconheceu. Era o caso mais comum que existe: um
1608
+ * item de `pages` e `string | grupo | link`, e o grupo e outra uniao, entao
1609
+ * todo erro estrutural dentro de um grupo empatava com o ramo `string` e
1610
+ * perdia pela ordem de declaracao. O cliente que escrevia
1611
+ * `{ "group": "G", "pages": 42 }` recebia "expected string, received
1612
+ * object" - conselho errado, nao so inutil. Achatando primeiro, o mesmo caso
1613
+ * vira `pages.0.pages: expected array, received number`. (Desde o WD-315 o
1614
+ * plano achatado nao e montado: resumoDoRamo faz a mesma conta.)
1615
+ *
1616
+ * 2. PROFUNDIDADE EFETIVA: `unrecognized_keys` reporta no caminho do PAI, com a
1617
+ * chave ofensora em `keys`, entao a profundidade dele sai subestimada em 1.
1618
+ * Sem a correcao, um ramo que identificou a chave errada perde para um que
1619
+ * so exigiu um campo ausente. (`validateDocsConfig` ja fazia a mesma conta
1620
+ * para achar a LINHA; aqui ela entra tambem na pontuacao.)
1621
+ *
1622
+ * Medido sobre as 60 folhas da `navigation` do `00-kitchen-sink`, trocando o
1623
+ * tipo de cada uma: a versao anterior apontava o campo exato em 42/60 e PARAVA
1624
+ * RASO em 18/60 (sempre os mesmos 18: os que ficam sob um `pages`); esta aponta
1625
+ * 60/60 para valor escalar errado e nunca para raso. Para um objeto vazio ou
1626
+ * parcial no lugar de uma pagina, as duas ficam tecnicamente empatadas (41
1627
+ * contra 42): a anterior diz "expected string", esta lista os campos que
1628
+ * faltam para ser um grupo. E o custo aceito desta versao, e substitui o antigo
1629
+ * (`tabs` e `products` escritos juntos, que agora sai como
1630
+ * `Unrecognized key: "products"`).
1631
+ *
1632
+ * EMPATE TOTAL (mesma profundidade E mesmo numero de issues): vence o ramo
1633
+ * declarado primeiro no schema - a varredura so troca de ramo diante de um
1634
+ * ESTRITAMENTE melhor (era um `sort` estavel e o [0], que da o mesmo; quem
1635
+ * trocar o `>`/`<` por `>=`/`<=` faz o desempate virar o ultimo). Duas razoes
1636
+ * para "o primeiro" em vez de "todos os empatados":
1637
+ * - um engano do cliente tem que virar UMA mensagem. Emitir os 5 ramos
1638
+ * empatados de um `"navigation": {}` produz cinco exigencias que se
1639
+ * contradizem ("tabs e obrigatorio", "versions e obrigatorio", ...);
1640
+ * - determinismo: a mesma config sempre da a mesma mensagem. Um palpite
1641
+ * instavel seria pior que um palpite ruim.
1642
+ * E nada se perde no palpite errado: `message` continua sendo o texto do Zod. */
1643
+ function melhorRamo(ramos: unknown[], resumos: Map<object, Resumo>): unknown {
1644
+ let melhor = ramos[0];
1645
+ const primeiro = resumoDoRamo(melhor, resumos);
1646
+ let profundidade = Math.max(0, primeiro.maior);
1647
+ let n = primeiro.n;
1648
+ for (let i = 1; i < ramos.length; i++) {
1649
+ const resumo = resumoDoRamo(ramos[i], resumos);
1650
+ const p = Math.max(0, resumo.maior);
1651
+ if (p > profundidade || (p === profundidade && resumo.n < n)) {
1652
+ melhor = ramos[i];
1653
+ profundidade = p;
1654
+ n = resumo.n;
1655
+ }
1656
+ }
1657
+ return melhor;
1658
+ }
1659
+
1660
+ /** Desembrulha `invalid_union` recursivamente - o ramo escolhido normalmente e
1661
+ * outra uniao (cada produto da navigation e, por sua vez, uma uniao de formas),
1662
+ * entao para so quando chega num erro concreto. Sem recursao, o
1663
+ * `navigation.products.0` para em "Invalid input" de novo, um nivel abaixo.
1664
+ *
1665
+ * WD-315: um gerador, que entrega cada erro concreto (o issue e o caminho
1666
+ * inteiro dele) na ordem de sempre, em vez de montar a lista: quem chama guarda
1667
+ * os primeiros VALIDATION_ISSUE_LIMIT e so conta o resto. Montada, a lista de
1668
+ * um writedocs.json com um milhao de erros (2 MB) era mais memoria do que o
1669
+ * proprio Zod gasta. (E sem `push(...lista)`: o spread virava argumentos de
1670
+ * chamada e estourava a pilha com ~150 mil issues numa uniao.) `resumos`: o
1671
+ * cache da pontuacao (resumoDoRamo), um por chamada do validateDocsConfig().
1672
+ *
1673
+ * WD-315 (07c): uma lista resumida (`wdLista`) e revalidada aqui, item a item,
1674
+ * so quando o fluxo chega nela - e so ate quem consome parar de pedir. */
1675
+ function* desembrulharUnioes(
1676
+ issues: IssueCru[],
1677
+ resumos: Map<object, Resumo>,
1678
+ prefixo: (string | number)[] = []
1679
+ ): Generator<[IssueCru, (string | number)[]]> {
1680
+ for (const issue of issues) {
1681
+ const caminho = [...prefixo, ...(issue.path ?? [])];
1682
+ if (issue.wdLista) {
1683
+ yield* itensDaLista(issue.wdLista, resumos, caminho);
1684
+ continue;
1685
+ }
1686
+ const ramos = ramosDaUniao(issue);
1687
+ if (ramos) yield* desembrulharUnioes(issuesDoRamo(melhorRamo(ramos, resumos)), resumos, caminho);
1688
+ else yield [issue, caminho];
1689
+ }
1690
+ }
1691
+
1692
+ const LISTAS_DE_CONTAINER = ['tabs', 'versions', 'languages', 'dropdowns', 'products'] as const;
1693
+ const ITENS_DE_CONTAINER: Record<string, { lista: string; nome: string }> = {
1694
+ tab: { lista: 'tabs', nome: 'A tab' },
1695
+ version: { lista: 'versions', nome: 'A version' },
1696
+ language: { lista: 'languages', nome: 'A language' },
1697
+ dropdown: { lista: 'dropdowns', nome: 'A dropdown' },
1698
+ product: { lista: 'products', nome: 'A product' },
1699
+ };
1700
+
1701
+ /** Um container (`{ "tabs": [...] }`, ou um item como `{ "tab": "API", ... }`)
1702
+ * dentro de uma lista de paginas - o `pages` de um grupo, de uma tab etc., ou
1703
+ * a `navigation` em forma de lista. O Zod tenta os tres formatos de item
1704
+ * (pagina, grupo, link) e reclama de cada um: "group is required", "pages is
1705
+ * required", "tabs is not an option" - tres erros, nenhum dizendo o que houve.
1706
+ * Aqui eles viram UM, no item, dizendo onde o container pode ficar.
1707
+ *
1708
+ * Um gerador, como o desembrulharUnioes que o alimenta (WD-315): entrega cada
1709
+ * issue final na ordem, e so guarda as chaves dos containers ja vistos. */
1710
+ function* containersEmPaginas(issues: Iterable<[IssueCru, (string | number)[]]>, raiz: unknown): Generator<IssuePlano> {
1711
+ const vistos = new Set<string>();
1712
+ for (const [issue, caminho] of issues) {
1713
+ const achado = containerEmPaginas(caminho, raiz);
1714
+ if (!achado) {
1715
+ yield { ...issue, caminho };
1716
+ continue;
1717
+ }
1718
+ const chave = achado.caminho.join('.');
1719
+ if (vistos.has(chave)) continue;
1720
+ vistos.add(chave);
1721
+ yield { ...issue, code: 'custom', caminho: achado.caminho, message: achado.mensagem, keys: undefined };
1722
+ }
1723
+ }
1724
+
1725
+ function containerEmPaginas(caminho: (string | number)[], raiz: unknown): { caminho: (string | number)[]; mensagem: string } | null {
1726
+ for (let k = 1; k < caminho.length; k++) {
1727
+ if (typeof caminho[k] !== 'number') continue;
1728
+ const naRaiz = k === 1 && caminho[0] === 'navigation';
1729
+ if (!naRaiz && caminho[k - 1] !== 'pages') continue;
1730
+ const item = valorEm(raiz, caminho.slice(0, k + 1));
1731
+ if (!item || typeof item !== 'object' || Array.isArray(item) || 'group' in item) continue;
1732
+ const lugar = naRaiz ? 'the navigation list' : 'a "pages" list';
1733
+ const rotulo = (texto: string) => (naRaiz ? 'The navigation list' : 'A "pages" list') + ` holds pages, groups and links only. ${texto}`;
1734
+ const lista = LISTAS_DE_CONTAINER.find((l) => l in item);
1735
+ if (lista) {
1736
+ return {
1737
+ caminho: caminho.slice(0, k + 1),
1738
+ mensagem: `"${lista}" can't go inside ${lugar}. ` + rotulo(
1739
+ naRaiz
1740
+ ? `To use ${lista}, make "navigation" an object: "navigation": { "${lista}": [ ... ] }, with the groups inside each of them.`
1741
+ : `Put "${lista}" on "navigation" itself, or on a tab, version, language, dropdown or product in place of its "pages".`
1742
+ ),
1743
+ };
1744
+ }
1745
+ const tipo = Object.keys(ITENS_DE_CONTAINER).find((t) => t in item);
1746
+ if (tipo) {
1747
+ const { lista: dela, nome } = ITENS_DE_CONTAINER[tipo];
1748
+ const nomeDoItem = (item as Record<string, unknown>)[tipo];
1749
+ return {
1750
+ caminho: caminho.slice(0, k + 1),
1751
+ mensagem: `${nome}${typeof nomeDoItem === 'string' ? ` ("${nomeDoItem}")` : ''} can't go inside ${lugar}. ` + rotulo(
1752
+ naRaiz ? `${nome} goes in a "${dela}" list: "navigation": { "${dela}": [ ... ] }.` : `${nome} goes in a "${dela}" list.`
1753
+ ),
1754
+ };
1755
+ }
1756
+ }
1757
+ return null;
1758
+ }
1759
+
1760
+ // ---------------------------------------------------------------------
1761
+ // WD-315 (07c) - PARAR CEDO
1762
+ //
1763
+ // O Zod nao tem "pare no N-esimo erro": o safeParse produz todos, e o custo e
1764
+ // por erro (~2 KB cada; 100 mil itens errados em 0,2 MB pediam ~270 MB). Por
1765
+ // isso, durante o validateDocsConfig() sem `all`, as listas (z.array) e os
1766
+ // registros (z.record) do schema sao validados por estas funcoes em vez das do
1767
+ // Zod, item a item, e param de trabalhar depois de VALIDATION_ISSUE_LIMIT + 1
1768
+ // itens errados. Fora dessa chamada (o `all`, ou o docsConfigSchema.safeParse()
1769
+ // de qualquer outro lugar) o Zod valida como sempre - nada no schema muda, e o
1770
+ // writedocs.schema.json, que sai dele, tambem nao.
1771
+ //
1772
+ // O PROBLEMA de parar: o desembrulho das unioes (WD-063) escolhe o ramo pela
1773
+ // profundidade e, no empate, pelo NUMERO de erros do ramo inteiro. Parar no
1774
+ // meio de uma lista pode mudar a escolha - e o erro mostrado. Um contador por
1775
+ // chamada, parando toda lista, mudava a saida mesmo abaixo de 100 erros: numa
1776
+ // tab com `pages` E `versions` (60 itens errados em cada), os erros contados no
1777
+ // ramo descartado gastavam o limite e o resto do arquivo deixava de ser
1778
+ // validado. Por isso tres modos, decididos pelo objeto em volta da lista:
1779
+ //
1780
+ // - PARAR (o normal): a lista para quando o limite acaba. So e seguro porque,
1781
+ // num objeto com no maximo UMA das CHAVES_DE_RAMO, o ramo que desce numa
1782
+ // lista com um item errado vence sempre pela profundidade (>= 2, contra no
1783
+ // maximo 1 dos outros ramos, que so reclamam da chave que falta ou que
1784
+ // sobra) - entao contar menos erros nele nao muda escolha nenhuma, e todo
1785
+ // item errado contado vira pelo menos um erro na saida, ANTES do ponto onde
1786
+ // a validacao parou. Conferido uniao por uniao do schema: navigation, os
1787
+ // itens de tabs/versions/languages/dropdowns/products, os itens de `pages`
1788
+ // (pagina, grupo, link) e o contextMenu. O `global` da navigation e
1789
+ // compartilhado por todas as opcoes, e o Zod (o memoizer dele) valida o
1790
+ // mesmo objeto uma vez so por chamada, entao ele sai igual em todas.
1791
+ // - CONTAR (um objeto "disputado", com duas ou mais CHAVES_DE_RAMO - uma tab
1792
+ // com `pages` e `versions`, um grupo com `pages` e `openapi`, a navigation
1793
+ // com `global` e `tabs`): ai a escolha depende da contagem inteira, entao a
1794
+ // lista e validada ate o fim - mas sem guardar os erros. Cada item errado
1795
+ // vira so o resumo que o resumoDoRamo precisaria dele, e a lista devolve um
1796
+ // unico "issue" de resumo (`wdLista`). Quando o fluxo de saida chega nele,
1797
+ // itensDaLista revalida os itens, um a um, so ate quem consome parar.
1798
+ // Memoria pequena; o tempo continua proporcional a lista.
1799
+ // - PULAR (um container dentro de uma lista de paginas, que o
1800
+ // containersEmPaginas resume num erro so): nada dentro dele aparece na
1801
+ // saida, entao as listas de dentro nao sao validadas.
1802
+ //
1803
+ // O modo de uma lista e o do objeto disputado ou recolhido mais externo em
1804
+ // volta dela (`regioes`). Dentro de uma regiao, um item errado nao conta pro
1805
+ // limite - so os das listas em PARAR contam, e so os "folha" (um item que erra
1806
+ // porque uma lista de dentro errou ja foi contado la).
1807
+ //
1808
+ // Prova (rodada gerador/07c): o corpus da plataforma e os casos das rodadas 06
1809
+ // e 07 saem iguais ate 100 erros, e com os mesmos 100 primeiros acima disso; e
1810
+ // scripts/validation-stop.test.js compara, em centenas de configs montadas de
1811
+ // proposito (as disputadas inclusive), o resultado com o de `{ all: true }`.
1812
+ // ---------------------------------------------------------------------
1813
+
1814
+ /** O resumo de uma lista validada no modo CONTAR: o que os itens errados dela
1815
+ * dariam ao resumoDoRamo (n e a maior profundidade, ja com o indice do item),
1816
+ * e o que itensDaLista precisa pra revalida-los. */
1817
+ type ResumoDeLista = { n: number; maior: number; entrada: unknown[]; elemento: { safeParse: (v: unknown) => { success: boolean; error?: { issues: unknown[] } } } };
1818
+
1819
+ type Regiao = 'contar' | 'pular';
1820
+
1821
+ /** O estado de UMA chamada do validateDocsConfig() sem `all`; null fora dela, e
1822
+ * entao as listas validam pelo Zod, como sempre. `contados`: itens errados nas
1823
+ * listas em PARAR; `esgotado`: passou de VALIDATION_ISSUE_LIMIT. */
1824
+ let corte: { contados: number; esgotado: boolean; regioes: Regiao[] } | null = null;
1825
+
1826
+ /** As chaves que escolhem o ramo de uma uniao com listas: o filho de um
1827
+ * container (withChildren), o `openapi` de um grupo, o `global` da navigation. */
1828
+ const CHAVES_DE_RAMO = ['pages', 'tabs', 'versions', 'languages', 'dropdowns', 'products', 'href', 'openapi', 'global'];
1829
+
1830
+ function disputado(objeto: object): boolean {
1831
+ let achadas = 0;
1832
+ for (const chave of CHAVES_DE_RAMO) if (chave in objeto && ++achadas >= 2) return true;
1833
+ return false;
1834
+ }
1835
+
1836
+ /** O mesmo teste do containerEmPaginas: um objeto numa lista de paginas que
1837
+ * nao e grupo e tem cara de container vira um erro so. */
1838
+ function recolhido(objeto: object): boolean {
1839
+ return !('group' in objeto) && (LISTAS_DE_CONTAINER.some((l) => l in objeto) || Object.keys(ITENS_DE_CONTAINER).some((t) => t in objeto));
1840
+ }
1841
+
1842
+ type Payload = { value: unknown; issues: IssueCru[]; aborted?: boolean };
1843
+ type Interno = { _zod: { def: any; parse: Function; run: Function; innerType?: unknown } };
1844
+ type ComCorte = (original: Function, schema: Interno, payload: Payload, ctx: unknown) => Payload;
1845
+
1846
+ function ehObjeto(v: unknown): v is Record<string, unknown> {
1847
+ return v !== null && typeof v === 'object' && !Array.isArray(v);
1848
+ }
1849
+
1850
+ /** Troca o `parse` (e o `run`, quando o Zod o copiou do `parse`) de um schema
1851
+ * por um que, fora de uma chamada com corte, so repassa. Por acessores, e nao
1852
+ * por atribuicao: o memoizer do Zod troca o `parse` de volta pelo original na
1853
+ * primeira validacao de um schema nao recursivo, e o setter guarda essa troca
1854
+ * como o novo original em vez de perder o embrulho. */
1855
+ function embrulhar(schema: Interno, comCorte: ComCorte) {
1856
+ const zod = schema._zod;
1857
+ let original = zod.parse;
1858
+ const runEhParse = zod.run === original;
1859
+ const embrulhado = (payload: Payload, ctx: unknown) => (corte ? comCorte(original, schema, payload, ctx) : original(payload, ctx));
1860
+ Object.defineProperty(zod, 'parse', { configurable: true, enumerable: true, get: () => embrulhado, set: (v) => { original = v; } });
1861
+ if (runEhParse) Object.defineProperty(zod, 'run', { configurable: true, enumerable: true, get: () => embrulhado, set: () => {} });
1862
+ }
1863
+
1864
+ /** Percorre o schema uma vez, ao carregar o modulo, e embrulha cada lista,
1865
+ * cada registro e cada objeto que e opcao de uma uniao (direto ou por um
1866
+ * z.lazy) - so nesses a escolha de ramo existe, e so eles abrem uma regiao. A
1867
+ * raiz, por exemplo, nao: chaves desconhecidas nela nao sao validadas.
1868
+ * `membros`: os objetos que validam itens de uma lista de paginas (grupo, grupo
1869
+ * de openapi, link) - os unicos que podem ser um container recolhido. */
1870
+ function instalarCorte(raiz: unknown, membros: Set<unknown>) {
1871
+ const todos: Interno[] = [];
1872
+ const opcoes = new Set<unknown>();
1873
+ const vistos = new Set<unknown>();
1874
+ const pendentes = [raiz];
1875
+ const resolver = (schema: Interno): unknown => (schema?._zod?.def?.type === 'lazy' ? schema._zod.innerType : schema);
1876
+ while (pendentes.length) {
1877
+ const schema = pendentes.pop() as Interno;
1878
+ if (!schema || typeof schema !== 'object' || !schema._zod || vistos.has(schema)) continue;
1879
+ vistos.add(schema);
1880
+ todos.push(schema);
1881
+ const def = schema._zod.def;
1882
+ if (def.type === 'array') pendentes.push(def.element);
1883
+ else if (def.type === 'record') pendentes.push(def.keyType, def.valueType);
1884
+ else if (def.type === 'object') {
1885
+ pendentes.push(...Object.values(def.shape as object));
1886
+ if (def.catchall) pendentes.push(def.catchall);
1887
+ } else if (def.type === 'union') {
1888
+ for (const opcao of def.options) opcoes.add(resolver(opcao));
1889
+ pendentes.push(...def.options);
1890
+ } else if (def.type === 'lazy') pendentes.push(schema._zod.innerType);
1891
+ else if (def.type === 'pipe') pendentes.push(def.in, def.out);
1892
+ else if (def.innerType) pendentes.push(def.innerType);
1893
+ }
1894
+ for (const schema of todos) {
1895
+ const tipo = schema._zod.def.type;
1896
+ if (tipo === 'array') embrulhar(schema, listaComCorte);
1897
+ else if (tipo === 'record') embrulhar(schema, registroComCorte);
1898
+ else if (tipo === 'object' && opcoes.has(schema)) embrulhar(schema, objetoComCorte(membros.has(schema)));
1899
+ }
1900
+ }
1901
+
1902
+ /** Uma opcao de uniao abre a regiao do seu modo (a mais externa vale pra tudo
1903
+ * dentro dela). */
1904
+ function objetoComCorte(membro: boolean): ComCorte {
1905
+ return (original, _schema, payload, ctx) => {
1906
+ const estado = corte!;
1907
+ const valor = payload.value;
1908
+ if (estado.regioes.length > 0 || !ehObjeto(valor)) return original(payload, ctx);
1909
+ const regiao: Regiao | null = disputado(valor) ? 'contar' : membro && recolhido(valor) ? 'pular' : null;
1910
+ if (!regiao) return original(payload, ctx);
1911
+ estado.regioes.push(regiao);
1912
+ try {
1913
+ return original(payload, ctx);
1914
+ } finally {
1915
+ estado.regioes.pop();
1916
+ }
1917
+ };
1918
+ }
1919
+
1920
+ /** Roda o schema de um item como o Zod roda (sincrono: nada neste schema e
1921
+ * assincrono). */
1922
+ function rodar(schema: Interno, valor: unknown, ctx: unknown): Payload {
1923
+ const resultado = schema._zod.run({ value: valor, issues: [] }, ctx);
1924
+ if (resultado instanceof Promise) throw new Error('[writedocs] async validation is not supported');
1925
+ return resultado;
1926
+ }
1927
+
1928
+ function abortou(resultado: Payload): boolean {
1929
+ return resultado.aborted === true || resultado.issues.some((issue) => (issue as { continue?: boolean }).continue !== true);
1930
+ }
1931
+
1932
+ /** O z.array: o laco do Zod (o valor de cada item, os erros com o indice na
1933
+ * frente), nos tres modos. Sem corte (lista sem erro, ou que nao chegou ao
1934
+ * limite), o resultado e o do Zod, item por item. */
1935
+ const listaComCorte: ComCorte = (original, schema, payload, ctx) => {
1936
+ const entrada = payload.value;
1937
+ if (!Array.isArray(entrada)) return original(payload, ctx);
1938
+ const estado = corte!;
1939
+ const elemento = schema._zod.def.element as Interno;
1940
+ const valor = new Array(entrada.length);
1941
+ payload.value = valor;
1942
+ const regiao = estado.regioes[estado.regioes.length - 1];
1943
+ if (regiao === 'pular') {
1944
+ for (let i = 0; i < entrada.length; i++) valor[i] = entrada[i];
1945
+ return payload;
1946
+ }
1947
+ if (regiao === 'contar') {
1948
+ let n = 0;
1949
+ let maior = -Infinity;
1950
+ let algumErrado = false;
1951
+ let algumAborta = false;
1952
+ for (let i = 0; i < entrada.length; i++) {
1953
+ const resultado = rodar(elemento, entrada[i], ctx);
1954
+ valor[i] = resultado.value;
1955
+ if (resultado.issues.length === 0) continue;
1956
+ algumErrado = true;
1957
+ if (abortou(resultado)) algumAborta = true;
1958
+ // Um Map so deste item: o resumo dele nao serve pra mais nada.
1959
+ const resumo = resumoDoRamo(resultado.issues, new Map());
1960
+ n += resumo.n;
1961
+ if (resumo.n > 0 && 1 + resumo.maior > maior) maior = 1 + resumo.maior;
1962
+ }
1963
+ // `continue` diz se o resultado "aborta", e as unioes do Zod decidem por
1964
+ // isso: o resumo aborta exatamente quando algum dos erros resumidos abortaria.
1965
+ if (algumErrado) {
1966
+ payload.issues.push({
1967
+ code: 'custom',
1968
+ message: 'writedocs: list summary',
1969
+ path: [],
1970
+ continue: !algumAborta,
1971
+ wdLista: { n, maior, entrada, elemento: elemento as unknown as ResumoDeLista['elemento'] },
1972
+ } as IssueCru);
1973
+ }
1974
+ return payload;
1975
+ }
1976
+ for (let i = 0; i < entrada.length; i++) {
1977
+ if (estado.esgotado) {
1978
+ valor[i] = entrada[i];
1979
+ continue;
1980
+ }
1981
+ const antes = estado.contados;
1982
+ const resultado = rodar(elemento, entrada[i], ctx);
1983
+ valor[i] = resultado.value;
1984
+ if (resultado.issues.length === 0) continue;
1985
+ for (const issue of resultado.issues) {
1986
+ (issue.path ??= []).unshift(i);
1987
+ payload.issues.push(issue);
1988
+ }
1989
+ // So o item "folha" conta: se uma lista de dentro dele ja contou, o erro
1990
+ // dele e o dela.
1991
+ if (estado.contados === antes && ++estado.contados > VALIDATION_ISSUE_LIMIT) estado.esgotado = true;
1992
+ }
1993
+ return payload;
1994
+ };
1995
+
1996
+ /** O z.record de chave texto (socials, variables, metatags, langAlias): o laco
1997
+ * do Zod, no modo PARAR. Qualquer outro (chave com regra, ou dentro de uma
1998
+ * regiao) fica com o do Zod - nenhum registro do schema mora numa regiao. */
1999
+ const registroComCorte: ComCorte = (original, schema, payload, ctx) => {
2000
+ const entrada = payload.value;
2001
+ const estado = corte!;
2002
+ const def = schema._zod.def;
2003
+ const chaveTexto = def.keyType?._zod?.def?.type === 'string' && !(def.keyType._zod.def.checks?.length > 0);
2004
+ if (estado.regioes.length > 0 || !ehObjeto(entrada) || !chaveTexto || Object.getPrototypeOf(entrada) !== Object.prototype) {
2005
+ return original(payload, ctx);
2006
+ }
2007
+ const valor: Record<string, unknown> = {};
2008
+ payload.value = valor;
2009
+ for (const chave of Object.keys(entrada)) {
2010
+ if (chave === '__proto__') continue;
2011
+ if (estado.esgotado) {
2012
+ valor[chave] = entrada[chave];
2013
+ continue;
2014
+ }
2015
+ const antes = estado.contados;
2016
+ const resultado = rodar(def.valueType, entrada[chave], ctx);
2017
+ valor[chave] = resultado.value;
2018
+ if (resultado.issues.length === 0) continue;
2019
+ for (const issue of resultado.issues) {
2020
+ (issue.path ??= []).unshift(chave);
2021
+ payload.issues.push(issue);
2022
+ }
2023
+ if (estado.contados === antes && ++estado.contados > VALIDATION_ISSUE_LIMIT) estado.esgotado = true;
2024
+ }
2025
+ return payload;
2026
+ };
2027
+
2028
+ /** Os erros de uma lista resumida (modo CONTAR), na ordem, revalidando um item
2029
+ * por vez - dentro de uma regiao CONTAR, como na primeira passada. */
2030
+ function* itensDaLista(lista: ResumoDeLista, resumos: Map<object, Resumo>, caminho: (string | number)[]): Generator<[IssueCru, (string | number)[]]> {
2031
+ for (let i = 0; i < lista.entrada.length; i++) {
2032
+ corte?.regioes.push('contar');
2033
+ let resultado;
2034
+ try {
2035
+ resultado = lista.elemento.safeParse(lista.entrada[i]);
2036
+ } finally {
2037
+ corte?.regioes.pop();
2038
+ }
2039
+ if (resultado.success) continue;
2040
+ yield* desembrulharUnioes(resultado.error!.issues as IssueCru[], resumos, [...caminho, i]);
2041
+ }
2042
+ }
2043
+
2044
+ instalarCorte(
2045
+ docsConfigSchema,
2046
+ new Set([(navGroupPagesSchema as unknown as Interno)._zod.innerType, navGroupOpenApiSchema, navLinkSchema])
2047
+ );
2048
+
2049
+ /** Linha e coluna de varios caminhos numa passada so pelo texto (o `visit` do
2050
+ * jsonc-parser), sem montar a arvore: com um milhao de valores, o parseTree
2051
+ * sozinho passava de 64 MB. A mesma resposta do criarLocalizador (parseTree +
2052
+ * findNodeAtLocation), inclusive com chave repetida num objeto, onde vale a
2053
+ * primeira; o que nao leva a nenhum caminho pedido e pulado sem callbacks. */
2054
+ function localizarCaminhos(rawText: string, caminhos: (string | number)[][]): (caminho: (string | number)[]) => { line: number; column: number } | null {
2055
+ rawText = semBom(rawText);
2056
+ type No = { filhos: Map<string | number, No>; alvo: boolean; offset?: number };
2057
+ const raiz: No = { filhos: new Map(), alvo: false };
2058
+ for (const caminho of caminhos) {
2059
+ if (caminho.length === 0) continue;
2060
+ let no = raiz;
2061
+ for (const passo of caminho) {
2062
+ let filho = no.filhos.get(passo);
2063
+ if (!filho) no.filhos.set(passo, (filho = { filhos: new Map(), alvo: false }));
2064
+ no = filho;
2065
+ }
2066
+ no.alvo = true;
2067
+ }
2068
+ type Quadro = { no: No | null; lista: boolean; indice: number; chave: string; vistas: Set<string> };
2069
+ const pilha: Quadro[] = [];
2070
+ const comecoDeValor = (offset: number): No | null => {
2071
+ const topo = pilha[pilha.length - 1];
2072
+ if (!topo) return raiz;
2073
+ if (!topo.no) return null;
2074
+ let filho: No | null;
2075
+ if (topo.lista) filho = topo.no.filhos.get(topo.indice++) ?? null;
2076
+ else {
2077
+ filho = topo.no.filhos.get(topo.chave) ?? null;
2078
+ // Chave repetida: o findNodeAtLocation desce pela primeira.
2079
+ if (filho) {
2080
+ if (topo.vistas.has(topo.chave)) filho = null;
2081
+ else topo.vistas.add(topo.chave);
2082
+ }
2083
+ }
2084
+ if (filho?.alvo && filho.offset === undefined) filho.offset = offset;
2085
+ return filho;
2086
+ };
2087
+ const abrir = (lista: boolean) => (offset: number) => {
2088
+ const no = comecoDeValor(offset);
2089
+ pilha.push({ no, lista, indice: 0, chave: '', vistas: new Set() });
2090
+ return no !== null && no.filhos.size > 0 ? undefined : false;
2091
+ };
2092
+ if (raiz.filhos.size > 0) {
2093
+ visit(rawText, {
2094
+ onObjectBegin: abrir(false),
2095
+ onArrayBegin: abrir(true),
2096
+ onObjectEnd: () => void pilha.pop(),
2097
+ onArrayEnd: () => void pilha.pop(),
2098
+ onObjectProperty: (chave: string) => {
2099
+ pilha[pilha.length - 1].chave = chave;
2100
+ },
2101
+ onLiteralValue: (_valor: unknown, offset: number) => void comecoDeValor(offset),
2102
+ });
2103
+ }
2104
+ let inicios: number[] | undefined;
2105
+ return (caminho) => {
2106
+ if (caminho.length === 0) return null;
2107
+ let no: No | undefined = raiz;
2108
+ for (const passo of caminho) {
2109
+ no = no.filhos.get(passo);
2110
+ if (!no) return null;
2111
+ }
2112
+ if (no.offset === undefined) return null;
2113
+ inicios ??= iniciosDeLinha(rawText);
2114
+ return linhaEColuna(inicios, no.offset);
2115
+ };
2116
+ }
2117
+
2118
+ /** Exported for `writedocs validate`'s content pass (lib/content-check.js),
2119
+ * which reports writedocs.json problems of its own - navigation entries
2120
+ * with no page, unknown icons - with the same line numbers as the schema
2121
+ * errors. Same function as criarLocalizador below. */
2122
+ export function createJsonLocator(rawText: string): (path: (string | number)[]) => { line: number; column: number } | null {
2123
+ return criarLocalizador(rawText);
2124
+ }
2125
+
2126
+ /** Parseia o texto UMA vez e devolve "caminho -> linha/coluna". Devolve null
2127
+ * quando o no nao existe no texto (campo obrigatorio ausente e o caso comum):
2128
+ * `line` ausente e melhor que `line` inventada.
2129
+ *
2130
+ * WD-315: o custo de cada busca tem que independer do tamanho do texto. A
2131
+ * versao anterior fazia `rawText.slice(0, offset).split('\n')` POR BUSCA - com
2132
+ * 66 mil erros num texto de 11 MB, 169 s e ~1,2 GB. Agora a arvore e os inicios
2133
+ * de linha sao calculados uma vez, na primeira busca (um config sem nada pra
2134
+ * localizar nao paga nenhum dos dois), e cada offset vira linha por busca
2135
+ * binaria. A linha e a coluna sao exatamente as de antes: a linha conta so
2136
+ * '\n' (um `\r\n` e um '\n' com o '\r' no fim da linha anterior), e a coluna e
2137
+ * em unidades UTF-16, como o offset do jsonc-parser - um emoji conta 2. */
2138
+ function criarLocalizador(rawText: string): (caminho: (string | number)[]) => { line: number; column: number } | null {
2139
+ rawText = semBom(rawText);
2140
+ let arvore: ReturnType<typeof parseTree> | undefined | null = null;
2141
+ let inicios: number[] | undefined;
2142
+ return (caminho) => {
2143
+ if (caminho.length === 0) return null;
2144
+ if (arvore === null) {
2145
+ try {
2146
+ arvore = parseTree(rawText);
2147
+ } catch {
2148
+ arvore = undefined;
2149
+ }
2150
+ }
2151
+ if (!arvore) return null;
2152
+ const no = findNodeAtLocation(arvore, caminho);
2153
+ if (!no) return null;
2154
+ inicios ??= iniciosDeLinha(rawText);
2155
+ return linhaEColuna(inicios, no.offset);
2156
+ };
2157
+ }
2158
+
2159
+ /** Os offsets em que cada linha comeca: 0, e o seguinte a cada '\n'. */
2160
+ function iniciosDeLinha(texto: string): number[] {
2161
+ const inicios = [0];
2162
+ for (let i = texto.indexOf('\n'); i !== -1; i = texto.indexOf('\n', i + 1)) inicios.push(i + 1);
2163
+ return inicios;
2164
+ }
2165
+
2166
+ /** A linha do offset e o ultimo inicio <= offset (busca binaria); a coluna
2167
+ * conta a partir de 1 nesse inicio. */
2168
+ function linhaEColuna(inicios: number[], offset: number): { line: number; column: number } {
2169
+ let baixo = 0;
2170
+ let alto = inicios.length - 1;
2171
+ while (baixo < alto) {
2172
+ const meio = (baixo + alto + 1) >> 1;
2173
+ if (inicios[meio] <= offset) baixo = meio;
2174
+ else alto = meio - 1;
2175
+ }
2176
+ return { line: baixo + 1, column: offset - inicios[baixo] + 1 };
2177
+ }
2178
+
2179
+ /** `styles.primaryColor` -> `config.styles`. Primeiro segmento so, com fallback
2180
+ * pra `config`: o conjunto tem que ficar pequeno e estavel, porque vira
2181
+ * superficie publica no instante em que alguem mapear chave -> URL. */
2182
+ function docKeyDoCaminho(caminho: (string | number)[]): string {
2183
+ const primeiro = caminho[0];
2184
+ return typeof primeiro === 'string' && primeiro ? `config.${primeiro}` : 'config';
2185
+ }
2186
+
2187
+ const ARTIGO_POR_TIPO: Record<string, string> = {
2188
+ string: 'a piece of text',
2189
+ number: 'a number',
2190
+ boolean: 'true or false',
2191
+ array: 'a list',
2192
+ object: 'an object',
2193
+ null: 'null',
2194
+ };
2195
+
2196
+ const COMO_ESCREVER: Record<string, string> = {
2197
+ string: 'Write the value in double quotes, like "Core Platform".',
2198
+ number: 'Write the value as a bare number, like 3 - no quotes.',
2199
+ boolean: 'Write true or false - no quotes.',
2200
+ array: 'Write the value as a list in square brackets: [ ... ].',
2201
+ object: 'Write the value as an object in curly braces: { ... }.',
2202
+ };
2203
+
2204
+ /** O tipo que o cliente REALMENTE escreveu, lido do JSON ja parseado em vez de
2205
+ * extraido da mensagem do Zod por regex - o Zod v4 nao carrega `received` como
2206
+ * propriedade, so dentro do texto, e depender do texto quebra na primeira vez
2207
+ * que ele mudar de forma. */
2208
+ function tipoReal(valor: unknown): string {
2209
+ if (valor === undefined) return 'missing';
2210
+ if (valor === null) return 'null';
2211
+ if (Array.isArray(valor)) return 'array';
2212
+ return typeof valor;
2213
+ }
2214
+
2215
+ function valorEm(raiz: unknown, caminho: (string | number)[]): unknown {
2216
+ let atual: unknown = raiz;
2217
+ for (const passo of caminho) {
2218
+ if (atual === null || typeof atual !== 'object') return undefined;
2219
+ atual = (atual as Record<string | number, unknown>)[passo];
2220
+ }
2221
+ return atual;
2222
+ }
2223
+
2224
+ function comoCampo(caminho: (string | number)[]): string {
2225
+ return caminho.length > 0 ? `"${caminho.join('.')}"` : 'writedocs.json';
2226
+ }
2227
+
2228
+ /** A frase de chave desconhecida, num lugar so.
2229
+ *
2230
+ * Decisao 6: chave desconhecida em sub-objeto strict e ERRO e na raiz e AVISO -
2231
+ * a assimetria de SEVERIDADE e intencional e fica. A de VOCABULARIO nao: os
2232
+ * dois caminhos chamam esta funcao, entao os dois dizem exatamente a mesma
2233
+ * coisa, e so quem chama decide o peso. */
2234
+ function fraseChaveDesconhecida(chaves: string[], dentroDe: (string | number)[]) {
2235
+ const onde = dentroDe.length > 0 ? ` inside "${dentroDe.join('.')}"` : '';
2236
+ const lista = chaves.map((k) => `"${k}"`).join(', ');
2237
+ return {
2238
+ humanMessage:
2239
+ chaves.length === 1
2240
+ ? `${lista} is not a writedocs.json option${onde}.`
2241
+ : `${lista} are not writedocs.json options${onde}.`,
2242
+ suggestion: 'Remove it, or check the spelling - options are case-sensitive.',
2243
+ };
2244
+ }
2245
+
2246
+ /** A frase humana + a sugestao, escolhidas pelo CODIGO do Zod. `raiz` e o JSON
2247
+ * ja parseado, usado so pra saber o que o cliente escreveu de fato. */
2248
+ function humanizar(issue: IssuePlano, raiz: unknown): { humanMessage?: string; suggestion?: string } {
2249
+ const campo = comoCampo(issue.caminho);
2250
+ switch (issue.code) {
2251
+ case 'invalid_type': {
2252
+ const esperado = issue.expected ?? 'a different type';
2253
+ const recebido = tipoReal(valorEm(raiz, issue.caminho));
2254
+ if (recebido === 'missing') {
2255
+ return {
2256
+ humanMessage: `${campo} is required, but writedocs.json does not set it.`,
2257
+ suggestion: `Add ${campo} with ${ARTIGO_POR_TIPO[esperado] ?? `a ${esperado}`} as its value.`,
2258
+ };
2259
+ }
2260
+ return {
2261
+ humanMessage: `${campo} must be ${ARTIGO_POR_TIPO[esperado] ?? `a ${esperado}`}, but writedocs.json has ${ARTIGO_POR_TIPO[recebido] ?? `a ${recebido}`}.`,
2262
+ suggestion: COMO_ESCREVER[esperado],
2263
+ };
2264
+ }
2265
+ case 'unrecognized_keys': {
2266
+ // O Zod agrega as chaves sobrando numa mensagem so, com o `path` no PAI.
2267
+ const chaves = issue.keys ?? [];
2268
+ if (chaves.length === 0) return {};
2269
+ return fraseChaveDesconhecida(chaves, issue.caminho);
2270
+ }
2271
+ case 'invalid_value': {
2272
+ const opcoes = (issue.values ?? []).map((v) => JSON.stringify(v)).join(', ');
2273
+ return {
2274
+ humanMessage: `${campo} must be one of: ${opcoes}.`,
2275
+ suggestion: 'Replace the value with one of the options above.',
2276
+ };
2277
+ }
2278
+ case 'too_small': {
2279
+ const unidade = issue.origin === 'array' ? 'item' : 'character';
2280
+ const minimo = issue.minimum ?? 1;
2281
+ return {
2282
+ humanMessage: `${campo} needs at least ${minimo} ${unidade}${minimo === 1 ? '' : 's'}.`,
2283
+ suggestion: issue.origin === 'array' ? 'Add an entry, or remove the field entirely.' : undefined,
2284
+ };
2285
+ }
2286
+ case 'too_big': {
2287
+ const unidade = issue.origin === 'array' ? 'item' : 'character';
2288
+ const maximo = issue.maximum ?? 0;
2289
+ return { humanMessage: `${campo} allows at most ${maximo} ${unidade}${maximo === 1 ? '' : 's'}.` };
2290
+ }
2291
+ case 'invalid_format':
2292
+ // A field with a pattern of its own (`basePath`) says what's wrong in
2293
+ // its own words.
2294
+ if (issue.format === 'regex' && issue.message) return { humanMessage: issue.message };
2295
+ return {
2296
+ humanMessage: `${campo} is not a valid ${issue.format ?? 'value'}.`,
2297
+ suggestion: 'Check the format against the documentation for this field.',
2298
+ };
2299
+ case 'invalid_union':
2300
+ // So chega aqui se o desembrulho nao achou ramo nenhum (uniao sem
2301
+ // `errors`). Raro, mas melhor dizer o que aconteceu do que "Invalid input".
2302
+ return {
2303
+ humanMessage: `${campo} does not match any of the shapes writedocs.json accepts here.`,
2304
+ suggestion: 'Check the documentation for the shapes this field accepts.',
2305
+ };
2306
+ case 'custom':
2307
+ // As mensagens de `.refine()` deste schema ja sao frases escritas pra
2308
+ // gente ("Each scripts.head/scripts.body entry needs exactly one of..."),
2309
+ // entao reescrever seria piorar. Repassa como frase humana pra que quem
2310
+ // exibe so `humanMessage` nao fique sem nada.
2311
+ return { humanMessage: issue.message };
2312
+ default:
2313
+ return {};
2314
+ }
2315
+ }
2316
+
2317
+ /** Avisos de chave desconhecida na RAIZ.
2318
+ *
2319
+ * A raiz nao e `.strict()` (decidido no E11-desenho-geral: tornar strict
2320
+ * quebraria configs existentes), entao o Zod descarta a chave em silencio e
2321
+ * nao ha issue nenhum. Quem quiser avisar chama isto. Mora aqui, e nao na
2322
+ * plataforma, pelo motivo de sempre: era o unico texto escrito pela plataforma,
2323
+ * e enquanto ele viver la os dois lados podem divergir.
2324
+ *
2325
+ * Severidade e de quem chama - isto so descreve o problema. `validateDocsConfig`
2326
+ * deliberadamente NAO chama: um config valido continua saindo com `issues: []`,
2327
+ * porque a plataforma repassa `issues` como `errors` e um aviso ali viraria
2328
+ * erro.
2329
+ *
2330
+ * WD-315: no maximo os primeiros VALIDATION_ISSUE_LIMIT avisos, na ordem das
2331
+ * chaves no texto. O total sai do unknownRootKeyWarnings() logo abaixo. */
2332
+ export function unknownRootKeyIssues(rawText: string): ValidationIssue[] {
2333
+ return unknownRootKeyWarnings(rawText).issues;
2334
+ }
2335
+
2336
+ /** O mesmo que unknownRootKeyIssues(), com o total (`issuesTotal`), como o
2337
+ * validateDocsConfig(). Uma funcao a parte, e nao outro retorno daquela, pra
2338
+ * que quem ja chama unknownRootKeyIssues() continue recebendo uma lista. O
2339
+ * total e sempre exato (contar chaves nao custa); `{ all: true }` devolve
2340
+ * todos os avisos. */
2341
+ export function unknownRootKeyWarnings(
2342
+ rawText: string,
2343
+ { all = false }: ValidationOptions = {}
2344
+ ): { issues: ValidationIssue[]; issuesTotal: number } {
2345
+ rawText = semBom(rawText);
2346
+ let raiz: unknown;
2347
+ try {
2348
+ raiz = JSON.parse(rawText);
2349
+ } catch {
2350
+ return { issues: [], issuesTotal: 0 };
2351
+ }
2352
+ if (raiz === null || typeof raiz !== 'object' || Array.isArray(raiz)) return { issues: [], issuesTotal: 0 };
2353
+ const conhecidas = new Set([...Object.keys(docsConfigSchema.shape), ...ROOT_ALLOWED_EXTRA_KEYS]);
2354
+ const desconhecidas = Object.keys(raiz as Record<string, unknown>).filter((chave) => !conhecidas.has(chave));
2355
+ const listadas = all ? desconhecidas : desconhecidas.slice(0, VALIDATION_ISSUE_LIMIT);
2356
+ const localizar = localizarCaminhos(rawText, listadas.map((chave) => [chave]));
2357
+ const issues = listadas
2358
+ .map((chave) => {
2359
+ const frase = fraseChaveDesconhecida([chave], []);
2360
+ return {
2361
+ path: chave,
2362
+ // O mesmo formato singular da mensagem `unrecognized_keys` do Zod, pra
2363
+ // que aviso e erro sejam indistinguiveis por quem so le `message`.
2364
+ message: `Unrecognized key: "${chave}"`,
2365
+ code: 'unrecognized_keys',
2366
+ ...(localizar([chave]) ?? {}),
2367
+ ...frase,
2368
+ // `config`, e NAO `config.<chave>`: a chave aqui e o que o cliente
2369
+ // digitou errado, e derivar a docKey dela faria cada erro de digitacao
2370
+ // inventar uma chave nova. O conjunto de docKeys tem que ser fechado -
2371
+ // `config` mais um por campo do schema, nada alem disso -, senao quem
2372
+ // mapeia chave -> URL do outro lado nao tem lista pra mapear.
2373
+ docKey: 'config',
2374
+ };
2375
+ });
2376
+ return { issues, issuesTotal: desconhecidas.length };
2377
+ }
2378
+
2379
+ /** Texto sem o BOM do UTF-8 no inicio. Editores do Windows (Bloco de Notas, o
2380
+ * `Out-File` do PowerShell 5.1) gravam um, e o JSON.parse o rejeita com uma
2381
+ * mensagem que culpa virgulas e colchetes. Copia local, e nao import de
2382
+ * lib/config-file.js: este modulo so importa zod e jsonc-parser (ver o topo). */
2383
+ function semBom(texto: string): string {
2384
+ return texto.charCodeAt(0) === 0xfeff ? texto.slice(1) : texto;
2385
+ }
2386
+
2387
+ export function validateDocsConfig(rawText: string, { all = false }: ValidationOptions = {}): ValidationResult {
2388
+ rawText = semBom(rawText);
2389
+ let raw: unknown;
2390
+ try {
2391
+ raw = JSON.parse(rawText);
2392
+ } catch (err) {
2393
+ const parseError = err as SyntaxError;
2394
+ const posicao = positionFromJsonError(parseError.message, rawText);
2395
+ return {
2396
+ ok: false,
2397
+ data: null,
2398
+ kind: 'invalid_json',
2399
+ parseError,
2400
+ issues: [
2401
+ {
2402
+ path: '(root)',
2403
+ message: parseError.message,
2404
+ code: 'invalid_json',
2405
+ ...(posicao ?? {}),
2406
+ humanMessage: 'writedocs.json is not valid JSON, so none of it could be checked.',
2407
+ suggestion: posicao
2408
+ ? `Look at line ${posicao.line} - a missing comma, an extra trailing comma, or an unclosed bracket is the usual cause.`
2409
+ : 'A missing comma, an extra trailing comma, or an unclosed bracket is the usual cause.',
2410
+ docKey: 'config',
2411
+ },
2412
+ ],
2413
+ issuesTotal: 1,
2414
+ issuesTruncated: false,
2415
+ };
2416
+ }
2417
+
2418
+ if (all) return validarTudo(rawText, raw);
2419
+
2420
+ // A validacao com corte (a secao PARAR CEDO): o `corte` vive ate o fluxo de
2421
+ // saida ser consumido, porque as listas resumidas sao revalidadas nele.
2422
+ corte = { contados: 0, esgotado: false, regioes: [] };
2423
+ try {
2424
+ const result = docsConfigSchema.safeParse(raw);
2425
+ if (result.success) return { ok: true, data: result.data, issues: [], issuesTotal: 0, issuesTruncated: false };
2426
+ // A lista, na ordem - o desembrulho e o containersEmPaginas mudam quantos sao
2427
+ // e em que ordem -, ate o VALIDATION_ISSUE_LIMIT-esimo e mais um, que so diz
2428
+ // que ha mais. Os primeiros sao localizados e humanizados.
2429
+ const primeiros: IssuePlano[] = [];
2430
+ let truncado = false;
2431
+ const resumos = new Map<object, Resumo>();
2432
+ for (const issue of containersEmPaginas(desembrulharUnioes(result.error.issues as IssueCru[], resumos), raw)) {
2433
+ if (primeiros.length === VALIDATION_ISSUE_LIMIT) {
2434
+ truncado = true;
2435
+ break;
2436
+ }
2437
+ primeiros.push(issue);
2438
+ }
2439
+ // Se a validacao parou, ela parou depois de VALIDATION_ISSUE_LIMIT + 1 itens
2440
+ // errados, e cada um e pelo menos um erro antes do ponto onde ela parou -
2441
+ // entao o fluxo tem que ter passado do teto. Se nao passou, a conta da secao
2442
+ // PARAR CEDO falhou em algum caso: entao vale a validacao inteira, que e
2443
+ // sempre certa, mesmo que cara.
2444
+ if (corte.esgotado && !truncado) {
2445
+ corte = null;
2446
+ recaidas++;
2447
+ return limitar(validarTudo(rawText, raw));
2448
+ }
2449
+ return {
2450
+ ok: false,
2451
+ data: null,
2452
+ kind: 'schema',
2453
+ issues: localizarEHumanizar(primeiros, rawText, raw, localizarCaminhos),
2454
+ issuesTotal: truncado ? VALIDATION_ISSUE_LIMIT + 1 : primeiros.length,
2455
+ issuesTruncated: truncado,
2456
+ };
2457
+ } finally {
2458
+ corte = null;
2459
+ }
2460
+ }
2461
+
2462
+ /** Quantas vezes, desde que o modulo carregou, a validacao com corte caiu na
2463
+ * validacao inteira (o `if` acima). Deve ser sempre 0: o resultado sai certo
2464
+ * mesmo assim, mas sem a economia - e um erro na secao PARAR CEDO. Exportado
2465
+ * pros testes (scripts/validation-stop.test.js), que exigem 0. */
2466
+ let recaidas = 0;
2467
+ export function stopFallbacks(): number {
2468
+ return recaidas;
2469
+ }
2470
+
2471
+ /** `{ all: true }`: o Zod inteiro, sem corte, e a lista inteira - o que o
2472
+ * validateDocsConfig() fazia antes do WD-315. */
2473
+ function validarTudo(rawText: string, raw: unknown): ValidationResult {
2474
+ const result = docsConfigSchema.safeParse(raw);
2475
+ if (result.success) return { ok: true, data: result.data, issues: [], issuesTotal: 0, issuesTruncated: false };
2476
+ const todos = [...containersEmPaginas(desembrulharUnioes(result.error.issues as IssueCru[], new Map()), raw)];
2477
+ const issues = localizarEHumanizar(todos, rawText, raw, (texto) => criarLocalizador(texto));
2478
+ return { ok: false, data: null, kind: 'schema', issues, issuesTotal: issues.length, issuesTruncated: false };
2479
+ }
2480
+
2481
+ /** O resultado de validarTudo() cortado no teto, como o normal o daria. */
2482
+ function limitar(resultado: ValidationResult): ValidationResult {
2483
+ if (resultado.issues.length <= VALIDATION_ISSUE_LIMIT) return resultado;
2484
+ return { ...resultado, issues: resultado.issues.slice(0, VALIDATION_ISSUE_LIMIT), issuesTotal: VALIDATION_ISSUE_LIMIT + 1, issuesTruncated: true };
2485
+ }
2486
+
2487
+ /** Do issue desembrulhado para o ValidationIssue: a linha, a frase humana, a
2488
+ * docKey. `criar` recebe o texto e os caminhos que serao procurados. */
2489
+ function localizarEHumanizar(
2490
+ lista: IssuePlano[],
2491
+ rawText: string,
2492
+ raw: unknown,
2493
+ criar: (texto: string, caminhos: (string | number)[][]) => (caminho: (string | number)[]) => { line: number; column: number } | null
2494
+ ): ValidationIssue[] {
2495
+ // Para chave desconhecida o `path` do Zod aponta pro PAI (`footer`), e a
2496
+ // chave ofensora vem em `keys`. Para a LINHA vale a pena descer ate ela
2497
+ // (`footer.banana`), que e onde o cliente precisa olhar; o `path` fica
2498
+ // como o Zod deu, pra nao mudar o que a plataforma ja grava.
2499
+ const alvos = lista.map((i) => (i.code === 'unrecognized_keys' && i.keys?.length ? [...i.caminho, i.keys[0]] : i.caminho));
2500
+ const localizar = criar(rawText, [...alvos, ...lista.map((i) => i.caminho)]);
2501
+ return lista.map((i, k) => ({
2502
+ path: i.caminho.join('.') || '(root)',
2503
+ message: i.message,
2504
+ code: i.code,
2505
+ ...(localizar(alvos[k]) ?? localizar(i.caminho) ?? {}),
2506
+ ...humanizar(i, raw),
2507
+ docKey: docKeyDoCaminho(i.caminho),
2508
+ }));
2509
+ }