@ekanos/harness 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +175 -79
  2. package/dist/api.d.ts +42 -0
  3. package/dist/api.js +17 -0
  4. package/dist/internal/components/dev-toolbar.js +4 -2
  5. package/dist/internal/components/harness-providers.js +1 -0
  6. package/dist/internal/components/local-oauth-panel.d.ts +29 -0
  7. package/dist/internal/components/local-oauth-panel.js +355 -0
  8. package/dist/internal/lib/harness-fetch-interceptor.d.ts +33 -13
  9. package/dist/internal/lib/harness-fetch-interceptor.js +10 -0
  10. package/dist/internal/lib/oauth-setup-guide.d.ts +43 -0
  11. package/dist/internal/lib/oauth-setup-guide.js +28 -0
  12. package/dist/internal/lib/original-fetch.d.ts +36 -0
  13. package/dist/internal/lib/original-fetch.js +23 -0
  14. package/dist/internal/lib/run-activation-hook.d.ts +2 -8
  15. package/dist/internal/lib/toolbar-context.d.ts +7 -3
  16. package/dist/internal/lib/toolbar-context.js +10 -5
  17. package/dist/internal/lib/trigger-contract.d.ts +99 -0
  18. package/dist/internal/lib/trigger-contract.js +25 -0
  19. package/dist/internal/lib/trigger-runner.d.ts +55 -0
  20. package/dist/internal/lib/trigger-runner.js +153 -0
  21. package/dist/internal/routes/activation-page.js +42 -28
  22. package/dist/internal/routes/integration-layout.js +5 -1
  23. package/dist/internal/routes/triggers-page.js +121 -147
  24. package/dist/internal/server/api-router.d.ts +42 -0
  25. package/dist/internal/server/api-router.js +465 -0
  26. package/dist/internal/server/live-context.d.ts +93 -0
  27. package/dist/internal/server/live-context.js +93 -0
  28. package/dist/internal/server/local-secrets.d.ts +84 -0
  29. package/dist/internal/server/local-secrets.js +144 -0
  30. package/dist/internal/server/loopback-guard.d.ts +33 -0
  31. package/dist/internal/server/loopback-guard.js +38 -0
  32. package/dist/internal/server/nonce-store.d.ts +38 -0
  33. package/dist/internal/server/nonce-store.js +40 -0
  34. package/dist/internal/server/oauth-loop.d.ts +114 -0
  35. package/dist/internal/server/oauth-loop.js +141 -0
  36. package/dist/internal/server/project-root.d.ts +29 -0
  37. package/dist/internal/server/project-root.js +31 -0
  38. package/dist/internal/server/storage-read.d.ts +34 -0
  39. package/dist/internal/server/storage-read.js +53 -0
  40. package/dist/registry.d.ts +73 -1
  41. package/dist/registry.js +21 -1
  42. package/package.json +10 -3
