@writedocs/generator 0.13.4 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +359 -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 +223 -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 +269 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +509 -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 +71 -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 +219 -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 +422 -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.js +12 -1
  48. package/src/lib/config-schema.ts +2523 -2509
  49. package/src/lib/config.ts +1331 -1316
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-check.js +4 -1
  52. package/src/lib/content-store-reload-integration.js +101 -101
  53. package/src/lib/drafts.js +186 -0
  54. package/src/lib/icon-data-dev.js +53 -53
  55. package/src/lib/image-size.js +152 -152
  56. package/src/lib/json-schema-descriptions.js +228 -228
  57. package/src/lib/link-check.js +553 -544
  58. package/src/lib/llms-index.ts +90 -90
  59. package/src/lib/mcp-dev-integration.js +65 -65
  60. package/src/lib/mcp-index.ts +102 -102
  61. package/src/lib/mintlify-convert.js +605 -605
  62. package/src/lib/moved-api-pages.js +49 -49
  63. package/src/lib/og-cards.js +33 -33
  64. package/src/lib/og-image.js +235 -235
  65. package/src/lib/openapi-dev-status.js +80 -80
  66. package/src/lib/openapi-reload-integration.js +193 -193
  67. package/src/lib/pages.js +346 -312
  68. package/src/lib/project-files-integration.js +116 -116
  69. package/src/lib/project-files.js +137 -137
  70. package/src/lib/rehype-base-path.js +62 -62
  71. package/src/lib/rehype-image-loading.js +71 -71
  72. package/src/lib/robots-txt.js +21 -21
  73. package/src/lib/search-scope.js +44 -44
  74. package/src/lib/selector-placement.js +50 -50
  75. package/src/lib/seo-tags.js +157 -155
  76. package/src/lib/shiki-code-block.js +7 -1
  77. package/src/lib/site-base.ts +27 -27
  78. package/src/lib/styles-asset-integration.js +291 -291
  79. package/src/lib/wdignore-cases.json +195 -195
  80. package/src/lib/wdignore.js +177 -177
  81. package/src/pages/404.astro +63 -63
  82. package/src/pages/[...slug].astro +1773 -1608
  83. package/src/pages/[...slug].md.ts +93 -93
  84. package/src/pages/llms-full.txt.ts +88 -88
  85. package/src/pages/og/[...slug].png.ts +63 -63
  86. package/src/scripts/mobile-menu.ts +80 -80
  87. package/src/scripts/search.ts +245 -245
  88. package/src/scripts/sidebar-scroll.ts +61 -61
  89. package/src/styles/global.css +40 -40
