@swirepay-developer/sparo-embed-sdk 1.0.3 → 1.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,9 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.5
4
+
5
+ - Fix DevOps publish: rename `eslint.config.js` → `eslint.config.mjs` and `vitest.config.js` → `vitest.config.mjs` (ESM configs without `"type": "module"` on package).
6
+ - Add `scripts/check-publish-manifest.mjs` and `scripts/ensure-dev-deps.mjs` (clear error if `npm ci` was skipped).
7
+ - Lint uses explicit `node_modules/eslint` path so publish fails with a clear message when devDeps are missing.
8
+ - `check-publish-manifest.mjs` blocks publish if `npm init` added bogus `dependencies` (restore with `git checkout -- package.json`).
9
+ - Added `scripts/devops-publish.sh` for one-command DevOps publish.
10
+ - `publishConfig.access` set to **`public`** (fixes npm `402 Payment Required` for private packages).
11
+ - Gateway should use `@swirepay-developer/sparo-embed-sdk@^1.0.5` after publish.
12
+
13
+ ## 1.0.4
14
+
15
+ - Published on npm as **`@swirepay-developer/sparo-embed-sdk`** (org scope `swirepay-developer`).
16
+ - Gateway must import `@swirepay-developer/sparo-embed-sdk` — **not** `@swirepay/sparo-embed-sdk`.
17
+ - Target release for gateway npm install (`@swirepay-developer/sparo-embed-sdk@^1.0.4`).
18
+ - Includes publish pipeline fixes and correct `dist/index.js` / `dist/index.mjs` entry points.
19
+
20
+ ## 1.0.1
21
+
22
+ - Fix package entry points (`main` / `exports`) to match build output (`dist/index.js`, `dist/index.mjs`).
23
+ - Add `publishConfig` for scoped npm publish (`restricted`).
24
+ - Remove `prepare: husky` so installing the published package does not run husky on gateway machines.
25
+ - Add [DEVOPS-NPM-PUBLISH.md](./DEVOPS-NPM-PUBLISH.md) and [bitbucket-pipelines.yml](./bitbucket-pipelines.yml) for Bitbucket → npm workflow.
26
+ - Point `repository` to Bitbucket (`zetametrics/sparo-swirepay-frontend`).
27
+
3
28
  ## 1.0.0
4
29
 
5
30
  - Introduced `embed(options)` SDK API aligned with SPARO guest-token backend flow.
6
31
  - Added iframe lifecycle handling, origin-pinned `postMessage` auth, and token auto-refresh.
7
32
  - Added `SPARO-EMBEDDING.md` integration guide for consumer applications.
8
33
  - Prepared package for distribution with `dist` outputs (CJS, ESM, browser global).
