@apifuse/provider-sdk 2.2.0-beta.2 → 2.2.0-beta.20

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 (290) hide show
  1. package/AUTHORING.md +487 -0
  2. package/CHANGELOG.md +85 -0
  3. package/README.md +49 -3
  4. package/SUBMISSION.md +1 -1
  5. package/bin/apifuse-check.ts +44 -59
  6. package/bin/apifuse-create.ts +1 -1
  7. package/bin/apifuse-dev.ts +27 -52
  8. package/bin/apifuse-pack-check.ts +14 -0
  9. package/bin/apifuse-pack-smoke.ts +36 -81
  10. package/bin/apifuse-pack-types.ts +305 -0
  11. package/bin/apifuse-perf.ts +45 -127
  12. package/bin/apifuse-record.ts +659 -111
  13. package/bin/apifuse-submit-check.ts +546 -48
  14. package/bin/apifuse-sync-assets.ts +117 -0
  15. package/bin/apifuse.ts +1 -1
  16. package/bin/submit-check-delimited-text.ts +50 -0
  17. package/bin/submit-check-xml-semantics.ts +204 -0
  18. package/bin/submit-check-xml.ts +134 -0
  19. package/dist/auth-turn/index.d.ts +3 -3
  20. package/dist/auth.d.ts +2 -2
  21. package/dist/auth.js +9 -18
  22. package/dist/ceremonies/index.d.ts +1 -1
  23. package/dist/ceremonies/index.js +8 -18
  24. package/dist/cli/commands.d.ts +1 -1
  25. package/dist/cli/commands.js +8 -0
  26. package/dist/cli/create.d.ts +3 -0
  27. package/dist/cli/create.js +34 -35
  28. package/dist/cli/prompt-assets.d.ts +80 -0
  29. package/dist/cli/prompt-assets.js +743 -0
  30. package/dist/cli/templates/provider/AGENTS.md.tpl +17 -8
  31. package/dist/config/loader.d.ts +176 -8
  32. package/dist/config/loader.js +424 -95
  33. package/dist/contract-serialization.d.ts +2 -2
  34. package/dist/contract-serialization.js +3 -6
  35. package/dist/contract-types.d.ts +2 -2
  36. package/dist/contract.d.ts +3 -3
  37. package/dist/contract.js +4 -6
  38. package/dist/define.d.ts +9 -1
  39. package/dist/define.js +208 -125
  40. package/dist/dev.d.ts +1 -1
  41. package/dist/dev.js +1 -1
  42. package/dist/error-resolution.d.ts +2 -0
  43. package/dist/error-resolution.js +90 -0
  44. package/dist/errors.d.ts +22 -1
  45. package/dist/errors.js +88 -0
  46. package/dist/fixture-sanitization.d.ts +26 -0
  47. package/dist/fixture-sanitization.js +216 -0
  48. package/dist/i18n/catalog.d.ts +2 -2
  49. package/dist/i18n/catalog.js +4 -10
  50. package/dist/i18n/index.d.ts +2 -2
  51. package/dist/i18n/index.js +2 -2
  52. package/dist/i18n/keys.d.ts +2 -2
  53. package/dist/index.d.ts +46 -42
  54. package/dist/index.js +41 -37
  55. package/dist/lint.js +8 -15
  56. package/dist/native-address.d.ts +43 -0
  57. package/dist/native-address.js +281 -0
  58. package/dist/native-egress-policy.d.ts +31 -0
  59. package/dist/native-egress-policy.js +288 -0
  60. package/dist/observability.d.ts +5 -2
  61. package/dist/observability.js +48 -1
  62. package/dist/provider.d.ts +12 -11
  63. package/dist/provider.js +10 -9
  64. package/dist/public-schema-field-lint.d.ts +1 -1
  65. package/dist/recipes/gov-api.js +1 -1
  66. package/dist/runtime/auth-flow.d.ts +1 -1
  67. package/dist/runtime/auth-flow.js +3 -3
  68. package/dist/runtime/browser.d.ts +1 -1
  69. package/dist/runtime/browser.js +15 -29
  70. package/dist/runtime/cache.d.ts +1 -1
  71. package/dist/runtime/cache.js +4 -8
  72. package/dist/runtime/choice.d.ts +1 -1
  73. package/dist/runtime/choice.js +31 -35
  74. package/dist/runtime/credential.d.ts +1 -1
  75. package/dist/runtime/credential.js +1 -1
  76. package/dist/runtime/env.d.ts +1 -1
  77. package/dist/runtime/executor.d.ts +1 -1
  78. package/dist/runtime/executor.js +31 -4
  79. package/dist/runtime/http.d.ts +2 -2
  80. package/dist/runtime/http.js +387 -47
  81. package/dist/runtime/insights.d.ts +1 -1
  82. package/dist/runtime/insights.js +6 -13
  83. package/dist/runtime/instrumentation.d.ts +2 -2
  84. package/dist/runtime/instrumentation.js +345 -22
  85. package/dist/runtime/keyring.js +1 -1
  86. package/dist/runtime/namespace.js +1 -1
  87. package/dist/runtime/native-network.d.ts +127 -0
  88. package/dist/runtime/native-network.js +1298 -0
  89. package/dist/runtime/otlp.d.ts +1 -1
  90. package/dist/runtime/perf.d.ts +1 -1
  91. package/dist/runtime/provider.d.ts +1 -1
  92. package/dist/runtime/provider.js +1 -2
  93. package/dist/runtime/proxy-errors.d.ts +1 -1
  94. package/dist/runtime/proxy-errors.js +9 -7
  95. package/dist/runtime/proxy-nodemaven.d.ts +56 -0
  96. package/dist/runtime/proxy-nodemaven.js +146 -0
  97. package/dist/runtime/proxy-retry-policy.d.ts +2 -2
  98. package/dist/runtime/proxy-retry-policy.js +2 -2
  99. package/dist/runtime/proxy-telemetry.d.ts +2 -1
  100. package/dist/runtime/proxy-telemetry.js +55 -52
  101. package/dist/runtime/redirects.d.ts +29 -0
  102. package/dist/runtime/redirects.js +36 -0
  103. package/dist/runtime/redis.d.ts +1 -1
  104. package/dist/runtime/redis.js +2 -4
  105. package/dist/runtime/request-options.d.ts +68 -1
  106. package/dist/runtime/request-options.js +548 -0
  107. package/dist/runtime/secrets.d.ts +27 -0
  108. package/dist/runtime/secrets.js +51 -0
  109. package/dist/runtime/state.d.ts +2 -2
  110. package/dist/runtime/state.js +15 -4
  111. package/dist/runtime/stealth.d.ts +5 -3
  112. package/dist/runtime/stealth.js +423 -143
  113. package/dist/runtime/stt.d.ts +1 -1
  114. package/dist/runtime/stt.js +11 -15
  115. package/dist/runtime/trace.d.ts +2 -2
  116. package/dist/runtime/trace.js +2 -4
  117. package/dist/runtime/waterfall.d.ts +1 -1
  118. package/dist/schema.d.ts +1 -1
  119. package/dist/schema.js +7 -15
  120. package/dist/serve.d.ts +1 -1
  121. package/dist/serve.js +1 -1
  122. package/dist/server/index.d.ts +7 -7
  123. package/dist/server/index.js +6 -6
  124. package/dist/server/self-test-input-tokens.d.ts +2 -1
  125. package/dist/server/self-test-input-tokens.js +18 -14
  126. package/dist/server/self-test-redaction.d.ts +1 -1
  127. package/dist/server/self-test-redaction.js +1 -1
  128. package/dist/server/self-test.d.ts +104 -3
  129. package/dist/server/self-test.js +673 -115
  130. package/dist/server/serve.d.ts +115 -4
  131. package/dist/server/serve.js +792 -127
  132. package/dist/server/types.d.ts +30 -9
  133. package/dist/server/types.js +8 -7
  134. package/dist/stateful/errors.d.ts +14 -0
  135. package/dist/stateful/errors.js +14 -0
  136. package/dist/stateful/http-provider-event-emitter.d.ts +40 -0
  137. package/dist/stateful/http-provider-event-emitter.js +237 -0
  138. package/dist/stateful/http-session-owner-registry.d.ts +44 -0
  139. package/dist/stateful/http-session-owner-registry.js +210 -0
  140. package/dist/stateful/index.d.ts +18 -0
  141. package/dist/stateful/index.js +18 -0
  142. package/dist/stateful/provider-event-delivery-failures.d.ts +32 -0
  143. package/dist/stateful/provider-event-delivery-failures.js +43 -0
  144. package/dist/stateful/provider-event-pipeline-metrics.d.ts +46 -0
  145. package/dist/stateful/provider-event-pipeline-metrics.js +48 -0
  146. package/dist/stateful/provider-event-pipeline.d.ts +50 -0
  147. package/dist/stateful/provider-event-pipeline.js +1 -0
  148. package/dist/stateful/provider-events.d.ts +101 -0
  149. package/dist/stateful/provider-events.js +289 -0
  150. package/dist/stateful/session-key.d.ts +15 -0
  151. package/dist/stateful/session-key.js +86 -0
  152. package/dist/stateful/stateful-provider-adapter-context.d.ts +5 -0
  153. package/dist/stateful/stateful-provider-adapter-context.js +42 -0
  154. package/dist/stateful/stateful-provider-adapter-metrics.d.ts +15 -0
  155. package/dist/stateful/stateful-provider-adapter-metrics.js +21 -0
  156. package/dist/stateful/stateful-provider-adapter.d.ts +98 -0
  157. package/dist/stateful/stateful-provider-adapter.js +287 -0
  158. package/dist/stateful/stateful-provider-observability.d.ts +62 -0
  159. package/dist/stateful/stateful-provider-observability.js +161 -0
  160. package/dist/stateful/stateful-provider-owner-forwarder.d.ts +41 -0
  161. package/dist/stateful/stateful-provider-owner-forwarder.js +215 -0
  162. package/dist/stateful/stateful-provider-runtime-context.d.ts +32 -0
  163. package/dist/stateful/stateful-provider-runtime-context.js +60 -0
  164. package/dist/stateful/stateful-provider-runtime-executor.d.ts +34 -0
  165. package/dist/stateful/stateful-provider-runtime-executor.js +52 -0
  166. package/dist/stateful/stateful-provider-session-routing.d.ts +71 -0
  167. package/dist/stateful/stateful-provider-session-routing.js +353 -0
  168. package/dist/stateful/stateful-provider-session-runtime.d.ts +98 -0
  169. package/dist/stateful/stateful-provider-session-runtime.js +245 -0
  170. package/dist/stateful-signing.d.ts +18 -0
  171. package/dist/stateful-signing.js +27 -0
  172. package/dist/stealth/profiles.d.ts +1 -1
  173. package/dist/stealth/profiles.js +5 -14
  174. package/dist/stream-evidence.d.ts +74 -0
  175. package/dist/stream-evidence.js +785 -0
  176. package/dist/stream.d.ts +1 -1
  177. package/dist/testing/index.d.ts +2 -2
  178. package/dist/testing/index.js +2 -2
  179. package/dist/testing/run.d.ts +32 -2
  180. package/dist/testing/run.js +477 -33
  181. package/dist/types.d.ts +323 -11
  182. package/dist/types.js +1 -0
  183. package/dist/user-input.d.ts +30 -0
  184. package/dist/user-input.js +66 -0
  185. package/package.json +16 -5
  186. package/src/auth-turn/index.ts +1 -1
  187. package/src/auth.ts +28 -86
  188. package/src/ceremonies/index.ts +24 -78
  189. package/src/cli/commands.ts +10 -0
  190. package/src/cli/create.ts +42 -35
  191. package/src/cli/prompt-assets.ts +865 -0
  192. package/src/cli/templates/provider/AGENTS.md.tpl +17 -8
  193. package/src/config/loader.ts +652 -204
  194. package/src/contract-serialization.ts +5 -11
  195. package/src/contract-types.ts +2 -2
  196. package/src/contract.ts +12 -28
  197. package/src/define.ts +368 -504
  198. package/src/dev.ts +4 -9
  199. package/src/error-resolution.ts +91 -0
  200. package/src/errors.ts +110 -5
  201. package/src/fixture-sanitization.ts +247 -0
  202. package/src/i18n/catalog.ts +10 -32
  203. package/src/i18n/index.ts +2 -2
  204. package/src/i18n/keys.ts +5 -11
  205. package/src/index.ts +111 -42
  206. package/src/lint.ts +89 -159
  207. package/src/native-address.ts +340 -0
  208. package/src/native-egress-policy.ts +358 -0
  209. package/src/observability.ts +51 -1
  210. package/src/provider.ts +65 -11
  211. package/src/public-schema-field-lint.ts +7 -33
  212. package/src/recipes/gov-api.ts +2 -5
  213. package/src/runtime/auth-flow.ts +5 -7
  214. package/src/runtime/browser.ts +64 -187
  215. package/src/runtime/cache.ts +20 -67
  216. package/src/runtime/choice.ts +79 -132
  217. package/src/runtime/credential.ts +2 -2
  218. package/src/runtime/env.ts +1 -1
  219. package/src/runtime/executor.ts +43 -20
  220. package/src/runtime/http.ts +494 -57
  221. package/src/runtime/insights.ts +15 -53
  222. package/src/runtime/instrumentation.ts +495 -66
  223. package/src/runtime/keyring.ts +7 -19
  224. package/src/runtime/namespace.ts +2 -7
  225. package/src/runtime/native-network.ts +1686 -0
  226. package/src/runtime/otlp.ts +12 -23
  227. package/src/runtime/perf.ts +1 -1
  228. package/src/runtime/provider.ts +4 -9
  229. package/src/runtime/proxy-errors.ts +29 -42
  230. package/src/runtime/proxy-nodemaven.ts +221 -0
  231. package/src/runtime/proxy-retry-policy.ts +3 -3
  232. package/src/runtime/proxy-telemetry.ts +79 -77
  233. package/src/runtime/redirects.ts +66 -0
  234. package/src/runtime/redis.ts +4 -12
  235. package/src/runtime/request-options.ts +679 -9
  236. package/src/runtime/secrets.ts +64 -0
  237. package/src/runtime/state.ts +41 -110
  238. package/src/runtime/stealth.ts +505 -154
  239. package/src/runtime/stt.ts +38 -94
  240. package/src/runtime/trace.ts +14 -44
  241. package/src/runtime/waterfall.ts +5 -18
  242. package/src/schema.ts +23 -84
  243. package/src/serve.ts +1 -1
  244. package/src/server/index.ts +29 -7
  245. package/src/server/self-test-input-tokens.ts +29 -14
  246. package/src/server/self-test-redaction.ts +2 -2
  247. package/src/server/self-test.ts +857 -132
  248. package/src/server/serve.ts +1141 -324
  249. package/src/server/types.ts +12 -19
  250. package/src/stateful/README.md +146 -0
  251. package/src/stateful/errors.ts +23 -0
  252. package/src/stateful/http-provider-event-emitter.ts +314 -0
  253. package/src/stateful/http-session-owner-registry.ts +306 -0
  254. package/src/stateful/index.ts +18 -0
  255. package/src/stateful/provider-event-delivery-failures.ts +80 -0
  256. package/src/stateful/provider-event-pipeline-metrics.ts +95 -0
  257. package/src/stateful/provider-event-pipeline.ts +61 -0
  258. package/src/stateful/provider-events.ts +462 -0
  259. package/src/stateful/session-key.ts +111 -0
  260. package/src/stateful/stateful-provider-adapter-context.ts +59 -0
  261. package/src/stateful/stateful-provider-adapter-metrics.ts +48 -0
  262. package/src/stateful/stateful-provider-adapter.ts +562 -0
  263. package/src/stateful/stateful-provider-observability.ts +261 -0
  264. package/src/stateful/stateful-provider-owner-forwarder.ts +287 -0
  265. package/src/stateful/stateful-provider-runtime-context.ts +92 -0
  266. package/src/stateful/stateful-provider-runtime-executor.ts +96 -0
  267. package/src/stateful/stateful-provider-session-routing.ts +555 -0
  268. package/src/stateful/stateful-provider-session-runtime.ts +403 -0
  269. package/src/stateful-signing.ts +46 -0
  270. package/src/stealth/profiles.ts +10 -26
  271. package/src/stream-evidence.ts +988 -0
  272. package/src/stream.ts +8 -19
  273. package/src/testing/index.ts +10 -2
  274. package/src/testing/run.ts +652 -79
  275. package/src/types.ts +369 -11
  276. package/src/user-input.ts +118 -0
  277. package/dist/cli/templates/provider/CLAUDE.md.tpl +0 -1
  278. package/src/cli/templates/provider/CLAUDE.md.tpl +0 -1
  279. /package/dist/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  280. /package/dist/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  281. /package/dist/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  282. /package/dist/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  283. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  284. /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
  285. /package/src/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
  286. /package/src/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
  287. /package/src/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
  288. /package/src/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
  289. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
  290. /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
