@colixsystems/widget-sdk 0.319.2 → 0.321.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.
package/README.md CHANGED
@@ -42,6 +42,7 @@ The data layer lives in **four separate domain-client packages**, each instantia
42
42
  | **CORE** | `useRefresh(handler)` | `void` | `ctx.refresh.subscribe` — no scope. Subscribes the handler to the page-level refresh tick (pull-to-refresh on mobile). Handler may return a Promise — the host waits for `allSettled` before clearing the spinner. The three datastore hooks auto-subscribe their own `refetch`; widgets only call this directly to re-run non-datastore work. No-op on a host that doesn't implement refresh. |
43
43
  | **CORE** | `useClipboard()` | `{ copy, paste, hasContent }` | platform clipboard (web `navigator.clipboard` / native `expo-clipboard`); rejects with `ClipboardError` — no scope |
44
44
  | **CORE** | `useToast()` | `{ showToast }` | `ctx.toast.showToast` — wired by the Player and the Expo export; an authoring preview omits it and the call is a no-op — no scope |
45
+ | **CORE** | `useDeviceStorage(key, initial)` (optional: initial) | `{ value, setValue, remove, loaded, supported, error }` | `ctx.device.storage` — no scope. Keeps a small JSON value on this device across page changes, refreshes and app restarts: a guest's shopping bag before checkout, a dismissed tip, a last-picked filter. `setValue(next)` takes a value or `(previous) => next`; `remove()` returns `value` to `initial`. Every widget in the app using the same key sees a change at once (a header bag count and the bag itself stay in step), and on the web a change in another tab arrives without a reload; the last write wins. `key` is 1-64 letters, digits, `.`, `_` or `-`; a value is at most 16384 bytes as JSON. Values are per workspace and per device, shared by everyone using the app on that device, so never store a secret or personal data. Wait for `loaded` before acting on an empty value. `supported` is false when the device keeps nothing (a private window): the value lasts until the page closes. `error` is `{ code, message }` or null (`INVALID_KEY`, `INVALID_VALUE`, `TOO_LARGE`, `CORRUPT`, `NOT_PERSISTED`, `WRITE_FAILED`). Builder previews keep values in memory only. Web stores in `localStorage`, the Expo export in a file in the app's documents folder; never touch `localStorage` yourself. |
45
46
  | **CORE** | `useGeolocation(options)` (optional: options) | `{ latitude, longitude, accuracy, loading, error, getCurrentPosition, backgroundSupported, backgroundWatching, startBackgroundWatch, stopBackgroundWatch }` | `ctx.device.geolocation` — no scope. Capture is IMPERATIVE: call `getCurrentPosition()` from a user gesture (a tap), never on mount. Resolves to `{ latitude, longitude, accuracy }`; rejects with `GeolocationError` (`.code` in `PERMISSION_DENIED \| UNAVAILABLE \| TIMEOUT \| UNSUPPORTED \| INTERNAL`). Identical on web (`navigator.geolocation`) and the Expo export (`expo-location`). **Background watch** — `startBackgroundWatch({ enableHighAccuracy, distanceIntervalMeters, timeIntervalMs })` keeps positions arriving while the app is backgrounded; `stopBackgroundWatch()` releases it. NATIVE-ONLY and opt-in per app: gate the control on `backgroundSupported` (false on web, and in an export whose workspace did not opt in). The watch outlives the widget's mount, and its positions land in the same `latitude`/`longitude`/`accuracy` slots. |
46
47
  | **CORE** | `useSpeechToText(options)` (optional: options) | `{ transcript, partial, listening, supported, error, start, stop, abort, reset }` | `ctx.device.speech` — no scope. Dictation with the device's **on-device** recogniser: no audio is uploaded and no AI credit is spent. Capture is IMPERATIVE: call `start()` from a user gesture (a tap), never on mount. `transcript` accumulates finalised speech, `partial` holds the uncommitted guess (needs `options.interimResults`); `stop()` keeps it, `abort()` discards it. Rejects with `SpeechToTextError` (`.code` in `PERMISSION_DENIED \| NO_SPEECH \| LANGUAGE_UNSUPPORTED \| NETWORK \| ABORTED \| UNSUPPORTED \| INTERNAL`). **Gate your mic button on `supported`** — Firefox ships no `SpeechRecognition`. Identical on web (`SpeechRecognition`) and the Expo export (`expo-speech-recognition`). |
47
48
  | **CORE** | `useCamera(options)` (optional: options) | `{ asset, loading, error, supported, capture, pick, reset }` | `ctx.device.camera` — no scope. Take a photo (`capture()`) or choose one (`pick()`). Capture is IMPERATIVE: call from a user gesture (a tap), never on mount. Both resolve a normalised `{ uri, name, mimeType, width, height, size, file }`, or **`null` when the user dismisses the picker** — dismissal is not an error, so no `try/catch` is needed on the happy path. Rejects with `CameraError` (`.code` in `PERMISSION_DENIED \| UNSUPPORTED \| INTERNAL`). `asset.file` is already the right upload part for the host, so `fd.append("file", asset.file)` → `ctx.assets.upload(fd)` is ONE code path on both. **Gate your camera button on `supported`.** Identical on web (a live `getUserMedia` preview, phones included; a file input only where getUserMedia is absent) and the Expo export (`expo-image-picker`). |
@@ -72,7 +73,7 @@ The data layer lives in **four separate domain-client packages**, each instantia
72
73
  | **DIRECTORY** | `useUsers(query)` (optional: query) | `{ users, loading, error, refetch, invite, deactivate, reactivate, remove, sendPasswordReset, update }` | `directory.users.*` — `users.read:*` plus the `users.read` (or `users.write`) capability, else `FORBIDDEN` (edits, incl. `sendPasswordReset()` and `update()`, also `users.write:*`; `remove()` also `users.delete:*`) |
73
74
  | **DIRECTORY** | `useGroups(query)` (optional: query) | `{ groups, loading, error, refetch, create, remove, addMember, removeMember }` | `directory.groups.*` — `groups.read:*` (mutations also `groups.write:*`) |
74
75
  | **DIRECTORY** | `useInvites(query)` (optional: query) | `{ invites, loading, error, refetch, resend, revoke }` | `directory.invites.*` — `users.write:*` + the SystemAcl `users.write` capability (the whole invite surface, list included). `query` is `{ status?, q?, app_user_id?, limit?, offset? }` with `status` ∈ `pending \| accepted \| revoked \| expired \| not_sent \| open \| all` (endpoint default `all`; `open` = `pending`, `not_sent` or `expired`); `q` matches the invite's name or email, `app_user_id` returns the invites reserving that user id. `resend(inviteId)` sends the invitation — the first send of a `not_sent` one included. |
75
- | **DIRECTORY** | `useBankIdLink()` | `{ linked, available, status, qr, message, startLink, refresh, cancel, unlink, refetchStatus, … }` | `directory.bankid.*` — no scope (JWT-gated self-service) |
76
+ | **DIRECTORY** | `useBankIdLink()` | `{ linked, available, status, qr, message, startLink, refresh, cancel, unlink, refetchStatus, … }` | `directory.bankid.*` — no scope (JWT-gated self-service). While `pending`, render `qr` in an `<Image>` (`bankid-order-not-shown` otherwise). |
76
77
  | **FILESTORE** (`ctx.filestore`) | `usePdfExport({ spaceType, folderId })` (optional: spaceType, folderId) | `{ openPdf, opening, canOpenPdf, exportToPdf, exporting, error, lastExported }` | `ctx.filestore.files.renderPdf` + `ctx.device.pdfViewer`, `ctx.filestore.files.exportPdf` — `files.write:*`. `openPdf(html, { fileName? })` renders the HTML to a PDF server-side and OPENS it (web: PDF tab; native: print / share sheet) without saving. `exportToPdf(html, { fileName?, folderId? })` renders it and saves it as a file (`application/pdf`). Same server-side renderer on web + native. |