9
-
@@ -0,0 +1,497 @@
1
+ # Gateway Frontend — SPARO SDK Integration Guide (React)
2
+
3
+ Step-by-step guide for **gateway-frontend** React developers integrating `@swirepay-developer/sparo-embed-sdk` from npm.
4
+
5
+ > **Prerequisite:** DevOps must publish the SDK from Bitbucket first.
6
+ > Repo: https://bitbucket.org/zetametrics/sparo-swirepay-frontend.git — runbook: [DEVOPS-NPM-PUBLISH.md](./DEVOPS-NPM-PUBLISH.md)
7
+ >
8
+ > ### Wrong package name (most common after publish)
9
+ >
10
+ > npm package is **`@swirepay-developer/sparo-embed-sdk`** (scope `swirepay-developer`).
11
+ > If your code imports **`@swirepay/sparo-embed-sdk`** (no `-developer`), webpack will always show **Module not found** even after `npm install` and cache clear.
12
+ >
13
+ > **Fix:** change import + `package.json` dependency to `@swirepay-developer/sparo-embed-sdk` (see Step 1).
14
+ >
15
+ > **`Module not found`** with the correct name usually means not installed — run `npm view @swirepay-developer/sparo-embed-sdk version` (DevOps screenshot should show `1.0.5`).
16
+
17
+ ---
18
+
19
+ ## What you are building
20
+
21
+ ```text
22
+ User (logged into gateway)
23
+ → React page (SparoChat)
24
+ → SDK calls YOUR backend: GET /sparo/token
25
+ → YOUR backend calls SPARO: POST /api/guest-token (SPARO_ADMIN_KEY)
26
+ → SDK receives { token, expiresIn, account }
27
+ → SDK loads SPARO iframe + sends JWT via postMessage
28
+ → SPARO chat UI renders (no SPARO login screen)
29
+ ```
30
+
31
+ You do **not** implement iframe auth yourself — the SDK handles iframe creation, `postMessage`, and token refresh.
32
+
33
+ ---
34
+
35
+ ## Prerequisites
36
+
37
+ Before starting, confirm with your team:
38
+
39
+ | Item | Owner | Notes |
40
+ |------|--------|-------|
41
+ | npm access to `@swirepay-developer/sparo-embed-sdk` | DevOps / npm org | `npm login` if private scope |
42
+ | `SPARO_ADMIN_KEY` | Backend | Never in React code or `.env` with `REACT_APP_` |
43
+ | Merchant enabled in SPARO | SPARO admin | Deny-by-default allowlist |
44
+ | Backend route `/sparo/token` | Backend | Returns guest JWT for logged-in user |
45
+ | SPARO environment URL | Config | Staging vs production `sparoDomain` |
46
+
47
+ ---
48
+
49
+ ## Step 1 — Install the SDK
50
+
51
+ From the **gateway-frontend** project root:
52
+
53
+ ```bash
54
+ npm install @swirepay-developer/sparo-embed-sdk
55
+ ```
56
+
57
+ Or add to `package.json`:
58
+
59
+ ```json
60
+ {
61
+ "dependencies": {
62
+ "@swirepay-developer/sparo-embed-sdk": "^1.0.5"
63
+ }
64
+ }
65
+ ```
66
+
67
+ Then:
68
+
69
+ ```bash
70
+ npm install
71
+ ```
72
+
73
+ ### Verify install
74
+
75
+ ```bash
76
+ npm ls @swirepay-developer/sparo-embed-sdk
77
+ ```
78
+
79
+ You should see the package listed. If not:
80
+
81
+ - Add `.npmrc` with `@swirepay-developer:registry` (see [.npmrc.example](../.npmrc.example)) and `npm login` if needed
82
+ - Remove any old `"file:..."` path dependency for this package
83
+ - Delete `node_modules` and `package-lock.json`, then `npm install` again
84
+
85
+ ---
86
+
87
+ ## Step 2 — Environment variables (frontend)
88
+
89
+ Add **non-secret** config only. Never put `SPARO_ADMIN_KEY` in React env vars.
90
+
91
+ ### `.env.development` (local / dev)
92
+
93
+ ```env
94
+ REACT_APP_SPARO_DOMAIN=https://sparo-staging.swirepay.com
95
+ ```
96
+
97
+ ### `.env.production`
98
+
99
+ ```env
100
+ REACT_APP_SPARO_DOMAIN=https://sparo.swirepay.com
101
+ ```
102
+
103
+ Use the URL your team provides for each environment.
104
+ `sparoDomain` must match the environment your **backend** uses when minting tokens.
105
+
106
+ ---
107
+
108
+ ## Step 3 — Backend contract (coordinate with backend team)
109
+
110
+ Your React app will call **your** API, not SPARO directly.
111
+
112
+ ### Required endpoint (example)
113
+
114
+ `GET /sparo/token` (or `/api/sparo/token` — match your gateway API prefix)
115
+
116
+ **Request**
117
+
118
+ - Authenticated user session (cookie or Bearer — same as rest of gateway)
119
+ - `credentials: 'include'` if cookie-based
120
+
121
+ **Response `200`**
122
+
123
+ ```json
124
+ {
125
+ "token": "eyJhbGciOi...",
126
+ "expiresIn": 900,
127
+ "account": "account-72ec92..."
128
+ }
129
+ ```
130
+
131
+ | Field | Meaning |
132
+ |-------|---------|
133
+ | `token` | Short-lived guest JWT from SPARO |
134
+ | `expiresIn` | Seconds until expiry (e.g. 900 = 15 min) |
135
+ | `account` | Merchant account GID for this user |
136
+
137
+ **Important:** `account` must be the merchant the logged-in user belongs to. Backend resolves it from session/DB — frontend must not let users pick arbitrary merchant IDs.
138
+
139
+ ### Error responses to handle in UI
140
+
141
+ | HTTP | Meaning | Suggested UI |
142
+ |------|---------|----------------|
143
+ | 401 | User not logged in | Redirect to login |
144
+ | 403 | `merchant_not_enabled` | “Contact us” / support message |
145
+ | 429 | Rate limited | Retry message |
146
+ | 500 | Mint failed | Generic error + support |
147
+
148
+ ---
149
+
150
+ ## Step 4 — Create the React page component
151
+
152
+ Create a route component, e.g. `src/routes/SparoChat/index.js`:
153
+
154
+ ```jsx
155
+ import React, { useEffect, useRef, useState } from 'react';
156
+ import { Alert, Spin } from 'antd';
157
+ import { embed } from '@swirepay-developer/sparo-embed-sdk';
158
+
159
+ const SPARO_DOMAIN = process.env.REACT_APP_SPARO_DOMAIN || 'https://sparo.swirepay.com';
160
+
161
+ function SparoChat() {
162
+ const mountRef = useRef(null);
163
+ const handleRef = useRef(null);
164
+ const [loading, setLoading] = useState(true);
165
+ const [error, setError] = useState('');
166
+
167
+ useEffect(() => {
168
+ const mountElement = mountRef.current;
169
+ if (!mountElement) return undefined;
170
+
171
+ setLoading(true);
172
+ setError('');
173
+
174
+ handleRef.current = embed({
175
+ id: 'sparo-chat',
176
+ sparoDomain: SPARO_DOMAIN,
177
+ mountPoint: mountElement,
178
+ fetchGuestToken: async () => {
179
+ const response = await fetch('/sparo/token', {
180
+ method: 'GET',
181
+ credentials: 'include',
182
+ });
183
+ if (response.status === 401) {
184
+ window.location.href = '/login';
185
+ throw new Error('Unauthorized');
186
+ }
187
+ const payload = await response.json();
188
+ if (!response.ok) {
189
+ const apiError = new Error(
190
+ payload?.message || payload?.error || 'Unable to fetch SPARO token',
191
+ );
192
+ apiError.code = payload?.code || 'fetch_failed';
193
+ throw apiError;
194
+ }
195
+ return payload; // { token, expiresIn, account }
196
+ },
197
+ uiConfig: {
198
+ theme: 'light',
199
+ showWelcome: true,
200
+ showSuggestions: true,
201
+ hideSidebar: false,
202
+ },
203
+ onReady: () => setLoading(false),
204
+ onError: (err) => {
205
+ console.error('[SPARO]', err);
206
+ setLoading(false);
207
+ switch (err?.code) {
208
+ case 'merchant_not_enabled':
209
+ setError('Your merchant account is not enabled for SPARO.');
210
+ break;
211
+ case 'rate_limited':
212
+ setError('Too many requests. Please try again shortly.');
213
+ break;
214
+ case 'invalid_token':
215
+ setError('Invalid authentication token received.');
216
+ break;
217
+ case 'iframe_load_failed':
218
+ setError('Unable to load SPARO assistant.');
219
+ break;
220
+ default:
221
+ setError(err?.message || 'Failed to initialize SPARO.');
222
+ }
223
+ },
224
+ });
225
+
226
+ return () => {
227
+ if (handleRef.current?.unmount) {
228
+ handleRef.current.unmount();
229
+ handleRef.current = null;
230
+ }
231
+ };
232
+ }, []);
233
+
234
+ return (
235
+ <div style={{ padding: 20 }}>
236
+ <h2>SPARO Assistant</h2>
237
+ {loading && (
238
+ <div style={{ marginBottom: 16, textAlign: 'center' }}>
239
+ <Spin size="large" />
240
+ </div>
241
+ )}
242
+ {error && (
243
+ <Alert type="error" showIcon message={error} style={{ marginBottom: 16 }} />
244
+ )}
245
+ <div
246
+ ref={mountRef}
247
+ style={{
248
+ width: '100%',
249
+ height: '720px',
250
+ minHeight: '480px',
251
+ border: '1px solid #d9d9d9',
252
+ borderRadius: 8,
253
+ overflow: 'hidden',
254
+ }}
255
+ />
256
+ </div>
257
+ );
258
+ }
259
+
260
+ export default SparoChat;
261
+ ```
262
+
263
+ ### If your API base URL is not same-origin
264
+
265
+ Use your existing axios instance or API helper:
266
+
267
+ ```js
268
+ import { axiosAuthInstance, API_END_POINTS } from 'api';
269
+
270
+ fetchGuestToken: async () => {
271
+ const { data } = await axiosAuthInstance.get('/sparo/token');
272
+ return data;
273
+ },
274
+ ```
275
+
276
+ ---
277
+
278
+ ## Step 5 — Register the route
279
+
280
+ Add a protected route in your router config (example for React Router v5):
281
+
282
+ ```js
283
+ import SparoChat from 'routes/SparoChat';
284
+
285
+ // In routes array:
286
+ {
287
+ key: 'sparo',
288
+ path: '/sparo',
289
+ exact: true,
290
+ protected: true,
291
+ component: SparoChat,
292
+ allowedRoles: [/* same roles as your team allows */],
293
+ }
294
+ ```
295
+
296
+ Add a nav link or header icon that navigates to `/sparo`.
297
+
298
+ Restart the dev server after adding the route:
299
+
300
+ ```bash
301
+ npm start
302
+ ```
303
+
304
+ ---
305
+
306
+ ## Step 6 — Test locally
307
+
308
+ 1. Log in to gateway as a user tied to an **enabled** merchant.
309
+ 2. Open `/sparo`.
310
+ 3. Open DevTools → **Network**:
311
+ - Confirm `GET /sparo/token` returns `200` with `token`, `expiresIn`, `account`.
312
+ 4. Open DevTools → **Console**:
313
+ - No `Module not found` for `@swirepay-developer/sparo-embed-sdk`.
314
+ 5. Confirm iframe loads (Elements tab → `iframe` under your mount div).
315
+ 6. SPARO UI should appear without a SPARO login page.
316
+
317
+ ### Staging vs production
318
+
319
+ | Environment | `REACT_APP_SPARO_DOMAIN` | Backend mint URL |
320
+ |-------------|--------------------------|------------------|
321
+ | Staging | Staging SPARO host | Same SPARO env as domain |
322
+ | Production | `https://sparo.swirepay.com` (or prod host) | Production SPARO API |
323
+
324
+ Mismatch (staging token + production domain) causes auth failures.
325
+
326
+ ---
327
+
328
+ ## Step 7 — SDK API reference (what you pass)
329
+
330
+ ### `embed(options)`
331
+
332
+ | Option | Required | Description |
333
+ |--------|----------|-------------|
334
+ | `sparoDomain` | Yes | SPARO host, e.g. `https://sparo.swirepay.com` |
335
+ | `mountPoint` | Yes | DOM element (use `ref.current`) |
336
+ | `fetchGuestToken` | Yes | Async function returning `{ token, expiresIn, account }` |
337
+ | `id` | No | iframe id (default `sparo-embed`) |
338
+ | `uiConfig` | No | Theme and UI flags (see below) |
339
+ | `onReady` | No | Called when iframe signals ready |
340
+ | `onError` | No | Called on token/iframe errors |
341
+
342
+ ### `uiConfig` (optional)
343
+
344
+ ```js
345
+ {
346
+ theme: 'light', // 'light' | 'dark'
347
+ showWelcome: true,
348
+ showSuggestions: true,
349
+ hideSidebar: false,
350
+ }
351
+ ```
352
+
353
+ ### Return value
354
+
355
+ ```js
356
+ const handle = embed({ ... });
357
+
358
+ handle.refresh(); // manually refresh token (usually not needed)
359
+ handle.unmount(); // cleanup — call on route leave (useEffect return)
360
+ ```
361
+
362
+ Token refresh is **automatic** ~30 seconds before expiry.
363
+
364
+ ---
365
+
366
+ ## Step 8 — Security checklist (frontend)
367
+
368
+ - Do not store `SPARO_ADMIN_KEY` in frontend.
369
+ - Do not put guest `token` in URL query params.
370
+ - Do not hardcode production tokens in source.
371
+ - Always use `credentials: 'include'` if session is cookie-based.
372
+ - Always `unmount()` when leaving the page (see `useEffect` cleanup).
373
+ - Size the mount container with CSS (`height: 720px` or full viewport).
374
+
375
+ ---
376
+
377
+ ## Troubleshooting
378
+
379
+ ### `Module not found: Can't resolve '@swirepay/sparo-embed-sdk'`
380
+
381
+ **Wrong package name.** DevOps published `@swirepay-developer/sparo-embed-sdk@1.0.5`, not `@swirepay/sparo-embed-sdk`.
382
+
383
+ Update **both**:
384
+
385
+ ```js
386
+ // SparoChat.js — change this line
387
+ import { embed } from '@swirepay-developer/sparo-embed-sdk';
388
+ ```
389
+
390
+ ```json
391
+ // package.json
392
+ "@swirepay-developer/sparo-embed-sdk": "^1.0.5"
393
+ ```
394
+
395
+ Then:
396
+
397
+ ```bash
398
+ npm uninstall @swirepay/sparo-embed-sdk
399
+ npm install @swirepay-developer/sparo-embed-sdk
400
+ npm start
401
+ ```
402
+
403
+ Add to gateway `.npmrc` (no token in git — use env in CI):
404
+
405
+ ```ini
406
+ @swirepay-developer:registry=https://registry.npmjs.org/
407
+ ```
408
+
409
+ ---
410
+
411
+ ### `Module not found: Can't resolve '@swirepay-developer/sparo-embed-sdk'`
412
+
413
+ Webpack shows this when the package is **not installed** under `node_modules` (install failed or was never run).
414
+
415
+ **Step 0 — verify the package exists on your registry**
416
+
417
+ From `gateway-frontend`:
418
+
419
+ ```bash
420
+ npm view @swirepay-developer/sparo-embed-sdk version
421
+ ```
422
+
423
+ | Result | Meaning |
424
+ |--------|---------|
425
+ | `1.0.5` (or similar) | Published — go to Step 1 |
426
+ | `404 Not Found` | **Not on registry.npmjs.org** (or wrong scope/name). `npm install` will not add the package → this error persists |
427
+
428
+ If you see **404**, DevOps has not published yet (or gateway lacks npm read access to `@swirepay-developer`). Do not merge gateway code that imports the SDK until `npm view` returns a version.
429
+
430
+ **Step 1 — install and confirm**
431
+
432
+ ```bash
433
+ cd gateway-frontend
434
+ npm install @swirepay-developer/sparo-embed-sdk
435
+ dir node_modules\@swirepay-developer\sparo-embed-sdk\dist
436
+ ```
437
+
438
+ You must see `index.js` and `index.mjs` in that folder. If the folder is missing, the install did not succeed.
439
+
440
+ **Step 2**
441
+
442
+ 1. Restart `npm start` (CRA caches module resolution).
443
+ 2. In `package.json`, use a normal semver dependency — not a broken `file:` path to a machine-specific folder unless every dev shares that path.
444
+
445
+ ### Blank iframe / “Awaiting auth”
446
+
447
+ - Check `/sparo/token` returns valid JSON shape.
448
+ - Confirm `account` matches an allowlisted merchant.
449
+ - Confirm `sparoDomain` matches token mint environment (HTTPS in prod).
450
+
451
+ ### Mixed content blocked
452
+
453
+ - Page is `https://` but `sparoDomain` is `http://` → use HTTPS SPARO URL.
454
+
455
+ ### `merchant_not_enabled` (403)
456
+
457
+ - Merchant not on SPARO allowlist — contact SPARO admin, not a frontend bug.
458
+
459
+ ### `fetch_failed`
460
+
461
+ - Backend down, CORS issue, or user session expired.
462
+ - Check Network tab on `/sparo/token`.
463
+
464
+ ### Iframe works on refresh but not first load
465
+
466
+ - Ensure `mountRef.current` exists before calling `embed` (use `useEffect`, not render body).
467
+ - Do not call `embed` with `null` mount point.
468
+
469
+ ---
470
+
471
+ ## Minimal checklist
472
+
473
+ - [ ] `npm install @swirepay-developer/sparo-embed-sdk`
474
+ - [ ] `REACT_APP_SPARO_DOMAIN` set per environment
475
+ - [ ] Backend `/sparo/token` implemented and tested
476
+ - [ ] `SparoChat` component with `useEffect` + `unmount` cleanup
477
+ - [ ] Route registered (e.g. `/sparo`)
478
+ - [ ] User has access to enabled merchant
479
+ - [ ] Dev server restarted after install
480
+
481
+ ---
482
+
483
+ ## Related docs
484
+
485
+ - [SPARO-EMBEDDING.md](./SPARO-EMBEDDING.md) — full architecture and backend mint examples
486
+ - [INSTALL.md](./INSTALL.md) — npm install troubleshooting
487
+ - [SECURITY.md](./SECURITY.md) — trust boundaries and secrets
488
+
489
+ ---
490
+
491
+ ## Support contacts
492
+
493
+ | Issue | Contact |
494
+ |-------|---------|
495
+ | SDK npm / import errors | Frontend platform / SDK maintainers |
496
+ | `/sparo/token` / `SPARO_ADMIN_KEY` | Backend team |
497
+ | Merchant allowlist | SPARO admin |
package/README.md CHANGED
@@ -1,30 +1,49 @@
1
1
  # SPARO Embed SDK
