@healthier-business/hub-sdk 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +155 -3
  2. package/dist/cjs/access.d.ts +60 -0
  3. package/dist/cjs/access.js +21 -0
  4. package/dist/cjs/browser/index.d.ts +3 -3
  5. package/dist/cjs/browser/index.js +3 -1
  6. package/dist/cjs/browser/mount.d.ts +2 -0
  7. package/dist/cjs/browser/mount.js +16 -4
  8. package/dist/cjs/core/errors.d.ts +56 -2
  9. package/dist/cjs/core/errors.js +126 -7
  10. package/dist/cjs/core/http.js +1 -1
  11. package/dist/cjs/embed/handler.js +3 -1
  12. package/dist/cjs/embed/protocol.d.ts +33 -3
  13. package/dist/cjs/embed/protocol.js +29 -1
  14. package/dist/cjs/generated/events.d.ts +8 -1
  15. package/dist/cjs/generated/events.js +7 -0
  16. package/dist/cjs/generated/operations.js +24 -0
  17. package/dist/cjs/generated/resources.d.ts +114 -1
  18. package/dist/cjs/generated/types.d.ts +288 -2
  19. package/dist/cjs/index.d.ts +3 -2
  20. package/dist/cjs/index.js +12 -1
  21. package/dist/cjs/version.d.ts +1 -1
  22. package/dist/cjs/version.js +1 -1
  23. package/dist/cjs/webhooks.d.ts +6 -0
  24. package/dist/cjs/webhooks.js +6 -0
  25. package/dist/esm/access.d.ts +60 -0
  26. package/dist/esm/access.js +18 -0
  27. package/dist/esm/browser/index.d.ts +3 -3
  28. package/dist/esm/browser/index.js +1 -1
  29. package/dist/esm/browser/mount.d.ts +2 -0
  30. package/dist/esm/browser/mount.js +17 -5
  31. package/dist/esm/core/errors.d.ts +56 -2
  32. package/dist/esm/core/errors.js +119 -6
  33. package/dist/esm/core/http.js +1 -1
  34. package/dist/esm/embed/handler.js +4 -2
  35. package/dist/esm/embed/protocol.d.ts +33 -3
  36. package/dist/esm/embed/protocol.js +27 -0
  37. package/dist/esm/generated/events.d.ts +8 -1
  38. package/dist/esm/generated/events.js +7 -0
  39. package/dist/esm/generated/operations.js +24 -0
  40. package/dist/esm/generated/resources.d.ts +114 -1
  41. package/dist/esm/generated/types.d.ts +288 -2
  42. package/dist/esm/index.d.ts +3 -2
  43. package/dist/esm/index.js +3 -2
  44. package/dist/esm/version.d.ts +1 -1
  45. package/dist/esm/version.js +1 -1
  46. package/dist/esm/webhooks.d.ts +6 -0
  47. package/dist/esm/webhooks.js +6 -0
  48. package/dist/iife/hb-embed.min.js +1 -1
  49. package/package.json +1 -1
