@armdesk/connect-sdk 0.0.0-stage → 1.1.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 (49) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/LICENSE.txt +15 -0
  3. package/README.md +525 -3
  4. package/dist/armdesk-connect.js +41 -0
  5. package/dist/esm/browser.d.ts +3 -0
  6. package/dist/esm/browser.js +18 -0
  7. package/dist/esm/client.d.ts +46 -0
  8. package/dist/esm/client.js +307 -0
  9. package/dist/esm/defaults.d.ts +8 -0
  10. package/dist/esm/defaults.js +22 -0
  11. package/dist/esm/elements.d.ts +3 -0
  12. package/dist/esm/elements.js +368 -0
  13. package/dist/esm/errors.d.ts +12 -0
  14. package/dist/esm/errors.js +34 -0
  15. package/dist/esm/handler.d.ts +40 -0
  16. package/dist/esm/handler.js +106 -0
  17. package/dist/esm/http.d.ts +22 -0
  18. package/dist/esm/http.js +66 -0
  19. package/dist/esm/index.d.ts +30 -0
  20. package/dist/esm/index.js +30 -0
  21. package/dist/esm/messenger.d.ts +8 -0
  22. package/dist/esm/messenger.js +269 -0
  23. package/dist/esm/mount.d.ts +8 -0
  24. package/dist/esm/mount.js +213 -0
  25. package/dist/esm/protocol.d.ts +37 -0
  26. package/dist/esm/protocol.js +57 -0
  27. package/dist/esm/react.d.ts +89 -0
  28. package/dist/esm/react.js +311 -0
  29. package/dist/esm/register.d.ts +1 -0
  30. package/dist/esm/register.js +5 -0
  31. package/dist/esm/sanitize.d.ts +8 -0
  32. package/dist/esm/sanitize.js +57 -0
  33. package/dist/esm/server.d.ts +17 -0
  34. package/dist/esm/server.js +93 -0
  35. package/dist/esm/sign.d.ts +54 -0
  36. package/dist/esm/sign.js +77 -0
  37. package/dist/esm/theme.d.ts +8 -0
  38. package/dist/esm/theme.js +46 -0
  39. package/dist/esm/types.d.ts +375 -0
  40. package/dist/esm/types.js +1 -0
  41. package/examples/express-server/package.json +10 -0
  42. package/examples/express-server/server.mjs +35 -0
  43. package/examples/mock-idp.mjs +30 -0
  44. package/examples/react-vite/index.html +11 -0
  45. package/examples/react-vite/package.json +15 -0
  46. package/examples/react-vite/src/main.jsx +25 -0
  47. package/examples/react-vite/vite.config.js +4 -0
  48. package/examples/wso2-browser.html +86 -0
  49. package/package.json +59 -4