2
2
 
3
- `@swirepay/sparo-embed-sdk` embeds SPARO in any web application using:
3
+ `@swirepay-developer/sparo-embed-sdk` embeds SPARO in web apps (including gateway React) using guest-token auth and an iframe.
4
4
 
5
- - iframe render (`/embed.html?embed=true&account=...`)
6
- - guest-token auth via `postMessage`
7
- - automatic token refresh before expiry
5
+ **Bitbucket:** https://bitbucket.org/zetametrics/sparo-swirepay-frontend.git
8
6
 
9
- **Gateway React developers:** start with [GATEWAY-REACT-GUIDE.md](./GATEWAY-REACT-GUIDE.md).
7
+ ---
10
8
 
11
- For backend architecture, see [SPARO-EMBEDDING.md](./SPARO-EMBEDDING.md).
12
- For Maven/WebJar distribution, see [MAVEN-PUBLISH.md](./MAVEN-PUBLISH.md).
9
+ ## Who does what
13
10
 
14
- ## Install
11
+ | Role | Action |
12
+ |------|--------|
13
+ | **You (SDK)** | Push this repo to Bitbucket (`sdkmaster` or release branch). Bump version in `package.json` for each release. |
14
+ | **DevOps** | Clone repo → `npm ci` → `npm publish`. See **[DEVOPS-NPM-PUBLISH.md](./DEVOPS-NPM-PUBLISH.md)**. |
15
+ | **Gateway developer** | After publish: `npm install @swirepay-developer/sparo-embed-sdk` and follow **[GATEWAY-REACT-GUIDE.md](./GATEWAY-REACT-GUIDE.md)**. |
16
+
17
+ Until DevOps publishes, gateway will show:
18
+
19
+ `Module not found: Can't resolve '@swirepay-developer/sparo-embed-sdk'`
20
+
21
+ That is expected — the package is not on npm yet.
22
+
23
+ ---
24
+
25
+ ## Gateway install (after DevOps publish)
15
26
 