77
78
  | **PAYMENTS** (`ctx.payments`) | `useAccessPlans()` | `{ plans, loading, error, purchaseAvailable, purchase, cancel, refresh }` | `ctx.payments.{listAccessPlans,purchaseAccessPlan,cancelAccessPlan}` — `payments.charge:appUser`. Plans selling access to restricted pages; `purchase(planId)` names only the plan, the server sets price and group. `purchaseAvailable` is `false` in an iOS / Android build (digital goods need store billing): show a visible not-available state. |
78
79
  | **PAYMENTS** (`ctx.payments`) | `useAppSubscription()` | `{ subscription, loading, error, cancel, refresh }` | `ctx.payments.{getAppSubscription,cancelAppSubscription}` — `payments.charge:appUser`. The signed-in user's subscription to a paid app (`{ active, renews, access_ends_at }`); `cancel()` stops it renewing, and access runs to `access_ends_at`. |
@@ -80,7 +81,7 @@ The data layer lives in **four separate domain-client packages**, each instantia
80
81
  | **NOTIFICATIONS** (`ctx.notifications`) | `useSendNotification()` | `{ send, sending, error }` | `ctx.notifications.send` — `notifications.send:appUser`. `send({ recipient_user_id, title, body, link?, payload? })` notifies one app user in the same workspace; call from an event handler (never render); rejects with `NotificationError`. |
81
82
  | **NOTIFICATIONS** (`ctx.notifications`) | `useRecordMutes(tableId)` | `{ isMuted, loading, error, refetch }` | `ctx.notifications.mutes` — no scope. Which records of one table the signed-in user has muted, in one request for a whole list; `isMuted(recordId)` turns false when a timed mute lapses, and a `useRecordMute` write shows at once. |
82
83
  | **NOTIFICATIONS** (`ctx.notifications`) | `useRecordMute(tableId, recordId)` | `{ muted, mutedUntil, loading, error, mute, unmute, refetch }` | `ctx.notifications.mutes` — no scope. Mutes one record's notifications for the signed-in user, `mute(until)` with an ISO time, a `Date`, or `null` for until unmuted. Needs read access to the record (`RECORD_NOT_FOUND` otherwise). |
83
- | **IDENTIFICATION** (`ctx.identification`) | `useIdentification({ provider, purpose, pollIntervalMs })` (optional: every key, and the whole argument) | `{ available, status, qr, autoStartToken, message, identity, identificationId, start, refresh, cancel, reset, … }` | `ctx.identification.*` — no scope (the visitor is deliberately NOT signed in). Gate the UI on `available`; `start()` opens the order and the hook polls to completion. `identity` carries `personal_number_masked` + a stable `subject_hash` — never a raw personal number. |
84
+ | **IDENTIFICATION** (`ctx.identification`) | `useIdentification({ provider, purpose, pollIntervalMs })` (optional: every key, and the whole argument) | `{ available, status, qr, autoStartToken, message, identity, identificationId, start, refresh, cancel, reset, … }` | `ctx.identification.*` — no scope (the visitor is deliberately NOT signed in). Gate the UI on `available`; `start()` opens the order and the hook polls to completion. The hook draws nothing: while `pending`, render `qr` in an `<Image>` and a button calling `Linking.openURL(bankIdAppUrl(autoStartToken))`, or the publish-blocking `bankid-order-not-shown` finding refuses the widget. `identity` carries `personal_number_masked` + a stable `subject_hash` — never a raw personal number. |
84
85
 
85
86
  All list calls return the `{ data, meta }` envelope; the read hooks unwrap `res.data` for you. There is no `useWorkspace()` or `useLogger()` hook — read the theme via `useTheme()` and the locale via `useI18n()`; the host logger lives on `ctx.logger` (`{ debug, info, warn, error }`).
86
87
 
@@ -90,7 +91,20 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
90
91
 
91
92
  ## Status
92
93
 
