@opendatalabs/vana-sdk 3.8.2 → 3.8.3

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.
@@ -29,14 +29,35 @@ function toError(value) {
29
29
  function isReadReadyStatus(status) {
30
30
  return status === "approved" || status === "ready_for_read";
31
31
  }
32
+ function defaultOpenApprovalWindow() {
33
+ if (typeof window === "undefined" || !window.open) return null;
34
+ const opened = window.open("", "_blank");
35
+ if (!opened) return null;
36
+ try {
37
+ opened.opener = null;
38
+ } catch {
39
+ }
40
+ return {
41
+ navigate(url) {
42
+ try {
43
+ const meta = opened.document.createElement("meta");
44
+ meta.name = "referrer";
45
+ meta.content = "no-referrer";
46
+ (opened.document.head ?? opened.document.documentElement)?.appendChild(
47
+ meta
48
+ );
49
+ } catch {
50
+ }
51
+ opened.location.href = url;
52
+ },
53
+ close() {
54
+ opened.close();
55
+ }
56
+ };
57
+ }
32
58
  function createDirectConnectFlow(transports, options = {}) {
33
59
  const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
34
60
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
35
- const openWindow = options.openWindow ?? ((url) => {
36
- if (typeof window !== "undefined" && window.open) {
37
- window.open(url, "_blank", "noopener,noreferrer");
38
- }
39
- });
40
61
  const setTimeoutFn = options.setTimeoutFn ?? ((cb, ms) => globalThis.setTimeout(cb, ms));
41
62
  const clearTimeoutFn = options.clearTimeoutFn ?? ((handle) => {
42
63
  globalThis.clearTimeout(handle);
@@ -46,6 +67,8 @@ function createDirectConnectFlow(transports, options = {}) {
46
67
  const listeners = /* @__PURE__ */ new Set();
47
68
  let pollHandle = null;
48
69
  let running = false;
70
+ let activeRunId = 0;
71
+ let openedWindow = null;
49
72
  function emit() {
50
73
  for (const listener of listeners) listener();
51
74
  }
@@ -59,6 +82,12 @@ function createDirectConnectFlow(transports, options = {}) {
59
82
  pollHandle = null;
60
83
  }
61
84
  }
85
+ function closeUnnavigatedWindow() {
86
+ if (openedWindow) {
87
+ openedWindow.close();
88
+ openedWindow = null;
89
+ }
90
+ }
62
91
  function isRunningPhase() {
63
92
  return state.type === "creating" || state.type === "awaiting_approval" || state.type === "reading";
64
93
  }
@@ -126,24 +155,45 @@ function createDirectConnectFlow(transports, options = {}) {
126
155
  async start() {
127
156
  if (running || isRunningPhase()) return;
128
157
  running = true;
158
+ const runId = ++activeRunId;
159
+ const openApprovalWindow = options.openApprovalWindow ?? defaultOpenApprovalWindow;
160
+ const approvalWindow = openApprovalWindow();
161
+ openedWindow = approvalWindow;
129
162
  setState({ type: "creating" });
130
163
  let request;
131
164
  try {
132
165
  request = await transports.createRequest();
133
166
  } catch (err) {
167
+ if (runId !== activeRunId) {
168
+ approvalWindow?.close();
169
+ return;
170
+ }
134
171
  running = false;
172
+ closeUnnavigatedWindow();
135
173
  setState({ type: "error", error: toError(err) });
136
174
  return;
137
175
  }
138
- if (!running) return;
139
- setState({ type: "awaiting_approval", request });
140
- openWindow(request.approvalUrl);
176
+ if (runId !== activeRunId) {
177
+ approvalWindow?.close();
178
+ return;
179
+ }
180
+ if (approvalWindow) {
181
+ approvalWindow.navigate(request.approvalUrl);
182
+ openedWindow = null;
183
+ }
184
+ setState({
185
+ type: "awaiting_approval",
186
+ request,
187
+ popupBlocked: approvalWindow === null
188
+ });
141
189
  const deadline = now() + timeoutMs;
142
190
  scheduleNextPoll(request, deadline);
143
191
  },
144
192
  reset() {
145
193
  running = false;
194
+ activeRunId++;
146
195
  clearPoll();
196
+ closeUnnavigatedWindow();
147
197
  setState({ type: "idle" });
148
198
  }
149
199
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /** Overall timeout in ms before giving up. Defaults to 300000 (5 min). */\n timeoutMs?: number;\n /** Opens the approval URL. Defaults to `window.open`. Injectable for tests. */\n openWindow?: (url: string) => void;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | { type: \"awaiting_approval\"; request: AccessRequest }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const openWindow =\n options.openWindow ??\n ((url: string) => {\n if (typeof window !== \"undefined\" && window.open) {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n }\n });\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n await readAndFinish(request);\n return;\n }\n if (status.status === \"denied\" || status.status === \"expired\") {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n return {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n setState({ type: \"awaiting_approval\", request });\n openWindow(request.approvalUrl);\n\n const deadline = now() + timeoutMs;\n scheduleNextPoll(request, deadline);\n },\n\n reset(): void {\n running = false;\n clearPoll();\n setState({ type: \"idle\" });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA8EA,MAAM,2BAA2B;AACjC,MAAM,qBAAqB;AAE3B,SAAS,QAAQ,OAAuB;AACtC,S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,EAAE,MAAM,WAAW,CAAC;AAE7B,UAAI;AACJ,UAAI;AACF,kBAAU,MAAM,WAAW,cAAc;AAAA,MAC3C,SAAS,KAAK;AACZ,kBAAU;AACV,iBAAS,EAAE,MAAM,SAAS,OAAO,QAAQ,GAAG,EAAE,CAAC;AAC/C;AAAA,MACF;AACA,UAAI,CAAC,QAAS;AAEd,eAAS,EAAE,MAAM,qBAAqB,QAAQ,CAAC;AAC/C,iBAAW,QAAQ,WAAW;AAE9B,YAAM,WAAW,IAAI,IAAI;AACzB,uBAAiB,SAAS,QAAQ;AAAA,IACpC;AAAA,IAEA,QAAc;AACZ,gBAAU;AACV,gBAAU;AACV,eAAS,EAAE,MAAM,OAAO,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/**\n * A handle to a tab opened synchronously under the user's click gesture.\n *\n * @remarks\n * The flow opens this tab *before* it knows the approval URL (popup blockers\n * only allow `window.open()` during the click's transient activation), then\n * navigates it once `createRequest` resolves.\n */\nexport interface ConnectWindow {\n /** Point the already-open tab at the approval URL. */\n navigate(url: string): void;\n /** Close the tab (used to clean up an un-navigated tab on failure/reset). */\n close(): void;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /** Overall timeout in ms before giving up. Defaults to 300000 (5 min). */\n timeoutMs?: number;\n /**\n * Synchronously open a blank tab under the click's transient activation and\n * return a handle to navigate later, or `null` if the browser blocked it.\n * Defaults to `window.open(\"\", \"_blank\")` (with `opener` severed). Injectable\n * for tests.\n *\n * @remarks\n * Renamed from the pre-3.8 `openWindow?: (url) => void`. The old contract was\n * the BUI-622 bug itself (it was called with the URL *after* an `await`, so\n * the popup blocker suppressed it); it cannot be preserved while fixing the\n * bug. Custom openers must now open synchronously and return a navigable\n * handle.\n */\n openApprovalWindow?: () => ConnectWindow | null;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | {\n type: \"awaiting_approval\";\n request: AccessRequest;\n /**\n * `true` when the browser blocked the approval popup. The UI should\n * render `request.approvalUrl` as a visible \"Open approval\" link so the\n * user can open it manually instead of the flow silently hanging.\n */\n popupBlocked: boolean;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\n/**\n * Default {@link DirectConnectOptions.openApprovalWindow}: open a blank tab\n * synchronously (inside the click gesture) and return a handle to navigate\n * once the approval URL is known. Returns `null` when blocked or non-DOM.\n */\nfunction defaultOpenApprovalWindow(): ConnectWindow | null {\n if (typeof window === \"undefined\" || !window.open) return null;\n // We can't pass the \"noopener\"/\"noreferrer\" feature string here: it makes\n // window.open() return null, which would throw away the handle we need to\n // navigate later. So we open plain and re-create both protections by hand.\n const opened = window.open(\"\", \"_blank\");\n if (!opened) return null;\n // Sever the opener link while the tab is still about:blank, so the approval\n // page can't reach back into the app (reverse tab-nabbing).\n try {\n opened.opener = null;\n } catch {\n // Some environments make `opener` read-only; best-effort only.\n }\n return {\n navigate(url: string) {\n // Restore the no-referrer protection the old \"noreferrer\" feature gave:\n // tag the blank document so the upcoming navigation sends no Referer to\n // the approval page (best-effort; the blank doc is same-origin here).\n try {\n const meta = opened.document.createElement(\"meta\");\n meta.name = \"referrer\";\n meta.content = \"no-referrer\";\n (opened.document.head ?? opened.document.documentElement)?.appendChild(\n meta,\n );\n } catch {\n // Cross-origin/unavailable document: skip, navigation still proceeds.\n }\n opened.location.href = url;\n },\n close() {\n opened.close();\n },\n };\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n // Resolved lazily at start() (see below) so a custom opener swapped in after\n // construction is still honoured — matching the latest-callback pattern the\n // React hook uses for its transports.\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n // Monotonic id for the current start() invocation. reset() (and an\n // immediately following start()) bumps it, so a previous run whose async\n // createRequest is still in flight can detect it has been superseded and\n // avoid touching shared state / the newer run's tab.\n let activeRunId = 0;\n // Holds the tab we opened only while it is still blank (un-navigated). Once\n // navigated to the approval URL we drop the reference so reset/cleanup never\n // closes the live approval tab the user is interacting with.\n let openedWindow: ConnectWindow | null = null;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n /** Close the opened tab if it is still blank (never navigated). */\n function closeUnnavigatedWindow(): void {\n if (openedWindow) {\n openedWindow.close();\n openedWindow = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n await readAndFinish(request);\n return;\n }\n if (status.status === \"denied\" || status.status === \"expired\") {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n return {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n const runId = ++activeRunId;\n\n // Open the approval tab *synchronously*, while the click's transient\n // activation is still live. The approval URL isn't known yet (it comes\n // from createRequest below), so open a blank tab now and navigate it\n // once the URL arrives. Opening *after* the await — as this flow used to\n // — runs outside the gesture, so the browser suppresses it as an\n // unsolicited popup and the flow stalls forever (BUI-622).\n // Read the opener option *now* (not at construction) so a custom opener\n // swapped in after the flow was created is still used.\n const openApprovalWindow =\n options.openApprovalWindow ?? defaultOpenApprovalWindow;\n const approvalWindow = openApprovalWindow();\n openedWindow = approvalWindow;\n\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n // If we were superseded (reset, possibly + a newer start()) while this\n // request was in flight, only clean up our own tab — never the shared\n // state or the newer run's window.\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n running = false;\n closeUnnavigatedWindow();\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n\n if (approvalWindow) {\n approvalWindow.navigate(request.approvalUrl);\n // Hand the tab off to the user; we no longer own/close it.\n openedWindow = null;\n }\n // `approvalWindow === null` means the popup was blocked. Surface it so\n // the UI renders request.approvalUrl as a visible \"Open approval\" link\n // instead of hanging. We poll either way, so a manual open still\n // resolves the flow, and the timeout still bounds the wait.\n setState({\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n\n const deadline = now() + timeoutMs;\n scheduleNextPoll(request, deadline);\n },\n\n reset(): void {\n running = false;\n // Invalidate any in-flight start() so a late createRequest can't clobber\n // a subsequent run.\n activeRunId++;\n clearPoll();\n closeUnnavigatedWindow();\n setState({ type: \"idle\" });\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAkHA,MAAM,2BAA2B;AACjC,MAAM,qBAAqB;AAE3B,SAAS,QAAQ,OAAuB;AACtC,SAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;AAEA,SAAS,kBAAkB,QAA2C;AACpE,SAAO,WAAW,cAAc,WAAW;AAC7C;AAOA,SAAS,4BAAkD;AACzD,MAAI,OAAO,WAAW,eAAe,CAAC,OAAO,KAAM,QAAO;AAI1D,QAAM,SAAS,OAAO,KAAK,IAAI,QAAQ;AACvC,MAAI,CAAC,OAAQ,QAAO;AAGpB,MAAI;AACF,WAAO,SAAS;AAAA,EAClB,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,SAAS,KAAa;AAIpB,UAAI;AACF,cAAM,OAAO,OAAO,SAAS,cAAc,MAAM;AACjD,aAAK,OAAO;AACZ,aAAK,UAAU;AACf,SAAC,OAAO,SAAS,QAAQ,OAAO,SAAS,kBAAkB;AAAA,UACzD;AAAA,QACF;AAAA,MACF,QAAQ;AAAA,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Q,sBAAsB;AAChC,YAAM,iBAAiB,mBAAmB;AAC1C,qBAAe;AAEf,eAAS,EAAE,MAAM,WAAW,CAAC;AAE7B,UAAI;AACJ,UAAI;AACF,kBAAU,MAAM,WAAW,cAAc;AAAA,MAC3C,SAAS,KAAK;AAIZ,YAAI,UAAU,aAAa;AACzB,0BAAgB,MAAM;AACtB;AAAA,QACF;AACA,kBAAU;AACV,+BAAuB;AACvB,iBAAS,EAAE,MAAM,SAAS,OAAO,QAAQ,GAAG,EAAE,CAAC;AAC/C;AAAA,MACF;AACA,UAAI,UAAU,aAAa;AACzB,wBAAgB,MAAM;AACtB;AAAA,MACF;AAEA,UAAI,gBAAgB;AAClB,uBAAe,SAAS,QAAQ,WAAW;AAE3C,uBAAe;AAAA,MACjB;AAKA,eAAS;AAAA,QACP,MAAM;AAAA,QACN;AAAA,QACA,cAAc,mBAAmB;AAAA,MACnC,CAAC;AAED,YAAM,WAAW,IAAI,IAAI;AACzB,uBAAiB,SAAS,QAAQ;AAAA,IACpC;AAAA,IAEA,QAAc;AACZ,gBAAU;AAGV;AACA,gBAAU;AACV,6BAAuB;AACvB,eAAS,EAAE,MAAM,OAAO,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;","names":[]}
@@ -25,14 +25,40 @@ export interface DirectConnectTransports<T = unknown> {
25
25
  /** Ask the backend to read the approved data. */
26
26
  readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;
27
27
  }
28
+ /**
29
+ * A handle to a tab opened synchronously under the user's click gesture.
30
+ *
31
+ * @remarks
32
+ * The flow opens this tab *before* it knows the approval URL (popup blockers
33
+ * only allow `window.open()` during the click's transient activation), then
34
+ * navigates it once `createRequest` resolves.
35
+ */
36
+ export interface ConnectWindow {
37
+ /** Point the already-open tab at the approval URL. */
38
+ navigate(url: string): void;
39
+ /** Close the tab (used to clean up an un-navigated tab on failure/reset). */
40
+ close(): void;
41
+ }
28
42
  /** Tunables for the connect flow. */
29
43
  export interface DirectConnectOptions {
30
44
  /** Status poll interval in ms. Defaults to 1500. */
31
45
  pollIntervalMs?: number;
32
46
  /** Overall timeout in ms before giving up. Defaults to 300000 (5 min). */
33
47
  timeoutMs?: number;
34
- /** Opens the approval URL. Defaults to `window.open`. Injectable for tests. */
35
- openWindow?: (url: string) => void;
48
+ /**
49
+ * Synchronously open a blank tab under the click's transient activation and
50
+ * return a handle to navigate later, or `null` if the browser blocked it.
51
+ * Defaults to `window.open("", "_blank")` (with `opener` severed). Injectable
52
+ * for tests.
53
+ *
54
+ * @remarks
55
+ * Renamed from the pre-3.8 `openWindow?: (url) => void`. The old contract was
56
+ * the BUI-622 bug itself (it was called with the URL *after* an `await`, so
57
+ * the popup blocker suppressed it); it cannot be preserved while fixing the
58
+ * bug. Custom openers must now open synchronously and return a navigable
59
+ * handle.
60
+ */
61
+ openApprovalWindow?: () => ConnectWindow | null;
36
62
  /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */
37
63
  setTimeoutFn?: (cb: () => void, ms: number) => unknown;
38
64
  /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */
@@ -54,6 +80,12 @@ export type DirectConnectState<T = unknown> = {
54
80
  } | {
55
81
  type: "awaiting_approval";
56
82
  request: AccessRequest;
83
+ /**
84
+ * `true` when the browser blocked the approval popup. The UI should
85
+ * render `request.approvalUrl` as a visible "Open approval" link so the
86
+ * user can open it manually instead of the flow silently hanging.
87
+ */
88
+ popupBlocked: boolean;
57
89
  } | {
58
90
  type: "reading";
59
91
  request: AccessRequest;
@@ -6,14 +6,35 @@ function toError(value) {
6
6
  function isReadReadyStatus(status) {
7
7
  return status === "approved" || status === "ready_for_read";
8
8
  }
9
+ function defaultOpenApprovalWindow() {
10
+ if (typeof window === "undefined" || !window.open) return null;
11
+ const opened = window.open("", "_blank");
12
+ if (!opened) return null;
13
+ try {
14
+ opened.opener = null;
15
+ } catch {
16
+ }
17
+ return {
18
+ navigate(url) {
19
+ try {
20
+ const meta = opened.document.createElement("meta");
21
+ meta.name = "referrer";
22
+ meta.content = "no-referrer";
23
+ (opened.document.head ?? opened.document.documentElement)?.appendChild(
24
+ meta
25
+ );
26
+ } catch {
27
+ }
28
+ opened.location.href = url;
29
+ },
30
+ close() {
31
+ opened.close();
32
+ }
33
+ };
34
+ }
9
35
  function createDirectConnectFlow(transports, options = {}) {
10
36
  const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
11
37
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
12
- const openWindow = options.openWindow ?? ((url) => {
13
- if (typeof window !== "undefined" && window.open) {
14
- window.open(url, "_blank", "noopener,noreferrer");
15
- }
16
- });
17
38
  const setTimeoutFn = options.setTimeoutFn ?? ((cb, ms) => globalThis.setTimeout(cb, ms));
18
39
  const clearTimeoutFn = options.clearTimeoutFn ?? ((handle) => {
19
40
  globalThis.clearTimeout(handle);
@@ -23,6 +44,8 @@ function createDirectConnectFlow(transports, options = {}) {
23
44
  const listeners = /* @__PURE__ */ new Set();
24
45
  let pollHandle = null;
25
46
  let running = false;
47
+ let activeRunId = 0;
48
+ let openedWindow = null;
26
49
  function emit() {
27
50
  for (const listener of listeners) listener();
28
51
  }
@@ -36,6 +59,12 @@ function createDirectConnectFlow(transports, options = {}) {
36
59
  pollHandle = null;
37
60
  }
38
61
  }
62
+ function closeUnnavigatedWindow() {
63
+ if (openedWindow) {
64
+ openedWindow.close();
65
+ openedWindow = null;
66
+ }
67
+ }
39
68
  function isRunningPhase() {
40
69
  return state.type === "creating" || state.type === "awaiting_approval" || state.type === "reading";
41
70
  }
@@ -103,24 +132,45 @@ function createDirectConnectFlow(transports, options = {}) {
103
132
  async start() {
104
133
  if (running || isRunningPhase()) return;
105
134
  running = true;
135
+ const runId = ++activeRunId;
136
+ const openApprovalWindow = options.openApprovalWindow ?? defaultOpenApprovalWindow;
137
+ const approvalWindow = openApprovalWindow();
138
+ openedWindow = approvalWindow;
106
139
  setState({ type: "creating" });
107
140
  let request;
108
141
  try {
109
142
  request = await transports.createRequest();
110
143
  } catch (err) {
144
+ if (runId !== activeRunId) {
145
+ approvalWindow?.close();
146
+ return;
147
+ }
111
148
  running = false;
149
+ closeUnnavigatedWindow();
112
150
  setState({ type: "error", error: toError(err) });
113
151
  return;
114
152
  }
115
- if (!running) return;
116
- setState({ type: "awaiting_approval", request });
117
- openWindow(request.approvalUrl);
153
+ if (runId !== activeRunId) {
154
+ approvalWindow?.close();
155
+ return;
156
+ }
157
+ if (approvalWindow) {
158
+ approvalWindow.navigate(request.approvalUrl);
159
+ openedWindow = null;
160
+ }
161
+ setState({
162
+ type: "awaiting_approval",
163
+ request,
164
+ popupBlocked: approvalWindow === null
165
+ });
118
166
  const deadline = now() + timeoutMs;
119
167
  scheduleNextPoll(request, deadline);
120
168
  },
121
169
  reset() {
122
170
  running = false;
171
+ activeRunId++;
123
172
  clearPoll();
173
+ closeUnnavigatedWindow();
124
174
  setState({ type: "idle" });
125
175
  }
126
176
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /** Overall timeout in ms before giving up. Defaults to 300000 (5 min). */\n timeoutMs?: number;\n /** Opens the approval URL. Defaults to `window.open`. Injectable for tests. */\n openWindow?: (url: string) => void;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | { type: \"awaiting_approval\"; request: AccessRequest }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const openWindow =\n options.openWindow ??\n ((url: string) => {\n if (typeof window !== \"undefined\" && window.open) {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n }\n });\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n await readAndFinish(request);\n return;\n }\n if (status.status === \"denied\" || status.status === \"expired\") {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n return {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n setState({ type: \"awaiting_approval\", request });\n openWindow(request.approvalUrl);\n\n const deadline = now() + timeoutMs;\n scheduleNextPoll(request, deadline);\n },\n\n reset(): void {\n running = false;\n clearPoll();\n setState({ type: \"idle\" });\n },\n };\n}\n"],"mappings":"AA8EA,MAAM,2BAA2B;AACjC,MAAM,qBAAqB;AAE3B,SAAS,QAAQ,OAAuB;AACtC,SAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;AACjE;AAEA,SAAS,kBAAkB,QAA2C;AACpE,SAAO,WAAW,cAAc,WAAW;AAC7C;AASO,SAAS,wBACd,YACA,UAAgC,CAAC,GACX;AACtB,QAAM,iBAAiB,QAAQ,kBAAkB;AACjD,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,aACJ,QAAQ,eACP,CAAC,QAAgB;AAChB,QAAI,OAAO,WAAW,eAAe,OAAO,MAAM;AAChD,aAAO,KAAK,KAAK,UAAU,qBAAqB;AAAA,IAClD;AAAA,EACF;AACF,QAAM,eACJ,QAAQ,iBACP,CAAC,IAAgB,OAAe,WAAW,WAAW,IAAI,EAAE;A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AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/direct/connect-flow.ts"],"sourcesContent":["/**\n * Framework-agnostic connect-flow state machine for the browser two-tab helper.\n *\n * @remarks\n * This is the testable core behind {@link useDirectVanaConnect}. It is pure\n * TypeScript (no React, no DOM-only APIs beyond an injectable window opener and\n * timers) so the full flow — create request, open Vana, poll status, read data —\n * can be exercised in a Node test environment.\n *\n * The React hook is a thin `useSyncExternalStore` binding over this store.\n *\n * @category Direct\n * @module direct/connect-flow\n */\n\nimport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./types\";\n\n/**\n * Caller-supplied transports. These typically `fetch` the app's own backend\n * routes, which in turn delegate to a {@link DirectDataController}.\n */\nexport interface DirectConnectTransports<T = unknown> {\n /** Ask the backend to create an access request. */\n createRequest: () => Promise<AccessRequest>;\n /** Ask the backend for the current status of a request. */\n getStatus: (requestId: string) => Promise<AccessRequestStatus>;\n /** Ask the backend to read the approved data. */\n readResult: (requestId: string) => Promise<ApprovedDataResult<T>>;\n}\n\n/**\n * A handle to a tab opened synchronously under the user's click gesture.\n *\n * @remarks\n * The flow opens this tab *before* it knows the approval URL (popup blockers\n * only allow `window.open()` during the click's transient activation), then\n * navigates it once `createRequest` resolves.\n */\nexport interface ConnectWindow {\n /** Point the already-open tab at the approval URL. */\n navigate(url: string): void;\n /** Close the tab (used to clean up an un-navigated tab on failure/reset). */\n close(): void;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /** Overall timeout in ms before giving up. Defaults to 300000 (5 min). */\n timeoutMs?: number;\n /**\n * Synchronously open a blank tab under the click's transient activation and\n * return a handle to navigate later, or `null` if the browser blocked it.\n * Defaults to `window.open(\"\", \"_blank\")` (with `opener` severed). Injectable\n * for tests.\n *\n * @remarks\n * Renamed from the pre-3.8 `openWindow?: (url) => void`. The old contract was\n * the BUI-622 bug itself (it was called with the URL *after* an `await`, so\n * the popup blocker suppressed it); it cannot be preserved while fixing the\n * bug. Custom openers must now open synchronously and return a navigable\n * handle.\n */\n openApprovalWindow?: () => ConnectWindow | null;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /** `clearTimeout`. Injectable for tests. Defaults to `globalThis.clearTimeout`. */\n clearTimeoutFn?: (handle: unknown) => void;\n /** Clock source in ms. Injectable for tests. Defaults to `Date.now`. */\n now?: () => number;\n}\n\n/**\n * Discriminated connect-flow state.\n *\n * @remarks\n * `type` matches the builder guide: it starts at `\"idle\"` and is non-idle while\n * connecting. The intermediate phases give richer UIs something to render.\n */\nexport type DirectConnectState<T = unknown> =\n | { type: \"idle\" }\n | { type: \"creating\" }\n | {\n type: \"awaiting_approval\";\n request: AccessRequest;\n /**\n * `true` when the browser blocked the approval popup. The UI should\n * render `request.approvalUrl` as a visible \"Open approval\" link so the\n * user can open it manually instead of the flow silently hanging.\n */\n popupBlocked: boolean;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** The store returned by {@link createDirectConnectFlow}. */\nexport interface DirectConnectFlow<T = unknown> {\n /** Current state. */\n getState(): DirectConnectState<T>;\n /** Subscribe to state changes; returns an unsubscribe function. */\n subscribe(listener: () => void): () => void;\n /** Begin the flow. No-op if already running. */\n start(): Promise<void>;\n /** Reset to `idle` and stop any in-flight polling. */\n reset(): void;\n}\n\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst DEFAULT_TIMEOUT_MS = 300_000;\n\nfunction toError(value: unknown): Error {\n return value instanceof Error ? value : new Error(String(value));\n}\n\nfunction isReadReadyStatus(status: AccessRequestStatusValue): boolean {\n return status === \"approved\" || status === \"ready_for_read\";\n}\n\n/**\n * Default {@link DirectConnectOptions.openApprovalWindow}: open a blank tab\n * synchronously (inside the click gesture) and return a handle to navigate\n * once the approval URL is known. Returns `null` when blocked or non-DOM.\n */\nfunction defaultOpenApprovalWindow(): ConnectWindow | null {\n if (typeof window === \"undefined\" || !window.open) return null;\n // We can't pass the \"noopener\"/\"noreferrer\" feature string here: it makes\n // window.open() return null, which would throw away the handle we need to\n // navigate later. So we open plain and re-create both protections by hand.\n const opened = window.open(\"\", \"_blank\");\n if (!opened) return null;\n // Sever the opener link while the tab is still about:blank, so the approval\n // page can't reach back into the app (reverse tab-nabbing).\n try {\n opened.opener = null;\n } catch {\n // Some environments make `opener` read-only; best-effort only.\n }\n return {\n navigate(url: string) {\n // Restore the no-referrer protection the old \"noreferrer\" feature gave:\n // tag the blank document so the upcoming navigation sends no Referer to\n // the approval page (best-effort; the blank doc is same-origin here).\n try {\n const meta = opened.document.createElement(\"meta\");\n meta.name = \"referrer\";\n meta.content = \"no-referrer\";\n (opened.document.head ?? opened.document.documentElement)?.appendChild(\n meta,\n );\n } catch {\n // Cross-origin/unavailable document: skip, navigation still proceeds.\n }\n opened.location.href = url;\n },\n close() {\n opened.close();\n },\n };\n}\n\n/**\n * Create a connect-flow store.\n *\n * @param transports - Backend transports (`createRequest`, `getStatus`, `readResult`).\n * @param options - Polling/timeout tunables and injectable side effects.\n * @returns A {@link DirectConnectFlow} store.\n */\nexport function createDirectConnectFlow<T = unknown>(\n transports: DirectConnectTransports<T>,\n options: DirectConnectOptions = {},\n): DirectConnectFlow<T> {\n const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n // Resolved lazily at start() (see below) so a custom opener swapped in after\n // construction is still honoured — matching the latest-callback pattern the\n // React hook uses for its transports.\n const setTimeoutFn =\n options.setTimeoutFn ??\n ((cb: () => void, ms: number) => globalThis.setTimeout(cb, ms));\n const clearTimeoutFn =\n options.clearTimeoutFn ??\n ((handle: unknown) => {\n globalThis.clearTimeout(handle as never);\n });\n const now = options.now ?? (() => Date.now());\n\n let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n // Monotonic id for the current start() invocation. reset() (and an\n // immediately following start()) bumps it, so a previous run whose async\n // createRequest is still in flight can detect it has been superseded and\n // avoid touching shared state / the newer run's tab.\n let activeRunId = 0;\n // Holds the tab we opened only while it is still blank (un-navigated). Once\n // navigated to the approval URL we drop the reference so reset/cleanup never\n // closes the live approval tab the user is interacting with.\n let openedWindow: ConnectWindow | null = null;\n\n function emit(): void {\n for (const listener of listeners) listener();\n }\n\n function setState(next: DirectConnectState<T>): void {\n state = next;\n emit();\n }\n\n function clearPoll(): void {\n if (pollHandle !== null) {\n clearTimeoutFn(pollHandle);\n pollHandle = null;\n }\n }\n\n /** Close the opened tab if it is still blank (never navigated). */\n function closeUnnavigatedWindow(): void {\n if (openedWindow) {\n openedWindow.close();\n openedWindow = null;\n }\n }\n\n function isRunningPhase(): boolean {\n return (\n state.type === \"creating\" ||\n state.type === \"awaiting_approval\" ||\n state.type === \"reading\"\n );\n }\n\n async function readAndFinish(request: AccessRequest): Promise<void> {\n setState({ type: \"reading\", request });\n try {\n const result = await transports.readResult(request.requestId);\n if (!running) return;\n setState({ type: \"done\", result });\n } catch (err) {\n if (!running) return;\n setState({ type: \"error\", error: toError(err) });\n } finally {\n running = false;\n }\n }\n\n function scheduleNextPoll(request: AccessRequest, deadline: number): void {\n pollHandle = setTimeoutFn(() => {\n void poll(request, deadline);\n }, pollIntervalMs);\n }\n\n async function poll(request: AccessRequest, deadline: number): Promise<void> {\n if (!running) return;\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Timed out waiting for approval\"),\n });\n return;\n }\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (!running) return;\n running = false;\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (!running) return;\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n await readAndFinish(request);\n return;\n }\n if (status.status === \"denied\" || status.status === \"expired\") {\n running = false;\n setState({\n type: \"error\",\n error: new Error(`Access request ${status.status}`),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\n }\n\n return {\n getState() {\n return state;\n },\n\n subscribe(listener: () => void) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n\n async start(): Promise<void> {\n if (running || isRunningPhase()) return;\n running = true;\n const runId = ++activeRunId;\n\n // Open the approval tab *synchronously*, while the click's transient\n // activation is still live. The approval URL isn't known yet (it comes\n // from createRequest below), so open a blank tab now and navigate it\n // once the URL arrives. Opening *after* the await — as this flow used to\n // — runs outside the gesture, so the browser suppresses it as an\n // unsolicited popup and the flow stalls forever (BUI-622).\n // Read the opener option *now* (not at construction) so a custom opener\n // swapped in after the flow was created is still used.\n const openApprovalWindow =\n options.openApprovalWindow ?? defaultOpenApprovalWindow;\n const approvalWindow = openApprovalWindow();\n openedWindow = approvalWindow;\n\n setState({ type: \"creating\" });\n\n let request: AccessRequest;\n try {\n request = await transports.createRequest();\n } catch (err) {\n // If we were superseded (reset, possibly + a newer start()) while this\n // request was in flight, only clean up our own tab — never the shared\n // state or the newer run's window.\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n running = false;\n closeUnnavigatedWindow();\n setState({ type: \"error\", error: toError(err) });\n return;\n }\n if (runId !== activeRunId) {\n approvalWindow?.close();\n return;\n }\n\n if (approvalWindow) {\n approvalWindow.navigate(request.approvalUrl);\n // Hand the tab off to the user; we no longer own/close it.\n openedWindow = null;\n }\n // `approvalWindow === null` means the popup was blocked. Surface it so\n // the UI renders request.approvalUrl as a visible \"Open approval\" link\n // instead of hanging. We poll either way, so a manual open still\n // resolves the flow, and the timeout still bounds the wait.\n setState({\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n\n const deadline = now() + timeoutMs;\n scheduleNextPoll(request, deadline);\n },\n\n reset(): void {\n running = false;\n // Invalidate any in-flight start() so a late createRequest can't clobber\n // a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;AAAA,QACN;AAAA,QACA,cAAc,mBAAmB;AAAA,MACnC,CAAC;AAED,YAAM,WAAW,IAAI,IAAI;AACzB,uBAAiB,SAAS,QAAQ;AAAA,IACpC;AAAA,IAEA,QAAc;AACZ,gBAAU;AAGV;AACA,gBAAU;AACV,6BAAuB;AACvB,eAAS,EAAE,MAAM,OAAO,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;","names":[]}
@@ -40,8 +40,8 @@ function useDirectVanaConnect(options) {
40
40
  get timeoutMs() {
41
41
  return optionsRef.current.timeoutMs;
42
42
  },
43
- get openWindow() {
44
- return optionsRef.current.openWindow;
43
+ get openApprovalWindow() {
44
+ return optionsRef.current.openApprovalWindow;
45
45
  }
46
46
  }
47
47
  ),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/direct/use-direct-vana-connect.ts"],"sourcesContent":["/**\n * React hook for the browser side of the direct Data Portability flow.\n *\n * @remarks\n * `useDirectVanaConnect` is a thin `useSyncExternalStore` binding over the\n * framework-agnostic {@link createDirectConnectFlow} store. The browser never\n * sees the app private key and never chooses scopes — it only calls the app's\n * own backend routes via the injected transports.\n *\n * This module is browser-safe and imports nothing Node-only. `react` is a peer\n * dependency.\n *\n * @category Direct\n * @module direct/use-direct-vana-connect\n */\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport {\n createDirectConnectFlow,\n type DirectConnectOptions,\n type DirectConnectState,\n type DirectConnectTransports,\n} from \"./connect-flow\";\n\n/** Options for {@link useDirectVanaConnect}: transports plus flow tunables. */\nexport type UseDirectVanaConnectOptions<T = unknown> =\n DirectConnectTransports<T> & DirectConnectOptions;\n\n/** Return value of {@link useDirectVanaConnect}. */\nexport interface UseDirectVanaConnectResult<T = unknown> {\n /** Current flow state (`state.type` is `\"idle\"` until `start()` is called). */\n state: DirectConnectState<T>;\n /** Begin the connect flow (create request, open Vana, poll, read). */\n start: () => void;\n /** Reset back to `idle` and cancel any in-flight polling. */\n reset: () => void;\n}\n\n/**\n * Drive the two-tab connect flow from a React component.\n *\n * @param options - The `createRequest`/`getStatus`/`readResult` transports plus\n * optional polling/timeout tunables.\n * @returns `{ state, start, reset }`.\n *\n * @example\n * ```tsx\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return <button disabled={connect.state.type !== \"idle\"} onClick={connect.start}>Connect</button>;\n * ```\n */\nexport function useDirectVanaConnect<T = unknown>(\n options: UseDirectVanaConnectOptions<T>,\n): UseDirectVanaConnectResult<T> {\n // Keep the latest options in a ref so the store reads current callbacks\n // without being recreated on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const flow = useMemo(\n () =>\n createDirectConnectFlow<T>(\n {\n createRequest: () => optionsRef.current.createRequest(),\n getStatus: (id) => optionsRef.current.getStatus(id),\n readResult: (id) => optionsRef.current.readResult(id),\n },\n {\n get pollIntervalMs() {\n return optionsRef.current.pollIntervalMs;\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs;\n },\n get openWindow() {\n return optionsRef.current.openWindow;\n },\n },\n ),\n // Created once per component instance; callbacks are read via optionsRef.\n [],\n );\n\n const state = useSyncExternalStore(\n flow.subscribe,\n flow.getState,\n flow.getState,\n );\n\n const start = useCallback(() => {\n void flow.start();\n }, [flow]);\n\n const reset = useCallback(() => {\n flow.reset();\n }, [flow]);\n\n return { state, start, reset };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,mBAAmE;AACnE,0BAKO;AAiCA,SAAS,qBACd,SAC+B;AAG/B,QAAM,iBAAa,qBAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,WAAO;AAAA,IACX,UACE;AAAA,MACE;AAAA,QACE,eAAe,MAAM,WAAW,QAAQ,cAAc;AAAA,QACtD,WAAW,CAAC,OAAO,WAAW,QAAQ,UAAU,EAAE;AAAA,QAClD,YAAY,CAAC,OAAO,WAAW,QAAQ,WAAW,EAAE;AAAA,MACtD;AAAA,MACA;AAAA,QACE,IAAI,iBAAiB;AACnB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,YAAY;AACd,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,aAAa;AACf,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,MACF;AAAA,IACF;AAAA;AAAA,IAEF,CAAC;AAAA,EACH;AAEA,QAAM,YAAQ;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,EACP;AAEA,QAAM,YAAQ,0BAAY,MAAM;AAC9B,SAAK,KAAK,MAAM;AAAA,EAClB,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,YAAQ,0BAAY,MAAM;AAC9B,SAAK,MAAM;AAAA,EACb,GAAG,CAAC,IAAI,CAAC;AAET,SAAO,EAAE,OAAO,OAAO,MAAM;AAC/B;","names":[]}
1
+ {"version":3,"sources":["../../src/direct/use-direct-vana-connect.ts"],"sourcesContent":["/**\n * React hook for the browser side of the direct Data Portability flow.\n *\n * @remarks\n * `useDirectVanaConnect` is a thin `useSyncExternalStore` binding over the\n * framework-agnostic {@link createDirectConnectFlow} store. The browser never\n * sees the app private key and never chooses scopes — it only calls the app's\n * own backend routes via the injected transports.\n *\n * This module is browser-safe and imports nothing Node-only. `react` is a peer\n * dependency.\n *\n * @category Direct\n * @module direct/use-direct-vana-connect\n */\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport {\n createDirectConnectFlow,\n type DirectConnectOptions,\n type DirectConnectState,\n type DirectConnectTransports,\n} from \"./connect-flow\";\n\n/** Options for {@link useDirectVanaConnect}: transports plus flow tunables. */\nexport type UseDirectVanaConnectOptions<T = unknown> =\n DirectConnectTransports<T> & DirectConnectOptions;\n\n/** Return value of {@link useDirectVanaConnect}. */\nexport interface UseDirectVanaConnectResult<T = unknown> {\n /** Current flow state (`state.type` is `\"idle\"` until `start()` is called). */\n state: DirectConnectState<T>;\n /** Begin the connect flow (create request, open Vana, poll, read). */\n start: () => void;\n /** Reset back to `idle` and cancel any in-flight polling. */\n reset: () => void;\n}\n\n/**\n * Drive the two-tab connect flow from a React component.\n *\n * @param options - The `createRequest`/`getStatus`/`readResult` transports plus\n * optional polling/timeout tunables.\n * @returns `{ state, start, reset }`.\n *\n * @example\n * ```tsx\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return <button disabled={connect.state.type !== \"idle\"} onClick={connect.start}>Connect</button>;\n * ```\n */\nexport function useDirectVanaConnect<T = unknown>(\n options: UseDirectVanaConnectOptions<T>,\n): UseDirectVanaConnectResult<T> {\n // Keep the latest options in a ref so the store reads current callbacks\n // without being recreated on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const flow = useMemo(\n () =>\n createDirectConnectFlow<T>(\n {\n createRequest: () => optionsRef.current.createRequest(),\n getStatus: (id) => optionsRef.current.getStatus(id),\n readResult: (id) => optionsRef.current.readResult(id),\n },\n {\n get pollIntervalMs() {\n return optionsRef.current.pollIntervalMs;\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs;\n },\n get openApprovalWindow() {\n return optionsRef.current.openApprovalWindow;\n },\n },\n ),\n // Created once per component instance; callbacks are read via optionsRef.\n [],\n );\n\n const state = useSyncExternalStore(\n flow.subscribe,\n flow.getState,\n flow.getState,\n );\n\n const start = useCallback(() => {\n void flow.start();\n }, [flow]);\n\n const reset = useCallback(() => {\n flow.reset();\n }, [flow]);\n\n return { state, start, reset };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,mBAAmE;AACnE,0BAKO;AAiCA,SAAS,qBACd,SAC+B;AAG/B,QAAM,iBAAa,qBAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,WAAO;AAAA,IACX,UACE;AAAA,MACE;AAAA,QACE,eAAe,MAAM,WAAW,QAAQ,cAAc;AAAA,QACtD,WAAW,CAAC,OAAO,WAAW,QAAQ,UAAU,EAAE;AAAA,QAClD,YAAY,CAAC,OAAO,WAAW,QAAQ,WAAW,EAAE;AAAA,MACtD;AAAA,MACA;AAAA,QACE,IAAI,iBAAiB;AACnB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,YAAY;AACd,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,qBAAqB;AACvB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,MACF;AAAA,IACF;AAAA;AAAA,IAEF,CAAC;AAAA,EACH;AAEA,QAAM,YAAQ;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,EACP;AAEA,QAAM,YAAQ,0BAAY,MAAM;AAC9B,SAAK,KAAK,MAAM;AAAA,EAClB,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,YAAQ,0BAAY,MAAM;AAC9B,SAAK,MAAM;AAAA,EACb,GAAG,CAAC,IAAI,CAAC;AAET,SAAO,EAAE,OAAO,OAAO,MAAM;AAC/B;","names":[]}
@@ -19,8 +19,8 @@ function useDirectVanaConnect(options) {
19
19
  get timeoutMs() {
20
20
  return optionsRef.current.timeoutMs;
21
21
  },
22
- get openWindow() {
23
- return optionsRef.current.openWindow;
22
+ get openApprovalWindow() {
23
+ return optionsRef.current.openApprovalWindow;
24
24
  }
25
25
  }
26
26
  ),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/direct/use-direct-vana-connect.ts"],"sourcesContent":["/**\n * React hook for the browser side of the direct Data Portability flow.\n *\n * @remarks\n * `useDirectVanaConnect` is a thin `useSyncExternalStore` binding over the\n * framework-agnostic {@link createDirectConnectFlow} store. The browser never\n * sees the app private key and never chooses scopes — it only calls the app's\n * own backend routes via the injected transports.\n *\n * This module is browser-safe and imports nothing Node-only. `react` is a peer\n * dependency.\n *\n * @category Direct\n * @module direct/use-direct-vana-connect\n */\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport {\n createDirectConnectFlow,\n type DirectConnectOptions,\n type DirectConnectState,\n type DirectConnectTransports,\n} from \"./connect-flow\";\n\n/** Options for {@link useDirectVanaConnect}: transports plus flow tunables. */\nexport type UseDirectVanaConnectOptions<T = unknown> =\n DirectConnectTransports<T> & DirectConnectOptions;\n\n/** Return value of {@link useDirectVanaConnect}. */\nexport interface UseDirectVanaConnectResult<T = unknown> {\n /** Current flow state (`state.type` is `\"idle\"` until `start()` is called). */\n state: DirectConnectState<T>;\n /** Begin the connect flow (create request, open Vana, poll, read). */\n start: () => void;\n /** Reset back to `idle` and cancel any in-flight polling. */\n reset: () => void;\n}\n\n/**\n * Drive the two-tab connect flow from a React component.\n *\n * @param options - The `createRequest`/`getStatus`/`readResult` transports plus\n * optional polling/timeout tunables.\n * @returns `{ state, start, reset }`.\n *\n * @example\n * ```tsx\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return <button disabled={connect.state.type !== \"idle\"} onClick={connect.start}>Connect</button>;\n * ```\n */\nexport function useDirectVanaConnect<T = unknown>(\n options: UseDirectVanaConnectOptions<T>,\n): UseDirectVanaConnectResult<T> {\n // Keep the latest options in a ref so the store reads current callbacks\n // without being recreated on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const flow = useMemo(\n () =>\n createDirectConnectFlow<T>(\n {\n createRequest: () => optionsRef.current.createRequest(),\n getStatus: (id) => optionsRef.current.getStatus(id),\n readResult: (id) => optionsRef.current.readResult(id),\n },\n {\n get pollIntervalMs() {\n return optionsRef.current.pollIntervalMs;\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs;\n },\n get openWindow() {\n return optionsRef.current.openWindow;\n },\n },\n ),\n // Created once per component instance; callbacks are read via optionsRef.\n [],\n );\n\n const state = useSyncExternalStore(\n flow.subscribe,\n flow.getState,\n flow.getState,\n );\n\n const start = useCallback(() => {\n void flow.start();\n }, [flow]);\n\n const reset = useCallback(() => {\n flow.reset();\n }, [flow]);\n\n return { state, start, reset };\n}\n"],"mappings":"AAgBA,SAAS,aAAa,SAAS,QAAQ,4BAA4B;AACnE;AAAA,EACE;AAAA,OAIK;AAiCA,SAAS,qBACd,SAC+B;AAG/B,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,OAAO;AAAA,IACX,MACE;AAAA,MACE;AAAA,QACE,eAAe,MAAM,WAAW,QAAQ,cAAc;AAAA,QACtD,WAAW,CAAC,OAAO,WAAW,QAAQ,UAAU,EAAE;AAAA,QAClD,YAAY,CAAC,OAAO,WAAW,QAAQ,WAAW,EAAE;AAAA,MACtD;AAAA,MACA;AAAA,QACE,IAAI,iBAAiB;AACnB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,YAAY;AACd,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,aAAa;AACf,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,MACF;AAAA,IACF;AAAA;AAAA,IAEF,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,EACP;AAEA,QAAM,QAAQ,YAAY,MAAM;AAC9B,SAAK,KAAK,MAAM;AAAA,EAClB,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,QAAQ,YAAY,MAAM;AAC9B,SAAK,MAAM;AAAA,EACb,GAAG,CAAC,IAAI,CAAC;AAET,SAAO,EAAE,OAAO,OAAO,MAAM;AAC/B;","names":[]}
1
+ {"version":3,"sources":["../../src/direct/use-direct-vana-connect.ts"],"sourcesContent":["/**\n * React hook for the browser side of the direct Data Portability flow.\n *\n * @remarks\n * `useDirectVanaConnect` is a thin `useSyncExternalStore` binding over the\n * framework-agnostic {@link createDirectConnectFlow} store. The browser never\n * sees the app private key and never chooses scopes — it only calls the app's\n * own backend routes via the injected transports.\n *\n * This module is browser-safe and imports nothing Node-only. `react` is a peer\n * dependency.\n *\n * @category Direct\n * @module direct/use-direct-vana-connect\n */\n\nimport { useCallback, useMemo, useRef, useSyncExternalStore } from \"react\";\nimport {\n createDirectConnectFlow,\n type DirectConnectOptions,\n type DirectConnectState,\n type DirectConnectTransports,\n} from \"./connect-flow\";\n\n/** Options for {@link useDirectVanaConnect}: transports plus flow tunables. */\nexport type UseDirectVanaConnectOptions<T = unknown> =\n DirectConnectTransports<T> & DirectConnectOptions;\n\n/** Return value of {@link useDirectVanaConnect}. */\nexport interface UseDirectVanaConnectResult<T = unknown> {\n /** Current flow state (`state.type` is `\"idle\"` until `start()` is called). */\n state: DirectConnectState<T>;\n /** Begin the connect flow (create request, open Vana, poll, read). */\n start: () => void;\n /** Reset back to `idle` and cancel any in-flight polling. */\n reset: () => void;\n}\n\n/**\n * Drive the two-tab connect flow from a React component.\n *\n * @param options - The `createRequest`/`getStatus`/`readResult` transports plus\n * optional polling/timeout tunables.\n * @returns `{ state, start, reset }`.\n *\n * @example\n * ```tsx\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return <button disabled={connect.state.type !== \"idle\"} onClick={connect.start}>Connect</button>;\n * ```\n */\nexport function useDirectVanaConnect<T = unknown>(\n options: UseDirectVanaConnectOptions<T>,\n): UseDirectVanaConnectResult<T> {\n // Keep the latest options in a ref so the store reads current callbacks\n // without being recreated on every render.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const flow = useMemo(\n () =>\n createDirectConnectFlow<T>(\n {\n createRequest: () => optionsRef.current.createRequest(),\n getStatus: (id) => optionsRef.current.getStatus(id),\n readResult: (id) => optionsRef.current.readResult(id),\n },\n {\n get pollIntervalMs() {\n return optionsRef.current.pollIntervalMs;\n },\n get timeoutMs() {\n return optionsRef.current.timeoutMs;\n },\n get openApprovalWindow() {\n return optionsRef.current.openApprovalWindow;\n },\n },\n ),\n // Created once per component instance; callbacks are read via optionsRef.\n [],\n );\n\n const state = useSyncExternalStore(\n flow.subscribe,\n flow.getState,\n flow.getState,\n );\n\n const start = useCallback(() => {\n void flow.start();\n }, [flow]);\n\n const reset = useCallback(() => {\n flow.reset();\n }, [flow]);\n\n return { state, start, reset };\n}\n"],"mappings":"AAgBA,SAAS,aAAa,SAAS,QAAQ,4BAA4B;AACnE;AAAA,EACE;AAAA,OAIK;AAiCA,SAAS,qBACd,SAC+B;AAG/B,QAAM,aAAa,OAAO,OAAO;AACjC,aAAW,UAAU;AAErB,QAAM,OAAO;AAAA,IACX,MACE;AAAA,MACE;AAAA,QACE,eAAe,MAAM,WAAW,QAAQ,cAAc;AAAA,QACtD,WAAW,CAAC,OAAO,WAAW,QAAQ,UAAU,EAAE;AAAA,QAClD,YAAY,CAAC,OAAO,WAAW,QAAQ,WAAW,EAAE;AAAA,MACtD;AAAA,MACA;AAAA,QACE,IAAI,iBAAiB;AACnB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,YAAY;AACd,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,QACA,IAAI,qBAAqB;AACvB,iBAAO,WAAW,QAAQ;AAAA,QAC5B;AAAA,MACF;AAAA,IACF;AAAA;AAAA,IAEF,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,EACP;AAEA,QAAM,QAAQ,YAAY,MAAM;AAC9B,SAAK,KAAK,MAAM;AAAA,EAClB,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,QAAQ,YAAY,MAAM;AAC9B,SAAK,MAAM;AAAA,EACb,GAAG,CAAC,IAAI,CAAC;AAET,SAAO,EAAE,OAAO,OAAO,MAAM;AAC/B;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react.ts"],"sourcesContent":["/**\n * React entry point for the Vana SDK direct Data Portability flow.\n *\n * @remarks\n * Exposes {@link useDirectVanaConnect} (and the underlying framework-agnostic\n * connect-flow store) for browser apps. This entry point is browser-safe and\n * imports nothing Node-only. `react` is a peer dependency.\n *\n * @example\n * ```tsx\n * \"use client\";\n * import { useDirectVanaConnect } from \"@opendatalabs/vana-sdk/react\";\n *\n * export function ConnectNotesButton() {\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return (\n * <button disabled={connect.state.type !== \"idle\"} onClick={connect.start} type=\"button\">\n * {connect.state.type === \"idle\" ? \"Connect Apple Notes\" : \"Connecting...\"}\n * </button>\n * );\n * }\n * ```\n *\n * @category Direct\n * @module react\n */\n\nexport {\n useDirectVanaConnect,\n type UseDirectVanaConnectOptions,\n type UseDirectVanaConnectResult,\n} from \"./direct/use-direct-vana-connect\";\n\n// Framework-agnostic store (usable without React).\nexport {\n createDirectConnectFlow,\n type DirectConnectFlow,\n type DirectConnectState,\n type DirectConnectOptions,\n type DirectConnectTransports,\n} from \"./direct/connect-flow\";\n\n// Shared types useful when typing the transports.\nexport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./direct/types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BA,qCAIO;AAGP,0BAMO;","names":[]}
1
+ {"version":3,"sources":["../src/react.ts"],"sourcesContent":["/**\n * React entry point for the Vana SDK direct Data Portability flow.\n *\n * @remarks\n * Exposes {@link useDirectVanaConnect} (and the underlying framework-agnostic\n * connect-flow store) for browser apps. This entry point is browser-safe and\n * imports nothing Node-only. `react` is a peer dependency.\n *\n * @example\n * ```tsx\n * \"use client\";\n * import { useDirectVanaConnect } from \"@opendatalabs/vana-sdk/react\";\n *\n * export function ConnectNotesButton() {\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * const { state, start } = connect;\n * return (\n * <div>\n * <button disabled={state.type !== \"idle\"} onClick={start} type=\"button\">\n * {state.type === \"idle\" ? \"Connect Apple Notes\" : \"Connecting...\"}\n * </button>\n * {state.type === \"awaiting_approval\" && (\n * // Fallback link: if the browser blocked the approval popup, the user\n * // can still open it manually instead of the flow silently hanging.\n * <a href={state.request.approvalUrl} target=\"_blank\" rel=\"noreferrer\">\n * {state.popupBlocked ? \"Popup blocked — open approval\" : \"Open approval\"}\n * </a>\n * )}\n * </div>\n * );\n * }\n * ```\n *\n * @category Direct\n * @module react\n */\n\nexport {\n useDirectVanaConnect,\n type UseDirectVanaConnectOptions,\n type UseDirectVanaConnectResult,\n} from \"./direct/use-direct-vana-connect\";\n\n// Framework-agnostic store (usable without React).\nexport {\n createDirectConnectFlow,\n type ConnectWindow,\n type DirectConnectFlow,\n type DirectConnectState,\n type DirectConnectOptions,\n type DirectConnectTransports,\n} from \"./direct/connect-flow\";\n\n// Shared types useful when typing the transports.\nexport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./direct/types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyCA,qCAIO;AAGP,0BAOO;","names":[]}
package/dist/react.d.ts CHANGED
@@ -17,10 +17,20 @@
17
17
  * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),
18
18
  * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),
19
19
  * });
20
+ * const { state, start } = connect;
20
21
  * return (
21
- * <button disabled={connect.state.type !== "idle"} onClick={connect.start} type="button">
22
- * {connect.state.type === "idle" ? "Connect Apple Notes" : "Connecting..."}
23
- * </button>
22
+ * <div>
23
+ * <button disabled={state.type !== "idle"} onClick={start} type="button">
24
+ * {state.type === "idle" ? "Connect Apple Notes" : "Connecting..."}
25
+ * </button>
26
+ * {state.type === "awaiting_approval" && (
27
+ * // Fallback link: if the browser blocked the approval popup, the user
28
+ * // can still open it manually instead of the flow silently hanging.
29
+ * <a href={state.request.approvalUrl} target="_blank" rel="noreferrer">
30
+ * {state.popupBlocked ? "Popup blocked — open approval" : "Open approval"}
31
+ * </a>
32
+ * )}
33
+ * </div>
24
34
  * );
25
35
  * }
26
36
  * ```
@@ -29,5 +39,5 @@
29
39
  * @module react
30
40
  */
31
41
  export { useDirectVanaConnect, type UseDirectVanaConnectOptions, type UseDirectVanaConnectResult, } from "./direct/use-direct-vana-connect";
32
- export { createDirectConnectFlow, type DirectConnectFlow, type DirectConnectState, type DirectConnectOptions, type DirectConnectTransports, } from "./direct/connect-flow";
42
+ export { createDirectConnectFlow, type ConnectWindow, type DirectConnectFlow, type DirectConnectState, type DirectConnectOptions, type DirectConnectTransports, } from "./direct/connect-flow";
33
43
  export type { AccessRequest, AccessRequestStatus, AccessRequestStatusValue, ApprovedDataResult, } from "./direct/types";
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react.ts"],"sourcesContent":["/**\n * React entry point for the Vana SDK direct Data Portability flow.\n *\n * @remarks\n * Exposes {@link useDirectVanaConnect} (and the underlying framework-agnostic\n * connect-flow store) for browser apps. This entry point is browser-safe and\n * imports nothing Node-only. `react` is a peer dependency.\n *\n * @example\n * ```tsx\n * \"use client\";\n * import { useDirectVanaConnect } from \"@opendatalabs/vana-sdk/react\";\n *\n * export function ConnectNotesButton() {\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * return (\n * <button disabled={connect.state.type !== \"idle\"} onClick={connect.start} type=\"button\">\n * {connect.state.type === \"idle\" ? \"Connect Apple Notes\" : \"Connecting...\"}\n * </button>\n * );\n * }\n * ```\n *\n * @category Direct\n * @module react\n */\n\nexport {\n useDirectVanaConnect,\n type UseDirectVanaConnectOptions,\n type UseDirectVanaConnectResult,\n} from \"./direct/use-direct-vana-connect\";\n\n// Framework-agnostic store (usable without React).\nexport {\n createDirectConnectFlow,\n type DirectConnectFlow,\n type DirectConnectState,\n type DirectConnectOptions,\n type DirectConnectTransports,\n} from \"./direct/connect-flow\";\n\n// Shared types useful when typing the transports.\nexport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./direct/types\";\n"],"mappings":"AA+BA;AAAA,EACE;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,OAKK;","names":[]}
1
+ {"version":3,"sources":["../src/react.ts"],"sourcesContent":["/**\n * React entry point for the Vana SDK direct Data Portability flow.\n *\n * @remarks\n * Exposes {@link useDirectVanaConnect} (and the underlying framework-agnostic\n * connect-flow store) for browser apps. This entry point is browser-safe and\n * imports nothing Node-only. `react` is a peer dependency.\n *\n * @example\n * ```tsx\n * \"use client\";\n * import { useDirectVanaConnect } from \"@opendatalabs/vana-sdk/react\";\n *\n * export function ConnectNotesButton() {\n * const connect = useDirectVanaConnect({\n * createRequest: () => fetch(\"/api/vana/request\", { method: \"POST\" }).then((r) => r.json()),\n * getStatus: (id) => fetch(`/api/vana/status?requestId=${id}`).then((r) => r.json()),\n * readResult: (id) => fetch(`/api/vana/data?requestId=${id}`).then((r) => r.json()),\n * });\n * const { state, start } = connect;\n * return (\n * <div>\n * <button disabled={state.type !== \"idle\"} onClick={start} type=\"button\">\n * {state.type === \"idle\" ? \"Connect Apple Notes\" : \"Connecting...\"}\n * </button>\n * {state.type === \"awaiting_approval\" && (\n * // Fallback link: if the browser blocked the approval popup, the user\n * // can still open it manually instead of the flow silently hanging.\n * <a href={state.request.approvalUrl} target=\"_blank\" rel=\"noreferrer\">\n * {state.popupBlocked ? \"Popup blocked — open approval\" : \"Open approval\"}\n * </a>\n * )}\n * </div>\n * );\n * }\n * ```\n *\n * @category Direct\n * @module react\n */\n\nexport {\n useDirectVanaConnect,\n type UseDirectVanaConnectOptions,\n type UseDirectVanaConnectResult,\n} from \"./direct/use-direct-vana-connect\";\n\n// Framework-agnostic store (usable without React).\nexport {\n createDirectConnectFlow,\n type ConnectWindow,\n type DirectConnectFlow,\n type DirectConnectState,\n type DirectConnectOptions,\n type DirectConnectTransports,\n} from \"./direct/connect-flow\";\n\n// Shared types useful when typing the transports.\nexport type {\n AccessRequest,\n AccessRequestStatus,\n AccessRequestStatusValue,\n ApprovedDataResult,\n} from \"./direct/types\";\n"],"mappings":"AAyCA;AAAA,EACE;AAAA,OAGK;AAGP;AAAA,EACE;AAAA,OAMK;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opendatalabs/vana-sdk",
3
- "version": "3.8.2",
3
+ "version": "3.8.3",
4
4
  "description": "A TypeScript library for interacting with Vana Network smart contracts.",
5
5
  "publishConfig": {
6
6
  "access": "public"