@apifuse/provider-sdk 2.1.0-beta.9 → 2.2.0-beta.2

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 (138) hide show
  1. package/AUTHORING.md +134 -0
  2. package/CHANGELOG.md +61 -0
  3. package/README.md +21 -9
  4. package/SUBMISSION.md +10 -11
  5. package/bin/apifuse-pack-check.ts +22 -0
  6. package/bin/apifuse-submit-check.ts +1747 -388
  7. package/dist/auth-turn/auth-turn.v1.schema.json +89 -0
  8. package/dist/auth-turn/fixtures/invalid/empty-kind.json +4 -0
  9. package/dist/auth-turn/fixtures/invalid/expires-at-not-string.json +5 -0
  10. package/dist/auth-turn/fixtures/invalid/missing-kind.json +3 -0
  11. package/dist/auth-turn/fixtures/invalid/missing-turn-id.json +3 -0
  12. package/dist/auth-turn/fixtures/invalid/timing-unknown-field.json +7 -0
  13. package/dist/auth-turn/fixtures/invalid/turn-id-snake-case.json +4 -0
  14. package/dist/auth-turn/fixtures/invalid/unknown-top-level-field.json +5 -0
  15. package/dist/auth-turn/fixtures/valid/abort.json +8 -0
  16. package/dist/auth-turn/fixtures/valid/challenge.json +17 -0
  17. package/dist/auth-turn/fixtures/valid/complete.json +13 -0
  18. package/dist/auth-turn/fixtures/valid/form.json +14 -0
  19. package/dist/auth-turn/fixtures/valid/message.json +13 -0
  20. package/dist/auth-turn/fixtures/valid/multi_choice.json +15 -0
  21. package/dist/auth-turn/fixtures/valid/pending.json +5 -0
  22. package/dist/auth-turn/fixtures/valid/poll.json +9 -0
  23. package/dist/auth-turn/fixtures/valid/redirect.json +16 -0
  24. package/dist/auth-turn/fixtures/valid/retry.json +8 -0
  25. package/dist/auth-turn/fixtures/valid/unknown-kind.json +7 -0
  26. package/dist/auth-turn/index.d.ts +195 -0
  27. package/dist/auth-turn/index.js +133 -0
  28. package/dist/auth.d.ts +76 -0
  29. package/dist/auth.js +436 -0
  30. package/dist/ceremonies/index.js +7 -31
  31. package/dist/cli/create.js +45 -30
  32. package/dist/cli/templates/provider/.dockerignore.tpl +22 -0
  33. package/dist/cli/templates/provider/.gitignore.tpl +22 -0
  34. package/dist/cli/templates/provider/AGENTS.md.tpl +87 -0
  35. package/dist/cli/templates/provider/CLAUDE.md.tpl +1 -0
  36. package/dist/cli/templates/provider/Dockerfile.tpl +7 -0
  37. package/dist/cli/templates/provider/README.md.tpl +163 -0
  38. package/dist/cli/templates/provider/dev.ts.tpl +5 -0
  39. package/dist/cli/templates/provider/domain/README.md.tpl +3 -0
  40. package/dist/cli/templates/provider/index.test.ts.tpl +13 -0
  41. package/dist/cli/templates/provider/index.ts.tpl +15 -0
  42. package/dist/cli/templates/provider/mappers/README.md.tpl +3 -0
  43. package/dist/cli/templates/provider/meta.ts.tpl +7 -0
  44. package/dist/cli/templates/provider/operations/index.ts.tpl +5 -0
  45. package/dist/cli/templates/provider/operations/ping.ts.tpl +24 -0
  46. package/dist/cli/templates/provider/schemas/ping.ts.tpl +24 -0
  47. package/dist/cli/templates/provider/skills/fixtures-and-recording/SKILL.md.tpl +58 -0
  48. package/dist/cli/templates/provider/skills/health-checks-and-fail-closed/SKILL.md.tpl +65 -0
  49. package/dist/cli/templates/provider/skills/normalization-standards/SKILL.md.tpl +57 -0
  50. package/dist/cli/templates/provider/skills/pagination-and-counts/SKILL.md.tpl +52 -0
  51. package/dist/cli/templates/provider/skills/upstream-contract-verification/SKILL.md.tpl +45 -0
  52. package/dist/cli/templates/provider/skills/upstream-notes/README.md.tpl +13 -0
  53. package/dist/cli/templates/provider/start.ts.tpl +5 -0
  54. package/dist/cli/templates/provider/upstream/README.md.tpl +3 -0
  55. package/dist/contract.js +1 -0
  56. package/dist/define.d.ts +6 -1
  57. package/dist/define.js +140 -70
  58. package/dist/index.d.ts +3 -2
  59. package/dist/index.js +2 -1
  60. package/dist/lint.d.ts +1 -0
  61. package/dist/lint.js +27 -0
  62. package/dist/provider.d.ts +4 -2
  63. package/dist/provider.js +2 -1
  64. package/dist/runtime/auth-flow.js +2 -0
  65. package/dist/runtime/browser.js +203 -0
  66. package/dist/runtime/http.js +46 -336
  67. package/dist/runtime/proxy-retry-policy.d.ts +40 -0
  68. package/dist/runtime/proxy-retry-policy.js +326 -0
  69. package/dist/runtime/stealth.d.ts +5 -2
  70. package/dist/runtime/stealth.js +206 -206
  71. package/dist/server/index.d.ts +4 -0
  72. package/dist/server/index.js +4 -0
  73. package/dist/server/self-test-input-tokens.d.ts +1 -0
  74. package/dist/server/self-test-input-tokens.js +37 -0
  75. package/dist/server/self-test-redaction.d.ts +20 -0
  76. package/dist/server/self-test-redaction.js +70 -0
  77. package/dist/server/self-test-token.d.ts +30 -0
  78. package/dist/server/self-test-token.js +50 -0
  79. package/dist/server/self-test.d.ts +98 -0
  80. package/dist/server/self-test.js +555 -0
  81. package/dist/server/serve.d.ts +6 -0
  82. package/dist/server/serve.js +38 -10
  83. package/dist/server/types.d.ts +1 -0
  84. package/dist/server/types.js +1 -0
  85. package/dist/testing/run.js +5 -1
  86. package/dist/types.d.ts +150 -0
  87. package/package.json +9 -2
  88. package/src/auth-turn/auth-turn.v1.schema.json +89 -0
  89. package/src/auth-turn/fixtures/invalid/empty-kind.json +4 -0
  90. package/src/auth-turn/fixtures/invalid/expires-at-not-string.json +5 -0
  91. package/src/auth-turn/fixtures/invalid/missing-kind.json +3 -0
  92. package/src/auth-turn/fixtures/invalid/missing-turn-id.json +3 -0
  93. package/src/auth-turn/fixtures/invalid/timing-unknown-field.json +7 -0
  94. package/src/auth-turn/fixtures/invalid/turn-id-snake-case.json +4 -0
  95. package/src/auth-turn/fixtures/invalid/unknown-top-level-field.json +5 -0
  96. package/src/auth-turn/fixtures/valid/abort.json +8 -0
  97. package/src/auth-turn/fixtures/valid/challenge.json +17 -0
  98. package/src/auth-turn/fixtures/valid/complete.json +13 -0
  99. package/src/auth-turn/fixtures/valid/form.json +14 -0
  100. package/src/auth-turn/fixtures/valid/message.json +13 -0
  101. package/src/auth-turn/fixtures/valid/multi_choice.json +15 -0
  102. package/src/auth-turn/fixtures/valid/pending.json +5 -0
  103. package/src/auth-turn/fixtures/valid/poll.json +9 -0
  104. package/src/auth-turn/fixtures/valid/redirect.json +16 -0
  105. package/src/auth-turn/fixtures/valid/retry.json +8 -0
  106. package/src/auth-turn/fixtures/valid/unknown-kind.json +7 -0
  107. package/src/auth-turn/index.ts +177 -0
  108. package/src/auth.ts +786 -0
  109. package/src/ceremonies/index.ts +9 -43
  110. package/src/cli/create.ts +60 -97
  111. package/src/cli/templates/provider/AGENTS.md.tpl +87 -0
  112. package/src/cli/templates/provider/CLAUDE.md.tpl +1 -0
  113. package/src/cli/templates/provider/README.md.tpl +7 -4
  114. package/src/cli/templates/provider/skills/fixtures-and-recording/SKILL.md.tpl +58 -0
  115. package/src/cli/templates/provider/skills/health-checks-and-fail-closed/SKILL.md.tpl +65 -0
  116. package/src/cli/templates/provider/skills/normalization-standards/SKILL.md.tpl +57 -0
  117. package/src/cli/templates/provider/skills/pagination-and-counts/SKILL.md.tpl +52 -0
  118. package/src/cli/templates/provider/skills/upstream-contract-verification/SKILL.md.tpl +45 -0
  119. package/src/cli/templates/provider/skills/upstream-notes/README.md.tpl +13 -0
  120. package/src/contract.ts +1 -0
  121. package/src/define.ts +198 -71
  122. package/src/index.ts +16 -0
  123. package/src/lint.ts +33 -0
  124. package/src/provider.ts +27 -0
  125. package/src/runtime/auth-flow.ts +2 -0
  126. package/src/runtime/browser.ts +293 -1
  127. package/src/runtime/http.ts +84 -530
  128. package/src/runtime/proxy-retry-policy.ts +469 -0
  129. package/src/runtime/stealth.ts +269 -353
  130. package/src/server/index.ts +36 -0
  131. package/src/server/self-test-input-tokens.ts +46 -0
  132. package/src/server/self-test-redaction.ts +97 -0
  133. package/src/server/self-test-token.ts +70 -0
  134. package/src/server/self-test.ts +725 -0
  135. package/src/server/serve.ts +75 -6
  136. package/src/server/types.ts +1 -0
  137. package/src/testing/run.ts +9 -1
  138. package/src/types.ts +186 -0
