@ahoy-ai/web 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/LICENSE +21 -0
  3. package/README.md +93 -2
  4. package/dist/ahoy.js +2 -0
  5. package/dist/esm/api-url.d.ts +7 -0
  6. package/dist/esm/api-url.d.ts.map +1 -0
  7. package/dist/esm/api-url.js +11 -0
  8. package/dist/esm/api-url.js.map +1 -0
  9. package/dist/esm/index.d.ts +11 -0
  10. package/dist/esm/index.d.ts.map +1 -0
  11. package/dist/esm/index.js +10 -0
  12. package/dist/esm/index.js.map +1 -0
  13. package/dist/esm/loader/ahoy.d.ts +198 -0
  14. package/dist/esm/loader/ahoy.d.ts.map +1 -0
  15. package/dist/esm/loader/ahoy.js +642 -0
  16. package/dist/esm/loader/ahoy.js.map +1 -0
  17. package/dist/esm/loader/global.d.ts +12 -0
  18. package/dist/esm/loader/global.d.ts.map +1 -0
  19. package/dist/esm/loader/global.js +65 -0
  20. package/dist/esm/loader/global.js.map +1 -0
  21. package/dist/esm/loader/launcher.d.ts +34 -0
  22. package/dist/esm/loader/launcher.d.ts.map +1 -0
  23. package/dist/esm/loader/launcher.js +135 -0
  24. package/dist/esm/loader/launcher.js.map +1 -0
  25. package/dist/esm/loader/navigation.d.ts +2 -0
  26. package/dist/esm/loader/navigation.d.ts.map +1 -0
  27. package/dist/esm/loader/navigation.js +37 -0
  28. package/dist/esm/loader/navigation.js.map +1 -0
  29. package/dist/esm/loader/style.d.ts +9 -0
  30. package/dist/esm/loader/style.d.ts.map +1 -0
  31. package/dist/esm/loader/style.js +13 -0
  32. package/dist/esm/loader/style.js.map +1 -0
  33. package/dist/esm/protocol.d.ts +127 -0
  34. package/dist/esm/protocol.d.ts.map +1 -0
  35. package/dist/esm/protocol.js +58 -0
  36. package/dist/esm/protocol.js.map +1 -0
  37. package/dist/esm/version.d.ts +3 -0
  38. package/dist/esm/version.d.ts.map +1 -0
  39. package/dist/esm/version.js +3 -0
  40. package/dist/esm/version.js.map +1 -0
  41. package/package.json +70 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,28 @@
