@ekanos/harness 0.1.4 → 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 +286 -174
  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 +5 -2
  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 +51 -28
  22. package/dist/internal/routes/integration-layout.js +5 -1
  23. package/dist/internal/routes/triggers-page.js +130 -149
  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 +103 -13
  41. package/dist/registry.js +21 -1
  42. package/package.json +13 -7
@@ -0,0 +1,28 @@
1
+ function buildOAuthSetupGuide(args) {
2
+ const oauth = args.definition.oauth;
3
+ if (!oauth) return null;
4
+ const setup = args.entry.oauth?.setup;
5
+ const consoleUrl = setup?.consoleUrl;
6
+ return {
7
+ providerHost: hostOf(oauth.provider.authorizationUrl),
8
+ console: consoleUrl ? { url: consoleUrl, label: setup?.consoleLabel ?? hostOf(consoleUrl) } : null,
9
+ redirectUri: args.redirectUri,
10
+ scopes: oauth.provider.scopes,
11
+ pkce: oauth.provider.pkce === true,
12
+ credentials: {
13
+ clientId: oauth.credentials.clientIdSecretName,
14
+ clientSecret: oauth.credentials.clientSecretSecretName
15
+ },
16
+ notes: setup?.notes ?? []
17
+ };
18
+ }
19
+ function hostOf(url) {
20
+ try {
21
+ return new URL(url).host;
22
+ } catch {
23
+ return url;
24
+ }
25
+ }
26
+ export {
27
+ buildOAuthSetupGuide
28
+ };
@@ -0,0 +1,36 @@
1
+ /**
2
+ * ─────────────────────────────────────────────────────────────────────────────
3
+ * FINDING THE REAL `fetch` FROM UNDER THE INTERCEPTOR
4
+ * ─────────────────────────────────────────────────────────────────────────────
5
+ *
6
+ * `harness-fetch-interceptor.ts` patches `globalThis.fetch` at module import,
7
+ * and `harness-providers.tsx` imports it — a `'use client'` module that Next
8
+ * ALSO evaluates during the server render, in the same Node process the API
9
+ * route handlers run in. So on the server, `globalThis.fetch` may be the
10
+ * interceptor, answering from whatever fixture table the last page render
11
+ * published: a route handler calling `globalThis.fetch(tokenUrl)` would then
12
+ * be refused as "no recorded response" in fixtures mode, or pass through in
13
+ * live mode, depending on which page happened to render last. Measured in
14
+ * review, not theorised.
15
+ *
16
+ * The interceptor therefore TAGS its wrapper with the function it wrapped,
17
+ * under a `Symbol.for` key so the tag survives duplicate module instances
18
+ * (dev HMR, two copies of this package). Server code that must reach the
19
+ * network unwraps here, at CALL time — the patch may land after this module
20
+ * was imported.
21
+ *
22
+ * Directive-free on purpose: imported by both the client interceptor and the
23
+ * server routes.
24
+ */
25
+ export declare const ORIGINAL_FETCH: unique symbol;
26
+ type Fetch = typeof globalThis.fetch;
27
+ /** Record on `wrapper` the fetch it delegates to. */
28
+ export declare function tagInterceptor(wrapper: Fetch, original: Fetch): void;
29
+ /**
30
+ * The fetch beneath every harness wrapper currently on `candidate` (default:
31
+ * the global). A function with no tag is taken to be the real one. Cycles
32
+ * cannot form through `tagInterceptor` alone, but the walk is bounded anyway
33
+ * so a hostile or buggy tag can never hang a request.
34
+ */
35
+ export declare function resolveOriginalFetch(candidate?: Fetch): Fetch;
36
+ export {};
@@ -0,0 +1,23 @@
1
+ const ORIGINAL_FETCH = /* @__PURE__ */ Symbol.for("ekanos.harness.original-fetch");
2
+ function tagInterceptor(wrapper, original) {
3
+ Object.defineProperty(wrapper, ORIGINAL_FETCH, {
4
+ value: original,
5
+ enumerable: false,
6
+ configurable: true,
7
+ writable: false
8
+ });
9
+ }
10
+ function resolveOriginalFetch(candidate = globalThis.fetch) {
11
+ let current = candidate;
12
+ const seen = /* @__PURE__ */ new Set();
13
+ while (current[ORIGINAL_FETCH] !== void 0 && !seen.has(current)) {
14
+ seen.add(current);
15
+ current = current[ORIGINAL_FETCH];
16
+ }
17
+ return current;
18
+ }
19
+ export {
20
+ ORIGINAL_FETCH,
21
+ resolveOriginalFetch,
22
+ tagInterceptor
23
+ };
@@ -1,5 +1,6 @@
1
1
  import type { IntegrationDefinition } from '@ekanos/sdk/integration';