93
- `v0.319.2` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
94
+ `v0.321.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
95
+
96
+ ### What's new in 0.321.0 (contract 1.261.0)
97
+
98
+ **The linter refuses a BankID order nobody can open.** `useIdentification()`, `useFileSignature()` and `useBankIdLink()` draw nothing: the widget shows the order. A widget that called `start()`, `initiate()` or `startLink()` and rendered only a "waiting" text passed every check, and BankID then ended each order unopened (`startFailed`). Starting an order without reading `qr` is now the publish-blocking `bankid-order-not-shown` finding, in `appstudio-widget lint` and in the platform's publish gate alike; `useIdentification` and `useFileSignature` must also read `autoStartToken`. Fix: while `pending`, render `<Image source={{ uri: qr }} />` and a button calling `Linking.openURL(bankIdAppUrl(autoStartToken))`. A widget that only reads a signature's status is not affected.
99
+
100
+ ### What's new in 0.320.0 (contract 1.260.0)
101
+
102
+ **New `useDeviceStorage()` hook: small values that stay on the device.** A widget can now keep a value across page changes, refreshes and app restarts without an account, such as a guest's shopping bag before checkout. `const { value, setValue, loaded } = useDeviceStorage("bag", [])` returns the stored JSON value, or the initial one until something is stored; `setValue` takes a value or `(previous) => next`, and `remove()` clears it. Every widget using the same key follows a change at once, so a header bag count and the bag stay in step, and on the web another tab follows without a reload. Keys are 1-64 letters, digits, `.`, `_` or `-`, and a value is at most 16384 bytes as JSON. Values are kept per workspace and per device, so never store a secret or personal data. `supported` is false where the device keeps nothing (a private window), and `error` names a refused, oversized or unreadable value. The web Player stores in `localStorage` and the Expo export in a file in the app's documents folder; widget code still may not touch `localStorage` itself. Additive.
103
+
104
+ ```jsx
105
+ const { value: bag, setValue: setBag, loaded } = useDeviceStorage("bag", []);
106
+ const add = (item) => setBag((items) => [...items, item]);
107
+ ```
94
108
 
95
109
  ### What's new in 0.319.2 (contract 1.259.0)
96
110
 
package/dist/contract.cjs CHANGED
@@ -2948,7 +2948,8 @@ const HOOKS = [
2948
2948
  "when BankID can't be used here (provider disabled or no platform cert) — " +
2949
2949
  "hide the Link affordance then. The link flow is an animated-QR poll like " +
2950
2950
  "useFileSignature: startLink() opens an order (status 'pending' + qr — a " +
2951
- "PNG data-URL, render with the Image primitive); refresh() polls (drive on " +
2951
+ "PNG data-URL the widget MUST render with the Image primitive while " +
2952
+ "pending, or the order cannot be opened); refresh() polls (drive on " +
2952
2953
  "a ~2s interval while pending; sets linked=true on complete); cancel() " +
2953
2954
  "aborts; unlink() removes the link (rejects DirectoryError LAST_AUTH_METHOD " +
2954
2955
  "when BankID is the only sign-in method). No requestedScopes entry needed.",
@@ -2956,7 +2957,7 @@ const HOOKS = [
2956
2957
  linked: "boolean | null // null until the status loads",
2957
2958
  available: "boolean // false → hide the Link affordance",
2958
2959
  status: "'pending' | 'complete' | 'failed' | 'cancelled' | null",
2959
- qr: "string | null // PNG data-URL of the animated BankID QR",
2960
+ qr: "string | null // PNG data-URL of the animated BankID QR; while pending the widget MUST render it in <Image source={{ uri: qr }} /> (the hook draws nothing)",
2960
2961
  message: "string | null",
2961
2962
  loading: "boolean",
2962
2963
  statusLoading: "boolean",
@@ -2988,12 +2989,18 @@ const HOOKS = [
2988
2989
  "to e-sign a file use useFileSignature(). On mount it reads provider " +
2989
2990
  "availability; `available` is false when identification can't be used here " +
2990
2991
  "(provider not configured) — render nothing rather than a dead button. " +
2991
- "start() opens an order (status 'pending' + qr, a PNG data-URL to render " +
2992
- "with the Image primitive) and the hook then POLLS to completion itself " +
2993
- "(pollIntervalMs, default 1000; pass 0 to drive refresh() yourself); " +
2994
- "cancel() aborts; reset() clears the flow. autoStartToken opens the " +
2995
- "provider app on the SAME device: Linking.openURL(bankIdAppUrl(" +
2996
- "autoStartToken)) opens bankid:///?autostarttoken=<token>&redirect=null. " +
2992
+ "start() opens an order (status 'pending') and the hook then POLLS to " +
2993
+ "completion itself (pollIntervalMs, default 1000; pass 0 to drive " +
2994
+ "refresh() yourself); cancel() aborts; reset() clears the flow. The hook " +
2995
+ "draws NOTHING: while status is 'pending' the widget MUST show both ways " +
2996
+ "to open the order, or BankID ends it unopened (hint startFailed) — " +
2997
+ "BankID on THIS device, the only way on a phone: a button, shown while " +
2998
+ "autoStartToken is set, whose onPress opens the app " +
2999
+ "(Linking.openURL(bankIdAppUrl(autoStartToken)) opens " +
3000
+ "bankid:///?autostarttoken=<token>&redirect=null); " +
3001
+ "BankID on ANOTHER device: qr (a PNG data-URL, a " +
3002
+ "new frame each poll) in <Image source={{ uri: qr }} />; plus message " +
3003
+ "beside them. The checker refuses a start() without both (bankid-order-not-shown). " +
2997
3004
  "On complete, `identity` is { provider, name, given_name, " +
2998
3005
  "surname, personal_number_masked, subject_hash, identified_at } — there is " +
2999
3006
  "NO raw personal number by design: write personal_number_masked " +
@@ -3005,8 +3012,8 @@ const HOOKS = [
3005
3012
  available: "boolean // false → don't offer the flow",
3006
3013
  availabilityLoading: "boolean",
3007
3014
  status: "'pending' | 'complete' | 'failed' | 'cancelled' | null",
3008
- qr: "string | null // PNG data-URL of the animated QR",
3009
- autoStartToken: "string | null // same-device deeplink token",
3015
+ qr: "string | null // PNG data-URL of the animated QR; while pending the widget MUST render it in <Image source={{ uri: qr }} /> (the hook draws nothing)",
3016
+ autoStartToken: "string | null // BankID on this device, the only way on a phone: while set the widget MUST show a button calling Linking.openURL(bankIdAppUrl(autoStartToken))",
3010
3017
  message: "string | null // display-ready instruction for this step",
3011
3018
  identity:
3012
3019
  "{ provider, name, given_name, surname, personal_number_masked, subject_hash, identified_at } | null",
@@ -3389,6 +3396,37 @@ const HOOKS = [
3389
3396
  requiredContextSlice: [],
3390
3397
  scopes: null,
3391
3398
  },
3399
+ // sc-16671 — host-brokered device storage. Optional slice; without it the
3400
+ // value lives in memory and the hook reports supported:false.
3401
+ {
3402
+ name: "useDeviceStorage",
3403
+ signature: "useDeviceStorage(key, initial)",
3404
+ optionalArgs: ["initial"],
3405
+ description:
3406
+ "Keep a small JSON value on this device across page changes, refreshes and app restarts — a guest's shopping bag, " +
3407
+ "a dismissed tip, a last-picked filter. Returns { value, setValue, remove, loaded, supported, error }. `value` is the " +
3408
+ "stored value, or `initial` until one is stored; setValue(next) stores a JSON value or (previous) => next; remove() " +
3409
+ "deletes it. Every widget in the app that uses the same key sees a change at once, and on the web a change in another " +
3410
+ "tab arrives without a reload; the last write wins. `key` is 1-64 letters, digits, '.', '_' or '-'; a value is at most " +
3411
+ "16384 bytes as JSON. Values are kept per workspace and per device, shared by everyone who uses the app on that device, " +
3412
+ "so NEVER store a password, token, card number or other secret or personal data — keep account data in the datastore. " +
3413
+ "Wait for `loaded` before acting on an empty value. `supported` is false when the device keeps nothing (a private " +
3414
+ "window, blocked storage): the value then lasts until the page closes. `error` is { code, message } or null: " +
3415
+ "INVALID_KEY | INVALID_VALUE | TOO_LARGE (nothing changed) | CORRUPT (the stored value was unreadable; `initial` is shown) | " +
3416
+ "NOT_PERSISTED (the device refused it, e.g. full; kept until the app closes) | WRITE_FAILED. In the Builder canvas and " +
3417
+ "widget previews values are kept in memory only. Never touch localStorage or window yourself — the linter refuses it. " +
3418
+ "Identical on web (localStorage) and the Expo export (a file in the app's documents folder).",
3419
+ returnShape: {
3420
+ value: "any // the stored JSON value, or `initial`",
3421
+ setValue: "(next | (previous) => next) => void",
3422
+ remove: "() => void",
3423
+ loaded: "boolean // the stored value has been read",
3424
+ supported: "boolean // false: kept in memory only",
3425
+ error: "{ code, message } | null",
3426
+ },
3427
+ requiredContextSlice: [],
3428
+ scopes: null,
3429
+ },
3392
3430
  // sc-6448 — host-brokered camera capture / photo picking. Optional slice;
3393
3431
  // the hook reports supported:false rather than throwing at render.
3394
3432
  {
@@ -4699,13 +4737,18 @@ const WIDGET_CONTEXT_SHAPE = {
4699
4737
  "{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
4700
4738
  "keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
4701
4739
  "repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
4740
+ "storage: { isSupported() -> boolean, read(key) -> Promise<string | null>, write(key, raw) -> Promise<boolean>, " +
4741
+ "remove(key) -> Promise<void>, subscribe(key, onChange(raw | null)) -> unsubscribe }, " +
4702
4742
  "purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
4703
4743
  "purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
4704
4744
  "purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
4705
4745
  "workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
4706
- "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and useKeyboard(). The web Player brokers them via " +
4707
- "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element and window key listeners; the Expo export via " +
4708
- "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-key-event. " +
4746
+ "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer(), useKeyboard() and useDeviceStorage(). The web Player brokers them via " +
4747
+ "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element, window key listeners and localStorage; the Expo export via " +
4748
+ "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio, expo-key-event and expo-file-system. " +
4749
+ "storage holds strings under keys scoped to the workspace; write resolves false when the device refused the value " +
4750
+ "(kept in memory instead) and notifies every subscriber of that key, as remove does with null; the web broker also " +
4751
+ "delivers other tabs' changes. " +
4709
4752
  "keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
4710
4753
  "pressed without Ctrl/Cmd/Alt, calls onRelease when the window or app loses focus or a text field opens and onDetected the first time any key " +
4711
4754
  "arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
@@ -4746,6 +4789,7 @@ const WIDGET_CONTEXT_SHAPE = {
4746
4789
  audioRecorder: "object",
4747
4790
  audioPlayer: "object",
4748
4791
  keyboard: "object",
4792
+ storage: "object",
4749
4793
  purchases: "object",
4750
4794
  },
4751
4795
  },
@@ -6975,7 +7019,11 @@ const CONTRACT = deepFreeze({
6975
7019
  // the publish-blocking `payment-kind-required` finding.
6976
7020
  // 1.259.0: `useDirectory()` / `useUsers()` rows carry `photo_url`, the
6977
7021
  // person's profile photo as an absolute URL or null.
6978
- version: "1.259.0",
7022
+ // 1.261.0: stricter lint (sc-17199) — starting a BankID order with
7023
+ // useIdentification / useFileSignature / useBankIdLink without rendering
7024
+ // its qr (and, where it exists, the autoStartToken button) is the
7025
+ // publish-blocking `bankid-order-not-shown` finding.
7026
+ version: "1.261.0",
6979
7027
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
6980
7028
  hooks: HOOKS,
6981
7029
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -2943,7 +2943,8 @@ const HOOKS = [
2943
2943
  "when BankID can't be used here (provider disabled or no platform cert) — " +
2944
2944
  "hide the Link affordance then. The link flow is an animated-QR poll like " +
2945
2945
  "useFileSignature: startLink() opens an order (status 'pending' + qr — a " +
2946
- "PNG data-URL, render with the Image primitive); refresh() polls (drive on " +
2946
+ "PNG data-URL the widget MUST render with the Image primitive while " +
2947
+ "pending, or the order cannot be opened); refresh() polls (drive on " +
2947
2948
  "a ~2s interval while pending; sets linked=true on complete); cancel() " +
2948
2949
  "aborts; unlink() removes the link (rejects DirectoryError LAST_AUTH_METHOD " +
2949
2950
  "when BankID is the only sign-in method). No requestedScopes entry needed.",
@@ -2951,7 +2952,7 @@ const HOOKS = [
2951
2952
  linked: "boolean | null // null until the status loads",
2952
2953
  available: "boolean // false → hide the Link affordance",
2953
2954
  status: "'pending' | 'complete' | 'failed' | 'cancelled' | null",
2954
- qr: "string | null // PNG data-URL of the animated BankID QR",
2955
+ qr: "string | null // PNG data-URL of the animated BankID QR; while pending the widget MUST render it in <Image source={{ uri: qr }} /> (the hook draws nothing)",
2955
2956
  message: "string | null",
2956
2957
  loading: "boolean",
2957
2958
  statusLoading: "boolean",
@@ -2983,12 +2984,18 @@ const HOOKS = [
2983
2984
  "to e-sign a file use useFileSignature(). On mount it reads provider " +
2984
2985
  "availability; `available` is false when identification can't be used here " +
2985
2986
  "(provider not configured) — render nothing rather than a dead button. " +
2986
- "start() opens an order (status 'pending' + qr, a PNG data-URL to render " +
2987
- "with the Image primitive) and the hook then POLLS to completion itself " +
2988
- "(pollIntervalMs, default 1000; pass 0 to drive refresh() yourself); " +
2989
- "cancel() aborts; reset() clears the flow. autoStartToken opens the " +
2990
- "provider app on the SAME device: Linking.openURL(bankIdAppUrl(" +
2991
- "autoStartToken)) opens bankid:///?autostarttoken=<token>&redirect=null. " +
2987
+ "start() opens an order (status 'pending') and the hook then POLLS to " +
2988
+ "completion itself (pollIntervalMs, default 1000; pass 0 to drive " +
2989
+ "refresh() yourself); cancel() aborts; reset() clears the flow. The hook " +
2990
+ "draws NOTHING: while status is 'pending' the widget MUST show both ways " +
2991
+ "to open the order, or BankID ends it unopened (hint startFailed) — " +
2992
+ "BankID on THIS device, the only way on a phone: a button, shown while " +
2993
+ "autoStartToken is set, whose onPress opens the app " +
2994
+ "(Linking.openURL(bankIdAppUrl(autoStartToken)) opens " +
2995
+ "bankid:///?autostarttoken=<token>&redirect=null); " +
2996
+ "BankID on ANOTHER device: qr (a PNG data-URL, a " +
2997
+ "new frame each poll) in <Image source={{ uri: qr }} />; plus message " +
2998
+ "beside them. The checker refuses a start() without both (bankid-order-not-shown). " +
2992
2999
  "On complete, `identity` is { provider, name, given_name, " +
2993
3000
  "surname, personal_number_masked, subject_hash, identified_at } — there is " +
2994
3001
  "NO raw personal number by design: write personal_number_masked " +
@@ -3000,8 +3007,8 @@ const HOOKS = [
3000
3007
  available: "boolean // false → don't offer the flow",
3001
3008
  availabilityLoading: "boolean",
3002
3009
  status: "'pending' | 'complete' | 'failed' | 'cancelled' | null",
3003
- qr: "string | null // PNG data-URL of the animated QR",
3004
- autoStartToken: "string | null // same-device deeplink token",
3010
+ qr: "string | null // PNG data-URL of the animated QR; while pending the widget MUST render it in <Image source={{ uri: qr }} /> (the hook draws nothing)",
3011
+ autoStartToken: "string | null // BankID on this device, the only way on a phone: while set the widget MUST show a button calling Linking.openURL(bankIdAppUrl(autoStartToken))",
3005
3012
  message: "string | null // display-ready instruction for this step",
3006
3013
  identity:
3007
3014
  "{ provider, name, given_name, surname, personal_number_masked, subject_hash, identified_at } | null",
@@ -3384,6 +3391,37 @@ const HOOKS = [
3384
3391
  requiredContextSlice: [],
3385
3392
  scopes: null,
3386
3393
  },
3394
+ // sc-16671 — host-brokered device storage. Optional slice; without it the
3395
+ // value lives in memory and the hook reports supported:false.
3396
+ {
3397
+ name: "useDeviceStorage",
3398
+ signature: "useDeviceStorage(key, initial)",
3399
+ optionalArgs: ["initial"],
3400
+ description:
3401
+ "Keep a small JSON value on this device across page changes, refreshes and app restarts — a guest's shopping bag, " +
3402
+ "a dismissed tip, a last-picked filter. Returns { value, setValue, remove, loaded, supported, error }. `value` is the " +
3403
+ "stored value, or `initial` until one is stored; setValue(next) stores a JSON value or (previous) => next; remove() " +
3404
+ "deletes it. Every widget in the app that uses the same key sees a change at once, and on the web a change in another " +
3405
+ "tab arrives without a reload; the last write wins. `key` is 1-64 letters, digits, '.', '_' or '-'; a value is at most " +
3406
+ "16384 bytes as JSON. Values are kept per workspace and per device, shared by everyone who uses the app on that device, " +
3407
+ "so NEVER store a password, token, card number or other secret or personal data — keep account data in the datastore. " +
3408
+ "Wait for `loaded` before acting on an empty value. `supported` is false when the device keeps nothing (a private " +
3409
+ "window, blocked storage): the value then lasts until the page closes. `error` is { code, message } or null: " +
3410
+ "INVALID_KEY | INVALID_VALUE | TOO_LARGE (nothing changed) | CORRUPT (the stored value was unreadable; `initial` is shown) | " +
3411
+ "NOT_PERSISTED (the device refused it, e.g. full; kept until the app closes) | WRITE_FAILED. In the Builder canvas and " +
3412
+ "widget previews values are kept in memory only. Never touch localStorage or window yourself — the linter refuses it. " +
3413
+ "Identical on web (localStorage) and the Expo export (a file in the app's documents folder).",
3414
+ returnShape: {
3415
+ value: "any // the stored JSON value, or `initial`",
3416
+ setValue: "(next | (previous) => next) => void",
3417
+ remove: "() => void",
3418
+ loaded: "boolean // the stored value has been read",
3419
+ supported: "boolean // false: kept in memory only",
3420
+ error: "{ code, message } | null",
3421
+ },
3422
+ requiredContextSlice: [],
3423
+ scopes: null,
3424
+ },
3387
3425
  // sc-6448 — host-brokered camera capture / photo picking. Optional slice;
3388
3426
  // the hook reports supported:false rather than throwing at render.
3389
3427
  {
@@ -4694,13 +4732,18 @@ const WIDGET_CONTEXT_SHAPE = {
4694
4732
  "{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
4695
4733
  "keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
4696
4734
  "repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
4735
+ "storage: { isSupported() -> boolean, read(key) -> Promise<string | null>, write(key, raw) -> Promise<boolean>, " +
4736
+ "remove(key) -> Promise<void>, subscribe(key, onChange(raw | null)) -> unsubscribe }, " +
4697
4737
  "purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
4698
4738
  "purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
4699
4739
  "purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
4700
4740
  "workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
4701
- "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and useKeyboard(). The web Player brokers them via " +
4702
- "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element and window key listeners; the Expo export via " +
4703
- "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-key-event. " +
4741
+ "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer(), useKeyboard() and useDeviceStorage(). The web Player brokers them via " +
4742
+ "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element, window key listeners and localStorage; the Expo export via " +
4743
+ "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio, expo-key-event and expo-file-system. " +
4744
+ "storage holds strings under keys scoped to the workspace; write resolves false when the device refused the value " +
4745
+ "(kept in memory instead) and notifies every subscriber of that key, as remove does with null; the web broker also " +
4746
+ "delivers other tabs' changes. " +
4704
4747
  "keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
4705
4748
  "pressed without Ctrl/Cmd/Alt, calls onRelease when the window or app loses focus or a text field opens and onDetected the first time any key " +
4706
4749
  "arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
@@ -4741,6 +4784,7 @@ const WIDGET_CONTEXT_SHAPE = {
4741
4784
  audioRecorder: "object",
4742
4785
  audioPlayer: "object",
4743
4786
  keyboard: "object",
4787
+ storage: "object",
4744
4788
  purchases: "object",
4745
4789
  },
4746
4790
  },
@@ -6970,7 +7014,11 @@ const CONTRACT = deepFreeze({
6970
7014
  // the publish-blocking `payment-kind-required` finding.
6971
7015
  // 1.259.0: `useDirectory()` / `useUsers()` rows carry `photo_url`, the
6972
7016
  // person's profile photo as an absolute URL or null.
6973
- version: "1.259.0",
7017
+ // 1.261.0: stricter lint (sc-17199) — starting a BankID order with
7018
+ // useIdentification / useFileSignature / useBankIdLink without rendering
7019
+ // its qr (and, where it exists, the autoStartToken button) is the
7020
+ // publish-blocking `bankid-order-not-shown` finding.
7021
+ version: "1.261.0",
6974
7022
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
6975
7023
  hooks: HOOKS,
6976
7024
  primitives: PRIMITIVES,
@@ -0,0 +1,168 @@
1
+ // sc-16671 — useDeviceStorage over ctx.device.storage, one source for both hosts.
2
+ // Brokers store strings; JSON, the key rule and the size cap live here.
3
+
4
+ import { useCallback, useEffect, useRef, useState } from "react";
5
+ import { useWidgetContextOrThrow } from "./hooks.js";
6
+
7
+ const DEVICE_STORAGE_KEY_PATTERN = /^[A-Za-z0-9._-]{1,64}$/;
8
+ const DEVICE_STORAGE_MAX_BYTES = 16384;
9
+
10
+ function isUsable(client) {
11
+ return Boolean(
12
+ client &&
13
+ typeof client.read === "function" &&
14
+ typeof client.write === "function" &&
15
+ typeof client.remove === "function" &&
16
+ typeof client.subscribe === "function",
17
+ );
18
+ }
19
+
20
+ function storageError(code, message) {
21
+ return { code, message };
22
+ }
23
+
24
+ /**
25
+ * Keep a small JSON value on this device, shared by every widget in the app
26
+ * that uses the same key. Returns `{ value, setValue, remove, loaded,
27
+ * supported, error }`.
28
+ *
29
+ * - `value` is the stored value, or `initial` until one is stored.
30
+ * - `setValue(next)` stores a JSON value or `(previous) => next`.
31
+ * - `remove()` deletes it; `value` returns to `initial`.
32
+ * - `loaded` turns true once the stored value has been read.
33
+ * - `supported` is false when the device keeps nothing (a private window,
34
+ * blocked storage): the value then lives in memory until the page closes.
35
+ * - `error` is `{ code, message }` or null. Codes: INVALID_KEY, INVALID_VALUE,
36
+ * TOO_LARGE, CORRUPT, NOT_PERSISTED, WRITE_FAILED.
37
+ */
38
+ export function useDeviceStorage(key, initial) {
39
+ const ctx = useWidgetContextOrThrow("useDeviceStorage");
40
+ const client = ctx.device && ctx.device.storage;
41
+ const validKey = typeof key === "string" && DEVICE_STORAGE_KEY_PATTERN.test(key);
42
+ const usable = validKey && isUsable(client);
43
+
44
+ const initialRef = useRef(initial);
45
+ initialRef.current = initial;
46
+
47
+ const fresh = () => ({
48
+ key,
49
+ value: initial,
50
+ loaded: !usable,
51
+ error: validKey ? null : storageError("INVALID_KEY", "Keys are 1-64 letters, digits, '.', '_' or '-'."),
52
+ });
53
+ const [stored, setState] = useState(fresh);
54
+ // A new key never shows, or builds an update on, the old key's value.
55
+ const state = stored.key === key ? stored : fresh();
56
+ if (state !== stored) setState(state);
57
+ const valueRef = useRef(state.value);
58
+ valueRef.current = state.value;
59
+ const writtenRef = useRef(false);
60
+ const lastWrittenRef = useRef(null);
61
+
62
+ useEffect(() => {
63
+ if (!usable) return undefined;
64
+ let live = true;
65
+ writtenRef.current = false;
66
+ lastWrittenRef.current = null;
67
+
68
+ const apply = (raw, fromRead) => {
69
+ if (!live || (fromRead && writtenRef.current)) return;
70
+ // Our own write echoed back: keep the value we already hold.
71
+ if (!fromRead && raw !== null && raw === lastWrittenRef.current) return;
72
+ lastWrittenRef.current = null;
73
+ if (raw === null || raw === undefined) {
74
+ setState({ key, value: initialRef.current, loaded: true, error: null });
75
+ return;
76
+ }
77
+ try {
78
+ setState({ key, value: JSON.parse(raw), loaded: true, error: null });
79
+ } catch {
80
+ setState({
81
+ key,
82
+ value: initialRef.current,
83
+ loaded: true,
84
+ error: storageError("CORRUPT", "The stored value was not valid JSON."),
85
+ });
86
+ }
87
+ };
88
+
89
+ const unsubscribe = client.subscribe(key, (raw) => apply(raw, false));
90
+ Promise.resolve()
91
+ .then(() => client.read(key))
92
+ .then(
93
+ (raw) => apply(raw, true),
94
+ () => apply(null, true),
95
+ );
96
+ return () => {
97
+ live = false;
98
+ if (typeof unsubscribe === "function") unsubscribe();
99
+ };
100
+ }, [client, key, usable]);
101
+
102
+ const setValue = useCallback(
103
+ (next) => {
104
+ const resolved = typeof next === "function" ? next(valueRef.current) : next;
105
+ let raw;
106
+ try {
107
+ raw = JSON.stringify(resolved);
108
+ } catch {
109
+ raw = undefined;
110
+ }
111
+ if (raw === undefined) {
112
+ setState((s) => ({ ...s, error: storageError("INVALID_VALUE", "Only JSON values can be stored.") }));
113
+ return;
114
+ }
115
+ if (new TextEncoder().encode(raw).length > DEVICE_STORAGE_MAX_BYTES) {
116
+ setState((s) => ({
117
+ ...s,
118
+ error: storageError("TOO_LARGE", `A stored value may be at most ${DEVICE_STORAGE_MAX_BYTES} bytes as JSON.`),
119
+ }));
120
+ return;
121
+ }
122
+ valueRef.current = resolved;
123
+ setState((s) => ({ ...s, value: resolved, loaded: true, error: null }));
124
+ if (!usable) return;
125
+ writtenRef.current = true;
126
+ lastWrittenRef.current = raw;
127
+ Promise.resolve()
128
+ .then(() => client.write(key, raw))
129
+ .then(
130
+ (persisted) => {
131
+ if (persisted === false) {
132
+ setState((s) => ({
133
+ ...s,
134
+ error: storageError("NOT_PERSISTED", "The device refused the value; it is kept until the app closes."),
135
+ }));
136
+ }
137
+ },
138
+ (err) => {
139
+ setState((s) => ({
140
+ ...s,
141
+ error: storageError("WRITE_FAILED", err && err.message ? err.message : String(err)),
142
+ }));
143
+ },
144
+ );
145
+ },
146
+ [client, key, usable],
147
+ );
148
+
149
+ const remove = useCallback(() => {
150
+ valueRef.current = initialRef.current;
151
+ setState({ key, value: initialRef.current, loaded: true, error: null });
152
+ if (!usable) return;
153
+ writtenRef.current = true;
154
+ lastWrittenRef.current = null;
155
+ Promise.resolve()
156
+ .then(() => client.remove(key))
157
+ .catch(() => {});
158
+ }, [client, key, usable]);
159
+
160
+ return {
161
+ value: state.value,
162
+ setValue,
163
+ remove,
164
+ loaded: state.loaded,
165
+ supported: usable && (typeof client.isSupported !== "function" || client.isSupported() !== false),
166
+ error: state.error,
167
+ };
168
+ }
package/dist/index.d.ts CHANGED
@@ -991,6 +991,15 @@ export interface WidgetContext<TProps = unknown> {
991
991
  onDetected(): void;
992
992
  }): () => void;
993
993
  };
994
+ /** sc-16671 — backs useDeviceStorage. Strings under workspace-scoped keys. */
995
+ storage?: {
996
+ isSupported?(): boolean;
997
+ read(key: string): Promise<string | null>;
998
+ /** False when the device refused the value and it is kept in memory. */
999
+ write(key: string, raw: string): Promise<boolean>;
1000
+ remove(key: string): Promise<void>;
1001
+ subscribe(key: string, onChange: (raw: string | null) => void): () => void;
1002
+ };
994
1003
  /** sc-15163 — backs usePurchases. Brokered by the Expo export only. */
995
1004
  purchases?: {
996
1005
  isSupported?(): boolean;
@@ -3237,6 +3246,33 @@ export interface KeyboardResult {
3237
3246
  */
3238
3247
  export function useKeyboard(options?: UseKeyboardOptions): KeyboardResult;
3239
3248
 
3249
+ export type DeviceStorageErrorCode =
3250
+ | "INVALID_KEY"
3251
+ | "INVALID_VALUE"
3252
+ | "TOO_LARGE"
3253
+ | "CORRUPT"
3254
+ | "NOT_PERSISTED"
3255
+ | "WRITE_FAILED";
3256
+
3257
+ export interface DeviceStorageResult<T> {
3258
+ /** The stored value, or `initial` until one is stored. */
3259
+ value: T;
3260
+ setValue(next: T | ((previous: T) => T)): void;
3261
+ remove(): void;
3262
+ /** The stored value has been read. */
3263
+ loaded: boolean;
3264
+ /** False when the device keeps nothing; the value lives in memory. */
3265
+ supported: boolean;
3266
+ error: { code: DeviceStorageErrorCode; message: string } | null;
3267
+ }
3268
+
3269
+ /**
3270
+ * A small JSON value kept on this device per workspace, shared live by every
3271
+ * widget using the same key: localStorage on the web Player, a file in the
3272
+ * documents folder in the Expo export. Never store secrets or personal data.
3273
+ */
3274
+ export function useDeviceStorage<T = unknown>(key: string, initial?: T): DeviceStorageResult<T>;
3275
+
3240
3276
  /** One package of the current offering, as the store prices it. */
3241
3277
  export interface PurchasePackage {
3242
3278
  id: string;
package/dist/index.js CHANGED
@@ -138,6 +138,8 @@ export {
138
138
  } from "./audio.js";
139
139
  // sc-15908 — one host-brokered source for both entries (ctx.device.keyboard).
140
140
  export { useKeyboard } from "./keyboard.js";
141
+ // sc-16671 — one host-brokered source for both entries (ctx.device.storage).
142
+ export { useDeviceStorage } from "./device-storage.js";
141
143
  // sc-15163 — native-only in-app purchase; the web Player brokers none.
142
144
  export { usePurchases, PurchasesError } from "./purchases.js";
143
145
  export { useDatastoreFigure } from "./datastore-figure.js";
@@ -136,6 +136,8 @@ export {
136
136
  } from "./audio.js";
137
137
  // sc-15908 — one host-brokered source for both entries (ctx.device.keyboard).
138
138
  export { useKeyboard } from "./keyboard.js";
139
+ // sc-16671 — one host-brokered source for both entries (ctx.device.storage).
140
+ export { useDeviceStorage } from "./device-storage.js";
139
141
  // sc-15163 — native-only in-app purchase; the web Player brokers none.
140
142
  export { usePurchases, PurchasesError } from "./purchases.js";
141
143
  export { useDatastoreFigure } from "./datastore-figure.js";
package/dist/linter.cjs CHANGED
@@ -1769,6 +1769,68 @@ function _datastoreErrorHandlingRules(source) {
1769
1769
  ];
1770
1770
  }
1771
1771
 
1772
+ // sc-17199 — a BankID order the user cannot open. The hooks draw nothing, so a
1773
+ // widget that starts one without its QR or same-device button shows only
1774
+ // "waiting" and BankID ends the order unopened (startFailed).
1775
+ const BANKID_ORDER_HOOKS = [
1776
+ { hook: "useIdentification", verb: "start", sameDevice: true },
1777
+ { hook: "useFileSignature", verb: "initiate", sameDevice: true },
1778
+ { hook: "useBankIdLink", verb: "startLink", sameDevice: false },
1779
+ ];
1780
+
1781
+ function _destructuredLocals(pattern) {
1782
+ const locals = {};
1783
+ for (const part of pattern.slice(1, -1).split(",")) {
1784
+ const m = /^\s*(\w+)\s*(?::\s*([\w$]+))?/.exec(part);
1785
+ if (m) locals[m[1]] = m[2] || m[1];
1786
+ }
1787
+ return locals;
1788
+ }
1789
+
1790
+ // Which reads of a binding count: `idn.qr` on an object, the local name on a destructure.
1791
+ function _bankIdOrderReads(binding) {
1792
+ const escaped = (name) => name.replace(/\$/g, "\\$");
1793
+ if (!binding.startsWith("{")) {
1794
+ const name = escaped(binding);
1795
+ const member = (field) => new RegExp(String.raw`(?<![\w$])${name}\s*\??\.\s*${field}(?![\w$])`);
1796
+ // Handed whole to a child component, which draws the order itself.
1797
+ const handedOn = new RegExp(String.raw`=\{\s*${name}\s*\}|\.\.\.\s*${name}(?![\w$])`);
1798
+ return { read: member, handedOn };
1799
+ }
1800
+ const locals = _destructuredLocals(binding);
1801
+ const word = (local) => new RegExp(String.raw`(?<![\w$.])${escaped(local)}(?![\w$])`);
1802
+ return { read: (field) => (locals[field] ? word(locals[field]) : null), handedOn: null };
1803
+ }
1804
+
1805
+ function _bankIdOrderRules(source) {
1806
+ const code = _stripNonCode(source);
1807
+ const findings = [];
1808
+ for (const { hook, verb, sameDevice } of BANKID_ORDER_HOOKS) {
1809
+ const bindings = new RegExp(String.raw`\b(?:const|let|var)\s+([\w$]+|\{[^{}]*\})\s*=\s*${hook}\s*\(`, "g");
1810
+ for (const call of code.matchAll(bindings)) {
1811
+ // The destructure itself names every field; only reads elsewhere count.
1812
+ const rest = code.slice(0, call.index) + " ".repeat(call[0].length) + code.slice(call.index + call[0].length);
1813
+ const { read, handedOn } = _bankIdOrderReads(call[1]);
1814
+ const reads = (field) => !!read(field) && read(field).test(rest);
1815
+ if (!reads(verb) || (handedOn && handedOn.test(rest))) continue;
1816
+ if (reads("qr") && (!sameDevice || reads("autoStartToken"))) continue;
1817
+ const line = code.slice(0, call.index).split(/\r?\n/).length;
1818
+ findings.push({
1819
+ rule: "bankid-order-not-shown",
1820
+ severity: "error",
1821
+ label:
1822
+ `${hook}().${verb}() opens a BankID order the widget never shows. While pending render ` +
1823
+ `<Image source={{ uri: qr }} />` +
1824
+ (sameDevice ? ` and a button calling Linking.openURL(bankIdAppUrl(autoStartToken))` : "") +
1825
+ `, or BankID ends it unopened.`,
1826
+ line,
1827
+ snippet: (source.split(/\r?\n/)[line - 1] || "").trim().slice(0, 200),
1828
+ });
1829
+ }
1830
+ }
1831
+ return findings;
1832
+ }
1833
+
1772
1834
  // sc-16511 — soft warning, the read twin of `datastore-error-not-branched`.
1773
1835
  // A read refused because the viewer may not see the table (a signed-out
1774
1836
  // visitor gets NOT_FOUND, a signed-in one FORBIDDEN) never clears on a retry,
@@ -3502,6 +3564,7 @@ function lintSource(source, options) {
3502
3564
  findings.push(..._paymentErrorHandlingRules(source));
3503
3565
  findings.push(..._datastoreErrorHandlingRules(source));
3504
3566
  findings.push(..._readErrorHandlingRules(source));
3567
+ findings.push(..._bankIdOrderRules(source));
3505
3568
  // sc-5206 — soft warnings steering a widget toward the two new hooks.
3506
3569
  findings.push(..._rawUseMemoIntoDatastoreQueryRules(source));
3507
3570
  findings.push(..._handRolledWriteGateRules(source));
package/dist/linter.js CHANGED
@@ -1764,6 +1764,68 @@ function _datastoreErrorHandlingRules(source) {
1764
1764
  ];
1765
1765
  }
1766
1766
 
1767
+ // sc-17199 — a BankID order the user cannot open. The hooks draw nothing, so a
1768
+ // widget that starts one without its QR or same-device button shows only
1769
+ // "waiting" and BankID ends the order unopened (startFailed).
1770
+ const BANKID_ORDER_HOOKS = [
1771
+ { hook: "useIdentification", verb: "start", sameDevice: true },
1772
+ { hook: "useFileSignature", verb: "initiate", sameDevice: true },
1773
+ { hook: "useBankIdLink", verb: "startLink", sameDevice: false },
1774
+ ];
1775
+
1776
+ function _destructuredLocals(pattern) {
1777
+ const locals = {};
1778
+ for (const part of pattern.slice(1, -1).split(",")) {
1779
+ const m = /^\s*(\w+)\s*(?::\s*([\w$]+))?/.exec(part);
1780
+ if (m) locals[m[1]] = m[2] || m[1];
1781
+ }
1782
+ return locals;
1783
+ }
1784
+
1785
+ // Which reads of a binding count: `idn.qr` on an object, the local name on a destructure.
1786
+ function _bankIdOrderReads(binding) {
1787
+ const escaped = (name) => name.replace(/\$/g, "\\$");
1788
+ if (!binding.startsWith("{")) {
1789
+ const name = escaped(binding);
1790
+ const member = (field) => new RegExp(String.raw`(?<![\w$])${name}\s*\??\.\s*${field}(?![\w$])`);
1791
+ // Handed whole to a child component, which draws the order itself.
1792
+ const handedOn = new RegExp(String.raw`=\{\s*${name}\s*\}|\.\.\.\s*${name}(?![\w$])`);
1793
+ return { read: member, handedOn };
1794
+ }
1795
+ const locals = _destructuredLocals(binding);
1796
+ const word = (local) => new RegExp(String.raw`(?<![\w$.])${escaped(local)}(?![\w$])`);
1797
+ return { read: (field) => (locals[field] ? word(locals[field]) : null), handedOn: null };
1798
+ }
1799
+
1800
+ function _bankIdOrderRules(source) {
1801
+ const code = _stripNonCode(source);
1802
+ const findings = [];
1803
+ for (const { hook, verb, sameDevice } of BANKID_ORDER_HOOKS) {
1804
+ const bindings = new RegExp(String.raw`\b(?:const|let|var)\s+([\w$]+|\{[^{}]*\})\s*=\s*${hook}\s*\(`, "g");
1805
+ for (const call of code.matchAll(bindings)) {
1806
+ // The destructure itself names every field; only reads elsewhere count.
1807
+ const rest = code.slice(0, call.index) + " ".repeat(call[0].length) + code.slice(call.index + call[0].length);
1808
+ const { read, handedOn } = _bankIdOrderReads(call[1]);
1809
+ const reads = (field) => !!read(field) && read(field).test(rest);
1810
+ if (!reads(verb) || (handedOn && handedOn.test(rest))) continue;
1811
+ if (reads("qr") && (!sameDevice || reads("autoStartToken"))) continue;
1812
+ const line = code.slice(0, call.index).split(/\r?\n/).length;
1813
+ findings.push({
1814
+ rule: "bankid-order-not-shown",
1815
+ severity: "error",
1816
+ label:
1817
+ `${hook}().${verb}() opens a BankID order the widget never shows. While pending render ` +
1818
+ `<Image source={{ uri: qr }} />` +
1819
+ (sameDevice ? ` and a button calling Linking.openURL(bankIdAppUrl(autoStartToken))` : "") +
1820
+ `, or BankID ends it unopened.`,
1821
+ line,
1822
+ snippet: (source.split(/\r?\n/)[line - 1] || "").trim().slice(0, 200),
1823
+ });
1824
+ }
1825
+ }
1826
+ return findings;
1827
+ }
1828
+
1767
1829
  // sc-16511 — soft warning, the read twin of `datastore-error-not-branched`.
1768
1830
  // A read refused because the viewer may not see the table (a signed-out
1769
1831
  // visitor gets NOT_FOUND, a signed-in one FORBIDDEN) never clears on a retry,
@@ -3497,6 +3559,7 @@ export function lintSource(source, options) {
3497
3559
  findings.push(..._paymentErrorHandlingRules(source));
3498
3560
  findings.push(..._datastoreErrorHandlingRules(source));
3499
3561
  findings.push(..._readErrorHandlingRules(source));
3562
+ findings.push(..._bankIdOrderRules(source));
3500
3563
  // sc-5206 — soft warnings steering a widget toward the two new hooks.
3501
3564
  findings.push(..._rawUseMemoIntoDatastoreQueryRules(source));
3502
3565
  findings.push(..._handRolledWriteGateRules(source));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.319.2",
3
+ "version": "0.321.0",
4
4
  "description": "Common widget interface for AppStudio. Implements WidgetManifest, WidgetContext, property schema, and helper hooks.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/contract.js CHANGED
@@ -2943,7 +2943,8 @@ const HOOKS = [
2943
2943
  "when BankID can't be used here (provider disabled or no platform cert) — " +
2944
2944
  "hide the Link affordance then. The link flow is an animated-QR poll like " +
2945
2945
  "useFileSignature: startLink() opens an order (status 'pending' + qr — a " +
2946
- "PNG data-URL, render with the Image primitive); refresh() polls (drive on " +
2946
+ "PNG data-URL the widget MUST render with the Image primitive while " +
2947
+ "pending, or the order cannot be opened); refresh() polls (drive on " +
2947
2948
  "a ~2s interval while pending; sets linked=true on complete); cancel() " +
2948
2949
  "aborts; unlink() removes the link (rejects DirectoryError LAST_AUTH_METHOD " +
2949
2950
  "when BankID is the only sign-in method). No requestedScopes entry needed.",
@@ -2951,7 +2952,7 @@ const HOOKS = [
2951
2952
  linked: "boolean | null // null until the status loads",
2952
2953
  available: "boolean // false → hide the Link affordance",
2953
2954
  status: "'pending' | 'complete' | 'failed' | 'cancelled' | null",
2954
- qr: "string | null // PNG data-URL of the animated BankID QR",
2955
+ qr: "string | null // PNG data-URL of the animated BankID QR; while pending the widget MUST render it in <Image source={{ uri: qr }} /> (the hook draws nothing)",
2955
2956
  message: "string | null",
2956
2957
  loading: "boolean",
2957
2958
  statusLoading: "boolean",
@@ -2983,12 +2984,18 @@ const HOOKS = [
2983
2984
  "to e-sign a file use useFileSignature(). On mount it reads provider " +
2984
2985
  "availability; `available` is false when identification can't be used here " +
2985
2986
  "(provider not configured) — render nothing rather than a dead button. " +
2986
- "start() opens an order (status 'pending' + qr, a PNG data-URL to render " +
2987
- "with the Image primitive) and the hook then POLLS to completion itself " +
2988
- "(pollIntervalMs, default 1000; pass 0 to drive refresh() yourself); " +
2989
- "cancel() aborts; reset() clears the flow. autoStartToken opens the " +
2990
- "provider app on the SAME device: Linking.openURL(bankIdAppUrl(" +
2991
- "autoStartToken)) opens bankid:///?autostarttoken=<token>&redirect=null. " +
2987
+ "start() opens an order (status 'pending') and the hook then POLLS to " +
2988
+ "completion itself (pollIntervalMs, default 1000; pass 0 to drive " +
2989
+ "refresh() yourself); cancel() aborts; reset() clears the flow. The hook " +
2990
+ "draws NOTHING: while status is 'pending' the widget MUST show both ways " +
2991
+ "to open the order, or BankID ends it unopened (hint startFailed) — " +
2992
+ "BankID on THIS device, the only way on a phone: a button, shown while " +
2993
+ "autoStartToken is set, whose onPress opens the app " +
2994
+ "(Linking.openURL(bankIdAppUrl(autoStartToken)) opens " +
2995
+ "bankid:///?autostarttoken=<token>&redirect=null); " +
2996
+ "BankID on ANOTHER device: qr (a PNG data-URL, a " +
2997
+ "new frame each poll) in <Image source={{ uri: qr }} />; plus message " +
2998
+ "beside them. The checker refuses a start() without both (bankid-order-not-shown). " +
2992
2999
  "On complete, `identity` is { provider, name, given_name, " +
2993
3000
  "surname, personal_number_masked, subject_hash, identified_at } — there is " +
2994
3001
  "NO raw personal number by design: write personal_number_masked " +
@@ -3000,8 +3007,8 @@ const HOOKS = [
3000
3007
  available: "boolean // false → don't offer the flow",
3001
3008
  availabilityLoading: "boolean",
3002
3009
  status: "'pending' | 'complete' | 'failed' | 'cancelled' | null",
3003
- qr: "string | null // PNG data-URL of the animated QR",
3004
- autoStartToken: "string | null // same-device deeplink token",
3010
+ qr: "string | null // PNG data-URL of the animated QR; while pending the widget MUST render it in <Image source={{ uri: qr }} /> (the hook draws nothing)",
3011
+ autoStartToken: "string | null // BankID on this device, the only way on a phone: while set the widget MUST show a button calling Linking.openURL(bankIdAppUrl(autoStartToken))",
3005
3012
  message: "string | null // display-ready instruction for this step",
3006
3013
  identity:
3007
3014
  "{ provider, name, given_name, surname, personal_number_masked, subject_hash, identified_at } | null",
@@ -3384,6 +3391,37 @@ const HOOKS = [
3384
3391
  requiredContextSlice: [],
3385
3392
  scopes: null,
3386
3393
  },
3394
+ // sc-16671 — host-brokered device storage. Optional slice; without it the
3395
+ // value lives in memory and the hook reports supported:false.
3396
+ {
3397
+ name: "useDeviceStorage",
3398
+ signature: "useDeviceStorage(key, initial)",
3399
+ optionalArgs: ["initial"],
3400
+ description:
3401
+ "Keep a small JSON value on this device across page changes, refreshes and app restarts — a guest's shopping bag, " +
3402
+ "a dismissed tip, a last-picked filter. Returns { value, setValue, remove, loaded, supported, error }. `value` is the " +
3403
+ "stored value, or `initial` until one is stored; setValue(next) stores a JSON value or (previous) => next; remove() " +
3404
+ "deletes it. Every widget in the app that uses the same key sees a change at once, and on the web a change in another " +
3405
+ "tab arrives without a reload; the last write wins. `key` is 1-64 letters, digits, '.', '_' or '-'; a value is at most " +
3406
+ "16384 bytes as JSON. Values are kept per workspace and per device, shared by everyone who uses the app on that device, " +
3407
+ "so NEVER store a password, token, card number or other secret or personal data — keep account data in the datastore. " +
3408
+ "Wait for `loaded` before acting on an empty value. `supported` is false when the device keeps nothing (a private " +
3409
+ "window, blocked storage): the value then lasts until the page closes. `error` is { code, message } or null: " +
3410
+ "INVALID_KEY | INVALID_VALUE | TOO_LARGE (nothing changed) | CORRUPT (the stored value was unreadable; `initial` is shown) | " +
3411
+ "NOT_PERSISTED (the device refused it, e.g. full; kept until the app closes) | WRITE_FAILED. In the Builder canvas and " +
3412
+ "widget previews values are kept in memory only. Never touch localStorage or window yourself — the linter refuses it. " +
3413
+ "Identical on web (localStorage) and the Expo export (a file in the app's documents folder).",
3414
+ returnShape: {
3415
+ value: "any // the stored JSON value, or `initial`",
3416
+ setValue: "(next | (previous) => next) => void",
3417
+ remove: "() => void",
3418
+ loaded: "boolean // the stored value has been read",
3419
+ supported: "boolean // false: kept in memory only",
3420
+ error: "{ code, message } | null",
3421
+ },
3422
+ requiredContextSlice: [],
3423
+ scopes: null,
3424
+ },
3387
3425
  // sc-6448 — host-brokered camera capture / photo picking. Optional slice;
3388
3426
  // the hook reports supported:false rather than throwing at render.
3389
3427
  {
@@ -4694,13 +4732,18 @@ const WIDGET_CONTEXT_SHAPE = {
4694
4732
  "{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
4695
4733
  "keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
4696
4734
  "repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
4735
+ "storage: { isSupported() -> boolean, read(key) -> Promise<string | null>, write(key, raw) -> Promise<boolean>, " +
4736
+ "remove(key) -> Promise<void>, subscribe(key, onChange(raw | null)) -> unsubscribe }, " +
4697
4737
  "purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
4698
4738
  "purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
4699
4739
  "purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
4700
4740
  "workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
4701
- "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and useKeyboard(). The web Player brokers them via " +
4702
- "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element and window key listeners; the Expo export via " +
4703
- "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-key-event. " +
4741
+ "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer(), useKeyboard() and useDeviceStorage(). The web Player brokers them via " +
4742
+ "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder, an <audio> element, window key listeners and localStorage; the Expo export via " +
4743
+ "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio, expo-key-event and expo-file-system. " +
4744
+ "storage holds strings under keys scoped to the workspace; write resolves false when the device refused the value " +
4745
+ "(kept in memory instead) and notifies every subscriber of that key, as remove does with null; the web broker also " +
4746
+ "delivers other tabs' changes. " +
4704
4747
  "keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
4705
4748
  "pressed without Ctrl/Cmd/Alt, calls onRelease when the window or app loses focus or a text field opens and onDetected the first time any key " +
4706
4749
  "arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
@@ -4741,6 +4784,7 @@ const WIDGET_CONTEXT_SHAPE = {
4741
4784
  audioRecorder: "object",
4742
4785
  audioPlayer: "object",
4743
4786
  keyboard: "object",
4787
+ storage: "object",
4744
4788
  purchases: "object",
4745
4789
  },
4746
4790
  },
@@ -6970,7 +7014,11 @@ const CONTRACT = deepFreeze({
6970
7014
  // the publish-blocking `payment-kind-required` finding.
6971
7015
  // 1.259.0: `useDirectory()` / `useUsers()` rows carry `photo_url`, the
6972
7016
  // person's profile photo as an absolute URL or null.
6973
- version: "1.259.0",
7017
+ // 1.261.0: stricter lint (sc-17199) — starting a BankID order with
7018
+ // useIdentification / useFileSignature / useBankIdLink without rendering
7019
+ // its qr (and, where it exists, the autoStartToken button) is the
7020
+ // publish-blocking `bankid-order-not-shown` finding.
7021
+ version: "1.261.0",
6974
7022
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
6975
7023
  hooks: HOOKS,
6976
7024
  primitives: PRIMITIVES,