1
+ # @ahoy-ai/web
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - caff64b: The chat says when it can't reach support. A message whose every send attempt got no HTTP response from the Ahoy API (a network error or a timeout each time: offline, a host that doesn't resolve, a dropped connection) is now told apart from one the API answered with an error. In the web chat panel such a message, once it has failed, reads "Couldn't reach support. Tap to retry." on touch screens or "Couldn't reach support. Click to retry." when a mouse or trackpad is the main pointer (`(pointer: fine)`), and the whole line retries it; other failures keep "Not sent" and Retry. While such a message is still being tried, a line above the composer says "Can't reach support right now. We'll keep trying." (in place of the offline banner, which may not be true then), in a polite `aria-live` region. Once such a message has failed, the offline or reconnecting banner stays hidden too (the web panel still shows it if the browser reports no network). All three strings (`chat.unreachable`, `message.unreachable`, `message.unreachableClick`) ship in all 20 languages; React Native always uses the "Tap" wording. In `@ahoy-ai/core`: `ChatMessage.failureReason` and `OutboxItem.failureReason` (`'unreachable' | 'error'`, type `SendFailureReason`), `ChatState.unreachable`, and `isUnreachable(error)`. Sending works as before: 5 automatic attempts with backoff, Retry, and resending on reconnect and foreground.
8
+ - 3fa49b7: A deleted app stands down. When an app is deleted in the Ahoy dashboard, the API answers 410 `app_deleted` on every `/sdk/v1` route and closes the app's sockets. The SDK now treats that answer, at startup or mid-session, as final for the session: no launcher, no chat panel (an open one closes), `Ahoy.open()` does nothing and warns once in the console, nothing more is sent (no reconnects, polling, events, profile updates or push registration), and one console line says why. The one exception is `deleteData()`: the API accepts an end user's data deletion for a deleted app, so the SDK still sends it (token refresh and `DELETE /devices/me`, never a new registration), clears the data on the device and resolves; if an older API answers 410, it still clears the local data and resolves, with one console line saying the server copy was not deleted. A realtime `error` frame with code `app_deleted` stops the SDK without another request. Queued events and the stored session are kept, and nothing is cached: the SDK asks the API again on the next page load or app launch, so an app restored in the dashboard (within 30 days) works again with the same visitors and history. Developers can see it as the `app_deleted` event (`onEvent`), the `app_deleted` status in the core state, `getState().appDeleted` on `window.Ahoy`, and the `useAhoyAppDeleted()` hook in `@ahoy-ai/react`, to hide their own Support button. The panel's `stopped` message carries `{ reason: 'app_deleted' }` (an optional payload within protocol 1; older loaders ignore it).
9
+
10
+ On websites, the loader (`ahoy.js`, and the loader bundled in `@ahoy-ai/web` and `@ahoy-ai/react`) now checks first: at `configure`, alongside the page-idle wait, it sends `GET <api>/sdk/v1/apps/<appId>/status` (a CORS simple request: no cookies, no custom headers, no preflight; the browser may reuse the answer for 5 minutes). On 410 `app_deleted` it creates nothing (no iframe, no launcher, no panel download, no config request), sets `getState().appDeleted`, sends the `app_deleted` event to `onEvent` listeners and logs one console line; `open()` does nothing and warns once, and `deleteData()` loads the panel hidden for that one call. Every other outcome fails open and loads the panel as before: 200, 404 for an App ID that never existed (a typo keeps showing the launcher), other errors, a network error, a Content-Security-Policy that blocks the request, or no answer within 3 seconds. The panel's own 410 handling stays as a second line of defence. Sites with a strict Content-Security-Policy add the Ahoy API to `connect-src` for the check (without it the chat loads as usual).
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [caff64b]
15
+ - Updated dependencies [3fa49b7]
16
+ - @ahoy-ai/core@0.2.0
17
+
18
+ ## 0.1.1
19
+
20
+ ### Patch Changes
21
+
22
+ - Web devices now send the page origin when they refresh their session token and when they update the device, so the API can apply "App settings → Web" on every visit, not only the first one. A refused origin keeps the session and stops the widget instead of registering a new visitor; the loader removes the launcher. Also: Pip welcome illustration, dark-mode polish, send button spacing and a `data-app-id`-first snippet.
23
+ - Updated dependencies
24
+ - @ahoy-ai/core@0.1.1
25
+
26
+ ## 0.1.0
27
+
28
+ - First release (ADR 0017 phase 3).
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NOJU LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ # @ahoy-ai/web
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ In-app support chat for websites and web apps: the same chat, inbox and AI agent as Ahoy's mobile SDK, with a launcher button and a chat panel (ADR 0017). Most sites paste the script tag; bundlers can install this package; React apps use [`@ahoy-ai/react`](../react).
4
+
5
+ ## Script tag
6
+
7
+ Paste before `</body>` (or in your site builder's custom-code field):
8
+
9
+ <!-- prettier-ignore -->
10
+ ```html
11
+ <script>window.Ahoy=window.Ahoy||{q:[],identify:function(){this.q.push(['identify',arguments])},open:function(){this.q.push(['open'])}};</script>
12
+ <script data-app-id="app_XXXX" async src="https://cdn.ahoysupport.com/web/v1/ahoy.js"></script>
13
+ ```
14
+
15
+ The first line is a queue stub: `Ahoy.identify(...)` and `Ahoy.open()` work before `ahoy.js` has loaded and are replayed in order once it has. `ahoy.js` runs before the page's `load` event and then replaces the stub with the full `window.Ahoy`; call the other methods (`setMetadata`, `track`, `logout`) after that.
16
+
17
+ | Attribute | Meaning |
18
+ | -------------------------------- | -------------------------------------------------------------------------------------- |
19
+ | `data-app-id` | Your App ID (`app_XXXX`). Without it nothing starts until `Ahoy.configure({ appId })`. |
20
+ | `data-environment="development"` | Turns on the setup check and development warnings. |
21
+ | `data-launcher="false"` | Hides the built-in button; open the chat with `Ahoy.open()` from your own. |
22
+ | `data-position="left"` | Overrides the launcher side published in the dashboard design (default: that side). |
23
+ | `data-language="de"` | Forces the chat's language (default: the page's `<html lang>`, then the browser's). |
24
+ | `data-api-url` | A local Ahoy API; used only with `data-environment="development"`. |
25
+
26
+ The panel is always loaded from `/web/v1/frame.html` on the same CDN as `ahoy.js` (or the CDN the file was built for, `AHOY_CDN_URL`).
27
+
28
+ ## npm
29
+
30
+ ```ts
31
+ import { getAhoy } from '@ahoy-ai/web';
32
+
33
+ const ahoy = getAhoy(); // window.Ahoy, created on first call
34
+ ahoy.configure({ appId: 'app_XXXX', environment: 'development' });
35
+ await ahoy.identify({ token }); // after login; ahoy.logout() on sign-out
36
+ ```
37
+
38
+ The npm entry is the loader only (about 5 KB gzip): no panel, no Preact, no runtime dependencies, and nothing touches `window` until you call it. The panel still comes from the CDN (`cdnUrl`, default `https://cdn.ahoysupport.com`); set `cdnUrl: 'http://localhost:4400'` for the local panel server.
39
+
40
+ ## `window.Ahoy`
41
+
42
+ The same names as the mobile SDK where they apply: `configure`, `identify`, `setMetadata`, `track`, `open`, `close`, `onEvent`, `logout`, `deleteData`, `appearance`, `runSetupCheck`. For framework wrappers: `getState()` (`{ ready, open, unread, appDeleted }`) and `subscribe(listener)`.
43
+
44
+ - Calls made before the panel is ready are queued. Methods that return a promise resolve once the call is queued for the panel: a refused identity token arrives as an `identity_rejected` event (`Ahoy.onEvent`), and the setup check result is logged in the browser console.
45
+ - `identify({ token })` takes the same HS256 token as mobile, signed by **your server**. The identity secret never ships to the browser: mint the token in a server route and fetch it after login.
46
+ - Not on web: `registerPush` (resolves `{ registered: false, reason: 'unsupported' }`), `notificationBehavior` (null), `onOffer` and `setPaywalls` (ignored). They exist so shared code compiles, and warn once in development.
47
+ - The panel sets the reserved metadata key `page` (the path, no query string) on every navigation, so your inbox shows where the visitor is; a `setMetadata({ page })` of your own is overwritten.
48
+
49
+ ## How it works
50
+
51
+ - **Loader** (`ahoy.js`, in your page): draws the launcher (a round button in your published accent color, with an unread badge), creates the panel iframe at page idle, and talks to it over `postMessage` (ADR 0017's message table; every message is `{ channel: 'ahoy', protocol: 1, type, payload }`, and both sides check the sender's origin). It adds no inline script or style to your page. Before it creates the panel, it checks that the app still exists (below), from your page to the Ahoy API. Sites with a strict Content-Security-Policy allow `script-src` and `frame-src` for the CDN and `connect-src` for the API (`https://api.dev.ahoysupport.com` today); without `connect-src` the browser blocks the check and the chat loads as usual.
52
+ - **Panel** (`frame.html` on the CDN): `@ahoy-ai/core` with browser adapters and a Preact chat UI. It holds the session (its own `localStorage`, which your page's scripts can't read; browsers partition it per site), the history cache (IndexedDB) and the WebSocket (`/ws?token=`). In private windows or with storage blocked, the session lives in memory and a reload starts a new one.
53
+ - **Layout**: a 400 × 700 panel 20 px from the side on desktop, as high above the bottom as the launcher; under 640 px the panel covers the viewport with its close button always visible. The launcher hides while the panel is open.
54
+ - **Launcher place**: the side and the bottom offset (0 to 200 px, default bottom right, 20 px up) come from the published chat design (the dashboard's chat design editor, or `ahoy_set_chat_design`), so the button can clear a cookie bar or a bottom navigation. A side set in code (`data-position`, `position`) wins over the published side. The panel waits up to 3 seconds for the published design before the launcher appears, so it shows once, in place.
55
+ - **Accessibility**: the panel is a labelled dialog; focus moves to the message field on open and back to the launcher on close, Escape closes, Tab stays inside, and new support messages are announced through a live region.
56
+ - **Sending**: messages go out one at a time in order. Network errors, timeouts, 429 and 5xx retry with backoff; after 5 attempts the message shows a retry action, and it is retried on its own when the socket reconnects or the tab becomes visible again. When no attempt got any answer from the Ahoy API (offline, or the host can't be reached), a polite live line above the composer says "Can't reach support right now. We'll keep trying." while it is still being tried, and the failed message reads "Couldn't reach support. Tap to retry." on touch screens or "… Click to retry." with a mouse or trackpad (the whole line retries). A message the API answered with an error shows "Not sent" with Retry.
57
+ - **Photos**: a file picker (the phone's own picker offers the camera), resized on a canvas to 2,048 px on the longest edge as JPEG, then uploaded with the same presigned POST as mobile. Queued photos keep their bytes in IndexedDB, so they survive a reload.
58
+ - **Deleted apps**: when the app was deleted in the Ahoy dashboard, the API answers 410 `app_deleted`. The loader asks first: at `configure`, alongside the page-idle wait, it sends `GET <api>/sdk/v1/apps/<appId>/status` (no cookies, no custom headers, so no preflight; the browser may reuse the answer for 5 minutes). On 410 `app_deleted` it creates nothing: no iframe, no launcher, no panel download and no config request: the page fetches nothing from Ahoy beyond `ahoy.js` (on the script-tag route) and this check. Any other answer (including 404 for an App ID that never existed, so a typo still shows the launcher), a network error, a blocked request or no answer within 3 seconds loads the panel as before; the check never delays the panel past the 3 seconds the idle wait can already take. The panel's own check stays as a second line: it learns about the deletion at startup (from `GET /config` or the registration), before it answers `ready`, so the launcher never appears; if the app is deleted during a visit, an open panel closes and the launcher is removed. `Ahoy.open()` then does nothing and warns once in the console, `getState().appDeleted` is `true`, `onEvent` listeners get an `app_deleted` event, and the panel sends nothing more (no reconnects or polling). `Ahoy.deleteData()` still works: the panel sends the end user's data deletion, which the API accepts for a deleted app, and clears the data stored in the browser. When the loader's check found the app deleted, `deleteData()` loads the panel hidden for that one call. Nothing is stored: the next page load asks again (the browser may reuse the status answer for up to 5 minutes), so an app restored in the dashboard within 30 days works again with the same visitors and history.
59
+ - **Allowed websites**: the panel sends your page's origin (from the referrer) when it registers, and again on every token refresh and device update, so a returning visitor's stored session is checked too. If the app lists allowed websites (dashboard App settings → Web) and yours isn't one, the API refuses (403 `origin_not_allowed`): the launcher never appears (or is removed, when the list changed during a visit), the panel sends nothing more until the page reloads, and the console says why.
60
+ - **`apiUrl`**: used only with `environment: 'development'` (a local API while building). In production the panel always uses the hosted API and the console says the `apiUrl` was ignored.
61
+ - **Setup check** (`environment: 'development'`): sent once per SDK version and origin, the first time the chat's socket connects (or falls back to polling), so it can report the origin, the config and the socket.
62
+ - Review cards and paywall offers are mobile-only; the panel hides them.
63
+
64
+ ## Develop
65
+
66
+ ```sh
67
+ pnpm build # dist/esm (npm), dist/ahoy.js and dist/frame/ (CDN)
68
+ pnpm test # Jest (jsdom): protocol, loader, adapters, bridge and panel UI
69
+ pnpm size # loader 12 KB, panel 70 KB gzip (ADR 0017 budgets)
70
+ pnpm dev # the local panel server on http://localhost:4400 (below)
71
+ pnpm e2e # Playwright on Chromium, Firefox and WebKit (below)
72
+ ```
73
+
74
+ Build variables: `AHOY_CDN_URL` (the CDN base the loader opens `<AHOY_CDN_URL>/web/v1/frame.html` on; unset: the origin `ahoy.js` was loaded from) and `AHOY_DEFAULT_API_URL` (the API the panel uses when the page names none; default the dev API).
75
+
76
+ CDN layout (what `ahoy-sdk/.github/workflows/deploy-cdn.yml` publishes): `dist/ahoy.js` → `/web/v1/ahoy.js` (and `/web/<version>/ahoy.js`), `dist/frame/frame.html` → `/web/v1/frame.html`, `dist/frame/assets/*` (content-hashed) → `/web/v1/assets/*`. `frame.html` has no inline script; it needs the CSP of CONTRACT C7.
77
+
78
+ ### Local panel server (port 4400)
79
+
80
+ `pnpm dev` builds into `.dev/` (never `dist/`) and serves the loader and panel like the CDN, plus demo host pages on a second origin:
81
+
82
+ - `http://localhost:4400/web/v1/ahoy.js`, `.../frame.html`: the loader and the panel (with the frame CSP).
83
+ - `http://127.0.0.1:4400/demo/?app=app_demo`: a host page with the two-line snippet (`&api=`, `&launcher=false`, `&position=left`, `&language=`, `&open=1` to call `Ahoy.open()` through the stub).
84
+ - `http://127.0.0.1:4400/demo/strict?app=app_demo`: the same under a strict CSP (`script-src`/`frame-src` the panel server, `connect-src` the API), no inline script; `&connect=none` leaves the API out of `connect-src` (the loader's status check is blocked and fails open).
85
+
86
+ `AHOY_API_URL` (default `http://localhost:8787`) is the API the panel uses there; `PORT` changes the port; `AHOY_DEV_WATCH=1` rebuilds on each request. The local API must accept the panel's origin in CORS (CONTRACT C10).
87
+
88
+ ### End-to-end tests
89
+
90
+ `pnpm e2e` starts `e2e/mock-api.mjs` (a mock `/sdk/v1` and `/ws` on port 8840) and the panel server, then runs `e2e/chat.spec.ts` on Chromium, Firefox and WebKit: anonymous chat (registration as web with the origin, the web setup check, `page` metadata), SPA navigation, photo upload (resized to 2,048 px, JPEG), identify with a token and a refused token, reconnect after a dropped socket, the unread badge across a reload, the mobile viewport, the desktop panel size, keyboard and axe (WCAG 2.1 AA), the queue stub, a strict-CSP page (with and without the API in `connect-src`), a deleted app (no iframe, no panel download, only the status request), a refused origin, and a returning visitor refused at the token refresh or a device update after the allowed list changed.
91
+
92
+ Against a real API: `AHOY_E2E_API_URL=http://localhost:8787 AHOY_E2E_APP_ID=app_demo pnpm e2e` (tests that need the mock's controls are skipped). `AHOY_E2E_REUSE=1` reuses servers you started yourself; `AHOY_E2E_PANEL_PORT=8841` runs the panel server on another port than 4400, and `AHOY_E2E_MOCK_PORT=8842` the mock API on another port than 8840.
93
+
94
+ Browsers: `npx playwright install chromium-headless-shell firefox webkit` (userland, in `~/.cache/ms-playwright`). WebKit on Linux needs `libevent-2.1-7t64 libavif16 libmanette-0.2-0` (`sudo npx playwright install-deps webkit`). On the build machine they were installed without sudo: `apt-get download` of those packages plus `libgav1-1` and `libhidapi-hidraw0`, extracted with `dpkg -x` to `~/.local/opt/playwright-webkit-deps`, and symlinked into `~/.cache/ms-playwright/webkit-2388/minibrowser-wpe/sys/lib` (redo after a Playwright browser update).
package/dist/ahoy.js ADDED
@@ -0,0 +1,2 @@
1
+ /*! Ahoy web loader 0.2.0 | MIT */
2
+ "use strict";(()=>{var k=Object.defineProperty;var H=(i,e,t)=>e in i?k(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var r=(i,e,t)=>H(i,typeof e!="symbol"?e+"":e,t);var I="https://api.dev.ahoysupport.com";function v(i,e){return(i==="development"&&e||I).replace(/\/+$/,"")}var T=[1],g="ahoy";var b=new Set(["ready","unread","resize","event","opened","closed","stopped"]);function A(i){return{channel:g,protocol:1,...i}}function w(i,e){if(!i||typeof i!="object")return null;let t=i;return t.channel!==g||typeof t.type!="string"||!e.has(t.type)||typeof t.protocol!="number"||!T.includes(t.protocol)?null:i}function y(i){if(!i)return null;try{let{protocol:e,host:t}=new URL(i);return e!=="http:"&&e!=="https:"?null:`${e}//${t}`.toLowerCase()}catch{return null}}function l(i,e){for(let[t,n]of Object.entries(e))i.style.setProperty(t,n,"important")}var u=2147483e3;var E="http://www.w3.org/2000/svg",C="M4 5.5A2.5 2.5 0 0 1 6.5 3h11A2.5 2.5 0 0 1 20 5.5v9a2.5 2.5 0 0 1-2.5 2.5H10l-4.2 3.6A.5.5 0 0 1 5 20.2V17h0a2.5 2.5 0 0 1-1-2Z",c=class{constructor(e,t){r(this,"doc",e);r(this,"host");r(this,"button");r(this,"badge");r(this,"label");r(this,"unread",0);this.label=t.label,this.host=e.createElement("div"),this.host.setAttribute("data-ahoy","launcher"),l(this.host,{position:"fixed","z-index":String(u),margin:"0"});let n=this.host.attachShadow?this.host.attachShadow({mode:"open"}):this.host,o=e.createElement("button");o.type="button",o.setAttribute("aria-haspopup","dialog"),o.setAttribute("aria-expanded","false"),o.setAttribute("aria-controls",t.controls),l(o,{all:"initial",display:"flex","align-items":"center","justify-content":"center",width:"56px",height:"56px","border-radius":"50%",cursor:"pointer","box-shadow":"0 6px 20px rgba(15, 23, 42, 0.24)",transition:"transform .15s ease",position:"relative",outline:"none"}),o.addEventListener("click",t.onClick),o.addEventListener("pointerenter",()=>l(o,{transform:"scale(1.06)"})),o.addEventListener("pointerleave",()=>l(o,{transform:"none"})),o.addEventListener("focus",()=>{D(o,":focus-visible")&&l(o,{"box-shadow":"0 0 0 3px #ffffff, 0 0 0 6px #111827"})}),o.addEventListener("blur",()=>l(o,{"box-shadow":"0 6px 20px rgba(15, 23, 42, 0.24)"}));let s=e.createElementNS(E,"svg");s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("width","28"),s.setAttribute("height","28"),s.setAttribute("aria-hidden","true"),s.setAttribute("focusable","false");let a=e.createElementNS(E,"path");a.setAttribute("d",C),a.setAttribute("fill","#ffffff"),s.appendChild(a),o.appendChild(s);let p=e.createElement("span");p.setAttribute("aria-hidden","true"),l(p,{all:"initial",position:"absolute",top:"-4px",right:"-4px","min-width":"20px",height:"20px",padding:"0 6px","box-sizing":"border-box","border-radius":"10px",background:"#d92d20",color:"#ffffff",font:'600 12px/20px system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',"text-align":"center",border:"2px solid #ffffff",display:"none"}),o.appendChild(p),n.appendChild(o),this.button=o,this.badge=p,this.setPosition(t.position,t.bottomOffset),this.setAccent(t.accent),this.render()}setPosition(e,t){l(this.host,{bottom:`${t}px`,...e==="left"?{left:"20px",right:"auto"}:{right:"20px",left:"auto"}})}setAccent(e){l(this.button,{background:e})}setLabel(e){this.label=e,this.render()}setUnread(e){this.unread=Math.max(0,Math.floor(e)),this.render()}setExpanded(e){this.button.setAttribute("aria-expanded",String(e))}setVisible(e){l(this.host,{display:e?"block":"none"})}focus(){this.button.focus()}remove(){this.host.remove()}render(){let e=this.unread;this.badge.textContent=e>99?"99+":String(e),l(this.badge,{display:e>0?"block":"none"}),this.button.setAttribute("aria-label",e>0?`${this.label} (${e})`:this.label)}};function D(i,e){try{return i.matches(e)}catch{return!0}}var O=Symbol.for("ahoy.history"),m="ahoy:locationchange";function x(i,e){let t=i.history;if(!t[O]){t[O]=!0;for(let s of["pushState","replaceState"]){let a=t[s];t[s]=function(...p){let h=a.apply(this,p);return i.dispatchEvent(new Event(m)),h}}}let n=null,o=()=>{let s=i.location.pathname||"/";s!==n&&(n=s,e(s))};return i.addEventListener("popstate",o),i.addEventListener(m,o),o(),()=>{i.removeEventListener("popstate",o),i.removeEventListener(m,o)}}var R="https://cdn.ahoysupport.com",W="/web/v1/frame.html",N=/^app_[A-Za-z0-9]+$/,$=400,P=700,f=20,F=200,q=640,V=1e4,z=500,Y=3e3,B=0,d=class{constructor(e={window,document},t=null){r(this,"env",e);r(this,"scriptSrc",t);r(this,"options",null);r(this,"frameUrl","");r(this,"frameOrigin","");r(this,"iframe",null);r(this,"launcher",null);r(this,"state",{ready:!1,open:!1,unread:0,appDeleted:!1});r(this,"listeners",new Set);r(this,"subscribers",new Set);r(this,"queue",[]);r(this,"wantOpen",!1);r(this,"mode","panel");r(this,"panelHeight",P);r(this,"position","right");r(this,"bottomOffset",f);r(this,"title","Support");r(this,"currentAppearance",{});r(this,"cleanups",[]);r(this,"idleHandle",null);r(this,"returnFocus",null);r(this,"stopped",!1);r(this,"gate","live");r(this,"mountWanted",!1);r(this,"warned",new Set);r(this,"frameId",`ahoy-frame-${++B}`)}configure(e){if(!e||typeof e.appId!="string"||!N.test(e.appId)){console.error('[Ahoy] configure: appId must look like "app_XXXX".');return}let t=this.options;this.options={...e},e.appearance&&(this.currentAppearance={...e.appearance});let n=this.resolveFrameUrl(e);if(t&&t.appId===e.appId&&t.apiUrl===e.apiUrl&&n===this.frameUrl&&(this.iframe||this.idleHandle||this.gate!=="live")){this.applyLauncherVisibility(),this.state.ready&&this.sendConfigure();return}this.teardown(t===null),this.frameUrl=n,this.frameOrigin=y(n)??"";let o=a=>this.onMessage(a);this.env.window.addEventListener("message",o);let s=()=>this.layout();this.env.window.addEventListener("resize",s),this.cleanups.push(()=>this.env.window.removeEventListener("message",o),()=>this.env.window.removeEventListener("resize",s)),this.checkStatus(e),this.wantOpen?this.mount():this.idleHandle=X(this.env.window,()=>this.mount())}identify(e){return this.send({type:"identify",payload:[e]}),Promise.resolve()}setMetadata(e,t){return this.send({type:"setMetadata",payload:t?[e,t]:[e]}),Promise.resolve()}track(e,t,n){let o=[e];(t!==void 0||n!==void 0)&&o.push(t),n!==void 0&&o.push(n),this.send({type:"track",payload:o})}open(){if(this.stopped){this.state.appDeleted&&!this.warned.has("open_app_deleted")&&(this.warned.add("open_app_deleted"),console.warn(`[Ahoy] open() ignored: app ${this.options?.appId??""} was deleted in the Ahoy dashboard.`));return}this.wantOpen=!0,this.options&&(this.iframe||this.mount(),this.state.ready&&this.post({type:"open"}))}close(){this.wantOpen=!1,this.state.ready&&this.post({type:"close"})}onEvent(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}logout(){return this.send({type:"logout"}),Promise.resolve()}deleteData(){return this.stopped&&this.state.appDeleted?this.iframe?this.post({type:"deleteData"}):this.eraseWithoutPanel():this.send({type:"deleteData"}),Promise.resolve()}get appearance(){return this.currentAppearance}set appearance(e){this.currentAppearance={...e??{}},this.options&&(this.options.appearance=this.currentAppearance),this.state.ready&&this.sendConfigure()}runSetupCheck(){return this.send({type:"runSetupCheck"}),Promise.resolve()}registerPush(){return this.warnOnce("registerPush","[Ahoy] registerPush: push is not available on web yet."),Promise.resolve({registered:!1,reason:"unsupported"})}notificationBehavior(){return this.warnOnce("notificationBehavior","[Ahoy] notificationBehavior: not available on web."),null}onOffer(e){return this.warnOnce("onOffer","[Ahoy] onOffer: offer cards are not shown on web."),()=>{}}setPaywalls(e){this.warnOnce("setPaywalls","[Ahoy] setPaywalls: paywall offers are not shown on web.")}getState(){return this.state}subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}destroy(){this.teardown(),this.options=null,this.wantOpen=!1}resolveFrameUrl(e){return`${(e.cdnUrl??null??y(this.scriptSrc)??R).replace(/\/+$/,"")}${W}`}checkStatus(e){let t=this.env.window;if(typeof t.fetch!="function")return;this.gate="pending";let n=typeof AbortController=="function"?new AbortController:null,o=!1,s=M=>{if(!o){if(o=!0,clearTimeout(a),M)return this.onAppDeletedBeforePanel();this.gate="live",this.mountWanted&&this.mount()}},a=setTimeout(()=>{n?.abort(),s(!1)},Y);this.cleanups.push(()=>{o=!0,clearTimeout(a),n?.abort()});let p=`${v(e.environment,e.apiUrl)}/sdk/v1/apps/${e.appId}/status`,h;try{h=t.fetch(p,{credentials:"omit",...n?{signal:n.signal}:{}})}catch{return s(!1)}h.then(G).then(s,()=>s(!1))}onAppDeletedBeforePanel(){let e=this.queue.some(t=>t.type==="deleteData");this.gate="deleted",this.stopped=!0,this.queue=[],this.wantOpen=!1,this.mountWanted=!1,this.idleHandle?.(),this.idleHandle=null,this.setState({appDeleted:!0}),console.warn(`[Ahoy] App ${this.options?.appId??""} was deleted in the Ahoy dashboard, so the chat is off and nothing is loaded. It checks again on the next page load; restoring the app in the dashboard turns the chat back on (within 5 minutes for visitors who already saw it off).`),this.dispatch({type:"app_deleted",at:Date.now()}),e&&this.eraseWithoutPanel()}eraseWithoutPanel(){this.queue=[{type:"deleteData"}],this.mount(!0)}mount(e=!1){if(this.idleHandle?.(),this.idleHandle=null,this.iframe||!this.options)return;if(!e&&this.gate!=="live"){this.mountWanted=this.gate==="pending";return}let t=this.env.document,n=t.createElement("iframe");n.id=this.frameId,n.title=this.title,n.src=this.frameUrl,n.referrerPolicy="origin",n.setAttribute("allow","clipboard-write"),n.setAttribute("data-ahoy","panel"),l(n,{position:"fixed",border:"0",margin:"0",padding:"0","z-index":String(u+1),background:"transparent","color-scheme":"normal","max-width":"100vw",display:"none"});let o=Date.now(),s=setInterval(()=>{if(this.state.ready||this.stopped){clearInterval(s);return}if(Date.now()-o>V){clearInterval(s),this.warnOnce("not_ready",`[Ahoy] The chat panel (${this.frameUrl}) did not start. A Content-Security-Policy without frame-src ${this.frameOrigin}, an ad blocker or a network error can cause this.`);return}this.sendConfigure()},z);n.addEventListener("load",()=>{!this.state.ready&&!this.stopped&&this.sendConfigure()}),(t.body??t.documentElement).appendChild(n),this.iframe=n,this.cleanups.push(()=>{n.remove(),clearInterval(s)})}sendConfigure(){let e=this.options;if(!e)return;let t=this.env.document;this.postNow({type:"configure",payload:{appId:e.appId,environment:e.environment==="development"?"development":"production",hostOrigin:this.env.window.location.origin,language:e.language,pageLanguage:t.documentElement.lang||void 0,appearance:this.currentAppearance,apiUrl:e.apiUrl,position:e.position==="left"||e.position==="right"?e.position:void 0,protocol:1}})}onMessage(e){if(!this.iframe||e.source!==this.iframe.contentWindow||e.origin!==this.frameOrigin)return;let t=w(e.data,b);if(t)switch(t.type){case"ready":return this.onReady(t.payload);case"unread":return this.setState({unread:Math.max(0,Number(t.payload?.count)||0)});case"resize":return this.mode=t.payload?.mode==="full"?"full":"panel",typeof t.payload?.height=="number"&&t.payload.height>0&&(this.panelHeight=Math.min(P,t.payload.height)),this.layout();case"event":return this.dispatch(t.payload);case"opened":return this.onOpened();case"closed":return this.onClosed();case"stopped":return this.onStopped(t.payload?.reason)}}onStopped(e){let t=e==="app_deleted"&&this.queue.some(n=>n.type==="deleteData");this.stopped=!0,this.queue=[],this.wantOpen=!1,this.launcher?.remove(),this.launcher=null,this.setState({ready:!1,open:!1,unread:0,appDeleted:e==="app_deleted"}),this.layout(),t&&this.post({type:"deleteData"})}onReady(e){if(this.stopped){let s=this.queue;this.queue=[];for(let a of s)this.post(a);return}typeof e?.title=="string"&&e.title&&(this.title=e.title),(e?.position==="left"||e?.position==="right")&&(this.position=e.position),typeof e?.bottomOffset=="number"&&Number.isFinite(e.bottomOffset)&&(this.bottomOffset=Math.min(F,Math.max(0,Math.round(e.bottomOffset))));let t=typeof e?.accent=="string"?e.accent:"#0A6FD8";if(this.iframe&&(this.iframe.title=this.title),this.options?.launcher!==!1){if(this.launcher)this.launcher.setAccent(t),this.launcher.setPosition(this.position,this.bottomOffset),this.launcher.setLabel(this.title);else{this.launcher=new c(this.env.document,{position:this.position,bottomOffset:this.bottomOffset,accent:t,label:this.title,controls:this.frameId,onClick:()=>this.open()}),(this.env.document.body??this.env.document.documentElement).appendChild(this.launcher.host);let s=this.launcher;this.cleanups.push(()=>s.remove())}this.launcher.setUnread(this.state.unread)}let n=!this.state.ready;if(this.setState({ready:!0}),this.applyLauncherVisibility(),this.layout(),!n)return;let o=this.queue;this.queue=[];for(let s of o)this.post(s);this.cleanups.push(x(this.env.window,s=>this.post({type:"page",payload:{path:s}}))),this.wantOpen&&this.post({type:"open"})}onOpened(){let e=this.env.document.activeElement;this.returnFocus=e instanceof HTMLElement&&e!==this.iframe?e:null,this.wantOpen=!0,this.setState({open:!0}),this.launcher?.setExpanded(!0),this.applyLauncherVisibility(),this.layout(),this.iframe?.focus()}onClosed(){this.wantOpen=!1,this.mode="panel",this.setState({open:!1}),this.launcher?.setExpanded(!1),this.applyLauncherVisibility(),this.layout();let e=this.launcher?null:this.returnFocus;this.launcher?this.launcher.focus():e?.isConnected&&e.focus(),this.returnFocus=null}applyLauncherVisibility(){if(!this.launcher)return;let e=this.options?.launcher!==!1&&this.state.ready&&!this.state.open;this.launcher.setVisible(e)}layout(){let e=this.iframe;if(!e)return;if(!this.state.open){l(e,{display:"none"});return}let t=this.env.window,n=this.mode==="full"||t.innerWidth<q;if(e.setAttribute("data-mode",n?"full":"panel"),n){l(e,{display:"block",top:"0",left:"0",right:"auto",bottom:"auto",width:"100%",height:"100%","border-radius":"0","box-shadow":"none"});return}let o=Math.max(320,Math.min(this.panelHeight,t.innerHeight-this.bottomOffset-f));l(e,{display:"block",top:"auto",bottom:`${this.bottomOffset}px`,left:this.position==="left"?`${f}px`:"auto",right:this.position==="left"?"auto":`${f}px`,width:`${$}px`,height:`${o}px`,"border-radius":"16px","box-shadow":"0 12px 48px rgba(15, 23, 42, 0.28)"})}send(e){this.stopped||(this.state.ready?this.post(e):this.queue.push(e))}post(e){this.postNow(e)}postNow(e){let t=this.iframe?.contentWindow;if(!(!t||!this.frameOrigin))try{t.postMessage(A(e),this.frameOrigin)}catch{}}dispatch(e){if(!(!e||typeof e.type!="string"))for(let t of[...this.listeners])try{t(e)}catch(n){console.warn("[Ahoy] onEvent listener threw",n)}}setState(e){let t={...this.state,...e};if(!(t.ready===this.state.ready&&t.open===this.state.open&&t.unread===this.state.unread&&t.appDeleted===this.state.appDeleted)){this.state=t,this.launcher?.setUnread(t.unread);for(let n of[...this.subscribers])n()}}warnOnce(e,t){this.options?.environment!=="development"||this.warned.has(e)||(this.warned.add(e),console.warn(t))}teardown(e=!1){this.idleHandle?.(),this.idleHandle=null;for(let t of this.cleanups.splice(0))t();this.iframe=null,this.launcher=null,this.stopped=!1,this.gate="live",this.mountWanted=!1,this.mode="panel",e||(this.queue=[]),this.setState({ready:!1,open:!1,unread:0,appDeleted:!1})}};async function G(i){return i.status!==410?!1:(await i.json())?.error?.code==="app_deleted"}function X(i,e){let t=i.requestIdleCallback;if(typeof t=="function"){let o=t.call(i,e,{timeout:3e3});return()=>i.cancelIdleCallback?.(o)}let n=setTimeout(e,200);return()=>clearTimeout(n)}function j(i){return i instanceof d||!!i&&typeof i.subscribe=="function"}function _(i=window,e=null,t=null){let n=i,o=n.Ahoy;if(j(o))return o;let s=new d({window:i,document:i.document},e);n.Ahoy=s,t&&s.configure(t);let a=o;return Q(s,a&&Array.isArray(a.q)?a.q:[]),s}function Q(i,e){for(let t of e){if(!Array.isArray(t)||typeof t[0]!="string")continue;let n=i[t[0]];if(typeof n!="function")continue;let o=t[1]&&typeof t[1]=="object"?Array.from(t[1]):[];try{n.apply(i,o)}catch(s){console.warn(`[Ahoy] Ahoy.${t[0]} from the snippet failed`,s)}}}function L(i){if(!i)return null;let e=h=>i.getAttribute(`data-${h}`)??void 0,t=e("app-id");if(!t)return null;let n={appId:t},o=e("environment");(o==="development"||o==="production")&&(n.environment=o);let s=e("api-url");s&&(n.apiUrl=s);let a=e("language");a&&(n.language=a),e("launcher")==="false"&&(n.launcher=!1);let p=e("position");return(p==="left"||p==="right")&&(n.position=p),n}var S=document.currentScript instanceof HTMLScriptElement?document.currentScript:document.querySelector('script[data-app-id][src*="ahoy.js"]');_(window,S?.src??null,L(S));})();
@@ -0,0 +1,7 @@
1
+ export declare const DEFAULT_API_URL: string;
2
+ /**
3
+ * The API the SDK uses: the page's `apiUrl` only in development (a local or self-hosted API while
4
+ * building); production always uses the built-in hosted API.
5
+ */
6
+ export declare function apiUrlFor(environment: string | undefined, apiUrl: string | undefined): string;
7
+ //# sourceMappingURL=api-url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-url.d.ts","sourceRoot":"","sources":["../../src/api-url.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,eAAe,QAGW,CAAC;AAExC;;;GAGG;AACH,wBAAgB,SAAS,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAE7F"}
@@ -0,0 +1,11 @@
1
+ export const DEFAULT_API_URL = typeof __AHOY_DEFAULT_API_URL__ === 'string' && __AHOY_DEFAULT_API_URL__
2
+ ? __AHOY_DEFAULT_API_URL__
3
+ : 'https://api.dev.ahoysupport.com';
4
+ /**
5
+ * The API the SDK uses: the page's `apiUrl` only in development (a local or self-hosted API while
6
+ * building); production always uses the built-in hosted API.
7
+ */
8
+ export function apiUrlFor(environment, apiUrl) {
9
+ return ((environment === 'development' && apiUrl) || DEFAULT_API_URL).replace(/\/+$/, '');
10
+ }
11
+ //# sourceMappingURL=api-url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"api-url.js","sourceRoot":"","sources":["../../src/api-url.ts"],"names":[],"mappings":"AAOA,MAAM,CAAC,MAAM,eAAe,GAC1B,OAAO,wBAAwB,KAAK,QAAQ,IAAI,wBAAwB;IACtE,CAAC,CAAC,wBAAwB;IAC1B,CAAC,CAAC,iCAAiC,CAAC;AAExC;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,WAA+B,EAAE,MAA0B;IACnF,OAAO,CAAC,CAAC,WAAW,KAAK,aAAa,IAAI,MAAM,CAAC,IAAI,eAAe,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;AAC5F,CAAC"}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @ahoy-ai/web for bundlers: the loader behind `window.Ahoy` (launcher, iframe panel from Ahoy's
3
+ * CDN, postMessage). It imports nothing at runtime and touches `window` only when called, so it is
4
+ * safe to import during server rendering. React apps use `@ahoy-ai/react`.
5
+ */
6
+ export { AhoyLoader, DEFAULT_CDN_URL, FRAME_PATH, FULL_SCREEN_BELOW, createAhoy, type AhoyWeb, type AhoyWebOptions, type AhoyWebState, } from './loader/ahoy.js';
7
+ export { getAhoy, optionsFromScript, replay } from './loader/global.js';
8
+ export { CHANNEL, PROTOCOL, type ConfigurePayload, type HostMessage, type LauncherPosition, type PanelMessage, type ReadyPayload, } from './protocol.js';
9
+ export { WEB_VERSION } from './version.js';
10
+ export type { AhoyAppearance, AhoyEnvironment, AhoyEvent, AhoyEventListener, AhoyEventType, AhoyIdentity, AhoyMetadata, AhoyPushResult, AhoyVerifiedIdentity, } from '@ahoy-ai/core';
11
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,UAAU,EACV,eAAe,EACf,UAAU,EACV,iBAAiB,EACjB,UAAU,EACV,KAAK,OAAO,EACZ,KAAK,cAAc,EACnB,KAAK,YAAY,GAClB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,OAAO,EACP,QAAQ,EACR,KAAK,gBAAgB,EACrB,KAAK,WAAW,EAChB,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,YAAY,GAClB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,YAAY,EACV,cAAc,EACd,eAAe,EACf,SAAS,EACT,iBAAiB,EACjB,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,cAAc,EACd,oBAAoB,GACrB,MAAM,eAAe,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @ahoy-ai/web for bundlers: the loader behind `window.Ahoy` (launcher, iframe panel from Ahoy's
3
+ * CDN, postMessage). It imports nothing at runtime and touches `window` only when called, so it is
4
+ * safe to import during server rendering. React apps use `@ahoy-ai/react`.
5
+ */
6
+ export { AhoyLoader, DEFAULT_CDN_URL, FRAME_PATH, FULL_SCREEN_BELOW, createAhoy, } from './loader/ahoy.js';
7
+ export { getAhoy, optionsFromScript, replay } from './loader/global.js';
8
+ export { CHANNEL, PROTOCOL, } from './protocol.js';
9
+ export { WEB_VERSION } from './version.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,UAAU,EACV,eAAe,EACf,UAAU,EACV,iBAAiB,EACjB,UAAU,GAIX,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACxE,OAAO,EACL,OAAO,EACP,QAAQ,GAMT,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,198 @@
1
+ import type { AhoyAppearance, AhoyEnvironment, AhoyEventListener, AhoyEventProps, AhoyIdentity, AhoyMetadata, AhoyOfferHandler, AhoyPaywall, AhoyPushResult, AhoyTrackOptions, AhoyVerifiedIdentity } from '@ahoy-ai/core';
2
+ import { type LauncherPosition } from '../protocol.js';
3
+ /**
4
+ * Where the panel is served when nothing else says (the npm route, `@ahoy-ai/react`): production.
5
+ * Local and dev setups pass `cdnUrl` (CONTRACT C11).
6
+ */
7
+ export declare const DEFAULT_CDN_URL = "https://cdn.ahoysupport.com";
8
+ /** The panel of this loader's major (ADR 0017: loader and panel always match on `/v1/`). */
9
+ export declare const FRAME_PATH = "/web/v1/frame.html";
10
+ export declare const FULL_SCREEN_BELOW = 640;
11
+ /**
12
+ * The longest the panel waits for the app status check before it loads anyway (fail-open). The
13
+ * same as the idle wait's own limit, so on a slow API the launcher is no later than an idle wait
14
+ * that runs out today.
15
+ */
16
+ export declare const STATUS_TIMEOUT_MS = 3000;
17
+ export interface AhoyWebOptions {
18
+ /** Public App ID from the dashboard, e.g. `app_XXXX`. */
19
+ appId: string;
20
+ /** `development` turns on the setup check and development warnings. Default `production`. */
21
+ environment?: AhoyEnvironment;
22
+ /**
23
+ * A local or self-hosted Ahoy API. Used only with `environment: 'development'`; production
24
+ * always uses the hosted API.
25
+ */
26
+ apiUrl?: string;
27
+ /** Force an interface language; defaults to the page's `lang`, then the browser's languages. */
28
+ language?: string;
29
+ /** `false` hides the built-in button, for sites that call `Ahoy.open()` from their own. */
30
+ launcher?: boolean;
31
+ /**
32
+ * The launcher's side. Set it only to override the side published in the dashboard design
33
+ * (Chat design → Launcher); default: the published side, else `right`.
34
+ */
35
+ position?: LauncherPosition;
36
+ appearance?: AhoyAppearance;
37
+ /**
38
+ * Where the panel is served (`<cdnUrl>/web/v1/frame.html`). Default: the CDN `ahoy.js` came from,
39
+ * or `https://cdn.ahoysupport.com` for bundled loaders. Set it for a local (`http://localhost:4400`)
40
+ * or dev CDN.
41
+ */
42
+ cdnUrl?: string;
43
+ }
44
+ /** What framework wrappers (`@ahoy-ai/react`) subscribe to. */
45
+ export interface AhoyWebState {
46
+ /** The panel answered `ready`. */
47
+ ready: boolean;
48
+ /** The chat panel is open. */
49
+ open: boolean;
50
+ /** Unread support messages, for a badge on your own button. */
51
+ unread: number;
52
+ /**
53
+ * The app was deleted in the Ahoy dashboard: no launcher, no panel, `open()` does nothing.
54
+ * Checked again on the next page load (the browser may reuse the answer for up to 5 minutes);
55
+ * an app restored in the dashboard works again.
56
+ */
57
+ appDeleted: boolean;
58
+ }
59
+ /**
60
+ * `window.Ahoy`: the same names as the mobile SDK where they apply (ADR 0017). Calls made before
61
+ * the panel is ready are queued; calls that return a promise resolve once queued (a refused
62
+ * identity token arrives as an `identity_rejected` event).
63
+ */
64
+ export interface AhoyWeb {
65
+ configure(options: AhoyWebOptions): void;
66
+ identify(identity: AhoyIdentity | AhoyVerifiedIdentity): Promise<void>;
67
+ setMetadata(metadata: AhoyMetadata, options?: {
68
+ merge?: boolean;
69
+ }): Promise<void>;
70
+ track(name: string, propsOrOptions?: AhoyEventProps | AhoyTrackOptions, options?: AhoyTrackOptions): void;
71
+ open(): void;
72
+ close(): void;
73
+ onEvent(listener: AhoyEventListener): () => void;
74
+ logout(): Promise<void>;
75
+ deleteData(): Promise<void>;
76
+ appearance: AhoyAppearance;
77
+ /** Development only: sends the setup check again; the result is logged in the console. */
78
+ runSetupCheck(): Promise<void>;
79
+ /** Not on web (no end-user push yet): resolves `{ registered: false, reason: 'unsupported' }`. */
80
+ registerPush(): Promise<AhoyPushResult>;
81
+ /** Not on web: always null. */
82
+ notificationBehavior(notification?: unknown): null;
83
+ /** Not on web (no paywalls on a web page): the handler is never called. */
84
+ onOffer(handler: AhoyOfferHandler | null): () => void;
85
+ /** Not on web: ignored. */
86
+ setPaywalls(paywalls: readonly AhoyPaywall[]): void;
87
+ getState(): AhoyWebState;
88
+ subscribe(listener: () => void): () => void;
89
+ /** Removes the launcher and the panel (tests, or a site that unmounts the chat). */
90
+ destroy(): void;
91
+ }
92
+ interface Environment {
93
+ window: Window;
94
+ document: Document;
95
+ }
96
+ /** The loader behind `window.Ahoy`: launcher, iframe, postMessage and the queue. */
97
+ export declare class AhoyLoader implements AhoyWeb {
98
+ private readonly env;
99
+ /** The script tag's `src`: the panel comes from the same CDN. */
100
+ private readonly scriptSrc;
101
+ private options;
102
+ private frameUrl;
103
+ private frameOrigin;
104
+ private iframe;
105
+ private launcher;
106
+ private state;
107
+ private readonly listeners;
108
+ private readonly subscribers;
109
+ private queue;
110
+ private wantOpen;
111
+ private mode;
112
+ private panelHeight;
113
+ /** The launcher's place, from the panel's `ready` (site option, else published design). */
114
+ private position;
115
+ private bottomOffset;
116
+ private title;
117
+ private currentAppearance;
118
+ private cleanups;
119
+ private idleHandle;
120
+ private returnFocus;
121
+ /** The panel stopped for good (`stopped`): no launcher, nothing sent, until a reload. */
122
+ private stopped;
123
+ private gate;
124
+ /** The panel was due (page idle or `open()`) while the status check ran. */
125
+ private mountWanted;
126
+ private readonly warned;
127
+ private readonly frameId;
128
+ constructor(env?: Environment,
129
+ /** The script tag's `src`: the panel comes from the same CDN. */
130
+ scriptSrc?: string | null);
131
+ configure(options: AhoyWebOptions): void;
132
+ identify(identity: AhoyIdentity | AhoyVerifiedIdentity): Promise<void>;
133
+ setMetadata(metadata: AhoyMetadata, options?: {
134
+ merge?: boolean;
135
+ }): Promise<void>;
136
+ track(name: string, propsOrOptions?: AhoyEventProps | AhoyTrackOptions, options?: AhoyTrackOptions): void;
137
+ open(): void;
138
+ close(): void;
139
+ onEvent(listener: AhoyEventListener): () => void;
140
+ logout(): Promise<void>;
141
+ deleteData(): Promise<void>;
142
+ get appearance(): AhoyAppearance;
143
+ set appearance(value: AhoyAppearance);
144
+ runSetupCheck(): Promise<void>;
145
+ registerPush(): Promise<AhoyPushResult>;
146
+ notificationBehavior(): null;
147
+ onOffer(handler: AhoyOfferHandler | null): () => void;
148
+ setPaywalls(paywalls: readonly AhoyPaywall[]): void;
149
+ getState(): AhoyWebState;
150
+ subscribe(listener: () => void): () => void;
151
+ destroy(): void;
152
+ private resolveFrameUrl;
153
+ /**
154
+ * Asks the API whether the app still exists, so a deleted app's site loads no panel (no panel
155
+ * download, no config request). A CORS simple request (no custom headers, no cookies, no
156
+ * preflight) that the browser may answer from its HTTP cache (`max-age=300`). Only 410
157
+ * `app_deleted` stops the loader; any other answer, a network error, a Content-Security-Policy
158
+ * without the API in `connect-src`, or no answer within `STATUS_TIMEOUT_MS` loads the panel as
159
+ * before, and the panel's own 410 handling still applies.
160
+ */
161
+ private checkStatus;
162
+ /** 410 `app_deleted` before the panel loaded: nothing is created, as if the panel had stopped. */
163
+ private onAppDeletedBeforePanel;
164
+ /**
165
+ * `deleteData()` for a deleted app whose panel never loaded: the end user's erasure still goes
166
+ * (the API accepts it), so the panel loads hidden for that one call. It stops for the deleted app
167
+ * and the queued deletion goes through `onStopped`.
168
+ */
169
+ private eraseWithoutPanel;
170
+ private mount;
171
+ private sendConfigure;
172
+ private onMessage;
173
+ /**
174
+ * The panel refused to run (its console line says why): the launcher goes, the frame stays
175
+ * hidden and loaded so `open()` doesn't start it again, and later calls are dropped.
176
+ */
177
+ private onStopped;
178
+ private onReady;
179
+ private onOpened;
180
+ private onClosed;
181
+ private applyLauncherVisibility;
182
+ /**
183
+ * Sizes the iframe: the panel (400 × 700, 20 px from the side, as high above the bottom as the
184
+ * launcher) or the whole viewport.
185
+ */
186
+ private layout;
187
+ private send;
188
+ private post;
189
+ private postNow;
190
+ private dispatch;
191
+ private setState;
192
+ private warnOnce;
193
+ private teardown;
194
+ }
195
+ /** A new loader for this page (the npm route; the script tag uses `install`). */
196
+ export declare function createAhoy(): AhoyWeb;
197
+ export {};
198
+ //# sourceMappingURL=ahoy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ahoy.d.ts","sourceRoot":"","sources":["../../../src/loader/ahoy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,cAAc,EACd,eAAe,EAEf,iBAAiB,EACjB,cAAc,EACd,YAAY,EACZ,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,cAAc,EACd,gBAAgB,EAChB,oBAAoB,EACrB,MAAM,eAAe,CAAC;AAGvB,OAAO,EAOL,KAAK,gBAAgB,EAItB,MAAM,gBAAgB,CAAC;AAKxB;;;GAGG;AACH,eAAO,MAAM,eAAe,gCAAgC,CAAC;AAG7D,4FAA4F;AAC5F,eAAO,MAAM,UAAU,uBAAuB,CAAC;AAS/C,eAAO,MAAM,iBAAiB,MAAM,CAAC;AAKrC;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,OAAQ,CAAC;AAQvC,MAAM,WAAW,cAAc;IAC7B,yDAAyD;IACzD,KAAK,EAAE,MAAM,CAAC;IACd,6FAA6F;IAC7F,WAAW,CAAC,EA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