@dataships/launcher 0.2.0 → 0.3.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.
@@ -1,4 +1,4 @@
1
1
  {
2
- "launcher.js": "sha384-G6itJsfiMshc5Sdg9NdFuI8cJxq4WCMsU19gsN9NxviUC7rxTApGRZ8lgvqXY5aG",
3
- "modules/alia-0.2.0.js": "sha384-jW/3r9fyQjBcLKnIiLSbASojfBstddKdOxHnOUtnHRvJBbaMuD3yDJprA0GaLkQv"
2
+ "launcher.js": "sha384-vwZeTLLmB6BK/WHxTbkMlHNo/f4TwOZGpTFhCMZdC7bA/LKSl7/Q9jlV6KB6hXLx",
3
+ "modules/alia-0.3.0.js": "sha384-xT/0dMdBCmn66PCdLNkknVwj2piQlxI2mc/AjrjFgbBLhXg776dyJRWNftzCB1+N"
4
4
  }
package/dist/launcher.js CHANGED
@@ -42,6 +42,23 @@
42
42
  return { datashipsSessionId, token, elements: refs };
43
43
  };
44
44
  var elementsOfType = (data, type) => data.elements.filter((element) => element.type === type);
45
+ var maxAgeMsOf = (response) => {
46
+ const directives = (response.headers.get("Cache-Control") ?? "").toLowerCase().split(",").map((directive) => directive.trim());
47
+ if (directives.includes("no-store") || directives.includes("no-cache"))
48
+ return 0;
49
+ for (const directive of directives) {
50
+ const seconds = /^max-age\s*=\s*"?(\d+)"?$/.exec(directive)?.[1];
51
+ if (seconds !== void 0) return Number(seconds) * 1e3;
52
+ }
53
+ return 0;
54
+ };
55
+ var outcomeOf = async (response) => {
56
+ if (response.status === 403) return { status: "refused" };
57
+ if (response.status !== 200) return { status: "failed" };
58
+ const data = parseElements(await response.json());
59
+ if (!data) return { status: "failed" };
60
+ return data.elements.length === 0 ? { status: "refused" } : { status: "ok", data };
61
+ };
45
62
  var fetchElements = async (fetchFn, baseUrl, publicKey) => {
46
63
  try {
47
64
  const response = await fetchFn(`${baseUrl}${ELEMENTS_PATH}`, {
@@ -49,13 +66,12 @@
49
66
  headers: { "x-api-key": publicKey },
50
67
  credentials: "omit"
51
68
  });
52
- if (response.status === 403) return { status: "refused" };
53
- if (response.status !== 200) return { status: "failed" };
54
- const data = parseElements(await response.json());
55
- if (!data) return { status: "failed" };
56
- return data.elements.length === 0 ? { status: "refused" } : { status: "ok", data };
69
+ return {
70
+ outcome: await outcomeOf(response),
71
+ maxAgeMs: maxAgeMsOf(response)
72
+ };
57
73
  } catch {
58
- return { status: "failed" };
74
+ return { outcome: { status: "failed" }, maxAgeMs: 0 };
59
75
  }
60
76
  };
61
77
 
@@ -77,18 +93,21 @@
77
93
  const entry = JSON.parse(raw);
78
94
  if (typeof entry.at !== "number" || now < entry.at || now - entry.at >= CACHE_TTL_MS)
79
95
  return null;
80
- if (entry.status === "refused") return { status: "refused" };
96
+ const at = entry.at;
97
+ const receivedAt = typeof entry.receivedAt === "number" && entry.receivedAt <= at ? entry.receivedAt : at;
98
+ if (entry.status === "refused")
99
+ return { answer: { status: "refused" }, at, receivedAt };
81
100
  const data = entry.status === "ok" ? parseElements(entry.data) : null;
82
- return data && data.elements.length > 0 ? { status: "ok", data } : null;
101
+ return data && data.elements.length > 0 ? { answer: { status: "ok", data }, at, receivedAt } : null;
83
102
  } catch {
84
103
  return null;
85
104
  }
86
105
  }
87
- write(answer, now) {
106
+ write(answer, now, receivedAt = now) {
88
107
  try {
89
108
  __privateGet(this, _win).sessionStorage.setItem(
90
109
  __privateGet(this, _key),
91
- JSON.stringify({ at: now, ...answer })
110
+ JSON.stringify({ at: now, receivedAt, ...answer })
92
111
  );
93
112
  } catch {
94
113
  }
@@ -147,11 +166,98 @@
147
166
  var MODULES = [
148
167
  {
149
168
  type: "ALIA_FORM",
150
- file: `modules/alia-${"0.2.0"}.js`,
169
+ file: `modules/alia-${"0.3.0"}.js`,
151
170
  watch: watchAlia
152
171
  }
153
172
  ];
154
173
 
174
+ // src/token.ts
175
+ var TOKEN_TTL_MS = 30 * 60 * 1e3;
176
+ var REFRESH_MARGIN_MS = 2 * 60 * 1e3;
177
+ var REFRESH_RETRY_DELAY_MS = 1e3;
178
+ var TOKEN_REFRESH_PATH = "/v1/elements/token/refresh";
179
+ var RefreshError = class extends Error {
180
+ constructor(message, transient) {
181
+ super(message);
182
+ this.transient = transient;
183
+ }
184
+ };
185
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
186
+ var createElementsToken = (options) => {
187
+ let token = options.token;
188
+ let receivedAt = options.receivedAt;
189
+ let stale = false;
190
+ let refreshing = null;
191
+ const needsRefresh = (now) => stale || now < receivedAt || now - receivedAt >= TOKEN_TTL_MS - REFRESH_MARGIN_MS;
192
+ const stillValid = (now) => !stale && now >= receivedAt && now - receivedAt < TOKEN_TTL_MS;
193
+ const wait = options.wait ?? sleep;
194
+ const attempt = async () => {
195
+ const sentAt = options.now();
196
+ const fresh = await requestToken(options, token);
197
+ token = fresh;
198
+ receivedAt = sentAt;
199
+ stale = false;
200
+ return fresh;
201
+ };
202
+ const refresh = async () => {
203
+ try {
204
+ return await attempt();
205
+ } catch (error) {
206
+ if (stillValid(options.now())) return token;
207
+ stale = true;
208
+ if (!(error instanceof RefreshError && error.transient)) throw error;
209
+ }
210
+ await wait(REFRESH_RETRY_DELAY_MS);
211
+ try {
212
+ return await attempt();
213
+ } catch (error) {
214
+ stale = true;
215
+ throw error;
216
+ }
217
+ };
218
+ return {
219
+ getToken: () => {
220
+ if (refreshing) return refreshing;
221
+ if (!needsRefresh(options.now())) return Promise.resolve(token);
222
+ refreshing = refresh().finally(() => {
223
+ refreshing = null;
224
+ });
225
+ return refreshing;
226
+ },
227
+ onUnauthorized: () => {
228
+ stale = true;
229
+ }
230
+ };
231
+ };
232
+ var requestToken = async ({ fetch, baseUrl, publicKey, datashipsSessionId }, held) => {
233
+ let response;
234
+ try {
235
+ response = await fetch(`${baseUrl}${TOKEN_REFRESH_PATH}`, {
236
+ method: "POST",
237
+ headers: {
238
+ "x-api-key": publicKey,
239
+ "Content-Type": "application/json",
240
+ Authorization: `Bearer ${held}`
241
+ },
242
+ credentials: "omit",
243
+ body: JSON.stringify({ datashipsSessionId })
244
+ });
245
+ } catch {
246
+ throw new RefreshError("token refresh failed (network)", true);
247
+ }
248
+ if (response.status !== 200) {
249
+ throw new RefreshError(
250
+ `token refresh failed (${response.status})`,
251
+ response.status >= 500
252
+ );
253
+ }
254
+ const body = await response.json().catch(() => null);
255
+ if (typeof body?.token !== "string" || body.token.length === 0) {
256
+ throw new RefreshError("token refresh returned no token", false);
257
+ }
258
+ return body.token;
259
+ };
260
+
155
261
  // src/boot.ts
156
262
  var defaultImport = (url) => import(
157
263
  /* @vite-ignore */
@@ -169,7 +275,7 @@
169
275
  if (!config) return;
170
276
  const guard = win;
171
277
  if (guard.__datashipsLauncher) return;
172
- guard.__datashipsLauncher = { version: "0.2.0" };
278
+ guard.__datashipsLauncher = { version: "0.3.0" };
173
279
  const modules = env.modules ?? MODULES;
174
280
  const importModule = env.importModule ?? defaultImport;
175
281
  const load = (definition, context, beforeStart) => startModule(importModule, config, definition, context, beforeStart);
@@ -178,7 +284,7 @@
178
284
  publicKey: config.publicKey,
179
285
  baseUrl: config.baseUrl,
180
286
  preview: true,
181
- token: null,
287
+ auth: null,
182
288
  datashipsSessionId: null,
183
289
  elements: [],
184
290
  events: []
@@ -190,7 +296,23 @@
190
296
  definition,
191
297
  watch: definition.watch(win)
192
298
  }));