@@ -0,0 +1,465 @@
1
+ import { invokeSchedule, invokeWebhook } from "@ekanos/sdk/testing";
2
+ import { findIntegration } from "../../registry.js";
3
+ import { runOnActivateHook } from "../lib/run-activation-hook.js";
4
+ import {
5
+ isLocalSetupWriteRequest,
6
+ isTriggerRequest
7
+ } from "../lib/trigger-contract.js";
8
+ import {
9
+ WARMUP_BUDGET_MS,
10
+ getLiveState,
11
+ startWarmup
12
+ } from "./live-context.js";
13
+ import {
14
+ LOCAL_SECRETS_RELATIVE_PATH,
15
+ declaredSecretNames,
16
+ readLocalSecrets,
17
+ writeLocalSecrets
18
+ } from "./local-secrets.js";
19
+ import { loopbackRefusal } from "./loopback-guard.js";
20
+ import {
21
+ buildAuthorizeUrl,
22
+ callbackUrl,
23
+ errorRedirectUrl,
24
+ exchangeAuthorizationCode,
25
+ generateCodeChallenge,
26
+ generateCodeVerifier,
27
+ safeReturnPath,
28
+ successRedirectUrl
29
+ } from "./oauth-loop.js";
30
+ import { resolveProjectRoot } from "./project-root.js";
31
+ import { parseStorageQuery, readClientReadableStorage } from "./storage-read.js";
32
+ function json(body, init = {}) {
33
+ return new Response(JSON.stringify(body), {
34
+ ...init,
35
+ headers: {
36
+ "content-type": "application/json",
37
+ "cache-control": "private, no-store",
38
+ ...init.headers ?? {}
39
+ }
40
+ });
41
+ }
42
+ function redirect(target) {
43
+ return new Response(null, {
44
+ status: 302,
45
+ headers: { location: String(target), "cache-control": "no-store" }
46
+ });
47
+ }
48
+ function defaultReturnPath(slug) {
49
+ return `/${slug}/activation`;
50
+ }
51
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
52
+ const ROUTES = {
53
+ "oauth/connect": { methods: ["GET"], handle: oauthConnect },
54
+ "oauth/callback": { methods: ["GET"], handle: oauthCallback },
55
+ "oauth/status": { methods: ["GET"], handle: oauthStatus },
56
+ storage: { methods: ["GET"], handle: storage },
57
+ trigger: { methods: ["POST"], handle: trigger },
58
+ "local-setup": { methods: ["GET", "PUT"], handle: localSetup }
59
+ };
60
+ function createHarnessApiRouter(registry, deps = {}) {
61
+ const env = deps.env ?? process.env;
62
+ const cwd = deps.cwd ?? process.cwd();
63
+ const now = deps.now ?? (() => /* @__PURE__ */ new Date());
64
+ return async (request, params) => {
65
+ const refusal = loopbackRefusal(request, env);
66
+ if (refusal) return refusal;
67
+ const routeKey = params.path.join("/");
68
+ const route = ROUTES[routeKey];
69
+ if (!route) {
70
+ if (routeKey === "connect") {
71
+ return json(
72
+ {
73
+ error: "not_found",
74
+ message: `The harness serves /api/integrations/${params.slug}/oauth/connect, not /connect. Your OAuthActivationForm is using the SDK's default \`connectPath\`, which points at a first-party route the host would not serve for a partner either.`,
75
+ hint: "Pass `connectPath: partnerOAuthConnectPath(slug)` from `@ekanos/sdk/hooks` in the form config."
76
+ },
77
+ { status: 404 }
78
+ );
79
+ }
80
+ return json(
81
+ {
82
+ error: "not_found",
83
+ message: `No harness API route at /api/integrations/${params.slug}/${routeKey}.`,
84
+ routes: Object.keys(ROUTES)
85
+ },
86
+ { status: 404 }
87
+ );
88
+ }
89
+ if (!route.methods.includes(request.method.toUpperCase())) {
90
+ return json(
91
+ { error: "method_not_allowed", allowed: route.methods },
92
+ { status: 405, headers: { allow: route.methods.join(", ") } }
93
+ );
94
+ }
95
+ const integration = findIntegration([...registry], params.slug);
96
+ if (!integration) {
97
+ return json(
98
+ {
99
+ error: "unknown_integration",
100
+ message: `"${params.slug}" is not registered in your harness config.`,
101
+ registered: registry.map((entry) => entry.slug)
102
+ },
103
+ { status: 404 }
104
+ );
105
+ }
106
+ const definition = integration.definition;
107
+ if (!definition) {
108
+ return json(
109
+ {
110
+ error: "no_definition",
111
+ message: `The harness entry for "${params.slug}" does not link its defineIntegration() output, so there is nothing to run.`,
112
+ hint: "Add `definition: asHarnessDefinition(integration)` to the entry in your harness config."
113
+ },
114
+ { status: 404 }
115
+ );
116
+ }
117
+ const root = resolveProjectRoot({ env, cwd });
118
+ if (!root.ok) {
119
+ return json(
120
+ {
121
+ error: "project_root_unresolved",
122
+ message: root.message,
123
+ hint: root.hint
124
+ },
125
+ { status: 500 }
126
+ );
127
+ }
128
+ const secrets = readLocalSecrets({
129
+ projectRoot: root.root,
130
+ slug: params.slug,
131
+ names: declaredSecretNames(definition)
132
+ });
133
+ if (!secrets.ok) {
134
+ return json(
135
+ { error: "local_secrets_unreadable", message: secrets.message },
136
+ { status: 500 }
137
+ );
138
+ }
139
+ if (secrets.generated) {
140
+ console.info(
141
+ `[harness:${params.slug}] wrote ${secrets.file} \u2014 fill in the values under "` + params.slug + '" to run the OAuth loop locally.'
142
+ );
143
+ }
144
+ const state = getLiveState({
145
+ integration,
146
+ definition,
147
+ adminSecrets: secrets.values,
148
+ secretsFingerprint: secrets.fingerprint
149
+ });
150
+ const url = new URL(request.url);
151
+ return route.handle({
152
+ request,
153
+ url,
154
+ origin: url.origin,
155
+ slug: params.slug,
156
+ integration,
157
+ definition,
158
+ projectRoot: root.root,
159
+ secrets,
160
+ state,
161
+ now
162
+ });
163
+ };
164
+ }
165
+ function notDeclared() {
166
+ return json(
167
+ { success: false, error: "This integration declares no OAuth surface" },
168
+ { status: 404 }
169
+ );
170
+ }
171
+ function oauthError(ctx, returnPath, code) {
172
+ return redirect(
173
+ errorRedirectUrl({
174
+ origin: ctx.origin,
175
+ returnPath,
176
+ integrationSlug: ctx.slug,
177
+ code
178
+ })
179
+ );
180
+ }
181
+ function clientCredentials(ctx) {
182
+ const oauth = ctx.definition.oauth;
183
+ if (!oauth) return null;
184
+ const clientId = ctx.secrets.values[oauth.credentials.clientIdSecretName];
185
+ const clientSecret = ctx.secrets.values[oauth.credentials.clientSecretSecretName];
186
+ return clientId && clientSecret ? { clientId, clientSecret } : null;
187
+ }
188
+ function oauthConnect(ctx) {
189
+ const oauth = ctx.definition.oauth;
190
+ if (!oauth) return notDeclared();
191
+ const returnPath = safeReturnPath(
192
+ ctx.url.searchParams.get("returnPath"),
193
+ defaultReturnPath(ctx.slug)
194
+ );
195
+ const credentials = clientCredentials(ctx);
196
+ if (!credentials) {
197
+ console.error(
198
+ `[harness:${ctx.slug}] oauth/connect: client credentials missing in ${ctx.secrets.file} (${ctx.secrets.missing.join(", ")}).`
199
+ );
200
+ return oauthError(ctx, returnPath, "not_configured");
201
+ }
202
+ const codeVerifier = oauth.provider.pkce ? generateCodeVerifier() : void 0;
203
+ const nonce = ctx.state.nonces.issue({
204
+ returnPath,
205
+ ...codeVerifier ? { codeVerifier } : {}
206
+ });
207
+ return redirect(
208
+ buildAuthorizeUrl({
209
+ provider: oauth.provider,
210
+ clientId: credentials.clientId,
211
+ redirectUri: callbackUrl(ctx.origin, ctx.slug),
212
+ state: nonce,
213
+ ...codeVerifier ? { codeChallenge: generateCodeChallenge(codeVerifier) } : {}
214
+ })
215
+ );
216
+ }
217
+ async function oauthCallback(ctx) {
218
+ const oauth = ctx.definition.oauth;
219
+ if (!oauth) return notDeclared();
220
+ const params = ctx.url.searchParams;
221
+ const stateParam = params.get("state");
222
+ const consumed = stateParam ? ctx.state.nonces.consume(stateParam) : { status: "unknown" };
223
+ const returnPath = consumed.status === "unknown" ? defaultReturnPath(ctx.slug) : consumed.entry.returnPath;
224
+ if (params.get("error")) {
225
+ return oauthError(ctx, returnPath, "denied");
226
+ }
227
+ if (consumed.status === "unknown")
228
+ return oauthError(ctx, returnPath, "invalid");
229
+ if (consumed.status === "expired")
230
+ return oauthError(ctx, returnPath, "expired");
231
+ const code = params.get("code");
232
+ if (!code) return oauthError(ctx, returnPath, "invalid");
233
+ const credentials = clientCredentials(ctx);
234
+ if (!credentials) return oauthError(ctx, returnPath, "not_configured");
235
+ const exchange = await exchangeAuthorizationCode({
236
+ ctx: ctx.state.ctx,
237
+ provider: oauth.provider,
238
+ ...credentials,
239
+ code,
240
+ redirectUri: callbackUrl(ctx.origin, ctx.slug),
241
+ ...consumed.entry.codeVerifier ? { codeVerifier: consumed.entry.codeVerifier } : {},
242
+ now: ctx.now
243
+ });
244
+ if (!exchange.ok) {
245
+ console.error(
246
+ `[harness:${ctx.slug}] oauth/callback: code exchange failed (${exchange.reason}${exchange.reason === "http_error" ? ` ${exchange.status}` : ""}${exchange.reason === "fetch_failed" ? `: ${exchange.message}` : ""}).`
247
+ );
248
+ return oauthError(ctx, returnPath, "exchange_failed");
249
+ }
250
+ try {
251
+ await oauth.onTokens(ctx.state.ctx, exchange.tokens);
252
+ } catch (error) {
253
+ console.error(
254
+ `[harness:${ctx.slug}] oauth/callback: onTokens threw`,
255
+ error
256
+ );
257
+ return oauthError(ctx, returnPath, "save_failed");
258
+ }
259
+ ctx.state.connection = {
260
+ obtainedAt: ctx.now().toISOString(),
261
+ expiresAt: exchange.tokens.expiresAt ?? null,
262
+ scope: exchange.tokens.scope ?? null
263
+ };
264
+ return redirect(successRedirectUrl({ origin: ctx.origin, returnPath }));
265
+ }
266
+ function oauthStatus(ctx) {
267
+ if (!ctx.definition.oauth) return notDeclared();
268
+ const accountId = ctx.url.searchParams.get("accountId");
269
+ if (!accountId || !UUID_PATTERN.test(accountId)) {
270
+ return json(
271
+ { success: false, error: "accountId must be a UUID" },
272
+ { status: 400 }
273
+ );
274
+ }
275
+ const connection = ctx.state.connection;
276
+ return connection ? json({ success: true, data: { obtainedAt: connection.obtainedAt } }) : json({ success: false, error: "Not connected" });
277
+ }
278
+ async function storage(ctx) {
279
+ const query = parseStorageQuery(ctx.url);
280
+ if (!query.ok) return json({ error: query.error }, { status: 400 });
281
+ const read = () => readClientReadableStorage({
282
+ ctx: ctx.state.ctx,
283
+ definition: ctx.definition,
284
+ keys: query.keys
285
+ });
286
+ const first = await read();
287
+ if (Object.keys(first).length > 0) return json(first);
288
+ const warmup = startWarmup(ctx.state, ctx.definition);
289
+ if (!warmup) return json(first);
290
+ const budgetExceeded = /* @__PURE__ */ Symbol("warmup-budget-exceeded");
291
+ const outcome = await Promise.race([
292
+ warmup,
293
+ new Promise(
294
+ (resolve) => setTimeout(() => resolve(budgetExceeded), WARMUP_BUDGET_MS)
295
+ )
296
+ ]);
297
+ if (outcome === budgetExceeded) {
298
+ console.info(
299
+ `[harness:${ctx.slug}] storage: read-through warm-up still running after ${WARMUP_BUDGET_MS}ms \u2014 answering empty; the next read gets the data.`
300
+ );
301
+ return json(first);
302
+ }
303
+ return json(await read());
304
+ }
305
+ function describeError(error) {
306
+ return error instanceof Error ? error.message : String(error);
307
+ }
308
+ async function trigger(ctx) {
309
+ let body;
310
+ try {
311
+ body = await ctx.request.json();
312
+ } catch {
313
+ return json({ error: "invalid_json" }, { status: 400 });
314
+ }
315
+ if (!isTriggerRequest(body)) {
316
+ return json(
317
+ {
318
+ error: "invalid_trigger",
319
+ hint: 'Expected { kind: "webhook", id, payload, headers? } | { kind: "schedule", id } | { kind: "activate" }.'
320
+ },
321
+ { status: 400 }
322
+ );
323
+ }
324
+ const liveCtx = ctx.state.ctx;
325
+ const logsBefore = liveCtx.logs.length;
326
+ const secretNames = await liveCtx.secrets.names();
327
+ const finish = (request, run) => run().then((result) => ({
328
+ kind: request.kind,
329
+ outcome: {
330
+ ok: true,
331
+ summary: result.status,
332
+ ...result.detail ? { detail: result.detail } : {},
333
+ logs: liveCtx.logs.slice(logsBefore),
334
+ storage: liveCtx.dumpStorage()
335
+ },
336
+ secretNames
337
+ })).catch((error) => ({
338
+ kind: request.kind,
339
+ outcome: {
340
+ ok: false,
341
+ summary: "failed",
342
+ detail: describeError(error),
343
+ logs: liveCtx.logs.slice(logsBefore),
344
+ storage: liveCtx.dumpStorage()
345
+ },
346
+ secretNames
347
+ }));
348
+ switch (body.kind) {
349
+ case "webhook": {
350
+ const webhook = ctx.definition.webhooks?.find((w) => w.id === body.id);
351
+ if (!webhook) {
352
+ return json({ error: "unknown_webhook", id: body.id }, { status: 400 });
353
+ }
354
+ const headers = body.headers ?? (webhook.signature === "none" ? {} : { [webhook.signature.header]: "(unverified \u2014 local transport)" });
355
+ return json(
356
+ await finish(body, async () => {
357
+ const { result } = await invokeWebhook(
358
+ ctx.definition,
359
+ body.id,
360
+ body.payload,
361
+ { context: liveCtx, headers }
362
+ );
363
+ return result;
364
+ })
365
+ );
366
+ }
367
+ case "schedule": {
368
+ if (!ctx.definition.schedules?.some((s) => s.id === body.id)) {
369
+ return json(
370
+ { error: "unknown_schedule", id: body.id },
371
+ { status: 400 }
372
+ );
373
+ }
374
+ return json(
375
+ await finish(body, async () => {
376
+ const { result } = await invokeSchedule(ctx.definition, body.id, {
377
+ context: liveCtx
378
+ });
379
+ return result;
380
+ })
381
+ );
382
+ }
383
+ case "activate": {
384
+ const outcome = await runOnActivateHook(ctx.definition, liveCtx);
385
+ const response = {
386
+ kind: "activate",
387
+ outcome,
388
+ logs: liveCtx.logs.slice(logsBefore),
389
+ storage: liveCtx.dumpStorage(),
390
+ secretNames
391
+ };
392
+ return json(response);
393
+ }
394
+ }
395
+ }
396
+ function localSetupResponse(ctx, secrets, connected) {
397
+ const names = declaredSecretNames(ctx.definition);
398
+ const missing = new Set(secrets.missing);
399
+ return {
400
+ slug: ctx.slug,
401
+ file: LOCAL_SECRETS_RELATIVE_PATH,
402
+ absolutePath: secrets.file,
403
+ redirectUri: ctx.definition.oauth ? callbackUrl(ctx.origin, ctx.slug) : null,
404
+ keys: names.map((name) => ({ name, filled: !missing.has(name) })),
405
+ connected,
406
+ connection: connected ? ctx.state.connection : null,
407
+ volatile: true
408
+ };
409
+ }
410
+ async function localSetup(ctx) {
411
+ if (ctx.request.method.toUpperCase() === "GET") {
412
+ return json(
413
+ localSetupResponse(ctx, ctx.secrets, ctx.state.connection !== null)
414
+ );
415
+ }
416
+ let body;
417
+ try {
418
+ body = await ctx.request.json();
419
+ } catch {
420
+ return json({ error: "invalid_json" }, { status: 400 });
421
+ }
422
+ if (!isLocalSetupWriteRequest(body)) {
423
+ return json(
424
+ {
425
+ error: "invalid_local_setup",
426
+ hint: 'Expected { values: { "<declared secret name>": "<value>" } }.'
427
+ },
428
+ { status: 400 }
429
+ );
430
+ }
431
+ const names = declaredSecretNames(ctx.definition);
432
+ const written = writeLocalSecrets({
433
+ projectRoot: ctx.projectRoot,
434
+ slug: ctx.slug,
435
+ names,
436
+ values: body.values
437
+ });
438
+ if (!written.ok) {
439
+ return json(
440
+ { error: "local_secrets_rejected", message: written.message },
441
+ { status: 400 }
442
+ );
443
+ }
444
+ const reread = readLocalSecrets({
445
+ projectRoot: ctx.projectRoot,
446
+ slug: ctx.slug,
447
+ names
448
+ });
449
+ if (!reread.ok) {
450
+ return json(
451
+ { error: "local_secrets_unreadable", message: reread.message },
452
+ { status: 500 }
453
+ );
454
+ }
455
+ const state = getLiveState({
456
+ integration: ctx.integration,
457
+ definition: ctx.definition,
458
+ adminSecrets: reread.values,
459
+ secretsFingerprint: reread.fingerprint
460
+ });
461
+ return json(localSetupResponse(ctx, reread, state.connection !== null));
462
+ }
463
+ export {
464
+ createHarnessApiRouter
465
+ };
@@ -0,0 +1,93 @@
1
+ import type { IntegrationDefinition } from '@ekanos/sdk/integration';
2
+ import { type MockFetchHandler, type MockIntegrationContext } from '@ekanos/sdk/testing';
3
+ import { type HarnessIntegration } from '../../registry.js';
4
+ import { type NonceStore } from './nonce-store.js';
5
+ /**
6
+ * ─────────────────────────────────────────────────────────────────────────────
7
+ * THE LIVE CONTEXT — one server-held `ctx` per integration
8
+ * ─────────────────────────────────────────────────────────────────────────────
9
+ *
10
+ * The Triggers and Activation surfaces run handlers against a mock context
11
+ * built in the BROWSER, per mount, from `triggerMocks` seeds. That is right
12
+ * for fixtures mode and useless for a real OAuth loop: the token exchange
13
+ * needs a server (the client secret must not reach the browser), and the
14
+ * tokens `onTokens` stores must outlive a page — the widgets read what the
15
+ * schedule wrote, minutes later, on a different route.
16
+ *
17
+ * So live mode gets ONE context per slug, held in this process:
18
+ *
19
+ * - built with `createMockContext` — the same storage-schema and egress
20
+ * enforcement partner tests and the host use, no new runtime;
21
+ * - `ctx.fetch` reaches the REAL network through a final catch-all fetch
22
+ * handler. The mock checks egress BEFORE it consults handlers, so an origin
23
+ * the definition does not declare fails here exactly as it would in
24
+ * production. A partner's own `triggerMocks.fetchHandlers` sit ahead of
25
+ * the passthrough, so an endpoint they deliberately mocked stays mocked;
26
+ * - admin-tier secrets come from `.ekanos/local-secrets.json`; account-tier
27
+ * secrets and storage are whatever the partner's own handlers wrote. No
28
+ * storage seeds: live means real data only.
29
+ *
30
+ * Kept on `globalThis` under a `Symbol.for` key so a dev-server recompile of
31
+ * the route module (which resets module scope) does not drop tokens mid-flow.
32
+ * NOT persisted to disk: `dumpStorage()` is lossy (no `expiresAt`), secret
33
+ * tiers cannot be restored, and a plaintext token file is a poor trade for
34
+ * saving one Connect click after a restart. The setup panel says so.
35
+ *
36
+ * Rebuilt when the declared secret VALUES change — a different client id
37
+ * invalidates every token issued under the old one anyway, and a stale admin
38
+ * tier is the kind of bug that presents as "the harness ignores my edits".
39
+ */
40
+ export interface LiveConnection {
41
+ obtainedAt: string;
42
+ expiresAt: string | null;
43
+ scope: string | null;
44
+ }
45
+ export interface LiveState {
46
+ slug: string;
47
+ ctx: MockIntegrationContext;
48
+ connection: LiveConnection | null;
49
+ nonces: NonceStore;
50
+ /** The `local-secrets.json` fingerprint this context was built from. */
51
+ secretsFingerprint: string;
52
+ warmup: {
53
+ inFlight: Promise<void> | null;
54
+ lastStartedAt: number;
55
+ };
56
+ }
57
+ export declare function getLiveStore(): Map<string, LiveState>;
58
+ /** Test seam: forget every live context. */
59
+ export declare function resetLiveStore(): void;
60
+ /**
61
+ * The last fetch handler: hand the request to the fetch beneath the harness
62
+ * interceptor. `redirect: 'error'` for the same reason live-mode widget
63
+ * requests carry it — an allowlist is a promise about ONE url, and a redirect
64
+ * would silently make it a promise about wherever that points next.
65
+ */
66
+ export declare function createNetworkPassthrough(networkFetch?: () => typeof globalThis.fetch): MockFetchHandler;
67
+ export interface LiveStateInput {
68
+ integration: HarnessIntegration;
69
+ definition: IntegrationDefinition;
70
+ /** Declared secret names → filled values, from `local-secrets.json`. */
71
+ adminSecrets: Record<string, string>;
72
+ secretsFingerprint: string;
73
+ /** Test seam for the passthrough's network fetch. */
74
+ networkFetch?: () => typeof globalThis.fetch;
75
+ /** Test seam for the nonce store. */
76
+ nonces?: () => NonceStore;
77
+ }
78
+ export declare function getLiveState(input: LiveStateInput): LiveState;
79
+ /** Between warm-ups for one slug, so a rendering burst is one invocation. */
80
+ export declare const WARMUP_COOLDOWN_MS = 30000;
81
+ /** How long the storage route waits for a warm-up before answering empty. */
82
+ export declare const WARMUP_BUDGET_MS = 8000;
83
+ /**
84
+ * Read-through warm-up, mirroring the host storage route: an EMPTY read runs
85
+ * the declared schedule handler(s) once so the first paint after Connect has
86
+ * data, instead of the widget staring at nothing until someone presses "Run
87
+ * now". One in-flight run per slug, one start per cooldown window; the
88
+ * caller races it against `WARMUP_BUDGET_MS` and re-reads if it finishes.
89
+ *
90
+ * Returns the in-flight promise when a run is happening, or `null` when
91
+ * nothing was (or could be) started.
92
+ */
93
+ export declare function startWarmup(state: LiveState, definition: IntegrationDefinition, now?: () => number): Promise<void> | null;
@@ -0,0 +1,93 @@
1
+ import {
2
+ createMockContext,
3
+ invokeSchedule
4
+ } from "@ekanos/sdk/testing";
5
+ import { HARNESS_ACCOUNT_ID } from "../../registry.js";
6
+ import { resolveOriginalFetch } from "../lib/original-fetch.js";
7
+ import { createNonceStore } from "./nonce-store.js";
8
+ const STORE = /* @__PURE__ */ Symbol.for("ekanos.harness.live-state");
9
+ function getLiveStore() {
10
+ const carrier = globalThis;
11
+ carrier[STORE] ??= /* @__PURE__ */ new Map();
12
+ return carrier[STORE];
13
+ }
14
+ function resetLiveStore() {
15
+ getLiveStore().clear();
16
+ }
17
+ function createNetworkPassthrough(networkFetch = resolveOriginalFetch) {
18
+ return {
19
+ match: /^/,
20
+ respond: (request) => networkFetch()(request, { redirect: "error" })
21
+ };
22
+ }
23
+ function getLiveState(input) {
24
+ const store = getLiveStore();
25
+ const existing = store.get(input.integration.slug);
26
+ if (existing && existing.secretsFingerprint === input.secretsFingerprint) {
27
+ return existing;
28
+ }
29
+ if (existing) {
30
+ console.info(
31
+ `[harness:${input.integration.slug}] local-secrets.json changed \u2014 rebuilding the live context. Any connection is forgotten; run Connect again.`
32
+ );
33
+ }
34
+ const definition = input.definition;
35
+ const ctx = createMockContext({
36
+ accountId: HARNESS_ACCOUNT_ID,
37
+ integration: { slug: definition.slug },
38
+ ...definition.storage ? { storageSchemas: definition.storage } : {},
39
+ egress: definition.egress ?? [],
40
+ secrets: { admin: input.adminSecrets },
41
+ fetchHandlers: [
42
+ ...input.integration.triggerMocks?.fetchHandlers ?? [],
43
+ createNetworkPassthrough(input.networkFetch)
44
+ ]
45
+ });
46
+ const state = {
47
+ slug: input.integration.slug,
48
+ ctx,
49
+ connection: null,
50
+ nonces: input.nonces?.() ?? createNonceStore(),
51
+ secretsFingerprint: input.secretsFingerprint,
52
+ warmup: { inFlight: null, lastStartedAt: 0 }
53
+ };
54
+ store.set(input.integration.slug, state);
55
+ return state;
56
+ }
57
+ const WARMUP_COOLDOWN_MS = 3e4;
58
+ const WARMUP_BUDGET_MS = 8e3;
59
+ function startWarmup(state, definition, now = Date.now) {
60
+ if (state.warmup.inFlight) return state.warmup.inFlight;
61
+ const schedules = definition.schedules ?? [];
62
+ if (schedules.length === 0) return null;
63
+ if (now() - state.warmup.lastStartedAt < WARMUP_COOLDOWN_MS) return null;
64
+ state.warmup.lastStartedAt = now();
65
+ const run = (async () => {
66
+ for (const schedule of schedules) {
67
+ try {
68
+ await invokeSchedule(definition, schedule.id, {
69
+ context: state.ctx,
70
+ trigger: "schedule"
71
+ });
72
+ } catch (error) {
73
+ console.warn(
74
+ `[harness:${state.slug}] read-through warm-up: schedule "${schedule.id}" threw`,
75
+ error
76
+ );
77
+ }
78
+ }
79
+ })().finally(() => {
80
+ state.warmup.inFlight = null;
81
+ });
82
+ state.warmup.inFlight = run;
83
+ return run;
84
+ }
85
+ export {
86
+ WARMUP_BUDGET_MS,
87
+ WARMUP_COOLDOWN_MS,
88
+ createNetworkPassthrough,
89
+ getLiveState,
90
+ getLiveStore,
91
+ resetLiveStore,
92
+ startWarmup
93
+ };