@apifuse/provider-sdk 2.2.0-beta.67 → 2.2.0-beta.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/AUTHORING.md +34 -2
  2. package/CHANGELOG.md +8 -0
  3. package/README.md +18 -7
  4. package/bin/apifuse-record.ts +81 -21
  5. package/bin/apifuse-submit-check.ts +170 -28
  6. package/dist/cli/templates/provider/.agents/skills/health-checks-and-fail-closed/SKILL.md.tpl +138 -23
  7. package/dist/cli/templates/provider/README.md.tpl +17 -9
  8. package/dist/config/loader.d.ts +16 -0
  9. package/dist/config/loader.js +25 -8
  10. package/dist/error-resolution.d.ts +13 -0
  11. package/dist/error-resolution.js +72 -35
  12. package/dist/fixture-sanitization.js +159 -15
  13. package/dist/lint.d.ts +2 -0
  14. package/dist/lint.js +549 -11
  15. package/dist/runtime/diagnostic-redactor.d.ts +6 -1
  16. package/dist/runtime/diagnostic-redactor.js +16 -14
  17. package/dist/runtime/executor.js +3 -0
  18. package/dist/runtime/http.d.ts +2 -0
  19. package/dist/runtime/http.js +17 -103
  20. package/dist/runtime/instrumentation.js +4 -1
  21. package/dist/runtime/provider.d.ts +7 -0
  22. package/dist/runtime/provider.js +14 -0
  23. package/dist/runtime/redirect-hop-headers.d.ts +19 -0
  24. package/dist/runtime/redirect-hop-headers.js +58 -0
  25. package/dist/runtime/redirects.d.ts +33 -1
  26. package/dist/runtime/redirects.js +113 -0
  27. package/dist/runtime/resolver-span-attributes.d.ts +34 -0
  28. package/dist/runtime/resolver-span-attributes.js +93 -0
  29. package/dist/runtime/resolver-usage.d.ts +8 -0
  30. package/dist/runtime/resolver-usage.js +5 -11
  31. package/dist/runtime/resolver-vendors/browser.js +5 -4
  32. package/dist/runtime/resolver-vendors/capsolver.js +11 -10
  33. package/dist/runtime/resolver-vendors/twocaptcha.js +9 -8
  34. package/dist/runtime/resolver.js +7 -6
  35. package/dist/runtime/stealth-owned-headers.d.ts +21 -8
  36. package/dist/runtime/stealth-owned-headers.js +28 -8
  37. package/dist/runtime/stealth-telemetry.d.ts +1 -1
  38. package/dist/runtime/stealth.js +158 -46
  39. package/dist/runtime/trace.js +2 -2
  40. package/dist/server/index.d.ts +1 -0
  41. package/dist/server/serve-implementation.d.ts +2 -1
  42. package/dist/server/serve-implementation.js +45 -30
  43. package/dist/server/state-backend-report.d.ts +70 -0
  44. package/dist/server/state-backend-report.js +113 -0
  45. package/dist/testing/run.js +14 -7
  46. package/dist/trace-sanitization.js +1 -1
  47. package/dist/types.d.ts +30 -6
  48. package/package.json +2 -2
  49. package/src/cli/templates/provider/.agents/skills/health-checks-and-fail-closed/SKILL.md.tpl +138 -23
  50. package/src/cli/templates/provider/README.md.tpl +17 -9
  51. package/src/config/loader.ts +49 -12
  52. package/src/error-resolution.ts +89 -35
  53. package/src/fixture-sanitization.ts +175 -17
  54. package/src/lint.ts +595 -10
  55. package/src/runtime/diagnostic-redactor.ts +19 -13
  56. package/src/runtime/executor.ts +3 -0
  57. package/src/runtime/http.ts +24 -112
  58. package/src/runtime/instrumentation.ts +4 -1
  59. package/src/runtime/provider.ts +15 -0
  60. package/src/runtime/redirect-hop-headers.ts +71 -0
  61. package/src/runtime/redirects.ts +150 -1
  62. package/src/runtime/resolver-span-attributes.ts +139 -0
  63. package/src/runtime/resolver-usage.ts +8 -5
  64. package/src/runtime/resolver-vendors/browser.ts +5 -4
  65. package/src/runtime/resolver-vendors/capsolver.ts +11 -10
  66. package/src/runtime/resolver-vendors/twocaptcha.ts +9 -8
  67. package/src/runtime/resolver.ts +7 -6
  68. package/src/runtime/stealth-owned-headers.ts +34 -8
  69. package/src/runtime/stealth-telemetry.ts +6 -1
  70. package/src/runtime/stealth.ts +180 -58
  71. package/src/runtime/trace.ts +6 -2
  72. package/src/server/index.ts +4 -0
  73. package/src/server/serve-implementation.ts +58 -31
  74. package/src/server/state-backend-report.ts +185 -0
  75. package/src/testing/run.ts +15 -2
  76. package/src/trace-sanitization.ts +1 -1
  77. package/src/types.ts +30 -6
package/dist/lint.js CHANGED
@@ -4,12 +4,12 @@ import { PROVIDER_ERROR_CATALOG_NAMESPACE } from "./i18n/error-messages.js";
4
4
  import { getProviderLocaleSegments, isProviderLocaleKey, } from "./i18n/keys.js";
