@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
@@ -0,0 +1,298 @@
1
+ /** The embed's colours, shape and header. Every key is optional; the desk validates again. */
2
+ export interface ConnectTheme {
3
+ primaryColor?: string;
4
+ backgroundColor?: string;
5
+ surfaceColor?: string;
6
+ textColor?: string;
7
+ mutedColor?: string;
8
+ borderColor?: string;
9
+ fontFamily?: "system" | "inter" | "roboto" | "open-sans" | "lato";
10
+ /** 0-24 px. */
11
+ radius?: number;
12
+ density?: "comfortable" | "compact";
13
+ /** https URL of a logo shown in the header. */
14
+ logoUrl?: string;
15
+ showHeader?: boolean;
16
+ headerTitle?: string;
17
+ mode?: "light" | "dark" | "auto";
18
+ }
19
+ /** Features can only be narrowed: a feature the organisation has switched off stays off. */
20
+ export interface ConnectFeatures {
21
+ newTicket?: boolean;
22
+ attachments?: boolean;
23
+ catalog?: boolean;
24
+ orgTickets?: boolean;
25
+ replies?: boolean;
26
+ closeTicket?: boolean;
27
+ }
28
+ export type ConnectLocale = "en" | "es" | "ar";
29
+ /** `tickets` (the list), `new` (the form) or `ticket:<id>` (one ticket). */
30
+ export type ConnectView = "tickets" | "new" | `ticket:${string}`;
31
+ export interface ConnectEvent {
32
+ name: "ticket.created" | "ticket.replied" | "navigate" | (string & {});
33
+ data?: unknown;
34
+ }
35
+ export interface ConnectError {
36
+ code: string;
37
+ message: string;
38
+ }
39
+ export interface MountOptions {
40
+ /** The desk, e.g. https://desk.example.com (https; http only for localhost). */
41
+ baseUrl: string;
42
+ /** The organisation's public key (org_...). */
43
+ orgKey: string;
44
+ /** Ask YOUR backend for a connect token (it calls createConnectSession). Called on load and when the token expires. */
45
+ getToken: () => Promise<string>;
46
+ view?: ConnectView;
47
+ theme?: ConnectTheme;
48
+ features?: ConnectFeatures;
49
+ locale?: ConnectLocale;
50
+ /** "auto" (default) follows the embed's content; a number is a fixed height in px. */
51
+ height?: "auto" | number;
52
+ onEvent?: (event: ConnectEvent) => void;
53
+ onError?: (error: ConnectError) => void;
54
+ }
55
+ export interface ConnectHandle {
56
+ navigate(view: ConnectView): void;
57
+ setTheme(theme: ConnectTheme): void;
58
+ /** Fetch a fresh token through getToken and hand it to the embed. */
59
+ refreshToken(): Promise<void>;
60
+ destroy(): void;
61
+ }
62
+ export interface ConnectUser {
63
+ /** The user's id in your system (WSO2 `sub`). Required unless idToken is used. */
64
+ uid: string;
65
+ email?: string;
66
+ name?: string;
67
+ firstName?: string;
68
+ lastName?: string;
69
+ phone?: string;
70
+ /** Your role name; the organisation's role mappings turn it into a CRM contact role. */
71
+ role?: string;
72
+ department?: string;
73
+ attributes?: Record<string, unknown>;
74
+ /**
75
+ * Whether `email` is verified by your sign-in (default true: your backend vouches for it).
76
+ * false = ARM Desk never links an existing account by this address.
77
+ */
78
+ emailVerified?: boolean;
79
+ }
80
+ export interface CreateConnectSessionOptions {
81
+ /** The desk, e.g. https://desk.example.com (its host also selects the tenant). */
82
+ baseUrl: string;
83
+ /** The API's own base (e.g. http://api:3000/api). Default: `<baseUrl>/api/proxy`. */
84
+ apiUrl?: string;
85
+ /** Name the tenant when you do not call the tenant's own host (sent as X-Tenant-Slug). */
86
+ tenantSlug?: string;
87
+ orgKey: string;
88
+ orgSecret: string;
89
+ user?: ConnectUser;
90
+ /** An OIDC ID token (WSO2 ...), verified by ARM Desk against the organisation's trusted issuers. */
91
+ idToken?: string;
92
+ /** Switch features OFF for this session (e.g. { closeTicket: false }). Can only narrow what the organisation allows. */
93
+ features?: ConnectFeatures;
94
+ /** Abort after this many ms (default 10000). */
95
+ timeoutMs?: number;
96
+ /** A fetch implementation (default: the global one, Node 18+). */
97
+ fetch?: typeof fetch;
98
+ }
99
+ export interface ConnectSession {
100
+ token: string;
101
+ /** Seconds until the token expires. */
102
+ expiresIn: number;
103
+ user: {
104
+ id: string;
105
+ email?: string;
106
+ name?: string;
107
+ emailVerified?: boolean;
108
+ };
109
+ contactId: string | null;
110
+ }
111
+ export type TicketStatus = "NEW" | "OPEN" | "IN_PROGRESS" | "PENDING" | "PENDING_APPROVAL" | "PENDING_PROCUREMENT" | "ON_HOLD" | "RESOLVED" | "CLOSED" | "CANCELED";
112
+ export type TicketPriority = "LOW" | "NORMAL" | "HIGH" | "URGENT";
113
+ export interface TicketSummary {
114
+ id: string;
115
+ number: string;
116
+ subject: string;
117
+ status: TicketStatus | (string & {});
118
+ priority: TicketPriority | (string & {});
119
+ createdAt: string;
120
+ updatedAt: string;
121
+ lastReplyAt: string | null;
122
+ }
123
+ export interface Attachment {
124
+ id: string;
125
+ name: string;
126
+ mimeType?: string;
127
+ size?: number;
128
+ /** A signed 15-minute download link. */
129
+ url?: string;
130
+ }
131
+ export interface Thread {
132
+ id: string;
133
+ author: {
134
+ name: string;
135
+ isAgent: boolean;
136
+ };
137
+ /** Sanitised HTML. */
138
+ body: string;
139
+ createdAt: string;
140
+ attachments?: Attachment[];
141
+ }
142
+ export interface TicketDetail extends TicketSummary {
143
+ category: {
144
+ id: string;
145
+ name: string;
146
+ } | null;
147
+ requester: {
148
+ name: string;
149
+ isMe: boolean;
150
+ };
151
+ canReply: boolean;
152
+ canClose: boolean;
153
+ threads: Thread[];
154
+ }
155
+ export interface TicketList {
156
+ items: TicketSummary[];
157
+ total: number;
158
+ }
159
+ export interface ListTicketsParams {
160
+ /** One status or several (sent as CSV). */
161
+ status?: string | string[];
162
+ search?: string;
163
+ page?: number;
164
+ /** Up to 100. */
165
+ limit?: number;
166
+ }
167
+ export interface CreateTicketInput {
168
+ /** 5 to 255 characters. */
169
+ subject: string;
170
+ /** 10 to 20000 characters of PLAIN TEXT. */
171
+ description: string;
172
+ priority?: TicketPriority;
173
+ categoryId?: string;
174
+ files?: Array<File | Blob>;
175
+ }
176
+ export interface CreatedTicket {
177
+ id: string;
178
+ number: string;
179
+ subject: string;
180
+ status: string;
181
+ createdAt: string;
182
+ attachments: Array<{
183
+ id: string;
184
+ name: string;
185
+ }>;
186
+ }
187
+ export interface ReplyInput {
188
+ /** Plain text. */
189
+ body: string;
190
+ files?: Array<File | Blob>;
191
+ }
192
+ export interface Reply {
193
+ id: string;
194
+ author: string;
195
+ body: string;
196
+ createdAt: string;
197
+ attachments: Array<{
198
+ id: string;
199
+ name: string;
200
+ }>;
201
+ }
202
+ export interface Me {
203
+ id: string;
204
+ email: string;
205
+ name: string;
206
+ firstName: string | null;
207
+ lastName: string | null;
208
+ phone: string | null;
209
+ uid: string | null;
210
+ role: string | null;
211
+ contactId: string | null;
212
+ organization: {
213
+ id: string;
214
+ name: string;
215
+ };
216
+ }
217
+ export interface Category {
218
+ id: string;
219
+ name: string;
220
+ parentId: string | null;
221
+ }
222
+ export interface DeskConfig {
223
+ organization: {
224
+ name: string;
225
+ };
226
+ theme?: ConnectTheme;
227
+ features?: ConnectFeatures;
228
+ locale?: string;
229
+ }
230
+ export interface CatalogRequestOptions {
231
+ quantity?: number;
232
+ requestedForId?: string;
233
+ /** Files by catalog variable name. */
234
+ files?: Record<string, File | Blob>;
235
+ }
236
+ export interface Unsubscribe {
237
+ (): void;
238
+ }
239
+ export type ClientEventMap = {
240
+ "ticket.created": CreatedTicket;
241
+ "ticket.replied": {
242
+ ticketId: string;
243
+ reply: Reply;
244
+ };
245
+ "session.expired": ArmDeskErrorLike;
246
+ error: ArmDeskErrorLike;
247
+ };
248
+ export type ArmDeskErrorLike = {
249
+ code: string;
250
+ message: string;
251
+ status?: number;
252
+ };
253
+ /**
254
+ * How the browser signs in. ONE of:
255
+ * - `userToken`: PRIMARY. A short-lived signed user token minted by YOUR server with signUserToken() (no network call
256
+ * on your side, no endpoint of yours). The library exchanges it for an ARM Desk token (OAuth 2.0 JWT bearer grant).
257
+ * - `idToken`: browser OIDC (WSO2 ...). The organisation must allow browser sessions.
258
+ * - `sessionUrl`: a route on YOUR server mounted with createConnectHandler (default `/armdesk/session`).
259
+ * - `getToken`: you obtain the ARM Desk connect token yourself (legacy; `mount` compatible).
260
+ */
261
+ export type AuthOption = {
262
+ userToken: () => string | Promise<string>;
263
+ } | {
264
+ idToken: () => string | Promise<string>;
265
+ nonce?: string;
266
+ } | {
267
+ sessionUrl?: string;
268
+ } | {
269
+ getToken: () => string | Promise<string>;
270
+ };
271
+ export interface ClientOptions {
272
+ /** The organisation's public key (org_...). */
273
+ orgKey: string;
274
+ /** The desk, e.g. https://desk.example.com. Default: the origin the script tag was loaded from. */
275
+ desk?: string;
276
+ /** Override the API base (default: announced by the desk's bootstrap, else `<desk>/api/proxy`). */
277
+ apiBase?: string;
278
+ auth: AuthOption;
279
+ locale?: ConnectLocale;
280
+ theme?: ConnectTheme;
281
+ features?: ConnectFeatures;
282
+ /** Retries on 429 / 5xx (default 2). */
283
+ retries?: number;
284
+ /** First backoff delay in ms (default 400; doubles each retry). */
285
+ retryDelayMs?: number;
286
+ /** Per-request timeout in ms (default 20000). */
287
+ timeoutMs?: number;
288
+ fetch?: typeof fetch;
289
+ }
290
+ export interface ClientMountOptions {
291
+ view?: ConnectView;
292
+ theme?: ConnectTheme;
293
+ features?: ConnectFeatures;
294
+ locale?: ConnectLocale;
295
+ height?: "auto" | number;
296
+ onEvent?: (event: ConnectEvent) => void;
297
+ onError?: (error: ConnectError) => void;
298
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "armdesk-connect-example-express",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": { "start": "node server.mjs" },
6
+ "dependencies": {
7
+ "@armdesk/connect-sdk": "file:../..",
8
+ "express": "^4.19.2"
9
+ }
10
+ }
@@ -0,0 +1,35 @@
1
+ // Server mode with Express. Run:
2
+ // cd examples/express-server && npm install && DESK_URL=http://localhost:3001 ORG_KEY=org_... ORG_SECRET=cos_... npm start
3
+ // then open http://localhost:4000 (add that origin to the organisation's allowed origins first).
4
+ import express from "express";
5
+ import { createConnectHandler, signUserToken } from "@armdesk/connect-sdk/server";
6
+
7
+ const { DESK_URL = "http://localhost:3001", ORG_KEY, ORG_SECRET, PORT = "4000" } = process.env;
8
+ if (!ORG_KEY || !ORG_SECRET) {
9
+ console.error("Set ORG_KEY and ORG_SECRET (shown once when the organisation is registered).");
10
+ process.exit(1);
11
+ }
12
+
13
+ // Your own sign-in would set req.user. This demo signs everybody in as one fixed user.
14
+ const DEMO_USER = { id: "demo-user-1", email: "demo.user@example.com", name: "Demo User", role: "manager", department: "Finance" };
15
+ const app = express();
16
+ app.use((req, _res, next) => ((req.user = DEMO_USER), next()));
17
+
18
+ // Mode A (server mode): the route the browser library calls by default.
19
+ const armdesk = createConnectHandler({ orgKey: ORG_KEY, orgSecret: ORG_SECRET, desk: DESK_URL, getUser: (req) => req.user });
20
+ app.post("/armdesk/session", armdesk.express());
21
+
22
+ // Mode B (signed user token): render a token into the page, no route needed.
23
+ app.get("/", (req, res) => {
24
+ const userToken = signUserToken({ orgKey: ORG_KEY, orgSecret: ORG_SECRET, user: req.user });
25
+ res.type("html").send(`<!doctype html><meta charset="utf-8"><title>Express host</title>
26
+ <h1>Express host product</h1><div id="support"></div>
27
+ <script src="${DESK_URL}/connect/armdesk-connect.js"></script>
28
+ <script>
29
+ const client = ArmDeskConnect.init({ orgKey: ${JSON.stringify(ORG_KEY)}, auth: { userToken: () => ${JSON.stringify(userToken)} } });
30
+ client.mount("#support");
31
+ // server mode instead: ArmDeskConnect.init({ orgKey: ..., auth: {} }).mount("#support");
32
+ </script>`);
33
+ });
34
+
35
+ app.listen(Number(PORT), () => console.log(`Express host on http://localhost:${PORT} (desk: ${DESK_URL})`));
@@ -0,0 +1,30 @@
1
+ // A local stand-in for WSO2, for trying browser mode against a real ARM Desk. Not for production.
2
+ // node examples/mock-idp.mjs
3
+ // Serves JWKS at /.well-known/jwks.json, discovery at /.well-known/openid-configuration and mints an RS256 ID token
4
+ // at POST /issue (CORS open). In ARM Desk (Admin > Connect > Identity) trust issuer http://localhost:4010, audience
5
+ // "demo-product", jwksUri http://localhost:4010/.well-known/jwks.json (plain http is a local-testing exception only).
6
+ import { createServer } from "node:http";
7
+ import { createSign, generateKeyPairSync } from "node:crypto";
8
+
9
+ const PORT = Number(process.env.PORT ?? 4010);
10
+ const ISSUER = `http://localhost:${PORT}`;
11
+ const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
12
+ const jwk = { ...publicKey.export({ format: "jwk" }), kid: "mock-1", use: "sig", alg: "RS256" };
13
+ const b64u = (v) => Buffer.from(typeof v === "string" ? v : JSON.stringify(v)).toString("base64url");
14
+
15
+ function issue() {
16
+ const now = Math.floor(Date.now() / 1000);
17
+ const input = `${b64u({ alg: "RS256", typ: "JWT", kid: "mock-1" })}.${b64u({ iss: ISSUER, aud: "demo-product", sub: "demo-user-1", email: "ana@example.com", email_verified: true, given_name: "Ana", family_name: "Silva", roles: "manager", iat: now, exp: now + 300 })}`;
18
+ return `${input}.${createSign("RSA-SHA256").update(input).sign(privateKey).toString("base64url")}`;
19
+ }
20
+
21
+ createServer((req, res) => {
22
+ res.setHeader("Access-Control-Allow-Origin", "*");
23
+ res.setHeader("Access-Control-Allow-Headers", "*");
24
+ if (req.method === "OPTIONS") return res.writeHead(204).end();
25
+ const json = (b) => res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify(b));
26
+ if (req.url === "/.well-known/jwks.json") return json({ keys: [jwk] });
27
+ if (req.url === "/.well-known/openid-configuration") return json({ issuer: ISSUER, jwks_uri: `${ISSUER}/.well-known/jwks.json` });
28
+ if (req.url === "/issue" && req.method === "POST") return json({ idToken: issue() });
29
+ res.writeHead(404).end();
30
+ }).listen(PORT, () => console.log(`Mock IdP on ${ISSUER}`));
@@ -0,0 +1,11 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <title>ARM Desk Connect - React + Vite</title>
6
+ </head>
7
+ <body>
8
+ <div id="root"></div>
9
+ <script type="module" src="/src/main.jsx"></script>
10
+ </body>
11
+ </html>
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "armdesk-connect-example-react-vite",
3
+ "private": true,
4
+ "type": "module",
5
+ "scripts": { "dev": "vite", "build": "vite build" },
6
+ "dependencies": {
7
+ "@armdesk/connect-sdk": "file:../..",
8
+ "react": "^18.3.1",
9
+ "react-dom": "^18.3.1"
10
+ },
11
+ "devDependencies": {
12
+ "@vitejs/plugin-react": "^4.3.1",
13
+ "vite": "^5.4.0"
14
+ }
15
+ }
@@ -0,0 +1,25 @@
1
+ // React + WSO2 (OIDC) in the browser: no backend of your own. Run:
2
+ // cd examples/react-vite && npm install && VITE_DESK_URL=http://localhost:3001 VITE_ORG_KEY=org_... npm run dev
3
+ // Replace getIdToken with your real OIDC client (oidc-client-ts, WSO2 SDK ...). Add http://localhost:5173 to the
4
+ // organisation's allowed origins, switch on Browser sessions and trust your issuer.
5
+ import React, { useState } from "react";
6
+ import { createRoot } from "react-dom/client";
7
+ import { ArmDeskEmbed, ArmDeskNewTicket, ArmDeskProvider, ArmDeskTicket, ArmDeskTickets } from "@dhrp-ticket/connect-sdk/react";
8
+
9
+ const getIdToken = async () => window.sessionStorage.getItem("id_token"); // your OIDC client's ID token
10
+
11
+ function App() {
12
+ const [open, setOpen] = useState(null);
13
+ return (
14
+ <ArmDeskProvider orgKey={import.meta.env.VITE_ORG_KEY} desk={import.meta.env.VITE_DESK_URL} auth={{ idToken: getIdToken }}>
15
+ <h1>Acme product</h1>
16
+ <h2>Your own layout with the headless components</h2>
17
+ {open ? <><button onClick={() => setOpen(null)}>Back</button><ArmDeskTicket ticketId={open} /></> : <ArmDeskTickets onSelect={setOpen} />}
18
+ <ArmDeskNewTicket />
19
+ <h2>Or the complete portal</h2>
20
+ <ArmDeskEmbed view="tickets" theme={{ primaryColor: "#0f766e" }} />
21
+ </ArmDeskProvider>
22
+ );
23
+ }
24
+
25
+ createRoot(document.getElementById("root")).render(<App />);
@@ -0,0 +1,4 @@
1
+ import react from "@vitejs/plugin-react";
2
+ import { defineConfig } from "vite";
3
+
4
+ export default defineConfig({ plugins: [react()], server: { port: 5173 } });
@@ -0,0 +1,86 @@
1
+ <!doctype html>
2
+ <!--
3
+ ARM Desk Connect, browser mode (WSO2 / OIDC), no backend of your own.
4
+
5
+ Two ways to run it (open the file in a browser, or serve this folder):
6
+
7
+ 1. Standalone demo (default): a mock IdP signs an RS256 ID token in this page (WebCrypto) and a mock desk
8
+ (a fetch stub) verifies nothing but answers like ARM Desk, so you can see the flow and the library calls offline.
9
+
10
+ 2. Against a real ARM Desk: wso2-browser.html?desk=https://desk.example.com&org=org_xxx
11
+ Needs the organisation to allow Browser sessions and to trust an issuer. For a local desk run
12
+ node examples/mock-idp.mjs (serves /.well-known/jwks.json and /issuer on http://localhost:4010)
13
+ trust issuer http://localhost:4010 with audience "demo-product" in Admin > Connect > Identity, add this page's
14
+ origin to the allowed origins, and add &idp=http://localhost:4010 to the URL.
15
+ -->
16
+ <html lang="en">
17
+ <head>
18
+ <meta charset="utf-8" />
19
+ <title>ARM Desk Connect - WSO2 browser mode</title>
20
+ <style>
21
+ body { font-family: system-ui, sans-serif; max-width: 760px; margin: 2rem auto; padding: 0 1rem; }
22
+ pre { background: #f3f4f6; padding: .75rem; overflow: auto; font-size: 12px; }
23
+ code { background: #f3f4f6; }
24
+ </style>
25
+ </head>
26
+ <body>
27
+ <h1>Acme product (signed in with WSO2)</h1>
28
+ <p id="mode"></p>
29
+ <armdesk-tickets limit="5"></armdesk-tickets>
30
+ <h2>Log</h2>
31
+ <pre id="log"></pre>
32
+
33
+ <script>
34
+ const q = new URLSearchParams(location.search);
35
+ const log = (m) => { document.getElementById("log").textContent += m + "\n"; };
36
+ const b64u = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
37
+ const enc = (o) => b64u(new TextEncoder().encode(JSON.stringify(o)));
38
+
39
+ // ---- the mock IdP (stand-in for WSO2): signs ID tokens with RS256 ----
40
+ let keyPair;
41
+ async function mockIdToken() {
42
+ keyPair ??= await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign"]);
43
+ const now = Math.floor(Date.now() / 1000);
44
+ const input = enc({ alg: "RS256", typ: "JWT", kid: "mock-1" }) + "." + enc({
45
+ iss: q.get("idp") || "https://mock-idp.local", aud: "demo-product", sub: "demo-user-1", email: "ana@example.com", email_verified: true,
46
+ given_name: "Ana", family_name: "Silva", roles: "manager", iat: now, exp: now + 300,
47
+ });
48
+ const sig = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", keyPair.privateKey, new TextEncoder().encode(input));
49
+ return input + "." + b64u(sig);
50
+ }
51
+ async function idToken() {
52
+ if (q.get("idp")) return (await (await fetch(q.get("idp") + "/issue", { method: "POST" })).json()).idToken; // mock-idp.mjs
53
+ return mockIdToken();
54
+ }
55
+
56
+ // ---- standalone: a stub desk so the page works offline ----
57
+ const standalone = !q.get("desk");
58
+ const stubDesk = async (url, init = {}) => {
59
+ const path = new URL(url, location.href).pathname;
60
+ const reply = (b, s = 200) => new Response(JSON.stringify(b), { status: s, headers: { "Content-Type": "application/json" } });
61
+ log(`desk <- ${init.method || "GET"} ${path}`);
62
+ if (path.endsWith("/sessions/browser")) return reply({ token: "demo-connect-token", expiresIn: 900, user: { id: "u1" } });
63
+ if (path.endsWith("/config")) return reply({ organization: { name: "Acme" }, theme: { primaryColor: "#0f766e" }, features: {} });
64
+ if (path.endsWith("/tickets")) return reply({ items: [{ id: "t1", number: "TKT-1042", subject: "VPN drops every hour", status: "OPEN", priority: "HIGH", createdAt: "", updatedAt: new Date().toISOString(), lastReplyAt: null }], total: 1 });
65
+ return reply({ message: "not in the demo" }, 404);
66
+ };
67
+
68
+ document.getElementById("mode").textContent = standalone ? "Standalone demo: mock IdP + stub desk." : "Real desk: " + q.get("desk");
69
+ </script>
70
+ <!-- In your product: <script src="https://<your-desk>/connect/armdesk-connect.js"></script>
71
+ For this example the built script is expected next to the package: ../dist/armdesk-connect.js -->
72
+ <script src="../dist/armdesk-connect.js"></script>
73
+ <script>
74
+ const client = ArmDeskConnect.init({
75
+ orgKey: q.get("org") || "org_demo",
76
+ desk: q.get("desk") || "https://desk.example.com",
77
+ apiBase: standalone ? "https://desk.example.com/api/proxy" : undefined,
78
+ fetch: standalone ? stubDesk : undefined,
79
+ auth: { idToken },
80
+ });
81
+ client.on("error", (e) => log("error: " + e.code + " " + e.message));
82
+ client.on("session.expired", () => log("session expired, sign in again"));
83
+ client.me().then((m) => log("me: " + JSON.stringify(m)), () => undefined);
84
+ </script>
85
+ </body>
86
+ </html>
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@armdesk/connect-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "ARM Desk Connect: embed ITSM tickets in another product. Headless client, web components, React, and a server helper.",
5
+ "keywords": [
6
+ "armdesk",
7
+ "embed",
8
+ "web-components",
9
+ "react",
10
+ "itsm"
11
+ ],
12
+ "author": "DHRP",
13
+ "homepage": "https://armdesk.org",
14
+ "license": "UNLICENSED",
15
+ "type": "module",
16
+ "main": "./dist/esm/index.js",
17
+ "module": "./dist/esm/index.js",
18
+ "types": "./dist/esm/index.d.ts",
19
+ "unpkg": "./dist/armdesk-connect.js",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/esm/index.d.ts",
23
+ "import": "./dist/esm/index.js"
24
+ },
25
+ "./server": {
26
+ "types": "./dist/esm/server.d.ts",
27
+ "import": "./dist/esm/server.js"
28
+ },
29
+ "./react": {
30
+ "types": "./dist/esm/react.d.ts",
31
+ "import": "./dist/esm/react.js"
32
+ },
33
+ "./elements": {
34
+ "types": "./dist/esm/register.d.ts",
35
+ "import": "./dist/esm/register.js"
36
+ },
37
+ "./iife": "./dist/armdesk-connect.js"
38
+ },
39
+ "sideEffects": [
40
+ "./dist/esm/register.js",
41
+ "./dist/esm/browser.js"
42
+ ],
43
+ "files": [
44
+ "dist",
45
+ "README.md",
46
+ "CHANGELOG.md",
47
+ "examples",
48
+ "LICENSE.txt"
49
+ ],
50
+ "peerDependencies": {
51
+ "react": ">=17"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "react": {
55
+ "optional": true
56
+ }
57
+ },
58
+ "publishConfig": {
59
+ "access": "public"
60
+ }
61
+ }