@colixsystems/widget-sdk 0.355.1 → 0.357.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
@@ -77,7 +77,7 @@ The data layer lives in **four separate domain-client packages**, each instantia
77
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. |
78
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. A held plan's `member_since` is when the user became a member (first paid charge, else when access was granted). `purchaseAvailable` is `false` in an iOS / Android build (digital goods need store billing): show a visible not-available state. |
79
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, member_since }`); `cancel()` stops it renewing, and access runs to `access_ends_at`. `member_since` is when they became a subscriber. |
80
- | **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 call without it is a publish-blocking `payment-kind-required` finding. A `"digital"` charge is refused in an iOS or Android build (`DIGITAL_SALE_NEEDS_STORE_BILLING`). Selling an order (goods, a booking, a ticket)? The orders table needs a payment-status column AND an order-total column (a write-once NUMBER holding the total in minor units). Create the row with its total, then pass `order: { table_id, record_id }` and omit `amount_cents` (or send the same value): the server charges the stored total, and only the payment marks the order paid, so never write a paid status yourself (a `payment-status-written` finding). The server refuses an order it cannot settle with `ORDER_NOT_FOUND`, `ORDER_NOT_PAYABLE` (also: no order-total column), `ORDER_ALREADY_PAID`, `ORDER_TOTAL_INVALID` or `ORDER_AMOUNT_MISMATCH`, none retryable. Give the table a `buyerEmail` column too: the platform emails the buyer's order confirmation and refund notice, and a guest charge needs a valid address there (`BUYER_EMAIL_INVALID`). 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
+ | **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 call without it is a publish-blocking `payment-kind-required` finding. A `"digital"` charge is refused in an iOS or Android build (`DIGITAL_SALE_NEEDS_STORE_BILLING`). Selling an order (goods, a booking, a ticket)? The orders table needs a payment-status column AND an order-total column the server prices from the order's lines and the products table's unit prices. Create the order, then its lines, then pass `order: { table_id, record_id }` and omit `amount_cents`: the server charges the total it priced, and only the payment marks the order paid, so never write a paid status yourself (a `payment-status-written` finding). Never take a price or total from `useRouteParams()`, a wire input or the device's bag: the buyer can change them (an order charge that does is a `payment-price-from-page` finding). The server refuses an order it cannot settle with `ORDER_NOT_FOUND`, `ORDER_NOT_PAYABLE` (also: no order-total column), `ORDER_ALREADY_PAID`, `ORDER_TOTAL_INVALID` or `ORDER_AMOUNT_MISMATCH`, none retryable. Give the table a `buyerEmail` column too: the platform emails the buyer's order confirmation and refund notice, and a guest charge needs a valid address there (`BUYER_EMAIL_INVALID`). 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). |
81
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`. |
82
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. |
83
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). |
@@ -91,7 +91,15 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
91
91
 
92
92
  ## Status
93
93
 
94
- `v0.355.1` — 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.357.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.357.0 (contract 1.293.0)
97
+
98
+ **The linter warns when an order charge takes its amount from the page address, a wire input or the device's bag.** The buyer holds all of them: they can type a price into the URL a page opens with, or edit what `useDeviceStorage` keeps, so an order charge whose `amount_cents` is computed from `useRouteParams()`, `usePageContext()`, `useWidgetInput()`, `useWidgetRoute()` or a `useDeviceStorage` value bills whatever the buyer wrote. The new rule `payment-price-from-page` (severity `warning`) follows the amount through local declarations, including ones wrapped over several lines, back to those sources. It judges only an order charge: one that passes `order`, or sells `kind: "physical"`. A donation or tip the buyer chooses is theirs to set. A value read from the datastore ends the trace, including a row looked up by an id from the page (`rows.find((r) => r.id === productId).price`). Keep only product ids and quantities in the bag and the page address, read each price you show from the products table, and let the server price the order: create the order and its lines, then call `requestPayment({ description, kind, order })` with no `amount_cents`. The scan does not follow values through functions or state setters, so a quiet rule is no proof of a safe charge. Additive.
99
+
100
+ ### What's new in 0.356.0 (contract 1.292.0)
101
+
102
+ **A shop cannot sell what it does not have.** Two buyers of the last item could both pay, and the seller had to refund one. A products table can now hold a stock column: a NUMBER column declared with `stockQuantity: true` in a `datastoreTemplate`, one per table, in a table with a `unitPrice` column, and NOT `immutable` (the seller restocks it in the Studio). It holds how many are left, a whole number of 0 or more; an empty cell is not counted and sells without limit. When `requestPayment({ order })` (or `requestGuestPayment`) opens a charge, the server takes each line's quantity off its product's stock in the same step that prices the order, so of two buyers of the last item one charge opens and the other is refused with the new non-retryable `PaymentError` code `OUT_OF_STOCK`, whose message names the product. An order refused before it was ever priced stays editable, so the buyer can remove the sold-out line; one already priced by an earlier charge is fixed, so start a new order. The stock goes back exactly once when the payment provider reports the charge failed, cancelled or expired, and an open checkout keeps it however old; a paid order keeps it, and a refund does not restock. The stock value is what is available to sell: items in checkouts still in progress are already taken off. Read the stock cell to show a product as sold out at 0, and never write it from a widget: a payer who may edit the products is refused anyway.
95
103
 
96
104
  ### What's new in 0.355.1 (contract 1.291.0)
97
105
 
