@opendatalabs/vana-sdk 4.4.0 → 4.5.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 (106) hide show
  1. package/README.md +176 -0
  2. package/dist/connect/account-origin.cjs +72 -0
  3. package/dist/connect/account-origin.cjs.map +1 -0
  4. package/dist/connect/account-origin.d.ts +92 -0
  5. package/dist/connect/account-origin.js +47 -0
  6. package/dist/connect/account-origin.js.map +1 -0
  7. package/dist/connect/account-origin.test.d.ts +1 -0
  8. package/dist/connect/chrome.cjs +284 -0
  9. package/dist/connect/chrome.cjs.map +1 -0
  10. package/dist/connect/chrome.d.ts +42 -0
  11. package/dist/connect/chrome.js +256 -0
  12. package/dist/connect/chrome.js.map +1 -0
  13. package/dist/connect/http-transports.cjs +100 -0
  14. package/dist/connect/http-transports.cjs.map +1 -0
  15. package/dist/connect/http-transports.d.ts +77 -0
  16. package/dist/connect/http-transports.js +75 -0
  17. package/dist/connect/http-transports.js.map +1 -0
  18. package/dist/connect/http-transports.test.d.ts +1 -0
  19. package/dist/connect/launcher.cjs +232 -0
  20. package/dist/connect/launcher.cjs.map +1 -0
  21. package/dist/connect/launcher.d.ts +129 -0
  22. package/dist/connect/launcher.js +220 -0
  23. package/dist/connect/launcher.js.map +1 -0
  24. package/dist/connect/launcher.test.d.ts +1 -0
  25. package/dist/connect/protocol.cjs +259 -0
  26. package/dist/connect/protocol.cjs.map +1 -0
  27. package/dist/connect/protocol.d.ts +331 -0
  28. package/dist/connect/protocol.js +215 -0
  29. package/dist/connect/protocol.js.map +1 -0
  30. package/dist/connect/protocol.test.d.ts +1 -0
  31. package/dist/connect.cjs +55 -0
  32. package/dist/connect.cjs.map +1 -0
  33. package/dist/connect.d.ts +35 -0
  34. package/dist/connect.js +34 -0
  35. package/dist/connect.js.map +1 -0
  36. package/dist/direct/connect-flow-sheet.test.d.ts +1 -0
  37. package/dist/direct/connect-flow.cjs +211 -1
  38. package/dist/direct/connect-flow.cjs.map +1 -1
  39. package/dist/direct/connect-flow.d.ts +75 -0
  40. package/dist/direct/connect-flow.js +213 -1
  41. package/dist/direct/connect-flow.js.map +1 -1
  42. package/dist/direct/connect-handler.cjs +493 -0
  43. package/dist/direct/connect-handler.cjs.map +1 -0
  44. package/dist/direct/connect-handler.d.ts +246 -0
  45. package/dist/direct/connect-handler.js +476 -0
  46. package/dist/direct/connect-handler.js.map +1 -0
  47. package/dist/direct/connect-handler.test.d.ts +1 -0
  48. package/dist/direct/controller.cjs +86 -17
  49. package/dist/direct/controller.cjs.map +1 -1
  50. package/dist/direct/controller.d.ts +101 -6
  51. package/dist/direct/controller.js +86 -16
  52. package/dist/direct/controller.js.map +1 -1
  53. package/dist/direct/endpoints.cjs +5 -2
  54. package/dist/direct/endpoints.cjs.map +1 -1
  55. package/dist/direct/endpoints.js +5 -2
  56. package/dist/direct/endpoints.js.map +1 -1
  57. package/dist/direct/request-authorization.cjs +65 -0
  58. package/dist/direct/request-authorization.cjs.map +1 -0
  59. package/dist/direct/request-authorization.d.ts +65 -0
  60. package/dist/direct/request-authorization.js +39 -0
  61. package/dist/direct/request-authorization.js.map +1 -0
  62. package/dist/direct/request-authorization.test.d.ts +1 -0
  63. package/dist/direct/types.cjs.map +1 -1
  64. package/dist/direct/types.d.ts +6 -0
  65. package/dist/direct/types.js.map +1 -1
  66. package/dist/direct/use-direct-vana-connect.cjs +18 -1
  67. package/dist/direct/use-direct-vana-connect.cjs.map +1 -1
  68. package/dist/direct/use-direct-vana-connect.js +18 -1
  69. package/dist/direct/use-direct-vana-connect.js.map +1 -1
  70. package/dist/direct/use-vana-connect.cjs +84 -0
  71. package/dist/direct/use-vana-connect.cjs.map +1 -0
  72. package/dist/direct/use-vana-connect.d.ts +59 -0
  73. package/dist/direct/use-vana-connect.js +64 -0
  74. package/dist/direct/use-vana-connect.js.map +1 -0
  75. package/dist/direct/use-vana-connect.test.d.ts +1 -0
  76. package/dist/index.browser.d.ts +1 -0
  77. package/dist/index.browser.js +104 -0
  78. package/dist/index.browser.js.map +4 -4
  79. package/dist/index.node.cjs +112 -0
  80. package/dist/index.node.cjs.map +3 -3
  81. package/dist/index.node.d.ts +1 -0
  82. package/dist/index.node.js +104 -0
  83. package/dist/index.node.js.map +4 -4
  84. package/dist/protocol/fixtures/pdpp-scope-keys.json +133 -0
  85. package/dist/protocol/pdpp-scopes.cjs +134 -0
  86. package/dist/protocol/pdpp-scopes.cjs.map +1 -0
  87. package/dist/protocol/pdpp-scopes.d.ts +123 -0
  88. package/dist/protocol/pdpp-scopes.js +103 -0
  89. package/dist/protocol/pdpp-scopes.js.map +1 -0
  90. package/dist/protocol/pdpp-scopes.test.d.ts +1 -0
  91. package/dist/protocol/scopes.cjs +17 -0
  92. package/dist/protocol/scopes.cjs.map +1 -1
  93. package/dist/protocol/scopes.d.ts +1 -0
  94. package/dist/protocol/scopes.js +18 -0
  95. package/dist/protocol/scopes.js.map +1 -1
  96. package/dist/react.cjs +10 -2
  97. package/dist/react.cjs.map +1 -1
  98. package/dist/react.d.ts +4 -1
  99. package/dist/react.js +11 -1
  100. package/dist/react.js.map +1 -1
  101. package/dist/server.cjs +61 -2
  102. package/dist/server.cjs.map +1 -1
  103. package/dist/server.d.ts +16 -4
  104. package/dist/server.js +67 -3
  105. package/dist/server.js.map +1 -1
  106. package/package.json +11 -1
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var connect_exports = {};
21
+ __export(connect_exports, {
22
+ DRAG_CLOSE_PX: () => import_chrome.DRAG_CLOSE_PX,
23
+ MAX_SHEET_RATIO: () => import_chrome.MAX_SHEET_RATIO,
24
+ RETURN_TAP_GUARD_MS: () => import_chrome.RETURN_TAP_GUARD_MS,
25
+ VanaConnectHttpError: () => import_http_transports.VanaConnectHttpError,
26
+ connect: () => import_launcher.connect,
27
+ createSheetChrome: () => import_chrome.createSheetChrome,
28
+ createVanaConnectTransports: () => import_http_transports.createVanaConnectTransports,
29
+ open: () => import_launcher.open,
30
+ openConnectSheet: () => import_launcher.openConnectSheet,
31
+ parseOriginAllowlist: () => import_account_origin.parseOriginAllowlist,
32
+ resolveVanaAccountOrigin: () => import_account_origin.resolveVanaAccountOrigin
33
+ });
34
+ module.exports = __toCommonJS(connect_exports);
35
+ var import_launcher = require("./connect/launcher");
36
+ var import_account_origin = require("./connect/account-origin");
37
+ var import_chrome = require("./connect/chrome");
38
+ var import_http_transports = require("./connect/http-transports");
39
+ __reExport(connect_exports, require("./connect/protocol"), module.exports);
40
+ // Annotate the CommonJS export names for ESM import in node:
41
+ 0 && (module.exports = {
42
+ DRAG_CLOSE_PX,
43
+ MAX_SHEET_RATIO,
44
+ RETURN_TAP_GUARD_MS,
45
+ VanaConnectHttpError,
46
+ connect,
47
+ createSheetChrome,
48
+ createVanaConnectTransports,
49
+ open,
50
+ openConnectSheet,
51
+ parseOriginAllowlist,
52
+ resolveVanaAccountOrigin,
53
+ ...require("./connect/protocol")
54
+ });
55
+ //# sourceMappingURL=connect.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/connect.ts"],"sourcesContent":["/**\n * Connect entry point: the launcher for Vana's in-page connect sheet, its\n * chrome, and browser transports for a `createVanaConnectHandler` backend.\n *\n * @remarks\n * Browser-safe and framework-free. Most apps use the sheet through\n * `useVanaConnect` (or `createDirectConnectFlow` with\n * `presentation: \"sheet\"`) from `@opendatalabs/vana-sdk/react`, which wires\n * it to the request, the status poll and the read. The message protocol\n * alone, with no other code, is `@opendatalabs/vana-sdk/connect/protocol`.\n *\n * @example\n * ```typescript\n * import { connect } from \"@opendatalabs/vana-sdk/connect\";\n *\n * const sheet = connect.open({\n * clientId: \"my-app\",\n * appName: \"My App\",\n * env: \"production\",\n * getRequest: () =>\n * fetch(\"/api/vana/request\", { method: \"POST\", body: \"{}\" })\n * .then((r) => r.json())\n * .then((body) => body.embed),\n * onEvent: (event) => console.log(event),\n * });\n * ```\n *\n * @category Connect\n * @module connect\n */\n\nexport {\n connect,\n open,\n openConnectSheet,\n type ConnectCloseReason,\n type ConnectEvent,\n type ConnectHandle,\n type ConnectOpenBaseOptions,\n type ConnectOpenOptions,\n type ConnectTarget,\n} from \"./connect/launcher\";\nexport {\n parseOriginAllowlist,\n resolveVanaAccountOrigin,\n type ResolveVanaAccountOriginInput,\n} from \"./connect/account-origin\";\nexport {\n createSheetChrome,\n DRAG_CLOSE_PX,\n MAX_SHEET_RATIO,\n RETURN_TAP_GUARD_MS,\n type CloseReason,\n type SheetChrome,\n} from \"./connect/chrome\";\nexport {\n createVanaConnectTransports,\n VanaConnectHttpError,\n type VanaConnectConfig,\n type VanaConnectRequestResponse,\n type VanaConnectTransportOptions,\n type VanaConnectTransports,\n} from \"./connect/http-transports\";\nexport * from \"./connect/protocol\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BA,sBAUO;AACP,4BAIO;AACP,oBAOO;AACP,6BAOO;AACP,4BAAc,+BA/Dd;","names":[]}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Connect entry point: the launcher for Vana's in-page connect sheet, its
3
+ * chrome, and browser transports for a `createVanaConnectHandler` backend.
4
+ *
5
+ * @remarks
6
+ * Browser-safe and framework-free. Most apps use the sheet through
7
+ * `useVanaConnect` (or `createDirectConnectFlow` with
8
+ * `presentation: "sheet"`) from `@opendatalabs/vana-sdk/react`, which wires
9
+ * it to the request, the status poll and the read. The message protocol
10
+ * alone, with no other code, is `@opendatalabs/vana-sdk/connect/protocol`.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import { connect } from "@opendatalabs/vana-sdk/connect";
15
+ *
16
+ * const sheet = connect.open({
17
+ * clientId: "my-app",
18
+ * appName: "My App",
19
+ * env: "production",
20
+ * getRequest: () =>
21
+ * fetch("/api/vana/request", { method: "POST", body: "{}" })
22
+ * .then((r) => r.json())
23
+ * .then((body) => body.embed),
24
+ * onEvent: (event) => console.log(event),
25
+ * });
26
+ * ```
27
+ *
28
+ * @category Connect
29
+ * @module connect
30
+ */
31
+ export { connect, open, openConnectSheet, type ConnectCloseReason, type ConnectEvent, type ConnectHandle, type ConnectOpenBaseOptions, type ConnectOpenOptions, type ConnectTarget, } from "./connect/launcher.js";
32
+ export { parseOriginAllowlist, resolveVanaAccountOrigin, type ResolveVanaAccountOriginInput, } from "./connect/account-origin.js";
33
+ export { createSheetChrome, DRAG_CLOSE_PX, MAX_SHEET_RATIO, RETURN_TAP_GUARD_MS, type CloseReason, type SheetChrome, } from "./connect/chrome.js";
34
+ export { createVanaConnectTransports, VanaConnectHttpError, type VanaConnectConfig, type VanaConnectRequestResponse, type VanaConnectTransportOptions, type VanaConnectTransports, } from "./connect/http-transports.js";
35
+ export * from "./connect/protocol.js";
@@ -0,0 +1,34 @@
1
+ import {
2
+ connect,
3
+ open,
4
+ openConnectSheet
5
+ } from "./connect/launcher.js";
6
+ import {
7
+ parseOriginAllowlist,
8
+ resolveVanaAccountOrigin
9
+ } from "./connect/account-origin.js";
10
+ import {
11
+ createSheetChrome,
12
+ DRAG_CLOSE_PX,
13
+ MAX_SHEET_RATIO,
14
+ RETURN_TAP_GUARD_MS
15
+ } from "./connect/chrome.js";
16
+ import {
17
+ createVanaConnectTransports,
18
+ VanaConnectHttpError
19
+ } from "./connect/http-transports.js";
20
+ export * from "./connect/protocol.js";
21
+ export {
22
+ DRAG_CLOSE_PX,
23
+ MAX_SHEET_RATIO,
24
+ RETURN_TAP_GUARD_MS,
25
+ VanaConnectHttpError,
26
+ connect,
27
+ createSheetChrome,
28
+ createVanaConnectTransports,
29
+ open,
30
+ openConnectSheet,
31
+ parseOriginAllowlist,
32
+ resolveVanaAccountOrigin
33
+ };
34
+ //# sourceMappingURL=connect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/connect.ts"],"sourcesContent":["/**\n * Connect entry point: the launcher for Vana's in-page connect sheet, its\n * chrome, and browser transports for a `createVanaConnectHandler` backend.\n *\n * @remarks\n * Browser-safe and framework-free. Most apps use the sheet through\n * `useVanaConnect` (or `createDirectConnectFlow` with\n * `presentation: \"sheet\"`) from `@opendatalabs/vana-sdk/react`, which wires\n * it to the request, the status poll and the read. The message protocol\n * alone, with no other code, is `@opendatalabs/vana-sdk/connect/protocol`.\n *\n * @example\n * ```typescript\n * import { connect } from \"@opendatalabs/vana-sdk/connect\";\n *\n * const sheet = connect.open({\n * clientId: \"my-app\",\n * appName: \"My App\",\n * env: \"production\",\n * getRequest: () =>\n * fetch(\"/api/vana/request\", { method: \"POST\", body: \"{}\" })\n * .then((r) => r.json())\n * .then((body) => body.embed),\n * onEvent: (event) => console.log(event),\n * });\n * ```\n *\n * @category Connect\n * @module connect\n */\n\nexport {\n connect,\n open,\n openConnectSheet,\n type ConnectCloseReason,\n type ConnectEvent,\n type ConnectHandle,\n type ConnectOpenBaseOptions,\n type ConnectOpenOptions,\n type ConnectTarget,\n} from \"./connect/launcher\";\nexport {\n parseOriginAllowlist,\n resolveVanaAccountOrigin,\n type ResolveVanaAccountOriginInput,\n} from \"./connect/account-origin\";\nexport {\n createSheetChrome,\n DRAG_CLOSE_PX,\n MAX_SHEET_RATIO,\n RETURN_TAP_GUARD_MS,\n type CloseReason,\n type SheetChrome,\n} from \"./connect/chrome\";\nexport {\n createVanaConnectTransports,\n VanaConnectHttpError,\n type VanaConnectConfig,\n type VanaConnectRequestResponse,\n type VanaConnectTransportOptions,\n type VanaConnectTransports,\n} from \"./connect/http-transports\";\nexport * from \"./connect/protocol\";\n"],"mappings":"AA+BA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAKK;AACP,cAAc;","names":[]}
@@ -0,0 +1 @@
1
+ export {};
@@ -22,6 +22,13 @@ __export(connect_flow_exports, {
22
22
  });