16
27
  ```bash
17
- npm install @swirepay/sparo-embed-sdk
28
+ npm install @swirepay-developer/sparo-embed-sdk
29
+ ```
30
+
31
+ ```json
32
+ {
33
+ "dependencies": {
34
+ "@swirepay-developer/sparo-embed-sdk": "^1.0.5"
35
+ }
36
+ }
18
37
  ```
19
38
 
20
- For private scope access, ensure the consumer app’s `.npmrc` is configured for your org registry (do not commit tokens).
39
+ Private package: use [.npmrc.example](./.npmrc.example) with org `NPM_TOKEN` (DevOps provides access).
21
40
 
22
- Local development without registry access: see [INSTALL.md](./INSTALL.md).
41
+ ---
23
42
 
24
43
  ## Quick Start
25
44
 
26
45
  ```js
27
- import { embed } from '@swirepay/sparo-embed-sdk';
46
+ import { embed } from '@swirepay-developer/sparo-embed-sdk';
28
47
 
29
48
  const handle = embed({
30
49
  id: 'sparo-chat',
@@ -35,72 +54,30 @@ const handle = embed({
35
54
  if (!res.ok) throw new Error('token fetch failed');
36
55
  return await res.json(); // { token, expiresIn, account }
37
56
  },
38
- uiConfig: { theme: 'light' },
39
- onReady: () => console.log('SPARO ready'),
40
- onError: (err) => console.error('SPARO error', err),
41
57
  });
42
-
43
- // handle.unmount();
44
58
  ```
