@armdesk/connect-sdk 0.0.0-stage → 1.0.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 (47) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/LICENSE.txt +15 -0
  3. package/README.md +403 -3
  4. package/dist/armdesk-connect.js +23 -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 +44 -0
  8. package/dist/esm/client.js +298 -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 +307 -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 +18 -0
  20. package/dist/esm/index.js +15 -0
  21. package/dist/esm/mount.d.ts +8 -0
  22. package/dist/esm/mount.js +170 -0
  23. package/dist/esm/protocol.d.ts +18 -0
  24. package/dist/esm/protocol.js +31 -0
  25. package/dist/esm/react.d.ts +61 -0
  26. package/dist/esm/react.js +199 -0
  27. package/dist/esm/register.d.ts +1 -0
  28. package/dist/esm/register.js +5 -0
  29. package/dist/esm/sanitize.d.ts +8 -0
  30. package/dist/esm/sanitize.js +57 -0
  31. package/dist/esm/server.d.ts +17 -0
  32. package/dist/esm/server.js +93 -0
  33. package/dist/esm/sign.d.ts +54 -0
  34. package/dist/esm/sign.js +77 -0
  35. package/dist/esm/theme.d.ts +8 -0
  36. package/dist/esm/theme.js +46 -0
  37. package/dist/esm/types.d.ts +298 -0
  38. package/dist/esm/types.js +1 -0
  39. package/examples/express-server/package.json +10 -0
  40. package/examples/express-server/server.mjs +35 -0
  41. package/examples/mock-idp.mjs +30 -0
  42. package/examples/react-vite/index.html +11 -0
  43. package/examples/react-vite/package.json +15 -0
  44. package/examples/react-vite/src/main.jsx +25 -0
  45. package/examples/react-vite/vite.config.js +4 -0
  46. package/examples/wso2-browser.html +86 -0
  47. package/package.json +59 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,22 @@