23
23
  module.exports = __toCommonJS(connect_flow_exports);
24
24
  var import_types = require("./types");
25
+ var import_launcher = require("../connect/launcher");
26
+ const SHEET_FALLBACK_CODES = [
27
+ "frame_blocked",
28
+ "origin_not_registered",
29
+ "incompatible_version"
30
+ ];
31
+ const DEFAULT_CLOSE_AFTER_DONE_MS = 1500;
25
32
  const DEFAULT_POLL_INTERVAL_MS = 1500;
26
33
  const DEFAULT_TIMEOUT_MS = 3e5;
27
34
  function toError(value) {
@@ -77,10 +84,18 @@ function createDirectConnectFlow(transports, options = {}) {
77
84
  let state = { type: "idle" };
78
85
  const listeners = /* @__PURE__ */ new Set();
79
86
  let pollHandle = null;
87
+ let pollTarget = null;
88
+ let pollInFlight = false;
89
+ let pollNudged = false;
80
90
  let running = false;
81
91
  let approvedRequest = null;
82
92
  let activeRunId = 0;
83
93
  let openedWindow = null;
94
+ let sheetHandle = null;
95
+ let sheetState = null;
96
+ let sheetUnavailable = null;
97
+ let sheetCloseAfterDoneMs = DEFAULT_CLOSE_AFTER_DONE_MS;
98
+ let sheetCloseTimer = null;
84
99
  function emit() {
85
100
  for (const listener of listeners) listener();
86
101
  }
@@ -93,6 +108,19 @@ function createDirectConnectFlow(transports, options = {}) {
93
108
  clearTimeoutFn(pollHandle);
94
109
  pollHandle = null;
95
110
  }
111
+ pollTarget = null;
112
+ pollNudged = false;
113
+ }
114
+ function nudgePoll() {
115
+ if (!running) return;
116
+ if (pollInFlight) {
117
+ pollNudged = true;
118
+ return;
119
+ }
120
+ const target = pollTarget;
121
+ if (pollHandle === null || !target) return;
122
+ clearPoll();
123
+ void poll(target.request, target.deadline);
96
124
  }
97
125
  function closeUnnavigatedWindow() {
98
126
  if (openedWindow) {
@@ -103,12 +131,114 @@ function createDirectConnectFlow(transports, options = {}) {
103
131
  function isRunningPhase() {
104
132
  return state.type === "creating" || state.type === "awaiting_approval" || state.type === "ready_to_open" || state.type === "reading";
105
133
  }
134
+ function closeSheet() {
135
+ const handle = sheetHandle;
136
+ sheetHandle = null;
137
+ handle?.close();
138
+ }
139
+ function clearSheet() {
140
+ if (sheetCloseTimer !== null) {
141
+ clearTimeoutFn(sheetCloseTimer);
142
+ sheetCloseTimer = null;
143
+ }
144
+ closeSheet();
145
+ sheetState = null;
146
+ sheetUnavailable = null;
147
+ }
148
+ function awaitingState(request) {
149
+ if (sheetUnavailable) {
150
+ return {
151
+ type: "awaiting_approval",
152
+ request,
153
+ popupBlocked: true,
154
+ sheetUnavailable
155
+ };
156
+ }
157
+ return {
158
+ type: "awaiting_approval",
159
+ request,
160
+ popupBlocked: false,
161
+ ...sheetState ? { sheet: { ...sheetState } } : {}
162
+ };
163
+ }
164
+ function updateSheet(patch) {
165
+ if (!sheetState) return;
166
+ sheetState = { ...sheetState, ...patch };
167
+ if (state.type === "awaiting_approval" && state.sheet) {
168
+ setState(awaitingState(state.request));
169
+ }
170
+ }
171
+ function failRun(error) {
172
+ running = false;
173
+ clearPoll();
174
+ setState({ type: "error", error });
175
+ }
176
+ function handleSheetEvent(event) {
177
+ switch (event.type) {
178
+ case "connected":
179
+ updateSheet({ completion: event.completion });
180
+ nudgePoll();
181
+ return;
182
+ case "progress":
183
+ updateSheet({ progress: event.phase });
184
+ return;
185
+ case "error": {
186
+ if (event.code === "request_failed") {
187
+ if (!running) return;
188
+ closeSheet();
189
+ failRun(new Error("Could not prepare the request for Vana's sheet"));
190
+ return;
191
+ }
192
+ if (SHEET_FALLBACK_CODES.includes(event.code)) {
193
+ sheetUnavailable = event.code;
194
+ sheetState = null;
195
+ closeSheet();
196
+ if (state.type === "awaiting_approval") {
197
+ setState(awaitingState(state.request));
198
+ }
199
+ return;
200
+ }
201
+ updateSheet({ error: event.code });
202
+ return;
203
+ }
204
+ case "close": {
205
+ if (!sheetHandle) return;
206
+ sheetHandle = null;
207
+ if (!running) return;
208
+ if (sheetState?.error) {
209
+ failRun(new Error(`Vana's sheet failed: ${sheetState.error}`));
210
+ return;
211
+ }
212
+ if (!sheetState?.completion) {
213
+ running = false;
214
+ activeRunId++;
215
+ clearPoll();
216
+ sheetState = null;
217
+ setState({ type: "idle" });
218
+ return;
219
+ }
220
+ updateSheet({ open: false });
221
+ return;
222
+ }
223
+ default:
224
+ return;
225
+ }
226
+ }
106
227
  async function readAndFinish(request) {
107
228
  setState({ type: "reading", request });
108
229
  try {
109
230
  const result = await transports.readResult(request.requestId);
110
231
  if (!running) return;
111
232
  setState({ type: "done", result });
233
+ if (sheetHandle) {
234
+ sheetHandle.setRequestStatus("completed");
235
+ if (sheetCloseAfterDoneMs !== null) {
236
+ sheetCloseTimer = setTimeoutFn(() => {
237
+ sheetCloseTimer = null;
238
+ closeSheet();
239
+ }, sheetCloseAfterDoneMs);
240
+ }
241
+ }
112
242
  } catch (err) {
113
243
  if (!running) return;
114
244
  setState({ type: "error", error: toError(err) });
@@ -117,9 +247,13 @@ function createDirectConnectFlow(transports, options = {}) {
117
247
  }
118
248
  }
119
249
  function scheduleNextPoll(request, deadline) {
250
+ const delay = pollNudged ? 0 : pollIntervalMs;
251
+ pollNudged = false;
252
+ pollTarget = { request, deadline };
120
253
  pollHandle = setTimeoutFn(() => {
254
+ pollHandle = null;
121
255
  void poll(request, deadline);
122
- }, pollIntervalMs);
256
+ }, delay);
123
257
  }
124
258
  function requestDeadline(request) {
125
259
  if (request.expiresAt !== void 0) {
@@ -129,6 +263,7 @@ function createDirectConnectFlow(transports, options = {}) {
129
263
  return now() + timeoutMs;
130
264
  }
131
265
  function startPolling(request, initialState) {
266
+ pollNudged = false;
132
267
  setState(initialState);
133
268
  const deadline = requestDeadline(request);
134
269
  if (now() >= deadline) {
@@ -152,6 +287,7 @@ function createDirectConnectFlow(transports, options = {}) {
152
287
  return;
153
288
  }
154
289
  let status;
290
+ pollInFlight = true;
155
291
  try {
156
292
  status = await transports.getStatus(request.requestId);
157
293
  } catch (err) {
@@ -159,6 +295,8 @@ function createDirectConnectFlow(transports, options = {}) {
159
295
  running = false;
160
296
  setState({ type: "error", error: toError(err) });
161
297
  return;
298
+ } finally {
299
+ pollInFlight = false;
162
300
  }
163
301
  if (!running) return;
164
302
  if (status.status === "pending" && state.type === "ready_to_open") {
@@ -181,6 +319,7 @@ function createDirectConnectFlow(transports, options = {}) {
181
319
  return;
182
320
  }
183
321
  if (status.status === "completed" || status.status === "denied" || status.status === "expired") {
322
+ sheetHandle?.setRequestStatus(status.status);
184
323
  running = false;
185
324
  setState({
186
325
  type: "error",
@@ -203,6 +342,11 @@ function createDirectConnectFlow(transports, options = {}) {
203
342
  running = true;
204
343
  approvedRequest = null;
205
344
  const runId = ++activeRunId;
345
+ clearSheet();
346
+ if (options.presentation === "sheet") {
347
+ await startSheet(runId);
348
+ return;
349
+ }
206
350
  const browserPlatform = (options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()).current();
207
351
  const approvalWindow = browserPlatform === "desktop" ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)() : null;
208
352
  openedWindow = approvalWindow;
@@ -292,9 +436,75 @@ function createDirectConnectFlow(transports, options = {}) {
292
436
  activeRunId++;
293
437
  clearPoll();
294
438
  closeUnnavigatedWindow();
439
+ clearSheet();
295
440
  setState({ type: "idle" });
296
441
  }
297
442
  };
443
+ async function startSheet(runId) {
444
+ setState({ type: "creating" });
445
+ const fail = (error) => {
446
+ if (runId !== activeRunId) return;
447
+ clearSheet();
448
+ failRun(toError(error));
449
+ };
450
+ const authorizeRequest = transports.authorizeRequest;
451
+ if (!authorizeRequest) {
452
+ fail(
453
+ new Error('presentation: "sheet" needs the authorizeRequest transport')
454
+ );
455
+ return;
456
+ }
457
+ let sheetOptions;
458
+ try {
459
+ const configured = options.sheet;
460
+ if (!configured) {
461
+ throw new Error('presentation: "sheet" needs sheet options');
462
+ }
463
+ sheetOptions = typeof configured === "function" ? await configured() : configured;
464
+ } catch (err) {
465
+ fail(err);
466
+ return;
467
+ }
468
+ if (runId !== activeRunId) return;
469
+ const created = transports.createRequest();
470
+ created.catch(() => void 0);
471
+ sheetCloseAfterDoneMs = sheetOptions.closeAfterDoneMs === void 0 ? DEFAULT_CLOSE_AFTER_DONE_MS : sheetOptions.closeAfterDoneMs;
472
+ sheetState = { open: true };
473
+ try {
474
+ sheetHandle = (sheetOptions.open ?? import_launcher.openConnectSheet)({
475
+ clientId: sheetOptions.clientId,
476
+ appName: sheetOptions.appName,
477
+ vanaOrigin: sheetOptions.accountOrigin,
478
+ container: sheetOptions.container,
479
+ readyTimeoutMs: sheetOptions.readyTimeoutMs,
480
+ async getRequest() {
481
+ const request2 = await created;
482
+ return {
483
+ id: request2.requestId,
484
+ authorization: await authorizeRequest(request2.requestId)
485
+ };
486
+ },
487
+ onEvent(event) {
488
+ if (runId !== activeRunId) return;
489
+ sheetOptions.onEvent?.(event);
490
+ handleSheetEvent(event);
491
+ }
492
+ });
493
+ } catch {
494
+ sheetHandle = null;
495
+ sheetState = null;
496
+ sheetUnavailable = "sheet_failed";
497
+ }
498
+ let request;
499
+ try {
500
+ request = await created;
501
+ } catch (err) {
502
+ fail(err);
503
+ return;
504
+ }
505
+ if (runId !== activeRunId || !running) return;
506
+ startPolling(request, awaitingState(request));
507
+ }
298
508
  return flow;
299
509
  }
300
510
  // Annotate the CommonJS export names for ESM import in node:
@@ -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\";\nimport { normalizeMobileContinuationUrl } 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/** Browser class used only to choose the destination returned by Vana. */\nexport type DirectBrowserPlatform = \"desktop\" | \"mobile\";\n\n/** Injectable browser-platform policy; it never asserts whether an app exists. */\nexport interface DirectBrowserPlatformPolicy {\n current(): DirectBrowserPlatform;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /**\n * Overall timeout in ms before giving up. Defaults to 300000 (5 min).\n * Used only when the access request does not carry an authoritative\n * `expiresAt` value.\n */\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 /** SDK-owned mobile/desktop policy. Injectable for deterministic tests. */\n browserPlatformPolicy?: DirectBrowserPlatformPolicy;\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 *\n * Desktop and light-data requests move through `\"awaiting_approval\"` (Vana Web\n * opens in a popup). A deep Direct request on a mobile browser moves through\n * `\"ready_to_open\"` instead: the SDK exposes a plain HTTPS\n * `mobileContinuationUrl` for the UI to render as a primary \"Open Vana\" link,\n * never launching it automatically, and keeps polling in memory.\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 popup was blocked. The UI should render the universal\n * HTTPS `request.approvalUrl` as a manual \"Open approval\" link.\n */\n popupBlocked: boolean;\n }\n | {\n type: \"ready_to_open\";\n request: AccessRequest;\n /**\n * Validated HTTPS continuation URL the mobile UI renders as the primary\n * \"Open Vana\" tap. Polling continues while it is shown; its embedded\n * ticket may rotate to a fresh URL between polls.\n */\n mobileContinuationUrl: string;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** Whether an explicit read retry reused consent or started fresh approval. */\nexport type DirectConnectRetryOutcome =\n | \"retried_existing_grant\"\n | \"fresh_approval_required\";\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 /**\n * Retry a failed read, reusing a still-live approved request when possible.\n *\n * @remarks\n * This explicit path avoids the observed double-approval symptom where\n * \"Try that again\" minted a new request after a transient read failure.\n * The return value tells callers whether existing consent was reused or a\n * fresh approval was required.\n */\n retryRead(): Promise<DirectConnectRetryOutcome>;\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\nconst MOBILE_USER_AGENT =\n /Android|iPhone|iPad|iPod|Mobile|Silk|Kindle|Opera Mini|IEMobile/i;\n\nfunction defaultBrowserPlatformPolicy(): DirectBrowserPlatformPolicy {\n return {\n current() {\n if (typeof navigator === \"undefined\") return \"desktop\";\n const isTouchCapableIpad =\n navigator.platform === \"MacIntel\" && navigator.maxTouchPoints > 1;\n return MOBILE_USER_AGENT.test(navigator.userAgent) || isTouchCapableIpad\n ? \"mobile\"\n : \"desktop\";\n },\n };\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 // `openApprovalWindow` and `browserPlatformPolicy` are resolved lazily at\n // start() (see below) so options swapped in after construction are still\n // honoured — matching the latest-callback pattern the React hook uses for its\n // 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 let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n let running = false;\n // Retained only after status proved this request had a read-ready grant.\n // A retry rechecks that status before trusting the prior consent.\n let approvedRequest: AccessRequest | null = null;\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 === \"ready_to_open\" ||\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 function requestDeadline(request: AccessRequest): number {\n if (request.expiresAt !== undefined) {\n const expiresAt = Date.parse(request.expiresAt);\n if (Number.isFinite(expiresAt)) return expiresAt;\n }\n return now() + timeoutMs;\n }\n\n /**\n * Enter the polling loop from the given initial state (either\n * `awaiting_approval` for desktop/light or `ready_to_open` for mobile-deep).\n * Errors out immediately if the request has already expired.\n */\n function startPolling(\n request: AccessRequest,\n initialState: DirectConnectState<T>,\n ): void {\n setState(initialState);\n const deadline = requestDeadline(request);\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Access request expired\"),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\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 // A pending deep-mobile status may rotate the continuation ticket. Adopt a\n // fresh, still-valid URL so the rendered \"Open Vana\" link always points at a\n // live ticket; ignore it on the desktop/light path.\n if (status.status === \"pending\" && state.type === \"ready_to_open\") {\n const refreshed = normalizeMobileContinuationUrl(\n status.mobileContinuationUrl,\n );\n if (refreshed && refreshed !== state.mobileContinuationUrl) {\n request = { ...request, mobileContinuationUrl: refreshed };\n setState({\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl: refreshed,\n });\n }\n }\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n approvedRequest = request;\n await readAndFinish(request);\n return;\n }\n if (\n status.status === \"completed\" ||\n status.status === \"denied\" ||\n status.status === \"expired\"\n ) {\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 const flow: DirectConnectFlow<T> = {\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 // start() deliberately keeps its established first-run semantics: every\n // explicit start creates a request. Only retryRead() may reuse consent.\n approvedRequest = null;\n const runId = ++activeRunId;\n // Read the platform policy at start time, like openApprovalWindow below,\n // so a policy swapped in after construction (a React rerender forwards\n // options through a ref) still decides this run's destination.\n const browserPlatform = (\n options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()\n ).current();\n\n // Desktop preserves the pre-mobile synchronous popup contract: open a\n // blank tab while the click's transient activation is live, then navigate\n // it once createRequest returns the approval URL (BUI-622). Mobile never\n // creates that transient tab; deep requests expose one explicit HTTPS\n // link, while light requests retain the manual approvalUrl fallback.\n // Read the opener option at start time so a swapped-in custom opener is\n // still honored for desktop flows.\n const approvalWindow =\n browserPlatform === \"desktop\"\n ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)()\n : null;\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 // Re-validate the continuation URL at the SDK boundary (defense in depth\n // for custom transports that bypass the default client).\n request = {\n ...request,\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n request.mobileContinuationUrl,\n ),\n };\n\n // The SDK owns only the small mobile-versus-desktop destination choice.\n // A deep Direct request on mobile carries a validated continuation URL;\n // desktop keeps its popup contract, while mobile light exposes the HTTPS\n // approval URL as the existing manual fallback without opening a tab.\n const mobileContinuationUrl =\n browserPlatform === \"mobile\"\n ? request.mobileContinuationUrl\n : undefined;\n\n if (mobileContinuationUrl) {\n // Do not auto-launch: DCR creation is async, so the original Connect\n // gesture can no longer be trusted to retain iOS user activation. Let\n // the UI render an explicit primary \"Open Vana\" link; polling continues\n // in this tab.\n startPolling(request, {\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl,\n });\n return;\n }\n\n // Desktop/light: navigate the synchronously-opened tab to the HTTPS\n // approval URL. `approvalWindow === null` means the popup was blocked;\n // surface it so the UI renders request.approvalUrl as a visible manual\n // \"Open approval\" link instead of hanging. We poll either way, so a manual\n // open still resolves the flow, and the timeout still bounds the wait.\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 startPolling(request, {\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n },\n\n async retryRead(): Promise<DirectConnectRetryOutcome> {\n if (running || isRunningPhase()) {\n throw new Error(\n \"Cannot retry a read while the connect flow is running\",\n );\n }\n\n const request = approvedRequest;\n const parsedExpiry = request?.expiresAt\n ? Date.parse(request.expiresAt)\n : Number.NaN;\n const requestExpired =\n Number.isFinite(parsedExpiry) && now() >= parsedExpiry;\n\n if (request && !requestExpired) {\n running = true;\n const runId = ++activeRunId;\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (runId !== activeRunId) {\n throw new Error(\"Read retry was superseded\");\n }\n running = false;\n const error = toError(err);\n setState({ type: \"error\", error });\n throw error;\n }\n if (runId !== activeRunId) {\n throw new Error(\"Read retry was superseded\");\n }\n if (isReadReadyStatus(status.status)) {\n await readAndFinish(request);\n return \"retried_existing_grant\";\n }\n running = false;\n }\n\n approvedRequest = null;\n await flow.start();\n return \"fresh_approval_required\";\n },\n\n reset(): void {\n running = false;\n approvedRequest = null;\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 return flow;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,mBAA+C;AA0I/C,MAAM,2BAA2B;AACjC,MAAM,qBAAqB;AAE3B,SAAS,QA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;AAAA,QACN;AAAA,QACA,cAAc,mBAAmB;AAAA,MACnC,CAAC;AAAA,IACH;AAAA,IAEA,MAAM,YAAgD;AACpD,UAAI,WAAW,eAAe,GAAG;AAC/B,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MACF;AAEA,YAAM,UAAU;AAChB,YAAM,eAAe,SAAS,YAC1B,KAAK,MAAM,QAAQ,SAAS,IAC5B,OAAO;AACX,YAAM,iBACJ,OAAO,SAAS,YAAY,KAAK,IAAI,KAAK;AAE5C,UAAI,WAAW,CAAC,gBAAgB;AAC9B,kBAAU;AACV,cAAM,QAAQ,EAAE;AAChB,YAAI;AACJ,YAAI;AACF,mBAAS,MAAM,WAAW,UAAU,QAAQ,SAAS;AAAA,QACvD,SAAS,KAAK;AACZ,cAAI,UAAU,aAAa;AACzB,kBAAM,IAAI,MAAM,2BAA2B;AAAA,UAC7C;AACA,oBAAU;AACV,gBAAM,QAAQ,QAAQ,GAAG;AACzB,mBAAS,EAAE,MAAM,SAAS,MAAM,CAAC;AACjC,gBAAM;AAAA,QACR;AACA,YAAI,UAAU,aAAa;AACzB,gBAAM,IAAI,MAAM,2BAA2B;AAAA,QAC7C;AACA,YAAI,kBAAkB,OAAO,MAAM,GAAG;AACpC,gBAAM,cAAc,OAAO;AAC3B,iBAAO;AAAA,QACT;AACA,kBAAU;AAAA,MACZ;AAEA,wBAAkB;AAClB,YAAM,KAAK,MAAM;AACjB,aAAO;AAAA,IACT;AAAA,IAEA,QAAc;AACZ,gBAAU;AACV,wBAAkB;AAGlB;AACA,gBAAU;AACV,6BAAuB;AACvB,eAAS,EAAE,MAAM,OAAO,CAAC;AAAA,IAC3B;AAAA,EACF;AAEA,SAAO;AACT;","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\";\nimport { normalizeMobileContinuationUrl } from \"./types\";\nimport {\n openConnectSheet,\n type ConnectEvent,\n type ConnectHandle,\n type ConnectOpenOptions,\n} from \"../connect/launcher\";\nimport type {\n ConnectCompletion,\n ConnectProgressPhase,\n RequestAuthorization,\n SheetErrorCode,\n} from \"../connect/protocol\";\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 * Ask the backend to sign the sheet's short-lived read capability for a\n * request it created for this browser (`controller.authorizeRequestRead`).\n * Required for `presentation: \"sheet\"`; called each time the sheet asks.\n */\n authorizeRequest?: (requestId: string) => Promise<RequestAuthorization>;\n}\n\n/** How the person approves: a Vana tab (default) or Vana's in-page sheet. */\nexport type DirectConnectPresentation = \"tab\" | \"sheet\";\n\n/** Sheet settings for `presentation: \"sheet\"`. */\nexport interface DirectConnectSheetOptions {\n /** The embed client id Vana Account registered for this page's origin. */\n clientId: string;\n /** Label on the sheet chrome (Vana shows the registered name inside). */\n appName: string;\n /**\n * Vana Account origin that serves the sheet. Required: there is no\n * production default, so a dev app never silently talks to production.\n * Use `VANA_ACCOUNT_ORIGINS[env]`, or `resolveVanaAccountOrigin` for\n * preview deploys. `useVanaConnect` fills it from the backend's config.\n */\n accountOrigin: string;\n /** Element the sheet mounts in. Defaults to `document.body`. */\n container?: HTMLElement;\n /** How long to wait for the sheet to start before falling back. */\n readyTimeoutMs?: number;\n /**\n * Close the sheet this long (ms) after the data is read, so the person sees\n * it finish. Defaults to 1500; `null` leaves it open for the person to close.\n */\n closeAfterDoneMs?: number | null;\n /** Every raw launcher event, for logging or custom UI. */\n onEvent?: (event: ConnectEvent) => void;\n /** Launcher. Defaults to the SDK's `openConnectSheet`; injectable for tests. */\n open?: (options: ConnectOpenOptions) => ConnectHandle;\n}\n\n/**\n * What the sheet has reported, while it presents approval.\n *\n * @remarks\n * These are hints for the UI, not outcomes. The flow settles only from the\n * backend: `done` once the status poll says the request is readable and the\n * read succeeds, `error` when the poll reports `denied`, `expired` or\n * `completed`, or the read fails.\n */\nexport interface DirectConnectSheetState {\n /** `false` once the person closed the sheet after approving. */\n open: boolean;\n /**\n * Set once the person approved: how the data will arrive. Approval is not\n * delivery; wait for `state.type === \"done\"` before treating data as\n * delivered.\n */\n completion?: ConnectCompletion;\n /** Coarse `remote_collect` progress. */\n progress?: ConnectProgressPhase;\n /** A failure the sheet is showing; it stays open for the person to read. */\n error?: SheetErrorCode;\n}\n\n/**\n * Sheet errors after which the flow closes the sheet and falls back to the\n * tab presentation (`popupBlocked: true`, so the UI shows the approval link).\n */\nconst SHEET_FALLBACK_CODES: readonly SheetErrorCode[] = [\n \"frame_blocked\",\n \"origin_not_registered\",\n \"incompatible_version\",\n];\n\nconst DEFAULT_CLOSE_AFTER_DONE_MS = 1500;\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/** Browser class used only to choose the destination returned by Vana. */\nexport type DirectBrowserPlatform = \"desktop\" | \"mobile\";\n\n/** Injectable browser-platform policy; it never asserts whether an app exists. */\nexport interface DirectBrowserPlatformPolicy {\n current(): DirectBrowserPlatform;\n}\n\n/** Tunables for the connect flow. */\nexport interface DirectConnectOptions {\n /** Status poll interval in ms. Defaults to 1500. */\n pollIntervalMs?: number;\n /**\n * Overall timeout in ms before giving up. Defaults to 300000 (5 min).\n * Used only when the access request does not carry an authoritative\n * `expiresAt` value.\n */\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 /** SDK-owned mobile/desktop policy. Injectable for deterministic tests. */\n browserPlatformPolicy?: DirectBrowserPlatformPolicy;\n /** `setTimeout`. Injectable for tests. Defaults to `globalThis.setTimeout`. */\n setTimeoutFn?: (cb: () => void, ms: number) => unknown;\n /**\n * `\"sheet\"` presents approval in Vana's in-page sheet instead of a tab;\n * needs {@link DirectConnectOptions.sheet} and the `authorizeRequest`\n * transport. Defaults to `\"tab\"`.\n */\n presentation?: DirectConnectPresentation;\n /** Sheet settings, or a loader for them (fetched at `start()`). */\n sheet?:\n | DirectConnectSheetOptions\n | (() => Promise<DirectConnectSheetOptions>);\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 *\n * Desktop and light-data requests move through `\"awaiting_approval\"` (Vana Web\n * opens in a popup). A deep Direct request on a mobile browser moves through\n * `\"ready_to_open\"` instead: the SDK exposes a plain HTTPS\n * `mobileContinuationUrl` for the UI to render as a primary \"Open Vana\" link,\n * never launching it automatically, and keeps polling in memory.\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 popup was blocked. The UI should render the universal\n * HTTPS `request.approvalUrl` as a manual \"Open approval\" link.\n */\n popupBlocked: boolean;\n /** Present while Vana's sheet presents approval (`presentation: \"sheet\"`). */\n sheet?: DirectConnectSheetState;\n /**\n * Set when the sheet could not run here and the flow fell back to the\n * tab presentation (with `popupBlocked: true`).\n */\n sheetUnavailable?: SheetErrorCode;\n }\n | {\n type: \"ready_to_open\";\n request: AccessRequest;\n /**\n * Validated HTTPS continuation URL the mobile UI renders as the primary\n * \"Open Vana\" tap. Polling continues while it is shown; its embedded\n * ticket may rotate to a fresh URL between polls.\n */\n mobileContinuationUrl: string;\n }\n | { type: \"reading\"; request: AccessRequest }\n | { type: \"done\"; result: ApprovedDataResult<T> }\n | { type: \"error\"; error: Error };\n\n/** Whether an explicit read retry reused consent or started fresh approval. */\nexport type DirectConnectRetryOutcome =\n | \"retried_existing_grant\"\n | \"fresh_approval_required\";\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 /**\n * Retry a failed read, reusing a still-live approved request when possible.\n *\n * @remarks\n * This explicit path avoids the observed double-approval symptom where\n * \"Try that again\" minted a new request after a transient read failure.\n * The return value tells callers whether existing consent was reused or a\n * fresh approval was required.\n */\n retryRead(): Promise<DirectConnectRetryOutcome>;\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\nconst MOBILE_USER_AGENT =\n /Android|iPhone|iPad|iPod|Mobile|Silk|Kindle|Opera Mini|IEMobile/i;\n\nfunction defaultBrowserPlatformPolicy(): DirectBrowserPlatformPolicy {\n return {\n current() {\n if (typeof navigator === \"undefined\") return \"desktop\";\n const isTouchCapableIpad =\n navigator.platform === \"MacIntel\" && navigator.maxTouchPoints > 1;\n return MOBILE_USER_AGENT.test(navigator.userAgent) || isTouchCapableIpad\n ? \"mobile\"\n : \"desktop\";\n },\n };\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 // `openApprovalWindow` and `browserPlatformPolicy` are resolved lazily at\n // start() (see below) so options swapped in after construction are still\n // honoured — matching the latest-callback pattern the React hook uses for its\n // 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 let state: DirectConnectState<T> = { type: \"idle\" };\n const listeners = new Set<() => void>();\n let pollHandle: unknown = null;\n // The request and deadline the poll loop is on, so a sheet event can ask\n // for the next poll now instead of after the interval.\n let pollTarget: { request: AccessRequest; deadline: number } | null = null;\n let pollInFlight = false;\n let pollNudged = false;\n let running = false;\n // Retained only after status proved this request had a read-ready grant.\n // A retry rechecks that status before trusting the prior consent.\n let approvedRequest: AccessRequest | null = null;\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 // The sheet of the current run (`presentation: \"sheet\"`), while open.\n let sheetHandle: ConnectHandle | null = null;\n let sheetState: DirectConnectSheetState | null = null;\n let sheetUnavailable: SheetErrorCode | null = null;\n let sheetCloseAfterDoneMs: number | null = DEFAULT_CLOSE_AFTER_DONE_MS;\n let sheetCloseTimer: unknown = 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 pollTarget = null;\n pollNudged = false;\n }\n\n /**\n * Poll now rather than after the interval. Sheet events call this: they\n * hint that the backend's status may have moved, but never settle the flow\n * themselves. The poll stays the one authority for `done` and `error`.\n */\n function nudgePoll(): void {\n if (!running) return;\n if (pollInFlight) {\n pollNudged = true;\n return;\n }\n const target = pollTarget;\n if (pollHandle === null || !target) return;\n clearPoll();\n void poll(target.request, target.deadline);\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 === \"ready_to_open\" ||\n state.type === \"reading\"\n );\n }\n\n /** Close the sheet without treating its close event as the person's. */\n function closeSheet(): void {\n const handle = sheetHandle;\n sheetHandle = null;\n handle?.close();\n }\n\n function clearSheet(): void {\n if (sheetCloseTimer !== null) {\n clearTimeoutFn(sheetCloseTimer);\n sheetCloseTimer = null;\n }\n closeSheet();\n sheetState = null;\n sheetUnavailable = null;\n }\n\n /** The waiting state for `request`, given what the sheet has reported. */\n function awaitingState(request: AccessRequest): DirectConnectState<T> {\n if (sheetUnavailable) {\n return {\n type: \"awaiting_approval\",\n request,\n popupBlocked: true,\n sheetUnavailable,\n };\n }\n return {\n type: \"awaiting_approval\",\n request,\n popupBlocked: false,\n ...(sheetState ? { sheet: { ...sheetState } } : {}),\n };\n }\n\n function updateSheet(patch: Partial<DirectConnectSheetState>): void {\n if (!sheetState) return;\n sheetState = { ...sheetState, ...patch };\n if (state.type === \"awaiting_approval\" && state.sheet) {\n setState(awaitingState(state.request));\n }\n }\n\n function failRun(error: Error): void {\n running = false;\n clearPoll();\n setState({ type: \"error\", error });\n }\n\n /**\n * Sheet events update what the UI shows and nudge the status poll; none of\n * them is an outcome. `connected` is the person's approval, not delivery.\n * A future terminal sheet event belongs here too, as another nudge: the\n * backend poll and read still decide `done` or `error`.\n */\n function handleSheetEvent(event: ConnectEvent): void {\n switch (event.type) {\n case \"connected\":\n updateSheet({ completion: event.completion });\n nudgePoll();\n return;\n case \"progress\":\n updateSheet({ progress: event.phase });\n return;\n case \"error\": {\n if (event.code === \"request_failed\") {\n // The backend could not create or sign the request for the sheet.\n if (!running) return;\n closeSheet();\n failRun(new Error(\"Could not prepare the request for Vana's sheet\"));\n return;\n }\n if (SHEET_FALLBACK_CODES.includes(event.code)) {\n // The sheet cannot run on this page: fall back to the approval URL.\n sheetUnavailable = event.code;\n sheetState = null;\n closeSheet();\n if (state.type === \"awaiting_approval\") {\n setState(awaitingState(state.request));\n }\n return;\n }\n updateSheet({ error: event.code });\n return;\n }\n case \"close\": {\n if (!sheetHandle) return; // closed by the flow itself\n sheetHandle = null;\n if (!running) return;\n if (sheetState?.error) {\n failRun(new Error(`Vana's sheet failed: ${sheetState.error}`));\n return;\n }\n if (!sheetState?.completion) {\n // Closed before approving: the person backed out.\n running = false;\n activeRunId++;\n clearPoll();\n sheetState = null;\n setState({ type: \"idle\" });\n return;\n }\n // Approved, then closed. The data may still be readable (a durable\n // Personal Server), so keep polling until the request settles.\n updateSheet({ open: false });\n return;\n }\n default:\n return;\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 if (sheetHandle) {\n sheetHandle.setRequestStatus(\"completed\");\n if (sheetCloseAfterDoneMs !== null) {\n sheetCloseTimer = setTimeoutFn(() => {\n sheetCloseTimer = null;\n closeSheet();\n }, sheetCloseAfterDoneMs);\n }\n }\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 const delay = pollNudged ? 0 : pollIntervalMs;\n pollNudged = false;\n pollTarget = { request, deadline };\n pollHandle = setTimeoutFn(() => {\n pollHandle = null;\n void poll(request, deadline);\n }, delay);\n }\n\n function requestDeadline(request: AccessRequest): number {\n if (request.expiresAt !== undefined) {\n const expiresAt = Date.parse(request.expiresAt);\n if (Number.isFinite(expiresAt)) return expiresAt;\n }\n return now() + timeoutMs;\n }\n\n /**\n * Enter the polling loop from the given initial state (either\n * `awaiting_approval` for desktop/light or `ready_to_open` for mobile-deep).\n * Errors out immediately if the request has already expired.\n */\n function startPolling(\n request: AccessRequest,\n initialState: DirectConnectState<T>,\n ): void {\n pollNudged = false;\n setState(initialState);\n const deadline = requestDeadline(request);\n if (now() >= deadline) {\n running = false;\n setState({\n type: \"error\",\n error: new Error(\"Access request expired\"),\n });\n return;\n }\n scheduleNextPoll(request, deadline);\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 pollInFlight = true;\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 } finally {\n pollInFlight = false;\n }\n if (!running) return;\n\n // A pending deep-mobile status may rotate the continuation ticket. Adopt a\n // fresh, still-valid URL so the rendered \"Open Vana\" link always points at a\n // live ticket; ignore it on the desktop/light path.\n if (status.status === \"pending\" && state.type === \"ready_to_open\") {\n const refreshed = normalizeMobileContinuationUrl(\n status.mobileContinuationUrl,\n );\n if (refreshed && refreshed !== state.mobileContinuationUrl) {\n request = { ...request, mobileContinuationUrl: refreshed };\n setState({\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl: refreshed,\n });\n }\n }\n\n if (isReadReadyStatus(status.status)) {\n clearPoll();\n approvedRequest = request;\n await readAndFinish(request);\n return;\n }\n if (\n status.status === \"completed\" ||\n status.status === \"denied\" ||\n status.status === \"expired\"\n ) {\n // The sheet shows the outcome; it stays open for the person to close.\n sheetHandle?.setRequestStatus(status.status);\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 const flow: DirectConnectFlow<T> = {\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 // start() deliberately keeps its established first-run semantics: every\n // explicit start creates a request. Only retryRead() may reuse consent.\n approvedRequest = null;\n const runId = ++activeRunId;\n clearSheet();\n if (options.presentation === \"sheet\") {\n await startSheet(runId);\n return;\n }\n // Read the platform policy at start time, like openApprovalWindow below,\n // so a policy swapped in after construction (a React rerender forwards\n // options through a ref) still decides this run's destination.\n const browserPlatform = (\n options.browserPlatformPolicy ?? defaultBrowserPlatformPolicy()\n ).current();\n\n // Desktop preserves the pre-mobile synchronous popup contract: open a\n // blank tab while the click's transient activation is live, then navigate\n // it once createRequest returns the approval URL (BUI-622). Mobile never\n // creates that transient tab; deep requests expose one explicit HTTPS\n // link, while light requests retain the manual approvalUrl fallback.\n // Read the opener option at start time so a swapped-in custom opener is\n // still honored for desktop flows.\n const approvalWindow =\n browserPlatform === \"desktop\"\n ? (options.openApprovalWindow ?? defaultOpenApprovalWindow)()\n : null;\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 // Re-validate the continuation URL at the SDK boundary (defense in depth\n // for custom transports that bypass the default client).\n request = {\n ...request,\n mobileContinuationUrl: normalizeMobileContinuationUrl(\n request.mobileContinuationUrl,\n ),\n };\n\n // The SDK owns only the small mobile-versus-desktop destination choice.\n // A deep Direct request on mobile carries a validated continuation URL;\n // desktop keeps its popup contract, while mobile light exposes the HTTPS\n // approval URL as the existing manual fallback without opening a tab.\n const mobileContinuationUrl =\n browserPlatform === \"mobile\"\n ? request.mobileContinuationUrl\n : undefined;\n\n if (mobileContinuationUrl) {\n // Do not auto-launch: DCR creation is async, so the original Connect\n // gesture can no longer be trusted to retain iOS user activation. Let\n // the UI render an explicit primary \"Open Vana\" link; polling continues\n // in this tab.\n startPolling(request, {\n type: \"ready_to_open\",\n request,\n mobileContinuationUrl,\n });\n return;\n }\n\n // Desktop/light: navigate the synchronously-opened tab to the HTTPS\n // approval URL. `approvalWindow === null` means the popup was blocked;\n // surface it so the UI renders request.approvalUrl as a visible manual\n // \"Open approval\" link instead of hanging. We poll either way, so a manual\n // open still resolves the flow, and the timeout still bounds the wait.\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 startPolling(request, {\n type: \"awaiting_approval\",\n request,\n popupBlocked: approvalWindow === null,\n });\n },\n\n async retryRead(): Promise<DirectConnectRetryOutcome> {\n if (running || isRunningPhase()) {\n throw new Error(\n \"Cannot retry a read while the connect flow is running\",\n );\n }\n\n const request = approvedRequest;\n const parsedExpiry = request?.expiresAt\n ? Date.parse(request.expiresAt)\n : Number.NaN;\n const requestExpired =\n Number.isFinite(parsedExpiry) && now() >= parsedExpiry;\n\n if (request && !requestExpired) {\n running = true;\n const runId = ++activeRunId;\n let status: AccessRequestStatus;\n try {\n status = await transports.getStatus(request.requestId);\n } catch (err) {\n if (runId !== activeRunId) {\n throw new Error(\"Read retry was superseded\");\n }\n running = false;\n const error = toError(err);\n setState({ type: \"error\", error });\n throw error;\n }\n if (runId !== activeRunId) {\n throw new Error(\"Read retry was superseded\");\n }\n if (isReadReadyStatus(status.status)) {\n await readAndFinish(request);\n return \"retried_existing_grant\";\n }\n running = false;\n }\n\n approvedRequest = null;\n await flow.start();\n return \"fresh_approval_required\";\n },\n\n reset(): void {\n running = false;\n approvedRequest = null;\n // Invalidate any in-flight start() so a late createRequest can't clobber\n // a subsequent run.\n activeRunId++;\n clearPoll();\n closeUnnavigatedWindow();\n clearSheet();\n setState({ type: \"idle\" });\n },\n };\n\n /**\n * `presentation: \"sheet\"`: open Vana's sheet at once and create the request\n * alongside it, so the request is ready by the time the person has signed\n * in. The sheet asks for the request's read capability; the status poll and\n * the read are the tab flow's.\n */\n async function startSheet(runId: number): Promise<void> {\n setState({ type: \"creating\" });\n const fail = (error: unknown) => {\n if (runId !== activeRunId) return;\n clearSheet();\n failRun(toError(error));\n };\n\n const authorizeRequest = transports.authorizeRequest;\n if (!authorizeRequest) {\n fail(\n new Error('presentation: \"sheet\" needs the authorizeRequest transport'),\n );\n return;\n }\n let sheetOptions: DirectConnectSheetOptions;\n try {\n const configured = options.sheet;\n if (!configured) {\n throw new Error('presentation: \"sheet\" needs sheet options');\n }\n sheetOptions =\n typeof configured === \"function\" ? await configured() : configured;\n } catch (err) {\n fail(err);\n return;\n }\n if (runId !== activeRunId) return;\n\n const created = transports.createRequest();\n // Observed below; this keeps an early rejection from going unhandled.\n created.catch(() => undefined);\n sheetCloseAfterDoneMs =\n sheetOptions.closeAfterDoneMs === undefined\n ? DEFAULT_CLOSE_AFTER_DONE_MS\n : sheetOptions.closeAfterDoneMs;\n sheetState = { open: true };\n try {\n sheetHandle = (sheetOptions.open ?? openConnectSheet)({\n clientId: sheetOptions.clientId,\n appName: sheetOptions.appName,\n vanaOrigin: sheetOptions.accountOrigin,\n container: sheetOptions.container,\n readyTimeoutMs: sheetOptions.readyTimeoutMs,\n async getRequest() {\n const request = await created;\n return {\n id: request.requestId,\n authorization: await authorizeRequest(request.requestId),\n };\n },\n onEvent(event) {\n if (runId !== activeRunId) return;\n sheetOptions.onEvent?.(event);\n handleSheetEvent(event);\n },\n });\n } catch {\n // A launcher that cannot open (no DOM, bad origin) is a sheet that\n // cannot run here: fall back to the approval URL.\n sheetHandle = null;\n sheetState = null;\n sheetUnavailable = \"sheet_failed\";\n }\n\n let request: AccessRequest;\n try {\n request = await created;\n } catch (err) {\n fail(err);\n return;\n }\n if (runId !== activeRunId || !running) return;\n startPolling(request, awaitingState(request));\n }\n\n return flow;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAqBA,mBAA+C;AAC/C,sBAKO;AAsFP,MAAM,uBAAkD;AAAA,EACtD;AAAA,EACA;AAAA,EACA;AACF;AAEA,MAAM,8BAA8B;AA8IpC,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;AAEA,MAAM,oBACJ;AAEF,SAAS,+BAA4D;AACnE,SAAO;AAAA,IACL,UAAU;AACR,UAAI,OAAO,cAAc,YAAa,QAAO;AAC7C,YAAM,qBACJ,UAAU,aAAa,cAAc,UAAU,iBAAiB;AAClE,aAAO,kBAAkB,KAAK,UAAU,SAAS,KAAK,qBAClD,WACA;AAAA,IACN;AAAA,EACF;AACF;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,c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