@sparkvault/sdk-js 15.2.0 → 15.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.
package/dist/index.cjs CHANGED
@@ -14968,6 +14968,107 @@ function mapInvitation(wire) {
14968
14968
  };
14969
14969
  }
14970
14970
 
14971
+ /** The native support ceremony. Identity receipts stay inside the first-party window. */
14972
+ const VALUE = /^[A-Za-z0-9_-]{43}$/;
14973
+ /** Open synchronously inside the user's gesture, before preparing the server challenge. */
14974
+ function openWidgetIdentity(options, prepare, ready, redeem) {
14975
+ if (typeof window === 'undefined')
14976
+ return Promise.reject(new ValidationError('Support sign-in requires a browser.'));
14977
+ if (options.signal?.aborted)
14978
+ return Promise.reject(new UserCancelledError());
14979
+ const popup = window.open('about:blank', '_blank', 'popup=1,width=480,height=640');
14980
+ if (!popup)
14981
+ return Promise.reject(new SparkVaultError('Allow the sign-in window, then try again.', 'HELP_DESK_POPUP_BLOCKED'));
14982
+ try {
14983
+ popup.document.title = 'Secure support sign-in';
14984
+ popup.document.body.textContent = 'Opening secure sign-in…';
14985
+ }
14986
+ catch { /* The popup may already have navigated. */ }
14987
+ return new Promise((resolve, reject) => {
14988
+ let challenge = null;
14989
+ let firstPartyOrigin = null;
14990
+ let settled = false;
14991
+ let checking = false;
14992
+ let interval;
14993
+ const timeout = setTimeout(() => finish(new SparkVaultError('Support sign-in expired. Try again.', 'HELP_DESK_WIDGET_SIGN_IN_EXPIRED')), 15 * 60 * 1000);
14994
+ const finish = (error, session) => {
14995
+ if (settled)
14996
+ return;
14997
+ settled = true;
14998
+ clearTimeout(timeout);
14999
+ if (interval)
15000
+ clearInterval(interval);
15001
+ window.removeEventListener('message', receive);
15002
+ options.signal?.removeEventListener('abort', cancel);
15003
+ try {
15004
+ popup.close();
15005
+ }
15006
+ catch { /* A severed opener is still completed by PKCE polling. */ }
15007
+ if (error)
15008
+ reject(error);
15009
+ else
15010
+ resolve(session);
15011
+ };
15012
+ const cancel = () => finish(new UserCancelledError());
15013
+ const complete = async (code) => {
15014
+ if (!challenge || settled || checking)
15015
+ return;
15016
+ checking = true;
15017
+ try {
15018
+ finish(null, await redeem(challenge, code));
15019
+ }
15020
+ catch (error) {
15021
+ finish(error instanceof Error ? error : new Error(String(error)));
15022
+ }
15023
+ };
15024
+ const receive = (event) => {
15025
+ if (!challenge || event.source !== popup || event.origin !== firstPartyOrigin)
15026
+ return;
15027
+ const data = event.data;
15028
+ if (!data || data.type !== 'sparkvault:help-desk:identity' || data.challenge_id !== challenge.challenge_id || data.state !== challenge.state)
15029
+ return;
15030
+ if (data.cancelled === true) {
15031
+ cancel();
15032
+ return;
15033
+ }
15034
+ if (typeof data.code === 'string' && VALUE.test(data.code))
15035
+ void complete(data.code);
15036
+ };
15037
+ window.addEventListener('message', receive);
15038
+ options.signal?.addEventListener('abort', cancel, { once: true });
15039
+ void prepare().then((value) => {
15040
+ if (settled)
15041
+ return;
15042
+ const url = new URL(value.sign_in_url);
15043
+ if (!VALUE.test(value.challenge_id) || !VALUE.test(value.verifier) || !VALUE.test(value.state) || !Number.isSafeInteger(value.expires_at) ||
15044
+ url.protocol !== 'https:' || url.origin !== 'https://auth.sv' || url.username || url.password || url.search || url.hash ||
15045
+ !/^\/help-desk\/acc_[0-9a-f]{32}\/[A-Za-z0-9_-]{43}$/.test(url.pathname) ||
15046
+ !url.pathname.endsWith(`/${value.challenge_id}`))
15047
+ throw new SparkVaultError('The support sign-in address is invalid.', 'HELP_DESK_INVALID_RESPONSE');
15048
+ challenge = value;
15049
+ firstPartyOrigin = url.origin;
15050
+ popup.location.replace(url.href);
15051
+ // Code delivery must survive a browser severing window.opener during
15052
+ // the first-party Identity redirect. Polling knows only the original
15053
+ // challenge and verifier; no Identity JWT ever reaches this page.
15054
+ interval = setInterval(() => {
15055
+ if (settled || checking || !challenge)
15056
+ return;
15057
+ checking = true;
15058
+ void ready(challenge).then((available) => {
15059
+ checking = false;
15060
+ if (available)
15061
+ void complete();
15062
+ }).catch((error) => {
15063
+ checking = false;
15064
+ if (error instanceof UserCancelledError || (error instanceof SparkVaultError && error.statusCode && error.statusCode < 500 && error.statusCode !== 429))
15065
+ finish(error);
15066
+ });
15067
+ }, 2500);
15068
+ }).catch((error) => finish(error instanceof Error ? error : new Error(String(error))));
15069
+ });
15070
+ }
15071
+
14971
15072
  /** The customer API. It never sends the enclosing SDK's operator credentials. */
14972
15073
  const CLIENT = 'help-desk-portal';
14973
15074
  const SESSION_TOKEN = /^hdt_[A-Za-z0-9_-]{43}$/;
@@ -15075,12 +15176,15 @@ class HelpDeskClient {
15075
15176
  this.deadline = null;
15076
15177
  this.token = null;
15077
15178
  this.revision = 0;
15179
+ this.websiteAccountSuppressed = false;
15180
+ this.ticketAccess = null;
15078
15181
  this.desk = Object.freeze({ ...desk, branding: Object.freeze({ ...desk.branding }), identity: desk.identity ? Object.freeze({ ...desk.identity }) : null,
15079
15182
  external_identity: desk.external_identity ? Object.freeze({ ...desk.external_identity }) : undefined });
15080
15183
  this.http = http;
15081
15184
  this.transfers = transfers;
15082
15185
  this.provider = provider;
15083
15186
  this.assertionProvider = assertionProvider;
15187
+ this.currentTicketPolicy = desk.ticket_access_control;
15084
15188
  }
15085
15189
  /** Discover a desk by its configured host, before any customer credentials are sent. */
