pi-lean-host 0.4.0 → 0.5.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.
- package/README.md +194 -557
- package/core/api-guide-types.ts +250 -47
- package/core/api-toggle.ts +244 -39
- package/core/auth.ts +996 -76
- package/core/delete-command.ts +1 -1
- package/core/fs-0600.ts +39 -0
- package/core/guide-catalog.ts +349 -0
- package/core/guide-picker.ts +76 -61
- package/core/guide-store.ts +2 -2
- package/core/helpers.ts +529 -142
- package/core/local-helpers.ts +7 -0
- package/core/oauth-command.ts +911 -0
- package/core/oauth-flow.ts +376 -0
- package/core/oauth-store.ts +306 -0
- package/core/parse-api-guide.ts +1122 -591
- package/core/path-template.ts +101 -0
- package/core/portal-projection.ts +3 -4
- package/core/resolve-op.ts +113 -67
- package/core/response-spill.ts +10 -7
- package/core/secrets-command.ts +18 -13
- package/core/secrets-store.ts +11 -44
- package/core/select-picker.ts +171 -0
- package/core/staging.ts +29 -0
- package/core/transport.ts +321 -34
- package/core/verify-command.ts +93 -65
- package/docs/migration-v1.md +56 -0
- package/index.ts +12 -10
- package/package.json +16 -6
- package/tools/api-fetch.ts +45 -18
- package/tools/api-guide.ts +20 -11
- package/tools/api-learn.ts +131 -57
- package/tools/api-probe.ts +455 -282
- package/tools/api-scaffold.ts +15 -22
- package/tools/api-store.ts +381 -0
- package/tools/oauth-mint.ts +338 -0
- package/tools/utils.ts +1 -1
- package/core/verify-ship-manifest.ts +0 -118
- package/tools/index.ts +0 -8
package/core/parse-api-guide.ts
CHANGED
|
@@ -9,10 +9,12 @@
|
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { parse as yamlParse } from "yaml";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
12
|
+
import { fileURLToPath } from "node:url";
|
|
13
|
+
import {
|
|
14
|
+
extractPathTokens,
|
|
15
|
+
tokenizeJsonPath,
|
|
16
|
+
wireParamName,
|
|
17
|
+
} from "./path-template.js";
|
|
16
18
|
import {
|
|
17
19
|
GATHER_ALL_MAX_FALLBACK,
|
|
18
20
|
GUIDE_SCHEMA_VERSION,
|
|
@@ -30,11 +32,21 @@ import {
|
|
|
30
32
|
type ResponseCharset,
|
|
31
33
|
type AuthConfig,
|
|
32
34
|
type AuthKind,
|
|
35
|
+
type SecretRef,
|
|
36
|
+
type StaticKeyAuth,
|
|
37
|
+
type OAuth2Auth,
|
|
38
|
+
type OAuth2ParamStyle,
|
|
39
|
+
type OAuth2TokenEndpointAuthMethod,
|
|
40
|
+
isOAuth2Grant,
|
|
41
|
+
isOAuth2TokenEndpointAuthMethod,
|
|
42
|
+
isListStyle,
|
|
43
|
+
LIST_STYLES,
|
|
44
|
+
oauth2GrantIssue,
|
|
45
|
+
OAUTH2_GRANTS,
|
|
46
|
+
OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS,
|
|
33
47
|
type ExecutorVia,
|
|
34
48
|
type AcceptType,
|
|
35
49
|
type QueryParamSpec,
|
|
36
|
-
type LoadedApiGuides,
|
|
37
|
-
type NotifyFn,
|
|
38
50
|
} from "./api-guide-types.js";
|
|
39
51
|
|
|
40
52
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -63,8 +75,7 @@ export function stampFrontmatterField(
|
|
|
63
75
|
const content = match[2] ?? "";
|
|
64
76
|
const nl = /^---(\r?\n)/.exec(raw)?.[1] ?? "\n";
|
|
65
77
|
const lines = fm.split(nl);
|
|
66
|
-
const
|
|
67
|
-
const idx = lines.findIndex((l) => keyRe.test(l));
|
|
78
|
+
const idx = lines.findIndex((l) => l.startsWith(`${key}:`));
|
|
68
79
|
const line = `${key}: ${value}`;
|
|
69
80
|
if (idx === -1) {
|
|
70
81
|
// Insert-only separation: a new key would land flush against the
|
|
@@ -82,6 +93,17 @@ export function stampFrontmatterField(
|
|
|
82
93
|
}
|
|
83
94
|
|
|
84
95
|
const VALID_VIA: ReadonlySet<string> = new Set(["restGet", "paginate"]);
|
|
96
|
+
// Closed param-spec key allowlist — the unknown-key tripwire rejects
|
|
97
|
+
// anything else (typo'd `listStyl:` / `requried:` must not silently no-op).
|
|
98
|
+
// Exported for the allowlist↔parser tripwire in
|
|
99
|
+
// __tests__/parse-api-guide.test.ts (same two-direction shape as
|
|
100
|
+
// AUTH_ALLOWLISTS / PAGINATION_ALLOWLISTS).
|
|
101
|
+
export const PARAM_SPEC_KEYS: ReadonlySet<string> = new Set([
|
|
102
|
+
"required",
|
|
103
|
+
"default",
|
|
104
|
+
"description",
|
|
105
|
+
"listStyle",
|
|
106
|
+
]);
|
|
85
107
|
// accept is a free-form string — any media type is valid (`json`/`xml`
|
|
86
108
|
// shorthands are mapped by the helper).
|
|
87
109
|
const VALID_FORMAT: ReadonlySet<string> = new Set(["json", "xml", "text"]);
|
|
@@ -99,27 +121,169 @@ const VALID_PAGINATION_STYLE: ReadonlySet<string> = new Set([
|
|
|
99
121
|
"tokenBag",
|
|
100
122
|
]);
|
|
101
123
|
|
|
102
|
-
//
|
|
103
|
-
//
|
|
104
|
-
//
|
|
105
|
-
//
|
|
106
|
-
|
|
124
|
+
// Per-variant auth field allowlists — each kind rejects fields not legal for
|
|
125
|
+
// it (stricter than the old single global set: a `tokenUrl` on a static-key
|
|
126
|
+
// block or a `headerPrefixes` on an oauth2 block now fails at parse). The old
|
|
127
|
+
// `none`-kind field-presence check is subsumed by the NoneAuth allowlist.
|
|
128
|
+
// Exported for the allowlist↔parser tripwire in __tests__/parse-api-guide.test.ts
|
|
129
|
+
// (same two-direction shape as PAGINATION_ALLOWLISTS).
|
|
130
|
+
export const AUTH_ALLOWLISTS: Record<AuthKind, ReadonlySet<string>> = {
|
|
131
|
+
none: new Set(["kind", "headers"]),
|
|
132
|
+
"static-key": new Set([
|
|
133
|
+
"kind",
|
|
134
|
+
"headers",
|
|
135
|
+
"secretRefs",
|
|
136
|
+
"secretQueryRefs",
|
|
137
|
+
"secretPathRefs",
|
|
138
|
+
]),
|
|
139
|
+
oauth2: new Set([
|
|
140
|
+
"kind",
|
|
141
|
+
"grant",
|
|
142
|
+
"tokenUrl",
|
|
143
|
+
"clientId",
|
|
144
|
+
"clientSecret",
|
|
145
|
+
"secretRefs",
|
|
146
|
+
"scopes",
|
|
147
|
+
"paramStyle",
|
|
148
|
+
"tokenEndpointAuthMethod",
|
|
149
|
+
"authorizeUrl",
|
|
150
|
+
"revokeUrl",
|
|
151
|
+
]),
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
// Per-style pagination field allowlists — same pattern as AUTH_ALLOWLISTS:
|
|
155
|
+
// each style rejects keys not legal for it, so a typo (`itemPath:`) or a
|
|
156
|
+
// wrong-style key (`cursorPath:` on a nextLink block) fails at parse instead
|
|
157
|
+
// of silently single-paging at runtime.
|
|
158
|
+
// Post-landing note: any schema change touching pagination fields updates
|
|
159
|
+
// these allowlists in the same commit — every future optional pagination
|
|
160
|
+
// field must be added to its style's set here (the allowlist↔parser tripwire
|
|
161
|
+
// in __tests__/parse-api-guide.test.ts enforces the parser side mechanically).
|
|
162
|
+
export const PAGINATION_ALLOWLISTS: Record<
|
|
163
|
+
PaginationStyle,
|
|
164
|
+
ReadonlySet<string>
|
|
165
|
+
> = {
|
|
166
|
+
"offset-limit": new Set([
|
|
167
|
+
"style",
|
|
168
|
+
"itemsPath",
|
|
169
|
+
"pageParam",
|
|
170
|
+
"pageSizeParam",
|
|
171
|
+
"pageSize",
|
|
172
|
+
"base",
|
|
173
|
+
"totalCountPath",
|
|
174
|
+
"hasMorePath",
|
|
175
|
+
]),
|
|
176
|
+
page: new Set([
|
|
177
|
+
"style",
|
|
178
|
+
"itemsPath",
|
|
179
|
+
"pageParam",
|
|
180
|
+
"pageSizeParam",
|
|
181
|
+
"pageSize",
|
|
182
|
+
"base",
|
|
183
|
+
"totalCountPath",
|
|
184
|
+
"hasMorePath",
|
|
185
|
+
]),
|
|
186
|
+
nextLink: new Set([
|
|
187
|
+
"style",
|
|
188
|
+
"itemsPath",
|
|
189
|
+
"nextLinkPath",
|
|
190
|
+
"totalCountPath",
|
|
191
|
+
"hasMorePath",
|
|
192
|
+
]),
|
|
193
|
+
cursor: new Set([
|
|
194
|
+
"style",
|
|
195
|
+
"itemsPath",
|
|
196
|
+
"cursorParam",
|
|
197
|
+
"cursorPath",
|
|
198
|
+
"pageSizeParam",
|
|
199
|
+
"pageSize",
|
|
200
|
+
"totalCountPath",
|
|
201
|
+
"hasMorePath",
|
|
202
|
+
]),
|
|
203
|
+
resumptionToken: new Set([
|
|
204
|
+
"style",
|
|
205
|
+
"itemsPath",
|
|
206
|
+
"tokenParam",
|
|
207
|
+
"tokenPath",
|
|
208
|
+
"totalCountPath",
|
|
209
|
+
"hasMorePath",
|
|
210
|
+
]),
|
|
211
|
+
tokenBag: new Set([
|
|
212
|
+
"style",
|
|
213
|
+
"itemsPath",
|
|
214
|
+
"continuationParams",
|
|
215
|
+
"totalCountPath",
|
|
216
|
+
"hasMorePath",
|
|
217
|
+
]),
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
// Op-block key allowlist — the closed-schema pass's largest surface. An
|
|
221
|
+
// unknown op key (`errorPaths:` instead of `errorPath:`) used to parse clean
|
|
222
|
+
// and silently no-op the intended behavior — worst case, a typo'd error
|
|
223
|
+
// envelope never fires. Exported for the allowlist↔parser tripwire in
|
|
224
|
+
// __tests__/parse-api-guide.test.ts (same two-direction shape as
|
|
225
|
+
// PAGINATION_ALLOWLISTS). Not `pathParamDocs` — that's a parser-derived
|
|
226
|
+
// OUTPUT field built from params.<token>.description, never authored.
|
|
227
|
+
export const OP_ALLOWLIST: ReadonlySet<string> = new Set([
|
|
228
|
+
"name",
|
|
229
|
+
"via",
|
|
230
|
+
"path",
|
|
231
|
+
"accept",
|
|
232
|
+
"params",
|
|
233
|
+
"requiresAnyOf",
|
|
234
|
+
"dateParams",
|
|
235
|
+
"helper",
|
|
236
|
+
"transform",
|
|
237
|
+
"passthrough",
|
|
238
|
+
"parse",
|
|
239
|
+
"errorPath",
|
|
240
|
+
"pagination",
|
|
241
|
+
"gatherAllMax",
|
|
242
|
+
]);
|
|
243
|
+
|
|
244
|
+
// responseShape block allowlist — same closed-schema pass, same philosophy:
|
|
245
|
+
// only `format` and `charset` are read; anything else is a typo.
|
|
246
|
+
// Exported for the allowlist↔parser tripwire in
|
|
247
|
+
// __tests__/parse-api-guide.test.ts.
|
|
248
|
+
export const RESPONSE_SHAPE_ALLOWLIST: ReadonlySet<string> = new Set([
|
|
249
|
+
"format",
|
|
250
|
+
"charset",
|
|
251
|
+
]);
|
|
252
|
+
|
|
253
|
+
// Guide-frontmatter key allowlist — the closed-schema pass's third surface.
|
|
254
|
+
// Exactly the 16 keys parseApiGuide reads from the parsed YAML mapping: the
|
|
255
|
+
// 15 literal m["…"] sites plus `domains` (read via requireStringArray).
|
|
256
|
+
// Deliberately NOT Object.keys(const guide) — that would drag in derived
|
|
257
|
+
// non-authored fields (`content`, `category`, `source`). Exported for the
|
|
258
|
+
// allowlist↔parser tripwire in __tests__/parse-api-guide.test.ts.
|
|
259
|
+
export const GUIDE_ALLOWLIST: ReadonlySet<string> = new Set([
|
|
107
260
|
"kind",
|
|
108
|
-
"
|
|
109
|
-
"
|
|
110
|
-
"
|
|
111
|
-
"
|
|
112
|
-
"
|
|
113
|
-
"
|
|
261
|
+
"domains",
|
|
262
|
+
"shortName",
|
|
263
|
+
"updated",
|
|
264
|
+
"icon",
|
|
265
|
+
"apiHost",
|
|
266
|
+
"verified",
|
|
267
|
+
"docs",
|
|
268
|
+
"organization",
|
|
269
|
+
"description",
|
|
270
|
+
"schemaVersion",
|
|
271
|
+
"gatherAllMax",
|
|
272
|
+
"auth",
|
|
273
|
+
"responseShape",
|
|
274
|
+
"operations",
|
|
275
|
+
"pagination",
|
|
114
276
|
]);
|
|
115
|
-
// Set insertion order — used to render the known-key list in error strings
|
|
116
|
-
// (expected + fallback fix) so they can't drift from the set.
|
|
117
|
-
const KNOWN_AUTH_KEYS_LIST = [...KNOWN_AUTH_KEYS].join(", ");
|
|
118
277
|
|
|
119
278
|
// ═══════════════════════════════════════════════════════════════════
|
|
120
279
|
// Error helper
|
|
121
280
|
// ═══════════════════════════════════════════════════════════════════
|
|
122
281
|
|
|
282
|
+
// The migration doc for the current schema bump, resolved from this module's
|
|
283
|
+
// own location so no hardcoded install path is ever rendered — the doc ships
|
|
284
|
+
// in the npm tarball (enforced by ship-manifest.test.ts).
|
|
285
|
+
const MIGRATION_DOC_NOTE = `See the migration guide for this schema bump: ${fileURLToPath(new URL("../docs/migration-v1.md", import.meta.url))}.`;
|
|
286
|
+
|
|
123
287
|
function fail(
|
|
124
288
|
file: string | undefined,
|
|
125
289
|
field: string,
|
|
@@ -348,6 +512,21 @@ function validatePagination(
|
|
|
348
512
|
}
|
|
349
513
|
const style = styleRaw as PaginationStyle;
|
|
350
514
|
|
|
515
|
+
// Per-style allowlist — reject keys not legal for this style (a typo like
|
|
516
|
+
// `itemPath:` or a `cursorPath:` on a nextLink block fails here instead of
|
|
517
|
+
// silently single-paging at runtime). Format mirrors AUTH_ALLOWLISTS.
|
|
518
|
+
const allowlist = PAGINATION_ALLOWLISTS[style];
|
|
519
|
+
const unknownKeys = Object.keys(p).filter((k) => !allowlist.has(k));
|
|
520
|
+
if (unknownKeys.length > 0) {
|
|
521
|
+
const first = unknownKeys[0]!; // guarded by the length check above
|
|
522
|
+
return fail(
|
|
523
|
+
file,
|
|
524
|
+
`${fieldPrefix}.${first}`,
|
|
525
|
+
`a known pagination key for style: ${style} (${[...allowlist].join(", ")})`,
|
|
526
|
+
`unknown key(s): ${unknownKeys.join(", ")}`,
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
|
|
351
530
|
const itemsPath = p["itemsPath"];
|
|
352
531
|
if (typeof itemsPath !== "string" || itemsPath === "") {
|
|
353
532
|
return fail(
|
|
@@ -422,6 +601,41 @@ function validatePagination(
|
|
|
422
601
|
}
|
|
423
602
|
Object.assign(cfg, { [req]: v });
|
|
424
603
|
}
|
|
604
|
+
// Optional, validated-if-present (both were silently dropped before).
|
|
605
|
+
const cPsp = p["pageSizeParam"];
|
|
606
|
+
if (cPsp !== undefined) {
|
|
607
|
+
if (typeof cPsp !== "string" || cPsp === "") {
|
|
608
|
+
return fail(
|
|
609
|
+
file,
|
|
610
|
+
`${fieldPrefix}.pageSizeParam`,
|
|
611
|
+
"a string param name",
|
|
612
|
+
describeFound(cPsp),
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
cfg.pageSizeParam = cPsp;
|
|
616
|
+
}
|
|
617
|
+
const cPs = p["pageSize"];
|
|
618
|
+
if (cPs !== undefined) {
|
|
619
|
+
if (typeof cPs !== "number" || !Number.isFinite(cPs) || cPs <= 0) {
|
|
620
|
+
return fail(
|
|
621
|
+
file,
|
|
622
|
+
`${fieldPrefix}.pageSize`,
|
|
623
|
+
"a positive number",
|
|
624
|
+
describeFound(cPs),
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
cfg.pageSize = cPs;
|
|
628
|
+
}
|
|
629
|
+
// pageSize without pageSizeParam is inert (the executor seeds only
|
|
630
|
+
// when both are present) — reject rather than silently no-op.
|
|
631
|
+
if (cPs !== undefined && cPsp === undefined) {
|
|
632
|
+
return fail(
|
|
633
|
+
file,
|
|
634
|
+
`${fieldPrefix}.pageSize`,
|
|
635
|
+
"set alongside pageSizeParam (cursor: the seed only applies with both)",
|
|
636
|
+
describeFound(cPs),
|
|
637
|
+
);
|
|
638
|
+
}
|
|
425
639
|
} else if (style === "resumptionToken") {
|
|
426
640
|
for (const req of ["tokenParam", "tokenPath"] as const) {
|
|
427
641
|
const v = p[req];
|
|
@@ -473,6 +687,21 @@ function validatePagination(
|
|
|
473
687
|
cfg.totalCountPath = tcp;
|
|
474
688
|
}
|
|
475
689
|
|
|
690
|
+
// optional hasMorePath (any style) — JSON path to a boolean/numeric
|
|
691
|
+
// "more pages" flag; a resolved falsy value stops the walk cleanly.
|
|
692
|
+
const hmp = p["hasMorePath"];
|
|
693
|
+
if (hmp !== undefined) {
|
|
694
|
+
if (typeof hmp !== "string" || hmp === "") {
|
|
695
|
+
return fail(
|
|
696
|
+
file,
|
|
697
|
+
`${fieldPrefix}.hasMorePath`,
|
|
698
|
+
"a non-empty string (JSON path to the has-more flag)",
|
|
699
|
+
describeFound(hmp),
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
cfg.hasMorePath = hmp;
|
|
703
|
+
}
|
|
704
|
+
|
|
476
705
|
return cfg;
|
|
477
706
|
}
|
|
478
707
|
|
|
@@ -495,6 +724,25 @@ function validateResponseShape(
|
|
|
495
724
|
}
|
|
496
725
|
const r = raw as Record<string, unknown>;
|
|
497
726
|
|
|
727
|
+
// responseShape allowlist — same closed-schema pass as OP_ALLOWLIST: only
|
|
728
|
+
// format/charset are read, so anything else is a typo that would
|
|
729
|
+
// silently no-op.
|
|
730
|
+
const unknownKeys = Object.keys(r).filter(
|
|
731
|
+
(k) => !RESPONSE_SHAPE_ALLOWLIST.has(k),
|
|
732
|
+
);
|
|
733
|
+
if (unknownKeys.length > 0) {
|
|
734
|
+
const first = unknownKeys[0]!; // guarded by the length check above
|
|
735
|
+
return fail(
|
|
736
|
+
file,
|
|
737
|
+
`${fieldPrefix}.${first}`,
|
|
738
|
+
`a known responseShape key (${[...RESPONSE_SHAPE_ALLOWLIST].join(", ")})`,
|
|
739
|
+
`unknown key(s): ${unknownKeys.join(", ")}`,
|
|
740
|
+
{
|
|
741
|
+
fix: `Remove ${fieldPrefix}.${first} — the responseShape schema is closed.`,
|
|
742
|
+
},
|
|
743
|
+
);
|
|
744
|
+
}
|
|
745
|
+
|
|
498
746
|
const formatRaw = r["format"];
|
|
499
747
|
let format: ResponseFormat = "json";
|
|
500
748
|
if (formatRaw !== undefined) {
|
|
@@ -590,7 +838,7 @@ function validateAuth(
|
|
|
590
838
|
"a string",
|
|
591
839
|
kindRaw === undefined ? "missing" : describeFound(kindRaw),
|
|
592
840
|
{
|
|
593
|
-
fix: "kind is one of: none | static-key — use `kind: none` (public)
|
|
841
|
+
fix: "kind is one of: none | static-key | oauth2 — use `kind: none` (public), `kind: static-key` (keyed header), or `kind: oauth2`; or call api-learn({domain, new: true}) for a full skeleton",
|
|
594
842
|
},
|
|
595
843
|
);
|
|
596
844
|
}
|
|
@@ -600,35 +848,175 @@ function validateAuth(
|
|
|
600
848
|
"auth.kind",
|
|
601
849
|
"one of: none | static-key | oauth2",
|
|
602
850
|
kindRaw,
|
|
603
|
-
{
|
|
851
|
+
{
|
|
852
|
+
fix: "Use `kind: none` (public), `kind: static-key` (keyed header), or `kind: oauth2`.",
|
|
853
|
+
},
|
|
604
854
|
);
|
|
605
855
|
}
|
|
606
|
-
|
|
607
|
-
//
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
}
|
|
613
|
-
// Strict auth schema — reject unknown keys. The parser used to
|
|
614
|
-
// silently drop unknown keys (a wrong-but-plausible shape like
|
|
615
|
-
// `name`/`secret` saved a guide the executor then silently couldn't
|
|
616
|
-
// honor). Reject, don't infer: `expected` already lists the known keys
|
|
617
|
-
// and `found` names the offenders — no separate fix needed.
|
|
618
|
-
const unknownKeys = Object.keys(a).filter((k) => !KNOWN_AUTH_KEYS.has(k));
|
|
856
|
+
const kind = kindRaw as AuthKind;
|
|
857
|
+
// Per-variant allowlist — reject keys not legal for this kind (a
|
|
858
|
+
// `tokenUrl` on a static-key block or a `headerPrefixes` on an oauth2
|
|
859
|
+
// block fails here, not silently downstream).
|
|
860
|
+
const allowlist = AUTH_ALLOWLISTS[kind];
|
|
861
|
+
const unknownKeys = Object.keys(a).filter((k) => !allowlist.has(k));
|
|
619
862
|
if (unknownKeys.length > 0) {
|
|
620
863
|
const first = unknownKeys[0]!;
|
|
621
864
|
return fail(
|
|
622
865
|
file,
|
|
623
866
|
`auth.${first}`,
|
|
624
|
-
`a known auth key (${
|
|
867
|
+
`a known auth key for kind: ${kind} (${[...allowlist].join(", ")})`,
|
|
625
868
|
`unknown key(s): ${unknownKeys.join(", ")}`,
|
|
626
869
|
{
|
|
627
870
|
snippet: snippetFor(fm, "auth"),
|
|
628
871
|
},
|
|
629
872
|
);
|
|
630
873
|
}
|
|
631
|
-
|
|
874
|
+
|
|
875
|
+
switch (kind) {
|
|
876
|
+
case "none": {
|
|
877
|
+
let headers: Record<string, string> | undefined;
|
|
878
|
+
if (a["headers"] !== undefined) {
|
|
879
|
+
const hr = parseStringRecord(
|
|
880
|
+
a["headers"],
|
|
881
|
+
file,
|
|
882
|
+
fm,
|
|
883
|
+
"auth.headers",
|
|
884
|
+
"a YAML mapping of string → string",
|
|
885
|
+
);
|
|
886
|
+
if (isParseErr(hr)) return hr;
|
|
887
|
+
headers = hr;
|
|
888
|
+
}
|
|
889
|
+
return { kind: "none", ...(headers === undefined ? {} : { headers }) };
|
|
890
|
+
}
|
|
891
|
+
case "static-key": {
|
|
892
|
+
return validateStaticKeyAuth(a, file, fm);
|
|
893
|
+
}
|
|
894
|
+
case "oauth2": {
|
|
895
|
+
return validateOAuth2Auth(a, file, fm);
|
|
896
|
+
}
|
|
897
|
+
default: {
|
|
898
|
+
const never: never = kind;
|
|
899
|
+
throw new Error(`Unhandled auth kind: ${never}`);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/**
|
|
905
|
+
* Parse a nested `Record<string, SecretRef>` (header/form-field name → ref).
|
|
906
|
+
* Each ref is self-contained: `secret` (store name), optional `prefix`, and
|
|
907
|
+
* optional `optional`. The old three-field consistency checks (ref→declared,
|
|
908
|
+
* declared→ref, prefix→ref) are structurally impossible here — there is no
|
|
909
|
+
* `requires`/`optional` roster to diverge from, and `prefix` lives on the ref
|
|
910
|
+
* it applies to.
|
|
911
|
+
*/
|
|
912
|
+
function parseSecretRefs(
|
|
913
|
+
raw: unknown,
|
|
914
|
+
file: string | undefined,
|
|
915
|
+
fm: string,
|
|
916
|
+
field: string,
|
|
917
|
+
): Record<string, SecretRef> | ParseApiGuideResult {
|
|
918
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
919
|
+
return fail(
|
|
920
|
+
file,
|
|
921
|
+
field,
|
|
922
|
+
"a YAML mapping of name → { secret: <store name>, prefix?, optional? }",
|
|
923
|
+
describeFound(raw),
|
|
924
|
+
{ snippet: snippetFor(fm, "auth") },
|
|
925
|
+
);
|
|
926
|
+
}
|
|
927
|
+
const out: Record<string, SecretRef> = {};
|
|
928
|
+
for (const [name, v] of Object.entries(raw)) {
|
|
929
|
+
const r = parseSecretRefValue(v, file, fm, `${field}.${name}`);
|
|
930
|
+
if (isParseErr(r)) return r;
|
|
931
|
+
out[name] = r;
|
|
932
|
+
}
|
|
933
|
+
return out;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* Parse a single self-contained `SecretRef` value ({ secret, prefix?,
|
|
938
|
+
* optional? }). Used per-entry by `parseSecretRefs` and directly for the
|
|
939
|
+
* oauth2 named `clientId` / `clientSecret` fields.
|
|
940
|
+
*/
|
|
941
|
+
function parseSecretRefValue(
|
|
942
|
+
raw: unknown,
|
|
943
|
+
file: string | undefined,
|
|
944
|
+
fm: string,
|
|
945
|
+
field: string,
|
|
946
|
+
): SecretRef | ParseApiGuideResult {
|
|
947
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
948
|
+
return fail(
|
|
949
|
+
file,
|
|
950
|
+
field,
|
|
951
|
+
"a mapping with secret: <store name>",
|
|
952
|
+
describeFound(raw),
|
|
953
|
+
{ snippet: snippetFor(fm, "auth") },
|
|
954
|
+
);
|
|
955
|
+
}
|
|
956
|
+
const ref = raw as Record<string, unknown>;
|
|
957
|
+
const unknownRefKeys = Object.keys(ref).filter(
|
|
958
|
+
(k) => !["secret", "prefix", "optional"].includes(k),
|
|
959
|
+
);
|
|
960
|
+
if (unknownRefKeys.length > 0) {
|
|
961
|
+
return fail(
|
|
962
|
+
file,
|
|
963
|
+
field,
|
|
964
|
+
"a mapping with only secret/prefix/optional keys",
|
|
965
|
+
`unknown key(s): ${unknownRefKeys.join(", ")}`,
|
|
966
|
+
{ snippet: snippetFor(fm, "auth") },
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
const secret = ref["secret"];
|
|
970
|
+
if (typeof secret !== "string" || secret.length === 0) {
|
|
971
|
+
return fail(
|
|
972
|
+
file,
|
|
973
|
+
`${field}.secret`,
|
|
974
|
+
"a non-empty store name",
|
|
975
|
+
describeFound(secret),
|
|
976
|
+
{ snippet: snippetFor(fm, "auth") },
|
|
977
|
+
);
|
|
978
|
+
}
|
|
979
|
+
let prefix: string | undefined;
|
|
980
|
+
if (ref["prefix"] !== undefined) {
|
|
981
|
+
if (
|
|
982
|
+
typeof ref["prefix"] !== "string" ||
|
|
983
|
+
/^\{[a-zA-Z0-9_]+\}$/.test(ref["prefix"])
|
|
984
|
+
) {
|
|
985
|
+
return fail(
|
|
986
|
+
file,
|
|
987
|
+
`${field}.prefix`,
|
|
988
|
+
"a string prefix (empty allowed; not a bare {placeholder})",
|
|
989
|
+
describeFound(ref["prefix"]),
|
|
990
|
+
{ snippet: snippetFor(fm, "auth") },
|
|
991
|
+
);
|
|
992
|
+
}
|
|
993
|
+
prefix = ref["prefix"];
|
|
994
|
+
}
|
|
995
|
+
let optional: boolean | undefined;
|
|
996
|
+
if (ref["optional"] !== undefined) {
|
|
997
|
+
if (typeof ref["optional"] !== "boolean") {
|
|
998
|
+
return fail(
|
|
999
|
+
file,
|
|
1000
|
+
`${field}.optional`,
|
|
1001
|
+
"a boolean",
|
|
1002
|
+
describeFound(ref["optional"]),
|
|
1003
|
+
{ snippet: snippetFor(fm, "auth") },
|
|
1004
|
+
);
|
|
1005
|
+
}
|
|
1006
|
+
optional = ref["optional"];
|
|
1007
|
+
}
|
|
1008
|
+
return {
|
|
1009
|
+
secret,
|
|
1010
|
+
...(prefix === undefined ? {} : { prefix }),
|
|
1011
|
+
...(optional === undefined ? {} : { optional }),
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
function validateStaticKeyAuth(
|
|
1016
|
+
a: Record<string, unknown>,
|
|
1017
|
+
file: string | undefined,
|
|
1018
|
+
fm: string,
|
|
1019
|
+
): StaticKeyAuth | ParseApiGuideResult {
|
|
632
1020
|
let headers: Record<string, string> | undefined;
|
|
633
1021
|
if (a["headers"] !== undefined) {
|
|
634
1022
|
const hr = parseStringRecord(
|
|
@@ -641,202 +1029,314 @@ function validateAuth(
|
|
|
641
1029
|
if (isParseErr(hr)) return hr;
|
|
642
1030
|
headers = hr;
|
|
643
1031
|
}
|
|
644
|
-
|
|
645
|
-
// static-key reference fields (secretRefs/requires/optional).
|
|
646
|
-
let secretRefs: Record<string, string> | undefined;
|
|
1032
|
+
let secretRefs: Record<string, SecretRef> | undefined;
|
|
647
1033
|
if (a["secretRefs"] !== undefined) {
|
|
648
|
-
const sr =
|
|
649
|
-
a["secretRefs"],
|
|
650
|
-
file,
|
|
651
|
-
fm,
|
|
652
|
-
"auth.secretRefs",
|
|
653
|
-
"a YAML mapping of header name → secret name",
|
|
654
|
-
);
|
|
1034
|
+
const sr = parseSecretRefs(a["secretRefs"], file, fm, "auth.secretRefs");
|
|
655
1035
|
if (isParseErr(sr)) return sr;
|
|
656
1036
|
secretRefs = sr;
|
|
657
1037
|
}
|
|
658
|
-
|
|
659
|
-
// Query-param secrets: maps query param name → secret store name.
|
|
660
|
-
// Same shape + consistency rules as secretRefs; the collision-with-op-`params`
|
|
661
|
-
// rule is enforced in parseApiGuide (auth is parsed before operations).
|
|
662
|
-
let secretQueryRefs: Record<string, string> | undefined;
|
|
1038
|
+
let secretQueryRefs: Record<string, SecretRef> | undefined;
|
|
663
1039
|
if (a["secretQueryRefs"] !== undefined) {
|
|
664
|
-
const qr =
|
|
1040
|
+
const qr = parseSecretRefs(
|
|
665
1041
|
a["secretQueryRefs"],
|
|
666
1042
|
file,
|
|
667
1043
|
fm,
|
|
668
1044
|
"auth.secretQueryRefs",
|
|
669
|
-
"a YAML mapping of query param name → secret name",
|
|
670
1045
|
);
|
|
671
1046
|
if (isParseErr(qr)) return qr;
|
|
672
1047
|
secretQueryRefs = qr;
|
|
673
1048
|
}
|
|
1049
|
+
let secretPathRefs: Record<string, SecretRef> | undefined;
|
|
1050
|
+
if (a["secretPathRefs"] !== undefined) {
|
|
1051
|
+
const pr = parseSecretRefs(
|
|
1052
|
+
a["secretPathRefs"],
|
|
1053
|
+
file,
|
|
1054
|
+
fm,
|
|
1055
|
+
"auth.secretPathRefs",
|
|
1056
|
+
);
|
|
1057
|
+
if (isParseErr(pr)) return pr;
|
|
1058
|
+
// Path-ref entry checks — fail loud, never silently ignore:
|
|
1059
|
+
// - `prefix` is rejected: path injection is the raw value (the store
|
|
1060
|
+
// value fills {name} verbatim).
|
|
1061
|
+
// - `optional` is rejected (presence, not just `true`): path refs are
|
|
1062
|
+
// required-only — an absent token fails closed in fillPathStrict
|
|
1063
|
+
// before any request, so an optional arm is an error-shaped
|
|
1064
|
+
// pseudostate, not a feature.
|
|
1065
|
+
// - a non-\w name is rejected: fillPathTemplate/extractPathTokens
|
|
1066
|
+
// only match {\w+}, so such a name could never fill — reject with
|
|
1067
|
+
// the grammar message instead of a confusing declared-but-unused
|
|
1068
|
+
// typo error downstream.
|
|
1069
|
+
for (const [name, ref] of Object.entries(pr)) {
|
|
1070
|
+
if (!/^\w+$/.test(name)) {
|
|
1071
|
+
return fail(
|
|
1072
|
+
file,
|
|
1073
|
+
`auth.secretPathRefs.${name}`,
|
|
1074
|
+
"a \\w+ path-token name (the {token} grammar matches \\w+ only)",
|
|
1075
|
+
`"${name}"`,
|
|
1076
|
+
{
|
|
1077
|
+
snippet: snippetFor(fm, "auth"),
|
|
1078
|
+
fix: `Rename the ref to an \\w+ name that matches a {token} in some operation's path — e.g. bot_token → {bot_token}.`,
|
|
1079
|
+
},
|
|
1080
|
+
);
|
|
1081
|
+
}
|
|
1082
|
+
if (ref.prefix !== undefined) {
|
|
1083
|
+
return fail(
|
|
1084
|
+
file,
|
|
1085
|
+
`auth.secretPathRefs.${name}.prefix`,
|
|
1086
|
+
"no prefix key — path injection is the raw secret value",
|
|
1087
|
+
`prefix: ${JSON.stringify(ref.prefix)}`,
|
|
1088
|
+
{
|
|
1089
|
+
snippet: snippetFor(fm, "auth"),
|
|
1090
|
+
fix: `Remove prefix from secretPathRefs.${name} — the value fills {${name}} in the path verbatim.`,
|
|
1091
|
+
},
|
|
1092
|
+
);
|
|
1093
|
+
}
|
|
1094
|
+
if (ref.optional !== undefined) {
|
|
1095
|
+
return fail(
|
|
1096
|
+
file,
|
|
1097
|
+
`auth.secretPathRefs.${name}.optional`,
|
|
1098
|
+
"no optional key — path refs are required-only (an absent path token fails closed before the request)",
|
|
1099
|
+
`optional: ${JSON.stringify(ref.optional)}`,
|
|
1100
|
+
{
|
|
1101
|
+
snippet: snippetFor(fm, "auth"),
|
|
1102
|
+
fix: `Remove optional from secretPathRefs.${name} — a path-keyed API has no unauthenticated state.`,
|
|
1103
|
+
},
|
|
1104
|
+
);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
secretPathRefs = pr;
|
|
1108
|
+
}
|
|
1109
|
+
const result: StaticKeyAuth = { kind: "static-key" };
|
|
1110
|
+
if (headers !== undefined) result.headers = headers;
|
|
1111
|
+
if (secretRefs !== undefined) result.secretRefs = secretRefs;
|
|
1112
|
+
if (secretQueryRefs !== undefined) result.secretQueryRefs = secretQueryRefs;
|
|
1113
|
+
if (secretPathRefs !== undefined) result.secretPathRefs = secretPathRefs;
|
|
1114
|
+
return result;
|
|
1115
|
+
}
|
|
674
1116
|
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
1117
|
+
function validateOAuth2Auth(
|
|
1118
|
+
a: Record<string, unknown>,
|
|
1119
|
+
file: string | undefined,
|
|
1120
|
+
fm: string,
|
|
1121
|
+
): OAuth2Auth | ParseApiGuideResult {
|
|
1122
|
+
const grant = a["grant"];
|
|
1123
|
+
if (!isOAuth2Grant(grant)) {
|
|
1124
|
+
return fail(
|
|
1125
|
+
file,
|
|
1126
|
+
"auth.grant",
|
|
1127
|
+
OAUTH2_GRANTS.join(" | "),
|
|
1128
|
+
describeFound(grant),
|
|
1129
|
+
{
|
|
1130
|
+
fix: "grant: client_credentials (server-to-server, no browser) or grant: authorization_code (interactive, PKCE).",
|
|
1131
|
+
},
|
|
1132
|
+
);
|
|
1133
|
+
}
|
|
1134
|
+
const tokenUrl = requireHttpUrl(a["tokenUrl"], "auth.tokenUrl", file, fm, {
|
|
1135
|
+
protocolFix: "Use https:// as the scheme",
|
|
1136
|
+
invalidFix: "Include the scheme, e.g. https://api.example.com/oauth/token",
|
|
1137
|
+
});
|
|
1138
|
+
if (typeof tokenUrl !== "string") return tokenUrl;
|
|
1139
|
+
if (a["clientId"] === undefined) {
|
|
1140
|
+
return fail(
|
|
1141
|
+
file,
|
|
1142
|
+
"auth.clientId",
|
|
1143
|
+
"a secret ref ({ secret: <store name> })",
|
|
1144
|
+
"missing",
|
|
1145
|
+
{
|
|
1146
|
+
snippet: snippetFor(fm, "auth"),
|
|
1147
|
+
fix: "Add clientId: { secret: client_id } — the store name provisioned via /api secrets <domain>. A shippable guide must not bake in one app's client id.",
|
|
1148
|
+
},
|
|
1149
|
+
);
|
|
1150
|
+
}
|
|
1151
|
+
const clientId = parseSecretRefValue(a["clientId"], file, fm, "auth.clientId");
|
|
1152
|
+
if (isParseErr(clientId)) return clientId;
|
|
1153
|
+
if (clientId.prefix !== undefined || clientId.optional !== undefined) {
|
|
1154
|
+
return fail(
|
|
1155
|
+
file,
|
|
1156
|
+
"auth.clientId",
|
|
1157
|
+
"a ref with only { secret } — prefix/optional are meaningless on the client id (it is always required and always used verbatim)",
|
|
1158
|
+
JSON.stringify(clientId),
|
|
1159
|
+
{
|
|
1160
|
+
snippet: snippetFor(fm, "auth"),
|
|
1161
|
+
fix: "Remove prefix/optional from clientId — keep clientId: { secret: <store name> }.",
|
|
1162
|
+
},
|
|
1163
|
+
);
|
|
1164
|
+
}
|
|
1165
|
+
let clientSecret: SecretRef | undefined;
|
|
1166
|
+
if (a["clientSecret"] !== undefined) {
|
|
1167
|
+
const cs = parseSecretRefValue(
|
|
1168
|
+
a["clientSecret"],
|
|
1169
|
+
file,
|
|
1170
|
+
fm,
|
|
1171
|
+
"auth.clientSecret",
|
|
1172
|
+
);
|
|
1173
|
+
if (isParseErr(cs)) return cs;
|
|
1174
|
+
if (cs.prefix !== undefined) {
|
|
683
1175
|
return fail(
|
|
684
1176
|
file,
|
|
685
|
-
"auth.
|
|
686
|
-
"
|
|
687
|
-
|
|
688
|
-
{
|
|
1177
|
+
"auth.clientSecret.prefix",
|
|
1178
|
+
"absent — the prefix would be silently ignored (the raw store value is sent as the client secret)",
|
|
1179
|
+
JSON.stringify(cs.prefix),
|
|
1180
|
+
{
|
|
1181
|
+
snippet: snippetFor(fm, "auth"),
|
|
1182
|
+
fix: "Remove prefix from clientSecret — keep clientSecret: { secret: <store name> }.",
|
|
1183
|
+
},
|
|
689
1184
|
);
|
|
690
1185
|
}
|
|
691
|
-
|
|
1186
|
+
if (cs.optional !== undefined && grant === "client_credentials") {
|
|
1187
|
+
return fail(
|
|
1188
|
+
file,
|
|
1189
|
+
"auth.clientSecret.optional",
|
|
1190
|
+
"absent for grant: client_credentials (clientSecret is parser-required there; optional can never fire)",
|
|
1191
|
+
"optional: true",
|
|
1192
|
+
{
|
|
1193
|
+
snippet: snippetFor(fm, "auth"),
|
|
1194
|
+
fix: "Remove optional from clientSecret — keep clientSecret: { secret: <store name> }.",
|
|
1195
|
+
},
|
|
1196
|
+
);
|
|
1197
|
+
}
|
|
1198
|
+
clientSecret = cs;
|
|
692
1199
|
}
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
1200
|
+
let secretRefs: Record<string, SecretRef> | undefined;
|
|
1201
|
+
if (a["secretRefs"] !== undefined) {
|
|
1202
|
+
const sr = parseSecretRefs(a["secretRefs"], file, fm, "auth.secretRefs");
|
|
1203
|
+
if (isParseErr(sr)) return sr;
|
|
1204
|
+
secretRefs = sr;
|
|
1205
|
+
}
|
|
1206
|
+
let scopes: string[] | undefined;
|
|
1207
|
+
if (a["scopes"] !== undefined) {
|
|
697
1208
|
if (
|
|
698
|
-
!Array.isArray(
|
|
699
|
-
|
|
700
|
-
optRaw.some((v) => typeof v !== "string")
|
|
1209
|
+
!Array.isArray(a["scopes"]) ||
|
|
1210
|
+
a["scopes"].some((s) => typeof s !== "string")
|
|
701
1211
|
) {
|
|
702
1212
|
return fail(
|
|
703
1213
|
file,
|
|
704
|
-
"auth.
|
|
705
|
-
"a
|
|
706
|
-
describeFound(
|
|
1214
|
+
"auth.scopes",
|
|
1215
|
+
"a list of scope strings",
|
|
1216
|
+
describeFound(a["scopes"]),
|
|
707
1217
|
{ snippet: snippetFor(fm, "auth") },
|
|
708
1218
|
);
|
|
709
1219
|
}
|
|
710
|
-
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
// static-key header prefixes: header name → prefix string prepended to the
|
|
714
|
-
// resolved secret value (empty allowed — a bare-key header like CMC's
|
|
715
|
-
// X-CMC_PRO_API_KEY has no scheme). Same mapping shape as secretRefs; every
|
|
716
|
-
// key must also be a secretRefs header (a prefix for a non-secret header is
|
|
717
|
-
// a mistake).
|
|
718
|
-
let headerPrefixes: Record<string, string> | undefined;
|
|
719
|
-
if (a["headerPrefixes"] !== undefined) {
|
|
720
|
-
const hp = parseStringRecord(
|
|
721
|
-
a["headerPrefixes"],
|
|
722
|
-
file,
|
|
723
|
-
fm,
|
|
724
|
-
"auth.headerPrefixes",
|
|
725
|
-
"a YAML mapping of header name → prefix string (empty allowed for bare-key headers)",
|
|
726
|
-
(v) => typeof v === "string" && !/^\{[a-zA-Z0-9_]+\}$/.test(v),
|
|
727
|
-
);
|
|
728
|
-
if (isParseErr(hp)) return hp;
|
|
729
|
-
headerPrefixes = hp;
|
|
1220
|
+
scopes = a["scopes"] as string[];
|
|
730
1221
|
}
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
fix: "Use auth.kind: static-key to reference stored secrets, or remove the auth fields for a public API.",
|
|
744
|
-
},
|
|
745
|
-
);
|
|
1222
|
+
let paramStyle: OAuth2ParamStyle | undefined;
|
|
1223
|
+
if (a["paramStyle"] !== undefined) {
|
|
1224
|
+
if (a["paramStyle"] !== "bearer-header" && a["paramStyle"] !== "query") {
|
|
1225
|
+
return fail(
|
|
1226
|
+
file,
|
|
1227
|
+
"auth.paramStyle",
|
|
1228
|
+
"bearer-header | query",
|
|
1229
|
+
describeFound(a["paramStyle"]),
|
|
1230
|
+
{ snippet: snippetFor(fm, "auth") },
|
|
1231
|
+
);
|
|
1232
|
+
}
|
|
1233
|
+
paramStyle = a["paramStyle"];
|
|
746
1234
|
}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
const
|
|
750
|
-
|
|
751
|
-
...Object.values(secretQueryRefs ?? {}),
|
|
752
|
-
]);
|
|
753
|
-
const checkRefs = (
|
|
754
|
-
refs: Record<string, string>,
|
|
755
|
-
field: string,
|
|
756
|
-
): ParseApiGuideResult | null => {
|
|
757
|
-
for (const outName of Object.keys(refs)) {
|
|
758
|
-
const secretName = refs[outName]!;
|
|
759
|
-
if (!declared.has(secretName)) {
|
|
760
|
-
return fail(
|
|
761
|
-
file,
|
|
762
|
-
`${field}.${outName}`,
|
|
763
|
-
"a secret name declared in auth.requires or auth.optional",
|
|
764
|
-
`"${secretName}" is not in requires/optional`,
|
|
765
|
-
{
|
|
766
|
-
fix: `Add "${secretName}" to auth.requires or auth.optional (or fix the reference).`,
|
|
767
|
-
},
|
|
768
|
-
);
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
return null;
|
|
772
|
-
};
|
|
773
|
-
const r1 = checkRefs(secretRefs ?? {}, "auth.secretRefs");
|
|
774
|
-
if (r1) return r1;
|
|
775
|
-
const r2 = checkRefs(secretQueryRefs ?? {}, "auth.secretQueryRefs");
|
|
776
|
-
if (r2) return r2;
|
|
777
|
-
const both = (requires ?? []).filter((n) => (optional ?? []).includes(n));
|
|
778
|
-
if (both.length > 0) {
|
|
1235
|
+
let tokenEndpointAuthMethod: OAuth2TokenEndpointAuthMethod | undefined;
|
|
1236
|
+
if (a["tokenEndpointAuthMethod"] !== undefined) {
|
|
1237
|
+
const m = a["tokenEndpointAuthMethod"];
|
|
1238
|
+
if (!isOAuth2TokenEndpointAuthMethod(m)) {
|
|
779
1239
|
return fail(
|
|
780
1240
|
file,
|
|
781
|
-
"auth.
|
|
782
|
-
"
|
|
783
|
-
|
|
784
|
-
{
|
|
785
|
-
fix: `Move "${both[0]}" to either requires or optional, not both.`,
|
|
786
|
-
},
|
|
1241
|
+
"auth.tokenEndpointAuthMethod",
|
|
1242
|
+
OAUTH2_TOKEN_ENDPOINT_AUTH_METHODS.join(" | "),
|
|
1243
|
+
describeFound(m),
|
|
1244
|
+
{ snippet: snippetFor(fm, "auth") },
|
|
787
1245
|
);
|
|
788
1246
|
}
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
1247
|
+
tokenEndpointAuthMethod = m;
|
|
1248
|
+
}
|
|
1249
|
+
let authorizeUrl: string | undefined;
|
|
1250
|
+
if (a["authorizeUrl"] !== undefined) {
|
|
1251
|
+
const au = requireHttpUrl(a["authorizeUrl"], "auth.authorizeUrl", file, fm);
|
|
1252
|
+
if (typeof au !== "string") return au;
|
|
1253
|
+
authorizeUrl = au;
|
|
1254
|
+
}
|
|
1255
|
+
let revokeUrl: string | undefined;
|
|
1256
|
+
if (a["revokeUrl"] !== undefined) {
|
|
1257
|
+
const rv = requireHttpUrl(a["revokeUrl"], "auth.revokeUrl", file, fm);
|
|
1258
|
+
if (typeof rv !== "string") return rv;
|
|
1259
|
+
revokeUrl = rv;
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// Grant invariants — the single shared statement of OAuth2 grant
|
|
1263
|
+
// semantics (also enforced by buildSyntheticOAuth2Auth in core/auth.ts
|
|
1264
|
+
// for the bootstrap surfaces). Adding a grant or invariant: edit
|
|
1265
|
+
// oauth2GrantIssue, then extend both callers' message maps.
|
|
1266
|
+
const issue = oauth2GrantIssue({
|
|
1267
|
+
grant,
|
|
1268
|
+
hasClientSecret: clientSecret !== undefined,
|
|
1269
|
+
authorizeUrl,
|
|
1270
|
+
tokenEndpointAuthMethod,
|
|
1271
|
+
});
|
|
1272
|
+
if (issue) {
|
|
1273
|
+
switch (issue.code) {
|
|
1274
|
+
case "noneWithSecret":
|
|
1275
|
+
return fail(
|
|
1276
|
+
file,
|
|
1277
|
+
"auth.clientSecret",
|
|
1278
|
+
"absent when tokenEndpointAuthMethod: none",
|
|
1279
|
+
"present",
|
|
1280
|
+
{
|
|
1281
|
+
snippet: snippetFor(fm, "auth"),
|
|
1282
|
+
fix: "Remove clientSecret — tokenEndpointAuthMethod: none sends no client credentials (PKCE public clients have no secret).",
|
|
1283
|
+
},
|
|
1284
|
+
);
|
|
1285
|
+
case "ccRequiresSecret":
|
|
820
1286
|
return fail(
|
|
821
1287
|
file,
|
|
822
|
-
|
|
823
|
-
"a
|
|
824
|
-
|
|
1288
|
+
"auth.clientSecret",
|
|
1289
|
+
"a clientSecret ref for grant: client_credentials",
|
|
1290
|
+
"missing",
|
|
825
1291
|
{
|
|
826
|
-
|
|
1292
|
+
snippet: snippetFor(fm, "auth"),
|
|
1293
|
+
fix: "Add clientSecret: { secret: client_secret } — the store name provisioned via /api secrets <domain>.",
|
|
827
1294
|
},
|
|
828
1295
|
);
|
|
1296
|
+
case "ccRejectsAuthorizeUrl":
|
|
1297
|
+
return fail(
|
|
1298
|
+
file,
|
|
1299
|
+
"auth.authorizeUrl",
|
|
1300
|
+
"absent for grant: client_credentials",
|
|
1301
|
+
"authorizeUrl present",
|
|
1302
|
+
{
|
|
1303
|
+
fix: "Remove authorizeUrl — client_credentials is server-to-server with no browser flow.",
|
|
1304
|
+
},
|
|
1305
|
+
);
|
|
1306
|
+
case "acRequiresAuthorizeUrl":
|
|
1307
|
+
return fail(
|
|
1308
|
+
file,
|
|
1309
|
+
"auth.authorizeUrl",
|
|
1310
|
+
"a URL for grant: authorization_code",
|
|
1311
|
+
"missing",
|
|
1312
|
+
{
|
|
1313
|
+
fix: "Add authorizeUrl — the provider's authorization endpoint. The redirect URI is the runtime convention http://127.0.0.1/callback (RFC 8252 §7.3); register it on your OAuth app.",
|
|
1314
|
+
},
|
|
1315
|
+
);
|
|
1316
|
+
default: {
|
|
1317
|
+
// Compile-time exhaustiveness tripwire: a new OAuth2GrantIssue
|
|
1318
|
+
// code must extend this switch (the builder's message map is
|
|
1319
|
+
// already forced via its return type). Unreachable at runtime.
|
|
1320
|
+
const uncovered: never = issue.code;
|
|
1321
|
+
throw new Error(`unhandled OAuth2 grant invariant: ${String(uncovered)}`);
|
|
829
1322
|
}
|
|
830
1323
|
}
|
|
831
1324
|
}
|
|
832
1325
|
|
|
833
|
-
const result:
|
|
834
|
-
|
|
1326
|
+
const result: OAuth2Auth = {
|
|
1327
|
+
kind: "oauth2",
|
|
1328
|
+
grant,
|
|
1329
|
+
tokenUrl,
|
|
1330
|
+
clientId,
|
|
1331
|
+
...(clientSecret === undefined ? {} : { clientSecret }),
|
|
1332
|
+
};
|
|
835
1333
|
if (secretRefs !== undefined) result.secretRefs = secretRefs;
|
|
836
|
-
if (
|
|
837
|
-
if (
|
|
838
|
-
if (
|
|
839
|
-
|
|
1334
|
+
if (scopes !== undefined) result.scopes = scopes;
|
|
1335
|
+
if (paramStyle !== undefined) result.paramStyle = paramStyle;
|
|
1336
|
+
if (tokenEndpointAuthMethod !== undefined)
|
|
1337
|
+
result.tokenEndpointAuthMethod = tokenEndpointAuthMethod;
|
|
1338
|
+
if (authorizeUrl !== undefined) result.authorizeUrl = authorizeUrl;
|
|
1339
|
+
if (revokeUrl !== undefined) result.revokeUrl = revokeUrl;
|
|
840
1340
|
return result;
|
|
841
1341
|
}
|
|
842
1342
|
|
|
@@ -849,6 +1349,9 @@ function validateOperation(
|
|
|
849
1349
|
index: number,
|
|
850
1350
|
file: string | undefined,
|
|
851
1351
|
topPagination: PaginationConfig | undefined,
|
|
1352
|
+
guideResponseShape: ResponseShape,
|
|
1353
|
+
injectedQuerySecretNames: ReadonlySet<string>,
|
|
1354
|
+
authKind: string,
|
|
852
1355
|
): Operation | ParseApiGuideResult {
|
|
853
1356
|
const fieldPath = (leaf: string) => `operations[${index}].${leaf}`;
|
|
854
1357
|
|
|
@@ -862,6 +1365,23 @@ function validateOperation(
|
|
|
862
1365
|
}
|
|
863
1366
|
const o = raw as Record<string, unknown>;
|
|
864
1367
|
|
|
1368
|
+
// Op-block allowlist — reject keys not legal for an op (a typo like
|
|
1369
|
+
// `errorPaths:` would silently no-op the intended behavior). Format
|
|
1370
|
+
// mirrors the pagination per-style allowlist check.
|
|
1371
|
+
const unknownKeys = Object.keys(o).filter((k) => !OP_ALLOWLIST.has(k));
|
|
1372
|
+
if (unknownKeys.length > 0) {
|
|
1373
|
+
const first = unknownKeys[0]!; // guarded by the length check above
|
|
1374
|
+
return fail(
|
|
1375
|
+
file,
|
|
1376
|
+
fieldPath(first),
|
|
1377
|
+
`a known op-block key (${[...OP_ALLOWLIST].join(", ")})`,
|
|
1378
|
+
`unknown key(s): ${unknownKeys.join(", ")}`,
|
|
1379
|
+
{
|
|
1380
|
+
fix: `Remove operations[${index}].${first} — the op-block schema is closed.`,
|
|
1381
|
+
},
|
|
1382
|
+
);
|
|
1383
|
+
}
|
|
1384
|
+
|
|
865
1385
|
// name
|
|
866
1386
|
const name = o["name"];
|
|
867
1387
|
if (typeof name !== "string" || name === "") {
|
|
@@ -995,6 +1515,24 @@ function validateOperation(
|
|
|
995
1515
|
);
|
|
996
1516
|
}
|
|
997
1517
|
const s = spec as Record<string, unknown>;
|
|
1518
|
+
// Unknown-key tripwire — the param-spec schema is closed
|
|
1519
|
+
// (required/default/description/listStyle). A typo'd key
|
|
1520
|
+
// (`listStyl:`, `requried:`) must not be silently dropped: that's
|
|
1521
|
+
// the silent-wrong-wire class. Same philosophy as the
|
|
1522
|
+
// pagination/auth allowlists.
|
|
1523
|
+
for (const k of Object.keys(s)) {
|
|
1524
|
+
if (!PARAM_SPEC_KEYS.has(k)) {
|
|
1525
|
+
return fail(
|
|
1526
|
+
file,
|
|
1527
|
+
fieldPath(`params.${key}.${k}`),
|
|
1528
|
+
`one of: ${[...PARAM_SPEC_KEYS].join(" | ")} (unknown param-spec key)`,
|
|
1529
|
+
`key "${k}"`,
|
|
1530
|
+
{
|
|
1531
|
+
fix: `Remove params.${key}.${k} — did you mean one of: ${[...PARAM_SPEC_KEYS].join(", ")}?`,
|
|
1532
|
+
},
|
|
1533
|
+
);
|
|
1534
|
+
}
|
|
1535
|
+
}
|
|
998
1536
|
const paramSpec: QueryParamSpec = {};
|
|
999
1537
|
if (s["required"] !== undefined) {
|
|
1000
1538
|
if (typeof s["required"] !== "boolean") {
|
|
@@ -1021,6 +1559,93 @@ function validateOperation(
|
|
|
1021
1559
|
}
|
|
1022
1560
|
paramSpec.description = s["description"];
|
|
1023
1561
|
}
|
|
1562
|
+
if (s["listStyle"] !== undefined) {
|
|
1563
|
+
if (!isListStyle(s["listStyle"])) {
|
|
1564
|
+
return fail(
|
|
1565
|
+
file,
|
|
1566
|
+
fieldPath(`params.${key}.listStyle`),
|
|
1567
|
+
`one of: ${LIST_STYLES.join(" | ")}`,
|
|
1568
|
+
describeFound(s["listStyle"]),
|
|
1569
|
+
);
|
|
1570
|
+
}
|
|
1571
|
+
paramSpec.listStyle = s["listStyle"];
|
|
1572
|
+
}
|
|
1573
|
+
// bracket double-dress — the style dresses the wire key with []
|
|
1574
|
+
// itself; a declared name already ending in [] would double-dress
|
|
1575
|
+
// (id[] + [] → id[][]=).
|
|
1576
|
+
if (s["listStyle"] === "bracket" && key.endsWith("[]")) {
|
|
1577
|
+
return fail(
|
|
1578
|
+
file,
|
|
1579
|
+
fieldPath(`params.${key}.listStyle`),
|
|
1580
|
+
"a param name that does not already end in [] (bracket adds the dress itself)",
|
|
1581
|
+
`"${key}" already ends in [] — the wire key would double-dress (id[][]=)`,
|
|
1582
|
+
{
|
|
1583
|
+
fix: `Declare the clean name (params.${key.slice(0, -2)}) with listStyle: bracket — the style appends [] to the wire key.`,
|
|
1584
|
+
},
|
|
1585
|
+
);
|
|
1586
|
+
}
|
|
1587
|
+
// Array default validation — both arms, same pass. An array default
|
|
1588
|
+
// on a non-listStyle param would throw on every call at runtime
|
|
1589
|
+
// (arrays are loud errors there once the serializer widening lands);
|
|
1590
|
+
// catch the authoring error at parse time. On a listStyle param the
|
|
1591
|
+
// elements are validated by the same rules the runtime serializer
|
|
1592
|
+
// enforces (scalars only; no comma-bearing element on comma — the
|
|
1593
|
+
// joined wire form can't distinguish it from a longer list).
|
|
1594
|
+
if (Array.isArray(paramSpec.default)) {
|
|
1595
|
+
if (paramSpec.listStyle === undefined) {
|
|
1596
|
+
return fail(
|
|
1597
|
+
file,
|
|
1598
|
+
fieldPath(`params.${key}.default`),
|
|
1599
|
+
"a scalar default (an array default requires listStyle)",
|
|
1600
|
+
"an array default on a param without listStyle",
|
|
1601
|
+
{
|
|
1602
|
+
fix: `Declare listStyle: ${LIST_STYLES.join(" | ")} on params.${key}, or use a scalar default — an array value on a non-listStyle param fails on every call.`,
|
|
1603
|
+
},
|
|
1604
|
+
);
|
|
1605
|
+
}
|
|
1606
|
+
// Empty array default — the same every-call-throw class as the
|
|
1607
|
+
// styleless case above: the runtime serializer rejects [] (the
|
|
1608
|
+
// param would be silently dropped), so a defaulted call with no
|
|
1609
|
+
// override always fails. Catch it at parse time.
|
|
1610
|
+
if (paramSpec.default.length === 0) {
|
|
1611
|
+
return fail(
|
|
1612
|
+
file,
|
|
1613
|
+
fieldPath(`params.${key}.default`),
|
|
1614
|
+
"a non-empty array default (an empty array default throws on every defaulted call — the param would be silently dropped)",
|
|
1615
|
+
"an empty array default ([])",
|
|
1616
|
+
{
|
|
1617
|
+
fix: `Omit params.${key}.default entirely, or default to a non-empty array — a caller-supplied [] on a listStyle param still fails per-call by design.`,
|
|
1618
|
+
},
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
1621
|
+
for (const el of paramSpec.default) {
|
|
1622
|
+
if (
|
|
1623
|
+
el === null ||
|
|
1624
|
+
(typeof el !== "string" &&
|
|
1625
|
+
typeof el !== "number" &&
|
|
1626
|
+
typeof el !== "boolean")
|
|
1627
|
+
) {
|
|
1628
|
+
return fail(
|
|
1629
|
+
file,
|
|
1630
|
+
fieldPath(`params.${key}.default`),
|
|
1631
|
+
"an array of scalar (string | number | boolean) elements",
|
|
1632
|
+
`array contains ${describeFound(el)}`,
|
|
1633
|
+
);
|
|
1634
|
+
}
|
|
1635
|
+
if (
|
|
1636
|
+
paramSpec.listStyle === "comma" &&
|
|
1637
|
+
typeof el === "string" &&
|
|
1638
|
+
el.includes(",")
|
|
1639
|
+
) {
|
|
1640
|
+
return fail(
|
|
1641
|
+
file,
|
|
1642
|
+
fieldPath(`params.${key}.default`),
|
|
1643
|
+
"comma-free elements (listStyle: comma joins with ',' — a comma-bearing element is indistinguishable from a longer list on the wire)",
|
|
1644
|
+
`element "${el}" contains a comma`,
|
|
1645
|
+
);
|
|
1646
|
+
}
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1024
1649
|
params[key] = paramSpec;
|
|
1025
1650
|
}
|
|
1026
1651
|
}
|
|
@@ -1031,7 +1656,9 @@ function validateOperation(
|
|
|
1031
1656
|
// member-exists, path-param reject, no `required: true` overlap, no
|
|
1032
1657
|
// `default` on a member. A group member that is `required` would defeat
|
|
1033
1658
|
// the group at runtime; a `default` would fire alongside a caller-supplied
|
|
1034
|
-
// sibling
|
|
1659
|
+
// sibling. Semantics are at-least-one-of with all supplied members sent
|
|
1660
|
+
// (members may combine freely); multi-group lands only as the reserved
|
|
1661
|
+
// `requiresAnyOfGroups` sibling key, never a union on this field.
|
|
1035
1662
|
const requiresAnyOfRaw = o["requiresAnyOf"];
|
|
1036
1663
|
let requiresAnyOf: string[] | undefined;
|
|
1037
1664
|
if (requiresAnyOfRaw !== undefined) {
|
|
@@ -1076,7 +1703,7 @@ function validateOperation(
|
|
|
1076
1703
|
"a param that is not also required: true",
|
|
1077
1704
|
`"${member}" is required: true`,
|
|
1078
1705
|
{
|
|
1079
|
-
fix: `Remove required: true from params.${member} — it is governed by the requiresAnyOf group, not per-param required.`,
|
|
1706
|
+
fix: `Remove required: true from params.${member} — it is governed by the requiresAnyOf at-least-one-of group, not per-param required.`,
|
|
1080
1707
|
},
|
|
1081
1708
|
);
|
|
1082
1709
|
}
|
|
@@ -1087,7 +1714,7 @@ function validateOperation(
|
|
|
1087
1714
|
"a param that does not also declare a default",
|
|
1088
1715
|
`"${member}" has a default`,
|
|
1089
1716
|
{
|
|
1090
|
-
fix: `Remove the default from params.${member} — requiresAnyOf members are
|
|
1717
|
+
fix: `Remove the default from params.${member} — requiresAnyOf members are at-least-one-of peers (all supplied members are sent), so a default would fire alongside a caller-supplied sibling.`,
|
|
1091
1718
|
},
|
|
1092
1719
|
);
|
|
1093
1720
|
}
|
|
@@ -1122,6 +1749,20 @@ function validateOperation(
|
|
|
1122
1749
|
describeFound(fmt),
|
|
1123
1750
|
);
|
|
1124
1751
|
}
|
|
1752
|
+
// Declared-but-dead: date normalization runs only in query assembly
|
|
1753
|
+
// (buildQueryParams), while fillPathTemplate fills path tokens raw —
|
|
1754
|
+
// a dateParams entry naming a path token can never fire.
|
|
1755
|
+
if (pathParams.includes(k)) {
|
|
1756
|
+
return fail(
|
|
1757
|
+
file,
|
|
1758
|
+
fieldPath(`dateParams.${k}`),
|
|
1759
|
+
"a query param name (not a path param)",
|
|
1760
|
+
`"${k}" is a path param — dateParams normalization runs only in query assembly, and path tokens are filled raw, so the declaration can never fire`,
|
|
1761
|
+
{
|
|
1762
|
+
fix: `Put the ISO date directly in the path (the real pattern: Polygon.io aggregates {from}/{to}, Frankfurter /{date}) — a future normalization for path tokens would be additive.`,
|
|
1763
|
+
},
|
|
1764
|
+
);
|
|
1765
|
+
}
|
|
1125
1766
|
}
|
|
1126
1767
|
dateParams = dateParamsRaw as Record<string, DateParamFormat>;
|
|
1127
1768
|
}
|
|
@@ -1178,6 +1819,62 @@ function validateOperation(
|
|
|
1178
1819
|
parseOverride = pr;
|
|
1179
1820
|
}
|
|
1180
1821
|
|
|
1822
|
+
// errorPath — present-only-on-error envelope path. Guards (all parse-time,
|
|
1823
|
+
// fail-loud in front of the author):
|
|
1824
|
+
// - non-empty string (wrong type → ParseError)
|
|
1825
|
+
// - tokenizeable — a malformed path would resolve `undefined` at runtime,
|
|
1826
|
+
// i.e. declared-absent → success: the exact confidently-wrong failure
|
|
1827
|
+
// mode this field exists to kill. Parse is the only code that runs
|
|
1828
|
+
// exactly once, in front of the author who can fix it.
|
|
1829
|
+
// - non-empty tokenization — the root path ("$", ".") tokenizes to [] and
|
|
1830
|
+
// would resolve the entire parsed body, which is always defined
|
|
1831
|
+
// post-parseResponse — every call would fail.
|
|
1832
|
+
// - effective shape not text — parseResponse returns the raw body string
|
|
1833
|
+
// for text ops and resolveJsonPath against a string always resolves
|
|
1834
|
+
// undefined (declared-then-dead). Covers an op-level parse override AND
|
|
1835
|
+
// an op without one under a text guide-level responseShape.
|
|
1836
|
+
const errorPathRaw = o["errorPath"];
|
|
1837
|
+
let errorPath: string | undefined;
|
|
1838
|
+
if (errorPathRaw !== undefined) {
|
|
1839
|
+
if (typeof errorPathRaw !== "string" || errorPathRaw === "") {
|
|
1840
|
+
return fail(
|
|
1841
|
+
file,
|
|
1842
|
+
fieldPath("errorPath"),
|
|
1843
|
+
"a non-empty string JSON path",
|
|
1844
|
+
describeFound(errorPathRaw),
|
|
1845
|
+
);
|
|
1846
|
+
}
|
|
1847
|
+
const tokens = tokenizeJsonPath(errorPathRaw);
|
|
1848
|
+
if (tokens === null) {
|
|
1849
|
+
return fail(
|
|
1850
|
+
file,
|
|
1851
|
+
fieldPath("errorPath"),
|
|
1852
|
+
"a tokenizeable JSON path",
|
|
1853
|
+
`"${errorPathRaw}" is malformed (unterminated or non-numeric bracket)`,
|
|
1854
|
+
{
|
|
1855
|
+
fix: 'Fix the path syntax — e.g. "OAI-PMH.error" or "result[0].message".',
|
|
1856
|
+
},
|
|
1857
|
+
);
|
|
1858
|
+
}
|
|
1859
|
+
if (tokens.length === 0) {
|
|
1860
|
+
return fail(
|
|
1861
|
+
file,
|
|
1862
|
+
fieldPath("errorPath"),
|
|
1863
|
+
"a JSON path to an error element (not the document root)",
|
|
1864
|
+
`"${errorPathRaw}" resolves the entire parsed body — every call would fail`,
|
|
1865
|
+
);
|
|
1866
|
+
}
|
|
1867
|
+
if ((parseOverride ?? guideResponseShape).format === "text") {
|
|
1868
|
+
return fail(
|
|
1869
|
+
file,
|
|
1870
|
+
fieldPath("errorPath"),
|
|
1871
|
+
"an op whose effective response shape is not format: text",
|
|
1872
|
+
"errorPath can never fire on a text op — parseResponse yields the raw body string, not a resolvable shape",
|
|
1873
|
+
);
|
|
1874
|
+
}
|
|
1875
|
+
errorPath = errorPathRaw;
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1181
1878
|
// pagination (op-level override)
|
|
1182
1879
|
const opPaginationRaw = o["pagination"];
|
|
1183
1880
|
let opPagination: PaginationConfig | undefined;
|
|
@@ -1203,6 +1900,97 @@ function validateOperation(
|
|
|
1203
1900
|
);
|
|
1204
1901
|
}
|
|
1205
1902
|
|
|
1903
|
+
// listStyle collision guard — under keyed supersession, pagination /
|
|
1904
|
+
// tokenBag continuation writes REPLACE same-named base params, so a
|
|
1905
|
+
// listStyle param colliding with an effective pagination wire name is
|
|
1906
|
+
// dead (its listStyle could never reach the wire). Checked against the
|
|
1907
|
+
// EFFECTIVE config (op-level ?? guide-level) — a guide-level pageParam
|
|
1908
|
+
// collides too. Scoped to via: paginate — the supersession writes only
|
|
1909
|
+
// happen in the paginate executor loop, so a restGet op's params are
|
|
1910
|
+
// never replaced and no collision is possible there. tokenBag wire names
|
|
1911
|
+
// derive via the same wireParamName helper advancePagination uses at
|
|
1912
|
+
// runtime — one derivation, two consumers, no drift. Scope: listStyle
|
|
1913
|
+
// params only; scalar collisions stay legal (the seeded
|
|
1914
|
+
// `page: {default: 0}` + pageParam: page pattern).
|
|
1915
|
+
if (via === "paginate" && effectivePagination !== undefined) {
|
|
1916
|
+
const wireNames: string[] = [];
|
|
1917
|
+
if (effectivePagination.style === "tokenBag") {
|
|
1918
|
+
for (const key of effectivePagination.continuationParams ?? []) {
|
|
1919
|
+
wireNames.push(wireParamName(key));
|
|
1920
|
+
}
|
|
1921
|
+
} else {
|
|
1922
|
+
if (effectivePagination.pageParam)
|
|
1923
|
+
wireNames.push(effectivePagination.pageParam);
|
|
1924
|
+
if (effectivePagination.pageSizeParam)
|
|
1925
|
+
wireNames.push(effectivePagination.pageSizeParam);
|
|
1926
|
+
if (effectivePagination.cursorParam)
|
|
1927
|
+
wireNames.push(effectivePagination.cursorParam);
|
|
1928
|
+
if (effectivePagination.tokenParam)
|
|
1929
|
+
wireNames.push(effectivePagination.tokenParam);
|
|
1930
|
+
}
|
|
1931
|
+
for (const [key, spec] of Object.entries(params)) {
|
|
1932
|
+
if (spec.listStyle === undefined) continue;
|
|
1933
|
+
if (wireNames.includes(key)) {
|
|
1934
|
+
return fail(
|
|
1935
|
+
file,
|
|
1936
|
+
fieldPath(`params.${key}.listStyle`),
|
|
1937
|
+
"a param name not colliding with this operation's pagination wire params",
|
|
1938
|
+
`"${key}" is a pagination wire param (pagination.style: ${effectivePagination.style})`,
|
|
1939
|
+
{
|
|
1940
|
+
fix: `Rename params.${key} — pagination/tokenBag writes replace same-named base params, so the declared listStyle would never reach the wire.`,
|
|
1941
|
+
},
|
|
1942
|
+
);
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
// Injected query-secret names vs pagination wire names — the paginate
|
|
1946
|
+
// URL is built as { ...pageParams, ...secretParams } (core/helpers.ts),
|
|
1947
|
+
// so the secret spreads last and overwrites the pagination value on
|
|
1948
|
+
// every page request: pagination silently never advances (valid-looking
|
|
1949
|
+
// 200s, page one forever). Injected names = static-key secretQueryRefs
|
|
1950
|
+
// key names plus oauth2 paramStyle: query's access_token — the same
|
|
1951
|
+
// secretQueryParams seam (core/auth.ts), merged last in the same spread.
|
|
1952
|
+
// Scoped to via: paginate like the listStyle guard — a restGet op never
|
|
1953
|
+
// builds pageParams, so a colliding name is legal there (the guide-level
|
|
1954
|
+
// secretQueryRefs-vs-params check must NOT extend to wire names).
|
|
1955
|
+
for (const secretName of injectedQuerySecretNames) {
|
|
1956
|
+
if (wireNames.includes(secretName)) {
|
|
1957
|
+
const isOAuth2 = authKind === "oauth2";
|
|
1958
|
+
return fail(
|
|
1959
|
+
file,
|
|
1960
|
+
isOAuth2 ? "auth.paramStyle" : `auth.secretQueryRefs.${secretName}`,
|
|
1961
|
+
"an injected query-secret name not colliding with this operation's pagination wire params",
|
|
1962
|
+
`"${secretName}" is a pagination wire param of operation "${name}" (pagination.style: ${effectivePagination.style}) — the injected secret overwrites the pagination value on every page request, so pagination never advances past page one`,
|
|
1963
|
+
{
|
|
1964
|
+
fix: isOAuth2
|
|
1965
|
+
? `Set auth.paramStyle to bearer-header (or rename the wire param in operation "${name}"'s pagination block) — the query-injected access_token is merged after the pagination params and wins every page request.`
|
|
1966
|
+
: `Rename the secret ref in auth.secretQueryRefs (or the wire param in operation "${name}"'s pagination block) — the secret is merged after the pagination params and wins every page request.`,
|
|
1967
|
+
},
|
|
1968
|
+
);
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
// listStyle × dateParams — mutually exclusive by design: date params are
|
|
1974
|
+
// single-valued (the runtime serializer throws before normalization on any
|
|
1975
|
+
// array), so a declared listStyle can never reach the wire. A defaulted
|
|
1976
|
+
// listStyle date param would additionally throw on every defaulted call —
|
|
1977
|
+
// the same every-call-throw class the array-default guard above exists for.
|
|
1978
|
+
if (dateParams !== undefined) {
|
|
1979
|
+
for (const key of Object.keys(dateParams)) {
|
|
1980
|
+
if (params[key]?.listStyle !== undefined) {
|
|
1981
|
+
return fail(
|
|
1982
|
+
file,
|
|
1983
|
+
fieldPath(`dateParams.${key}`),
|
|
1984
|
+
"a param not declaring listStyle (date params are single-valued — listStyle can never apply)",
|
|
1985
|
+
`"${key}" declares both listStyle: ${params[key]!.listStyle} and a dateParams entry`,
|
|
1986
|
+
{
|
|
1987
|
+
fix: `Drop one of the two — keep dateParams.${key} for date normalization, or remove it and declare listStyle on params.${key} if the API truly accepts multi-value dates.`,
|
|
1988
|
+
},
|
|
1989
|
+
);
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1206
1994
|
// gatherAllMax (op-level override)
|
|
1207
1995
|
const opGatherAllMaxRaw = o["gatherAllMax"];
|
|
1208
1996
|
let opGatherAllMax: number | undefined;
|
|
@@ -1236,6 +2024,7 @@ function validateOperation(
|
|
|
1236
2024
|
...(dateParams === undefined ? {} : { dateParams }),
|
|
1237
2025
|
...(requiresAnyOf === undefined ? {} : { requiresAnyOf }),
|
|
1238
2026
|
...(parseOverride ? { parse: parseOverride } : {}),
|
|
2027
|
+
...(errorPath === undefined ? {} : { errorPath }),
|
|
1239
2028
|
...(opPagination ? { pagination: opPagination } : {}),
|
|
1240
2029
|
...(opGatherAllMax === undefined ? {} : { gatherAllMax: opGatherAllMax }),
|
|
1241
2030
|
};
|
|
@@ -1354,6 +2143,24 @@ export function parseApiGuide(
|
|
|
1354
2143
|
}
|
|
1355
2144
|
const m = meta as Record<string, unknown>;
|
|
1356
2145
|
|
|
2146
|
+
// Frontmatter allowlist — reject keys parseApiGuide never reads (a typo'd
|
|
2147
|
+
// top-level key would be silently ignored today and hard-fail later once
|
|
2148
|
+
// the schema is published). Same closed-schema check as the op-block
|
|
2149
|
+
// allowlist; format mirrors the pagination per-style allowlist check.
|
|
2150
|
+
const unknownFmKeys = Object.keys(m).filter((k) => !GUIDE_ALLOWLIST.has(k));
|
|
2151
|
+
if (unknownFmKeys.length > 0) {
|
|
2152
|
+
const first = unknownFmKeys[0]!; // guarded by the length check above
|
|
2153
|
+
return fail(
|
|
2154
|
+
file,
|
|
2155
|
+
first,
|
|
2156
|
+
`a known frontmatter key (${[...GUIDE_ALLOWLIST].join(", ")})`,
|
|
2157
|
+
`unknown key(s): ${unknownFmKeys.join(", ")}`,
|
|
2158
|
+
{
|
|
2159
|
+
fix: `Remove ${first} from the frontmatter — the guide schema is closed.`,
|
|
2160
|
+
},
|
|
2161
|
+
);
|
|
2162
|
+
}
|
|
2163
|
+
|
|
1357
2164
|
// ── projection slice ──────────────────────────────────────────
|
|
1358
2165
|
const kindRaw = m["kind"];
|
|
1359
2166
|
if (kindRaw !== undefined && kindRaw !== "api") {
|
|
@@ -1452,14 +2259,13 @@ export function parseApiGuide(
|
|
|
1452
2259
|
description = descriptionRaw;
|
|
1453
2260
|
}
|
|
1454
2261
|
|
|
1455
|
-
// schemaVersion — breaking-change detection
|
|
1456
|
-
//
|
|
1457
|
-
//
|
|
1458
|
-
//
|
|
1459
|
-
// the
|
|
1460
|
-
//
|
|
1461
|
-
//
|
|
1462
|
-
// value falls back to 0 and never rejects a guide.
|
|
2262
|
+
// schemaVersion — breaking-change detection, enforced by the hard gate.
|
|
2263
|
+
// Stamped on save by api-learn; absent-on-read defaults to 0 (the floor),
|
|
2264
|
+
// so an unversioned guide is treated as pre-v1. A valid-integer frontmatter
|
|
2265
|
+
// value overrides the floor. A stale value (< current) fails to parse and
|
|
2266
|
+
// routes to malformed (the gate below). A malformed (non-integer/negative)
|
|
2267
|
+
// value also falls to the floor 0 and is caught by the same gate — one
|
|
2268
|
+
// code path, one message.
|
|
1463
2269
|
let schemaVersion = 0;
|
|
1464
2270
|
const schemaVersionRaw = m["schemaVersion"];
|
|
1465
2271
|
if (
|
|
@@ -1469,6 +2275,20 @@ export function parseApiGuide(
|
|
|
1469
2275
|
) {
|
|
1470
2276
|
schemaVersion = schemaVersionRaw;
|
|
1471
2277
|
}
|
|
2278
|
+
if (isStaleSchema(schemaVersion, GUIDE_SCHEMA_VERSION)) {
|
|
2279
|
+
return fail(
|
|
2280
|
+
file,
|
|
2281
|
+
"schemaVersion",
|
|
2282
|
+
`>= ${GUIDE_SCHEMA_VERSION} (current)`,
|
|
2283
|
+
describeFound(schemaVersionRaw),
|
|
2284
|
+
{
|
|
2285
|
+
fix:
|
|
2286
|
+
`Guide ${file ?? "this guide"} was authored against schema ${schemaVersion}; the current schema is ${GUIDE_SCHEMA_VERSION}. ` +
|
|
2287
|
+
`Re-stamp its frontmatter to schemaVersion: ${GUIDE_SCHEMA_VERSION}, hand-fixing any breaking changes listed in the migration doc. ${MIGRATION_DOC_NOTE} ` +
|
|
2288
|
+
`Ask your agent to make this fix, then /reload.`,
|
|
2289
|
+
},
|
|
2290
|
+
);
|
|
2291
|
+
}
|
|
1472
2292
|
|
|
1473
2293
|
let gatherAllMax = GATHER_ALL_MAX_FALLBACK;
|
|
1474
2294
|
const gatherAllMaxRaw = m["gatherAllMax"];
|
|
@@ -1528,10 +2348,30 @@ export function parseApiGuide(
|
|
|
1528
2348
|
);
|
|
1529
2349
|
}
|
|
1530
2350
|
const operations: Operation[] = [];
|
|
2351
|
+
// Injected query-secret names (the secretQueryParams seam in core/auth.ts):
|
|
2352
|
+
// static-key secretQueryRefs key names, plus oauth2 paramStyle: query's
|
|
2353
|
+
// access_token. Derived once here (auth is validated above) and passed to
|
|
2354
|
+
// every validateOperation for the paginate wire-name collision check.
|
|
2355
|
+
const injectedQuerySecretNames: ReadonlySet<string> = new Set([
|
|
2356
|
+
...(auth.kind === "static-key" && auth.secretQueryRefs
|
|
2357
|
+
? Object.keys(auth.secretQueryRefs)
|
|
2358
|
+
: []),
|
|
2359
|
+
...(auth.kind === "oauth2" && auth.paramStyle === "query"
|
|
2360
|
+
? ["access_token"]
|
|
2361
|
+
: []),
|
|
2362
|
+
]);
|
|
1531
2363
|
for (let i = 0; i < opsRaw.length; i++) {
|
|
1532
2364
|
const opRaw = opsRaw[i];
|
|
1533
2365
|
if (opRaw === undefined) continue;
|
|
1534
|
-
const opRes = validateOperation(
|
|
2366
|
+
const opRes = validateOperation(
|
|
2367
|
+
opRaw,
|
|
2368
|
+
i,
|
|
2369
|
+
file,
|
|
2370
|
+
pagination,
|
|
2371
|
+
responseShape,
|
|
2372
|
+
injectedQuerySecretNames,
|
|
2373
|
+
auth.kind,
|
|
2374
|
+
);
|
|
1535
2375
|
if (!("name" in opRes)) return opRes as ParseApiGuideResult;
|
|
1536
2376
|
operations.push(opRes);
|
|
1537
2377
|
}
|
|
@@ -1560,6 +2400,82 @@ export function parseApiGuide(
|
|
|
1560
2400
|
}
|
|
1561
2401
|
}
|
|
1562
2402
|
|
|
2403
|
+
// Cross-field (oauth2 arm of the same D1 class): on paramStyle: query the
|
|
2404
|
+
// injected access_token must not be a declared op param — it spreads last
|
|
2405
|
+
// in `{ ...query, ...secretParams }`, so the agent's value would be
|
|
2406
|
+
// silently overwritten. Scoped to paramStyle: query — with the default
|
|
2407
|
+
// bearer-header the token rides the Authorization header and a legit
|
|
2408
|
+
// access_token query param is legal. Paginate ops with access_token as a
|
|
2409
|
+
// wire name are already rejected earlier by the wire-name collision check.
|
|
2410
|
+
if (auth.kind === "oauth2" && auth.paramStyle === "query") {
|
|
2411
|
+
for (const dOp of operations) {
|
|
2412
|
+
if ("access_token" in dOp.params) {
|
|
2413
|
+
return fail(
|
|
2414
|
+
file,
|
|
2415
|
+
"auth.paramStyle",
|
|
2416
|
+
"an injected query-secret name not declared in any operation's params",
|
|
2417
|
+
`also a param of operation "${dOp.name}"`,
|
|
2418
|
+
{
|
|
2419
|
+
fix: `Remove access_token from operation "${dOp.name}"'s params map — it is code-injected from the token store on paramStyle: query and the agent must not be able to set it.`,
|
|
2420
|
+
},
|
|
2421
|
+
);
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
}
|
|
2425
|
+
|
|
2426
|
+
// Cross-field: secretPathRefs rules. Every path-ref name is a
|
|
2427
|
+
// secret-owned path token — the agent must never be able to set it, and
|
|
2428
|
+
// it must be load-bearing. Checked after operations (the operative fact
|
|
2429
|
+
// is that this runs after BOTH parses):
|
|
2430
|
+
// - a name in any op's `params` map (agent-suppliable). Path-token-keyed
|
|
2431
|
+
// params entries never reach dOp.params (the parser routes them to
|
|
2432
|
+
// pathParamDocs, description-only), so `in dOp.params` is exactly
|
|
2433
|
+
// "agent-suppliable" — a docs-only params.<name>.description entry
|
|
2434
|
+
// stays legal.
|
|
2435
|
+
// - a name in NO op's path as {name} → declared-but-unused (typo).
|
|
2436
|
+
// - a name shared with secretQueryRefs — would inject one secret into
|
|
2437
|
+
// the path and another into the query under the same name.
|
|
2438
|
+
if (auth.kind === "static-key" && auth.secretPathRefs) {
|
|
2439
|
+
for (const paramName of Object.keys(auth.secretPathRefs)) {
|
|
2440
|
+
if (auth.secretQueryRefs && paramName in auth.secretQueryRefs) {
|
|
2441
|
+
return fail(
|
|
2442
|
+
file,
|
|
2443
|
+
`auth.secretPathRefs.${paramName}`,
|
|
2444
|
+
"a path-token name not shared with secretQueryRefs",
|
|
2445
|
+
`also a secretQueryRefs key`,
|
|
2446
|
+
{
|
|
2447
|
+
fix: `"${paramName}" is declared in both secretPathRefs and secretQueryRefs — one would fill it in the path and the other in the query under the same name. Rename one.`,
|
|
2448
|
+
},
|
|
2449
|
+
);
|
|
2450
|
+
}
|
|
2451
|
+
for (const dOp of operations) {
|
|
2452
|
+
if (paramName in dOp.params) {
|
|
2453
|
+
return fail(
|
|
2454
|
+
file,
|
|
2455
|
+
`auth.secretPathRefs.${paramName}`,
|
|
2456
|
+
"a path-token name not declared in any operation's params",
|
|
2457
|
+
`also a param of operation "${dOp.name}"`,
|
|
2458
|
+
{
|
|
2459
|
+
fix: `Remove "${paramName}" from operation "${dOp.name}"'s params map — it is code-injected from the secrets store and the agent must not be able to set it. (A docs-only params.${paramName}.description entry is fine.)`,
|
|
2460
|
+
},
|
|
2461
|
+
);
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
const used = operations.some((dOp) => dOp.pathParams.includes(paramName));
|
|
2465
|
+
if (!used) {
|
|
2466
|
+
return fail(
|
|
2467
|
+
file,
|
|
2468
|
+
`auth.secretPathRefs.${paramName}`,
|
|
2469
|
+
`a path-token name used by at least one operation's path as {${paramName}}`,
|
|
2470
|
+
"no operation's path contains {" + paramName + "}",
|
|
2471
|
+
{
|
|
2472
|
+
fix: `Use {${paramName}} in at least one operation's path, or remove the secretPathRefs entry (declared-but-unused is usually a typo).`,
|
|
2473
|
+
},
|
|
2474
|
+
);
|
|
2475
|
+
}
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
|
|
1563
2479
|
const guide: ApiGuide = {
|
|
1564
2480
|
content,
|
|
1565
2481
|
updated,
|
|
@@ -1584,191 +2500,8 @@ export function parseApiGuide(
|
|
|
1584
2500
|
return { ok: true, guide };
|
|
1585
2501
|
}
|
|
1586
2502
|
|
|
1587
|
-
// ═══════════════════════════════════════════════════════════════════
|
|
1588
|
-
// projectToGuide — strips recipe fields, keeps presentation + kind
|
|
1589
|
-
// ═══════════════════════════════════════════════════════════════════
|
|
1590
|
-
|
|
1591
|
-
export function projectToGuide(guide: ApiGuide): Guide {
|
|
1592
|
-
const projection: Guide = {
|
|
1593
|
-
content: guide.content,
|
|
1594
|
-
updated: guide.updated,
|
|
1595
|
-
category: guide.category,
|
|
1596
|
-
source: guide.source,
|
|
1597
|
-
icon: guide.icon,
|
|
1598
|
-
shortName: guide.shortName,
|
|
1599
|
-
kind: guide.kind,
|
|
1600
|
-
...(guide.domains ? { domains: guide.domains } : {}),
|
|
1601
|
-
};
|
|
1602
|
-
return projection;
|
|
1603
|
-
}
|
|
1604
|
-
|
|
1605
|
-
// ═══════════════════════════════════════════════════════════════════
|
|
1606
|
-
// Directory loader — one malformed guide doesn't block the store.
|
|
1607
|
-
//
|
|
1608
|
-
// Loads from per-guide subdirectories: <dir>/<slug(shortName)>/guide.md.
|
|
1609
|
-
// The folder name must equal slug(shortName) — a divergent folder routes to
|
|
1610
|
-
// malformed (enforced), so the active set holds at most one guide per
|
|
1611
|
-
// shortName. Flat top-level .md files are not loaded.
|
|
1612
|
-
// ═══════════════════════════════════════════════════════════════════
|
|
1613
|
-
|
|
1614
|
-
/**
|
|
1615
|
-
* Push a malformed guide and warn about it. One helper owns both the catalog
|
|
1616
|
-
* entry and the load-time warn, so every malformed guide — parse
|
|
1617
|
-
* failure, illegal shortName, divergent folder — surfaces the same signal
|
|
1618
|
-
* (and its actionable `fix` when present) instead of being silently
|
|
1619
|
-
* quarantined. Fires once per cached scan, same channel as the duplicate-
|
|
1620
|
-
* shortName check.
|
|
1621
|
-
*/
|
|
1622
|
-
function pushMalformed(
|
|
1623
|
-
result: LoadedApiGuides,
|
|
1624
|
-
file: string,
|
|
1625
|
-
filename: string,
|
|
1626
|
-
error: ParseError,
|
|
1627
|
-
warn: (msg: string) => void,
|
|
1628
|
-
): void {
|
|
1629
|
-
result.malformed.push({ file, filename, error });
|
|
1630
|
-
warn(
|
|
1631
|
-
`⚠ Malformed guide '${filename}': ${error.field} — expected ${error.expected}; found ${error.found}.` +
|
|
1632
|
-
(error.fix ? ` ${error.fix}` : ""),
|
|
1633
|
-
);
|
|
1634
|
-
}
|
|
1635
|
-
|
|
1636
|
-
export function loadApiGuidesFromDir(
|
|
1637
|
-
dir: string,
|
|
1638
|
-
notify?: NotifyFn,
|
|
1639
|
-
): LoadedApiGuides {
|
|
1640
|
-
const result: LoadedApiGuides = { guides: {}, malformed: [] };
|
|
1641
|
-
if (!existsSync(dir)) return result;
|
|
1642
|
-
let entries: string[];
|
|
1643
|
-
try {
|
|
1644
|
-
entries = readdirSync(dir);
|
|
1645
|
-
} catch {
|
|
1646
|
-
return result;
|
|
1647
|
-
}
|
|
1648
|
-
// Scan-local duplicate-shortName tracker (migration-window check only).
|
|
1649
|
-
// shortName → the first folder that declared it, so the duplicate warning
|
|
1650
|
-
// can name both folders. Not a field on LoadedApiGuides.
|
|
1651
|
-
const seenShortNames = new Map<string, string>();
|
|
1652
|
-
|
|
1653
|
-
// Every load-time diagnostic routes through one channel: ctx.ui.notify
|
|
1654
|
-
// when the caller has a UI context (renders via the Text component —
|
|
1655
|
-
// wraps long lines, honors newlines), else console.warn. One fallback
|
|
1656
|
-
// here, not one repeated per call site.
|
|
1657
|
-
const warn = (msg: string) => {
|
|
1658
|
-
if (notify) notify(msg, "warning");
|
|
1659
|
-
else console.warn(msg);
|
|
1660
|
-
};
|
|
1661
|
-
|
|
1662
|
-
// TODO(0.5.0): remove — migration banner for the 0.4.0 folder-structure
|
|
1663
|
-
// change only. The permanent divergence + illegal-shortName checks below
|
|
1664
|
-
// stay; only this prelude and the duplicate-shortName check are 0.5.0
|
|
1665
|
-
// deletions. Fires once, immediately before the first identity warning, so
|
|
1666
|
-
// it prepends the wall of migration warnings with the agent instructions.
|
|
1667
|
-
let bannerEmitted = false;
|
|
1668
|
-
const emitMigrationBanner = () => {
|
|
1669
|
-
if (bannerEmitted) return;
|
|
1670
|
-
bannerEmitted = true;
|
|
1671
|
-
const msg =
|
|
1672
|
-
`\n⚠ pi-lean-host 0.4.0 changed the guide folder structure: each guide must now live ` +
|
|
1673
|
-
`in a folder named slug(shortName). Pass the warnings below to the ` +
|
|
1674
|
-
`agent to fix them (rename the folder or set a valid shortName), then /reload.\n`;
|
|
1675
|
-
warn(msg);
|
|
1676
|
-
};
|
|
1677
|
-
for (const entry of entries) {
|
|
1678
|
-
const entryPath = join(dir, entry);
|
|
1679
|
-
try {
|
|
1680
|
-
if (!statSync(entryPath).isDirectory()) continue;
|
|
1681
|
-
} catch {
|
|
1682
|
-
continue;
|
|
1683
|
-
}
|
|
1684
|
-
const guidePath = join(entryPath, "guide.md");
|
|
1685
|
-
try {
|
|
1686
|
-
if (!statSync(guidePath).isFile()) continue;
|
|
1687
|
-
} catch {
|
|
1688
|
-
continue;
|
|
1689
|
-
}
|
|
1690
|
-
const name = entry; // folder name = slug(shortName) in steady state
|
|
1691
|
-
let raw: string;
|
|
1692
|
-
try {
|
|
1693
|
-
raw = readFileSync(guidePath, "utf-8");
|
|
1694
|
-
} catch {
|
|
1695
|
-
continue;
|
|
1696
|
-
}
|
|
1697
|
-
const parsed = parseApiGuide(raw, {
|
|
1698
|
-
file: guidePath,
|
|
1699
|
-
filename: name,
|
|
1700
|
-
});
|
|
1701
|
-
if (parsed.ok) {
|
|
1702
|
-
const guide = parsed.guide;
|
|
1703
|
-
// Illegal-shortName + divergence checks (permanent). One try/catch
|
|
1704
|
-
// owns the slug() call: a throw (empty or all-symbol shortName) is
|
|
1705
|
-
// routed to malformed, never escaped. This wrapping lives in the
|
|
1706
|
-
// permanent checks so the loader stays safe after the 0.5.0
|
|
1707
|
-
// duplicate-check deletion.
|
|
1708
|
-
let slugged: string;
|
|
1709
|
-
try {
|
|
1710
|
-
slugged = slug(guide.shortName);
|
|
1711
|
-
} catch {
|
|
1712
|
-
emitMigrationBanner();
|
|
1713
|
-
pushMalformed(
|
|
1714
|
-
result,
|
|
1715
|
-
guidePath,
|
|
1716
|
-
name,
|
|
1717
|
-
{
|
|
1718
|
-
field: "shortName",
|
|
1719
|
-
expected: "a shortName that slugs to a non-empty safe directory name",
|
|
1720
|
-
found: `"${guide.shortName}"`,
|
|
1721
|
-
fix: "Set a valid shortName (lowercase letters, digits, and '-') in the guide's frontmatter.",
|
|
1722
|
-
},
|
|
1723
|
-
warn,
|
|
1724
|
-
);
|
|
1725
|
-
continue;
|
|
1726
|
-
}
|
|
1727
|
-
// TODO(0.5.0): remove — save-time slug() makes duplicate shortNames
|
|
1728
|
-
// unreachable once all folders are migrated. Tracked on guides that
|
|
1729
|
-
// pass the slug (before divergence routing) so the migration window —
|
|
1730
|
-
// two divergent folders sharing a valid shortName — still surfaces a
|
|
1731
|
-
// clear "delete one" warning instead of two opaque malformed entries.
|
|
1732
|
-
const first = seenShortNames.get(guide.shortName);
|
|
1733
|
-
if (first === undefined) {
|
|
1734
|
-
seenShortNames.set(guide.shortName, entry);
|
|
1735
|
-
} else {
|
|
1736
|
-
emitMigrationBanner();
|
|
1737
|
-
const dupMsg =
|
|
1738
|
-
`⚠ Duplicate shortName '${guide.shortName}' in folders '${first}' and '${entry}'. ` +
|
|
1739
|
-
`Delete one: /api delete <one>`;
|
|
1740
|
-
warn(dupMsg);
|
|
1741
|
-
}
|
|
1742
|
-
// Divergence check (permanent) — ENFORCED, not advisory: the folder
|
|
1743
|
-
// name must equal slug(shortName); the coupling IS the identity. A
|
|
1744
|
-
// divergent guide routes to malformed (never loads), so the active
|
|
1745
|
-
// set structurally holds at most one guide per shortName.
|
|
1746
|
-
if (entry !== slugged) {
|
|
1747
|
-
emitMigrationBanner();
|
|
1748
|
-
pushMalformed(
|
|
1749
|
-
result,
|
|
1750
|
-
guidePath,
|
|
1751
|
-
name,
|
|
1752
|
-
{
|
|
1753
|
-
field: "shortName",
|
|
1754
|
-
expected: `a folder named slug(shortName) ('${slugged}')`,
|
|
1755
|
-
found: `folder '${entry}'`,
|
|
1756
|
-
fix: `Rename the folder to '${slugged}': mv ${entryPath} ${join(dir, slugged)}`,
|
|
1757
|
-
},
|
|
1758
|
-
warn,
|
|
1759
|
-
);
|
|
1760
|
-
continue;
|
|
1761
|
-
}
|
|
1762
|
-
result.guides[entry] = guide;
|
|
1763
|
-
} else {
|
|
1764
|
-
pushMalformed(result, guidePath, name, parsed.error, warn);
|
|
1765
|
-
}
|
|
1766
|
-
}
|
|
1767
|
-
return result;
|
|
1768
|
-
}
|
|
1769
|
-
|
|
1770
2503
|
// ════════════════════════════════════════════════════════════════════
|
|
1771
|
-
// Schema-version staleness —
|
|
2504
|
+
// Schema-version staleness — the hard gate's predicate
|
|
1772
2505
|
// ════════════════════════════════════════════════════════════════════
|
|
1773
2506
|
|
|
1774
2507
|
/**
|
|
@@ -1782,205 +2515,3 @@ export function isStaleSchema(
|
|
|
1782
2515
|
): boolean {
|
|
1783
2516
|
return guideSchemaVersion < currentSchemaVersion;
|
|
1784
2517
|
}
|
|
1785
|
-
|
|
1786
|
-
/**
|
|
1787
|
-
* Non-blocking stale-schema warning line for a guide, or undefined when the
|
|
1788
|
-
* guide is current. Peer of the `⚠ malformed` catalog line — detection,
|
|
1789
|
-
* never a gate (the guide still loads and runs). `current` defaults to
|
|
1790
|
-
* GUIDE_SCHEMA_VERSION; tests pass a bumped value to force staleness.
|
|
1791
|
-
*/
|
|
1792
|
-
export function staleSchemaLine(
|
|
1793
|
-
guide: ApiGuide,
|
|
1794
|
-
current: number = GUIDE_SCHEMA_VERSION,
|
|
1795
|
-
): string | undefined {
|
|
1796
|
-
const v = guide.schemaVersion ?? 0;
|
|
1797
|
-
if (!isStaleSchema(v, current)) return undefined;
|
|
1798
|
-
return ` ⚠ schemaVersion ${v} < current ${current} — guide may need updating`;
|
|
1799
|
-
}
|
|
1800
|
-
|
|
1801
|
-
// ════════════════════════════════════════════════════════════════════
|
|
1802
|
-
// Disambiguation helpers — shared by the api-guide menu and the
|
|
1803
|
-
// api-fetch ambiguous-operation error. One rendering of the per-guide
|
|
1804
|
-
// listing so the two surfaces stay visually consistent.
|
|
1805
|
-
// ════════════════════════════════════════════════════════════════════
|
|
1806
|
-
|
|
1807
|
-
/**
|
|
1808
|
-
* Truncated op-name summary for disambiguation surfaces:
|
|
1809
|
-
* "N ops: a, b, c, d, e, +K more" (first 5 names, then the remaining count).
|
|
1810
|
-
* A 50-op guide must not dump 50 names into context — the menu exists to
|
|
1811
|
-
* help pick a guide cheaply; the full op list is one api-guide call away.
|
|
1812
|
-
*/
|
|
1813
|
-
function formatOpSummary(ops: { name: string }[]): string {
|
|
1814
|
-
const names = ops.map((o) => o.name);
|
|
1815
|
-
const count = names.length;
|
|
1816
|
-
const head = names.slice(0, 5);
|
|
1817
|
-
const remaining = count - head.length;
|
|
1818
|
-
const tail = remaining > 0 ? `, +${remaining} more` : "";
|
|
1819
|
-
return `${count} ops: ${head.join(", ")}${tail}`;
|
|
1820
|
-
}
|
|
1821
|
-
|
|
1822
|
-
/**
|
|
1823
|
-
* Per-guide listing lines for a disambiguation surface (the api-guide
|
|
1824
|
-
* multi-guide menu and the api-fetch ambiguous-op error). Each entry:
|
|
1825
|
-
* `icon shortName` [+ ` — description` when present] then the truncated
|
|
1826
|
-
* op-name list. When `description:` is absent the line falls back to
|
|
1827
|
-
* shortName + op names only (the status-quo shape), so un-backfilled
|
|
1828
|
-
* guides render consistently with those that have a one-line summary.
|
|
1829
|
-
*/
|
|
1830
|
-
export function formatGuideListings(
|
|
1831
|
-
entries: { guide: ApiGuide }[],
|
|
1832
|
-
current: number = GUIDE_SCHEMA_VERSION,
|
|
1833
|
-
): string {
|
|
1834
|
-
const lines: string[] = [];
|
|
1835
|
-
for (const { guide } of entries) {
|
|
1836
|
-
lines.push(
|
|
1837
|
-
` ${guide.icon} ${guide.shortName}` +
|
|
1838
|
-
(guide.description ? ` — ${guide.description}` : ""),
|
|
1839
|
-
);
|
|
1840
|
-
lines.push(` ${formatOpSummary(guide.operations)}`);
|
|
1841
|
-
const stale = staleSchemaLine(guide, current);
|
|
1842
|
-
if (stale) lines.push(stale);
|
|
1843
|
-
}
|
|
1844
|
-
return lines.join("\n");
|
|
1845
|
-
}
|
|
1846
|
-
|
|
1847
|
-
/**
|
|
1848
|
-
* Resolve a guide by shortName across a domain's matches (exact,
|
|
1849
|
-
* case-insensitive). Shared by api-guide, api-learn's fetch-recipe, and
|
|
1850
|
-
* /api verify — three call sites, one resolution rule (a drifted copy would
|
|
1851
|
-
* ship a known second bug). Returns a structured outcome; each caller renders
|
|
1852
|
-
* its own message (tool result vs command notify).
|
|
1853
|
-
*/
|
|
1854
|
-
export function selectGuideByShortName(
|
|
1855
|
-
matches: { guide: ApiGuide; dirName: string }[],
|
|
1856
|
-
selector: string,
|
|
1857
|
-
):
|
|
1858
|
-
| { ok: true; guide: ApiGuide; dirName: string }
|
|
1859
|
-
| { ok: false; reason: "no_match"; valid: string[] }
|
|
1860
|
-
| { ok: false; reason: "ambiguous"; directories: string[] } {
|
|
1861
|
-
const lc = selector.toLowerCase();
|
|
1862
|
-
const sel = matches.filter((m) => m.guide.shortName.toLowerCase() === lc);
|
|
1863
|
-
if (sel.length === 0) {
|
|
1864
|
-
return {
|
|
1865
|
-
ok: false,
|
|
1866
|
-
reason: "no_match",
|
|
1867
|
-
valid: matches.map((m) => m.guide.shortName),
|
|
1868
|
-
};
|
|
1869
|
-
}
|
|
1870
|
-
if (sel.length > 1) {
|
|
1871
|
-
return {
|
|
1872
|
-
ok: false,
|
|
1873
|
-
reason: "ambiguous",
|
|
1874
|
-
directories: sel.map((s) => s.dirName),
|
|
1875
|
-
};
|
|
1876
|
-
}
|
|
1877
|
-
return { ok: true, guide: sel[0]!.guide, dirName: sel[0]!.dirName };
|
|
1878
|
-
}
|
|
1879
|
-
|
|
1880
|
-
/**
|
|
1881
|
-
* Render the no-match / ambiguous error text for a failed
|
|
1882
|
-
* `selectGuideByShortName` result. `callToAction` is the trailing
|
|
1883
|
-
* "how to see the menu" sentence — it differs per surface (tool vs
|
|
1884
|
-
* command), so callers pass their own.
|
|
1885
|
-
*/
|
|
1886
|
-
export function shortNameErrorText(
|
|
1887
|
-
sel: Extract<ReturnType<typeof selectGuideByShortName>, { ok: false }>,
|
|
1888
|
-
domain: string,
|
|
1889
|
-
selector: string,
|
|
1890
|
-
callToAction: string,
|
|
1891
|
-
): string {
|
|
1892
|
-
if (sel.reason === "no_match") {
|
|
1893
|
-
return (
|
|
1894
|
-
`No guide named '${selector}' for '${domain}'. ` +
|
|
1895
|
-
`Available guides: ${sel.valid.join(", ")}. ` +
|
|
1896
|
-
callToAction
|
|
1897
|
-
);
|
|
1898
|
-
}
|
|
1899
|
-
return (
|
|
1900
|
-
`Ambiguous guide '${selector}' for '${domain}' — ` +
|
|
1901
|
-
`${sel.directories.length} guides share shortName '${selector}' ` +
|
|
1902
|
-
`(directories: ${sel.directories.join(", ")}). Rename one guide's shortName to ` +
|
|
1903
|
-
`disambiguate. ` +
|
|
1904
|
-
callToAction
|
|
1905
|
-
);
|
|
1906
|
-
}
|
|
1907
|
-
|
|
1908
|
-
// ════════════════════════════════════════════════════════════════════
|
|
1909
|
-
// Catalog rendering — healthy + ⚠ malformed together
|
|
1910
|
-
//
|
|
1911
|
-
// Base catalog is collapsed by `organization:`: one line per org with its
|
|
1912
|
-
// guide count and domain set. Guides without `organization:` fall back to
|
|
1913
|
-
// the per-guide line, so the un-backfilled corpus renders unchanged (no
|
|
1914
|
-
// forced migration). Op counts live on the per-domain disambiguation menu
|
|
1915
|
-
// (api-guide {domain}), where they're useful for picking a guide — not
|
|
1916
|
-
// here, where they'd bloat context for orgs with many guides.
|
|
1917
|
-
// ════════════════════════════════════════════════════════════════════
|
|
1918
|
-
|
|
1919
|
-
export function formatApiGuideCatalog(
|
|
1920
|
-
loaded: LoadedApiGuides,
|
|
1921
|
-
current: number = GUIDE_SCHEMA_VERSION,
|
|
1922
|
-
): string {
|
|
1923
|
-
const lines: string[] = ["API guides:"];
|
|
1924
|
-
|
|
1925
|
-
// Org-grouped rows preserve first-appearance order; guides without
|
|
1926
|
-
// organization fall back to the per-guide line (no forced migration).
|
|
1927
|
-
const orgRows: { org: string; guides: ApiGuide[] }[] = [];
|
|
1928
|
-
const orgIndex = new Map<string, number>();
|
|
1929
|
-
const orgless: { name: string; guide: ApiGuide }[] = [];
|
|
1930
|
-
for (const [name, guide] of Object.entries(loaded.guides)) {
|
|
1931
|
-
if (guide.organization) {
|
|
1932
|
-
const idx = orgIndex.get(guide.organization);
|
|
1933
|
-
if (idx === undefined) {
|
|
1934
|
-
orgIndex.set(guide.organization, orgRows.length);
|
|
1935
|
-
orgRows.push({ org: guide.organization, guides: [guide] });
|
|
1936
|
-
} else {
|
|
1937
|
-
orgRows[idx]!.guides.push(guide);
|
|
1938
|
-
}
|
|
1939
|
-
} else {
|
|
1940
|
-
orgless.push({ name, guide });
|
|
1941
|
-
}
|
|
1942
|
-
}
|
|
1943
|
-
|
|
1944
|
-
for (const row of orgRows) {
|
|
1945
|
-
const domains = new Set<string>();
|
|
1946
|
-
for (const g of row.guides) {
|
|
1947
|
-
for (const d of g.domains ?? []) domains.add(d);
|
|
1948
|
-
}
|
|
1949
|
-
const domList = domains.size > 0 ? [...domains].join(", ") : "—";
|
|
1950
|
-
const n = row.guides.length;
|
|
1951
|
-
// Collapsed org row: a trailing ⚠ glyph when ANY guide in it is stale
|
|
1952
|
-
// (hint only — the per-guide ⚠ line lives on the menu / detail view).
|
|
1953
|
-
const stale = row.guides.some((g) =>
|
|
1954
|
-
isStaleSchema(g.schemaVersion ?? 0, current),
|
|
1955
|
-
);
|
|
1956
|
-
lines.push(
|
|
1957
|
-
` 🏛️ ${row.org} — ${n} guide${n > 1 ? "s" : ""} (${domList})${stale ? " ⚠" : ""}`,
|
|
1958
|
-
);
|
|
1959
|
-
}
|
|
1960
|
-
for (const { name, guide } of orgless) {
|
|
1961
|
-
const domains =
|
|
1962
|
-
guide.domains && guide.domains.length > 0 ? guide.domains.join(", ") : name;
|
|
1963
|
-
lines.push(
|
|
1964
|
-
` ${guide.icon} ${guide.shortName} — ${domains} (verified ${guide.verified}, ${guide.operations.length} ops)`,
|
|
1965
|
-
);
|
|
1966
|
-
const stale = staleSchemaLine(guide, current);
|
|
1967
|
-
if (stale) lines.push(stale);
|
|
1968
|
-
}
|
|
1969
|
-
for (const mal of loaded.malformed) {
|
|
1970
|
-
lines.push(
|
|
1971
|
-
` ⚠ malformed — ${mal.filename}: ${mal.error.field} — expected ${mal.error.expected}; found ${mal.error.found}`,
|
|
1972
|
-
);
|
|
1973
|
-
// Actionable advice on its own line, matching api-fetch/api-learn's
|
|
1974
|
-
// `Fix:` convention — multi-line fixes (e.g. the frontmatter template)
|
|
1975
|
-
// render naturally instead of being inlined into the summary line.
|
|
1976
|
-
if (mal.error.fix) lines.push(` fix: ${mal.error.fix}`);
|
|
1977
|
-
}
|
|
1978
|
-
if (Object.keys(loaded.guides).length === 0 && loaded.malformed.length === 0) {
|
|
1979
|
-
lines.push(" (no guides — call api-learn({domain, dir}) to author one)");
|
|
1980
|
-
}
|
|
1981
|
-
lines.push("");
|
|
1982
|
-
lines.push(
|
|
1983
|
-
'Call api-guide({domain: "<name>"}) for detail. Multiple guides for a domain show a disambiguation menu.',
|
|
1984
|
-
);
|
|
1985
|
-
return lines.join("\n");
|
|
1986
|
-
}
|