193
- const outcome = await resolveElements(env, config);
299
+ const fetchFn = env.fetch ?? ((url, init) => env.window.fetch(url, init));
300
+ const now = env.now ?? Date.now;
301
+ const { outcome, receivedAt } = await resolveElements(
302
+ env.window,
303
+ fetchFn,
304
+ now,
305
+ config
306
+ );
307
+ const auth = outcome.status === "ok" ? createElementsToken({
308
+ fetch: fetchFn,
309
+ baseUrl: config.baseUrl,
310
+ publicKey: config.publicKey,
311
+ datashipsSessionId: outcome.data.datashipsSessionId,
312
+ token: outcome.data.token,
313
+ receivedAt,
314
+ now
315
+ }) : null;
194
316
  for (const { definition, watch } of watched) {
195
317
  const elements = outcome.status === "ok" ? elementsOfType(outcome.data, definition.type).map(
196
318
  ({ id, channels }) => ({ id, channels })
@@ -203,7 +325,7 @@
203
325
  publicKey: config.publicKey,
204
326
  baseUrl: config.baseUrl,
205
327
  preview: false,
206
- token: outcome.data.token,
328
+ auth,
207
329
  datashipsSessionId: outcome.data.datashipsSessionId,
208
330
  elements,
209
331
  events: watch.events
@@ -211,19 +333,19 @@
211
333
  void watch.present.then(() => load(definition, context, watch.stop));
212
334
  }
213
335
  };