2
2
  import { type MockIntegrationContext } from '@ekanos/sdk/testing';
3
+ import type { OnActivateOutcome } from './trigger-contract.js';
3
4
  /**
4
5
  * The outcome of one local run of a definition's `onActivate` hook, for the
5
6
  * Activation surface's readout:
@@ -17,12 +18,5 @@ import { type MockIntegrationContext } from '@ekanos/sdk/testing';
17
18
  * rendering anything — the harness deliberately carries no component/DOM
18
19
  * tests (see vitest.config.ts), only the underlying logic.
19
20
  */
20
- export type OnActivateOutcome = {
21
- status: 'skipped';
22
- } | {
23
- status: 'ran';
24
- } | {
25
- status: 'threw';
26
- message: string;
27
- };
21
+ export type { OnActivateOutcome };
28
22
  export declare function runOnActivateHook(definition: IntegrationDefinition | undefined, ctx: MockIntegrationContext | null): Promise<OnActivateOutcome>;
@@ -27,11 +27,15 @@ export interface ToolbarState {
27
27
  * Where a widget's data comes from. `fixtures` seeds the react-query cache
28
28
  * and blocks every request; `live` lets the widget's own query functions run
29
29
  * against the real third-party API, through a fetch bound to the
30
- * integration's declared egress allowlist. Fusion stays mocked in both.
30
+ * integration's declared egress allowlist, and lets the shell's own API
31
+ * routes answer `/api/integrations/<slug>/…` over the live context.
31
32
  *
32
- * Only honoured for integrations that declare a `live` block in the registry.
33
+ * `null` means nobody has picked one yet, so the integration's own
34
+ * `live.default` decides (fixtures unless it says otherwise) — see
35
+ * `resolveEffectiveDataMode`. Only honoured for integrations that declare a
36
+ * `live` block in the registry.
33
37
  */
34
- dataMode: DataMode;
38
+ dataMode: DataMode | null;
35
39
  variant: FixtureVariant;
36
40
  viewport: ViewportKey;
37
41
  collapsed: boolean;
@@ -24,16 +24,18 @@ const VIEWPORTS = {
24
24
  };
25
25
  const DEFAULT_STATE = {
26
26
  renderState: "active",
27
- // Fixtures by default, always. Opening the harness must never fire a request
28
- // at somebody's API just because a previous session left a switch flipped for
29
- // a different integration.
30
- dataMode: "fixtures",
27
+ // Unset by default, which RESOLVES to fixtures unless the integration itself
28
+ // declares `live: { default: 'live' }`. Opening the harness must never fire a
29
+ // request at somebody's API just because a previous session left a switch
30
+ // flipped for a different integration — and an integration only declares a
31
+ // live default when its widgets never call the vendor from the browser.
32
+ dataMode: null,
31
33
  variant: "default",
32
34
  viewport: "full",
33
35
  collapsed: false,
34
36
  unhealthy: false
35
37
  };
36
- const STORAGE_KEY = "fusion-harness-toolbar";
38
+ const STORAGE_KEY = "fusion-harness-toolbar-v2";
37
39
  function isRenderState(value) {
38
40
  return RENDER_STATES.includes(value);
39
41
  }
@@ -55,6 +57,9 @@ function readStored() {
55
57
  const candidate = parsed;
56
58
  return {
57
59
  renderState: isRenderState(candidate.renderState) ? candidate.renderState : DEFAULT_STATE.renderState,
60
+ // A stored `'fixtures'` is an explicit choice from an earlier session and
61
+ // still wins over an integration's live default — that is what makes
62
+ // the default safe to declare.
58
63
  dataMode: isDataMode(candidate.dataMode) ? candidate.dataMode : DEFAULT_STATE.dataMode,
59
64
  variant: isVariant(candidate.variant) ? candidate.variant : DEFAULT_STATE.variant,
60
65
  viewport: isViewport(candidate.viewport) ? candidate.viewport : DEFAULT_STATE.viewport,
@@ -0,0 +1,99 @@
1
+ /**
2
+ * The wire and render contract shared by the Triggers/Activation surfaces and
3
+ * the harness's own `POST /api/integrations/[slug]/trigger` route.
4
+ *
5
+ * In FIXTURES mode the pages run handlers in the browser against a per-mount
6
+ * mock context and build these shapes locally. In LIVE mode they post to the
7
+ * route, which runs the same helpers against the server-held live context —
8
+ * the one `onTokens` stored real tokens in — and answers with the same shapes.
9
+ * One contract, so a panel cannot render one mode differently from the other.
10
+ *
11
+ * Directive-free: imported by client pages and by the server route.
12
+ */
13
+ export interface HandlerLog {
14
+ level: string;
15
+ message: string;
16
+ }
17
+ export interface StorageDump {
18
+ account: Record<string, unknown>;
19
+ user: Record<string, unknown>;
20
+ }
21
+ /** The outcome of one webhook delivery or schedule run. */
22
+ export interface InvocationOutcome {
23
+ ok: boolean;
24
+ summary: string;
25
+ detail?: string;
26
+ logs: readonly HandlerLog[];
27
+ /**
28
+ * BOTH scopes. `ctx.dumpStorage()` returns `{ account, user }`, and this
29
+ * panel used to render only `account` — so a handler writing to user scope
30
+ * looked like a handler that had written nothing.
31
+ */
32
+ storage: StorageDump;
33
+ }
34
+ /** The outcome of one `onActivate` run — see `run-activation-hook.ts`. */
35
+ export type OnActivateOutcome = {
36
+ status: 'skipped';
37
+ } | {
38
+ status: 'ran';
39
+ } | {
40
+ status: 'threw';
41
+ message: string;
42
+ };
43
+ export type TriggerRequest = {
44
+ kind: 'webhook';
45
+ id: string;
46
+ payload: unknown;
47
+ /** Delivery headers. Defaults to the local transport's unverified marker. */
48
+ headers?: Record<string, string>;
49
+ } | {
50
+ kind: 'schedule';
51
+ id: string;
52
+ } | {
53
+ kind: 'activate';
54
+ };
55
+ export type TriggerResponse = {
56
+ kind: 'webhook' | 'schedule';
57
+ outcome: InvocationOutcome;
58
+ /** Names only — never values. */
59
+ secretNames: string[];
60
+ } | {
61
+ kind: 'activate';
62
+ outcome: OnActivateOutcome;
63
+ logs: readonly HandlerLog[];
64
+ storage: StorageDump;
65
+ secretNames: string[];
66
+ };
67
+ /** The setup readout behind `GET /api/integrations/[slug]/local-setup`. */
68
+ export interface LocalSetupResponse {
69
+ slug: string;
70
+ /** The credentials file, relative to the project root. */
71
+ file: string;
72
+ /** Absolute, for copying into an editor. */
73
+ absolutePath: string;
74
+ /** `null` when the definition declares no `oauth`. */
75
+ redirectUri: string | null;
76
+ keys: {
77
+ name: string;
78
+ filled: boolean;
79
+ }[];
80
+ connected: boolean;
81
+ connection: {
82
+ obtainedAt: string;
83
+ expiresAt: string | null;
84
+ scope: string | null;
85
+ } | null;
86
+ /** Always true today: the connection lives in server memory only. */
87
+ volatile: true;
88
+ }
89
+ /**
90
+ * `PUT /api/integrations/[slug]/local-setup` — the Local OAuth panel's Save.
91
+ * Values travel browser → dev server over loopback ONCE, are written to
92
+ * `.ekanos/local-secrets.json`, and never come back: the response is the same
93
+ * `LocalSetupResponse` the GET returns, filled/missing only.
94
+ */
95
+ export interface LocalSetupWriteRequest {
96
+ values: Record<string, string>;
97
+ }
98
+ export declare function isLocalSetupWriteRequest(value: unknown): value is LocalSetupWriteRequest;
99
+ export declare function isTriggerRequest(value: unknown): value is TriggerRequest;
@@ -0,0 +1,25 @@
1
+ function isLocalSetupWriteRequest(value) {
2
+ if (typeof value !== "object" || value === null) return false;
3
+ const values = value.values;
4
+ return typeof values === "object" && values !== null && !Array.isArray(values) && Object.values(values).every(
5
+ (v) => typeof v === "string"
6
+ );
7
+ }
8
+ function isTriggerRequest(value) {
9
+ if (typeof value !== "object" || value === null) return false;
10
+ const record = value;
11
+ switch (record.kind) {
12
+ case "webhook":
13
+ return typeof record.id === "string" && (record.headers === void 0 || typeof record.headers === "object" && record.headers !== null);
14
+ case "schedule":
15
+ return typeof record.id === "string";
16
+ case "activate":
17
+ return true;
18
+ default:
19
+ return false;
20
+ }
21
+ }
22
+ export {
23
+ isLocalSetupWriteRequest,
24
+ isTriggerRequest
25
+ };
@@ -0,0 +1,55 @@
1
+ import type { IntegrationDefinition } from '@ekanos/sdk/integration';
2
+ import { type MockIntegrationContext } from '@ekanos/sdk/testing';
3
+ import type { InvocationOutcome, LocalSetupResponse, LocalSetupWriteRequest, OnActivateOutcome } from './trigger-contract.js';
4
+ /**
5
+ * ─────────────────────────────────────────────────────────────────────────────
6
+ * ONE WAY TO RUN A HANDLER, TWO PLACES IT CAN RUN
7
+ * ─────────────────────────────────────────────────────────────────────────────
8
+ *
9
+ * The Triggers and Activation surfaces used to hold a per-mount mock context
10
+ * and call `invokeWebhook`/`invokeSchedule`/`invokeActivate` on it directly.
11
+ * That is still exactly right for FIXTURES mode. It is wrong for LIVE mode,
12
+ * where the context that holds the real tokens lives on the SERVER
13
+ * (`internal/server/live-context.ts`) — a browser-side context would run the
14
+ * partner's schedule with no credentials and report a confident "skipped".
15
+ *
16
+ * So the pages ask a `TriggerRunner` and never touch a context themselves:
17
+ *
18
+ * createLocalTriggerRunner(definition, ctx) fixtures — in the browser
19
+ * createServerTriggerRunner(slug) live — POST …/trigger
20
+ *
21
+ * Both return the SAME outcome shapes (`trigger-contract.ts`), so the panels
22
+ * render identically whichever ran.
23
+ */
24
+ export interface TriggerRunner {
25
+ webhook(id: string, payload: unknown, headers?: Record<string, string>): Promise<InvocationOutcome>;
26
+ schedule(id: string): Promise<InvocationOutcome>;
27
+ activate(): Promise<OnActivateOutcome>;
28
+ }
29
+ /** Fixtures mode: run against the per-mount browser context. */
30
+ export declare function createLocalTriggerRunner(definition: IntegrationDefinition, ctx: MockIntegrationContext): TriggerRunner;
31
+ export declare function triggerUrl(slug: string): string;
32
+ export declare function localSetupUrl(slug: string): string;
33
+ /**
34
+ * A harness API error, with the server's own message when it sent one — the
35
+ * loopback refusal and the project-root failure both explain themselves, and
36
+ * that explanation must reach the panel rather than a bare status code.
37
+ */
38
+ export declare class HarnessApiError extends Error {
39
+ readonly status: number;
40
+ constructor(status: number, message: string);
41
+ }
42
+ /**
43
+ * Live mode: run on the server-held live context. The request goes through
44
+ * `globalThis.fetch`, which the interceptor passes through for the active
45
+ * integration's `/api/integrations/<slug>/` paths in live mode.
46
+ */
47
+ export declare function createServerTriggerRunner(slug: string, fetchImpl?: typeof globalThis.fetch): TriggerRunner;
48
+ /** The setup readout for the Local OAuth panel. Live mode only. */
49
+ export declare function fetchLocalSetup(slug: string, fetchImpl?: typeof globalThis.fetch): Promise<LocalSetupResponse>;
50
+ /**
51
+ * The Local OAuth panel's Save: write declared secret values into
52
+ * `.ekanos/local-secrets.json` through the dev server. The values leave the
53
+ * browser exactly once, to loopback; the response reports filled/missing.
54
+ */
55
+ export declare function saveLocalSetup(slug: string, request: LocalSetupWriteRequest, fetchImpl?: typeof globalThis.fetch): Promise<LocalSetupResponse>;
@@ -0,0 +1,153 @@
1
+ import {
2
+ invokeSchedule,
3
+ invokeWebhook
4
+ } from "@ekanos/sdk/testing";
5
+ import { runOnActivateHook } from "./run-activation-hook.js";
6
+ function describeError(error) {
7
+ return error instanceof Error ? error.message : String(error);
8
+ }
9
+ function createLocalTriggerRunner(definition, ctx) {
10
+ const run = async (invoke) => {
11
+ const logsBefore = ctx.logs.length;
12
+ try {
13
+ const result = await invoke();
14
+ return {
15
+ ok: true,
16
+ summary: result.status,
17
+ ...result.detail ? { detail: result.detail } : {},
18
+ logs: ctx.logs.slice(logsBefore),
19
+ storage: ctx.dumpStorage()
20
+ };
21
+ } catch (error) {
22
+ console.error("[harness] handler invocation failed:", error);
23
+ return {
24
+ ok: false,
25
+ summary: "failed",
26
+ detail: describeError(error),
27
+ logs: ctx.logs.slice(logsBefore),
28
+ storage: ctx.dumpStorage()
29
+ };
30
+ }
31
+ };
32
+ return {
33
+ webhook: (id, payload, headers) => run(async () => {
34
+ const webhook = definition.webhooks?.find((w) => w.id === id);
35
+ const { result } = await invokeWebhook(definition, id, payload, {
36
+ context: ctx,
37
+ headers: headers ?? (!webhook || webhook.signature === "none" ? {} : {
38
+ [webhook.signature.header]: "(unverified \u2014 local transport)"
39
+ })
40
+ });
41
+ return result;
42
+ }),
43
+ schedule: (id) => run(async () => {
44
+ const { result } = await invokeSchedule(definition, id, {
45
+ context: ctx
46
+ });
47
+ return result;
48
+ }),
49
+ activate: () => runOnActivateHook(definition, ctx)
50
+ };
51
+ }
52
+ function triggerUrl(slug) {
53
+ return `/api/integrations/${slug}/trigger`;
54
+ }
55
+ function localSetupUrl(slug) {
56
+ return `/api/integrations/${slug}/local-setup`;
57
+ }
58
+ class HarnessApiError extends Error {
59
+ constructor(status, message) {
60
+ super(message);
61
+ this.status = status;
62
+ this.name = "HarnessApiError";
63
+ }
64
+ }
65
+ async function readError(response) {
66
+ let message = `${response.status} ${response.statusText}`;
67
+ try {
68
+ const body = await response.json();
69
+ const detail = [body.message, body.hint].filter((part) => typeof part === "string").join(" ");
70
+ if (detail) message = `${message} \u2014 ${detail}`;
71
+ else if (typeof body.error === "string")
72
+ message = `${message} \u2014 ${body.error}`;
73
+ } catch {
74
+ }
75
+ return new HarnessApiError(response.status, message);
76
+ }
77
+ function createServerTriggerRunner(slug, fetchImpl = (input, init) => globalThis.fetch(input, init)) {
78
+ const post = async (request) => {
79
+ const response = await fetchImpl(triggerUrl(slug), {
80
+ method: "POST",
81
+ headers: {
82
+ "content-type": "application/json",
83
+ accept: "application/json"
84
+ },
85
+ body: JSON.stringify(request)
86
+ });
87
+ if (!response.ok) throw await readError(response);
88
+ return await response.json();
89
+ };
90
+ const invocation = async (request) => {
91
+ try {
92
+ const result = await post(request);
93
+ if (result.kind === "activate") {
94
+ throw new Error("trigger route answered the wrong kind");
95
+ }
96
+ return result.outcome;
97
+ } catch (error) {
98
+ console.error("[harness] server trigger failed:", error);
99
+ return {
100
+ ok: false,
101
+ summary: "failed",
102
+ detail: describeError(error),
103
+ logs: [],
104
+ storage: { account: {}, user: {} }
105
+ };
106
+ }
107
+ };
108
+ return {
109
+ webhook: (id, payload, headers) => invocation({
110
+ kind: "webhook",
111
+ id,
112
+ payload,
113
+ ...headers ? { headers } : {}
114
+ }),
115
+ schedule: (id) => invocation({ kind: "schedule", id }),
116
+ activate: async () => {
117
+ try {
118
+ const result = await post({ kind: "activate" });
119
+ return result.kind === "activate" ? result.outcome : {
120
+ status: "threw",
121
+ message: "trigger route answered the wrong kind"
122
+ };
123
+ } catch (error) {
124
+ return { status: "threw", message: describeError(error) };
125
+ }
126
+ }
127
+ };
128
+ }
129
+ async function fetchLocalSetup(slug, fetchImpl = (input, init) => globalThis.fetch(input, init)) {
130
+ const response = await fetchImpl(localSetupUrl(slug), {
131
+ headers: { accept: "application/json" }
132
+ });
133
+ if (!response.ok) throw await readError(response);
134
+ return await response.json();
135
+ }
136
+ async function saveLocalSetup(slug, request, fetchImpl = (input, init) => globalThis.fetch(input, init)) {
137
+ const response = await fetchImpl(localSetupUrl(slug), {
138
+ method: "PUT",
139
+ headers: { "content-type": "application/json", accept: "application/json" },
140
+ body: JSON.stringify(request)
141
+ });
142
+ if (!response.ok) throw await readError(response);
143
+ return await response.json();
144
+ }
145
+ export {
146
+ HarnessApiError,
147
+ createLocalTriggerRunner,
148
+ createServerTriggerRunner,
149
+ fetchLocalSetup,
150
+ localSetupUrl,
151
+ saveLocalSetup,
152
+ triggerUrl
153
+ };
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
- import { useState } from "react";
3
+ import { useMemo, useState } from "react";
4
4
  import { notFound } from "next/navigation";
5
5
  import { Alert, AlertDescription, AlertTitle } from "@ekanos/ui/alert";
6
6
  import { Badge } from "@ekanos/ui/badge";
@@ -13,6 +13,7 @@ import {
13
13
  DialogTitle
14
14
  } from "@ekanos/ui/dialog";
15
15
  import { HARNESS_ACCOUNT_ID } from "../../registry.js";
16
+ import { LocalOAuthPanel } from "../components/local-oauth-panel.js";
16
17
  import { useDefinitionMockContext } from "../lib/definition-mock-context.js";
17
18
  import {
18
19
  useHarnessDataMode,
@@ -20,20 +21,25 @@ import {
20
21
  } from "../lib/harness-hooks.js";
21
22
  import { clearLiveActivationData } from "../lib/live-activation-store.js";
22
23
  import { hasSensitiveValues, redactSensitive } from "../lib/redact.js";
23
- import {
24
- runOnActivateHook
25
- } from "../lib/run-activation-hook.js";
26
24
  import { useToolbar } from "../lib/toolbar-context.js";
25
+ import {
26
+ createLocalTriggerRunner,
27
+ createServerTriggerRunner
28
+ } from "../lib/trigger-runner.js";
27
29
  import { useHarnessIntegration } from "../registry-context.js";
28
30
  function ActivationPage() {
29
- const [flow, setFlow] = useState({
30
- open: true,
31
+ const integration = useHarnessIntegration();
32
+ const [flow, setFlow] = useState(() => ({
33
+ // An OAuth integration starts with the dialog CLOSED: its Connect button
34
+ // needs the Local OAuth credentials saved first, and the panel that takes
35
+ // them sits on this page — under a modal backdrop if the dialog opened
36
+ // on top of it. Everything else opens straight into the connect flow.
37
+ open: !integration?.definition?.oauth,
31
38
  connected: false,
32
39
  result: null,
33
40
  revealed: false,
34
41
  activationHook: null
35
- });
36
- const integration = useHarnessIntegration();
42
+ }));
37
43
  const { state: toolbar } = useToolbar();
38
44
  const mode = useHarnessDataMode();
39
45
  const activationData = useLiveActivationData();
@@ -41,9 +47,14 @@ function ActivationPage() {
41
47
  integration ?? { slug: "", name: "", description: "", widgets: [] },
42
48
  toolbar.variant
43
49
  );
50
+ const definition = integration?.definition;
51
+ const runner = useMemo(() => {
52
+ if (!integration || !definition) return null;
53
+ if (mode === "live") return createServerTriggerRunner(integration.slug);
54
+ return ctx ? createLocalTriggerRunner(definition, ctx) : null;
55
+ }, [integration, definition, mode, ctx]);
44
56
  if (!integration) notFound();
45
57
  const ActivationForm = integration.activationForm;
46
- const definition = integration.definition;
47
58
  const capabilities = definition?.capabilities ?? [];
48
59
  const permissions = definition?.permissions ?? [];
49
60
  const summary = definition?.description ?? integration.description;
@@ -54,21 +65,24 @@ function ActivationPage() {
54
65
  "data-test": "activation",
55
66
  children: [
56
67
  /* @__PURE__ */ jsxs(Alert, { children: [
57
- /* @__PURE__ */ jsx(AlertTitle, { children: "Submissions go nowhere" }),
58
- /* @__PURE__ */ jsx(AlertDescription, { children: /* @__PURE__ */ jsxs("p", { children: [
59
- "The harness has no backend. Submitting shows you the",
60
- " ",
61
- /* @__PURE__ */ jsx("code", { children: "ActivationResult" }),
62
- " your form handed back instead of posting it \u2014 which is the part worth checking, since that payload is what the real activation action would persist. The dialog, the capability and permission sections and the connected state are the real ones, rendered from your ",
63
- /* @__PURE__ */ jsx("code", { children: "defineIntegration()" }),
64
- " ",
65
- "declaration."
66
- ] }) })
68
+ /* @__PURE__ */ jsx(AlertTitle, { children: mode === "live" ? "Submissions run onActivate on the dev server" : "Submissions go nowhere" }),
69
+ /* @__PURE__ */ jsxs(AlertDescription, { children: [
70
+ /* @__PURE__ */ jsxs("p", { children: [
71
+ "The harness has no Fusion backend. Submitting shows you the",
72
+ " ",
73
+ /* @__PURE__ */ jsx("code", { children: "ActivationResult" }),
74
+ " your form handed back instead of persisting it \u2014 which is the part worth checking, since that payload is what the real activation action would store. The dialog, the capability and permission sections and the connected state are the real ones, rendered from your ",
75
+ /* @__PURE__ */ jsx("code", { children: "defineIntegration()" }),
76
+ " ",
77
+ "declaration."
78
+ ] }),
79
+ /* @__PURE__ */ jsx("p", { "data-test": "activation-mode-notice-top", children: mode === "live" ? "Live API: an OAuth form\u2019s Connect runs the real loop through the generated shell (see Local OAuth below), onActivate runs on the server-held context that loop stored tokens in, and widgets reach real vendors through useIntegrationFetch(). The host runs the same declarations, with real enforcement, after you publish." : "Fixtures: an OAuth form reads its connection status from oauth.connected in your harness entry, onActivate runs in this browser against a context seeded from triggerMocks, and nothing leaves your machine." })
80
+ ] })
67
81
  ] }),
68
82
  /* @__PURE__ */ jsxs("div", { className: "bg-card flex flex-wrap items-center justify-between gap-3 rounded-lg border p-5", children: [
69
83
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1", children: [
70
84
  /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: flow.connected ? "Connected" : "Not connected" }),
71
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: flow.connected ? "The dialog now shows the manage view, whose only action is Disconnect." : "The dialog shows the scope disclosure and your activation form." })
85
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: flow.connected ? "The dialog now shows the manage view, whose only action is Disconnect." : definition?.oauth ? "Save your local OAuth credentials below, then open the connect dialog and click Connect." : "The dialog shows the scope disclosure and your activation form." })
72
86
  ] }),
73
87
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
74
88
  /* @__PURE__ */ jsx(
@@ -101,6 +115,15 @@ function ActivationPage() {
101
115
  )
102
116
  ] })