@@ -3,7 +3,7 @@ import { existsSync, readFileSync } from "node:fs";
3
3
  import { mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { dirname, relative, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
- import { cancel, intro, isCancel, note, outro, select, text, } from "@clack/prompts";
6
+ import { cancel, intro, isCancel, note, outro, select, text } from "@clack/prompts";
7
7
  import { z } from "zod";
8
8
  import packageJson from "../../package.json";
9
9
  export const PROVIDER_NAME_REGEX = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
@@ -17,12 +17,7 @@ export const CATEGORY_OPTIONS = [
17
17
  "communication",
18
18
  "other",
19
19
  ];
20
- export const AUTH_MODE_OPTIONS = [
21
- "none",
22
- "platform-managed",
23
- "credentials",
24
- "oauth2",
25
- ];
20
+ export const AUTH_MODE_OPTIONS = ["none", "platform-managed", "credentials", "oauth2"];
26
21
  export const RUNTIME_OPTIONS = ["standard", "browser"];
27
22
  export const PRESET_OPTIONS = ["standalone", "monorepo"];
28
23
  const CREATE_CONFIG_SCHEMA = z.object({
@@ -64,9 +59,7 @@ export async function main() {
64
59
  return;
65
60
  }
66
61
  const parsed = parseArgs(normalizedArgs);
67
- const config = parsed.configPath
68
- ? await loadConfig(parsed.configPath)
69
- : undefined;
62
+ const config = parsed.configPath ? await loadConfig(parsed.configPath) : undefined;
70
63
  const resolved = await resolveCreateOptions(parsed, config, process.cwd());
71
64
  const plan = await buildProviderCreatePlan(resolved, process.cwd());
72
65
  if (resolved.dryRun) {
@@ -174,9 +167,7 @@ async function resolveCreateOptions(parsed, config, cwd) {
174
167
  category: parsed.category ?? config?.category,
175
168
  authMode: parsed.authMode ?? config?.authMode,
176
169
  runtime: parsed.runtime ?? config?.runtime,
177
- sdkSpecifier: parsed.sdkSpecifier ??
178
- config?.sdkSpecifier ??
179
- process.env.APIFUSE__SDK__SPECIFIER,
170
+ sdkSpecifier: parsed.sdkSpecifier ?? config?.sdkSpecifier ?? process.env.APIFUSE__SDK__SPECIFIER,
180
171
  dryRun: parsed.dryRun,
181
172
  json: parsed.json,
182
173
  yes: parsed.yes,
@@ -267,9 +258,7 @@ async function promptValue(prompt) {
267
258
  return result;
268
259
  }
269
260
  export async function buildProviderCreatePlan(options, cwd) {
270
- const resolvedWorkspaceRoot = options.preset === "monorepo"
271
- ? findApifuseInternalWorkspaceRoot(cwd)
272
- : undefined;
261
+ const resolvedWorkspaceRoot = options.preset === "monorepo" ? findApifuseInternalWorkspaceRoot(cwd) : undefined;
273
262
  if (options.preset === "monorepo" && !resolvedWorkspaceRoot) {
274
263
  throw new Error("Monorepo preset is internal to the APIFuse repository. External bounty workspaces are one-provider repositories; use the standalone default create flow.");
275
264
  }
@@ -278,9 +267,7 @@ export async function buildProviderCreatePlan(options, cwd) {
278
267
  if (options.outputDir) {
279
268
  providerRoot = resolve(cwd, options.outputDir);
280
269
  installCwd =
281
- options.preset === "monorepo" && resolvedWorkspaceRoot
282
- ? resolvedWorkspaceRoot
283
- : providerRoot;
270
+ options.preset === "monorepo" && resolvedWorkspaceRoot ? resolvedWorkspaceRoot : providerRoot;
284
271
  }
285
272
  else if (options.preset === "monorepo" && resolvedWorkspaceRoot) {
286
273
  providerRoot = resolve(resolvedWorkspaceRoot, "providers", options.name);
@@ -293,8 +280,7 @@ export async function buildProviderCreatePlan(options, cwd) {
293
280
  if (existsSync(providerRoot)) {
294
281
  throw new Error(`Target directory already exists: ${providerRoot}`);
295
282
  }
296
- if (options.sdkSpecifier?.startsWith("workspace:") &&
297
- !resolvedWorkspaceRoot) {
283
+ if (options.sdkSpecifier?.startsWith("workspace:") && !resolvedWorkspaceRoot) {
298
284
  throw new Error("workspace:* is only valid inside the APIFuse monorepo because public Provider SDK scaffolds must install from npm or an explicit tarball/file specifier.");
299
285
  }
300
286
  const sdkSpecifier = options.sdkSpecifier ??
@@ -419,6 +405,38 @@ export async function buildProviderCreatePlan(options, cwd) {
419
405
  PROVIDER_ID: options.name,
420
406
  }),
421
407
  },
408
+ {
409
+ path: resolve(providerRoot, "AGENTS.md"),
410
+ content: await renderTemplate("AGENTS.md.tpl", {}),
411
+ },
412
+ {
413
+ path: resolve(providerRoot, "CLAUDE.md"),
414
+ content: await renderTemplate("CLAUDE.md.tpl", {}),
415
+ },
416
+ {
417
+ path: resolve(providerRoot, "skills", "normalization-standards", "SKILL.md"),
418
+ content: await renderTemplate("skills/normalization-standards/SKILL.md.tpl", {}),
419
+ },
420
+ {
421
+ path: resolve(providerRoot, "skills", "upstream-contract-verification", "SKILL.md"),
422
+ content: await renderTemplate("skills/upstream-contract-verification/SKILL.md.tpl", {}),
423
+ },
424
+ {
425
+ path: resolve(providerRoot, "skills", "fixtures-and-recording", "SKILL.md"),
426
+ content: await renderTemplate("skills/fixtures-and-recording/SKILL.md.tpl", {}),
427
+ },
428
+ {
429
+ path: resolve(providerRoot, "skills", "pagination-and-counts", "SKILL.md"),
430
+ content: await renderTemplate("skills/pagination-and-counts/SKILL.md.tpl", {}),
431
+ },
432
+ {
433
+ path: resolve(providerRoot, "skills", "health-checks-and-fail-closed", "SKILL.md"),
434
+ content: await renderTemplate("skills/health-checks-and-fail-closed/SKILL.md.tpl", {}),
435
+ },
436
+ {
437
+ path: resolve(providerRoot, "skills", "upstream-notes", "README.md"),
438
+ content: await renderTemplate("skills/upstream-notes/README.md.tpl", {}),
439
+ },
422
440
  ];
423
441
  return {
424
442
  displayName: options.displayName,
@@ -434,7 +452,7 @@ export async function buildProviderCreatePlan(options, cwd) {
434
452
  validationCommands: [
435
453
  "bun run check",
436
454
  "bun run type-check",
437
- "bun run submit-check",
455
+ "bun run submit-check -- --smoke",
438
456
  "bun run test",
439
457
  ],
440
458
  workspaceRoot: resolvedWorkspaceRoot,
@@ -461,7 +479,6 @@ function renderPackageJson(input) {
461
479
  "submit-check": "apifuse submit-check . --markdown submission-report.md",
462
480
  test: "apifuse test .",
463
481
  record: "apifuse record .",
464
- "perf:sample": "apifuse perf . --operation ping --runs 3",
465
482
  start: "bun start.ts",
466
483
  },
467
484
  dependencies: {
@@ -544,8 +561,8 @@ function renderAuthBlock(authMode) {
544
561
  return `{
545
562
  mode: "credentials",
546
563
  flow: {
547
- start: async () => ({
548
- kind: "input",
564
+ start: async (_ctx) => ({
565
+ kind: "form",
549
566
  turnId: crypto.randomUUID(),
550
567
  expectedInput: {
551
568
  schema: {
@@ -588,7 +605,7 @@ function renderAuthBlock(authMode) {
588
605
  return `{
589
606
  mode: "oauth2",
590
607
  flow: {
591
- start: async () => ({
608
+ start: async (_ctx) => ({
592
609
  kind: "redirect",
593
610
  turnId: crypto.randomUUID(),
594
611
  data: {
@@ -716,9 +733,7 @@ async function runCommand(command, cwd, jsonMode) {
716
733
  resolvePromise();
717
734
  return;
718
735
  }
719
- rejectPromise(new Error(`Command failed (${command}) in ${cwd}${stdout || stderr
720
- ? `\n${[stdout, stderr].filter(Boolean).join("\n")}`
721
- : ""}`));
736
+ rejectPromise(new Error(`Command failed (${command}) in ${cwd}${stdout || stderr ? `\n${[stdout, stderr].filter(Boolean).join("\n")}` : ""}`));
722
737
  });
723
738
  });
724
739
  }
@@ -752,7 +767,7 @@ function printResult(plan, jsonMode, dryRun) {
752
767
  console.log(`Validation: (cd ${plan.providerRoot} && ${command})`);
753
768
  }
754
769
  console.log(`Next local dev: ${plan.nextDevCommand}`);
755
- console.log("Submission evidence: run `bun run submit-check`, save the generated report, and note `/health` plus `POST /v1/{operation}` smoke results.");
770
+ console.log("Submission evidence: run `bun run submit-check -- --smoke` to archive measured `/health` and `POST /v1/{operation}` results.");
756
771
  if (plan.files.some((file) => file.content.includes('runtime: "browser"'))) {
757
772
  console.log("Browser runtime: run `bunx playwright install chromium` locally or set `APIFUSE__CDP_POOL__URL` before browser-backed smoke tests.");
758
773
  }
@@ -0,0 +1,22 @@
1
+ node_modules/
2
+ .git/
3
+ .github/
4
+
5
+ # Environment and local secrets
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+
10
+ # Local reports and generated artifacts
11
+ submission-report.md
12
+ coverage/
13
+ dist/
14
+ .cache/
15
+ .turbo/
16
+ .bun/
17
+ *.tsbuildinfo
18
+
19
+ # OS/editor junk
20
+ .DS_Store
21
+ Thumbs.db
22
+ *.swp
@@ -0,0 +1,22 @@
1
+ node_modules/
2
+
3
+ # Environment and local secrets
4
+ .env
5
+ .env.*
6
+ !.env.example
7
+
8
+ # Build, coverage, cache, and local runtime artifacts
9
+ coverage/
10
+ dist/
11
+ .cache/
12
+ .turbo/
13
+ .bun/
14
+ *.tsbuildinfo
15
+
16
+ # Bounty submission output
17
+ submission-report.md
18
+
19
+ # OS/editor junk
20
+ .DS_Store
21
+ Thumbs.db
22
+ *.swp
@@ -0,0 +1,87 @@
1
+ # APIFuse Provider Workspace — Agent Guide
2
+
3
+ You are building an APIFuse provider. APIFuse turns messy upstream APIs into
4
+ normalized, typed, evidence-backed public APIs. A provider that merely proxies
5
+ the upstream is a failed provider, even if every check passes.
6
+
7
+ This file is the core contract. Detailed procedures live in `skills/` — load
8
+ the matching skill BEFORE working on that area (index at the bottom).
9
+
10
+ ## Non-negotiable principles
11
+
12
+ ### 1. Normalize, don't proxy
13
+ Public output is an APIFuse contract, not the upstream's shape.
14
+ - Field names: `snake_case`, semantic, English. Never leak vendor keys
15
+ (`dutyTel1`, `hvec`, `MKioskTy7`) into public output.
16
+ - Timestamps: ISO 8601 in public output. Vendor formats (`20260707222855`)
17
+ are parsed inside mappers only. If a value cannot be parsed, omit/null it —
18
+ never pass the raw vendor string through.
19
+ - Enums: normalize vendor status text/codes (`Y` / `불가능` / `정보미제공`) into a
20
+ declared enum. Mixed raw-text passthrough is a contract failure.
21
+ - Units: every numeric field name states its unit (`distance_meters`), and the
22
+ mapper proves the conversion. Never relabel an upstream number without
23
+ verifying its unit against docs or live data.
24
+
25
+ ### 2. Fail closed, never fabricate
26
+ - Never invent output values to satisfy a schema. Missing upstream data → null
27
+ field or structured error, never a plausible dummy.
28
+ - Parse failures are errors, not defaults. Returning `0`, `[]`, or `null`
29
+ when the upstream shape changed hides breakage from every downstream gate.
30
+ - If a non-empty upstream collection normalizes to zero rows, throw
31
+ `UPSTREAM_SCHEMA_ERROR` — silent empty success is the worst failure mode.
32
+ - Model the upstream's real value domain. Check live data before adding
33
+ constraints like `nonnegative()` — some upstreams legitimately return
34
+ negative counts (e.g. overcapacity) and a wrong constraint silently
35
+ nulls real data.
36
+
37
+ ### 3. Preserve every input or fail loudly
38
+ - Every accepted input must be representable in the upstream request. If it
39
+ isn't, reject at the schema or throw — never silently drop it.
40
+ - Upstream parameter dependencies (param B ignored without param A) must be
41
+ enforced in YOUR schema. The upstream ignoring input silently is not an
42
+ excuse for your provider to do the same.
43
+
44
+ ### 4. Evidence over assumption
45
+ - Upstream parameter names and response fields must be verified against the
46
+ official spec AND at least one live call. Do not guess casing or
47
+ underscores; do not copy from a sibling API without re-verifying.
48
+ - No speculative field probing (`row.distance ?? row.dist ?? row.Distance`).
49
+ Map exactly the fields you have evidence for. One verified name per field.
50
+ - Fixtures are recorded live evidence (`bun run record`), never hand-written.
51
+ Placeholder-looking values (`02-1234-5678`, "테헤란로 123") mean the fixture
52
+ is fabricated and the submission is not reviewable.
53
+ - An empty result set from a dense query (0 hospitals within 5km of a city
54
+ center) is a request bug, not a valid fixture. Investigate before recording.
55
+
56
+ ### 5. Honest pagination and counts
57
+ - If you filter rows client-side, the upstream `totalCount` is no longer your
58
+ `total_count`. Either expose upstream semantics honestly (documented) or
59
+ don't expose a total at all. A count the caller cannot page against is a lie.
60
+
61
+ ### 6. Health checks must detect real regressions
62
+ - `Array.isArray(data.items)` alone can never fail. Every list operation's
63
+ health check must also flag the zero-rows case for a query that is known to
64
+ return data (dense-area query), so a broken upstream contract degrades
65
+ visibly instead of passing forever.
66
+
67
+ ## Verification loop (before every submit)
68
+
69
+ ```bash
70
+ bun run check # apifuse check + type-check
71
+ bun run test # your tests — cover mappers, error paths, edge rows
72
+ bun run submit-check # structural score; a high score does NOT prove quality
73
+ ```
74
+
75
+ `submit-check` is a structural gate. Every principle above can be violated
76
+ while scoring 95/100 — reviewers and CI audit for exactly these classes.
77
+
78
+ ## Skill index — load before working on:
79
+
80
+ | Area | Load |
81
+ | --- | --- |
82
+ | Output schemas, mappers, field naming, timestamps, enums | `skills/normalization-standards/SKILL.md` |
83
+ | Upstream request params, new endpoint wiring, field mapping | `skills/upstream-contract-verification/SKILL.md` |
84
+ | Recording fixtures, writing tests against fixtures | `skills/fixtures-and-recording/SKILL.md` |
85
+ | List operations, paging, totals, client-side filtering | `skills/pagination-and-counts/SKILL.md` |
86
+ | healthCheck blocks, error classification, fail-closed guards | `skills/health-checks-and-fail-closed/SKILL.md` |
87
+ | Upstream-specific known pitfalls for THIS bounty | `skills/upstream-notes/` (read every file) |
@@ -0,0 +1 @@
1
+ @AGENTS.md
@@ -0,0 +1,7 @@
1
+ FROM oven/bun:1.2-alpine
2
+ WORKDIR /provider
3
+ COPY package.json bun.lockb* ./
4
+ RUN bun install --frozen-lockfile
5
+ COPY . .
6
+ EXPOSE 3000
7
+ CMD ["bun", "run", "start"]
@@ -0,0 +1,163 @@
1
+ # {{DISPLAY_NAME}}
2
+
3
+ Generated with `apifuse create`.
4
+
5
+ ## Commands
6
+
7
+ ```bash
8
+ bun run dev
9
+ bun run check
10
+ bun run test
11
+ bun run submit-check -- --smoke
12
+ bunx apifuse perf . --operation <operation-id> --runs 3
13
+ ```
14
+
15
+
16
+ ## Module layout
17
+
18
+ The generated provider uses the recommended split layout:
19
+
20
+ ```text
21
+ index.ts # composition root: defineProvider() and wiring only
22
+ meta.ts # provider metadata
23
+ operations/ # APIFuse operation contracts and handlers
24
+ schemas/ # public input/output schemas near operations
25
+ upstream/ # upstream ceremony: clients, auth, request builders
26
+ mappers/ # upstream-to-APIFuse normalization helpers
27
+ domain/ # shared provider-specific business ceremony
28
+ ```
29
+
30
+ Small providers may stay in one file, but larger providers are easier to
31
+ review when `index.ts` remains a short composition root.
32
+
33
+ ## Pre-submission report
34
+
35
+ Before posting bounty evidence, run:
36
+
37
+ ```bash
38
+ bun run submit-check -- --smoke
39
+ ```
40
+
41
+ This writes `submission-report.md` with a review-readiness score, blockers,
42
+ warnings, health coverage notes, fixture/schema evidence, and remediation. A
43
+ score is not a payout guarantee; blockers must be fixed before maintainer
44
+ review. The generated `ping` starter intentionally warns until you replace it
45
+ with real upstream-backed Operations. `APIFUSE__PROVIDER__*` env vars enable
46
+ live upstream calls; without them, structured provider errors can still verify
47
+ runtime routing. The full public-only checklist is shipped in
48
+ `node_modules/@apifuse/provider-sdk/SUBMISSION.md`.
49
+
50
+
51
+ ## Operation guide
52
+
53
+ ### Parameters
54
+
55
+ Starter `ping` accepts `{ "value": string }`. Replace this section with each
56
+ real operation's input schema, required fields, formats, limits, and examples
57
+ before submitting bounty evidence.
58
+
59
+ ### Response
60
+
61
+ Starter `ping` returns `{ "ok": boolean, "message": string }`. Replace this
62
+ section with the normalized response fields, units, enum values, pagination,
63
+ and upstream caveats for each real operation.
64
+
65
+ ### Example
66
+
67
+ ```json
68
+ {
69
+ "requestId": "req_local_ping",
70
+ "input": { "value": "hello" },
71
+ "headers": {}
72
+ }
73
+ ```
74
+
75
+ ## Provider server contract
76
+
77
+ - Dev default: `3900`
78
+ - Start/Docker/container contract: `3000`
79
+ - `GET /health`
80
+ - `POST /v1/{operation}`
81
+ - `POST /auth/start`
82
+ - `POST /auth/continue`
83
+ - `POST /auth/poll`
84
+ - `POST /auth/disconnect`
85
+
86
+ ## Local smoke
87
+
88
+ ```bash
89
+ curl -s http://localhost:3900/health
90
+ curl -s -X POST http://localhost:3900/v1/ping \
91
+ -H 'Content-Type: application/json' \
92
+ -d '{"requestId":"req_local_ping","input":{"value":"hello"},"headers":{}}'
93
+ ```
94
+
95
+ The `POST /v1/{operation}` body is a request envelope:
96
+
97
+ - `requestId` is required and can be any unique local debugging string.
98
+ - `input` contains the operation input shape.
99
+ - `headers` is optional.
100
+ - `connection` is optional; omit it for no-auth/public operations. For
101
+ credential debugging, pass `{ "id", "mode", "secrets", "metadata",
102
+ "externalRef" }` with local-only secret values.
103
+
104
+ Structured errors return an `error` object with `code`, `message`,
105
+ `requestId`, and optional `details`; validation failures include field paths in
106
+ `details`, and the `apifuse dev` terminal prints a structured provider log.
107
+
108
+ ## Debugging checklist
109
+
110
+ - `invalid_request`: include `requestId` and `input`; omit `connection` for
111
+ public/no-auth operations and never send `connection: null`.
112
+ - Credentials: declare `credential.keys`, pass local-only values through
113
+ `connection.secrets`, and read them with `ctx.credential`.
114
+ - Auth flow: call `/auth/start`, then `/auth/continue` with the same `flowId`;
115
+ carry returned `contextPatch` values into the next request's `context`.
116
+ - Stealth/browser runtime: keep access-sensitive operations on `ctx.stealth.fetch()` with an
117
+ SDK stealth `profile`; the TypeScript stealth runtime uses `impit` internally.
118
+ `ctx.stealth` supports Chrome/Firefox-style profiles. For TypeScript browser
119
+ Providers or Safari-specific behavior use `browser.engine: "playwright-stealth"`
120
+ (`nodriver` is Python-runtime only), then install local Chromium with
121
+ `bunx playwright install chromium` or set `APIFUSE__CDP_POOL__URL`.
122
+
123
+ ## Next steps
124
+
125
+ 1. Replace the sample `ping` operation with real upstream logic.
126
+ 2. Once the real operation declares `upstream.baseUrl` and uses `ctx.http` or
127
+ `ctx.stealth`, record a fixture with:
128
+ `bun run record -- --operation <operation> --params '<json-input>'`.
129
+ 3. Replace the starter `healthCheckUnsupported` with a real `healthCheck` for read-only upstream operations when safe.
130
+ 4. Extend tests and operation metadata until the provider is bounty-ready.
131
+
132
+ `apifuse record` is not expected to work with the generated local-only `ping`
133
+ operation because it intentionally has no upstream response to capture.
134
+
135
+ ## Health-check authorship
136
+
137
+ Every operation must declare exactly one of:
138
+
139
+ - `healthCheck` — preferred for safe read-only upstream probes.
140
+ - `healthCheckUnsupported` — allowed only when a probe is destructive, paid,
141
+ credential-sensitive, flaky by design, or otherwise unsafe. Use a specific
142
+ reason; reviewers reject placeholder reasons such as "TODO" or "later".
143
+
144
+ The generated `ping` operation uses `healthCheckUnsupported` only because it is
145
+ a local scaffold check, not a real upstream API probe.
146
+
147
+ `healthCheck.cases[].assertions` receives `{ data, status, durationMs, meta }`.
148
+ `data` is the parsed operation output. Use this shape in real operations:
149
+
150
+ ```ts
151
+ healthCheck: {
152
+ interval: "5m",
153
+ cases: [{
154
+ name: "lookup baseline",
155
+ input: { q: "btc" },
156
+ assertions: ({ data, status, durationMs }) => {
157
+ if (status !== 200 || data.results.length === 0 || durationMs > 3000) {
158
+ return { status: "degraded", label: "lookup baseline changed" };
159
+ }
160
+ },
161
+ }],
162
+ }
163
+ ```
@@ -0,0 +1,5 @@
1
+ import { startDevServer } from "@apifuse/provider-sdk";
2
+
3
+ import provider from "./index";
4
+
5
+ startDevServer(provider, { port: Number(process.env.APIFUSE__RUNTIME__PORT) || 3900 });
@@ -0,0 +1,3 @@
1
+ # Domain
2
+
3
+ Put provider-specific business ceremony here when it is shared across operations and too complex to live inside one operation module.
@@ -0,0 +1,13 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { runStandardTests } from "@apifuse/provider-sdk/testing";
3
+
4
+ import provider from "../index";
5
+
6
+ runStandardTests(provider);
7
+
8
+ describe("{{PROVIDER_ID}}", () => {
9
+ it("exposes provider metadata from defineProvider", () => {
10
+ expect(provider.id).toBe("{{PROVIDER_ID}}");
11
+ expect(provider.reviewed).toBe("community");
12
+ });
13
+ });
@@ -0,0 +1,15 @@
1
+ import { defineProvider } from "@apifuse/provider-sdk/provider";
2
+
3
+ import { providerMeta } from "./meta";
4
+ import { operations } from "./operations";
5
+
6
+ export default defineProvider({
7
+ id: "{{PROVIDER_ID}}",
8
+ version: "1.0.0",
9
+ runtime: "{{RUNTIME}}"{{BROWSER_BLOCK}},
10
+ allowedHosts: ["api.example.com"],
11
+ reviewed: "community",
12
+ {{SECRETS_BLOCK}}{{CREDENTIAL_BLOCK}}auth: {{AUTH_BLOCK}},
13
+ meta: providerMeta,
14
+ operations: operations,
15
+ });
@@ -0,0 +1,3 @@
1
+ # Mappers
2
+
3
+ Put normalization helpers here when upstream responses need to become public APIFuse operation outputs.
@@ -0,0 +1,7 @@
1
+ export const providerMeta = {
2
+ displayName: "{{PROVIDER_ID}}",
3
+ displayNameKey: "meta.displayName",
4
+ descriptionKey: "meta.description",
5
+ category: "{{CATEGORY}}",
6
+ tags: ["{{PROVIDER_ID}}", "starter", "community"],
7
+ } as const;
@@ -0,0 +1,5 @@
1
+ import { pingOperation } from "./ping";
2
+
3
+ export const operations = {
4
+ ping: pingOperation,
5
+ };
@@ -0,0 +1,24 @@
1
+ import { defineOperation } from "@apifuse/provider-sdk/provider";
2
+
3
+ import { pingInputSchema, pingOutputSchema } from "../schemas/ping";
4
+
5
+ export const pingOperation = defineOperation({
6
+ descriptionKey: "operations.ping.description",
7
+ input: pingInputSchema,
8
+ output: pingOutputSchema,
9
+ handler: async ({{HANDLER_CTX}}, input) => {
10
+ {{BROWSER_HANDLER_BLOCK}}
11
+ return {
12
+ ok: true,
13
+ message: "{{DISPLAY_NAME}} received: " + input.value{{BROWSER_RESPONSE_FIELDS}},
14
+ };
15
+ },
16
+ fixtures: {
17
+ request: { value: "hello" },
18
+ response: { ok: true, message: "{{DISPLAY_NAME}} received: hello" },
19
+ },
20
+ healthCheckUnsupported: {
21
+ reason:
22
+ "Generated local-only scaffold operation. Replace this with a real healthCheck for upstream-backed bounty operations when safe; keep healthCheckUnsupported only for destructive, paid, credential-sensitive, or otherwise unprobeable operations with a specific rationale.",
23
+ },
24
+ });
@@ -0,0 +1,24 @@
1
+ import { describeKey, z } from "@apifuse/provider-sdk/provider";
2
+
3
+ export const pingInputSchema = describeKey(
4
+ z.object({
5
+ value: describeKey(z.string(), "schemaDescriptions.input.value"),
6
+ }),
7
+ "schemaDescriptions.input.root",
8
+ );
9
+
10
+ export const pingOutputSchema = describeKey(
11
+ z.object({
12
+ ok: describeKey(z.boolean(), "schemaDescriptions.output.ok"),
13
+ message: describeKey(z.string(), "schemaDescriptions.output.message"),
14
+ pageTitle: describeKey(
15
+ z.string().optional(),
16
+ "schemaDescriptions.output.pageTitle",
17
+ ),
18
+ frameCount: describeKey(
19
+ z.number().int().nonnegative().optional(),
20
+ "schemaDescriptions.output.frameCount",
21
+ ),
22
+ }),
23
+ "schemaDescriptions.output.root",
24
+ );
@@ -0,0 +1,58 @@
1
+ ---
2
+ name: fixtures-and-recording
3
+ description: Recording live fixtures and writing trustworthy tests from them. Load before touching __fixtures__/ or writing operation tests.
4
+ ---
5
+
6
+ # Fixtures and recording
7
+
8
+ Fixtures are evidence, not examples. Reviewers treat fixtures as proof your
9
+ provider ran against the real upstream.
10
+
11
+ ## Recording
12
+ - Always record from the live upstream: `bun run record -- --operation <op>
13
+ --params '<json>'` with the real service key configured.
14
+ - Record queries that RETURN DATA. Choose dense/known-good inputs (major city
15
+ district, a real entity id from a prior list call).
16
+ - Re-record after any request-param or mapper change; stale fixtures make
17
+ every downstream test meaningless.
18
+
19
+ ## Forbidden fixture states
20
+ - **Hand-written fixtures.** Values like `02-1234-5678`, "테헤란로 123",
21
+ round-number coordinates, or sequential ids are fabrication tells. If it
22
+ wasn't returned by the upstream, it cannot be in `__fixtures__/`.
23
+ - **Empty-result fixtures for dense queries.** `items: [], total_count: 0`
24
+ for "hospitals within 5km of Gangnam" is not a fixture — it is an
25
+ unfixed request bug (wrong param name/format). Investigate first.
26
+ - **Fixtures that contradict each other.** If one operation's fixture proves
27
+ `total_count: 541` while returning 1 filtered row, your count semantics are
28
+ broken (see pagination skill), not your fixture.
29
+
30
+ ## Fixture shape
31
+ `apifuse record` (`bun run record`) writes the captured RAW UPSTREAM payload
32
+ to `__fixtures__/raw.json` (secrets sanitized). With `--append` it
33
+ accumulates an array of raw payloads. The recorder does NOT write your
34
+ normalized output — raw.json is upstream evidence only.
35
+
36
+ Derive normalized expectations in TESTS, not in the fixture file: load the
37
+ recorded raw payload, run your mapper over it, and assert the exact expected
38
+ normalized rows inline in the test. If you keep expected-output snapshots,
39
+ generate them from the mapper and review them row by row — never hand-author
40
+ values that the upstream did not return.
41
+
42
+ ## Tests to derive from fixtures
43
+ - Mapper: `map(recordedUpstreamRow)` equals the expected normalized row
44
+ (toEqual, not toMatchObject, for full rows — partial matching hides
45
+ dropped fields).
46
+ - Edge rows: single-item object vs array (`items.item` unwrapping), missing
47
+ optional fields, unpadded/numeric time values, vendor error headers.
48
+ - Error paths: upstream error `resultCode`, HTTP failure, missing secret,
49
+ NO_DATA — each asserts the structured `ProviderError` code.
50
+ - Handler-level: run the operation handler against a mock ctx that returns
51
+ the fixture upstream body; assert the full normalized envelope.
52
+
53
+ ## Checklist
54
+ - [ ] Every fixture recorded live; no placeholder-looking values
55
+ - [ ] No empty-result fixture for a query that must have data
56
+ - [ ] normalized expectations derived from mapper(recorded raw), not
57
+ hand-authored
58
+ - [ ] Error and edge-shape rows covered, not just the happy row