5
5
  import { lintPublicSchemaFieldNames } from "./public-schema-field-lint.js";
6
6
  import { isStealthOwnedHeaderName, SDK_OWNED_CHROME_HEADER_PREFIX, } from "./runtime/stealth-owned-headers.js";
7
- import { lintRuntimeBoundary, scriptKindForSourceFile,
7
+ import { lintRuntimeBoundary,
8
8
  // This module already has a narrower TEST_SOURCE_FILE_PATTERN of its own,
9
9
  // used by the older source rules; it does not cover a plain `tests/`
10
10
  // directory. Aliased rather than merged because consolidating the two would
11
11
  // silently change what those rules scan.
12
- TEST_SOURCE_FILE_PATTERN as SHARED_TEST_SOURCE_FILE_PATTERN, } from "./runtime-boundary-lint.js";
12
+ TEST_SOURCE_FILE_PATTERN as SHARED_TEST_SOURCE_FILE_PATTERN, scriptKindForSourceFile, } from "./runtime-boundary-lint.js";
13
13
  import { APIFUSE_DESCRIPTION_KEY_META_KEY, APIFUSE_SENSITIVE_META_KEY } from "./schema.js";
14
14
  import { getTypeScript } from "./typescript-module.js";
15
15
  const CREDENTIAL_BEARING_AUTH_MODES = [
@@ -821,6 +821,49 @@ function isStealthContextAccess(node) {
821
821
  }
822
822
  return false;
823
823
  }