package/dist/stream.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { SseMessage } from "./types";
1
+ import type { SseMessage } from "./types.js";
2
2
  export interface SseEvent<TData = unknown> {
3
3
  event: string;
4
4
  data: TData;
@@ -1,2 +1,2 @@
1
- export { describeTransform, snapshotTransform, toMatchShape } from "./helpers";
2
- export { runStandardTests } from "./run";
1
+ export { describeTransform, snapshotTransform, toMatchShape } from "./helpers.js";
2
+ export { runStandardTests, type StandardTestsManifest, type StandardTestsOptions, type StandardTestsResult, type StandardTestsUpstreamCall, type StandardTestsUpstreamResponse, type StandardTestsUpstreamStub, } from "./run.js";
@@ -1,2 +1,2 @@
1
- export { describeTransform, snapshotTransform, toMatchShape } from "./helpers";
2
- export { runStandardTests } from "./run";
1
+ export { describeTransform, snapshotTransform, toMatchShape } from "./helpers.js";
2
+ export { runStandardTests, } from "./run.js";
@@ -1,4 +1,4 @@
1
- import type { AuthMode, ProviderDefinition } from "../types";
1
+ import type { AuthMode, ProviderContext, ProviderDefinition } from "../types.js";
2
2
  export interface StandardTestsManifest {
3
3
  id?: string;
4
4
  displayName?: string;
@@ -22,7 +22,34 @@ export interface StandardTestsOptions {
22
22
  validateAuthMode?: boolean;
23
23
  /** Override inferred __fixtures__ directory for tests generated outside providers/<id>. */
24
24
  fixtureDir?: string;
25
+ /** Opt in to real-handler E2E with strict, offline canned upstream responses. */
26
+ upstreamStub?: StandardTestsUpstreamStub;
27
+ /** Require a committed snapshot; missing files fail unless --update-snapshots is passed. */
28
+ requireSnapshot?: boolean;
25
29
  }
30
+ export interface StandardTestsUpstreamCall {
31
+ /** Operation whose real handler initiated the call. */
32
+ operationName: string;
33
+ /** ProviderContext transport surface used by the handler. */
34
+ transport: "http" | "stealth" | "browser" | "native";
35
+ method: string;
36
+ url?: string;
37
+ body?: unknown;
38
+ options?: unknown;
39
+ }
40
+ export interface StandardTestsUpstreamResponse {
41
+ status?: number;
42
+ headers?: Readonly<Record<string, string>>;
43
+ /** JSON-compatible values are encoded as JSON; strings and bytes are preserved. */
44
+ body?: unknown;
45
+ }
46
+ export type StandardTestsUpstreamStub = (call: StandardTestsUpstreamCall) => Response | StandardTestsUpstreamResponse | undefined | Promise<Response | StandardTestsUpstreamResponse | undefined>;
47
+ export interface StandardTestsResult {
48
+ warnings: readonly string[];
49
+ }
50
+ export declare function createSnapshotContext(rawFixture: unknown): ProviderContext;
51
+ /** Internal execution seam exported for focused SDK tests; use runStandardTests as public API. */
52
+ export declare function executeStandardTestHandler(provider: ProviderDefinition, operationName: string, upstreamStub: StandardTestsUpstreamStub): Promise<unknown>;
26
53
  /**
27
54
  * Run standard SDK tests for a provider in one line.
28
55
  *
@@ -31,4 +58,7 @@ export interface StandardTestsOptions {
31
58
  * import { runStandardTests } from "@apifuse/provider-sdk/testing";
32
59
  * runStandardTests(myProvider, rawFixture, manifest, { snapshot: true });
33
60
  */
34
- export declare function runStandardTests(provider: ProviderDefinition, rawFixture?: unknown, manifest?: StandardTestsManifest, options?: StandardTestsOptions): void;
61
+ export declare function runStandardTests(provider: ProviderDefinition, options: StandardTestsOptions & {
62
+ upstreamStub: StandardTestsUpstreamStub;
63
+ }): StandardTestsResult;
64
+ export declare function runStandardTests(provider: ProviderDefinition, rawFixture?: unknown, manifest?: StandardTestsManifest, options?: StandardTestsOptions): StandardTestsResult;
@@ -1,20 +1,19 @@
1
1
  import { describe, expect, it } from "bun:test";
2
- import { createProviderCache } from "../runtime/cache";
3
- import { createTestProviderChoiceContext } from "../runtime/choice";
4
- import { createMemoryProviderRuntimeState } from "../runtime/state";
5
- import { createUnsupportedSttClient } from "../runtime/stt";
6
- import { safeParseSchemaSync } from "../schema";
2
+ import { createProviderCache } from "../runtime/cache.js";
3
+ import { createTestProviderChoiceContext } from "../runtime/choice.js";
4
+ import { createMemoryProviderRuntimeState } from "../runtime/state.js";
5
+ import { createUnsupportedSttClient } from "../runtime/stt.js";
6
+ import { createNativeEgressAuthorization, NativeNetworkError, snapshotNativeConnectInput, snapshotNativeGrantInput, } from "../runtime/native-network.js";
7
+ import { safeParseSchemaSync } from "../schema.js";
8
+ import { requestPathForFixture } from "../fixture-sanitization.js";
9
+ import { findStreamCaptureGroup, replayStreamEvidence } from "../stream-evidence.js";
7
10
  // Mirrors CONNECTOR_ID_REGEX in ../define.ts, which defineProvider() enforces.
8
11
  // A single lowercase segment (no hyphen) is a valid id, so the trailing group
9
12
  // is optional (`*`), matching providers like `kakaomap`, `kstartup`, `triple`.
10
13
  const CONNECTOR_ID_REGEX = /^[a-z][a-z0-9]*(-[a-z][a-z0-9]*)*$/;
11
- const VALID_AUTH_MODES = [
12
- "none",
13
- "platform-managed",
14
- "credentials",
15
- "oauth2",
16
- ];
14
+ const VALID_AUTH_MODES = ["none", "platform-managed", "credentials", "oauth2"];
17
15
  const UPDATE_SNAPSHOT_ARGS = new Set(["-u", "--update-snapshots"]);
16
+ const snapshotCaptureStates = new WeakMap();
18
17
  function isFixtureEnvelope(value) {
19
18
  return (value !== null &&
20
19
  typeof value === "object" &&
@@ -60,9 +59,7 @@ function inferFixtureDir(providerId) {
60
59
  .map((line) => line.match(/\(?((?:file:\/\/)?[^():]+\.test\.ts)/)?.[1])
61
60
  .find((file) => file !== undefined);
62
61
  if (testFile) {
63
- const pathname = testFile.startsWith("file://")
64
- ? new URL(testFile).pathname
65
- : testFile;
62
+ const pathname = testFile.startsWith("file://") ? new URL(testFile).pathname : testFile;
66
63
  return `${pathname.replace(/\/[^/]+$/, "")}/../__fixtures__`;
67
64
  }
68
65
  return `providers/${providerId}/__fixtures__`;
@@ -81,10 +78,349 @@ function jsonResponse(data) {
81
78
  bytes: async () => bodyBytes.slice(0),
82
79
  };
83
80
  }
81
+ function headersToRecord(headers) {
82
+ return Object.fromEntries(headers.entries());
83
+ }
84
+ async function normalizeUpstreamResponse(response) {
85
+ if (response instanceof Response) {
86
+ const bytes = new Uint8Array(await response.arrayBuffer());
87
+ const text = new TextDecoder().decode(bytes);
88
+ const headers = headersToRecord(response.headers);
89
+ let data = text;
90
+ if (response.headers.get("content-type")?.includes("application/json")) {
91
+ data = text.length > 0 ? JSON.parse(text) : null;
92
+ }
93
+ return { status: response.status, headers, data, text, bytes };
94
+ }
95
+ const headers = { ...(response.headers ?? {}) };
96
+ const body = response.body ?? null;
97
+ let bytes;
98
+ let text;
99
+ let data;
100
+ if (body instanceof Uint8Array) {
101
+ bytes = body.slice(0);
102
+ text = new TextDecoder().decode(bytes);
103
+ data = text;
104
+ }
105
+ else if (body instanceof ArrayBuffer) {
106
+ bytes = new Uint8Array(body.slice(0));
107
+ text = new TextDecoder().decode(bytes);
108
+ data = text;
109
+ }
110
+ else if (typeof body === "string") {
111
+ text = body;
112
+ bytes = new TextEncoder().encode(text);
113
+ data = body;
114
+ }
115
+ else {
116
+ text = JSON.stringify(body);
117
+ bytes = new TextEncoder().encode(text);
118
+ data = body;
119
+ if (!Object.keys(headers).some((name) => name.toLowerCase() === "content-type")) {
120
+ headers["content-type"] = "application/json";
121
+ }
122
+ }
123
+ return { status: response.status ?? 200, headers, data, text, bytes };
124
+ }
125
+ function toHttpResponse(response) {
126
+ return {
127
+ status: response.status,
128
+ ok: response.status >= 200 && response.status < 300,
129
+ headers: response.headers,
130
+ data: response.data,
131
+ json: async () => JSON.parse(response.text),
132
+ text: async () => response.text,
133
+ arrayBuffer: async () => response.bytes.slice(0).buffer,
134
+ bytes: async () => response.bytes.slice(0),
135
+ };
136
+ }
137
+ const emptyCookieJar = {
138
+ get: () => undefined,
139
+ getAll: () => ({}),
140
+ toString: () => "",
141
+ };
142
+ function emptyCookieStore() {
143
+ return {
144
+ version: 1,
145
+ jar: { cookies: [] },
146
+ };
147
+ }
148
+ function toStealthResponse(response, url) {
149
+ return {
150
+ status: response.status,
151
+ ok: response.status >= 200 && response.status < 300,
152
+ url,
153
+ redirected: false,
154
+ headers: response.headers,
155
+ rawHeaders: Object.entries(response.headers),
156
+ body: response.text,
157
+ cookies: emptyCookieJar,
158
+ json: async () => JSON.parse(response.text),
159
+ arrayBuffer: async () => response.bytes.slice(0).buffer,
160
+ bytes: async () => response.bytes.slice(0),
161
+ };
162
+ }
163
+ function streamFromBytes(bytes) {
164
+ return new ReadableStream({
165
+ start(controller) {
166
+ controller.enqueue(bytes.slice(0));
167
+ controller.close();
168
+ },
169
+ });
170
+ }
171
+ async function* singleBytes(bytes) {
172
+ yield bytes.slice(0);
173
+ }
174
+ async function* singleText(textValue) {
175
+ yield textValue;
176
+ }
177
+ function createUpstreamContext(provider, operationName, upstreamStub) {
178
+ const credential = {
179
+ mode: "none",
180
+ get: () => undefined,
181
+ getAll: () => ({}),
182
+ getAccessToken: () => undefined,
183
+ getScopes: () => [],
184
+ };
185
+ const request = { headers: {} };
186
+ const state = createMemoryProviderRuntimeState();
187
+ const nativeEgress = provider.native
188
+ ? createNativeEgressAuthorization({ egress: provider.native.network })
189
+ : undefined;
190
+ const requireNativeEgress = () => {
191
+ if (!nativeEgress)
192
+ throw new NativeNetworkError("Native egress authorization is unavailable", "native_egress_policy_invalid");
193
+ return nativeEgress;
194
+ };
195
+ const dispatch = async (call) => {
196
+ const canned = await upstreamStub({ operationName, ...call });
197
+ if (canned === undefined) {
198
+ throw new Error(`Unmatched upstream call for operation "${operationName}": ${call.transport}.${call.method}${call.url ? ` ${call.url}` : ""}. Add a canned response to upstreamStub; live network passthrough is disabled.`);
199
+ }
200
+ return normalizeUpstreamResponse(canned);
201
+ };
202
+ const httpCall = async (method, url, body, options) => toHttpResponse(await dispatch({ transport: "http", method, url, body, options }));
203
+ const stealthCall = async (url, options) => toStealthResponse(await dispatch({
204
+ transport: "stealth",
205
+ method: options?.method?.toUpperCase() ?? "GET",
206
+ url,
207
+ body: options?.body,
208
+ options,
209
+ }), url);
210
+ const createBrowserPage = () => {
211
+ let currentUrl = "about:blank";
212
+ let currentResponse;
213
+ const browserAction = async (method, body) => {
214
+ currentResponse = await dispatch({
215
+ transport: "browser",
216
+ method,
217
+ url: currentUrl,
218
+ body,
219
+ });
220
+ return currentResponse;
221
+ };
222
+ const page = {
223
+ id: `standard-test-${operationName}`,
224
+ url: async () => currentUrl,
225
+ title: async () => currentResponse?.text.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1] ?? "",
226
+ content: async () => currentResponse?.text ?? "",
227
+ evaluate: async (fn) => (await browserAction("evaluate", typeof fn === "string" ? fn : String(fn))).data,
228
+ locator: (selector) => ({
229
+ click: async () => {
230
+ await browserAction("locator.click", { selector });
231
+ },
232
+ fill: async (textValue) => {
233
+ await browserAction("locator.fill", { selector, text: textValue });
234
+ },
235
+ textContent: async () => {
236
+ const value = (await browserAction("locator.textContent", { selector })).data;
237
+ return value === null || value === undefined ? null : String(value);
238
+ },
239
+ waitFor: async (options) => {
240
+ await browserAction("locator.waitFor", { selector, options });
241
+ },
242
+ }),
243
+ close: async () => { },
244
+ fill: async (selector, textValue) => {
245
+ await browserAction("fill", { selector, text: textValue });
246
+ },
247
+ goto: async (url) => {
248
+ currentUrl = url;
249
+ await browserAction("goto");
250
+ },
251
+ screenshot: async (options) => Buffer.from((await browserAction("screenshot", options)).bytes),
252
+ click: async (selector) => {
253
+ await browserAction("click", { selector });
254
+ },
255
+ type: async (selector, textValue) => {
256
+ await browserAction("type", { selector, text: textValue });
257
+ },
258
+ waitForSelector: async (selector, options) => {
259
+ await browserAction("waitForSelector", { selector, options });
260
+ },
261
+ frames: async () => [page],
262
+ withResourcePolicy: async (_policy, run) => run(),
263
+ };
264
+ return page;
265
+ };
266
+ const createStealthSession = () => ({
267
+ fetch: stealthCall,
268
+ cookies: {
269
+ ...emptyCookieJar,
270
+ has: () => false,
271
+ setFromCookieStrings: () => { },
272
+ toHeader: () => "",
273
+ snapshot: () => ({}),
274
+ restore: () => { },
275
+ serialize: emptyCookieStore,
276
+ deserialize: () => { },
277
+ clear: () => { },
278
+ },
279
+ redirects: {
280
+ run: async (options) => {
281
+ const final = await stealthCall(options.url, options);
282
+ return {
283
+ final,
284
+ hops: [],
285
+ reason: "completed",
286
+ cookies: {},
287
+ cookieStore: emptyCookieStore(),
288
+ };
289
+ },
290
+ },
291
+ close: () => { },
292
+ });
293
+ return {
294
+ env: { get: () => undefined },
295
+ credential,
296
+ request,
297
+ http: {
298
+ request: (url, options) => httpCall(options?.method?.toUpperCase() ?? "GET", url, options?.body, options),
299
+ get: (url, options) => httpCall("GET", url, undefined, options),
300
+ post: (url, body, options) => httpCall("POST", url, body, options),
301
+ put: (url, body, options) => httpCall("PUT", url, body, options),
302
+ delete: (url, options) => httpCall("DELETE", url, undefined, options),
303
+ stream: async (url, options) => {
304
+ const response = await dispatch({
305
+ transport: "http",
306
+ method: options?.method?.toUpperCase() ?? "GET",
307
+ url,
308
+ body: options?.body,
309
+ options,
310
+ });
311
+ return {
312
+ status: response.status,
313
+ ok: response.status >= 200 && response.status < 300,
314
+ headers: response.headers,
315
+ body: streamFromBytes(response.bytes),
316
+ bytes: () => singleBytes(response.bytes),
317
+ textChunks: () => singleText(response.text),
318
+ lines: () => singleText(response.text),
319
+ };
320
+ },
321
+ sse: async (url, options) => {
322
+ const response = await dispatch({
323
+ transport: "http",
324
+ method: options?.method?.toUpperCase() ?? "GET",
325
+ url,
326
+ body: options?.body,
327
+ options,
328
+ });
329
+ async function* messages() {
330
+ for (const block of response.text.split(/\r?\n\r?\n/)) {
331
+ const data = block
332
+ .split(/\r?\n/)
333
+ .filter((line) => line.startsWith("data:"))
334
+ .map((line) => line.slice(5).trimStart())
335
+ .join("\n");
336
+ if (!data)
337
+ continue;
338
+ yield { event: "message", data, json: () => JSON.parse(data) };
339
+ }
340
+ }
341
+ return messages();
342
+ },
343
+ },
344
+ cache: createProviderCache({ providerId: `standard-test-${operationName}` }),
345
+ state,
346
+ stealth: {
347
+ fetch: stealthCall,
348
+ createSession: createStealthSession,
349
+ },
350
+ browser: {
351
+ engine: "playwright-stealth",
352
+ newPage: async () => createBrowserPage(),
353
+ rawPage: async () => createBrowserPage(),
354
+ withIsolatedContext: async (handler) => handler(createBrowserPage()),
355
+ solveChallenge: async (challenge) => (await dispatch({
356
+ transport: "browser",
357
+ method: "solveChallenge",
358
+ body: challenge,
359
+ })).data,
360
+ },
361
+ ...(provider.native
362
+ ? {
363
+ native: {
364
+ network: {
365
+ connectTcp: async (options) => {
366
+ const request = snapshotNativeConnectInput(options);
367
+ requireNativeEgress().assertConnect(request, "disabled");
368
+ return createNativeConnection(await dispatch({
369
+ transport: "native",
370
+ method: "connectTcp",
371
+ url: `tcp://${request.host}:${request.port}`,
372
+ options: request,
373
+ }), dispatch, `tcp://${request.host}:${request.port}`);
374
+ },
375
+ connectTls: async (options) => {
376
+ const request = snapshotNativeConnectInput(options);
377
+ requireNativeEgress().assertConnect(request, "required");
378
+ return createNativeConnection(await dispatch({
379
+ transport: "native",
380
+ method: "connectTls",
381
+ url: `tls://${request.host}:${request.port}`,
382
+ options: request,
383
+ }), dispatch, `tls://${request.host}:${request.port}`);
384
+ },
385
+ grantTcpEgress: (input) => {
386
+ return requireNativeEgress().grant(snapshotNativeGrantInput(input));
387
+ },
388
+ },
389
+ },
390
+ }
391
+ : {}),
392
+ trace: { span: async (_name, fn) => fn() },
393
+ auth: { requestField: async (name) => unsupported(`ctx.auth.requestField(${name})`) },
394
+ stt: createUnsupportedSttClient("Standard test upstream context does not support ctx.stt.transcribe"),
395
+ choice: createTestProviderChoiceContext({
396
+ providerId: `standard-test-${operationName}`,
397
+ request,
398
+ credential,
399
+ state,
400
+ }),
401
+ };
402
+ }
403
+ function createNativeConnection(initialResponse, dispatch, url) {
404
+ let unread = initialResponse.bytes.slice(0);
405
+ return {
406
+ read: async () => {
407
+ if (unread.byteLength === 0)
408
+ return null;
409
+ const bytes = unread;
410
+ unread = new Uint8Array();
411
+ return bytes;
412
+ },
413
+ write: async (body) => {
414
+ const response = await dispatch({ transport: "native", method: "write", url, body });
415
+ unread = response.bytes.slice(0);
416
+ },
417
+ close: async () => { },
418
+ };
419
+ }
84
420
  function unsupported(name) {
85
421
  throw new Error(`Standard test snapshot context does not support ${name}`);
86
422
  }
87
- function createSnapshotContext(rawFixture) {
423
+ export function createSnapshotContext(rawFixture) {
88
424
  const credential = {
89
425
  mode: "none",
90
426
  get: () => undefined,
@@ -94,17 +430,52 @@ function createSnapshotContext(rawFixture) {
94
430
  };
95
431
  const request = { headers: {} };
96
432
  const state = createMemoryProviderRuntimeState();
97
- return {
433
+ const streamCaptureGroup = findStreamCaptureGroup(rawFixture);
434
+ let nextCaptureItem = 0;
435
+ const replayJsonResponse = () => {
436
+ if (!streamCaptureGroup)
437
+ return jsonResponse(rawFixture);
438
+ const item = streamCaptureGroup.items[nextCaptureItem];
439
+ if (!item) {
440
+ throw new Error(`Stream fixture exhausted: no recorded response exists for ordinary HTTP call ${nextCaptureItem + 1}.`);
441
+ }
442
+ if (item.kind !== "response") {
443
+ throw new Error(`Stream fixture call-order mismatch: expected a stream call at position ${nextCaptureItem + 1}, received an ordinary HTTP call.`);
444
+ }
445
+ nextCaptureItem += 1;
446
+ return jsonResponse(item.value);
447
+ };
448
+ const context = {
98
449
  env: { get: () => undefined },
99
450
  credential,
100
451
  request,
101
452
  http: {
102
- request: async () => jsonResponse(rawFixture),
103
- get: async () => jsonResponse(rawFixture),
104
- post: async () => jsonResponse(rawFixture),
105
- put: async () => jsonResponse(rawFixture),
106
- delete: async () => jsonResponse(rawFixture),
107
- stream: async () => unsupported("ctx.http.stream"),
453
+ request: async () => replayJsonResponse(),
454
+ get: async () => replayJsonResponse(),
455
+ post: async () => replayJsonResponse(),
456
+ put: async () => replayJsonResponse(),
457
+ delete: async () => replayJsonResponse(),
458
+ stream: async (...args) => {
459
+ if (!streamCaptureGroup)
460
+ return unsupported("ctx.http.stream");
461
+ const item = streamCaptureGroup.items[nextCaptureItem];
462
+ if (!item) {
463
+ throw new Error(`Stream fixture exhausted: no recorded evidence exists for stream call ${nextCaptureItem + 1}.`);
464
+ }
465
+ if (item.kind !== "stream") {
466
+ throw new Error(`Stream fixture call-order mismatch: expected an ordinary HTTP call at position ${nextCaptureItem + 1}, received a stream call.`);
467
+ }
468
+ if (item.evidence.request) {
469
+ const expected = item.evidence.request;
470
+ const actualMethod = (args[1]?.method ?? "GET").toUpperCase();
471
+ const actualPath = replayRequestPath(args[0], expected.path);
472
+ if (actualMethod !== expected.method || actualPath !== expected.path) {
473
+ throw new Error(`Stream fixture request mismatch: expected ${expected.method} ${expected.path}, received ${actualMethod} ${actualPath}.`);
474
+ }
475
+ }
476
+ nextCaptureItem += 1;
477
+ return replayStreamEvidence(item.evidence);
478
+ },
108
479
  sse: async () => unsupported("ctx.http.sse"),
109
480
  },
110
481
  cache: createProviderCache({ providerId: "standard-test" }),
@@ -134,15 +505,39 @@ function createSnapshotContext(rawFixture) {
134
505
  state,
135
506
  }),
136
507
  };
508
+ snapshotCaptureStates.set(context, {
509
+ assertConsumed() {
510
+ if (streamCaptureGroup && nextCaptureItem !== streamCaptureGroup.items.length) {
511
+ throw new Error(`Stream fixture has ${streamCaptureGroup.items.length - nextCaptureItem} unconsumed capture item${streamCaptureGroup.items.length - nextCaptureItem === 1 ? "" : "s"} after handler completion.`);
512
+ }
513
+ },
514
+ consumed: () => nextCaptureItem,
515
+ });
516
+ return context;
517
+ }
518
+ function replayRequestPath(requestUrl, expectedPath) {
519
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(requestUrl) || requestUrl.startsWith("/")) {
520
+ return requestPathForFixture(requestUrl);
521
+ }
522
+ return requestPathForFixture(new URL(requestUrl, `https://fixture.invalid${expectedPath}`).toString());
137
523
  }
138
524
  async function transformSnapshotOutput(provider, rawFixture) {
139
525
  const entries = Object.entries(provider.operations);
140
- const context = createSnapshotContext(rawFixture);
526
+ const captureStates = [];
141
527
  const outputs = await Promise.all(entries.map(async ([operationName, operation]) => {
528
+ const context = createSnapshotContext(rawFixture);
142
529
  const request = operation.fixtures?.request ?? {};
143
530
  const output = await operation.handler(context, request);
531
+ const captureState = snapshotCaptureStates.get(context);
532
+ if (captureState)
533
+ captureStates.push(captureState);
534
+ if (captureState?.consumed())
535
+ captureState.assertConsumed();
144
536
  return [operationName, output];
145
537
  }));
538
+ if (findStreamCaptureGroup(rawFixture) && !captureStates.some((state) => state.consumed() > 0)) {
539
+ captureStates[0]?.assertConsumed();
540
+ }
146
541
  if (outputs.length === 1) {
147
542
  return outputs[0]?.[1];
148
543
  }
@@ -187,16 +582,51 @@ function expectSchemaFixture(operationName, fieldName, fixture, result) {
187
582
  function parseSchemaFixture(operationName, fieldName, schema, fixture) {
188
583
  expectSchemaFixture(operationName, fieldName, fixture, safeParseSchemaSync(schema, fixture, `operations.${operationName}.fixtures.${fieldName}`));
189
584
  }
190
- /**
191
- * Run standard SDK tests for a provider in one line.
192
- *
193
- * Usage:
194
- * import { myProvider } from "../index";
195
- * import { runStandardTests } from "@apifuse/provider-sdk/testing";
196
- * runStandardTests(myProvider, rawFixture, manifest, { snapshot: true });
197
- */
198
- export function runStandardTests(provider, rawFixture, manifest, options = {}) {
585
+ async function materializeHandlerOutput(output) {
586
+ if (!(output instanceof Response))
587
+ return output;
588
+ const contentType = output.headers.get("content-type") ?? "";
589
+ if (contentType.includes("application/json"))
590
+ return output.json();
591
+ return output.text();
592
+ }
593
+ /** Internal execution seam exported for focused SDK tests; use runStandardTests as public API. */
594
+ export async function executeStandardTestHandler(provider, operationName, upstreamStub) {
595
+ const operation = provider.operations[operationName];
596
+ if (!operation)
597
+ throw new Error(`Unknown operation "${operationName}".`);
598
+ if (operation.fixtures?.request === undefined) {
599
+ throw new Error(`Operation "${operationName}" has no fixtures.request for handler E2E execution.`);
600
+ }
601
+ const context = createUpstreamContext(provider, operationName, upstreamStub);
602
+ const output = await materializeHandlerOutput(await operation.handler(context, operation.fixtures.request));
603
+ const result = safeParseSchemaSync(operation.output, output, `operations.${operationName}.handler.output`);
604
+ if (!result.success) {
605
+ throw new Error([
606
+ `Handler output for operation "${operationName}" failed schema validation.`,
607
+ formatJsonDiff({ valid: false, value: output, error: result.error }, { valid: true, value: output }),
608
+ ].join("\n"));
609
+ }
610
+ return output;
611
+ }
612
+ function isOptionsShortcut(value) {
613
+ return (value !== null &&
614
+ typeof value === "object" &&
615
+ !Array.isArray(value) &&
616
+ Object.hasOwn(value, "upstreamStub"));
617
+ }
618
+ export function runStandardTests(provider, rawFixtureOrOptions, manifest, legacyOptions) {
619
+ const shortcut = manifest === undefined && legacyOptions === undefined && isOptionsShortcut(rawFixtureOrOptions);
620
+ const rawFixture = shortcut ? undefined : rawFixtureOrOptions;
621
+ const options = shortcut ? rawFixtureOrOptions : (legacyOptions ?? {});
199
622
  const operations = Object.entries(provider.operations);
623
+ const warnings = options.upstreamStub
624
+ ? operations
625
+ .filter(([, operation]) => operation.fixtures?.request === undefined)
626
+ .map(([operationName]) => `[provider-sdk] Operation "${provider.id}.${operationName}" has no fixtures.request, so runStandardTests cannot invoke its handler E2E.`)
627
+ : operations.map(([operationName]) => `[provider-sdk] Operation "${provider.id}.${operationName}" has no handler E2E coverage in runStandardTests; configure upstreamStub to invoke the real handler.`);
628
+ for (const warning of warnings)
629
+ console.warn(warning);
200
630
  const assertFixtureValidation = () => {
201
631
  expect(rawFixture).toBeDefined();
202
632
  expect(isJsonCompatible(rawFixture)).toBe(true);
@@ -296,12 +726,26 @@ export function runStandardTests(provider, rawFixture, manifest, options = {}) {
296
726
  const actual = await transformSnapshotOutput(provider, rawFixture);
297
727
  const serialized = stableStringify(actual);
298
728
  const snapshotFile = Bun.file(snapshotPath);
299
- if (shouldUpdateSnapshots() || !(await snapshotFile.exists())) {
729
+ const snapshotExists = await snapshotFile.exists();
730
+ if (!snapshotExists && options.requireSnapshot && !shouldUpdateSnapshots()) {
731
+ throw new Error(`Required golden snapshot is missing: ${snapshotPath}. Regenerate it with bun test --update-snapshots.`);
732
+ }
733
+ if (shouldUpdateSnapshots() || !snapshotExists) {
300
734
  await Bun.write(snapshotPath, serialized);
301
735
  }
302
736
  const expected = JSON.parse(await Bun.file(snapshotPath).text());
303
737
  expect(actual).toEqual(expected);
304
738
  });
305
739
  }
740
+ if (options.upstreamStub) {
741
+ for (const [operationName, operation] of operations) {
742
+ if (operation.fixtures?.request === undefined)
743
+ continue;
744
+ it(`invokes the real ${operationName} handler with canned upstream responses`, async () => {
745
+ await executeStandardTestHandler(provider, operationName, options.upstreamStub);
746
+ });
747
+ }
748
+ }
306
749
  });
750
+ return { warnings };
307
751
  }