45
59
 
46
- ## API
47
-
48
- ### `embed(options)`
49
-
50
- Required:
51
-
52
- - `sparoDomain: string`
53
- - `mountPoint: HTMLElement`
54
- - `fetchGuestToken: () => Promise<{ token: string, expiresIn: number, account: string }>`
55
-
56
- Optional:
60
+ ---
57
61
 
58
- - `id: string` (default `sparo-embed`)
59
- - `uiConfig: object`
60
- - `onReady: () => void`
61
- - `onError: (error) => void`
62
+ ## Docs
62
63
 
63
- Returns:
64
+ | Document | Audience |
65
+ |----------|----------|
66
+ | [DEVOPS-NPM-PUBLISH.md](./DEVOPS-NPM-PUBLISH.md) | DevOps — publish to npm |
67
+ | [GATEWAY-REACT-GUIDE.md](./GATEWAY-REACT-GUIDE.md) | Gateway React — SparoChat integration |
68
+ | [SPARO-EMBEDDING.md](./SPARO-EMBEDDING.md) | Backend + architecture |
69
+ | [INSTALL.md](./INSTALL.md) | npm install / troubleshooting |
70
+ | [MAVEN-PUBLISH.md](./MAVEN-PUBLISH.md) | Java/WebJar only (not gateway) |
64
71
 
65
- - `refresh(): Promise<void>`
66
- - `unmount(): void`
72
+ ---
67
73
 
68
- ## Development
74
+ ## Development (SDK repo only)
69
75
 
70
76
  ```bash
71
77
  npm install
72
- npm run lint
73
- npm test
74
- npm run build
75
- npm pack --dry-run
76
- ```
77
-
78
- ## Package Outputs
79
-
80
- `npm run build` generates:
81
-
82
- - `dist/index.cjs` (CommonJS — used by CRA/webpack `require`)
83
- - `dist/index.js` (ES module)
84
- - `dist/sparo-embed-sdk.global.js` (browser global: `window.SparoEmbedSDK`)
85
-
86
- ## Publish Checklist
87
-
88
- Scoped packages (`@swirepay/...`) do **not** appear on registry.npmjs.org until you publish successfully.
89
-
90
- ```bash
91
78
  npm run verify
92
- npm pack --dry-run
93
- npm login
94
- # Private to @swirepay org (gateway devs need npm login + org access):
95
- npm publish --access restricted
96
- # OR public on npmjs (anyone can npm install):
97
- npm publish --access public
98
79
  ```
99
80
 
100
- After publish, confirm from any machine:
101
-
102
- ```bash
103
- npm view @swirepay/sparo-embed-sdk version
104
- ```
81
+ Build outputs: `dist/index.js`, `dist/index.mjs`, `dist/sparo-embed-sdk.global.js`
105
82
 
106
- If this returns **404**, gateway `npm install` will fail and CRA will keep reporting **Module not found**.
83
+ `dist/` is built during `npm publish` via `prepublishOnly` — do not commit `dist/`.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Embed the SPARO assistant into your application with short-lived guest JWTs, no SPARO login screen, and automatic token refresh.
4
4
 
5
- - SDK: `@swirepay/sparo-embed-sdk`
5
+ - SDK: `@swirepay-developer/sparo-embed-sdk`
6
6
  - SPARO backend: `v1.10.1+`
7
7
 
8
8
  ## Architecture
@@ -56,7 +56,7 @@ Response:
56
56
  ```
57
57
 
58
58
  ```js
59
- import { embed } from '@swirepay/sparo-embed-sdk';
59
+ import { embed } from '@swirepay-developer/sparo-embed-sdk';
60
60
 