103
117
  ] }),
118
+ definition ? /* @__PURE__ */ jsx(
119
+ LocalOAuthPanel,
120
+ {
121
+ integration,
122
+ definition,
123
+ mode,
124
+ variant: toolbar.variant
125
+ }
126
+ ) : null,
104
127
  ActivationForm ? /* @__PURE__ */ jsx(
105
128
  Dialog,
106
129
  {
@@ -147,10 +170,7 @@ function ActivationPage() {
147
170
  productSlug: integration.slug,
148
171
  inline: true,
149
172
  onSuccess: async (result) => {
150
- const activationHook = await runOnActivateHook(
151
- definition,
152
- ctx
153
- );
173
+ const activationHook = runner ? await runner.activate() : { status: "skipped" };
154
174
  setFlow({
155
175
  open: false,
156
176
  connected: true,
@@ -215,12 +235,15 @@ function ActivationPage() {
215
235
  2
216
236
  ) })
217
237
  ] }) : null,
218
- flow.activationHook ? /* @__PURE__ */ jsx(OnActivatePanel, { outcome: flow.activationHook }) : null
238
+ flow.activationHook ? /* @__PURE__ */ jsx(OnActivatePanel, { outcome: flow.activationHook, mode }) : null
219
239
  ]
220
240
  }