15086
15190
  static async connect(config, options) {
@@ -15119,6 +15223,8 @@ class HelpDeskClient {
15119
15223
  * resumes the provider.
15120
15224
  */
15121
15225
  setSession(session) {
15226
+ if (session?.customer.assurance === 'identity' && ['external_sso', 'external_unavailable'].includes(this.desk.auth_mode))
15227
+ this.websiteAccountSuppressed = true;
15122
15228
  this.installSession(session, null);
15123
15229
  }
15124
15230
  installSession(session, deadline) {
@@ -15160,14 +15266,49 @@ class HelpDeskClient {
15160
15266
  }
15161
15267
  /** Whether company identity can be established without customer interaction. */
15162
15268
  get hasIdentityProvider() { return typeof this.assertionProvider === 'function'; }
15269
+ /** The independent ticket gate must be met before rendering authenticated ticket UI. */
15270
+ get hasTicketAccess() {
15271
+ const policy = this.currentTicketPolicy;
15272
+ if (!policy || policy.mode === 'public')
15273
+ return true;
15274
+ if (policy.mode === 'ip_allowlist')
15275
+ return policy.ip_allowed === true;
15276
+ return this.ticketAccess !== null && this.ticketAccess.deadline > Date.now() / 1000;
15277
+ }
15278
+ clearTicketAccess() { this.ticketAccess = null; }
15279
+ get ticketAccessPolicy() { return this.currentTicketPolicy; }
15280
+ /** Refresh network/policy hints without replacing requester state or composition. */
15281
+ async refreshTicketAccessPolicy() {
15282
+ const { data } = await this.http.request(apiPath `/v1/hd/desks`, {
15283
+ query: { host: this.desk.canonical_host }, headers: { 'X-SV-Client': CLIENT }, credentials: 'omit',
15284
+ });
15285
+ if (data?.kind !== 'desk' || data.desk_id !== this.desk.desk_id || data.portal_client !== CLIENT) {
15286
+ throw new SparkVaultError('This help desk could not refresh its access settings.', 'HELP_DESK_INVALID_RESPONSE');
15287
+ }
15288
+ if (JSON.stringify(data.ticket_access_control) !== JSON.stringify(this.currentTicketPolicy))
15289
+ this.clearTicketAccess();
15290
+ this.currentTicketPolicy = data.ticket_access_control ? Object.freeze({ ...data.ticket_access_control }) : undefined;
15291
+ }
15292
+ async unlockTicketAccess(options) {
15293
+ if ((options.password !== undefined) === (options.identityGrant !== undefined))
15294
+ throw new ValidationError('Choose a password or a verified employee identity.');
15295
+ const revision = this.revision;
15296
+ const mode = options.password !== undefined ? 'password' : 'identity';
15297
+ const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/access/${mode}`, mode === 'password' ? { password: options.password } : { token: options.identityGrant }, undefined, false);
15298
+ if (revision !== this.revision)
15299
+ throw sessionChanged();
15300
+ if (!/^hdapt_[A-Za-z0-9_-]{43}$/.test(result?.token) || !validLifetime(result.ttl_seconds))
15301
+ throw new SparkVaultError('The help desk returned an invalid access grant.', 'HELP_DESK_INVALID_RESPONSE');
15302
+ this.ticketAccess = { token: result.token, deadline: Date.now() / 1000 + result.ttl_seconds };
15303
+ }
15163
15304
  /** @internal Read an installed server-proven company bearer without invoking any identity provider. */
15164
15305
  verifiedSessionTokenFor(requesterId) {
15165
15306
  return this.verifiedRequesterId === requesterId && this.provedSession && this.session?.token === this.token ? this.token : null;
15166
15307
  }
15167
15308
  async getSessionToken() {
15168
- if (this.desk.auth_mode === 'external_unavailable')
15309
+ if (!this.websiteAccountSuppressed && this.desk.auth_mode === 'external_unavailable')
15169
15310
  throw new SparkVaultError('Company-session authentication is unavailable.', 'HELP_DESK_EXTERNAL_UNAVAILABLE', 503);
15170
- if (this.assertionProvider && this.desk.auth_mode === 'external_sso' &&
15311
+ if (!this.websiteAccountSuppressed && this.assertionProvider && this.desk.auth_mode === 'external_sso' &&
15171
15312
  (this.session === undefined || (this.session && (!this.provedSession || (this.verifiedRequesterId !== null && this.deadline !== null && this.deadline <= Date.now() / 1000 + RENEW_BEFORE_SECONDS))))) {
15172
15313
  await this.authenticate();
15173
15314
  return this.session?.token ?? null;
@@ -15177,6 +15318,8 @@ class HelpDeskClient {
15177
15318
  this.clearSession();
15178
15319
  return this.session?.token ?? null;
15179
15320
  }
15321
+ if (this.websiteAccountSuppressed)
15322
+ return null;
15180
15323
  const revision = this.revision;
15181
15324
  const token = await this.provider?.() ?? null;
15182
15325
  if (revision !== this.revision)
@@ -15220,7 +15363,8 @@ class HelpDeskClient {
15220
15363
  try {
15221
15364
  const { data } = await this.http.request(path, {
15222
15365
  method, body, query, credentials: 'omit',
15223
- headers: { 'X-SV-Client': CLIENT, ...(token ? { Authorization: `Bearer ${token}` } : {}) },
15366
+ headers: { 'X-SV-Client': CLIENT, ...(token ? { Authorization: `Bearer ${token}` } : {}),
15367
+ ...(this.ticketAccess && this.ticketAccess.deadline > Date.now() / 1000 ? { 'X-SV-HelpDesk-Access': this.ticketAccess.token } : {}) },
15224
15368
  });
15225
15369
  // A headless caller can render an awaited result without its own UI
15226
15370
  // generation guard. Never return the former customer's data after an
@@ -15232,6 +15376,8 @@ class HelpDeskClient {
15232
15376
  catch (error) {
15233
15377
  if (!stillCurrent())
15234
15378
  throw sessionChanged();
15379
+ if (error instanceof SparkVaultError && ['HELP_DESK_ACCESS_REQUIRED', 'HELP_DESK_IP_DENIED'].includes(error.serviceCode || error.code))
15380
+ this.clearTicketAccess();
15235
15381
  if (token && error instanceof SparkVaultError && error.statusCode === 401 && revision === this.revision && this.token === token)
15236
15382
  this.clearSession();
15237
15383
  throw error;
@@ -15279,6 +15425,8 @@ class HelpDeskClient {
15279
15425
  }
15280
15426
  /** Silently establish/renew a company session. Concurrent calls share one proof. */
15281
15427
  authenticate() {
15428
+ if (this.websiteAccountSuppressed)
15429
+ return Promise.resolve(null);
15282
15430
  if (this.authentication)
15283
15431
  return this.authentication;
15284
15432
  if (this.desk.auth_mode !== 'external_sso' || !this.assertionProvider || !this.desk.external_identity) {
@@ -15366,6 +15514,48 @@ class HelpDeskClient {
15366
15514
  completeIdentity(options) {
15367
15515
  return this.establish(apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/identity/complete`, { token: options.token });
15368
15516
  }
15517
+ /** Uninstalled result: the owning form/controller decides when the new requester becomes current. */
15518
+ signInWidgetIdentity(options = {}) {
15519
+ const revision = this.revision;
15520
+ return openWidgetIdentity(options, () => this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/widget/challenge`, {
15521
+ ...(options.email && { email: options.email }), ...(options.givenName && { given_name: options.givenName }),
15522
+ ...(options.familyName && { family_name: options.familyName }), ...(options.selectAccount && { select_account: true }),
15523
+ ...(options.employeeCompanyId && { employee_company_id: options.employeeCompanyId }),
15524
+ }, undefined, false), async (challenge) => {
15525
+ const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/widget/result`, {
15526
+ challenge_id: challenge.challenge_id, verifier: challenge.verifier,
15527
+ }, undefined, false);
15528
+ if (result.cancelled)
15529
+ throw new UserCancelledError();
15530
+ return result.ready;
15531
+ }, async (challenge, code) => {
15532
+ const result = await this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/widget/redeem`, {
15533
+ challenge_id: challenge.challenge_id, verifier: challenge.verifier, ...(code && { code }),
15534
+ }, undefined, false);
15535
+ if (revision !== this.revision)
15536
+ throw sessionChanged();
15537
+ if (!validToken(result?.token) || result.customer?.assurance !== 'identity' || !/^hdwip_[A-Za-z0-9_-]{43}$/.test(result.identity_grant?.token)) {
15538
+ throw new SparkVaultError('The help desk returned an invalid support identity.', 'HELP_DESK_INVALID_RESPONSE');
15539
+ }
15540
+ return result;
15541
+ });
15542
+ }
15543
+ /** Choose a different support identity without logging out or changing the host website. */
15544
+ switchSupportAccount() {
15545
+ this.websiteAccountSuppressed = true;
15546
+ return this.logout();
15547
+ }
15548
+ /** The only operation that resumes the website's configured identity provider after an explicit switch. */
15549
+ async useWebsiteAccount() {
15550
+ await this.logout();
15551
+ this.websiteAccountSuppressed = false;
15552
+ if (!this.hasTicketAccess)
15553
+ return null;
15554
+ if (this.assertionProvider)
15555
+ return this.authenticate();
15556
+ await this.refreshSession();
15557
+ return null;
15558
+ }
15369
15559
  getMe() { return this.send('GET', apiPath `/v1/hd/desks/${this.desk.desk_id}/me`); }
15370
15560
  updateMe(patch, context) { return this.send('PUT', apiPath `/v1/hd/desks/${this.desk.desk_id}/me`, patch, undefined, true, context); }
15371
15561
  createDraft(context) { return this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/drafts`, undefined, undefined, true, context); }
@@ -15374,6 +15564,8 @@ class HelpDeskClient {
15374
15564
  const ticket = resource('ticket', options.ticketId, 'ticketId');
15375
15565
  return this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets`, {
15376
15566
  ticket_id: ticket, subject: options.subject, body: options.body, attachments: options.attachments ?? [],
15567
+ ...(options.assistance_attempt_id && { assistance_attempt_id: options.assistance_attempt_id }),
15568
+ ...(options.assistance_visitor_id && { assistance_visitor_id: options.assistance_visitor_id }),
15377
15569
  }, undefined, true, context);
15378
15570
  }
15379
15571
  listTickets(options = {}) {
@@ -15421,11 +15613,13 @@ class HelpDeskClient {
15421
15613
  // Snapshot first: logging out must not call a provider or renew a session
15422
15614
  // using a website account which may already have changed.
15423
15615
  const token = this.token;
15616
+ const accessToken = this.ticketAccess?.token;
15424
15617
  this.clearSession();
15425
- if (!token)
15618
+ this.clearTicketAccess();
15619
+ if (!token && !accessToken)
15426
15620
  return;
15427
15621
  await this.http.request(apiPath `/v1/hd/desks/${this.desk.desk_id}/auth/logout`, {
15428
- method: 'POST', credentials: 'omit', headers: { 'X-SV-Client': CLIENT, Authorization: `Bearer ${token}` },
15622
+ method: 'POST', credentials: 'omit', headers: { 'X-SV-Client': CLIENT, ...(token && { Authorization: `Bearer ${token}` }), ...(accessToken && { 'X-SV-HelpDesk-Access': accessToken }) },
15429
15623
  });
15430
15624
  }
15431
15625
  }
@@ -16375,6 +16569,7 @@ function injectHelpDeskFormStyles() {
16375
16569
  .svhd-done{display:grid;gap:12px}
16376
16570
  .svhd-done-title{font-size:18px;line-height:1.3;margin:0}
16377
16571
  .svhd-done-title:focus{outline:none}
16572
+ .svhd-confirmation-message{white-space:pre-wrap;overflow-wrap:anywhere}
16378
16573
  .svhd-link{display:inline-flex;align-items:center;justify-self:start;min-height:44px;color:${DS.action};text-decoration:underline}
16379
16574
  .svhd-attachments[hidden],.svhd-attachments [hidden]{display:none}
16380
16575
  .svhd-file-hint{font-size:13px;color:${DS.slate600};margin:0}
@@ -17213,7 +17408,7 @@ function createDescriptionInput() {
17213
17408
  return document.createElement('textarea');
17214
17409
  }
17215
17410
  /** Host callback failures do not change a ticket's accepted or failed result. */
17216
- function notify(callback, value) {
17411
+ function notify$1(callback, value) {
17217
17412
  try {
17218
17413
  void Promise.resolve(callback?.(value)).catch(() => undefined);
17219
17414
  }
@@ -17325,7 +17520,9 @@ function mountHelpDeskForm(client, options) {
17325
17520
  const email = field('Email address', 'email');
17326
17521
  const code = field('Email code', 'code');
17327
17522
  const name = field('Your name', 'display_name');
17328
- const fields = [subject, description, email, code, name];
17523
+ const firstName = field('First name', 'given_name');
17524
+ const lastName = field('Last name (optional)', 'family_name');
17525
+ const fields = [subject, description, email, code, name, firstName, lastName];
17329
17526
  subject.input.maxLength = 200;
17330
17527
  subject.input.value = options.subject ?? '';
17331
17528
  description.input.value = options.body ?? '';
@@ -17334,6 +17531,10 @@ function mountHelpDeskForm(client, options) {
17334
17531
  code.input.inputMode = 'numeric';
17335
17532
  code.input.autocomplete = 'one-time-code';
17336
17533
  name.input.autocomplete = 'name';
17534
+ firstName.input.autocomplete = 'given-name';
17535
+ lastName.input.autocomplete = 'family-name';
17536
+ firstName.input.maxLength = 100;
17537
+ lastName.input.maxLength = 100;
17337
17538
  const codeHint = document.createElement('p');
17338
17539
  codeHint.id = `${code.input.id}-hint`;
17339
17540
  codeHint.className = 'svhd-file-hint';
@@ -17357,6 +17558,19 @@ function mountHelpDeskForm(client, options) {
17357
17558
  auth.className = 'svhd-auth';
17358
17559
  auth.hidden = true;
17359
17560
  auth.append(email.wrapper, code.wrapper, name.wrapper);
17561
+ const widgetAccount = document.createElement('div');
17562
+ widgetAccount.className = 'svhd-widget-account';
17563
+ let widgetCustomer = options.widgetIdentity?.customer ?? null;
17564
+ if (options.widgetIdentity) {
17565
+ const names = document.createElement('div');
17566
+ names.className = 'svhd-widget-names';
17567
+ names.append(firstName.wrapper, lastName.wrapper);
17568
+ auth.prepend(names);
17569
+ form.classList.add('svhd-widget-form');
17570
+ heading.textContent = `Contact ${client.desk.organization_name || 'support'}`;
17571
+ description.wrapper.querySelector('label').textContent = 'Message';
17572
+ description.wrapper.classList.add('svhd-widget-message');
17573
+ }
17360
17574
  const status = document.createElement('p');
17361
17575
  status.className = 'svhd-status';
17362
17576
  status.setAttribute('role', 'status');
@@ -17376,7 +17590,7 @@ function mountHelpDeskForm(client, options) {
17376
17590
  const send = document.createElement('button');
17377
17591
  send.className = 'svhd-button';
17378
17592
  send.type = 'submit';
17379
- send.textContent = 'Send request';
17593
+ send.textContent = options.widgetIdentity ? widgetCustomer ? 'Send message' : 'Continue' : 'Send request';
17380
17594
  const cancel = document.createElement('button');
17381
17595
  cancel.className = 'svhd-button svhd-secondary';
17382
17596
  cancel.type = 'button';
@@ -17408,7 +17622,7 @@ function mountHelpDeskForm(client, options) {
17408
17622
  discard.textContent = DISCARD_REQUEST_COPY.discard;
17409
17623
  confirmActions.append(keepEditing, discard);
17410
17624
  confirm.append(confirmTitle, confirmNote, confirmActions);
17411
- form.append(subject.wrapper, description.wrapper, auth, status, hosted, actions, confirm);
17625
+ form.append(subject.wrapper, description.wrapper, auth, widgetAccount, status, hosted, actions, confirm);
17412
17626
  let state = 'editing';
17413
17627
  let destroyed = false;
17414
17628
  let pending = false;
@@ -17435,9 +17649,59 @@ function mountHelpDeskForm(client, options) {
17435
17649
  let resendTimer = null;
17436
17650
  let confirmReturn = null;
17437
17651
  let done = null;
17652
+ function safeComposition() {
17653
+ // An account switch must not turn an uncertain send into a fresh request.
17654
+ return pending || uncertainSubmission !== null || completed ? null : { subject: subject.input.value, body: description.input.value };
17655
+ }
17656
+ function renderWidgetIdentity() {
17657
+ if (!options.widgetIdentity)
17658
+ return;
17659
+ widgetAccount.replaceChildren();
17660
+ send.textContent = widgetCustomer ? 'Send message' : 'Continue';
17661
+ auth.hidden = widgetCustomer !== null;
17662
+ email.wrapper.hidden = false;
17663
+ code.wrapper.hidden = true;
17664
+ name.wrapper.hidden = true;
17665
+ if (widgetCustomer) {
17666
+ const identity = document.createElement('p');
17667
+ identity.className = 'svhd-widget-identity';
17668
+ const customerName = document.createElement('strong');
17669
+ customerName.textContent = widgetCustomer.display_name || widgetCustomer.email;
17670
+ const customerEmail = document.createElement('span');
17671
+ customerEmail.textContent = widgetCustomer.email;
17672
+ identity.append(customerName, customerEmail);
17673
+ const change = document.createElement('button');
17674
+ change.type = 'button';
17675
+ change.className = 'svhd-widget-account-link';
17676
+ change.textContent = 'Not you?';
17677
+ change.addEventListener('click', () => {
17678
+ if (pending || destroyed || uncertainSubmission !== null || completed)
17679
+ return;
17680
+ options.widgetIdentity?.switchAccount(safeComposition());
17681
+ });
17682
+ widgetAccount.append(identity, change);
17683
+ }
17684
+ else {
17685
+ const note = document.createElement('p');
17686
+ note.className = 'svhd-file-hint';
17687
+ note.textContent = 'We’ll confirm your email before sending your request.';
17688
+ widgetAccount.append(note);
17689
+ }
17690
+ if (options.widgetIdentity.useWebsiteAccount) {
17691
+ const website = document.createElement('button');
17692
+ website.type = 'button';
17693
+ website.className = 'svhd-widget-account-link';
17694
+ website.textContent = 'Use website account';
17695
+ website.addEventListener('click', () => {
17696
+ if (!pending && !destroyed && uncertainSubmission === null && !completed)
17697
+ options.widgetIdentity?.useWebsiteAccount?.(safeComposition());
17698
+ });
17699
+ widgetAccount.append(website);
17700
+ }
17701
+ }
17438
17702
  function setState(next) {
17439
17703
  state = next;
17440
- notify(options.onStateChange, next);
17704
+ notify$1(options.onStateChange, next);
17441
17705
  }
17442
17706
  function message(text, isError = false) {
17443
17707
  status.textContent = text;
@@ -17464,8 +17728,10 @@ function mountHelpDeskForm(client, options) {
17464
17728
  renderResend();
17465
17729
  }
17466
17730
  function disable(disabled) {
17467
- for (const input of [subject.input, description.input, email.input, code.input, name.input, send, cancel, changeEmail])
17731
+ for (const input of [subject.input, description.input, email.input, code.input, name.input, firstName.input, lastName.input, send, cancel, changeEmail])
17468
17732
  input.disabled = disabled;
17733
+ for (const button of widgetAccount.querySelectorAll('button'))
17734
+ button.disabled = disabled || uncertainSubmission !== null || completed;
17469
17735
  renderResend();
17470
17736
  attachments?.disablePicking(disabled);
17471
17737
  attachments?.lock(completed || uncertainSubmission !== null);
@@ -17574,6 +17840,12 @@ function mountHelpDeskForm(client, options) {
17574
17840
  note.textContent = next.join(' ');
17575
17841
  section.append(note);
17576
17842
  }
17843
+ if (client.desk.ticket_confirmation_message) {
17844
+ const message = document.createElement('p');
17845
+ message.className = 'svhd-status svhd-confirmation-message';
17846
+ message.textContent = client.desk.ticket_confirmation_message;
17847
+ section.append(message);
17848
+ }
17577
17849
  if (requestUrl) {
17578
17850
  const link = document.createElement('a');
17579
17851
  link.className = 'svhd-link';
@@ -17617,6 +17889,11 @@ function mountHelpDeskForm(client, options) {
17617
17889
  code.wrapper.hidden = true;
17618
17890
  name.wrapper.hidden = true;
17619
17891
  auth.hidden = true;
17892
+ if (options.widgetIdentity) {
17893
+ firstName.input.value = '';
17894
+ lastName.input.value = '';
17895
+ renderWidgetIdentity();
17896
+ }
17620
17897
  hosted.hidden = true;
17621
17898
  draftId = null;
17622
17899
  draftPromise = null;
@@ -17668,6 +17945,8 @@ function mountHelpDeskForm(client, options) {
17668
17945
  generation += 1;
17669
17946
  pending = false;
17670
17947
  sessionKnown = false;
17948
+ if (options.widgetIdentity)
17949
+ widgetCustomer = null;
17671
17950
  clearComposer();
17672
17951
  disable(false);
17673
17952
  setState('editing');
@@ -17773,19 +18052,51 @@ function mountHelpDeskForm(client, options) {
17773
18052
  refused.input.focus();
17774
18053
  return;
17775
18054
  }
18055
+ let widgetSignIn;
18056
+ if (options.widgetIdentity && !widgetCustomer) {
18057
+ const givenName = firstName.input.value.trim();
18058
+ const familyName = lastName.input.value.trim();
18059
+ const emailAddress = email.input.value.trim();
18060
+ const invalid = !givenName ? firstName : !email.input.validity.valid || !emailAddress ? email : null;
18061
+ if (invalid) {
18062
+ setFieldError(invalid, invalid === email ? 'Enter your email address.' : 'Enter your first name.');
18063
+ invalid.input.focus();
18064
+ return;
18065
+ }
18066
+ // Invoke in the original submit gesture, before any awaited token read:
18067
+ // the Identity adapter can open its native window without a popup block.
18068
+ try {
18069
+ widgetSignIn = options.widgetIdentity.signIn({ email: emailAddress, givenName, familyName });
18070
+ }
18071
+ catch (failure) {
18072
+ const error = failure instanceof Error ? failure : new Error('Sign-in could not be opened.');
18073
+ message(error.message, true);
18074
+ notify$1(options.onError, error);
18075
+ return;
18076
+ }
18077
+ // A failed popup must not produce an unhandled rejection while the
18078
+ // account provider finishes its own asynchronous token read.
18079
+ void widgetSignIn.catch(() => undefined);
18080
+ }
17776
18081
  const ownGeneration = generation;
17777
18082
  let ticketAttempted = false;
17778
18083
  pending = true;
17779
18084
  disable(true);
17780
18085
  message('');
17781
18086
  try {
18087
+ if (widgetSignIn) {
18088
+ authenticating = true;
18089
+ authNotification = false;
18090
+ setState('authenticating');
18091
+ message('Confirm your email in the sign-in window.');
18092
+ }
17782
18093
  let token = await tokenFor(ownGeneration);
17783
18094
  if (!alive(ownGeneration))
17784
18095
  return;
17785
- if (!token && options.onAuthRequired && client.desk.auth_mode !== 'external_sso' && client.desk.auth_mode !== 'external_unavailable') {
18096
+ if (widgetSignIn || (!token && options.onAuthRequired && client.desk.auth_mode !== 'external_sso' && client.desk.auth_mode !== 'external_unavailable')) {
17786
18097
  authenticating = true;
17787
18098
  authNotification = false;
17788
- const session = await options.onAuthRequired();
18099
+ const session = await (widgetSignIn ?? options.onAuthRequired());
17789
18100
  if (!alive(ownGeneration))
17790
18101
  return;
17791
18102
  const currentToken = await client.getSessionToken();
@@ -17806,6 +18117,11 @@ function mountHelpDeskForm(client, options) {
17806
18117
  attachments.element.hidden = false;
17807
18118
  subject.input.value = subjectText;
17808
18119
  description.input.value = body;
18120
+ if (options.widgetIdentity && session) {
18121
+ widgetCustomer = session.customer;
18122
+ renderWidgetIdentity();
18123
+ message('');
18124
+ }
17809
18125
  }
17810
18126
  if (!alive(ownGeneration))
17811
18127
  return;
@@ -17895,7 +18211,7 @@ function mountHelpDeskForm(client, options) {
17895
18211
  setState('submitting');
17896
18212
  if (!alive(ownGeneration))
17897
18213
  return;
17898
- send.textContent = 'Sending request';
18214
+ send.textContent = options.widgetIdentity ? 'Sending message' : 'Sending request';
17899
18215
  if (!uncertainSubmission) {
17900
18216
  const id = await ensureDraft(ownGeneration, token);
17901
18217
  if (!alive(ownGeneration) || !(await tokenFor(ownGeneration)))
@@ -17904,7 +18220,7 @@ function mountHelpDeskForm(client, options) {
17904
18220
  }
17905
18221
  attachments?.lock(true);
17906
18222
  ticketAttempted = true;
17907
- const ticket = await client.createTicket({ ...uncertainSubmission, attachments: [...uncertainSubmission.attachments] }, { expectedSessionToken: token });
18223
+ const ticket = await client.createTicket({ ...uncertainSubmission, attachments: [...uncertainSubmission.attachments], ...options.assistanceContext?.() }, { expectedSessionToken: token });
17908
18224
  if (!alive(ownGeneration) || !(await tokenFor(ownGeneration)))
17909
18225
  return;
17910
18226
  completed = true;
@@ -17913,7 +18229,7 @@ function mountHelpDeskForm(client, options) {
17913
18229
  if (!alive(ownGeneration))
17914
18230
  return;
17915
18231
  showDone(ticket, customer);
17916
- notify(options.onSuccess, ticket);
18232
+ notify$1(options.onSuccess, ticket);
17917
18233
  }
17918
18234
  catch (failure) {
17919
18235
  if (!alive(ownGeneration))
@@ -17954,8 +18270,8 @@ function mountHelpDeskForm(client, options) {
17954
18270
  setState(uncertainSubmission ? 'uncertain' : challenge ? 'verifying' : 'editing');
17955
18271
  if (!alive(ownGeneration))
17956
18272
  return;
17957
- send.textContent = uncertainSubmission ? 'Check submission' : challenge ? 'Verify and send request' : 'Send request';
17958
- notify(options.onError, error);
18273
+ send.textContent = uncertainSubmission ? 'Check submission' : challenge ? 'Verify and send request' : options.widgetIdentity ? widgetCustomer ? 'Send message' : 'Continue' : 'Send request';
18274
+ notify$1(options.onError, error);
17959
18275
  }
17960
18276
  finally {
17961
18277
  if (alive(ownGeneration)) {
@@ -17989,7 +18305,7 @@ function mountHelpDeskForm(client, options) {
17989
18305
  return;
17990
18306
  const error = failure instanceof Error ? failure : new Error('A new code could not be sent. Try again.');
17991
18307
  message(error instanceof SparkVaultError && error.statusCode === 429 ? 'Too many codes have been sent. Try again later.' : error.message, true);
17992
- notify(options.onError, error);
18308
+ notify$1(options.onError, error);
17993
18309
  }
17994
18310
  finally {
17995
18311
  if (alive(ownGeneration)) {
@@ -18020,7 +18336,7 @@ function mountHelpDeskForm(client, options) {
18020
18336
  /** The Cancel path: remove the form, then tell the host the customer closed it. */
18021
18337
  function dismiss() {
18022
18338
  controller.destroy();
18023
- notify(options.onCancel, undefined);
18339
+ notify$1(options.onCancel, undefined);
18024
18340
  }
18025
18341
  const controller = {
18026
18342
  destroy() {
@@ -18045,6 +18361,11 @@ function mountHelpDeskForm(client, options) {
18045
18361
  setState('editing');
18046
18362
  },
18047
18363
  getState: () => state,
18364
+ getComposition: safeComposition,
18365
+ resumeAfterAccess() {
18366
+ if (!destroyed && !pending && !completed && uncertainSubmission === null)
18367
+ message('');
18368
+ },
18048
18369
  requestDismiss() {
18049
18370
  if (destroyed)
18050
18371
  return;
@@ -18078,10 +18399,11 @@ function mountHelpDeskForm(client, options) {
18078
18399
  keepEditing.addEventListener('click', () => closeConfirm(true));
18079
18400
  discard.addEventListener('click', dismiss);
18080
18401
  form.addEventListener('submit', onSubmit);
18081
- notify(options.onStateChange, state);
18402
+ renderWidgetIdentity();
18403
+ notify$1(options.onStateChange, state);
18082
18404
  // Native company identity starts as the form opens, never from a Connect,
18083
18405
  // Allow, verification or submit gesture. Guest email is explicit desk policy.
18084
- if ((client.desk.auth_mode === 'external_sso' && client.hasIdentityProvider) || client.desk.auth_mode === 'external_unavailable') {
18406
+ if (!options.widgetIdentity && ((client.desk.auth_mode === 'external_sso' && client.hasIdentityProvider) || client.desk.auth_mode === 'external_unavailable')) {
18085
18407
  const ownGeneration = generation;
18086
18408
  nativeProofGeneration = ownGeneration;
18087
18409
  pending = true;
@@ -18109,7 +18431,7 @@ function mountHelpDeskForm(client, options) {
18109
18431
  if (!alive(ownGeneration))
18110
18432
  return;
18111
18433
  message(error.message, true);
18112
- notify(options.onError, error);
18434
+ notify$1(options.onError, error);
18113
18435
  }).finally(() => {
18114
18436
  if (nativeProofGeneration === ownGeneration)
18115
18437
  nativeProofGeneration = null;
@@ -18217,13 +18539,2492 @@ function openHelpDeskForm(client, options = {}) {
18217
18539
  return handle;
18218
18540
  }
18219
18541
 
18220
- class HelpDeskModule {
18221
- constructor(config) {
18222
- this.config = config;
18542
+ /** Dependency-free local search shared by the help center and embedded support. */
18543
+ const SEARCH_STOP_WORDS = new Set('a an and are as at be been but by can do does for from had has have how i if in is it its me my of on or our should so that the their them there these they this to was we were what when where which who why will with would you your'.split(' '));
18544
+ const SEARCH_FIELD_WEIGHTS = [160, 140, 80, 60, 45, 10];
18545
+ const SEARCH_MAX_QUERY_LENGTH = 300;
18546
+ const SEARCH_MAX_QUERY_TERMS = 12;
18547
+ const SEARCH_MAX_TYPO_LENGTH = 64;
18548
+ const RECOMMEND_STOP_WORDS = new Set('also am anymore around back because could did didnt doesnt dont else even getting get gets got hello help hey hi im into just like looking lot much need needing now please really something thank thanks trying tried try using want wanted whenever whether without working'.split(' '));
18549
+ const RECOMMEND_MAX_QUERY_LENGTH = 20000;
18550
+ const RECOMMEND_MAX_KNOWN_TERMS = 36;
18551
+ const RECOMMEND_MAX_UNKNOWN_TERMS = 12;
18552
+
18553
+ function searchTokens(value) {
18554
+ return String(value ?? '').toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '').match(/[\p{L}\p{N}]+/gu) || [];
18555
+ }
18556
+ function searchCompare(left, right) {
18557
+ return left < right ? -1 : left > right ? 1 : 0;
18558
+ }
18559
+ function searchLowerBound(values, target) {
18560
+ let lo = 0; let hi = values.length;
18561
+ while (lo < hi) { const mid = (lo + hi) >>> 1; if (values[mid] < target) lo = mid + 1; else hi = mid; }
18562
+ return lo;
18563
+ }
18564
+ /** One insertion, deletion, substitution or adjacent transposition; never edit distance two. */
18565
+ function searchOneEdit(left, right) {
18566
+ if (left === right) return false;
18567
+ if (Math.abs(left.length - right.length) > 1) return false;
18568
+ let i = 0;
18569
+ while (i < left.length && left[i] === right[i]) i++;
18570
+ if (left.length === right.length) {
18571
+ if (left.slice(i + 1) === right.slice(i + 1)) return true;
18572
+ return left[i] === right[i + 1] && left[i + 1] === right[i] && left.slice(i + 2) === right.slice(i + 2);
18573
+ }
18574
+ return left.length > right.length ? left.slice(i + 1) === right.slice(i) : left.slice(i) === right.slice(i + 1);
18575
+ }
18576
+
18577
+ /** Prepare normalization, vocabulary and weighted postings once after the index downloads. */
18578
+ function prepareSearchIndex(rows) {
18579
+ const postings = new Map();
18580
+ const entries = (Array.isArray(rows) ? rows : []).map((article, index) => {
18581
+ const keywords = typeof article.seo_keywords === 'string' ? article.seo_keywords : Array.isArray(article.seo_keywords) ? article.seo_keywords.filter(value => typeof value === 'string').join(' ') : '';
18582
+ const tokenFields = [article.title, article.seo_title, keywords, article.summary, article.category, article.text].map(searchTokens);
18583
+ tokenFields.forEach((tokens, field) => {
18584
+ for (const word of new Set(tokens)) {
18585
+ if (!postings.has(word)) postings.set(word, new Map());
18586
+ const docs = postings.get(word);
18587
+ docs.set(index, Math.max(docs.get(index) || 0, SEARCH_FIELD_WEIGHTS[field]));
18588
+ }
18589
+ });
18590
+ const fields = tokenFields.map(tokens => tokens.join(' '));
18591
+ return { article, fields, title: fields[0], categoryId: article.category_id ?? article.categoryId ?? null, tie: `${article.path || ''}\u0000${article.id || ''}`, index };
18592
+ });
18593
+ const vocabulary = [...postings.keys()].sort(searchCompare);
18594
+ // A single edit preserves either the first or last character. These buckets
18595
+ // avoid scanning the entire vocabulary for every typo, including transpositions.
18596
+ const typoBuckets = new Map();
18597
+ for (const word of vocabulary) {
18598
+ if (word.length < 3 || word.length > SEARCH_MAX_TYPO_LENGTH + 1) continue;
18599
+ for (const key of [`${word.length}:first:${word[0]}`, `${word.length}:last:${word.at(-1)}`]) {
18600
+ if (!typoBuckets.has(key)) typoBuckets.set(key, []);
18601
+ typoBuckets.get(key).push(word);
18223
18602
  }
18224
- /** Resolve a configured desk host and obtain its customer-only, headless API. */
18225
- connect(options) {
18226
- return HelpDeskClient.connect(this.config, options);
18603
+ }
18604
+ return { entries, postings, vocabulary, typoBuckets };
18605
+ }
18606
+
18607
+ function searchTermMatches(prepared, term, mode) {
18608
+ const matches = new Map();
18609
+ const append = (word, multiplier, typo, minimumWeight = 0) => {
18610
+ for (const [index, weight] of prepared.postings.get(word) || []) {
18611
+ if (weight < minimumWeight) continue;
18612
+ const score = Math.round(weight * multiplier);
18613
+ const previous = matches.get(index);
18614
+ if (!previous || score > previous.score || (score === previous.score && searchCompare(word, previous.word) < 0)) matches.set(index, { score, word, typo });
18615
+ }
18616
+ };
18617
+ append(term, 1, false);
18618
+ for (let i = searchLowerBound(prepared.vocabulary, term); i < prepared.vocabulary.length; i++) {
18619
+ const word = prepared.vocabulary[i];
18620
+ if (!word.startsWith(term)) break;
18621
+ if (word !== term) append(word, 0.75, false);
18622
+ }
18623
+ // Recover partial title/metadata words only when exact/prefix search failed.
18624
+ // Broad body substrings are intentionally excluded: "word" should recover a
18625
+ // Password article without matching every page mentioning it deep in its body.
18626
+ if (mode !== 'exact' && term.length >= 3) {
18627
+ for (const word of prepared.vocabulary) {
18628
+ if (word.includes(term) && !word.startsWith(term)) append(word, 0.5, false, SEARCH_FIELD_WEIGHTS[2]);
18629
+ }
18630
+ }
18631
+ if (mode === 'typo' && term.length >= 4 && term.length <= SEARCH_MAX_TYPO_LENGTH) {
18632
+ const candidates = new Set();
18633
+ for (let length = term.length - 1; length <= term.length + 1; length++) {
18634
+ for (const side of ['first', 'last']) {
18635
+ const character = side === 'first' ? term[0] : term.at(-1);
18636
+ for (const word of prepared.typoBuckets.get(`${length}:${side}:${character}`) || []) candidates.add(word);
18637
+ }
18638
+ }
18639
+ for (const word of candidates) if (searchOneEdit(term, word)) append(word, 0.35, true);
18640
+ }
18641
+ return matches;
18642
+ }
18643
+ function searchRank(prepared, terms, phrase, categoryId, mode) {
18644
+ const matches = terms.map(term => searchTermMatches(prepared, term, mode));
18645
+ if (matches.some(map => !map.size)) return [];
18646
+ const smallest = matches.reduce((left, right) => left.size <= right.size ? left : right);
18647
+ const results = [];
18648
+ for (const index of smallest.keys()) {
18649
+ const entry = prepared.entries[index];
18650
+ if (categoryId !== null && entry.categoryId !== categoryId) continue;
18651
+ const parts = matches.map(map => map.get(index));
18652
+ if (parts.some(part => !part)) continue;
18653
+ let score = parts.reduce((sum, part) => sum + part.score, 0);
18654
+ if (entry.title === phrase) score += 4000;
18655
+ else if (` ${entry.title} `.includes(` ${phrase} `)) score += 1500;
18656
+ if (entry.fields[1] === phrase) score += 3000;
18657
+ else if (` ${entry.fields[1]} `.includes(` ${phrase} `)) score += 1000;
18658
+ if (` ${entry.fields[3]} `.includes(` ${phrase} `)) score += 25;
18659
+ const typo = parts.some(part => part.typo);
18660
+ results.push({ article: entry.article, score, matchedTerms: [...new Set(parts.map(part => part.word))], typo, entry });
18661
+ }
18662
+ results.sort((left, right) => right.score - left.score || searchCompare(left.entry.title, right.entry.title) || searchCompare(left.entry.tie, right.entry.tie) || left.entry.index - right.entry.index);
18663
+ return results;
18664
+ }
18665
+
18666
+ /** All query terms must match. Search falls back from exact/prefix to title substrings, then typos. */
18667
+ function searchKnowledgeBase(prepared, query, { limit = 20, offset = 0, categoryId = null } = {}) {
18668
+ const value = String(query ?? '').trim();
18669
+ if (value.length < 2 || value.length > SEARCH_MAX_QUERY_LENGTH) return { results: [], total: 0 };
18670
+ const raw = searchTokens(value);
18671
+ const meaningful = raw.filter(term => !SEARCH_STOP_WORDS.has(term));
18672
+ const terms = [...new Set(meaningful.length ? meaningful : raw)];
18673
+ if (!terms.length || terms.length > SEARCH_MAX_QUERY_TERMS) return { results: [], total: 0 };
18674
+ const phrase = terms.join(' ');
18675
+ let ranked = searchRank(prepared, terms, phrase, categoryId, 'exact');
18676
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'substring');
18677
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'typo');
18678
+ const start = Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
18679
+ const size = Number.isSafeInteger(limit) && limit >= 0 ? limit : 20;
18680
+ return { results: ranked.slice(start, start + size).map(({ article, score, matchedTerms, typo }) => ({ article, score, matchedTerms, typo })), total: ranked.length };
18681
+ }
18682
+
18683
+ /** Select bounded, useful terms without making a long description an AND query. */
18684
+ function recommendationTerms(prepared, issue) {
18685
+ const terms = new Map();
18686
+ const raw = searchTokens(String(issue ?? '').slice(0, RECOMMEND_MAX_QUERY_LENGTH));
18687
+ for (const term of raw) {
18688
+ if (term.length < 2 || term.length > SEARCH_MAX_TYPO_LENGTH || SEARCH_STOP_WORDS.has(term) || RECOMMEND_STOP_WORDS.has(term)) continue;
18689
+ if (!terms.has(term)) terms.set(term, { term, frequency: 0, order: terms.size, documents: prepared.postings.get(term)?.size ?? 0 });
18690
+ terms.get(term).frequency++;
18691
+ }
18692
+ const values = [...terms.values()];
18693
+ // Rare indexed terms carry useful detail even when they occur after a long
18694
+ // introduction. A separate small budget retains prefixes and misspellings.
18695
+ const known = values.filter(value => value.documents).sort((a, b) => a.documents - b.documents || b.frequency - a.frequency || a.order - b.order).slice(0, RECOMMEND_MAX_KNOWN_TERMS);
18696
+ const unknown = values.filter(value => !value.documents).sort((a, b) => b.frequency - a.frequency || b.term.length - a.term.length || a.order - b.order).slice(0, RECOMMEND_MAX_UNKNOWN_TERMS);
18697
+ return [...known, ...unknown].sort((a, b) => a.order - b.order).map(value => value.term);
18698
+ }
18699
+
18700
+ /**
18701
+ * Recommend published answers for a paragraph using the same prepared postings,
18702
+ * normalization, field weights and bounded spelling recovery as normal search.
18703
+ * Unknown details do not veto an otherwise relevant answer. Coverage and field
18704
+ * strength keep incidental body mentions out of multi-word recommendations.
18705
+ */
18706
+ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null } = {}) {
18707
+ const terms = recommendationTerms(prepared, issue);
18708
+ if (!terms.length) return { results: [], total: 0 };
18709
+ const candidates = new Map();
18710
+ const withinCategory = matches => categoryId === null ? matches : new Map([...matches].filter(([index]) => prepared.entries[index].categoryId === categoryId));
18711
+ let totalWeight = 0; let searchableTerms = 0;
18712
+ for (const term of terms) {
18713
+ let matches = withinCategory(searchTermMatches(prepared, term, 'exact'));
18714
+ if (!matches.size) matches = withinCategory(searchTermMatches(prepared, term, 'substring'));
18715
+ if (!matches.size) matches = withinCategory(searchTermMatches(prepared, term, 'typo'));
18716
+ if (!matches.size) continue;
18717
+ const weight = 1 + Math.log((prepared.entries.length + 1) / (matches.size + 1));
18718
+ totalWeight += weight; searchableTerms++;
18719
+ for (const [index, part] of matches) {
18720
+ if (!candidates.has(index)) candidates.set(index, { entry: prepared.entries[index], score: 0, matchedTerms: [], count: 0, weight: 0, strongest: 0, typo: false });
18721
+ const hit = candidates.get(index);
18722
+ hit.score += part.score * weight; hit.weight += weight; hit.count++;
18723
+ hit.strongest = Math.max(hit.strongest, part.score); hit.typo ||= part.typo;
18724
+ hit.matchedTerms.push(part.word);
18725
+ }
18726
+ }
18727
+ const ranked = [];
18728
+ for (const hit of candidates.values()) {
18729
+ const coverage = hit.weight / totalWeight;
18730
+ const strong = hit.strongest >= 50;
18731
+ // One clear keyword is useful. Within a paragraph, a weak body-only match
18732
+ // needs corroboration; category names alone must not recommend every page.
18733
+ if (!strong && hit.count < 2 && !(terms.length === 1 && hit.strongest <= SEARCH_FIELD_WEIGHTS[5])) continue;
18734
+ if (coverage < (strong ? 0.25 : 0.5)) continue;
18735
+ const score = Math.round(hit.score + coverage * 100 + hit.count / searchableTerms * 50);
18736
+ ranked.push({ article: hit.entry.article, score, matchedTerms: [...new Set(hit.matchedTerms)], typo: hit.typo, coverage, entry: hit.entry });
18737
+ }
18738
+ ranked.sort((a, b) => b.score - a.score || b.coverage - a.coverage || searchCompare(a.entry.title, b.entry.title) || searchCompare(a.entry.tie, b.entry.tie) || a.entry.index - b.entry.index);
18739
+ const size = Number.isSafeInteger(limit) && limit >= 0 ? Math.min(limit, 20) : 5;
18740
+ return { results: ranked.slice(0, size).map(({ article, score, matchedTerms, typo, coverage }) => ({ article, score, matchedTerms, typo, coverage })), total: ranked.length };
18741
+ }
18742
+
18743
+ /** The emitted module uses exactly the tested engine, with no runtime dependencies. */
18744
+ [
18745
+ `const SEARCH_STOP_WORDS=new Set(${JSON.stringify([...SEARCH_STOP_WORDS])});`,
18746
+ `const SEARCH_FIELD_WEIGHTS=${JSON.stringify(SEARCH_FIELD_WEIGHTS)};`,
18747
+ `const SEARCH_MAX_QUERY_LENGTH=${SEARCH_MAX_QUERY_LENGTH};`,
18748
+ `const SEARCH_MAX_QUERY_TERMS=${SEARCH_MAX_QUERY_TERMS};`,
18749
+ `const SEARCH_MAX_TYPO_LENGTH=${SEARCH_MAX_TYPO_LENGTH};`,
18750
+ `const RECOMMEND_STOP_WORDS=new Set(${JSON.stringify([...RECOMMEND_STOP_WORDS])});`,
18751
+ `const RECOMMEND_MAX_QUERY_LENGTH=${RECOMMEND_MAX_QUERY_LENGTH};`,
18752
+ `const RECOMMEND_MAX_KNOWN_TERMS=${RECOMMEND_MAX_KNOWN_TERMS};`,
18753
+ `const RECOMMEND_MAX_UNKNOWN_TERMS=${RECOMMEND_MAX_UNKNOWN_TERMS};`,
18754
+ searchTokens, searchCompare, searchLowerBound, searchOneEdit, prepareSearchIndex,
18755
+ searchTermMatches, searchRank, searchKnowledgeBase, recommendationTerms, recommendKnowledgeBase,
18756
+ ].map(value => typeof value === 'function' ? value.toString() : value).join('\n') + '\nexport { prepareSearchIndex, searchKnowledgeBase, recommendKnowledgeBase };\n';
18757
+
18758
+ /** One published-KB transport and shared local search engine for support entry points. */
18759
+ const invalid = () => new SparkVaultError('The help center returned an invalid answer. Try again.', 'KB_INVALID_RESPONSE');
18760
+ const changed = () => new SparkVaultError('The help center changed. Search again to see current answers.', 'KB_PUBLICATION_CHANGED', 409);
18761
+ const validPath = (value) => typeof value === 'string' && value.startsWith('/') && !value.startsWith('//') &&
18762
+ !Array.from(value).some(character => character.charCodeAt(0) <= 32 || character.charCodeAt(0) === 127 || character === '\\') &&
18763
+ !value.split(/[/?#]/).some(part => part === '.' || part === '..');
18764
+ const assetPath = (value) => validPath(value) && /^\/_kb\/assets\/[a-zA-Z0-9_./-]+$/.test(value);
18765
+ class HelpDeskKnowledgeBaseClient {
18766
+ constructor(sdkConfig, deskId) {
18767
+ this.sdkConfig = sdkConfig;
18768
+ this.deskId = deskId;
18769
+ this.grant = null;
18770
+ this.grantDeadline = null;
18771
+ this.config = null;
18772
+ this.index = null;
18773
+ this.indexPending = null;
18774
+ this.objectUrls = new Set();
18775
+ this.generation = 0;
18776
+ this.readerRevision = 0;
18777
+ this.readerDocument = null;
18778
+ this.activeMedia = null;
18779
+ this.destroyed = false;
18780
+ this.close = new AbortController();
18781
+ if (!isResourceIdOf('account', deskId))
18782
+ throw new ValidationError('deskId must be a Help Desk account');
18783
+ }
18784
+ getAccessHeaders() {
18785
+ if (this.grantDeadline !== null && this.grantDeadline <= Date.now())
18786
+ this.clearAccess();
18787
+ return this.grant ? { Authorization: `Bearer ${this.grant}` } : {};
18788
+ }
18789
+ async request(suffix, options = {}) {
18790
+ if (this.destroyed)
18791
+ throw new SparkVaultError('This support session has closed.', 'KB_CLOSED');
18792
+ const route = typeof suffix === 'object'
18793
+ ? apiPath `/v1/hd/desks/${this.deskId}/kb/widget/documents/${suffix.document}`
18794
+ : apiPath `/v1/hd/desks/${this.deskId}/kb/widget/${suffix}`;
18795
+ const url = new URL(`${this.sdkConfig.apiBaseUrl}${route}`);
18796
+ if (options.release)
18797
+ url.searchParams.set('release_id', options.release);
18798
+ if (options.path)
18799
+ url.searchParams.set('path', options.path);
18800
+ if (options.cursor)
18801
+ url.searchParams.set('cursor', options.cursor);
18802
+ if (options.offset !== undefined)
18803
+ url.searchParams.set('offset', String(options.offset));
18804
+ const accessHeaders = this.getAccessHeaders();
18805
+ const generation = this.generation;
18806
+ return exchange(url.href, { method: options.body !== undefined ? 'POST' : 'GET', credentials: 'omit', redirect: 'error',
18807
+ headers: { Accept: 'application/json', ...accessHeaders,
18808
+ ...(options.body !== undefined && { 'Content-Type': 'application/json' }) },
18809
+ ...(options.body !== undefined && { body: JSON.stringify(options.body) }) }, {
18810
+ timeoutMs: this.sdkConfig.timeout, closeSignal: options.signal ?? this.close.signal,
18811
+ read: async (response) => {
18812
+ if (!response.ok) {
18813
+ const failure = await readApiFailure(response);
18814
+ if (['KB_ACCESS_REQUIRED', 'KB_PUBLICATION_CHANGED', 'KB_IP_RESTRICTED', 'KB_UNAVAILABLE'].includes(failure.code))
18815
+ this.clearAccess();
18816
+ throw new SparkVaultError(failure.message, failure.code, failure.status, failure.details, failure.retryAfterMs, failure.code);
18817
+ }
18818
+ if (generation !== this.generation)
18819
+ throw changed();
18820
+ const value = await response.json();
18821
+ return (value !== null && typeof value === 'object' && 'data' in value ? value.data : value);
18822
+ },
18823
+ fail: failure => failure === 'timeout' ? new TimeoutError() : new NetworkError('The help center could not be reached. Try again.')
18824
+ });
18825
+ }
18826
+ /** Fresh config validates publication and access before a cached index is reused. */
18827
+ async load() {
18828
+ const value = await this.request('config');
18829
+ if (typeof value?.available !== 'boolean' || typeof value.authorized !== 'boolean' || typeof value.search_enabled !== 'boolean' ||
18830
+ !['public', 'password', 'ip_allowlist', 'identity'].includes(value.access?.mode) ||
18831
+ (value.available && (!/^[a-f0-9]{64}$/.test(value.release_id ?? '') || !this.canonicalOrigin(value.canonical_origin))))
18832
+ throw invalid();
18833
+ if (this.config?.release_id !== value.release_id || !value.authorized)
18834
+ this.clearContent();
18835
+ this.config = value;
18836
+ return value;
18837
+ }
18838
+ canonicalOrigin(value) {
18839
+ try {
18840
+ const url = new URL(String(value));
18841
+ return url.protocol === 'https:' && url.origin === value && !url.username && !url.password && !url.port;
18842
+ }
18843
+ catch {
18844
+ return false;
18845
+ }
18846
+ }
18847
+ async unlock(options) {
18848
+ const current = this.config ?? await this.load();
18849
+ const answer = await this.request('access', {
18850
+ body: { ...options, release_id: current.release_id }
18851
+ });
18852
+ if (!answer || (answer.token !== null && (typeof answer.token !== 'string' || !/^(?:hdkbt_[A-Za-z0-9_-]{43}|hdkbw_\d{10,12}\.[a-f0-9]{64})$/.test(answer.token))))
18853
+ throw invalid();
18854
+ if (answer.token && (!Number.isSafeInteger(answer.ttl_seconds) || (answer.ttl_seconds ?? 0) <= 0))
18855
+ throw invalid();
18856
+ this.clearAccess();
18857
+ this.grant = answer.token;
18858
+ this.grantDeadline = answer.ttl_seconds ? Date.now() + answer.ttl_seconds * 1000 : null;
18859
+ return this.load();
18860
+ }
18861
+ async currentIndex() {
18862
+ const config = await this.load();
18863
+ if (!config.available)
18864
+ throw new SparkVaultError('This help center is unavailable. Contact support to continue.', 'KB_UNAVAILABLE', 404);
18865
+ if (!config.authorized)
18866
+ throw new SparkVaultError(config.access.mode === 'ip_allowlist' ? 'Connect to an approved network to read this help center.' : 'Sign in to this help center to read its answers.', config.access.mode === 'ip_allowlist' ? 'KB_IP_RESTRICTED' : 'KB_ACCESS_REQUIRED', config.access.mode === 'ip_allowlist' ? 403 : 401);
18867
+ if (!config.search_enabled)
18868
+ throw new SparkVaultError('Search is not enabled for this help center.', 'KB_SEARCH_UNAVAILABLE', 404);
18869
+ if (this.index?.release_id === config.release_id)
18870
+ return this.index;
18871
+ if (this.indexPending)
18872
+ return this.indexPending;
18873
+ const release = config.release_id;
18874
+ const generation = this.generation;
18875
+ const pending = (async () => {
18876
+ const articles = [];
18877
+ const seen = new Set();
18878
+ let cursor;
18879
+ do {
18880
+ const value = await this.request('index', { release, cursor });
18881
+ if (!value || generation !== this.generation || value.release_id !== release || value.canonical_origin !== config.canonical_origin ||
18882
+ !Array.isArray(value.articles) || articles.length + value.articles.length > 4000 || value.articles.some(row => typeof row.id !== 'string' || row.id.length > 256 ||
18883
+ typeof row.title !== 'string' || !validPath(row.path)))
18884
+ throw invalid();
18885
+ articles.push(...value.articles);
18886
+ const next = value.next_cursor;
18887
+ if (next !== undefined && next !== null && (typeof next !== 'string' || !new RegExp(`^${release}\\.[0-9]{1,6}$`).test(next) || seen.has(next) || seen.size >= 32))
18888
+ throw invalid();
18889
+ if (next)
18890
+ seen.add(next);
18891
+ cursor = next ?? undefined;
18892
+ } while (cursor);
18893
+ const held = { release_id: release, canonical_origin: config.canonical_origin, articles, prepared: prepareSearchIndex(articles) };
18894
+ this.index = held;
18895
+ return held;
18896
+ })();
18897
+ this.indexPending = pending;
18898
+ try {
18899
+ return await pending;
18900
+ }
18901
+ finally {
18902
+ if (this.indexPending === pending)
18903
+ this.indexPending = null;
18904
+ }
18905
+ }
18906
+ result(row, index) {
18907
+ return { id: row.id, kind: row.kind ?? (row.path.startsWith('/faq/') && row.path.includes('#') ? 'faq' : 'article'),
18908
+ title: row.title, summary: String(row.summary ?? ''), category: String(row.category ?? ''), path: row.path,
18909
+ canonical_url: new URL(row.path, index.canonical_origin).href, release_id: index.release_id };
18910
+ }
18911
+ async search(issue) {
18912
+ if (typeof issue !== 'string' || !issue.trim())
18913
+ throw new ValidationError('Describe what you need help with.');
18914
+ const index = await this.currentIndex();
18915
+ const found = recommendKnowledgeBase(index.prepared, issue, { limit: 5 });
18916
+ return { release_id: index.release_id, total: found.total, results: found.results.map(hit => this.result(hit.article, index)) };
18917
+ }
18918
+ async resolveLink(value) {
18919
+ const index = await this.currentIndex();
18920
+ let url;
18921
+ try {
18922
+ url = new URL(value, index.canonical_origin);
18923
+ }
18924
+ catch {
18925
+ return null;
18926
+ }
18927
+ if (url.origin !== index.canonical_origin || url.username || url.password)
18928
+ return null;
18929
+ const path = url.pathname + url.hash;
18930
+ const row = index.articles.find(article => article.path === path || (!url.hash && article.path === url.pathname));
18931
+ return row ? this.result(row, index) : null;
18932
+ }
18933
+ async read(result) {
18934
+ const config = await this.load();
18935
+ if (config.release_id !== result.release_id)
18936
+ throw changed();
18937
+ if (!config.authorized)
18938
+ throw new SparkVaultError('Sign in to this help center to read its answers.', config.access.mode === 'ip_allowlist' ? 'KB_IP_RESTRICTED' : 'KB_ACCESS_REQUIRED', config.access.mode === 'ip_allowlist' ? 403 : 401);
18939
+ const readerRevision = ++this.readerRevision;
18940
+ const value = await this.request({ document: result.id }, { release: result.release_id });
18941
+ if (value?.version !== 1 || value.id !== result.id || value.release_id !== result.release_id || value.kind !== result.kind ||
18942
+ value.canonical_url !== result.canonical_url || typeof value.body_html !== 'string' || value.body_html.length > 5 * 1024 ** 2 ||
18943
+ !Array.isArray(value.assets) || value.assets.some(path => !assetPath(path)))
18944
+ throw invalid();
18945
+ if (readerRevision !== this.readerRevision)
18946
+ throw changed();
18947
+ const body_html = sanitizeReader(value.body_html, value.canonical_url, new Set(value.assets));
18948
+ this.activeMedia?.abort();
18949
+ this.activeMedia = null;
18950
+ for (const url of this.objectUrls)
18951
+ URL.revokeObjectURL(url);
18952
+ this.objectUrls.clear();
18953
+ this.readerDocument = { ...value, body_html };
18954
+ return this.readerDocument;
18955
+ }
18956
+ /** Paint article text first; hydrate only approved media without replacing the reader DOM. */
18957
+ hydrateAssets(document, callbacks) {
18958
+ if (this.destroyed || this.readerDocument?.id !== document.id || this.readerDocument.release_id !== document.release_id)
18959
+ return () => { };
18960
+ this.activeMedia?.abort();
18961
+ const close = new AbortController();
18962
+ this.activeMedia = close;
18963
+ const readerRevision = this.readerRevision;
18964
+ const generation = this.generation;
18965
+ const urls = new Set();
18966
+ const paths = [...new Set(this.readerDocument.assets)];
18967
+ let cancelled = false;
18968
+ let bytes = 0;
18969
+ const active = () => !cancelled && !close.signal.aborted && generation === this.generation && readerRevision === this.readerRevision;
18970
+ void (async () => {
18971
+ for (let offset = 0; offset < paths.length && active(); offset += 4) {
18972
+ await Promise.all(paths.slice(offset, offset + 4).map(async (path, index) => {
18973
+ try {
18974
+ if (offset + index >= 64 || bytes >= 32 * 1024 ** 2)
18975
+ throw new SparkVaultError('Open the full answer to view all its images.', 'KB_READER_UNAVAILABLE');
18976
+ const blob = await this.readAsset(document.release_id, path, close.signal);
18977
+ bytes += blob.size;
18978
+ if (bytes > 32 * 1024 ** 2)
18979
+ throw new SparkVaultError('Open the full answer to view all its images.', 'KB_READER_UNAVAILABLE');
18980
+ if (!active())
18981
+ return;
18982
+ const url = URL.createObjectURL(blob);
18983
+ this.objectUrls.add(url);
18984
+ urls.add(url);
18985
+ callbacks.onAsset(path, url);
18986
+ }
18987
+ catch (error) {
18988
+ if (!cancelled && !this.destroyed)
18989
+ callbacks.onError?.(path, error);
18990
+ }
18991
+ }));
18992
+ }
18993
+ })();
18994
+ return () => {
18995
+ cancelled = true;
18996
+ close.abort();
18997
+ for (const url of urls) {
18998
+ URL.revokeObjectURL(url);
18999
+ this.objectUrls.delete(url);
19000
+ }
19001
+ if (this.activeMedia === close)
19002
+ this.activeMedia = null;
19003
+ };
19004
+ }
19005
+ async readAsset(release, path, signal) {
19006
+ const chunks = [];
19007
+ let offset = 0;
19008
+ let size = null;
19009
+ let contentType = null;
19010
+ for (let page = 0; page < 21; page++) {
19011
+ const value = await this.request('asset', { release, path, offset, signal });
19012
+ if (!value || !Number.isSafeInteger(value.total_size) || value.total_size < 0 || value.total_size > 10 * 1024 ** 2 || value.offset !== offset ||
19013
+ (size !== null && size !== value.total_size) || (contentType !== null && contentType !== value.content_type) ||
19014
+ !/^image\/(?:png|jpeg|gif|webp|avif|svg\+xml)$/.test(value.content_type) || typeof value.data !== 'string' ||
19015
+ value.data.length > 700000 || value.data.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(value.data))
19016
+ throw invalid();
19017
+ size = value.total_size;
19018
+ contentType = value.content_type;
19019
+ let text;
19020
+ try {
19021
+ text = globalThis.atob(value.data);
19022
+ }
19023
+ catch {
19024
+ throw invalid();
19025
+ }
19026
+ if (text.length > 512 * 1024 || offset + text.length > size)
19027
+ throw invalid();
19028
+ const bytes = new Uint8Array(text.length);
19029
+ for (let i = 0; i < text.length; i++)
19030
+ bytes[i] = text.charCodeAt(i);
19031
+ chunks.push(bytes);
19032
+ offset += bytes.byteLength;
19033
+ if (value.next_offset === null) {
19034
+ if (offset !== size)
19035
+ throw invalid();
19036
+ return new Blob(chunks, { type: contentType });
19037
+ }
19038
+ if (!bytes.byteLength || value.next_offset !== offset || offset >= size)
19039
+ throw invalid();
19040
+ }
19041
+ throw invalid();
19042
+ }
19043
+ clearContent() {
19044
+ this.generation++;
19045
+ this.readerRevision++;
19046
+ this.readerDocument = null;
19047
+ this.activeMedia?.abort();
19048
+ this.activeMedia = null;
19049
+ this.index = null;
19050
+ this.indexPending = null;
19051
+ for (const url of this.objectUrls)
19052
+ URL.revokeObjectURL(url);
19053
+ this.objectUrls.clear();
19054
+ }
19055
+ clearAccess() {
19056
+ this.grant = null;
19057
+ this.grantDeadline = null;
19058
+ this.config = null;
19059
+ this.clearContent();
19060
+ }
19061
+ destroy() { this.destroyed = true; this.close.abort(); this.clearAccess(); }
19062
+ }
19063
+ /** Defense in depth: a reader can never run theme HTML or fetch unapproved image URLs. */
19064
+ function sanitizeReader(html, canonical, assets) {
19065
+ if (typeof globalThis.document === 'undefined')
19066
+ throw new SparkVaultError('Open this answer in the help center to read it.', 'KB_READER_UNAVAILABLE');
19067
+ // Template contents stay inert, including image/iframe requests, until the
19068
+ // sanitized result is mounted. DOMParser documents can load remote media.
19069
+ const document = globalThis.document;
19070
+ const template = document.createElement('template');
19071
+ template.innerHTML = html;
19072
+ const tags = new Set('p h1 h2 h3 h4 h5 h6 ul ol li blockquote pre code em strong del s hr br table thead tbody tr th td figure figcaption img a div span details summary'.split(' '));
19073
+ for (const element of [...template.content.querySelectorAll('*')]) {
19074
+ if (!tags.has(element.localName)) {
19075
+ element.remove();
19076
+ continue;
19077
+ }
19078
+ const source = element.getAttribute('src');
19079
+ const href = element.getAttribute('href');
19080
+ for (const attribute of [...element.attributes]) {
19081
+ if (!['class', 'id', 'alt', 'title', 'width', 'height', 'colspan', 'rowspan', 'start', 'aria-level'].includes(attribute.name))
19082
+ element.removeAttribute(attribute.name);
19083
+ }
19084
+ if (element.localName === 'img') {
19085
+ if (!source || !assets.has(source)) {
19086
+ const fallback = document.createElement('span');
19087
+ fallback.textContent = element.getAttribute('alt') || 'Image unavailable';
19088
+ element.replaceWith(fallback);
19089
+ continue;
19090
+ }
19091
+ element.setAttribute('data-kb-asset', source);
19092
+ element.setAttribute('data-kb-image-state', 'loading');
19093
+ element.setAttribute('loading', 'lazy');
19094
+ element.setAttribute('decoding', 'async');
19095
+ }
19096
+ if (element.localName === 'a' && href) {
19097
+ try {
19098
+ const url = new URL(href, canonical);
19099
+ if (!['https:', 'http:', 'mailto:', 'tel:'].includes(url.protocol) || url.username || url.password)
19100
+ continue;
19101
+ element.setAttribute('href', href.startsWith('#') ? href : url.href);
19102
+ if (!href.startsWith('#')) {
19103
+ element.setAttribute('target', '_blank');
19104
+ element.setAttribute('rel', 'noopener noreferrer');
19105
+ }
19106
+ }
19107
+ catch { /* Keep the readable link text without an unsafe destination. */ }
19108
+ }
19109
+ }
19110
+ return template.innerHTML;
19111
+ }
19112
+
19113
+ let sequence$2 = 0;
19114
+ const interactionId = () => `${Date.now()}-${++sequence$2}`;
19115
+ function createSupportAnalytics({ deskId, post }) {
19116
+ const base = `/hd/desks/${encodeURIComponent(deskId)}/support`;
19117
+ let disposed = false;
19118
+ let visitor = null;
19119
+ // The same IDs are retried after a lost response; neither attempts nor outcomes multiply.
19120
+ async function send(path, body) {
19121
+ try {
19122
+ return await post(path, body);
19123
+ }
19124
+ catch (error) {
19125
+ if (disposed)
19126
+ throw error;
19127
+ return post(path, body);
19128
+ }
19129
+ }
19130
+ function getVisitor() {
19131
+ if (!visitor) {
19132
+ visitor = send(`${base}/visitor`, {}).then((answer) => {
19133
+ if (!/^[a-f0-9]{64}$/.test(answer.visitor_id))
19134
+ throw new Error('Invalid support visitor');
19135
+ return answer;
19136
+ }).catch((error) => { visitor = null; throw error; });
19137
+ }
19138
+ return visitor;
19139
+ }
19140
+ async function start(options) {
19141
+ if (disposed)
19142
+ return null;
19143
+ const attemptId = interactionId();
19144
+ try {
19145
+ const active = await getVisitor();
19146
+ if (disposed)
19147
+ return null;
19148
+ await send(`${base}/attempts`, {
19149
+ visitor_id: active.visitor_id, attempt_id: attemptId, availability: options.availability,
19150
+ ...(options.availability === 'available' && { release_id: options.releaseId, result_count: options.resultCount }),
19151
+ });
19152
+ if (disposed)
19153
+ return null;
19154
+ let queue = Promise.resolve();
19155
+ let terminal = false;
19156
+ let opened = false;
19157
+ const context = { assistance_attempt_id: attemptId, assistance_visitor_id: active.visitor_id };
19158
+ const emit = (fields) => {
19159
+ const body = { visitor_id: active.visitor_id, event_id: interactionId(), ...fields };
19160
+ queue = queue.then(async () => {
19161
+ if (!disposed)
19162
+ await send(`${base}/attempts/${encodeURIComponent(attemptId)}/events`, body);
19163
+ }).catch(() => { });
19164
+ };
19165
+ return {
19166
+ articleOpened(articleId, releaseId) {
19167
+ if (disposed || terminal || options.availability !== 'available')
19168
+ return;
19169
+ opened = true;
19170
+ emit({ type: 'article_opened', article_id: articleId, release_id: releaseId ?? options.releaseId });
19171
+ },
19172
+ solved() {
19173
+ if (disposed || terminal || !opened)
19174
+ return;
19175
+ terminal = true;
19176
+ emit({ type: 'solved' });
19177
+ },
19178
+ contactRequested(reason) {
19179
+ if (disposed || terminal || (options.availability === 'available' && !reason))
19180
+ return;
19181
+ terminal = true;
19182
+ emit({ type: 'contact_requested', ...(options.availability === 'available' && { reason }) });
19183
+ },
19184
+ ticketContext() { return disposed ? undefined : { ...context }; },
19185
+ };
19186
+ }
19187
+ catch {
19188
+ visitor = null;
19189
+ return null;
19190
+ }
19191
+ }
19192
+ return { start, dispose: () => { disposed = true; visitor = null; } };
19193
+ }
19194
+
19195
+ let launcherSequence = 0;
19196
+ /** A convenience path only: it never owns a second support flow. */
19197
+ function createSupportLauncher(options, open) {
19198
+ const button = document.createElement('button');
19199
+ button.type = 'button';
19200
+ button.className = 'sv-support-launcher';
19201
+ button.id = `sv-support-launcher-${++launcherSequence}`;
19202
+ button.setAttribute('aria-label', options.label || 'Open support');
19203
+ button.setAttribute('aria-haspopup', 'dialog');
19204
+ button.setAttribute('aria-expanded', 'false');
19205
+ const offset = (value, fallback) => typeof value === 'number' && Number.isFinite(value) ? Math.min(240, Math.max(12, value)) : fallback;
19206
+ button.style.cssText = `position:fixed;right:calc(${offset(options.right, 24)}px + env(safe-area-inset-right,0px));bottom:calc(${offset(options.bottom, 24)}px + env(safe-area-inset-bottom,0px));z-index:2147482800;width:56px;height:56px;border-radius:50%;border:1px solid ${withAlpha(DS.white, .22)};background:${DS.slate900};color:${DS.white};box-shadow:${DS.shadowPopover};display:grid;place-items:center;cursor:pointer;padding:0;overflow:hidden;`;
19207
+ if (options.imageUrl) {
19208
+ let url;
19209
+ try {
19210
+ url = new URL(options.imageUrl);
19211
+ }
19212
+ catch {
19213
+ throw new ValidationError('launcher.imageUrl must be an HTTPS URL');
19214
+ }
19215
+ if (url.protocol !== 'https:' || url.username || url.password)
19216
+ throw new ValidationError('launcher.imageUrl must be an HTTPS URL');
19217
+ const image = document.createElement('img');
19218
+ image.src = url.href;
19219
+ image.alt = '';
19220
+ image.style.cssText = 'width:100%;height:100%;object-fit:cover';
19221
+ image.referrerPolicy = 'no-referrer';
19222
+ image.addEventListener('error', () => { image.remove(); button.textContent = '?'; }, { once: true });
19223
+ button.append(image);
19224
+ }
19225
+ else {
19226
+ const mark = document.createElement('span');
19227
+ mark.setAttribute('aria-hidden', 'true');
19228
+ mark.textContent = '?';
19229
+ mark.style.cssText = 'display:grid;place-items:center;width:26px;height:26px;border:1.8px solid currentColor;border-radius:50%;font:600 20px/1 system-ui,sans-serif';
19230
+ button.append(mark);
19231
+ }
19232
+ button.addEventListener('click', open);
19233
+ document.body.append(button);
19234
+ return {
19235
+ setExpanded(expanded) { button.setAttribute('aria-expanded', String(expanded)); },
19236
+ destroy() { button.removeEventListener('click', open); button.remove(); },
19237
+ };
19238
+ }
19239
+
19240
+ /** The support journey's only skin. Customer content stays in the product register. */
19241
+ function injectHelpDeskSupportStyles() {
19242
+ if (document.getElementById('sparkvault-help-desk-support-styles'))
19243
+ return;
19244
+ const style = document.createElement('style');
19245
+ style.id = 'sparkvault-help-desk-support-styles';
19246
+ style.textContent = `
19247
+ .svhs-panel,.svhs-panel *{box-sizing:border-box}
19248
+ .svhs-panel{position:fixed;right:calc(var(--svhs-right,24px) + env(safe-area-inset-right,0px));bottom:calc(var(--svhs-bottom,96px) + env(safe-area-inset-bottom,0px));z-index:2147482900;width:408px;height:438px;max-width:calc(100vw - 32px);max-height:calc(100dvh - var(--svhs-bottom,96px) - 24px);display:flex;flex-direction:column;overflow:hidden;border:1px solid ${DS.slate200};border-radius:16px;background:${DS.white};color:${DS.slate900};font:400 15px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',sans-serif;text-align:left;box-shadow:${DS.shadowPopover};transform-origin:bottom right;transition:width 180ms cubic-bezier(.2,0,0,1),height 180ms cubic-bezier(.2,0,0,1)}
19249
+ .svhs-panel[hidden],.svhs-panel [hidden]{display:none!important}
19250
+ .svhs-panel[data-stage=results]{height:680px}
19251
+ .svhs-panel[data-stage=article]{width:704px;height:700px}
19252
+ .svhs-panel[data-stage=feedback]{height:358px}
19253
+ .svhs-panel[data-stage=contact]{height:720px}
19254
+ .svhs-panel[data-stage=receipt]{height:430px}
19255
+ .svhs-panel button,.svhs-panel input,.svhs-panel textarea{font:inherit;letter-spacing:normal;text-transform:none}
19256
+ .svhs-panel button,.svhs-panel a{touch-action:manipulation;-webkit-tap-highlight-color:transparent}
19257
+ .svhs-panel button{appearance:none;cursor:pointer;margin:0}
19258
+ .svhs-panel button:active{transform:translateY(1px)}
19259
+ .svhs-panel button:focus-visible,.svhs-panel a:focus-visible,.svhs-panel input:focus-visible,.svhs-panel textarea:focus-visible{outline:2px solid ${DS.action};outline-offset:3px}
19260
+ .svhs-panel svg{display:block;width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;flex:none;pointer-events:none}
19261
+ .svhs-toolbar{display:flex;align-items:center;justify-content:space-between;gap:8px;min-height:68px;flex:none;padding:12px 14px 12px 24px;border-bottom:1px solid ${DS.slate100}}
19262
+ .svhs-desk-name{font-size:14px;font-weight:600;line-height:1.35;color:${DS.slate600};overflow-wrap:anywhere;min-width:0}
19263
+ .svhs-toolbar-actions{display:flex;align-items:center;gap:4px;margin-left:auto;flex:none}
19264
+ .svhs-identity-notice{display:flex;align-items:center;justify-content:space-between;gap:8px;flex:none;padding:8px 24px;border-bottom:1px solid ${DS.slate200};background:${DS.slate50}}
19265
+ .svhs-identity-notice .svhs-status{margin:0;font-size:13px}
19266
+ .svhs-identity-notice .svhs-text-button{flex:none;font-size:13px!important}
19267
+ .svhs-icon-button{display:grid;place-items:center;width:40px;height:40px;flex:none;padding:0;border:0;border-radius:6px;background:transparent;color:${DS.slate500};text-decoration:none}
19268
+ .svhs-icon-button:hover{background:${DS.slate100};color:${DS.slate900}}
19269
+ .svhs-back{display:flex;align-items:center;gap:4px;flex:none;min-height:40px;margin-left:-10px!important;padding:8px;border:0;border-radius:6px;background:transparent;color:${DS.slate600};font-size:14px!important;font-weight:500!important;line-height:1.4}
19270
+ .svhs-back:hover{background:${DS.slate50}}
19271
+ .svhs-back:disabled{background:transparent;color:${DS.slate500};cursor:default;transform:none}
19272
+ .svhs-screen{display:flex;flex-direction:column;min-height:0;flex:1}
19273
+ .svhs-scroll{padding:26px 24px;overflow:auto;overscroll-behavior:contain;min-height:0;flex:1;scrollbar-gutter:stable}
19274
+ .svhs-heading{margin:0 0 9px;padding:0;color:${DS.slate900};font-size:23px;font-weight:600;line-height:1.25;letter-spacing:-.7px;overflow-wrap:anywhere}
19275
+ .svhs-heading:focus,.svhs-article-title:focus{outline:none}
19276
+ .svhs-copy{margin:0 0 20px;color:${DS.slate500};font-size:14px;line-height:1.55}
19277
+ .svhs-label{display:block;margin:0 0 7px;font-size:13px;font-weight:600;color:${DS.slate600}}
19278
+ .svhs-issue{display:block;width:100%;min-height:116px;max-height:200px;resize:none;overflow-y:auto;border:1px solid ${DS.slate300};border-radius:6px;padding:11px 12px;background:${DS.white};color:${DS.slate900};font-size:16px!important;line-height:1.5!important;box-shadow:none}
19279
+ .svhs-issue::placeholder{color:${DS.slate500};opacity:1}
19280
+ .svhs-issue:focus{border-color:${DS.action}}
19281
+ .svhs-primary,.svhs-secondary{display:flex;align-items:center;justify-content:center;gap:8px;min-height:44px;padding:10px 16px;border:1px solid transparent;border-radius:6px;font-size:14px!important;font-weight:600!important;line-height:1.4!important;text-decoration:none;transition:background 120ms cubic-bezier(.2,0,0,1)}
19282
+ .svhs-primary{background:${DS.action};color:${DS.white}}
19283
+ .svhs-primary:hover{background:${DS.actionHover}}
19284
+ .svhs-primary[aria-disabled=true]{cursor:progress}
19285
+ .svhs-secondary{border-color:${DS.slate300};background:${DS.white};color:${DS.slate600}}
19286
+ .svhs-secondary:hover{background:${DS.slate50}}
19287
+ .svhs-text-button{display:inline-flex;align-items:center;justify-content:center;min-height:44px;padding:9px 4px;border:0;border-radius:6px;background:transparent;color:${DS.action};font-size:14px!important;line-height:1.4!important;text-decoration:none}
19288
+ .svhs-text-button:hover{text-decoration:underline}
19289
+ .svhs-full{width:100%}
19290
+ .svhs-bottom{padding:16px 24px 18px;flex:none;border-top:1px solid ${DS.slate100}}
19291
+ .svhs-start-bottom{display:flex;flex-direction:column;align-items:center;gap:6px;padding-top:0;border-top:0}
19292
+ .svhs-start-bottom .svhs-primary{width:100%}
19293
+ .svhs-query{display:flex;align-items:flex-start;gap:12px;margin:0 0 15px;padding:0 0 18px;border-bottom:1px solid ${DS.slate100}}
19294
+ .svhs-query-text{display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;flex:1;margin:0;color:${DS.slate600};font-size:14px;line-height:1.5;overflow-wrap:anywhere}
19295
+ .svhs-query .svhs-text-button{flex:none;min-height:32px;padding:4px 0}
19296
+ .svhs-results{display:flex;flex-direction:column;margin:0;padding:0;list-style:none}
19297
+ .svhs-result{display:block;width:100%;padding:17px 0;border:0;border-bottom:1px solid ${DS.slate100};background:${DS.white};color:${DS.slate900};text-align:left}
19298
+ .svhs-results li:last-child .svhs-result{border-bottom:0}
19299
+ .svhs-result-title{display:block;margin:0 0 5px;color:inherit;font-size:16px;font-weight:600;line-height:1.4;letter-spacing:-.2px;overflow-wrap:anywhere}
19300
+ .svhs-result:hover .svhs-result-title{color:${DS.action};text-decoration:underline}
19301
+ .svhs-result-excerpt{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;margin:0;color:${DS.slate500};font-size:13px;line-height:1.55;overflow-wrap:anywhere}
19302
+ .svhs-result-category{display:block;margin-top:7px;color:${DS.slate500};font-size:12px;line-height:1.4}
19303
+ .svhs-footer-copy{margin:0 0 9px;color:${DS.slate500};font-size:13px;line-height:1.5;text-align:center}
19304
+ .svhs-error{margin:12px 0 0;color:${DS.error};font-size:14px;line-height:1.5;overflow-wrap:anywhere}
19305
+ .svhs-status{margin:16px 0;color:${DS.slate600};font-size:14px;line-height:1.5}
19306
+ .svhs-empty{padding:12px 0 4px}
19307
+ .svhs-empty .svhs-heading{font-size:18px;letter-spacing:-.3px}
19308
+ .svhs-spinner{width:15px;height:15px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;animation:svhs-spin .7s linear infinite;flex:none}
19309
+ @keyframes svhs-spin{to{transform:rotate(360deg)}}
19310
+ .svhs-article-scroll{padding:34px 48px 28px}
19311
+ .svhs-category{margin:0 0 12px;color:${DS.slate500};font-size:13px;line-height:1.5;overflow-wrap:anywhere}
19312
+ .svhs-article-title{margin:0 0 18px;color:${DS.slate900};font-size:28px;font-weight:600;line-height:1.2;letter-spacing:-.8px;overflow-wrap:anywhere}
19313
+ .svhs-article-content{color:${DS.slate600};font-size:15px;line-height:1.65;overflow-wrap:anywhere}
19314
+ .svhs-article-content>*:first-child{margin-top:0}
19315
+ .svhs-article-content p{margin:0 0 18px;font:inherit;color:inherit}
19316
+ .svhs-article-content h1,.svhs-article-content h2,.svhs-article-content h3,.svhs-article-content h4,.svhs-article-content h5,.svhs-article-content h6{margin:28px 0 12px;color:${DS.slate900};font-size:18px;font-weight:600;line-height:1.35;letter-spacing:-.3px;scroll-margin-top:24px}
19317
+ .svhs-article-content h3,.svhs-article-content h4,.svhs-article-content h5,.svhs-article-content h6{font-size:16px}
19318
+ .svhs-article-content ul,.svhs-article-content ol{margin:0 0 22px;padding-left:22px}
19319
+ .svhs-article-content li{margin:8px 0;padding-left:5px}
19320
+ .svhs-article-content strong{font-weight:600;color:${DS.slate900}}
19321
+ .svhs-article-content a{color:${DS.action};text-decoration:underline;text-underline-offset:2px}
19322
+ .svhs-article-content img,.svhs-article-content video{display:block;max-width:100%;height:auto;margin:20px 0}
19323
+ .svhs-reader-asset{display:block;max-width:100%;margin:20px 0}
19324
+ .svhs-reader-asset img{margin:0}
19325
+ .svhs-reader-asset-status{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:4px;min-height:140px;padding:20px;border:1px solid ${DS.slate200};border-radius:6px;background:${DS.slate50};color:${DS.slate500};font-size:13px;text-align:center}
19326
+ .svhs-reader-asset-status[style]{min-height:0}
19327
+ .svhs-article-content blockquote{margin:22px 0;padding:0 0 0 16px;border-left:2px solid ${DS.slate300};font-size:14px}
19328
+ .svhs-article-content pre{margin:20px 0;padding:14px;border:1px solid ${DS.slate200};border-radius:6px;background:${DS.slate50};overflow:auto;overscroll-behavior:contain;font:13px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace}
19329
+ .svhs-article-content code{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:.9em}
19330
+ .svhs-article-content table{display:block;max-width:100%;border-collapse:collapse;overflow:auto;overscroll-behavior:contain;margin:20px 0;font-size:14px}
19331
+ .svhs-article-content th,.svhs-article-content td{padding:10px 12px;border:1px solid ${DS.slate200};text-align:left}
19332
+ .svhs-article-content hr{margin:24px 0;border:0;border-top:1px solid ${DS.slate200}}
19333
+ .svhs-article-footer{display:flex;align-items:center;justify-content:space-between;gap:14px;padding:14px 24px;border-top:1px solid ${DS.slate100};flex:none}
19334
+ .svhs-article-footer .svhs-primary{min-width:110px}
19335
+ .svhs-article-footer .svhs-text-button{white-space:nowrap;font-size:13px!important}
19336
+ .svhs-article-question{color:${DS.slate500};font-size:13px;line-height:1.5}
19337
+ .svhs-reader-actions{display:flex;align-items:stretch;gap:12px;flex:none}
19338
+ .svhs-feedback-scroll{padding-top:30px}
19339
+ .svhs-feedback-actions{display:flex;flex-direction:column;gap:9px;margin-top:24px}
19340
+ .svhs-feedback-actions .svhs-text-button{align-self:center;color:${DS.slate500}}
19341
+ .svhs-contact-scroll{padding:0;scrollbar-gutter:auto}
19342
+ .svhs-contact-target{display:flex;flex-direction:column;min-height:100%}
19343
+ .svhs-contact-target:empty{display:none;min-height:0}
19344
+ .svhs-contact-prelude{padding:24px}
19345
+ .svhs-contact-prelude .svhs-secondary{margin-top:16px}
19346
+ .svhs-ticket-gate{padding:0 24px 24px}
19347
+ .svhs-unlock-input{display:block;box-sizing:border-box;width:100%;min-height:46px;margin:0 0 16px;border:1px solid ${DS.slate300};border-radius:6px;padding:11px 12px;background:${DS.white};color:${DS.slate900};font-size:16px!important;line-height:1.5!important}
19348
+ .svhs-unlock-input:focus{border-color:${DS.action}}
19349
+ .svhs-unlock-form{margin:0}
19350
+ .svhs-contact-target>.svhd-container{display:flex;flex:1;flex-direction:column;min-height:100%;max-width:none;padding:24px;border:0;border-radius:0;box-shadow:none;background:transparent}
19351
+ .svhs-contact-target .svhd-body{display:flex;flex:1;flex-direction:column;min-height:0}
19352
+ .svhs-contact-target .svhd-container h2{margin-bottom:12px;font-size:22px;line-height:1.25;letter-spacing:-.6px;overflow-wrap:anywhere}
19353
+ .svhs-contact-target .svhd-form{gap:16px}
19354
+ .svhs-contact-target .svhd-label{font-size:13px;line-height:1.5}
19355
+ .svhs-contact-target .svhd-input{font-size:16px;line-height:1.5}
19356
+ .svhs-contact-target .svhd-description{min-height:138px}
19357
+ .svhs-contact-target .svhd-actions{gap:10px}
19358
+ .svhs-contact-target .svhd-actions>.svhd-button:first-child{flex:1}
19359
+ .svhs-contact-target .svhd-status{font-size:14px}
19360
+ .svhs-contact-target .svhd-auth{gap:14px}
19361
+ .svhs-contact-target .svhd-widget-account{display:flex;align-items:center;flex-wrap:wrap;gap:8px 12px;min-width:0}
19362
+ .svhs-contact-target .svhd-widget-identity{display:flex;flex:1;min-width:0;flex-direction:column;gap:2px;margin:0;line-height:1.4;overflow-wrap:anywhere}
19363
+ .svhs-contact-target .svhd-widget-identity strong{color:${DS.slate900};font-size:14px;font-weight:600}
19364
+ .svhs-contact-target .svhd-widget-identity span{color:${DS.slate500};font-size:13px}
19365
+ .svhs-contact-target .svhd-widget-account-link{display:inline-flex;align-items:center;justify-content:center;min-height:44px;max-width:100%;padding:8px 0;border:0;border-radius:6px;background:transparent;color:${DS.action};font-size:13px;line-height:1.4}
19366
+ .svhs-contact-target .svhd-widget-account-link:hover{text-decoration:underline}
19367
+ .svhs-contact-target .svhd-widget-account-link:focus-visible{outline:2px solid ${DS.action};outline-offset:3px}
19368
+ .svhs-contact-target .svhd-widget-account-link:disabled{cursor:progress;color:${DS.slate500}}
19369
+ .svhs-contact-target .svhd-widget-names{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:12px}
19370
+ .svhs-contact-target .svhd-widget-form{display:flex;flex:1;flex-direction:column;gap:16px}
19371
+ .svhs-contact-target .svhd-widget-message{display:flex;flex:1;flex-direction:column;gap:6px;min-height:164px}
19372
+ .svhs-contact-target .svhd-widget-message .svhd-description{flex:1;resize:vertical}
19373
+ .svhs-contact-target .svhd-widget-form>.svhd-actions{position:sticky;bottom:0;z-index:1;margin:auto -24px 0;padding:16px 24px 0;border-top:1px solid ${DS.slate100};background:${DS.white}}
19374
+ .svhs-contact-target .svhd-widget-form>.svhd-actions>.svhd-secondary{display:none}
19375
+ .svhs-contact-target .svhd-widget-form .svhd-actions>.svhd-button{font-size:14px}
19376
+ .svhs-contact-target .svhd-widget-form>.svhd-confirm{position:sticky;bottom:-24px;z-index:2;margin:0 -24px -24px;padding:16px 24px 24px;border-top:1px solid ${DS.slate200};background:${DS.white}}
19377
+ .svhs-contact-target .svhd-widget-form>.svhd-confirm .svhd-actions{flex-wrap:nowrap}
19378
+ .svhs-contact-target .svhd-widget-form>.svhd-confirm .svhd-button{flex:1}
19379
+ .svhs-contact-target .svhd-footer{margin-top:16px;text-align:center;font-size:11px}
19380
+ .svhs-account-return{padding:0 24px 12px}
19381
+ .svhs-account-return .svhs-text-button{font-size:13px!important}
19382
+ .svhs-receipt-scroll{padding-top:36px}
19383
+ .svhs-receipt-mark{width:30px!important;height:30px!important;margin-bottom:20px;color:${DS.action}}
19384
+ .svhs-ticket-link{display:inline-flex;align-items:center;min-height:44px;margin:0 0 10px;color:${DS.action};font-size:14px;font-weight:600;text-decoration:underline}
19385
+ .svhs-receipt-note{white-space:pre-wrap;overflow-wrap:anywhere}
19386
+ .svhs-receipt-actions{display:flex;flex-direction:column;align-items:center;gap:4px}
19387
+ .svhs-live{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
19388
+ .svhs-toast{box-sizing:border-box;position:fixed;right:24px;bottom:calc(96px + var(--svhs-toast-offset,0px) + env(safe-area-inset-bottom));z-index:2147482901;display:flex;align-items:center;gap:10px;max-width:calc(100vw - 36px);padding:14px 18px;border:1px solid transparent;border-radius:8px;background:${DS.slate900};color:${DS.white};box-shadow:${DS.shadowPopover};font:400 14px/1.5 -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',sans-serif;overflow-wrap:anywhere}
19389
+ .svhs-toast svg{width:18px;height:18px;flex:none;fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
19390
+ .svhs-overlay{position:fixed;inset:0;z-index:2147482900;display:flex;background:${DS.white};padding:0;overflow:hidden}
19391
+ .svhs-modal{width:100%;height:100%;min-width:0;outline:none}
19392
+ .svhs-overlay .svhs-panel{position:relative;inset:auto;width:100%;height:100%;max-width:none;max-height:none;border:0;border-radius:0;box-shadow:none;padding-top:env(safe-area-inset-top);transition:none}
19393
+ .sv-support-launcher{touch-action:manipulation;-webkit-tap-highlight-color:transparent;transition:background 120ms cubic-bezier(.2,0,0,1)}
19394
+ .sv-support-launcher:hover{filter:brightness(1.12)}
19395
+ .sv-support-launcher:active{transform:translateY(1px)}
19396
+ .sv-support-launcher:focus-visible{outline:3px solid ${DS.action};outline-offset:3px}
19397
+ @media(max-width:640px){
19398
+ .svhs-panel{right:0;bottom:0;width:100%;height:100dvh;max-width:none;max-height:none;border:0;border-radius:0}
19399
+ .svhs-toolbar{min-height:70px;padding:12px 12px 12px 24px;border-bottom-color:${DS.slate200}}
19400
+ .svhs-icon-button{width:44px;height:44px}
19401
+ .svhs-back{min-height:44px;max-width:42%}
19402
+ .svhs-scroll{padding:28px 24px}
19403
+ .svhs-heading{font-size:25px}
19404
+ .svhs-issue{min-height:148px;max-height:260px}
19405
+ .svhs-bottom{padding-bottom:calc(20px + env(safe-area-inset-bottom))}
19406
+ .svhs-start-bottom{margin-top:0}
19407
+ .svhs-panel[data-stage=issue] .svhs-scroll{flex:0}
19408
+ .svhs-query .svhs-text-button{min-height:44px;min-width:44px}
19409
+ .svhs-query-text{font-size:15px}
19410
+ .svhs-result{padding:20px 0}
19411
+ .svhs-result-title{font-size:17px}
19412
+ .svhs-result-excerpt{font-size:14px}
19413
+ .svhs-article-scroll{padding:32px 25px}
19414
+ .svhs-article-title{font-size:28px}
19415
+ .svhs-article-content{font-size:16px}
19416
+ .svhs-article-footer{align-items:stretch;padding:12px 24px calc(12px + env(safe-area-inset-bottom))}
19417
+ .svhs-article-question{display:none}
19418
+ .svhs-reader-actions{flex:1}
19419
+ .svhs-article-footer .svhs-primary,.svhs-article-footer .svhs-text-button{flex:1;font-size:14px!important}
19420
+ .svhs-feedback-scroll{padding-top:50px}
19421
+ .svhs-feedback-actions{margin-top:30px}
19422
+ .svhs-feedback-actions .svhs-primary,.svhs-feedback-actions .svhs-secondary{min-height:48px}
19423
+ .svhs-contact-scroll{padding:0}
19424
+ .svhs-contact-target .svhd-description{min-height:160px}
19425
+ .svhs-contact-target>.svhd-container{padding:24px}
19426
+ .svhs-contact-target .svhd-widget-form>.svhd-actions{padding-bottom:env(safe-area-inset-bottom)}
19427
+ .svhs-receipt-scroll{padding-top:58px;flex:0}
19428
+ .svhs-panel[data-stage=receipt] .svhs-bottom{border-top:0;padding-top:8px}
19429
+ .svhs-toast{right:18px;left:18px;bottom:calc(88px + var(--svhs-toast-offset,0px) + env(safe-area-inset-bottom));max-width:none}
19430
+ }
19431
+ @media(pointer:coarse){.svhs-icon-button{width:44px;height:44px}.svhs-back{min-height:44px}.svhs-query .svhs-text-button{min-height:44px;min-width:44px}}
19432
+ @media(prefers-reduced-motion:reduce){.svhs-panel,.svhs-panel *,.sv-support-launcher{transition-duration:0s!important;animation-duration:.01ms!important;animation-iteration-count:1!important;scroll-behavior:auto!important}}
19433
+ @media(forced-colors:active){.svhs-panel button:focus-visible,.svhs-panel a:focus-visible,.svhs-panel input:focus-visible,.svhs-panel textarea:focus-visible{outline:2px solid Highlight}.svhs-panel,.svhs-primary,.svhs-secondary{border:1px solid ButtonText}}
19434
+ `;
19435
+ document.head.appendChild(style);
19436
+ }
19437
+
19438
+ /** Same-document history belongs to the host; support only owns its marked entry. */
19439
+ let internalMutation = 0;
19440
+ const hostMutationListeners = new Set();
19441
+ let stopObserving = null;
19442
+ let sequence$1 = 0;
19443
+ function observeHostMutations(listener) {
19444
+ hostMutationListeners.add(listener);
19445
+ if (!stopObserving) {
19446
+ const history = window.history;
19447
+ const push = history.pushState;
19448
+ const replace = history.replaceState;
19449
+ const changed = () => {
19450
+ if (!internalMutation)
19451
+ for (const notify of [...hostMutationListeners])
19452
+ notify();
19453
+ };
19454
+ const wrappedPush = function (...args) { push.apply(this, args); changed(); };
19455
+ const wrappedReplace = function (...args) { replace.apply(this, args); changed(); };
19456
+ history.pushState = wrappedPush;
19457
+ history.replaceState = wrappedReplace;
19458
+ stopObserving = () => {
19459
+ // A host may install its own adapter after support opened. Never undo it.
19460
+ if (history.pushState === wrappedPush)
19461
+ history.pushState = push;
19462
+ if (history.replaceState === wrappedReplace)
19463
+ history.replaceState = replace;
19464
+ stopObserving = null;
19465
+ };
19466
+ }
19467
+ return () => {
19468
+ hostMutationListeners.delete(listener);
19469
+ if (!hostMutationListeners.size)
19470
+ stopObserving?.();
19471
+ };
19472
+ }
19473
+ function ownMutation(action) {
19474
+ internalMutation += 1;
19475
+ try {
19476
+ action();
19477
+ }
19478
+ finally {
19479
+ internalMutation -= 1;
19480
+ }
19481
+ }
19482
+ /**
19483
+ * One same-URL entry while phone support is open. No popstate is cancelled or
19484
+ * swallowed, and no cleanup ever calls history.back()/go(). Explicit close,
19485
+ * resize and disposal replace only a proven owned current entry with its
19486
+ * original host state. The inactive entry can be reused while still owned.
19487
+ * A harmless same-URL entry is preferable to consuming a host's later route.
19488
+ */
19489
+ class SupportPhoneHistory {
19490
+ constructor(actions) {
19491
+ this.actions = actions;
19492
+ this.marker = `__sv_support_phone_${++sequence$1}`;
19493
+ // A DOM ownership label, never a credential or an unpredictable identifier.
19494
+ this.token = `${Date.now()}-${sequence$1}`;
19495
+ this.baseState = null;
19496
+ this.url = '';
19497
+ this.hasInactiveEntry = false;
19498
+ this.wantsPhone = false;
19499
+ this.mobile = false;
19500
+ this.active = false;
19501
+ this.forwardAllowed = false;
19502
+ this.destroyed = false;
19503
+ this.unobserve = null;
19504
+ this.onHostMutation = () => {
19505
+ this.active = false;
19506
+ this.hasInactiveEntry = false;
19507
+ this.forwardAllowed = false;
19508
+ this.activeReference = undefined;
19509
+ this.inactiveReference = undefined;
19510
+ };
19511
+ this.onPopState = () => {
19512
+ if (this.destroyed)
19513
+ return;
19514
+ if (this.isMarkedEntry() && this.active && window.history.state === this.activeReference)
19515
+ return;
19516
+ if (this.isMarkedEntry() && this.forwardAllowed && this.mobile && !this.wantsPhone) {
19517
+ this.active = true;
19518
+ this.wantsPhone = true;
19519
+ this.activeReference = window.history.state;
19520
+ this.actions.onForward();
19521
+ return;
19522
+ }
19523
+ if (this.wantsPhone) {
19524
+ this.forwardAllowed = this.active;
19525
+ this.active = false;
19526
+ this.wantsPhone = false;
19527
+ this.activeReference = undefined;
19528
+ this.actions.onBack();
19529
+ }
19530
+ };
19531
+ window.addEventListener('popstate', this.onPopState);
19532
+ }
19533
+ sync(visible, mobile) {
19534
+ if (this.destroyed)
19535
+ return;
19536
+ this.mobile = mobile;
19537
+ if (!mobile)
19538
+ this.forwardAllowed = false;
19539
+ const wantsPhone = visible && mobile;
19540
+ if (wantsPhone === this.wantsPhone)
19541
+ return;
19542
+ this.wantsPhone = wantsPhone;
19543
+ if (wantsPhone)
19544
+ this.arm();
19545
+ else
19546
+ this.deactivate();
19547
+ }
19548
+ /** Explicit close also invalidates a forward entry after a neutral Back. */
19549
+ deactivate() {
19550
+ if (this.destroyed)
19551
+ return;
19552
+ this.wantsPhone = false;
19553
+ this.forwardAllowed = false;
19554
+ const ownsEntry = this.active && this.isMarkedEntry() && window.history.state === this.activeReference;
19555
+ this.active = false;
19556
+ this.activeReference = undefined;
19557
+ if (!ownsEntry)
19558
+ return;
19559
+ ownMutation(() => window.history.replaceState(this.baseState, '', this.url));
19560
+ this.inactiveReference = window.history.state;
19561
+ this.hasInactiveEntry = true;
19562
+ }
19563
+ destroy() {
19564
+ if (this.destroyed)
19565
+ return;
19566
+ this.deactivate();
19567
+ this.destroyed = true;
19568
+ window.removeEventListener('popstate', this.onPopState);
19569
+ this.unobserve?.();
19570
+ this.unobserve = null;
19571
+ }
19572
+ arm() {
19573
+ this.unobserve ?? (this.unobserve = observeHostMutations(this.onHostMutation));
19574
+ const reuse = this.hasInactiveEntry && window.location.href === this.url && window.history.state === this.inactiveReference;
19575
+ this.baseState = window.history.state;
19576
+ this.url = window.location.href;
19577
+ const value = this.baseState;
19578
+ const record = value !== null && typeof value === 'object' && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
19579
+ const state = record ? { ...value, [this.marker]: this.token } : { [this.marker]: this.token, hostState: value };
19580
+ try {
19581
+ ownMutation(() => {
19582
+ if (reuse)
19583
+ window.history.replaceState(state, '', this.url);
19584
+ else
19585
+ window.history.pushState(state, '', this.url);
19586
+ });
19587
+ this.activeReference = window.history.state;
19588
+ this.active = true;
19589
+ this.hasInactiveEntry = false;
19590
+ this.forwardAllowed = false;
19591
+ }
19592
+ catch {
19593
+ // A denied history write must never prevent someone contacting support.
19594
+ this.active = false;
19595
+ this.forwardAllowed = false;
19596
+ }
19597
+ }
19598
+ isMarkedEntry() {
19599
+ const state = window.history.state;
19600
+ return window.location.href === this.url && state !== null && typeof state === 'object' &&
19601
+ state[this.marker] === this.token;
19602
+ }
19603
+ }
19604
+
19605
+ /* global MediaQueryList, HTMLImageElement, HTMLAnchorElement, Element */
19606
+ let sequence = 0;
19607
+ function element(tag, className, text) {
19608
+ const node = document.createElement(tag);
19609
+ if (className)
19610
+ node.className = className;
19611
+ if (text !== undefined)
19612
+ node.textContent = text;
19613
+ return node;
19614
+ }
19615
+ function button(className, text, action) {
19616
+ const node = element('button', className, text);
19617
+ node.type = 'button';
19618
+ node.addEventListener('click', action);
19619
+ return node;
19620
+ }
19621
+ function icon(name) {
19622
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
19623
+ svg.setAttribute('viewBox', '0 0 24 24');
19624
+ svg.setAttribute('aria-hidden', 'true');
19625
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
19626
+ path.setAttribute('d', {
19627
+ back: 'm14.5 6-6 6 6 6',
19628
+ close: 'm6 6 12 12M18 6 6 18',
19629
+ external: 'M14 4h6v6m0-6L10 14M11 5H5a1 1 0 0 0-1 1v13a1 1 0 0 0 1 1h13a1 1 0 0 0 1-1v-6',
19630
+ check: 'm5 12 4 4L19 6',
19631
+ }[name]);
19632
+ svg.append(path);
19633
+ return svg;
19634
+ }
19635
+ function httpUrl(value, base = window.location.href) {
19636
+ if (!value)
19637
+ return null;
19638
+ try {
19639
+ const url = new URL(value, base);
19640
+ return (url.protocol === 'https:' || url.protocol === 'http:') && !url.username && !url.password ? url : null;
19641
+ }
19642
+ catch {
19643
+ return null;
19644
+ }
19645
+ }
19646
+ /**
19647
+ * The durable support surface. Every screen is kept, including the shared
19648
+ * contact form's mount node; navigating, minimizing and stacking Identity do
19649
+ * not destroy the caller's unsent composition.
19650
+ *
19651
+ * Desktop is deliberately nonmodal. Phone uses the SDK's shared ModalShell,
19652
+ * so its page lock and keyboard ownership compose with the Identity dialog.
19653
+ */
19654
+ class SupportView {
19655
+ constructor(actions) {
19656
+ this.actions = actions;
19657
+ this.contactTarget = element('div', 'svhs-contact-target');
19658
+ this.panel = element('section', 'svhs-panel');
19659
+ this.prefix = `svhs-${++sequence}`;
19660
+ this.screens = new Map();
19661
+ this.scrollers = new Map();
19662
+ this.scrollPositions = new Map();
19663
+ this.headings = new Map();
19664
+ this.deskName = element('span', 'svhs-desk-name');
19665
+ this.external = element('a', 'svhs-icon-button');
19666
+ this.issue = element('textarea', 'svhs-issue');
19667
+ this.issueError = element('p', 'svhs-error');
19668
+ this.query = element('p', 'svhs-query-text');
19669
+ this.resultList = element('ul', 'svhs-results');
19670
+ this.resultCopy = element('p', 'svhs-copy');
19671
+ this.resultStatus = element('div', 'svhs-empty');
19672
+ this.resultError = element('p', 'svhs-error');
19673
+ this.articleTitle = element('h2', 'svhs-article-title');
19674
+ this.articleCategory = element('p', 'svhs-category');
19675
+ this.articleContent = element('div', 'svhs-article-content');
19676
+ this.articleStatus = element('p', 'svhs-status');
19677
+ this.articleError = element('p', 'svhs-error');
19678
+ this.articleFooter = element('div', 'svhs-article-footer');
19679
+ this.contactTitle = element('h2', 'svhs-heading');
19680
+ this.contactStatus = element('p', 'svhs-status');
19681
+ this.contactError = element('p', 'svhs-error');
19682
+ this.ticketGate = element('div', 'svhs-ticket-gate');
19683
+ this.receiptCopy = element('p', 'svhs-copy');
19684
+ this.receiptTicket = element('a', 'svhs-ticket-link');
19685
+ this.receiptMessage = element('p', 'svhs-copy svhs-receipt-note');
19686
+ this.live = element('div', 'svhs-live');
19687
+ this.identityNotice = element('div', 'svhs-identity-notice');
19688
+ this.onMediaChange = () => this.syncPresentation();
19689
+ this.onViewportChange = () => this.syncViewport();
19690
+ this.shell = null;
19691
+ this.opener = null;
19692
+ this.state = null;
19693
+ this.resultSignature = '';
19694
+ this.resultStatusSignature = '';
19695
+ this.articleSignature = '';
19696
+ this.ticketGateSignature = '';
19697
+ this.toastCleanups = new Set();
19698
+ this.destroyed = false;
19699
+ injectHelpDeskSupportStyles();
19700
+ this.phoneHistory = actions.onBrowserBack && actions.onBrowserForward ? new SupportPhoneHistory({
19701
+ onBack: () => this.actions.onBrowserBack?.(),
19702
+ onForward: () => this.actions.onBrowserForward?.(),
19703
+ }) : null;
19704
+ this.panel.id = `${this.prefix}-panel`;
19705
+ this.panel.tabIndex = -1;
19706
+ this.panel.hidden = true;
19707
+ this.panel.setAttribute('aria-labelledby', `${this.prefix}-name`);
19708
+ this.deskName.id = `${this.prefix}-name`;
19709
+ this.live.setAttribute('role', 'status');
19710
+ this.live.setAttribute('aria-live', 'polite');
19711
+ const toolbar = element('header', 'svhs-toolbar');
19712
+ this.back = button('svhs-back', 'Back', () => this.actions.onBack());
19713
+ this.back.prepend(icon('back'));
19714
+ this.close = button('svhs-icon-button', '', () => this.actions.onClose());
19715
+ this.close.setAttribute('aria-label', 'Close support');
19716
+ this.close.append(icon('close'));
19717
+ this.external.setAttribute('aria-label', 'Open article in a new tab');
19718
+ this.external.title = 'Open article in a new tab';
19719
+ this.external.target = '_blank';
19720
+ this.external.rel = 'noopener noreferrer';
19721
+ this.external.append(icon('external'));
19722
+ const toolbarActions = element('div', 'svhs-toolbar-actions');
19723
+ toolbarActions.append(this.external, this.close);
19724
+ toolbar.append(this.back, this.deskName, toolbarActions);
19725
+ this.panel.append(toolbar);
19726
+ this.identityNotice.append(element('p', 'svhs-status', 'Sign-in is open in another window.'), button('svhs-text-button', 'Cancel sign-in', () => this.actions.onCancelIdentity?.()));
19727
+ this.identityNotice.hidden = true;
19728
+ this.panel.append(this.identityNotice);
19729
+ const intro = this.screen('issue', 'How can we help?');
19730
+ intro.append(element('p', 'svhs-copy', 'Tell us what you need. We’ll look for an answer in our help articles.'));
19731
+ const issueLabel = element('label', 'svhs-live', 'What do you need help with?');
19732
+ issueLabel.htmlFor = `${this.prefix}-issue`;
19733
+ this.issue.id = issueLabel.htmlFor;
19734
+ this.issue.name = 'support_issue';
19735
+ this.issue.placeholder = 'Describe your question or issue…';
19736
+ this.issue.autocomplete = 'off';
19737
+ this.issue.setAttribute('aria-describedby', `${this.prefix}-issue-error`);
19738
+ this.issueError.id = `${this.prefix}-issue-error`;
19739
+ this.issueError.setAttribute('role', 'alert');
19740
+ this.issueError.hidden = true;
19741
+ this.issue.addEventListener('input', () => {
19742
+ this.resizeIssue();
19743
+ this.issueError.hidden = true;
19744
+ this.issue.removeAttribute('aria-invalid');
19745
+ this.actions.onIssueChange(this.issue.value);
19746
+ });
19747
+ this.issue.addEventListener('keydown', (event) => {
19748
+ if ((event.metaKey || event.ctrlKey) && event.key === 'Enter' && !event.isComposing) {
19749
+ event.preventDefault();
19750
+ this.search();
19751
+ }
19752
+ });
19753
+ intro.append(issueLabel, this.issue, this.issueError);
19754
+ this.find = button('svhs-primary', 'Find answers', () => this.search());
19755
+ this.footer('issue', 'svhs-start-bottom').append(this.find, button('svhs-text-button', 'Contact support instead', () => this.actions.onContact('direct')));
19756
+ const results = this.screen('results', 'These may help');
19757
+ const queryLine = element('div', 'svhs-query');
19758
+ queryLine.append(this.query, button('svhs-text-button', 'Edit', () => this.actions.onBack()));
19759
+ results.append(this.resultCopy, queryLine, this.resultList, this.resultStatus, this.resultError);
19760
+ this.resultError.setAttribute('role', 'alert');
19761
+ this.contactResults = button('svhs-secondary svhs-full', 'None of these help. Contact support', () => {
19762
+ this.actions.onContact(this.state?.busy || ['locked', 'unavailable'].includes(this.state?.kbState || '') ? 'direct' : this.state?.results?.length ? 'none_match' : 'no_results');
19763
+ });
19764
+ this.footer('results').append(element('p', 'svhs-footer-copy', 'Still need a hand?'), this.contactResults);
19765
+ const article = this.screen('article');
19766
+ article.classList.add('svhs-article-scroll');
19767
+ this.articleTitle.tabIndex = -1;
19768
+ this.articleTitle.id = `${this.prefix}-article-title`;
19769
+ this.headings.set('article', this.articleTitle);
19770
+ this.articleStatus.setAttribute('role', 'status');
19771
+ this.articleError.setAttribute('role', 'alert');
19772
+ this.articleRetry = button('svhs-secondary', 'Try again', () => this.actions.onRetry?.());
19773
+ article.append(this.articleCategory, this.articleTitle, this.articleStatus, this.articleContent, this.articleError, this.articleRetry);
19774
+ this.articleContent.addEventListener('click', (event) => this.articleLink(event));
19775
+ const readerActions = element('div', 'svhs-reader-actions');
19776
+ readerActions.append(button('svhs-primary', 'Yes, thanks', () => { if (this.state?.article && !this.state.busy && !this.state.error)
19777
+ this.actions.onAnswered(); }), button('svhs-text-button', 'Contact support', () => this.actions.onContact('article_not_answered')));
19778
+ this.articleFooter.append(element('span', 'svhs-article-question', 'Did this answer your question?'), readerActions);
19779
+ this.screens.get('article').append(this.articleFooter);
19780
+ const feedback = this.screen('feedback', 'Did this answer your question?');
19781
+ feedback.classList.add('svhs-feedback-scroll');
19782
+ feedback.append(element('p', 'svhs-copy', 'Your feedback helps us improve our help articles.'));
19783
+ const feedbackActions = element('div', 'svhs-feedback-actions');
19784
+ feedbackActions.append(button('svhs-primary', 'Yes, that helped', () => this.actions.onAnswered()), button('svhs-secondary', 'No, contact support', () => this.actions.onContact('article_not_answered')), button('svhs-text-button', 'Not now', () => this.actions.onClose()));
19785
+ feedback.append(feedbackActions);
19786
+ const contact = this.screen('contact');
19787
+ contact.classList.add('svhs-contact-scroll');
19788
+ const contactPrelude = element('div', 'svhs-contact-prelude');
19789
+ this.contactTitle.tabIndex = -1;
19790
+ this.contactStatus.setAttribute('role', 'status');
19791
+ this.contactError.setAttribute('role', 'alert');
19792
+ this.contactError.id = `${this.prefix}-contact-error`;
19793
+ this.contactRetry = button('svhs-secondary', 'Try again', () => this.actions.onRetry?.());
19794
+ contactPrelude.append(this.contactTitle, this.contactStatus, this.contactError, this.contactRetry);
19795
+ contact.append(contactPrelude);
19796
+ contact.append(this.ticketGate);
19797
+ contact.append(this.contactTarget);
19798
+ const accountReturn = element('div', 'svhs-account-return');
19799
+ this.accountReturn = button('svhs-text-button', 'Use website account', () => this.actions.onUseWebsiteAccount?.());
19800
+ accountReturn.append(this.accountReturn);
19801
+ this.screens.get('contact').append(accountReturn);
19802
+ const receipt = this.screen('receipt', 'Message sent');
19803
+ receipt.classList.add('svhs-receipt-scroll');
19804
+ const receiptMark = icon('check');
19805
+ receiptMark.classList.add('svhs-receipt-mark');
19806
+ receipt.prepend(receiptMark);
19807
+ this.receiptTicket.target = '_blank';
19808
+ this.receiptTicket.rel = 'noopener noreferrer';
19809
+ receipt.append(this.receiptCopy, this.receiptTicket, this.receiptMessage);
19810
+ this.restart = button('svhs-text-button', 'Ask another question', () => this.actions.onRestart?.());
19811
+ const receiptFooter = this.footer('receipt', 'svhs-receipt-actions');
19812
+ receiptFooter.append(button('svhs-secondary svhs-full', 'Done', () => this.actions.onClose()), this.restart);
19813
+ this.panel.append(this.live);
19814
+ this.media = typeof window.matchMedia === 'function' ? window.matchMedia('(max-width:640px)') : null;
19815
+ this.media?.addEventListener('change', this.onMediaChange);
19816
+ window.visualViewport?.addEventListener('resize', this.onViewportChange);
19817
+ window.visualViewport?.addEventListener('scroll', this.onViewportChange);
19818
+ this.onKeydown = (event) => {
19819
+ if (this.shell || !this.state?.visible || this.destroyed || event.defaultPrevented || event.isComposing || event.keyCode === 229)
19820
+ return;
19821
+ // A nonmodal panel leaves the host's shortcuts alone once focus leaves.
19822
+ if (event.key !== 'Escape' || !this.panel.contains(document.activeElement))
19823
+ return;
19824
+ const activeDialog = document.activeElement?.closest('[role="dialog"],[role="alertdialog"],[aria-modal="true"]');
19825
+ if (activeDialog && activeDialog !== this.panel)
19826
+ return;
19827
+ event.preventDefault();
19828
+ this.actions.onClose();
19829
+ };
19830
+ document.addEventListener('keydown', this.onKeydown);
19831
+ }
19832
+ render(next) {
19833
+ if (this.destroyed)
19834
+ return;
19835
+ const previous = this.state;
19836
+ if (previous)
19837
+ this.saveScroll(previous);
19838
+ this.state = next;
19839
+ this.panel.dataset.stage = next.stage;
19840
+ const inset = (value, fallback) => typeof value === 'number' && Number.isFinite(value) ? Math.min(480, Math.max(0, value)) : fallback;
19841
+ this.panel.style.setProperty('--svhs-right', `${inset(next.position?.right, 24)}px`);
19842
+ this.panel.style.setProperty('--svhs-bottom', `${inset(next.position?.bottom, 96)}px`);
19843
+ this.deskName.textContent = next.deskName || 'Support';
19844
+ this.identityNotice.hidden = !next.identityPending || !this.actions.onCancelIdentity;
19845
+ this.restart.hidden = !this.actions.onRestart;
19846
+ this.back.hidden = !['results', 'article', 'feedback', 'contact'].includes(next.stage);
19847
+ this.back.disabled = Boolean(next.navigationLocked || next.identityPending);
19848
+ this.back.lastChild.textContent = next.stage === 'article' ? 'All answers' : next.stage === 'feedback' ? 'Keep reading' : 'Back';
19849
+ this.deskName.hidden = next.stage === 'article';
19850
+ this.panel.setAttribute('aria-labelledby', next.stage === 'article' ? this.articleTitle.id : this.deskName.id);
19851
+ for (const [stage, screen] of this.screens)
19852
+ screen.hidden = stage !== next.stage;
19853
+ if (this.issue.value !== next.issue)
19854
+ this.issue.value = next.issue;
19855
+ this.resizeIssue();
19856
+ this.find.setAttribute('aria-disabled', String(Boolean(next.busy)));
19857
+ this.find.setAttribute('aria-busy', String(Boolean(next.busy)));
19858
+ this.find.replaceChildren();
19859
+ if (next.busy)
19860
+ this.find.append(element('span', 'svhs-spinner'));
19861
+ this.find.append(document.createTextNode(next.busy ? 'Finding answers…' : 'Find answers'));
19862
+ this.issueError.textContent = next.stage === 'issue' ? next.error || '' : '';
19863
+ this.issueError.hidden = !this.issueError.textContent;
19864
+ this.query.textContent = next.issue;
19865
+ this.renderResults(next);
19866
+ this.renderArticle(next);
19867
+ this.accountReturn.parentElement.hidden = !next.returnToWebsiteAccount;
19868
+ this.contactTitle.textContent = `Contact ${next.deskName}`;
19869
+ this.contactTitle.hidden = !next.ticketAccessRequired && Boolean(this.contactTarget.querySelector('h1,h2,h3'));
19870
+ this.contactStatus.textContent = next.stage === 'contact' && next.busy ? next.ticketAccessRequired ? 'Checking support access…' : 'Connecting to support…' : '';
19871
+ this.contactStatus.hidden = !this.contactStatus.textContent;
19872
+ this.contactError.textContent = next.stage === 'contact' ? next.error || '' : '';
19873
+ this.contactError.hidden = !this.contactError.textContent;
19874
+ this.contactRetry.hidden = Boolean(next.ticketAccessRequired) || !this.contactError.textContent || !this.actions.onRetry || Boolean(next.busy);
19875
+ this.contactTitle.parentElement.hidden = this.contactTitle.hidden && this.contactStatus.hidden && this.contactError.hidden;
19876
+ this.renderTicketGate(next);
19877
+ this.renderReceipt(next);
19878
+ this.syncPresentation();
19879
+ if (!next.visible)
19880
+ return;
19881
+ if (!previous?.visible || previous.stage !== next.stage || previous.article?.id !== next.article?.id) {
19882
+ this.restoreScroll(next);
19883
+ this.focusCurrent();
19884
+ }
19885
+ }
19886
+ /** Programmatic close invalidates Forward restoration even after neutral Back. */
19887
+ deactivateHistory() {
19888
+ this.phoneHistory?.deactivate();
19889
+ }
19890
+ /** Focus the shared form after its controller has mounted it. */
19891
+ focusContact() {
19892
+ if (this.destroyed || !this.state?.visible || this.state.stage !== 'contact')
19893
+ return;
19894
+ const heading = this.contactTarget.querySelector('h1,h2,h3');
19895
+ this.contactTitle.hidden = Boolean(heading);
19896
+ this.contactTitle.parentElement.hidden = this.contactTitle.hidden && this.contactStatus.hidden && this.contactError.hidden;
19897
+ const target = heading ?? this.contactTarget;
19898
+ target.tabIndex = -1;
19899
+ target.focus({ preventScroll: true });
19900
+ }
19901
+ /** Hydrate only the current reader's matching authorized publication assets. */
19902
+ setArticleAsset(path, blobUrl) {
19903
+ if (this.destroyed || !blobUrl.startsWith('blob:'))
19904
+ return;
19905
+ for (const image of this.articleContent.querySelectorAll('img[data-kb-asset]')) {
19906
+ if (image.getAttribute('data-kb-asset') !== path)
19907
+ continue;
19908
+ image.src = blobUrl;
19909
+ image.hidden = false;
19910
+ const frame = image.closest('.svhs-reader-asset');
19911
+ if (frame) {
19912
+ frame.setAttribute('aria-busy', 'false');
19913
+ const status = frame.querySelector('.svhs-reader-asset-status');
19914
+ if (status)
19915
+ status.hidden = true;
19916
+ }
19917
+ }
19918
+ }
19919
+ setArticleAssetError(path) {
19920
+ if (this.destroyed)
19921
+ return;
19922
+ for (const image of this.articleContent.querySelectorAll('img[data-kb-asset]')) {
19923
+ if (image.getAttribute('data-kb-asset') !== path || image.hasAttribute('src'))
19924
+ continue;
19925
+ const frame = image.closest('.svhs-reader-asset');
19926
+ const status = frame?.querySelector('.svhs-reader-asset-status');
19927
+ if (!frame || !status)
19928
+ continue;
19929
+ frame.setAttribute('aria-busy', 'false');
19930
+ status.hidden = false;
19931
+ status.replaceChildren(document.createTextNode('This image couldn’t be loaded.'));
19932
+ const canonical = httpUrl(this.state?.article?.canonical_url);
19933
+ if (canonical) {
19934
+ const link = element('a', '', 'Open the full article');
19935
+ link.href = canonical.href;
19936
+ link.target = '_blank';
19937
+ link.rel = 'noopener noreferrer';
19938
+ link.setAttribute('data-svhs-canonical', 'true');
19939
+ status.append(document.createTextNode(' '), link);
19940
+ }
19941
+ }
19942
+ }
19943
+ /** A nonessential confirmation; timers pause while it cannot be read. */
19944
+ showToast(message) {
19945
+ if (this.destroyed || !message.trim())
19946
+ return;
19947
+ const toast = element('div', 'svhs-toast');
19948
+ toast.setAttribute('role', 'status');
19949
+ toast.setAttribute('aria-atomic', 'true');
19950
+ toast.append(icon('check'), document.createTextNode(message));
19951
+ document.body.append(toast);
19952
+ const arrange = () => {
19953
+ let offset = 0;
19954
+ for (const item of document.querySelectorAll('.svhs-toast')) {
19955
+ item.style.setProperty('--svhs-toast-offset', `${offset}px`);
19956
+ offset += item.getBoundingClientRect().height + 8;
19957
+ }
19958
+ };
19959
+ arrange();
19960
+ let remaining = 4000;
19961
+ let started = 0;
19962
+ let timer;
19963
+ let hovered = false;
19964
+ const pause = () => {
19965
+ if (timer === undefined)
19966
+ return;
19967
+ window.clearTimeout(timer);
19968
+ timer = undefined;
19969
+ remaining = Math.max(0, remaining - (Date.now() - started));
19970
+ };
19971
+ const cleanup = () => {
19972
+ pause();
19973
+ toast.remove();
19974
+ document.removeEventListener('visibilitychange', visibility);
19975
+ this.toastCleanups.delete(cleanup);
19976
+ arrange();
19977
+ };
19978
+ const resume = () => {
19979
+ if (timer !== undefined || document.hidden || hovered)
19980
+ return;
19981
+ started = Date.now();
19982
+ timer = window.setTimeout(cleanup, remaining);
19983
+ };
19984
+ const visibility = () => { if (document.hidden)
19985
+ pause();
19986
+ else
19987
+ resume(); };
19988
+ toast.addEventListener('pointerenter', () => { hovered = true; pause(); });
19989
+ toast.addEventListener('pointerleave', () => { hovered = false; resume(); });
19990
+ toast.addEventListener('focusin', pause);
19991
+ toast.addEventListener('focusout', resume);
19992
+ document.addEventListener('visibilitychange', visibility);
19993
+ this.toastCleanups.add(cleanup);
19994
+ resume();
19995
+ }
19996
+ destroy() {
19997
+ if (this.destroyed)
19998
+ return;
19999
+ this.destroyed = true;
20000
+ this.phoneHistory?.destroy();
20001
+ document.removeEventListener('keydown', this.onKeydown);
20002
+ this.media?.removeEventListener('change', this.onMediaChange);
20003
+ window.visualViewport?.removeEventListener('resize', this.onViewportChange);
20004
+ window.visualViewport?.removeEventListener('scroll', this.onViewportChange);
20005
+ for (const cleanup of [...this.toastCleanups])
20006
+ cleanup();
20007
+ this.hide();
20008
+ this.panel.remove();
20009
+ }
20010
+ screen(stage, title) {
20011
+ const screen = element('section', 'svhs-screen');
20012
+ screen.hidden = true;
20013
+ const body = element('div', 'svhs-scroll');
20014
+ if (title) {
20015
+ const heading = element('h2', 'svhs-heading', title);
20016
+ heading.tabIndex = -1;
20017
+ body.append(heading);
20018
+ this.headings.set(stage, heading);
20019
+ }
20020
+ screen.append(body);
20021
+ this.panel.append(screen);
20022
+ this.screens.set(stage, screen);
20023
+ this.scrollers.set(stage, body);
20024
+ return body;
20025
+ }
20026
+ footer(stage, extraClass = '') {
20027
+ const footer = element('div', `svhs-bottom ${extraClass}`.trim());
20028
+ this.screens.get(stage).append(footer);
20029
+ return footer;
20030
+ }
20031
+ search() {
20032
+ if (this.state?.busy)
20033
+ return;
20034
+ if (!this.issue.value.trim()) {
20035
+ this.issueError.textContent = 'Tell us a little about what you need help with.';
20036
+ this.issueError.hidden = false;
20037
+ this.issue.setAttribute('aria-invalid', 'true');
20038
+ this.issue.focus();
20039
+ return;
20040
+ }
20041
+ this.issue.removeAttribute('aria-invalid');
20042
+ this.actions.onSearch(this.issue.value);
20043
+ }
20044
+ resizeIssue() {
20045
+ if (!this.issue.isConnected || this.issue.closest('[hidden]'))
20046
+ return;
20047
+ this.issue.style.height = 'auto';
20048
+ const maximum = this.media?.matches ? 260 : 200;
20049
+ if (this.issue.scrollHeight)
20050
+ this.issue.style.height = `${Math.min(this.issue.scrollHeight, maximum)}px`;
20051
+ }
20052
+ renderResults(state) {
20053
+ const results = state.results ?? [];
20054
+ const signature = JSON.stringify(results);
20055
+ if (signature !== this.resultSignature) {
20056
+ this.resultSignature = signature;
20057
+ this.resultList.replaceChildren();
20058
+ for (const result of results) {
20059
+ const item = element('li');
20060
+ const open = button('svhs-result', '', () => this.actions.onOpenArticle(result.id));
20061
+ open.append(element('span', 'svhs-result-title', result.title));
20062
+ if (result.summary)
20063
+ open.append(element('span', 'svhs-result-excerpt', result.summary));
20064
+ if (result.category)
20065
+ open.append(element('span', 'svhs-result-category', result.category));
20066
+ item.append(open);
20067
+ this.resultList.append(item);
20068
+ }
20069
+ }
20070
+ this.resultCopy.textContent = results.length === 1 ? `1 suggestion from the ${state.deskName} help center.` : `${results.length} suggestions from the ${state.deskName} help center.`;
20071
+ this.resultList.hidden = Boolean(state.busy) || state.kbState === 'locked' || state.kbState === 'unavailable';
20072
+ this.resultCopy.hidden = this.resultList.hidden || results.length === 0;
20073
+ this.resultError.textContent = state.stage === 'results' ? state.error || '' : '';
20074
+ this.resultError.hidden = !this.resultError.textContent;
20075
+ this.renderResultStatus(state, results);
20076
+ for (const control of this.resultStatus.querySelectorAll('button')) {
20077
+ control.setAttribute('aria-disabled', String(Boolean(state.busy)));
20078
+ control.setAttribute('aria-busy', String(Boolean(state.busy)));
20079
+ }
20080
+ this.contactResults.textContent = results.length > 0 && !this.resultList.hidden ? 'None of these help. Contact support' : 'Contact support';
20081
+ }
20082
+ renderResultStatus(state, results) {
20083
+ const signature = state.kbState === 'locked' ? `locked:${state.kbAccessMode}` : state.busy ? 'busy' : state.kbState === 'unavailable' ? 'unavailable' : results.length ? 'matches' : 'empty';
20084
+ if (signature === this.resultStatusSignature)
20085
+ return;
20086
+ this.resultStatusSignature = signature;
20087
+ this.resultStatus.replaceChildren();
20088
+ this.resultStatus.hidden = false;
20089
+ if (state.busy && state.kbState !== 'locked') {
20090
+ this.resultStatus.append(element('p', 'svhs-status', 'Looking for answers…'));
20091
+ this.resultStatus.setAttribute('role', 'status');
20092
+ }
20093
+ else if (state.kbState === 'locked') {
20094
+ this.resultStatus.removeAttribute('role');
20095
+ this.resultStatus.append(element('h3', 'svhs-heading', 'These articles are protected'));
20096
+ if (state.kbAccessMode === 'password' && this.actions.onUnlock) {
20097
+ this.resultStatus.append(element('p', 'svhs-copy', 'Enter the help center password to view articles, or contact support below.'));
20098
+ const form = element('form', 'svhs-unlock-form');
20099
+ const label = element('label', 'svhs-label', 'Help center password');
20100
+ const input = element('input', 'svhs-unlock-input');
20101
+ input.id = `${this.prefix}-password`;
20102
+ input.type = 'password';
20103
+ input.autocomplete = 'current-password';
20104
+ input.required = true;
20105
+ label.htmlFor = input.id;
20106
+ const submit = button('svhs-secondary svhs-full', 'View articles', () => undefined);
20107
+ submit.type = 'submit';
20108
+ form.addEventListener('submit', (event) => { event.preventDefault(); if (!this.state?.busy)
20109
+ this.actions.onUnlock?.(input.value); });
20110
+ form.append(label, input, submit);
20111
+ this.resultStatus.append(form);
20112
+ }
20113
+ else if (state.kbAccessMode === 'identity' && this.actions.onUnlock) {
20114
+ this.resultStatus.append(element('p', 'svhs-copy', 'Sign in to view the help center, or contact support below.'), button('svhs-secondary svhs-full', 'Sign in to view articles', () => { if (!this.state?.busy)
20115
+ this.actions.onUnlock?.(); }));
20116
+ }
20117
+ else {
20118
+ this.resultStatus.append(element('p', 'svhs-copy', 'The help center isn’t available from this network. You can still contact support below.'));
20119
+ }
20120
+ }
20121
+ else if (state.kbState === 'unavailable') {
20122
+ this.resultStatus.removeAttribute('role');
20123
+ this.resultStatus.append(element('h3', 'svhs-heading', 'We couldn’t load the help center'), element('p', 'svhs-copy', 'Try again, or send your question to support. Your message is saved here.'));
20124
+ if (this.actions.onRetry)
20125
+ this.resultStatus.append(button('svhs-secondary', 'Try again', () => this.actions.onRetry?.()));
20126
+ }
20127
+ else if (results.length === 0) {
20128
+ this.resultStatus.removeAttribute('role');
20129
+ this.resultStatus.append(element('h3', 'svhs-heading', 'No matching articles'), element('p', 'svhs-copy', 'Try describing your question a different way, or contact our support team.'));
20130
+ }
20131
+ else
20132
+ this.resultStatus.hidden = true;
20133
+ }
20134
+ renderArticle(state) {
20135
+ const article = state.article;
20136
+ const url = httpUrl(article?.canonical_url || state.articleUrl);
20137
+ this.external.hidden = state.stage !== 'article' || !url;
20138
+ this.articleFooter.hidden = !article || Boolean(state.busy) || Boolean(state.error);
20139
+ if (url)
20140
+ this.external.href = url.href;
20141
+ else
20142
+ this.external.removeAttribute('href');
20143
+ this.articleStatus.hidden = !state.busy;
20144
+ this.articleStatus.textContent = state.busy ? 'Loading article…' : '';
20145
+ this.articleError.textContent = state.stage === 'article' ? state.error || '' : '';
20146
+ this.articleError.hidden = !this.articleError.textContent;
20147
+ this.articleRetry.hidden = !this.articleError.textContent || Boolean(state.busy) || !this.actions.onRetry;
20148
+ this.articleContent.hidden = Boolean(state.busy);
20149
+ this.articleTitle.textContent = article?.title || (state.error ? 'We couldn’t load this article' : 'Help article');
20150
+ const category = state.results?.find((result) => result.id === article?.id)?.category;
20151
+ this.articleCategory.textContent = category || '';
20152
+ this.articleCategory.hidden = !category;
20153
+ const signature = article ? `${article.release_id}:${article.id}:${article.body_html}` : '';
20154
+ if (signature === this.articleSignature)
20155
+ return;
20156
+ this.articleSignature = signature;
20157
+ this.articleContent.replaceChildren();
20158
+ if (!article)
20159
+ return;
20160
+ // The platform owns Markdown rendering and sanitization. Keep this a
20161
+ // second boundary for executable markup and URLs, not a second renderer.
20162
+ const template = element('template');
20163
+ template.innerHTML = article.body_html;
20164
+ template.content.querySelectorAll('script,style,iframe,object,embed,form,input,button,textarea,select,link,meta,base,svg,math,template').forEach((node) => node.remove());
20165
+ for (const node of template.content.querySelectorAll('*')) {
20166
+ for (const attribute of [...node.attributes]) {
20167
+ if (/^on/i.test(attribute.name) || ['style', 'srcdoc', 'formaction', 'autofocus'].includes(attribute.name))
20168
+ node.removeAttribute(attribute.name);
20169
+ }
20170
+ if (node.id)
20171
+ node.id = `${this.prefix}-article-${node.id}`;
20172
+ if (node instanceof HTMLAnchorElement) {
20173
+ const href = node.getAttribute('href') || '';
20174
+ if (href.startsWith('#'))
20175
+ node.setAttribute('href', href);
20176
+ else if (/^(?:mailto:|tel:)/i.test(href)) {
20177
+ // The canonical reader permits explicit email and telephone links.
20178
+ // They invoke the customer's chosen app rather than another KB view.
20179
+ node.href = href;
20180
+ node.removeAttribute('target');
20181
+ node.rel = 'noopener noreferrer';
20182
+ }
20183
+ else {
20184
+ const link = httpUrl(href, article.canonical_url);
20185
+ if (!link)
20186
+ node.removeAttribute('href');
20187
+ else {
20188
+ node.href = link.href;
20189
+ node.target = '_blank';
20190
+ node.rel = 'noopener noreferrer';
20191
+ }
20192
+ }
20193
+ }
20194
+ if (node instanceof HTMLImageElement) {
20195
+ // KbClient authorizes and rewrites every publication asset to a
20196
+ // memory-only URL. Reader content cannot turn into a tracking pixel.
20197
+ if (!node.getAttribute('src')?.startsWith('blob:'))
20198
+ node.removeAttribute('src');
20199
+ node.removeAttribute('srcset');
20200
+ node.loading = 'lazy';
20201
+ if (node.getAttribute('data-kb-asset') && !node.hasAttribute('src')) {
20202
+ const frame = element('span', 'svhs-reader-asset');
20203
+ frame.setAttribute('aria-busy', 'true');
20204
+ const status = element('span', 'svhs-reader-asset-status', 'Loading image…');
20205
+ if (node.width > 0 && node.height > 0)
20206
+ status.style.aspectRatio = `${node.width}/${node.height}`;
20207
+ node.replaceWith(frame);
20208
+ frame.append(status, node);
20209
+ node.hidden = true;
20210
+ node.addEventListener('error', () => {
20211
+ if (!this.articleContent.contains(node) || !node.getAttribute('src')?.startsWith('blob:'))
20212
+ return;
20213
+ node.removeAttribute('src');
20214
+ node.hidden = true;
20215
+ this.setArticleAssetError(node.getAttribute('data-kb-asset'));
20216
+ });
20217
+ }
20218
+ }
20219
+ }
20220
+ this.articleContent.append(template.content);
20221
+ }
20222
+ articleLink(event) {
20223
+ if (!(event.target instanceof Element))
20224
+ return;
20225
+ const link = event.target.closest('a[href]');
20226
+ if (!link || !this.articleContent.contains(link))
20227
+ return;
20228
+ if (link.hasAttribute('data-svhs-canonical'))
20229
+ return;
20230
+ const href = link.getAttribute('href') || '';
20231
+ if (href.startsWith('#')) {
20232
+ event.preventDefault();
20233
+ let id;
20234
+ try {
20235
+ id = decodeURIComponent(href.slice(1));
20236
+ }
20237
+ catch {
20238
+ return;
20239
+ }
20240
+ const target = document.getElementById(`${this.prefix}-article-${id}`);
20241
+ if (!target || !this.articleContent.contains(target))
20242
+ return;
20243
+ const scroll = this.scrollers.get('article');
20244
+ scroll.scrollTop += target.getBoundingClientRect().top - scroll.getBoundingClientRect().top - 24;
20245
+ return;
20246
+ }
20247
+ const articleUrl = httpUrl(this.state?.article?.canonical_url);
20248
+ const targetUrl = httpUrl(href, articleUrl?.href);
20249
+ if (articleUrl && targetUrl?.origin === articleUrl.origin && this.actions.onArticleLink) {
20250
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0)
20251
+ return;
20252
+ event.preventDefault();
20253
+ this.actions.onArticleLink(targetUrl.href);
20254
+ }
20255
+ }
20256
+ renderReceipt(state) {
20257
+ const receipt = state.receipt;
20258
+ this.receiptCopy.replaceChildren(document.createTextNode(receipt?.email ? 'Your message has been sent. We’ll reply to ' : 'Your message has been sent.'));
20259
+ if (receipt?.email)
20260
+ this.receiptCopy.append(element('strong', '', receipt.email), document.createTextNode('.'));
20261
+ this.receiptTicket.textContent = receipt?.ticketNumber !== undefined ? `Ticket #${receipt.ticketNumber}` : '';
20262
+ const ticketUrl = httpUrl(receipt?.ticketUrl);
20263
+ this.receiptTicket.hidden = !receipt?.ticketNumber;
20264
+ if (ticketUrl)
20265
+ this.receiptTicket.href = ticketUrl.href;
20266
+ else
20267
+ this.receiptTicket.removeAttribute('href');
20268
+ this.receiptMessage.textContent = receipt?.message || '';
20269
+ this.receiptMessage.hidden = !receipt?.message;
20270
+ }
20271
+ renderTicketGate(state) {
20272
+ this.ticketGate.hidden = !state.ticketAccessRequired;
20273
+ this.contactTarget.hidden = Boolean(state.ticketAccessRequired);
20274
+ const signature = state.ticketAccessRequired ? `${state.ticketAccessMode}:${state.ticketPortalUrl || ''}` : '';
20275
+ if (signature !== this.ticketGateSignature) {
20276
+ this.ticketGateSignature = signature;
20277
+ this.ticketGate.replaceChildren();
20278
+ if (state.ticketAccessRequired && state.ticketAccessMode === 'password') {
20279
+ this.ticketGate.append(element('p', 'svhs-copy', 'This support desk is password protected. Enter its password to continue. Your message is saved here.'));
20280
+ const form = element('form', 'svhs-unlock-form');
20281
+ const input = element('input', 'svhs-unlock-input');
20282
+ input.id = `${this.prefix}-ticket-password`;
20283
+ input.name = 'support-password';
20284
+ input.type = 'password';
20285
+ input.autocomplete = 'current-password';
20286
+ input.required = true;
20287
+ input.setAttribute('aria-describedby', this.contactError.id);
20288
+ const label = element('label', 'svhs-label', 'Ticket portal password');
20289
+ label.htmlFor = input.id;
20290
+ const submit = button('svhs-primary svhs-full', 'Continue', () => undefined);
20291
+ submit.type = 'submit';
20292
+ form.addEventListener('submit', (event) => {
20293
+ event.preventDefault();
20294
+ if (!this.state?.busy)
20295
+ this.actions.onUnlockTicketAccess?.(input.value);
20296
+ });
20297
+ form.append(label, input, submit);
20298
+ this.ticketGate.append(form);
20299
+ }
20300
+ else if (state.ticketAccessRequired && state.ticketAccessMode === 'identity') {
20301
+ this.ticketGate.append(element('p', 'svhs-copy', 'This support desk is for employees. Sign in with your employee email to continue. Your message is saved here.'), button('svhs-primary svhs-full', 'Sign in with employee email', () => { if (!this.state?.busy)
20302
+ this.actions.onUnlockTicketAccess?.(); }));
20303
+ }
20304
+ else if (state.ticketAccessRequired) {
20305
+ this.ticketGate.append(element('p', 'svhs-copy', 'Connect to an approved network to contact support. Your message is saved here.'), button('svhs-secondary svhs-full', 'Check access again', () => { if (!this.state?.busy)
20306
+ this.actions.onRetry?.(); }));
20307
+ }
20308
+ const portal = httpUrl(state.ticketPortalUrl);
20309
+ if (state.ticketAccessRequired && portal) {
20310
+ const link = element('a', 'svhs-text-button', 'Open support in a new tab');
20311
+ link.href = portal.href;
20312
+ link.target = '_blank';
20313
+ link.rel = 'noopener noreferrer';
20314
+ this.ticketGate.append(link);
20315
+ }
20316
+ }
20317
+ for (const control of this.ticketGate.querySelectorAll('button')) {
20318
+ control.setAttribute('aria-disabled', String(Boolean(state.busy)));
20319
+ control.setAttribute('aria-busy', String(Boolean(state.busy)));
20320
+ }
20321
+ }
20322
+ syncPresentation() {
20323
+ if (this.destroyed)
20324
+ return;
20325
+ this.phoneHistory?.sync(Boolean(this.state?.visible), Boolean(this.media?.matches));
20326
+ const active = this.panel.contains(document.activeElement) && document.activeElement instanceof HTMLElement ? document.activeElement : null;
20327
+ if (!this.state?.visible) {
20328
+ this.hide();
20329
+ return;
20330
+ }
20331
+ if (this.panel.hidden)
20332
+ this.opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
20333
+ this.panel.hidden = false;
20334
+ if (this.media?.matches) {
20335
+ if (!this.shell) {
20336
+ this.panel.removeAttribute('role');
20337
+ this.panel.removeAttribute('aria-modal');
20338
+ this.shell = new ModalShell({
20339
+ overlayId: `${this.prefix}-overlay`, modalId: `${this.prefix}-modal`, classPrefix: 'svhs',
20340
+ titleId: this.panel.getAttribute('aria-labelledby'), backdropBlur: false, onDismiss: () => this.actions.onClose(),
20341
+ });
20342
+ this.shell.modal.append(this.panel);
20343
+ active?.focus({ preventScroll: true });
20344
+ }
20345
+ }
20346
+ else {
20347
+ if (this.shell) {
20348
+ document.body.append(this.panel);
20349
+ this.shell.destroy();
20350
+ this.shell = null;
20351
+ active?.focus({ preventScroll: true });
20352
+ }
20353
+ else if (!this.panel.isConnected)
20354
+ document.body.append(this.panel);
20355
+ this.panel.setAttribute('role', 'dialog');
20356
+ this.panel.setAttribute('aria-modal', 'false');
20357
+ }
20358
+ this.resizeIssue();
20359
+ this.shell?.overlay.setAttribute('aria-labelledby', this.panel.getAttribute('aria-labelledby'));
20360
+ this.syncViewport();
20361
+ }
20362
+ syncViewport() {
20363
+ const viewport = window.visualViewport;
20364
+ if (!this.shell || !viewport)
20365
+ return;
20366
+ // Mobile keyboards shrink the visual viewport without always resizing
20367
+ // the CSS viewport. Keep the support actions above that keyboard. Zoom
20368
+ // remains the browser's own: never resize content to cancel its scale.
20369
+ if (viewport.scale === 1) {
20370
+ this.shell.overlay.style.top = `${viewport.offsetTop}px`;
20371
+ this.shell.overlay.style.height = `${viewport.height}px`;
20372
+ this.shell.overlay.style.bottom = 'auto';
20373
+ }
20374
+ else {
20375
+ this.shell.overlay.style.top = '';
20376
+ this.shell.overlay.style.height = '';
20377
+ this.shell.overlay.style.bottom = '';
20378
+ }
20379
+ }
20380
+ hide() {
20381
+ const wasVisible = !this.panel.hidden;
20382
+ this.panel.hidden = true;
20383
+ if (this.shell) {
20384
+ this.panel.remove();
20385
+ this.shell.destroy();
20386
+ this.shell = null;
20387
+ }
20388
+ this.panel.remove();
20389
+ if (wasVisible && this.opener?.isConnected)
20390
+ this.opener.focus({ preventScroll: true });
20391
+ }
20392
+ scrollKey(state) {
20393
+ return state.stage === 'article' ? `article:${state.article?.release_id}:${state.article?.id}` : state.stage;
20394
+ }
20395
+ saveScroll(state) {
20396
+ const scroll = this.scrollers.get(state.stage);
20397
+ if (scroll && state.visible)
20398
+ this.scrollPositions.set(this.scrollKey(state), scroll.scrollTop);
20399
+ }
20400
+ restoreScroll(state) {
20401
+ const scroll = this.scrollers.get(state.stage);
20402
+ if (scroll)
20403
+ scroll.scrollTop = this.scrollPositions.get(this.scrollKey(state)) ?? 0;
20404
+ }
20405
+ focusCurrent() {
20406
+ if (!this.state?.visible)
20407
+ return;
20408
+ if (this.state.stage === 'issue') {
20409
+ (this.media?.matches ? this.close : this.issue).focus({ preventScroll: true });
20410
+ }
20411
+ else if (this.state.stage === 'contact')
20412
+ this.focusContact();
20413
+ else
20414
+ (this.headings.get(this.state.stage) ?? this.panel).focus({ preventScroll: true });
20415
+ }
20416
+ }
20417
+
20418
+ function notify(callback, value) {
20419
+ try {
20420
+ void Promise.resolve(callback?.(value)).catch(() => undefined);
20421
+ }
20422
+ catch { /* Host callbacks do not own support state. */ }
20423
+ }
20424
+ function failure(value) { return value instanceof Error ? value : new Error('Support could not be loaded. Please try again.'); }
20425
+ function errorCode(value) { return value instanceof SparkVaultError ? value.serviceCode ?? value.code : undefined; }
20426
+ /** One state machine owns launcher, host links, KB suggestions and the ticket front door. */
20427
+ function createHelpDeskSupport(config, options) {
20428
+ if (typeof document === 'undefined' || !document.body)
20429
+ throw new ValidationError('Create support after the document body is available.');
20430
+ let destroyed = false;
20431
+ let sequence = 0;
20432
+ let connected = null;
20433
+ let client = null;
20434
+ let kb = null;
20435
+ let kbConfig = null;
20436
+ let contact = null;
20437
+ let contactCustomer = null;
20438
+ let contactOpening = false;
20439
+ let pendingComposition = null;
20440
+ let nativeIdentity = null;
20441
+ let switchedAccount = false;
20442
+ let attempt = null;
20443
+ let results = [];
20444
+ let requestedArticle = null;
20445
+ let articleRetrySearch = false;
20446
+ let cancelArticleAssets = null;
20447
+ const lifetime = new AbortController();
20448
+ const bindings = new Set();
20449
+ let state = { visible: false, stage: 'issue', deskName: 'Support', issue: '' };
20450
+ if (typeof options.launcher === 'object') {
20451
+ const offset = (value, fallback) => typeof value === 'number' && Number.isFinite(value) ? Math.min(240, Math.max(12, value)) : fallback;
20452
+ state.position = { right: offset(options.launcher.right, 24), bottom: offset(options.launcher.bottom, 24) + 72 };
20453
+ }
20454
+ const http = new HttpClient({ ...config, accessToken: undefined, getAccessToken: undefined, apiKey: undefined });
20455
+ const analytics = createSupportAnalytics({
20456
+ deskId: config.accountId,
20457
+ post: async (path, body) => {
20458
+ if (destroyed)
20459
+ throw new Error('Support is closed.');
20460
+ const prefix = `/hd/desks/${encodeURIComponent(config.accountId)}/support`;
20461
+ const suffix = path.slice(prefix.length);
20462
+ if (!path.startsWith(prefix))
20463
+ throw new Error('Invalid support analytics route.');
20464
+ const event = /^\/attempts\/([^/]+)\/events$/.exec(suffix);
20465
+ const route = suffix === '/visitor' ? apiPath `/v1/hd/desks/${config.accountId}/support/visitor`
20466
+ : suffix === '/attempts' ? apiPath `/v1/hd/desks/${config.accountId}/support/attempts`
20467
+ : event ? apiPath `/v1/hd/desks/${config.accountId}/support/attempts/${decodeURIComponent(event[1])}/events` : null;
20468
+ if (!route)
20469
+ throw new Error('Invalid support analytics route.');
20470
+ const headers = kb?.getAccessHeaders() ?? {};
20471
+ return (await http.request(route, { method: 'POST', body, credentials: 'omit', headers: { 'X-SV-Client': 'help-desk-portal', ...headers } })).data;
20472
+ },
20473
+ });
20474
+ const view = new SupportView({
20475
+ onIssueChange: (issue) => { state.issue = issue; },
20476
+ onSearch: (issue) => { void search(issue); },
20477
+ onContact: (reason) => { void showContact(reason); },
20478
+ onOpenArticle: (id) => { void openArticle(id); },
20479
+ onArticleLink: (url) => { void followArticle(url); },
20480
+ onBack: () => {
20481
+ if (destroyed || state.navigationLocked || state.identityPending)
20482
+ return;
20483
+ if (state.busy) {
20484
+ sequence += 1;
20485
+ contactOpening = false;
20486
+ }
20487
+ update({ busy: false });
20488
+ if (state.stage === 'feedback')
20489
+ update({ stage: 'article', error: undefined });
20490
+ else if (state.stage === 'article') {
20491
+ cancelArticleAssets?.();
20492
+ cancelArticleAssets = null;
20493
+ update({ stage: 'results', error: undefined, article: undefined, articleUrl: undefined });
20494
+ }
20495
+ else if (state.stage === 'contact')
20496
+ update({ stage: results.length || kbConfig ? 'results' : 'issue', error: undefined });
20497
+ else
20498
+ update({ stage: 'issue', error: undefined });
20499
+ },
20500
+ onClose: () => {
20501
+ if (state.stage === 'article' && state.article)
20502
+ update({ stage: 'feedback', error: undefined });
20503
+ else {
20504
+ if (state.stage === 'feedback')
20505
+ update({ stage: 'article' });
20506
+ minimize();
20507
+ }
20508
+ },
20509
+ onAnswered: () => {
20510
+ if (destroyed || !state.article)
20511
+ return;
20512
+ void attempt?.then((active) => active?.solved());
20513
+ contact?.destroy();
20514
+ contact = null;
20515
+ contactCustomer = null;
20516
+ cancelArticleAssets?.();
20517
+ cancelArticleAssets = null;
20518
+ minimize();
20519
+ view.showToast('We’re happy we could help.');
20520
+ sequence += 1;
20521
+ attempt = null;
20522
+ results = [];
20523
+ state = { visible: false, stage: 'issue', deskName: state.deskName, issue: '', position: state.position };
20524
+ update({});
20525
+ },
20526
+ onRestart: () => {
20527
+ contact?.destroy();
20528
+ contact = null;
20529
+ contactCustomer = null;
20530
+ cancelArticleAssets?.();
20531
+ cancelArticleAssets = null;
20532
+ sequence += 1;
20533
+ attempt = null;
20534
+ results = [];
20535
+ requestedArticle = null;
20536
+ pendingComposition = null;
20537
+ update({ stage: 'issue', issue: '', results: [], article: undefined, receipt: undefined, error: undefined, busy: false });
20538
+ },
20539
+ onRetry: () => {
20540
+ if (state.stage === 'contact')
20541
+ void showContact('direct');
20542
+ else if (state.stage === 'article' && articleRetrySearch)
20543
+ void search(state.issue);
20544
+ else if (state.stage === 'article' && requestedArticle)
20545
+ void readArticle(requestedArticle);
20546
+ else
20547
+ void search(state.issue);
20548
+ },
20549
+ onUnlock: (password) => { void unlock(password); },
20550
+ onUnlockTicketAccess: (password) => { void unlockTicketAccess(password); },
20551
+ onCancelIdentity: () => nativeIdentity?.abort(),
20552
+ onBrowserBack: minimize,
20553
+ onBrowserForward: () => update({ visible: true }),
20554
+ });
20555
+ const launcher = (() => {
20556
+ try {
20557
+ return options.launcher ? createSupportLauncher(typeof options.launcher === 'object' ? options.launcher : {}, () => { void open(); }) : null;
20558
+ }
20559
+ catch (error) {
20560
+ view.destroy();
20561
+ analytics.dispose();
20562
+ throw error;
20563
+ }
20564
+ })();
20565
+ function snapshot() { return { visible: state.visible, stage: state.stage, busy: state.busy === true }; }
20566
+ function update(change) {
20567
+ if (destroyed)
20568
+ return;
20569
+ state = { ...state, ...change };
20570
+ view.render(state);
20571
+ launcher?.setExpanded(state.visible);
20572
+ notify(options.onStateChange, snapshot());
20573
+ }
20574
+ async function connect() {
20575
+ if (!connected)
20576
+ connected = HelpDeskClient.connect(config, options).then((answer) => {
20577
+ if (destroyed)
20578
+ throw new Error('Support is closed.');
20579
+ client = answer;
20580
+ kb = new HelpDeskKnowledgeBaseClient(config, answer.desk.desk_id);
20581
+ update({ deskName: answer.desk.organization_name || 'Support' });
20582
+ return answer;
20583
+ }).catch((error) => { connected = null; throw error; });
20584
+ return connected;
20585
+ }
20586
+ async function open(input = {}) {
20587
+ if (destroyed)
20588
+ return;
20589
+ if (state.stage === 'issue' && !state.issue && input.issue)
20590
+ state.issue = input.issue.slice(0, 12000);
20591
+ update({ visible: true });
20592
+ try {
20593
+ await connect();
20594
+ }
20595
+ catch (value) {
20596
+ if (!destroyed) {
20597
+ const error = failure(value);
20598
+ update({ error: error.message });
20599
+ notify(options.onError, error);
20600
+ }
20601
+ }
20602
+ }
20603
+ function minimize() { update({ visible: false }); }
20604
+ function signIn(input = {}) {
20605
+ if (!client)
20606
+ return Promise.reject(new Error('Support is still loading. Please try again.'));
20607
+ nativeIdentity?.abort();
20608
+ const operation = new AbortController();
20609
+ nativeIdentity = operation;
20610
+ const cancel = () => operation.abort();
20611
+ lifetime.signal.addEventListener('abort', cancel, { once: true });
20612
+ // This call must remain synchronous with the invoking user gesture.
20613
+ const result = client.signInWidgetIdentity({ ...input, signal: operation.signal });
20614
+ update({ identityPending: true });
20615
+ return result.finally(() => {
20616
+ lifetime.signal.removeEventListener('abort', cancel);
20617
+ if (nativeIdentity === operation) {
20618
+ nativeIdentity = null;
20619
+ update({ identityPending: false });
20620
+ }
20621
+ });
20622
+ }
20623
+ function startAttempt(available, releaseId, resultCount) {
20624
+ if (!attempt)
20625
+ attempt = available && releaseId !== undefined && resultCount !== undefined
20626
+ ? analytics.start({ availability: 'available', releaseId, resultCount })
20627
+ : analytics.start({ availability: 'unavailable' });
20628
+ return attempt;
20629
+ }
20630
+ async function search(issue) {
20631
+ if (destroyed || !issue.trim())
20632
+ return;
20633
+ const ownSequence = ++sequence;
20634
+ update({ stage: 'results', issue: issue.slice(0, 12000), busy: true, error: undefined, results: [], article: undefined, kbState: undefined });
20635
+ results = [];
20636
+ try {
20637
+ const active = await connect();
20638
+ if (destroyed || ownSequence !== sequence)
20639
+ return;
20640
+ if (!active.desk.knowledge_base_enabled) {
20641
+ update({ busy: false, kbState: 'unavailable' });
20642
+ await showContact('direct');
20643
+ return;
20644
+ }
20645
+ kbConfig = await kb.load();
20646
+ if (destroyed || ownSequence !== sequence)
20647
+ return;
20648
+ if (!kbConfig.available || !kbConfig.search_enabled) {
20649
+ update({ busy: false, kbState: 'unavailable' });
20650
+ await showContact('direct');
20651
+ return;
20652
+ }
20653
+ if (!kbConfig.authorized) {
20654
+ update({ busy: false, kbState: 'locked', kbAccessMode: kbConfig.access.mode === 'public' ? undefined : kbConfig.access.mode });
20655
+ return;
20656
+ }
20657
+ const answer = await kb.search(state.issue);
20658
+ if (destroyed || ownSequence !== sequence)
20659
+ return;
20660
+ results = answer.results;
20661
+ update({ busy: false, results, kbState: results.length ? 'ready' : 'empty' });
20662
+ startAttempt(true, answer.release_id, results.length);
20663
+ }
20664
+ catch (value) {
20665
+ if (destroyed || ownSequence !== sequence)
20666
+ return;
20667
+ const error = failure(value);
20668
+ const locked = ['KB_ACCESS_REQUIRED', 'KB_IP_RESTRICTED'].includes(errorCode(value) ?? '');
20669
+ update({ busy: false, kbState: locked ? 'locked' : 'unavailable', kbAccessMode: kbConfig?.access.mode === 'public' ? undefined : kbConfig?.access.mode, error: error.message });
20670
+ notify(options.onError, error);
20671
+ }
20672
+ }
20673
+ async function unlock(password) {
20674
+ if (destroyed || !kb || state.busy)
20675
+ return;
20676
+ const ownSequence = ++sequence;
20677
+ update({ busy: true, error: undefined });
20678
+ try {
20679
+ if (password !== undefined)
20680
+ await kb.unlock({ password });
20681
+ else {
20682
+ // A platform grant proves employee access independently of the host's ticket identity.
20683
+ if (!client)
20684
+ throw new Error('Support is still loading. Please try again.');
20685
+ const session = await signIn({ employeeCompanyId: kbConfig?.access.company_id });
20686
+ await kb.unlock({ identity_grant: session.identity_grant.token });
20687
+ }
20688
+ if (destroyed || ownSequence !== sequence)
20689
+ return;
20690
+ await search(state.issue);
20691
+ }
20692
+ catch (value) {
20693
+ if (destroyed || ownSequence !== sequence)
20694
+ return;
20695
+ const error = failure(value);
20696
+ update({ busy: false, error: error.message });
20697
+ notify(options.onError, error);
20698
+ }
20699
+ }
20700
+ async function readArticle(result) {
20701
+ cancelArticleAssets?.();
20702
+ cancelArticleAssets = null;
20703
+ requestedArticle = result;
20704
+ articleRetrySearch = false;
20705
+ const ownSequence = ++sequence;
20706
+ update({ stage: 'article', busy: true, error: undefined, article: undefined, articleUrl: result.canonical_url });
20707
+ try {
20708
+ const article = await kb.read(result);
20709
+ if (destroyed || ownSequence !== sequence)
20710
+ return;
20711
+ update({ article, busy: false });
20712
+ cancelArticleAssets = kb.hydrateAssets(article, {
20713
+ onAsset: (path, url) => { if (!destroyed && ownSequence === sequence && state.article?.id === article.id)
20714
+ view.setArticleAsset(path, url); },
20715
+ onError: (path) => { if (!destroyed && ownSequence === sequence && state.article?.id === article.id)
20716
+ view.setArticleAssetError(path); },
20717
+ });
20718
+ void attempt?.then((active) => active?.articleOpened(article.id, article.release_id));
20719
+ }
20720
+ catch (value) {
20721
+ if (destroyed || ownSequence !== sequence)
20722
+ return;
20723
+ const error = failure(value);
20724
+ articleRetrySearch = ['KB_PUBLICATION_CHANGED', 'KB_DOCUMENT_NOT_FOUND', 'KB_ACCESS_REQUIRED', 'KB_IP_RESTRICTED'].includes(errorCode(error) ?? '');
20725
+ update({ busy: false, error: error.message });
20726
+ notify(options.onError, error);
20727
+ }
20728
+ }
20729
+ async function openArticle(id) {
20730
+ const result = results.find((candidate) => candidate.id === id);
20731
+ if (result && kb)
20732
+ await readArticle(result);
20733
+ }
20734
+ async function followArticle(url) {
20735
+ if (!kb || destroyed)
20736
+ return;
20737
+ const ownSequence = sequence;
20738
+ try {
20739
+ const result = await kb.resolveLink(url);
20740
+ if (destroyed || ownSequence !== sequence)
20741
+ return;
20742
+ if (result)
20743
+ await readArticle(result);
20744
+ else
20745
+ window.open(url, '_blank', 'noopener,noreferrer');
20746
+ }
20747
+ catch (value) {
20748
+ const error = failure(value);
20749
+ update({ error: error.message });
20750
+ notify(options.onError, error);
20751
+ }
20752
+ }
20753
+ function mountContact(composition, customer) {
20754
+ if (!client || destroyed)
20755
+ return;
20756
+ contactCustomer = customer;
20757
+ let activeAttempt = null;
20758
+ contact = mountHelpDeskForm(client, {
20759
+ target: view.contactTarget,
20760
+ ...composition,
20761
+ attachments: options.attachments,
20762
+ widgetIdentity: {
20763
+ customer,
20764
+ signIn: (input) => signIn(input).then((session) => { contactCustomer = session.customer; return session; }),
20765
+ switchAccount: (safe) => { void switchAccount(safe); },
20766
+ ...(switchedAccount && (options.getSessionToken || options.getIdentityAssertion || options.identityEndpoint) ? { useWebsiteAccount: (safe) => { void useWebsiteAccount(safe); } } : {}),
20767
+ },
20768
+ assistanceContext: () => activeAttempt?.ticketContext(),
20769
+ onError: (error) => {
20770
+ notify(options.onError, error);
20771
+ if (['HELP_DESK_ACCESS_REQUIRED', 'HELP_DESK_IP_DENIED'].includes(errorCode(error) ?? ''))
20772
+ window.queueMicrotask(() => {
20773
+ void client?.refreshTicketAccessPolicy().catch(() => undefined).then(() => {
20774
+ if (destroyed || contact !== activeForm)
20775
+ return;
20776
+ const policy = client?.ticketAccessPolicy;
20777
+ update({ ticketAccessRequired: true, ticketAccessMode: policy?.mode === 'public' ? undefined : policy?.mode,
20778
+ ticketPortalUrl: `https://${client.desk.canonical_host}/requests/new`, error: error.message });
20779
+ });
20780
+ });
20781
+ },
20782
+ onCancel: () => { contact = null; minimize(); },
20783
+ onSuccess: (ticket) => receipt(ticket),
20784
+ onStateChange: (next) => update({ navigationLocked: ['authenticating', 'submitting', 'uncertain'].includes(next) }),
20785
+ });
20786
+ const activeForm = contact;
20787
+ void attempt?.then((active) => {
20788
+ // Keep the mutable callback small: an analytics response arriving late
20789
+ // must not delay contact, authentication or ticket submission.
20790
+ if (contact === activeForm && active)
20791
+ activeAttempt = active;
20792
+ });
20793
+ view.focusContact();
20794
+ }
20795
+ async function showContact(reason) {
20796
+ if (destroyed || contactOpening)
20797
+ return;
20798
+ cancelArticleAssets?.();
20799
+ cancelArticleAssets = null;
20800
+ if (reason === 'direct' && state.kbState === 'unavailable' && !attempt) {
20801
+ void startAttempt(false).then((active) => active?.contactRequested());
20802
+ }
20803
+ if (reason !== 'direct')
20804
+ void attempt?.then((active) => active?.contactRequested(reason));
20805
+ update({ stage: 'contact', busy: !contact || state.ticketAccessRequired, error: undefined });
20806
+ contactOpening = true;
20807
+ const ownSequence = ++sequence;
20808
+ try {
20809
+ const active = await connect();
20810
+ await active.refreshTicketAccessPolicy();
20811
+ if (destroyed || ownSequence !== sequence)
20812
+ return;
20813
+ if (!active.hasTicketAccess) {
20814
+ const policy = active.ticketAccessPolicy;
20815
+ update({ busy: false, ticketAccessRequired: true, ticketAccessMode: policy?.mode === 'public' ? undefined : policy?.mode,
20816
+ ticketPortalUrl: `https://${active.desk.canonical_host}/requests/new` });
20817
+ return;
20818
+ }
20819
+ if (contact) {
20820
+ contact.resumeAfterAccess();
20821
+ update({ busy: false, ticketAccessRequired: false, ticketAccessMode: undefined });
20822
+ view.focusContact();
20823
+ return;
20824
+ }
20825
+ const token = await active.getSessionToken();
20826
+ const customer = token ? await active.getMe() : null;
20827
+ if (destroyed || ownSequence !== sequence)
20828
+ return;
20829
+ update({ busy: false, ticketAccessRequired: false, ticketAccessMode: undefined });
20830
+ mountContact(pendingComposition ?? { subject: state.issue.trim().split(/\n|(?<=[.!?])\s/)[0].slice(0, 200), body: state.issue }, customer);
20831
+ pendingComposition = null;
20832
+ }
20833
+ catch (value) {
20834
+ if (destroyed || ownSequence !== sequence)
20835
+ return;
20836
+ const error = failure(value);
20837
+ const gate = ['HELP_DESK_ACCESS_REQUIRED', 'HELP_DESK_IP_DENIED'].includes(errorCode(error) ?? '');
20838
+ update({ busy: false, error: error.message, ...(gate && { ticketAccessRequired: true,
20839
+ ticketAccessMode: client?.ticketAccessPolicy?.mode === 'public' ? undefined : client?.ticketAccessPolicy?.mode,
20840
+ ticketPortalUrl: `https://${client.desk.canonical_host}/requests/new` }) });
20841
+ notify(options.onError, error);
20842
+ }
20843
+ finally {
20844
+ if (ownSequence === sequence)
20845
+ contactOpening = false;
20846
+ }
20847
+ }
20848
+ async function unlockTicketAccess(password) {
20849
+ if (destroyed || !client || state.busy)
20850
+ return;
20851
+ const ownSequence = ++sequence;
20852
+ const active = client;
20853
+ const policy = active.ticketAccessPolicy;
20854
+ // Native Identity must be invoked before the first await in this gesture.
20855
+ const identity = policy?.mode === 'identity' ? signIn({ employeeCompanyId: policy.company_id }) : null;
20856
+ update({ busy: true, error: undefined });
20857
+ try {
20858
+ if (policy?.mode === 'password')
20859
+ await active.unlockTicketAccess({ password });
20860
+ else if (identity) {
20861
+ const session = await identity;
20862
+ await active.unlockTicketAccess({ identityGrant: session.identity_grant.token });
20863
+ const hostToken = await active.getSessionToken();
20864
+ if (!hostToken)
20865
+ active.setSession(session);
20866
+ }
20867
+ else
20868
+ throw new Error('Connect to an approved network, then try again.');
20869
+ if (destroyed || ownSequence !== sequence)
20870
+ return;
20871
+ update({ busy: false, ticketAccessRequired: false, ticketAccessMode: undefined });
20872
+ await showContact('direct');
20873
+ }
20874
+ catch (value) {
20875
+ if (destroyed || ownSequence !== sequence)
20876
+ return;
20877
+ const error = failure(value);
20878
+ update({ busy: false, error: error.message });
20879
+ notify(options.onError, error);
20880
+ }
20881
+ }
20882
+ async function switchAccount(composition) {
20883
+ if (!client || destroyed || state.navigationLocked)
20884
+ return;
20885
+ const ownSequence = ++sequence;
20886
+ const active = client;
20887
+ contact?.destroy();
20888
+ contact = null;
20889
+ cancelArticleAssets?.();
20890
+ cancelArticleAssets = null;
20891
+ pendingComposition = composition ?? { subject: '', body: '' };
20892
+ kb?.clearAccess();
20893
+ kbConfig = null;
20894
+ results = [];
20895
+ requestedArticle = null;
20896
+ attempt = null;
20897
+ update({ results: [], article: undefined, articleUrl: undefined, kbState: undefined });
20898
+ switchedAccount = true;
20899
+ const logout = active.switchSupportAccount();
20900
+ // Open synchronously in the Not you? gesture, before awaiting revocation.
20901
+ const signingIn = signIn({ selectAccount: true, employeeCompanyId: active.ticketAccessPolicy?.mode === 'identity' ? active.ticketAccessPolicy.company_id : undefined });
20902
+ update({ stage: 'contact', busy: true, error: undefined });
20903
+ try {
20904
+ const [, session] = await Promise.all([logout, signingIn]);
20905
+ if (destroyed || ownSequence !== sequence)
20906
+ return;
20907
+ if (active.ticketAccessPolicy?.mode === 'identity')
20908
+ await active.unlockTicketAccess({ identityGrant: session.identity_grant.token });
20909
+ if (destroyed || ownSequence !== sequence)
20910
+ return;
20911
+ active.setSession(session);
20912
+ update({ busy: false });
20913
+ await showContact('direct');
20914
+ }
20915
+ catch (value) {
20916
+ await logout.catch(() => undefined);
20917
+ if (destroyed || ownSequence !== sequence)
20918
+ return;
20919
+ const error = failure(value);
20920
+ update({ busy: false, error: error.message });
20921
+ if (active.hasTicketAccess) {
20922
+ mountContact(composition ?? { subject: '', body: '' }, null);
20923
+ pendingComposition = null;
20924
+ }
20925
+ else
20926
+ await showContact('direct');
20927
+ }
20928
+ }
20929
+ async function useWebsiteAccount(composition) {
20930
+ if (!client || destroyed || state.navigationLocked)
20931
+ return;
20932
+ const ownSequence = ++sequence;
20933
+ contact?.destroy();
20934
+ contact = null;
20935
+ cancelArticleAssets?.();
20936
+ cancelArticleAssets = null;
20937
+ pendingComposition = composition ?? { subject: '', body: '' };
20938
+ kb?.clearAccess();
20939
+ kbConfig = null;
20940
+ results = [];
20941
+ requestedArticle = null;
20942
+ attempt = null;
20943
+ update({ busy: true, error: undefined, results: [], article: undefined, articleUrl: undefined, kbState: undefined });
20944
+ try {
20945
+ await client.useWebsiteAccount();
20946
+ if (destroyed || ownSequence !== sequence)
20947
+ return;
20948
+ switchedAccount = false;
20949
+ update({ busy: false });
20950
+ await showContact('direct');
20951
+ }
20952
+ catch (value) {
20953
+ if (destroyed || ownSequence !== sequence)
20954
+ return;
20955
+ const error = failure(value);
20956
+ update({ busy: false, error: error.message });
20957
+ if (client.hasTicketAccess) {
20958
+ mountContact(composition ?? { subject: '', body: '' }, null);
20959
+ pendingComposition = null;
20960
+ }
20961
+ else
20962
+ await showContact('direct');
20963
+ }
20964
+ }
20965
+ function receipt(ticket) {
20966
+ const customer = contactCustomer;
20967
+ update({ stage: 'receipt', busy: false, error: undefined, receipt: {
20968
+ ticketNumber: ticket.number,
20969
+ ticketUrl: `https://${client.desk.canonical_host}/requests/${ticket.number}`,
20970
+ ...(customer?.email_updates === true && customer.email_verified !== false ? { email: customer.email } : {}),
20971
+ message: client.desk.ticket_confirmation_message ?? undefined,
20972
+ } });
20973
+ notify(options.onSuccess, ticket);
20974
+ // A completed journey must never reopen an old draft or its file authority.
20975
+ contact?.destroy();
20976
+ contact = null;
20977
+ contactCustomer = null;
20978
+ }
20979
+ return {
20980
+ open,
20981
+ close: () => { view.deactivateHistory(); minimize(); },
20982
+ getState: snapshot,
20983
+ attach(selector) {
20984
+ if (destroyed)
20985
+ return () => undefined;
20986
+ const detach = attachClickHandler(selector, (event) => { event.preventDefault(); void open(); });
20987
+ const cleanup = () => { detach(); bindings.delete(cleanup); };
20988
+ bindings.add(cleanup);
20989
+ return cleanup;
20990
+ },
20991
+ destroy() {
20992
+ if (destroyed)
20993
+ return;
20994
+ destroyed = true;
20995
+ sequence += 1;
20996
+ lifetime.abort();
20997
+ for (const cleanup of bindings)
20998
+ cleanup();
20999
+ contact?.destroy();
21000
+ contact = null;
21001
+ cancelArticleAssets?.();
21002
+ cancelArticleAssets = null;
21003
+ kb?.destroy();
21004
+ kb = null;
21005
+ analytics.dispose();
21006
+ launcher?.destroy();
21007
+ view.destroy();
21008
+ // Only this support client is cleared; the host site's sign-in is untouched.
21009
+ client?.clearTicketAccess();
21010
+ client?.setSession(null);
21011
+ client = null;
21012
+ state = { visible: false, stage: 'issue', deskName: 'Support', issue: '' };
21013
+ },
21014
+ };
21015
+ }
21016
+
21017
+ class HelpDeskModule {
21018
+ constructor(config) {
21019
+ this.config = config;
21020
+ }
21021
+ /** Resolve a configured desk host and obtain its customer-only, headless API. */
21022
+ connect(options) {
21023
+ return HelpDeskClient.connect(this.config, options);
21024
+ }
21025
+ /** Create one KB-first support front door, with an optional floating launcher. */
21026
+ createSupport(options) {
21027
+ return createHelpDeskSupport(this.config, options);
18227
21028
  }
18228
21029
  /**
18229
21030
  * Inject a ticket form, including email-code verification where the desk
@@ -22206,7 +25007,7 @@ class SparkVault {
22206
25007
  }
22207
25008
  /** Get the SDK version */
22208
25009
  static get version() {
22209
- return '15.2.0';
25010
+ return '15.3.0';
22210
25011
  }
22211
25012
  }
22212
25013
  if (typeof window !== 'undefined') {