61
61
  const handle = embed({
62
62
  id: 'sparo-chat',
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- function v(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function c(e,o,i){let s=new Error(o||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function D(e){if(!e||typeof e!="object")throw c("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw c("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw c("invalid_token","Missing account in fetchGuestToken response");let o=Number(e.expiresIn||900);if(!Number.isFinite(o)||o<=0)throw c("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:o}}function L(e,o){let i=new URLSearchParams({embed:"true",account:o});return`${e}/embed.html?${i.toString()}`}function _(e){let{id:o="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:w,uiConfig:R={},onReady:E,onError:g}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof w!="function")throw new Error("fetchGuestToken must be a function");let p=v(i),r=document.createElement("iframe");r.id=o,r.title="SPARO Assistant",r.style.width="100%",r.style.height="100%",r.style.border="0",r.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),r.setAttribute("referrerpolicy","no-referrer");let f=!0,k=!1,l=null,m=null,b=()=>{m&&(window.clearTimeout(m),m=null)},d=t=>{g&&g(t)},T=()=>{if(!f||!k||!l)return;let t=r.contentWindow;!t||typeof t.postMessage!="function"||t.postMessage({type:"sparo:auth",token:l.token,account:l.account,uiConfig:R},p)},x=t=>{b();let n=Math.max(5,t-30);m=window.setTimeout(()=>{h().catch(()=>{})},n*1e3)},h=async()=>{if(!f)return;let t;try{t=await w()}catch(u){let S=c("fetch_failed",(u==null?void 0:u.message)||"Failed to fetch guest token");throw d(S),S}let n=D(t);l=n,x(n.expiresIn);let a=L(p,n.account);!r.src||r.src!==a?r.src=a:T()},y=t=>{if(!f||t.origin!==p)return;let n=t.data;if(!(!n||typeof n!="object"||typeof n.type!="string")){if(n.type==="sparo:ready"||n.type==="SPARO_EMBED_READY"){k=!0,T(),E&&E();return}if(n.type==="sparo:error"){let a=n.code||"iframe_error",u=c(a,n.message||a,n.status);d(u)}}};return window.addEventListener("message",y),s.innerHTML="",s.appendChild(r),h().catch(t=>{d(t)}),{refresh:()=>h(),unmount:()=>{f=!1,b(),window.removeEventListener("message",y),r.parentNode===s&&s.removeChild(r)}}}var M=_;export{M as default,_ as embed};
1
+ var E=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var i in t)E(e,i,{get:t[i],enumerable:!0})},F=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of M(t))!A.call(e,c)&&c!==i&&E(e,c,{get:()=>t[c],enumerable:!(s=L(t,c))||s.enumerable});return e};var G=e=>F(E({},"__esModule",{value:!0}),e);var P={};I(P,{default:()=>x,embed:()=>g});module.exports=G(P);function C(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function a(e,t,i){let s=new Error(t||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function H(e){if(!e||typeof e!="object")throw a("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw a("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw a("invalid_token","Missing account in fetchGuestToken response");let t=Number(e.expiresIn||900);if(!Number.isFinite(t)||t<=0)throw a("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:t}}function N(e,t){let i=new URLSearchParams({embed:"true",account:t});return`${e}/embed.html?${i.toString()}`}function g(e){let{id:t="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:c,uiConfig:v={},onReady:k,onError:b}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof c!="function")throw new Error("fetchGuestToken must be a function");let d=C(i),o=document.createElement("iframe");o.id=t,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let l=!0,T=!1,m=null,p=null,y=()=>{p&&(window.clearTimeout(p),p=null)},h=n=>{b&&b(n)},S=()=>{if(!l||!T||!m)return;let n=o.contentWindow;!n||typeof n.postMessage!="function"||n.postMessage({type:"sparo:auth",token:m.token,account:m.account,uiConfig:v},d)},D=n=>{y();let r=Math.max(5,n-30);p=window.setTimeout(()=>{w().catch(()=>{})},r*1e3)},w=async()=>{if(!l)return;let n;try{n=await c()}catch(f){let R=a("fetch_failed",(f==null?void 0:f.message)||"Failed to fetch guest token");throw h(R),R}let r=H(n);m=r,D(r.expiresIn);let u=N(d,r.account);!o.src||o.src!==u?o.src=u:S()},_=n=>{if(!l||n.origin!==d)return;let r=n.data;if(!(!r||typeof r!="object"||typeof r.type!="string")){if(r.type==="sparo:ready"||r.type==="SPARO_EMBED_READY"){T=!0,S(),k&&k();return}if(r.type==="sparo:error"){let u=r.code||"iframe_error",f=a(u,r.message||u,r.status);h(f)}}};return window.addEventListener("message",_),s.innerHTML="",s.appendChild(o),w().catch(n=>{h(n)}),{refresh:()=>w(),unmount:()=>{l=!1,y(),window.removeEventListener("message",_),o.parentNode===s&&s.removeChild(o)}}}var x=g;0&&(module.exports={embed});
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ function v(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function c(e,o,i){let s=new Error(o||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function D(e){if(!e||typeof e!="object")throw c("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw c("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw c("invalid_token","Missing account in fetchGuestToken response");let o=Number(e.expiresIn||900);if(!Number.isFinite(o)||o<=0)throw c("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:o}}function L(e,o){let i=new URLSearchParams({embed:"true",account:o});return`${e}/embed.html?${i.toString()}`}function _(e){let{id:o="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:w,uiConfig:R={},onReady:E,onError:g}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof w!="function")throw new Error("fetchGuestToken must be a function");let p=v(i),r=document.createElement("iframe");r.id=o,r.title="SPARO Assistant",r.style.width="100%",r.style.height="100%",r.style.border="0",r.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),r.setAttribute("referrerpolicy","no-referrer");let f=!0,k=!1,l=null,m=null,b=()=>{m&&(window.clearTimeout(m),m=null)},d=t=>{g&&g(t)},T=()=>{if(!f||!k||!l)return;let t=r.contentWindow;!t||typeof t.postMessage!="function"||t.postMessage({type:"sparo:auth",token:l.token,account:l.account,uiConfig:R},p)},x=t=>{b();let n=Math.max(5,t-30);m=window.setTimeout(()=>{h().catch(()=>{})},n*1e3)},h=async()=>{if(!f)return;let t;try{t=await w()}catch(u){let S=c("fetch_failed",(u==null?void 0:u.message)||"Failed to fetch guest token");throw d(S),S}let n=D(t);l=n,x(n.expiresIn);let a=L(p,n.account);!r.src||r.src!==a?r.src=a:T()},y=t=>{if(!f||t.origin!==p)return;let n=t.data;if(!(!n||typeof n!="object"||typeof n.type!="string")){if(n.type==="sparo:ready"||n.type==="SPARO_EMBED_READY"){k=!0,T(),E&&E();return}if(n.type==="sparo:error"){let a=n.code||"iframe_error",u=c(a,n.message||a,n.status);d(u)}}};return window.addEventListener("message",y),s.innerHTML="",s.appendChild(r),h().catch(t=>{d(t)}),{refresh:()=>h(),unmount:()=>{f=!1,b(),window.removeEventListener("message",y),r.parentNode===s&&s.removeChild(r)}}}var M=_;export{M as default,_ as embed};
package/package.json CHANGED
@@ -1,23 +1,22 @@
1
1
  {
2
2
  "name": "@swirepay-developer/sparo-embed-sdk",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "SPARO embedding SDK for guest-token based iframe integration",
5
5
  "private": false,
6
6
  "license": "UNLICENSED",
7
7
  "author": "Swirepay",
8
8
  "sideEffects": false,
9
- "main": "./dist/index.cjs",
10
- "module": "./dist/index.js",
9
+ "main": "./dist/index.js",
10
+ "module": "./dist/index.mjs",
11
11
  "types": "./types/index.d.ts",
12
12
  "unpkg": "./dist/sparo-embed-sdk.global.js",
13
- "type": "module",
14
13
  "jsdelivr": "./dist/sparo-embed-sdk.global.js",
15
14
  "exports": {
16
15
  ".": {
17
16
  "types": "./types/index.d.ts",
18
- "import": "./dist/index.js",
19
- "require": "./dist/index.cjs",
20
- "default": "./dist/index.js"
17
+ "import": "./dist/index.mjs",
18
+ "require": "./dist/index.js",
19
+ "default": "./dist/index.mjs"
21
20
  },
22
21
  "./package.json": "./package.json"
23
22
  },
@@ -27,6 +26,7 @@
27
26
  "README.md",
28
27
  "CHANGELOG.md",
29
28
  "SPARO-EMBEDDING.md",
29
+ "GATEWAY-REACT-GUIDE.md",
30
30
  "SECURITY.md",
31
31
  "LICENSE"
32
32
  ],
@@ -39,21 +39,28 @@
39
39
  ],
40
40
  "repository": {
41
41
  "type": "git",
42
- "url": "git+https://github.com/swirepay/sparo-embed-sdk.git"
42
+ "url": "git+https://bitbucket.org/zetametrics/sparo-swirepay-frontend.git"
43
43
  },
44
44
  "bugs": {
45
- "url": "https://github.com/swirepay/sparo-embed-sdk/issues"
45
+ "url": "https://bitbucket.org/zetametrics/sparo-swirepay-frontend/issues"
46
+ },
47
+ "homepage": "https://bitbucket.org/zetametrics/sparo-swirepay-frontend#readme",
48
+ "publishConfig": {
49
+ "access": "public",
50
+ "registry": "https://registry.npmjs.org/"
51
+ },
52
+ "engines": {
53
+ "node": ">=18"
46
54
  },
47
- "homepage": "https://github.com/swirepay/sparo-embed-sdk#readme",
48
55
  "scripts": {
49
56
  "clean": "rimraf dist",
50
57
  "build": "npm run clean && tsup src/sdk/index.js --format cjs,esm --out-dir dist --minify --clean && esbuild src/sdk/index.js --bundle --format=iife --global-name=SparoEmbedSDK --platform=browser --outfile=dist/sparo-embed-sdk.global.js --minify",
58
+ "build:sdk": "npm run build",
51
59
  "test": "vitest run",
52
60
  "test:watch": "vitest",
53
- "lint": "eslint src",
54
- "verify": "npm run lint && npm run test && npm run build",
55
- "prepublishOnly": "npm run verify",
56
- "prepare": "husky"
61
+ "lint": "node ./node_modules/eslint/bin/eslint.js src",
62
+ "verify": "node scripts/ensure-dev-deps.mjs && npm run lint && npm run test && npm run build",
63
+ "prepublishOnly": "npm run verify && node scripts/check-publish-manifest.mjs"
57
64
  },
58
65
  "devDependencies": {
59
66
  "@testing-library/dom": "^10.4.0",
@@ -72,182 +79,5 @@
72
79
  "eslint --fix",
73
80
  "prettier --write"
74
81
  ]
75
- },
76
- "dependencies": {
77
- "acorn": "^8.16.0",
78
- "acorn-jsx": "^5.3.2",
79
- "agent-base": "^7.1.4",
80
- "ajv": "^6.15.0",
81
- "ansi-regex": "^5.0.1",
82
- "ansi-styles": "^4.3.0",
83
- "any-promise": "^1.3.0",
84
- "argparse": "^2.0.1",
85
- "assertion-error": "^2.0.1",
86
- "balanced-match": "^1.0.2",
87
- "brace-expansion": "^1.1.14",
88
- "braces": "^3.0.3",
89
- "buffer-from": "^1.1.2",
90
- "bundle-require": "^5.1.0",
91
- "cac": "^6.7.14",
92
- "callsites": "^3.1.0",
93
- "chai": "^5.3.3",
94
- "chalk": "^4.1.2",
95
- "check-error": "^2.1.3",
96
- "cli-cursor": "^5.0.0",
97
- "cli-truncate": "^4.0.0",
98
- "color-convert": "^2.0.1",
99
- "color-name": "^1.1.4",
100
- "colorette": "^2.0.20",
101
- "commander": "^4.1.1",
102
- "concat-map": "^0.0.1",
103
- "confbox": "^0.1.8",
104
- "consola": "^3.4.2",
105
- "cross-spawn": "^7.0.6",
106
- "cssstyle": "^4.6.0",
107
- "data-urls": "^5.0.0",
108
- "debug": "^4.4.3",
109
- "decimal.js": "^10.6.0",
110
- "deep-eql": "^5.0.2",
111
- "deep-is": "^0.1.4",
112
- "dequal": "^2.0.3",
113
- "environment": "^1.1.0",
114
- "escape-string-regexp": "^4.0.0",
115
- "eslint-scope": "^8.4.0",
116
- "eslint-visitor-keys": "^3.4.3",
117
- "espree": "^10.4.0",
118
- "esquery": "^1.7.0",
119
- "esrecurse": "^4.3.0",
120
- "estraverse": "^5.3.0",
121
- "esutils": "^2.0.3",
122
- "expect-type": "^1.3.0",
123
- "fast-deep-equal": "^3.1.3",
124
- "fast-json-stable-stringify": "^2.1.0",
125
- "fast-levenshtein": "^2.0.6",
126
- "file-entry-cache": "^8.0.0",
127
- "fill-range": "^7.1.1",
128
- "find-up": "^5.0.0",
129
- "fix-dts-default-cjs-exports": "^1.0.1",
130
- "flat-cache": "^4.0.1",
131
- "flatted": "^3.4.2",
132
- "get-east-asian-width": "^1.6.0",
133
- "glob-parent": "^6.0.2",
134
- "has-flag": "^4.0.0",
135
- "html-encoding-sniffer": "^4.0.0",
136
- "http-proxy-agent": "^7.0.2",
137
- "https-proxy-agent": "^7.0.6",
138
- "iconv-lite": "^0.6.3",
139
- "ignore": "^5.3.2",
140
- "import-fresh": "^3.3.1",
141
- "imurmurhash": "^0.1.4",
142
- "is-extglob": "^2.1.1",
143
- "is-glob": "^4.0.3",
144
- "is-number": "^7.0.0",
145
- "is-potential-custom-element-name": "^1.0.1",
146
- "isexe": "^2.0.0",
147
- "jiti": "^1.21.7",
148
- "joycon": "^3.1.1",
149
- "js-tokens": "^4.0.0",
150
- "js-yaml": "^4.1.1",
151
- "json-buffer": "^3.0.1",
152
- "json-schema-traverse": "^0.4.1",
153
- "json-stable-stringify-without-jsonify": "^1.0.1",
154
- "keyv": "^4.5.4",
155
- "levn": "^0.4.1",
156
- "lines-and-columns": "^1.2.4",
157
- "listr2": "^8.3.3",
158
- "load-tsconfig": "^0.2.5",
159
- "locate-path": "^6.0.0",
160
- "lodash.merge": "^4.6.2",
161
- "log-update": "^6.1.0",
162
- "loupe": "^3.2.1",
163
- "lz-string": "^1.5.0",
164
- "merge-stream": "^2.0.0",
165
- "micromatch": "^4.0.8",
166
- "mimic-function": "^5.0.1",
167
- "minimatch": "^3.1.5",
168
- "minipass": "^7.1.3",
169
- "mlly": "^1.8.2",
170
- "ms": "^2.1.3",
171
- "mz": "^2.7.0",
172
- "nanoid": "^3.3.12",
173
- "natural-compare": "^1.4.0",
174
- "nwsapi": "^2.2.23",
175
- "object-assign": "^4.1.1",
176
- "optionator": "^0.9.4",
177
- "p-limit": "^3.1.0",
178
- "p-locate": "^5.0.0",
179
- "package-json-from-dist": "^1.0.1",
180
- "parent-module": "^1.0.1",
181
- "parse5": "^7.3.0",
182
- "path-exists": "^4.0.0",
183
- "path-key": "^3.1.1",
184
- "path-scurry": "^2.0.2",
185
- "pathe": "^2.0.3",
186
- "pathval": "^2.0.1",
187
- "picocolors": "^1.1.1",
188
- "picomatch": "^2.3.2",
189
- "pidtree": "^0.6.0",
190
- "pirates": "^4.0.7",
191
- "pkg-types": "^1.3.1",
192
- "postcss": "^8.5.15",
193
- "prelude-ls": "^1.2.1",
194
- "pretty-format": "^27.5.1",
195
- "punycode": "^2.3.1",
196
- "react-is": "^17.0.2",
197
- "resolve-from": "^4.0.0",
198
- "restore-cursor": "^5.1.0",
199
- "rfdc": "^1.4.1",
200
- "rrweb-cssom": "^0.8.0",
201
- "safer-buffer": "^2.1.2",
202
- "saxes": "^6.0.0",
203
- "shebang-command": "^2.0.0",
204
- "shebang-regex": "^3.0.0",
205
- "siginfo": "^2.0.0",
206
- "slice-ansi": "^5.0.0",
207
- "source-map": "^0.7.6",
208
- "source-map-js": "^1.2.1",
209
- "source-map-support": "^0.5.21",
210
- "stackback": "^0.0.2",
211
- "std-env": "^3.10.0",
212
- "string-argv": "^0.3.2",
213
- "strip-json-comments": "^3.1.1",
214
- "strip-literal": "^3.1.0",
215
- "sucrase": "^3.35.1",
216
- "supports-color": "^7.2.0",
217
- "symbol-tree": "^3.2.4",
218
- "terser": "^5.47.1",
219
- "thenify": "^3.3.1",
220
- "thenify-all": "^1.6.0",
221
- "tinybench": "^2.9.0",
222
- "tinyexec": "^0.3.2",
223
- "tinyglobby": "^0.2.16",
224
- "tinypool": "^1.1.1",
225
- "tinyrainbow": "^2.0.0",
226
- "tinyspy": "^4.0.4",
227
- "tldts": "^6.1.86",
228
- "tldts-core": "^6.1.86",
229
- "to-regex-range": "^5.0.1",
230
- "tough-cookie": "^5.1.2",
231
- "tr46": "^5.1.1",
232
- "tree-kill": "^1.2.2",
233
- "ts-interface-checker": "^0.1.13",
234
- "type-check": "^0.4.0",
235
- "typescript": "^4.9.5",
236
- "ufo": "^1.6.4",
237
- "undici-types": "^7.24.6",
238
- "uri-js": "^4.4.1",
239
- "vite-node": "^3.2.4",
240
- "w3c-xmlserializer": "^5.0.0",
241
- "webidl-conversions": "^7.0.0",
242
- "whatwg-encoding": "^3.1.1",
243
- "whatwg-mimetype": "^4.0.0",
244
- "whatwg-url": "^14.2.0",
245
- "which": "^2.0.2",
246
- "why-is-node-running": "^2.3.0",
247
- "word-wrap": "^1.2.5",
248
- "ws": "^8.21.0",
249
- "xml-name-validator": "^5.0.0",
250
- "xmlchars": "^2.2.0",
251
- "yocto-queue": "^0.1.0"
252
82
  }
253
83
  }
package/dist/index.cjs DELETED
@@ -1 +0,0 @@
1
- var E=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var i in t)E(e,i,{get:t[i],enumerable:!0})},F=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of M(t))!A.call(e,c)&&c!==i&&E(e,c,{get:()=>t[c],enumerable:!(s=L(t,c))||s.enumerable});return e};var G=e=>F(E({},"__esModule",{value:!0}),e);var P={};I(P,{default:()=>x,embed:()=>g});module.exports=G(P);function C(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function a(e,t,i){let s=new Error(t||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function H(e){if(!e||typeof e!="object")throw a("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw a("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw a("invalid_token","Missing account in fetchGuestToken response");let t=Number(e.expiresIn||900);if(!Number.isFinite(t)||t<=0)throw a("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:t}}function N(e,t){let i=new URLSearchParams({embed:"true",account:t});return`${e}/embed.html?${i.toString()}`}function g(e){let{id:t="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:c,uiConfig:v={},onReady:k,onError:b}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof c!="function")throw new Error("fetchGuestToken must be a function");let d=C(i),o=document.createElement("iframe");o.id=t,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let l=!0,T=!1,m=null,p=null,y=()=>{p&&(window.clearTimeout(p),p=null)},h=n=>{b&&b(n)},S=()=>{if(!l||!T||!m)return;let n=o.contentWindow;!n||typeof n.postMessage!="function"||n.postMessage({type:"sparo:auth",token:m.token,account:m.account,uiConfig:v},d)},D=n=>{y();let r=Math.max(5,n-30);p=window.setTimeout(()=>{w().catch(()=>{})},r*1e3)},w=async()=>{if(!l)return;let n;try{n=await c()}catch(f){let R=a("fetch_failed",(f==null?void 0:f.message)||"Failed to fetch guest token");throw h(R),R}let r=H(n);m=r,D(r.expiresIn);let u=N(d,r.account);!o.src||o.src!==u?o.src=u:S()},_=n=>{if(!l||n.origin!==d)return;let r=n.data;if(!(!r||typeof r!="object"||typeof r.type!="string")){if(r.type==="sparo:ready"||r.type==="SPARO_EMBED_READY"){T=!0,S(),k&&k();return}if(r.type==="sparo:error"){let u=r.code||"iframe_error",f=a(u,r.message||u,r.status);h(f)}}};return window.addEventListener("message",_),s.innerHTML="",s.appendChild(o),w().catch(n=>{h(n)}),{refresh:()=>w(),unmount:()=>{l=!1,y(),window.removeEventListener("message",_),o.parentNode===s&&s.removeChild(o)}}}var x=g;0&&(module.exports={embed});