1
+ # Changelog
2
+
3
+ ## 1.0.0
4
+
5
+ The complete library. An integrating product needs only this package; it never calls an ARM Desk endpoint itself.
6
+
7
+ - `ArmDeskConnect.init({ orgKey, auth })` / `createClient`: the desk URL is detected from the script tag's origin.
8
+ Auth modes: `userToken` (signed user token, primary), `idToken` (browser OIDC / WSO2), `sessionUrl` (server route),
9
+ `getToken` (legacy).
10
+ - Headless typed client: `me`, `config`, `categories`, `tickets.{list,get,create,reply,close}`, `catalog.{list,request}`,
11
+ events (`ticket.created`, `ticket.replied`, `session.expired`, `error`), `signOut`, `mount`. Typed `ArmDeskError`.
12
+ Retries with backoff on 429 / 5xx (Retry-After honoured), never on other 4xx; in-memory token cache with early renewal.
13
+ - Web components (Shadow DOM): `<armdesk-tickets>`, `<armdesk-new-ticket>`, `<armdesk-ticket>`, `<armdesk-launcher>`.
14
+ - React: `ArmDeskProvider`, `useArmDesk`, `useTickets`, `useTicket`, `useCreateTicket`, `ArmDeskEmbed`, `ArmDeskTickets`,
15
+ `ArmDeskTicket`, `ArmDeskNewTicket` (React is an optional peer).
16
+ - Server (`/server`): `signUserToken` (HS256 with a key derived from the org secret, or RS256/ES256 with your private key),
17
+ `createConnectHandler` (Express, Next.js, fetch, Node adapters; CSRF-checked), `createConnectSession`.
18
+ - Deprecated: `ArmDeskConnect.mount(el, { baseUrl, orgKey, getToken })` still works; use `init(...).mount(el)`.
19
+
20
+ ## 0.1.0
21
+
22
+ First release: iframe embed (`mount`), `createConnectSession`, `<ArmDeskEmbed>`.
package/LICENSE.txt ADDED
@@ -0,0 +1,15 @@
1
+ ARM Desk SDK licence
2
+
3
+ Copyright (c) 2026 DHRP. All rights reserved.
4
+
5
+ This package is proprietary software. It is made available on the npm registry
6
+ so that customers of ARM Desk can install it, and it may be used only to build
7
+ integrations with an ARM Desk service under the customer's agreement with DHRP.
8
+
9
+ No other right is granted. You may not copy, modify, sublicense, sell or
10
+ redistribute this package, or use it with any service other than ARM Desk,
11
+ except as that agreement allows.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED. IN NO EVENT SHALL DHRP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15
+ LIABILITY ARISING FROM THE SOFTWARE OR ITS USE, EXCEPT AS THAT AGREEMENT SAYS.
package/README.md CHANGED
@@ -1,3 +1,403 @@
1
- # Temporary Holding Version
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.
1
+ # @armdesk/connect-sdk
2
+
3
+ ARM Desk Connect: put support tickets (My tickets, New ticket, conversation) inside your own product, with your own
4
+ sign-in and your own look. **This package is everything you need.** You never call an ARM Desk endpoint yourself and
5
+ never read an API reference.
6
+
7
+ ```
8
+ your server your page ARM Desk
9
+ signUserToken({orgKey, orgSecret, ArmDeskConnect.init({ orgKey, verifies the signature, creates/updates
10
+ user}) -> short-lived token --> auth: { userToken: () => token } }) the customer + CRM contact, issues a
11
+ (local, no network call) client.mount(...) / <armdesk-tickets> 15-minute session the library renews
12
+ ```
13
+
14
+ 1. A tenant admin registers your product as a **Connected organization** (Admin > Developer > Connect) and gets an
15
+ `orgKey` (`org_...`, public) and an `orgSecret` (`cos_...`, **shown once**), and lists your site's origins.
16
+ 2. Your **server** signs a short-lived token for the signed-in user (`signUserToken`, no network call) and renders it
17
+ into your page.
18
+ 3. Your **page** gives that token to the library. Done.
19
+
20
+ Contents: [Quick starts](#quick-starts) | [Signing without Node](#signing-the-user-token-without-node) |
21
+ [Client API](#client-api) | [UI](#ui) | [Server helpers](#server-helpers) | [Theme](#theme-keys) | [Errors](#errors) |
22
+ [Security](#security-notes) | [Embed protocol](#embed-protocol)
23
+
24
+ ## Install
25
+
26
+ Script tag (served by your ARM Desk; it detects the desk from its own URL, so only `orgKey` is needed):
27
+
28
+ ```html
29
+ <script src="https://<your-desk>/connect/armdesk-connect.js"></script>
30
+ ```
31
+
32
+ npm: `pnpm add @armdesk/connect-sdk`. Entries: `.` (browser client), `/server` (Node 18+), `/react` (React 17+, optional
33
+ peer), `/elements` (web components). The IIFE has no dependencies (about 9 kB gzipped, web components included).
34
+
35
+ ## Quick starts
36
+
37
+ ### 1. Script tag + signed user token (recommended)
38
+
39
+ Your server signs the token while rendering the page the user is already signed in to (no new endpoint):
40
+
41
+ ```js
42
+ // server (Node). Other languages: see "Signing the user token without Node".
43
+ import { signUserToken } from "@armdesk/connect-sdk/server";
44
+
45
+ const userToken = signUserToken({
46
+ orgKey: process.env.ARMDESK_ORG_KEY,
47
+ orgSecret: process.env.ARMDESK_ORG_SECRET, // server only
48
+ user: { id: user.id, email: user.email, name: user.name, role: user.role, department: user.department, phone: user.phone },
49
+ expiresIn: 300, // seconds, default 300, max 600
50
+ });
51
+ // render it into the page, e.g. <meta name="armdesk-user-token" content="...">
52
+ ```
53
+
54
+ ```html
55
+ <div id="support"></div>
56
+ <script src="https://<your-desk>/connect/armdesk-connect.js"></script>
57
+ <script>
58
+ const client = ArmDeskConnect.init({
59
+ orgKey: "org_xxxxxxxxxxxxxxxxxxxxxxxx",
60
+ auth: { userToken: () => document.querySelector('meta[name="armdesk-user-token"]').content },
61
+ });
62
+ client.mount("#support", { theme: { primaryColor: "#0f766e" } }); // the full portal UI in an iframe
63
+ </script>
64
+ ```
65
+
66
+ The token is short-lived on purpose. When the ARM Desk session (15 minutes) runs out the library calls `userToken()`
67
+ again, so make it return a fresh token (for example by reloading a tiny JSON from your own page, or by minting a token
68
+ per call in a server-rendered app). Prefer the pieces in your own layout? Use the [web components](#ui) instead of
69
+ `client.mount`.
70
+
71
+ ### 2. Script tag + WSO2 / OIDC, no backend at all
72
+
73
+ If your product signs users in with WSO2 (or any OIDC provider) in the browser, hand the library the ID token. Nothing
74
+ of yours runs on a server. The admin must switch on **Browser sessions** and trust your issuer (Admin > Connect > Identity).
75
+
76
+ ```html
77
+ <script src="https://<your-desk>/connect/armdesk-connect.js"></script>
78
+ <script>
79
+ const client = ArmDeskConnect.init({
80
+ orgKey: "org_xxxxxxxxxxxxxxxxxxxxxxxx",
81
+ auth: { idToken: () => myOidcClient.getIdToken() }, // your existing WSO2 sign-in
82
+ });
83
+ client.mount("#support");
84
+ </script>
85
+ ```
86
+
87
+ The library keeps the ARM Desk session in memory and renews it itself; it asks for a new ID token only when it must.
88
+ Try it locally with `examples/wso2-browser.html` (it contains a mock identity provider).
89
+
90
+ ### 3. React
91
+
92
+ ```tsx
93
+ import { ArmDeskProvider, ArmDeskEmbed, ArmDeskTickets, ArmDeskNewTicket, useTickets } from "@armdesk/connect-sdk/react";
94
+
95
+ export function Support({ userToken }: { userToken: string }) {
96
+ return (
97
+ <ArmDeskProvider orgKey="org_xxxxxxxxxxxxxxxxxxxxxxxx" desk="https://desk.example.com" auth={{ userToken: () => userToken }}>
98
+ <ArmDeskEmbed view="tickets" theme={{ primaryColor: "#0f766e" }} />
99
+ {/* or build your own UI: <ArmDeskTickets onSelect={openTicket} /> <ArmDeskNewTicket /> */}
100
+ </ArmDeskProvider>
101
+ );
102
+ }
103
+
104
+ function OpenCount() {
105
+ const { data, loading, error, refetch } = useTickets({ status: "OPEN", limit: 5 });
106
+ return <span>{loading ? "..." : data?.total}</span>;
107
+ }
108
+ ```
109
+
110
+ With WSO2 in the browser use `auth={{ idToken: () => oidc.getIdToken() }}`. Hooks: `useArmDesk()` (the client),
111
+ `useTickets(params)`, `useTicket(id)`, `useCreateTicket()`. They refetch on `ticket.created` / `ticket.replied`.
112
+
113
+ ### 4. Express, server mode
114
+
115
+ When you prefer a route to render-time tokens, the helper mounts the route the browser library calls by default
116
+ (`/armdesk/session`). It reads YOUR signed-in user, talks to ARM Desk with the org secret, and returns only the token.
117
+
118
+ ```js
119
+ import express from "express";
120
+ import { createConnectHandler } from "@armdesk/connect-sdk/server";
121
+
122
+ const armdesk = createConnectHandler({
123
+ orgKey: process.env.ARMDESK_ORG_KEY,
124
+ orgSecret: process.env.ARMDESK_ORG_SECRET,
125
+ desk: "https://desk.example.com",
126
+ getUser: (req) => req.user && { id: req.user.id, email: req.user.email, name: req.user.name, role: req.user.role },
127
+ });
128
+
129
+ const app = express();
130
+ app.post("/armdesk/session", armdesk.express());
131
+ ```
132
+
133
+ ```html
134
+ <script>
135
+ ArmDeskConnect.init({ orgKey: "org_...", auth: {} }).mount("#support"); // sessionUrl defaults to /armdesk/session
136
+ </script>
137
+ ```
138
+
139
+ ### 5. Next.js, server mode
140
+
141
+ ```ts
142
+ // app/armdesk/session/route.ts
143
+ import { createConnectHandler } from "@armdesk/connect-sdk/server";
144
+ import { getSession } from "@/lib/auth"; // yours
145
+
146
+ export const POST = createConnectHandler({
147
+ orgKey: process.env.ARMDESK_ORG_KEY!,
148
+ orgSecret: process.env.ARMDESK_ORG_SECRET!,
149
+ desk: process.env.ARMDESK_URL!,
150
+ getUser: async (req: Request) => {
151
+ const s = await getSession(req);
152
+ return s && { id: s.userId, email: s.email, name: s.name };
153
+ },
154
+ }).next();
155
+ ```
156
+
157
+ Client: `<ArmDeskProvider orgKey="org_..." desk="..." auth={{}}>` (empty auth means `sessionUrl: "/armdesk/session"`).
158
+ Cloudflare Workers, Deno and Bun use `handler.fetch(request)`; plain `http` uses `handler.node(req, res)`.
159
+ CSRF: the route requires the `X-ArmDesk-Csrf: 1` header (sent by the library; a cross-site form cannot add it), refuses
160
+ a foreign `Origin` (add trusted ones with `allowedOrigins`), and never caches.
161
+
162
+ ### 6. Headless (no UI from us)
163
+
164
+ ```ts
165
+ import { createClient, ArmDeskError } from "@armdesk/connect-sdk";
166
+
167
+ const client = createClient({ orgKey: "org_...", desk: "https://desk.example.com", auth: { userToken: () => fetchToken() } });
168
+
169
+ const { items, total } = await client.tickets.list({ status: ["OPEN", "PENDING"], search: "vpn", page: 1, limit: 20 });
170
+ const t = await client.tickets.create({ subject: "Cannot log in", description: "Plain text.", priority: "HIGH", files: [file] });
171
+ await client.tickets.reply(t.id, { body: "Thanks, that worked.", files: [] });
172
+ await client.tickets.close(t.id);
173
+
174
+ client.on("ticket.created", (t) => analytics.track("ticket", t.number));
175
+ client.on("session.expired", () => window.location.assign("/login"));
176
+ try { await client.me(); } catch (e) { if (e instanceof ArmDeskError) console.log(e.code, e.status); }
177
+ ```
178
+
179
+ ## Signing the user token without Node
180
+
181
+ `signUserToken` produces a standard JWT (RFC 7523 assertion), so any JWT library can do it. Rules:
182
+
183
+ - Header: `alg: HS256`, `typ: JWT`, `kid: "<orgKey>:<secretVersion>"` (secret version 1 unless the admin rotated your
184
+ secret; the Connect screen shows the key id to use).
185
+ - HMAC key: `HMAC-SHA256(key = orgSecret, message = "armdesk-connect-assertion-v1")` as raw bytes. The raw secret is never
186
+ the JWT key.
187
+ - Claims: `iss` = orgKey, `sub` = your user id, `aud` = `armdesk-connect`, `iat`, `nbf`, `exp` (at most `iat` + 600 s),
188
+ `jti` (random, single use), and optionally `email`, `email_verified`, `name`, `given_name`, `family_name`,
189
+ `phone_number`, `role`, `department`, `attributes` (object, at most 4 KB).
190
+
191
+ Python (PyJWT):
192
+
193
+ ```python
194
+ import hashlib, hmac, secrets, time, jwt
195
+
196
+ key = hmac.new(ORG_SECRET.encode(), b"armdesk-connect-assertion-v1", hashlib.sha256).digest()
197
+ now = int(time.time())
198
+ token = jwt.encode(
199
+ {"iss": ORG_KEY, "sub": user.id, "aud": "armdesk-connect", "iat": now, "nbf": now, "exp": now + 300,
200
+ "jti": secrets.token_hex(16), "email": user.email, "name": user.name, "role": user.role},
201
+ key, algorithm="HS256", headers={"kid": f"{ORG_KEY}:1"})
202
+ ```
203
+
204
+ Java (com.auth0:java-jwt):
205
+
206
+ ```java
207
+ Mac mac = Mac.getInstance("HmacSHA256");
208
+ mac.init(new SecretKeySpec(ORG_SECRET.getBytes(UTF_8), "HmacSHA256"));
209
+ byte[] key = mac.doFinal("armdesk-connect-assertion-v1".getBytes(UTF_8));
210
+ Instant now = Instant.now();
211
+ String token = JWT.create()
212
+ .withKeyId(ORG_KEY + ":1").withIssuer(ORG_KEY).withSubject(user.getId()).withAudience("armdesk-connect")
213
+ .withIssuedAt(now).withNotBefore(now).withExpiresAt(now.plusSeconds(300)).withJWTId(UUID.randomUUID().toString())
214
+ .withClaim("email", user.getEmail()).withClaim("name", user.getName()).withClaim("role", user.getRole())
215
+ .sign(Algorithm.HMAC256(key));
216
+ ```
217
+
218
+ .NET (System.IdentityModel.Tokens.Jwt):
219
+
220
+ ```csharp
221
+ using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(orgSecret));
222
+ var key = new SymmetricSecurityKey(hmac.ComputeHash(Encoding.UTF8.GetBytes("armdesk-connect-assertion-v1"))) { KeyId = $"{orgKey}:1" };
223
+ var now = DateTime.UtcNow;
224
+ var jwt = new JwtSecurityToken(
225
+ issuer: orgKey, audience: "armdesk-connect", notBefore: now, expires: now.AddMinutes(5),
226
+ signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256),
227
+ claims: new[] { new Claim("sub", user.Id), new Claim("jti", Guid.NewGuid().ToString("N")), new Claim("email", user.Email), new Claim("name", user.Name) });
228
+ jwt.Payload["iat"] = new DateTimeOffset(now).ToUnixTimeSeconds();
229
+ var token = new JwtSecurityTokenHandler().WriteToken(jwt);
230
+ ```
231
+
232
+ PHP (firebase/php-jwt):
233
+
234
+ ```php
235
+ $key = hash_hmac('sha256', 'armdesk-connect-assertion-v1', $orgSecret, true);
236
+ $now = time();
237
+ $token = JWT::encode([
238
+ 'iss' => $orgKey, 'sub' => (string) $user->id, 'aud' => 'armdesk-connect', 'iat' => $now, 'nbf' => $now,
239
+ 'exp' => $now + 300, 'jti' => bin2hex(random_bytes(16)), 'email' => $user->email, 'name' => $user->name,
240
+ ], $key, 'HS256', $orgKey . ':1');
241
+ ```
242
+
243
+ Go (golang-jwt/jwt/v5):
244
+
245
+ ```go
246
+ mac := hmac.New(sha256.New, []byte(orgSecret))
247
+ mac.Write([]byte("armdesk-connect-assertion-v1"))
248
+ key := mac.Sum(nil)
249
+ now := time.Now()
250
+ t := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
251
+ "iss": orgKey, "sub": user.ID, "aud": "armdesk-connect", "iat": now.Unix(), "nbf": now.Unix(),
252
+ "exp": now.Add(5 * time.Minute).Unix(), "jti": uuid.NewString(), "email": user.Email, "name": user.Name,
253
+ })
254
+ t.Header["kid"] = orgKey + ":1"
255
+ token, err := t.SignedString(key)
256
+ ```
257
+
258
+ Prefer asymmetric keys? Register a public key (or JWKS URL) for the organisation and sign RS256 / ES256 with your
259
+ private key; the secret then never exists on your servers: `signUserToken({ orgKey, privateKey, kid, user })`.
260
+
261
+ ## Client API
262
+
263
+ `ArmDeskConnect.init(options)` (script tag) or `createClient(options)` (ESM). `init` also makes the client the one the web
264
+ components use.
265
+
266
+ | Option | Notes |
267
+ |---|---|
268
+ | `orgKey` | Required. |
269
+ | `desk` | The desk URL. Default: the origin the script tag was loaded from. Required with npm. https (http for localhost). |
270
+ | `auth` | One of `{ userToken }`, `{ idToken, nonce? }`, `{ sessionUrl? }`, `{ getToken }` (legacy). |
271
+ | `apiBase` | Override where the API lives (default: announced by the desk, else `<desk>/api/proxy`). |
272
+ | `locale`, `theme`, `features` | Defaults for `mount`. |
273
+ | `retries` / `retryDelayMs` / `timeoutMs` | Default 2 / 400 / 20000. |
274
+ | `fetch` | Custom fetch. |
275
+
276
+ | Method | Returns |
277
+ |---|---|
278
+ | `me()` | the signed-in user and organisation |
279
+ | `config()` | organisation name, theme, features, locale |
280
+ | `tickets.list({ status, search, page, limit })` | `{ items, total }` (status: one value or an array; up to 100 per page) |
281
+ | `tickets.get(id)` | ticket with its public threads (HTML is sanitised) and `canReply` / `canClose` |
282
+ | `tickets.create({ subject, description, priority?, categoryId?, files? })` | the created ticket (description is plain text) |
283
+ | `tickets.reply(id, { body, files? })` | the reply |
284
+ | `tickets.close(id)` | "Mark as solved" |
285
+ | `categories()` | help topics |
286
+ | `catalog.list({ search?, categoryId? })`, `catalog.request(itemId, answers, { quantity?, requestedForId?, files? })` | service catalog |
287
+ | `on(event, cb)` | `ticket.created`, `ticket.replied`, `session.expired`, `error`; returns an unsubscribe function |
288
+ | `mount(el, { view, theme, features, height, onEvent, onError })` | the iframe embed; returns `{ navigate, setTheme, refreshToken, destroy }` |
289
+ | `getAccessToken()`, `signOut()` | the cached session token; forget it |
290
+
291
+ Files are `File` or `Blob`. The token lives in memory only, is renewed 30 seconds before it expires, and a rejected token
292
+ triggers one fresh sign-in and a retry. Requests are retried with exponential backoff on 429 and 5xx (a `Retry-After`
293
+ header wins; a POST is retried only on 429 and 503), never on other 4xx.
294
+
295
+ ### Sign-in modes
296
+
297
+ | `auth` | Who proves the user | Your side |
298
+ |---|---|---|
299
+ | `{ userToken }` | Your server, with the org secret (signed token, 5 minutes) | `signUserToken` (any language) |
300
+ | `{ idToken }` | Your IdP (WSO2 / OIDC); needs "Browser sessions" on and the issuer trusted | nothing |
301
+ | `{ sessionUrl }` | Your server route | `createConnectHandler` |
302
+ | `{ getToken }` | You fetch an ARM Desk connect token yourself (legacy) | `createConnectSession` |
303
+
304
+ ## UI
305
+
306
+ Two ways, same data layer:
307
+
308
+ - **`client.mount(el)`**: the complete ARM Desk portal UI in an iframe (origin-checked postMessage, token never in the
309
+ URL, auto-resize). Fastest, always up to date.
310
+ - **Web components** (Shadow DOM, no framework; registered by the script tag or `import "@armdesk/connect-sdk/elements"`):
311
+
312
+ ```html
313
+ <armdesk-tickets limit="10" status="OPEN,PENDING"></armdesk-tickets>
314
+ <armdesk-new-ticket></armdesk-new-ticket>
315
+ <armdesk-ticket ticket-id="..."></armdesk-ticket>
316
+ <armdesk-launcher label="Help" view="tickets" position="right"></armdesk-launcher>
317
+ ```
318
+
319
+ Why Shadow DOM rather than iframe wrappers: the elements are for hosts that want tickets to be part of their page (their
320
+ layout and scrolling, no frame, no cross-origin resize), and they run on the same headless client, so there is one
321
+ contract. Shadow DOM isolates our CSS from yours. Everything is built from DOM nodes and `textContent`; the only HTML
322
+ (ticket threads) goes through an allow-list sanitiser. `<armdesk-launcher>` is the exception on purpose: it opens the full
323
+ iframe embed in a floating panel. Elements emit `armdesk-ticket-select`, `armdesk-ticket-created` and
324
+ `armdesk-ticket-replied` events (bubbling, composed), take a `theme` attribute (JSON), and a `client` property when you do
325
+ not want the global one.
326
+
327
+ ## Server helpers
328
+
329
+ `@armdesk/connect-sdk/server`: `signUserToken(options)`, `createConnectHandler(options)` (`.express()`, `.next()`,
330
+ `.fetch(req)`, `.node(req, res)`), `createConnectSession(options)` (server-to-server, orgKey + orgSecret, returns a
331
+ connect token), `deriveAssertionKey(secret)`.
332
+
333
+ ## Theme keys
334
+
335
+ All optional; the desk validates them again. Colours are `#rrggbb`. Anything invalid is ignored. They become CSS
336
+ variables (`--ad-primary`, `--ad-bg`, ...) in the web components and style the iframe embed.
337
+
338
+ | Key | Values |
339
+ |---|---|
340
+ | `primaryColor` | Buttons, links, highlights. |
341
+ | `backgroundColor`, `surfaceColor`, `textColor`, `mutedColor`, `borderColor` | Page, cards, text, secondary text, dividers. |
342
+ | `fontFamily` | `system` \| `inter` \| `roboto` \| `open-sans` \| `lato` |
343
+ | `radius` | 0 to 24 (px). |
344
+ | `density` | `comfortable` \| `compact` |
345
+ | `logoUrl`, `showHeader`, `headerTitle` | Header of the embed (https logo, up to 80 characters). |
346
+ | `mode` | `light` \| `dark` \| `auto` (follows the visitor's system) |
347
+
348
+ Features (can only narrow what the organisation allows): `newTicket`, `attachments`, `catalog`, `orgTickets`, `replies`,
349
+ `closeTicket`.
350
+
351
+ ## Errors
352
+
353
+ Every failure is an `ArmDeskError` with `code`, `status`, `message`:
354
+
355
+ | code | When |
356
+ |---|---|
357
+ | `unauthorized` | 401: the session could not be established |
358
+ | `forbidden` | 403: feature off, origin not allowed |
359
+ | `not_found`, `conflict`, `validation` | 404, 409, 400 / 422 |
360
+ | `rate_limited`, `server` | 429, 5xx after the retries |
361
+ | `network` | the desk could not be reached |
362
+ | `invalid_grant`, `invalid_request`, `unauthorized_client` | the token exchange refused the signed user token (expired, replayed, wrong key ...) |
363
+ | `config` | wrong library options |
364
+
365
+ ## Security notes
366
+
367
+ - **The secret stays on your server.** It is only used by `signUserToken` / `createConnectHandler` /
368
+ `createConnectSession`. Never put it in a page, an app bundle or a repository. Rotate it in ARM Desk (the previous one
369
+ keeps working for 24 hours).
370
+ - Keep user tokens short-lived (default 5 minutes, hard maximum 10). Each carries a random `jti` and works once.
371
+ - Serve everything over HTTPS. The library refuses a non-https desk except localhost.
372
+ - The ARM Desk session token (15 minutes) is kept in memory, sent as a Bearer header or by postMessage to the desk's exact
373
+ origin, and never put in a URL, cookie or storage.
374
+ - ARM Desk lets only the organisation's **allowed origins** frame the embed and call the API from a browser.
375
+ - Users only see their own tickets (and their organisation's when enabled), never internal notes.
376
+ - Theme values are validated and become CSS variables; no host CSS or HTML is injected. Your Content-Security-Policy must
377
+ allow the desk in `frame-src` and `connect-src` (and `script-src` for the script tag).
378
+
379
+ ## Embed protocol
380
+
381
+ Only for custom hosts of the iframe. The URL is `<desk>/embed/itsm?org=<orgKey>&view=<view>&locale=<locale>`. Messages are
382
+ `{ source: "armdesk-connect", type, payload }`; both sides check `event.origin` and the sender window.
383
+
384
+ | Direction | type | payload |
385
+ |---|---|---|
386
+ | frame to host | `ready` | none (sent first) |
387
+ | host to frame | `init` | `{ token, theme, features }` |
388
+ | frame to host | `request-token` | none |
389
+ | host to frame | `token` / `navigate` / `theme` | `{ token }` / `{ view }` / `{ theme }` |
390
+ | frame to host | `resize` / `event` / `error` | `{ height }` / `{ name, data }` / `{ code, message }` |
391
+
392
+ ## Legacy
393
+
394
+ `ArmDeskConnect.mount(el, { baseUrl, orgKey, getToken })` and `<ArmDeskEmbed baseUrl orgKey getToken />` still work
395
+ (deprecated; use `init(...)` and `client.mount(el)`). `getToken` returns an ARM Desk connect token from your own backend
396
+ (`createConnectSession`).
397
+
398
+ ## Examples and release
399
+
400
+ `examples/wso2-browser.html` (script tag + a mock IdP, nothing to install), `examples/express-server/` (server mode),
401
+ `examples/react-vite/` (React). None is wired into Docker. `pnpm --filter @armdesk/connect-sdk build` enforces the size
402
+ budget (IIFE at most 25 kB gzipped) and publishes the script to the web app; `pnpm --filter @armdesk/connect-sdk
403
+ release` writes the npm tarball to `release/` (see CHANGELOG.md).
@@ -0,0 +1,23 @@
1
+ var ArmDeskConnect=function(C){"use strict";var Je=Object.defineProperty,Xe=Object.defineProperties;var Ve=Object.getOwnPropertyDescriptors;var fe=Object.getOwnPropertySymbols;var Ye=Object.prototype.hasOwnProperty,Ze=Object.prototype.propertyIsEnumerable;var me=(C,_,I)=>_ in C?Je(C,_,{enumerable:!0,configurable:!0,writable:!0,value:I}):C[_]=I,U=(C,_)=>{for(var I in _||(_={}))Ye.call(_,I)&&me(C,I,_[I]);if(fe)for(var I of fe(_))Ze.call(_,I)&&me(C,I,_[I]);return C},pe=(C,_)=>Xe(C,Ve(_));let _,I=null;const B=new Set;function be(e){_=e}function ge(){return _}function ye(e){I=e,B.forEach(t=>t(e))}function ke(){return I}function we(e){return B.add(e),()=>B.delete(e)}const ve=new Set(["p","br","b","strong","i","em","u","s","ul","ol","li","a","code","pre","blockquote","span","div","h1","h2","h3","h4","h5","h6","hr"]),xe=new Set(["script","style","iframe","object","embed","template","noscript","svg","math","form","textarea","select","head","title"]);function Te(e){const t=e.trim();return/^(https?:|mailto:)/i.test(t)?t:null}function W(e,t,s){e.childNodes.forEach(l=>{var f,n;if(l.nodeType===3){t.appendChild(s.createTextNode((f=l.textContent)!=null?f:""));return}if(l.nodeType!==1)return;const c=l,h=c.tagName.toLowerCase();if(xe.has(h))return;if(!ve.has(h)){W(c,t,s);return}const S=s.createElement(h);if(h==="a"){const i=Te((n=c.getAttribute("href"))!=null?n:"");i&&(S.setAttribute("href",i),S.setAttribute("target","_blank"),S.setAttribute("rel","noopener noreferrer nofollow"))}W(c,S,s),t.appendChild(S)})}function Ae(e){if(typeof DOMParser=="undefined")return e.replace(/<[^>]*>/g,"");const t=new DOMParser().parseFromString(e,"text/html"),s=t.createElement("div");return W(t.body,s,t),s.innerHTML}function Ee(e,t){const s=e.ownerDocument.createElement("div");s.innerHTML=Ae(t),e.replaceChildren(...Array.from(s.childNodes))}const Ce=/^#[0-9a-fA-F]{6}$/,J={system:'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',inter:'Inter, system-ui, -apple-system, "Segoe UI", sans-serif',roboto:'Roboto, system-ui, "Segoe UI", sans-serif',"open-sans":'"Open Sans", system-ui, "Segoe UI", sans-serif',lato:'Lato, system-ui, "Segoe UI", sans-serif'},Se={"--ad-bg":"#ffffff","--ad-surface":"#f8f9fb","--ad-text":"#1a1d23","--ad-muted":"#6b7280","--ad-border":"#e5e7eb","--ad-primary":"#2563eb"},V={"--ad-bg":"#0f1115","--ad-surface":"#181b21","--ad-text":"#f3f4f6","--ad-muted":"#9ca3af","--ad-border":"#2a2f38","--ad-primary":"#60a5fa"},Me=[["backgroundColor","--ad-bg"],["surfaceColor","--ad-surface"],["textColor","--ad-text"],["mutedColor","--ad-muted"],["borderColor","--ad-border"],["primaryColor","--ad-primary"]],X=e=>Object.entries(e).map(([t,s])=>`${t}:${s};`).join("");function $e(e){const t={},s=e!=null?e:{};for(const[l,c]of Me){const h=s[l];typeof h=="string"&&Ce.test(h)&&(t[c]=h.toLowerCase())}return typeof s.fontFamily=="string"&&J[s.fontFamily]&&(t["--ad-font"]=J[s.fontFamily]),typeof s.radius=="number"&&Number.isFinite(s.radius)&&(t["--ad-radius"]=`${Math.min(24,Math.max(0,Math.round(s.radius)))}px`),t["--ad-pad"]=s.density==="compact"?"6px 10px":"10px 14px",t}function De(e){var c;const t=(c=e==null?void 0:e.mode)!=null?c:"auto",s=`:host{display:block;--ad-font:${J.system};--ad-radius:8px;--ad-pad:10px 14px;${X(t==="dark"?V:Se)}}`,l=t==="auto"?`@media (prefers-color-scheme:dark){:host{${X(V)}}}`:"";return`${s}${l}:host{${X($e(e))}}`}function a(e,t={},...s){const l=document.createElement(e);for(const[c,h]of Object.entries(t))h===void 0||h===!1||(typeof h=="function"?l.addEventListener(c.replace(/^on/,""),h):h===!0?l.setAttribute(c,""):l.setAttribute(c,h));for(const c of s)c&&l.append(c);return l}const Oe=`
2
+ *{box-sizing:border-box}
3
+ .ad{font-family:var(--ad-font);color:var(--ad-text);background:var(--ad-bg);font-size:14px;line-height:1.45}
4
+ .ad h3{margin:0 0 8px;font-size:16px}
5
+ .card{background:var(--ad-surface);border:1px solid var(--ad-border);border-radius:var(--ad-radius);padding:var(--ad-pad);margin:0 0 8px}
6
+ .row{display:flex;gap:8px;align-items:center;justify-content:space-between;width:100%;text-align:left;font:inherit;color:inherit;cursor:pointer}
7
+ .muted{color:var(--ad-muted);font-size:12px}
8
+ .badge{border:1px solid var(--ad-border);border-radius:999px;padding:0 8px;font-size:12px;color:var(--ad-muted);white-space:nowrap}
9
+ button,input,select,textarea{font:inherit;color:inherit}
10
+ input,select,textarea{width:100%;background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:var(--ad-radius);padding:var(--ad-pad)}
11
+ .btn{background:var(--ad-primary);color:#fff;border:0;border-radius:var(--ad-radius);padding:var(--ad-pad);cursor:pointer}
12
+ .btn.ghost{background:transparent;color:var(--ad-primary);border:1px solid var(--ad-border)}
13
+ .btn[disabled]{opacity:.6;cursor:default}
14
+ label{display:block;margin:0 0 10px}
15
+ .err{color:#b91c1c}
16
+ .agent{border-left:3px solid var(--ad-primary)}
17
+ .body a{color:var(--ad-primary)}.body pre{white-space:pre-wrap;overflow:auto}
18
+ .bar{display:flex;gap:8px;justify-content:space-between;align-items:center}
19
+ .fab{position:fixed;bottom:20px;z-index:2147483000}
20
+ .fab.right{right:20px}.fab.left{left:20px}
21
+ .panel{position:fixed;bottom:76px;width:min(400px,calc(100vw - 24px));height:min(640px,calc(100vh - 100px));background:var(--ad-bg);border:1px solid var(--ad-border);border-radius:var(--ad-radius);overflow:hidden;z-index:2147483000;box-shadow:0 8px 30px rgba(0,0,0,.25)}
22
+ .panel.right{right:20px}.panel.left{left:20px}
23
+ `;function Y(e){if(e)try{const t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch(t){return}}function Z(){if(typeof customElements=="undefined"||typeof HTMLElement=="undefined")return;class e extends HTMLElement{constructor(){super(...arguments),this.client=null,this.unsub=null,this.bound=null,this.offEvents=[]}static get observedAttributes(){return["theme","ticket-id","status","limit","view","label","position"]}get c(){var n;return(n=this.client)!=null?n:ke()}connectedCallback(){this.root||(this.root=this.attachShadow({mode:"open"}),this.styleEl=document.createElement("style"),this.box=a("div",{class:"ad",part:"root"}),this.root.append(this.styleEl,this.box)),this.paintTheme(),this.unsub=we(()=>this.start()),this.start()}disconnectedCallback(){var n;(n=this.unsub)==null||n.call(this),this.unsub=null,this.offEvents.forEach(i=>i()),this.offEvents=[],this.bound=null,this.teardown()}attributeChangedCallback(){!this.isConnected||!this.root||(this.paintTheme(),this.load())}paintTheme(){const n=U(U({},this.cfgTheme),Y(this.getAttribute("theme")));this.styleEl.textContent=De(n)+Oe}start(){const n=this.c;if(!n){this.box.replaceChildren(a("p",{class:"muted"},"ARM Desk is not initialised yet."));return}n!==this.bound&&(this.offEvents.forEach(i=>i()),this.offEvents=this.watch(n),this.bound=n,n.config().then(i=>{this.cfgTheme=i.theme,this.paintTheme()},()=>{})),this.load()}watch(n){return[]}async load(){}teardown(){}fail(n,i){this.box.replaceChildren(a("p",{class:"err",role:"alert"},n instanceof Error?n.message:"Something went wrong."),a("button",{class:"btn ghost",onclick:i},"Try again"))}emit(n,i){this.dispatchEvent(new CustomEvent(n,{detail:i,bubbles:!0,composed:!0}))}}const t=f=>f?new Date(f).toLocaleString():"";class s extends e{constructor(){super(...arguments),this.page=1}watch(n){return[n.on("ticket.created",()=>void this.load()),n.on("ticket.replied",()=>void this.load())]}async load(){const n=this.c;if(!n)return;const i=Math.min(100,Math.max(1,Number(this.getAttribute("limit"))||10));this.box.replaceChildren(a("p",{class:"muted"},"Loading..."));try{const u=await n.tickets.list({status:this.getAttribute("status")||void 0,page:this.page,limit:i});this.draw(u,i)}catch(u){this.fail(u,()=>void this.load())}}draw(n,i){const u=Math.max(1,Math.ceil(n.total/i)),T=n.items.map(b=>{var M;return a("div",{class:"card"},a("button",{class:"row",style:"background:none;border:0;padding:0",onclick:()=>this.emit("armdesk-ticket-select",{id:b.id,number:b.number})},a("span",{},a("strong",{},b.number)," ",b.subject,a("div",{class:"muted"},t((M=b.lastReplyAt)!=null?M:b.updatedAt))),a("span",{class:"badge"},b.status.replace(/_/g," "))))});this.box.replaceChildren(a("h3",{},"My tickets"),...T.length?T:[a("p",{class:"muted"},"No tickets yet.")],a("div",{class:"bar"},a("button",{class:"btn ghost",disabled:this.page<=1,onclick:()=>{this.page--,this.load()}},"Previous"),a("span",{class:"muted"},`${this.page} / ${u}`),a("button",{class:"btn ghost",disabled:this.page>=u,onclick:()=>{this.page++,this.load()}},"Next")))}}class l extends e{async load(){var p,w;const n=this.c;if(!n)return;let i=[],u=!0,T=!0;try{const y=await n.config();u=((p=y.features)==null?void 0:p.attachments)!==!1,T=((w=y.features)==null?void 0:w.newTicket)!==!1,i=await n.categories()}catch(y){}if(!T){this.box.replaceChildren(a("p",{class:"muted"},"Raising tickets is turned off."));return}const b=a("input",{name:"subject",required:!0,minlength:"5",maxlength:"255"}),M=a("textarea",{name:"description",required:!0,minlength:"10",maxlength:"20000",rows:"6"}),q=a("select",{name:"priority"},...["NORMAL","LOW","HIGH","URGENT"].map(y=>a("option",{value:y},y.charAt(0)+y.slice(1).toLowerCase()))),R=a("select",{name:"categoryId"},a("option",{value:""},"None"),...i.map(y=>a("option",{value:y.id},y.name))),A=a("input",{type:"file",multiple:!0}),D=a("p",{role:"status",class:"muted"}),j=a("button",{class:"btn",type:"submit"},"Submit ticket"),d=a("form",{onsubmit:y=>{var F;y.preventDefault(),j.disabled=!0,D.className="muted",D.textContent="Sending...",n.tickets.create({subject:b.value,description:M.value,priority:q.value,categoryId:R.value||void 0,files:Array.from((F=A.files)!=null?F:[])}).then(L=>{D.textContent=`Ticket ${L.number} created.`,d.reset(),this.emit("armdesk-ticket-created",L)}).catch(L=>{D.className="err",D.textContent=L instanceof Error?L.message:"Could not create the ticket."}).finally(()=>j.disabled=!1)}},a("label",{},"Subject",b),a("label",{},"Description",M),a("label",{},"Priority",q),i.length?a("label",{},"Category",R):null,u?a("label",{},"Attachments",A):null,j,D);this.box.replaceChildren(a("h3",{},"New ticket"),d)}}class c extends e{watch(n){return[n.on("ticket.replied",i=>i.ticketId===this.getAttribute("ticket-id")&&void this.load())]}async load(){const n=this.c,i=this.getAttribute("ticket-id");if(n){if(!i){this.box.replaceChildren(a("p",{class:"muted"},"Set the ticket-id attribute."));return}try{this.draw(n,await n.tickets.get(i))}catch(u){this.fail(u,()=>void this.load())}}}draw(n,i){const u=i.threads.map(A=>{var d;const D=a("div",{class:"body"});Ee(D,A.body);const j=((d=A.attachments)!=null?d:[]).filter(p=>p.url&&/^(https?:\/|\/)/.test(p.url)).map(p=>a("a",{href:p.url,target:"_blank",rel:"noopener noreferrer"},p.name));return a("div",{class:`card${A.author.isAgent?" agent":""}`},a("div",{class:"muted"},`${A.author.name} - ${t(A.createdAt)}`),D,...j.length?[a("div",{class:"muted"},"Files: ",...j.flatMap(p=>[p," "]))]:[])}),T=a("textarea",{rows:"4",required:!0,minlength:"1","aria-label":"Reply"}),b=a("p",{role:"status",class:"err"}),M=a("button",{class:"btn",type:"submit"},"Send reply"),q=a("form",{onsubmit:A=>{A.preventDefault(),M.disabled=!0,n.tickets.reply(i.id,{body:T.value}).then(()=>this.emit("armdesk-ticket-replied",{id:i.id}),D=>{b.textContent=D instanceof Error?D.message:"Could not send the reply.",M.disabled=!1})}},T,M,b),R=i.canClose?a("button",{class:"btn ghost",onclick:()=>void n.tickets.close(i.id).then(()=>this.load(),A=>this.fail(A,()=>void this.load()))},"Mark as solved"):null;this.box.replaceChildren(a("div",{class:"bar"},a("h3",{},`${i.number} ${i.subject}`),a("span",{class:"badge"},i.status.replace(/_/g," "))),...u,...[i.canReply?q:null,R].filter(A=>A!==null))}}class h extends e{constructor(){super(...arguments),this.handle=null,this.open=!1}teardown(){var n;(n=this.handle)==null||n.destroy(),this.handle=null}async load(){const n=this.getAttribute("position")==="left"?"left":"right",i=a("div",{class:`panel ${n}`,role:"dialog","aria-label":this.getAttribute("label")||"Support",hidden:!0}),u=a("button",{class:`btn fab ${n}`,"aria-expanded":"false",onclick:()=>{this.open=!this.open,i.hidden=!this.open,u.setAttribute("aria-expanded",String(this.open));const T=this.c;if(this.open&&!this.handle&&T){const b=this.getAttribute("view")||"tickets";this.handle=T.mount(i,{view:b,theme:Y(this.getAttribute("theme")),height:640})}}},this.getAttribute("label")||"Support");this.teardown(),this.box.replaceChildren(u,i)}}const S=[["armdesk-tickets",s],["armdesk-new-ticket",l],["armdesk-ticket",c],["armdesk-launcher",h]];for(const[f,n]of S)customElements.get(f)||customElements.define(f,n)}class $ extends Error{constructor(t,s,l=0,c){super(s),this.name="ArmDeskError",this.code=t,this.status=l,this.retryAfter=c}}function _e(e){return e===401?"unauthorized":e===403?"forbidden":e===404?"not_found":e===409?"conflict":e===429?"rate_limited":e>=500?"server":"validation"}function Ie(e,t,s){const l=t&&typeof t=="object"?t:{};if(typeof l.error=="string"){const h=typeof l.error_description=="string"?l.error_description:l.error;return new $(l.error,h,e,s)}const c=Array.isArray(l.message)?l.message.join("; "):typeof l.message=="string"?l.message:`ARM Desk answered ${e}`;return new $(_e(e),c,e,s)}const Q=3e4,ee=e=>new Promise(t=>setTimeout(t,e));function te(e){const t=e.headers.get("Retry-After");if(!t)return;const s=Number(t);if(Number.isFinite(s))return Math.max(0,s*1e3);const l=Date.parse(t);return Number.isNaN(l)?void 0:Math.max(0,l-Date.now())}async function H(e,t,s){const l=c=>c===429||(s.method==="GET"?c>=500:c===503);for(let c=0;;c++){const h=new AbortController,S=setTimeout(()=>h.abort(),e.timeoutMs);let f=null,n=null;try{f=await e.fetch(t,{method:s.method,headers:s.headers,body:s.body,credentials:s.credentials,signal:h.signal})}catch(u){n=u}finally{clearTimeout(S)}const i=c>=e.retries;if(f){if(f.ok||!l(f.status)||i)return f;const u=te(f);await ee(Math.min(Q,u!=null?u:e.retryDelayMs*2**c));continue}if(s.method!=="GET"||i)throw new $("network",n instanceof Error?`Could not reach ARM Desk: ${n.message}`:"Could not reach ARM Desk");await ee(Math.min(Q,e.retryDelayMs*2**c))}}async function K(e){let t=null;try{t=await e.json()}catch(s){}if(!e.ok){const s=te(e);throw Ie(e.status,t,s===void 0?void 0:Math.ceil(s/1e3))}if(t==null)throw new $("bad_response","ARM Desk returned an empty response",e.status);return t}const re="armdesk-connect",ne=/^(tickets|new|ticket:[A-Za-z0-9_-]{1,64})$/,je=["en","es","ar"],se=8192;function Ne(e){if(typeof e!="object"||e===null)return!1;const t=e;return t.source===re&&typeof t.type=="string"}function ae(e){let t;try{t=new URL(e)}catch(l){throw new Error("ArmDeskConnect: baseUrl must be an absolute URL")}const s=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";if(t.protocol!=="https:"&&!(t.protocol==="http:"&&s))throw new Error("ArmDeskConnect: baseUrl must be https (http is allowed for localhost only)");return t.origin}const Re="X-ArmDesk-Csrf",Le="/armdesk/session",qe="urn:ietf:params:oauth:grant-type:jwt-bearer",Fe=2e4,oe=4,Pe=400,Ue=120,He=2e4;function Ke(e){const t=typeof e=="string"?document.querySelector(e):e;if(!t)throw new Error("ArmDeskConnect: container not found");return t}const Ge=e=>new Promise(t=>setTimeout(t,e));function ie(e,t){var D,j;const s=Ke(e),l=ae(t.baseUrl);if(!t.orgKey)throw new Error("ArmDeskConnect: orgKey is required");if(typeof t.getToken!="function")throw new Error("ArmDeskConnect: getToken is required");if(t.view!==void 0&&!ne.test(t.view))throw new Error("ArmDeskConnect: invalid view");let c=(D=t.view)!=null?D:"tickets",h=U({},(j=t.theme)!=null?j:{}),S=!1,f=!1,n=null;const i=new URLSearchParams({org:t.orgKey,view:c});t.locale&&je.includes(t.locale)&&i.set("locale",t.locale);const u=document.createElement("iframe");u.src=`${l}/embed/itsm?${i.toString()}`,u.title="Support tickets",u.setAttribute("referrerpolicy","strict-origin"),u.setAttribute("loading","lazy"),u.setAttribute("data-armdesk-connect",""),Object.assign(u.style,{width:"100%",border:"0",display:"block",colorScheme:"normal"}),u.style.height=typeof t.height=="number"?`${t.height}px`:"480px";const T=(d,p)=>{const w=u.contentWindow;f||!w||w.postMessage({source:re,type:d,payload:p},l)},b=(d,p)=>{var w;try{(w=t.onError)==null||w.call(t,{code:d,message:p})}catch(y){}},M=()=>n||(n=(async()=>{for(let d=0;d<oe&&!f;d++)try{const p=await t.getToken();if(typeof p=="string"&&p.length>0&&p.length<=se)return p;throw new Error("getToken returned an invalid token")}catch(p){if(d===oe-1){b("token_failed",p instanceof Error?p.message:"Could not get a token");break}await Ge(Pe*2**d)}return null})().finally(()=>{n=null}),n),q=async d=>{var w;const p=await M();!p||f||T(d,d==="init"?{token:p,theme:h,features:(w=t.features)!=null?w:{}}:{token:p})};let R=setTimeout(()=>{S||b("timeout","The embed did not respond. Check baseUrl and the organisation's allowed origins.")},Fe);const A=d=>{var F;if(f||d.origin!==l||d.source!==u.contentWindow||!Ne(d.data))return;const{type:p,payload:w}=d.data,y=typeof w=="object"&&w!==null?w:{};switch(p){case"ready":S=!0,R&&clearTimeout(R),R=null,q("init");break;case"request-token":q("token");break;case"resize":{const L=Number(y.height);(t.height===void 0||t.height==="auto")&&Number.isFinite(L)&&(u.style.height=`${Math.min(He,Math.max(Ue,Math.ceil(L)))}px`);break}case"event":if(typeof y.name=="string")try{(F=t.onEvent)==null||F.call(t,{name:y.name,data:y.data})}catch(L){}break;case"error":b(typeof y.code=="string"?y.code:"error",typeof y.message=="string"?y.message:"Embed error");break}};return window.addEventListener("message",A),s.appendChild(u),{navigate(d){if(!ne.test(d))throw new Error("ArmDeskConnect: invalid view");c=d,S&&T("navigate",{view:c})},setTheme(d){h=U({},d),S&&T("theme",{theme:h})},refreshToken:()=>q("token"),destroy(){f||(f=!0,R&&clearTimeout(R),window.removeEventListener("message",A),u.remove())}}}const ze=3e4,G=840,z="/connect/v1";function ce(e){var F,L,le,de,ue,he;if(!e||!e.orgKey)throw new $("config","ArmDeskConnect: orgKey is required");if(!e.auth||typeof e.auth!="object")throw new $("config","ArmDeskConnect: auth is required");const t=(F=e.desk)!=null?F:ge();if(!t)throw new $("config","ArmDeskConnect: desk is required (it is detected only when the script tag is used)");const s=ae(t),l=(le=e.fetch)!=null?le:(L=globalThis.fetch)==null?void 0:L.bind(globalThis);if(typeof l!="function")throw new $("config","fetch is not available");const c={fetch:l,retries:(de=e.retries)!=null?de:2,retryDelayMs:(ue=e.retryDelayMs)!=null?ue:400,timeoutMs:(he=e.timeoutMs)!=null?he:2e4},h=e.auth,S=new Map,f=(r,o)=>{var m;(m=S.get(r))==null||m.forEach(g=>{try{g(o)}catch(O){}})};let n=null;const i=`${s}/api/proxy`,u=r=>r.replace(/\/+$/,"").replace(/\/connect\/v1$/,""),T=()=>e.apiBase?Promise.resolve(u(e.apiBase)):(n!=null||(n=(async()=>{try{const r=await H(pe(U({},c),{retries:0}),`${i}${z}/bootstrap?org=${encodeURIComponent(e.orgKey)}`,{method:"GET",headers:{Accept:"application/json"}}),o=await K(r);if(typeof o.apiBase=="string"&&o.apiBase)return u(new URL(o.apiBase,s).toString())}catch(r){}return i})()),n);let b=null,M=null;const q=r=>{if(typeof r.token!="string"||!r.token||r.token.length>se)throw new $("bad_response","ARM Desk returned an invalid token");return b={token:r.token,expiresAt:Date.now()+(Number.isFinite(r.expiresIn)?r.expiresIn:G)*1e3},r.token},R=async()=>{var g,O,v,k;const r=await T();if("userToken"in h){const E=await h.userToken();if(typeof E!="string"||!E)throw new $("config","userToken() must return the signed user token");const N=new URLSearchParams({grant_type:qe,assertion:E}),x=await H(c,`${r}${z}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:N.toString()}),P=await K(x);if(typeof P.access_token!="string")throw new $("bad_response","ARM Desk returned no access_token",x.status);return{token:P.access_token,expiresIn:(g=P.expires_in)!=null?g:G}}if("idToken"in h){const E=await h.idToken(),N={orgKey:e.orgKey,idToken:E};h.nonce&&(N.nonce=h.nonce);const x=await H(c,`${r}${z}/sessions/browser`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(N)}),P=await K(x);return{token:P.token,expiresIn:(O=P.expiresIn)!=null?O:G}}if("getToken"in h)return{token:await h.getToken(),expiresIn:G};const o=await H(c,(v=h.sessionUrl)!=null?v:Le,{method:"POST",headers:{[Re]:"1",Accept:"application/json"},credentials:"same-origin"}),m=await K(o);return{token:m.token,expiresIn:(k=m.expiresIn)!=null?k:G}},A=async()=>{var r;if(!("idToken"in h)||!b)return null;try{const o=await T(),m=await H(c,`${o}${z}/sessions/refresh`,{method:"POST",headers:{Authorization:`Bearer ${b.token}`,Accept:"application/json"}}),g=await K(m);return{token:g.token,expiresIn:(r=g.expiresIn)!=null?r:G}}catch(o){return null}},D=()=>(M!=null||(M=(async()=>{var r;try{const o=(r=await A())!=null?r:await R();return q(o)}catch(o){const m=b!==null;b=null;const g=o instanceof $?o:new $("session_expired",o instanceof Error?o.message:"Could not sign in");throw m&&f("session.expired",{code:g.code,message:g.message,status:g.status}),f("error",{code:g.code,message:g.message,status:g.status}),g}finally{M=null}})()),M),j=async()=>b&&b.expiresAt-ze>Date.now()?b.token:D(),d=async(r,o=!1)=>{const m=await j(),g=await T(),O=r.query?Object.entries(r.query).filter(([,x])=>x!==void 0&&x!==""):[],v=`${g}${z}${r.path}${O.length?`?${new URLSearchParams(O.map(([x,P])=>[x,String(P)])).toString()}`:""}`,k={Authorization:`Bearer ${m}`,Accept:"application/json"};let E;r.form?E=r.form:r.json!==void 0&&(k["Content-Type"]="application/json",E=JSON.stringify(r.json));const N=await H(c,v,{method:r.method,headers:k,body:E});if(N.status===401&&!o)return b=null,d(r,!0);try{return await K(N)}catch(x){throw x instanceof $&&!(o&&x.status===401)&&f("error",{code:x.code,message:x.message,status:x.status}),x instanceof $&&x.status===401&&f("session.expired",{code:x.code,message:x.message,status:401}),x}},p=(r,o,m="files")=>{var v;const g=Object.fromEntries(Object.entries(r).filter(([,k])=>k!==void 0&&k!==""));if(!o||o.length===0)return{json:g};const O=new FormData;for(const[k,E]of Object.entries(g))O.append(k,E);for(const k of o)O.append(m,k,(v=k.name)!=null?v:"file");return{form:O}},w=r=>{if(!r||typeof r!="string")throw new $("validation","An id is required");return encodeURIComponent(r)};return{orgKey:e.orgKey,desk:s,me:()=>d({method:"GET",path:"/me"}),config:()=>d({method:"GET",path:"/config",query:{locale:e.locale}}),categories:async()=>{var o;const r=await d({method:"GET",path:"/categories"});return Array.isArray(r)?r:(o=r.items)!=null?o:[]},tickets:{list:(r={})=>d({method:"GET",path:"/tickets",query:{status:Array.isArray(r.status)?r.status.join(","):r.status,search:r.search,page:r.page,limit:r.limit}}),get:async r=>d({method:"GET",path:`/tickets/${w(r)}`}),async create(r){const o=await d(U({method:"POST",path:"/tickets"},p({subject:r.subject,description:r.description,priority:r.priority,categoryId:r.categoryId},r.files)));return f("ticket.created",o),o},async reply(r,o){const m=await d(U({method:"POST",path:`/tickets/${w(r)}/replies`},p({body:o.body},o.files)));return f("ticket.replied",{ticketId:r,reply:m}),m},close:async r=>d({method:"POST",path:`/tickets/${w(r)}/close`})},catalog:{list:(r={})=>d({method:"GET",path:"/catalog",query:{search:r.search,categoryId:r.categoryId}}),async request(r,o={},m={}){var k;const g={answers:JSON.stringify(o),quantity:m.quantity===void 0?void 0:String(m.quantity),requestedForId:m.requestedForId},O=m.files?Object.entries(m.files):[];if(O.length===0){const E={answers:o};return m.quantity!==void 0&&(E.quantity=m.quantity),m.requestedForId&&(E.requestedForId=m.requestedForId),d({method:"POST",path:`/catalog/${w(r)}/requests`,json:E})}const v=new FormData;for(const[E,N]of Object.entries(g))N!==void 0&&v.append(E,N);for(const[E,N]of O)v.append(`file:${E}`,N,(k=N.name)!=null?k:"file");return d({method:"POST",path:`/catalog/${w(r)}/requests`,form:v})}},on(r,o){let m=S.get(r);return m||S.set(r,m=new Set),m.add(o),()=>m.delete(o)},mount(r,o={}){var m,g,O;return ie(r,{baseUrl:s,orgKey:e.orgKey,getToken:j,view:o.view,theme:(m=o.theme)!=null?m:e.theme,features:(g=o.features)!=null?g:e.features,locale:(O=o.locale)!=null?O:e.locale,height:o.height,onEvent:v=>{var k;v.name==="ticket.created"&&f("ticket.created",v.data),v.name==="ticket.replied"&&f("ticket.replied",v.data),(k=o.onEvent)==null||k.call(o,v)},onError:v=>{var k;f("error",v),(k=o.onError)==null||k.call(o,v)}})},getAccessToken:j,signOut(){b=null,M=null}}}function Be(e){const t=ce(e);return ye(t),t}const We="1.0.0";if(typeof document!="undefined"){const e=document.currentScript;if(e&&e.src)try{be(new URL(e.src).origin)}catch(t){}Z()}return C.ArmDeskError=$,C.createClient=ce,C.defineElements=Z,C.init=Be,C.mount=ie,C.version=We,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"}),C}({});
@@ -0,0 +1,3 @@
1
+ import { defineElements } from "./elements.js";
2
+ export { init, createClient, mount, ArmDeskError, VERSION as version } from "./index.js";
3
+ export { defineElements };
@@ -0,0 +1,18 @@
1
+ // Entry of the script-tag build: window.ArmDeskConnect = { init, createClient, mount, version, ... }.
2
+ // The desk URL defaults to the origin this script was loaded from, and the web components register themselves.
3
+ import { setDefaultDesk } from "./defaults.js";
4
+ import { defineElements } from "./elements.js";
5
+ if (typeof document !== "undefined") {
6
+ const script = document.currentScript;
7
+ if (script && script.src) {
8
+ try {
9
+ setDefaultDesk(new URL(script.src).origin);
10
+ }
11
+ catch (_a) {
12
+ // keep the explicit `desk` option as the only way
13
+ }
14
+ }
15
+ defineElements();
16
+ }
17
+ export { init, createClient, mount, ArmDeskError, VERSION as version } from "./index.js";
18
+ export { defineElements };
@@ -0,0 +1,44 @@
1
+ import type { Category, ClientEventMap, ClientMountOptions, ClientOptions, ConnectHandle, CatalogRequestOptions, CreatedTicket, CreateTicketInput, DeskConfig, ListTicketsParams, Me, Reply, ReplyInput, TicketDetail, TicketList, Unsubscribe } from "./types.js";
2
+ type Listener<K extends keyof ClientEventMap> = (payload: ClientEventMap[K]) => void;
3
+ export interface ArmDeskClient {
4
+ readonly orgKey: string;
5
+ /** The desk's origin. */
6
+ readonly desk: string;
7
+ me(): Promise<Me>;
8
+ config(): Promise<DeskConfig>;
9
+ categories(): Promise<Category[]>;
10
+ tickets: {
11
+ list(params?: ListTicketsParams): Promise<TicketList>;
12
+ get(id: string): Promise<TicketDetail>;
13
+ create(input: CreateTicketInput): Promise<CreatedTicket>;
14
+ reply(id: string, input: ReplyInput): Promise<Reply>;
15
+ close(id: string): Promise<{
16
+ id: string;
17
+ number: string;
18
+ status: string;
19
+ }>;
20
+ };
21
+ catalog: {
22
+ list(params?: {
23
+ search?: string;
24
+ categoryId?: string;
25
+ }): Promise<unknown>;
26
+ request(itemId: string, answers?: Record<string, unknown>, options?: CatalogRequestOptions): Promise<unknown>;
27
+ };
28
+ on<K extends keyof ClientEventMap>(event: K, cb: Listener<K>): Unsubscribe;
29
+ /** Mounts the iframe embed (the full ARM Desk portal UI) into an element. */
30
+ mount(el: HTMLElement | string, options?: ClientMountOptions): ConnectHandle;
31
+ /** A valid ARM Desk connect token (cached in memory, renewed shortly before it expires). */
32
+ getAccessToken(): Promise<string>;
33
+ /** Forget the token and stop; the next call signs in again. */
34
+ signOut(): void;
35
+ }
36
+ /**
37
+ * The headless client: typed, Promise-based, no endpoint strings for the caller. It signs in with the `auth` option,
38
+ * keeps the connect token in memory only, renews it before it expires, retries 429 / 5xx with backoff and throws
39
+ * `ArmDeskError` for everything else.
40
+ */
41
+ export declare function createClient(options: ClientOptions): ArmDeskClient;
42
+ /** `ArmDeskConnect.init(...)`: createClient, and make it the client the web components use. */
43
+ export declare function init(options: ClientOptions): ArmDeskClient;
44
+ export {};