@unisim/assess-kit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +223 -0
  2. package/dist/evidence.d.ts +102 -0
  3. package/dist/evidence.d.ts.map +1 -0
  4. package/dist/evidence.js +241 -0
  5. package/dist/evidence.js.map +1 -0
  6. package/dist/export-gate.d.ts +184 -0
  7. package/dist/export-gate.d.ts.map +1 -0
  8. package/dist/export-gate.js +320 -0
  9. package/dist/export-gate.js.map +1 -0
  10. package/dist/hub.d.ts +67 -0
  11. package/dist/hub.d.ts.map +1 -0
  12. package/dist/hub.js +60 -0
  13. package/dist/hub.js.map +1 -0
  14. package/dist/index.d.ts +8 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +10 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/pdf-fold.d.ts +20 -0
  19. package/dist/pdf-fold.d.ts.map +1 -0
  20. package/dist/pdf-fold.js +51 -0
  21. package/dist/pdf-fold.js.map +1 -0
  22. package/dist/pdf-fonts.d.ts +49 -0
  23. package/dist/pdf-fonts.d.ts.map +1 -0
  24. package/dist/pdf-fonts.js +84 -0
  25. package/dist/pdf-fonts.js.map +1 -0
  26. package/dist/platform.d.ts +14 -0
  27. package/dist/platform.d.ts.map +1 -0
  28. package/dist/platform.js +30 -0
  29. package/dist/platform.js.map +1 -0
  30. package/dist/react/evidence.d.ts +78 -0
  31. package/dist/react/evidence.d.ts.map +1 -0
  32. package/dist/react/evidence.js +148 -0
  33. package/dist/react/evidence.js.map +1 -0
  34. package/dist/react/index.d.ts +4 -0
  35. package/dist/react/index.d.ts.map +1 -0
  36. package/dist/react/index.js +6 -0
  37. package/dist/react/index.js.map +1 -0
  38. package/dist/react/purchase.d.ts +40 -0
  39. package/dist/react/purchase.d.ts.map +1 -0
  40. package/dist/react/purchase.js +81 -0
  41. package/dist/react/purchase.js.map +1 -0
  42. package/dist/react/wizard.d.ts +85 -0
  43. package/dist/react/wizard.d.ts.map +1 -0
  44. package/dist/react/wizard.js +138 -0
  45. package/dist/react/wizard.js.map +1 -0
  46. package/dist/save-file.d.ts +28 -0
  47. package/dist/save-file.d.ts.map +1 -0
  48. package/dist/save-file.js +121 -0
  49. package/dist/save-file.js.map +1 -0
  50. package/package.json +83 -0