@@ -1,1792 +1,1792 @@
1
- ---
2
- import fs from 'node:fs';
3
- import { Code } from 'astro:components';
4
- import {
5
- exampleFromSchema,
6
- emptyValueFromSchema,
7
- primaryContentType,
8
- buildCurlSnippet,
9
- buildFetchSnippet,
10
- buildPythonSnippet,
11
- buildPhpSnippet,
12
- buildGoSnippet,
13
- buildJavaSnippet,
14
- buildRubySnippet,
15
- findOperationFile,
16
- type OpenApiOperation,
17
- } from '../lib/openapi-render';
18
- import { parseOpenApiRef } from '../lib/openapi-ref.js';
19
- import { loadDocsConfig, resolveCodeblockTheme } from '../lib/config';
20
- import ApiLangSelect from './ApiLangSelect.astro';
21
-
22
- interface Props {
23
- operation: string;
24
- contentDir: string;
25
- }
26
- const { operation, contentDir } = Astro.props as Props;
27
-
28
- // Shiki language id for each request-sample tab - <Code/> falls back to
29
- // "plaintext" for anything it doesn't recognize, so this only needs to
30
- // cover the ids actually used by `samples` below.
31
- const SNIPPET_LANG: Record<string, string> = {
32
- curl: 'bash',
33
- js: 'javascript',
34
- py: 'python',
35
- php: 'php',
36
- go: 'go',
37
- java: 'java',
38
- ruby: 'ruby',
39
- };
40
- // Iconify id for each request-sample tab's language, shown in both of
41
- // this panel's language dropdowns (sidebar + Try-it modal) - see
42
- // ApiLangSelect.astro. mdi's language-* set (not simple-icons' brand
43
- // marks) since those render as plain currentColor monochrome glyphs,
44
- // matching every other inline icon on this page instead of introducing
45
- // a second, full-color icon style just for this one control.
46
- const LANG_ICON: Record<string, string> = {
47
- curl: 'mdi:console',
48
- js: 'mdi:language-javascript',
49
- py: 'mdi:language-python',
50
- php: 'mdi:language-php',
51
- go: 'mdi:language-go',
52
- java: 'mdi:language-java',
53
- ruby: 'mdi:language-ruby',
54
- };
55
- // Same dual light/dark themes as the sitewide MDX code-fence config in
56
- // astro.config.mjs (writedocs.json's styles.codeblocks, via the shared
57
- // resolveCodeblockTheme() helper - <Code/> doesn't inherit
58
- // markdown.shikiConfig at all, so this needs its own copy of the same
59
- // resolved value), so the response/request panels here follow the
60
- // [data-theme] toggle exactly like article content does - see the
61
- // [data-theme='dark'] :global(.astro-code) override in BaseLayout.astro.
62
- const docsConfig = loadDocsConfig(contentDir);
63
- const SNIPPET_THEMES = resolveCodeblockTheme(docsConfig);
64
- // Whether the Send button in the Try-it modal routes its request through
65
- // writedocs' CORS proxy - see PROXY_BASE_URL in the <script> below.
66
- const proxyEnabled = docsConfig.api.proxy;
67
-
68
- // "METHOD /path", or Mintlify's "spec.json METHOD /path" - see lib/openapi-ref.js.
69
- const ref = parseOpenApiRef(operation);
70
- const method = ref?.method ?? '';
71
- const urlPath = ref?.path ?? '';
72
- const opFile = ref ? findOperationFile(contentDir, method, urlPath, ref.spec) : null;
73
- const op: OpenApiOperation | null = opFile ? JSON.parse(fs.readFileSync(opFile, 'utf-8')) : null;
74
-
75
- // ApiPlayground.astro (rendered in the article column) already shows a
76
- // clear error when no matching operation is found - this panel just
77
- // quietly renders nothing in that case rather than duplicating it.
78
- const servers = op?.servers ?? [];
79
- const baseUrl = servers[0]?.url ?? '';
80
- const sampleBaseUrl = baseUrl || 'https://api.example.com';
81
- const pathParams = op?.parameters.filter((p) => p.in === 'path') ?? [];
82
- const queryParams = op?.parameters.filter((p) => p.in === 'query') ?? [];
83
- const headerParams = op?.parameters.filter((p) => p.in === 'header') ?? [];
84
-
85
- const requestContentType = op ? primaryContentType(op.requestBody?.content) : null;
86
- const requestSchema = requestContentType ? op?.requestBody?.content?.[requestContentType]?.schema : undefined;
87
- const requestExample = requestSchema ? JSON.stringify(exampleFromSchema(requestSchema), null, 2) : null;
88
- // What the Body textarea resets to when the reader picks "Default" in
89
- // the examples select (see requestExampleEntries below) - the same
90
- // field shape as requestExample above, but blank rather than filled
91
- // with synthesized placeholder values, so picking it clears prior
92
- // input without losing sight of what the body actually needs.
93
- const blankRequestExample = requestSchema ? JSON.stringify(emptyValueFromSchema(requestSchema), null, 2) : null;
94
- // OpenAPI's plural, *named* `examples` map on the request body's media
95
- // type object (distinct from the singular `example`/schema-derived
96
- // default above) - when a spec author provides one or more of these,
97
- // the modal gets a selector for them (see the "Example" <select> in the
98
- // modal head below) that swaps the Body textarea to that exact value on
99
- // selection. Scoped deliberately to the request body only, not
100
- // parameters - OpenAPI parameters can carry their own `examples` map
101
- // too, but there's no standard link between "this body example" and
102
- // "these parameter values" the way there sometimes conceptually is in a
103
- // hand-written doc, so auto-populating anything beyond the body from a
104
- // body example would be guessing at an association the spec itself
105
- // doesn't actually make.
106
- const requestExamples = requestContentType ? (op?.requestBody?.content?.[requestContentType]?.examples ?? {}) : {};
107
- const requestExampleEntries = Object.entries(requestExamples);
108
- // The modal's own header title - "the endpoint title, not a dropdown"
109
- // (an earlier version showed the raw path here instead, which reads
110
- // more like plumbing than a title a reader would recognize). Same
111
- // summary-with-a-fallback op.summary ?? "METHOD /path" that
112
- // generate-api-pages.js already uses for a generated stub page's own
113
- // <title>, so the modal's heading matches whatever the reader already
114
- // clicked "Try it" from.
115
- const modalTitle = op ? (op.summary ?? `${op.method} ${op.path}`) : '';
116
-
117
- const samples = op
118
- ? [
119
- { id: 'curl', label: 'cURL', code: buildCurlSnippet(op, sampleBaseUrl) },
120
- { id: 'js', label: 'JavaScript', code: buildFetchSnippet(op, sampleBaseUrl) },
121
- { id: 'py', label: 'Python', code: buildPythonSnippet(op, sampleBaseUrl) },
122
- { id: 'php', label: 'PHP', code: buildPhpSnippet(op, sampleBaseUrl) },
123
- { id: 'go', label: 'Go', code: buildGoSnippet(op, sampleBaseUrl) },
124
- { id: 'java', label: 'Java', code: buildJavaSnippet(op, sampleBaseUrl) },
125
- { id: 'ruby', label: 'Ruby', code: buildRubySnippet(op, sampleBaseUrl) },
126
- ]
127
- : [];
128
- // Same {id, label} shape samples already carries, plus the icon each
129
- // dropdown item shows - kept as its own array (not folded into samples
130
- // itself) since ApiLangSelect.astro only needs id/label/icon, not the
131
- // snippet code samples also carries.
132
- const langOptions = samples.map((s) => ({ id: s.id, label: s.label, icon: LANG_ICON[s.id] ?? 'mdi:code-tags' }));
133
-
134
- // Classifies a response status into the same ok/error tone the Try-it
135
- // modal's own live response status already uses (wd-api-status-ok/
136
- // -error, see the <script> below) - reused here for the status select's
137
- // leading color dot, so "green means success, red means an error status"
138
- // reads consistently whether it's a live request result or just a
139
- // static example being browsed. Anything outside 2xx/4xx/5xx (a 3xx
140
- // redirect, mainly) gets a neutral gray dot rather than being force-fit
141
- // into ok-or-error.
142
- function statusToneClass(status: string): string {
143
- const code = parseInt(status, 10);
144
- if (code >= 200 && code < 300) return 'wd-api-status-dot-ok';
145
- if (code >= 400) return 'wd-api-status-dot-error';
146
- return 'wd-api-status-dot-neutral';
147
- }
148
-
149
- const responseExamples = op
150
- ? Object.entries(op.responses).map(([status, resp]) => {
151
- const contentType = primaryContentType(resp.content);
152
- const schema = contentType ? resp.content?.[contentType]?.schema : undefined;
153
- return {
154
- status,
155
- tone: statusToneClass(status),
156
- code: schema ? JSON.stringify(exampleFromSchema(schema), null, 2) : '(no body)',
157
- };
158
- })
159
- : [];
160
-
161
- const paramsJson = JSON.stringify(op?.parameters ?? []);
162
- const securityJson = JSON.stringify(op?.security ?? []);
163
- ---
164
-
165
- {op && (
166
- <div class="wd-api-panel" data-api-panel data-method={op.method} data-path={op.path}>
167
- <div class="wd-api-card">
168
- <div class="wd-api-card-head">
169
- <span class="wd-api-card-label">Request</span>
170
- <div class="wd-api-card-actions">
171
- <ApiLangSelect options={langOptions} rolePrefix="lang" ariaLabel="Language" />
172
- <button type="button" class="wd-api-try-inline" data-role="open-modal">
173
- Try <span class="wd-api-try-icon" aria-hidden="true">&#9656;</span>
174
- </button>
175
- </div>
176
- </div>
177
- <div class="wd-api-card-body">
178
- {samples.map((s, i) => (
179
- <Code
180
- code={s.code}
181
- lang={SNIPPET_LANG[s.id] ?? 'plaintext'}
182
- themes={SNIPPET_THEMES}
183
- class="wd-api-pre wd-api-pre-lines"
184
- data-lang-panel={s.id}
185
- style={`display: ${i === 0 ? 'block' : 'none'}`}
186
- />
187
- ))}
188
- <button type="button" class="wd-api-code-copy-btn" data-role="copy-request" aria-label="Copy">⧉</button>
189
- </div>
190
- </div>
191
-
192
- {responseExamples.length > 0 && (
193
- <div class="wd-api-card">
194
- <div class="wd-api-card-head">
195
- <span class="wd-api-card-label">Response</span>
196
- <div class="wd-api-card-actions">
197
- <span class="wd-api-select-wrap wd-api-status-select-wrap">
198
- <span class={`wd-api-status-dot ${responseExamples[0].tone}`} data-role="status-dot"></span>
199
- <select class="wd-api-select" data-role="status-select" aria-label="Status">
200
- {responseExamples.map((r) => <option value={r.status} data-tone={r.tone}>{r.status}</option>)}
201
- </select>
202
- </span>
203
- </div>
204
- </div>
205
- <div class="wd-api-card-body">
206
- {responseExamples.map((r, i) => (
207
- <Code
208
- code={r.code}
209
- lang="json"
210
- themes={SNIPPET_THEMES}
211
- class="wd-api-pre wd-api-pre-lines"
212
- data-status-panel={r.status}
213
- style={`display: ${i === 0 ? 'block' : 'none'}`}
214
- />
215
- ))}
216
- <button type="button" class="wd-api-code-copy-btn" data-role="copy-response" aria-label="Copy">⧉</button>
217
- </div>
218
- </div>
219
- )}
220
- </div>
221
-
222
- <div class="wd-api-modal-overlay" data-role="modal-overlay" hidden>
223
- <div class="wd-api-modal" role="dialog" aria-modal="true" aria-label="Try it">
224
- <div class="wd-api-modal-head">
225
- <div class="wd-api-modal-title">
226
- <span class={`wd-api-method wd-api-method-${op.method.toLowerCase()}`}>{op.method}</span>
227
- <span class="wd-api-modal-title-text">{modalTitle}</span>
228
- </div>
229
- {requestExampleEntries.length > 0 && (
230
- <span class="wd-api-select-wrap wd-api-modal-example-wrap">
231
- <select class="wd-api-select" data-role="example-select" aria-label="Example">
232
- <option value="">Default</option>
233
- {requestExampleEntries.map(([name, ex]) => (
234
- <option value={name}>{ex.summary ?? name}</option>
235
- ))}
236
- </select>
237
- </span>
238
- )}
239
- <div class="wd-api-modal-actions">
240
- <button type="button" class="wd-api-send" data-role="send">Send <span aria-hidden="true">&#9656;</span></button>
241
- <button type="button" class="wd-api-icon-btn" data-role="close-modal" aria-label="Close">&times;</button>
242
- </div>
243
- </div>
244
- <div
245
- class="wd-api-modal-body"
246
- data-api-tryit
247
- data-params={paramsJson}
248
- data-security={securityJson}
249
- data-examples={JSON.stringify(requestExamples)}
250
- data-blank-body={blankRequestExample}
251
- data-method={op.method}
252
- data-path={op.path}
253
- data-themes={JSON.stringify(SNIPPET_THEMES)}
254
- data-proxy={proxyEnabled}
255
- >
256
- <div class="wd-api-modal-form">
257
- <div class="wd-api-modal-url-bar">
258
- <span class={`wd-api-method wd-api-method-${op.method.toLowerCase()}`}>{op.method}</span>
259
- {servers.length > 1 ? (
260
- // Multiple servers in the spec - a real <select>, not free
261
- // text, since these are the only base URLs the operation
262
- // actually supports. Each option's own label is the full
263
- // concatenated URL (server + path), not just the server,
264
- // so the control always reads as one complete request URL
265
- // whether it's open or closed - never a bare host with the
266
- // path implied elsewhere.
267
- <select class="wd-api-url-select" data-role="base-url" aria-label="Server">
268
- {servers.map((s) => (
269
- <option value={s.url}>{s.url}{op.path}</option>
270
- ))}
271
- </select>
272
- ) : (
273
- // Single server (the common case) - nothing to choose
274
- // between, so this is plain non-editable text rather than
275
- // an input the reader might mistake for something they
276
- // need to fill in. data-value carries the base URL alone
277
- // (the part collectLiveRequest() below needs) since the
278
- // element's own text content is the base+path combined.
279
- <span class="wd-api-url-full" data-role="base-url" data-value={baseUrl}>{baseUrl}{op.path}</span>
280
- )}
281
- </div>
282
-
283
- {headerParams.length > 0 && (
284
- <div class="wd-api-field-group">
285
- <span class="wd-api-field-group-label">Header</span>
286
- {headerParams.map((p) => (
287
- <label class="wd-api-field">
288
- <span>{p.name}{p.required && <span class="wd-api-pill wd-api-pill-required">required</span>}</span>
289
- <input type="text" class="wd-api-input" data-role="param" data-param-name={p.name} data-param-in="header" />
290
- </label>
291
- ))}
292
- </div>
293
- )}
294
-
295
- {pathParams.length > 0 && (
296
- <div class="wd-api-field-group">
297
- <span class="wd-api-field-group-label">Path</span>
298
- {pathParams.map((p) => (
299
- <label class="wd-api-field">
300
- <span>{p.name}{p.required && <span class="wd-api-pill wd-api-pill-required">required</span>}</span>
301
- <input
302
- type="text"
303
- class="wd-api-input"
304
- data-role="param"
305
- data-param-name={p.name}
306
- data-param-in="path"
307
- value={String(p.example ?? p.schema?.example ?? p.schema?.default ?? '')}
308
- />
309
- </label>
310
- ))}
311
- </div>
312
- )}
313
-
314
- {queryParams.length > 0 && (
315
- <div class="wd-api-field-group">
316
- <span class="wd-api-field-group-label">Query</span>
317
- {queryParams.map((p) => (
318
- <label class="wd-api-field">
319
- <span>{p.name}{p.required && <span class="wd-api-pill wd-api-pill-required">required</span>}</span>
320
- <input
321
- type="text"
322
- class="wd-api-input"
323
- data-role="param"
324
- data-param-name={p.name}
325
- data-param-in="query"
326
- value={String(p.example ?? p.schema?.example ?? p.schema?.default ?? '')}
327
- />
328
- </label>
329
- ))}
330
- </div>
331
- )}
332
-
333
- {requestSchema && (
334
- <div class="wd-api-field-group">
335
- <span class="wd-api-field-group-label">Body</span>
336
- <textarea class="wd-api-textarea" data-role="body" rows="8">{requestExample}</textarea>
337
- </div>
338
- )}
339
- </div>
340
-
341
- <div class="wd-api-modal-preview">
342
- {op.security.length > 0 && (
343
- <div class="wd-api-card wd-api-auth-card">
344
- <div class="wd-api-card-head">
345
- <span class="wd-api-card-label">Authentication</span>
346
- </div>
347
- <div class="wd-api-card-body wd-api-auth-card-body">
348
- {op.security.map((s) => {
349
- const label =
350
- s.type === 'http' && s.scheme === 'bearer' ? 'Bearer token' :
351
- s.type === 'http' && s.scheme === 'basic' ? 'Basic auth (user:pass)' :
352
- s.name;
353
- return (
354
- <label class="wd-api-auth-field">
355
- <input
356
- type="text"
357
- class="wd-api-input wd-api-auth-input"
358
- data-role="auth"
359
- data-auth-name={s.name}
360
- data-auth-type={s.type}
361
- data-auth-scheme={s.scheme ?? ''}
362
- data-auth-in={s.in ?? ''}
363
- placeholder={`<${label}>`}
364
- />
365
- <span class="wd-api-auth-icons">
366
- <span class="wd-api-auth-icon" title="Sent with your request, kept only in this browser">
367
- <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
368
- <rect x="2.5" y="5.5" width="7" height="5" rx="1" stroke="currentColor" stroke-width="1.1" fill="none" />
369
- <path d="M4 5.5V4a2 2 0 0 1 4 0v1.5" stroke="currentColor" stroke-width="1.1" fill="none" stroke-linecap="round" />
370
- </svg>
371
- </span>
372
- <span class="wd-api-auth-icon" title={label}>
373
- <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
374
- <circle cx="6" cy="6" r="5" stroke="currentColor" stroke-width="1.1" fill="none" />
375
- <text x="6" y="8.3" text-anchor="middle" font-size="6.5" fill="currentColor" stroke="none" font-family="sans-serif">?</text>
376
- </svg>
377
- </span>
378
- </span>
379
- </label>
380
- );
381
- })}
382
- </div>
383
- </div>
384
- )}
385
- <div class="wd-api-card">
386
- <div class="wd-api-card-head">
387
- <span class="wd-api-card-label">Request</span>
388
- <ApiLangSelect options={langOptions} rolePrefix="modal-lang" ariaLabel="Language" />
389
- </div>
390
- <div class="wd-api-card-body">
391
- {samples.map((s, i) => (
392
- <pre
393
- class="wd-api-pre"
394
- data-modal-lang-panel={s.id}
395
- style={`display: ${i === 0 ? 'block' : 'none'}`}
396
- ><code>{s.code}</code></pre>
397
- ))}
398
- </div>
399
- </div>
400
- <div class="wd-api-card">
401
- <div class="wd-api-card-head">
402
- <span class="wd-api-card-label">Response</span>
403
- </div>
404
- <div class="wd-api-card-body">
405
- <div class="wd-api-response-status" data-role="response-status"></div>
406
- <pre class="wd-api-pre" data-role="response-body"><code></code></pre>
407
- </div>
408
- </div>
409
- </div>
410
- </div>
411
- </div>
412
- </div>
413
- )}
414
-
415
- <style is:global>
416
- /* Widens the shared .wd-toc-col (defined in BaseLayout.astro) only on
417
- pages that actually render this panel into it, rather than adding a
418
- prop BaseLayout has to thread through just for this - :has() lets
419
- the override live entirely in this component instead. */
420
- .wd-toc-col:has(.wd-api-panel) {
421
- width: 380px;
422
- }
423
- /* top/max-height match Sidebar.astro/TableOfContents.astro's own
424
- sticky columns - see Sidebar.astro's comment on --wd-topbar-offset
425
- (src/scripts/topbar-offset.ts), the topbar's real measured height. */
426
- .wd-api-panel {
427
- position: sticky;
428
- top: var(--wd-topbar-offset, 5rem);
429
- padding: 1.5rem 0 1.5rem 1rem;
430
- max-height: calc(100vh - var(--wd-topbar-offset, 5rem));
431
- overflow-y: auto;
432
- display: flex;
433
- flex-direction: column;
434
- gap: 1rem;
435
- }
436
- .wd-api-card {
437
- background: var(--wd-surface);
438
- border: 1px solid var(--wd-border);
439
- border-radius: 0.75rem;
440
- /* Soft elevation - same scale TopBar/MobileMenu's own dropdown panel
441
- (dropdown.css's .wd-dropdown-menu) already uses for a resting,
442
- non-modal floating panel - what turns this from a flat bordered
443
- box into a card that visually lifts off the page background,
444
- matching the reference design's own drop shadow around both
445
- cards. */
446
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
447
- }
448
- /* Sidebar-only (the Try-it modal reuses .wd-api-card too, inside
449
- .wd-api-modal-preview - a plain scrolling column with no height cap
450
- of its own, so it never needs any of this). .wd-api-panel is a flex
451
- column with its own bounded max-height + overflow-y: auto (see that
452
- rule's comment) - by default a flex item won't shrink below its own
453
- content's natural height, so without help here, two cards taller
454
- than the panel just push the *panel* into needing to scroll as a
455
- whole (previously "fixed" by giving cards flex-shrink: 0, forcing
456
- every code block to keep its own fixed max-height regardless of how
457
- little room was actually left - the panel scrolling, not the code
458
- blocks resizing to fit it, which is backwards from what a reader
459
- actually wants: both Request and Response staying visible at once,
460
- each shrinking to fit, only truly overflowing (this rule's own
461
- overflow-y: auto, still very much intentional as a last resort) once
462
- even a sensible minimum won't fit both.
463
- flex: 0 1 auto (grow: 0, shrink: 1, basis: auto) is what makes a
464
- card sit at its own natural size when there's room, and only shrink
465
- - never stretch - when there isn't; min-height: 0 lifts the default
466
- "never shrink below natural content height" floor so that shrink
467
- can actually happen. The genuine floor lives one level down, on
468
- .wd-api-card-head (never shrinks at all - the RESPONSE label,
469
- language dropdown etc. always stay fully visible) and
470
- .wd-api-card-body (shrinks, but never below a legible minimum - see
471
- that rule's own comment).
472
-
473
- Two things had to be true at once here, and getting only one right
474
- broke the other (both tried and measured against a real headless
475
- render before landing on this):
476
-
477
- 1) min-height: 0 is required for the card to shrink at all below its
478
- natural content height - flex items default to min-height: auto,
479
- which without this override refuses to shrink a flex *container*
480
- item below its own children's natural (max-content) size. Tried
481
- leaving this at the default `auto` instead, on the theory that
482
- auto would resolve to the "real" content-based minimum (head's
483
- natural height + body's own 8rem floor, ~11rem) - measured
484
- against a real build instead of assumed, and it doesn't: Chromium
485
- resolves a flex container's automatic minimum size to something
486
- much closer to its full natural (unshrunk) content height here,
487
- not the smaller nested-floor value - so `auto` just pinned every
488
- card at full height regardless of available space, the opposite
489
- of what this whole redesign is for.
490
-
491
- 2) But min-height: 0 alone throws away the card's *only* protection
492
- against being shrunk smaller than its own children can actually
493
- render at - .wd-api-panel's own flex-shrink distributes the
494
- deficit across both cards using each card's min-height as its
495
- floor, with no visibility into what's two levels further down
496
- (card-head's flex-shrink: 0, card-body's own min-height: 8rem);
497
- min-height: 0 tells that outer algorithm "I have no floor," so it
498
- shrinks the card's own box smaller than head+body's genuine
499
- minimum, and - since a shrunk-too-small flex item doesn't clip
500
- its own overflowing children by default - the code block renders
501
- at its real 8rem floor anyway, just spilling past the card's own
502
- (too-small) box into the space belowe reserved for the next
503
- sibling card. Measured this directly: at a short enough viewport,
504
- card height read smaller than head-height + body-height combined.
505
-
506
- The explicit calc() below is what actually fixes both at once: an
507
- honest floor (safely above the ~2.95rem this card-head design
508
- measures at across themes, rounded up to 3.5rem for headroom) plus
509
- card-body's own real 8rem floor, so .wd-api-panel's shrink algorithm
510
- now sees the true minimum instead of either extreme. */
511
- .wd-api-panel .wd-api-card {
512
- display: flex;
513
- flex-direction: column;
514
- flex: 0 1 auto;
515
- min-height: calc(3.5rem + 8rem);
516
- }
517
- .wd-api-panel .wd-api-card-head {
518
- flex-shrink: 0;
519
- }
520
- .wd-api-card-head {
521
- display: flex;
522
- align-items: center;
523
- justify-content: space-between;
524
- gap: 0.5rem;
525
- padding: 0.65rem 0.85rem;
526
- border-bottom: 1px solid var(--wd-border);
527
- }
528
- .wd-api-card-label {
529
- font-size: 0.75rem;
530
- font-weight: 700;
531
- text-transform: uppercase;
532
- letter-spacing: 0.05em;
533
- color: var(--wd-text-muted);
534
- }
535
- .wd-api-card-actions {
536
- display: flex;
537
- align-items: center;
538
- gap: 0.5rem;
539
- }
540
- /* Distinct tinted card so Authentication reads as its own concern
541
- sitting above Request/Response, not a third copy of the same
542
- neutral-surface card - color-mix over --wd-primary matches the
543
- tinted-background convention used elsewhere (NavTree.astro's hover
544
- state, the status dot colors below). */
545
- .wd-api-auth-card {
546
- background: color-mix(in srgb, var(--wd-primary) 6%, var(--wd-surface));
547
- border-color: color-mix(in srgb, var(--wd-primary) 18%, var(--wd-border));
548
- }
549
- .wd-api-auth-card-body {
550
- display: flex;
551
- flex-direction: column;
552
- gap: 0.6rem;
553
- padding: 0.85rem;
554
- }
555
- .wd-api-auth-field {
556
- display: flex;
557
- align-items: center;
558
- gap: 0.5rem;
559
- }
560
- .wd-api-auth-input {
561
- flex: 1;
562
- min-width: 0;
563
- }
564
- .wd-api-auth-icons {
565
- display: flex;
566
- align-items: center;
567
- gap: 0.35rem;
568
- flex-shrink: 0;
569
- color: var(--wd-text-muted);
570
- }
571
- .wd-api-auth-icon {
572
- display: inline-flex;
573
- }
574
- /* Wraps the remaining plain <select> controls on this panel - the
575
- status select-with-dot (Response), the Try-it modal's Example picker,
576
- and its multi-server base-URL select - in the same rounded-pill
577
- chrome as ApiLangSelect.astro's own trigger button, so every control
578
- in this family still reads as one kind of thing even though the
579
- language pickers themselves moved to that separate icon+label+
580
- checkmark dropdown rather than a native <select>. The wrapper owns
581
- border/radius/background; the <select> inside is stripped down to
582
- borderless/transparent (below) so it doesn't paint a second,
583
- conflicting box on top of its own wrapper's. */
584
- .wd-api-select-wrap {
585
- display: inline-flex;
586
- align-items: center;
587
- gap: 0.35rem;
588
- padding: 0.2rem 0.55rem;
589
- border-radius: 999px;
590
- border: 1px solid var(--wd-border);
591
- background: var(--wd-background);
592
- }
593
- .wd-api-select {
594
- border: none;
595
- background: none;
596
- padding: 0;
597
- margin: 0;
598
- font-size: 0.75rem;
599
- font-family: inherit;
600
- color: var(--wd-text);
601
- cursor: pointer;
602
- /* appearance: none + this file's own chevron svg (data-uri, same
603
- stroke/curve as Expandable.astro's/NavTree.astro's own chevrons -
604
- one visual "this is a dropdown" affordance across the whole site,
605
- not a second one improvised just for this control) replaces each
606
- browser's own inconsistently-styled native arrow, so the pill
607
- reads the same in Chrome/Firefox/Safari alike. */
608
- appearance: none;
609
- -webkit-appearance: none;
610
- background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'%3E%3Cpath d='M2 3.5L5 6.5L8 3.5' stroke='%23888' stroke-width='1.4' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
611
- background-repeat: no-repeat;
612
- background-position: right center;
613
- padding-right: 1rem;
614
- }
615
- /* The dropdown list a native <select> opens is a separate,
616
- browser-rendered popup that the rules above (all scoped to the
617
- closed box) can't reach - left alone it renders with the OS/browser
618
- default light popup (white background, near-black text) regardless
619
- of the site's dark theme, which is exactly the jarring flash of
620
- light seen against everything else here. Chrome/Firefox/Edge do
621
- respect background-color/color set directly on <option>, so this
622
- is the most that can be done without replacing the native <select>
623
- with a fully custom listbox - Safari has weaker support and falls
624
- back to its own default popup, but degrades no worse than before. */
625
- .wd-api-select option,
626
- .wd-api-url-select option {
627
- background-color: var(--wd-surface);
628
- color: var(--wd-text);
629
- }
630
- .wd-api-status-select-wrap {
631
- padding-left: 0.45rem;
632
- }
633
- .wd-api-status-dot {
634
- flex-shrink: 0;
635
- width: 0.5rem;
636
- height: 0.5rem;
637
- border-radius: 999px;
638
- background: var(--wd-text-muted);
639
- }
640
- .wd-api-status-dot-ok {
641
- background: #16a34a;
642
- }
643
- .wd-api-status-dot-error {
644
- background: #dc2626;
645
- }
646
- .wd-api-status-dot-neutral {
647
- background: var(--wd-text-muted);
648
- }
649
- /* The "Try it" button used to be a separate full-width block below the
650
- card; moved inline into the Request card's own header, next to the
651
- language select, matching the reference design - a compact pill
652
- button rather than a full-width bar. */
653
- .wd-api-try-inline {
654
- display: inline-flex;
655
- align-items: center;
656
- gap: 0.3rem;
657
- padding: 0.3rem 0.75rem;
658
- border-radius: 0.5rem;
659
- border: none;
660
- background: var(--wd-primary);
661
- color: var(--wd-on-primary);
662
- font-size: 0.75rem;
663
- font-weight: 600;
664
- cursor: pointer;
665
- }
666
- .wd-api-try-icon {
667
- font-size: 0.65rem;
668
- }
669
- .wd-api-icon-btn {
670
- display: inline-flex;
671
- align-items: center;
672
- justify-content: center;
673
- width: 1.8rem;
674
- height: 1.8rem;
675
- border-radius: 0.4rem;
676
- border: none;
677
- background: none;
678
- color: var(--wd-text-muted);
679
- cursor: pointer;
680
- font-size: 0.95rem;
681
- }
682
- .wd-api-icon-btn:hover {
683
- background: var(--wd-background);
684
- color: var(--wd-text);
685
- }
686
- /* Clips its own content (a code block's baked-in Shiki background,
687
- mainly) to the card's bottom corners - moved here from .wd-api-card
688
- itself so that clip only ever applies to the body, not the head
689
- above it, where ApiLangSelect.astro's dropdown menu now lives.
690
- overflow: hidden directly on .wd-api-card clipped that menu too
691
- whenever it opened past the card's own edge (visible on any
692
- narrower/shorter card, e.g. a short request sample) - the head
693
- never had a distinct background box of its own needing this same
694
- clip, so it doesn't need overflow: hidden at all. */
695
- .wd-api-card-body {
696
- position: relative;
697
- padding: 0.75rem;
698
- overflow: hidden;
699
- border-radius: 0 0 0.75rem 0.75rem;
700
- }
701
- /* Floating overlay on top of the code block itself, not a header
702
- button - matches the reference design, where the copy affordance
703
- sits at the top-right corner of the code area rather than beside
704
- the language/status select. Always visible here (unlike
705
- .wd-code-copy-btn's hover-reveal in [...slug].astro, the same idea
706
- applied to prose code fences) - this is a persistent reference
707
- panel a reader is actively using, not flowing article content where
708
- a visible-on-hover control is less visually noisy. */
709
- .wd-api-code-copy-btn {
710
- position: absolute;
711
- top: 0.65rem;
712
- right: 0.65rem;
713
- z-index: 1;
714
- display: inline-flex;
715
- align-items: center;
716
- justify-content: center;
717
- width: 1.7rem;
718
- height: 1.7rem;
719
- padding: 0;
720
- border-radius: 0.4rem;
721
- border: 1px solid var(--wd-border);
722
- background: var(--wd-surface);
723
- color: var(--wd-text-muted);
724
- font-size: 0.85rem;
725
- line-height: 1;
726
- cursor: pointer;
727
- }
728
- .wd-api-code-copy-btn:hover {
729
- color: var(--wd-text);
730
- background: var(--wd-background);
731
- }
732
- /* Line-number gutter - the exact same CSS-counter approach
733
- .wd-code-lines uses for a fenced (```) content code block
734
- ([...slug].astro's own comment on that rule explains the mechanism)
735
- - Astro's <Code/> (used for these sidebar samples) produces the
736
- identical per-line `.line` span structure Shiki's markdown pipeline
737
- does, so the same counter trick applies unchanged. Unconditional
738
- here (no opt-in class/meta-flag needed, unlike article content) -
739
- every request/response sample in this panel always shows line
740
- numbers, matching the reference design. */
741
- .wd-api-pre-lines code {
742
- counter-reset: wd-api-code-line;
743
- }
744
- .wd-api-pre-lines .line {
745
- counter-increment: wd-api-code-line;
746
- }
747
- .wd-api-pre-lines .line::before {
748
- content: counter(wd-api-code-line);
749
- display: inline-block;
750
- width: 1.6em;
751
- margin-right: 1em;
752
- text-align: right;
753
- color: var(--wd-text-muted);
754
- user-select: none;
755
- }
756
- .wd-api-card-body .wd-api-pre {
757
- border: none;
758
- background: none;
759
- padding: 0;
760
- }
761
- /* max-height + overflow-y (on top of the pre-existing overflow-x, for
762
- a long single line like a curl command's own URL) is what makes a
763
- long code block scroll *internally* instead of just growing the
764
- card to fit it - without this, a request/response body long enough
765
- to need it (the kitchen-sink POST .../variants example this was
766
- caught against, comparing its 201/400/404 response bodies of very
767
- different lengths) just kept growing the Request card taller every
768
- time more of it needed to render, which - since both cards share
769
- one sticky, fixed-max-height panel (.wd-api-panel, see its own
770
- comment) - pushed the Response card further down and further out of
771
- the panel's own bounded height each time, looking like it was
772
- "getting more hidden" the more content the Request card grew to
773
- fit. Bounding every .wd-api-pre's own height here fixes both at
774
- once: the block itself gets a real scrollbar for content past this
775
- height, and neither card can grow tall enough to squeeze its sibling
776
- out of view anymore. Applies to every .wd-api-pre in this file
777
- uniformly - the sidebar's Request/Response cards and the Try-it
778
- modal's own preview panels (request samples + the live response
779
- body) all share this one class, so one rule covers all of them. */
780
- .wd-api-pre {
781
- overflow-x: auto;
782
- overflow-y: auto;
783
- max-height: 20rem;
784
- font-size: 0.8rem;
785
- margin: 0;
786
- }
787
- .wd-api-pre code {
788
- background: none;
789
- padding: 0;
790
- white-space: pre;
791
- }
792
- /* The sidebar request/response samples are rendered via astro:components'
793
- <Code/> (see the frontmatter) so they get real Shiki highlighting
794
- that follows the site's [data-theme] toggle. Earlier this forced
795
- the baked-in background transparent to blend into .wd-api-card's
796
- own surface color - but that strips a theme's background away
797
- while keeping its foreground, which only looks right for themes
798
- whose foreground happens to already have enough contrast against
799
- the card's own (unrelated) surface color. A regular MDX fenced
800
- code block never does this (see .wd-article pre.astro-code in
801
- [...slug].astro) - it always keeps the theme's own background+
802
- foreground pairing intact, which is what makes *any* Shiki theme
803
- name safe to use on either side of writedocs.json's styles.codeblocks.
804
- Matching that here instead: the card-body's own padding moves onto
805
- the codeblock itself, so the theme's real background fills the
806
- card edge-to-edge (clipped to its rounded corners by .wd-api-card's
807
- own overflow: hidden) exactly like a regular content codeblock,
808
- rather than floating disconnected from it. */
809
- .wd-api-panel .wd-api-card-body {
810
- padding: 0;
811
- /* The genuine floor .wd-api-panel .wd-api-card's own comment refers
812
- to: this can shrink (flex: 1 1 auto, min-height overridden down
813
- from its own multi-rem default below) as the panel runs out of
814
- room, but never past ~8rem - enough for a handful of code lines to
815
- stay readable. display: flex here (not the .astro-code child
816
- directly) is what lets that child claim 100% of whatever height
817
- this ends up with via its own flex: 1 below, in place of the fixed
818
- max-height: 20rem every other .wd-api-pre in this file still uses
819
- (Try-it modal's own preview panels, .wd-api-pre's own comment) -
820
- those sit in .wd-api-modal-preview, a plain scrolling column with
821
- no height cap of its own, so they never hit this squeeze at all. */
822
- display: flex;
823
- flex-direction: column;
824
- flex: 1 1 auto;
825
- min-height: 8rem;
826
- }
827
- .wd-api-panel .wd-api-card-body .astro-code {
828
- margin: 0;
829
- padding: 0.75rem 0.9rem;
830
- border-radius: 0;
831
- /* Overrides .wd-api-pre's own max-height: 20rem (that rule's own
832
- comment) - here the code block fills whatever height its
833
- flex-column parent above actually has, shrinking or growing with
834
- it, rather than sitting at a fixed height regardless of how much
835
- (or little) room is actually available. min-height: 0 lets it
836
- shrink freely - the real floor is the parent's own min-height:
837
- 8rem above, not this element's. */
838
- flex: 1 1 auto;
839
- min-height: 0;
840
- max-height: none;
841
- }
842
-
843
- .wd-api-card .wd-api-card-body .shiki {
844
- border-radius: 0;
845
- }
846
- /* The modal's request preview starts as a plain <pre> (see the
847
- frontmatter) and only gains the .astro-code class once
848
- initApiPanel()'s renderModalPanel() swaps in real Shiki output -
849
- lazily, the first time the modal is opened (see loadHighlighter()
850
- in the <script> below). :has() lets the same edge-to-edge treatment
851
- as the sidebar above apply the instant that happens, without any
852
- extra JS to toggle a class on the card-body itself. Before that,
853
- the plain-text panel keeps the ordinary blended-into-the-card look
854
- via .wd-api-card-body .wd-api-pre above. */
855
- .wd-api-modal-preview .wd-api-card-body:has(.astro-code) {
856
- padding: 0;
857
- }
858
- .wd-api-modal-preview .wd-api-card-body .astro-code {
859
- margin: 0;
860
- padding: 0.75rem 0.9rem;
861
- }
862
-
863
- .wd-api-modal-overlay {
864
- position: fixed;
865
- inset: 0;
866
- z-index: 100;
867
- display: flex;
868
- align-items: center;
869
- justify-content: center;
870
- padding: 2rem;
871
- background: rgba(15, 23, 42, 0.5);
872
- }
873
- .wd-api-modal-overlay[hidden] { display: none; }
874
- .wd-api-modal {
875
- width: 100%;
876
- max-width: min(96vw, 1440px);
877
- max-height: 85vh;
878
- display: flex;
879
- flex-direction: column;
880
- background: var(--wd-background);
881
- border: 1px solid var(--wd-border);
882
- border-radius: 0.75rem;
883
- box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
884
- overflow: hidden;
885
- }
886
- .wd-api-modal-head {
887
- display: flex;
888
- align-items: center;
889
- /* Not space-between: the title stays flush left and everything
890
- else (examples select, then Send/Close) is pushed flush right by
891
- .wd-api-modal-example-wrap's margin-left: auto below - so a spec
892
- with no examples still ends up with title-left/actions-right,
893
- the same layout space-between gave before this component had a
894
- middle item to place. */
895
- justify-content: flex-start;
896
- gap: 1rem;
897
- padding: 1rem 1.25rem;
898
- border-bottom: 1px solid var(--wd-border);
899
- flex-shrink: 0;
900
- }
901
- .wd-api-modal-title {
902
- display: flex;
903
- align-items: center;
904
- gap: 0.6rem;
905
- font-size: 0.95rem;
906
- }
907
- .wd-api-modal-title-text {
908
- font-weight: 600;
909
- color: var(--wd-heading);
910
- }
911
- /* Only rendered when the operation's request body actually carries a
912
- named `examples` map (see requestExampleEntries above) - sits
913
- between the title and the Send/Close actions when present. */
914
- .wd-api-modal-example-wrap {
915
- flex-shrink: 0;
916
- }
917
- .wd-api-modal-actions {
918
- display: flex;
919
- align-items: center;
920
- gap: 0.5rem;
921
- /* Pushes just this element flush to the right edge, leaving the
922
- title (and the examples select right after it, when present)
923
- packed on the left per the mockup - works whether or not the
924
- examples select is rendered, so a spec without any `examples`
925
- still lands title-left/actions-right same as before this select
926
- existed. */
927
- margin-left: auto;
928
- }
929
- .wd-api-send {
930
- padding: 0.5rem 1rem;
931
- border-radius: 0.4rem;
932
- border: none;
933
- background: var(--wd-primary);
934
- color: var(--wd-on-primary);
935
- font-size: 0.85rem;
936
- font-weight: 600;
937
- cursor: pointer;
938
- }
939
- .wd-api-send:disabled {
940
- opacity: 0.6;
941
- cursor: default;
942
- }
943
- .wd-api-modal-body {
944
- display: grid;
945
- /* Form (params/body inputs) gets roughly twice the preview
946
- column's width - the form has more to lay out (header/path/
947
- query groups, the body textarea, potentially long field lists),
948
- while the preview is just two-three fixed-height cards. */
949
- grid-template-columns: 2fr 1fr;
950
- gap: 0;
951
- overflow-y: auto;
952
- }
953
- .wd-api-modal-form {
954
- padding: 1.25rem;
955
- border-right: 1px solid var(--wd-border);
956
- overflow-y: auto;
957
- }
958
- .wd-api-modal-preview {
959
- padding: 1.25rem;
960
- display: flex;
961
- flex-direction: column;
962
- gap: 1rem;
963
- overflow-y: auto;
964
- /* No background of its own - inherits .wd-api-modal's background,
965
- same as .wd-api-modal-form on the other side of the divider, so
966
- the two columns read as one surface. The Authentication/Request/
967
- Response cards inside still pop off it via their own
968
- background: var(--wd-surface) (.wd-api-card below). */
969
- }
970
- @media (max-width: 760px) {
971
- .wd-api-modal-body {
972
- grid-template-columns: 1fr;
973
- }
974
- .wd-api-modal-form {
975
- border-right: none;
976
- border-bottom: 1px solid var(--wd-border);
977
- }
978
- }
979
- .wd-api-field {
980
- display: flex;
981
- flex-direction: column;
982
- gap: 0.3rem;
983
- margin-bottom: 0.75rem;
984
- font-size: 0.85rem;
985
- }
986
- .wd-api-field > span:first-child {
987
- color: var(--wd-text-muted);
988
- font-weight: 500;
989
- display: flex;
990
- align-items: center;
991
- gap: 0.4rem;
992
- }
993
- .wd-api-field-group {
994
- margin-bottom: 1.1rem;
995
- }
996
- /* Replaces the old standalone "Base URL" labeled field - a single
997
- method+URL bar where the URL itself is always one element showing
998
- the complete request URL (server + path together), never an
999
- editable text input split from a separately-boxed path. With one
1000
- server in the spec it's plain non-editable text (.wd-api-url-full);
1001
- with more than one, a real <select> (.wd-api-url-select) whose
1002
- every option's own label is already the full concatenated URL, so
1003
- the control still reads as one complete URL whether it's open or
1004
- closed - see the markup above for which one renders. */
1005
- .wd-api-modal-url-bar {
1006
- display: flex;
1007
- align-items: center;
1008
- gap: 0.5rem;
1009
- padding: 0.4rem 0.5rem;
1010
- margin-bottom: 1.1rem;
1011
- border: 1px solid var(--wd-border);
1012
- border-radius: 0.5rem;
1013
- background: var(--wd-background);
1014
- }
1015
- .wd-api-url-full {
1016
- flex: 1;
1017
- min-width: 0;
1018
- overflow-wrap: anywhere;
1019
- color: var(--wd-text);
1020
- font-size: 0.85rem;
1021
- font-family: monospace;
1022
- }
1023
- .wd-api-url-select {
1024
- flex: 1;
1025
- min-width: 0;
1026
- border: none;
1027
- background: none;
1028
- padding: 0.2rem 1rem 0.2rem 0;
1029
- color: var(--wd-text);
1030
- font-size: 0.85rem;
1031
- font-family: monospace;
1032
- /* Same custom-chevron treatment as .wd-api-select below - unlike
1033
- that one this isn't wrapped in a pill, since it needs to read as
1034
- plain inline text flowing right after the method badge, not a
1035
- separate control floating in the bar. */
1036
- appearance: none;
1037
- -webkit-appearance: none;
1038
- background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'%3E%3Cpath d='M2 3.5L5 6.5L8 3.5' stroke='%23888' stroke-width='1.4' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
1039
- background-repeat: no-repeat;
1040
- background-position: right center;
1041
- cursor: pointer;
1042
- }
1043
- .wd-api-url-select:focus {
1044
- outline: none;
1045
- }
1046
- .wd-api-field-group-label {
1047
- display: block;
1048
- font-size: 1rem;
1049
- font-weight: 600;
1050
- color: var(--wd-text);
1051
- margin-bottom: 0.6rem;
1052
- padding-bottom: 0.4rem;
1053
- border-bottom: 1px solid var(--wd-border);
1054
- }
1055
- .wd-api-input,
1056
- .wd-api-textarea {
1057
- width: 100%;
1058
- padding: 0.5rem 0.65rem;
1059
- border: 1px solid var(--wd-border);
1060
- border-radius: 0.4rem;
1061
- background: var(--wd-background);
1062
- color: var(--wd-text);
1063
- font-size: 0.85rem;
1064
- font-family: inherit;
1065
- }
1066
- .wd-api-textarea {
1067
- font-family: monospace;
1068
- resize: vertical;
1069
- }
1070
- .wd-api-response-status {
1071
- font-size: 0.8rem;
1072
- font-weight: 600;
1073
- margin-bottom: 0.5rem;
1074
- color: var(--wd-text-muted);
1075
- }
1076
- .wd-api-response-status.wd-api-status-ok { color: #16a34a; }
1077
- .wd-api-response-status.wd-api-status-error { color: #dc2626; }
1078
- @media (max-width: 1150px) {
1079
- .wd-api-panel { display: none; }
1080
- }
1081
- </style>
1082
-
1083
- <script>
1084
- // Shiki's WASM engine, exactly the 3 grammars the Try-it modal needs,
1085
- // and the 2 writedocs.json styles.codeblocks themes are fetched lazily, only
1086
- // once the modal is actually opened - not on every operation page load
1087
- // - so the live-updating preview can use *real* Shiki highlighting
1088
- // (matching every other codeblock on the site, see ApiReferencePanel's
1089
- // own CSS comment on this) without adding that weight to pages nobody
1090
- // ever opens Try-it on. Declared at true module scope (outside
1091
- // initApiPanel) so it's fetched once and reused across astro:page-load
1092
- // navigations between operation pages - they all share the same
1093
- // writedocs.json styles.codeblocks, so one cached highlighter is always
1094
- // correct regardless of which operation is currently active.
1095
- //
1096
- // Deliberately the fine-grained core API (shiki/core +
1097
- // shiki/engine/oniguruma + the individual @shikijs/langs/* packages)
1098
- // rather than shiki/bundle/web's own createHighlighter(): that
1099
- // convenience wrapper's own docs note "importing this function will
1100
- // bundle all languages and themes" - true even though each is only
1101
- // *fetched* on demand, Vite still has to code-split and ship every
1102
- // bundled language (100+, several hundred KB each for ts/tsx/jsx/...)
1103
- // as its own chunk, just in case. Themes still come from shiki/themes'
1104
- // full by-name lookup table (unavoidable - which theme is needed isn't
1105
- // known until writedocs.json is read, so it can't be a static import like
1106
- // the 3 languages below can), but that alone is a much smaller tax
1107
- // than the language side would have been.
1108
- interface ShikiHighlighter {
1109
- codeToHtml(code: string, options: { lang: string; themes: { light: string; dark: string } }): string;
1110
- }
1111
- let wdHighlighter: ShikiHighlighter | null = null;
1112
- let wdHighlighterPromise: Promise<ShikiHighlighter> | null = null;
1113
- const MODAL_LANG_TO_SHIKI: Record<string, string> = {
1114
- curl: 'bash',
1115
- js: 'javascript',
1116
- py: 'python',
1117
- php: 'php',
1118
- go: 'go',
1119
- java: 'java',
1120
- ruby: 'ruby',
1121
- };
1122
- // cors-anywhere-style proxy: forwards GET/POST/etc to the URL appended
1123
- // after the base (protocol required), preserving method/headers/body,
1124
- // and returns CORS headers so the browser fetch() below succeeds even
1125
- // when the target API itself doesn't send Access-Control-Allow-Origin.
1126
- // Only a fallback: a request goes straight to the API first, and through
1127
- // here only when the browser blocks that (see the send handler below).
1128
- // Toggle via writedocs.json's `api.proxy` (see data-proxy on the tryit
1129
- // section below); the displayed curl/fetch/python snippets deliberately
1130
- // keep showing the real, non-proxied URL - only this in-browser request
1131
- // actually routes through the proxy.
1132
- const PROXY_BASE_URL = 'https://proxy.writechoice.io/';
1133
- function loadHighlighter(themes: { light: string; dark: string }): Promise<ShikiHighlighter> {
1134
- if (!wdHighlighterPromise) {
1135
- wdHighlighterPromise = Promise.all([
1136
- import('shiki/core'),
1137
- import('shiki/engine/oniguruma'),
1138
- import('shiki/themes'),
1139
- import('@shikijs/langs/bash'),
1140
- import('@shikijs/langs/javascript'),
1141
- import('@shikijs/langs/python'),
1142
- import('@shikijs/langs/php'),
1143
- import('@shikijs/langs/go'),
1144
- import('@shikijs/langs/java'),
1145
- import('@shikijs/langs/ruby'),
1146
- ]).then(([core, engine, themeTable, bash, javascript, python, php, go, java, ruby]) =>
1147
- core.createHighlighterCore({
1148
- langs: [bash.default, javascript.default, python.default, php.default, go.default, java.default, ruby.default],
1149
- themes: [themeTable.bundledThemes[themes.light](), themeTable.bundledThemes[themes.dark]()],
1150
- engine: engine.createOnigurumaEngine(import('shiki/wasm')),
1151
- })
1152
- ) as Promise<ShikiHighlighter>;
1153
- }
1154
- return wdHighlighterPromise;
1155
- }
1156
- // Same github-light/github-dark fallback as resolveCodeblockTheme()
1157
- // (src/lib/config.ts) - kept as a literal default here rather than
1158
- // imported, since this <script> runs in the browser and can't reach
1159
- // back into server-only modules; the data-themes JSON below is
1160
- // already resolveCodeblockTheme()'s own output, so this only matters
1161
- // if that attribute is ever missing or malformed.
1162
- function parseThemes(raw: string | undefined): { light: string; dark: string } {
1163
- try {
1164
- const parsed = raw ? JSON.parse(raw) : {};
1165
- return { light: parsed.light ?? 'github-light', dark: parsed.dark ?? 'github-dark' };
1166
- } catch {
1167
- return { light: 'github-light', dark: 'github-dark' };
1168
- }
1169
- }
1170
-
1171
- // Drives the hidden <select data-role="{rolePrefix}-select"> rendered
1172
- // by ApiLangSelect.astro from a click on its custom icon+label+
1173
- // checkmark dropdown - open/close/outside-click/Escape all come free
1174
- // from the site's shared initDropdowns() (already wired globally
1175
- // against `document` by TopBar.astro/MobileMenu.astro), so this only
1176
- // needs to: swap the trigger's icon/label to match the pick (by
1177
- // cloning the clicked item's own already-rendered <svg> rather than
1178
- // this script knowing any Iconify id itself), move which item shows
1179
- // .active, and set+dispatch 'change' on the hidden select so every
1180
- // listener already written against lang-select/modal-lang-select
1181
- // below (panel-toggle, live-preview refresh) keeps working unchanged.
1182
- function initLangDropdown(scope: ParentNode, rolePrefix: string) {
1183
- const nativeSelect = scope.querySelector<HTMLSelectElement>(`[data-role="${rolePrefix}-select"]`);
1184
- const trigger = scope.querySelector<HTMLElement>(`[data-role="${rolePrefix}-trigger"]`);
1185
- // A distinct dataset key from plain wdInit - the trigger is also a
1186
- // .wd-dropdown-trigger, and initDropdowns() (dropdowns.ts, wired
1187
- // globally by TopBar.astro/MobileMenu.astro) already claims
1188
- // trigger.dataset.wdInit as its own "have I wired open/close yet"
1189
- // guard on this exact element. Sharing that key meant whichever of
1190
- // the two ran first silently blocked the other from ever attaching -
1191
- // in practice initDropdowns() always won the race, so the item click
1192
- // listeners below were never being attached at all.
1193
- if (!nativeSelect || !trigger || trigger.dataset.wdLangInit) return;
1194
- trigger.dataset.wdLangInit = 'true';
1195
- const items = Array.from(scope.querySelectorAll<HTMLButtonElement>(`[data-role="${rolePrefix}-item"]`));
1196
- items.forEach((item) => {
1197
- item.addEventListener('click', () => {
1198
- items.forEach((it) => it.classList.toggle('active', it === item));
1199
- const icon = item.querySelector('.wd-api-lang-icon');
1200
- const triggerIcon = trigger.querySelector('.wd-api-lang-icon');
1201
- if (icon && triggerIcon) triggerIcon.replaceWith(icon.cloneNode(true));
1202
- const label = item.querySelector('.wd-api-lang-label')?.textContent ?? '';
1203
- const triggerLabel = trigger.querySelector('.wd-api-lang-label');
1204
- if (triggerLabel) triggerLabel.textContent = label;
1205
- nativeSelect.value = item.dataset.value ?? '';
1206
- nativeSelect.dispatchEvent(new Event('change'));
1207
- });
1208
- });
1209
- }
1210
-
1211
- function initApiPanel(root: ParentNode) {
1212
- // Set once the tryit section below wires it up - there's exactly one
1213
- // Try-it modal per operation page, so a single shared reference (like
1214
- // the existing `document.querySelector('[data-role="send"]')` a few
1215
- // lines down, which makes the same single-instance assumption) is all
1216
- // that's needed for the open-modal handler in the loop below to
1217
- // trigger a re-render once Shiki finishes loading.
1218
- let refreshModalPreview: (() => void) | null = null;
1219
-
1220
- root.querySelectorAll<HTMLElement>('[data-api-panel]').forEach((panel) => {
1221
- if (panel.dataset.wdInit) return;
1222
- panel.dataset.wdInit = 'true';
1223
-
1224
- const langSelect = panel.querySelector<HTMLSelectElement>('[data-role="lang-select"]');
1225
- const langPanels = Array.from(panel.querySelectorAll<HTMLElement>('[data-lang-panel]'));
1226
- langSelect?.addEventListener('change', () => {
1227
- langPanels.forEach((p) => {
1228
- p.style.display = p.dataset.langPanel === langSelect.value ? 'block' : 'none';
1229
- });
1230
- });
1231
- initLangDropdown(panel, 'lang');
1232
-
1233
- const statusSelect = panel.querySelector<HTMLSelectElement>('[data-role="status-select"]');
1234
- const statusPanels = Array.from(panel.querySelectorAll<HTMLElement>('[data-status-panel]'));
1235
- const statusDot = panel.querySelector<HTMLElement>('[data-role="status-dot"]');
1236
- statusSelect?.addEventListener('change', () => {
1237
- statusPanels.forEach((p) => {
1238
- p.style.display = p.dataset.statusPanel === statusSelect.value ? 'block' : 'none';
1239
- });
1240
- // Keeps the leading color dot (green/red/gray, set server-side
1241
- // from statusToneClass() in the frontmatter - see this file's
1242
- // own comment there) in sync with whichever status the reader
1243
- // has switched to - each <option> carries its own tone as a
1244
- // data attribute for exactly this, since the dot itself isn't
1245
- // part of the native <select> box the browser renders.
1246
- const tone = statusSelect.selectedOptions[0]?.dataset.tone;
1247
- if (statusDot && tone) statusDot.className = `wd-api-status-dot ${tone}`;
1248
- });
1249
-
1250
- panel.querySelector('[data-role="copy-request"]')?.addEventListener('click', () => {
1251
- const visible = langPanels.find((p) => p.style.display !== 'none');
1252
- if (visible) navigator.clipboard?.writeText(visible.textContent ?? '');
1253
- });
1254
- panel.querySelector('[data-role="copy-response"]')?.addEventListener('click', () => {
1255
- const visible = statusPanels.find((p) => p.style.display !== 'none');
1256
- if (visible) navigator.clipboard?.writeText(visible.textContent ?? '');
1257
- });
1258
-
1259
- const overlay = document.querySelector<HTMLElement>('[data-role="modal-overlay"]');
1260
- panel.querySelector('[data-role="open-modal"]')?.addEventListener('click', () => {
1261
- if (overlay) {
1262
- overlay.hidden = false;
1263
- document.body.style.overflow = 'hidden';
1264
- }
1265
- if (!wdHighlighter) {
1266
- const tryitSection = document.querySelector<HTMLElement>('[data-api-tryit]');
1267
- const themes = parseThemes(tryitSection?.dataset.themes);
1268
- loadHighlighter(themes).then((h) => {
1269
- wdHighlighter = h;
1270
- refreshModalPreview?.();
1271
- });
1272
- }
1273
- });
1274
- });
1275
-
1276
- const overlay = root.querySelector<HTMLElement>('[data-role="modal-overlay"]');
1277
- if (overlay && !overlay.dataset.wdInit) {
1278
- overlay.dataset.wdInit = 'true';
1279
- const close = () => {
1280
- overlay.hidden = true;
1281
- document.body.style.overflow = '';
1282
- };
1283
- overlay.addEventListener('click', (e) => {
1284
- if (e.target === overlay) close();
1285
- });
1286
- overlay.querySelector('[data-role="close-modal"]')?.addEventListener('click', close);
1287
- document.addEventListener('keydown', (e) => {
1288
- if (e.key === 'Escape' && !overlay.hidden) close();
1289
- });
1290
-
1291
- const modalLangSelect = overlay.querySelector<HTMLSelectElement>('[data-role="modal-lang-select"]');
1292
- const modalLangPanels = Array.from(overlay.querySelectorAll<HTMLElement>('[data-modal-lang-panel]'));
1293
- modalLangSelect?.addEventListener('change', () => {
1294
- modalLangPanels.forEach((p) => {
1295
- p.style.display = p.dataset.modalLangPanel === modalLangSelect.value ? 'block' : 'none';
1296
- });
1297
- });
1298
- initLangDropdown(overlay, 'modal-lang');
1299
- }
1300
-
1301
- root.querySelectorAll<HTMLElement>('[data-api-tryit]').forEach((section) => {
1302
- if (section.dataset.wdInit) return;
1303
- section.dataset.wdInit = 'true';
1304
-
1305
- const method = section.dataset.method ?? 'GET';
1306
- const opPath = section.dataset.path ?? '';
1307
- const themes = parseThemes(section.dataset.themes);
1308
- const proxyEnabled = section.dataset.proxy === 'true';
1309
- // Either a plain <span data-value="..."> (single-server spec) or a
1310
- // <select> (multiple servers) - see the markup comment above.
1311
- // getBaseUrl() normalizes the two into one string, whichever
1312
- // element actually rendered.
1313
- const baseUrlEl = section.querySelector<HTMLElement>('[data-role="base-url"]');
1314
- function getBaseUrl(): string {
1315
- if (!baseUrlEl) return '';
1316
- if (baseUrlEl instanceof HTMLSelectElement) return baseUrlEl.value;
1317
- return baseUrlEl.dataset.value ?? '';
1318
- }
1319
- const authInputs = Array.from(section.querySelectorAll<HTMLInputElement>('[data-role="auth"]'));
1320
- const paramInputs = Array.from(section.querySelectorAll<HTMLInputElement>('[data-role="param"]'));
1321
- const bodyInput = section.querySelector<HTMLTextAreaElement>('[data-role="body"]');
1322
- const sendBtn = document.querySelector<HTMLButtonElement>('[data-role="send"]');
1323
- const responseStatusEl = section.querySelector<HTMLElement>('[data-role="response-status"]');
1324
- const responseBodyEl = section.querySelector<HTMLElement>('[data-role="response-body"] code');
1325
- const modalLangPanels = Array.from(section.querySelectorAll<HTMLElement>('[data-modal-lang-panel]'));
1326
-
1327
- // A reader's credentials last for the tab, not forever: sessionStorage
1328
- // carries them across the pages of one visit and forgets them when the
1329
- // tab closes. Older versions kept them in localStorage indefinitely -
1330
- // a key found there is moved over once and deleted.
1331
- authInputs.forEach((input) => {
1332
- const storageKey = `wd-api-auth:${input.dataset.authName ?? ''}`;
1333
- try {
1334
- const legacy = localStorage.getItem(storageKey);
1335
- if (legacy !== null) {
1336
- if (sessionStorage.getItem(storageKey) === null) sessionStorage.setItem(storageKey, legacy);
1337
- localStorage.removeItem(storageKey);
1338
- }
1339
- const saved = sessionStorage.getItem(storageKey);
1340
- if (saved) input.value = saved;
1341
- } catch {
1342
- // storage unavailable - auth just won't carry across pages
1343
- }
1344
- input.addEventListener('input', () => {
1345
- try {
1346
- sessionStorage.setItem(storageKey, input.value);
1347
- } catch {
1348
- // ignore
1349
- }
1350
- });
1351
- });
1352
-
1353
- // Keeps the modal's request-sample preview (plain <pre><code> - see
1354
- // the frontmatter) in sync with whatever the user has typed into
1355
- // the form so far, substituting a bracketed placeholder (<name>,
1356
- // <token>, ...) for anything still empty so the preview always
1357
- // renders something readable instead of looking broken. This is
1358
- // deliberately its own code path rather than reusing the Send
1359
- // handler below: Send needs strict validation with user-facing
1360
- // error messages, while this needs lenient, always-renders-
1361
- // something behavior on every keystroke. It loosely mirrors the
1362
- // structure of buildCurlSnippet/buildFetchSnippet/buildPythonSnippet
1363
- // (src/lib/openapi-render.ts) - same per-language shape, live values
1364
- // instead of a schema-derived example.
1365
- function collectLiveRequest() {
1366
- const baseUrl = (getBaseUrl().trim() || 'https://api.example.com').replace(/\/$/, '');
1367
- let path = opPath;
1368
- const queryParams: { name: string; value: string }[] = [];
1369
- const headerParams: { name: string; value: string }[] = [];
1370
- for (const input of paramInputs) {
1371
- const name = input.dataset.paramName ?? '';
1372
- const paramIn = input.dataset.paramIn;
1373
- const value = input.value.trim() || `<${name}>`;
1374
- if (paramIn === 'path') {
1375
- path = path.replace(`{${name}}`, value);
1376
- } else if (paramIn === 'query') {
1377
- queryParams.push({ name, value });
1378
- } else if (paramIn === 'header') {
1379
- headerParams.push({ name, value });
1380
- }
1381
- }
1382
-
1383
- const securityHeaders: { name: string; value: string }[] = [];
1384
- const securityQuery: { name: string; value: string }[] = [];
1385
- let basicAuth: string | null = null;
1386
- for (const input of authInputs) {
1387
- const name = input.dataset.authName ?? '';
1388
- const type = input.dataset.authType;
1389
- const scheme = input.dataset.authScheme;
1390
- const authIn = input.dataset.authIn;
1391
- const value = input.value.trim();
1392
- if (type === 'apiKey' && authIn === 'header') {
1393
- securityHeaders.push({ name, value: value || `<${name}>` });
1394
- } else if (type === 'apiKey' && authIn === 'query') {
1395
- securityQuery.push({ name, value: value || `<${name}>` });
1396
- } else if (type === 'http' && scheme === 'bearer') {
1397
- securityHeaders.push({ name: 'Authorization', value: `Bearer ${value || '<token>'}` });
1398
- } else if (type === 'http' && scheme === 'basic') {
1399
- basicAuth = value || '<username>:<password>';
1400
- }
1401
- }
1402
-
1403
- const hasBodyField = !!bodyInput;
1404
- const bodyRaw = bodyInput?.value.trim() ?? '';
1405
-
1406
- return { method, baseUrl, path, queryParams, headerParams, securityHeaders, securityQuery, basicAuth, hasBodyField, bodyRaw };
1407
- }
1408
- type LiveRequestState = ReturnType<typeof collectLiveRequest>;
1409
-
1410
- function liveCurlSnippet(state: LiveRequestState): string {
1411
- const query = [...state.queryParams, ...state.securityQuery];
1412
- const url =
1413
- state.baseUrl + state.path + (query.length ? '?' + query.map((q) => `${q.name}=${q.value}`).join('&') : '');
1414
- const lines = [`curl -X ${state.method} "${url}" \\`];
1415
- if (state.hasBodyField) lines.push(` -H "Content-Type: application/json" \\`);
1416
- for (const h of state.headerParams) lines.push(` -H "${h.name}: ${h.value}" \\`);
1417
- for (const h of state.securityHeaders) lines.push(` -H "${h.name}: ${h.value}" \\`);
1418
- if (state.basicAuth) lines.push(` -u "${state.basicAuth}" \\`);
1419
- if (state.bodyRaw) lines.push(` -d '${state.bodyRaw}'`);
1420
- const last = lines[lines.length - 1];
1421
- lines[lines.length - 1] = last.endsWith('\\') ? last.slice(0, -2) : last;
1422
- return lines.join('\n');
1423
- }
1424
-
1425
- function liveFetchSnippet(state: LiveRequestState): string {
1426
- const url = state.baseUrl + state.path;
1427
- const headers = [
1428
- ...(state.hasBodyField ? [`'Content-Type': 'application/json'`] : []),
1429
- ...state.securityHeaders.map((h) => `'${h.name}': '${h.value}'`),
1430
- ];
1431
- const optsLines = [
1432
- `method: '${state.method}'`,
1433
- headers.length ? `headers: { ${headers.join(', ')} }` : null,
1434
- state.hasBodyField && state.bodyRaw ? `body: JSON.stringify(${state.bodyRaw})` : null,
1435
- ].filter(Boolean);
1436
- return `const response = await fetch(\`${url}\`, {\n ${optsLines.join(',\n ')}\n});\nconst data = await response.json();`;
1437
- }
1438
-
1439
- function livePythonSnippet(state: LiveRequestState): string {
1440
- const url = state.baseUrl + state.path;
1441
- const headers = state.securityHeaders.map((h) => `"${h.name}": "${h.value}"`);
1442
- const lines = ['import requests', '', `response = requests.request(`, ` "${state.method}",`, ` "${url}",`];
1443
- if (headers.length) lines.push(` headers={ ${headers.join(', ')} },`);
1444
- if (state.hasBodyField && state.bodyRaw) {
1445
- lines.push(
1446
- ` json=${state.bodyRaw.replace(/\btrue\b/g, 'True').replace(/\bfalse\b/g, 'False').replace(/\bnull\b/g, 'None')},`
1447
- );
1448
- }
1449
- lines.push(')', 'data = response.json()');
1450
- return lines.join('\n');
1451
- }
1452
-
1453
- // php/go/java/ruby mirror liveFetchSnippet/livePythonSnippet's own
1454
- // subset of liveCurlSnippet's behavior (no query-param URL
1455
- // building, no basic-auth) - same precedent buildPhpSnippet/
1456
- // buildGoSnippet/buildJavaSnippet/buildRubySnippet in
1457
- // src/lib/openapi-render.ts follow for the static versions of
1458
- // these same four, for the same reason (see that file's comment).
1459
- function livePhpSnippet(state: LiveRequestState): string {
1460
- const url = state.baseUrl + state.path;
1461
- const headers = [
1462
- ...(state.hasBodyField ? [`"Content-Type: application/json"`] : []),
1463
- ...state.headerParams.map((h) => `"${h.name}: ${h.value}"`),
1464
- ...state.securityHeaders.map((h) => `"${h.name}: ${h.value}"`),
1465
- ];
1466
- const lines = [
1467
- '$ch = curl_init();',
1468
- `curl_setopt($ch, CURLOPT_URL, "${url}");`,
1469
- 'curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);',
1470
- `curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "${state.method}");`,
1471
- ];
1472
- if (headers.length) lines.push(`curl_setopt($ch, CURLOPT_HTTPHEADER, [${headers.join(', ')}]);`);
1473
- if (state.hasBodyField && state.bodyRaw) lines.push(`curl_setopt($ch, CURLOPT_POSTFIELDS, '${state.bodyRaw}');`);
1474
- lines.push('$response = curl_exec($ch);', 'curl_close($ch);');
1475
- return `<?php\n${lines.join('\n')}`;
1476
- }
1477
-
1478
- function liveGoSnippet(state: LiveRequestState): string {
1479
- const url = state.baseUrl + state.path;
1480
- const headers = [
1481
- ...(state.hasBodyField ? [`req.Header.Set("Content-Type", "application/json")`] : []),
1482
- ...state.headerParams.map((h) => `req.Header.Set("${h.name}", "${h.value}")`),
1483
- ...state.securityHeaders.map((h) => `req.Header.Set("${h.name}", "${h.value}")`),
1484
- ];
1485
- const hasBody = state.hasBodyField && state.bodyRaw;
1486
- const bodyExpr = hasBody ? `strings.NewReader(\`${state.bodyRaw}\`)` : 'nil';
1487
- const lines = [
1488
- 'package main',
1489
- '',
1490
- 'import (',
1491
- '\t"fmt"',
1492
- '\t"io"',
1493
- '\t"net/http"',
1494
- ...(hasBody ? ['\t"strings"'] : []),
1495
- ')',
1496
- '',
1497
- 'func main() {',
1498
- `\treq, _ := http.NewRequest("${state.method}", "${url}", ${bodyExpr})`,
1499
- ...headers.map((h) => `\t${h}`),
1500
- '',
1501
- '\tresp, err := http.DefaultClient.Do(req)',
1502
- '\tif err != nil {',
1503
- '\t\tpanic(err)',
1504
- '\t}',
1505
- '\tdefer resp.Body.Close()',
1506
- '',
1507
- '\tdata, _ := io.ReadAll(resp.Body)',
1508
- '\tfmt.Println(string(data))',
1509
- '}',
1510
- ];
1511
- return lines.join('\n');
1512
- }
1513
-
1514
- function liveJavaSnippet(state: LiveRequestState): string {
1515
- const url = state.baseUrl + state.path;
1516
- const headers = [
1517
- ...(state.hasBodyField ? [`.header("Content-Type", "application/json")`] : []),
1518
- ...state.headerParams.map((h) => `.header("${h.name}", "${h.value}")`),
1519
- ...state.securityHeaders.map((h) => `.header("${h.name}", "${h.value}")`),
1520
- ];
1521
- const hasBody = state.hasBodyField && state.bodyRaw;
1522
- const bodyPublisher = hasBody
1523
- ? `HttpRequest.BodyPublishers.ofString(${JSON.stringify(state.bodyRaw)})`
1524
- : 'HttpRequest.BodyPublishers.noBody()';
1525
- const lines = [
1526
- 'HttpClient client = HttpClient.newHttpClient();',
1527
- 'HttpRequest request = HttpRequest.newBuilder()',
1528
- ` .uri(URI.create("${url}"))`,
1529
- ...headers.map((h) => ` ${h}`),
1530
- ` .method("${state.method}", ${bodyPublisher})`,
1531
- ' .build();',
1532
- '',
1533
- 'HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());',
1534
- 'System.out.println(response.body());',
1535
- ];
1536
- return lines.join('\n');
1537
- }
1538
-
1539
- function liveRubySnippet(state: LiveRequestState): string {
1540
- const url = state.baseUrl + state.path;
1541
- const methodClass = state.method.charAt(0).toUpperCase() + state.method.slice(1).toLowerCase();
1542
- const headers = [
1543
- ...(state.hasBodyField ? [`request["Content-Type"] = "application/json"`] : []),
1544
- ...state.headerParams.map((h) => `request["${h.name}"] = "${h.value}"`),
1545
- ...state.securityHeaders.map((h) => `request["${h.name}"] = "${h.value}"`),
1546
- ];
1547
- const hasBody = state.hasBodyField && state.bodyRaw;
1548
- const lines = [
1549
- 'require "net/http"',
1550
- 'require "uri"',
1551
- '',
1552
- `uri = URI("${url}")`,
1553
- 'http = Net::HTTP.new(uri.host, uri.port)',
1554
- 'http.use_ssl = uri.scheme == "https"',
1555
- '',
1556
- `request = Net::HTTP::${methodClass}.new(uri)`,
1557
- ...headers,
1558
- ...(hasBody ? [`request.body = ${JSON.stringify(state.bodyRaw)}`] : []),
1559
- '',
1560
- 'response = http.request(request)',
1561
- 'puts response.body',
1562
- ];
1563
- return lines.join('\n');
1564
- }
1565
-
1566
- const LIVE_SNIPPET_BUILDERS: Record<string, (state: LiveRequestState) => string> = {
1567
- curl: liveCurlSnippet,
1568
- js: liveFetchSnippet,
1569
- py: livePythonSnippet,
1570
- php: livePhpSnippet,
1571
- go: liveGoSnippet,
1572
- java: liveJavaSnippet,
1573
- ruby: liveRubySnippet,
1574
- };
1575
-
1576
- // Renders one modal panel's code - through real Shiki once
1577
- // wdHighlighter has loaded (see the open-modal click handler above),
1578
- // so the live preview ends up looking identical to every other
1579
- // codeblock on the site; until then, plain text keeps it accurate
1580
- // without blocking on the network. codeToHtml() on an already-built
1581
- // highlighter instance is synchronous (all langs/themes are already
1582
- // loaded into it), so this is cheap enough to call on every
1583
- // keystroke with no debouncing needed.
1584
- function renderModalPanel(panel: HTMLElement, code: string) {
1585
- if (!wdHighlighter) {
1586
- const codeEl = panel.querySelector('code');
1587
- if (codeEl) codeEl.textContent = code;
1588
- return;
1589
- }
1590
- const shikiLang = MODAL_LANG_TO_SHIKI[panel.dataset.modalLangPanel ?? ''] ?? 'plaintext';
1591
- const html = wdHighlighter.codeToHtml(code, { lang: shikiLang, themes });
1592
- const template = document.createElement('template');
1593
- template.innerHTML = html.trim();
1594
- const rendered = template.content.firstElementChild as HTMLElement | null;
1595
- if (!rendered) return;
1596
- // Shiki's own output owns class/style (background, --shiki-dark-*
1597
- // vars, etc. - same as the sidebar's <Code/> panels, see
1598
- // ApiReferencePanel's CSS) but display: block/none is this
1599
- // panel's own toggle state (driven by modalLangSelect above), not
1600
- // something Shiki knows about - preserved across the swap rather
1601
- // than clobbered by it.
1602
- const currentDisplay = panel.style.display;
1603
- panel.setAttribute('style', rendered.getAttribute('style') ?? '');
1604
- panel.style.display = currentDisplay;
1605
- panel.className = `${rendered.className} wd-api-pre astro-code`.trim();
1606
- panel.innerHTML = rendered.innerHTML;
1607
- }
1608
-
1609
- function updateModalPreview() {
1610
- if (modalLangPanels.length === 0) return;
1611
- const state = collectLiveRequest();
1612
- modalLangPanels.forEach((panel) => {
1613
- const build = LIVE_SNIPPET_BUILDERS[panel.dataset.modalLangPanel ?? ''];
1614
- if (build) renderModalPanel(panel, build(state));
1615
- });
1616
- }
1617
- refreshModalPreview = updateModalPreview;
1618
-
1619
- // Only a <select> fires a meaningful change here - the static
1620
- // <span> case has nothing for the reader to alter, so there's no
1621
- // listener to attach for it (getBaseUrl() above still reads its
1622
- // fixed data-value on every other input's own 'input' event).
1623
- if (baseUrlEl instanceof HTMLSelectElement) {
1624
- baseUrlEl.addEventListener('change', updateModalPreview);
1625
- }
1626
- paramInputs.forEach((input) => input.addEventListener('input', updateModalPreview));
1627
- authInputs.forEach((input) => input.addEventListener('input', updateModalPreview));
1628
- bodyInput?.addEventListener('input', updateModalPreview);
1629
- updateModalPreview();
1630
-
1631
- // Examples select (only rendered when the spec's request body
1632
- // carries a named `examples` map - see requestExampleEntries in
1633
- // the frontmatter). Selecting one only ever touches the Body
1634
- // field: OpenAPI's `examples` keyword lives on the request body's
1635
- // media-type object, with no standard link to path/query/header
1636
- // parameter values, so there's nothing else to populate from it.
1637
- // "Default" (value="") is its own real option, not a no-op
1638
- // placeholder - picking it resets the Body to blankRequestExample
1639
- // (see the frontmatter's emptyValueFromSchema call), the same
1640
- // field shape as a named example but with every value left empty,
1641
- // so the reader still sees what the body needs instead of losing
1642
- // the shape to a blank textarea.
1643
- const exampleSelect = section.parentElement?.querySelector<HTMLSelectElement>('[data-role="example-select"]');
1644
- const blankBody = section.dataset.blankBody ?? '';
1645
- let examples: Record<string, { summary?: string; description?: string; value?: unknown }> = {};
1646
- try {
1647
- examples = JSON.parse(section.dataset.examples ?? '{}');
1648
- } catch {
1649
- // malformed/absent - examples select just won't populate anything
1650
- }
1651
- exampleSelect?.addEventListener('change', () => {
1652
- if (!bodyInput) return;
1653
- const chosen = examples[exampleSelect.value];
1654
- bodyInput.value = chosen ? JSON.stringify(chosen.value, null, 2) : blankBody;
1655
- updateModalPreview();
1656
- });
1657
- // Once the reader edits the body by hand, it no longer matches
1658
- // whichever example (if any) is still shown selected - reset the
1659
- // select back to "Default" so it doesn't keep claiming a match
1660
- // that's now stale. Only fires on direct typing into the
1661
- // textarea, not on the programmatic set above (that dispatches no
1662
- // 'input' event), so picking an example doesn't immediately
1663
- // un-pick itself.
1664
- bodyInput?.addEventListener('input', () => {
1665
- if (exampleSelect) exampleSelect.value = '';
1666
- });
1667
-
1668
- sendBtn?.addEventListener('click', async () => {
1669
- if (!responseStatusEl || !responseBodyEl) return;
1670
- const baseUrl = getBaseUrl().replace(/\/$/, '');
1671
- if (!baseUrl) {
1672
- responseStatusEl.textContent = 'No base URL is configured for this operation.';
1673
- responseStatusEl.className = 'wd-api-response-status wd-api-status-error';
1674
- responseBodyEl.textContent = '';
1675
- return;
1676
- }
1677
-
1678
- let requestPath = opPath;
1679
- const query = new URLSearchParams();
1680
- for (const input of paramInputs) {
1681
- const name = input.dataset.paramName ?? '';
1682
- const paramIn = input.dataset.paramIn;
1683
- const value = input.value;
1684
- if (paramIn === 'path') {
1685
- requestPath = requestPath.replace(`{${name}}`, encodeURIComponent(value));
1686
- } else if (paramIn === 'query' && value) {
1687
- query.set(name, value);
1688
- }
1689
- }
1690
-
1691
- const headers: Record<string, string> = {};
1692
- for (const input of paramInputs) {
1693
- if (input.dataset.paramIn === 'header' && input.value) {
1694
- headers[input.dataset.paramName ?? ''] = input.value;
1695
- }
1696
- }
1697
- for (const input of authInputs) {
1698
- const type = input.dataset.authType;
1699
- const scheme = input.dataset.authScheme;
1700
- const authIn = input.dataset.authIn;
1701
- const value = input.value;
1702
- if (!value) continue;
1703
- if (type === 'apiKey' && authIn === 'header') {
1704
- headers[input.dataset.authName ?? ''] = value;
1705
- } else if (type === 'apiKey' && authIn === 'query') {
1706
- query.set(input.dataset.authName ?? '', value);
1707
- } else if (type === 'http' && scheme === 'bearer') {
1708
- headers['Authorization'] = `Bearer ${value}`;
1709
- } else if (type === 'http' && scheme === 'basic') {
1710
- headers['Authorization'] = `Basic ${btoa(value)}`;
1711
- }
1712
- }
1713
-
1714
- let body: string | undefined;
1715
- if (bodyInput && bodyInput.value.trim()) {
1716
- try {
1717
- body = JSON.stringify(JSON.parse(bodyInput.value));
1718
- headers['Content-Type'] = headers['Content-Type'] ?? 'application/json';
1719
- } catch {
1720
- responseStatusEl.textContent = 'Request body is not valid JSON.';
1721
- responseStatusEl.className = 'wd-api-response-status wd-api-status-error';
1722
- responseBodyEl.textContent = '';
1723
- return;
1724
- }
1725
- }
1726
-
1727
- const targetUrl = baseUrl + requestPath + (query.toString() ? `?${query.toString()}` : '');
1728
- // A "simple" request (CORS spec: GET/HEAD/POST, no JSON body, no
1729
- // auth or custom headers) skips the preflight, so the server may
1730
- // already have run it when the browser blocks the response.
1731
- // Retrying one that changes something (a POST) through the proxy
1732
- // could run it twice - so that one case isn't retried.
1733
- const isSimple = ['GET', 'HEAD', 'POST'].includes(method) && Object.keys(headers).length === 0;
1734
- const mayHaveRun = isSimple && method === 'POST';
1735
-
1736
- if (sendBtn) {
1737
- sendBtn.disabled = true;
1738
- sendBtn.textContent = 'Sending...';
1739
- }
1740
- responseStatusEl.textContent = 'Sending request...';
1741
- responseStatusEl.className = 'wd-api-response-status';
1742
- responseBodyEl.textContent = '';
1743
-
1744
- const startedAt = performance.now();
1745
- let viaProxy = false;
1746
- try {
1747
- // Straight to the API first, so a reader's key and body only reach
1748
- // the API itself. fetch() rejects when the browser blocks the
1749
- // response (CORS) or can't reach the host - only then, and only
1750
- // when writedocs.json's `api.proxy` allows it, the same request is
1751
- // retried through writedocs' proxy (PROXY_BASE_URL above), and the
1752
- // status line says so.
1753
- let res: Response;
1754
- try {
1755
- res = await fetch(targetUrl, { method, headers, body });
1756
- } catch (directErr) {
1757
- if (!proxyEnabled || mayHaveRun) throw directErr;
1758
- viaProxy = true;
1759
- responseStatusEl.textContent = 'Blocked by the browser (CORS) - retrying through the writedocs proxy...';
1760
- res = await fetch(`${PROXY_BASE_URL}${targetUrl}`, { method, headers, body });
1761
- }
1762
- const elapsed = Math.round(performance.now() - startedAt);
1763
- const text = await res.text();
1764
- let pretty = text;
1765
- try {
1766
- pretty = JSON.stringify(JSON.parse(text), null, 2);
1767
- } catch {
1768
- // not JSON - show raw text as-is
1769
- }
1770
- responseStatusEl.textContent = `${res.status} ${res.statusText} - ${elapsed}ms${viaProxy ? ' - sent through the writedocs proxy (the API blocks direct browser requests)' : ''}`;
1771
- responseStatusEl.className = `wd-api-response-status ${res.ok ? 'wd-api-status-ok' : 'wd-api-status-error'}`;
1772
- responseBodyEl.textContent = pretty;
1773
- } catch (err) {
1774
- responseStatusEl.textContent = viaProxy
1775
- ? 'Request failed through the writedocs proxy too - the base URL may be unreachable from the internet.'
1776
- : mayHaveRun && proxyEnabled
1777
- ? 'Blocked by the browser (CORS). Not retried through the proxy: this POST may already have reached the API.'
1778
- : 'Request failed - likely blocked by CORS, or the base URL is unreachable from your browser.';
1779
- responseStatusEl.className = 'wd-api-response-status wd-api-status-error';
1780
- responseBodyEl.textContent = err instanceof Error ? err.message : String(err);
1781
- } finally {
1782
- if (sendBtn) {
1783
- sendBtn.disabled = false;
1784
- sendBtn.innerHTML = 'Send <span aria-hidden="true">&#9656;</span>';
1785
- }
1786
- }
1787
- });
1788
- });
1789
- }
1790
- initApiPanel(document);
1791
- document.addEventListener('astro:page-load', () => initApiPanel(document));
1792
- </script>
1
+ ---
2
+ import fs from 'node:fs';
3
+ import { Code } from 'astro:components';
4
+ import {
5
+ exampleFromSchema,
6
+ emptyValueFromSchema,
7
+ primaryContentType,
8
+ buildCurlSnippet,
9
+ buildFetchSnippet,
10
+ buildPythonSnippet,
11
+ buildPhpSnippet,
12
+ buildGoSnippet,
13
+ buildJavaSnippet,
14
+ buildRubySnippet,
15
+ findOperationFile,
16
+ type OpenApiOperation,
17
+ } from '../lib/openapi-render';
18
+ import { parseOpenApiRef } from '../lib/openapi-ref.js';
19
+ import { loadDocsConfig, resolveCodeblockTheme } from '../lib/config';
20
+ import ApiLangSelect from './ApiLangSelect.astro';
21
+
22
+ interface Props {
23
+ operation: string;
24
+ contentDir: string;
25
+ }
26
+ const { operation, contentDir } = Astro.props as Props;
27
+
28
+ // Shiki language id for each request-sample tab - <Code/> falls back to
29
+ // "plaintext" for anything it doesn't recognize, so this only needs to
30
+ // cover the ids actually used by `samples` below.
31
+ const SNIPPET_LANG: Record<string, string> = {
32
+ curl: 'bash',
33
+ js: 'javascript',
34
+ py: 'python',
35
+ php: 'php',
36
+ go: 'go',
37
+ java: 'java',
38
+ ruby: 'ruby',
39
+ };
40
+ // Iconify id for each request-sample tab's language, shown in both of
41
+ // this panel's language dropdowns (sidebar + Try-it modal) - see
42
+ // ApiLangSelect.astro. mdi's language-* set (not simple-icons' brand
43
+ // marks) since those render as plain currentColor monochrome glyphs,
44
+ // matching every other inline icon on this page instead of introducing
45
+ // a second, full-color icon style just for this one control.
46
+ const LANG_ICON: Record<string, string> = {
47
+ curl: 'mdi:console',
48
+ js: 'mdi:language-javascript',
49
+ py: 'mdi:language-python',
50
+ php: 'mdi:language-php',
51
+ go: 'mdi:language-go',
52
+ java: 'mdi:language-java',
53
+ ruby: 'mdi:language-ruby',
54
+ };
55
+ // Same dual light/dark themes as the sitewide MDX code-fence config in
56
+ // astro.config.mjs (writedocs.json's styles.codeblocks, via the shared
57
+ // resolveCodeblockTheme() helper - <Code/> doesn't inherit
58
+ // markdown.shikiConfig at all, so this needs its own copy of the same
59
+ // resolved value), so the response/request panels here follow the
60
+ // [data-theme] toggle exactly like article content does - see the
61
+ // [data-theme='dark'] :global(.astro-code) override in BaseLayout.astro.
62
+ const docsConfig = loadDocsConfig(contentDir);
63
+ const SNIPPET_THEMES = resolveCodeblockTheme(docsConfig);
64
+ // Whether the Send button in the Try-it modal routes its request through
65
+ // writedocs' CORS proxy - see PROXY_BASE_URL in the <script> below.
66
+ const proxyEnabled = docsConfig.api.proxy;
67
+
68
+ // "METHOD /path", or Mintlify's "spec.json METHOD /path" - see lib/openapi-ref.js.
69
+ const ref = parseOpenApiRef(operation);
70
+ const method = ref?.method ?? '';
71
+ const urlPath = ref?.path ?? '';
72
+ const opFile = ref ? findOperationFile(contentDir, method, urlPath, ref.spec) : null;
73
+ const op: OpenApiOperation | null = opFile ? JSON.parse(fs.readFileSync(opFile, 'utf-8')) : null;
74
+
75
+ // ApiPlayground.astro (rendered in the article column) already shows a
76
+ // clear error when no matching operation is found - this panel just
77
+ // quietly renders nothing in that case rather than duplicating it.
78
+ const servers = op?.servers ?? [];
79
+ const baseUrl = servers[0]?.url ?? '';
80
+ const sampleBaseUrl = baseUrl || 'https://api.example.com';
81
+ const pathParams = op?.parameters.filter((p) => p.in === 'path') ?? [];
82
+ const queryParams = op?.parameters.filter((p) => p.in === 'query') ?? [];
83
+ const headerParams = op?.parameters.filter((p) => p.in === 'header') ?? [];
84
+
85
+ const requestContentType = op ? primaryContentType(op.requestBody?.content) : null;
86
+ const requestSchema = requestContentType ? op?.requestBody?.content?.[requestContentType]?.schema : undefined;
87
+ const requestExample = requestSchema ? JSON.stringify(exampleFromSchema(requestSchema), null, 2) : null;
88
+ // What the Body textarea resets to when the reader picks "Default" in
89
+ // the examples select (see requestExampleEntries below) - the same
90
+ // field shape as requestExample above, but blank rather than filled
91
+ // with synthesized placeholder values, so picking it clears prior
92
+ // input without losing sight of what the body actually needs.
93
+ const blankRequestExample = requestSchema ? JSON.stringify(emptyValueFromSchema(requestSchema), null, 2) : null;
94
+ // OpenAPI's plural, *named* `examples` map on the request body's media
95
+ // type object (distinct from the singular `example`/schema-derived
96
+ // default above) - when a spec author provides one or more of these,
97
+ // the modal gets a selector for them (see the "Example" <select> in the
98
+ // modal head below) that swaps the Body textarea to that exact value on
99
+ // selection. Scoped deliberately to the request body only, not
100
+ // parameters - OpenAPI parameters can carry their own `examples` map
101
+ // too, but there's no standard link between "this body example" and
102
+ // "these parameter values" the way there sometimes conceptually is in a
103
+ // hand-written doc, so auto-populating anything beyond the body from a
104
+ // body example would be guessing at an association the spec itself
105
+ // doesn't actually make.
106
+ const requestExamples = requestContentType ? (op?.requestBody?.content?.[requestContentType]?.examples ?? {}) : {};
107
+ const requestExampleEntries = Object.entries(requestExamples);
108
+ // The modal's own header title - "the endpoint title, not a dropdown"
109
+ // (an earlier version showed the raw path here instead, which reads
110
+ // more like plumbing than a title a reader would recognize). Same
111
+ // summary-with-a-fallback op.summary ?? "METHOD /path" that
112
+ // generate-api-pages.js already uses for a generated stub page's own
113
+ // <title>, so the modal's heading matches whatever the reader already
114
+ // clicked "Try it" from.
115
+ const modalTitle = op ? (op.summary ?? `${op.method} ${op.path}`) : '';
116
+
117
+ const samples = op
118
+ ? [
119
+ { id: 'curl', label: 'cURL', code: buildCurlSnippet(op, sampleBaseUrl) },
120
+ { id: 'js', label: 'JavaScript', code: buildFetchSnippet(op, sampleBaseUrl) },
121
+ { id: 'py', label: 'Python', code: buildPythonSnippet(op, sampleBaseUrl) },
122
+ { id: 'php', label: 'PHP', code: buildPhpSnippet(op, sampleBaseUrl) },
123
+ { id: 'go', label: 'Go', code: buildGoSnippet(op, sampleBaseUrl) },
124
+ { id: 'java', label: 'Java', code: buildJavaSnippet(op, sampleBaseUrl) },
125
+ { id: 'ruby', label: 'Ruby', code: buildRubySnippet(op, sampleBaseUrl) },
126
+ ]
127
+ : [];
128
+ // Same {id, label} shape samples already carries, plus the icon each
129
+ // dropdown item shows - kept as its own array (not folded into samples
130
+ // itself) since ApiLangSelect.astro only needs id/label/icon, not the
131
+ // snippet code samples also carries.
132
+ const langOptions = samples.map((s) => ({ id: s.id, label: s.label, icon: LANG_ICON[s.id] ?? 'mdi:code-tags' }));
133
+
134
+ // Classifies a response status into the same ok/error tone the Try-it
135
+ // modal's own live response status already uses (wd-api-status-ok/
136
+ // -error, see the <script> below) - reused here for the status select's
137
+ // leading color dot, so "green means success, red means an error status"
138
+ // reads consistently whether it's a live request result or just a
139
+ // static example being browsed. Anything outside 2xx/4xx/5xx (a 3xx
140
+ // redirect, mainly) gets a neutral gray dot rather than being force-fit
141
+ // into ok-or-error.
142
+ function statusToneClass(status: string): string {
143
+ const code = parseInt(status, 10);
144
+ if (code >= 200 && code < 300) return 'wd-api-status-dot-ok';
145
+ if (code >= 400) return 'wd-api-status-dot-error';
146
+ return 'wd-api-status-dot-neutral';
147
+ }
148
+
149
+ const responseExamples = op
150
+ ? Object.entries(op.responses).map(([status, resp]) => {
151
+ const contentType = primaryContentType(resp.content);
152
+ const schema = contentType ? resp.content?.[contentType]?.schema : undefined;
153
+ return {
154
+ status,
155
+ tone: statusToneClass(status),
156
+ code: schema ? JSON.stringify(exampleFromSchema(schema), null, 2) : '(no body)',
157
+ };
158
+ })
159
+ : [];
160
+
161
+ const paramsJson = JSON.stringify(op?.parameters ?? []);
162
+ const securityJson = JSON.stringify(op?.security ?? []);
163
+ ---
164
+
165
+ {op && (
166
+ <div class="wd-api-panel" data-api-panel data-method={op.method} data-path={op.path}>
167
+ <div class="wd-api-card">
168
+ <div class="wd-api-card-head">
169
+ <span class="wd-api-card-label">Request</span>
170
+ <div class="wd-api-card-actions">
171
+ <ApiLangSelect options={langOptions} rolePrefix="lang" ariaLabel="Language" />
172
+ <button type="button" class="wd-api-try-inline" data-role="open-modal">
173
+ Try <span class="wd-api-try-icon" aria-hidden="true">&#9656;</span>
174
+ </button>
175
+ </div>
176
+ </div>
177
+ <div class="wd-api-card-body">
178
+ {samples.map((s, i) => (
179
+ <Code
180
+ code={s.code}
181
+ lang={SNIPPET_LANG[s.id] ?? 'plaintext'}
182
+ themes={SNIPPET_THEMES}
183
+ class="wd-api-pre wd-api-pre-lines"
184
+ data-lang-panel={s.id}
185
+ style={`display: ${i === 0 ? 'block' : 'none'}`}
186
+ />
187
+ ))}
188
+ <button type="button" class="wd-api-code-copy-btn" data-role="copy-request" aria-label="Copy">⧉</button>
189
+ </div>
190
+ </div>
191
+
192
+ {responseExamples.length > 0 && (
193
+ <div class="wd-api-card">
194
+ <div class="wd-api-card-head">
195
+ <span class="wd-api-card-label">Response</span>
196
+ <div class="wd-api-card-actions">
197
+ <span class="wd-api-select-wrap wd-api-status-select-wrap">
198
+ <span class={`wd-api-status-dot ${responseExamples[0].tone}`} data-role="status-dot"></span>
199
+ <select class="wd-api-select" data-role="status-select" aria-label="Status">
200
+ {responseExamples.map((r) => <option value={r.status} data-tone={r.tone}>{r.status}</option>)}
201
+ </select>
202
+ </span>
203
+ </div>
204
+ </div>
205
+ <div class="wd-api-card-body">
206
+ {responseExamples.map((r, i) => (
207
+ <Code
208
+ code={r.code}
209
+ lang="json"
210
+ themes={SNIPPET_THEMES}
211
+ class="wd-api-pre wd-api-pre-lines"
212
+ data-status-panel={r.status}
213
+ style={`display: ${i === 0 ? 'block' : 'none'}`}
214
+ />
215
+ ))}
216
+ <button type="button" class="wd-api-code-copy-btn" data-role="copy-response" aria-label="Copy">⧉</button>
217
+ </div>
218
+ </div>
219
+ )}
220
+ </div>
221
+
222
+ <div class="wd-api-modal-overlay" data-role="modal-overlay" hidden>
223
+ <div class="wd-api-modal" role="dialog" aria-modal="true" aria-label="Try it">
224
+ <div class="wd-api-modal-head">
225
+ <div class="wd-api-modal-title">
226
+ <span class={`wd-api-method wd-api-method-${op.method.toLowerCase()}`}>{op.method}</span>
227
+ <span class="wd-api-modal-title-text">{modalTitle}</span>
228
+ </div>
229
+ {requestExampleEntries.length > 0 && (
230
+ <span class="wd-api-select-wrap wd-api-modal-example-wrap">
231
+ <select class="wd-api-select" data-role="example-select" aria-label="Example">
232
+ <option value="">Default</option>
233
+ {requestExampleEntries.map(([name, ex]) => (
234
+ <option value={name}>{ex.summary ?? name}</option>
235
+ ))}
236
+ </select>
237
+ </span>
238
+ )}
239
+ <div class="wd-api-modal-actions">
240
+ <button type="button" class="wd-api-send" data-role="send">Send <span aria-hidden="true">&#9656;</span></button>
241
+ <button type="button" class="wd-api-icon-btn" data-role="close-modal" aria-label="Close">&times;</button>
242
+ </div>
243
+ </div>
244
+ <div
245
+ class="wd-api-modal-body"
246
+ data-api-tryit
247
+ data-params={paramsJson}
248
+ data-security={securityJson}
249
+ data-examples={JSON.stringify(requestExamples)}
250
+ data-blank-body={blankRequestExample}
251
+ data-method={op.method}
252
+ data-path={op.path}
253
+ data-themes={JSON.stringify(SNIPPET_THEMES)}
254
+ data-proxy={proxyEnabled}
255
+ >
256
+ <div class="wd-api-modal-form">
257
+ <div class="wd-api-modal-url-bar">
258
+ <span class={`wd-api-method wd-api-method-${op.method.toLowerCase()}`}>{op.method}</span>
259
+ {servers.length > 1 ? (
260
+ // Multiple servers in the spec - a real <select>, not free
261
+ // text, since these are the only base URLs the operation
262
+ // actually supports. Each option's own label is the full
263
+ // concatenated URL (server + path), not just the server,
264
+ // so the control always reads as one complete request URL
265
+ // whether it's open or closed - never a bare host with the
266
+ // path implied elsewhere.
267
+ <select class="wd-api-url-select" data-role="base-url" aria-label="Server">
268
+ {servers.map((s) => (
269
+ <option value={s.url}>{s.url}{op.path}</option>
270
+ ))}
271
+ </select>
272
+ ) : (
273
+ // Single server (the common case) - nothing to choose
274
+ // between, so this is plain non-editable text rather than
275
+ // an input the reader might mistake for something they
276
+ // need to fill in. data-value carries the base URL alone
277
+ // (the part collectLiveRequest() below needs) since the
278
+ // element's own text content is the base+path combined.
279
+ <span class="wd-api-url-full" data-role="base-url" data-value={baseUrl}>{baseUrl}{op.path}</span>
280
+ )}
281
+ </div>
282
+
283
+ {headerParams.length > 0 && (
284
+ <div class="wd-api-field-group">
285
+ <span class="wd-api-field-group-label">Header</span>
286
+ {headerParams.map((p) => (
287
+ <label class="wd-api-field">
288
+ <span>{p.name}{p.required && <span class="wd-api-pill wd-api-pill-required">required</span>}</span>
289
+ <input type="text" class="wd-api-input" data-role="param" data-param-name={p.name} data-param-in="header" />
290
+ </label>
291
+ ))}
292
+ </div>
293
+ )}
294
+
295
+ {pathParams.length > 0 && (
296
+ <div class="wd-api-field-group">
297
+ <span class="wd-api-field-group-label">Path</span>
298
+ {pathParams.map((p) => (
299
+ <label class="wd-api-field">
300
+ <span>{p.name}{p.required && <span class="wd-api-pill wd-api-pill-required">required</span>}</span>
301
+ <input
302
+ type="text"
303
+ class="wd-api-input"
304
+ data-role="param"
305
+ data-param-name={p.name}
306
+ data-param-in="path"
307
+ value={String(p.example ?? p.schema?.example ?? p.schema?.default ?? '')}
308
+ />
309
+ </label>
310
+ ))}
311
+ </div>
312
+ )}
313
+
314
+ {queryParams.length > 0 && (
315
+ <div class="wd-api-field-group">
316
+ <span class="wd-api-field-group-label">Query</span>
317
+ {queryParams.map((p) => (
318
+ <label class="wd-api-field">
319
+ <span>{p.name}{p.required && <span class="wd-api-pill wd-api-pill-required">required</span>}</span>
320
+ <input
321
+ type="text"
322
+ class="wd-api-input"
323
+ data-role="param"
324
+ data-param-name={p.name}
325
+ data-param-in="query"
326
+ value={String(p.example ?? p.schema?.example ?? p.schema?.default ?? '')}
327
+ />
328
+ </label>
329
+ ))}
330
+ </div>
331
+ )}
332
+
333
+ {requestSchema && (
334
+ <div class="wd-api-field-group">
335
+ <span class="wd-api-field-group-label">Body</span>
336
+ <textarea class="wd-api-textarea" data-role="body" rows="8">{requestExample}</textarea>
337
+ </div>
338
+ )}
339
+ </div>
340
+
341
+ <div class="wd-api-modal-preview">
342
+ {op.security.length > 0 && (
343
+ <div class="wd-api-card wd-api-auth-card">
344
+ <div class="wd-api-card-head">
345
+ <span class="wd-api-card-label">Authentication</span>
346
+ </div>
347
+ <div class="wd-api-card-body wd-api-auth-card-body">
348
+ {op.security.map((s) => {
349
+ const label =
350
+ s.type === 'http' && s.scheme === 'bearer' ? 'Bearer token' :
351
+ s.type === 'http' && s.scheme === 'basic' ? 'Basic auth (user:pass)' :
352
+ s.name;
353
+ return (
354
+ <label class="wd-api-auth-field">
355
+ <input
356
+ type="text"
357
+ class="wd-api-input wd-api-auth-input"
358
+ data-role="auth"
359
+ data-auth-name={s.name}
360
+ data-auth-type={s.type}
361
+ data-auth-scheme={s.scheme ?? ''}
362
+ data-auth-in={s.in ?? ''}
363
+ placeholder={`<${label}>`}
364
+ />
365
+ <span class="wd-api-auth-icons">
366
+ <span class="wd-api-auth-icon" title="Sent with your request, kept only in this browser">
367
+ <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
368
+ <rect x="2.5" y="5.5" width="7" height="5" rx="1" stroke="currentColor" stroke-width="1.1" fill="none" />
369
+ <path d="M4 5.5V4a2 2 0 0 1 4 0v1.5" stroke="currentColor" stroke-width="1.1" fill="none" stroke-linecap="round" />
370
+ </svg>
371
+ </span>
372
+ <span class="wd-api-auth-icon" title={label}>
373
+ <svg width="11" height="11" viewBox="0 0 12 12" aria-hidden="true">
374
+ <circle cx="6" cy="6" r="5" stroke="currentColor" stroke-width="1.1" fill="none" />
375
+ <text x="6" y="8.3" text-anchor="middle" font-size="6.5" fill="currentColor" stroke="none" font-family="sans-serif">?</text>
376
+ </svg>
377
+ </span>
378
+ </span>
379
+ </label>
380
+ );
381
+ })}
382
+ </div>
383
+ </div>
384
+ )}
385
+ <div class="wd-api-card">
386
+ <div class="wd-api-card-head">
387
+ <span class="wd-api-card-label">Request</span>
388
+ <ApiLangSelect options={langOptions} rolePrefix="modal-lang" ariaLabel="Language" />
389
+ </div>
390
+ <div class="wd-api-card-body">
391
+ {samples.map((s, i) => (
392
+ <pre
393
+ class="wd-api-pre"
394
+ data-modal-lang-panel={s.id}
395
+ style={`display: ${i === 0 ? 'block' : 'none'}`}
396
+ ><code>{s.code}</code></pre>
397
+ ))}
398
+ </div>
399
+ </div>
400
+ <div class="wd-api-card">
401
+ <div class="wd-api-card-head">
402
+ <span class="wd-api-card-label">Response</span>
403
+ </div>
404
+ <div class="wd-api-card-body">
405
+ <div class="wd-api-response-status" data-role="response-status"></div>
406
+ <pre class="wd-api-pre" data-role="response-body"><code></code></pre>
407
+ </div>
408
+ </div>
409
+ </div>
410
+ </div>
411
+ </div>
412
+ </div>
413
+ )}
414
+
415
+ <style is:global>
416
+ /* Widens the shared .wd-toc-col (defined in BaseLayout.astro) only on
417
+ pages that actually render this panel into it, rather than adding a
418
+ prop BaseLayout has to thread through just for this - :has() lets
419
+ the override live entirely in this component instead. */
420
+ .wd-toc-col:has(.wd-api-panel) {
421
+ width: 380px;
422
+ }
423
+ /* top/max-height match Sidebar.astro/TableOfContents.astro's own
424
+ sticky columns - see Sidebar.astro's comment on --wd-topbar-offset
425
+ (src/scripts/topbar-offset.ts), the topbar's real measured height. */
426
+ .wd-api-panel {
427
+ position: sticky;
428
+ top: var(--wd-topbar-offset, 5rem);
429
+ padding: 1.5rem 0 1.5rem 1rem;
430
+ max-height: calc(100vh - var(--wd-topbar-offset, 5rem));
431
+ overflow-y: auto;
432
+ display: flex;
433
+ flex-direction: column;
434
+ gap: 1rem;
435
+ }
436
+ .wd-api-card {
437
+ background: var(--wd-surface);
438
+ border: 1px solid var(--wd-border);
439
+ border-radius: 0.75rem;
440
+ /* Soft elevation - same scale TopBar/MobileMenu's own dropdown panel
441
+ (dropdown.css's .wd-dropdown-menu) already uses for a resting,
442
+ non-modal floating panel - what turns this from a flat bordered
443
+ box into a card that visually lifts off the page background,
444
+ matching the reference design's own drop shadow around both
445
+ cards. */
446
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
447
+ }
448
+ /* Sidebar-only (the Try-it modal reuses .wd-api-card too, inside
449
+ .wd-api-modal-preview - a plain scrolling column with no height cap
450
+ of its own, so it never needs any of this). .wd-api-panel is a flex
451
+ column with its own bounded max-height + overflow-y: auto (see that
452
+ rule's comment) - by default a flex item won't shrink below its own
453
+ content's natural height, so without help here, two cards taller
454
+ than the panel just push the *panel* into needing to scroll as a
455
+ whole (previously "fixed" by giving cards flex-shrink: 0, forcing
456
+ every code block to keep its own fixed max-height regardless of how
457
+ little room was actually left - the panel scrolling, not the code
458
+ blocks resizing to fit it, which is backwards from what a reader
459
+ actually wants: both Request and Response staying visible at once,
460
+ each shrinking to fit, only truly overflowing (this rule's own
461
+ overflow-y: auto, still very much intentional as a last resort) once
462
+ even a sensible minimum won't fit both.
463
+ flex: 0 1 auto (grow: 0, shrink: 1, basis: auto) is what makes a
464
+ card sit at its own natural size when there's room, and only shrink
465
+ - never stretch - when there isn't; min-height: 0 lifts the default
466
+ "never shrink below natural content height" floor so that shrink
467
+ can actually happen. The genuine floor lives one level down, on
468
+ .wd-api-card-head (never shrinks at all - the RESPONSE label,
469
+ language dropdown etc. always stay fully visible) and
470
+ .wd-api-card-body (shrinks, but never below a legible minimum - see
471
+ that rule's own comment).
472
+
473
+ Two things had to be true at once here, and getting only one right
474
+ broke the other (both tried and measured against a real headless
475
+ render before landing on this):
476
+
477
+ 1) min-height: 0 is required for the card to shrink at all below its
478
+ natural content height - flex items default to min-height: auto,
479
+ which without this override refuses to shrink a flex *container*
480
+ item below its own children's natural (max-content) size. Tried
481
+ leaving this at the default `auto` instead, on the theory that
482
+ auto would resolve to the "real" content-based minimum (head's
483
+ natural height + body's own 8rem floor, ~11rem) - measured
484
+ against a real build instead of assumed, and it doesn't: Chromium
485
+ resolves a flex container's automatic minimum size to something
486
+ much closer to its full natural (unshrunk) content height here,
487
+ not the smaller nested-floor value - so `auto` just pinned every
488
+ card at full height regardless of available space, the opposite
489
+ of what this whole redesign is for.
490
+
491
+ 2) But min-height: 0 alone throws away the card's *only* protection
492
+ against being shrunk smaller than its own children can actually
493
+ render at - .wd-api-panel's own flex-shrink distributes the
494
+ deficit across both cards using each card's min-height as its
495
+ floor, with no visibility into what's two levels further down
496
+ (card-head's flex-shrink: 0, card-body's own min-height: 8rem);
497
+ min-height: 0 tells that outer algorithm "I have no floor," so it
498
+ shrinks the card's own box smaller than head+body's genuine
499
+ minimum, and - since a shrunk-too-small flex item doesn't clip
500
+ its own overflowing children by default - the code block renders
501
+ at its real 8rem floor anyway, just spilling past the card's own
502
+ (too-small) box into the space belowe reserved for the next
503
+ sibling card. Measured this directly: at a short enough viewport,
504
+ card height read smaller than head-height + body-height combined.
505
+
506
+ The explicit calc() below is what actually fixes both at once: an
507
+ honest floor (safely above the ~2.95rem this card-head design
508
+ measures at across themes, rounded up to 3.5rem for headroom) plus
509
+ card-body's own real 8rem floor, so .wd-api-panel's shrink algorithm
510
+ now sees the true minimum instead of either extreme. */
511
+ .wd-api-panel .wd-api-card {
512
+ display: flex;
513
+ flex-direction: column;
514
+ flex: 0 1 auto;
515
+ min-height: calc(3.5rem + 8rem);
516
+ }
517
+ .wd-api-panel .wd-api-card-head {
518
+ flex-shrink: 0;
519
+ }
520
+ .wd-api-card-head {
521
+ display: flex;
522
+ align-items: center;
523
+ justify-content: space-between;
524
+ gap: 0.5rem;
525
+ padding: 0.65rem 0.85rem;
526
+ border-bottom: 1px solid var(--wd-border);
527
+ }
528
+ .wd-api-card-label {
529
+ font-size: 0.75rem;
530
+ font-weight: 700;
531
+ text-transform: uppercase;
532
+ letter-spacing: 0.05em;
533
+ color: var(--wd-text-muted);
534
+ }
535
+ .wd-api-card-actions {
536
+ display: flex;
537
+ align-items: center;
538
+ gap: 0.5rem;
539
+ }
540
+ /* Distinct tinted card so Authentication reads as its own concern
541
+ sitting above Request/Response, not a third copy of the same
542
+ neutral-surface card - color-mix over --wd-primary matches the
543
+ tinted-background convention used elsewhere (NavTree.astro's hover
544
+ state, the status dot colors below). */
545
+ .wd-api-auth-card {
546
+ background: color-mix(in srgb, var(--wd-primary) 6%, var(--wd-surface));
547
+ border-color: color-mix(in srgb, var(--wd-primary) 18%, var(--wd-border));
548
+ }
549
+ .wd-api-auth-card-body {
550
+ display: flex;
551
+ flex-direction: column;
552
+ gap: 0.6rem;
553
+ padding: 0.85rem;
554
+ }
555
+ .wd-api-auth-field {
556
+ display: flex;
557
+ align-items: center;
558
+ gap: 0.5rem;
559
+ }
560
+ .wd-api-auth-input {
561
+ flex: 1;
562
+ min-width: 0;
563
+ }
564
+ .wd-api-auth-icons {
565
+ display: flex;
566
+ align-items: center;
567
+ gap: 0.35rem;
568
+ flex-shrink: 0;
569
+ color: var(--wd-text-muted);
570
+ }
571
+ .wd-api-auth-icon {
572
+ display: inline-flex;
573
+ }
574
+ /* Wraps the remaining plain <select> controls on this panel - the
575
+ status select-with-dot (Response), the Try-it modal's Example picker,
576
+ and its multi-server base-URL select - in the same rounded-pill
577
+ chrome as ApiLangSelect.astro's own trigger button, so every control
578
+ in this family still reads as one kind of thing even though the
579
+ language pickers themselves moved to that separate icon+label+
580
+ checkmark dropdown rather than a native <select>. The wrapper owns
581
+ border/radius/background; the <select> inside is stripped down to
582
+ borderless/transparent (below) so it doesn't paint a second,
583
+ conflicting box on top of its own wrapper's. */
584
+ .wd-api-select-wrap {
585
+ display: inline-flex;
586
+ align-items: center;
587
+ gap: 0.35rem;
588
+ padding: 0.2rem 0.55rem;
589
+ border-radius: 999px;
590
+ border: 1px solid var(--wd-border);
591
+ background: var(--wd-background);
592
+ }
593
+ .wd-api-select {
594
+ border: none;
595
+ background: none;
596
+ padding: 0;
597
+ margin: 0;
598
+ font-size: 0.75rem;
599
+ font-family: inherit;
600
+ color: var(--wd-text);
601
+ cursor: pointer;
602
+ /* appearance: none + this file's own chevron svg (data-uri, same
603
+ stroke/curve as Expandable.astro's/NavTree.astro's own chevrons -
604
+ one visual "this is a dropdown" affordance across the whole site,
605
+ not a second one improvised just for this control) replaces each
606
+ browser's own inconsistently-styled native arrow, so the pill
607
+ reads the same in Chrome/Firefox/Safari alike. */
608
+ appearance: none;
609
+ -webkit-appearance: none;
610
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'%3E%3Cpath d='M2 3.5L5 6.5L8 3.5' stroke='%23888' stroke-width='1.4' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
611
+ background-repeat: no-repeat;
612
+ background-position: right center;
613
+ padding-right: 1rem;
614
+ }
615
+ /* The dropdown list a native <select> opens is a separate,
616
+ browser-rendered popup that the rules above (all scoped to the
617
+ closed box) can't reach - left alone it renders with the OS/browser
618
+ default light popup (white background, near-black text) regardless
619
+ of the site's dark theme, which is exactly the jarring flash of
620
+ light seen against everything else here. Chrome/Firefox/Edge do
621
+ respect background-color/color set directly on <option>, so this
622
+ is the most that can be done without replacing the native <select>
623
+ with a fully custom listbox - Safari has weaker support and falls
624
+ back to its own default popup, but degrades no worse than before. */
625
+ .wd-api-select option,
626
+ .wd-api-url-select option {
627
+ background-color: var(--wd-surface);
628
+ color: var(--wd-text);
629
+ }
630
+ .wd-api-status-select-wrap {
631
+ padding-left: 0.45rem;
632
+ }
633
+ .wd-api-status-dot {
634
+ flex-shrink: 0;
635
+ width: 0.5rem;
636
+ height: 0.5rem;
637
+ border-radius: 999px;
638
+ background: var(--wd-text-muted);
639
+ }
640
+ .wd-api-status-dot-ok {
641
+ background: #16a34a;
642
+ }
643
+ .wd-api-status-dot-error {
644
+ background: #dc2626;
645
+ }
646
+ .wd-api-status-dot-neutral {
647
+ background: var(--wd-text-muted);
648
+ }
649
+ /* The "Try it" button used to be a separate full-width block below the
650
+ card; moved inline into the Request card's own header, next to the
651
+ language select, matching the reference design - a compact pill
652
+ button rather than a full-width bar. */
653
+ .wd-api-try-inline {
654
+ display: inline-flex;
655
+ align-items: center;
656
+ gap: 0.3rem;
657
+ padding: 0.3rem 0.75rem;
658
+ border-radius: 0.5rem;
659
+ border: none;
660
+ background: var(--wd-primary);
661
+ color: var(--wd-on-primary);
662
+ font-size: 0.75rem;
663
+ font-weight: 600;
664
+ cursor: pointer;
665
+ }
666
+ .wd-api-try-icon {
667
+ font-size: 0.65rem;
668
+ }
669
+ .wd-api-icon-btn {
670
+ display: inline-flex;
671
+ align-items: center;
672
+ justify-content: center;
673
+ width: 1.8rem;
674
+ height: 1.8rem;
675
+ border-radius: 0.4rem;
676
+ border: none;
677
+ background: none;
678
+ color: var(--wd-text-muted);
679
+ cursor: pointer;
680
+ font-size: 0.95rem;
681
+ }
682
+ .wd-api-icon-btn:hover {
683
+ background: var(--wd-background);
684
+ color: var(--wd-text);
685
+ }
686
+ /* Clips its own content (a code block's baked-in Shiki background,
687
+ mainly) to the card's bottom corners - moved here from .wd-api-card
688
+ itself so that clip only ever applies to the body, not the head
689
+ above it, where ApiLangSelect.astro's dropdown menu now lives.
690
+ overflow: hidden directly on .wd-api-card clipped that menu too
691
+ whenever it opened past the card's own edge (visible on any
692
+ narrower/shorter card, e.g. a short request sample) - the head
693
+ never had a distinct background box of its own needing this same
694
+ clip, so it doesn't need overflow: hidden at all. */
695
+ .wd-api-card-body {
696
+ position: relative;
697
+ padding: 0.75rem;
698
+ overflow: hidden;
699
+ border-radius: 0 0 0.75rem 0.75rem;
700
+ }
701
+ /* Floating overlay on top of the code block itself, not a header
702
+ button - matches the reference design, where the copy affordance
703
+ sits at the top-right corner of the code area rather than beside
704
+ the language/status select. Always visible here (unlike
705
+ .wd-code-copy-btn's hover-reveal in [...slug].astro, the same idea
706
+ applied to prose code fences) - this is a persistent reference
707
+ panel a reader is actively using, not flowing article content where
708
+ a visible-on-hover control is less visually noisy. */
709
+ .wd-api-code-copy-btn {
710
+ position: absolute;
711
+ top: 0.65rem;
712
+ right: 0.65rem;
713
+ z-index: 1;
714
+ display: inline-flex;
715
+ align-items: center;
716
+ justify-content: center;
717
+ width: 1.7rem;
718
+ height: 1.7rem;
719
+ padding: 0;
720
+ border-radius: 0.4rem;
721
+ border: 1px solid var(--wd-border);
722
+ background: var(--wd-surface);
723
+ color: var(--wd-text-muted);
724
+ font-size: 0.85rem;
725
+ line-height: 1;
726
+ cursor: pointer;
727
+ }
728
+ .wd-api-code-copy-btn:hover {
729
+ color: var(--wd-text);
730
+ background: var(--wd-background);
731
+ }
732
+ /* Line-number gutter - the exact same CSS-counter approach
733
+ .wd-code-lines uses for a fenced (```) content code block
734
+ ([...slug].astro's own comment on that rule explains the mechanism)
735
+ - Astro's <Code/> (used for these sidebar samples) produces the
736
+ identical per-line `.line` span structure Shiki's markdown pipeline
737
+ does, so the same counter trick applies unchanged. Unconditional
738
+ here (no opt-in class/meta-flag needed, unlike article content) -
739
+ every request/response sample in this panel always shows line
740
+ numbers, matching the reference design. */
741
+ .wd-api-pre-lines code {
742
+ counter-reset: wd-api-code-line;
743
+ }
744
+ .wd-api-pre-lines .line {
745
+ counter-increment: wd-api-code-line;
746
+ }
747
+ .wd-api-pre-lines .line::before {
748
+ content: counter(wd-api-code-line);
749
+ display: inline-block;
750
+ width: 1.6em;
751
+ margin-right: 1em;
752
+ text-align: right;
753
+ color: var(--wd-text-muted);
754
+ user-select: none;
755
+ }
756
+ .wd-api-card-body .wd-api-pre {
757
+ border: none;
758
+ background: none;
759
+ padding: 0;
760
+ }
761
+ /* max-height + overflow-y (on top of the pre-existing overflow-x, for
762
+ a long single line like a curl command's own URL) is what makes a
763
+ long code block scroll *internally* instead of just growing the
764
+ card to fit it - without this, a request/response body long enough
765
+ to need it (the kitchen-sink POST .../variants example this was
766
+ caught against, comparing its 201/400/404 response bodies of very
767
+ different lengths) just kept growing the Request card taller every
768
+ time more of it needed to render, which - since both cards share
769
+ one sticky, fixed-max-height panel (.wd-api-panel, see its own
770
+ comment) - pushed the Response card further down and further out of
771
+ the panel's own bounded height each time, looking like it was
772
+ "getting more hidden" the more content the Request card grew to
773
+ fit. Bounding every .wd-api-pre's own height here fixes both at
774
+ once: the block itself gets a real scrollbar for content past this
775
+ height, and neither card can grow tall enough to squeeze its sibling
776
+ out of view anymore. Applies to every .wd-api-pre in this file
777
+ uniformly - the sidebar's Request/Response cards and the Try-it
778
+ modal's own preview panels (request samples + the live response
779
+ body) all share this one class, so one rule covers all of them. */
780
+ .wd-api-pre {
781
+ overflow-x: auto;
782
+ overflow-y: auto;
783
+ max-height: 20rem;
784
+ font-size: 0.8rem;
785
+ margin: 0;
786
+ }
787
+ .wd-api-pre code {
788
+ background: none;
789
+ padding: 0;
790
+ white-space: pre;
791
+ }
792
+ /* The sidebar request/response samples are rendered via astro:components'
793
+ <Code/> (see the frontmatter) so they get real Shiki highlighting
794
+ that follows the site's [data-theme] toggle. Earlier this forced
795
+ the baked-in background transparent to blend into .wd-api-card's
796
+ own surface color - but that strips a theme's background away
797
+ while keeping its foreground, which only looks right for themes
798
+ whose foreground happens to already have enough contrast against
799
+ the card's own (unrelated) surface color. A regular MDX fenced
800
+ code block never does this (see .wd-article pre.astro-code in
801
+ [...slug].astro) - it always keeps the theme's own background+
802
+ foreground pairing intact, which is what makes *any* Shiki theme
803
+ name safe to use on either side of writedocs.json's styles.codeblocks.
804
+ Matching that here instead: the card-body's own padding moves onto
805
+ the codeblock itself, so the theme's real background fills the
806
+ card edge-to-edge (clipped to its rounded corners by .wd-api-card's
807
+ own overflow: hidden) exactly like a regular content codeblock,
808
+ rather than floating disconnected from it. */
809
+ .wd-api-panel .wd-api-card-body {
810
+ padding: 0;
811
+ /* The genuine floor .wd-api-panel .wd-api-card's own comment refers
812
+ to: this can shrink (flex: 1 1 auto, min-height overridden down
813
+ from its own multi-rem default below) as the panel runs out of
814
+ room, but never past ~8rem - enough for a handful of code lines to
815
+ stay readable. display: flex here (not the .astro-code child
816
+ directly) is what lets that child claim 100% of whatever height
817
+ this ends up with via its own flex: 1 below, in place of the fixed
818
+ max-height: 20rem every other .wd-api-pre in this file still uses
819
+ (Try-it modal's own preview panels, .wd-api-pre's own comment) -
820
+ those sit in .wd-api-modal-preview, a plain scrolling column with
821
+ no height cap of its own, so they never hit this squeeze at all. */
822
+ display: flex;
823
+ flex-direction: column;
824
+ flex: 1 1 auto;
825
+ min-height: 8rem;
826
+ }
827
+ .wd-api-panel .wd-api-card-body .astro-code {
828
+ margin: 0;
829
+ padding: 0.75rem 0.9rem;
830
+ border-radius: 0;
831
+ /* Overrides .wd-api-pre's own max-height: 20rem (that rule's own
832
+ comment) - here the code block fills whatever height its
833
+ flex-column parent above actually has, shrinking or growing with
834
+ it, rather than sitting at a fixed height regardless of how much
835
+ (or little) room is actually available. min-height: 0 lets it
836
+ shrink freely - the real floor is the parent's own min-height:
837
+ 8rem above, not this element's. */
838
+ flex: 1 1 auto;
839
+ min-height: 0;
840
+ max-height: none;
841
+ }
842
+
843
+ .wd-api-card .wd-api-card-body .shiki {
844
+ border-radius: 0;
845
+ }
846
+ /* The modal's request preview starts as a plain <pre> (see the
847
+ frontmatter) and only gains the .astro-code class once
848
+ initApiPanel()'s renderModalPanel() swaps in real Shiki output -
849
+ lazily, the first time the modal is opened (see loadHighlighter()
850
+ in the <script> below). :has() lets the same edge-to-edge treatment
851
+ as the sidebar above apply the instant that happens, without any
852
+ extra JS to toggle a class on the card-body itself. Before that,
853
+ the plain-text panel keeps the ordinary blended-into-the-card look
854
+ via .wd-api-card-body .wd-api-pre above. */
855
+ .wd-api-modal-preview .wd-api-card-body:has(.astro-code) {
856
+ padding: 0;
857
+ }
858
+ .wd-api-modal-preview .wd-api-card-body .astro-code {
859
+ margin: 0;
860
+ padding: 0.75rem 0.9rem;
861
+ }
862
+
863
+ .wd-api-modal-overlay {
864
+ position: fixed;
865
+ inset: 0;
866
+ z-index: 100;
867
+ display: flex;
868
+ align-items: center;
869
+ justify-content: center;
870
+ padding: 2rem;
871
+ background: rgba(15, 23, 42, 0.5);
872
+ }
873
+ .wd-api-modal-overlay[hidden] { display: none; }
874
+ .wd-api-modal {
875
+ width: 100%;
876
+ max-width: min(96vw, 1440px);
877
+ max-height: 85vh;
878
+ display: flex;
879
+ flex-direction: column;
880
+ background: var(--wd-background);
881
+ border: 1px solid var(--wd-border);
882
+ border-radius: 0.75rem;
883
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
884
+ overflow: hidden;
885
+ }
886
+ .wd-api-modal-head {
887
+ display: flex;
888
+ align-items: center;
889
+ /* Not space-between: the title stays flush left and everything
890
+ else (examples select, then Send/Close) is pushed flush right by
891
+ .wd-api-modal-example-wrap's margin-left: auto below - so a spec
892
+ with no examples still ends up with title-left/actions-right,
893
+ the same layout space-between gave before this component had a
894
+ middle item to place. */
895
+ justify-content: flex-start;
896
+ gap: 1rem;
897
+ padding: 1rem 1.25rem;
898
+ border-bottom: 1px solid var(--wd-border);
899
+ flex-shrink: 0;
900
+ }
901
+ .wd-api-modal-title {
902
+ display: flex;
903
+ align-items: center;
904
+ gap: 0.6rem;
905
+ font-size: 0.95rem;
906
+ }
907
+ .wd-api-modal-title-text {
908
+ font-weight: 600;
909
+ color: var(--wd-heading);
910
+ }
911
+ /* Only rendered when the operation's request body actually carries a
912
+ named `examples` map (see requestExampleEntries above) - sits
913
+ between the title and the Send/Close actions when present. */
914
+ .wd-api-modal-example-wrap {
915
+ flex-shrink: 0;
916
+ }
917
+ .wd-api-modal-actions {
918
+ display: flex;
919
+ align-items: center;
920
+ gap: 0.5rem;
921
+ /* Pushes just this element flush to the right edge, leaving the
922
+ title (and the examples select right after it, when present)
923
+ packed on the left per the mockup - works whether or not the
924
+ examples select is rendered, so a spec without any `examples`
925
+ still lands title-left/actions-right same as before this select
926
+ existed. */
927
+ margin-left: auto;
928
+ }
929
+ .wd-api-send {
930
+ padding: 0.5rem 1rem;
931
+ border-radius: 0.4rem;
932
+ border: none;
933
+ background: var(--wd-primary);
934
+ color: var(--wd-on-primary);
935
+ font-size: 0.85rem;
936
+ font-weight: 600;
937
+ cursor: pointer;
938
+ }
939
+ .wd-api-send:disabled {
940
+ opacity: 0.6;
941
+ cursor: default;
942
+ }
943
+ .wd-api-modal-body {
944
+ display: grid;
945
+ /* Form (params/body inputs) gets roughly twice the preview
946
+ column's width - the form has more to lay out (header/path/
947
+ query groups, the body textarea, potentially long field lists),
948
+ while the preview is just two-three fixed-height cards. */
949
+ grid-template-columns: 2fr 1fr;
950
+ gap: 0;
951
+ overflow-y: auto;
952
+ }
953
+ .wd-api-modal-form {
954
+ padding: 1.25rem;
955
+ border-right: 1px solid var(--wd-border);
956
+ overflow-y: auto;
957
+ }
958
+ .wd-api-modal-preview {
959
+ padding: 1.25rem;
960
+ display: flex;
961
+ flex-direction: column;
962
+ gap: 1rem;
963
+ overflow-y: auto;
964
+ /* No background of its own - inherits .wd-api-modal's background,
965
+ same as .wd-api-modal-form on the other side of the divider, so
966
+ the two columns read as one surface. The Authentication/Request/
967
+ Response cards inside still pop off it via their own
968
+ background: var(--wd-surface) (.wd-api-card below). */
969
+ }
970
+ @media (max-width: 760px) {
971
+ .wd-api-modal-body {
972
+ grid-template-columns: 1fr;
973
+ }
974
+ .wd-api-modal-form {
975
+ border-right: none;
976
+ border-bottom: 1px solid var(--wd-border);
977
+ }
978
+ }
979
+ .wd-api-field {
980
+ display: flex;
981
+ flex-direction: column;
982
+ gap: 0.3rem;
983
+ margin-bottom: 0.75rem;
984
+ font-size: 0.85rem;
985
+ }
986
+ .wd-api-field > span:first-child {
987
+ color: var(--wd-text-muted);
988
+ font-weight: 500;
989
+ display: flex;
990
+ align-items: center;
991
+ gap: 0.4rem;
992
+ }
993
+ .wd-api-field-group {
994
+ margin-bottom: 1.1rem;
995
+ }
996
+ /* Replaces the old standalone "Base URL" labeled field - a single
997
+ method+URL bar where the URL itself is always one element showing
998
+ the complete request URL (server + path together), never an
999
+ editable text input split from a separately-boxed path. With one
1000
+ server in the spec it's plain non-editable text (.wd-api-url-full);
1001
+ with more than one, a real <select> (.wd-api-url-select) whose
1002
+ every option's own label is already the full concatenated URL, so
1003
+ the control still reads as one complete URL whether it's open or
1004
+ closed - see the markup above for which one renders. */
1005
+ .wd-api-modal-url-bar {
1006
+ display: flex;
1007
+ align-items: center;
1008
+ gap: 0.5rem;
1009
+ padding: 0.4rem 0.5rem;
1010
+ margin-bottom: 1.1rem;
1011
+ border: 1px solid var(--wd-border);
1012
+ border-radius: 0.5rem;
1013
+ background: var(--wd-background);
1014
+ }
1015
+ .wd-api-url-full {
1016
+ flex: 1;
1017
+ min-width: 0;
1018
+ overflow-wrap: anywhere;
1019
+ color: var(--wd-text);
1020
+ font-size: 0.85rem;
1021
+ font-family: monospace;
1022
+ }
1023
+ .wd-api-url-select {
1024
+ flex: 1;
1025
+ min-width: 0;
1026
+ border: none;
1027
+ background: none;
1028
+ padding: 0.2rem 1rem 0.2rem 0;
1029
+ color: var(--wd-text);
1030
+ font-size: 0.85rem;
1031
+ font-family: monospace;
1032
+ /* Same custom-chevron treatment as .wd-api-select below - unlike
1033
+ that one this isn't wrapped in a pill, since it needs to read as
1034
+ plain inline text flowing right after the method badge, not a
1035
+ separate control floating in the bar. */
1036
+ appearance: none;
1037
+ -webkit-appearance: none;
1038
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='10' viewBox='0 0 10 10'%3E%3Cpath d='M2 3.5L5 6.5L8 3.5' stroke='%23888' stroke-width='1.4' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
1039
+ background-repeat: no-repeat;
1040
+ background-position: right center;
1041
+ cursor: pointer;
1042
+ }
1043
+ .wd-api-url-select:focus {
1044
+ outline: none;
1045
+ }
1046
+ .wd-api-field-group-label {
1047
+ display: block;
1048
+ font-size: 1rem;
1049
+ font-weight: 600;
1050
+ color: var(--wd-text);
1051
+ margin-bottom: 0.6rem;
1052
+ padding-bottom: 0.4rem;
1053
+ border-bottom: 1px solid var(--wd-border);
1054
+ }
1055
+ .wd-api-input,
1056
+ .wd-api-textarea {
1057
+ width: 100%;
1058
+ padding: 0.5rem 0.65rem;
1059
+ border: 1px solid var(--wd-border);
1060
+ border-radius: 0.4rem;
1061
+ background: var(--wd-background);
1062
+ color: var(--wd-text);
1063
+ font-size: 0.85rem;
1064
+ font-family: inherit;
1065
+ }
1066
+ .wd-api-textarea {
1067
+ font-family: monospace;
1068
+ resize: vertical;
1069
+ }
1070
+ .wd-api-response-status {
1071
+ font-size: 0.8rem;
1072
+ font-weight: 600;
1073
+ margin-bottom: 0.5rem;
1074
+ color: var(--wd-text-muted);
1075
+ }
1076
+ .wd-api-response-status.wd-api-status-ok { color: #16a34a; }
1077
+ .wd-api-response-status.wd-api-status-error { color: #dc2626; }
1078
+ @media (max-width: 1150px) {
1079
+ .wd-api-panel { display: none; }
1080
+ }
1081
+ </style>
1082
+
1083
+ <script>
1084
+ // Shiki's WASM engine, exactly the 3 grammars the Try-it modal needs,
1085
+ // and the 2 writedocs.json styles.codeblocks themes are fetched lazily, only
1086
+ // once the modal is actually opened - not on every operation page load
1087
+ // - so the live-updating preview can use *real* Shiki highlighting
1088
+ // (matching every other codeblock on the site, see ApiReferencePanel's
1089
+ // own CSS comment on this) without adding that weight to pages nobody
1090
+ // ever opens Try-it on. Declared at true module scope (outside
1091
+ // initApiPanel) so it's fetched once and reused across astro:page-load
1092
+ // navigations between operation pages - they all share the same
1093
+ // writedocs.json styles.codeblocks, so one cached highlighter is always
1094
+ // correct regardless of which operation is currently active.
1095
+ //
1096
+ // Deliberately the fine-grained core API (shiki/core +
1097
+ // shiki/engine/oniguruma + the individual @shikijs/langs/* packages)
1098
+ // rather than shiki/bundle/web's own createHighlighter(): that
1099
+ // convenience wrapper's own docs note "importing this function will
1100
+ // bundle all languages and themes" - true even though each is only
1101
+ // *fetched* on demand, Vite still has to code-split and ship every
1102
+ // bundled language (100+, several hundred KB each for ts/tsx/jsx/...)
1103
+ // as its own chunk, just in case. Themes still come from shiki/themes'
1104
+ // full by-name lookup table (unavoidable - which theme is needed isn't
1105
+ // known until writedocs.json is read, so it can't be a static import like
1106
+ // the 3 languages below can), but that alone is a much smaller tax
1107
+ // than the language side would have been.
1108
+ interface ShikiHighlighter {
1109
+ codeToHtml(code: string, options: { lang: string; themes: { light: string; dark: string } }): string;
1110
+ }
1111
+ let wdHighlighter: ShikiHighlighter | null = null;
1112
+ let wdHighlighterPromise: Promise<ShikiHighlighter> | null = null;
1113
+ const MODAL_LANG_TO_SHIKI: Record<string, string> = {
1114
+ curl: 'bash',
1115
+ js: 'javascript',
1116
+ py: 'python',
1117
+ php: 'php',
1118
+ go: 'go',
1119
+ java: 'java',
1120
+ ruby: 'ruby',
1121
+ };
1122
+ // cors-anywhere-style proxy: forwards GET/POST/etc to the URL appended
1123
+ // after the base (protocol required), preserving method/headers/body,
1124
+ // and returns CORS headers so the browser fetch() below succeeds even
1125
+ // when the target API itself doesn't send Access-Control-Allow-Origin.
1126
+ // Only a fallback: a request goes straight to the API first, and through
1127
+ // here only when the browser blocks that (see the send handler below).
1128
+ // Toggle via writedocs.json's `api.proxy` (see data-proxy on the tryit
1129
+ // section below); the displayed curl/fetch/python snippets deliberately
1130
+ // keep showing the real, non-proxied URL - only this in-browser request
1131
+ // actually routes through the proxy.
1132
+ const PROXY_BASE_URL = 'https://proxy.writechoice.io/';
1133
+ function loadHighlighter(themes: { light: string; dark: string }): Promise<ShikiHighlighter> {
1134
+ if (!wdHighlighterPromise) {
1135
+ wdHighlighterPromise = Promise.all([
1136
+ import('shiki/core'),
1137
+ import('shiki/engine/oniguruma'),
1138
+ import('shiki/themes'),
1139
+ import('@shikijs/langs/bash'),
1140
+ import('@shikijs/langs/javascript'),
1141
+ import('@shikijs/langs/python'),
1142
+ import('@shikijs/langs/php'),
1143
+ import('@shikijs/langs/go'),
1144
+ import('@shikijs/langs/java'),
1145
+ import('@shikijs/langs/ruby'),
1146
+ ]).then(([core, engine, themeTable, bash, javascript, python, php, go, java, ruby]) =>
1147
+ core.createHighlighterCore({
1148
+ langs: [bash.default, javascript.default, python.default, php.default, go.default, java.default, ruby.default],
1149
+ themes: [themeTable.bundledThemes[themes.light](), themeTable.bundledThemes[themes.dark]()],
1150
+ engine: engine.createOnigurumaEngine(import('shiki/wasm')),
1151
+ })
1152
+ ) as Promise<ShikiHighlighter>;
1153
+ }
1154
+ return wdHighlighterPromise;
1155
+ }
1156
+ // Same github-light/github-dark fallback as resolveCodeblockTheme()
1157
+ // (src/lib/config.ts) - kept as a literal default here rather than
1158
+ // imported, since this <script> runs in the browser and can't reach
1159
+ // back into server-only modules; the data-themes JSON below is
1160
+ // already resolveCodeblockTheme()'s own output, so this only matters
1161
+ // if that attribute is ever missing or malformed.
1162
+ function parseThemes(raw: string | undefined): { light: string; dark: string } {
1163
+ try {
1164
+ const parsed = raw ? JSON.parse(raw) : {};
1165
+ return { light: parsed.light ?? 'github-light', dark: parsed.dark ?? 'github-dark' };
1166
+ } catch {
1167
+ return { light: 'github-light', dark: 'github-dark' };
1168
+ }
1169
+ }
1170
+
1171
+ // Drives the hidden <select data-role="{rolePrefix}-select"> rendered
1172
+ // by ApiLangSelect.astro from a click on its custom icon+label+
1173
+ // checkmark dropdown - open/close/outside-click/Escape all come free
1174
+ // from the site's shared initDropdowns() (already wired globally
1175
+ // against `document` by TopBar.astro/MobileMenu.astro), so this only
1176
+ // needs to: swap the trigger's icon/label to match the pick (by
1177
+ // cloning the clicked item's own already-rendered <svg> rather than
1178
+ // this script knowing any Iconify id itself), move which item shows
1179
+ // .active, and set+dispatch 'change' on the hidden select so every
1180
+ // listener already written against lang-select/modal-lang-select
1181
+ // below (panel-toggle, live-preview refresh) keeps working unchanged.
1182
+ function initLangDropdown(scope: ParentNode, rolePrefix: string) {
1183
+ const nativeSelect = scope.querySelector<HTMLSelectElement>(`[data-role="${rolePrefix}-select"]`);
1184
+ const trigger = scope.querySelector<HTMLElement>(`[data-role="${rolePrefix}-trigger"]`);
1185
+ // A distinct dataset key from plain wdInit - the trigger is also a
1186
+ // .wd-dropdown-trigger, and initDropdowns() (dropdowns.ts, wired
1187
+ // globally by TopBar.astro/MobileMenu.astro) already claims
1188
+ // trigger.dataset.wdInit as its own "have I wired open/close yet"
1189
+ // guard on this exact element. Sharing that key meant whichever of
1190
+ // the two ran first silently blocked the other from ever attaching -
1191
+ // in practice initDropdowns() always won the race, so the item click
1192
+ // listeners below were never being attached at all.
1193
+ if (!nativeSelect || !trigger || trigger.dataset.wdLangInit) return;
1194
+ trigger.dataset.wdLangInit = 'true';
1195
+ const items = Array.from(scope.querySelectorAll<HTMLButtonElement>(`[data-role="${rolePrefix}-item"]`));
1196
+ items.forEach((item) => {
1197
+ item.addEventListener('click', () => {
1198
+ items.forEach((it) => it.classList.toggle('active', it === item));
1199
+ const icon = item.querySelector('.wd-api-lang-icon');
1200
+ const triggerIcon = trigger.querySelector('.wd-api-lang-icon');
1201
+ if (icon && triggerIcon) triggerIcon.replaceWith(icon.cloneNode(true));
1202
+ const label = item.querySelector('.wd-api-lang-label')?.textContent ?? '';
1203
+ const triggerLabel = trigger.querySelector('.wd-api-lang-label');
1204
+ if (triggerLabel) triggerLabel.textContent = label;
1205
+ nativeSelect.value = item.dataset.value ?? '';
1206
+ nativeSelect.dispatchEvent(new Event('change'));
1207
+ });
1208
+ });
1209
+ }
1210
+
1211
+ function initApiPanel(root: ParentNode) {
1212
+ // Set once the tryit section below wires it up - there's exactly one
1213
+ // Try-it modal per operation page, so a single shared reference (like
1214
+ // the existing `document.querySelector('[data-role="send"]')` a few
1215
+ // lines down, which makes the same single-instance assumption) is all
1216
+ // that's needed for the open-modal handler in the loop below to
1217
+ // trigger a re-render once Shiki finishes loading.
1218
+ let refreshModalPreview: (() => void) | null = null;
1219
+
1220
+ root.querySelectorAll<HTMLElement>('[data-api-panel]').forEach((panel) => {
1221
+ if (panel.dataset.wdInit) return;
1222
+ panel.dataset.wdInit = 'true';
1223
+
1224
+ const langSelect = panel.querySelector<HTMLSelectElement>('[data-role="lang-select"]');
1225
+ const langPanels = Array.from(panel.querySelectorAll<HTMLElement>('[data-lang-panel]'));
1226
+ langSelect?.addEventListener('change', () => {
1227
+ langPanels.forEach((p) => {
1228
+ p.style.display = p.dataset.langPanel === langSelect.value ? 'block' : 'none';
1229
+ });
1230
+ });
1231
+ initLangDropdown(panel, 'lang');
1232
+
1233
+ const statusSelect = panel.querySelector<HTMLSelectElement>('[data-role="status-select"]');
1234
+ const statusPanels = Array.from(panel.querySelectorAll<HTMLElement>('[data-status-panel]'));
1235
+ const statusDot = panel.querySelector<HTMLElement>('[data-role="status-dot"]');
1236
+ statusSelect?.addEventListener('change', () => {
1237
+ statusPanels.forEach((p) => {
1238
+ p.style.display = p.dataset.statusPanel === statusSelect.value ? 'block' : 'none';
1239
+ });
1240
+ // Keeps the leading color dot (green/red/gray, set server-side
1241
+ // from statusToneClass() in the frontmatter - see this file's
1242
+ // own comment there) in sync with whichever status the reader
1243
+ // has switched to - each <option> carries its own tone as a
1244
+ // data attribute for exactly this, since the dot itself isn't
1245
+ // part of the native <select> box the browser renders.
1246
+ const tone = statusSelect.selectedOptions[0]?.dataset.tone;
1247
+ if (statusDot && tone) statusDot.className = `wd-api-status-dot ${tone}`;
1248
+ });
1249
+
1250
+ panel.querySelector('[data-role="copy-request"]')?.addEventListener('click', () => {
1251
+ const visible = langPanels.find((p) => p.style.display !== 'none');
1252
+ if (visible) navigator.clipboard?.writeText(visible.textContent ?? '');
1253
+ });
1254
+ panel.querySelector('[data-role="copy-response"]')?.addEventListener('click', () => {
1255
+ const visible = statusPanels.find((p) => p.style.display !== 'none');
1256
+ if (visible) navigator.clipboard?.writeText(visible.textContent ?? '');
1257
+ });
1258
+
1259
+ const overlay = document.querySelector<HTMLElement>('[data-role="modal-overlay"]');
1260
+ panel.querySelector('[data-role="open-modal"]')?.addEventListener('click', () => {
1261
+ if (overlay) {
1262
+ overlay.hidden = false;
1263
+ document.body.style.overflow = 'hidden';
1264
+ }
1265
+ if (!wdHighlighter) {
1266
+ const tryitSection = document.querySelector<HTMLElement>('[data-api-tryit]');
1267
+ const themes = parseThemes(tryitSection?.dataset.themes);
1268
+ loadHighlighter(themes).then((h) => {
1269
+ wdHighlighter = h;
1270
+ refreshModalPreview?.();
1271
+ });
1272
+ }
1273
+ });
1274
+ });
1275
+
1276
+ const overlay = root.querySelector<HTMLElement>('[data-role="modal-overlay"]');
1277
+ if (overlay && !overlay.dataset.wdInit) {
1278
+ overlay.dataset.wdInit = 'true';
1279
+ const close = () => {
1280
+ overlay.hidden = true;
1281
+ document.body.style.overflow = '';
1282
+ };
1283
+ overlay.addEventListener('click', (e) => {
1284
+ if (e.target === overlay) close();
1285
+ });
1286
+ overlay.querySelector('[data-role="close-modal"]')?.addEventListener('click', close);
1287
+ document.addEventListener('keydown', (e) => {
1288
+ if (e.key === 'Escape' && !overlay.hidden) close();
1289
+ });
1290
+
1291
+ const modalLangSelect = overlay.querySelector<HTMLSelectElement>('[data-role="modal-lang-select"]');
1292
+ const modalLangPanels = Array.from(overlay.querySelectorAll<HTMLElement>('[data-modal-lang-panel]'));
1293
+ modalLangSelect?.addEventListener('change', () => {
1294
+ modalLangPanels.forEach((p) => {
1295
+ p.style.display = p.dataset.modalLangPanel === modalLangSelect.value ? 'block' : 'none';
1296
+ });
1297
+ });
1298
+ initLangDropdown(overlay, 'modal-lang');
1299
+ }
1300
+
1301
+ root.querySelectorAll<HTMLElement>('[data-api-tryit]').forEach((section) => {
1302
+ if (section.dataset.wdInit) return;
1303
+ section.dataset.wdInit = 'true';
1304
+
1305
+ const method = section.dataset.method ?? 'GET';
1306
+ const opPath = section.dataset.path ?? '';
1307
+ const themes = parseThemes(section.dataset.themes);
1308
+ const proxyEnabled = section.dataset.proxy === 'true';
1309
+ // Either a plain <span data-value="..."> (single-server spec) or a
1310
+ // <select> (multiple servers) - see the markup comment above.
1311
+ // getBaseUrl() normalizes the two into one string, whichever
1312
+ // element actually rendered.
1313
+ const baseUrlEl = section.querySelector<HTMLElement>('[data-role="base-url"]');
1314
+ function getBaseUrl(): string {
1315
+ if (!baseUrlEl) return '';
1316
+ if (baseUrlEl instanceof HTMLSelectElement) return baseUrlEl.value;
1317
+ return baseUrlEl.dataset.value ?? '';
1318
+ }
1319
+ const authInputs = Array.from(section.querySelectorAll<HTMLInputElement>('[data-role="auth"]'));
1320
+ const paramInputs = Array.from(section.querySelectorAll<HTMLInputElement>('[data-role="param"]'));
1321
+ const bodyInput = section.querySelector<HTMLTextAreaElement>('[data-role="body"]');
1322
+ const sendBtn = document.querySelector<HTMLButtonElement>('[data-role="send"]');
1323
+ const responseStatusEl = section.querySelector<HTMLElement>('[data-role="response-status"]');
1324
+ const responseBodyEl = section.querySelector<HTMLElement>('[data-role="response-body"] code');
1325
+ const modalLangPanels = Array.from(section.querySelectorAll<HTMLElement>('[data-modal-lang-panel]'));
1326
+
1327
+ // A reader's credentials last for the tab, not forever: sessionStorage
1328
+ // carries them across the pages of one visit and forgets them when the
1329
+ // tab closes. Older versions kept them in localStorage indefinitely -
1330
+ // a key found there is moved over once and deleted.
1331
+ authInputs.forEach((input) => {
1332
+ const storageKey = `wd-api-auth:${input.dataset.authName ?? ''}`;
1333
+ try {
1334
+ const legacy = localStorage.getItem(storageKey);
1335
+ if (legacy !== null) {
1336
+ if (sessionStorage.getItem(storageKey) === null) sessionStorage.setItem(storageKey, legacy);
1337
+ localStorage.removeItem(storageKey);
1338
+ }
1339
+ const saved = sessionStorage.getItem(storageKey);
1340
+ if (saved) input.value = saved;
1341
+ } catch {
1342
+ // storage unavailable - auth just won't carry across pages
1343
+ }
1344
+ input.addEventListener('input', () => {
1345
+ try {
1346
+ sessionStorage.setItem(storageKey, input.value);
1347
+ } catch {
1348
+ // ignore
1349
+ }
1350
+ });
1351
+ });
1352
+
1353
+ // Keeps the modal's request-sample preview (plain <pre><code> - see
1354
+ // the frontmatter) in sync with whatever the user has typed into
1355
+ // the form so far, substituting a bracketed placeholder (<name>,
1356
+ // <token>, ...) for anything still empty so the preview always
1357
+ // renders something readable instead of looking broken. This is
1358
+ // deliberately its own code path rather than reusing the Send
1359
+ // handler below: Send needs strict validation with user-facing
1360
+ // error messages, while this needs lenient, always-renders-
1361
+ // something behavior on every keystroke. It loosely mirrors the
1362
+ // structure of buildCurlSnippet/buildFetchSnippet/buildPythonSnippet
1363
+ // (src/lib/openapi-render.ts) - same per-language shape, live values
1364
+ // instead of a schema-derived example.
1365
+ function collectLiveRequest() {
1366
+ const baseUrl = (getBaseUrl().trim() || 'https://api.example.com').replace(/\/$/, '');
1367
+ let path = opPath;
1368
+ const queryParams: { name: string; value: string }[] = [];
1369
+ const headerParams: { name: string; value: string }[] = [];
1370
+ for (const input of paramInputs) {
1371
+ const name = input.dataset.paramName ?? '';
1372
+ const paramIn = input.dataset.paramIn;
1373
+ const value = input.value.trim() || `<${name}>`;
1374
+ if (paramIn === 'path') {
1375
+ path = path.replace(`{${name}}`, value);
1376
+ } else if (paramIn === 'query') {
1377
+ queryParams.push({ name, value });
1378
+ } else if (paramIn === 'header') {
1379
+ headerParams.push({ name, value });
1380
+ }
1381
+ }
1382
+
1383
+ const securityHeaders: { name: string; value: string }[] = [];
1384
+ const securityQuery: { name: string; value: string }[] = [];
1385
+ let basicAuth: string | null = null;
1386
+ for (const input of authInputs) {
1387
+ const name = input.dataset.authName ?? '';
1388
+ const type = input.dataset.authType;
1389
+ const scheme = input.dataset.authScheme;
1390
+ const authIn = input.dataset.authIn;
1391
+ const value = input.value.trim();
1392
+ if (type === 'apiKey' && authIn === 'header') {
1393
+ securityHeaders.push({ name, value: value || `<${name}>` });
1394
+ } else if (type === 'apiKey' && authIn === 'query') {
1395
+ securityQuery.push({ name, value: value || `<${name}>` });
1396
+ } else if (type === 'http' && scheme === 'bearer') {
1397
+ securityHeaders.push({ name: 'Authorization', value: `Bearer ${value || '<token>'}` });
1398
+ } else if (type === 'http' && scheme === 'basic') {
1399
+ basicAuth = value || '<username>:<password>';
1400
+ }
1401
+ }
1402
+
1403
+ const hasBodyField = !!bodyInput;
1404
+ const bodyRaw = bodyInput?.value.trim() ?? '';
1405
+
1406
+ return { method, baseUrl, path, queryParams, headerParams, securityHeaders, securityQuery, basicAuth, hasBodyField, bodyRaw };
1407
+ }
1408
+ type LiveRequestState = ReturnType<typeof collectLiveRequest>;
1409
+
1410
+ function liveCurlSnippet(state: LiveRequestState): string {
1411
+ const query = [...state.queryParams, ...state.securityQuery];
1412
+ const url =
1413
+ state.baseUrl + state.path + (query.length ? '?' + query.map((q) => `${q.name}=${q.value}`).join('&') : '');
1414
+ const lines = [`curl -X ${state.method} "${url}" \\`];
1415
+ if (state.hasBodyField) lines.push(` -H "Content-Type: application/json" \\`);
1416
+ for (const h of state.headerParams) lines.push(` -H "${h.name}: ${h.value}" \\`);
1417
+ for (const h of state.securityHeaders) lines.push(` -H "${h.name}: ${h.value}" \\`);
1418
+ if (state.basicAuth) lines.push(` -u "${state.basicAuth}" \\`);
1419
+ if (state.bodyRaw) lines.push(` -d '${state.bodyRaw}'`);
1420
+ const last = lines[lines.length - 1];
1421
+ lines[lines.length - 1] = last.endsWith('\\') ? last.slice(0, -2) : last;
1422
+ return lines.join('\n');
1423
+ }
1424
+
1425
+ function liveFetchSnippet(state: LiveRequestState): string {
1426
+ const url = state.baseUrl + state.path;
1427
+ const headers = [
1428
+ ...(state.hasBodyField ? [`'Content-Type': 'application/json'`] : []),
1429
+ ...state.securityHeaders.map((h) => `'${h.name}': '${h.value}'`),
1430
+ ];
1431
+ const optsLines = [
1432
+ `method: '${state.method}'`,
1433
+ headers.length ? `headers: { ${headers.join(', ')} }` : null,
1434
+ state.hasBodyField && state.bodyRaw ? `body: JSON.stringify(${state.bodyRaw})` : null,
1435
+ ].filter(Boolean);
1436
+ return `const response = await fetch(\`${url}\`, {\n ${optsLines.join(',\n ')}\n});\nconst data = await response.json();`;
1437
+ }
1438
+
1439
+ function livePythonSnippet(state: LiveRequestState): string {
1440
+ const url = state.baseUrl + state.path;
1441
+ const headers = state.securityHeaders.map((h) => `"${h.name}": "${h.value}"`);
1442
+ const lines = ['import requests', '', `response = requests.request(`, ` "${state.method}",`, ` "${url}",`];
1443
+ if (headers.length) lines.push(` headers={ ${headers.join(', ')} },`);
1444
+ if (state.hasBodyField && state.bodyRaw) {
1445
+ lines.push(
1446
+ ` json=${state.bodyRaw.replace(/\btrue\b/g, 'True').replace(/\bfalse\b/g, 'False').replace(/\bnull\b/g, 'None')},`
1447
+ );
1448
+ }
1449
+ lines.push(')', 'data = response.json()');
1450
+ return lines.join('\n');
1451
+ }
1452
+
1453
+ // php/go/java/ruby mirror liveFetchSnippet/livePythonSnippet's own
1454
+ // subset of liveCurlSnippet's behavior (no query-param URL
1455
+ // building, no basic-auth) - same precedent buildPhpSnippet/
1456
+ // buildGoSnippet/buildJavaSnippet/buildRubySnippet in
1457
+ // src/lib/openapi-render.ts follow for the static versions of
1458
+ // these same four, for the same reason (see that file's comment).
1459
+ function livePhpSnippet(state: LiveRequestState): string {
1460
+ const url = state.baseUrl + state.path;
1461
+ const headers = [
1462
+ ...(state.hasBodyField ? [`"Content-Type: application/json"`] : []),
1463
+ ...state.headerParams.map((h) => `"${h.name}: ${h.value}"`),
1464
+ ...state.securityHeaders.map((h) => `"${h.name}: ${h.value}"`),
1465
+ ];
1466
+ const lines = [
1467
+ '$ch = curl_init();',
1468
+ `curl_setopt($ch, CURLOPT_URL, "${url}");`,
1469
+ 'curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);',
1470
+ `curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "${state.method}");`,
1471
+ ];
1472
+ if (headers.length) lines.push(`curl_setopt($ch, CURLOPT_HTTPHEADER, [${headers.join(', ')}]);`);
1473
+ if (state.hasBodyField && state.bodyRaw) lines.push(`curl_setopt($ch, CURLOPT_POSTFIELDS, '${state.bodyRaw}');`);
1474
+ lines.push('$response = curl_exec($ch);', 'curl_close($ch);');
1475
+ return `<?php\n${lines.join('\n')}`;
1476
+ }
1477
+
1478
+ function liveGoSnippet(state: LiveRequestState): string {
1479
+ const url = state.baseUrl + state.path;
1480
+ const headers = [
1481
+ ...(state.hasBodyField ? [`req.Header.Set("Content-Type", "application/json")`] : []),
1482
+ ...state.headerParams.map((h) => `req.Header.Set("${h.name}", "${h.value}")`),
1483
+ ...state.securityHeaders.map((h) => `req.Header.Set("${h.name}", "${h.value}")`),
1484
+ ];
1485
+ const hasBody = state.hasBodyField && state.bodyRaw;
1486
+ const bodyExpr = hasBody ? `strings.NewReader(\`${state.bodyRaw}\`)` : 'nil';
1487
+ const lines = [
1488
+ 'package main',
1489
+ '',
1490
+ 'import (',
1491
+ '\t"fmt"',
1492
+ '\t"io"',
1493
+ '\t"net/http"',
1494
+ ...(hasBody ? ['\t"strings"'] : []),
1495
+ ')',
1496
+ '',
1497
+ 'func main() {',
1498
+ `\treq, _ := http.NewRequest("${state.method}", "${url}", ${bodyExpr})`,
1499
+ ...headers.map((h) => `\t${h}`),
1500
+ '',
1501
+ '\tresp, err := http.DefaultClient.Do(req)',
1502
+ '\tif err != nil {',
1503
+ '\t\tpanic(err)',
1504
+ '\t}',
1505
+ '\tdefer resp.Body.Close()',
1506
+ '',
1507
+ '\tdata, _ := io.ReadAll(resp.Body)',
1508
+ '\tfmt.Println(string(data))',
1509
+ '}',
1510
+ ];
1511
+ return lines.join('\n');
1512
+ }
1513
+
1514
+ function liveJavaSnippet(state: LiveRequestState): string {
1515
+ const url = state.baseUrl + state.path;
1516
+ const headers = [
1517
+ ...(state.hasBodyField ? [`.header("Content-Type", "application/json")`] : []),
1518
+ ...state.headerParams.map((h) => `.header("${h.name}", "${h.value}")`),
1519
+ ...state.securityHeaders.map((h) => `.header("${h.name}", "${h.value}")`),
1520
+ ];
1521
+ const hasBody = state.hasBodyField && state.bodyRaw;
1522
+ const bodyPublisher = hasBody
1523
+ ? `HttpRequest.BodyPublishers.ofString(${JSON.stringify(state.bodyRaw)})`
1524
+ : 'HttpRequest.BodyPublishers.noBody()';
1525
+ const lines = [
1526
+ 'HttpClient client = HttpClient.newHttpClient();',
1527
+ 'HttpRequest request = HttpRequest.newBuilder()',
1528
+ ` .uri(URI.create("${url}"))`,
1529
+ ...headers.map((h) => ` ${h}`),
1530
+ ` .method("${state.method}", ${bodyPublisher})`,
1531
+ ' .build();',
1532
+ '',
1533
+ 'HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());',
1534
+ 'System.out.println(response.body());',
1535
+ ];
1536
+ return lines.join('\n');
1537
+ }
1538
+
1539
+ function liveRubySnippet(state: LiveRequestState): string {
1540
+ const url = state.baseUrl + state.path;
1541
+ const methodClass = state.method.charAt(0).toUpperCase() + state.method.slice(1).toLowerCase();
1542
+ const headers = [
1543
+ ...(state.hasBodyField ? [`request["Content-Type"] = "application/json"`] : []),
1544
+ ...state.headerParams.map((h) => `request["${h.name}"] = "${h.value}"`),
1545
+ ...state.securityHeaders.map((h) => `request["${h.name}"] = "${h.value}"`),
1546
+ ];
1547
+ const hasBody = state.hasBodyField && state.bodyRaw;
1548
+ const lines = [
1549
+ 'require "net/http"',
1550
+ 'require "uri"',
1551
+ '',
1552
+ `uri = URI("${url}")`,
1553
+ 'http = Net::HTTP.new(uri.host, uri.port)',
1554
+ 'http.use_ssl = uri.scheme == "https"',
1555
+ '',
1556
+ `request = Net::HTTP::${methodClass}.new(uri)`,
1557
+ ...headers,
1558
+ ...(hasBody ? [`request.body = ${JSON.stringify(state.bodyRaw)}`] : []),
1559
+ '',
1560
+ 'response = http.request(request)',
1561
+ 'puts response.body',
1562
+ ];
1563
+ return lines.join('\n');
1564
+ }
1565
+
1566
+ const LIVE_SNIPPET_BUILDERS: Record<string, (state: LiveRequestState) => string> = {
1567
+ curl: liveCurlSnippet,
1568
+ js: liveFetchSnippet,
1569
+ py: livePythonSnippet,
1570
+ php: livePhpSnippet,
1571
+ go: liveGoSnippet,
1572
+ java: liveJavaSnippet,
1573
+ ruby: liveRubySnippet,
1574
+ };
1575
+
1576
+ // Renders one modal panel's code - through real Shiki once
1577
+ // wdHighlighter has loaded (see the open-modal click handler above),
1578
+ // so the live preview ends up looking identical to every other
1579
+ // codeblock on the site; until then, plain text keeps it accurate
1580
+ // without blocking on the network. codeToHtml() on an already-built
1581
+ // highlighter instance is synchronous (all langs/themes are already
1582
+ // loaded into it), so this is cheap enough to call on every
1583
+ // keystroke with no debouncing needed.
1584
+ function renderModalPanel(panel: HTMLElement, code: string) {
1585
+ if (!wdHighlighter) {
1586
+ const codeEl = panel.querySelector('code');
1587
+ if (codeEl) codeEl.textContent = code;
1588
+ return;
1589
+ }
1590
+ const shikiLang = MODAL_LANG_TO_SHIKI[panel.dataset.modalLangPanel ?? ''] ?? 'plaintext';
1591
+ const html = wdHighlighter.codeToHtml(code, { lang: shikiLang, themes });
1592
+ const template = document.createElement('template');
1593
+ template.innerHTML = html.trim();
1594
+ const rendered = template.content.firstElementChild as HTMLElement | null;
1595
+ if (!rendered) return;
1596
+ // Shiki's own output owns class/style (background, --shiki-dark-*
1597
+ // vars, etc. - same as the sidebar's <Code/> panels, see
1598
+ // ApiReferencePanel's CSS) but display: block/none is this
1599
+ // panel's own toggle state (driven by modalLangSelect above), not
1600
+ // something Shiki knows about - preserved across the swap rather
1601
+ // than clobbered by it.
1602
+ const currentDisplay = panel.style.display;
1603
+ panel.setAttribute('style', rendered.getAttribute('style') ?? '');
1604
+ panel.style.display = currentDisplay;
1605
+ panel.className = `${rendered.className} wd-api-pre astro-code`.trim();
1606
+ panel.innerHTML = rendered.innerHTML;
1607
+ }
1608
+
1609
+ function updateModalPreview() {
1610
+ if (modalLangPanels.length === 0) return;
1611
+ const state = collectLiveRequest();
1612
+ modalLangPanels.forEach((panel) => {
1613
+ const build = LIVE_SNIPPET_BUILDERS[panel.dataset.modalLangPanel ?? ''];
1614
+ if (build) renderModalPanel(panel, build(state));
1615
+ });
1616
+ }
1617
+ refreshModalPreview = updateModalPreview;
1618
+
1619
+ // Only a <select> fires a meaningful change here - the static
1620
+ // <span> case has nothing for the reader to alter, so there's no
1621
+ // listener to attach for it (getBaseUrl() above still reads its
1622
+ // fixed data-value on every other input's own 'input' event).
1623
+ if (baseUrlEl instanceof HTMLSelectElement) {
1624
+ baseUrlEl.addEventListener('change', updateModalPreview);
1625
+ }
1626
+ paramInputs.forEach((input) => input.addEventListener('input', updateModalPreview));
1627
+ authInputs.forEach((input) => input.addEventListener('input', updateModalPreview));
1628
+ bodyInput?.addEventListener('input', updateModalPreview);
1629
+ updateModalPreview();
1630
+
1631
+ // Examples select (only rendered when the spec's request body
1632
+ // carries a named `examples` map - see requestExampleEntries in
1633
+ // the frontmatter). Selecting one only ever touches the Body
1634
+ // field: OpenAPI's `examples` keyword lives on the request body's
1635
+ // media-type object, with no standard link to path/query/header
1636
+ // parameter values, so there's nothing else to populate from it.
1637
+ // "Default" (value="") is its own real option, not a no-op
1638
+ // placeholder - picking it resets the Body to blankRequestExample
1639
+ // (see the frontmatter's emptyValueFromSchema call), the same
1640
+ // field shape as a named example but with every value left empty,
1641
+ // so the reader still sees what the body needs instead of losing
1642
+ // the shape to a blank textarea.
1643
+ const exampleSelect = section.parentElement?.querySelector<HTMLSelectElement>('[data-role="example-select"]');
1644
+ const blankBody = section.dataset.blankBody ?? '';
1645
+ let examples: Record<string, { summary?: string; description?: string; value?: unknown }> = {};
1646
+ try {
1647
+ examples = JSON.parse(section.dataset.examples ?? '{}');
1648
+ } catch {
1649
+ // malformed/absent - examples select just won't populate anything
1650
+ }
1651
+ exampleSelect?.addEventListener('change', () => {
1652
+ if (!bodyInput) return;
1653
+ const chosen = examples[exampleSelect.value];
1654
+ bodyInput.value = chosen ? JSON.stringify(chosen.value, null, 2) : blankBody;
1655
+ updateModalPreview();
1656
+ });
1657
+ // Once the reader edits the body by hand, it no longer matches
1658
+ // whichever example (if any) is still shown selected - reset the
1659
+ // select back to "Default" so it doesn't keep claiming a match
1660
+ // that's now stale. Only fires on direct typing into the
1661
+ // textarea, not on the programmatic set above (that dispatches no
1662
+ // 'input' event), so picking an example doesn't immediately
1663
+ // un-pick itself.
1664
+ bodyInput?.addEventListener('input', () => {
1665
+ if (exampleSelect) exampleSelect.value = '';
1666
+ });
1667
+
1668
+ sendBtn?.addEventListener('click', async () => {
1669
+ if (!responseStatusEl || !responseBodyEl) return;
1670
+ const baseUrl = getBaseUrl().replace(/\/$/, '');
1671
+ if (!baseUrl) {
1672
+ responseStatusEl.textContent = 'No base URL is configured for this operation.';
1673
+ responseStatusEl.className = 'wd-api-response-status wd-api-status-error';
1674
+ responseBodyEl.textContent = '';
1675
+ return;
1676
+ }
1677
+
1678
+ let requestPath = opPath;
1679
+ const query = new URLSearchParams();
1680
+ for (const input of paramInputs) {
1681
+ const name = input.dataset.paramName ?? '';
1682
+ const paramIn = input.dataset.paramIn;
1683
+ const value = input.value;
1684
+ if (paramIn === 'path') {
1685
+ requestPath = requestPath.replace(`{${name}}`, encodeURIComponent(value));
1686
+ } else if (paramIn === 'query' && value) {
1687
+ query.set(name, value);
1688
+ }
1689
+ }
1690
+
1691
+ const headers: Record<string, string> = {};
1692
+ for (const input of paramInputs) {
1693
+ if (input.dataset.paramIn === 'header' && input.value) {
1694
+ headers[input.dataset.paramName ?? ''] = input.value;
1695
+ }
1696
+ }
1697
+ for (const input of authInputs) {
1698
+ const type = input.dataset.authType;
1699
+ const scheme = input.dataset.authScheme;
1700
+ const authIn = input.dataset.authIn;
1701
+ const value = input.value;
1702
+ if (!value) continue;
1703
+ if (type === 'apiKey' && authIn === 'header') {
1704
+ headers[input.dataset.authName ?? ''] = value;
1705
+ } else if (type === 'apiKey' && authIn === 'query') {
1706
+ query.set(input.dataset.authName ?? '', value);
1707
+ } else if (type === 'http' && scheme === 'bearer') {
1708
+ headers['Authorization'] = `Bearer ${value}`;
1709
+ } else if (type === 'http' && scheme === 'basic') {
1710
+ headers['Authorization'] = `Basic ${btoa(value)}`;
1711
+ }
1712
+ }
1713
+
1714
+ let body: string | undefined;
1715
+ if (bodyInput && bodyInput.value.trim()) {
1716
+ try {
1717
+ body = JSON.stringify(JSON.parse(bodyInput.value));
1718
+ headers['Content-Type'] = headers['Content-Type'] ?? 'application/json';
1719
+ } catch {
1720
+ responseStatusEl.textContent = 'Request body is not valid JSON.';
1721
+ responseStatusEl.className = 'wd-api-response-status wd-api-status-error';
1722
+ responseBodyEl.textContent = '';
1723
+ return;
1724
+ }
1725
+ }
1726
+
1727
+ const targetUrl = baseUrl + requestPath + (query.toString() ? `?${query.toString()}` : '');
1728
+ // A "simple" request (CORS spec: GET/HEAD/POST, no JSON body, no
1729
+ // auth or custom headers) skips the preflight, so the server may
1730
+ // already have run it when the browser blocks the response.
1731
+ // Retrying one that changes something (a POST) through the proxy
1732
+ // could run it twice - so that one case isn't retried.
1733
+ const isSimple = ['GET', 'HEAD', 'POST'].includes(method) && Object.keys(headers).length === 0;
1734
+ const mayHaveRun = isSimple && method === 'POST';
1735
+
1736
+ if (sendBtn) {
1737
+ sendBtn.disabled = true;
1738
+ sendBtn.textContent = 'Sending...';
1739
+ }
1740
+ responseStatusEl.textContent = 'Sending request...';
1741
+ responseStatusEl.className = 'wd-api-response-status';
1742
+ responseBodyEl.textContent = '';
1743
+
1744
+ const startedAt = performance.now();
1745
+ let viaProxy = false;
1746
+ try {
1747
+ // Straight to the API first, so a reader's key and body only reach
1748
+ // the API itself. fetch() rejects when the browser blocks the
1749
+ // response (CORS) or can't reach the host - only then, and only
1750
+ // when writedocs.json's `api.proxy` allows it, the same request is
1751
+ // retried through writedocs' proxy (PROXY_BASE_URL above), and the
1752
+ // status line says so.
1753
+ let res: Response;
1754
+ try {
1755
+ res = await fetch(targetUrl, { method, headers, body });
1756
+ } catch (directErr) {
1757
+ if (!proxyEnabled || mayHaveRun) throw directErr;
1758
+ viaProxy = true;
1759
+ responseStatusEl.textContent = 'Blocked by the browser (CORS) - retrying through the writedocs proxy...';
1760
+ res = await fetch(`${PROXY_BASE_URL}${targetUrl}`, { method, headers, body });
1761
+ }
1762
+ const elapsed = Math.round(performance.now() - startedAt);
1763
+ const text = await res.text();
1764
+ let pretty = text;
1765
+ try {
1766
+ pretty = JSON.stringify(JSON.parse(text), null, 2);
1767
+ } catch {
1768
+ // not JSON - show raw text as-is
1769
+ }
1770
+ responseStatusEl.textContent = `${res.status} ${res.statusText} - ${elapsed}ms${viaProxy ? ' - sent through the writedocs proxy (the API blocks direct browser requests)' : ''}`;
1771
+ responseStatusEl.className = `wd-api-response-status ${res.ok ? 'wd-api-status-ok' : 'wd-api-status-error'}`;
1772
+ responseBodyEl.textContent = pretty;
1773
+ } catch (err) {
1774
+ responseStatusEl.textContent = viaProxy
1775
+ ? 'Request failed through the writedocs proxy too - the base URL may be unreachable from the internet.'
1776
+ : mayHaveRun && proxyEnabled
1777
+ ? 'Blocked by the browser (CORS). Not retried through the proxy: this POST may already have reached the API.'
1778
+ : 'Request failed - likely blocked by CORS, or the base URL is unreachable from your browser.';
1779
+ responseStatusEl.className = 'wd-api-response-status wd-api-status-error';
1780
+ responseBodyEl.textContent = err instanceof Error ? err.message : String(err);
1781
+ } finally {
1782
+ if (sendBtn) {
1783
+ sendBtn.disabled = false;
1784
+ sendBtn.innerHTML = 'Send <span aria-hidden="true">&#9656;</span>';
1785
+ }
1786
+ }
1787
+ });
1788
+ });
1789
+ }
1790
+ initApiPanel(document);
1791
+ document.addEventListener('astro:page-load', () => initApiPanel(document));
1792
+ </script>