package/dist/contract.cjs CHANGED
@@ -2517,7 +2517,7 @@ const HOOKS = [
2517
2517
  signature: "usePayments()",
2518
2518
  returnShape: {
2519
2519
  requestPayment:
2520
- "({ 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); amount_cents (minor units) is REQUIRED without order; 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). The orders table also REQUIRES an order-total column the server prices (orderTotal: { lines, via } in the datastoreTemplate; without one: ORDER_NOT_PAYABLE): create the order, then its lines, then pass order and omit amount_cents — the server sums quantity × the products table's unitPrice (plus the order's own pricedItem, e.g. shipping), writes the total and charges it; never compute, write or send a total (if amount_cents is sent it must equal the total; refused, not retryable: ORDER_LINES_INVALID when the lines cannot be priced, ORDER_TOTAL_INVALID when the total is zero, ORDER_AMOUNT_MISMATCH when amount_cents differs; ORDER_NOT_PAYABLE also when the payer could write or create a price). Once priced, the order's lines are fixed (adding or removing one: ORDER_LOCKED); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2520
+ "({ 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); amount_cents (minor units) is REQUIRED without order; 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). The orders table also REQUIRES an order-total column the server prices (orderTotal: { lines, via } in the datastoreTemplate; without one: ORDER_NOT_PAYABLE): create the order, then its lines, then pass order and omit amount_cents — the server sums quantity × the products table's unitPrice (plus the order's own pricedItem, e.g. shipping), writes the total and charges it; never compute, write or send a total (if amount_cents is sent it must equal the total; refused, not retryable: ORDER_LINES_INVALID when the lines cannot be priced, ORDER_TOTAL_INVALID when the total is zero, ORDER_AMOUNT_MISMATCH when amount_cents differs; ORDER_NOT_PAYABLE also when the payer could write or create a price; OUT_OF_STOCK, naming the product, when a product's stockQuantity cannot cover the order — show it sold out and let the buyer start a new order without it). Once priced, the order's lines are fixed (adding or removing one: ORDER_LOCKED); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2521
2521
  getPayment:
2522
2522
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // order: { table_id, record_id } | null — read it after returning from Checkout",
2523
2523
  requestGuestPayment:
@@ -4390,7 +4390,7 @@ const MANIFEST_SCHEMA = {
4390
4390
  type: "object",
4391
4391
  required: false,
4392
4392
  description:
4393
- "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: { lines: \"<lines table suffix>\", via: \"<its relation to this table>\" }` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The SERVER prices it when the charge opens and ignores any client value: Σ over the order's lines of `lineQuantity` × the `unitPrice` of the row the line's `pricedItem` names, plus the order table's own `pricedItem` once (a shipping option). `via` is a write-once ONE_TO_MANY relation on the lines table pointing at this table. A bare `orderTotal: true` is accepted only on an orders table that has its own `pricedItem`; publishing any other unpriced order total is refused (an already published template still installs, and its order charges are refused with ORDER_NOT_PAYABLE). `unitPrice: true` makes a NUMBER column a product's price in minor units (one per table). `pricedItem: true` makes a write-once single RELATION (one per table) to a table with a unitPrice column the item a line or an order is priced by. `lineQuantity: true` makes a write-once NUMBER column (one per table) a line's quantity, a whole number from 1 to 999 (empty is 1). A payer who may edit or create rows in a priced table is refused, and once an order holds its total no line is added or removed (ORDER_LOCKED). `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4393
+ "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: { lines: \"<lines table suffix>\", via: \"<its relation to this table>\" }` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The SERVER prices it when the charge opens and ignores any client value: Σ over the order's lines of `lineQuantity` × the `unitPrice` of the row the line's `pricedItem` names, plus the order table's own `pricedItem` once (a shipping option). `via` is a write-once ONE_TO_MANY relation on the lines table pointing at this table. A bare `orderTotal: true` is accepted only on an orders table that has its own `pricedItem`; publishing any other unpriced order total is refused (an already published template still installs, and its order charges are refused with ORDER_NOT_PAYABLE). `unitPrice: true` makes a NUMBER column a product's price in minor units (one per table). `pricedItem: true` makes a write-once single RELATION (one per table) to a table with a unitPrice column the item a line or an order is priced by. `lineQuantity: true` makes a write-once NUMBER column (one per table) a line's quantity, a whole number from 1 to 999 (empty is 1). `stockQuantity: true` makes a NUMBER column (one per table, in a table with a unitPrice column, not immutable) how many of a product are left, a whole number of 0 or more (empty is not counted): a charge takes its order's quantities when it opens, refusing with OUT_OF_STOCK when one cannot be covered, and gives them back exactly once if it fails, is cancelled or stays unpaid past 15 minutes; a paid order keeps them and a refund does not restock (the seller restocks in the Studio). Read it to show a product sold out at 0; a widget never writes it. A payer who may edit or create rows in a priced table is refused, and once an order holds its total no line is added or removed (ORDER_LOCKED). `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4394
4394
  },
4395
4395
  translations: {
4396
4396
  type: "object",
@@ -7202,7 +7202,13 @@ const CONTRACT = deepFreeze({
7202
7202
  // draw is the publish-blocking `button-unknown-variant` finding.
7203
7203
  // 1.291.0: behaviour (sc-18689) — a vertical native `ScrollView`, `FlatList`
7204
7204
  // or `SectionList` sets `nestedScrollEnabled` unless inverted or the author sets it.
7205
- version: "1.291.0",
7205
+ // 1.292.0: additive (sc-18009) — a template column may declare
7206
+ // `stockQuantity: true`; a charge reserves stock and refuses with the new
7207
+ // PaymentError code OUT_OF_STOCK when a product cannot cover the order.
7208
+ // 1.293.0: additive (sc-16652) — the `payment-price-from-page` lint warning
7209
+ // flags an order charge whose amount comes from the page address, a
7210
+ // wire input or the bag.
7211
+ version: "1.293.0",
7206
7212
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7207
7213
  hooks: HOOKS,
7208
7214
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -2512,7 +2512,7 @@ const HOOKS = [
2512
2512
  signature: "usePayments()",
2513
2513
  returnShape: {
2514
2514
  requestPayment:
2515
- "({ 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); amount_cents (minor units) is REQUIRED without order; 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). The orders table also REQUIRES an order-total column the server prices (orderTotal: { lines, via } in the datastoreTemplate; without one: ORDER_NOT_PAYABLE): create the order, then its lines, then pass order and omit amount_cents — the server sums quantity × the products table's unitPrice (plus the order's own pricedItem, e.g. shipping), writes the total and charges it; never compute, write or send a total (if amount_cents is sent it must equal the total; refused, not retryable: ORDER_LINES_INVALID when the lines cannot be priced, ORDER_TOTAL_INVALID when the total is zero, ORDER_AMOUNT_MISMATCH when amount_cents differs; ORDER_NOT_PAYABLE also when the payer could write or create a price). Once priced, the order's lines are fixed (adding or removing one: ORDER_LOCKED); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2515
+ "({ 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); amount_cents (minor units) is REQUIRED without order; 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). The orders table also REQUIRES an order-total column the server prices (orderTotal: { lines, via } in the datastoreTemplate; without one: ORDER_NOT_PAYABLE): create the order, then its lines, then pass order and omit amount_cents — the server sums quantity × the products table's unitPrice (plus the order's own pricedItem, e.g. shipping), writes the total and charges it; never compute, write or send a total (if amount_cents is sent it must equal the total; refused, not retryable: ORDER_LINES_INVALID when the lines cannot be priced, ORDER_TOTAL_INVALID when the total is zero, ORDER_AMOUNT_MISMATCH when amount_cents differs; ORDER_NOT_PAYABLE also when the payer could write or create a price; OUT_OF_STOCK, naming the product, when a product's stockQuantity cannot cover the order — show it sold out and let the buyer start a new order without it). Once priced, the order's lines are fixed (adding or removing one: ORDER_LOCKED); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2516
2516
  getPayment:
2517
2517
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // order: { table_id, record_id } | null — read it after returning from Checkout",
2518
2518
  requestGuestPayment:
@@ -4385,7 +4385,7 @@ const MANIFEST_SCHEMA = {
4385
4385
  type: "object",
4386
4386
  required: false,
4387
4387
  description:
4388
- "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: { lines: \"<lines table suffix>\", via: \"<its relation to this table>\" }` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The SERVER prices it when the charge opens and ignores any client value: Σ over the order's lines of `lineQuantity` × the `unitPrice` of the row the line's `pricedItem` names, plus the order table's own `pricedItem` once (a shipping option). `via` is a write-once ONE_TO_MANY relation on the lines table pointing at this table. A bare `orderTotal: true` is accepted only on an orders table that has its own `pricedItem`; publishing any other unpriced order total is refused (an already published template still installs, and its order charges are refused with ORDER_NOT_PAYABLE). `unitPrice: true` makes a NUMBER column a product's price in minor units (one per table). `pricedItem: true` makes a write-once single RELATION (one per table) to a table with a unitPrice column the item a line or an order is priced by. `lineQuantity: true` makes a write-once NUMBER column (one per table) a line's quantity, a whole number from 1 to 999 (empty is 1). A payer who may edit or create rows in a priced table is refused, and once an order holds its total no line is added or removed (ORDER_LOCKED). `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4388
+ "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: { lines: \"<lines table suffix>\", via: \"<its relation to this table>\" }` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The SERVER prices it when the charge opens and ignores any client value: Σ over the order's lines of `lineQuantity` × the `unitPrice` of the row the line's `pricedItem` names, plus the order table's own `pricedItem` once (a shipping option). `via` is a write-once ONE_TO_MANY relation on the lines table pointing at this table. A bare `orderTotal: true` is accepted only on an orders table that has its own `pricedItem`; publishing any other unpriced order total is refused (an already published template still installs, and its order charges are refused with ORDER_NOT_PAYABLE). `unitPrice: true` makes a NUMBER column a product's price in minor units (one per table). `pricedItem: true` makes a write-once single RELATION (one per table) to a table with a unitPrice column the item a line or an order is priced by. `lineQuantity: true` makes a write-once NUMBER column (one per table) a line's quantity, a whole number from 1 to 999 (empty is 1). `stockQuantity: true` makes a NUMBER column (one per table, in a table with a unitPrice column, not immutable) how many of a product are left, a whole number of 0 or more (empty is not counted): a charge takes its order's quantities when it opens, refusing with OUT_OF_STOCK when one cannot be covered, and gives them back exactly once if it fails, is cancelled or stays unpaid past 15 minutes; a paid order keeps them and a refund does not restock (the seller restocks in the Studio). Read it to show a product sold out at 0; a widget never writes it. A payer who may edit or create rows in a priced table is refused, and once an order holds its total no line is added or removed (ORDER_LOCKED). `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4389
4389
  },
4390
4390
  translations: {
4391
4391
  type: "object",
@@ -7197,7 +7197,13 @@ const CONTRACT = deepFreeze({
7197
7197
  // draw is the publish-blocking `button-unknown-variant` finding.
7198
7198
  // 1.291.0: behaviour (sc-18689) — a vertical native `ScrollView`, `FlatList`
7199
7199
  // or `SectionList` sets `nestedScrollEnabled` unless inverted or the author sets it.
7200
- version: "1.291.0",
7200
+ // 1.292.0: additive (sc-18009) — a template column may declare
7201
+ // `stockQuantity: true`; a charge reserves stock and refuses with the new
7202
+ // PaymentError code OUT_OF_STOCK when a product cannot cover the order.
7203
+ // 1.293.0: additive (sc-16652) — the `payment-price-from-page` lint warning
7204
+ // flags an order charge whose amount comes from the page address, a
7205
+ // wire input or the bag.
7206
+ version: "1.293.0",
7201
7207
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7202
7208
  hooks: HOOKS,
7203
7209
  primitives: PRIMITIVES,
package/dist/hooks.js CHANGED
@@ -7514,6 +7514,7 @@ const NON_RETRYABLE_PAYMENT_CODES = new Set([
7514
7514
  "ORDER_LINES_INVALID",
7515
7515
  "ORDER_NOT_PAYABLE",
7516
7516
  "ORDER_TOTAL_INVALID",
7517
+ "OUT_OF_STOCK",
7517
7518
  "PAYMENTS_DISABLED",
7518
7519
  "PAYMENTS_SCOPE_NOT_GRANTED",
7519
7520
  "PAYMENTS_UNAVAILABLE",
@@ -7552,6 +7553,9 @@ const NON_RETRYABLE_PAYMENT_CODES = new Set([
7552
7553
  * - "ORDER_LINES_INVALID" — the server cannot price the order's lines
7553
7554
  * (none, a gone or unpriced product, a
7554
7555
  * quantity outside 1–999, over 100 lines)
7556
+ * - "OUT_OF_STOCK" — a product's stock cannot cover the order;
7557
+ * the message names it. Start a new order
7558
+ * without it (a priced order's lines are fixed)
7555
7559
  * - "BUYER_EMAIL_INVALID" — a guest's order has no valid email in
7556
7560
  * its buyer-email column; the receipt needs one
7557
7561
  * - "ORDER_PAYMENT_IN_PROGRESS" — another checkout for the order is open
package/dist/index.d.ts CHANGED
@@ -309,6 +309,15 @@ export interface WidgetDatastoreTemplateColumn {
309
309
  pricedItem?: boolean;
310
310
  /** NUMBER only, `immutable: true`, one per table: a line's quantity, 1 to 999 (empty is 1). */
311
311
  lineQuantity?: boolean;
312
+ /**
313
+ * NUMBER only, one per table, in a table with a `unitPrice`, NOT immutable:
314
+ * how many of a product are left (a whole number, 0 or more; empty is not
315
+ * counted). The server takes an order's quantities when its charge opens
316
+ * and gives them back once its provider reports it failed, cancelled or
317
+ * expired; a refund does not restock. It is what is available: items in
318
+ * checkouts in progress are already taken off. Read it to show a product as sold out; never write it.
319
+ */
320
+ stockQuantity?: boolean;
312
321
  /**
313
322
  * STRING only, at most one per table, in a table with a `paymentStatus`
314
323
  * column, and it must be `immutable: true` (not encrypted, `latestVia` or
@@ -1683,7 +1692,8 @@ export interface PaymentRequest {
1683
1692
  * order from its lines and charges that: ORDER_LINES_INVALID when it cannot,
1684
1693
  * ORDER_TOTAL_INVALID when the total is zero, and ORDER_AMOUNT_MISMATCH when
1685
1694
  * `amount_cents` differs from it. Once priced, adding or removing a line is
1686
- * refused with ORDER_LOCKED.
1695
+ * refused with ORDER_LOCKED. OUT_OF_STOCK when a product's `stockQuantity`
1696
+ * cannot cover the order; its message names the product.
1687
1697
  */
1688
1698
  order?: PaymentOrder;
1689
1699
  }
@@ -1860,6 +1870,7 @@ export class PaymentError extends Error {
1860
1870
  | "ORDER_TOTAL_INVALID"
1861
1871
  | "ORDER_AMOUNT_MISMATCH"
1862
1872
  | "ORDER_LINES_INVALID"
1873
+ | "OUT_OF_STOCK"
1863
1874
  | "BUYER_EMAIL_INVALID"
1864
1875
  | "ORDER_PAYMENT_IN_PROGRESS"
1865
1876
  | "ALREADY_OWNED"
package/dist/linter.cjs CHANGED
@@ -1881,6 +1881,166 @@ function _orderTotalUpdatedRules(source) {
1881
1881
  return findings;
1882
1882
  }
1883
1883
 
1884
+ // sc-16652 — payment-price-from-page.
1885
+ //
1886
+ // The page address, a wire input, the widget's own route and the device's bag
1887
+ // are the buyer's own: they can type a price into the URL or edit what
1888
+ // `useDeviceStorage` holds. An order charge whose `amount_cents` is computed
1889
+ // from one of them bills whatever the buyer wrote. The server prices an order
1890
+ // from the products table instead, so a shop creates the order and its lines
1891
+ // and charges with `order` and no amount. Only an order charge (`order`, or a
1892
+ // `kind: "physical"` sale) is judged: a donation or a tip the buyer chooses is
1893
+ // theirs to set. A value read from the datastore (a row, or a lookup into
1894
+ // rows) ends the trace, and the scan follows names through declarations, not
1895
+ // through functions or state setters.
1896
+ const _PAGE_HELD_HOOKS = ["useRouteParams", "usePageContext", "useWidgetInput", "useWidgetRoute", "useDeviceStorage"];
1897
+ const _DATASTORE_READ_RE = /^use(?:Paged)?Datastore(?!Mutation)/;
1898
+ const _DECLARATION_RE =
1899
+ /(?<![\w$.])(?:const|let|var)\s+(?:([A-Za-z_$][\w$]*)|\{([^{}]{0,400})\}|\[([^[\]]{0,200})\])\s*=(?![=>])/g;
1900
+ const _NAME_REFERENCE_RE = /(?<![\w$.])[A-Za-z_$][\w$]*/g;
1901
+ // Bounds each right-hand side, so one declaration never scans to EOF.
1902
+ const _DECLARATION_VALUE_MAX_CHARS = 400;
1903
+ // Taint moves one declaration per round; real widgets settle in two or three.
1904
+ const _TAINT_ROUNDS = 8;
1905
+ // A line ending on one of these, or a next line starting with one, continues.
1906
+ const _CONTINUES_AFTER = "=+-*/%&|?:(,.";
1907
+ const _CONTINUES_BEFORE = ".?:+-*/%&|";
1908
+ const _ENTRY_KEY_RE = /^(['"]?)([A-Za-z_$][\w$]*)\1\s*(?::|$)/;
1909
+ const _PHYSICAL_KIND_RE = /^\s*(['"`])physical\1\s*$/;
1910
+
1911
+ /** Index of the next non-space character at or after `from`, or `end`. */
1912
+ function _nextCodeAt(masked, from, end) {
1913
+ for (let i = from; i < end; i += 1) if (!/\s/.test(masked[i])) return i;
1914
+ return end;
1915
+ }
1916
+
1917
+ /** Text from `from` to the end of its statement or declarator, across wrapped lines. */
1918
+ function _declarationValue(masked, from) {
1919
+ let depth = 0;
1920
+ let last = "=";
1921
+ const end = Math.min(masked.length, from + _DECLARATION_VALUE_MAX_CHARS);
1922
+ for (let i = from; i < end; i += 1) {
1923
+ const ch = masked[i];
1924
+ if (_OPENERS.includes(ch) && !(ch === "{" && masked[i - 1] === "$")) depth += 1;
1925
+ else if (_CLOSERS.includes(ch)) {
1926
+ if (depth === 0) return masked.slice(from, i);
1927
+ depth -= 1;
1928
+ } else if (depth === 0 && (ch === ";" || ch === ",")) {
1929
+ return masked.slice(from, i);
1930
+ } else if (depth === 0 && ch === "\n" && !_CONTINUES_AFTER.includes(last)) {
1931
+ // Jump to the next code, so a run of blank lines is read once.
1932
+ const next = _nextCodeAt(masked, i + 1, end);
1933
+ if (next === end || !_CONTINUES_BEFORE.includes(masked[next])) return masked.slice(from, i);
1934
+ i = next - 1;
1935
+ continue;
1936
+ }
1937
+ if (!/\s/.test(ch)) last = ch;
1938
+ }
1939
+ return masked.slice(from, end);
1940
+ }
1941
+
1942
+ /** The local names a destructuring pattern's body binds. */
1943
+ function _patternNames(body) {
1944
+ const names = [];
1945
+ for (const entry of body.split(",")) {
1946
+ const target = entry.replace(/^\s*\.\.\./, "").split(":").pop().split("=")[0].trim();
1947
+ if (/^[A-Za-z_$][\w$]*$/.test(target)) names.push(target);
1948
+ }
1949
+ return names;
1950
+ }
1951
+
1952
+ /** Grows `into` with every declaration's names whose value uses one of its names. */
1953
+ function _spread(declarations, into, skip = null) {
1954
+ for (let round = 0; round < _TAINT_ROUNDS; round += 1) {
1955
+ let grew = false;
1956
+ for (const { names, uses } of declarations) {
1957
+ if (names.every((n) => into.has(n)) || (skip && names.some((n) => skip.has(n)))) continue;
1958
+ if (![...uses].some((u) => into.has(u))) continue;
1959
+ for (const n of names) into.add(n);
1960
+ grew = true;
1961
+ }
1962
+ if (!grew) break;
1963
+ }
1964
+ return into;
1965
+ }
1966
+
1967
+ /** Names read from the datastore, and names derived from what the buyer holds. */
1968
+ function _valueSources(masked) {
1969
+ const declarations = [];
1970
+ const stored = new Set();
1971
+ for (const m of masked.matchAll(_DECLARATION_RE)) {
1972
+ const names = m[1] ? [m[1]] : _patternNames(m[2] ?? m[3]);
1973
+ if (!names.length) continue;
1974
+ const uses = new Set(_declarationValue(masked, m.index + m[0].length).match(_NAME_REFERENCE_RE));
1975
+ if ([...uses].some((u) => _DATASTORE_READ_RE.test(u))) for (const n of names) stored.add(n);
1976
+ declarations.push({ names, uses });
1977
+ }
1978
+ _spread(declarations, stored);
1979
+ const held = _spread(declarations, new Set(_PAGE_HELD_HOOKS), stored);
1980
+ return { stored, held };
1981
+ }
1982
+
1983
+ /** Top-level `key -> value code` of the object literal opening at `open`, or null. */
1984
+ function _objectEntries(masked, kept, open) {
1985
+ const close = _closingParen(masked, open);
1986
+ if (close === -1) return null;
1987
+ const entries = new Map();
1988
+ let depth = 0;
1989
+ let start = open + 1;
1990
+ for (let i = start; i <= close; i += 1) {
1991
+ const ch = masked[i];
1992
+ if (i === close || (depth === 0 && ch === ",")) {
1993
+ // The key may be quoted, so it is read with strings kept.
1994
+ const key = _ENTRY_KEY_RE.exec(kept.slice(start, i).trim());
1995
+ if (key) {
1996
+ const colon = kept.indexOf(":", start);
1997
+ const hasValue = colon !== -1 && colon < i;
1998
+ entries.set(key[2], { code: hasValue ? masked.slice(colon + 1, i) : key[2], text: hasValue ? kept.slice(colon + 1, i) : key[2] });
1999
+ }
2000
+ start = i + 1;
2001
+ continue;
2002
+ }
2003
+ if (_OPENERS.includes(ch) && !(ch === "{" && masked[i - 1] === "$")) depth += 1;
2004
+ else if (_CLOSERS.includes(ch)) depth -= 1;
2005
+ }
2006
+ return entries;
2007
+ }
2008
+
2009
+ function _paymentPriceFromPageRules(source) {
2010
+ const masked = _stripNonCode(source);
2011
+ if (!PAYMENT_CHARGE_CALL_RE.test(masked)) return [];
2012
+ if (!_PAGE_HELD_HOOKS.some((hook) => masked.includes(hook))) return [];
2013
+ const kept = _stripNonCode(source, { keepStrings: true });
2014
+ const { stored, held } = _valueSources(masked);
2015
+ const sourceLines = source.split(/\r?\n/);
2016
+ const lineAt = _lineCounter(masked);
2017
+ const findings = [];
2018
+ for (const call of masked.matchAll(REQUEST_PAYMENT_CALL_RE)) {
2019
+ if (/\bfunction\s*$/.test(masked.slice(Math.max(0, call.index - 16), call.index))) continue;
2020
+ const open = _paymentArgumentObject(masked, kept, call.index + call[0].length);
2021
+ if (open === -1) continue;
2022
+ const entries = _objectEntries(masked, kept, open);
2023
+ const amount = entries?.get("amount_cents");
2024
+ if (!amount) continue;
2025
+ const sellsOrder = entries.has("order") || _PHYSICAL_KIND_RE.test(entries.get("kind")?.text ?? "");
2026
+ const names = amount.code.match(_NAME_REFERENCE_RE) ?? [];
2027
+ if (!sellsOrder || names.some((n) => stored.has(n)) || !names.some((n) => held.has(n))) continue;
2028
+ const line = lineAt(call.index);
2029
+ findings.push({
2030
+ rule: "payment-price-from-page",
2031
+ severity: "warning",
2032
+ label:
2033
+ `this order charge's amount comes from the page address, a wire ` +
2034
+ `input or the device's bag, which the buyer can change. Keep only ` +
2035
+ `product ids and quantities there: create the order and its lines, ` +
2036
+ `then call requestPayment with order and no amount_cents.`,
2037
+ line,
2038
+ snippet: (sourceLines[line - 1] || "").trim().slice(0, 200),
2039
+ });
2040
+ }
2041
+ return findings;
2042
+ }
2043
+
1884
2044
  // sc-4686 — no-hardcoded-currency-label.
1885
2045
  //
1886
2046
  // The charge is safe once `currency` is omitted, but the DISPLAY is not: a "kr"
@@ -5111,6 +5271,7 @@ function lintSource(source, options) {
5111
5271
  findings.push(..._paymentKindRules(source));
5112
5272
  findings.push(..._paymentStatusWrittenRules(source));
5113
5273
  findings.push(..._orderTotalUpdatedRules(source));
5274
+ findings.push(..._paymentPriceFromPageRules(source));
5114
5275
  findings.push(..._hardcodedCurrencyLabelRules(source));
5115
5276
  findings.push(..._fixedDateFormatRules(source));
5116
5277
  findings.push(..._paymentErrorHandlingRules(source));
package/dist/linter.js CHANGED
@@ -1876,6 +1876,166 @@ function _orderTotalUpdatedRules(source) {
1876
1876
  return findings;
1877
1877
  }
1878
1878
 
1879
+ // sc-16652 — payment-price-from-page.
1880
+ //
1881
+ // The page address, a wire input, the widget's own route and the device's bag
1882
+ // are the buyer's own: they can type a price into the URL or edit what
1883
+ // `useDeviceStorage` holds. An order charge whose `amount_cents` is computed
1884
+ // from one of them bills whatever the buyer wrote. The server prices an order
1885
+ // from the products table instead, so a shop creates the order and its lines
1886
+ // and charges with `order` and no amount. Only an order charge (`order`, or a
1887
+ // `kind: "physical"` sale) is judged: a donation or a tip the buyer chooses is
1888
+ // theirs to set. A value read from the datastore (a row, or a lookup into
1889
+ // rows) ends the trace, and the scan follows names through declarations, not
1890
+ // through functions or state setters.
1891
+ const _PAGE_HELD_HOOKS = ["useRouteParams", "usePageContext", "useWidgetInput", "useWidgetRoute", "useDeviceStorage"];
1892
+ const _DATASTORE_READ_RE = /^use(?:Paged)?Datastore(?!Mutation)/;
1893
+ const _DECLARATION_RE =
1894
+ /(?<![\w$.])(?:const|let|var)\s+(?:([A-Za-z_$][\w$]*)|\{([^{}]{0,400})\}|\[([^[\]]{0,200})\])\s*=(?![=>])/g;
1895
+ const _NAME_REFERENCE_RE = /(?<![\w$.])[A-Za-z_$][\w$]*/g;
1896
+ // Bounds each right-hand side, so one declaration never scans to EOF.
1897
+ const _DECLARATION_VALUE_MAX_CHARS = 400;
1898
+ // Taint moves one declaration per round; real widgets settle in two or three.
1899
+ const _TAINT_ROUNDS = 8;
1900
+ // A line ending on one of these, or a next line starting with one, continues.
1901
+ const _CONTINUES_AFTER = "=+-*/%&|?:(,.";
1902
+ const _CONTINUES_BEFORE = ".?:+-*/%&|";
1903
+ const _ENTRY_KEY_RE = /^(['"]?)([A-Za-z_$][\w$]*)\1\s*(?::|$)/;
1904
+ const _PHYSICAL_KIND_RE = /^\s*(['"`])physical\1\s*$/;
1905
+
1906
+ /** Index of the next non-space character at or after `from`, or `end`. */
1907
+ function _nextCodeAt(masked, from, end) {
1908
+ for (let i = from; i < end; i += 1) if (!/\s/.test(masked[i])) return i;
1909
+ return end;
1910
+ }
1911
+
1912
+ /** Text from `from` to the end of its statement or declarator, across wrapped lines. */
1913
+ function _declarationValue(masked, from) {
1914
+ let depth = 0;
1915
+ let last = "=";
1916
+ const end = Math.min(masked.length, from + _DECLARATION_VALUE_MAX_CHARS);
1917
+ for (let i = from; i < end; i += 1) {
1918
+ const ch = masked[i];
1919
+ if (_OPENERS.includes(ch) && !(ch === "{" && masked[i - 1] === "$")) depth += 1;
1920
+ else if (_CLOSERS.includes(ch)) {
1921
+ if (depth === 0) return masked.slice(from, i);
1922
+ depth -= 1;
1923
+ } else if (depth === 0 && (ch === ";" || ch === ",")) {
1924
+ return masked.slice(from, i);
1925
+ } else if (depth === 0 && ch === "\n" && !_CONTINUES_AFTER.includes(last)) {
1926
+ // Jump to the next code, so a run of blank lines is read once.
1927
+ const next = _nextCodeAt(masked, i + 1, end);
1928
+ if (next === end || !_CONTINUES_BEFORE.includes(masked[next])) return masked.slice(from, i);
1929
+ i = next - 1;
1930
+ continue;
1931
+ }
1932
+ if (!/\s/.test(ch)) last = ch;
1933
+ }
1934
+ return masked.slice(from, end);
1935
+ }
1936
+
1937
+ /** The local names a destructuring pattern's body binds. */
1938
+ function _patternNames(body) {
1939
+ const names = [];
1940
+ for (const entry of body.split(",")) {
1941
+ const target = entry.replace(/^\s*\.\.\./, "").split(":").pop().split("=")[0].trim();
1942
+ if (/^[A-Za-z_$][\w$]*$/.test(target)) names.push(target);
1943
+ }
1944
+ return names;
1945
+ }
1946
+
1947
+ /** Grows `into` with every declaration's names whose value uses one of its names. */
1948
+ function _spread(declarations, into, skip = null) {
1949
+ for (let round = 0; round < _TAINT_ROUNDS; round += 1) {
1950
+ let grew = false;
1951
+ for (const { names, uses } of declarations) {
1952
+ if (names.every((n) => into.has(n)) || (skip && names.some((n) => skip.has(n)))) continue;
1953
+ if (![...uses].some((u) => into.has(u))) continue;
1954
+ for (const n of names) into.add(n);
1955
+ grew = true;
1956
+ }
1957
+ if (!grew) break;
1958
+ }
1959
+ return into;
1960
+ }
1961
+
1962
+ /** Names read from the datastore, and names derived from what the buyer holds. */
1963
+ function _valueSources(masked) {
1964
+ const declarations = [];
1965
+ const stored = new Set();
1966
+ for (const m of masked.matchAll(_DECLARATION_RE)) {
1967
+ const names = m[1] ? [m[1]] : _patternNames(m[2] ?? m[3]);
1968
+ if (!names.length) continue;
1969
+ const uses = new Set(_declarationValue(masked, m.index + m[0].length).match(_NAME_REFERENCE_RE));
1970
+ if ([...uses].some((u) => _DATASTORE_READ_RE.test(u))) for (const n of names) stored.add(n);
1971
+ declarations.push({ names, uses });
1972
+ }
1973
+ _spread(declarations, stored);
1974
+ const held = _spread(declarations, new Set(_PAGE_HELD_HOOKS), stored);
1975
+ return { stored, held };
1976
+ }
1977
+
1978
+ /** Top-level `key -> value code` of the object literal opening at `open`, or null. */
1979
+ function _objectEntries(masked, kept, open) {
1980
+ const close = _closingParen(masked, open);
1981
+ if (close === -1) return null;
1982
+ const entries = new Map();
1983
+ let depth = 0;
1984
+ let start = open + 1;
1985
+ for (let i = start; i <= close; i += 1) {
1986
+ const ch = masked[i];
1987
+ if (i === close || (depth === 0 && ch === ",")) {
1988
+ // The key may be quoted, so it is read with strings kept.
1989
+ const key = _ENTRY_KEY_RE.exec(kept.slice(start, i).trim());
1990
+ if (key) {
1991
+ const colon = kept.indexOf(":", start);
1992
+ const hasValue = colon !== -1 && colon < i;
1993
+ entries.set(key[2], { code: hasValue ? masked.slice(colon + 1, i) : key[2], text: hasValue ? kept.slice(colon + 1, i) : key[2] });
1994
+ }
1995
+ start = i + 1;
1996
+ continue;
1997
+ }
1998
+ if (_OPENERS.includes(ch) && !(ch === "{" && masked[i - 1] === "$")) depth += 1;
1999
+ else if (_CLOSERS.includes(ch)) depth -= 1;
2000
+ }
2001
+ return entries;
2002
+ }
2003
+
2004
+ function _paymentPriceFromPageRules(source) {
2005
+ const masked = _stripNonCode(source);
2006
+ if (!PAYMENT_CHARGE_CALL_RE.test(masked)) return [];
2007
+ if (!_PAGE_HELD_HOOKS.some((hook) => masked.includes(hook))) return [];
2008
+ const kept = _stripNonCode(source, { keepStrings: true });
2009
+ const { stored, held } = _valueSources(masked);
2010
+ const sourceLines = source.split(/\r?\n/);
2011
+ const lineAt = _lineCounter(masked);
2012
+ const findings = [];
2013
+ for (const call of masked.matchAll(REQUEST_PAYMENT_CALL_RE)) {
2014
+ if (/\bfunction\s*$/.test(masked.slice(Math.max(0, call.index - 16), call.index))) continue;
2015
+ const open = _paymentArgumentObject(masked, kept, call.index + call[0].length);
2016
+ if (open === -1) continue;
2017
+ const entries = _objectEntries(masked, kept, open);
2018
+ const amount = entries?.get("amount_cents");
2019
+ if (!amount) continue;
2020
+ const sellsOrder = entries.has("order") || _PHYSICAL_KIND_RE.test(entries.get("kind")?.text ?? "");
2021
+ const names = amount.code.match(_NAME_REFERENCE_RE) ?? [];
2022
+ if (!sellsOrder || names.some((n) => stored.has(n)) || !names.some((n) => held.has(n))) continue;
2023
+ const line = lineAt(call.index);
2024
+ findings.push({
2025
+ rule: "payment-price-from-page",
2026
+ severity: "warning",
2027
+ label:
2028
+ `this order charge's amount comes from the page address, a wire ` +
2029
+ `input or the device's bag, which the buyer can change. Keep only ` +
2030
+ `product ids and quantities there: create the order and its lines, ` +
2031
+ `then call requestPayment with order and no amount_cents.`,
2032
+ line,
2033
+ snippet: (sourceLines[line - 1] || "").trim().slice(0, 200),
2034
+ });
2035
+ }
2036
+ return findings;
2037
+ }
2038
+
1879
2039
  // sc-4686 — no-hardcoded-currency-label.
1880
2040
  //
1881
2041
  // The charge is safe once `currency` is omitted, but the DISPLAY is not: a "kr"
@@ -5106,6 +5266,7 @@ export function lintSource(source, options) {
5106
5266
  findings.push(..._paymentKindRules(source));
5107
5267
  findings.push(..._paymentStatusWrittenRules(source));
5108
5268
  findings.push(..._orderTotalUpdatedRules(source));
5269
+ findings.push(..._paymentPriceFromPageRules(source));
5109
5270
  findings.push(..._hardcodedCurrencyLabelRules(source));
5110
5271
  findings.push(..._fixedDateFormatRules(source));
5111
5272
  findings.push(..._paymentErrorHandlingRules(source));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.355.1",
3
+ "version": "0.357.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
@@ -2512,7 +2512,7 @@ const HOOKS = [
2512
2512
  signature: "usePayments()",
2513
2513
  returnShape: {
2514
2514
  requestPayment:
2515
- "({ 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); amount_cents (minor units) is REQUIRED without order; 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). The orders table also REQUIRES an order-total column the server prices (orderTotal: { lines, via } in the datastoreTemplate; without one: ORDER_NOT_PAYABLE): create the order, then its lines, then pass order and omit amount_cents — the server sums quantity × the products table's unitPrice (plus the order's own pricedItem, e.g. shipping), writes the total and charges it; never compute, write or send a total (if amount_cents is sent it must equal the total; refused, not retryable: ORDER_LINES_INVALID when the lines cannot be priced, ORDER_TOTAL_INVALID when the total is zero, ORDER_AMOUNT_MISMATCH when amount_cents differs; ORDER_NOT_PAYABLE also when the payer could write or create a price). Once priced, the order's lines are fixed (adding or removing one: ORDER_LOCKED); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2515
+ "({ 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); amount_cents (minor units) is REQUIRED without order; 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). The orders table also REQUIRES an order-total column the server prices (orderTotal: { lines, via } in the datastoreTemplate; without one: ORDER_NOT_PAYABLE): create the order, then its lines, then pass order and omit amount_cents — the server sums quantity × the products table's unitPrice (plus the order's own pricedItem, e.g. shipping), writes the total and charges it; never compute, write or send a total (if amount_cents is sent it must equal the total; refused, not retryable: ORDER_LINES_INVALID when the lines cannot be priced, ORDER_TOTAL_INVALID when the total is zero, ORDER_AMOUNT_MISMATCH when amount_cents differs; ORDER_NOT_PAYABLE also when the payer could write or create a price; OUT_OF_STOCK, naming the product, when a product's stockQuantity cannot cover the order — show it sold out and let the buyer start a new order without it). Once priced, the order's lines are fixed (adding or removing one: ORDER_LOCKED); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2516
2516
  getPayment:
2517
2517
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // order: { table_id, record_id } | null — read it after returning from Checkout",
2518
2518
  requestGuestPayment:
@@ -4385,7 +4385,7 @@ const MANIFEST_SCHEMA = {
4385
4385
  type: "object",
4386
4386
  required: false,
4387
4387
  description:
4388
- "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: { lines: \"<lines table suffix>\", via: \"<its relation to this table>\" }` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The SERVER prices it when the charge opens and ignores any client value: Σ over the order's lines of `lineQuantity` × the `unitPrice` of the row the line's `pricedItem` names, plus the order table's own `pricedItem` once (a shipping option). `via` is a write-once ONE_TO_MANY relation on the lines table pointing at this table. A bare `orderTotal: true` is accepted only on an orders table that has its own `pricedItem`; publishing any other unpriced order total is refused (an already published template still installs, and its order charges are refused with ORDER_NOT_PAYABLE). `unitPrice: true` makes a NUMBER column a product's price in minor units (one per table). `pricedItem: true` makes a write-once single RELATION (one per table) to a table with a unitPrice column the item a line or an order is priced by. `lineQuantity: true` makes a write-once NUMBER column (one per table) a line's quantity, a whole number from 1 to 999 (empty is 1). A payer who may edit or create rows in a priced table is refused, and once an order holds its total no line is added or removed (ORDER_LOCKED). `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4388
+ "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: { lines: \"<lines table suffix>\", via: \"<its relation to this table>\" }` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The SERVER prices it when the charge opens and ignores any client value: Σ over the order's lines of `lineQuantity` × the `unitPrice` of the row the line's `pricedItem` names, plus the order table's own `pricedItem` once (a shipping option). `via` is a write-once ONE_TO_MANY relation on the lines table pointing at this table. A bare `orderTotal: true` is accepted only on an orders table that has its own `pricedItem`; publishing any other unpriced order total is refused (an already published template still installs, and its order charges are refused with ORDER_NOT_PAYABLE). `unitPrice: true` makes a NUMBER column a product's price in minor units (one per table). `pricedItem: true` makes a write-once single RELATION (one per table) to a table with a unitPrice column the item a line or an order is priced by. `lineQuantity: true` makes a write-once NUMBER column (one per table) a line's quantity, a whole number from 1 to 999 (empty is 1). `stockQuantity: true` makes a NUMBER column (one per table, in a table with a unitPrice column, not immutable) how many of a product are left, a whole number of 0 or more (empty is not counted): a charge takes its order's quantities when it opens, refusing with OUT_OF_STOCK when one cannot be covered, and gives them back exactly once if it fails, is cancelled or stays unpaid past 15 minutes; a paid order keeps them and a refund does not restock (the seller restocks in the Studio). Read it to show a product sold out at 0; a widget never writes it. A payer who may edit or create rows in a priced table is refused, and once an order holds its total no line is added or removed (ORDER_LOCKED). `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4389
4389
  },
4390
4390
  translations: {
4391
4391
  type: "object",
@@ -7197,7 +7197,13 @@ const CONTRACT = deepFreeze({
7197
7197
  // draw is the publish-blocking `button-unknown-variant` finding.
7198
7198
  // 1.291.0: behaviour (sc-18689) — a vertical native `ScrollView`, `FlatList`
7199
7199
  // or `SectionList` sets `nestedScrollEnabled` unless inverted or the author sets it.
7200
- version: "1.291.0",
7200
+ // 1.292.0: additive (sc-18009) — a template column may declare
7201
+ // `stockQuantity: true`; a charge reserves stock and refuses with the new
7202
+ // PaymentError code OUT_OF_STOCK when a product cannot cover the order.
7203
+ // 1.293.0: additive (sc-16652) — the `payment-price-from-page` lint warning
7204
+ // flags an order charge whose amount comes from the page address, a
7205
+ // wire input or the bag.
7206
+ version: "1.293.0",
7201
7207
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7202
7208
  hooks: HOOKS,
7203
7209
  primitives: PRIMITIVES,