package/README.md ADDED
@@ -0,0 +1,223 @@
1
+ # @unisim/assess-kit
2
+
3
+ What every Assess app shares: saving a file on the web and in the phone app, PDF
4
+ fonts, the server export gate, the evidence locker, and the wizard shell. One
5
+ copy instead of five.
6
+
7
+ ```bash
8
+ npm install @unisim/assess-kit
9
+ ```
10
+
11
+ ```ts
12
+ import { saveFile, issueAssessExport, officialFooter, hubLoginHref } from '@unisim/assess-kit'
13
+ import { useUnsavedChanges, useWizardSteps, SaveStatus } from '@unisim/assess-kit/react'
14
+ ```
15
+
16
+ The root entry has no framework in it. `@unisim/assess-kit/react` holds the
17
+ hooks and one component, and works with React 18 or 19. The package itself
18
+ depends on nothing; React and the two Capacitor plugins are optional peers.
19
+
20
+ ## Why this package exists
21
+
22
+ Workplace, Cyber, Risk, Fire and COSHH Assess each carried their own copy of the
23
+ same code. The copies drifted, and fixes had to be carried from app to app by
24
+ hand. On 2026-10-04 a sweep found three of these gaps still open:
25
+
26
+ - **Fire and COSHH** showed "See plans" and "Buy this report" inside the phone
27
+ app. App Store rule 3.1.1 and Play's payments policy forbid that. The other
28
+ three apps already hid both.
29
+ - **Cyber**'s "Sign in to import your branding" link sent no `?return=`, so
30
+ signing in landed you on the Assess portal instead of back in Cyber.
31
+ - **Cyber**'s one-question-per-screen flow dropped keyboard focus to `<body>`
32
+ when the button you pressed went away with the old question. The other three
33
+ wizards already moved focus to the new step.
34
+
35
+ The export gate also existed in three shapes. One returned a result and never
36
+ threw. One threw. One handed back the server's raw snake_case reply. The phone
37
+ upload token format (`<token>_<ts>-<name>`, required by platform migration 0239)
38
+ lived in two hand-synced files.
39
+
40
+ ## API
41
+
42
+ ### Saving a file — `saveFile(opts) → 'shared' | 'downloaded' | 'cancelled'`
43
+
44
+ `<a download>` (which is also what jsPDF's `doc.save()` does) and
45
+ `window.print()` do nothing inside a Capacitor web view. `saveFile` picks the
46
+ right route for each platform:
47
+
48
+ - **Phone app:** writes the file with `@capacitor/filesystem`, then opens the
49
+ share sheet with `@capacitor/share`.
50
+ - **Touch browser:** uses `navigator.share({ files })`.
51
+ - **Anywhere else:** falls back to `<a download>`.
52
+
53
+ Pass `{ blob | data, filename, mimeType?, title? }`. Related exports:
54
+ `safeFileName`, `toBlob`, `blobToBase64`.
55
+
56
+ ### Where the app is running
57
+
58
+ - `isNativeApp()` is true inside the Capacitor shell. ⚠️ No purchase routes may
59
+ be shown when it is true.
60
+ - `isTouchDevice()` and `prefersReducedMotion()` are also exported.
61
+
62
+ ### PDF fonts
63
+
64
+ **jsPDF:**
65
+
66
+ ```ts
67
+ import regular from './assets/fonts/NotoSans-Regular.ttf?url'
68
+ import bold from './assets/fonts/NotoSans-Bold.ttf?url'
69
+
70
+ const fonts = createPdfFontLoader(notoSansFaces({ regular, bold }))
71
+ await fonts.embed(doc) // registers every face as 'NotoSans' and selects it
72
+ ```
73
+
74
+ - The font files stay in the app, so that Vite's `?url` import puts them under
75
+ the app's base path.
76
+ - Each face is fetched once per page load. A failed fetch is not cached, so the
77
+ next export tries again.
78
+ - `pdfText(s)` removes the emoji, flags and joiners that the subset can't draw.
79
+
80
+ **pdf-lib** (Helvetica, which throws on anything outside WinAnsi):
81
+
82
+ ```ts
83
+ const font = await embedSafeFont(doc, StandardFonts.Helvetica)
84
+ ```
85
+
86
+ `embedSafeFont` patches `encodeText` and `widthOfTextAtSize` so that any
87
+ character the font lacks is folded instead of throwing. It tries each of these
88
+ in turn:
89
+
90
+ 1. The NFKC form: `₂` becomes `2`.
91
+ 2. The base letter: "Tŷ Gwyn" prints as "Ty Gwyn".
92
+ 3. A plain-text stand-in: `ł` becomes `l`, `≤` becomes `<=`.
93
+ 4. `?`.
94
+
95
+ `foldText(text, has)` and `makeFontSafe(font)` expose the same logic directly.
96
+
97
+ ### The export gate (platform 0215 / 0218)
98
+
99
+ ```ts
100
+ const res = await issueAssessExport(supabase, {
101
+ product: ASSESS_PRODUCTS.fire, orgId, assessmentRef: row.id, docName, data: row,
102
+ session, // optional: guests get not_signed_in without a round trip
103
+ })
104
+ if (!res.ok) return showBlocked(res.error, res.offer) // 'not_signed_in' | 'no_company' | 'not_entitled' | 'failed'
105
+ buildPdf({ footer: officialFooter(res.certId, { draft: row.status !== 'complete' }) })
106
+ ```
107
+
108
+ The gate never throws. It also fails closed: a reply of `ok` that carries no
109
+ certificate counts as `failed`. A refusal comes with a normalised
110
+ `ReportOffer`: `{ canBuy, pricePence, fullPricePence, onOffer, offerEndsAt }`.
111
+
112
+ Related functions:
113
+
114
+ - **Server calls:**
115
+ - `startReportPurchase(supabase, { product, assessmentRef, orgId })` returns
116
+ one of these:
117
+ - `{ kind: 'pay', paymentUrl }` (https only)
118
+ - `{ kind: 'already_paid' }`
119
+ - `{ kind: 'refused', error }`
120
+ - `{ kind: 'failed' }`
121
+ - `assessExportAllowed`, `hasPaidReport` (filtered on the user, because RLS
122
+ lets the platform admin read everyone's purchases), `fetchReportOffer` and
123
+ `redeemAccessCode`.
124
+ - **Report text:**
125
+ - `certificateLine(certId)`, `verifyUrl(certId)` and
126
+ `officialFooter(certId, { draft })`.
127
+ - `DRAFT_PREFIX` is `"DRAFT — not yet complete · "`.
128
+ - **Formatting:**
129
+ - `formatPence` gives "£10" or "£10.50" in English.
130
+ - `formatPounds(pence, locale)` formats with `Intl`.
131
+ - `offerLastDay(endsAt, locale)` gives the day before the end, in UK time.
132
+ Plain `en` is treated as `en-GB`.
133
+ - `offerLine(offer)` gives the English line shown under the Buy button.
134
+ - **File names:**
135
+ - `fileSlug(s, { ascii?, fallback? })`: by default it keeps letters in any
136
+ script; `ascii` folds to base letters.
137
+ - `fileDate()`.
138
+ - **Hashing:**
139
+ - `stableJson(value)` sorts keys at every level, honours `toJSON` (so Dates
140
+ are kept) and otherwise follows JSON's rules.
141
+ - `sha256Hex(text)` returns `null` where `crypto.subtle` is missing.
142
+
143
+ ### The hub
144
+
145
+ `HUB_URL`, `HUB_LOGIN_URL`, `PLANS_URL` and `COMPANY_SETUP_URL` are exported as
146
+ constants.
147
+
148
+ - `hubLoginHref(returnTo?)` builds a sign-in link that brings the user back:
149
+ the hub reads `?return=`.
150
+ - `isSignedIn(session)` is true only when the session has a user who is not
151
+ anonymous. The apps sign every visitor in anonymously, so having a session is
152
+ not the same as being signed in.
153
+
154
+ ### The evidence locker (`assess-evidence` bucket, platform 0037 / 0239)
155
+
156
+ Files are stored at `<org>/<assessment>/<ts>-<name>`. Phone uploads are stored
157
+ at `<org>/<assessment>/<token>_<ts>-<name>`: since 0239, the storage policy
158
+ reads the token from the object name.
159
+
160
+ Functions:
161
+
162
+ - **Files:** `uploadEvidence(supabase, orgId, assessmentId, file, { token? })`,
163
+ `listEvidence`, `signedEvidenceUrl`, `deleteEvidence`.
164
+ - **Phone tokens:** `mintEvidenceToken({ app, orgId, assessmentId, userId })`,
165
+ `revokeEvidenceToken`, `resolveEvidenceToken`,
166
+ `evidenceMobileUrl(token, { base })`.
167
+ - **Storage use:** `orgStorageUsage`, `usageLevel`.
168
+ - **Names:**
169
+ - `evidenceObjectName` builds the name a file is stored under.
170
+ - `evidenceDisplayName` strips the token and timestamp for display.
171
+ - `safeEvidenceName` cleans up an upload's file name.
172
+ - **Checks and formatting:** `checkEvidenceFile` (catches size and type
173
+ problems before a long upload), `fmtBytes`, `isImageMime`.
174
+ - **Token cache:** `readCachedEvidenceToken` and `writeCachedEvidenceToken`.
175
+ They survive a `localStorage` that throws.
176
+
177
+ ### React (`@unisim/assess-kit/react`)
178
+
179
+ - **`useUnsavedChanges(value)`** returns `{ dirty, markSaved(v), confirmLeave(msg?) }`.
180
+ While there are unsaved changes, the browser warns before the tab closes or
181
+ reloads.
182
+ - **`useWizardSteps(count)`** returns
183
+ `{ step, goStep, next, back, setStep, isFirst, isLast, stepRef }`. Moving
184
+ between steps puts focus on the new step and scrolls it into view.
185
+ - **`useFocusOnChange(key, { onlyIfLost?, scroll? })`** returns a ref, and
186
+ moves focus to that element when `key` changes. Use it for flows whose
187
+ Back/Next buttons persist (Cyber's QuestionFlow).
188
+ - **`useSavedFlash(ms)`** and **`<SaveStatus saved dirty canSave />`** show
189
+ "Saved." / "Unsaved changes" in a polite live region.
190
+ - **`useReportPurchase({ offer, enabled, start, downloadAgain })`** runs the
191
+ "Buy this report" state machine: idle → starting → waiting ⇄ checking. It
192
+ opens the payment page in a new tab. Pass `enabled: !isNativeApp()`.
193
+ - **`useEvidenceLocker({ supabase, app, orgId, assessmentId, userId, base })`**
194
+ handles the locker: listing, upload, delete, usage, and the QR handoff with a
195
+ remembered phone link. While the QR panel is open it polls for new files,
196
+ and stops while the tab is hidden.
197
+ - **`usePhoneUpload({ supabase, token, ready })`** drives the public phone page.
198
+
199
+ ## Developing
200
+
201
+ ```bash
202
+ npm test # vitest (happy-dom) — 89 tests, incl. real pdf-lib folding
203
+ npm run typecheck
204
+ npm run build # dist/ (ESM + .d.ts)
205
+ ```
206
+
207
+ An app can use this before it is published, through a `file:` path:
208
+
209
+ ```bash
210
+ npm install --install-links ../../backoffice/universal-platform/packages/assess-kit
211
+ ```
212
+
213
+ Build the kit first. `--install-links` copies the package instead of symlinking
214
+ it. That means the app's own React is the one the kit uses, the same as with
215
+ the published package.
216
+
217
+ Once the kit is published, change the app's dependency to `"^0.1.0"` and run
218
+ `npm install`.
219
+
220
+ The first publish is **0.1.0 as it stands**. Use `npm publish` here rather than
221
+ `packages/publish.sh`, which always bumps the version first (it would publish
222
+ 0.1.1). Use `publish.sh assess-kit` for later releases. Either way, publishing
223
+ needs James's security key.
@@ -0,0 +1,102 @@
1
+ import type { SupabaseLike } from './export-gate.js';
2
+ export declare const EVIDENCE_BUCKET = "assess-evidence";
3
+ /** The bucket's per-file cap (0037). */
4
+ export declare const MAX_EVIDENCE_BYTES: number;
5
+ /** The types the bucket takes; `accept=` for the file input. */
6
+ export declare const EVIDENCE_ACCEPT = "image/*,video/*,audio/*,application/pdf";
7
+ export interface EvidenceItem {
8
+ /** The stored object name (`<ts>-<name>` or `<token>_<ts>-<name>`). */
9
+ name: string;
10
+ /** Full path in the bucket. */
11
+ path: string;
12
+ size: number;
13
+ mimetype: string;
14
+ created_at: string | null;
15
+ }
16
+ export type EvidenceResult = {
17
+ ok: true;
18
+ path: string;
19
+ } | {
20
+ ok: false;
21
+ error: string;
22
+ };
23
+ export declare function evidencePrefix(orgId: string, assessmentId: string): string;
24
+ /** Keeps object keys tidy and ASCII; preserves the extension for mime sniffing. */
25
+ export declare function safeEvidenceName(name: unknown): string;
26
+ /** The object name an upload is stored under: `<ts>-<name>`, or `<token>_<ts>-<name>` from the phone. */
27
+ export declare function evidenceObjectName(fileName: unknown, { token, now }?: {
28
+ token?: string | null;
29
+ now?: number;
30
+ }): string;
31
+ /** The name to show for a stored object: without the phone token (`<token>_`) and the upload time (`<ts>-`). */
32
+ export declare function evidenceDisplayName(name: unknown): string;
33
+ export declare function fmtBytes(n: unknown): string;
34
+ export declare function isImageMime(m: unknown): boolean;
35
+ /**
36
+ * Why the bucket would refuse this file (size, type), as a sentence — checked
37
+ * BEFORE a long upload on mobile data rather than reported after it. Null: fine.
38
+ */
39
+ export declare function checkEvidenceFile(file: {
40
+ name: string;
41
+ size: number;
42
+ type?: string;
43
+ }): string | null;
44
+ /** Uploads one file. `token` = the phone route (see the header). */
45
+ export declare function uploadEvidence(supabase: SupabaseLike, orgId: string | null | undefined, assessmentId: string | null | undefined, file: File, { token, now }?: {
46
+ token?: string | null;
47
+ now?: number;
48
+ }): Promise<EvidenceResult>;
49
+ /** The assessment's files, newest first. Empty on any failure. */
50
+ export declare function listEvidence(supabase: SupabaseLike, orgId: string | null | undefined, assessmentId: string | null | undefined): Promise<EvidenceItem[]>;
51
+ export declare function signedEvidenceUrl(supabase: SupabaseLike, path: string, expiresIn?: number): Promise<string | null>;
52
+ export declare function deleteEvidence(supabase: SupabaseLike, path: string): Promise<{
53
+ ok: true;
54
+ } | {
55
+ ok: false;
56
+ error: string;
57
+ }>;
58
+ export interface EvidenceToken {
59
+ id: string;
60
+ expires_at: string;
61
+ }
62
+ export declare function mintEvidenceToken(supabase: SupabaseLike, { app, orgId, assessmentId, userId }: {
63
+ app: string;
64
+ orgId: string | null | undefined;
65
+ assessmentId: string | null | undefined;
66
+ userId?: string | null;
67
+ }): Promise<({
68
+ ok: true;
69
+ } & EvidenceToken) | {
70
+ ok: false;
71
+ error: string;
72
+ }>;
73
+ export declare function revokeEvidenceToken(supabase: SupabaseLike, token: string | null | undefined): Promise<void>;
74
+ export interface EvidenceTokenTarget {
75
+ org_id: string;
76
+ assessment_id: string;
77
+ app: string;
78
+ expires_at?: string;
79
+ }
80
+ /** What a phone token points at, or null when it is unknown or expired. */
81
+ export declare function resolveEvidenceToken(supabase: SupabaseLike, token: string | null | undefined): Promise<EvidenceTokenTarget | null>;
82
+ /**
83
+ * The public phone page for a token: `<origin><base>upload/<token>`. Pass the
84
+ * app's `import.meta.env.BASE_URL` as `base` — '/fire/' in production.
85
+ */
86
+ export declare function evidenceMobileUrl(token: string, { base, origin }?: {
87
+ base?: string;
88
+ origin?: string;
89
+ }): string;
90
+ export declare function readCachedEvidenceToken(key: string, now?: number): EvidenceToken | null;
91
+ export declare function writeCachedEvidenceToken(key: string, token: EvidenceToken | null): void;
92
+ export interface StorageUsage {
93
+ used: number;
94
+ quota: number;
95
+ }
96
+ export declare function orgStorageUsage(supabase: SupabaseLike, orgId: string | null | undefined): Promise<StorageUsage | null>;
97
+ /** Percentage used (0–100) and whether to warn (≥ 80%). */
98
+ export declare function usageLevel(usage: StorageUsage | null | undefined): {
99
+ pct: number;
100
+ nearlyFull: boolean;
101
+ };
102
+ //# sourceMappingURL=evidence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evidence.d.ts","sourceRoot":"","sources":["../src/evid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GAAG,IAAI,CAKvF;AAID,MAAM,WAAW,YAAY;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE;AAE7D,wBAAsB,eAAe,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAY5H;AAED,2DAA2D;AAC3D,wBAAgB,UAAU,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,GAAG,SAAS,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,OAAO,CAAA;CAAE,CAGvG"}
@@ -0,0 +1,241 @@
1
+ // evidence.ts — the evidence locker's data layer over the shared, private
2
+ // `assess-evidence` Storage bucket (universal-platform 0037). Photos,
3
+ // recordings and PDFs attached to an assessment live at
4
+ //
5
+ // assess-evidence/<org_id>/<assessment_id>/<ts>-<name> (desktop)
6
+ // assess-evidence/<org_id>/<assessment_id>/<token>_<ts>-<name> (phone)
7
+ //
8
+ // Two upload routes share the bucket:
9
+ // • Desktop — a signed-in company member uploads directly (member RLS).
10
+ // • Phone — a public /upload/:token page on the anonymous session uploads,
11
+ // authorised by a short-lived token the desktop mints
12
+ // (assess_evidence_tokens). Since 0239 the storage policy reads
13
+ // the token FROM THE OBJECT NAME and checks that THIS upload
14
+ // carries a live token for this assessment, rather than that one
15
+ // merely exists — so the phone route must name it, and
16
+ // evidenceDisplayName() hides it again.
17
+ // The bucket is private: the locker shows files through member-scoped signed
18
+ // URLs. Fire and COSHH Assess had identical copies of this (and of the upload
19
+ // page and locker logic, now in @unisim/assess-kit/react).
20
+ export const EVIDENCE_BUCKET = 'assess-evidence';
21
+ /** The bucket's per-file cap (0037). */
22
+ export const MAX_EVIDENCE_BYTES = 50 * 1024 * 1024;
23
+ /** The types the bucket takes; `accept=` for the file input. */
24
+ export const EVIDENCE_ACCEPT = 'image/*,video/*,audio/*,application/pdf';
25
+ export function evidencePrefix(orgId, assessmentId) {
26
+ return `${orgId}/${assessmentId}`;
27
+ }
28
+ /** Keeps object keys tidy and ASCII; preserves the extension for mime sniffing. */
29
+ export function safeEvidenceName(name) {
30
+ const raw = String(name || 'capture');
31
+ const dot = raw.lastIndexOf('.');
32
+ const ext = dot >= 0 ? raw.slice(dot).toLowerCase().replace(/[^.a-z0-9]/g, '') : '';
33
+ const base = (dot >= 0 ? raw.slice(0, dot) : raw).replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').slice(0, 48) || 'file';
34
+ return `${base}${ext}`;
35
+ }
36
+ /** The object name an upload is stored under: `<ts>-<name>`, or `<token>_<ts>-<name>` from the phone. */
37
+ export function evidenceObjectName(fileName, { token, now = Date.now() } = {}) {
38
+ const stamp = `${now}-${safeEvidenceName(fileName)}`;
39
+ return token ? `${token}_${stamp}` : stamp;
40
+ }
41
+ /** The name to show for a stored object: without the phone token (`<token>_`) and the upload time (`<ts>-`). */
42
+ export function evidenceDisplayName(name) {
43
+ return String(name || '').replace(/^[^/_]+_(?=\d+-)/, '').replace(/^\d+-/, '');
44
+ }
45
+ export function fmtBytes(n) {
46
+ const num = Number(n) || 0;
47
+ if (num < 1024)
48
+ return `${num} B`;
49
+ const u = ['KB', 'MB', 'GB'];
50
+ let v = num / 1024;
51
+ let i = 0;
52
+ while (v >= 1024 && i < u.length - 1) {
53
+ v /= 1024;
54
+ i++;
55
+ }
56
+ return `${v.toFixed(v < 10 ? 1 : 0)} ${u[i]}`;
57
+ }
58
+ export function isImageMime(m) {
59
+ return typeof m === 'string' && m.startsWith('image/');
60
+ }
61
+ /**
62
+ * Why the bucket would refuse this file (size, type), as a sentence — checked
63
+ * BEFORE a long upload on mobile data rather than reported after it. Null: fine.
64
+ */
65
+ export function checkEvidenceFile(file) {
66
+ if (file.size > MAX_EVIDENCE_BYTES) {
67
+ return `${file.name} is ${fmtBytes(file.size)} — files can be up to ${fmtBytes(MAX_EVIDENCE_BYTES)}.`;
68
+ }
69
+ if (file.type && !/^(image|video|audio)\//.test(file.type) && file.type !== 'application/pdf') {
70
+ return `${file.name} isn't a photo, video, recording or PDF.`;
71
+ }
72
+ return null;
73
+ }
74
+ /** Uploads one file. `token` = the phone route (see the header). */
75
+ export async function uploadEvidence(supabase, orgId, assessmentId, file, { token, now } = {}) {
76
+ if (!orgId || !assessmentId)
77
+ return { ok: false, error: 'Missing organisation or assessment' };
78
+ const problem = checkEvidenceFile(file);
79
+ if (problem)
80
+ return { ok: false, error: problem };
81
+ const path = `${evidencePrefix(orgId, assessmentId)}/${evidenceObjectName(file.name, { token, now })}`;
82
+ try {
83
+ const { error } = await supabase.storage
84
+ .from(EVIDENCE_BUCKET)
85
+ .upload(path, file, { contentType: file.type || 'application/octet-stream', upsert: false });
86
+ if (error) {
87
+ // An RLS denial (quota full / expired token) surfaces as a generic policy error.
88
+ const quotaish = /row-level security|exceeded|payload/i.test(error.message || '');
89
+ return { ok: false, error: quotaish ? 'Upload blocked — storage may be full or the link expired.' : (error.message || 'Upload failed') };
90
+ }
91
+ return { ok: true, path };
92
+ }
93
+ catch (err) {
94
+ return { ok: false, error: err instanceof Error ? err.message : 'Upload failed' };
95
+ }
96
+ }
97
+ /** The assessment's files, newest first. Empty on any failure. */
98
+ export async function listEvidence(supabase, orgId, assessmentId) {
99
+ if (!orgId || !assessmentId)
100
+ return [];
101
+ try {
102
+ const { data, error } = await supabase.storage
103
+ .from(EVIDENCE_BUCKET)
104
+ .list(evidencePrefix(orgId, assessmentId), { limit: 200, sortBy: { column: 'created_at', order: 'desc' } });
105
+ if (error) {
106
+ console.warn('[assess-kit] list evidence failed', error);
107
+ return [];
108
+ }
109
+ return (data ?? [])
110
+ // Real objects only — folder placeholders have a null id.
111
+ .filter((o) => !!o && !!o.name && !!o.id)
112
+ .map((o) => {
113
+ const meta = (o.metadata ?? {});
114
+ return {
115
+ name: String(o.name),
116
+ path: `${evidencePrefix(orgId, assessmentId)}/${String(o.name)}`,
117
+ size: meta.size ?? 0,
118
+ mimetype: meta.mimetype || '',
119
+ created_at: o.created_at || null,
120
+ };
121
+ });
122
+ }
123
+ catch (err) {
124
+ console.warn('[assess-kit] list evidence threw', err);
125
+ return [];
126
+ }
127
+ }
128
+ export async function signedEvidenceUrl(supabase, path, expiresIn = 3600) {
129
+ try {
130
+ const { data, error } = await supabase.storage.from(EVIDENCE_BUCKET).createSignedUrl(path, expiresIn);
131
+ if (error) {
132
+ console.warn('[assess-kit] signed url failed', error);
133
+ return null;
134
+ }
135
+ return data?.signedUrl || null;
136
+ }
137
+ catch {
138
+ return null;
139
+ }
140
+ }
141
+ export async function deleteEvidence(supabase, path) {
142
+ try {
143
+ const { error } = await supabase.storage.from(EVIDENCE_BUCKET).remove([path]);
144
+ return error ? { ok: false, error: error.message || 'Could not delete that file.' } : { ok: true };
145
+ }
146
+ catch (err) {
147
+ return { ok: false, error: err instanceof Error ? err.message : 'Could not delete that file.' };
148
+ }
149
+ }
150
+ export async function mintEvidenceToken(supabase, { app, orgId, assessmentId, userId }) {
151
+ if (!orgId || !assessmentId)
152
+ return { ok: false, error: 'Missing organisation or assessment' };
153
+ try {
154
+ const { data, error } = await supabase
155
+ .from('assess_evidence_tokens')
156
+ .insert({ app, org_id: orgId, assessment_id: assessmentId, created_by_id: userId ?? null })
157
+ .select('id, expires_at')
158
+ .single();
159
+ return error ? { ok: false, error: error.message || 'Could not make a phone link.' } : { ok: true, id: data.id, expires_at: data.expires_at };
160
+ }
161
+ catch (err) {
162
+ return { ok: false, error: err instanceof Error ? err.message : 'Could not make a phone link.' };
163
+ }
164
+ }
165
+ export async function revokeEvidenceToken(supabase, token) {
166
+ if (!token)
167
+ return;
168
+ try {
169
+ await supabase.from('assess_evidence_tokens').delete().eq('id', token);
170
+ }
171
+ catch { /* expires anyway */ }
172
+ }
173
+ /** What a phone token points at, or null when it is unknown or expired. */
174
+ export async function resolveEvidenceToken(supabase, token) {
175
+ if (!token)
176
+ return null;
177
+ try {
178
+ const { data, error } = await supabase.rpc('assess_evidence_token_info', { p_token: token });
179
+ if (error) {
180
+ console.warn('[assess-kit] resolve token failed', error);
181
+ return null;
182
+ }
183
+ const row = Array.isArray(data) ? data[0] : data;
184
+ return row || null;
185
+ }
186
+ catch {
187
+ return null;
188
+ }
189
+ }
190
+ /**
191
+ * The public phone page for a token: `<origin><base>upload/<token>`. Pass the
192
+ * app's `import.meta.env.BASE_URL` as `base` — '/fire/' in production.
193
+ */
194
+ export function evidenceMobileUrl(token, { base = '/', origin } = {}) {
195
+ const o = origin ?? (typeof window !== 'undefined' ? window.location.origin : '');
196
+ const b = base.endsWith('/') ? base : `${base}/`;
197
+ return `${o}${b}upload/${token}`;
198
+ }
199
+ // ── Remembering the phone link per assessment ────────────────────────────────
200
+ // A storage that throws (Safari private mode, blocked site data) only costs
201
+ // the cache — never the locker.
202
+ export function readCachedEvidenceToken(key, now = Date.now()) {
203
+ try {
204
+ const cached = JSON.parse(localStorage.getItem(key) || 'null');
205
+ if (cached?.id && cached.expires_at && Date.parse(cached.expires_at) > now)
206
+ return cached;
207
+ }
208
+ catch { /* unreadable: mint a new one */ }
209
+ return null;
210
+ }
211
+ export function writeCachedEvidenceToken(key, token) {
212
+ try {
213
+ if (token)
214
+ localStorage.setItem(key, JSON.stringify({ id: token.id, expires_at: token.expires_at }));
215
+ else
216
+ localStorage.removeItem(key);
217
+ }
218
+ catch { /* storage unavailable */ }
219
+ }
220
+ export async function orgStorageUsage(supabase, orgId) {
221
+ if (!orgId)
222
+ return null;
223
+ try {
224
+ const [usage, quota] = await Promise.all([
225
+ supabase.rpc('assess_bucket_usage_bytes', { p_org: orgId }),
226
+ supabase.rpc('assess_org_quota_bytes', { p_org: orgId }),
227
+ ]);
228
+ if (usage.error || quota.error)
229
+ return null;
230
+ return { used: Number(usage.data) || 0, quota: Number(quota.data) || 0 };
231
+ }
232
+ catch {
233
+ return null;
234
+ }
235
+ }
236
+ /** Percentage used (0–100) and whether to warn (≥ 80%). */
237
+ export function usageLevel(usage) {
238
+ const pct = usage && usage.quota ? Math.min(100, Math.round((usage.used / usage.quota) * 100)) : 0;
239
+ return { pct, nearlyFull: pct >= 80 };
240
+ }
241
+ //# sourceMappingURL=evidence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evidence.js","sourceRoot":"","sources":["../src/evidence.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,sEAAsE;AACtE,wDAAwD;AACxD,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,EAAE;AACF,sCAAsC;AACtC,0EAA0E;AAC1E,+EAA+E;AAC/E,oEAAoE;AACpE,8EAA8E;AAC9E,2EAA2E;AAC3E,+EAA+E;AAC/E,qEAAqE;AACrE,sDAAsD;AACtD,6EAA6E;AAC7E,8EAA8E;AAC9E,2DAA2D;AAI3D,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,CAAA;AAChD,wCAAwC;AACxC,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAA;AAClD,gEAAgE;AAChE,MAAM,CAAC,MAAM,eAAe,GAAG,yCAAyC,CAAA;AAcxE,MAAM,UAAU,cAAc,CAAC,KAAa,EAAE,YAAoB;IAChE,OAAO,GAAG,KAAK,IAAI,YAAY,EAAE,CAAA;AACnC,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,gBAAgB,CAAC,IAAa;IAC5C,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,IAAI,SAAS,CAAC,CAAA;IACrC,MAAM,GAAG,GAAG,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAA;IAChC,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC,OAAO,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAA;IACnF,MAAM,IAAI,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CA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