214
- var resolveElements = async (env, config) => {
215
- const now = env.now ?? Date.now;
216
- const cache = new ElementsCache(env.window, config.publicKey);
336
+ var resolveElements = async (win, fetchFn, now, config) => {
337
+ const cache = new ElementsCache(win, config.publicKey);
217
338
  const cached = cache.read(now());
218
- if (cached) return cached;
219
- const fetchFn = env.fetch ?? ((url, init) => env.window.fetch(url, init));
220
- const outcome = await fetchElements(
339
+ if (cached) return { outcome: cached.answer, receivedAt: cached.receivedAt };
340
+ const sentAt = now();
341
+ const { outcome, maxAgeMs } = await fetchElements(
221
342
  fetchFn,
222
343
  config.baseUrl,
223
344
  config.publicKey
224
345
  );
225
- if (outcome.status !== "failed") cache.write(outcome, now());
226
- return outcome;
346
+ const receivedAt = sentAt - maxAgeMs;
347
+ if (outcome.status !== "failed") cache.write(outcome, sentAt, receivedAt);
348
+ return { outcome, receivedAt };
227
349
  };
228
350
  var startModule = async (importModule, config, definition, context, beforeStart) => {
229
351
  try {
@@ -1,4 +1,4 @@
1
- // node_modules/@dataships/sdk/dist/index.js
1
+ // node_modules/@dataships/elements/node_modules/@dataships/sdk/dist/index.js
2
2
  var __typeError = (msg) => {
3
3
  throw TypeError(msg);
4
4
  };
@@ -600,7 +600,7 @@ post_fn = async function(args) {
600
600
  });
601
601
  };
602
602
 
603
- // node_modules/@dataships/sdk/dist/adapters/custom-platform-checkout/index.js
603
+ // node_modules/@dataships/elements/node_modules/@dataships/sdk/dist/adapters/custom-platform-checkout/index.js
604
604
  var __typeError2 = (msg) => {
605
605
  throw TypeError(msg);
606
606
  };
@@ -952,7 +952,7 @@ resolveSessionId_fn = function() {
952
952
  };
953
953
  var isCollectionStep = (value) => value === "CHECKOUT_INFORMATION" || value === "THANK_YOU" || value === "ORDER_STATUS";
954
954
 
955
- // node_modules/@dataships/sdk/dist/adapters/custom-platform-signup/index.js
955
+ // node_modules/@dataships/elements/node_modules/@dataships/sdk/dist/adapters/custom-platform-signup/index.js
956
956
  var __typeError3 = (msg) => {
957
957
  throw TypeError(msg);
958
958
  };
@@ -1346,6 +1346,14 @@ var BASE_STYLES = (
1346
1346
  /* The modal has its own background, so it must not take the page's text styles. */
1347
1347
  :host([data-host-styled]) .modal { color: var(--ds-color-text, #111827); font-size: 1rem; text-align: start; }
1348
1348
 
1349
+ .preview-badge {
1350
+ justify-self: center;
1351
+ margin: 0;
1352
+ padding: 0.15em 0.6em;
1353
+ font-size: var(--ds-font-size, inherit);
1354
+ border-radius: var(--ds-border-radius, 6px);
1355
+ }
1356
+
1349
1357
  .modal {
1350
1358
  max-width: min(560px, 90vw);
1351
1359
  padding: 0;
@@ -1473,6 +1481,7 @@ var el = (tag, { className, text, attrs = {} } = {}, children = []) => {
1473
1481
  for (const c of children) node.append(c);
1474
1482
  return node;
1475
1483
  };
1484
+ var PREVIEW_BADGE = "Preview \xB7 nothing is recorded";
1476
1485
  var _shadow;
1477
1486
  var _root;
1478
1487
  var _onConsentChange;
@@ -1513,7 +1522,7 @@ _shadow = /* @__PURE__ */ new WeakMap();
1513
1522
  _root = /* @__PURE__ */ new WeakMap();
1514
1523
  _onConsentChange = /* @__PURE__ */ new WeakMap();
1515
1524
  _DatashipsWidget_instances = /* @__PURE__ */ new WeakSet();
1516
- renderInto_fn = function(response, { page, locale = "en", heading = "Email marketing preferences", channel = "EMAIL" }) {
1525
+ renderInto_fn = function(response, { page, locale = "en", heading = "Email marketing preferences", channel = "EMAIL", preview = false }) {
1517
1526
  __privateGet4(this, _root)?.remove();
1518
1527
  __privateSet4(this, _root, null);
1519
1528
  const item = (response?.consents ?? []).find((c) => c.channel === channel);
@@ -1585,6 +1594,7 @@ renderInto_fn = function(response, { page, locale = "en", heading = "Email marke
1585
1594
  root.append(el("p", { className: "description" }, formatCopy(description, locale, rules(cfg.policyURL))));
1586
1595
  }
1587
1596
  if (modal) root.append(modal);
1597
+ if (preview) root.append(el("p", { className: "preview-badge", text: PREVIEW_BADGE }));
1588
1598
  __privateGet4(this, _shadow).append(root);
1589
1599
  __privateSet4(this, _root, root);
1590
1600
  this.setAttribute("data-visible", "");
@@ -1641,7 +1651,7 @@ var createSdkClient = (opts) => {
1641
1651
  ...preview ? {} : opts.unsafeServerKey ? { auth: { unsafeServerKey: opts.unsafeServerKey } } : { auth: { publicKey: opts.publicKey, token: opts.token } },
1642
1652
  env: opts.env ?? "production",
1643
1653
  app: ELEMENTS_APP_NAME,
1644
- version: "2.5.0",
1654
+ version: "2.6.0",
1645
1655
  adapter,
1646
1656
  ...opts.baseUrl ? { baseUrl: opts.baseUrl } : {},
1647
1657
  ...opts.fetch ? { fetch: opts.fetch } : {}
@@ -2126,6 +2136,7 @@ var mount = (config) => {
2126
2136
  defineWidget();
2127
2137
  const { page, appearance = {}, locale = "en", position = "after" } = config;
2128
2138
  const target = config.mount;
2139
+ const preview = config.preview === true;
2129
2140
  const log = config.log ?? defaultLog;
2130
2141
  const root = config.root ?? document;
2131
2142
  const registry = registryFor(root);
@@ -2159,7 +2170,7 @@ var mount = (config) => {
2159
2170
  emit,
2160
2171
  heartbeat: strategy.heartbeat,
2161
2172
  identifierType,
2162
- onResponse: (response) => widget.render(response, { page, locale, channel })
2173
+ onResponse: (response) => widget.render(response, { page, locale, channel, preview })
2163
2174
  });
2164
2175
  widget.onConsentChange = (consent) => session.saveConsent(consent);
2165
2176
  keepPlaced(dom, widget, target, position);
@@ -2169,7 +2180,7 @@ var mount = (config) => {
2169
2180
  update: ({ appearance: a, page: p }) => {
2170
2181
  widget.setAppearance(a);
2171
2182
  if (p !== page) log("page change on a repeat mount() is not supported; unmount first");
2172
- widget.render(session.response, { page, locale, channel });
2183
+ widget.render(session.response, { page, locale, channel, preview });
2173
2184
  },
2174
2185
  handle: {
2175
2186
  ready,
@@ -2188,7 +2199,7 @@ var mount = (config) => {
2188
2199
  return entry.handle;
2189
2200
  };
2190
2201
 
2191
- // node_modules/@dataships/sdk/dist/adapters/alia-form/index.js
2202
+ // node_modules/@dataships/sdk/dist/index.js
2192
2203
  var __typeError5 = (msg) => {
2193
2204
  throw TypeError(msg);
2194
2205
  };
@@ -2196,6 +2207,638 @@ var __accessCheck5 = (obj, member, msg) => member.has(obj) || __typeError5("Cann
2196
2207
  var __privateGet5 = (obj, member, getter) => (__accessCheck5(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
2197
2208
  var __privateAdd5 = (obj, member, value) => member.has(obj) ? __typeError5("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2198
2209
  var __privateSet5 = (obj, member, value, setter) => (__accessCheck5(obj, member, "write to private field"), member.set(obj, value), value);
2210
+ var __privateMethod5 = (obj, member, method) => (__accessCheck5(obj, member, "access private method"), method);
2211
+ var SERVER_KEY_PREFIX2 = "ds_sk_";
2212
+ var isServerKey2 = (key) => key.startsWith(SERVER_KEY_PREFIX2);
2213
+ var isServerKeyAuth2 = (auth) => "serverKey" in auth;
2214
+ var isUnsafeServerKeyAuth2 = (auth) => "unsafeServerKey" in auth;
2215
+ var isTokenProviderAuth2 = (auth) => typeof auth.getToken === "function";
2216
+ var resolveTokenProviderAuth2 = async (auth) => {
2217
+ const token = await auth.getToken();
2218
+ if (!token) {
2219
+ throw new Error("DatashipsClient: auth.getToken() returned an empty token");
2220
+ }
2221
+ return { publicKey: auth.publicKey, token };
2222
+ };
2223
+ var UNSAFE_SERVER_KEY_APP_MARKER2 = "unsafe-server-key";
2224
+ var UNSAFE_SERVER_KEY_WARNING2 = "Dataships SDK: the merchant SERVER KEY is being used in the browser (auth.unsafeServerKey). Anyone who views this page's source can act as this merchant until the key is revoked. Mint a short-lived token on your server and pass auth: { publicKey, token } instead.";
2225
+ var assertBrowserAuth2 = (auth) => {
2226
+ if (isUnsafeServerKeyAuth2(auth)) {
2227
+ if (!auth.unsafeServerKey || !isServerKey2(auth.unsafeServerKey)) {
2228
+ throw new Error(
2229
+ "DatashipsClient: auth.unsafeServerKey must be a server key (ds_sk_\u2026); a public key belongs in auth: { publicKey, token }"
2230
+ );
2231
+ }
2232
+ warnUnsafeServerKey2();
2233
+ return;
2234
+ }
2235
+ if (isServerKey2(auth.publicKey)) {
2236
+ throw new Error(
2237
+ "DatashipsClient: a server key (ds_sk_\u2026) must never be used in the browser; use the public key with a merchant-signed token, or DatashipsServerClient from '@dataships/sdk/server' on your server"
2238
+ );
2239
+ }
2240
+ const hasProvider = "getToken" in auth && auth.getToken !== void 0;
2241
+ const hook = auth.onUnauthorized;
2242
+ if (hook !== void 0 && typeof hook !== "function") {
2243
+ throw new Error("DatashipsClient: auth.onUnauthorized must be a function");
2244
+ }
2245
+ if (hook !== void 0 && !hasProvider) {
2246
+ throw new Error(
2247
+ "DatashipsClient: auth.onUnauthorized requires getToken; a fixed token cannot be refreshed for the retry"
2248
+ );
2249
+ }
2250
+ if (hasProvider && "token" in auth && auth.token !== void 0) {
2251
+ throw new Error(
2252
+ "DatashipsClient: pass either auth.token or auth.getToken, not both"
2253
+ );
2254
+ }
2255
+ if (hasProvider) {
2256
+ if (!isTokenProviderAuth2(auth)) {
2257
+ throw new Error("DatashipsClient: auth.getToken must be a function");
2258
+ }
2259
+ return;
2260
+ }
2261
+ if (!auth.token) {
2262
+ throw new Error(
2263
+ "DatashipsClient: auth.token is required with a public key (the merchant's server mints it), or auth.getToken to fetch one per request"
2264
+ );
2265
+ }
2266
+ };
2267
+ var warnUnsafeServerKey2 = () => {
2268
+ const c = globalThis.console;
2269
+ c?.warn?.(UNSAFE_SERVER_KEY_WARNING2);
2270
+ };
2271
+ var authHeaders2 = (auth) => {
2272
+ if (isUnsafeServerKeyAuth2(auth)) return { "X-Api-Key": auth.unsafeServerKey };
2273
+ return isServerKeyAuth2(auth) ? { "X-Api-Key": auth.serverKey } : { "X-Api-Key": auth.publicKey, Authorization: `Bearer ${auth.token}` };
2274
+ };
2275
+ var PRODUCTION_BASE_URL2 = "https://api.dataships.io";
2276
+ var resolveBaseUrl2 = (env = "production", baseUrl) => {
2277
+ if (baseUrl) return baseUrl;
2278
+ if (env === "production") return PRODUCTION_BASE_URL2;
2279
+ throw new Error(
2280
+ `Dataships SDK: env "${env}" has no default base URL; pass \`baseUrl\``
2281
+ );
2282
+ };
2283
+ var TERMINAL_STATUSES2 = /* @__PURE__ */ new Set([
2284
+ 400,
2285
+ 401,
2286
+ 403,
2287
+ 404,
2288
+ 417,
2289
+ 422,
2290
+ 426
2291
+ ]);
2292
+ var isTerminalStatus2 = (status) => status !== void 0 && TERMINAL_STATUSES2.has(status);
2293
+ var CONSENT_SESSION_ALREADY_PROCESSED2 = "CONSENT_SESSION_ALREADY_PROCESSED";
2294
+ var TERMINAL_ERROR_CODES2 = /* @__PURE__ */ new Set([
2295
+ CONSENT_SESSION_ALREADY_PROCESSED2
2296
+ ]);
2297
+ var isTerminalErrorCode2 = (errorCode) => errorCode !== void 0 && TERMINAL_ERROR_CODES2.has(errorCode);
2298
+ var MAX_FAILURES2 = 4;
2299
+ var backoffMs2 = (failureCount) => failureCount >= MAX_FAILURES2 ? 0 : failureCount * 2e3;
2300
+ var defaultRetryPolicy2 = {
2301
+ shouldRetry: (failureCount, status, errorCode) => !isTerminalStatus2(status) && !isTerminalErrorCode2(errorCode) && failureCount < MAX_FAILURES2,
2302
+ delayMs: backoffMs2
2303
+ };
2304
+ var upsertSessionRetryPolicy2 = defaultRetryPolicy2;
2305
+ var noRetryPolicy2 = {
2306
+ shouldRetry: () => false,
2307
+ delayMs: () => 0
2308
+ };
2309
+ var DatashipsError2 = class extends Error {
2310
+ constructor(args) {
2311
+ super(`Dataships request failed (${args.status || "network"})`);
2312
+ this.name = "DatashipsError";
2313
+ this.status = args.status;
2314
+ this.body = args.body;
2315
+ this.challenge = args.challenge ?? null;
2316
+ this.code = errorCodeFromBody2(args.body);
2317
+ this.reason = reasonFromBody2(args.body);
2318
+ }
2319
+ /** 401 (missing / refused credential) or 403 (unknown, revoked or disabled key). */
2320
+ get isAuthenticationFailure() {
2321
+ return this.status === 401 || this.status === 403;
2322
+ }
2323
+ /** 409 `CONSENT_SESSION_ALREADY_PROCESSED`: the session is closed; no later call on it can succeed. */
2324
+ get isSessionProcessed() {
2325
+ return this.code === CONSENT_SESSION_ALREADY_PROCESSED2;
2326
+ }
2327
+ };
2328
+ var errorCodeFromBody2 = (body) => {
2329
+ if (typeof body !== "object" || body === null) return null;
2330
+ const errors = body.errors;
2331
+ if (!Array.isArray(errors)) return null;
2332
+ const code = errors[0]?.code;
2333
+ return typeof code === "string" ? code : null;
2334
+ };
2335
+ var reasonFromBody2 = (body) => {
2336
+ if (typeof body !== "object" || body === null) return null;
2337
+ const message = body.message;
2338
+ return typeof message === "string" && message.length > 0 ? message : null;
2339
+ };
2340
+ var CONSENT_SESSION_START_PATH2 = "/v1/consent-session";
2341
+ var CONSENT_SESSION_CONSENT_PATH2 = "/v1/consent-session/consent";
2342
+ var CONSENT_SESSION_HEARTBEAT_PATH2 = "/v1/consent-session/heartbeat";
2343
+ var CONSENT_SESSION_TRIGGER_VERIFICATION_CODE_PATH2 = "/v1/consent-session/trigger-verification-code";
2344
+ var CONSENT_SESSION_SUBMIT_VERIFICATION_CODE_PATH2 = "/v1/consent-session/submit-verification-code";
2345
+ var CONSENT_SESSION_SUBMIT_PATH2 = "/v1/consent-session/submit";
2346
+ var COUNTRY_NOT_FOUND_CODE2 = "COUNTRY_NOT_FOUND";
2347
+ var verificationErrorCodeFromBody2 = errorCodeFromBody2;
2348
+ var buildUpsertRequest2 = (args) => ({
2349
+ identifier: args.identifier,
2350
+ identifierType: args.identifierType,
2351
+ locale: args.locale,
2352
+ ...args.userIp ? { userIp: args.userIp } : {},
2353
+ ...args.format ? { format: args.format } : {},
2354
+ integration: {
2355
+ ...args.context,
2356
+ type: args.integrationType
2357
+ }
2358
+ });
2359
+ var isCountryNotFound2 = (error) => error.status === 422 && error.code === COUNTRY_NOT_FOUND_CODE2;
2360
+ var emptyUpsertResponse2 = () => ({
2361
+ consentSessionId: null,
2362
+ consents: [],
2363
+ userVerificationRequired: null,
2364
+ lastHeartbeat: null,
2365
+ identifier: null
2366
+ });
2367
+ var buildSaveConsentRequest2 = (args) => ({
2368
+ consentSessionId: args.consentSessionId,
2369
+ channel: args.channel,
2370
+ consent: args.consent
2371
+ });
2372
+ var buildHeartbeatRequest2 = (args) => ({
2373
+ consentSessionId: args.consentSessionId
2374
+ });
2375
+ var buildTriggerVerificationCodeRequest2 = (args) => ({
2376
+ consentSessionId: args.consentSessionId
2377
+ });
2378
+ var buildSubmitVerificationCodeRequest2 = (args) => ({
2379
+ consentSessionId: args.consentSessionId,
2380
+ verificationCode: args.verificationCode,
2381
+ referenceId: args.referenceId
2382
+ });
2383
+ var buildSubmitRequest2 = (args) => {
2384
+ const details = { ...args.details };
2385
+ if (details.submittedAt instanceof Date) details.submittedAt = details.submittedAt.toISOString();
2386
+ if (typeof details.billingCountryCode === "string") {
2387
+ details.billingCountryCode = details.billingCountryCode.trim().toUpperCase();
2388
+ }
2389
+ const omitUser = args.user === void 0 && args.requiresUser === false;
2390
+ return {
2391
+ datashipsSessionId: args.datashipsSessionId,
2392
+ ...omitUser ? {} : { user: normaliseSubmitUser2(args.user) },
2393
+ integration: { ...details, type: args.integrationType }
2394
+ };
2395
+ };
2396
+ var normaliseSubmitUser2 = (user) => {
2397
+ const firstName = user?.firstName?.trim() ?? "";
2398
+ const lastName = user?.lastName?.trim() ?? "";
2399
+ if (!firstName || !lastName) {
2400
+ throw new Error(
2401
+ "submitSession: user.firstName and user.lastName are required (core-api refuses a blank name)"
2402
+ );
2403
+ }
2404
+ return { firstName, lastName };
2405
+ };
2406
+ var upsertSession2 = async (args) => {
2407
+ const { adapter, input } = args;
2408
+ const identifier = input.identifier ?? (await adapter.getIdentifier(input.identifierType)).identifier;
2409
+ const context = await adapter.getSessionContext();
2410
+ const body = buildUpsertRequest2({
2411
+ integrationType: adapter.integrationType,
2412
+ locale: adapter.getLocale(),
2413
+ identifier,
2414
+ identifierType: input.identifierType,
2415
+ userIp: input.userIp,
2416
+ format: input.format,
2417
+ context
2418
+ });
2419
+ try {
2420
+ const response = await args.post({
2421
+ path: CONSENT_SESSION_START_PATH2,
2422
+ body,
2423
+ retry: args.retry
2424
+ });
2425
+ return response ?? emptyUpsertResponse2();
2426
+ } catch (error) {
2427
+ if (error instanceof DatashipsError2 && isCountryNotFound2(error)) {
2428
+ return emptyUpsertResponse2();
2429
+ }
2430
+ throw error;
2431
+ }
2432
+ };
2433
+ var saveConsent2 = (args) => args.post({
2434
+ path: CONSENT_SESSION_CONSENT_PATH2,
2435
+ body: buildSaveConsentRequest2({
2436
+ consentSessionId: args.consentSessionId,
2437
+ channel: args.channel,
2438
+ consent: args.consent
2439
+ }),
2440
+ retry: args.retry
2441
+ });
2442
+ var heartbeat2 = (args) => args.post({
2443
+ path: CONSENT_SESSION_HEARTBEAT_PATH2,
2444
+ body: buildHeartbeatRequest2({ consentSessionId: args.consentSessionId }),
2445
+ retry: args.retry
2446
+ });
2447
+ var triggerVerificationCode2 = (args) => args.post({
2448
+ path: CONSENT_SESSION_TRIGGER_VERIFICATION_CODE_PATH2,
2449
+ body: buildTriggerVerificationCodeRequest2({
2450
+ consentSessionId: args.consentSessionId
2451
+ }),
2452
+ retry: noRetryPolicy2
2453
+ });
2454
+ var submitVerificationCode2 = async (args) => {
2455
+ try {
2456
+ await args.post({
2457
+ path: CONSENT_SESSION_SUBMIT_VERIFICATION_CODE_PATH2,
2458
+ body: buildSubmitVerificationCodeRequest2({
2459
+ consentSessionId: args.consentSessionId,
2460
+ verificationCode: args.verificationCode,
2461
+ referenceId: args.referenceId
2462
+ }),
2463
+ retry: noRetryPolicy2
2464
+ });
2465
+ return { verified: true, errorCode: null };
2466
+ } catch (error) {
2467
+ if (error instanceof DatashipsError2 && error.status === 400) {
2468
+ return {
2469
+ verified: false,
2470
+ errorCode: verificationErrorCodeFromBody2(error.body)
2471
+ };
2472
+ }
2473
+ throw error;
2474
+ }
2475
+ };
2476
+ var submitSession2 = async (args) => {
2477
+ const { adapter, input } = args;
2478
+ const datashipsSessionId = input.datashipsSessionId ?? adapter.getDatashipsSessionId?.();
2479
+ if (!datashipsSessionId) {
2480
+ throw new Error(
2481
+ "submitSession: datashipsSessionId is required; this adapter holds no beacon of its own"
2482
+ );
2483
+ }
2484
+ await args.post({
2485
+ path: CONSENT_SESSION_SUBMIT_PATH2,
2486
+ body: buildSubmitRequest2({
2487
+ datashipsSessionId,
2488
+ integrationType: adapter.integrationType,
2489
+ user: input.user,
2490
+ details: input.details,
2491
+ requiresUser: adapter.submitRequiresUser
2492
+ }),
2493
+ retry: args.retry
2494
+ });
2495
+ if (input.datashipsSessionId === void 0 && input.resetBeacon !== false) {
2496
+ adapter.resetDatashipsSessionId?.();
2497
+ }
2498
+ };
2499
+ var postJson2 = async ({
2500
+ url,
2501
+ headers,
2502
+ body,
2503
+ fetch,
2504
+ retry
2505
+ }) => {
2506
+ let attempt = 0;
2507
+ while (true) {
2508
+ let response;
2509
+ let networkError;
2510
+ const attemptHeaders = typeof headers === "function" ? await headers() : headers;
2511
+ try {
2512
+ response = await fetch(url, {
2513
+ method: "POST",
2514
+ headers: { "Content-Type": "application/json", ...attemptHeaders },
2515
+ body: JSON.stringify(body)
2516
+ });
2517
+ } catch (err) {
2518
+ networkError = err;
2519
+ }
2520
+ const status = response?.status;
2521
+ const ok = response?.ok ?? false;
2522
+ if (ok && response) {
2523
+ const text = await response.text();
2524
+ return text ? JSON.parse(text) : void 0;
2525
+ }
2526
+ const errorBody = response ? await readBody2(response) : null;
2527
+ const errorCode = errorCodeFromBody2(errorBody) ?? void 0;
2528
+ if (!retry.shouldRetry(attempt, status, errorCode)) {
2529
+ if (networkError) throw networkError;
2530
+ throw new DatashipsError2({
2531
+ status: status ?? 0,
2532
+ body: errorBody,
2533
+ challenge: response?.headers.get("WWW-Authenticate") ?? null
2534
+ });
2535
+ }
2536
+ attempt += 1;
2537
+ const delay = retry.delayMs(attempt);
2538
+ if (delay > 0) await new Promise((r) => setTimeout(r, delay));
2539
+ }
2540
+ };
2541
+ var readBody2 = async (response) => {
2542
+ const text = await response.text();
2543
+ if (!text) return null;
2544
+ try {
2545
+ return JSON.parse(text);
2546
+ } catch {
2547
+ return text;
2548
+ }
2549
+ };
2550
+ var DEFAULT_HEARTBEAT_INTERVAL_MS2 = 210 * 1e3;
2551
+ var DEFAULT_HEARTBEAT_DURATION_MS2 = 10 * 60 * 1e3;
2552
+ var _auth2;
2553
+ var _fetch2;
2554
+ var _upsertSessionRetry2;
2555
+ var _defaultRetry2;
2556
+ var _DatashipsClient_instances2;
2557
+ var previewUpsertResponse_fn2;
2558
+ var credentialHeaders_fn2;
2559
+ var requireAuth_fn2;
2560
+ var requireConsentSessionId_fn2;
2561
+ var sendHeartbeat_fn2;
2562
+ var post_fn2;
2563
+ var send_fn;
2564
+ var DatashipsClient2 = class {
2565
+ constructor(opts) {
2566
+ __privateAdd5(this, _DatashipsClient_instances2);
2567
+ __privateAdd5(this, _auth2);
2568
+ __privateAdd5(this, _fetch2);
2569
+ __privateAdd5(this, _upsertSessionRetry2);
2570
+ __privateAdd5(this, _defaultRetry2);
2571
+ this.adapter = opts.adapter;
2572
+ if (opts.auth) assertBrowserAuth2(opts.auth);
2573
+ if (!opts.auth && !opts.adapter.previewMode) {
2574
+ throw new Error(
2575
+ "DatashipsClient: `auth: { publicKey, token }` (or `{ publicKey, getToken }`) is required unless the adapter runs in preview mode"
2576
+ );
2577
+ }
2578
+ this.publicKey = opts.auth && !isUnsafeServerKeyAuth2(opts.auth) ? opts.auth.publicKey : null;
2579
+ __privateSet5(this, _auth2, opts.auth ?? null);
2580
+ this.app = opts.app;
2581
+ this.version = opts.version;
2582
+ this.baseUrl = resolveBaseUrl2(opts.env, opts.baseUrl);
2583
+ __privateSet5(this, _fetch2, opts.fetch ?? globalThis.fetch.bind(globalThis));
2584
+ __privateSet5(this, _upsertSessionRetry2, opts.retry?.upsertSession ?? upsertSessionRetryPolicy2);
2585
+ __privateSet5(this, _defaultRetry2, opts.retry?.default ?? defaultRetryPolicy2);
2586
+ }
2587
+ /** The credentials in use, or null for a preview-mode client constructed without them. */
2588
+ get auth() {
2589
+ return __privateGet5(this, _auth2);
2590
+ }
2591
+ /** Whether this client runs on the unsafe server-key escape hatch. */
2592
+ get isUnsafeServerKey() {
2593
+ return __privateGet5(this, _auth2) !== null && isUnsafeServerKeyAuth2(__privateGet5(this, _auth2));
2594
+ }
2595
+ /**
2596
+ * Replace the Bearer token before it expires. The next call and any running
2597
+ * heartbeat use it; a missed rotation surfaces as a 401 on the next call.
2598
+ * Not applicable under `auth.getToken`, which already fetches one per request.
2599
+ */
2600
+ setToken(token) {
2601
+ if (!__privateGet5(this, _auth2)) {
2602
+ throw new Error(
2603
+ "DatashipsClient: setToken() requires a client constructed with `auth`"
2604
+ );
2605
+ }
2606
+ if (isUnsafeServerKeyAuth2(__privateGet5(this, _auth2))) {
2607
+ throw new Error(
2608
+ "DatashipsClient: setToken() does not apply under auth.unsafeServerKey; there is no token to rotate"
2609
+ );
2610
+ }
2611
+ if (isTokenProviderAuth2(__privateGet5(this, _auth2))) {
2612
+ throw new Error(
2613
+ "DatashipsClient: setToken() does not apply under auth.getToken; the provider is called before every request"
2614
+ );
2615
+ }
2616
+ if (!token) {
2617
+ throw new Error("DatashipsClient: token must be a non-empty string");
2618
+ }
2619
+ __privateSet5(this, _auth2, { ...__privateGet5(this, _auth2), token });
2620
+ }
2621
+ /**
2622
+ * Open or update the consent session for one identifier type
2623
+ * (`POST /v1/consent-session`, contract v2). The client only states which
2624
+ * identifier type it holds; the server decides the channels and returns one
2625
+ * entry per channel to render. An empty `consents` means render nothing:
2626
+ * that also covers a 204 No Content (a surface that never collects, no
2627
+ * eligible channel, or a checkout that already asked on an earlier step) and
2628
+ * a user IP the API could not geolocate (422 COUNTRY_NOT_FOUND), both of
2629
+ * which resolve instead of throwing.
2630
+ */
2631
+ async upsertSession(input) {
2632
+ const preview = __privateMethod5(this, _DatashipsClient_instances2, previewUpsertResponse_fn2).call(this, input.identifierType, input.format);
2633
+ if (preview) return preview;
2634
+ return upsertSession2({
2635
+ adapter: this.adapter,
2636
+ input,
2637
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this),
2638
+ retry: __privateGet5(this, _upsertSessionRetry2)
2639
+ });
2640
+ }
2641
+ async saveConsent(input) {
2642
+ if (this.adapter.previewMode) return;
2643
+ await saveConsent2({
2644
+ consentSessionId: __privateMethod5(this, _DatashipsClient_instances2, requireConsentSessionId_fn2).call(this, input.session),
2645
+ channel: input.channel,
2646
+ consent: input.consent,
2647
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this),
2648
+ retry: __privateGet5(this, _defaultRetry2)
2649
+ });
2650
+ }
2651
+ /**
2652
+ * Ask the backend to send an OTP verification code to the phone-channel
2653
+ * session's number. `referenceId` must be echoed back on
2654
+ * {@link submitVerificationCode}. Never retried — a retry could send the
2655
+ * buyer duplicate codes.
2656
+ *
2657
+ * In preview mode no code is sent and `{ userVerificationTriggered: false }` is
2658
+ * returned, mirroring a store without verification enabled.
2659
+ */
2660
+ async triggerVerificationCode(input) {
2661
+ if (this.adapter.previewMode) {
2662
+ return {
2663
+ userVerificationTriggered: false,
2664
+ referenceId: null,
2665
+ codeLength: null,
2666
+ resendAfterSeconds: null
2667
+ };
2668
+ }
2669
+ return triggerVerificationCode2({
2670
+ consentSessionId: input.consentSessionId,
2671
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this)
2672
+ });
2673
+ }
2674
+ /**
2675
+ * Submit the OTP code the buyer received. Resolves
2676
+ * `{ verified: true, errorCode: null }` on 2xx. A 400 rejection resolves
2677
+ * `{ verified: false, errorCode }` with the body's `errors[0].code` (see
2678
+ * `SUBMIT_VERIFICATION_CODE_ERROR_CODES`), or `null` when the body carries
2679
+ * none. Any other failure throws. Never retried — a rejection is definitive.
2680
+ *
2681
+ * In preview mode resolves verified without a network call.
2682
+ */
2683
+ async submitVerificationCode(input) {
2684
+ if (this.adapter.previewMode) return { verified: true, errorCode: null };
2685
+ return submitVerificationCode2({
2686
+ ...input,
2687
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this)
2688
+ });
2689
+ }
2690
+ /**
2691
+ * Complete the sessions opened under a beacon: the placed order (or the
2692
+ * flow's equivalent) lands on every sibling session and processing is
2693
+ * queued (`POST /v1/consent-session/submit`).
2694
+ *
2695
+ * `user.firstName` / `lastName` are required (the backend refuses a blank
2696
+ * name; the SDK refuses it before sending), unless the adapter's
2697
+ * `submitRequiresUser` is false, as on the Alia form adapters: then `user` may be
2698
+ * omitted and the submit goes without it. The beacon defaults to the
2699
+ * adapter's own `datashipsSessionId`, which is then discarded once the
2700
+ * submit is accepted. Idempotent on the backend; a
2701
+ * beacon that matches no session is accepted silently. Retried on 409 and
2702
+ * server errors like any other call.
2703
+ *
2704
+ * In preview mode nothing is sent; the beacon is still discarded so a
2705
+ * styled sandbox behaves like a real checkout.
2706
+ */
2707
+ async submitSession(input) {
2708
+ const adapter = this.adapter;
2709
+ if (adapter.previewMode) {
2710
+ if (input.datashipsSessionId === void 0 && input.resetBeacon !== false) {
2711
+ adapter.resetDatashipsSessionId?.();
2712
+ }
2713
+ return;
2714
+ }
2715
+ await submitSession2({
2716
+ adapter,
2717
+ input,
2718
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this),
2719
+ retry: __privateGet5(this, _defaultRetry2)
2720
+ });
2721
+ }
2722
+ /**
2723
+ * Begin a periodic heartbeat. Returns an idempotent stop function. The
2724
+ * scheduler stops itself at the duration limit, when the credential is
2725
+ * refused (401 / 403) and when the session has already been processed; every
2726
+ * failure is reported through `onError`.
2727
+ */
2728
+ startHeartbeat(session, opts = {}) {
2729
+ if (this.adapter.previewMode) return () => {
2730
+ };
2731
+ const intervalMs = opts.intervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS2;
2732
+ const durationMs = opts.durationMs ?? DEFAULT_HEARTBEAT_DURATION_MS2;
2733
+ const startedAt = Date.now();
2734
+ let stopped = false;
2735
+ const stop = () => {
2736
+ if (stopped) return;
2737
+ stopped = true;
2738
+ clearInterval(handle);
2739
+ };
2740
+ const handle = setInterval(() => {
2741
+ if (Date.now() - startedAt >= durationMs) {
2742
+ stop();
2743
+ return;
2744
+ }
2745
+ __privateMethod5(this, _DatashipsClient_instances2, sendHeartbeat_fn2).call(this, session).catch((error) => {
2746
+ opts.onError?.(error);
2747
+ if (error instanceof DatashipsError2 && (error.isAuthenticationFailure || error.isSessionProcessed)) {
2748
+ stop();
2749
+ }
2750
+ });
2751
+ }, intervalMs);
2752
+ return stop;
2753
+ }
2754
+ };
2755
+ _auth2 = /* @__PURE__ */ new WeakMap();
2756
+ _fetch2 = /* @__PURE__ */ new WeakMap();
2757
+ _upsertSessionRetry2 = /* @__PURE__ */ new WeakMap();
2758
+ _defaultRetry2 = /* @__PURE__ */ new WeakMap();
2759
+ _DatashipsClient_instances2 = /* @__PURE__ */ new WeakSet();
2760
+ previewUpsertResponse_fn2 = function(identifierType, format) {
2761
+ if (this.adapter.previewMode && this.adapter.getPreviewUpsertResponse) {
2762
+ return this.adapter.getPreviewUpsertResponse(identifierType, format);
2763
+ }
2764
+ return null;
2765
+ };
2766
+ credentialHeaders_fn2 = async function() {
2767
+ const auth = __privateMethod5(this, _DatashipsClient_instances2, requireAuth_fn2).call(this);
2768
+ return authHeaders2(
2769
+ isTokenProviderAuth2(auth) ? await resolveTokenProviderAuth2(auth) : auth
2770
+ );
2771
+ };
2772
+ requireAuth_fn2 = function() {
2773
+ if (!__privateGet5(this, _auth2)) {
2774
+ throw new Error(
2775
+ "DatashipsClient: no credentials configured; pass `auth: { publicKey, token }`"
2776
+ );
2777
+ }
2778
+ return __privateGet5(this, _auth2);
2779
+ };
2780
+ requireConsentSessionId_fn2 = function(session) {
2781
+ if (!session.consentSessionId) {
2782
+ throw new Error(
2783
+ "DatashipsClient: consentSessionId is required"
2784
+ );
2785
+ }
2786
+ return session.consentSessionId;
2787
+ };
2788
+ sendHeartbeat_fn2 = async function(session) {
2789
+ await heartbeat2({
2790
+ consentSessionId: __privateMethod5(this, _DatashipsClient_instances2, requireConsentSessionId_fn2).call(this, session),
2791
+ post: __privateMethod5(this, _DatashipsClient_instances2, post_fn2).bind(this),
2792
+ retry: __privateGet5(this, _defaultRetry2)
2793
+ });
2794
+ };
2795
+ post_fn2 = async function(args) {
2796
+ try {
2797
+ return await __privateMethod5(this, _DatashipsClient_instances2, send_fn).call(this, args);
2798
+ } catch (error) {
2799
+ const auth = __privateGet5(this, _auth2);
2800
+ if (!(error instanceof DatashipsError2) || error.status !== 401 || !auth || !isTokenProviderAuth2(auth) || !auth.onUnauthorized) {
2801
+ throw error;
2802
+ }
2803
+ let credentials;
2804
+ try {
2805
+ await auth.onUnauthorized();
2806
+ credentials = await __privateMethod5(this, _DatashipsClient_instances2, credentialHeaders_fn2).call(this);
2807
+ } catch {
2808
+ throw error;
2809
+ }
2810
+ return __privateMethod5(this, _DatashipsClient_instances2, send_fn).call(this, { ...args, retry: noRetryPolicy2 }, credentials);
2811
+ }
2812
+ };
2813
+ send_fn = async function(args, credentials) {
2814
+ let pending = credentials;
2815
+ const staticHeaders = {
2816
+ // The marker lets the backend tell an exposed key in a page from a genuine server call.
2817
+ "X-Dataships-App": `${this.app} (SDK: ${this.adapter.name}${this.isUnsafeServerKey ? `; ${UNSAFE_SERVER_KEY_APP_MARKER2}` : ""})`,
2818
+ "X-Dataships-Version": `${this.version} (SDK: ${"2.5.0"})`
2819
+ };
2820
+ return postJson2({
2821
+ url: `${this.baseUrl}${args.path}`,
2822
+ // Resolved per attempt so a token provider hands every retry a fresh token.
2823
+ headers: async () => {
2824
+ const resolved = pending ?? await __privateMethod5(this, _DatashipsClient_instances2, credentialHeaders_fn2).call(this);
2825
+ pending = void 0;
2826
+ return { ...resolved, ...staticHeaders };
2827
+ },
2828
+ body: args.body,
2829
+ fetch: __privateGet5(this, _fetch2),
2830
+ retry: args.retry
2831
+ });
2832
+ };
2833
+
2834
+ // node_modules/@dataships/sdk/dist/adapters/alia-form/index.js
2835
+ var __typeError6 = (msg) => {
2836
+ throw TypeError(msg);
2837
+ };
2838
+ var __accessCheck6 = (obj, member, msg) => member.has(obj) || __typeError6("Cannot " + msg);
2839
+ var __privateGet6 = (obj, member, getter) => (__accessCheck6(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
2840
+ var __privateAdd6 = (obj, member, value) => member.has(obj) ? __typeError6("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2841
+ var __privateSet6 = (obj, member, value, setter) => (__accessCheck6(obj, member, "write to private field"), member.set(obj, value), value);
2199
2842
  var DEFAULT_EMAIL_OPT_IN_TEXT3 = "We would like to email you news and promotions. Tick to opt in.";
2200
2843
  var DEFAULT_EMAIL_OPT_IN_CONSENT_DESCRIPTION3 = "Click here for an overview of how your personal data is processed for marketing purposes or see our Privacy Policy for further information.";
2201
2844
  var DEFAULT_SMS_OPT_IN_TEXT3 = "We would like to text you news and promotions. Tick to opt in.";
@@ -2328,19 +2971,19 @@ var AliaFormAdapterBase = class {
2328
2971
  constructor(adapterName, opts) {
2329
2972
  this.sessionApi = "consent-session";
2330
2973
  this.submitRequiresUser = false;
2331
- __privateAdd5(this, _datashipsSessionId);
2332
- __privateAdd5(this, _campaignId);
2333
- __privateAdd5(this, _locale3);
2334
- __privateSet5(this, _datashipsSessionId, required(adapterName, opts.datashipsSessionId, "datashipsSessionId"));
2335
- __privateSet5(this, _campaignId, required(adapterName, opts.campaignId, "campaignId"));
2336
- __privateSet5(this, _locale3, coerceLocale3(opts.locale));
2974
+ __privateAdd6(this, _datashipsSessionId);
2975
+ __privateAdd6(this, _campaignId);
2976
+ __privateAdd6(this, _locale3);
2977
+ __privateSet6(this, _datashipsSessionId, required(adapterName, opts.datashipsSessionId, "datashipsSessionId"));
2978
+ __privateSet6(this, _campaignId, required(adapterName, opts.campaignId, "campaignId"));
2979
+ __privateSet6(this, _locale3, coerceLocale3(opts.locale));
2337
2980
  }
2338
2981
  getLocale() {
2339
- return __privateGet5(this, _locale3);
2982
+ return __privateGet6(this, _locale3);
2340
2983
  }
2341
2984
  /** Change the envelope locale, e.g. when the visitor switches language. */
2342
2985
  setLocale(locale) {
2343
- __privateSet5(this, _locale3, coerceLocale3(locale));
2986
+ __privateSet6(this, _locale3, coerceLocale3(locale));
2344
2987
  }
2345
2988
  /** The adapter holds no contact: the popup's field is passed to `upsertSession({ identifier })`. */
2346
2989
  getIdentifier(identifierType) {
@@ -2348,10 +2991,10 @@ var AliaFormAdapterBase = class {
2348
2991
  }
2349
2992
  /** The id the adapter was given; a submit leaves it in place. */
2350
2993
  getDatashipsSessionId() {
2351
- return __privateGet5(this, _datashipsSessionId);
2994
+ return __privateGet6(this, _datashipsSessionId);
2352
2995
  }
2353
2996
  baseSessionContext() {
2354
- return { datashipsSessionId: __privateGet5(this, _datashipsSessionId), campaignId: __privateGet5(this, _campaignId) };
2997
+ return { datashipsSessionId: __privateGet6(this, _datashipsSessionId), campaignId: __privateGet6(this, _campaignId) };
2355
2998
  }
2356
2999
  };
2357
3000
  _datashipsSessionId = /* @__PURE__ */ new WeakMap();
@@ -2380,19 +3023,19 @@ var AliaFormListenAdapter = class extends AliaFormAdapterBase {
2380
3023
  super("AliaFormListenAdapter", opts);
2381
3024
  this.name = "AliaFormListenAdapter";
2382
3025
  this.integrationType = ALIA_FORM_LISTEN_INTEGRATION_TYPE;
2383
- __privateAdd5(this, _disclosureText);
2384
- __privateAdd5(this, _privacyPolicyUrl);
2385
- __privateAdd5(this, _termsUrl);
2386
- __privateSet5(this, _disclosureText, optional(opts.disclosureText));
2387
- __privateSet5(this, _privacyPolicyUrl, optional(opts.privacyPolicyUrl));
2388
- __privateSet5(this, _termsUrl, optional(opts.termsUrl));
3026
+ __privateAdd6(this, _disclosureText);
3027
+ __privateAdd6(this, _privacyPolicyUrl);
3028
+ __privateAdd6(this, _termsUrl);
3029
+ __privateSet6(this, _disclosureText, optional(opts.disclosureText));
3030
+ __privateSet6(this, _privacyPolicyUrl, optional(opts.privacyPolicyUrl));
3031
+ __privateSet6(this, _termsUrl, optional(opts.termsUrl));
2389
3032
  }
2390
3033
  async getSessionContext() {
2391
3034
  return {
2392
3035
  ...this.baseSessionContext(),
2393
- ...__privateGet5(this, _disclosureText) === void 0 ? {} : { disclosureText: __privateGet5(this, _disclosureText) },
2394
- ...__privateGet5(this, _privacyPolicyUrl) === void 0 ? {} : { privacyPolicyUrl: __privateGet5(this, _privacyPolicyUrl) },
2395
- ...__privateGet5(this, _termsUrl) === void 0 ? {} : { termsUrl: __privateGet5(this, _termsUrl) }
3036
+ ...__privateGet6(this, _disclosureText) === void 0 ? {} : { disclosureText: __privateGet6(this, _disclosureText) },
3037
+ ...__privateGet6(this, _privacyPolicyUrl) === void 0 ? {} : { privacyPolicyUrl: __privateGet6(this, _privacyPolicyUrl) },
3038
+ ...__privateGet6(this, _termsUrl) === void 0 ? {} : { termsUrl: __privateGet6(this, _termsUrl) }
2396
3039
  };
2397
3040
  }
2398
3041
  };
@@ -2619,7 +3262,7 @@ var watchPopups = (context, deps) => {
2619
3262
  datashipsSessionId: context.datashipsSessionId,
2620
3263
  publicKey: context.publicKey,
2621
3264
  baseUrl: context.baseUrl,
2622
- token: context.token,
3265
+ auth: context.auth,
2623
3266
  preview: context.preview
2624
3267
  });
2625
3268
  const hideOwnText = (handle, ownText, shadow) => {
@@ -2659,6 +3302,8 @@ var watchPopups = (context, deps) => {
2659
3302
  position: "after",
2660
3303
  ...step,
2661
3304
  className: source ? classOf(source) : COMPLIANCE_CLASS,
3305
+ // Elements labels the widget as a preview only when told.
3306
+ preview: context.preview,
2662
3307
  ...shadow ? { root: shadow } : {},
2663
3308
  // The submit names the campaign, because one session id can hold several campaigns'
2664
3309
  // sessions, and the step's identifier type, so it completes this step's session only
@@ -2740,7 +3385,7 @@ var watchPopups = (context, deps) => {
2740
3385
  popup.sms = { kind: "render", handle, retag: true };
2741
3386
  };
2742
3387
  const listenSms = (root) => {
2743
- const token = context.token;
3388
+ const auth = context.auth;
2744
3389
  const datashipsSessionId = context.datashipsSessionId;
2745
3390
  const disclosure = readSmsDisclosure(root);
2746
3391
  const shown = disclosure.kind === "unreadable" ? [] : elementsOf(root, [
@@ -2748,7 +3393,7 @@ var watchPopups = (context, deps) => {
2748
3393
  ...disclosure.ownText
2749
3394
  ]);
2750
3395
  const disclosureText = textOf(shown);
2751
- if (disclosure.kind === "unreadable" || !token || !datashipsSessionId) {
3396
+ if (disclosure.kind === "unreadable" || !auth || !datashipsSessionId) {
2752
3397
  popup.sms = { kind: "none" };
2753
3398
  return;
2754
3399
  }
@@ -2759,7 +3404,7 @@ var watchPopups = (context, deps) => {
2759
3404
  datashipsSessionId,
2760
3405
  publicKey: context.publicKey,
2761
3406
  baseUrl: context.baseUrl,
2762
- token,
3407
+ auth,
2763
3408
  ...disclosureText ? { disclosureText } : {},
2764
3409
  ...privacyPolicyUrl ? { privacyPolicyUrl } : {},
2765
3410
  ...termsUrl ? { termsUrl } : {}
@@ -2828,7 +3473,7 @@ var watchPopups = (context, deps) => {
2828
3473
  const campaignId = idOf(detail.campaignID);
2829
3474
  if (!popupId || !campaignId || popups.has(popupId)) return;
2830
3475
  if (!context.preview) {
2831
- if (!context.token || !context.elements.some((element) => element.id === campaignId))
3476
+ if (!context.auth || !context.elements.some((element) => element.id === campaignId))
2832
3477
  return;
2833
3478
  }
2834
3479
  track(popupId, campaignId);
@@ -2873,15 +3518,21 @@ var createRenderClient = (options) => {
2873
3518
  campaignId: options.campaignId,
2874
3519
  previewMode: options.preview
2875
3520
  });
2876
- return new DatashipsClient({
3521
+ return new DatashipsClient2({
2877
3522
  adapter,
2878
3523
  app: "launcher",
2879
- version: "0.2.0",
3524
+ version: "0.3.0",
2880
3525
  baseUrl: options.baseUrl,
2881
- ...options.token ? { auth: { publicKey: options.publicKey, token: options.token } } : {}
3526
+ ...options.auth ? {
3527
+ auth: {
3528
+ publicKey: options.publicKey,
3529
+ getToken: options.auth.getToken,
3530
+ onUnauthorized: options.auth.onUnauthorized
3531
+ }
3532
+ } : {}
2882
3533
  });
2883
3534
  };
2884
- var createListenClient = (options) => new DatashipsClient({
3535
+ var createListenClient = (options) => new DatashipsClient2({
2885
3536
  adapter: new AliaFormListenAdapter({
2886
3537
  datashipsSessionId: options.datashipsSessionId,
2887
3538
  campaignId: options.campaignId,
@@ -2890,9 +3541,13 @@ var createListenClient = (options) => new DatashipsClient({
2890
3541
  ...options.termsUrl ? { termsUrl: options.termsUrl } : {}
2891
3542
  }),
2892
3543
  app: "launcher",
2893
- version: "0.2.0",
3544
+ version: "0.3.0",
2894
3545
  baseUrl: options.baseUrl,
2895
- auth: { publicKey: options.publicKey, token: options.token }
3546
+ auth: {
3547
+ publicKey: options.publicKey,
3548
+ getToken: options.auth.getToken,
3549
+ onUnauthorized: options.auth.onUnauthorized
3550
+ }
2896
3551
  });
2897
3552
  var start = (context) => {
2898
3553
  watchPopups(context, { mount, createRenderClient, createListenClient });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dataships/launcher",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Dataships Launcher — the one storefront script. Reads the public key from its script tag, asks the Dataships API what to render and loads the matching module.",
5
5
  "private": false,
6
6
  "license": "Apache-2.0",
@@ -33,8 +33,8 @@
33
33
  "smoke:cdn": "node scripts/smoke-cdn.mjs"
34
34
  },
35
35
  "devDependencies": {
36
- "@dataships/elements": "2.5.0",
37
- "@dataships/sdk": "2.4.0",
36
+ "@dataships/elements": "2.6.0",
37
+ "@dataships/sdk": "2.5.0",
38
38
  "@types/node": "^20.12.11",
39
39
  "@typescript-eslint/eslint-plugin": "^7.0.0",
40
40
  "@typescript-eslint/parser": "^7.0.0",