@hubspot/app-connect-sdk 1.0.0-alpha.13 → 1.0.0-alpha.15
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.
- package/.turbo/turbo-format$colon$check.log +1 -1
- package/.turbo/turbo-test.log +63 -58
- package/.turbo/turbo-tsdown.log +12 -12
- package/build/tsconfig.browser.tsbuildinfo +1 -1
- package/build/tsconfig.server.tsbuildinfo +1 -1
- package/dist/browser/{create-crdncXsh.js → create-D-oTtxX-.js} +252 -92
- package/dist/browser/create-D-oTtxX-.js.map +1 -0
- package/dist/browser/index.d.ts +2 -2
- package/dist/browser/index.js +1 -1
- package/dist/browser/react/lovable.d.ts +8 -0
- package/dist/browser/react/lovable.js +6 -3
- package/dist/browser/react/lovable.js.map +1 -1
- package/dist/browser/react.d.ts +1 -1
- package/dist/browser/{types-rTQw6A54.d.ts → types-DkAmHcZt.d.ts} +22 -7
- package/dist/server/shared/constants.js.map +1 -1
- package/package.json +3 -3
- package/src/browser/app-connect-controller/README.md +5 -2
- package/src/browser/app-connect-controller/connect-start.test.ts +156 -0
- package/src/browser/app-connect-controller/connect-start.ts +18 -3
- package/src/browser/app-connect-controller/init.test.ts +43 -2
- package/src/browser/app-connect-controller/init.ts +23 -48
- package/src/browser/app-connect-controller/oauth-complete.test.ts +106 -0
- package/src/browser/app-connect-controller/oauth-complete.ts +53 -0
- package/src/browser/app-connect-controller/oauth-popup.test.ts +192 -0
- package/src/browser/app-connect-controller/oauth-popup.ts +152 -0
- package/src/browser/app-connect-controller/utils/iframe-utils.ts +12 -0
- package/src/browser/app-connect-controller/utils/resolve-oauth-connect-mode.test.ts +35 -0
- package/src/browser/app-connect-controller/utils/resolve-oauth-connect-mode.ts +21 -0
- package/src/browser/index.ts +1 -0
- package/src/browser/react/lovable/LovableHubSpotAppConnect.tsx +12 -2
- package/src/browser/types.ts +21 -5
- package/src/shared/constants.ts +9 -0
- package/dist/browser/create-crdncXsh.js.map +0 -1
|
@@ -35,63 +35,6 @@ const noopLogger = {
|
|
|
35
35
|
warn: () => {},
|
|
36
36
|
error: () => {}
|
|
37
37
|
};
|
|
38
|
-
//#endregion
|
|
39
|
-
//#region src/browser/app-connect-controller/utils/timeout-utils.ts
|
|
40
|
-
function delay(ms) {
|
|
41
|
-
if (ms <= 0) return Promise.resolve();
|
|
42
|
-
return new Promise((resolve) => {
|
|
43
|
-
setTimeout(resolve, ms);
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
//#endregion
|
|
47
|
-
//#region src/browser/app-connect-controller/connect-start.ts
|
|
48
|
-
/** Extra wait before redirect so the connect progress UI is visible; set to `0` to disable. */
|
|
49
|
-
const ARTIFICIAL_CONNECT_REDIRECT_DELAY_MS = 500;
|
|
50
|
-
/**
|
|
51
|
-
* Begins the OAuth connect flow:
|
|
52
|
-
*
|
|
53
|
-
* 1. Calls the SDK's `auth/init-session` route to mint a fresh PKCE
|
|
54
|
-
* verifier + state and obtain HubSpot's `authorize` URL.
|
|
55
|
-
* 2. Navigates the browser to that URL (full-page redirect).
|
|
56
|
-
*
|
|
57
|
-
* The `return_path` is the current path + query so the user lands
|
|
58
|
-
* back where they started after authorizing.
|
|
59
|
-
*
|
|
60
|
-
* Throws when the init call fails. Does not return after the redirect
|
|
61
|
-
* begins because the page is unloaded.
|
|
62
|
-
*/
|
|
63
|
-
async function startHubSpotConnection(context) {
|
|
64
|
-
const { config } = context;
|
|
65
|
-
const returnPath = `${window.location.pathname}${window.location.search}`;
|
|
66
|
-
const initUrl = new URL(`${config.hubSpotConnectBaseUrl}/auth/init-session`, window.location.origin);
|
|
67
|
-
initUrl.searchParams.set("return_path", returnPath);
|
|
68
|
-
const initResponse = await fetch(initUrl.toString(), { credentials: "include" });
|
|
69
|
-
if (!initResponse.ok) throw new Error(`Failed to init session: ${initResponse.status}`);
|
|
70
|
-
const { authorization_url: authorizationUrl } = await initResponse.json();
|
|
71
|
-
await delay(ARTIFICIAL_CONNECT_REDIRECT_DELAY_MS);
|
|
72
|
-
window.location.href = authorizationUrl;
|
|
73
|
-
}
|
|
74
|
-
//#endregion
|
|
75
|
-
//#region src/browser/app-connect-controller/default-session-storage.ts
|
|
76
|
-
/**
|
|
77
|
-
* Builds a `SessionStorage` adapter that delegates to the global
|
|
78
|
-
* `sessionStorage` object exposed by browsers. The controller uses
|
|
79
|
-
* this when no custom storage is supplied (e.g. for tests or non-DOM
|
|
80
|
-
* environments).
|
|
81
|
-
*/
|
|
82
|
-
function createDefaultSessionStorage() {
|
|
83
|
-
return {
|
|
84
|
-
setItem: (key, value) => {
|
|
85
|
-
sessionStorage.setItem(key, value);
|
|
86
|
-
},
|
|
87
|
-
getItem: (key) => {
|
|
88
|
-
return sessionStorage.getItem(key);
|
|
89
|
-
},
|
|
90
|
-
removeItem: (key) => {
|
|
91
|
-
sessionStorage.removeItem(key);
|
|
92
|
-
}
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
38
|
/**
|
|
96
39
|
* Query parameter on the `auth/complete` POST request carrying the
|
|
97
40
|
* authorization `code` HubSpot returned to the frontend callback.
|
|
@@ -102,6 +45,13 @@ const AUTH_COMPLETE_CODE_PARAM = "code";
|
|
|
102
45
|
* OAuth `state` HubSpot echoed back to the frontend callback.
|
|
103
46
|
*/
|
|
104
47
|
const AUTH_COMPLETE_STATE_PARAM = "state";
|
|
48
|
+
/**
|
|
49
|
+
* `postMessage` `data.type` value the OAuth popup sends to its opener
|
|
50
|
+
* with the authorization `code` and `state` from the callback URL. The
|
|
51
|
+
* opener POSTs them to `auth/complete` so credentialed cookies stay in
|
|
52
|
+
* the same CHIPS partition as `auth/init-session`.
|
|
53
|
+
*/
|
|
54
|
+
const OAUTH_POPUP_CALLBACK_MESSAGE_TYPE = "hubspot-app-connect:oauth-callback";
|
|
105
55
|
//#endregion
|
|
106
56
|
//#region src/browser/app-connect-controller/constants.ts
|
|
107
57
|
/**
|
|
@@ -163,6 +113,226 @@ function isClientSessionActive(context) {
|
|
|
163
113
|
return expiresAt !== null && Date.now() < expiresAt;
|
|
164
114
|
}
|
|
165
115
|
//#endregion
|
|
116
|
+
//#region src/browser/app-connect-controller/oauth-complete.ts
|
|
117
|
+
/**
|
|
118
|
+
* Finishes the OAuth token exchange by POSTing `code` and `state` to the
|
|
119
|
+
* SDK's `auth/complete` route with credentialed cookies from the current
|
|
120
|
+
* browsing context (must match the partition used by `auth/init-session`).
|
|
121
|
+
*/
|
|
122
|
+
async function completeHubSpotOAuthSession(context, options) {
|
|
123
|
+
const { code, state } = options;
|
|
124
|
+
const completeUrl = new URL(`${context.config.hubSpotConnectBaseUrl}/auth/complete`, window.location.origin);
|
|
125
|
+
completeUrl.searchParams.set(AUTH_COMPLETE_CODE_PARAM, code);
|
|
126
|
+
completeUrl.searchParams.set(AUTH_COMPLETE_STATE_PARAM, state);
|
|
127
|
+
let response;
|
|
128
|
+
try {
|
|
129
|
+
response = await fetch(completeUrl.toString(), {
|
|
130
|
+
method: "POST",
|
|
131
|
+
credentials: "include"
|
|
132
|
+
});
|
|
133
|
+
} catch (err) {
|
|
134
|
+
clearSessionStorage(context);
|
|
135
|
+
throw new Error(`Failed to complete HubSpot OAuth: ${err instanceof Error ? err.message : String(err)}`);
|
|
136
|
+
}
|
|
137
|
+
if (!response.ok) {
|
|
138
|
+
clearSessionStorage(context);
|
|
139
|
+
throw new Error(`Failed to complete HubSpot OAuth: ${response.status} ${response.statusText}`);
|
|
140
|
+
}
|
|
141
|
+
return await response.json();
|
|
142
|
+
}
|
|
143
|
+
//#endregion
|
|
144
|
+
//#region src/browser/app-connect-controller/oauth-popup.ts
|
|
145
|
+
const OAUTH_POPUP_WINDOW_NAME = "hubspot-app-connect-oauth";
|
|
146
|
+
const OAUTH_POPUP_POLL_INTERVAL_MS = 300;
|
|
147
|
+
function isOAuthPopupCallbackMessage(data) {
|
|
148
|
+
if (typeof data !== "object" || data === null) return false;
|
|
149
|
+
const record = data;
|
|
150
|
+
return record.type === "hubspot-app-connect:oauth-callback" && typeof record.code === "string" && record.code.length > 0 && typeof record.state === "string" && record.state.length > 0;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Opens HubSpot's authorize URL in a popup and waits for the callback
|
|
154
|
+
* page to relay `code` + `state` back. The opener POSTs to
|
|
155
|
+
* `auth/complete` so credentialed cookies use the same CHIPS partition
|
|
156
|
+
* as `auth/init-session`.
|
|
157
|
+
*/
|
|
158
|
+
async function waitForHubSpotOAuthPopup(options) {
|
|
159
|
+
const { context, authorizationUrl } = options;
|
|
160
|
+
const targetOrigin = window.location.origin;
|
|
161
|
+
return new Promise((resolve, reject) => {
|
|
162
|
+
let popup = null;
|
|
163
|
+
let pollTimer;
|
|
164
|
+
let isSettled = false;
|
|
165
|
+
const cleanup = () => {
|
|
166
|
+
window.removeEventListener("message", onMessage);
|
|
167
|
+
if (pollTimer !== void 0) clearInterval(pollTimer);
|
|
168
|
+
};
|
|
169
|
+
const settleSuccess = (expiresAtMs) => {
|
|
170
|
+
if (isSettled) return;
|
|
171
|
+
isSettled = true;
|
|
172
|
+
cleanup();
|
|
173
|
+
storeExpiresAt({
|
|
174
|
+
context,
|
|
175
|
+
expiresAtMs
|
|
176
|
+
});
|
|
177
|
+
context.store.setState({
|
|
178
|
+
isSessionConnected: true,
|
|
179
|
+
error: null
|
|
180
|
+
});
|
|
181
|
+
resolve();
|
|
182
|
+
};
|
|
183
|
+
const settleFailure = (message) => {
|
|
184
|
+
if (isSettled) return;
|
|
185
|
+
isSettled = true;
|
|
186
|
+
cleanup();
|
|
187
|
+
try {
|
|
188
|
+
popup?.close();
|
|
189
|
+
} catch {}
|
|
190
|
+
reject(new Error(message));
|
|
191
|
+
};
|
|
192
|
+
const onMessage = (event) => {
|
|
193
|
+
if (event.origin !== targetOrigin) return;
|
|
194
|
+
if (!isOAuthPopupCallbackMessage(event.data)) return;
|
|
195
|
+
(async () => {
|
|
196
|
+
try {
|
|
197
|
+
settleSuccess((await completeHubSpotOAuthSession(context, {
|
|
198
|
+
code: event.data.code,
|
|
199
|
+
state: event.data.state
|
|
200
|
+
})).expires_at);
|
|
201
|
+
} catch (err) {
|
|
202
|
+
settleFailure(err instanceof Error ? err.message : "HubSpot OAuth failed");
|
|
203
|
+
}
|
|
204
|
+
})();
|
|
205
|
+
};
|
|
206
|
+
window.addEventListener("message", onMessage);
|
|
207
|
+
popup = window.open(authorizationUrl, OAUTH_POPUP_WINDOW_NAME, "popup=yes,width=600,height=700");
|
|
208
|
+
if (!popup) {
|
|
209
|
+
settleFailure("Popup blocked. Allow popups for this site and try again.");
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
pollTimer = setInterval(() => {
|
|
213
|
+
if (popup?.closed) settleFailure("Connect to HubSpot was cancelled.");
|
|
214
|
+
}, OAUTH_POPUP_POLL_INTERVAL_MS);
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Called from the OAuth callback page inside the popup. Relays `code`
|
|
219
|
+
* and `state` to the opener (which runs `auth/complete`) and closes.
|
|
220
|
+
*/
|
|
221
|
+
function relayOAuthCallbackToOpener(options) {
|
|
222
|
+
const { code, state } = options;
|
|
223
|
+
const opener = window.opener;
|
|
224
|
+
if (!opener || opener.closed) return false;
|
|
225
|
+
const message = {
|
|
226
|
+
type: OAUTH_POPUP_CALLBACK_MESSAGE_TYPE,
|
|
227
|
+
code,
|
|
228
|
+
state
|
|
229
|
+
};
|
|
230
|
+
opener.postMessage(message, window.location.origin);
|
|
231
|
+
try {
|
|
232
|
+
window.close();
|
|
233
|
+
} catch {}
|
|
234
|
+
return true;
|
|
235
|
+
}
|
|
236
|
+
function hasOAuthPopupOpener() {
|
|
237
|
+
try {
|
|
238
|
+
return Boolean(window.opener && !window.opener.closed);
|
|
239
|
+
} catch {
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
//#endregion
|
|
244
|
+
//#region src/browser/app-connect-controller/utils/iframe-utils.ts
|
|
245
|
+
/**
|
|
246
|
+
* Returns `true` when the app runs inside a parent frame (same-origin
|
|
247
|
+
* or cross-origin). Cross-origin parent access throws; treat that as
|
|
248
|
+
* embedded so OAuth uses a popup instead of a top-level redirect.
|
|
249
|
+
*/
|
|
250
|
+
function isAppEmbeddedInIframe() {
|
|
251
|
+
try {
|
|
252
|
+
return window.self !== window.top;
|
|
253
|
+
} catch {
|
|
254
|
+
return true;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
//#endregion
|
|
258
|
+
//#region src/browser/app-connect-controller/utils/resolve-oauth-connect-mode.ts
|
|
259
|
+
/**
|
|
260
|
+
* Maps the configured {@link OAuthConnectMode} to the concrete connect
|
|
261
|
+
* behavior for the current browsing context.
|
|
262
|
+
*/
|
|
263
|
+
function resolveOAuthConnectMode(options) {
|
|
264
|
+
const mode = options.oauthConnectMode ?? "auto";
|
|
265
|
+
if (mode === "popup") return "popup";
|
|
266
|
+
if (mode === "redirect") return "redirect";
|
|
267
|
+
return isAppEmbeddedInIframe() ? "popup" : "redirect";
|
|
268
|
+
}
|
|
269
|
+
//#endregion
|
|
270
|
+
//#region src/browser/app-connect-controller/utils/timeout-utils.ts
|
|
271
|
+
function delay(ms) {
|
|
272
|
+
if (ms <= 0) return Promise.resolve();
|
|
273
|
+
return new Promise((resolve) => {
|
|
274
|
+
setTimeout(resolve, ms);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/browser/app-connect-controller/connect-start.ts
|
|
279
|
+
/** Extra wait before redirect so the connect progress UI is visible; set to `0` to disable. */
|
|
280
|
+
const ARTIFICIAL_CONNECT_REDIRECT_DELAY_MS = 500;
|
|
281
|
+
/**
|
|
282
|
+
* Begins the OAuth connect flow:
|
|
283
|
+
*
|
|
284
|
+
* 1. Calls the SDK's `auth/init-session` route to mint a fresh PKCE
|
|
285
|
+
* verifier + state and obtain HubSpot's `authorize` URL.
|
|
286
|
+
* 2. Navigates to that URL via full-page redirect, or opens it in a
|
|
287
|
+
* popup when embedded in an iframe or when `oauthConnectMode` is
|
|
288
|
+
* `'popup'`.
|
|
289
|
+
*
|
|
290
|
+
* The `return_path` is the current path + query so the user lands
|
|
291
|
+
* back where they started after authorizing (redirect mode only).
|
|
292
|
+
*
|
|
293
|
+
* Throws when the init call fails. Does not return after a redirect
|
|
294
|
+
* begins because the page is unloaded.
|
|
295
|
+
*/
|
|
296
|
+
async function startHubSpotConnection(context) {
|
|
297
|
+
const { config } = context;
|
|
298
|
+
const returnPath = `${window.location.pathname}${window.location.search}`;
|
|
299
|
+
const initUrl = new URL(`${config.hubSpotConnectBaseUrl}/auth/init-session`, window.location.origin);
|
|
300
|
+
initUrl.searchParams.set("return_path", returnPath);
|
|
301
|
+
const initResponse = await fetch(initUrl.toString(), { credentials: "include" });
|
|
302
|
+
if (!initResponse.ok) throw new Error(`Failed to init session: ${initResponse.status}`);
|
|
303
|
+
const { authorization_url: authorizationUrl } = await initResponse.json();
|
|
304
|
+
await delay(ARTIFICIAL_CONNECT_REDIRECT_DELAY_MS);
|
|
305
|
+
if (resolveOAuthConnectMode(config.oauthConnectMode !== void 0 ? { oauthConnectMode: config.oauthConnectMode } : {}) === "popup") {
|
|
306
|
+
await waitForHubSpotOAuthPopup({
|
|
307
|
+
context,
|
|
308
|
+
authorizationUrl
|
|
309
|
+
});
|
|
310
|
+
return;
|
|
311
|
+
}
|
|
312
|
+
window.location.href = authorizationUrl;
|
|
313
|
+
}
|
|
314
|
+
//#endregion
|
|
315
|
+
//#region src/browser/app-connect-controller/default-session-storage.ts
|
|
316
|
+
/**
|
|
317
|
+
* Builds a `SessionStorage` adapter that delegates to the global
|
|
318
|
+
* `sessionStorage` object exposed by browsers. The controller uses
|
|
319
|
+
* this when no custom storage is supplied (e.g. for tests or non-DOM
|
|
320
|
+
* environments).
|
|
321
|
+
*/
|
|
322
|
+
function createDefaultSessionStorage() {
|
|
323
|
+
return {
|
|
324
|
+
setItem: (key, value) => {
|
|
325
|
+
sessionStorage.setItem(key, value);
|
|
326
|
+
},
|
|
327
|
+
getItem: (key) => {
|
|
328
|
+
return sessionStorage.getItem(key);
|
|
329
|
+
},
|
|
330
|
+
removeItem: (key) => {
|
|
331
|
+
sessionStorage.removeItem(key);
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
//#endregion
|
|
166
336
|
//#region src/browser/app-connect-controller/disconnect.ts
|
|
167
337
|
/**
|
|
168
338
|
* Disconnect flow:
|
|
@@ -214,23 +384,18 @@ async function disconnectFromHubSpot(context) {
|
|
|
214
384
|
* On `controller.start()`:
|
|
215
385
|
*
|
|
216
386
|
* 1. If the browser has been redirected back to the SDK's frontend
|
|
217
|
-
* OAuth callback path (`
|
|
218
|
-
* `?
|
|
219
|
-
*
|
|
220
|
-
*
|
|
221
|
-
*
|
|
222
|
-
*
|
|
223
|
-
*
|
|
224
|
-
*
|
|
225
|
-
*
|
|
226
|
-
*
|
|
227
|
-
* 2. Pick up `?__hs_expires_at` from `window.location` (placed there
|
|
228
|
-
* by step 1, or by an in-progress refresh hop), persist it to the
|
|
229
|
-
* controller's store + sessionStorage, and strip it from the
|
|
230
|
-
* address bar so it isn't logged or bookmarked.
|
|
387
|
+
* OAuth callback path (`/__hubspot_oauth_callback`) with `?code` +
|
|
388
|
+
* `?state`:
|
|
389
|
+
* - **Redirect flow** (no `window.opener`): POST to `auth/complete`
|
|
390
|
+
* from this window, persist `expires_at`, and `history.replaceState`
|
|
391
|
+
* to `return_path`.
|
|
392
|
+
* - **Popup flow** (`window.opener` present): relay `code` + `state`
|
|
393
|
+
* to the opener via `postMessage` and close. The opener POSTs to
|
|
394
|
+
* `auth/complete` so partitioned cookies match `init-session`.
|
|
395
|
+
* 2. Pick up `?__hs_expires_at` from `window.location` (refresh hop),
|
|
396
|
+
* persist it, and strip it from the address bar.
|
|
231
397
|
*
|
|
232
|
-
* A no-op when neither set of parameters is present
|
|
233
|
-
* load other than the OAuth return trip).
|
|
398
|
+
* A no-op when neither set of parameters is present.
|
|
234
399
|
*/
|
|
235
400
|
async function initAppConnect(context) {
|
|
236
401
|
await consumeOAuthCallback(context);
|
|
@@ -241,26 +406,21 @@ async function consumeOAuthCallback(context) {
|
|
|
241
406
|
const code = params.get(AUTH_COMPLETE_CODE_PARAM);
|
|
242
407
|
const state = params.get(AUTH_COMPLETE_STATE_PARAM);
|
|
243
408
|
if (!code || !state) return;
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
try {
|
|
249
|
-
response = await fetch(completeUrl.toString(), {
|
|
250
|
-
method: "POST",
|
|
251
|
-
credentials: "include"
|
|
409
|
+
if (hasOAuthPopupOpener()) {
|
|
410
|
+
relayOAuthCallbackToOpener({
|
|
411
|
+
code,
|
|
412
|
+
state
|
|
252
413
|
});
|
|
253
|
-
|
|
254
|
-
clearSessionStorage(context);
|
|
255
|
-
throw new Error(`Failed to complete HubSpot OAuth: ${err instanceof Error ? err.message : String(err)}`);
|
|
414
|
+
return;
|
|
256
415
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
416
|
+
const { expires_at: expiresAt, return_path: returnPath } = await completeHubSpotOAuthSession(context, {
|
|
417
|
+
code,
|
|
418
|
+
state
|
|
419
|
+
});
|
|
420
|
+
storeExpiresAt({
|
|
421
|
+
context,
|
|
422
|
+
expiresAtMs: expiresAt
|
|
423
|
+
});
|
|
264
424
|
const targetUrl = new URL(returnPath, window.location.origin);
|
|
265
425
|
history.replaceState(null, "", `${targetUrl.pathname}${targetUrl.search}${targetUrl.hash}`);
|
|
266
426
|
}
|
|
@@ -543,4 +703,4 @@ function createAppConnectController(options) {
|
|
|
543
703
|
//#endregion
|
|
544
704
|
export { createLogger as n, createAppConnectController as t };
|
|
545
705
|
|
|
546
|
-
//# sourceMappingURL=create-
|
|
706
|
+
//# sourceMappingURL=create-D-oTtxX-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-D-oTtxX-.js","names":["disconnectFromHubSpot","runDisconnectFromHubSpot"],"sources":["../../src/shared/logger.ts","../../src/shared/constants.ts","../../src/browser/app-connect-controller/constants.ts","../../src/browser/app-connect-controller/utils/session-utils.ts","../../src/browser/app-connect-controller/oauth-complete.ts","../../src/browser/app-connect-controller/oauth-popup.ts","../../src/browser/app-connect-controller/utils/iframe-utils.ts","../../src/browser/app-connect-controller/utils/resolve-oauth-connect-mode.ts","../../src/browser/app-connect-controller/utils/timeout-utils.ts","../../src/browser/app-connect-controller/connect-start.ts","../../src/browser/app-connect-controller/default-session-storage.ts","../../src/browser/app-connect-controller/disconnect.ts","../../src/browser/app-connect-controller/init.ts","../../src/browser/app-connect-controller/refresh.ts","../../src/browser/app-connect-controller/utils/memoize-utils.ts","../../src/browser/app-connect-controller/utils/store-utils.ts","../../src/browser/app-connect-controller/view-state.ts","../../src/browser/app-connect-controller/create.ts"],"sourcesContent":["/**\n * Pluggable logger contract used by the SDK on both the browser and\n * server. Consumers can pass `console`-like loggers, structured\n * loggers (pino / winston / etc.) or no-op stubs in tests.\n */\nexport interface Logger {\n debug: (message: string, ...args: unknown[]) => void;\n info: (message: string, ...args: unknown[]) => void;\n warn: (message: string, ...args: unknown[]) => void;\n error: (message: string, ...args: unknown[]) => void;\n}\n\nfunction formatPrefix(name: string): string {\n return `[${name}]`;\n}\n\n/**\n * Creates a console-backed logger that prefixes every line with the\n * supplied `name`. Used as the default when no custom logger is\n * provided.\n */\nexport function createLogger(name: string): Logger {\n const prefix = formatPrefix(name);\n return {\n debug: (message, ...args) => {\n console.debug(prefix, message, ...args);\n },\n info: (message, ...args) => {\n console.info(prefix, message, ...args);\n },\n warn: (message, ...args) => {\n console.warn(prefix, message, ...args);\n },\n error: (message, ...args) => {\n console.error(prefix, message, ...args);\n },\n };\n}\n\n/**\n * Logger that swallows every message. Convenient for tests and for\n * the SDK's server-side handlers when no logger is provided by the\n * host application.\n */\nexport const noopLogger: Logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n};\n","/**\n * Constants whose values are part of the contract between the browser\n * controller and the server-side hubspot-connect routes. Both halves\n * import from this module so the wire format stays in sync.\n */\n\n/**\n * Query parameter on the OAuth return URL that carries the new access\n * token's expiry (Unix epoch milliseconds). The browser controller\n * sets this in the URL after a successful `auth/complete` call and\n * then strips it during `initAppConnect` via `history.replaceState`.\n */\nexport const EXPIRES_AT_URL_PARAM = '__hs_expires_at';\n\n/**\n * Path the browser visits after HubSpot's authorize endpoint\n * redirects back to the app. Mounted on the **frontend** origin (not\n * the SDK's edge function host) so all OAuth-related cookies live in\n * the `(frontend, edge)` CHIPS partition.\n *\n * The SDK's `auth/init-session` builds the OAuth `redirect_uri` as\n * `${requestOrigin}${HUBSPOT_FRONTEND_CALLBACK_PATH}`. The browser\n * controller, on `start()`, recognizes this path on `window.location`\n * and forwards `?code` + `?state` to the SDK's `auth/complete`\n * endpoint via a credentialed cross-site fetch. The host app must\n * register `${app_origin}${HUBSPOT_FRONTEND_CALLBACK_PATH}` as a\n * redirect URI in its HubSpot app settings.\n */\nexport const OAUTH_CALLBACK_PATH = '/__hubspot_oauth_callback';\n\n/**\n * Query parameter on the `auth/complete` POST request carrying the\n * authorization `code` HubSpot returned to the frontend callback.\n */\nexport const AUTH_COMPLETE_CODE_PARAM = 'code';\n\n/**\n * Query parameter on the `auth/complete` POST request carrying the\n * OAuth `state` HubSpot echoed back to the frontend callback.\n */\nexport const AUTH_COMPLETE_STATE_PARAM = 'state';\n\n/**\n * `postMessage` `data.type` value the OAuth popup sends to its opener\n * with the authorization `code` and `state` from the callback URL. The\n * opener POSTs them to `auth/complete` so credentialed cookies stay in\n * the same CHIPS partition as `auth/init-session`.\n */\nexport const OAUTH_POPUP_CALLBACK_MESSAGE_TYPE =\n 'hubspot-app-connect:oauth-callback';\n","export { EXPIRES_AT_URL_PARAM } from '../../shared/constants.ts';\n\n/**\n * Key the controller persists the access-token `expiresAt` (Unix\n * epoch milliseconds) under in `sessionStorage`. Survives full-page\n * navigations within the same tab.\n */\nexport const EXPIRES_AT_KEY = 'hubspot_token_expires_at';\n\n/**\n * Number of milliseconds before `expiresAt` that the refresh\n * scheduler attempts to mint a new access token. 60s is comfortably\n * larger than typical network latency without burning lifetime.\n */\nexport const REFRESH_BUFFER_MS = 60_000;\n","import { EXPIRES_AT_KEY } from '../constants.ts';\nimport type { AppConnectContext } from '../types.ts';\n\ninterface StoreExpiresAtOptions {\n context: AppConnectContext;\n expiresAtMs: number;\n}\n\n/**\n * Persists the access-token `expiresAt` (Unix epoch milliseconds) to\n * both the in-memory store and `sessionStorage` so it survives\n * full-page navigations within the same tab.\n */\nexport function storeExpiresAt(options: StoreExpiresAtOptions): void {\n const { context, expiresAtMs } = options;\n context.store.setState({ expiresAt: expiresAtMs });\n context.sessionStorage.setItem(EXPIRES_AT_KEY, String(expiresAtMs));\n}\n\n/**\n * Reads the persisted `expiresAt` from `sessionStorage`. Removes the\n * value (and returns `null`) if it is malformed or already expired,\n * so a stale entry never reactivates a dead session.\n */\nexport function getExpiresAtFromSessionStorage(\n context: AppConnectContext\n): number | null {\n const raw = context.sessionStorage.getItem(EXPIRES_AT_KEY);\n if (!raw) return null;\n const val = parseInt(raw, 10);\n if (isNaN(val)) {\n context.sessionStorage.removeItem(EXPIRES_AT_KEY);\n return null;\n }\n if (Date.now() > val) {\n context.sessionStorage.removeItem(EXPIRES_AT_KEY);\n return null;\n }\n return val;\n}\n\n/**\n * Clears the persisted session-storage state. Called on disconnect.\n */\nexport function clearSessionStorage(context: AppConnectContext): void {\n context.sessionStorage.removeItem(EXPIRES_AT_KEY);\n}\n\n/**\n * Returns `true` when the controller has an `expiresAt` whose value\n * is still in the future. Used both to drive the UI status and to\n * decide whether the refresh scheduler should run.\n */\nexport function isClientSessionActive(context: AppConnectContext): boolean {\n const state = context.store.getSnapshot();\n const expiresAt = state.expiresAt;\n return expiresAt !== null && Date.now() < expiresAt;\n}\n","import {\n AUTH_COMPLETE_CODE_PARAM,\n AUTH_COMPLETE_STATE_PARAM,\n} from '../../shared/constants.ts';\nimport type { AuthCompleteResponse } from '../../shared/wire-types.ts';\nimport type { AppConnectContext } from './types.ts';\nimport { clearSessionStorage } from './utils/session-utils.ts';\n\ninterface CompleteHubSpotOAuthSessionOptions {\n code: string;\n state: string;\n}\n\n/**\n * Finishes the OAuth token exchange by POSTing `code` and `state` to the\n * SDK's `auth/complete` route with credentialed cookies from the current\n * browsing context (must match the partition used by `auth/init-session`).\n */\nexport async function completeHubSpotOAuthSession(\n context: AppConnectContext,\n options: CompleteHubSpotOAuthSessionOptions\n): Promise<AuthCompleteResponse> {\n const { code, state } = options;\n\n const completeUrl = new URL(\n `${context.config.hubSpotConnectBaseUrl}/auth/complete`,\n window.location.origin\n );\n completeUrl.searchParams.set(AUTH_COMPLETE_CODE_PARAM, code);\n completeUrl.searchParams.set(AUTH_COMPLETE_STATE_PARAM, state);\n\n let response: Response;\n try {\n response = await fetch(completeUrl.toString(), {\n method: 'POST',\n credentials: 'include',\n });\n } catch (err) {\n clearSessionStorage(context);\n throw new Error(\n `Failed to complete HubSpot OAuth: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n\n if (!response.ok) {\n clearSessionStorage(context);\n throw new Error(\n `Failed to complete HubSpot OAuth: ${response.status} ${response.statusText}`\n );\n }\n\n return (await response.json()) as AuthCompleteResponse;\n}\n","import { OAUTH_POPUP_CALLBACK_MESSAGE_TYPE } from '../../shared/constants.ts';\nimport { completeHubSpotOAuthSession } from './oauth-complete.ts';\nimport type { AppConnectContext } from './types.ts';\nimport { storeExpiresAt } from './utils/session-utils.ts';\n\nconst OAUTH_POPUP_WINDOW_NAME = 'hubspot-app-connect-oauth';\nconst OAUTH_POPUP_POLL_INTERVAL_MS = 300;\n\ninterface OAuthPopupCallbackMessage {\n type: typeof OAUTH_POPUP_CALLBACK_MESSAGE_TYPE;\n code: string;\n state: string;\n}\n\ninterface WaitForHubSpotOAuthPopupOptions {\n context: AppConnectContext;\n authorizationUrl: string;\n}\n\ninterface RelayOAuthCallbackToOpenerOptions {\n code: string;\n state: string;\n}\n\nfunction isOAuthPopupCallbackMessage(\n data: unknown\n): data is OAuthPopupCallbackMessage {\n if (typeof data !== 'object' || data === null) return false;\n const record = data as Record<string, unknown>;\n return (\n record.type === OAUTH_POPUP_CALLBACK_MESSAGE_TYPE &&\n typeof record.code === 'string' &&\n record.code.length > 0 &&\n typeof record.state === 'string' &&\n record.state.length > 0\n );\n}\n\n/**\n * Opens HubSpot's authorize URL in a popup and waits for the callback\n * page to relay `code` + `state` back. The opener POSTs to\n * `auth/complete` so credentialed cookies use the same CHIPS partition\n * as `auth/init-session`.\n */\nexport async function waitForHubSpotOAuthPopup(\n options: WaitForHubSpotOAuthPopupOptions\n): Promise<void> {\n const { context, authorizationUrl } = options;\n const targetOrigin = window.location.origin;\n\n return new Promise<void>((resolve, reject) => {\n let popup: Window | null = null;\n let pollTimer: ReturnType<typeof setInterval> | undefined;\n let isSettled = false;\n\n const cleanup = () => {\n window.removeEventListener('message', onMessage);\n if (pollTimer !== undefined) clearInterval(pollTimer);\n };\n\n const settleSuccess = (expiresAtMs: number) => {\n if (isSettled) return;\n isSettled = true;\n cleanup();\n storeExpiresAt({ context, expiresAtMs });\n context.store.setState({ isSessionConnected: true, error: null });\n resolve();\n };\n\n const settleFailure = (message: string) => {\n if (isSettled) return;\n isSettled = true;\n cleanup();\n try {\n popup?.close();\n } catch {\n // ignore close errors\n }\n reject(new Error(message));\n };\n\n const onMessage = (event: MessageEvent) => {\n if (event.origin !== targetOrigin) return;\n if (!isOAuthPopupCallbackMessage(event.data)) return;\n\n void (async () => {\n try {\n const body = await completeHubSpotOAuthSession(context, {\n code: event.data.code,\n state: event.data.state,\n });\n settleSuccess(body.expires_at);\n } catch (err) {\n const message =\n err instanceof Error ? err.message : 'HubSpot OAuth failed';\n settleFailure(message);\n }\n })();\n };\n\n window.addEventListener('message', onMessage);\n\n popup = window.open(\n authorizationUrl,\n OAUTH_POPUP_WINDOW_NAME,\n 'popup=yes,width=600,height=700'\n );\n if (!popup) {\n settleFailure('Popup blocked. Allow popups for this site and try again.');\n return;\n }\n\n pollTimer = setInterval(() => {\n if (popup?.closed) {\n settleFailure('Connect to HubSpot was cancelled.');\n }\n }, OAUTH_POPUP_POLL_INTERVAL_MS);\n });\n}\n\n/**\n * Called from the OAuth callback page inside the popup. Relays `code`\n * and `state` to the opener (which runs `auth/complete`) and closes.\n */\nexport function relayOAuthCallbackToOpener(\n options: RelayOAuthCallbackToOpenerOptions\n): boolean {\n const { code, state } = options;\n const opener = window.opener;\n if (!opener || opener.closed) return false;\n\n const message: OAuthPopupCallbackMessage = {\n type: OAUTH_POPUP_CALLBACK_MESSAGE_TYPE,\n code,\n state,\n };\n opener.postMessage(message, window.location.origin);\n try {\n window.close();\n } catch {\n // ignore close errors\n }\n return true;\n}\n\nexport function hasOAuthPopupOpener(): boolean {\n try {\n return Boolean(window.opener && !window.opener.closed);\n } catch {\n return false;\n }\n}\n","/**\n * Returns `true` when the app runs inside a parent frame (same-origin\n * or cross-origin). Cross-origin parent access throws; treat that as\n * embedded so OAuth uses a popup instead of a top-level redirect.\n */\nexport function isAppEmbeddedInIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n","import type { OAuthConnectMode } from '../../types.ts';\nimport { isAppEmbeddedInIframe } from './iframe-utils.ts';\n\nexport type ResolvedOAuthConnectMode = 'redirect' | 'popup';\n\ninterface ResolveOAuthConnectModeOptions {\n oauthConnectMode?: OAuthConnectMode;\n}\n\n/**\n * Maps the configured {@link OAuthConnectMode} to the concrete connect\n * behavior for the current browsing context.\n */\nexport function resolveOAuthConnectMode(\n options: ResolveOAuthConnectModeOptions\n): ResolvedOAuthConnectMode {\n const mode = options.oauthConnectMode ?? 'auto';\n if (mode === 'popup') return 'popup';\n if (mode === 'redirect') return 'redirect';\n return isAppEmbeddedInIframe() ? 'popup' : 'redirect';\n}\n","export function delay(ms: number): Promise<void> {\n if (ms <= 0) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n","import type { InitSessionResponse } from '../../shared/wire-types.ts';\nimport { waitForHubSpotOAuthPopup } from './oauth-popup.ts';\nimport type { AppConnectContext } from './types.ts';\nimport { resolveOAuthConnectMode } from './utils/resolve-oauth-connect-mode.ts';\nimport { delay } from './utils/timeout-utils.ts';\n\n/** Extra wait before redirect so the connect progress UI is visible; set to `0` to disable. */\nconst ARTIFICIAL_CONNECT_REDIRECT_DELAY_MS = 500;\n\n/**\n * Begins the OAuth connect flow:\n *\n * 1. Calls the SDK's `auth/init-session` route to mint a fresh PKCE\n * verifier + state and obtain HubSpot's `authorize` URL.\n * 2. Navigates to that URL via full-page redirect, or opens it in a\n * popup when embedded in an iframe or when `oauthConnectMode` is\n * `'popup'`.\n *\n * The `return_path` is the current path + query so the user lands\n * back where they started after authorizing (redirect mode only).\n *\n * Throws when the init call fails. Does not return after a redirect\n * begins because the page is unloaded.\n */\nexport async function startHubSpotConnection(\n context: AppConnectContext\n): Promise<void> {\n const { config } = context;\n\n const returnPath = `${window.location.pathname}${window.location.search}`;\n\n const initUrl = new URL(\n `${config.hubSpotConnectBaseUrl}/auth/init-session`,\n window.location.origin\n );\n initUrl.searchParams.set('return_path', returnPath);\n\n const initResponse = await fetch(initUrl.toString(), {\n credentials: 'include',\n });\n if (!initResponse.ok)\n throw new Error(`Failed to init session: ${initResponse.status}`);\n const { authorization_url: authorizationUrl } =\n (await initResponse.json()) as InitSessionResponse;\n\n await delay(ARTIFICIAL_CONNECT_REDIRECT_DELAY_MS);\n\n const connectMode = resolveOAuthConnectMode(\n config.oauthConnectMode !== undefined\n ? { oauthConnectMode: config.oauthConnectMode }\n : {}\n );\n\n if (connectMode === 'popup') {\n await waitForHubSpotOAuthPopup({ context, authorizationUrl });\n return;\n }\n\n window.location.href = authorizationUrl;\n}\n","import type { SessionStorage } from './types.ts';\n\n/**\n * Builds a `SessionStorage` adapter that delegates to the global\n * `sessionStorage` object exposed by browsers. The controller uses\n * this when no custom storage is supplied (e.g. for tests or non-DOM\n * environments).\n */\nexport function createDefaultSessionStorage(): SessionStorage {\n return {\n setItem: (key, value) => {\n sessionStorage.setItem(key, value);\n },\n getItem: (key) => {\n return sessionStorage.getItem(key);\n },\n removeItem: (key) => {\n sessionStorage.removeItem(key);\n },\n };\n}\n","import type { LogoutResponse } from '../../shared/wire-types.ts';\nimport type { AppConnectContext } from './types.ts';\nimport { clearSessionStorage } from './utils/session-utils.ts';\n\n/**\n * Disconnect flow:\n *\n * 1. Calls the SDK's `auth/logout` route to revoke the upstream token\n * and clear the refresh-token cookie.\n * 2. Clears the local session-storage `expiresAt` entry.\n * 3. Updates the controller state to `disconnected` and navigates the\n * browser to the URL the server returned in `redirect_to`.\n *\n * Errors are caught, logged, and surfaced via the controller's\n * `error` field so the UI can show a retry state.\n */\nexport async function disconnectFromHubSpot(\n context: AppConnectContext\n): Promise<void> {\n const { config, logger, store } = context;\n logger.info('disconnectFromHubSpot: starting');\n store.setState({ error: null, isDisconnectInFlight: true });\n const { hubSpotConnectBaseUrl: appConnectBaseUrl } = config;\n\n try {\n clearSessionStorage(context);\n\n const response = await fetch(`${appConnectBaseUrl}/auth/logout`, {\n method: 'POST',\n credentials: 'include',\n });\n if (!response.ok) {\n throw new Error(`Logout failed: ${response.status}`);\n }\n const { redirect_to: redirectTo } =\n (await response.json()) as LogoutResponse;\n\n store.setState({\n expiresAt: null,\n isSessionConnected: false,\n isDisconnectInFlight: false,\n });\n\n window.location.href = redirectTo;\n logger.info('disconnectFromHubSpot: redirecting');\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Disconnect failed';\n logger.error('disconnectFromHubSpot: failed', err);\n store.setState({\n error: message,\n isDisconnectInFlight: false,\n });\n }\n}\n","import {\n AUTH_COMPLETE_CODE_PARAM,\n AUTH_COMPLETE_STATE_PARAM,\n OAUTH_CALLBACK_PATH,\n} from '../../shared/constants.ts';\nimport { completeHubSpotOAuthSession } from './oauth-complete.ts';\nimport {\n hasOAuthPopupOpener,\n relayOAuthCallbackToOpener,\n} from './oauth-popup.ts';\nimport type { AppConnectContext } from './types.ts';\nimport { storeExpiresAt } from './utils/session-utils.ts';\n\n/**\n * On `controller.start()`:\n *\n * 1. If the browser has been redirected back to the SDK's frontend\n * OAuth callback path (`/__hubspot_oauth_callback`) with `?code` +\n * `?state`:\n * - **Redirect flow** (no `window.opener`): POST to `auth/complete`\n * from this window, persist `expires_at`, and `history.replaceState`\n * to `return_path`.\n * - **Popup flow** (`window.opener` present): relay `code` + `state`\n * to the opener via `postMessage` and close. The opener POSTs to\n * `auth/complete` so partitioned cookies match `init-session`.\n * 2. Pick up `?__hs_expires_at` from `window.location` (refresh hop),\n * persist it, and strip it from the address bar.\n *\n * A no-op when neither set of parameters is present.\n */\nexport async function initAppConnect(\n context: AppConnectContext\n): Promise<void> {\n await consumeOAuthCallback(context);\n}\n\nasync function consumeOAuthCallback(context: AppConnectContext): Promise<void> {\n if (window.location.pathname !== OAUTH_CALLBACK_PATH) return;\n\n const params = new URLSearchParams(window.location.search);\n const code = params.get(AUTH_COMPLETE_CODE_PARAM);\n const state = params.get(AUTH_COMPLETE_STATE_PARAM);\n if (!code || !state) return;\n\n if (hasOAuthPopupOpener()) {\n relayOAuthCallbackToOpener({ code, state });\n return;\n }\n\n const body = await completeHubSpotOAuthSession(context, { code, state });\n const { expires_at: expiresAt, return_path: returnPath } = body;\n\n storeExpiresAt({ context, expiresAtMs: expiresAt });\n\n const targetUrl = new URL(returnPath, window.location.origin);\n history.replaceState(\n null,\n '',\n `${targetUrl.pathname}${targetUrl.search}${targetUrl.hash}`\n );\n}\n","import type { RefreshTokenResponse } from '../../shared/wire-types.ts';\nimport { REFRESH_BUFFER_MS } from './constants.ts';\nimport type { AppConnectContext } from './types.ts';\nimport {\n isClientSessionActive,\n storeExpiresAt,\n} from './utils/session-utils.ts';\n\n/**\n * Tear-down handle returned by {@link startRefreshScheduler}. Calling\n * `stop()` clears any pending refresh timer and unsubscribes from the\n * store so the controller can be garbage-collected.\n */\nexport interface RefreshSchedulerHandle {\n stop: () => void;\n}\n\nasync function refreshAccessToken(context: AppConnectContext): Promise<void> {\n const { config } = context;\n\n const refreshResponse = await fetch(\n `${config.hubSpotConnectBaseUrl}/auth/refresh`,\n {\n method: 'POST',\n credentials: 'include',\n }\n );\n if (!refreshResponse.ok) {\n throw new Error(`Refresh failed: ${refreshResponse.status}`);\n }\n const { expires_in: expiresInSeconds } =\n (await refreshResponse.json()) as RefreshTokenResponse;\n if (\n typeof expiresInSeconds !== 'number' ||\n !Number.isFinite(expiresInSeconds) ||\n expiresInSeconds <= 0\n ) {\n throw new Error('Refresh response missing or invalid expires_in');\n }\n const expiresAtMs = Date.now() + expiresInSeconds * 1000;\n\n storeExpiresAt({ context, expiresAtMs });\n}\n\n/**\n * Subscribes to store changes and (re)schedules a token refresh\n * whenever `expiresAt` moves. Returns a handle that the caller can\n * use to stop the scheduler when the controller is destroyed.\n */\nexport function startRefreshScheduler(\n context: AppConnectContext\n): RefreshSchedulerHandle {\n const { logger, store } = context;\n\n let refreshTimer: ReturnType<typeof setTimeout> | null = null;\n let stopped = false;\n\n const scheduleRefresh = () => {\n if (refreshTimer) {\n clearTimeout(refreshTimer);\n refreshTimer = null;\n }\n if (stopped) return;\n\n const state = store.getSnapshot();\n if (!state.isInitComplete || !state.isSessionConnected) {\n return;\n }\n\n const expiresAt = state.expiresAt;\n if (!expiresAt) {\n logger.debug('scheduleRefresh: no expiresAt, skipping');\n return;\n }\n const delayMs = Math.max(0, expiresAt - Date.now() - REFRESH_BUFFER_MS);\n logger.debug(\n 'scheduleRefresh: next refresh in ',\n (delayMs / 1000).toFixed(1),\n 's',\n {\n expiresAt,\n }\n );\n refreshTimer = setTimeout(() => {\n logger.debug('scheduleRefresh: timer fired, refreshing token');\n refreshTimer = null;\n if (stopped) return;\n\n void (async () => {\n try {\n await refreshAccessToken(context);\n if (stopped) return;\n if (isClientSessionActive(context)) {\n logger.info('token refresh: success, session still active');\n } else {\n logger.warn(\n 'token refresh: success but no active session in storage'\n );\n store.setState({ isSessionConnected: false });\n }\n } catch (err) {\n logger.error('token refresh: failed', err);\n if (stopped) return;\n store.setState({ isSessionConnected: false });\n }\n })();\n }, delayMs);\n };\n\n const unsubscribe = store.subscribe(() => {\n scheduleRefresh();\n });\n\n return {\n stop: () => {\n stopped = true;\n unsubscribe();\n if (refreshTimer) {\n clearTimeout(refreshTimer);\n refreshTimer = null;\n }\n },\n };\n}\n","/**\n * Wraps `fn` so that calls with the same input (compared via\n * `Object.is`) return the previous output without re-invoking `fn`.\n * The cache holds at most one entry, so this is safe to use for\n * derived view-state from a single store snapshot.\n *\n * Used by `getSnapshot` to keep the React state reference stable\n * between unrelated store updates — `useSyncExternalStore` would\n * otherwise re-render every consumer on every change.\n */\nexport function memoizeLast<TInput, TOutput>(\n fn: (input: TInput) => TOutput\n): (input: TInput) => TOutput {\n let lastInput: TInput;\n let lastOutput: TOutput;\n let hasValue = false;\n return (input: TInput): TOutput => {\n if (hasValue && Object.is(lastInput, input)) {\n return lastOutput;\n }\n lastInput = input;\n lastOutput = fn(input);\n hasValue = true;\n return lastOutput;\n };\n}\n","/**\n * Tiny external store used by the controller. Shaped to be compatible\n * with React's `useSyncExternalStore` while remaining usable outside\n * React.\n */\nexport interface Store<TState extends object> {\n /** Returns the current state. The reference changes on every update. */\n getSnapshot: () => Readonly<TState>;\n /**\n * Subscribes to state changes. Returns an unsubscribe function the\n * caller can invoke at teardown.\n */\n subscribe: (onChange: () => void) => () => void;\n /**\n * Merges `update` into the current state. When `update` is a\n * function, it receives the current state and returns a partial.\n * Listeners are only notified when at least one key actually\n * changed (shallow compare).\n */\n setState: (\n update:\n | Partial<TState>\n | ((prev: Readonly<TState>) => Partial<TState> | TState)\n ) => void;\n /** Reads a single key from the current state. */\n get: <K extends keyof TState>(key: K) => TState[K];\n /** Writes a single key. Listeners only fire when the value changes. */\n set: <K extends keyof TState>(key: K, value: TState[K]) => void;\n /**\n * Drops every listener and prevents future `setState`/`set` calls\n * from notifying. Used by `controller.destroy()`.\n */\n destroy: () => void;\n}\n\nfunction shallowEqualState<TState extends object>(\n a: TState,\n b: TState\n): boolean {\n const keys = new Set([\n ...Object.keys(a),\n ...Object.keys(b),\n ] as (keyof TState)[]);\n for (const k of keys) {\n if (!Object.is(a[k], b[k])) {\n return false;\n }\n }\n return true;\n}\n\nfunction mergeState<TState extends object>(\n prev: TState,\n partial: Partial<TState>\n): TState {\n return { ...prev, ...partial } as TState;\n}\n\n/**\n * Creates a new {@link Store}. The store starts with a shallow copy\n * of `initialState`; subsequent mutations never touch the caller's\n * object.\n */\nexport function createStore<TState extends object>(\n initialState: TState\n): Store<TState> {\n let state: TState = { ...initialState };\n const listeners = new Set<() => void>();\n let destroyed = false;\n\n const notify = () => {\n for (const listener of listeners) {\n listener();\n }\n };\n\n return {\n getSnapshot() {\n return state as Readonly<TState>;\n },\n subscribe(onChange) {\n listeners.add(onChange);\n return () => {\n listeners.delete(onChange);\n };\n },\n setState(update) {\n if (destroyed) return;\n const patch =\n typeof update === 'function'\n ? update(state as Readonly<TState>)\n : update;\n if (typeof patch !== 'object' || patch == null) {\n return;\n }\n const next = mergeState(state, patch as Partial<TState>);\n if (shallowEqualState(state, next)) {\n return;\n }\n state = next;\n notify();\n },\n get(key) {\n return state[key];\n },\n set(key, value) {\n if (destroyed) return;\n if (Object.is(state[key], value)) {\n return;\n }\n state = { ...state, [key]: value } as TState;\n notify();\n },\n destroy() {\n destroyed = true;\n listeners.clear();\n },\n };\n}\n","import type { AppConnectState, AppConnectStatus } from '../types.ts';\nimport type { AppConnectInternalState } from './types.ts';\n\nconst noop = (): Promise<void> => Promise.resolve();\n\n/**\n * Snapshot returned by `getServerSnapshot` for SSR. Has stable\n * references and inert connect/disconnect actions because actions are\n * meaningless before hydration.\n */\nexport const SERVER_VIEW: AppConnectState = {\n status: 'initializing',\n error: null,\n connectToHubSpot: noop,\n disconnectFromHubSpot: noop,\n};\n\n/**\n * Reduces the boolean lifecycle flags into the user-facing\n * `AppConnectStatus` enum value. The order of checks matters:\n * disconnect-in-flight beats connect-in-flight (a transitional logout\n * shouldn't show a \"connecting\" spinner), and connected beats default.\n */\nexport function getDerivedStatus(\n state: AppConnectInternalState\n): AppConnectStatus {\n const {\n isInitComplete,\n isConnectInFlight,\n isSessionConnected,\n isDisconnectInFlight,\n } = state;\n if (!isInitComplete) {\n return 'initializing';\n }\n if (isDisconnectInFlight) return 'disconnecting';\n if (isConnectInFlight) return 'connecting';\n if (isSessionConnected) return 'connected';\n return 'disconnected';\n}\n","import { noopLogger, type Logger } from '../../shared/logger.ts';\nimport type {\n AppConnectBrowserConfig,\n AppConnectController,\n AppConnectState,\n} from '../types.ts';\nimport { startHubSpotConnection } from './connect-start.ts';\nimport { createDefaultSessionStorage } from './default-session-storage.ts';\nimport { disconnectFromHubSpot as runDisconnectFromHubSpot } from './disconnect.ts';\nimport { initAppConnect } from './init.ts';\nimport { startRefreshScheduler } from './refresh.ts';\nimport type {\n AppConnectContext,\n AppConnectInternalState,\n AppConnectStore,\n} from './types.ts';\nimport { memoizeLast } from './utils/memoize-utils.ts';\nimport {\n getExpiresAtFromSessionStorage,\n isClientSessionActive,\n} from './utils/session-utils.ts';\nimport { createStore } from './utils/store-utils.ts';\nimport { getDerivedStatus, SERVER_VIEW } from './view-state.ts';\n\n/**\n * Options accepted by {@link createAppConnectController}.\n */\nexport interface CreateAppConnectControllerOptions {\n /** Runtime configuration; see {@link AppConnectBrowserConfig}. */\n config: AppConnectBrowserConfig;\n /** Logger the controller uses for status/debug messages. */\n logger?: Logger;\n}\n\n/**\n * Creates an `AppConnectController`. Exactly one controller should be\n * shared by the entire app — the React provider takes the controller\n * as a prop and exposes it via context.\n *\n * The returned controller is inert until `start()` is called: nothing\n * is read from session storage, no refresh timer is scheduled, and no\n * fetches are issued. Tests can construct a controller and inspect\n * its initial snapshot without triggering side effects.\n */\nexport function createAppConnectController(\n options: CreateAppConnectControllerOptions\n): AppConnectController {\n const { config, logger = noopLogger } = options;\n const sessionStorage = createDefaultSessionStorage();\n const store: AppConnectStore = createStore<AppConnectInternalState>({\n isInitComplete: false,\n isConnectInFlight: false,\n isDisconnectInFlight: false,\n isSessionConnected: false,\n error: null,\n expiresAt: null,\n });\n const context: AppConnectContext = {\n config,\n logger,\n sessionStorage,\n store,\n };\n\n store.setState({ expiresAt: getExpiresAtFromSessionStorage(context) });\n\n let hasStarted = false;\n\n const connectToHubSpot = async () => {\n logger.info('connectToHubSpot: starting');\n store.setState({ error: null, isConnectInFlight: true });\n try {\n await startHubSpotConnection(context);\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Connection failed';\n logger.error('connectToHubSpot: failed', err);\n store.setState({ error: message });\n } finally {\n logger.debug(\n 'connectToHubSpot: connect flow step finished (may redirect to HubSpot)'\n );\n store.setState({ isConnectInFlight: false });\n }\n };\n const disconnectFromHubSpot = () => runDisconnectFromHubSpot(context);\n\n const getViewStateMemoized = memoizeLast<\n Readonly<AppConnectInternalState>,\n AppConnectState\n >((storeState) => ({\n status: getDerivedStatus(storeState),\n error: storeState.error,\n connectToHubSpot,\n disconnectFromHubSpot,\n }));\n\n function getSnapshot() {\n return getViewStateMemoized(store.getSnapshot());\n }\n\n return {\n start() {\n if (hasStarted) {\n logger.debug('start skipped (already started)');\n return;\n }\n hasStarted = true;\n startRefreshScheduler(context);\n\n logger.info('start: initSdk (OAuth return handling if applicable)');\n void (async () => {\n try {\n await initAppConnect(context);\n logger.info('initSdk: completed without error');\n } catch (err) {\n logger.error('initSdk: failed', err);\n store.setState({\n error:\n err instanceof Error\n ? err.message\n : 'App Connect initialization failed',\n });\n } finally {\n const sessionActive = isClientSessionActive(context);\n logger.info('start: init complete, session active:', sessionActive);\n store.setState({\n isInitComplete: true,\n isSessionConnected: sessionActive,\n });\n }\n })();\n },\n subscribe: (fn) => store.subscribe(fn),\n getSnapshot,\n getServerSnapshot: () => SERVER_VIEW,\n };\n}\n"],"mappings":";AAY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;MACb,gBAAgB;MAChB,oBAAoB;KACtB,CAAC;IACH;GACF,GAAG;EACL;EACA,YAAY,OAAO,MAAM,UAAU,EAAE;EACrC;EACA,yBAAyB;CAC3B;AACF"}
|
package/dist/browser/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as AppConnectStatus, n as AppConnectController, r as AppConnectState, t as AppConnectBrowserConfig } from "./types-
|
|
1
|
+
import { a as OAuthConnectMode, i as AppConnectStatus, n as AppConnectController, r as AppConnectState, t as AppConnectBrowserConfig } from "./types-DkAmHcZt.js";
|
|
2
2
|
|
|
3
3
|
//#region src/shared/logger.d.ts
|
|
4
4
|
/**
|
|
@@ -461,5 +461,5 @@ declare const themeClass: string, themeVars: {
|
|
|
461
461
|
};
|
|
462
462
|
};
|
|
463
463
|
//#endregion
|
|
464
|
-
export { type AppConnectBrowserConfig, type AppConnectController, type AppConnectState, type AppConnectStatus, type CreateAppConnectControllerOptions, type Logger, createAppConnectController, createLogger, themeClass, themeVars };
|
|
464
|
+
export { type AppConnectBrowserConfig, type AppConnectController, type AppConnectState, type AppConnectStatus, type CreateAppConnectControllerOptions, type Logger, type OAuthConnectMode, createAppConnectController, createLogger, themeClass, themeVars };
|
|
465
465
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/browser/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as createLogger, t as createAppConnectController } from "./create-
|
|
1
|
+
import { n as createLogger, t as createAppConnectController } from "./create-D-oTtxX-.js";
|
|
2
2
|
import { n as themeVars, t as themeClass } from "./theme.css-CJbxi5hC.js";
|
|
3
3
|
export { createAppConnectController, createLogger, themeClass, themeVars };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { a as OAuthConnectMode } from "../types-DkAmHcZt.js";
|
|
1
2
|
import { ReactNode } from "react";
|
|
2
3
|
|
|
3
4
|
//#region src/browser/react/lovable/LovableHubSpotAppConnect.d.ts
|
|
@@ -14,6 +15,12 @@ interface LovableHubSpotAppConnectProps {
|
|
|
14
15
|
* @example `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/hubspot-connect`
|
|
15
16
|
*/
|
|
16
17
|
hubSpotConnectBaseUrl: string;
|
|
18
|
+
/**
|
|
19
|
+
* How connect navigates to HubSpot OAuth. Defaults to `'auto'` (popup
|
|
20
|
+
* when embedded in an iframe). Set to `'popup'` to test the popup flow
|
|
21
|
+
* without embedding.
|
|
22
|
+
*/
|
|
23
|
+
oauthConnectMode?: OAuthConnectMode;
|
|
17
24
|
/** Title text rendered in the standard SDK header. */
|
|
18
25
|
title: string;
|
|
19
26
|
/** Content rendered when the controller is in the `connected` state. */
|
|
@@ -34,6 +41,7 @@ interface LovableHubSpotAppConnectProps {
|
|
|
34
41
|
*/
|
|
35
42
|
declare function LovableHubSpotAppConnect({
|
|
36
43
|
hubSpotConnectBaseUrl,
|
|
44
|
+
oauthConnectMode,
|
|
37
45
|
title,
|
|
38
46
|
connected,
|
|
39
47
|
disconnectedMessage
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as createAppConnectController } from "../create-
|
|
1
|
+
import { t as createAppConnectController } from "../create-D-oTtxX-.js";
|
|
2
2
|
import { t as HubSpotAppConnect } from "../HubSpotAppConnect-DFe9b90e.js";
|
|
3
3
|
import { useRef } from "react";
|
|
4
4
|
import { jsx } from "react/jsx-runtime";
|
|
@@ -11,9 +11,12 @@ import { jsx } from "react/jsx-runtime";
|
|
|
11
11
|
* canonical `HubSpotAppConnect` from `@hubspot/app-connect-sdk/react`
|
|
12
12
|
* instead.
|
|
13
13
|
*/
|
|
14
|
-
function LovableHubSpotAppConnect({ hubSpotConnectBaseUrl, title, connected, disconnectedMessage }) {
|
|
14
|
+
function LovableHubSpotAppConnect({ hubSpotConnectBaseUrl, oauthConnectMode, title, connected, disconnectedMessage }) {
|
|
15
15
|
const controllerRef = useRef(null);
|
|
16
|
-
if (controllerRef.current === null) controllerRef.current = createAppConnectController({ config: {
|
|
16
|
+
if (controllerRef.current === null) controllerRef.current = createAppConnectController({ config: {
|
|
17
|
+
hubSpotConnectBaseUrl,
|
|
18
|
+
oauthConnectMode: oauthConnectMode || "auto"
|
|
19
|
+
} });
|
|
17
20
|
return /* @__PURE__ */ jsx(HubSpotAppConnect, {
|
|
18
21
|
title,
|
|
19
22
|
connected,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lovable.js","names":[],"sources":["../../../src/browser/react/lovable/LovableHubSpotAppConnect.tsx"],"sourcesContent":["import { useRef, type ReactNode } from 'react';\n\nimport { createAppConnectController } from '../../app-connect-controller/create.ts';\nimport type { AppConnectController } from '../../types.ts';\nimport { HubSpotAppConnect } from '../components/HubSpotAppConnect/HubSpotAppConnect.tsx';\n\n/**\n * Props accepted by {@link LovableHubSpotAppConnect}.\n */\nexport interface LovableHubSpotAppConnectProps {\n /**\n * URL prefix the Lovable backend mounts the SDK's `hubspot-connect`\n * routes on (no trailing slash). In a Vite + Supabase Lovable app,\n * read the Supabase origin from `import.meta.env.VITE_SUPABASE_URL`\n * and append `/functions/v1/hubspot-connect`.\n *\n * @example `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/hubspot-connect`\n */\n hubSpotConnectBaseUrl: string;\n /** Title text rendered in the standard SDK header. */\n title: string;\n /** Content rendered when the controller is in the `connected` state. */\n connected: ReactNode;\n /**\n * Description text rendered inside the SDK-owned disconnected card,\n * above the primary \"Connect to HubSpot\" button.\n */\n disconnectedMessage: ReactNode;\n}\n\n/**\n * Lovable-preset variant of `HubSpotAppConnect`. Takes\n * `hubSpotConnectBaseUrl` as a prop and lazily creates a single\n * controller per component instance. Callers that need a custom\n * logger or full control over controller construction should use the\n * canonical `HubSpotAppConnect` from `@hubspot/app-connect-sdk/react`\n * instead.\n */\nexport function LovableHubSpotAppConnect({\n hubSpotConnectBaseUrl,\n title,\n connected,\n disconnectedMessage,\n}: LovableHubSpotAppConnectProps) {\n // useRef null-check pattern: create the controller exactly once per\n // component instance and never recreate it when props change. The\n // first hubSpotConnectBaseUrl wins; later changes are ignored, which\n // matches the \"one controller per app\" semantics the canonical\n // HubSpotAppConnect also enforces.\n const controllerRef = useRef<AppConnectController | null>(null);\n if (controllerRef.current === null) {\n controllerRef.current = createAppConnectController({\n config: {
|
|
1
|
+
{"version":3,"file":"lovable.js","names":[],"sources":["../../../src/browser/react/lovable/LovableHubSpotAppConnect.tsx"],"sourcesContent":["import { useRef, type ReactNode } from 'react';\n\nimport { createAppConnectController } from '../../app-connect-controller/create.ts';\nimport type { AppConnectController, OAuthConnectMode } from '../../types.ts';\nimport { HubSpotAppConnect } from '../components/HubSpotAppConnect/HubSpotAppConnect.tsx';\n\n/**\n * Props accepted by {@link LovableHubSpotAppConnect}.\n */\nexport interface LovableHubSpotAppConnectProps {\n /**\n * URL prefix the Lovable backend mounts the SDK's `hubspot-connect`\n * routes on (no trailing slash). In a Vite + Supabase Lovable app,\n * read the Supabase origin from `import.meta.env.VITE_SUPABASE_URL`\n * and append `/functions/v1/hubspot-connect`.\n *\n * @example `${import.meta.env.VITE_SUPABASE_URL}/functions/v1/hubspot-connect`\n */\n hubSpotConnectBaseUrl: string;\n /**\n * How connect navigates to HubSpot OAuth. Defaults to `'auto'` (popup\n * when embedded in an iframe). Set to `'popup'` to test the popup flow\n * without embedding.\n */\n oauthConnectMode?: OAuthConnectMode;\n /** Title text rendered in the standard SDK header. */\n title: string;\n /** Content rendered when the controller is in the `connected` state. */\n connected: ReactNode;\n /**\n * Description text rendered inside the SDK-owned disconnected card,\n * above the primary \"Connect to HubSpot\" button.\n */\n disconnectedMessage: ReactNode;\n}\n\n/**\n * Lovable-preset variant of `HubSpotAppConnect`. Takes\n * `hubSpotConnectBaseUrl` as a prop and lazily creates a single\n * controller per component instance. Callers that need a custom\n * logger or full control over controller construction should use the\n * canonical `HubSpotAppConnect` from `@hubspot/app-connect-sdk/react`\n * instead.\n */\nexport function LovableHubSpotAppConnect({\n hubSpotConnectBaseUrl,\n oauthConnectMode,\n title,\n connected,\n disconnectedMessage,\n}: LovableHubSpotAppConnectProps) {\n // useRef null-check pattern: create the controller exactly once per\n // component instance and never recreate it when props change. The\n // first hubSpotConnectBaseUrl wins; later changes are ignored, which\n // matches the \"one controller per app\" semantics the canonical\n // HubSpotAppConnect also enforces.\n const controllerRef = useRef<AppConnectController | null>(null);\n if (controllerRef.current === null) {\n controllerRef.current = createAppConnectController({\n config: {\n hubSpotConnectBaseUrl,\n oauthConnectMode: oauthConnectMode || 'auto',\n },\n });\n }\n return (\n <HubSpotAppConnect\n title={title}\n connected={connected}\n disconnectedMessage={disconnectedMessage}\n controller={controllerRef.current}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;AA4CA,SAAgB,yBAAyB,EACvC,uBACA,kBACA,OACA,WACA,uBACgC;CAMhC,MAAM,gBAAgB,OAAoC,IAAI;CAC9D,IAAI,cAAc,YAAY,MAC5B,cAAc,UAAU,2BAA2B,EACjD,QAAQ;EACN;EACA,kBAAkB,oBAAoB;CACxC,EACF,CAAC;CAEH,OACE,oBAAC,mBAAD;EACS;EACI;EACU;EACrB,YAAY,cAAc;CAC3B,CAAA;AAEL"}
|
package/dist/browser/react.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as AppConnectController, r as AppConnectState } from "./types-
|
|
1
|
+
import { n as AppConnectController, r as AppConnectState } from "./types-DkAmHcZt.js";
|
|
2
2
|
import { ReactNode } from "react";
|
|
3
3
|
|
|
4
4
|
//#region src/browser/react/components/HubSpotAppConnect/HubSpotAppConnect.d.ts
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
//#region src/browser/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* How the browser navigates to HubSpot's OAuth authorize endpoint when
|
|
4
|
+
* the user calls `connectToHubSpot`.
|
|
5
|
+
*/
|
|
6
|
+
type OAuthConnectMode = 'auto' | 'redirect' | 'popup';
|
|
2
7
|
/**
|
|
3
8
|
* Runtime configuration for an `AppConnectController`. The browser
|
|
4
9
|
* controller uses these URLs to talk to the SDK's server-side OAuth
|
|
@@ -12,6 +17,15 @@ interface AppConnectBrowserConfig {
|
|
|
12
17
|
* @example '/functions/v1/hubspot-connect'
|
|
13
18
|
*/
|
|
14
19
|
hubSpotConnectBaseUrl: string;
|
|
20
|
+
/**
|
|
21
|
+
* Controls whether connect uses a full-page redirect or a popup.
|
|
22
|
+
*
|
|
23
|
+
* - `'auto'` (default): popup when the app is embedded in an iframe,
|
|
24
|
+
* full-page redirect otherwise.
|
|
25
|
+
* - `'redirect'`: always full-page redirect.
|
|
26
|
+
* - `'popup'`: always open a popup (useful for local iframe testing).
|
|
27
|
+
*/
|
|
28
|
+
oauthConnectMode?: OAuthConnectMode;
|
|
15
29
|
}
|
|
16
30
|
/**
|
|
17
31
|
* Public lifecycle of an `AppConnectController`. Every state in the
|
|
@@ -19,8 +33,7 @@ interface AppConnectBrowserConfig {
|
|
|
19
33
|
*
|
|
20
34
|
* - `initializing`: the controller hasn't finished `start()` yet.
|
|
21
35
|
* - `disconnected`: no active session, ready to call `connectToHubSpot`.
|
|
22
|
-
* - `connecting`: a connect flow is in flight (
|
|
23
|
-
* to redirect to HubSpot).
|
|
36
|
+
* - `connecting`: a connect flow is in flight (redirect or OAuth popup).
|
|
24
37
|
* - `connected`: a refresh-token cookie is present and the access
|
|
25
38
|
* token is being refreshed in the background.
|
|
26
39
|
* - `disconnecting`: a `disconnectFromHubSpot()` call is in flight.
|
|
@@ -36,9 +49,11 @@ interface AppConnectState {
|
|
|
36
49
|
/** Last error message that occurred, or `null` if no error. */
|
|
37
50
|
error: string | null;
|
|
38
51
|
/**
|
|
39
|
-
* Begins the OAuth connect flow. On success the browser
|
|
40
|
-
* to HubSpot's authorize endpoint
|
|
41
|
-
*
|
|
52
|
+
* Begins the OAuth connect flow. On success the browser either
|
|
53
|
+
* redirects to HubSpot's authorize endpoint or opens it in a popup
|
|
54
|
+
* (when embedded in an iframe or when `oauthConnectMode` is
|
|
55
|
+
* `'popup'`). The promise resolves when the popup flow completes, or
|
|
56
|
+
* just before a full-page redirect begins.
|
|
42
57
|
*/
|
|
43
58
|
connectToHubSpot: () => Promise<void>;
|
|
44
59
|
/**
|
|
@@ -75,5 +90,5 @@ interface AppConnectController {
|
|
|
75
90
|
start: () => void;
|
|
76
91
|
}
|
|
77
92
|
//#endregion
|
|
78
|
-
export { AppConnectStatus as i, AppConnectController as n, AppConnectState as r, AppConnectBrowserConfig as t };
|
|
79
|
-
//# sourceMappingURL=types-
|
|
93
|
+
export { OAuthConnectMode as a, AppConnectStatus as i, AppConnectController as n, AppConnectState as r, AppConnectBrowserConfig as t };
|
|
94
|
+
//# sourceMappingURL=types-DkAmHcZt.d.ts.map
|