@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
@@ -0,0 +1,184 @@
1
+ import { type SessionLike } from './hub.js';
2
+ /** The product codes the server knows (product_access.product). */
3
+ export declare const ASSESS_PRODUCTS: {
4
+ readonly workplace: "workplace_assess";
5
+ readonly cyber: "cyber_assess";
6
+ readonly risk: "risk_assess";
7
+ readonly fire: "fire_assess";
8
+ readonly coshh: "coshh_assess";
9
+ readonly ergo: "ergo_assess";
10
+ };
11
+ export type AssessProduct = (typeof ASSESS_PRODUCTS)[keyof typeof ASSESS_PRODUCTS] | (string & {});
12
+ /**
13
+ * The Supabase client — only `rpc` and `from` are used. Loosely typed on
14
+ * purpose: the SDK's client and a bare supabase-js client both fit.
15
+ */
16
+ export type SupabaseLike = {
17
+ rpc: (fn: string, args?: Record<string, unknown>) => any;
18
+ from: (table: string) => any;
19
+ storage?: any;
20
+ };
21
+ /** Why the server refused an export. */
22
+ export type ExportVerdict = 'not_signed_in' | 'no_company' | 'not_entitled';
23
+ export declare function isExportVerdict(v: unknown): v is ExportVerdict;
24
+ /**
25
+ * Buying this one report (0218), as a refusal describes it. `canBuy` stays
26
+ * false until the owner stores a Stripe Payment Link, so "Buy this report"
27
+ * appears on its own once one exists.
28
+ */
29
+ export interface ReportOffer {
30
+ canBuy: boolean;
31
+ pricePence: number;
32
+ /** The usual price while on offer; null when the server didn't say. */
33
+ fullPricePence: number | null;
34
+ onOffer: boolean;
35
+ /** The instant the offer price stops (its last day is the day before). */
36
+ offerEndsAt: string | null;
37
+ }
38
+ /** A reply's offer fields as a ReportOffer — null when it carries none. */
39
+ export declare function parseOffer(raw: unknown): ReportOffer | null;
40
+ export type IssueResult = {
41
+ ok: true;
42
+ certId: string;
43
+ issuedAt: string;
44
+ orgName: string | null;
45
+ }
46
+ /** `failed` = the call itself went wrong (network, RPC error, odd reply) — not a verdict. */
47
+ | {
48
+ ok: false;
49
+ error: ExportVerdict | 'failed';
50
+ offer: ReportOffer | null;
51
+ message?: string;
52
+ };
53
+ export interface IssueArgs {
54
+ product: AssessProduct;
55
+ /** The company the export is for: the assessment's own, else the active one; null for none. */
56
+ orgId: string | null | undefined;
57
+ /** The assessment's id — one bought report unlocks every export of it. */
58
+ assessmentRef: string | null | undefined;
59
+ /** The file's name, decided before asking (it is recorded with the certificate). */
60
+ docName: string | null | undefined;
61
+ /** The data the file is built from; its SHA-256 (stableJson) is recorded. */
62
+ data?: unknown;
63
+ /** …or the hash itself, when the caller already has it. Wins over `data`. */
64
+ docHash?: string | null;
65
+ /**
66
+ * Pass the session to answer guests without a round trip: no session, or an
67
+ * anonymous one, is `not_signed_in` (anon has no EXECUTE on the function,
68
+ * so asking would be an error rather than a verdict).
69
+ */
70
+ session?: SessionLike | null;
71
+ }
72
+ /** Ask the server for an official export. Never throws. */
73
+ export declare function issueAssessExport(supabase: SupabaseLike, args: IssueArgs): Promise<IssueResult>;
74
+ /**
75
+ * The same verdict without issuing anything — for an up-front lock hint only.
76
+ * Null when it couldn't be asked; issueAssessExport() stays the real gate.
77
+ */
78
+ export declare function assessExportAllowed(supabase: SupabaseLike, { product, orgId }: {
79
+ product: AssessProduct;
80
+ orgId: string | null | undefined;
81
+ }): Promise<boolean | null>;
82
+ /**
83
+ * Whether this user has a PAID one-report purchase of this assessment. RLS
84
+ * lets a buyer read their own purchases — and the platform admin everyone's,
85
+ * which is why the user id filter is not optional. Display only.
86
+ */
87
+ export declare function hasPaidReport(supabase: SupabaseLike, { product, userId, assessmentRef }: {
88
+ product: AssessProduct;
89
+ userId: string;
90
+ assessmentRef: string;
91
+ }): Promise<boolean>;
92
+ /** The one-report offer on its own (`assess_report_offer`), or null. */
93
+ export declare function fetchReportOffer(supabase: SupabaseLike): Promise<ReportOffer | null>;
94
+ export type PurchaseStart = {
95
+ kind: 'pay';
96
+ paymentUrl: string;
97
+ } | {
98
+ kind: 'already_paid';
99
+ } | {
100
+ kind: 'refused';
101
+ error: 'not_signed_in' | 'invalid' | 'not_available';
102
+ }
103
+ /** The call went wrong, or the server said something this doesn't expect. */
104
+ | {
105
+ kind: 'failed';
106
+ message?: string;
107
+ };
108
+ /**
109
+ * Start buying this one report (`start_assess_report_purchase`, 0218): the
110
+ * Stripe Payment Link to open, or that it is already paid for. Never throws.
111
+ * `assessmentRef` and `orgId` MUST be exactly what the refused export passed,
112
+ * or the payment won't unlock it. Opens nothing itself.
113
+ */
114
+ export declare function startReportPurchase(supabase: SupabaseLike, { product, assessmentRef, orgId }: {
115
+ product: AssessProduct;
116
+ assessmentRef: string;
117
+ orgId: string | null | undefined;
118
+ }): Promise<PurchaseStart>;
119
+ /** https:// and nothing else. */
120
+ export declare function isHttpsUrl(url: string): boolean;
121
+ /**
122
+ * Redeem an access code FOR THIS PRODUCT (0217): the company gets product
123
+ * access — what every export checks — rather than only credits. Never throws.
124
+ */
125
+ export declare function redeemAccessCode(supabase: SupabaseLike, { product, code }: {
126
+ product: AssessProduct;
127
+ code: string;
128
+ }): Promise<{
129
+ ok: boolean;
130
+ error?: string;
131
+ grantedProducts?: string[];
132
+ }>;
133
+ /** Where a printed certificate id can be checked (no scheme: it is printed). */
134
+ export declare function verifyUrl(certId: string): string;
135
+ /** The line every page of an official report carries. */
136
+ export declare function certificateLine(certId: string): string;
137
+ /** Printed before the certificate line on a report of an unfinished assessment. */
138
+ export declare const DRAFT_PREFIX = "DRAFT \u2014 not yet complete \u00B7 ";
139
+ /**
140
+ * The footer of an official report: the certificate line, saying DRAFT first
141
+ * when the assessment isn't complete (the server issues certificates for
142
+ * drafts too, so the file has to say so itself).
143
+ */
144
+ export declare function officialFooter(certId: string, { draft }?: {
145
+ draft?: boolean;
146
+ }): string;
147
+ /** 1000 → "£10", 1050 → "£10.50" (English only; see formatPounds). */
148
+ export declare function formatPence(pence: number): string;
149
+ /** A language code as a date/number locale: plain `en` is the US; the suite's English is British. */
150
+ export declare function suiteLocale(language?: string | null): string;
151
+ /** Pence as pounds in the reader's locale: "£10", or "£10.50" when not whole. */
152
+ export declare function formatPounds(pence: number, locale?: string | null): string;
153
+ /**
154
+ * The offer's last day ("31 December 2026") in the reader's locale. The offer
155
+ * runs UNTIL offerEndsAt (2027-01-01 00:00 UK), so its last day is the day
156
+ * before. Null when there is no usable date.
157
+ */
158
+ export declare function offerLastDay(offerEndsAt: string | null | undefined, locale?: string | null): string | null;
159
+ /** The small line under "Buy this report", in English (for the English-only apps). */
160
+ export declare function offerLine(offer: ReportOffer): string;
161
+ /**
162
+ * A file-name part. Default: letters and digits in any script, the rest as
163
+ * single dashes ("Doğan Ltd" → "doğan-ltd"). `ascii: true` folds accents to
164
+ * their base letter and drops anything else ("doğan-ltd" → "dogan-ltd"), for
165
+ * names that must survive any mail client. `fallback` stands in for an empty
166
+ * result.
167
+ */
168
+ export declare function fileSlug(s: unknown, { ascii, fallback }?: {
169
+ ascii?: boolean;
170
+ fallback?: string;
171
+ }): string;
172
+ /** A date as YYYY-MM-DD, for file names (default: today, UTC). */
173
+ export declare function fileDate(at?: Date): string;
174
+ /**
175
+ * JSON with object keys sorted at every level, so the same data always gives
176
+ * the same text — and the same hash — whatever order it was stored in. Same
177
+ * rules as JSON.stringify otherwise: toJSON() is honoured (a Date becomes its
178
+ * ISO string), undefined / functions are left out of objects and become null
179
+ * in arrays.
180
+ */
181
+ export declare function stableJson(value: unknown): string;
182
+ /** SHA-256 of a string as lower-case hex — null where crypto.subtle is unavailable (an insecure context). */
183
+ export declare function sha256Hex(text: string): Promise<string | null>;
184
+ //# sourceMappingURL=export-gate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"export-gate.d.ts","sourceRoot":"","sources":["../src/export-gate.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAc,KAAK,WAAW,EAAE,MAAM,UAAU,CAAA;AAEvD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D;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,KAAa,EAAE,GAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GAAG,MAAM,CAElG;AAID,sEAAsE;AACtE,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAGjD;AAED,qGAAqG;AACrG,wBAAgB,WAAW,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAG5D;AAED,iFAAiF;AACjF,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,CAY1E;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,MAAM,GAAG,IAAI,CAS1G;AAED,sFAAsF;AACtF,wBAAgB,SAAS,CAAC,KAAK,EAAE,WAAW,GAAG,MAAM,CAKpD;AAID;;;;;;GAMG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,KAAa,EAAE,QAAa,EAAE,GAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,MAAM,CAM1H;AAED,kEAAkE;AAClE,wBAAgB,QAAQ,CAAC,EAAE,GAAE,IAAiB,GAAG,MAAM,CAEtD;AAID;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAQjD;AAED,6GAA6G;AAC7G,wBAAsB,SAAS,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAOpE"}
@@ -0,0 +1,320 @@
1
+ // export-gate.ts — the server-side export gate every Assess app puts in front
2
+ // of its reports (the Assess free trial, universal-platform 0215, 2026-10-02).
3
+ //
4
+ // Filling in and saving an assessment is free for any signed-in Universal ID.
5
+ // Downloading, exporting or sharing the REPORT needs the product for the
6
+ // company — a `product_access` row, checked on the SERVER. Before any file is
7
+ // built, `issue_assess_export` re-checks that and, when allowed, records the
8
+ // export and hands back a certificate id the file then carries on every page:
9
+ // "Official report · Certificate … · Verify at app.unisim.co.uk/verify/…".
10
+ //
11
+ // ⚠️ Call issueAssessExport() IMMEDIATELY before building a file, and build the
12
+ // file only on `ok: true`. No certificate, no file. A failed call is never a
13
+ // reason to build it anyway.
14
+ //
15
+ // A refusal carries the one-report offer (0218): buy this ONE assessment's
16
+ // report. A paid report is matched on (product, assessment ref), so the
17
+ // purchase must pass exactly the ref (and org) the export passed.
18
+ //
19
+ // Five apps had five copies of this: three never-throwing ones with an
20
+ // anonymous short-circuit (Workplace, Risk, Cyber's caller), one that threw
21
+ // (Cyber), and one that returned the raw snake_case reply (Fire / COSHH). This
22
+ // is the best of them: it never throws, it fails closed (an "ok" with no
23
+ // certificate is a failure), and it normalises every reply.
24
+ import { isSignedIn } from './hub.js';
25
+ /** The product codes the server knows (product_access.product). */
26
+ export const ASSESS_PRODUCTS = {
27
+ workplace: 'workplace_assess',
28
+ cyber: 'cyber_assess',
29
+ risk: 'risk_assess',
30
+ fire: 'fire_assess',
31
+ coshh: 'coshh_assess',
32
+ ergo: 'ergo_assess',
33
+ };
34
+ async function callRpc(supabase, fn, args) {
35
+ const reply = (await supabase.rpc(fn, args));
36
+ return { data: reply?.data ?? null, error: reply?.error ?? null };
37
+ }
38
+ const VERDICTS = ['not_signed_in', 'no_company', 'not_entitled'];
39
+ export function isExportVerdict(v) {
40
+ return typeof v === 'string' && VERDICTS.includes(v);
41
+ }
42
+ /** A reply's offer fields as a ReportOffer — null when it carries none. */
43
+ export function parseOffer(raw) {
44
+ if (!raw || typeof raw !== 'object')
45
+ return null;
46
+ const r = raw;
47
+ const price = typeof r.price_pence === 'number' ? r.price_pence : typeof r.price_pence === 'string' ? Number(r.price_pence) : NaN;
48
+ if (!Number.isFinite(price))
49
+ return null;
50
+ const full = r.full_price_pence == null ? null : Number(r.full_price_pence);
51
+ return {
52
+ canBuy: r.can_buy === true,
53
+ pricePence: price,
54
+ fullPricePence: full != null && Number.isFinite(full) ? full : null,
55
+ onOffer: r.on_offer === true,
56
+ offerEndsAt: typeof r.offer_ends_at === 'string' ? r.offer_ends_at : null,
57
+ };
58
+ }
59
+ /** Ask the server for an official export. Never throws. */
60
+ export async function issueAssessExport(supabase, args) {
61
+ if ('session' in args && !isSignedIn(args.session))
62
+ return { ok: false, error: 'not_signed_in', offer: null };
63
+ const docHash = args.docHash !== undefined
64
+ ? args.docHash
65
+ : args.data === undefined ? null : await sha256Hex(stableJson(args.data));
66
+ try {
67
+ const { data, error } = await callRpc(supabase, 'issue_assess_export', {
68
+ p_product: args.product,
69
+ p_org: args.orgId || null,
70
+ p_assessment_ref: args.assessmentRef || null,
71
+ p_doc_name: args.docName || null,
72
+ p_doc_hash: docHash,
73
+ });
74
+ if (error) {
75
+ console.error(`[${args.product}] issue_assess_export failed`, error);
76
+ return { ok: false, error: 'failed', offer: null, message: error.message || 'issue_assess_export failed' };
77
+ }
78
+ const res = (data ?? {});
79
+ // Fail closed: a yes without a certificate is not an issued report.
80
+ if (res.ok === true && typeof res.cert_id === 'string' && res.cert_id) {
81
+ return {
82
+ ok: true,
83
+ certId: res.cert_id,
84
+ issuedAt: typeof res.issued_at === 'string' ? res.issued_at : new Date().toISOString(),
85
+ orgName: typeof res.org_name === 'string' ? res.org_name : null,
86
+ };
87
+ }
88
+ if (isExportVerdict(res.error))
89
+ return { ok: false, error: res.error, offer: parseOffer(res) };
90
+ return { ok: false, error: 'failed', offer: null, message: `issue_assess_export: unexpected reply ${JSON.stringify(res)}` };
91
+ }
92
+ catch (err) {
93
+ console.error(`[${args.product}] issue_assess_export threw`, err);
94
+ return { ok: false, error: 'failed', offer: null, message: err instanceof Error ? err.message : String(err) };
95
+ }
96
+ }
97
+ /**
98
+ * The same verdict without issuing anything — for an up-front lock hint only.
99
+ * Null when it couldn't be asked; issueAssessExport() stays the real gate.
100
+ */
101
+ export async function assessExportAllowed(supabase, { product, orgId }) {
102
+ try {
103
+ const { data, error } = await callRpc(supabase, 'assess_export_allowed', { p_product: product, p_org: orgId || null });
104
+ if (error)
105
+ return null;
106
+ return data === true;
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ }
112
+ /**
113
+ * Whether this user has a PAID one-report purchase of this assessment. RLS
114
+ * lets a buyer read their own purchases — and the platform admin everyone's,
115
+ * which is why the user id filter is not optional. Display only.
116
+ */
117
+ export async function hasPaidReport(supabase, { product, userId, assessmentRef }) {
118
+ if (!userId || !assessmentRef)
119
+ return false;
120
+ try {
121
+ const { data, error } = await supabase
122
+ .from('assess_report_purchases')
123
+ .select('id')
124
+ .eq('user_id', userId)
125
+ .eq('product', product)
126
+ .eq('assessment_ref', assessmentRef)
127
+ .eq('status', 'paid')
128
+ .limit(1);
129
+ if (error)
130
+ return false;
131
+ return (data?.length ?? 0) > 0;
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ }
137
+ /** The one-report offer on its own (`assess_report_offer`), or null. */
138
+ export async function fetchReportOffer(supabase) {
139
+ try {
140
+ const { data, error } = await callRpc(supabase, 'assess_report_offer', {});
141
+ if (error || !data)
142
+ return null;
143
+ return parseOffer(data);
144
+ }
145
+ catch {
146
+ return null;
147
+ }
148
+ }
149
+ /**
150
+ * Start buying this one report (`start_assess_report_purchase`, 0218): the
151
+ * Stripe Payment Link to open, or that it is already paid for. Never throws.
152
+ * `assessmentRef` and `orgId` MUST be exactly what the refused export passed,
153
+ * or the payment won't unlock it. Opens nothing itself.
154
+ */
155
+ export async function startReportPurchase(supabase, { product, assessmentRef, orgId }) {
156
+ try {
157
+ const { data, error } = await callRpc(supabase, 'start_assess_report_purchase', {
158
+ p_product: product,
159
+ p_assessment_ref: assessmentRef,
160
+ p_org: orgId || null,
161
+ });
162
+ if (error) {
163
+ console.error(`[${product}] start_assess_report_purchase failed`, error);
164
+ return { kind: 'failed', message: error.message };
165
+ }
166
+ const res = (data ?? {});
167
+ if (res.ok === true && res.already_paid === true)
168
+ return { kind: 'already_paid' };
169
+ // Only an https link is ever opened (defence in depth — it is the owner's
170
+ // stored Stripe Payment Link, but it reaches window.open and an href).
171
+ if (res.ok === true && typeof res.payment_url === 'string' && isHttpsUrl(res.payment_url)) {
172
+ return { kind: 'pay', paymentUrl: res.payment_url };
173
+ }
174
+ if (res.error === 'not_signed_in' || res.error === 'invalid' || res.error === 'not_available') {
175
+ return { kind: 'refused', error: res.error };
176
+ }
177
+ return { kind: 'failed', message: `start_assess_report_purchase: unexpected reply ${JSON.stringify(res)}` };
178
+ }
179
+ catch (err) {
180
+ console.error(`[${product}] start_assess_report_purchase threw`, err);
181
+ return { kind: 'failed', message: err instanceof Error ? err.message : String(err) };
182
+ }
183
+ }
184
+ /** https:// and nothing else. */
185
+ export function isHttpsUrl(url) {
186
+ return /^https:\/\//i.test(url);
187
+ }
188
+ /**
189
+ * Redeem an access code FOR THIS PRODUCT (0217): the company gets product
190
+ * access — what every export checks — rather than only credits. Never throws.
191
+ */
192
+ export async function redeemAccessCode(supabase, { product, code }) {
193
+ try {
194
+ const { data, error } = await callRpc(supabase, 'redeem_access_code', { p_code: code, p_product: product });
195
+ if (error)
196
+ return { ok: false, error: error.message };
197
+ const res = (data ?? { ok: false, error: 'invalid' });
198
+ return { ok: res.ok === true, error: res.error, grantedProducts: res.granted_products };
199
+ }
200
+ catch (err) {
201
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
202
+ }
203
+ }
204
+ // ── What the file says ───────────────────────────────────────────────────────
205
+ /** Where a printed certificate id can be checked (no scheme: it is printed). */
206
+ export function verifyUrl(certId) {
207
+ return `app.unisim.co.uk/verify/${certId}`;
208
+ }
209
+ /** The line every page of an official report carries. */
210
+ export function certificateLine(certId) {
211
+ return `Official report · Certificate ${certId} · Verify at ${verifyUrl(certId)}`;
212
+ }
213
+ /** Printed before the certificate line on a report of an unfinished assessment. */
214
+ export const DRAFT_PREFIX = 'DRAFT — not yet complete · ';
215
+ /**
216
+ * The footer of an official report: the certificate line, saying DRAFT first
217
+ * when the assessment isn't complete (the server issues certificates for
218
+ * drafts too, so the file has to say so itself).
219
+ */
220
+ export function officialFooter(certId, { draft = false } = {}) {
221
+ return (draft ? DRAFT_PREFIX : '') + certificateLine(certId);
222
+ }
223
+ // ── Prices and dates ─────────────────────────────────────────────────────────
224
+ /** 1000 → "£10", 1050 → "£10.50" (English only; see formatPounds). */
225
+ export function formatPence(pence) {
226
+ const n = Number(pence) || 0;
227
+ return n % 100 === 0 ? `£${n / 100}` : `£${(n / 100).toFixed(2)}`;
228
+ }
229
+ /** A language code as a date/number locale: plain `en` is the US; the suite's English is British. */
230
+ export function suiteLocale(language) {
231
+ const l = (language ?? '').trim();
232
+ return !l || /^en$/i.test(l) ? 'en-GB' : l;
233
+ }
234
+ /** Pence as pounds in the reader's locale: "£10", or "£10.50" when not whole. */
235
+ export function formatPounds(pence, locale) {
236
+ const n = Number(pence) || 0;
237
+ const digits = n % 100 === 0 ? 0 : 2;
238
+ const opts = {
239
+ style: 'currency', currency: 'GBP', currencyDisplay: 'narrowSymbol',
240
+ minimumFractionDigits: digits, maximumFractionDigits: digits,
241
+ };
242
+ try {
243
+ return new Intl.NumberFormat(suiteLocale(locale), opts).format(n / 100);
244
+ }
245
+ catch {
246
+ return formatPence(n);
247
+ }
248
+ }
249
+ /**
250
+ * The offer's last day ("31 December 2026") in the reader's locale. The offer
251
+ * runs UNTIL offerEndsAt (2027-01-01 00:00 UK), so its last day is the day
252
+ * before. Null when there is no usable date.
253
+ */
254
+ export function offerLastDay(offerEndsAt, locale) {
255
+ const t = offerEndsAt ? Date.parse(offerEndsAt) : NaN;
256
+ if (Number.isNaN(t))
257
+ return null;
258
+ const opts = { day: 'numeric', month: 'long', year: 'numeric', timeZone: 'Europe/London' };
259
+ try {
260
+ return new Date(t - 1).toLocaleDateString(suiteLocale(locale), opts);
261
+ }
262
+ catch {
263
+ return new Date(t - 1).toLocaleDateString('en-GB', opts);
264
+ }
265
+ }
266
+ /** The small line under "Buy this report", in English (for the English-only apps). */
267
+ export function offerLine(offer) {
268
+ if (!offer.onOffer)
269
+ return 'One report for this assessment.';
270
+ const normally = offer.fullPricePence != null ? ` — normally ${formatPence(offer.fullPricePence)}.` : '.';
271
+ const day = offerLastDay(offer.offerEndsAt);
272
+ return day ? `Special offer until ${day}${normally}` : `Special offer${normally}`;
273
+ }
274
+ // ── File names ───────────────────────────────────────────────────────────────
275
+ /**
276
+ * A file-name part. Default: letters and digits in any script, the rest as
277
+ * single dashes ("Doğan Ltd" → "doğan-ltd"). `ascii: true` folds accents to
278
+ * their base letter and drops anything else ("doğan-ltd" → "dogan-ltd"), for
279
+ * names that must survive any mail client. `fallback` stands in for an empty
280
+ * result.
281
+ */
282
+ export function fileSlug(s, { ascii = false, fallback = '' } = {}) {
283
+ const lower = String(s ?? '').toLowerCase();
284
+ const slug = ascii
285
+ ? lower.normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
286
+ : lower.replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '');
287
+ return slug || fallback;
288
+ }
289
+ /** A date as YYYY-MM-DD, for file names (default: today, UTC). */
290
+ export function fileDate(at = new Date()) {
291
+ return at.toISOString().slice(0, 10);
292
+ }
293
+ // ── Hashing ──────────────────────────────────────────────────────────────────
294
+ /**
295
+ * JSON with object keys sorted at every level, so the same data always gives
296
+ * the same text — and the same hash — whatever order it was stored in. Same
297
+ * rules as JSON.stringify otherwise: toJSON() is honoured (a Date becomes its
298
+ * ISO string), undefined / functions are left out of objects and become null
299
+ * in arrays.
300
+ */
301
+ export function stableJson(value) {
302
+ return JSON.stringify(value, (_key, v) => {
303
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
304
+ const obj = v;
305
+ return Object.fromEntries(Object.keys(obj).sort().map((k) => [k, obj[k]]));
306
+ }
307
+ return v;
308
+ }) ?? 'null';
309
+ }
310
+ /** SHA-256 of a string as lower-case hex — null where crypto.subtle is unavailable (an insecure context). */
311
+ export async function sha256Hex(text) {
312
+ try {
313
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
314
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');
315
+ }
316
+ catch {
317
+ return null;
318
+ }
319
+ }
320
+ //# sourceMappingURL=export-gate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"export-gate.js","sourceRoot":"","sources":["../src/export-gate.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,+EAA+E;AAC/E,EAAE;AACF,8EAA8E;AAC9E,yEAAyE;AACzE,8EAA8E;AAC9E,6EAA6E;AAC7E,8EAA8E;AAC9E,2EAA2E;AAC3E,EAAE;AACF,gFAAgF;AAChF,6EAA6E;AAC7E,6BAA6B;AAC7B,EAAE;AACF,2EAA2E;AAC3E,wEAAwE;AACxE,kEAAkE;AAClE,EAAE;AACF,uEAAuE;AACvE,4EAA4E;AAC5E,+EAA+E;AAC/E,yEAAyE;AACzE,4DAA4D;AAE5D,OAAO,EAAE,UAAU,EAAoB,MAAM,UAAU,CAAA;AAEvD,mEAAmE;AACnE,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,SAAS,EAAE,kBAAkB;IAC7B,KAAK,EAAE,cAAc;IACrB,IAAI,EAAE,aAAa;IACnB,IAAI,EAAE,aAAa;IACnB,KAAK,EAAE,cAAc;IACrB,IAAI,EAAE,aAAa;CACX,CAAA;AAaV,KAAK,UAAU,OAAO,CAAC,QAAsB,EAAE,EAAU,EAAE,IAA6B;IACtF,MAAM,KAAK,GAAG,CAAC,MAAM,QAAQ,CAAC,GAAG,CAAC,EAAE,EAAE,IAAI,CAAC,CAAgC,CAAA;IAC3E,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,IAAI,IAAI,E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AC,CAAC,CAAA;QACpF,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAA;IAC5F,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC"}
package/dist/hub.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ /** The hub's home ("Me" page — it lists the company's admins). */
2
+ export declare const HUB_URL = "https://app.unisim.co.uk/";
3
+ /** The hub's sign-in page. Use hubLoginHref(), which comes back here. */
4
+ export declare const HUB_LOGIN_URL = "https://app.unisim.co.uk/login";
5
+ /** Plans and pricing. ⚠️ Never shown inside the native app (App Store 3.1.1). */
6
+ export declare const PLANS_URL = "https://unisim.co.uk/subscription";
7
+ /** Where a company-less Universal ID sets up a company. */
8
+ export declare const COMPANY_SETUP_URL = "https://app.unisim.co.uk/branding";
9
+ /**
10
+ * The hub's sign-in page, returning to `returnTo` (default: this page). The
11
+ * hub reads `?return=` — not `returnTo` — and only follows it to a suite
12
+ * address, else lands on the Assess portal, so pass the page you are on.
13
+ * Cyber's Default settings link sent no `?return=` until 2026-10-04.
14
+ */
15
+ export declare function hubLoginHref(returnTo?: string): string;
16
+ /** The bits of a Supabase session this needs. */
17
+ export interface SessionLike {
18
+ user?: {
19
+ id?: string;
20
+ is_anonymous?: boolean | null;
21
+ } | null;
22
+ }
23
+ /**
24
+ * A real Universal ID: a session whose user is not anonymous. The Assess apps
25
+ * sign every visitor in anonymously at start-up (for the phone-upload page and
26
+ * telemetry), so "has a session" is NOT "signed in". Anonymous users have no
27
+ * EXECUTE on the export RPCs, so asking the server for them is an error, not
28
+ * a verdict.
29
+ */
30
+ export declare function isSignedIn(session: SessionLike | null | undefined): boolean;
31
+ export interface AssessAccess {
32
+ /** Still finding out (the provider, or a signed-in user's companies). */
33
+ loading: boolean;
34
+ /** No Universal ID: no user, or an anonymous session. */
35
+ isGuest: boolean;
36
+ /** Signed in, and their companies loaded and there are none. */
37
+ noCompany: boolean;
38
+ /** The company a save or export belongs to; null for a company-less ID. */
39
+ orgId: string | null;
40
+ /** Saving is possible: signed in, settled, and either company-less or with a company. */
41
+ canSave: boolean;
42
+ /** The membership query failed (never read as "no company"). */
43
+ orgError: unknown;
44
+ userId: string | null;
45
+ }
46
+ /**
47
+ * Who is this, and where do their saves go — from what the SDK's
48
+ * useUniversal / useUser / useOrg report (the Assess free trial, 0215).
49
+ *
50
+ * `orgId` is null for a company-less ID even if a stale active-org cookie from
51
+ * another account is lying around (useOrg only repairs that when the user HAS
52
+ * companies), else the active company. ⚠️ A FAILED membership query is NOT
53
+ * "no company": it leaves canSave false rather than saving a company's work
54
+ * as a private row.
55
+ */
56
+ export declare function assessAccess(s: {
57
+ session: SessionLike | null | undefined;
58
+ user: {
59
+ id?: string;
60
+ } | null | undefined;
61
+ activeOrgId: string | null | undefined;
62
+ providerLoading: boolean;
63
+ orgs: readonly unknown[] | null | undefined;
64
+ orgsLoading: boolean;
65
+ orgsError: unknown;
66
+ }): AssessAccess;
67
+ //# sourceMappingURL=hub.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hub.d.ts","sourceRoot":"","sources":["../src/hub.ts"],"names":[],"mappings":"AAEA,kEAAkE;AAClE,eAAO,MAAM,OAAO,8BAA8B,CAAA;AAClD,yEAAyE;AACzE,eAAO,MAAM,aAAa,mCAAmC,CAAA;AAC7D,iFAAiF;AACjF,eAAO,MAAM,SAAS,sCAAsC,CAAA;AAC5D,2DAA2D;AAC3D,eAAO,MAAM,iBAAiB,sCAAsC,CAAA;AAEpE;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CAOtD;AAED,iDAAiD;AACjD,MAAM,WAAW,WAAW;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