824
+ function isTupleTypeNode(type) {
825
+ if (!type)
826
+ return false;
827
+ const ts = getTypeScript();
828
+ if (ts.isTypeOperatorNode(type))
829
+ return isTupleTypeNode(type.type);
830
+ return ts.isTupleTypeNode(type);
831
+ }
832
+ /**
833
+ * True where a two-element array is consumed as a `[name, value]` header entry:
834
+ * inside an entries list (`new Headers([[name, value]])`,
835
+ * `Object.fromEntries([...])`), passed to a call such as `tuples.push(...)`, or
836
+ * declared with a tuple type. A two-name list is bound, iterated, or handed to
837
+ * a constructor instead — `const STRIP = ["sec-fetch-dest", "referer"]`,
838
+ * `for (const name of [...])`, `new Set([...])` — and is not an entry. The
839
+ * position decides because a Sec-Fetch-* value ("document", "navigate") is
840
+ * token-shaped exactly like a header name.
841
+ */
842
+ function isHeaderEntryPosition(node) {
843
+ const ts = getTypeScript();
844
+ let child = node;
845
+ let parent = node.parent;
846
+ while (parent &&
847
+ (ts.isParenthesizedExpression(parent) ||
848
+ ts.isAsExpression(parent) ||
849
+ ts.isSatisfiesExpression(parent) ||
850
+ ts.isTypeAssertionExpression(parent))) {
851
+ if (!ts.isParenthesizedExpression(parent) && isTupleTypeNode(parent.type))
852
+ return true;
853
+ child = parent;
854
+ parent = parent.parent;
855
+ }
856
+ if (!parent)
857
+ return false;
858
+ if (ts.isArrayLiteralExpression(parent))
859
+ return true;
860
+ if (ts.isCallExpression(parent))
861
+ return parent.arguments.some((argument) => argument === child);
862
+ if (ts.isVariableDeclaration(parent)) {
863
+ return parent.initializer === child && isTupleTypeNode(parent.type);
864
+ }
865
+ return false;
866
+ }
824
867
  function isStaticUndefined(node) {
825
868
  if (!node)
826
869
  return false;
@@ -842,9 +885,14 @@ function calleeName(node) {
842
885
  * runtime rejection: host, connection, and accept-encoding are left alone
843
886
  * because ctx.http callers set them legitimately in the same files, and
844
887
  * user-agent only reaches a finding through the "user-agent" kind, which
845
- * matches a versioned literal value rather than the name — a user-agent read
846
- * from a variable is rejected by the runtime and stays silent here. Widening
847
- * the set needs a per-file transport scope and a suppression path first.
888
+ * matches a versioned literal value rather than the name.
889
+ *
890
+ * This rule is the early, same-file signal only. The complete check is the
891
+ * offline test harness: `runStandardTests` runs every `ctx.stealth` request
892
+ * through the runtime's own `assertCallerHeadersSupported`, so a header spread
893
+ * from another module, or a user-agent read from a variable or
894
+ * `getStealthProfile(...)`, fails the provider's tests exactly as it would fail
895
+ * in production.
848
896
  */
849
897
  function isReportedOwnedHeaderName(value) {
850
898
  if (value === undefined)
@@ -928,13 +976,12 @@ function collectBrowserVersionLiteralFindings(fileName, source) {
928
976
  : false);
929
977
  }
930
978
  if (ts.isArrayLiteralExpression(node) && node.elements[0]) {
931
- // Only a `[name, value]` tuple is a header. A name list such as
932
- // `new Set(["sec-ch-ua-mobile", "sec-ch-ua-platform"])` is not: it is
933
- // the argument of a constructor, or its second element is itself an
934
- // owned name.
979
+ // Only a `[name, value]` tuple is a header: a two-element array in an
980
+ // entry position (isHeaderEntryPosition) whose second element is not
981
+ // itself an owned name.
935
982
  const second = node.elements[1];
936
983
  inspectHeaderEntry(node.elements[0], staticStringText(node.elements[0]), second, node.elements.length === 2 &&
937
- !ts.isNewExpression(node.parent) &&
984
+ isHeaderEntryPosition(node) &&
938
985
  !isStealthOwnedHeaderName(staticStringText(second) ?? "")
939
986
  ? "entry"
940
987
  : false);
@@ -967,7 +1014,7 @@ function browserVersionLiteralMessage(finding) {
967
1014
  case "sec-ch-ua":
968
1015
  return 'Hardcoded sec-ch-ua versions can disagree with the stealth TLS fingerprint. Remove the literal and let ctx.stealth generate client hints from stealth: { browser: "chrome", os: "macos" }. ctx.stealth also owns User-Agent, so omit that header there as well; for ctx.http only, derive it from getStealthProfile({ browser: "chrome", os: "macos" }).userAgent.';
969
1016
  case "owned-header":
970
- return `ctx.stealth owns the "${finding.literal}" header and rejects a caller value with STEALTH_HEADER_OVERRIDE_UNSUPPORTED (HTTP 500 at request time). Remove it; declare stealth: { requestClass: "navigation" | "xhr" | "post" } to drive Sec-Fetch-* and select the profile with stealth: { browser: "chrome", os: "macos" } for client hints.`;
1017
+ return `ctx.stealth owns the "${finding.literal}" header and rejects a caller value with STEALTH_HEADER_OVERRIDE_UNSUPPORTED (HTTP 500 at request time). Remove it; declare stealth: { requestClass: "navigation" | "form-post" | "xhr" | "post" } to drive Sec-Fetch-* and select the profile with stealth: { browser: "chrome", os: "macos" } for client hints.`;
971
1018
  }
972
1019
  }
973
1020
  function lintBrowserVersionLiterals(provider) {
@@ -2307,6 +2354,496 @@ function lintProviderMetaNarrowing(provider) {
2307
2354
  }
2308
2355
  return diagnostics;
2309
2356
  }
2357
+ const STALE_IF_ERROR_OPTION = "staleIfErrorMs";
2358
+ const STALE_IF_ERROR_PATTERN = /\bstaleIfErrorMs\b/;
2359
+ /**
2360
+ * Whether a property assignment's initializer leaves no stale window.
2361
+ * `staleIfErrorMs: 0` makes `staleUntil` equal `freshUntil` in
2362
+ * `runtime/cache.ts`, so a loader failure propagates instead of being answered
2363
+ * from cache — a provider deliberately turning stale serving OFF must not be
2364
+ * told its probes conceal outages.
2365
+ */
2366
+ function disablesStaleWindow(ts, initializer) {
2367
+ if (ts.isNumericLiteral(initializer))
2368
+ return Number(initializer.text) === 0;
2369
+ return ts.isIdentifier(initializer) && initializer.text === "undefined";
2370
+ }
2371
+ /**
2372
+ * Whether executable source configures a stale-if-error window.
2373
+ *
2374
+ * Parsed, not matched: comments and unrelated string literals must not count,
2375
+ * and a regex cannot tell them apart (an `Accept: "*​/*"` header literal opens a
2376
+ * block comment to a stripping regex and swallows the cache call after it).
2377
+ * This is the approach `findLegacyChoiceUsage` already uses here. All three
2378
+ * spellings of the option count — `staleIfErrorMs: n`, the shorthand
2379
+ * `{ ttlMs, staleIfErrorMs }`, and the quoted `"staleIfErrorMs": n` — because
2380
+ * refactoring between them must not change the verdict. Falls back to the raw
2381
+ * identifier match when TypeScript is not installed, which is the fail-closed
2382
+ * direction for this rule: it warns rather than goes quiet.
2383
+ */
2384
+ function servesStaleIfError(source, fileName = "provider.ts") {
2385
+ if (!source.includes(STALE_IF_ERROR_OPTION))
2386
+ return false;
2387
+ let ts;
2388
+ try {
2389
+ ts = getTypeScript();
2390
+ }
2391
+ catch {
2392
+ return STALE_IF_ERROR_PATTERN.test(source);
2393
+ }
2394
+ const file = ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, false, scriptKindForSourceFile(ts, fileName));
2395
+ /** The statically known name of a property, however it is written. */
2396
+ const propertyName = (name) => {
2397
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name))
2398
+ return name.text;
2399
+ if (ts.isComputedPropertyName(name) && ts.isStringLiteral(name.expression)) {
2400
+ return name.expression.text;
2401
+ }
2402
+ return undefined;
2403
+ };
2404
+ /**
2405
+ * A type declaring the option is not a cache call setting it. Skipping these
2406
+ * whole subtrees also stops a `CachePolicy` interface from overriding the
2407
+ * disabled-window exemption for a provider whose only real call passes 0.
2408
+ */
2409
+ const isTypeOnly = (node) => ts.isInterfaceDeclaration(node) ||
2410
+ ts.isTypeAliasDeclaration(node) ||
2411
+ ts.isTypeLiteralNode(node) ||
2412
+ ts.isPropertySignature(node) ||
2413
+ ts.isTypeReferenceNode(node) ||
2414
+ ts.isTypeParameterDeclaration(node);
2415
+ /**
2416
+ * The cache write options that travel with `staleIfErrorMs`
2417
+ * (`ProviderCacheWriteOptions`). An object literal carrying one of these
2418
+ * alongside the option is a cache configuration wherever it is declared.
2419
+ */
2420
+ const siblingCacheOptions = new Set(["ttlMs", "jitterPct"]);
2421
+ /**
2422
+ * A callee that writes the provider cache: `ctx.cache.getOrSet(...)`,
2423
+ * `ctx.cache.set(...)`, and the `cached*` helpers built on them. An unrelated
2424
+ * call receiving an object that happens to carry the name is not cache
2425
+ * configuration. Every one of these takes its options LAST.
2426
+ */
2427
+ const isCacheCallee = (expression) => {
2428
+ if (ts.isIdentifier(expression))
2429
+ return /^cached[A-Z]/.test(expression.text);
2430
+ if (!ts.isPropertyAccessExpression(expression))
2431
+ return false;
2432
+ if (expression.name.text === "getOrSet")
2433
+ return true;
2434
+ return ((expression.name.text === "set" || expression.name.text === "write") &&
2435
+ ts.isPropertyAccessExpression(expression.expression) &&
2436
+ expression.expression.name.text === "cache");
2437
+ };
2438
+ /**
2439
+ * `const POLICY = { ... }` object literals, so `{ ...POLICY }` can be judged.
2440
+ * Keyed by name file-wide: a shadowed name may resolve to the wrong literal,
2441
+ * which at warning level is a mis-nudge rather than a wrong build — but the
2442
+ * expansion below still has to be cycle-safe, because shadowing can make the
2443
+ * resolution circular in valid source.
2444
+ */
2445
+ const literalsByName = new Map();
2446
+ const collect = (node) => {
2447
+ if (ts.isVariableDeclaration(node) &&
2448
+ ts.isIdentifier(node.name) &&
2449
+ node.initializer !== undefined &&
2450
+ ts.isObjectLiteralExpression(node.initializer)) {
2451
+ literalsByName.set(node.name.text, node.initializer);
2452
+ }
2453
+ ts.forEachChild(node, collect);
2454
+ };
2455
+ collect(file);
2456
+ /**
2457
+ * The EFFECTIVE stale-window setting of an object literal, spreads expanded
2458
+ * and later properties overriding earlier ones the way JavaScript does — so
2459
+ * `{ ...policy, staleIfErrorMs: 0 }` reads as disabled even when `policy`
2460
+ * enables it.
2461
+ */
2462
+ const readOptions = (literal, seen) => {
2463
+ if (seen.has(literal))
2464
+ return { window: undefined, hasSibling: false };
2465
+ seen.add(literal);
2466
+ let window;
2467
+ let hasSibling = false;
2468
+ for (const property of literal.properties) {
2469
+ if (ts.isSpreadAssignment(property)) {
2470
+ const target = ts.isIdentifier(property.expression)
2471
+ ? literalsByName.get(property.expression.text)
2472
+ : ts.isObjectLiteralExpression(property.expression)
2473
+ ? property.expression
2474
+ : undefined;
2475
+ if (target === undefined)
2476
+ continue;
2477
+ const inner = readOptions(target, seen);
2478
+ if (inner.window !== undefined)
2479
+ window = inner.window;
2480
+ hasSibling ||= inner.hasSibling;
2481
+ continue;
2482
+ }
2483
+ if (ts.isShorthandPropertyAssignment(property)) {
2484
+ if (property.name.text === STALE_IF_ERROR_OPTION)
2485
+ window = "enabled";
2486
+ else if (siblingCacheOptions.has(property.name.text))
2487
+ hasSibling = true;
2488
+ continue;
2489
+ }
2490
+ if (!ts.isPropertyAssignment(property))
2491
+ continue;
2492
+ const name = propertyName(property.name);
2493
+ if (name === STALE_IF_ERROR_OPTION) {
2494
+ window = disablesStaleWindow(ts, property.initializer) ? "disabled" : "enabled";
2495
+ }
2496
+ else if (name !== undefined && siblingCacheOptions.has(name)) {
2497
+ hasSibling = true;
2498
+ }
2499
+ }
2500
+ seen.delete(literal);
2501
+ return { window, hasSibling };
2502
+ };
2503
+ let found = false;
2504
+ /**
2505
+ * `inOptionsArgument` is the second way to recognise a cache configuration:
2506
+ * the literal is the options argument of a cache call. Together with the
2507
+ * sibling-option test this covers the real shapes, while an upstream payload
2508
+ * that merely carries a field of the same name does not count.
2509
+ */
2510
+ const visit = (node, inOptionsArgument) => {
2511
+ if (found || isTypeOnly(node))
2512
+ return;
2513
+ if (ts.isObjectLiteralExpression(node)) {
2514
+ const { window, hasSibling } = readOptions(node, new Set());
2515
+ if (window === "enabled" && (hasSibling || inOptionsArgument)) {
2516
+ found = true;
2517
+ return;
2518
+ }
2519
+ }
2520
+ if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
2521
+ const argumentList = node.arguments ?? [];
2522
+ // Options come last on every cache API; the earlier arguments are the
2523
+ // key, the loader, or the value being cached.
2524
+ const optionsIndex = isCacheCallee(node.expression) ? argumentList.length - 1 : -1;
2525
+ visit(node.expression, false);
2526
+ for (const [index, argument] of [...argumentList].entries()) {
2527
+ visit(argument, index === optionsIndex);
2528
+ }
2529
+ return;
2530
+ }
2531
+ ts.forEachChild(node, (child) => visit(child, false));
2532
+ };
2533
+ visit(file, false);
2534
+ return found;
2535
+ }
2536
+ /** The operation-step field that distinguishes a stale-if-error serve. */
2537
+ const SERVED_STALE_CACHE_OPERAND = "served_stale_cache";
2538
+ /**
2539
+ * Sources that describe behaviour rather than serve it. Mirrors the broadest
2540
+ * test-source predicate in the repository (`runtime-boundary-lint.ts:82`, which
2541
+ * covers a plain `tests/` directory and `__mocks__/` as well as `__tests__/`)
2542
+ * and adds recorded-fixture directories, so a mock that mentions
2543
+ * `staleIfErrorMs` cannot raise a warning about code the runtime never serves.
2544
+ */
2545
+ const NON_SERVING_SOURCE_FILE_PATTERN = /(?:^|\/)(?:__tests__|__mocks__|__fixtures__|tests|fixtures)\/|\.(?:test|spec)\.[cm]?[jt]sx?$/;
2546
+ /**
2547
+ * Operator tooling and bootstrap entrypoints, mirroring
2548
+ * `runtime-boundary-lint.ts`: a cache option used by a fixture recorder or a
2549
+ * start script is not the request path a probe reads through.
2550
+ */
2551
+ const NON_SERVING_TOOLING_DIRECTORY_PATTERN = /^(?:scripts|tools|bin)\//;
2552
+ const NON_SERVING_BOOTSTRAP_FILE_PATTERN = /^(?:dev|start|deploy)\.[cm]?[jt]sx?$/;
2553
+ function isServingProviderSourcePath(relativePath) {
2554
+ return (JAVASCRIPT_SOURCE_FILE_PATTERN.test(relativePath) &&
2555
+ !NON_SERVING_SOURCE_FILE_PATTERN.test(relativePath) &&
2556
+ !NON_SERVING_TOOLING_DIRECTORY_PATTERN.test(relativePath) &&
2557
+ !NON_SERVING_BOOTSTRAP_FILE_PATTERN.test(relativePath));
2558
+ }
2559
+ function isLintRecord(value) {
2560
+ return !!value && typeof value === "object" && !Array.isArray(value);
2561
+ }
2562
+ /**
2563
+ * Reads `healthCheck.cases` structurally. The lint input is the loaded provider
2564
+ * declaration, which `defineProvider` has already validated, but this rule must
2565
+ * not throw on a shape it did not expect.
2566
+ */
2567
+ function readHealthCheckCases(healthCheck) {
2568
+ if (!isLintRecord(healthCheck))
2569
+ return [];
2570
+ const cases = healthCheck.cases;
2571
+ if (!Array.isArray(cases))
2572
+ return [];
2573
+ return cases.filter(isLintRecord);
2574
+ }
2575
+ /**
2576
+ * The `result` bindings of the `operation` steps that invoke `operationId`.
2577
+ *
2578
+ * Scoped to the probe's own operation on purpose: a scenario may invoke a
2579
+ * preparatory read before the operation the case is about, and a guard on the
2580
+ * preparation's result says nothing about whether the checked operation was
2581
+ * answered from a stale cache.
2582
+ */
2583
+ function operationStepBindings(steps, operationId) {
2584
+ const bindings = new Set();
2585
+ for (const step of steps) {
2586
+ if (isLintRecord(step) &&
2587
+ step.kind === "operation" &&
2588
+ step.operationId === operationId &&
2589
+ typeof step.result === "string") {
2590
+ bindings.add(step.result);
2591
+ }
2592
+ }
2593
+ return bindings;
2594
+ }
2595
+ /**
2596
+ * Whether an operand is the operand: the runtime's `served_stale_cache`
2597
+ * projection on an operation step result for the probe's own operation.
2598
+ *
2599
+ * Exact on three counts, because each looser form is a way to silence the rule
2600
+ * without checking cache provenance: a literal `"served_stale_cache"` in an
2601
+ * `inputTemplate` or a `reasonKey` is not a reference at all;
2602
+ * `["data", "served_stale_cache"]` is an upstream payload field the provider
2603
+ * happens to have named that way; and a reference bound to an `extract` result
2604
+ * is not the operation step this probe invoked.
2605
+ */
2606
+ function isStaleCacheOperand(operand, bindings) {
2607
+ if (!isLintRecord(operand))
2608
+ return false;
2609
+ const reference = operand.ref;
2610
+ return (isLintRecord(reference) &&
2611
+ reference.namespace === "steps" &&
2612
+ typeof reference.binding === "string" &&
2613
+ bindings.has(reference.binding) &&
2614
+ Array.isArray(reference.path) &&
2615
+ reference.path.length === 1 &&
2616
+ reference.path[0] === SERVED_STALE_CACHE_OPERAND);
2617
+ }
2618
+ /**
2619
+ * Whether a single predicate over the operand is FALSE for a stale serve, under
2620
+ * `negated` negation depth. `served_stale_cache` is always present and always a
2621
+ * boolean, so `exists` and `type_is: "boolean"` pass for a stale serve too —
2622
+ * reading the operand is not the same as rejecting it.
2623
+ */
2624
+ function predicateRejectsStaleServe(predicate, bindings, negated) {
2625
+ // `equals`/`not_equals` are symmetric and the schema allows a reference on
2626
+ // either side, so `equals(actual: false, expected: <ref>)` is the same check
2627
+ // written the other way round.
2628
+ const onActual = isStaleCacheOperand(predicate.actual, bindings);
2629
+ const onExpected = isStaleCacheOperand(predicate.expected, bindings);
2630
+ if (!onActual && !onExpected)
2631
+ return false;
2632
+ const { operator } = predicate;
2633
+ const literal = onActual ? predicate.expected : predicate.actual;
2634
+ const failsWhenStale = (operator === "not_equals" && literal === true) || (operator === "equals" && literal === false);
2635
+ const holdsWhenStale = (operator === "is_true" && onActual) ||
2636
+ (operator === "equals" && literal === true) ||
2637
+ (operator === "not_equals" && literal === false);
2638
+ return negated ? holdsWhenStale : failsWhenStale;
2639
+ }
2640
+ /**
2641
+ * Whether an assertion expression evaluates FALSE when the operation step was
2642
+ * answered from a stale cache — the only thing that makes a guard degrade or an
2643
+ * assert fail. A clause under `any` only counts if every sibling branch also
2644
+ * rejects the stale serve, because `any` is satisfied by the branch that still
2645
+ * passes (`status_2xx` on a stale 200 being the obvious one).
2646
+ */
2647
+ function rejectsStaleServe(node, bindings, negated = false) {
2648
+ if (!isLintRecord(node))
2649
+ return false;
2650
+ if (node.kind === "not")
2651
+ return rejectsStaleServe(node.clause, bindings, !negated);
2652
+ if (node.kind === "all" || node.kind === "any") {
2653
+ if (!Array.isArray(node.clauses))
2654
+ return false;
2655
+ // `all` fails if ANY clause fails; `any` fails only if EVERY clause fails.
2656
+ // Negation swaps which of the two the operator behaves like.
2657
+ const conjunctive = negated ? node.kind === "any" : node.kind === "all";
2658
+ return conjunctive
2659
+ ? node.clauses.some((clause) => rejectsStaleServe(clause, bindings, negated))
2660
+ : node.clauses.every((clause) => rejectsStaleServe(clause, bindings, negated));
2661
+ }
2662
+ if (node.kind === "predicate")
2663
+ return predicateRejectsStaleServe(node, bindings, negated);
2664
+ return false;
2665
+ }
2666
+ /**
2667
+ * Whether a guard's degrade lands on the operation the case is about. A guard
2668
+ * whose condition reads the checked operation's freshness but attributes the
2669
+ * failure to a different operation leaves the checked one green through the
2670
+ * stale serve — covered on paper, not on the status page.
2671
+ */
2672
+ /**
2673
+ * Whether an assert records its verdict against the checked operation. Same
2674
+ * concern as `guardAttributesTo`: an assertion that covers only some other
2675
+ * operation fails that one, not this one.
2676
+ */
2677
+ function assertCoversOperation(coversOperations, operationId) {
2678
+ return Array.isArray(coversOperations) && coversOperations.includes(operationId);
2679
+ }
2680
+ function guardAttributesTo(onFail, operationId) {
2681
+ if (!isLintRecord(onFail) || !Array.isArray(onFail.attribute))
2682
+ return false;
2683
+ return onFail.attribute.some((entry) => isLintRecord(entry) && entry.operationId === operationId);
2684
+ }
2685
+ /**
2686
+ * Whether a scenario reaches a verdict on freshness: a `guard` condition
2687
+ * (degraded, the shape this rule recommends) or an `assert` expression (down,
2688
+ * harsher but still real coverage). Any other position — an extract selector,
2689
+ * an operation input — is not a verdict.
2690
+ *
2691
+ * Order matters, and this is the rule the guidance states: the freshness
2692
+ * verdict must come before any OTHER guard. Every guard stops the scenario when
2693
+ * it fires, so a row or emptiness guard placed first answers a stale serve that
2694
+ * happens to be empty with its own reason and the freshness guard never runs —
2695
+ * the probe degrades for the wrong cause and the tenant reads "no rows" during
2696
+ * an upstream outage. Asserts before it are fine; they are the evidence clauses
2697
+ * and only stop the scenario by failing it outright.
2698
+ */
2699
+ function scenarioChecksFreshness(scenario, operationId) {
2700
+ if (!isLintRecord(scenario) || !Array.isArray(scenario.steps))
2701
+ return false;
2702
+ const bindings = [...operationStepBindings(scenario.steps, operationId)];
2703
+ if (bindings.length === 0)
2704
+ return false;
2705
+ // EVERY read of the operation must be checked. A scenario that invokes it
2706
+ // twice with different inputs has two chances to serve stale, and one fresh
2707
+ // read must not conceal the other.
2708
+ return bindings.every((binding) => resultBindingChecksFreshness(scenario.steps, binding, operationId, bindings));
2709
+ }
2710
+ function resultBindingChecksFreshness(steps, binding, operationId, siblingBindings) {
2711
+ const operand = new Set([binding]);
2712
+ let produced = false;
2713
+ for (const step of steps) {
2714
+ if (!isLintRecord(step))
2715
+ continue;
2716
+ if (!produced) {
2717
+ // Nothing before the read can have checked its freshness.
2718
+ produced = step.kind === "operation" && step.result === binding;
2719
+ continue;
2720
+ }
2721
+ if (step.kind === "assert" &&
2722
+ rejectsStaleServe(step.expression, operand) &&
2723
+ assertCoversOperation(step.coversOperations, operationId)) {
2724
+ return true;
2725
+ }
2726
+ if (step.kind !== "guard")
2727
+ continue;
2728
+ if (rejectsStaleServe(step.condition, operand)) {
2729
+ return guardAttributesTo(step.onFail, operationId);
2730
+ }
2731
+ // A freshness guard for ANOTHER read of the same operation is not a row or
2732
+ // emptiness guard masking the cause: it degrades on exactly this concern,
2733
+ // so `read A, read B, guard A, guard B` covers both. Anything else stops
2734
+ // the scenario first and shadows a later freshness guard.
2735
+ const coversSibling = siblingBindings.some((sibling) => sibling !== binding &&
2736
+ rejectsStaleServe(step.condition, new Set([sibling])) &&
2737
+ guardAttributesTo(step.onFail, operationId));
2738
+ if (!coversSibling)
2739
+ return false;
2740
+ }
2741
+ return false;
2742
+ }
2743
+ /** How many uncovered probes the stale-serve message names before eliding. */
2744
+ const STALE_SERVE_MESSAGE_PROBE_LIMIT = 8;
2745
+ /**
2746
+ * Health-check cases the platform monitor cannot execute, and stale-if-error
2747
+ * serves no probe can see.
2748
+ *
2749
+ * The monitor runs a case's SERIALIZED `scenario` and nothing else — a closure
2750
+ * cannot cross the registry's serialization boundary. A case carrying only
2751
+ * `assertions` is still published as a probe, but the registry projects it as
2752
+ * `legacy_function_assertions_not_serializable` and the monitor answers
2753
+ * `unknown` / `monitoring_unavailable` for it forever: the operation reads as
2754
+ * monitored on the status page while nothing is checked.
2755
+ *
2756
+ * A provider that reads its upstream through `ctx.cache.getOrSet(..., {
2757
+ * staleIfErrorMs })` answers an upstream outage with HTTP 200 and a
2758
+ * schema-valid body for the whole stale window, so every clause over
2759
+ * `status_code` and `data` passes and the probe rolls up `ok` through the
2760
+ * outage. `served_stale_cache` on the operation step result is the only operand
2761
+ * that separates that from a live read.
2762
+ *
2763
+ * Both are warnings while the fleet migrates; they become errors once no
2764
+ * repository carries an unmonitored case.
2765
+ */
2766
+ function lintHealthCheckMonitorability(provider) {
2767
+ const diagnostics = [];
2768
+ const providerLabel = provider.id ? `Provider "${provider.id}"` : "Provider";
2769
+ // Freshness is judged per CASE. Operation-level bookkeeping would let one
2770
+ // guarded case silence its unguarded siblings, which still report `ok`
2771
+ // through a stale serve — the same fail-open this rule exists to close.
2772
+ const uncoveredByOperation = new Map();
2773
+ for (const [operationKey, operation] of Object.entries(provider.operations ?? {})) {
2774
+ const cases = readHealthCheckCases(operation.healthCheck);
2775
+ const unmonitored = [];
2776
+ for (const [caseIndex, healthCase] of cases.entries()) {
2777
+ const caseLabel = typeof healthCase.name === "string" && healthCase.name.length > 0
2778
+ ? `"${healthCase.name}"`
2779
+ : `[${caseIndex}]`;
2780
+ if (healthCase.scenario === undefined) {
2781
+ unmonitored.push(caseLabel);
2782
+ }
2783
+ if (!scenarioChecksFreshness(healthCase.scenario, operationKey)) {
2784
+ const uncovered = uncoveredByOperation.get(operationKey) ?? [];
2785
+ uncovered.push(`${operationKey} ${caseLabel}`);
2786
+ uncoveredByOperation.set(operationKey, uncovered);
2787
+ }
2788
+ }
2789
+ if (unmonitored.length > 0) {
2790
+ diagnostics.push({
2791
+ rule: "health-check-assertions-not-monitored",
2792
+ level: "warn",
2793
+ field: `operations.${operationKey}.healthCheck.cases`,
2794
+ message: `${providerLabel} operation "${operationKey}" health-check ${unmonitored.length === 1 ? "case" : "cases"} ${unmonitored.join(", ")} declare assertions without a scenario. The platform health monitor executes only a case's serialized scenario, so this operation publishes a probe whose outcome is permanently unknown/monitoring_unavailable — it reads as monitored while nothing is checked. Express the checks as scenario: defineHealthScenario({ ... }).`,
2795
+ });
2796
+ }
2797
+ }
2798
+ if (uncoveredByOperation.size === 0)
2799
+ return diagnostics;
2800
+ // Attribution. A handler that carries the cache call in its OWN source names
2801
+ // exactly the operation that serves stale. A file does not: the linter cannot
2802
+ // follow the call graph, and it cannot reliably tell a handler's own file
2803
+ // from a shared helper either — `getOperationSource` returns the runtime's
2804
+ // `handler.toString()`, which type erasure and reformatting make textually
2805
+ // unequal to the TypeScript on disk. So any file-level evidence degrades the
2806
+ // verdict to "somewhere in this provider", and the message says so instead of
2807
+ // implying every listed probe reads through that cache.
2808
+ const sources = new Set();
2809
+ const operationsServingStale = new Set();
2810
+ for (const [operationKey, operation] of Object.entries(provider.operations ?? {})) {
2811
+ if (servesStaleIfError(getOperationSource(operation), `${operationKey}.ts`)) {
2812
+ sources.add(`operations.${operationKey} handler`);
2813
+ operationsServingStale.add(operationKey);
2814
+ }
2815
+ }
2816
+ let unattributed = false;
2817
+ for (const [filePath, source] of Object.entries(provider.providerSourceFiles ?? {})) {
2818
+ if (!isServingProviderSourcePath(filePath) || !servesStaleIfError(source, filePath))
2819
+ continue;
2820
+ sources.add(filePath);
2821
+ unattributed = true;
2822
+ }
2823
+ if (sources.size === 0)
2824
+ return diagnostics;
2825
+ const attributable = !unattributed;
2826
+ const uncovered = [...uncoveredByOperation]
2827
+ .filter(([operationKey]) => !attributable || operationsServingStale.has(operationKey))
2828
+ .flatMap(([, probes]) => probes);
2829
+ if (uncovered.length === 0)
2830
+ return diagnostics;
2831
+ const elided = uncovered.length - STALE_SERVE_MESSAGE_PROBE_LIMIT;
2832
+ const named = uncovered
2833
+ .slice(0, STALE_SERVE_MESSAGE_PROBE_LIMIT)
2834
+ .join(", ")
2835
+ .concat(elided > 0 ? `, and ${elided} more` : "");
2836
+ const caveat = attributable
2837
+ ? ""
2838
+ : ` The cache call is in provider source the linter cannot attribute to one operation, so every uncovered probe is listed — skip any whose operation does not read through that cache.`;
2839
+ diagnostics.push({
2840
+ rule: "health-check-stale-serve-unguarded",
2841
+ level: "warn",
2842
+ field: "healthCheck",
2843
+ message: `${providerLabel} serves stale-if-error (staleIfErrorMs in ${[...sources].sort().join(", ")}) and these health-check cases never check ${SERVED_STALE_CACHE_OPERAND}: ${named}. During an upstream outage the cache answers HTTP 200 with a schema-valid body, so every clause over status_code and data still passes and those probes report ok for the whole stale window. Add one guard step per affected probe on { ref: { namespace: "steps", binding: "<operation step result>", path: ["${SERVED_STALE_CACHE_OPERAND}"] } } attributing status "degraded" with reasonCode "expected_absence", placed before any row or emptiness guard.${caveat}`,
2844
+ });
2845
+ return diagnostics;
2846
+ }
2310
2847
  export function lintOperation(op) {
2311
2848
  const diagnostics = [];
2312
2849
  const hasDescriptionKey = typeof op.descriptionKey === "string" && op.descriptionKey.length > 0;
@@ -2411,6 +2948,7 @@ export function lintProviderWithInformation(provider, options = {}) {
2411
2948
  ...lintLegacyChoiceUsage(provider),
2412
2949
  ...lintProviderMetaNarrowing(provider),
2413
2950
  ...lintHandleDeclarations(provider),
2951
+ ...lintHealthCheckMonitorability(provider),
2414
2952
  ];
2415
2953
  // Runtime boundary rules (process.env, node:fs/net/child_process, raw
2416
2954
  // fetch) also yield information entries for `@apifuse-allow` acknowledgements.
@@ -41,7 +41,12 @@ export declare function isDiagnosticRedactionSuppressed(redact?: DiagnosticRedac
41
41
  export declare function diagnosticStructuredRedactor(redact?: DiagnosticRedactor): DiagnosticRedactor | undefined;
42
42
  export declare function redactDiagnosticAttributeKey(key: string, redact?: DiagnosticRedactor): string;
43
43
  export declare function redactCriticalDiagnosticText(text: string, redact?: DiagnosticRedactor): string;
44
- export declare function diagnosticAttributeRedactor(key: string, redact?: DiagnosticRedactor): DiagnosticRedactor | undefined;
44
+ /**
45
+ * The redactor for one attribute value. A value its producer declares as a closed-enum literal for
46
+ * this key is a contract, like a typed number: exhaustion suppression skips it, while registered
47
+ * credentials still match. Any other value under the same key stays free text.
48
+ */
49
+ export declare function diagnosticAttributeRedactor(key: string, redact?: DiagnosticRedactor, value?: unknown): DiagnosticRedactor | undefined;
45
50
  export declare function isDiagnosticBigintAttribute(attributes: object, key: string): boolean;
46
51
  export declare function copyDiagnosticAttributeTypes<T extends Record<string, unknown>>(source: Record<string, unknown>, target: T): T;
47
52
  /** Reserve existing keys so independently redacted names never drop an attribute. */