package/README.md CHANGED
@@ -37,10 +37,12 @@ That is all the setup there is. No token calls, no refresh logic, no storage.
37
37
  - [Calling the API](#calling-the-api)
38
38
  - [Pagination](#pagination)
39
39
  - [Errors](#errors)
40
+ - [Approval for sensitive areas](#approval-for-sensitive-areas)
40
41
  - [Retries, timeouts and idempotency](#retries-timeouts-and-idempotency)
41
42
  - [Files](#files)
42
43
  - [Webhooks](#webhooks)
43
44
  - [Embedding courses, tests and OH forms](#embedding-courses-tests-and-oh-forms)
45
+ - [Access, payment and renewal](#access-payment-and-renewal)
44
46
  - [Sandbox](#sandbox)
45
47
  - [Serverless and token storage](#serverless-and-token-storage)
46
48
  - [Updating the SDK when the API changes](#updating-the-sdk-when-the-api-changes)
@@ -110,8 +112,11 @@ Everything the Hub refuses is an `ApiError` with `status`, `code` (the stable `s
110
112
  | --- | --- |
111
113
  | `ValidationError` (422) | `error.fields` maps each field to its messages. Nothing was changed. |
112
114
  | `PermissionError` (403) | `insufficient_scope`, `portal_unavailable`, `key_inactive`, `ip_not_allowed`. |
115
+ | `ApiAccessError` (403, a `PermissionError`) | `api_access_not_approved`, `api_access_pending`, `api_access_rejected`, `api_access_revoked`: the area needs the Hub's manual approval. `error.areas`, `error.docsUrl`, `error.state`. Not retried. See [Approval for sensitive areas](#approval-for-sensitive-areas). |
116
+ | `WebhookEventsNotApprovedError` (403, a `PermissionError`) | `webhook_events_not_approved`: an endpoint asked for events of an area you are not approved for. `error.events`, `error.areas`. |
113
117
  | `AuthenticationError` (401) | The key is wrong, or was regenerated. |
114
118
  | `NotFoundError` (404), `ConflictError` (409) | |
119
+ | `EmbedAccessError` (409, a `ConflictError`) | An embed session was refused because the candidate's access is not in place. `error.access` is `{ state, payer, next }`. See [Access, payment and renewal](#access-payment-and-renewal). |
115
120
  | `InsufficientCreditsError` (402) | Nothing was charged. |
116
121
  | `RateLimitError` (429) | After the SDK ran out of retries. `retryAfterSeconds` is set. |
117
122
  | `GoneError` (410) | For example `session_expired`. |
@@ -128,6 +133,49 @@ try {
128
133
  }
129
134
  ```
130
135
 
136
+ ## Approval for sensitive areas
137
+
138
+ Occupational Health and DBS & Right To Work (by default; Hub staff choose the list) hold health and criminal record information. With a **live** key, their API calls and their webhook events work only after a member of the Hub team has approved your organisation. A user of your organisation asks for it once, in the Hub under **Developer > API access**; you are emailed the decision. The [sandbox](#sandbox) is always open. The full rules are in the [API access approval guide](https://dev.hbcompliance.co.uk/docs/api-access-approval).
139
+
140
+ **Check where you stand** (works with any valid key, no scope needed):
141
+
142
+ ```ts
143
+ const { data } = await hb.account.apiAccess.get();
144
+ for (const a of data.filter((x) => x.sensitive)) {
145
+ console.log(a.label, a.status); // not_requested | pending | approved | rejected | revoked
146
+ }
147
+ ```
148
+
149
+ `status` is `not_required` (the area is open, always the case in the sandbox), `not_requested`, `pending`, `approved`, `rejected` or `revoked`. Read the list instead of hard-coding the areas. The reason for a rejection or a withdrawal is shown in the Hub and in the email, never in the API.
150
+
151
+ **Catch the refusals.** A call to an area you are not approved for answers `403` and the SDK throws an `ApiAccessError`. It is never retried: show a message and fix the approval.
152
+
153
+ ```ts
154
+ import { ApiAccessError, WebhookEventsNotApprovedError } from '@healthier-business/hub-sdk';
155
+
156
+ try {
157
+ await hb.occupationalHealth.requests.list();
158
+ } catch (e) {
159
+ if (e instanceof ApiAccessError) {
160
+ // e.code: api_access_not_approved | api_access_pending | api_access_rejected | api_access_revoked
161
+ // e.state: 'not_requested' | 'pending' | 'rejected' | 'revoked'
162
+ console.warn(`${e.areas.join(', ')} needs approval (${e.state}). ${e.docsUrl}`);
163
+ } else if (e instanceof WebhookEventsNotApprovedError) {
164
+ console.warn('Remove these events or get approved first:', e.events);
165
+ } else throw e;
166
+ }
167
+ ```
168
+
169
+ `isApiAccessError(e)` and `isWebhookEventsNotApprovedError(e)` do the same checks as type guards, and `e.hint` is a plain-words next step.
170
+
171
+ **Webhooks.** `WEBHOOK_EVENT_TYPES` lists every event type, but events of an area that needs approval (`occupational-health.*`, `dbs-rtw.*` by default) are only sent to an approved organisation, are not queued and are not replayed after approval (fetch what you missed from the API). Creating or updating an endpoint with such events before approval throws `WebhookEventsNotApprovedError`. Create those endpoints once `hb.account.apiAccess.get()` shows `approved`.
172
+
173
+ **Try the refusals in the sandbox.** Send the header `X-HB-Simulate-Access` with `not_approved`, `pending`, `rejected` or `revoked` on a sandbox call to get the matching error:
174
+
175
+ ```ts
176
+ await hb.occupationalHealth.requests.list({}, { headers: { 'X-HB-Simulate-Access': 'pending' } });
177
+ ```
178
+
131
179
  ## Retries, timeouts and idempotency
132
180
 
133
181
  - Reads and deletes are retried on network errors, `429`, `502`, `503` and `504` (twice by default, with exponential backoff and jitter). A `429` waits for `Retry-After` (or the rate-limit reset) when it is 30 seconds or less, otherwise the error is raised straight away.
@@ -232,7 +280,7 @@ const frame = HealthierBusiness.mount(document.getElementById('course')!, {
232
280
 
233
281
  ### Events
234
282
 
235
- Every event below is sent by the Hub frame. The callbacks (`onProgress`, `onCompleted`, `onPassed`, `onFailed`, `onSubmitted`, `onError`, `onReady`), `onEvent` and `controller.on(name, handler)` all receive the data typed exactly as the frame sends it:
283
+ Every event below is sent by the Hub frame. The callbacks (`onProgress`, `onCompleted`, `onPassed`, `onFailed`, `onSubmitted`, `onTermsAccepted`, `onError`, `onReady`), `onEvent` and `controller.on(name, handler)` all receive the data typed exactly as the frame sends it:
236
284
 
237
285
  | Event | Sent when | Data |
238
286
  | --- | --- | --- |
@@ -241,7 +289,8 @@ Every event below is sent by the Hub frame. The callbacks (`onProgress`, `onComp
241
289
  | `completed` | The learner finished the course. Final. | `{ courseId }`: the Online Training course id of the session. |
242
290
  | `passed` / `failed` | The learner submitted the test. Final. | `{ score, passMark }`: both percentages, `score` with one decimal. The frame does not say how many attempts are left. |
243
291
  | `submitted` | The OH form was submitted. Final. | `{ requestId }`: the numeric OH request id. |
244
- | `error` | The frame could not show the session, or a call was refused after it started. | `{ code }`, plus a plain-words `message` added by the SDK. See [Troubleshooting](#troubleshooting). |
292
+ | `terms-accepted` | The candidate accepted the Hub terms on the first screen of the frame. Not final: the content follows. | `{ version, acceptedAt }`: the terms version and an ISO 8601 time. |
293
+ | `error` | The frame could not show the session, or a call was refused after it started. | `{ code }`, plus a plain-words `message` added by the SDK, and `details` (`{ state, payer, next }`) for the four access codes. See [Troubleshooting](#troubleshooting). |
245
294
  | `token-expiring` | About 2 minutes before the frame's access ends. The SDK renews it for you; you only see the event. | `{ expires_at }`: ISO 8601. |
246
295
 
247
296
  The last event of a session (`completed`, `passed`, `failed` or `submitted`) finishes it, and the Hub sends it exactly once. The events come from what the Hub recorded, never from what the browser says, so they are safe to act on in the page, but your server should still read the result from the API (or a webhook) before it grants anything.
@@ -307,11 +356,15 @@ Errors from creating or refreshing a session (these are `ApiError`s; `error.hint
307
356
  | `404 not_found` | The candidate, request or session does not exist (for your account). | Check the id; sandbox ids mean nothing for a real account, and the other way round. |
308
357
  | `409 course_not_embeddable` | The course is not a Course Studio course linked to an Online Training course. | Use a Course Studio course. |
309
358
  | `409 course_not_pending` | The candidate already completed this course. | Only courses still to do can be opened. |
310
- | `409 course_access_required` | The candidate does not have the course. | Assign it first with `hb.onlineTraining.candidates.courses()`. |
359
+ | `409 course_access_required` | The candidate's access has not been started (or the course is not assigned). `details.next` is `start_access`. | Start it with `hb.onlineTraining.candidates.accessStart()`, then create the session again. If the course is not assigned, assign it first with `hb.onlineTraining.candidates.courses()`. |
360
+ | `409 payment_pending` | The candidate has a payment link that is not paid yet. `details.next` is `pay`. | Ask them to pay, or start access again for a new link (it replaces the old one). Create the session after `online-training.access.started`. |
361
+ | `409 renewal_approval_required` | A manual renewal needs your approval. The request is recorded and your agency emailed once. `details.next` is `await_approval`. | Approve it with `renewalApprove()` (or in Hub), then create the session again. |
362
+ | `409 access_expired` | The candidate's access has ended. `details.next` is `renew`. | Renew with `accessStart()`, or `renewalRequest()` when renewals need approval, then create the session again. |
311
363
  | `409 form_not_pending` | That questionnaire was already sent, or the request has an outcome. | Pick a form that is still to answer. |
312
364
  | `409 session_finished` | The session is complete. | Create a new session. |
313
365
  | `410 session_expired` | 60 minutes passed without a refresh, or 12 hours in all. (`GoneError`) | Create a new session. |
314
366
  | `403 insufficient_scope` | The key lacks `online-training:embed:create` or `occupational-health:embed:create`. | Add the scope on the Developer page. |
367
+ | `403 api_access_*` | An OH embed session needs the Hub's approval for Occupational Health (live keys). | See [Approval for sensitive areas](#approval-for-sensitive-areas). |
315
368
 
316
369
  The `error` event of `mount` (what the frame or the SDK reports; `embedErrorHint(code)` returns the text):
317
370
 
@@ -323,12 +376,111 @@ The `error` event of `mount` (what the frame or the SDK reports; `embedErrorHint
323
376
  | `frame_invalid` | The frame was not opened by the SDK (your own iframe, or a copied URL). |
324
377
  | `origin_not_allowed` | This page is not the origin the session was created for, or the origin is not registered. |
325
378
  | `not_allowed` | The content can only be opened through the SDK from the right website. |
379
+ | `terms_required` | The candidate has not accepted the terms. The frame shows them first and nothing else opens until they do (see `terms-accepted`). |
380
+ | `access_expired` | The candidate's access ended while they were working. Renew it, then create a new session. |
381
+ | `course_access_required`, `payment_pending`, `renewal_approval_required`, `course_not_pending` | Your embed route refused to create the session. With `hb.embed.handler()` the page gets the code and `details` here; see the table above. |
326
382
  | `session_expired`, `session_finished`, `not_found` | See the table above. |
327
383
  | `network` | The frame could not reach the Hub. |
328
384
  | `frame_timeout` | The frame never started. A session that expired, finished or was made for another origin shows an error page inside the frame but sends the page nothing, so this is how you find out. |
329
385
  | `origin_mismatch` | The session's `allowedOrigin` is not this page's origin. Pass this page's origin when your server creates the session. |
330
386
  | `session_failed`, `session_changed`, `token_refresh_failed`, `init_failed` | Your route failed or returned the wrong thing. Check its response in the network tab. |
331
387
 
388
+ ## Access, payment and renewal
389
+
390
+ An embed opens nothing the Hub account would not open. Before a candidate can use a course in the frame, three things must be true: they have accepted the terms, their **training access is started**, and (for a course they have finished before) their access has not ended. Your server starts access through the API; the frame never takes payment and never starts access itself.
391
+
392
+ ### Start access
393
+
394
+ ```ts
395
+ import { accessStartResult } from '@healthier-business/hub-sdk';
396
+
397
+ const res = await hb.onlineTraining.candidates.accessStart(
398
+ { candidate_ref, body: { return_url: 'https://learn.example.com/training' } },
399
+ { idempotencyKey: `start-access-${order.id}` }, // your own id for this start
400
+ );
401
+ const result = accessStartResult(res.data); // typed: switch on result.outcome
402
+ ```
403
+
404
+ Hub decides who pays each course group (the group's setting, else the candidate's charge); the request cannot change it, and a candidate-paid group is never paid from your credits. The three outcomes:
405
+
406
+ | `outcome` | Meaning | What you do |
407
+ | --- | --- | --- |
408
+ | `enabled` | Your credits were taken (or the groups were free) and access is on. `credits_charged`, `balance_after` and the `groups` with their `expires_at` are in the answer. | Create the embed session. |
409
+ | `payment_required` | The candidate pays. `payment.url` is a **one-time payment link**, a Hub page; `payment.id`, `expires_at` (7 days), `amount_gross_pence` and the groups come with it. Nothing was started. | Give `payment.url` to the candidate (email, your page, a button). The link is shown **only in this answer** and cannot be read again. Wait for the webhook below. |
410
+ | `partial` | The same, and the groups your account pays were started (`started`). | As `payment_required`; those groups are already usable. |
411
+ | `none` | Nothing needed access, or another call just started it. Nothing was charged. | Create the embed session. |
412
+
413
+ A new link for the same candidate replaces the old one (it becomes `superseded`). Read one link's status (`pending`, `paid`, `expired`, `superseded`, `refunded`, `cancelled`) with `hb.onlineTraining.candidates.accessPayment({ candidate_ref, payment_id })`, and the candidate's current state per course group, the terms and the renewal with `hb.onlineTraining.candidates.access({ candidate_ref })`. The candidate agrees to the payment terms on the Hub page and pays through HB Pay; only HB Pay's confirmation switches access on, never the page the candidate returns to.
414
+
415
+ `accessStart` errors are the usual `ApiError`s: `InsufficientCreditsError` (402, nothing charged), `409 renewal_list_required`, `409 renewal_approval_required`, `503 payments_unavailable` (card payments are not set up: no link was made and nothing was started), `422` for a bad `group_ids`, `months` or `return_url` (it must be on one of your registered origins).
416
+
417
+ **Idempotency.** Send your own `Idempotency-Key` (`{ idempotencyKey }` as above), so that retrying after a lost answer starts and charges once. The SDK adds a random one when you do not, which protects only its own automatic retries. The same key and body within 24 hours returns the first answer without charging again (`Idempotent-Replayed: true`). A second call with a new key finds nothing left to start and answers `none`. Limits: 30 calls a minute per key, 5 a minute per candidate.
418
+
419
+ ### When the embed refuses
420
+
421
+ `hb.embed.createCourseSession`, `createTestSession` and the handler refuse a candidate whose access is not in place with a **409 `EmbedAccessError`** (a `ConflictError`). Nothing is charged and nothing is started by a refused session. `error.access` (also `error.details`) says what to do:
422
+
423
+ | `code` | `access.state` | `access.next` | Do this |
424
+ | --- | --- | --- | --- |
425
+ | `course_access_required` | `not_started` | `start_access` | `accessStart()`. |
426
+ | `payment_pending` | `payment_pending` | `pay` | The candidate pays the link you gave them. |
427
+ | `renewal_approval_required` | `awaiting_approval` | `await_approval` | Approve the renewal. |
428
+ | `access_expired` | `expired` | `renew` | Renew with `accessStart()` (or `renewalRequest()` when renewals need approval). |
429
+
430
+ `access.payer` is `client` (your credits) or `candidate`. Every field is optional: one the Hub did not send is left out.
431
+
432
+ ```ts
433
+ import { isEmbedAccessError } from '@healthier-business/hub-sdk';
434
+
435
+ try {
436
+ session = await hb.embed.createCourseSession({ candidateRef, courseId, origin });
437
+ } catch (e) {
438
+ if (!isEmbedAccessError(e)) throw e;
439
+ if (e.access.next === 'start_access') await startAccessFor(candidateRef);
440
+ else tellTheCandidate(e.code, e.hint);
441
+ }
442
+ ```
443
+
444
+ With `hb.embed.handler()` you write none of that: the route passes these four codes and `course_not_pending` to the page as `{ error, message, hint, requestId, details }` (and nothing else from the Hub), `mount()` does not create a frame, and `onError` and `ready` report them:
445
+
446
+ ```ts
447
+ HealthierBusiness.mount(el, {
448
+ endpoint: '/api/hb/embed', kind: 'course', courseId: 12,
449
+ onError: ({ code, details }) => {
450
+ if (code === 'payment_pending') showMessage('Please pay with the link we sent you.');
451
+ else if (code === 'course_access_required') askServerToStartAccess(details?.next);
452
+ },
453
+ });
454
+ ```
455
+
456
+ ### Terms in the frame
457
+
458
+ The first screen of every frame (course, test and OH form) is the Hub terms for a candidate who has not accepted the current version; nothing else opens until they do, and a new version asks again. Acceptance is recorded by the Hub with its evidence. **No API can accept the terms for a candidate**, you can only read the `terms` block of `access()`. Your page hears `terms-accepted` (`onTermsAccepted({ version, acceptedAt })`) and your server the webhook `online-training.terms.accepted`. A frame call made before acceptance is refused and the page gets the `terms_required` error event.
459
+
460
+ ### Renewals
461
+
462
+ When a course is due for renewal, `hb.onlineTraining.candidates.renewal`, `renewalRequest`, `renewalApprove` and `renewalDecline` (and `hb.onlineTraining.renewals.list`) read and decide it; the scopes are `online-training:renewals:read` and `:write`. Approving takes credits and grants access again. Embedding a candidate whose manual renewal is not approved answers `renewal_approval_required`, and records the request once.
463
+
464
+ ### Webhooks to listen for
465
+
466
+ | Event | When |
467
+ | --- | --- |
468
+ | `online-training.access.started` | Access was switched on, by credits, free groups, **candidate payment** (`source: "payment"`) or a renewal. Create the embed session when you see it for your candidate. |
469
+ | `online-training.access.payment_link.expired` | A payment link ran out unpaid: start access again for a new one. |
470
+ | `online-training.access.revoked` | A paid access was taken back (for example a refund). |
471
+ | `online-training.terms.accepted` | The candidate accepted the terms. |
472
+ | `online-training.renewal.requested`, `.approved`, `.declined` | The renewal request moved. |
473
+
474
+ They are verified and typed by `hb.webhooks.constructEvent` like every other event. Webhooks carry `candidate_ref`, never names or emails.
475
+
476
+ ### Do not trust browser events
477
+
478
+ Events such as `passed`, `completed` and `submitted` reach your page from a frame, and **a person at the browser can forge them**. Use them to update the screen. Before you issue your own certificate, record a result or grant anything, confirm it with the API (`hb.onlineTraining.candidates.results`) or a webhook on your server.
479
+
480
+ ### Sandbox
481
+
482
+ The sandbox demo candidates for each access state (enabled, payment link, renewal approval) are described in the documentation: <https://dev.hbcompliance.co.uk/sdk-overview>.
483
+
332
484
  ## Sandbox
333
485
 
334
486
  The sandbox is a safe copy of the Hub API with demo data, so you can build and test the embed without a real candidate, course or form. It is run by the Healthier Business developer platform, not by the Hub: a sandbox key never reaches the real Hub and nothing is sent or charged.
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The answer of `hb.onlineTraining.candidates.accessStart()`, typed. The OpenAPI document describes it as a list of unknowns, so
3
+ * these types are written by hand from the Hub's documented body (`outcome` and the fields each outcome adds). This file does not
4
+ * depend on the generated files, so syncing the spec never touches it.
5
+ */
6
+ export interface AccessStartGroup {
7
+ group_id: number;
8
+ title: string;
9
+ /** ISO 8601 UTC: when the access ends. */
10
+ expires_at: string;
11
+ }
12
+ /** The one-time link for the groups the candidate pays for. `url` is shown only in the start answer: store it or hand it over at once. */
13
+ export interface AccessStartPayment {
14
+ /** Use it to read the link's status and to match the `access.started`, `access.payment_link.expired` and `access.revoked` webhooks. */
15
+ id: string;
16
+ /** A Hub page to give to the candidate. Works until paid or expired; a newer link for the same candidate replaces it. */
17
+ url: string;
18
+ /** ISO 8601 UTC. */
19
+ expires_at: string;
20
+ /** What the candidate would pay now, in pence including VAT. */
21
+ amount_gross_pence: number;
22
+ currency: 'GBP';
23
+ /** 12, or 24 when the account allows it and it was asked for. */
24
+ months: number;
25
+ groups: {
26
+ group_id: number;
27
+ title: string;
28
+ gross_pence: number;
29
+ }[];
30
+ }
31
+ interface Started {
32
+ credits_charged: number;
33
+ balance_after: number;
34
+ groups: AccessStartGroup[];
35
+ }
36
+ /**
37
+ * - `enabled`: switched on by this call (credits taken or free groups opened).
38
+ * - `none`: nothing needed access, or another call had just started it. Nothing was charged.
39
+ * - `payment_required`: the candidate pays: give them `payment.url`. Nothing was started.
40
+ * - `partial`: the same, and the groups your account pays were started (`started`).
41
+ */
42
+ export type AccessStartResult = ({
43
+ outcome: 'enabled';
44
+ } & Started) | {
45
+ outcome: 'none';
46
+ } | {
47
+ outcome: 'payment_required';
48
+ payment: AccessStartPayment;
49
+ started: Started;
50
+ } | {
51
+ outcome: 'partial';
52
+ payment: AccessStartPayment;
53
+ started: Started;
54
+ };
55
+ /**
56
+ * Types the `data` of an `accessStart` answer: `accessStartResult((await hb.onlineTraining.candidates.accessStart(...)).data)`.
57
+ * Throws a TypeError if the Hub answered with an outcome this version does not know, so a new outcome is never mistaken for success.
58
+ */
59
+ export declare function accessStartResult(data: unknown): AccessStartResult;
60
+ export {};
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /**
3
+ * The answer of `hb.onlineTraining.candidates.accessStart()`, typed. The OpenAPI document describes it as a list of unknowns, so
4
+ * these types are written by hand from the Hub's documented body (`outcome` and the fields each outcome adds). This file does not
5
+ * depend on the generated files, so syncing the spec never touches it.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.accessStartResult = accessStartResult;
9
+ /**
10
+ * Types the `data` of an `accessStart` answer: `accessStartResult((await hb.onlineTraining.candidates.accessStart(...)).data)`.
11
+ * Throws a TypeError if the Hub answered with an outcome this version does not know, so a new outcome is never mistaken for success.
12
+ */
13
+ function accessStartResult(data) {
14
+ const d = data;
15
+ const outcome = d && typeof d === 'object' ? d.outcome : undefined;
16
+ if (outcome === 'enabled' || outcome === 'none')
17
+ return data;
18
+ if ((outcome === 'payment_required' || outcome === 'partial') && typeof d?.payment?.url === 'string')
19
+ return data;
20
+ throw new TypeError(`The Hub answered access/start with an outcome this SDK version does not know (${JSON.stringify(outcome)}). Update the SDK.`);
21
+ }
@@ -1,9 +1,9 @@
1
1
  import { mount } from './mount.js';
2
2
  export { mount, sessionFetcher, SANDBOX, ALLOW, type EmbedController, type MountOptions, type SessionRequest } from './mount.js';
3
- export { embedErrorHint, isEmbedSession, PROTOCOL_VERSION, type EmbedErrorCode, type EmbedEventMap, type EmbedEventName, type EmbedKind, type EmbedSession, type FrameMessage, type ParentMessage } from '../embed/protocol.js';
3
+ export { cleanAccessDetails, EMBED_ACCESS_CODES, embedErrorHint, isEmbedSession, PROTOCOL_VERSION, type EmbedAccessCode, type EmbedAccessDetails, type EmbedAccessNext, type EmbedAccessState, type EmbedErrorCode, type EmbedEventMap, type EmbedEventName, type EmbedKind, type EmbedSession, type FrameMessage, type ParentMessage } from '../embed/protocol.js';
4
4
  /** `HealthierBusiness.mount(element, options)` for the browser. It holds no API key and cannot make API calls. */
5
5
  export declare const HealthierBusiness: {
6
6
  readonly mount: typeof mount;
7
- readonly version: "0.1.1";
7
+ readonly version: "0.3.0";
8
8
  };
9
- export declare const version = "0.1.1";
9
+ export declare const version = "0.3.0";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.version = exports.HealthierBusiness = exports.PROTOCOL_VERSION = exports.isEmbedSession = exports.embedErrorHint = exports.ALLOW = exports.SANDBOX = exports.sessionFetcher = exports.mount = void 0;
3
+ exports.version = exports.HealthierBusiness = exports.PROTOCOL_VERSION = exports.isEmbedSession = exports.embedErrorHint = exports.EMBED_ACCESS_CODES = exports.cleanAccessDetails = exports.ALLOW = exports.SANDBOX = exports.sessionFetcher = exports.mount = void 0;
4
4
  const mount_js_1 = require("./mount.js");
5
5
  const version_js_1 = require("../version.js");
6
6
  var mount_js_2 = require("./mount.js");
@@ -9,6 +9,8 @@ Object.defineProperty(exports, "sessionFetcher", { enumerable: true, get: functi
9
9
  Object.defineProperty(exports, "SANDBOX", { enumerable: true, get: function () { return mount_js_2.SANDBOX; } });
10
10
  Object.defineProperty(exports, "ALLOW", { enumerable: true, get: function () { return mount_js_2.ALLOW; } });
11
11
  var protocol_js_1 = require("../embed/protocol.js");
12
+ Object.defineProperty(exports, "cleanAccessDetails", { enumerable: true, get: function () { return protocol_js_1.cleanAccessDetails; } });
13
+ Object.defineProperty(exports, "EMBED_ACCESS_CODES", { enumerable: true, get: function () { return protocol_js_1.EMBED_ACCESS_CODES; } });
12
14
  Object.defineProperty(exports, "embedErrorHint", { enumerable: true, get: function () { return protocol_js_1.embedErrorHint; } });
13
15
  Object.defineProperty(exports, "isEmbedSession", { enumerable: true, get: function () { return protocol_js_1.isEmbedSession; } });
14
16
  Object.defineProperty(exports, "PROTOCOL_VERSION", { enumerable: true, get: function () { return protocol_js_1.PROTOCOL_VERSION; } });
@@ -36,6 +36,8 @@ export interface MountOptions {
36
36
  onPassed?: (data: EmbedEventMap['passed']) => void;
37
37
  onFailed?: (data: EmbedEventMap['failed']) => void;
38
38
  onSubmitted?: (data: EmbedEventMap['submitted']) => void;
39
+ /** The candidate accepted the Hub terms in the frame. */
40
+ onTermsAccepted?: (data: EmbedEventMap['terms-accepted']) => void;
39
41
  onError?: (error: EmbedEventMap['error']) => void;
40
42
  /**
41
43
  * The frame asks for the top of its content to be in view when the learner moves to another lesson or page. By default the SDK
@@ -53,8 +53,12 @@ function sessionFetcher(options) {
53
53
  body: JSON.stringify(reason === 'refresh' ? { action: 'refresh', sessionId } : { action: 'create', kind, courseId, formShortcode }),
54
54
  });
55
55
  const body = (await res.json().catch(() => ({})));
56
- if (!res.ok)
57
- throw new Error(typeof body.message === 'string' ? body.message : `Your server answered HTTP ${res.status}.`);
56
+ if (!res.ok) {
57
+ const message = typeof body.message === 'string' ? body.message : `Your server answered HTTP ${res.status}.`;
58
+ // A refusal from the Hub that the page can act on (the access errors, course_not_pending) keeps its code and details.
59
+ const code = typeof body.error === 'string' && protocol_js_1.EMBED_SESSION_ERROR_CODES.includes(body.error) ? body.error : undefined;
60
+ throw Object.assign(new Error(message), code ? { code, details: (0, protocol_js_1.cleanAccessDetails)(body.details) } : {});
61
+ }
58
62
  return body;
59
63
  };
60
64
  }
@@ -107,16 +111,19 @@ function mount(element, options) {
107
111
  case 'submitted':
108
112
  options.onSubmitted?.(d);
109
113
  break;
114
+ case 'terms-accepted':
115
+ options.onTermsAccepted?.(d);
116
+ break;
110
117
  case 'error':
111
118
  options.onError?.(d);
112
119
  break;
113
120
  }
114
121
  handlers.get(name)?.forEach((h) => h(d));
115
122
  };
116
- const fail = (code, message) => {
123
+ const fail = (code, message, details) => {
117
124
  win.clearTimeout(readyTimer);
118
125
  rejectReady(new Error(message));
119
- emit('error', { code, message: message || (0, protocol_js_1.embedErrorHint)(code) });
126
+ emit('error', { code, message: message || (0, protocol_js_1.embedErrorHint)(code), ...(details ? { details } : {}) });
120
127
  };
121
128
  const waitForFrame = () => {
122
129
  win.clearTimeout(readyTimer);
@@ -260,6 +267,11 @@ function mount(element, options) {
260
267
  element.appendChild(iframe);
261
268
  }
262
269
  catch (e) {
270
+ const known = e?.code;
271
+ if (typeof known === 'string' && protocol_js_1.EMBED_SESSION_ERROR_CODES.includes(known)) {
272
+ fail(known, e.message || (0, protocol_js_1.embedErrorHint)(known) || known, (0, protocol_js_1.cleanAccessDetails)(e.details));
273
+ return;
274
+ }
263
275
  fail('session_failed', e instanceof Error ? e.message : 'Could not get a session from your server.');
264
276
  }
265
277
  })();
@@ -1,3 +1,4 @@
1
+ import { type EmbedAccessDetails, type EmbedAccessNext } from '../embed/protocol.js';
1
2
  export interface RateLimitInfo {
2
3
  /** Calls the key may make per hour. */
3
4
  limit?: number;
@@ -29,31 +30,84 @@ export declare class ApiError extends HubError {
29
30
  readonly requestId: string | undefined;
30
31
  readonly retryAfterSeconds: number | undefined;
31
32
  readonly rateLimit: RateLimitInfo;
33
+ /** The whole error body as the Hub sent it, for the extra fields some codes carry (`areas`, `docs_url`, `events`). */
34
+ readonly body: Record<string, unknown>;
32
35
  constructor(
33
36
  /** HTTP status. */
34
37
  status: number,
35
38
  /** Stable snake_case code to program against, for example `not_found` or `insufficient_scope`. */
36
39
  code: string, message: string,
37
40
  /** The `details` object (for a 422 it maps each field to its messages). */
38
- details: unknown, requestId: string | undefined, retryAfterSeconds: number | undefined, rateLimit?: RateLimitInfo);
41
+ details: unknown, requestId: string | undefined, retryAfterSeconds: number | undefined, rateLimit?: RateLimitInfo,
42
+ /** The whole error body as the Hub sent it, for the extra fields some codes carry (`areas`, `docs_url`, `events`). */
43
+ body?: Record<string, unknown>);
39
44
  /** A plain-words next step for the codes people hit most, or undefined. */
40
45
  get hint(): string | undefined;
41
46
  toJSON(): Record<string, unknown>;
42
47
  }
43
48
  /** Next steps for error codes, shown by `ApiError.hint` and used in the README troubleshooting table. */
44
49
  export declare const CODE_HINTS: Record<string, string>;
50
+ /** What to do for each `details.next` of an access error. */
51
+ export declare const NEXT_HINTS: Record<EmbedAccessNext, string>;
45
52
  /** 401: the token was refused even after renewing it, or the API key is wrong. */
46
53
  export declare class AuthenticationError extends ApiError {
47
54
  }
48
55
  /** 403: the key may not do this (`insufficient_scope`, `portal_unavailable`, `key_inactive`, `ip_not_allowed`). */
49
56
  export declare class PermissionError extends ApiError {
50
57
  }
58
+ /** The four codes of a call refused because the area needs the Hub's manual approval and the client does not have it. */
59
+ export declare const API_ACCESS_CODES: readonly ["api_access_not_approved", "api_access_pending", "api_access_rejected", "api_access_revoked"];
60
+ export type ApiAccessCode = (typeof API_ACCESS_CODES)[number];
61
+ /** The states of an area that needs approval, as `hb.account.apiAccess.get()` reports them (`not_requested` when nothing was asked). */
62
+ export type ApiAccessRefusal = 'not_requested' | 'pending' | 'rejected' | 'revoked';
63
+ /**
64
+ * 403 `api_access_not_approved`, `api_access_pending`, `api_access_rejected` or `api_access_revoked`: the key holds a scope of an area
65
+ * that needs the Hub's manual approval (by default Occupational Health and DBS & Right To Work) and your organisation does not have it.
66
+ * Not retryable: retrying changes nothing until the state does. Live keys only; the sandbox is always open.
67
+ */
68
+ export declare class ApiAccessError extends PermissionError {
69
+ /** The portal keys involved, for example `['occupational-health']`. */
70
+ get areas(): string[];
71
+ /** Where to read more about the approval. */
72
+ get docsUrl(): string | undefined;
73
+ /** Where your organisation stands, matching the `status` of `hb.account.apiAccess.get()`. */
74
+ get state(): ApiAccessRefusal;
75
+ toJSON(): Record<string, unknown>;
76
+ /** Always false: do not loop on this error. Ask for, or follow up, the approval in the Hub under Developer > API access. */
77
+ get retryable(): false;
78
+ }
79
+ /** True for an `ApiAccessError` (any of the four `api_access_*` codes). */
80
+ export declare function isApiAccessError(error: unknown): error is ApiAccessError;
81
+ /**
82
+ * 403 `webhook_events_not_approved`: a webhook endpoint was created or updated with events of an area that needs approval your
83
+ * organisation does not hold. `events` lists the offending event names and `areas` their portal keys. Nothing was saved.
84
+ */
85
+ export declare class WebhookEventsNotApprovedError extends PermissionError {
86
+ /** The portal keys involved. */
87
+ get areas(): string[];
88
+ /** The event names that were refused, for example `['occupational-health.request.submitted']`. */
89
+ get events(): string[];
90
+ get docsUrl(): string | undefined;
91
+ get retryable(): false;
92
+ }
93
+ /** True for a `WebhookEventsNotApprovedError`. */
94
+ export declare function isWebhookEventsNotApprovedError(error: unknown): error is WebhookEventsNotApprovedError;
51
95
  /** 404. */
52
96
  export declare class NotFoundError extends ApiError {
53
97
  }
54
98
  /** 409: a taken slot, or an idempotency key reused with a different body. */
55
99
  export declare class ConflictError extends ApiError {
56
100
  }
101
+ /**
102
+ * 409 when the Hub will not create an embed session because the candidate's access is not in place: `course_access_required`,
103
+ * `payment_pending`, `renewal_approval_required` or `access_expired`. `access` says what to do next. Nothing was charged or started.
104
+ */
105
+ export declare class EmbedAccessError extends ConflictError {
106
+ /** `{ state, payer, next }` from the Hub. Unknown fields and values are dropped. */
107
+ get access(): EmbedAccessDetails;
108
+ }
109
+ /** True for an `EmbedAccessError`. */
110
+ export declare function isEmbedAccessError(error: unknown): error is EmbedAccessError;
57
111
  /** 402: not enough credits or balance. Nothing was charged. */
58
112
  export declare class InsufficientCreditsError extends ApiError {
59
113
  }
@@ -96,4 +150,4 @@ export declare class EmbedError extends HubError {
96
150
  readonly status?: number | undefined;
97
151
  constructor(message: string, code: string, status?: number | undefined);
98
152
  }
99
- export declare function apiErrorFrom(status: number, code: string, message: string, details: unknown, requestId: string | undefined, retryAfter: number | undefined, rateLimit: RateLimitInfo): ApiError;
153
+ export declare function apiErrorFrom(status: number, code: string, message: string, details: unknown, requestId: string | undefined, retryAfter: number | undefined, rateLimit: RateLimitInfo, body?: Record<string, unknown>): ApiError;