@colixsystems/widget-sdk 0.293.0 → 0.296.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
@@ -76,7 +76,7 @@ The data layer lives in **four separate domain-client packages**, each instantia
76
76
  | **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
77
  | **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
78
  | **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`. |
79
- | **PAYMENTS** (`ctx.payments`) | `usePayments()` | `{ requestPayment, getPayment }` | `ctx.payments.*` — `payments.charge:appUser`. `requestPayment` requires `kind` (`"physical"` \| `"service"` \| `"digital"`): what is sold. A `"digital"` charge is refused in an iOS or Android build (`DIGITAL_SALE_NEEDS_STORE_BILLING`). Rejects with `PaymentError { code, message, retryable }`; when `retryable` is `false` show `message` and drop the retry. Charges are accepted ONLY in the currency the workspace sells in — omit `currency` and the platform applies it (a disagreeing literal is a publish-blocking `payment-currency` finding). |
79
+ | **PAYMENTS** (`ctx.payments`) | `usePayments()` | `{ requestPayment, getPayment, requestGuestPayment, getGuestPayment }` | `ctx.payments.*` — `payments.charge:appUser`; guest checkout (`requestGuestPayment`, a visitor with no account buying physical goods for an order they created) also `payments.charge:guest`. `requestPayment` requires `kind` (`"physical"` \| `"service"` \| `"digital"`): what is sold. A `"digital"` charge is refused in an iOS or Android build (`DIGITAL_SALE_NEEDS_STORE_BILLING`). Rejects with `PaymentError { code, message, retryable }`; when `retryable` is `false` show `message` and drop the retry. Charges are accepted ONLY in the currency the workspace sells in — omit `currency` and the platform applies it (a disagreeing literal is a publish-blocking `payment-currency` finding). |
80
80
  | **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
81
  | **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
82
  | **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). |
@@ -90,7 +90,20 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
90
90
 
91
91
  ## Status
92
92
 
93
- `v0.293.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**.
93
+ `v0.296.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**.
94
+
95
+ ### What's new in 0.296.0 (contract 1.243.0)
96
+
97
+ **New `useKeyboard()` hook: hardware keyboard input on both hosts.** A game or an editor no longer needs `onKeyDown` on a focused `View`, which stopped hearing keys the moment focus moved. `useKeyboard({ keys, onKeyDown, onKeyUp, active })` returns `{ supported, pressed }`. Key names are `KeyboardEvent.code` values on every host (`ArrowLeft`, `KeyW`, `Space`), so they do not change with the keyboard layout, and `pressed` is the set held right now. Name the keys the widget handles in `keys`: only those are delivered, and the host stops their browser default, so arrows and Space no longer scroll the page. On the web, keys keep arriving after a click elsewhere on the page; a focused button or link keeps Enter and Space, and a slider, list or tab set keeps its keys. On iOS and Android, keys pause while a text field is open. Keys typed into a text field are never delivered. Held keys are released, each with an `onKeyUp`, when the window or app loses focus or a text field opens, so a character never keeps running. `onKeyDown` repeats while a key is held on the web and Android; iOS sends one per press. `supported` is true where a keyboard is present (a mouse or trackpad on the web, or once any key is pressed); false means none has been seen yet, so show touch controls. In the Builder canvas and widget previews keys arrive only while the preview has focus. The web Player listens on the window; the Expo export reads iPad and phone hardware keyboards through `expo-key-event`. Additive.
98
+
99
+ ```js
100
+ const { supported, pressed } = useKeyboard({ keys: ["ArrowLeft", "ArrowRight", "Space"] });
101
+ const dx = (pressed.has("ArrowRight") ? 1 : 0) - (pressed.has("ArrowLeft") ? 1 : 0);
102
+ ```
103
+
104
+ ### What's new in 0.295.0 (contract 1.242.0)
105
+
106
+ **Guest checkout: a visitor who is not signed in can pay for physical goods.** `usePayments()` gains `requestGuestPayment({ amount_cents, currency?, description, return_path?, order })` and `getGuestPayment(paymentId)`. There is no `kind`: a guest buys physical goods only, and the shipping address and contact live on the order. So `order` is required, and it must be a row the visitor created with `useDatastoreMutation().create` in the last 15 minutes, in a table with a payment-status column that the maker lets everyone add rows to (and nobody read). Only that visitor can pay for it. The host runs a security check, opens hosted Checkout as for `requestPayment`, and keeps the guest's one-time credential; `getGuestPayment(id)` reads the payment back with it, so a widget passes only the id. The widget also needs the `payments.charge:guest` scope, and the workspace must offer guest checkout. New `PaymentError` codes: `TRIAL_RESTRICTED` (non-retryable), and the retryable `GUEST_CHECKOUT_LIMIT_REACHED`, `CAPTCHA_FAILED` and `CAPTCHA_UNAVAILABLE`. The injected payments client gains `requestGuestPayment()` and `getGuestPayment()` (`@colixsystems/payments-client` 0.7.0). Additive.
94
107
 
95
108
  ### What's new in 0.293.0 (contract 1.240.0)
96
109
 
package/dist/contract.cjs CHANGED
@@ -2428,6 +2428,10 @@ const HOOKS = [
2428
2428
  "({ amount_cents, currency?, description, kind, return_path?, order? }) => Promise<{ id, status, order }> // kind is REQUIRED: \"physical\" | \"service\" | \"digital\" — what is sold; a digital charge is refused in an iOS/Android build (DIGITAL_SALE_NEEDS_STORE_BILLING); order: { table_id, record_id } — the order row this pays for, in a table with a payment-status column; the SERVER marks it paid when the payment settles, so never write \"paid\" yourself (refused: ORDER_NOT_FOUND, ORDER_NOT_PAYABLE, ORDER_ALREADY_PAID; ORDER_PAYMENT_IN_PROGRESS is retryable while another checkout for the order is open); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2429
2429
  getPayment:
2430
2430
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // order: { table_id, record_id } | null — read it after returning from Checkout",
2431
+ requestGuestPayment:
2432
+ "({ amount_cents, currency?, description, return_path?, order }) => Promise<{ id, status, order }> // a visitor who is NOT signed in buys physical goods (no kind). order is REQUIRED: create the order row first with useDatastoreMutation().create (the maker lets everyone add rows to the orders table and nobody read them; collect the shipping address and contact there), then pay for it within 15 minutes — only the visitor who created it can. Needs the payments.charge:guest scope too. The host runs a security check and opens hosted Checkout. Refused: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable), CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), NOT_FOUND where the shop does not offer guest checkout, plus the requestPayment refusals",
2433
+ getGuestPayment:
2434
+ "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // a guest's status read; the host holds the guest's one-time credential, so pass only the id",
2431
2435
  },
2432
2436
  requiredContextSlice: ["payments.requestPayment"],
2433
2437
  scopes: ["payments.charge:appUser"],
@@ -3323,6 +3327,36 @@ const HOOKS = [
3323
3327
  requiredContextSlice: [],
3324
3328
  scopes: null,
3325
3329
  },
3330
+ // sc-15908 — host-brokered hardware keyboard. Optional slice; the hook
3331
+ // reports supported:false rather than throwing at render.
3332
+ {
3333
+ name: "useKeyboard",
3334
+ signature: "useKeyboard({ keys, onKeyDown, onKeyUp, active })",
3335
+ description:
3336
+ "Read hardware keyboard input — arrow keys in a game, shortcuts in an editor. Returns { supported, pressed }. " +
3337
+ "Key names are KeyboardEvent.code values on every host ('ArrowLeft', 'KeyW', 'Space', 'Enter', 'Escape', " +
3338
+ "'Digit1', 'ShiftLeft'), so they do not change with the keyboard layout. `pressed` is the Set of keys held now. " +
3339
+ "`keys` lists the keys the widget handles: only those are delivered, and the host stops their browser default so " +
3340
+ "arrows and Space do not scroll the page. Omit `keys` to hear every key with no default stopped. " +
3341
+ "onKeyDown(event) / onKeyUp(event) receive { key, character, repeat, shiftKey, ctrlKey, altKey, metaKey }; " +
3342
+ "onKeyDown repeats while a key is held (repeat: true) on the web and Android; iOS sends one onKeyDown per press and " +
3343
+ "may drop one key of two pressed at the same instant. `active: false` stops listening. On the web keys keep " +
3344
+ "arriving after a click elsewhere on the page, except Enter/Space on a focused button or link and keys inside a " +
3345
+ "slider, list or tab set, which stay with that control; on iOS and Android keys pause while a text field is open " +
3346
+ "and resume when its keyboard closes. Keys typed into a text field are never delivered. Held keys are released, " +
3347
+ "each with an onKeyUp, when the window or app loses focus, a text field opens or the hook turns inactive, so " +
3348
+ "nothing sticks; unmounting calls no handler. `supported` is true when a keyboard is present: on the web where the " +
3349
+ "device has a mouse or trackpad, and on any host once a key is pressed. False means no keyboard has been seen, so " +
3350
+ "ALWAYS render touch controls when supported is false (an iPad with a keyboard turns true at its first key press). " +
3351
+ "In the Builder canvas and widget previews keys arrive only while the preview has focus (click it first). " +
3352
+ "Identical on web (window key listeners) and the Expo export (expo-key-event, iOS and Android hardware keyboards).",
3353
+ returnShape: {
3354
+ supported: "boolean // a keyboard is present (fine pointer on web, or a key was pressed)",
3355
+ pressed: "ReadonlySet<string> // KeyboardEvent.code names held now",
3356
+ },
3357
+ requiredContextSlice: [],
3358
+ scopes: null,
3359
+ },
3326
3360
  // sc-6448 — host-brokered camera capture / photo picking. Optional slice;
3327
3361
  // the hook reports supported:false rather than throwing at render.
3328
3362
  {
@@ -4531,11 +4565,13 @@ const WIDGET_CONTEXT_SHAPE = {
4531
4565
  },
4532
4566
  payments: {
4533
4567
  description:
4534
- "Injected @colixsystems/payments-client instance (REQ-BILL-07-WIDGETPAY). { requestPayment(body) -> Promise<{ id, status }>, getPayment(id) -> Promise<payment>, listAccessPlans() -> Promise<{ data, meta }>, purchaseAccessPlan({ plan_id, return_path? }) -> Promise<{ plan_id, status }>, cancelAccessPlan(planId) -> Promise<{ plan_id, renews, access_ends_at }>, getAppSubscription() -> Promise<{ active, renews, access_ends_at }>, cancelAppSubscription() -> Promise<{ active, renews, access_ends_at }> }; wire is snake_case (amount_cents, return_path, order). Backs usePayments(), useAccessPlans() and useAppSubscription(); requires the payments.charge:appUser scope. The host opens hosted Checkout itself — same-tab on web, in-app browser on native (or auto-confirms under the mock provider); the charge settles to the workspace owner.",
4568
+ "Injected @colixsystems/payments-client instance (REQ-BILL-07-WIDGETPAY). { requestPayment(body) -> Promise<{ id, status }>, getPayment(id) -> Promise<payment>, requestGuestPayment(body) -> Promise<{ id, status }>, getGuestPayment(id) -> Promise<payment>, listAccessPlans() -> Promise<{ data, meta }>, purchaseAccessPlan({ plan_id, return_path? }) -> Promise<{ plan_id, status }>, cancelAccessPlan(planId) -> Promise<{ plan_id, renews, access_ends_at }>, getAppSubscription() -> Promise<{ active, renews, access_ends_at }>, cancelAppSubscription() -> Promise<{ active, renews, access_ends_at }> }; wire is snake_case (amount_cents, return_path, order). Backs usePayments(), useAccessPlans() and useAppSubscription(); requires the payments.charge:appUser scope, and guest checkout (requestGuestPayment, a visitor with no account buying physical goods) also payments.charge:guest. The host opens hosted Checkout itself — same-tab on web, in-app browser on native (or auto-confirms under the mock provider); the charge settles to the workspace owner.",
4535
4569
  required: true,
4536
4570
  fields: {
4537
4571
  requestPayment: "function",
4538
4572
  getPayment: "function",
4573
+ requestGuestPayment: "function",
4574
+ getGuestPayment: "function",
4539
4575
  listAccessPlans: "function",
4540
4576
  purchaseAccessPlan: "function",
4541
4577
  cancelAccessPlan: "function",
@@ -4623,13 +4659,18 @@ const WIDGET_CONTEXT_SHAPE = {
4623
4659
  "start() -> Promise<{ getStatus() -> { durationMs, levelDb, ended }, stop() -> Promise<{ file, uri, durationMs, mime, release? }>, cancel() }> }, " +
4624
4660
  "audioPlayer: { isSupported() -> boolean, load(uri, onStatus({ loaded, playing, positionMs, durationMs, error? })) -> " +
4625
4661
  "{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
4662
+ "keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
4663
+ "repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
4626
4664
  "purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
4627
4665
  "purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
4628
4666
  "purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
4629
4667
  "workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
4630
- "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder() and useAudioPlayer(). The web Player brokers them via " +
4631
- "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder and an <audio> element; the Expo export via " +
4632
- "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print and expo-audio. " +
4668
+ "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and useKeyboard(). The web Player brokers them via " +
4669
+ "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 " +
4670
+ "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-key-event. " +
4671
+ "keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
4672
+ "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 " +
4673
+ "arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
4633
4674
  "audioRecorder.start rejects with .code PERMISSION_DENIED | UNSUPPORTED | INTERNAL; getStatus().levelDb is the input level in dBFS " +
4634
4675
  "(null when unknown); `ended` is true once the host stopped the recording itself (a lost headset, a call), and stop() then " +
4635
4676
  "still resolves that clip. audioPlayer reports the end of a clip as playing:false at positionMs 0. " +
@@ -4666,6 +4707,7 @@ const WIDGET_CONTEXT_SHAPE = {
4666
4707
  pdfViewer: "object",
4667
4708
  audioRecorder: "object",
4668
4709
  audioPlayer: "object",
4710
+ keyboard: "object",
4669
4711
  purchases: "object",
4670
4712
  },
4671
4713
  },
@@ -6821,7 +6863,14 @@ const CONTRACT = deepFreeze({
6821
6863
  // 1.239.0: additive (sc-15658) — an app-triggered run must finish within 250 ms
6822
6864
  // of the press; `useAction` errors carry the new code ACTION_TIMEOUT
6823
6865
  // (504), whose outcome is unknown.
6824
- version: "1.240.0",
6866
+ // 1.242.0: additive (sc-15359) — `usePayments()` gains
6867
+ // `requestGuestPayment` / `getGuestPayment` (a visitor with no account
6868
+ // pays for an order they created), the payments slice gains both, the
6869
+ // `payments.charge:guest` scope, and four new PaymentError codes.
6870
+ // 1.243.0: additive (sc-15908) — `useKeyboard({ keys, onKeyDown, onKeyUp,
6871
+ // active })` + the optional `device.keyboard` slice (window key listeners
6872
+ // on web, expo-key-event on native).
6873
+ version: "1.243.0",
6825
6874
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
6826
6875
  hooks: HOOKS,
6827
6876
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -2424,6 +2424,10 @@ const HOOKS = [
2424
2424
  "({ amount_cents, currency?, description, kind, return_path?, order? }) => Promise<{ id, status, order }> // kind is REQUIRED: \"physical\" | \"service\" | \"digital\" — what is sold; a digital charge is refused in an iOS/Android build (DIGITAL_SALE_NEEDS_STORE_BILLING); order: { table_id, record_id } — the order row this pays for, in a table with a payment-status column; the SERVER marks it paid when the payment settles, so never write \"paid\" yourself (refused: ORDER_NOT_FOUND, ORDER_NOT_PAYABLE, ORDER_ALREADY_PAID; ORDER_PAYMENT_IN_PROGRESS is retryable while another checkout for the order is open); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2425
2425
  getPayment:
2426
2426
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // order: { table_id, record_id } | null — read it after returning from Checkout",
2427
+ requestGuestPayment:
2428
+ "({ amount_cents, currency?, description, return_path?, order }) => Promise<{ id, status, order }> // a visitor who is NOT signed in buys physical goods (no kind). order is REQUIRED: create the order row first with useDatastoreMutation().create (the maker lets everyone add rows to the orders table and nobody read them; collect the shipping address and contact there), then pay for it within 15 minutes — only the visitor who created it can. Needs the payments.charge:guest scope too. The host runs a security check and opens hosted Checkout. Refused: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable), CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), NOT_FOUND where the shop does not offer guest checkout, plus the requestPayment refusals",
2429
+ getGuestPayment:
2430
+ "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // a guest's status read; the host holds the guest's one-time credential, so pass only the id",
2427
2431
  },
2428
2432
  requiredContextSlice: ["payments.requestPayment"],
2429
2433
  scopes: ["payments.charge:appUser"],
@@ -3319,6 +3323,36 @@ const HOOKS = [
3319
3323
  requiredContextSlice: [],
3320
3324
  scopes: null,
3321
3325
  },
3326
+ // sc-15908 — host-brokered hardware keyboard. Optional slice; the hook
3327
+ // reports supported:false rather than throwing at render.
3328
+ {
3329
+ name: "useKeyboard",
3330
+ signature: "useKeyboard({ keys, onKeyDown, onKeyUp, active })",
3331
+ description:
3332
+ "Read hardware keyboard input — arrow keys in a game, shortcuts in an editor. Returns { supported, pressed }. " +
3333
+ "Key names are KeyboardEvent.code values on every host ('ArrowLeft', 'KeyW', 'Space', 'Enter', 'Escape', " +
3334
+ "'Digit1', 'ShiftLeft'), so they do not change with the keyboard layout. `pressed` is the Set of keys held now. " +
3335
+ "`keys` lists the keys the widget handles: only those are delivered, and the host stops their browser default so " +
3336
+ "arrows and Space do not scroll the page. Omit `keys` to hear every key with no default stopped. " +
3337
+ "onKeyDown(event) / onKeyUp(event) receive { key, character, repeat, shiftKey, ctrlKey, altKey, metaKey }; " +
3338
+ "onKeyDown repeats while a key is held (repeat: true) on the web and Android; iOS sends one onKeyDown per press and " +
3339
+ "may drop one key of two pressed at the same instant. `active: false` stops listening. On the web keys keep " +
3340
+ "arriving after a click elsewhere on the page, except Enter/Space on a focused button or link and keys inside a " +
3341
+ "slider, list or tab set, which stay with that control; on iOS and Android keys pause while a text field is open " +
3342
+ "and resume when its keyboard closes. Keys typed into a text field are never delivered. Held keys are released, " +
3343
+ "each with an onKeyUp, when the window or app loses focus, a text field opens or the hook turns inactive, so " +
3344
+ "nothing sticks; unmounting calls no handler. `supported` is true when a keyboard is present: on the web where the " +
3345
+ "device has a mouse or trackpad, and on any host once a key is pressed. False means no keyboard has been seen, so " +
3346
+ "ALWAYS render touch controls when supported is false (an iPad with a keyboard turns true at its first key press). " +
3347
+ "In the Builder canvas and widget previews keys arrive only while the preview has focus (click it first). " +
3348
+ "Identical on web (window key listeners) and the Expo export (expo-key-event, iOS and Android hardware keyboards).",
3349
+ returnShape: {
3350
+ supported: "boolean // a keyboard is present (fine pointer on web, or a key was pressed)",
3351
+ pressed: "ReadonlySet<string> // KeyboardEvent.code names held now",
3352
+ },
3353
+ requiredContextSlice: [],
3354
+ scopes: null,
3355
+ },
3322
3356
  // sc-6448 — host-brokered camera capture / photo picking. Optional slice;
3323
3357
  // the hook reports supported:false rather than throwing at render.
3324
3358
  {
@@ -4527,11 +4561,13 @@ const WIDGET_CONTEXT_SHAPE = {
4527
4561
  },
4528
4562
  payments: {
4529
4563
  description:
4530
- "Injected @colixsystems/payments-client instance (REQ-BILL-07-WIDGETPAY). { requestPayment(body) -> Promise<{ id, status }>, getPayment(id) -> Promise<payment>, listAccessPlans() -> Promise<{ data, meta }>, purchaseAccessPlan({ plan_id, return_path? }) -> Promise<{ plan_id, status }>, cancelAccessPlan(planId) -> Promise<{ plan_id, renews, access_ends_at }>, getAppSubscription() -> Promise<{ active, renews, access_ends_at }>, cancelAppSubscription() -> Promise<{ active, renews, access_ends_at }> }; wire is snake_case (amount_cents, return_path, order). Backs usePayments(), useAccessPlans() and useAppSubscription(); requires the payments.charge:appUser scope. The host opens hosted Checkout itself — same-tab on web, in-app browser on native (or auto-confirms under the mock provider); the charge settles to the workspace owner.",
4564
+ "Injected @colixsystems/payments-client instance (REQ-BILL-07-WIDGETPAY). { requestPayment(body) -> Promise<{ id, status }>, getPayment(id) -> Promise<payment>, requestGuestPayment(body) -> Promise<{ id, status }>, getGuestPayment(id) -> Promise<payment>, listAccessPlans() -> Promise<{ data, meta }>, purchaseAccessPlan({ plan_id, return_path? }) -> Promise<{ plan_id, status }>, cancelAccessPlan(planId) -> Promise<{ plan_id, renews, access_ends_at }>, getAppSubscription() -> Promise<{ active, renews, access_ends_at }>, cancelAppSubscription() -> Promise<{ active, renews, access_ends_at }> }; wire is snake_case (amount_cents, return_path, order). Backs usePayments(), useAccessPlans() and useAppSubscription(); requires the payments.charge:appUser scope, and guest checkout (requestGuestPayment, a visitor with no account buying physical goods) also payments.charge:guest. The host opens hosted Checkout itself — same-tab on web, in-app browser on native (or auto-confirms under the mock provider); the charge settles to the workspace owner.",
4531
4565
  required: true,
4532
4566
  fields: {
4533
4567
  requestPayment: "function",
4534
4568
  getPayment: "function",
4569
+ requestGuestPayment: "function",
4570
+ getGuestPayment: "function",
4535
4571
  listAccessPlans: "function",
4536
4572
  purchaseAccessPlan: "function",
4537
4573
  cancelAccessPlan: "function",
@@ -4619,13 +4655,18 @@ const WIDGET_CONTEXT_SHAPE = {
4619
4655
  "start() -> Promise<{ getStatus() -> { durationMs, levelDb, ended }, stop() -> Promise<{ file, uri, durationMs, mime, release? }>, cancel() }> }, " +
4620
4656
  "audioPlayer: { isSupported() -> boolean, load(uri, onStatus({ loaded, playing, positionMs, durationMs, error? })) -> " +
4621
4657
  "{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
4658
+ "keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
4659
+ "repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
4622
4660
  "purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
4623
4661
  "purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
4624
4662
  "purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
4625
4663
  "workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
4626
- "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder() and useAudioPlayer(). The web Player brokers them via " +
4627
- "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder and an <audio> element; the Expo export via " +
4628
- "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print and expo-audio. " +
4664
+ "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and useKeyboard(). The web Player brokers them via " +
4665
+ "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 " +
4666
+ "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-key-event. " +
4667
+ "keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
4668
+ "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 " +
4669
+ "arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
4629
4670
  "audioRecorder.start rejects with .code PERMISSION_DENIED | UNSUPPORTED | INTERNAL; getStatus().levelDb is the input level in dBFS " +
4630
4671
  "(null when unknown); `ended` is true once the host stopped the recording itself (a lost headset, a call), and stop() then " +
4631
4672
  "still resolves that clip. audioPlayer reports the end of a clip as playing:false at positionMs 0. " +
@@ -4662,6 +4703,7 @@ const WIDGET_CONTEXT_SHAPE = {
4662
4703
  pdfViewer: "object",
4663
4704
  audioRecorder: "object",
4664
4705
  audioPlayer: "object",
4706
+ keyboard: "object",
4665
4707
  purchases: "object",
4666
4708
  },
4667
4709
  },
@@ -6817,7 +6859,14 @@ const CONTRACT = deepFreeze({
6817
6859
  // 1.239.0: additive (sc-15658) — an app-triggered run must finish within 250 ms
6818
6860
  // of the press; `useAction` errors carry the new code ACTION_TIMEOUT
6819
6861
  // (504), whose outcome is unknown.
6820
- version: "1.240.0",
6862
+ // 1.242.0: additive (sc-15359) — `usePayments()` gains
6863
+ // `requestGuestPayment` / `getGuestPayment` (a visitor with no account
6864
+ // pays for an order they created), the payments slice gains both, the
6865
+ // `payments.charge:guest` scope, and four new PaymentError codes.
6866
+ // 1.243.0: additive (sc-15908) — `useKeyboard({ keys, onKeyDown, onKeyUp,
6867
+ // active })` + the optional `device.keyboard` slice (window key listeners
6868
+ // on web, expo-key-event on native).
6869
+ version: "1.243.0",
6821
6870
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
6822
6871
  hooks: HOOKS,
6823
6872
  primitives: PRIMITIVES,
package/dist/hooks.js CHANGED
@@ -7008,6 +7008,7 @@ const NON_RETRYABLE_PAYMENT_CODES = new Set([
7008
7008
  "PAYMENTS_DISABLED",
7009
7009
  "PAYMENTS_SCOPE_NOT_GRANTED",
7010
7010
  "PAYMENTS_UNAVAILABLE",
7011
+ "TRIAL_RESTRICTED",
7011
7012
  "UNSUPPORTED_CURRENCY",
7012
7013
  "VALIDATION",
7013
7014
  ]);
@@ -7036,6 +7037,9 @@ const NON_RETRYABLE_PAYMENT_CODES = new Set([
7036
7037
  * `order` is not one this user can pay for
7037
7038
  * - "ORDER_PAYMENT_IN_PROGRESS" — another checkout for the order is open
7038
7039
  * (retryable: it clears when that one ends)
7040
+ * - "TRIAL_RESTRICTED" — a trial workspace takes no guest payments
7041
+ * - "GUEST_CHECKOUT_LIMIT_REACHED" — the shop's guest budget is spent for now
7042
+ * - "CAPTCHA_FAILED" / "CAPTCHA_UNAVAILABLE" — the guest's security check
7039
7043
  * - "CONNECT_NOT_READY" / "PAYMENTS_DISABLED" — provider not ready
7040
7044
  * - "DECLINED" — the charge was declined
7041
7045
  * - "INTERNAL" — anything else
@@ -7135,6 +7139,23 @@ function toPaymentError(err) {
7135
7139
  * Mollie webhook may land a moment after the redirect; if it is still `PENDING`
7136
7140
  * when you give up, show a "still processing" state rather than "paid".
7137
7141
  *
7142
+ * GUEST CHECKOUT — a visitor who is NOT signed in buys physical goods:
7143
+ * requestGuestPayment({ amount_cents, currency?, description, return_path?,
7144
+ * order }) → Promise<{ id, status, order, ... }>. Create the order row
7145
+ * first with `useDatastoreMutation().create` (the maker gives everyone
7146
+ * permission to add rows to the orders table, and no permission to read
7147
+ * them), then pass its `{ table_id, record_id }` as `order` within 15
7148
+ * minutes — it is REQUIRED, and only the visitor who created it can pay for
7149
+ * it. Collect the shipping address and contact on that order row. There is
7150
+ * no `kind`: guest checkout sells physical goods only. The host runs a
7151
+ * security check and opens hosted Checkout exactly as for requestPayment.
7152
+ * getGuestPayment(paymentId) → Promise<payment> — the same read for a guest;
7153
+ * the host holds the guest's one-time credential, so pass only the id.
7154
+ * Requires the `payments.charge:guest` scope as well. Refusals beyond the
7155
+ * charge refusals: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable),
7156
+ * CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), and NOT_FOUND where the
7157
+ * workspace does not offer guest checkout.
7158
+ *
7138
7159
  * Requires the `payments.charge:appUser` scope in the manifest's
7139
7160
  * `requestedScopes`. The charge settles to the workspace owner; the app user
7140
7161
  * confirms the amount in hosted Checkout. No card data touches the widget —
@@ -7149,39 +7170,26 @@ export function usePayments() {
7149
7170
  "workspace whose host supports payments.",
7150
7171
  );
7151
7172
  }
7152
- const requestRef = useRef(ctx.payments.requestPayment);
7153
- const getRef = useRef(
7154
- typeof ctx.payments.getPayment === "function"
7155
- ? ctx.payments.getPayment
7156
- : null,
7157
- );
7158
- requestRef.current = ctx.payments.requestPayment;
7159
- getRef.current =
7160
- typeof ctx.payments.getPayment === "function"
7161
- ? ctx.payments.getPayment
7162
- : null;
7173
+ const paymentsRef = useRef(ctx.payments);
7174
+ paymentsRef.current = ctx.payments;
7163
7175
 
7164
- const requestPayment = useCallback(async (args) => {
7165
- try {
7166
- return await requestRef.current(args);
7167
- } catch (err) {
7168
- throw toPaymentError(err);
7169
- }
7170
- }, []);
7171
- const getPayment = useCallback(async (paymentId) => {
7172
- if (!getRef.current) {
7173
- throw new PaymentError(
7174
- "INTERNAL",
7175
- "getPayment is not supported by this host.",
7176
- );
7176
+ // Read the host's method at call time: the host may rebuild its slice.
7177
+ const call = useCallback(async (name, args) => {
7178
+ const method = paymentsRef.current[name];
7179
+ if (typeof method !== "function") {
7180
+ throw new PaymentError("INTERNAL", `${name} is not supported by this host.`);
7177
7181
  }
7178
7182
  try {
7179
- return await getRef.current(paymentId);
7183
+ return await method(...args);
7180
7184
  } catch (err) {
7181
7185
  throw toPaymentError(err);
7182
7186
  }
7183
7187
  }, []);
7184
- return { requestPayment, getPayment };
7188
+ const requestPayment = useCallback((args) => call("requestPayment", [args]), [call]);
7189
+ const getPayment = useCallback((paymentId) => call("getPayment", [paymentId]), [call]);
7190
+ const requestGuestPayment = useCallback((args) => call("requestGuestPayment", [args]), [call]);
7191
+ const getGuestPayment = useCallback((paymentId) => call("getGuestPayment", [paymentId]), [call]);
7192
+ return { requestPayment, getPayment, requestGuestPayment, getGuestPayment };
7185
7193
  }
7186
7194
 
7187
7195
  /**
package/dist/index.d.ts CHANGED
@@ -968,6 +968,16 @@ export interface WidgetContext<TProps = unknown> {
968
968
  release(): void;
969
969
  };
970
970
  };
971
+ /** sc-15908 — backs useKeyboard. */
972
+ keyboard?: {
973
+ hasKeyboard(): boolean;
974
+ subscribe(subscriber: {
975
+ keys: string[] | null;
976
+ onKey(event: KeyboardKeyEvent & { type: "down" | "up" }): void;
977
+ onRelease(): void;
978
+ onDetected(): void;
979
+ }): () => void;
980
+ };
971
981
  /** sc-15163 — backs usePurchases. Brokered by the Expo export only. */
972
982
  purchases?: {
973
983
  isSupported?(): boolean;
@@ -1569,9 +1579,34 @@ export interface PaymentResult {
1569
1579
  order?: PaymentOrder | null;
1570
1580
  }
1571
1581
 
1582
+ /**
1583
+ * A visitor who is not signed in paying for physical goods. There is no
1584
+ * `kind`: guest checkout sells physical goods only.
1585
+ */
1586
+ export interface GuestPaymentRequest {
1587
+ amount_cents: number;
1588
+ currency?: string;
1589
+ description: string;
1590
+ return_path?: string;
1591
+ /**
1592
+ * Required. The order row the visitor created with
1593
+ * `useDatastoreMutation().create` in the last 15 minutes, in a table with a
1594
+ * payment-status column that everyone may add rows to. Collect the shipping
1595
+ * address and contact on it.
1596
+ */
1597
+ order: PaymentOrder;
1598
+ }
1599
+
1572
1600
  export interface PaymentsApi {
1573
1601
  requestPayment(args: PaymentRequest): Promise<PaymentResult>;
1574
1602
  getPayment(paymentId: string): Promise<PaymentResult>;
1603
+ /**
1604
+ * Guest checkout. Requires the `payments.charge:guest` scope as well. The
1605
+ * host runs a security check and opens hosted Checkout.
1606
+ */
1607
+ requestGuestPayment(args: GuestPaymentRequest): Promise<PaymentResult>;
1608
+ /** A guest's status read; the host holds their credential, so pass only the id. */
1609
+ getGuestPayment(paymentId: string): Promise<PaymentResult>;
1575
1610
  }
1576
1611
 
1577
1612
  /**
@@ -1581,7 +1616,8 @@ export interface PaymentsApi {
1581
1616
  * redirect on web, the in-app browser on native) — you never open a URL and
1582
1617
  * never collect card data. Confirm completion from server state (the webhook
1583
1618
  * flips your record) or poll `getPayment(id)`. The charge settles to the
1584
- * workspace owner.
1619
+ * workspace owner. A visitor who is not signed in pays with
1620
+ * `requestGuestPayment`, which also needs the `payments.charge:guest` scope.
1585
1621
  */
1586
1622
  export function usePayments(): PaymentsApi;
1587
1623
 
@@ -1682,6 +1718,10 @@ export class PaymentError extends Error {
1682
1718
  | "ORDER_NOT_PAYABLE"
1683
1719
  | "ORDER_ALREADY_PAID"
1684
1720
  | "ORDER_PAYMENT_IN_PROGRESS"
1721
+ | "TRIAL_RESTRICTED"
1722
+ | "GUEST_CHECKOUT_LIMIT_REACHED"
1723
+ | "CAPTCHA_FAILED"
1724
+ | "CAPTCHA_UNAVAILABLE"
1685
1725
  | "PAYMENTS_DISABLED"
1686
1726
  | "DECLINED"
1687
1727
  | "FORBIDDEN"
@@ -3105,6 +3145,42 @@ export interface AudioPlayerResult {
3105
3145
  */
3106
3146
  export function useAudioPlayer(uri: string | null | undefined): AudioPlayerResult;
3107
3147
 
3148
+ /** A key event as `useKeyboard()` delivers it. */
3149
+ export interface KeyboardKeyEvent {
3150
+ /** KeyboardEvent.code name: "ArrowLeft", "KeyW", "Space", "Enter". */
3151
+ key: string;
3152
+ /** The printed character, or "" for keys that print none. */
3153
+ character: string;
3154
+ repeat: boolean;
3155
+ shiftKey: boolean;
3156
+ ctrlKey: boolean;
3157
+ altKey: boolean;
3158
+ metaKey: boolean;
3159
+ }
3160
+
3161
+ export interface UseKeyboardOptions {
3162
+ /** Keys the widget handles; only these arrive, with their browser default stopped. Omit for every key. */
3163
+ keys?: string[];
3164
+ onKeyDown?(event: KeyboardKeyEvent): void;
3165
+ onKeyUp?(event: KeyboardKeyEvent): void;
3166
+ /** False stops listening and releases held keys. Default true. */
3167
+ active?: boolean;
3168
+ }
3169
+
3170
+ export interface KeyboardResult {
3171
+ /** A keyboard is present: a fine pointer on web, or a key was pressed. */
3172
+ supported: boolean;
3173
+ /** Keys held right now. */
3174
+ pressed: ReadonlySet<string>;
3175
+ }
3176
+
3177
+ /**
3178
+ * Hardware keyboard input on both hosts: window key listeners in the web
3179
+ * Player, `expo-key-event` in the Expo export. Held keys are released when
3180
+ * the window or app loses focus.
3181
+ */
3182
+ export function useKeyboard(options?: UseKeyboardOptions): KeyboardResult;
3183
+
3108
3184
  /** One package of the current offering, as the store prices it. */
3109
3185
  export interface PurchasePackage {
3110
3186
  id: string;
package/dist/index.js CHANGED
@@ -136,6 +136,8 @@ export {
136
136
  useAudioPlayer,
137
137
  AudioPlayerError,
138
138
  } from "./audio.js";
139
+ // sc-15908 — one host-brokered source for both entries (ctx.device.keyboard).
140
+ export { useKeyboard } from "./keyboard.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";
@@ -134,6 +134,8 @@ export {
134
134
  useAudioPlayer,
135
135
  AudioPlayerError,
136
136
  } from "./audio.js";
137
+ // sc-15908 — one host-brokered source for both entries (ctx.device.keyboard).
138
+ export { useKeyboard } from "./keyboard.js";
137
139
  // sc-15163 — native-only in-app purchase; the web Player brokers none.
138
140
  export { usePurchases, PurchasesError } from "./purchases.js";
139
141
  export { useDatastoreFigure } from "./datastore-figure.js";
@@ -0,0 +1,138 @@
1
+ // sc-15908 — host-brokered hardware keyboard input: `useKeyboard()`.
2
+ //
3
+ // One source for both hosts. The web Player brokers ctx.device.keyboard with
4
+ // window key listeners; the Expo export brokers it with expo-key-event. Key
5
+ // names are KeyboardEvent.code values ("ArrowLeft", "KeyW", "Space") on both,
6
+ // so they do not change with the keyboard layout.
7
+ //
8
+ // This file avoids JSX so it can ship as a plain .js without a transform.
9
+
10
+ import { useEffect, useRef, useState } from "react";
11
+ import { useWidgetContextOrThrow } from "./hooks.js";
12
+
13
+ const NO_KEYS = new Set();
14
+
15
+ function isUsable(client) {
16
+ return Boolean(
17
+ client &&
18
+ typeof client.subscribe === "function" &&
19
+ typeof client.hasKeyboard === "function",
20
+ );
21
+ }
22
+
23
+ function callQuietly(fn, event) {
24
+ if (typeof fn !== "function") return;
25
+ try {
26
+ fn(event);
27
+ } catch {
28
+ /* a widget handler's throw must not break the host's listener */
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Read hardware keyboard input. Returns `{ supported, pressed }`.
34
+ *
35
+ * - `supported` is true when a keyboard is present: on the web where the
36
+ * device has a fine pointer, and on any host once a key has been pressed.
37
+ * A phone without a keyboard reports false, so a widget shows its touch
38
+ * controls instead of a "press the arrow keys" hint.
39
+ * - `pressed` is the set of keys held right now (KeyboardEvent.code names).
40
+ *
41
+ * Options:
42
+ * - `keys` — the key names the widget handles. Only these are delivered, and
43
+ * the host stops their browser default (arrows and Space scroll no page).
44
+ * Omit it to receive every key with no default stopped.
45
+ * - `onKeyDown(event)` / `onKeyUp(event)` — `event` is `{ key, character,
46
+ * repeat, shiftKey, ctrlKey, altKey, metaKey }`.
47
+ * - `active` (default true) — false stops listening and releases held keys.
48
+ *
49
+ * Held keys are released, with an `onKeyUp` for each, when the window loses
50
+ * focus or the hook turns inactive, so a game never sticks "running". Keys
51
+ * typed into a text field are never delivered.
52
+ */
53
+ export function useKeyboard(options) {
54
+ const opts = options || {};
55
+ const ctx = useWidgetContextOrThrow("useKeyboard");
56
+ const client = ctx.device && ctx.device.keyboard;
57
+ const usable = isUsable(client);
58
+ const active = opts.active !== false;
59
+
60
+ const [detected, setDetected] = useState(false);
61
+ const [pressed, setPressed] = useState(NO_KEYS);
62
+
63
+ const handlersRef = useRef(opts);
64
+ handlersRef.current = opts;
65
+
66
+ // Declared first so its cleanup runs before the subscription's on unmount.
67
+ const unmountedRef = useRef(false);
68
+ useEffect(() => {
69
+ unmountedRef.current = false;
70
+ return () => {
71
+ unmountedRef.current = true;
72
+ };
73
+ }, []);
74
+
75
+ const keysId = Array.isArray(opts.keys) ? opts.keys.join("\u0000") : null;
76
+
77
+ useEffect(() => {
78
+ if (!usable || !active) return undefined;
79
+ const held = new Set();
80
+ const publish = () => setPressed(held.size ? new Set(held) : NO_KEYS);
81
+
82
+ const onKey = (event) => {
83
+ if (event.type === "down") {
84
+ if (!held.has(event.key)) {
85
+ held.add(event.key);
86
+ publish();
87
+ }
88
+ callQuietly(handlersRef.current.onKeyDown, toWidgetEvent(event));
89
+ } else if (held.delete(event.key)) {
90
+ publish();
91
+ callQuietly(handlersRef.current.onKeyUp, toWidgetEvent(event));
92
+ }
93
+ };
94
+
95
+ const releaseAll = () => {
96
+ if (held.size === 0) return;
97
+ const keys = [...held];
98
+ held.clear();
99
+ publish();
100
+ if (unmountedRef.current) return;
101
+ for (const key of keys) callQuietly(handlersRef.current.onKeyUp, releasedEvent(key));
102
+ };
103
+
104
+ const unsubscribe = client.subscribe({
105
+ keys: keysId === null ? null : keysId.split("\u0000"),
106
+ onKey,
107
+ onRelease: releaseAll,
108
+ onDetected: () => setDetected(true),
109
+ });
110
+
111
+ return () => {
112
+ if (typeof unsubscribe === "function") unsubscribe();
113
+ // Deactivated while mounted, the widget still hears its keys go up.
114
+ releaseAll();
115
+ };
116
+ }, [client, usable, active, keysId]);
117
+
118
+ return {
119
+ supported: usable && (detected || client.hasKeyboard()),
120
+ pressed: usable && active ? pressed : NO_KEYS,
121
+ };
122
+ }
123
+
124
+ function toWidgetEvent(event) {
125
+ return {
126
+ key: event.key,
127
+ character: event.character || "",
128
+ repeat: Boolean(event.repeat),
129
+ shiftKey: Boolean(event.shiftKey),
130
+ ctrlKey: Boolean(event.ctrlKey),
131
+ altKey: Boolean(event.altKey),
132
+ metaKey: Boolean(event.metaKey),
133
+ };
134
+ }
135
+
136
+ function releasedEvent(key) {
137
+ return toWidgetEvent({ key });
138
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.293.0",
3
+ "version": "0.296.0",
4
4
  "description": "Common widget interface for AppStudio. Implements WidgetManifest, WidgetContext, property schema, and helper hooks.",
5
5
  "homepage": "https://github.com/Colix-AB/AppStudio",
6
6
  "type": "module",
package/src/contract.js CHANGED
@@ -2424,6 +2424,10 @@ const HOOKS = [
2424
2424
  "({ amount_cents, currency?, description, kind, return_path?, order? }) => Promise<{ id, status, order }> // kind is REQUIRED: \"physical\" | \"service\" | \"digital\" — what is sold; a digital charge is refused in an iOS/Android build (DIGITAL_SALE_NEEDS_STORE_BILLING); order: { table_id, record_id } — the order row this pays for, in a table with a payment-status column; the SERVER marks it paid when the payment settles, so never write \"paid\" yourself (refused: ORDER_NOT_FOUND, ORDER_NOT_PAYABLE, ORDER_ALREADY_PAID; ORDER_PAYMENT_IN_PROGRESS is retryable while another checkout for the order is open); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2425
2425
  getPayment:
2426
2426
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // order: { table_id, record_id } | null — read it after returning from Checkout",
2427
+ requestGuestPayment:
2428
+ "({ amount_cents, currency?, description, return_path?, order }) => Promise<{ id, status, order }> // a visitor who is NOT signed in buys physical goods (no kind). order is REQUIRED: create the order row first with useDatastoreMutation().create (the maker lets everyone add rows to the orders table and nobody read them; collect the shipping address and contact there), then pay for it within 15 minutes — only the visitor who created it can. Needs the payments.charge:guest scope too. The host runs a security check and opens hosted Checkout. Refused: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable), CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), NOT_FOUND where the shop does not offer guest checkout, plus the requestPayment refusals",
2429
+ getGuestPayment:
2430
+ "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // a guest's status read; the host holds the guest's one-time credential, so pass only the id",
2427
2431
  },
2428
2432
  requiredContextSlice: ["payments.requestPayment"],
2429
2433
  scopes: ["payments.charge:appUser"],
@@ -3319,6 +3323,36 @@ const HOOKS = [
3319
3323
  requiredContextSlice: [],
3320
3324
  scopes: null,
3321
3325
  },
3326
+ // sc-15908 — host-brokered hardware keyboard. Optional slice; the hook
3327
+ // reports supported:false rather than throwing at render.
3328
+ {
3329
+ name: "useKeyboard",
3330
+ signature: "useKeyboard({ keys, onKeyDown, onKeyUp, active })",
3331
+ description:
3332
+ "Read hardware keyboard input — arrow keys in a game, shortcuts in an editor. Returns { supported, pressed }. " +
3333
+ "Key names are KeyboardEvent.code values on every host ('ArrowLeft', 'KeyW', 'Space', 'Enter', 'Escape', " +
3334
+ "'Digit1', 'ShiftLeft'), so they do not change with the keyboard layout. `pressed` is the Set of keys held now. " +
3335
+ "`keys` lists the keys the widget handles: only those are delivered, and the host stops their browser default so " +
3336
+ "arrows and Space do not scroll the page. Omit `keys` to hear every key with no default stopped. " +
3337
+ "onKeyDown(event) / onKeyUp(event) receive { key, character, repeat, shiftKey, ctrlKey, altKey, metaKey }; " +
3338
+ "onKeyDown repeats while a key is held (repeat: true) on the web and Android; iOS sends one onKeyDown per press and " +
3339
+ "may drop one key of two pressed at the same instant. `active: false` stops listening. On the web keys keep " +
3340
+ "arriving after a click elsewhere on the page, except Enter/Space on a focused button or link and keys inside a " +
3341
+ "slider, list or tab set, which stay with that control; on iOS and Android keys pause while a text field is open " +
3342
+ "and resume when its keyboard closes. Keys typed into a text field are never delivered. Held keys are released, " +
3343
+ "each with an onKeyUp, when the window or app loses focus, a text field opens or the hook turns inactive, so " +
3344
+ "nothing sticks; unmounting calls no handler. `supported` is true when a keyboard is present: on the web where the " +
3345
+ "device has a mouse or trackpad, and on any host once a key is pressed. False means no keyboard has been seen, so " +
3346
+ "ALWAYS render touch controls when supported is false (an iPad with a keyboard turns true at its first key press). " +
3347
+ "In the Builder canvas and widget previews keys arrive only while the preview has focus (click it first). " +
3348
+ "Identical on web (window key listeners) and the Expo export (expo-key-event, iOS and Android hardware keyboards).",
3349
+ returnShape: {
3350
+ supported: "boolean // a keyboard is present (fine pointer on web, or a key was pressed)",
3351
+ pressed: "ReadonlySet<string> // KeyboardEvent.code names held now",
3352
+ },
3353
+ requiredContextSlice: [],
3354
+ scopes: null,
3355
+ },
3322
3356
  // sc-6448 — host-brokered camera capture / photo picking. Optional slice;
3323
3357
  // the hook reports supported:false rather than throwing at render.
3324
3358
  {
@@ -4527,11 +4561,13 @@ const WIDGET_CONTEXT_SHAPE = {
4527
4561
  },
4528
4562
  payments: {
4529
4563
  description:
4530
- "Injected @colixsystems/payments-client instance (REQ-BILL-07-WIDGETPAY). { requestPayment(body) -> Promise<{ id, status }>, getPayment(id) -> Promise<payment>, listAccessPlans() -> Promise<{ data, meta }>, purchaseAccessPlan({ plan_id, return_path? }) -> Promise<{ plan_id, status }>, cancelAccessPlan(planId) -> Promise<{ plan_id, renews, access_ends_at }>, getAppSubscription() -> Promise<{ active, renews, access_ends_at }>, cancelAppSubscription() -> Promise<{ active, renews, access_ends_at }> }; wire is snake_case (amount_cents, return_path, order). Backs usePayments(), useAccessPlans() and useAppSubscription(); requires the payments.charge:appUser scope. The host opens hosted Checkout itself — same-tab on web, in-app browser on native (or auto-confirms under the mock provider); the charge settles to the workspace owner.",
4564
+ "Injected @colixsystems/payments-client instance (REQ-BILL-07-WIDGETPAY). { requestPayment(body) -> Promise<{ id, status }>, getPayment(id) -> Promise<payment>, requestGuestPayment(body) -> Promise<{ id, status }>, getGuestPayment(id) -> Promise<payment>, listAccessPlans() -> Promise<{ data, meta }>, purchaseAccessPlan({ plan_id, return_path? }) -> Promise<{ plan_id, status }>, cancelAccessPlan(planId) -> Promise<{ plan_id, renews, access_ends_at }>, getAppSubscription() -> Promise<{ active, renews, access_ends_at }>, cancelAppSubscription() -> Promise<{ active, renews, access_ends_at }> }; wire is snake_case (amount_cents, return_path, order). Backs usePayments(), useAccessPlans() and useAppSubscription(); requires the payments.charge:appUser scope, and guest checkout (requestGuestPayment, a visitor with no account buying physical goods) also payments.charge:guest. The host opens hosted Checkout itself — same-tab on web, in-app browser on native (or auto-confirms under the mock provider); the charge settles to the workspace owner.",
4531
4565
  required: true,
4532
4566
  fields: {
4533
4567
  requestPayment: "function",
4534
4568
  getPayment: "function",
4569
+ requestGuestPayment: "function",
4570
+ getGuestPayment: "function",
4535
4571
  listAccessPlans: "function",
4536
4572
  purchaseAccessPlan: "function",
4537
4573
  cancelAccessPlan: "function",
@@ -4619,13 +4655,18 @@ const WIDGET_CONTEXT_SHAPE = {
4619
4655
  "start() -> Promise<{ getStatus() -> { durationMs, levelDb, ended }, stop() -> Promise<{ file, uri, durationMs, mime, release? }>, cancel() }> }, " +
4620
4656
  "audioPlayer: { isSupported() -> boolean, load(uri, onStatus({ loaded, playing, positionMs, durationMs, error? })) -> " +
4621
4657
  "{ play() -> Promise<void>, pause(), seek(ms) -> Promise<void>, release() } }, " +
4658
+ "keyboard: { hasKeyboard() -> boolean, subscribe({ keys: string[] | null, onKey({ type: 'down' | 'up', key, character, " +
4659
+ "repeat, shiftKey, ctrlKey, altKey, metaKey }), onRelease(), onDetected() }) -> unsubscribe }, " +
4622
4660
  "purchases: { isSupported() -> boolean, getOffering() -> Promise<offering | null>, getEntitlements() -> Promise<string[]>, " +
4623
4661
  "purchase(packageId) -> Promise<string[]>, restore() -> Promise<string[]> } }. " +
4624
4662
  "purchases backs usePurchases() and is NATIVE-ONLY: the Expo export brokers it through react-native-purchases when the " +
4625
4663
  "workspace connected RevenueCat; the web Player never does, because a browser has no store billing. " +
4626
- "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder() and useAudioPlayer(). The web Player brokers them via " +
4627
- "navigator.geolocation, window.SpeechRecognition, a getUserMedia camera preview, a host-side canvas, BarcodeDetector, a new browser tab, MediaRecorder and an <audio> element; the Expo export via " +
4628
- "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print and expo-audio. " +
4664
+ "Backs useGeolocation(), useSpeechToText(), useCamera(), useImageEditor(), useBarcodeScanner(), usePdfExport().openPdf, useAudioRecorder(), useAudioPlayer() and useKeyboard(). The web Player brokers them via " +
4665
+ "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 " +
4666
+ "expo-location, expo-speech-recognition, expo-image-picker, expo-image-manipulator, expo-camera, expo-print, expo-audio and expo-key-event. " +
4667
+ "keyboard.subscribe delivers only the `keys` named (all when null), stops the browser default of a delivered key " +
4668
+ "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 " +
4669
+ "arrives; a Builder preview's broker accepts keys only while focus is inside the preview. " +
4629
4670
  "audioRecorder.start rejects with .code PERMISSION_DENIED | UNSUPPORTED | INTERNAL; getStatus().levelDb is the input level in dBFS " +
4630
4671
  "(null when unknown); `ended` is true once the host stopped the recording itself (a lost headset, a call), and stop() then " +
4631
4672
  "still resolves that clip. audioPlayer reports the end of a clip as playing:false at positionMs 0. " +
@@ -4662,6 +4703,7 @@ const WIDGET_CONTEXT_SHAPE = {
4662
4703
  pdfViewer: "object",
4663
4704
  audioRecorder: "object",
4664
4705
  audioPlayer: "object",
4706
+ keyboard: "object",
4665
4707
  purchases: "object",
4666
4708
  },
4667
4709
  },
@@ -6817,7 +6859,14 @@ const CONTRACT = deepFreeze({
6817
6859
  // 1.239.0: additive (sc-15658) — an app-triggered run must finish within 250 ms
6818
6860
  // of the press; `useAction` errors carry the new code ACTION_TIMEOUT
6819
6861
  // (504), whose outcome is unknown.
6820
- version: "1.240.0",
6862
+ // 1.242.0: additive (sc-15359) — `usePayments()` gains
6863
+ // `requestGuestPayment` / `getGuestPayment` (a visitor with no account
6864
+ // pays for an order they created), the payments slice gains both, the
6865
+ // `payments.charge:guest` scope, and four new PaymentError codes.
6866
+ // 1.243.0: additive (sc-15908) — `useKeyboard({ keys, onKeyDown, onKeyUp,
6867
+ // active })` + the optional `device.keyboard` slice (window key listeners
6868
+ // on web, expo-key-event on native).
6869
+ version: "1.243.0",
6821
6870
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
6822
6871
  hooks: HOOKS,
6823
6872
  primitives: PRIMITIVES,