221
241
  );
222
242
  }
223
- function OnActivatePanel({ outcome }) {
243
+ function OnActivatePanel({
244
+ outcome,
245
+ mode
246
+ }) {
224
247
  const badge = outcome.status === "ran" ? { variant: "default", label: "onActivate ran" } : outcome.status === "skipped" ? {
225
248
  variant: "secondary",
226
249
  label: "onActivate skipped \u2014 not declared"
@@ -241,7 +264,7 @@ function OnActivatePanel({ outcome }) {
241
264
  ] }) : outcome.status === "threw" ? /* @__PURE__ */ jsxs(Fragment, { children: [
242
265
  /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm", children: "In production this is NON-FATAL: the throw is logged and shown to the user as a warning, and the activation stays connected \u2014 this hook is for cache seeding and eager validation, not a connect gate." }),
243
266
  /* @__PURE__ */ jsx("pre", { className: "bg-muted overflow-x-auto rounded-md p-3 text-xs", children: outcome.message })
244
- ] }) : /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm", children: "Ran against the same kind of capability context (storage, secrets, egress) your schedules and webhooks run against." })
267
+ ] }) : /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-sm", children: mode === "live" ? "Ran on the dev server against the live context \u2014 the same storage and secrets the OAuth loop and your schedules use, with ctx.fetch reaching your vendor under the declared egress." : "Ran against the same kind of capability context (storage, secrets, egress) your schedules and webhooks run against." })
245
268
  ]
246
269
  }
247
270
  );
@@ -299,7 +322,7 @@ function ConnectedState({
299
322
  {
300
323
  className: "text-muted-foreground text-sm",
301
324
  "data-test": "activation-mode-notice",
302
- children: mode === "live" ? hasLiveActivationData ? "The toolbar is on Live API \u2014 this activation data is available to live-mode widgets on this visit." : "The toolbar is on Live API, but this activation submitted no data for live-mode widgets to authenticate with." : "This surface is Fusion-mocked; widgets read fixtures \u2014 switch the toolbar to Live API to exercise real requests."
325
+ children: mode === "live" ? hasLiveActivationData ? "The toolbar is on Live API \u2014 this activation data is available to live-mode widgets on this visit." : "The toolbar is on Live API. This activation submitted no data of its own; an OAuth integration\u2019s credentials live on the dev server, where onTokens stored them." : "This surface is Fusion-mocked; widgets read fixtures \u2014 switch the toolbar to Live API to exercise real requests."
303
326
  }
304
327
  ),
305
328
  /* @__PURE__ */ jsx(