pi-lean-host 0.2.1 → 0.3.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 +66 -89
- package/core/api-guide-types.ts +9 -0
- package/core/api-toggle.ts +23 -1
- package/core/delete-command.ts +190 -0
- package/core/guide-picker.ts +104 -0
- package/core/helpers-command.ts +2 -4
- package/core/helpers.ts +28 -0
- package/core/parse-api-guide.ts +373 -23
- package/core/resolve-op.ts +222 -0
- package/core/transport.ts +1 -1
- package/core/verify-command.ts +399 -0
- package/package.json +5 -1
- package/tools/api-fetch.ts +148 -228
- package/tools/api-guide.ts +32 -37
- package/tools/api-learn.ts +431 -115
- package/tools/api-probe.ts +266 -45
package/core/helpers.ts
CHANGED
|
@@ -170,6 +170,26 @@ function buildQueryParams(
|
|
|
170
170
|
}
|
|
171
171
|
}
|
|
172
172
|
|
|
173
|
+
// At-least-one-of constraint: at least one group member must be supplied.
|
|
174
|
+
// Members can't be `required` or carry a `default` (parser-enforced), so
|
|
175
|
+
// this is the only guard the group needs — same fail-closed seam as the
|
|
176
|
+
// per-param `required` check above. Both api-fetch and /api verify route
|
|
177
|
+
// through here (resolveOpForExecution → restGet/paginate), so one guard
|
|
178
|
+
// covers both call sites.
|
|
179
|
+
if (operation.requiresAnyOf && operation.requiresAnyOf.length > 0) {
|
|
180
|
+
const satisfied = operation.requiresAnyOf.some(
|
|
181
|
+
(name) => params[name] !== undefined,
|
|
182
|
+
);
|
|
183
|
+
if (!satisfied) {
|
|
184
|
+
throw new HelperError(
|
|
185
|
+
"params.requiresAnyOf",
|
|
186
|
+
`Missing one of: ${operation.requiresAnyOf.join(", ")}`,
|
|
187
|
+
`at least one of: ${operation.requiresAnyOf.join(", ")}`,
|
|
188
|
+
"none supplied",
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
173
193
|
// `passthrough`: forward caller-supplied params not declared in the
|
|
174
194
|
// recipe's `params` map onto the query string as-is. For APIs with an
|
|
175
195
|
// open param surface (Infogami /query.json flat form, CKAN, OAI-PMH)
|
|
@@ -219,7 +239,11 @@ export function normalizeDateParam(
|
|
|
219
239
|
/**
|
|
220
240
|
* Resolve a simple dot-delimited JSON path against an object.
|
|
221
241
|
* Supports `data.items`, `resultados[0].campo`, `$.items` prefix.
|
|
242
|
+
*
|
|
243
|
+
* Returns `unknown` by design — the value at an arbitrary JSON path has no
|
|
244
|
+
* named domain type until the caller knows the path they asked for.
|
|
222
245
|
*/
|
|
246
|
+
// pi-lens-ignore: ast-grep:no-unknown-returns
|
|
223
247
|
export function resolveJsonPath(obj: unknown, path: string): unknown {
|
|
224
248
|
// Normalise: strip leading $ or $., convert bracket notation.
|
|
225
249
|
const normalised = path
|
|
@@ -267,10 +291,14 @@ const xmlParser = new XMLParser({
|
|
|
267
291
|
* header charset wins). `parseResponse` itself does no decoding — the
|
|
268
292
|
* `charset` field is consumed by the transport, not here.
|
|
269
293
|
*
|
|
294
|
+
* Returns `unknown` by design — an arbitrary API response body has no named
|
|
295
|
+
* domain type; callers resolve JSON paths or run transforms against it.
|
|
296
|
+
*
|
|
270
297
|
* @param body The response body string (correctly decoded).
|
|
271
298
|
* @param shape The response shape (format dictates XML vs JSON parsing).
|
|
272
299
|
* @returns Parsed JSON value or XML-converted object.
|
|
273
300
|
*/
|
|
301
|
+
// pi-lens-ignore: ast-grep:no-unknown-returns
|
|
274
302
|
export function parseResponse(body: string, shape: ResponseShape): unknown {
|
|
275
303
|
if (shape.format === "text") {
|
|
276
304
|
// Raw passthrough — returned as-is, no trim (matches xml/json branches).
|
package/core/parse-api-guide.ts
CHANGED
|
@@ -15,6 +15,7 @@ import type { Guide } from "./guide-loader.js";
|
|
|
15
15
|
import { extractPathTokens } from "./path-template.js";
|
|
16
16
|
import {
|
|
17
17
|
GATHER_ALL_MAX_FALLBACK,
|
|
18
|
+
GUIDE_SCHEMA_VERSION,
|
|
18
19
|
KNOWN_AUTH_KINDS,
|
|
19
20
|
type ApiGuide,
|
|
20
21
|
type DateParamFormat,
|
|
@@ -43,6 +44,42 @@ const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/;
|
|
|
43
44
|
|
|
44
45
|
export const TODAY = () => new Date().toISOString().slice(0, 10);
|
|
45
46
|
|
|
47
|
+
/**
|
|
48
|
+
* Line-level frontmatter stamp — replace (or insert) a single `key: value`
|
|
49
|
+
* line inside the isolated frontmatter block, preserving comments and key
|
|
50
|
+
* order (no YAML round-trip — a round-trip reformats and strips comments).
|
|
51
|
+
* Used by api-learn (schemaVersion save-stamp) and /api verify (verified
|
|
52
|
+
* stamp). Returns the document unchanged when it has no frontmatter block.
|
|
53
|
+
*/
|
|
54
|
+
export function stampFrontmatterField(
|
|
55
|
+
raw: string,
|
|
56
|
+
key: string,
|
|
57
|
+
value: string,
|
|
58
|
+
): string {
|
|
59
|
+
const match = raw.match(FRONTMATTER_RE);
|
|
60
|
+
if (!match) return raw;
|
|
61
|
+
const fm = match[1] ?? "";
|
|
62
|
+
const content = match[2] ?? "";
|
|
63
|
+
const nl = /^---(\r?\n)/.exec(raw)?.[1] ?? "\n";
|
|
64
|
+
const lines = fm.split(nl);
|
|
65
|
+
const keyRe = new RegExp(`^${key}:\\s*.+$`);
|
|
66
|
+
const idx = lines.findIndex((l) => keyRe.test(l));
|
|
67
|
+
const line = `${key}: ${value}`;
|
|
68
|
+
if (idx === -1) {
|
|
69
|
+
// Insert-only separation: a new key would land flush against the
|
|
70
|
+
// preceding line (e.g. under the last op's params block). Push a
|
|
71
|
+
// blank line first when the preceding line is non-empty. Replace
|
|
72
|
+
// must NOT do this — every /api verify re-stamp would drift the file.
|
|
73
|
+
if (lines.length > 0 && lines.at(-1)?.trim() !== "") {
|
|
74
|
+
lines.push("");
|
|
75
|
+
}
|
|
76
|
+
lines.push(line);
|
|
77
|
+
} else {
|
|
78
|
+
lines[idx] = line;
|
|
79
|
+
}
|
|
80
|
+
return `---${nl}${lines.join(nl)}${nl}---${nl}${content}`;
|
|
81
|
+
}
|
|
82
|
+
|
|
46
83
|
const VALID_VIA: ReadonlySet<string> = new Set(["restGet", "paginate"]);
|
|
47
84
|
// accept is a free-form string — any media type is valid (`json`/`xml`
|
|
48
85
|
// shorthands are mapped by the helper).
|
|
@@ -61,6 +98,23 @@ const VALID_PAGINATION_STYLE: ReadonlySet<string> = new Set([
|
|
|
61
98
|
"tokenBag",
|
|
62
99
|
]);
|
|
63
100
|
|
|
101
|
+
// Strict auth schema (gap 1): the only keys validateAuth reads. Any other key
|
|
102
|
+
// under `auth` is rejected at parse — the parser used to silently drop
|
|
103
|
+
// unknowns, so a wrong-but-plausible shape (e.g. `name`/`secret`) saved a
|
|
104
|
+
// guide the executor then silently couldn't honor.
|
|
105
|
+
const KNOWN_AUTH_KEYS: ReadonlySet<string> = new Set([
|
|
106
|
+
"kind",
|
|
107
|
+
"headers",
|
|
108
|
+
"secretRefs",
|
|
109
|
+
"secretQueryRefs",
|
|
110
|
+
"requires",
|
|
111
|
+
"optional",
|
|
112
|
+
"headerPrefixes",
|
|
113
|
+
]);
|
|
114
|
+
// Set insertion order — used to render the known-key list in error strings
|
|
115
|
+
// (expected + fallback fix) so they can't drift from the set.
|
|
116
|
+
const KNOWN_AUTH_KEYS_LIST = [...KNOWN_AUTH_KEYS].join(", ");
|
|
117
|
+
|
|
64
118
|
// ═══════════════════════════════════════════════════════════════════
|
|
65
119
|
// Error helper
|
|
66
120
|
// ═══════════════════════════════════════════════════════════════════
|
|
@@ -156,10 +210,13 @@ function requireStringArray(
|
|
|
156
210
|
key: string,
|
|
157
211
|
file: string | undefined,
|
|
158
212
|
fm: string,
|
|
213
|
+
opts?: { missingFix?: string },
|
|
159
214
|
): string[] | ParseApiGuideResult {
|
|
160
215
|
const v = m[key];
|
|
161
216
|
if (v === undefined) {
|
|
162
|
-
return fail(file, key, "a list of strings", "missing"
|
|
217
|
+
return fail(file, key, "a list of strings", "missing", {
|
|
218
|
+
...(opts?.missingFix ? { fix: opts.missingFix } : {}),
|
|
219
|
+
});
|
|
163
220
|
}
|
|
164
221
|
if (!Array.isArray(v) || v.length === 0) {
|
|
165
222
|
return fail(file, key, "a non-empty list of strings", describeFound(v), {
|
|
@@ -431,6 +488,65 @@ function isParseErr<T>(v: T | ParseApiGuideResult): v is ParseApiGuideResult {
|
|
|
431
488
|
);
|
|
432
489
|
}
|
|
433
490
|
|
|
491
|
+
/** Levenshtein edit distance — spots near-miss auth keys (e.g. `requiers:` →
|
|
492
|
+
* `requires`) so the unknown-key error can say "did you mean X?" instead of a
|
|
493
|
+
* bare rejection. */
|
|
494
|
+
function editDistance(a: string, b: string): number {
|
|
495
|
+
const m = a.length;
|
|
496
|
+
const n = b.length;
|
|
497
|
+
if (m === 0) return n;
|
|
498
|
+
if (n === 0) return m;
|
|
499
|
+
let prev = Array.from({ length: n + 1 }, (_, j) => j);
|
|
500
|
+
for (let i = 1; i <= m; i++) {
|
|
501
|
+
const cur = new Array<number>(n + 1);
|
|
502
|
+
cur[0] = i;
|
|
503
|
+
for (let j = 1; j <= n; j++) {
|
|
504
|
+
cur[j] = Math.min(
|
|
505
|
+
prev[j]! + 1,
|
|
506
|
+
cur[j - 1]! + 1,
|
|
507
|
+
prev[j - 1]! + (a[i - 1] === b[j - 1] ? 0 : 1),
|
|
508
|
+
);
|
|
509
|
+
}
|
|
510
|
+
prev = cur;
|
|
511
|
+
}
|
|
512
|
+
return prev[n]!;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Nearest known auth key within edit distance ≤ 2, or undefined. */
|
|
516
|
+
function nearestKnownKey(
|
|
517
|
+
key: string,
|
|
518
|
+
known: ReadonlySet<string>,
|
|
519
|
+
): string | undefined {
|
|
520
|
+
let best: string | undefined;
|
|
521
|
+
let bestDist = Infinity;
|
|
522
|
+
for (const k of known) {
|
|
523
|
+
const d = editDistance(key, k);
|
|
524
|
+
if (d < bestDist) {
|
|
525
|
+
bestDist = d;
|
|
526
|
+
best = k;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
return bestDist <= 2 ? best : undefined;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* Adaptive fix for an unknown-auth-key rejection: near-miss → "did you mean
|
|
534
|
+
* X?"; the observed wrong shape (`name`/`secret` under static-key) → point at
|
|
535
|
+
* the real secretRefs/requires shape; anything else → list the known keys.
|
|
536
|
+
*/
|
|
537
|
+
function authUnknownKeyFix(unknownKeys: string[]): string {
|
|
538
|
+
for (const key of unknownKeys) {
|
|
539
|
+
const known = nearestKnownKey(key, KNOWN_AUTH_KEYS);
|
|
540
|
+
if (known !== undefined) {
|
|
541
|
+
return `Unknown auth key "${key}" — did you mean "${known}"?`;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (unknownKeys.includes("name") || unknownKeys.includes("secret")) {
|
|
545
|
+
return `The keyed-header shape is auth.secretRefs: { <header>: <secret-name> } with the secret declared in auth.requires (or auth.optional) — replace name/secret with secretRefs + requires.`;
|
|
546
|
+
}
|
|
547
|
+
return `Unknown auth key(s): ${unknownKeys.join(", ")} — known keys: ${KNOWN_AUTH_KEYS_LIST}.`;
|
|
548
|
+
}
|
|
549
|
+
|
|
434
550
|
function validateAuth(
|
|
435
551
|
raw: unknown,
|
|
436
552
|
file: string | undefined,
|
|
@@ -453,6 +569,9 @@ function validateAuth(
|
|
|
453
569
|
"auth.kind",
|
|
454
570
|
"a string",
|
|
455
571
|
kindRaw === undefined ? "missing" : describeFound(kindRaw),
|
|
572
|
+
{
|
|
573
|
+
fix: "kind is one of: none | static-key — use `kind: none` (public) or `kind: static-key` (keyed header); or call api-learn({domain, new: true}) for a full skeleton",
|
|
574
|
+
},
|
|
456
575
|
);
|
|
457
576
|
}
|
|
458
577
|
if (!KNOWN_AUTH_KINDS.has(kindRaw)) {
|
|
@@ -471,6 +590,25 @@ function validateAuth(
|
|
|
471
590
|
fix: "OAuth2 is not yet implemented. Use kind: none (public) or kind: static-key (keyed header) for now.",
|
|
472
591
|
});
|
|
473
592
|
}
|
|
593
|
+
// Strict auth schema — reject unknown keys (gap 1). The parser used to
|
|
594
|
+
// silently drop unknown keys (a wrong-but-plausible shape like
|
|
595
|
+
// `name`/`secret` saved a guide the executor then silently couldn't
|
|
596
|
+
// honor). Reject, don't infer: the fix is adaptive (near-miss → "did you
|
|
597
|
+
// mean X?", wrong shape → secretRefs/requires).
|
|
598
|
+
const unknownKeys = Object.keys(a).filter((k) => !KNOWN_AUTH_KEYS.has(k));
|
|
599
|
+
if (unknownKeys.length > 0) {
|
|
600
|
+
const first = unknownKeys[0]!;
|
|
601
|
+
return fail(
|
|
602
|
+
file,
|
|
603
|
+
`auth.${first}`,
|
|
604
|
+
`a known auth key (${KNOWN_AUTH_KEYS_LIST})`,
|
|
605
|
+
`unknown key(s): ${unknownKeys.join(", ")}`,
|
|
606
|
+
{
|
|
607
|
+
snippet: snippetFor(fm, "auth"),
|
|
608
|
+
fix: authUnknownKeyFix(unknownKeys),
|
|
609
|
+
},
|
|
610
|
+
);
|
|
611
|
+
}
|
|
474
612
|
// Parse optional headers (per-kind extra headers, e.g. X-Api-Key for DEMO_KEY).
|
|
475
613
|
let headers: Record<string, string> | undefined;
|
|
476
614
|
if (a["headers"] !== undefined) {
|
|
@@ -565,7 +703,8 @@ function validateAuth(
|
|
|
565
703
|
fm,
|
|
566
704
|
"auth.headerPrefixes",
|
|
567
705
|
"a YAML mapping of header name → non-empty prefix string",
|
|
568
|
-
(v) =>
|
|
706
|
+
(v) =>
|
|
707
|
+
typeof v === "string" && v.length > 0 && !/^\{[a-zA-Z0-9_]+\}$/.test(v),
|
|
569
708
|
);
|
|
570
709
|
if (isParseErr(hp)) return hp;
|
|
571
710
|
headerPrefixes = hp;
|
|
@@ -867,6 +1006,76 @@ function validateOperation(
|
|
|
867
1006
|
}
|
|
868
1007
|
}
|
|
869
1008
|
|
|
1009
|
+
// requiresAnyOf — at-least-one-of constraint (one group per op, v1).
|
|
1010
|
+
// Parser cross-field checks, same class as the secretQueryRefs collision
|
|
1011
|
+
// guard: empty-array reject (check #0, before member inspection),
|
|
1012
|
+
// member-exists, path-param reject, no `required: true` overlap, no
|
|
1013
|
+
// `default` on a member. A group member that is `required` would defeat
|
|
1014
|
+
// the group at runtime; a `default` would fire alongside a caller-supplied
|
|
1015
|
+
// sibling (the members are mutually exclusive peers).
|
|
1016
|
+
const requiresAnyOfRaw = o["requiresAnyOf"];
|
|
1017
|
+
let requiresAnyOf: string[] | undefined;
|
|
1018
|
+
if (requiresAnyOfRaw !== undefined) {
|
|
1019
|
+
if (!Array.isArray(requiresAnyOfRaw) || requiresAnyOfRaw.length === 0) {
|
|
1020
|
+
return fail(
|
|
1021
|
+
file,
|
|
1022
|
+
fieldPath("requiresAnyOf"),
|
|
1023
|
+
"a non-empty list of param names",
|
|
1024
|
+
describeFound(requiresAnyOfRaw),
|
|
1025
|
+
);
|
|
1026
|
+
}
|
|
1027
|
+
for (const member of requiresAnyOfRaw) {
|
|
1028
|
+
if (typeof member !== "string" || member === "") {
|
|
1029
|
+
return fail(
|
|
1030
|
+
file,
|
|
1031
|
+
fieldPath("requiresAnyOf"),
|
|
1032
|
+
"a non-empty list of param names",
|
|
1033
|
+
`contains ${describeFound(member)}`,
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
1036
|
+
if (pathParams.includes(member)) {
|
|
1037
|
+
return fail(
|
|
1038
|
+
file,
|
|
1039
|
+
fieldPath(`requiresAnyOf.${member}`),
|
|
1040
|
+
"a query param name (not a path param)",
|
|
1041
|
+
`"${member}" is a path param — path params are always required via {${member}} in path`,
|
|
1042
|
+
);
|
|
1043
|
+
}
|
|
1044
|
+
const spec = params[member];
|
|
1045
|
+
if (spec === undefined) {
|
|
1046
|
+
return fail(
|
|
1047
|
+
file,
|
|
1048
|
+
fieldPath(`requiresAnyOf.${member}`),
|
|
1049
|
+
"a param name declared in this operation's params",
|
|
1050
|
+
`"${member}" is not a declared param`,
|
|
1051
|
+
);
|
|
1052
|
+
}
|
|
1053
|
+
if (spec.required === true) {
|
|
1054
|
+
return fail(
|
|
1055
|
+
file,
|
|
1056
|
+
fieldPath(`requiresAnyOf.${member}`),
|
|
1057
|
+
"a param that is not also required: true",
|
|
1058
|
+
`"${member}" is required: true`,
|
|
1059
|
+
{
|
|
1060
|
+
fix: `Remove required: true from params.${member} — it is governed by the requiresAnyOf group, not per-param required.`,
|
|
1061
|
+
},
|
|
1062
|
+
);
|
|
1063
|
+
}
|
|
1064
|
+
if (spec.default !== undefined) {
|
|
1065
|
+
return fail(
|
|
1066
|
+
file,
|
|
1067
|
+
fieldPath(`requiresAnyOf.${member}`),
|
|
1068
|
+
"a param that does not also declare a default",
|
|
1069
|
+
`"${member}" has a default`,
|
|
1070
|
+
{
|
|
1071
|
+
fix: `Remove the default from params.${member} — requiresAnyOf members are mutually exclusive peers, so a default would fire alongside a caller-supplied sibling.`,
|
|
1072
|
+
},
|
|
1073
|
+
);
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
requiresAnyOf = requiresAnyOfRaw as string[];
|
|
1077
|
+
}
|
|
1078
|
+
|
|
870
1079
|
// dateParams — param name → date format normalization
|
|
871
1080
|
const dateParamsRaw = o["dateParams"];
|
|
872
1081
|
let dateParams: Record<string, DateParamFormat> | undefined;
|
|
@@ -1006,6 +1215,7 @@ function validateOperation(
|
|
|
1006
1215
|
...(transform === undefined ? {} : { transform }),
|
|
1007
1216
|
...(passthrough === undefined ? {} : { passthrough }),
|
|
1008
1217
|
...(dateParams === undefined ? {} : { dateParams }),
|
|
1218
|
+
...(requiresAnyOf === undefined ? {} : { requiresAnyOf }),
|
|
1009
1219
|
...(parseOverride ? { parse: parseOverride } : {}),
|
|
1010
1220
|
...(opPagination ? { pagination: opPagination } : {}),
|
|
1011
1221
|
...(opGatherAllMax === undefined ? {} : { gatherAllMax: opGatherAllMax }),
|
|
@@ -1026,6 +1236,34 @@ export function parseApiGuide(
|
|
|
1026
1236
|
|
|
1027
1237
|
const match = raw.match(FRONTMATTER_RE);
|
|
1028
1238
|
if (!match) {
|
|
1239
|
+
// Opening delimiter present → the failure is on the closing side, not
|
|
1240
|
+
// a missing frontmatter block. Detect the opener with /^---\r?\n/ (not
|
|
1241
|
+
// startsWith("---\n")) so a CRLF-prefixed file is routed here too.
|
|
1242
|
+
if (/^---\r?\n/.test(raw)) {
|
|
1243
|
+
// A `\n---` after the opener means a closer exists but FRONTMATTER_RE
|
|
1244
|
+
// still failed — the closer is malformed (e.g. no trailing newline
|
|
1245
|
+
// at EOF). Otherwise there is no closer at all.
|
|
1246
|
+
if (/\n---/.test(raw.replace(/^---\r?\n/, ""))) {
|
|
1247
|
+
return fail(
|
|
1248
|
+
file,
|
|
1249
|
+
"frontmatter",
|
|
1250
|
+
"a closing --- followed by a newline",
|
|
1251
|
+
"closing --- present but malformed (missing trailing newline after it)",
|
|
1252
|
+
{
|
|
1253
|
+
fix: "Ensure the closing --- is on its own line and followed by a newline before any prose.",
|
|
1254
|
+
},
|
|
1255
|
+
);
|
|
1256
|
+
}
|
|
1257
|
+
return fail(
|
|
1258
|
+
file,
|
|
1259
|
+
"frontmatter",
|
|
1260
|
+
"YAML frontmatter delimited by ---",
|
|
1261
|
+
"missing closing ---",
|
|
1262
|
+
{
|
|
1263
|
+
fix: "Close the frontmatter block with a --- line after the YAML.",
|
|
1264
|
+
},
|
|
1265
|
+
);
|
|
1266
|
+
}
|
|
1029
1267
|
return fail(
|
|
1030
1268
|
file,
|
|
1031
1269
|
"frontmatter",
|
|
@@ -1088,7 +1326,10 @@ export function parseApiGuide(
|
|
|
1088
1326
|
}
|
|
1089
1327
|
const kind = "api";
|
|
1090
1328
|
|
|
1091
|
-
const domainsRes = requireStringArray(m, "domains", file, fm
|
|
1329
|
+
const domainsRes = requireStringArray(m, "domains", file, fm, {
|
|
1330
|
+
missingFix:
|
|
1331
|
+
"Call api-learn({domain: '<domain>', new: true}) — it returns a template with `domains` pre-filled",
|
|
1332
|
+
});
|
|
1092
1333
|
if (!Array.isArray(domainsRes)) return domainsRes;
|
|
1093
1334
|
const domains = domainsRes;
|
|
1094
1335
|
|
|
@@ -1101,7 +1342,7 @@ export function parseApiGuide(
|
|
|
1101
1342
|
// ── recipe slice ──────────────────────────────────────────────
|
|
1102
1343
|
const apiHostRes = requireHttpUrl(m["apiHost"], "apiHost", file, fm, {
|
|
1103
1344
|
protocolFix: "Use https:// as the scheme",
|
|
1104
|
-
invalidFix: "Include the scheme, e.g. https://
|
|
1345
|
+
invalidFix: "Include the scheme, e.g. https://api.example.com/v1",
|
|
1105
1346
|
});
|
|
1106
1347
|
if (typeof apiHostRes !== "string") return apiHostRes;
|
|
1107
1348
|
const apiHost = apiHostRes;
|
|
@@ -1169,22 +1410,22 @@ export function parseApiGuide(
|
|
|
1169
1410
|
description = descriptionRaw;
|
|
1170
1411
|
}
|
|
1171
1412
|
|
|
1172
|
-
// schemaVersion —
|
|
1173
|
-
//
|
|
1174
|
-
//
|
|
1175
|
-
//
|
|
1176
|
-
//
|
|
1177
|
-
|
|
1413
|
+
// schemaVersion — breaking-change detection (design: "schemaVersion is
|
|
1414
|
+
// detection, not enforcement"). Stamped on save by api-learn; absent-on-
|
|
1415
|
+
// read defaults to 0 (the floor), so an unversioned guide flags as
|
|
1416
|
+
// potentially stale after any schema bump rather than silently inheriting
|
|
1417
|
+
// the new current. A valid-integer frontmatter value overrides the floor.
|
|
1418
|
+
// A stale value (< current) warns non-blockingly in the api-guide catalog/
|
|
1419
|
+
// detail and on api-fetch; never gates. A malformed (non-integer/negative)
|
|
1420
|
+
// value falls back to 0 and never rejects a guide.
|
|
1421
|
+
let schemaVersion = 0;
|
|
1178
1422
|
const schemaVersionRaw = m["schemaVersion"];
|
|
1179
|
-
if (
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
schemaVersion = schemaVersionRaw;
|
|
1186
|
-
}
|
|
1187
|
-
// else: tolerated + ignored — metadata stays silent on malformed input.
|
|
1423
|
+
if (
|
|
1424
|
+
typeof schemaVersionRaw === "number" &&
|
|
1425
|
+
Number.isInteger(schemaVersionRaw) &&
|
|
1426
|
+
schemaVersionRaw >= 0
|
|
1427
|
+
) {
|
|
1428
|
+
schemaVersion = schemaVersionRaw;
|
|
1188
1429
|
}
|
|
1189
1430
|
|
|
1190
1431
|
let gatherAllMax = GATHER_ALL_MAX_FALLBACK;
|
|
@@ -1291,7 +1532,7 @@ export function parseApiGuide(
|
|
|
1291
1532
|
...(docs ? { docs } : {}),
|
|
1292
1533
|
...(organization ? { organization } : {}),
|
|
1293
1534
|
...(description ? { description } : {}),
|
|
1294
|
-
|
|
1535
|
+
schemaVersion,
|
|
1295
1536
|
gatherAllMax,
|
|
1296
1537
|
auth,
|
|
1297
1538
|
responseShape,
|
|
@@ -1373,6 +1614,37 @@ export function loadApiGuidesFromDir(dir: string): LoadedApiGuides {
|
|
|
1373
1614
|
return result;
|
|
1374
1615
|
}
|
|
1375
1616
|
|
|
1617
|
+
// ════════════════════════════════════════════════════════════════════
|
|
1618
|
+
// Schema-version staleness — detection, never a gate
|
|
1619
|
+
// ════════════════════════════════════════════════════════════════════
|
|
1620
|
+
|
|
1621
|
+
/**
|
|
1622
|
+
* Pure staleness predicate: a guide is stale when its schemaVersion predates
|
|
1623
|
+
* the current schema (a bump may have broken it). A forward-stamped guide
|
|
1624
|
+
* (authored against a newer schema than the running host) is NOT stale.
|
|
1625
|
+
*/
|
|
1626
|
+
export function isStaleSchema(
|
|
1627
|
+
guideSchemaVersion: number,
|
|
1628
|
+
currentSchemaVersion: number,
|
|
1629
|
+
): boolean {
|
|
1630
|
+
return guideSchemaVersion < currentSchemaVersion;
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
/**
|
|
1634
|
+
* Non-blocking stale-schema warning line for a guide, or undefined when the
|
|
1635
|
+
* guide is current. Peer of the `⚠ malformed` catalog line — detection,
|
|
1636
|
+
* never a gate (the guide still loads and runs). `current` defaults to
|
|
1637
|
+
* GUIDE_SCHEMA_VERSION; tests pass a bumped value to force staleness.
|
|
1638
|
+
*/
|
|
1639
|
+
export function staleSchemaLine(
|
|
1640
|
+
guide: ApiGuide,
|
|
1641
|
+
current: number = GUIDE_SCHEMA_VERSION,
|
|
1642
|
+
): string | undefined {
|
|
1643
|
+
const v = guide.schemaVersion ?? 0;
|
|
1644
|
+
if (!isStaleSchema(v, current)) return undefined;
|
|
1645
|
+
return ` ⚠ schemaVersion ${v} < current ${current} — guide may need updating`;
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1376
1648
|
// ════════════════════════════════════════════════════════════════════
|
|
1377
1649
|
// Disambiguation helpers — shared by the api-guide menu and the
|
|
1378
1650
|
// api-fetch ambiguous-operation error. One rendering of the per-guide
|
|
@@ -1402,7 +1674,10 @@ function formatOpSummary(ops: { name: string }[]): string {
|
|
|
1402
1674
|
* shortName + op names only (the status-quo shape), so un-backfilled
|
|
1403
1675
|
* guides render consistently with those that have a one-line summary.
|
|
1404
1676
|
*/
|
|
1405
|
-
export function formatGuideListings(
|
|
1677
|
+
export function formatGuideListings(
|
|
1678
|
+
entries: { guide: ApiGuide }[],
|
|
1679
|
+
current: number = GUIDE_SCHEMA_VERSION,
|
|
1680
|
+
): string {
|
|
1406
1681
|
const lines: string[] = [];
|
|
1407
1682
|
for (const { guide } of entries) {
|
|
1408
1683
|
lines.push(
|
|
@@ -1410,10 +1685,73 @@ export function formatGuideListings(entries: { guide: ApiGuide }[]): string {
|
|
|
1410
1685
|
(guide.description ? ` — ${guide.description}` : ""),
|
|
1411
1686
|
);
|
|
1412
1687
|
lines.push(` ${formatOpSummary(guide.operations)}`);
|
|
1688
|
+
const stale = staleSchemaLine(guide, current);
|
|
1689
|
+
if (stale) lines.push(stale);
|
|
1413
1690
|
}
|
|
1414
1691
|
return lines.join("\n");
|
|
1415
1692
|
}
|
|
1416
1693
|
|
|
1694
|
+
/**
|
|
1695
|
+
* Resolve a guide by shortName across a domain's matches (exact,
|
|
1696
|
+
* case-insensitive). Shared by api-guide, api-learn's fetch-recipe, and
|
|
1697
|
+
* /api verify — three call sites, one resolution rule (a drifted copy would
|
|
1698
|
+
* ship a known second bug). Returns a structured outcome; each caller renders
|
|
1699
|
+
* its own message (tool result vs command notify).
|
|
1700
|
+
*/
|
|
1701
|
+
export function selectGuideByShortName(
|
|
1702
|
+
matches: { guide: ApiGuide; dirName: string }[],
|
|
1703
|
+
selector: string,
|
|
1704
|
+
):
|
|
1705
|
+
| { ok: true; guide: ApiGuide; dirName: string }
|
|
1706
|
+
| { ok: false; reason: "no_match"; valid: string[] }
|
|
1707
|
+
| { ok: false; reason: "ambiguous"; directories: string[] } {
|
|
1708
|
+
const lc = selector.toLowerCase();
|
|
1709
|
+
const sel = matches.filter((m) => m.guide.shortName.toLowerCase() === lc);
|
|
1710
|
+
if (sel.length === 0) {
|
|
1711
|
+
return {
|
|
1712
|
+
ok: false,
|
|
1713
|
+
reason: "no_match",
|
|
1714
|
+
valid: matches.map((m) => m.guide.shortName),
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
if (sel.length > 1) {
|
|
1718
|
+
return {
|
|
1719
|
+
ok: false,
|
|
1720
|
+
reason: "ambiguous",
|
|
1721
|
+
directories: sel.map((s) => s.dirName),
|
|
1722
|
+
};
|
|
1723
|
+
}
|
|
1724
|
+
return { ok: true, guide: sel[0]!.guide, dirName: sel[0]!.dirName };
|
|
1725
|
+
}
|
|
1726
|
+
|
|
1727
|
+
/**
|
|
1728
|
+
* Render the no-match / ambiguous error text for a failed
|
|
1729
|
+
* `selectGuideByShortName` result. `callToAction` is the trailing
|
|
1730
|
+
* "how to see the menu" sentence — it differs per surface (tool vs
|
|
1731
|
+
* command), so callers pass their own.
|
|
1732
|
+
*/
|
|
1733
|
+
export function shortNameErrorText(
|
|
1734
|
+
sel: Extract<ReturnType<typeof selectGuideByShortName>, { ok: false }>,
|
|
1735
|
+
domain: string,
|
|
1736
|
+
selector: string,
|
|
1737
|
+
callToAction: string,
|
|
1738
|
+
): string {
|
|
1739
|
+
if (sel.reason === "no_match") {
|
|
1740
|
+
return (
|
|
1741
|
+
`No guide named '${selector}' for '${domain}'. ` +
|
|
1742
|
+
`Available guides: ${sel.valid.join(", ")}. ` +
|
|
1743
|
+
callToAction
|
|
1744
|
+
);
|
|
1745
|
+
}
|
|
1746
|
+
return (
|
|
1747
|
+
`Ambiguous guide '${selector}' for '${domain}' — ` +
|
|
1748
|
+
`${sel.directories.length} guides share shortName '${selector}' ` +
|
|
1749
|
+
`(directories: ${sel.directories.join(", ")}). Rename one guide's shortName to ` +
|
|
1750
|
+
`disambiguate. ` +
|
|
1751
|
+
callToAction
|
|
1752
|
+
);
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1417
1755
|
// ════════════════════════════════════════════════════════════════════
|
|
1418
1756
|
// Catalog rendering — healthy + ⚠ malformed together
|
|
1419
1757
|
//
|
|
@@ -1425,7 +1763,10 @@ export function formatGuideListings(entries: { guide: ApiGuide }[]): string {
|
|
|
1425
1763
|
// here, where they'd bloat context for orgs with many guides.
|
|
1426
1764
|
// ════════════════════════════════════════════════════════════════════
|
|
1427
1765
|
|
|
1428
|
-
export function formatApiGuideCatalog(
|
|
1766
|
+
export function formatApiGuideCatalog(
|
|
1767
|
+
loaded: LoadedApiGuides,
|
|
1768
|
+
current: number = GUIDE_SCHEMA_VERSION,
|
|
1769
|
+
): string {
|
|
1429
1770
|
const lines: string[] = ["API guides:"];
|
|
1430
1771
|
|
|
1431
1772
|
// Org-grouped rows preserve first-appearance order; guides without
|
|
@@ -1454,7 +1795,14 @@ export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
|
|
|
1454
1795
|
}
|
|
1455
1796
|
const domList = domains.size > 0 ? [...domains].join(", ") : "—";
|
|
1456
1797
|
const n = row.guides.length;
|
|
1457
|
-
|
|
1798
|
+
// Collapsed org row: a trailing ⚠ glyph when ANY guide in it is stale
|
|
1799
|
+
// (hint only — the per-guide ⚠ line lives on the menu / detail view).
|
|
1800
|
+
const stale = row.guides.some((g) =>
|
|
1801
|
+
isStaleSchema(g.schemaVersion ?? 0, current),
|
|
1802
|
+
);
|
|
1803
|
+
lines.push(
|
|
1804
|
+
` 🏛️ ${row.org} — ${n} guide${n > 1 ? "s" : ""} (${domList})${stale ? " ⚠" : ""}`,
|
|
1805
|
+
);
|
|
1458
1806
|
}
|
|
1459
1807
|
for (const { name, guide } of orgless) {
|
|
1460
1808
|
const domains =
|
|
@@ -1462,6 +1810,8 @@ export function formatApiGuideCatalog(loaded: LoadedApiGuides): string {
|
|
|
1462
1810
|
lines.push(
|
|
1463
1811
|
` ${guide.icon} ${guide.shortName} — ${domains} (verified ${guide.verified}, ${guide.operations.length} ops)`,
|
|
1464
1812
|
);
|
|
1813
|
+
const stale = staleSchemaLine(guide, current);
|
|
1814
|
+
if (stale) lines.push(stale);
|
|
1465
1815
|
}
|
|
1466
1816
|
for (const mal of loaded.malformed) {
|
|
1467
1817
|
lines.push(
|