@@ -0,0 +1,30 @@
1
+ import { createClient, init, type ArmDeskClient } from "./client.js";
2
+ import { mount } from "./mount.js";
3
+ import type { ClientOptions, ConnectHandle, MessengerController, MessengerOptions, MountOptions } from "./types.js";
4
+ export declare const VERSION = "1.1.0";
5
+ /**
6
+ * `ArmDeskConnect.messenger(...)`: the messenger bubble.
7
+ * - `messenger({ orgKey, auth, ...messengerOptions })` signs in (like init) and shows it;
8
+ * - `messenger(messengerOptions)` uses the client from the last `init()`.
9
+ */
10
+ export type MessengerInit = MessengerOptions & Partial<Pick<ClientOptions, "orgKey" | "auth" | "desk" | "apiBase">> & {
11
+ client?: ArmDeskClient;
12
+ };
13
+ export declare function messenger(options?: MessengerInit): MessengerController;
14
+ /** The IIFE's global: `ArmDeskConnect.init({ orgKey, auth })`. `mount(el, { getToken })` still works (deprecated). */
15
+ export declare const ArmDeskConnect: {
16
+ version: string;
17
+ init: typeof init;
18
+ createClient: typeof createClient;
19
+ messenger: typeof messenger;
20
+ /** @deprecated Use `init({ orgKey, auth })` and `client.mount(el)`. */
21
+ mount: (container: HTMLElement | string, options: MountOptions) => ConnectHandle;
22
+ };
23
+ export { init, createClient, mount };
24
+ export { createMessenger } from "./messenger.js";
25
+ export type { ArmDeskClient } from "./client.js";
26
+ export { ArmDeskError, type ArmDeskErrorCode } from "./errors.js";
27
+ export { sanitizeHtml } from "./sanitize.js";
28
+ export { themeCss, themeVars } from "./theme.js";
29
+ export { VIEW_PATTERN, isView } from "./protocol.js";
30
+ export type * from "./types.js";
@@ -0,0 +1,30 @@
1
+ import { createClient, init } from "./client.js";
2
+ import { getCurrentClient } from "./defaults.js";
3
+ import { ArmDeskError } from "./errors.js";
4
+ import { mount } from "./mount.js";
5
+ export const VERSION = "1.1.0";
6
+ export function messenger(options = {}) {
7
+ const { client: given, orgKey, auth, desk, apiBase, ...rest } = options;
8
+ let client = given !== null && given !== void 0 ? given : null;
9
+ if (!client && orgKey && auth)
10
+ client = init({ orgKey, auth, desk, apiBase, theme: rest.theme, features: rest.features, locale: rest.locale });
11
+ client !== null && client !== void 0 ? client : (client = getCurrentClient());
12
+ if (!client)
13
+ throw new ArmDeskError("config", "ArmDeskConnect.messenger: call init({ orgKey, auth }) first, or pass orgKey and auth");
14
+ return client.messenger(rest);
15
+ }
16
+ /** The IIFE's global: `ArmDeskConnect.init({ orgKey, auth })`. `mount(el, { getToken })` still works (deprecated). */
17
+ export const ArmDeskConnect = {
18
+ version: VERSION,
19
+ init,
20
+ createClient,
21
+ messenger,
22
+ /** @deprecated Use `init({ orgKey, auth })` and `client.mount(el)`. */
23
+ mount: (container, options) => mount(container, options),
24
+ };
25
+ export { init, createClient, mount };
26
+ export { createMessenger } from "./messenger.js";
27
+ export { ArmDeskError } from "./errors.js";
28
+ export { sanitizeHtml } from "./sanitize.js";
29
+ export { themeCss, themeVars } from "./theme.js";
30
+ export { VIEW_PATTERN, isView } from "./protocol.js";
@@ -0,0 +1,8 @@
1
+ import type { ClientMountOptions, ConnectHandle, ConnectTheme, MessengerController, MessengerOptions } from "./types.js";
2
+ export interface MessengerDeps {
3
+ mount: (el: HTMLElement, options: ClientMountOptions) => ConnectHandle;
4
+ /** The organisation's theme (colours the bubble). Optional; errors are ignored. */
5
+ loadTheme?: () => Promise<ConnectTheme | undefined>;
6
+ }
7
+ /** Creates the bubble + panel. Use `client.messenger(options)` (or `ArmDeskConnect.messenger(...)`). */
8
+ export declare function createMessenger(deps: MessengerDeps, options?: MessengerOptions): MessengerController;
@@ -0,0 +1,269 @@
1
+ import { isView } from "./protocol.js";
2
+ import { themeCss } from "./theme.js";
3
+ const PANEL_W = 380;
4
+ const PANEL_H = 640;
5
+ const BUBBLE = 56;
6
+ const GAP = 16;
7
+ const MOBILE = 480;
8
+ const CSS = `
9
+ *{box-sizing:border-box}
10
+ .bubble{position:fixed;display:inline-flex;align-items:center;justify-content:center;gap:8px;min-width:${BUBBLE}px;height:${BUBBLE}px;padding:0 16px;border:0;border-radius:999px;background:var(--ad-primary);color:#fff;font:600 15px/1 var(--ad-font);cursor:pointer;box-shadow:0 6px 20px rgba(0,0,0,.22);transition:transform .2s ease,box-shadow .2s ease}
11
+ .bubble.round{width:${BUBBLE}px;padding:0}
12
+ .bubble:hover{transform:scale(1.05);box-shadow:0 8px 26px rgba(0,0,0,.28)}
13
+ .bubble:focus-visible{outline:3px solid var(--ad-primary);outline-offset:3px}
14
+ .bubble svg{width:26px;height:26px;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round}
15
+ .bubble img{width:28px;height:28px;object-fit:contain}
16
+ .ico{display:inline-flex;transition:transform .2s ease,opacity .2s ease}
17
+ .x{position:absolute;opacity:0;transform:rotate(-90deg)}
18
+ .is-open .ico.main{opacity:0;transform:rotate(90deg)}
19
+ .is-open .x{opacity:1;transform:none}
20
+ .is-open .lbl{display:none}
21
+ .is-open.bubble{width:${BUBBLE}px;padding:0}
22
+ .badge{position:absolute;top:-4px;right:-4px;min-width:20px;height:20px;padding:0 6px;border-radius:999px;background:#dc2626;color:#fff;font:700 11px/20px var(--ad-font);text-align:center;border:2px solid #fff}
23
+ .badge[hidden],.is-open .badge{display:none}
24
+ .panel{position:fixed;width:${PANEL_W}px;height:${PANEL_H}px;max-height:calc(100vh - var(--ad-y) - ${BUBBLE + GAP * 2}px);background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:16px;overflow:hidden;box-shadow:0 12px 48px rgba(0,0,0,.24);visibility:hidden;opacity:0;transform:translateY(12px) scale(.98);pointer-events:none;transition:opacity .2s ease,transform .2s ease,visibility 0s linear .2s}
25
+ .panel.open{visibility:visible;opacity:1;transform:none;pointer-events:auto;transition-delay:0s}
26
+ .right .panel{transform-origin:bottom right}.left .panel{transform-origin:bottom left}
27
+ .panel iframe{width:100%;height:100% !important;border:0;display:block}
28
+ @media (max-width:${MOBILE}px){.panel{inset:0 !important;width:100%;height:100%;max-height:none;border:0;border-radius:0}.wrap.is-open .bubble{display:none}}
29
+ @media (prefers-reduced-motion:reduce){.bubble,.panel,.ico{transition:none !important}.bubble:hover{transform:none}}
30
+ `;
31
+ const SVG_NS = "http://www.w3.org/2000/svg";
32
+ function icon(paths) {
33
+ const svg = document.createElementNS(SVG_NS, "svg");
34
+ svg.setAttribute("viewBox", "0 0 24 24");
35
+ svg.setAttribute("aria-hidden", "true");
36
+ for (const d of paths) {
37
+ const p = document.createElementNS(SVG_NS, "path");
38
+ p.setAttribute("d", d);
39
+ svg.appendChild(p);
40
+ }
41
+ return svg;
42
+ }
43
+ const CHAT = ["M21 12a8 8 0 0 1-11.6 7.1L4 20.5l1.4-4.9A8 8 0 1 1 21 12z"];
44
+ const CLOSE = ["M6 6l12 12", "M18 6L6 18"];
45
+ function span(cls, ...kids) {
46
+ const s = document.createElement("span");
47
+ s.className = cls;
48
+ s.append(...kids);
49
+ return s;
50
+ }
51
+ const isHttpsUrl = (u) => {
52
+ if (typeof u !== "string")
53
+ return false;
54
+ try {
55
+ return new URL(u).protocol === "https:";
56
+ }
57
+ catch (_a) {
58
+ return false;
59
+ }
60
+ };
61
+ let seq = 0;
62
+ /** Creates the bubble + panel. Use `client.messenger(options)` (or `ArmDeskConnect.messenger(...)`). */
63
+ export function createMessenger(deps, options = {}) {
64
+ var _a, _b, _c, _d, _e, _f, _g;
65
+ if (typeof document === "undefined")
66
+ throw new Error("ArmDeskConnect: the messenger needs a browser");
67
+ if (options.view !== undefined && !isView(options.view))
68
+ throw new Error("ArmDeskConnect: invalid view");
69
+ const side = options.position === "bottom-left" || options.position === "left" ? "left" : "right";
70
+ const off = typeof options.offset === "number" ? { x: options.offset, y: options.offset } : (_a = options.offset) !== null && _a !== void 0 ? _a : {};
71
+ const x = Math.max(0, Math.round((_b = off.x) !== null && _b !== void 0 ? _b : 20));
72
+ const y = Math.max(0, Math.round((_c = off.y) !== null && _c !== void 0 ? _c : 20));
73
+ const z = Number.isFinite(options.zIndex) ? Math.round(options.zIndex) : 2147483000;
74
+ const name = options.ariaLabel || options.label || "Support";
75
+ const panelId = `armdesk-messenger-${++seq}`;
76
+ let theme = { ...((_d = options.theme) !== null && _d !== void 0 ? _d : {}) };
77
+ let opened = false;
78
+ let unread = 0;
79
+ let destroyed = false;
80
+ let handle = null;
81
+ let view = (_e = options.view) !== null && _e !== void 0 ? _e : "home";
82
+ const listeners = new Map();
83
+ const emit = (event, payload) => {
84
+ var _a;
85
+ (_a = listeners.get(event)) === null || _a === void 0 ? void 0 : _a.forEach((cb) => {
86
+ try {
87
+ cb(payload);
88
+ }
89
+ catch (_a) {
90
+ // a throwing host listener must not break the messenger
91
+ }
92
+ });
93
+ };
94
+ // ---- DOM -------------------------------------------------------------------
95
+ const host = document.createElement("div");
96
+ host.setAttribute("data-armdesk-messenger", "");
97
+ const root = host.attachShadow({ mode: "open" });
98
+ const style = document.createElement("style");
99
+ const wrap = document.createElement("div");
100
+ wrap.className = `wrap ${side}`;
101
+ wrap.setAttribute("part", "messenger");
102
+ const bubble = document.createElement("button");
103
+ bubble.type = "button";
104
+ bubble.className = `bubble${options.label ? "" : " round"}`;
105
+ bubble.setAttribute("part", "bubble");
106
+ bubble.setAttribute("aria-controls", panelId);
107
+ bubble.setAttribute("aria-expanded", "false");
108
+ bubble.setAttribute("aria-haspopup", "dialog");
109
+ let main = icon(CHAT);
110
+ if (isHttpsUrl(options.iconUrl)) {
111
+ const img = document.createElement("img");
112
+ img.src = options.iconUrl;
113
+ img.alt = "";
114
+ main = img;
115
+ }
116
+ const badge = span("badge");
117
+ badge.hidden = true;
118
+ badge.setAttribute("aria-hidden", "true");
119
+ bubble.append(span("ico main", main), span("ico x", icon(CLOSE)), ...(options.label ? [span("lbl", document.createTextNode(options.label))] : []), badge);
120
+ bubble.style.cssText = `${side}:${x}px;bottom:${y}px;z-index:${z}`;
121
+ const panel = document.createElement("div");
122
+ panel.id = panelId;
123
+ panel.className = "panel";
124
+ panel.setAttribute("part", "panel");
125
+ panel.setAttribute("role", "dialog");
126
+ panel.setAttribute("aria-label", name);
127
+ panel.setAttribute("aria-hidden", "true");
128
+ panel.style.cssText = `${side}:${x}px;bottom:${y + BUBBLE + GAP}px;z-index:${z}`;
129
+ wrap.append(panel, bubble);
130
+ root.append(style, wrap);
131
+ const paint = () => {
132
+ style.textContent = `${themeCss(theme)}:host{display:contents;--ad-y:${y}px}${CSS}`;
133
+ };
134
+ const label = () => {
135
+ const base = opened ? `Close ${name}` : `Open ${name}`;
136
+ bubble.setAttribute("aria-label", unread > 0 && !opened ? `${base}, ${unread} unread` : base);
137
+ };
138
+ paint();
139
+ label();
140
+ // ---- the iframe --------------------------------------------------------------
141
+ const ensureFrame = () => {
142
+ if (handle || destroyed)
143
+ return;
144
+ handle = deps.mount(panel, {
145
+ view,
146
+ theme: options.theme,
147
+ features: options.features,
148
+ locale: options.locale,
149
+ height: PANEL_H,
150
+ host: "messenger",
151
+ title: name,
152
+ onEvent: options.onEvent,
153
+ onError: options.onError,
154
+ onUnread: (n) => setUnread(n),
155
+ onClose: () => close(),
156
+ });
157
+ };
158
+ const setUnread = (n) => {
159
+ if (n === unread)
160
+ return;
161
+ unread = n;
162
+ badge.textContent = n > 99 ? "99+" : String(n);
163
+ badge.hidden = n <= 0;
164
+ label();
165
+ emit("unread", n);
166
+ };
167
+ // ---- open / close ------------------------------------------------------------
168
+ const onKey = (e) => {
169
+ if (e.key === "Escape" && opened) {
170
+ e.stopPropagation();
171
+ close();
172
+ }
173
+ };
174
+ function open(next) {
175
+ if (destroyed)
176
+ return;
177
+ if (next !== undefined && !isView(next))
178
+ throw new Error("ArmDeskConnect: invalid view");
179
+ if (next)
180
+ view = next;
181
+ ensureFrame();
182
+ if (opened) {
183
+ if (next)
184
+ handle === null || handle === void 0 ? void 0 : handle.open(next);
185
+ return;
186
+ }
187
+ opened = true;
188
+ panel.classList.add("open");
189
+ wrap.classList.add("is-open");
190
+ bubble.classList.add("is-open");
191
+ panel.setAttribute("aria-hidden", "false");
192
+ bubble.setAttribute("aria-expanded", "true");
193
+ label();
194
+ handle === null || handle === void 0 ? void 0 : handle.open(next);
195
+ document.addEventListener("keydown", onKey, true);
196
+ // focus moves into the panel (the frame) so keyboard users land in the conversation
197
+ const frame = panel.querySelector("iframe");
198
+ setTimeout(() => opened && (frame === null || frame === void 0 ? void 0 : frame.focus()), 0);
199
+ emit("open", { view: next !== null && next !== void 0 ? next : null });
200
+ }
201
+ function close() {
202
+ if (destroyed || !opened)
203
+ return;
204
+ const focusInPanel = root.activeElement !== null && panel.contains(root.activeElement);
205
+ opened = false;
206
+ panel.classList.remove("open");
207
+ wrap.classList.remove("is-open");
208
+ bubble.classList.remove("is-open");
209
+ panel.setAttribute("aria-hidden", "true");
210
+ bubble.setAttribute("aria-expanded", "false");
211
+ label();
212
+ document.removeEventListener("keydown", onKey, true);
213
+ // focus returns to the bubble when it was inside the panel (WAI-ARIA dialog pattern)
214
+ if (focusInPanel)
215
+ bubble.focus();
216
+ emit("close", undefined);
217
+ }
218
+ bubble.addEventListener("click", () => (opened ? close() : open()));
219
+ panel.addEventListener("keydown", onKey);
220
+ ((_f = options.container) !== null && _f !== void 0 ? _f : document.body).appendChild(host);
221
+ if (!options.lazy)
222
+ ensureFrame();
223
+ if (deps.loadTheme && !((_g = options.theme) === null || _g === void 0 ? void 0 : _g.primaryColor)) {
224
+ deps.loadTheme().then((org) => {
225
+ var _a;
226
+ if (destroyed || !org)
227
+ return;
228
+ theme = { ...org, ...((_a = options.theme) !== null && _a !== void 0 ? _a : {}) };
229
+ paint();
230
+ }, () => undefined);
231
+ }
232
+ if (options.open)
233
+ open();
234
+ return {
235
+ open,
236
+ close,
237
+ toggle: () => (opened ? close() : open()),
238
+ navigate(next) {
239
+ if (!isView(next))
240
+ throw new Error("ArmDeskConnect: invalid view");
241
+ view = next;
242
+ handle === null || handle === void 0 ? void 0 : handle.navigate(next);
243
+ },
244
+ setTheme(next) {
245
+ theme = { ...next };
246
+ paint();
247
+ handle === null || handle === void 0 ? void 0 : handle.setTheme(next);
248
+ },
249
+ isOpen: () => opened,
250
+ unread: () => unread,
251
+ on(event, cb) {
252
+ let set = listeners.get(event);
253
+ if (!set)
254
+ listeners.set(event, (set = new Set()));
255
+ set.add(cb);
256
+ return () => set.delete(cb);
257
+ },
258
+ destroy() {
259
+ if (destroyed)
260
+ return;
261
+ document.removeEventListener("keydown", onKey, true);
262
+ handle === null || handle === void 0 ? void 0 : handle.destroy();
263
+ handle = null;
264
+ destroyed = true;
265
+ listeners.clear();
266
+ host.remove();
267
+ },
268
+ };
269
+ }
@@ -0,0 +1,8 @@
1
+ import type { ConnectHandle, MountOptions } from "./types.js";
2
+ /**
3
+ * Mounts the ARM Desk ITSM embed into `container` and speaks the embed
4
+ * protocol with it. The token travels only by postMessage to the desk's exact
5
+ * origin - never in the iframe URL - and every incoming message must come from
6
+ * that iframe window AND that origin.
7
+ */
8
+ export declare function mount(container: HTMLElement | string, options: MountOptions): ConnectHandle;
@@ -0,0 +1,213 @@
1
+ import { deskOrigin, isProtocolMessage, LOCALES, MAX_TOKEN_LENGTH, PROTOCOL_SOURCE, readUnread, VIEW_PATTERN } from "./protocol.js";
2
+ const READY_TIMEOUT_MS = 20000;
3
+ const TOKEN_ATTEMPTS = 4;
4
+ const TOKEN_BACKOFF_MS = 400;
5
+ const MIN_HEIGHT = 120;
6
+ const MAX_HEIGHT = 20000;
7
+ function resolveContainer(target) {
8
+ const el = typeof target === "string" ? document.querySelector(target) : target;
9
+ if (!el)
10
+ throw new Error("ArmDeskConnect: container not found");
11
+ return el;
12
+ }
13
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
14
+ /**
15
+ * Mounts the ARM Desk ITSM embed into `container` and speaks the embed
16
+ * protocol with it. The token travels only by postMessage to the desk's exact
17
+ * origin - never in the iframe URL - and every incoming message must come from
18
+ * that iframe window AND that origin.
19
+ */
20
+ export function mount(container, options) {
21
+ var _a, _b;
22
+ const host = resolveContainer(container);
23
+ const origin = deskOrigin(options.baseUrl);
24
+ if (!options.orgKey)
25
+ throw new Error("ArmDeskConnect: orgKey is required");
26
+ if (typeof options.getToken !== "function")
27
+ throw new Error("ArmDeskConnect: getToken is required");
28
+ if (options.view !== undefined && !VIEW_PATTERN.test(options.view))
29
+ throw new Error("ArmDeskConnect: invalid view");
30
+ let view = (_a = options.view) !== null && _a !== void 0 ? _a : "tickets";
31
+ let theme = { ...((_b = options.theme) !== null && _b !== void 0 ? _b : {}) };
32
+ let ready = false;
33
+ let destroyed = false;
34
+ let tokenInFlight = null;
35
+ let initSent = false;
36
+ /** An `open` asked for before init went out: sent right after it. */
37
+ let pendingOpen = null;
38
+ const params = new URLSearchParams({ org: options.orgKey, view });
39
+ if (options.locale && LOCALES.includes(options.locale))
40
+ params.set("locale", options.locale);
41
+ const frame = document.createElement("iframe");
42
+ frame.src = `${origin}/embed/itsm?${params.toString()}`;
43
+ frame.title = options.title || "Support tickets";
44
+ frame.setAttribute("referrerpolicy", "strict-origin");
45
+ frame.setAttribute("loading", "lazy");
46
+ frame.setAttribute("data-armdesk-connect", "");
47
+ Object.assign(frame.style, { width: "100%", border: "0", display: "block", colorScheme: "normal" });
48
+ frame.style.height = typeof options.height === "number" ? `${options.height}px` : "480px";
49
+ const post = (type, payload) => {
50
+ const win = frame.contentWindow;
51
+ if (destroyed || !win)
52
+ return;
53
+ win.postMessage({ source: PROTOCOL_SOURCE, type, payload }, origin);
54
+ };
55
+ const safe = (fn) => {
56
+ try {
57
+ fn();
58
+ }
59
+ catch (_a) {
60
+ // host callback errors stay the host's
61
+ }
62
+ };
63
+ const fail = (code, message) => {
64
+ var _a;
65
+ try {
66
+ (_a = options.onError) === null || _a === void 0 ? void 0 : _a.call(options, { code, message });
67
+ }
68
+ catch (_b) {
69
+ // a throwing host callback must not break the protocol loop
70
+ }
71
+ };
72
+ /** getToken with retry and exponential backoff; one request at a time. */
73
+ const fetchToken = () => {
74
+ if (tokenInFlight)
75
+ return tokenInFlight;
76
+ tokenInFlight = (async () => {
77
+ for (let attempt = 0; attempt < TOKEN_ATTEMPTS && !destroyed; attempt++) {
78
+ try {
79
+ const token = await options.getToken();
80
+ if (typeof token === "string" && token.length > 0 && token.length <= MAX_TOKEN_LENGTH)
81
+ return token;
82
+ throw new Error("getToken returned an invalid token");
83
+ }
84
+ catch (err) {
85
+ if (attempt === TOKEN_ATTEMPTS - 1) {
86
+ fail("token_failed", err instanceof Error ? err.message : "Could not get a token");
87
+ break;
88
+ }
89
+ await sleep(TOKEN_BACKOFF_MS * 2 ** attempt);
90
+ }
91
+ }
92
+ return null;
93
+ })().finally(() => {
94
+ tokenInFlight = null;
95
+ });
96
+ return tokenInFlight;
97
+ };
98
+ const sendToken = async (type) => {
99
+ var _a;
100
+ const token = await fetchToken();
101
+ if (!token || destroyed)
102
+ return;
103
+ if (type === "token") {
104
+ post("token", { token });
105
+ return;
106
+ }
107
+ const init = { token, theme, features: (_a = options.features) !== null && _a !== void 0 ? _a : {} };
108
+ if (options.host)
109
+ init.host = options.host;
110
+ post("init", init);
111
+ initSent = true;
112
+ if (pendingOpen) {
113
+ post("open", pendingOpen);
114
+ pendingOpen = null;
115
+ }
116
+ };
117
+ let readyTimer = setTimeout(() => {
118
+ if (!ready)
119
+ fail("timeout", "The embed did not respond. Check baseUrl and the organisation's allowed origins.");
120
+ }, READY_TIMEOUT_MS);
121
+ const onMessage = (event) => {
122
+ var _a;
123
+ if (destroyed)
124
+ return;
125
+ if (event.origin !== origin || event.source !== frame.contentWindow)
126
+ return;
127
+ if (!isProtocolMessage(event.data))
128
+ return;
129
+ const { type, payload } = event.data;
130
+ const body = (typeof payload === "object" && payload !== null ? payload : {});
131
+ switch (type) {
132
+ case "ready":
133
+ ready = true;
134
+ if (readyTimer)
135
+ clearTimeout(readyTimer);
136
+ readyTimer = null;
137
+ void sendToken("init");
138
+ break;
139
+ case "request-token":
140
+ void sendToken("token");
141
+ break;
142
+ case "resize": {
143
+ const h = Number(body.height);
144
+ if (options.height === undefined || options.height === "auto") {
145
+ if (Number.isFinite(h))
146
+ frame.style.height = `${Math.min(MAX_HEIGHT, Math.max(MIN_HEIGHT, Math.ceil(h)))}px`;
147
+ }
148
+ break;
149
+ }
150
+ case "event":
151
+ if (typeof body.name === "string") {
152
+ try {
153
+ (_a = options.onEvent) === null || _a === void 0 ? void 0 : _a.call(options, { name: body.name, data: body.data });
154
+ }
155
+ catch (_b) {
156
+ // host callback errors stay the host's
157
+ }
158
+ }
159
+ break;
160
+ case "unread": {
161
+ const n = readUnread(payload);
162
+ if (n !== null)
163
+ safe(() => { var _a; return (_a = options.onUnread) === null || _a === void 0 ? void 0 : _a.call(options, n); });
164
+ break;
165
+ }
166
+ case "close":
167
+ safe(() => { var _a; return (_a = options.onClose) === null || _a === void 0 ? void 0 : _a.call(options); });
168
+ break;
169
+ case "error":
170
+ fail(typeof body.code === "string" ? body.code : "error", typeof body.message === "string" ? body.message : "Embed error");
171
+ break;
172
+ default:
173
+ break;
174
+ }
175
+ };
176
+ window.addEventListener("message", onMessage);
177
+ host.appendChild(frame);
178
+ return {
179
+ navigate(next) {
180
+ if (!VIEW_PATTERN.test(next))
181
+ throw new Error("ArmDeskConnect: invalid view");
182
+ view = next;
183
+ if (ready)
184
+ post("navigate", { view });
185
+ },
186
+ open(next) {
187
+ if (next !== undefined && !VIEW_PATTERN.test(next))
188
+ throw new Error("ArmDeskConnect: invalid view");
189
+ if (next)
190
+ view = next;
191
+ const payload = next ? { view: next } : {};
192
+ if (initSent)
193
+ post("open", payload);
194
+ else
195
+ pendingOpen = payload;
196
+ },
197
+ setTheme(next) {
198
+ theme = { ...next };
199
+ if (ready)
200
+ post("theme", { theme });
201
+ },
202
+ refreshToken: () => sendToken("token"),
203
+ destroy() {
204
+ if (destroyed)
205
+ return;
206
+ destroyed = true;
207
+ if (readyTimer)
208
+ clearTimeout(readyTimer);
209
+ window.removeEventListener("message", onMessage);
210
+ frame.remove();
211
+ },
212
+ };
213
+ }
@@ -0,0 +1,37 @@
1
+ /** The embed protocol shared by the SDK and the embed page (apps/web components/connect-embed). */
2
+ export declare const PROTOCOL_SOURCE = "armdesk-connect";
3
+ /**
4
+ * Views the embed understands. 1.0: `tickets`, `new`, `ticket:<id>`. 1.1 (messenger): `home`, `messages`, `help`,
5
+ * `chat:<conversationId>`, `article:<id>`. Ids are 1-64 URL-safe characters.
6
+ */
7
+ export declare const VIEW_PATTERN: RegExp;
8
+ export declare const LOCALES: readonly ["en", "es", "ar"];
9
+ export declare const MAX_TOKEN_LENGTH = 8192;
10
+ /** Highest unread count the host accepts from the frame (anything above shows as "99+"). */
11
+ export declare const MAX_UNREAD = 9999;
12
+ /**
13
+ * Message types.
14
+ * host -> frame: `init {token, theme, features, host?}`, `token {token}`, `navigate {view}`, `theme {theme}`,
15
+ * `open {view?}` (the messenger panel became visible; optionally switch view).
16
+ * frame -> host: `ready`, `request-token`, `resize {height}`, `event {name, data}`, `error {code, message}`,
17
+ * `unread {count}` (launcher badge), `close` (the user closed the messenger from inside the frame).
18
+ */
19
+ export declare const HOST_MESSAGES: readonly ["init", "token", "navigate", "theme", "open"];
20
+ export declare const FRAME_MESSAGES: readonly ["ready", "request-token", "resize", "event", "error", "unread", "close"];
21
+ export interface ProtocolMessage {
22
+ source: typeof PROTOCOL_SOURCE;
23
+ type: string;
24
+ payload?: unknown;
25
+ }
26
+ export declare function isProtocolMessage(data: unknown): data is ProtocolMessage;
27
+ /** True for a view string the embed accepts. */
28
+ export declare function isView(v: unknown): boolean;
29
+ /** A sane unread count from an untrusted payload: an integer in 0..MAX_UNREAD, else null. */
30
+ export declare function readUnread(payload: unknown): number | null;
31
+ /** The origin of a desk URL: https, or http for localhost only. Throws for anything else. */
32
+ export declare function deskOrigin(baseUrl: string): string;
33
+ /** Sent by the library to a server-mode session route; a custom header a cross-site form cannot add. */
34
+ export declare const CSRF_HEADER = "X-ArmDesk-Csrf";
35
+ export declare const DEFAULT_SESSION_PATH = "/armdesk/session";
36
+ export declare const JWT_BEARER_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer";
37
+ export declare const ASSERTION_AUDIENCE = "armdesk-connect";
@@ -0,0 +1,57 @@
1
+ /** The embed protocol shared by the SDK and the embed page (apps/web components/connect-embed). */
2
+ export const PROTOCOL_SOURCE = "armdesk-connect";
3
+ /**
4
+ * Views the embed understands. 1.0: `tickets`, `new`, `ticket:<id>`. 1.1 (messenger): `home`, `messages`, `help`,
5
+ * `chat:<conversationId>`, `article:<id>`. Ids are 1-64 URL-safe characters.
6
+ */
7
+ export const VIEW_PATTERN = /^(tickets|new|home|messages|help|(ticket|chat|article):[A-Za-z0-9_-]{1,64})$/;
8
+ export const LOCALES = ["en", "es", "ar"];
9
+ export const MAX_TOKEN_LENGTH = 8192;
10
+ /** Highest unread count the host accepts from the frame (anything above shows as "99+"). */
11
+ export const MAX_UNREAD = 9999;
12
+ /**
13
+ * Message types.
14
+ * host -> frame: `init {token, theme, features, host?}`, `token {token}`, `navigate {view}`, `theme {theme}`,
15
+ * `open {view?}` (the messenger panel became visible; optionally switch view).
16
+ * frame -> host: `ready`, `request-token`, `resize {height}`, `event {name, data}`, `error {code, message}`,
17
+ * `unread {count}` (launcher badge), `close` (the user closed the messenger from inside the frame).
18
+ */
19
+ export const HOST_MESSAGES = ["init", "token", "navigate", "theme", "open"];
20
+ export const FRAME_MESSAGES = ["ready", "request-token", "resize", "event", "error", "unread", "close"];
21
+ export function isProtocolMessage(data) {
22
+ if (typeof data !== "object" || data === null)
23
+ return false;
24
+ const d = data;
25
+ return d.source === PROTOCOL_SOURCE && typeof d.type === "string";
26
+ }
27
+ /** True for a view string the embed accepts. */
28
+ export function isView(v) {
29
+ return typeof v === "string" && VIEW_PATTERN.test(v);
30
+ }
31
+ /** A sane unread count from an untrusted payload: an integer in 0..MAX_UNREAD, else null. */
32
+ export function readUnread(payload) {
33
+ const n = Number(payload === null || payload === void 0 ? void 0 : payload.count);
34
+ if (!Number.isFinite(n) || n < 0)
35
+ return null;
36
+ return Math.min(MAX_UNREAD, Math.floor(n));
37
+ }
38
+ /** The origin of a desk URL: https, or http for localhost only. Throws for anything else. */
39
+ export function deskOrigin(baseUrl) {
40
+ let url;
41
+ try {
42
+ url = new URL(baseUrl);
43
+ }
44
+ catch (_a) {
45
+ throw new Error("ArmDeskConnect: baseUrl must be an absolute URL");
46
+ }
47
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
48
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
49
+ throw new Error("ArmDeskConnect: baseUrl must be https (http is allowed for localhost only)");
50
+ }
51
+ return url.origin;
52
+ }
53
+ /** Sent by the library to a server-mode session route; a custom header a cross-site form cannot add. */
54
+ export const CSRF_HEADER = "X-ArmDesk-Csrf";
55
+ export const DEFAULT_SESSION_PATH = "/armdesk/session";
56
+ export const JWT_BEARER_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer";
57
+ export const ASSERTION_AUDIENCE = "armdesk-connect";