@colixsystems/widget-sdk 0.86.0 → 0.88.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
@@ -17,11 +17,11 @@ The data layer lives in **four separate domain-client packages**, each instantia
17
17
 
18
18
  | Group | Hook (signature) | Returns | Reads / scope |
19
19
  | ----- | ---------------- | ------- | ------------- |
20
- | **CORE** | `useTheme()` | `{ colors, elevation, spacing, radii, typography, components }` | `ctx.workspace.theme` — no scope. `elevation` is the shared depth scale (`none / sm / md / lg / xl`) you spread into a style; `colors` includes the accent's quiet tiers (`primarySoft` / `onPrimarySoft` / `primaryStrong`). `components` is HOST-OWNED (the theme's per-component style tokens); the host has already folded it into your `props.style`, so read `useWidgetStyle()` and ignore this slice. |
20
+ | **CORE** | `useTheme()` | `{ colors, elevation, spacing, spacingScale, radii, typography, components, widgetStyles }` | `ctx.workspace.theme` — no scope. `elevation` is the shared depth scale (`none / sm / md / lg / xl`) you spread into a style; `colors` includes the accent's quiet tiers (`primarySoft` / `onPrimarySoft` / `primaryStrong`). `components` is HOST-OWNED (the theme's per-component style tokens); the host has already folded it into your `props.style`, so read `useWidgetStyle()` and ignore this slice. |
21
21
  | **CORE** | `useWorkspaceCurrency()` | `{ currency, formatMoney }` | `ctx.workspace.currency` — no scope. The currency this workspace charges its app users in, resolved at RENDER time. Render every price as `formatMoney(minorUnits)` and never write a currency symbol or code into a widget: the owner can change it after the widget ships, and a baked label then contradicts the charge. |
22
22
  | **CORE** | `useWidgetStyle()` | `{ [styleField]: value }` | `ctx.props.style` — no scope. The author-set per-widget style values declared in `manifest.styleSchema`; apply each onto whatever element you choose. |
23
23
  | **CORE** | `useUser()` | `{ id, email, displayName, roles, groupIds }` | `ctx.user` (host-built context, **camelCase** — not a wire payload; `id` null when anonymous) — no scope |
24
- | **CORE** | `useNavigation()` | `{ goTo, goBack, push, replace, back, currentRoute }` | `ctx.navigation` — no scope (external URLs use the `Linking` primitive) |
24
+ | **CORE** | `useNavigation()` | `{ goTo, goBack, push, replace, back, currentRoute, openLink }` | `ctx.navigation` — no scope (`openLink` for a link of unknown shape; a known external URL can also use the `Linking` primitive) |
25
25
  | **CORE** | `useRouteParams()` | `{ [paramKey]: value }` | `ctx.navigation.currentRoute.params` — no scope. The nav params the previous page passed via `goTo(pageId, params)`; the flat accessor for master→detail (read `recordId` on a detail page). Empty object when none. |
26
26
  | **CORE** | `usePageContext()` | `{ params, records }` | `ctx.pageContext` — no scope. The page's DECLARED parameters, resolved once by the host: `params` are coerced to their declared types, `records` holds the row already fetched for each `record` param (read it instead of fetching again). Both empty when the page declares none. |
27
27
  | **CORE** | `useWidgetEvent(name)` | `(payload?) => void` | `ctx.events.emit` — no scope. The hook IS the emitter: `const emitSlot = useWidgetEvent("slotChosen")`, then `emitSlot(payload)`. Never destructure the result — there is no `emit` member. |
@@ -33,7 +33,7 @@ The data layer lives in **four separate domain-client packages**, each instantia
33
33
  | **CORE** | `useSectionEmpty(isEmpty)` | `void` | `ctx.section.reportEmpty` — no scope. Declares that the widget has NO content to show, so the host drops its layout slot instead of reserving space (and its parent's `gap`) for it. Returning `null` is not enough: the host wraps every widget in an entrance element, so a widget rendering nothing still leaves an empty box the parent stack gaps around. For a CONDITIONALLY ABSENT section (a per-record child collection with no rows for this record), never to suppress a genuine empty state. Stays mounted while collapsed, so passing `false` brings it back. Authoring surfaces never collapse. No-op on a host that doesn't implement it. |
34
34
  | **CORE** | `useRefresh(handler)` | `void` | `ctx.refresh.subscribe` — no scope. Subscribes the handler to the page-level refresh tick (pull-to-refresh on mobile). Handler may return a Promise — the host waits for `allSettled` before clearing the spinner. The three datastore hooks auto-subscribe their own `refetch`; widgets only call this directly to re-run non-datastore work. No-op on a host that doesn't implement refresh. |
35
35
  | **CORE** | `useClipboard()` | `{ copy, paste, hasContent }` | platform clipboard (web `navigator.clipboard` / native `expo-clipboard`); rejects with `ClipboardError` — no scope |
36
- | **CORE** | `useToast()` | `{ showToast }` | `ctx.toast.showToast` (falls back to a CustomEvent / console) — no scope |
36
+ | **CORE** | `useToast()` | `{ showToast }` | `ctx.toast.showToast` wired by the Player and the Expo export; an authoring preview omits it and the call is a no-op — no scope |
37
37
  | **CORE** | `useGeolocation(options?)` | `{ latitude, longitude, accuracy, loading, error, getCurrentPosition }` | `ctx.device.geolocation` — no scope. Capture is IMPERATIVE: call `getCurrentPosition()` from a user gesture (a tap), never on mount. Resolves to `{ latitude, longitude, accuracy }`; rejects with `GeolocationError` (`.code` in `PERMISSION_DENIED \| UNAVAILABLE \| TIMEOUT \| UNSUPPORTED \| INTERNAL`). Identical on web (`navigator.geolocation`) and the Expo export (`expo-location`). |
38
38
  | **CORE** | `useI18n()` | `{ t, locale }` | `ctx.i18n` — no scope. `t(key)` resolves the widget-namespaced key (`widget.<id>.<key>`, declared in `manifest.translations`) first, then a **predefined shared key** (`shared.<key>`) when `key` is one of the standard strings (`submit`, `cancel`, `save`, `loading`, …), then the raw key. Use a shared key for an identical default string so it translates once and any per-instance `widget.<id>.<key>` override still wins. |
39
39
  | **CORE** | `useTranslate()` | `{ translate, translating, error, language, available }` | `ctx.i18n.translate` — no scope. Machine-translates **user-generated content** (record text, file names, API payloads) into the app user's language; `useI18n().t()` is still the answer for your own copy. `translate(str)` → `Promise<string>`, `translate(str[])` → `Promise<string[]>` in ONE request. Target defaults to the app user's language. Cached per session, per pod, and durably per workspace, so repeat text is free. Limits: 50 segments / 5 000 chars each / 20 000 total. Rejects with `TranslateError`; `available` is false where the host cannot translate. |
@@ -61,7 +61,71 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
61
61
 
62
62
  ## Status
63
63
 
64
- `v0.86.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**.
64
+ `v0.88.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**.
65
+
66
+ ### What's new in 0.88.0 (contract 1.62.0)
67
+
68
+ **A refused datastore / directory / permission call now reaches the widget as its real reason (sc-4986).**
69
+
70
+ - **The reason was being thrown away.** Each `@colixsystems/*-client` throws typed
71
+ errors carrying `.code` / `.status` / `.details` (the parsed envelope) and **no
72
+ `.response`** — but `toDatastoreError`, `toDirectoryError` and
73
+ `toPermissionError` read `err.response.*` only. Every typed client rejection
74
+ fell through every branch and arrived as `code: "INTERNAL"`, so a 403 the
75
+ workspace owner has to lift was indistinguishable from a dropped socket, and
76
+ `DatastoreError.fieldErrors` never populated at all. `toPaymentError` was fixed
77
+ for exactly this in 0.83.0; these three were not.
78
+ - **All three mappers now read both shapes**, preferring the envelope's own
79
+ `message` (the canonical `{ statusCode, message, code }` field — the old code
80
+ read a `.error` key the envelope has never carried). The documented `code`
81
+ vocabularies are unchanged, so a widget already branching on
82
+ `code === "FORBIDDEN"` starts working rather than having to change.
83
+ - **`DatastoreError` / `DirectoryError` / `PermissionError` gain `retryable`**
84
+ (and `status`). `retryable === false` for a refusal only the caller, the record
85
+ or the workspace can clear — 403 / 404 / 400 / 422 / 409 — and `true` for a
86
+ timeout, a rate limit, a 5xx or a dropped socket. Branch on it instead of
87
+ offering a blanket "try again". This is deliberately *not* the payments rule:
88
+ a 402 `DECLINED` card IS worth another attempt, so that contract differs.
89
+ - **`fieldErrors` works again** — a 400/422 carrying
90
+ `errors: [{ field, code, message }]` becomes the flat `{ field: message }` map
91
+ the type has always advertised, so a form can mark the offending input.
92
+ - **New soft lint rule `datastore-error-not-branched`** (severity `warning`,
93
+ never blocks a publish): a widget that writes with `useDatastoreMutation` but
94
+ never reads `retryable`, branches on `code ===`, or renders the error's own
95
+ `.message` is flagged, so the AI widget agent's repair loop closes the gap.
96
+ - `CONTRACT.version` → `1.62.0`: the three hooks' `returnShape` entries now name
97
+ the `{ code, message, retryable }` triple. No export or signature changed —
98
+ additive fields on three error classes.
99
+
100
+ ### What's new in 0.87.0 (contract 1.61.1)
101
+
102
+ **Widget toasts are actually rendered now — both hosts wire `ctx.toast` (sc-4939).**
103
+
104
+ - **The host half of `useToast()` shipped.** The hook has existed since 0.15.0 and
105
+ the AI widget agent has always been told to confirm a write with
106
+ `showToast({ kind: "success", … })` — but no host ever populated the
107
+ `WidgetContext.toast` slot. So the web variant dispatched an
108
+ `appstudio:widget-toast` CustomEvent that nothing listened for, and native fell
109
+ through to `console.log`. Every write confirmation an app raised was invisible:
110
+ a user tapped Save and got nothing back. The web Player and the exported Expo
111
+ app now both paint a workspace-themed stack, so a confirmation you raise is a
112
+ confirmation the user sees.
113
+ - **New host exports (`@colixsystems/widget-sdk/host`)** — `createToastController()`
114
+ (the queue, the auto-dismiss timing, newest-first stacking, injectable timers)
115
+ and `resolveToastTokens(theme, kind)` (the themed values a toast is painted
116
+ with, `error` mapping to the theme's `danger` role), plus `normalizeToastKind`
117
+ and `TOAST_DEFAULTS`. Both hosts drive these, so only the JSX differs and the
118
+ two cannot drift. This entry point is host integration, not the author API —
119
+ a widget author still just calls `useToast()`.
120
+ - **No author-facing change.** No export, signature, hook or manifest field
121
+ moved; a widget already calling `showToast` is unchanged and simply becomes
122
+ visible. `CONTRACT.version` → `1.61.1` for the corrected `useToast` /
123
+ `widgetContextShape.toast` descriptions, which used to imply a host might not
124
+ render the toast at all.
125
+ - **An authoring preview still wires nothing.** The Studio canvas leaves the slot
126
+ unset on purpose — a confirmation belongs to the running app, not to
127
+ design-time — so `showToast` is a no-op there, as `navigation` and `events`
128
+ already are.
65
129
 
66
130
  ### What's new in 0.86.0 (contract unchanged)
67
131
 
@@ -72,6 +136,16 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
72
136
 
73
137
  `CONTRACT` is unchanged (no new field), and no export changed signature.
74
138
 
139
+ ### What's new in 0.86.0 (contract 1.61.0)
140
+
141
+ - **The workspace theme now reaches the elements an app is built from.** Three things that used to be unreachable are now themeable: an element inside YOUR widget, the structural card container a page is made of, and any style field whose name the platform does not know. For a widget author the practical change is that **your `styleSchema` is the contract**: every field you declare becomes a knob the workspace owner can set once for the whole app, so declare the fields that describe your widget's appearance and give them clear `label`s and `ui.group`s — those labels are what the owner reads.
142
+ - **A field name you invented is as reachable as a canonical one.** A theme may carry values keyed by your widget's manifest id and then by your own field names, so `panelFill` is adjustable app-wide exactly like `cardBackground`. Separately, the unambiguous card names (`cardBackground`, `cardBorderColor`, `cardRadius`, `cardPadding`, `cardGradient`) bind by NAME to any widget that declares them, so naming a genuine card surface canonically opts it into the workspace's Cards controls for free.
143
+ - **`useTheme().colors` describes the surface your widget SITS ON, not the page.** A layout container that paints its own background re-derives the surface roles for everything inside it, so reading `colors.onSurface` for your text is readable whether your widget lands on the page, in a dark hero, or in a light card nested inside that hero. Nothing to opt into.
144
+ - **Precedence, unchanged in spirit.** Contract default → workspace palette → component scope → per-widget-type value → the app author's per-instance `props.style`. Most specific wins, and the Properties Panel is still the final word. Your widget reads `props.style` exactly as before and never learns which layer supplied a value.
145
+ - **A colour may carry OPACITY.** `isHexColor` accepts the 8-digit `#RRGGBBAA` form alongside 3 and 6 digits, so a theme colour with an alpha reaches `useTheme()` with its transparency intact. It used to be rejected and the host dropped the key outright, which is why a translucent page background never reached the dark-surface derivation and every panel fell back to white.
146
+ - **The colour maths ignores alpha, on purpose.** `hexChannels` reads the R/G/B pair and skips any alpha, so contrast, readable text and the derived accent tints reason about the opaque colour. None of them can composite without knowing the backdrop, which a token table does not have — so transparency lives in the VALUE your widget renders, not in the decision about whether that colour reads as light or dark.
147
+ - **`CONTRACT.version` → `1.61.0`** (additive: `themeTokens.spacingScale` + `widgetStyles` and their bounds, `themeComponents.card.universalFields`, and the `normaliseWidgetStyles` / `deriveSurfaceTokens` host exports). No author-facing export changed signature, and a theme that sets none of it resolves exactly as before.
148
+
75
149
  ### What's new in 0.85.1 (contract 1.60.1)
76
150
 
77
151
  **`useWidgetEvent(name)` returns the emitter FUNCTION — the declared contract said otherwise (sc-4753).** `CONTRACT.hooks`'s entry for the hook declared `returnShape: { emit }`, so every surface derived from it — chiefly the Widget Builder Agent's hooks table — told authors the hook resolves to an object. It never did: `useWidgetEvent("slotChosen")` hands back the callable you invoke directly (`emitSlot({ courtId })`), exactly as the typings and the Developer guide have always documented. A widget written against the declared shape destructured a function, got `undefined`, and threw the moment a user interacted — a cross-widget wire that rendered perfectly and only failed on click. The declaration is now a bare callable and the publish-time render harness models the same shape, so a wrong destructure is caught instead of waved through. `CONTRACT.version` → `1.60.1`. Documentation-only correction: no export, signature, or runtime behaviour changed — a widget already calling the result is unaffected.
@@ -204,6 +278,7 @@ useEffect(() => {
204
278
 
205
279
  **The theme can restyle ONE component type — buttons, cards or text — without moving the global palette (sc-1497).** A workspace theme may now carry `themeConfig.components` (`{ button, card, text }`), and the host resolves each scope onto the `styleSchema` fields the target widgets already read. **Nothing changes for a widget author:** you keep reading `props.style` / `useWidgetStyle()`, and an author's per-instance value still wins over a theme token — the theme is the app-wide default underneath it.
206
280
 
281
+ - **`useTheme()` gains `spacingScale`.** The app-wide spacing multiplier (default `1`) the workspace sets from Theme Settings. HOST-OWNED for layout: the host already scales every container's `padding` / `gap` / `margin` by it, so do not re-apply it to anything the host laid out. Read it only when your widget draws spacing of its own and you want that to breathe with the rest of the app — multiply your own paddings by it and leave radii and font sizes alone.
207
282
  - **`useTheme()` gains a `components` slice.** It is HOST-OWNED plumbing, not an author API: by the time your component renders, the host has already folded the matching tokens into `props.style`. Do not read `theme.components` and do not re-apply it — you would double-apply the theme and defeat the author's own styling.
208
283
  - **New host-only exports on `@colixsystems/widget-sdk/host`:** `normaliseThemeComponents(raw)` and `applyThemeComponentStyle(manifestId, theme, props)`. These are the platform-host surface (the web Player / Studio canvas and the exported Expo app), never the author API — one implementation, so the two hosts cannot diverge.
209
284
  - **`CONTRACT.themeComponents` / `CONTRACT.themeComponentShadows` / `CONTRACT.themeComponentGradient`** publish the vocabulary: each scope's tokens, their value types and ranges, and the widget → style-field bindings. `themeTokens.components` defaults to `{}`.
@@ -583,7 +658,8 @@ The "split-implementation + vetted package list" pivot.
583
658
 
584
659
  ### What's new in 0.11.0
585
660
 
586
- - **`useNavigation()` is wired.** Returns the host-provided navigation surface `{ goTo, goBack, push, replace, back, currentRoute }` for internal page-to-page navigation. Missing methods degrade to no-ops on the Studio canvas preview. Additive.
661
+ - **`useNavigation()` is wired.** Returns the host-provided navigation surface `{ goTo, goBack, push, replace, back, currentRoute, openLink }` for internal page-to-page navigation. Missing methods degrade to no-ops on the Studio canvas preview. Additive.
662
+ - **`openLink(link)` follows a link whose shape you do NOT control** — a value off a datastore row, a notification's `link`, anything author- or user-supplied. It resolves the string through the host's shared resolver and then acts: an in-app page routes internally, an off-app `http(s)` URL opens outside, and anything unsafe (`javascript:`, `data:`, scheme-relative `//host`, a scheme split by a control character) is refused. Returns `true` when it acted. **Prefer it over `Linking.openURL` for untrusted values** — `Linking.openURL` performs whatever it is handed, so passing it a stored string is how a `javascript:` URL reaches the browser. Reach for `goTo(pageId)` when you already know the page, and `Linking.openURL` only for a URL your own code constructed.
587
663
  - **`usePageContext()` reads the page's DECLARED parameters.** When a page declares parameters (Page Settings → Parameters), the host resolves them ONCE before any widget renders and fetches each `record` parameter's row for the whole page. `params` holds the values coerced to their declared types (a `number` parameter is a number, not the string `useRouteParams()` returns); `records` maps each `record` parameter to its already-loaded row — read it rather than issuing the same request from every widget. A required parameter that is absent, malformed, or whose record does not resolve never reaches the widget: the host renders one page-level state instead. Both bags are empty on a page that declares nothing, so fall back to `useRouteParams()` for a page you do not control. Additive (v0.77.0).
588
664
  - **`useRouteParams()` reads the nav params.** Returns `currentRoute.params` — the bag a `goTo(pageId, params)` carried to this page. The flat accessor for master→detail: navigate with `goTo(detailPageId, { recordId: row.id })`, then read `const { recordId } = useRouteParams()`. It is an OBJECT — read a param off it, never call it. Empty object when the page was opened without params. Additive (v0.61.0).
589
665
  - **`Linking` primitive re-exported.** `Linking.openURL(url)` opens an external URL with the OS handler — web (`react-native-web`) maps to `window.open` / `location.href`; native hands off to the system. Use this for external URLs; use `useNavigation().goTo(pageId)` for internal pages.
@@ -658,7 +734,7 @@ import { defineWidget, validateManifest, useDatastoreQuery, Text, View } from "@
658
734
 
659
735
  - `defineWidget({ manifest, component })` — validates the manifest and produces a widget module the host can register.
660
736
  - `validateManifest(m)` / `validatePropertySchema(s)` / `validateProps(schema, props)` — shape validation; no third-party deps.
661
- - `useDatastoreQuery`, `useDatastoreRecord`, `useDatastoreSchema`, `useDatastoreMutation`, `useDirectory`, `useUsers`, `useGroups`, `useRecordPermissions`, `useAsset`, `useWidgetEvent`, `useWidgetInput`, `usePayments`, `useSendNotification`, `useTheme`, `useI18n`, `useUser`, `useNavigation`, `useRouteParams`, `usePageContext`, `useChildRenderer`, `useClipboard`, `useToast` — hooks that read from the host-provided `WidgetContext` (or, for `useClipboard`, the platform clipboard API directly). `useDirectory(query?)` returns `{ users, loading, error, refetch }` (each user `{ id, name, role }`) and requires the `directory.read:users` scope. `useUsers(query?)` returns `{ users, loading, error, refetch, invite, deactivate, reactivate, remove }` and requires `users.read:*` (mutations also need `users.write:*`); rejections are a `DirectoryError`. `useGroups(query?)` returns `{ groups, loading, error, refetch, create, remove, addMember, removeMember }` and requires `groups.read:*` (mutations also need `groups.write:*`). `usePayments()` returns `{ requestPayment, getPayment }` and requires the `payments.charge:appUser` scope; `requestPayment(...)` rejects with a `PaymentError` carrying `code`, the server's user-safe `message`, and `retryable` (`false` = this charge cannot succeed until the workspace, manifest, or amount changes — show the message, not a retry). `useSendNotification()` returns `{ send, sending, error }` and requires the `notifications.send:appUser` scope; `send({ recipient_user_id, title, body, link?, payload? })` notifies one app user in the same workspace (cross-workspace `recipient_user_id` is rejected), must be called from an event handler rather than render, and rejects with a `NotificationError`. `useUser()` returns the active end-user identity `{ id, email, displayName, roles, groupIds }` (camelCase — the host-built context object, not a wire payload; `id` is `null` for anonymous / preview). `useNavigation()` returns `{ goTo, goBack, push, replace, back, currentRoute }` for internal page navigation for external URLs use the `Linking` primitive (`Linking.openURL(url)`). `useRouteParams()` returns the current route's params object (`currentRoute.params`) — the flat master→detail accessor; read a param off it (e.g. `recordId`), never call it. `useDatastoreRecord(tableId, recordId)` returns `{ data, loading, error, refetch }` for a single record (data is one row or null). `useDatastoreSchema(tableId)` returns `{ schema, loading, error, refetch }` where `schema` is `{ id, name, columns: [{ id, name, data_type, required, relation_type, target_table_id, is_identification }] }` (structure only, no row data; snake_case verbatim) — use it to resolve a stored `columnId` to its column type at runtime; requires the `datastore.read:<table>` scope. `useAsset(fileId)` returns `{ url, file, loading, error, refetch }` — the `url` is an absolute URL composed against the host's API base. `useChildRenderer()` returns `{ renderNode(node) }` — container widgets call it to render arbitrary child page-tree nodes (prefer the `WidgetTree` component for the common case). `useWidgetInput(inputName)` returns the latest payload a sibling widget published on the event the page author wired to this widget's declared `inputs` entry (`undefined` when unwired or not yet published).
737
+ - `useDatastoreQuery`, `useDatastoreRecord`, `useDatastoreSchema`, `useDatastoreMutation`, `useDirectory`, `useUsers`, `useGroups`, `useRecordPermissions`, `useAsset`, `useWidgetEvent`, `useWidgetInput`, `usePayments`, `useSendNotification`, `useTheme`, `useI18n`, `useUser`, `useNavigation`, `useRouteParams`, `usePageContext`, `useChildRenderer`, `useClipboard`, `useToast` — hooks that read from the host-provided `WidgetContext` (or, for `useClipboard`, the platform clipboard API directly). `useDirectory(query?)` returns `{ users, loading, error, refetch }` (each user `{ id, name, role }`) and requires the `directory.read:users` scope. `useUsers(query?)` returns `{ users, loading, error, refetch, invite, deactivate, reactivate, remove }` and requires `users.read:*` (mutations also need `users.write:*`); rejections are a `DirectoryError`. `useGroups(query?)` returns `{ groups, loading, error, refetch, create, remove, addMember, removeMember }` and requires `groups.read:*` (mutations also need `groups.write:*`). `usePayments()` returns `{ requestPayment, getPayment }` and requires the `payments.charge:appUser` scope; `requestPayment(...)` rejects with a `PaymentError` carrying `code`, the server's user-safe `message`, and `retryable` (`false` = this charge cannot succeed until the workspace, manifest, or amount changes — show the message, not a retry). `useSendNotification()` returns `{ send, sending, error }` and requires the `notifications.send:appUser` scope; `send({ recipient_user_id, title, body, link?, payload? })` notifies one app user in the same workspace (cross-workspace `recipient_user_id` is rejected), must be called from an event handler rather than render, and rejects with a `NotificationError`. `useUser()` returns the active end-user identity `{ id, email, displayName, roles, groupIds }` (camelCase — the host-built context object, not a wire payload; `id` is `null` for anonymous / preview). `useNavigation()` returns `{ goTo, goBack, push, replace, back, currentRoute, openLink }` for internal page navigation; `openLink(link)` follows an author- or data-supplied link of unknown shape through the host's shared resolver (in-app page → internal route, off-app http(s) → opened outside, unsafe → refused) and is the safe choice for any value your code did not construct, while `Linking.openURL(url)` is for an external URL you built yourself. `useRouteParams()` returns the current route's params object (`currentRoute.params`) — the flat master→detail accessor; read a param off it (e.g. `recordId`), never call it. `useDatastoreRecord(tableId, recordId)` returns `{ data, loading, error, refetch }` for a single record (data is one row or null). `useDatastoreSchema(tableId)` returns `{ schema, loading, error, refetch }` where `schema` is `{ id, name, columns: [{ id, name, data_type, required, relation_type, target_table_id, is_identification }] }` (structure only, no row data; snake_case verbatim) — use it to resolve a stored `columnId` to its column type at runtime; requires the `datastore.read:<table>` scope. `useAsset(fileId)` returns `{ url, file, loading, error, refetch }` — the `url` is an absolute URL composed against the host's API base. `useChildRenderer()` returns `{ renderNode(node) }` — container widgets call it to render arbitrary child page-tree nodes (prefer the `WidgetTree` component for the common case). `useWidgetInput(inputName)` returns the latest payload a sibling widget published on the event the page author wired to this widget's declared `inputs` entry (`undefined` when unwired or not yet published).
662
738
  - `WidgetTree({ node })` — component that renders an author-authored child node through the host's renderer; used by Tabs / Card / custom containers to host arbitrary child widgets.
663
739
  - `Text`, `View`, `Pressable`, `Image`, `ScrollView`, `TextInput`, `FlatList`, `SectionList`, `ActivityIndicator`, `Switch`, `StyleSheet`, `Linking`, `Icon`, `DateTimePicker` — re-exported from `react-native` (the RN primitives) or implemented in the SDK (`Icon` wraps `lucide-react-native`; `DateTimePicker` wraps `@react-native-community/datetimepicker` on native and renders `<input type="date|time|datetime-local">` directly on web because the RN library has no react-native-web mapping). The web build aliases `react-native` to `react-native-web` so the RN-re-exported primitives render in the browser without any per-platform code; the exported Expo app's Metro bundler resolves the real `react-native` library. `Linking` is a static API (`Linking.openURL(url)`) — use it for external URLs, and use `useNavigation().goTo(pageId)` for internal page navigation. See https://reactnative.dev/docs/ for per-component props.
664
740
  - `WidgetContextProvider` — React context provider that the host (Studio, Player, exported app) wraps widgets with.
@@ -680,7 +756,7 @@ A widget that works but looks unfinished is only half done. `useTheme()` is the
680
756
  - **Respond to touch.** Give every `Pressable` a pressed state via the function-style `style={({ pressed }) => [base, pressed && { opacity: 0.7 }]}`.
681
757
  - **Drag and drop — show what is being dragged.** A drag where the item stays put reads as broken. Three things change the moment a drag starts: the **drag proxy** (the item lifts and follows the finger — `...theme.elevation.lg`, `{ scale: 1.03 }`, `opacity: 0.9`; for a tall or full-width item drag a compact `primarySoft` pill with its icon + one line of label instead), the **source placeholder** (the vacated slot keeps its height as a quiet `colors.surfaceMuted` block so the list doesn't collapse), and the **drop target** (one slot at a time highlighted with `primarySoft` or a 2px `colors.primary` border). Always animate the release — settle into the new slot, or `Animated.spring(pan, { toValue: { x: 0, y: 0 }, useNativeDriver: false })` back to the origin on cancel. Build it with `Animated` + `PanResponder` from `react-native` (the only mechanism that behaves identically on both hosts) — never HTML5 drag events (`draggable` / `onDragStart` / `dataTransfer` are web-only, and `document` / `window` are banned) — and start the drag from a `GripVertical` grip handle whenever the row is also tappable or sits in a `ScrollView`.
682
758
  - **Use icons for clarity.** Pair a `lucide-react-native` icon with its label at a consistent size, coloured from the theme. The label never repeats the icon as a character — with a `Plus` icon the button says "Add item", never "+ Add item" (that renders a doubled plus).
683
- - **Use imagery deliberately.** Render pictures with the `Image` primitive (`source` takes a URL or `{ uri }`); resolve workspace assets via `useAsset()`. Give every image a sized, `radii`-clipped container so it never renders as a raw rectangle, and never hardcode a credentialed image URL — expose an `image`-type property instead.
759
+ - **Use imagery deliberately.** Render pictures with the `Image` primitive (`source` takes a URL or `{ uri }`); resolve workspace assets via `useAsset()`. Give every image a sized, `radii`-clipped container so it never renders as a raw rectangle, and never hardcode a credentialed image URL — expose an `image`-type property instead. The frame is your decision, never the picture's: size it for the role (a 40–56 square avatar, a 72–96 square row thumbnail, a `16 / 9` card cover, a 160–240 tall band) and let `resizeMode="cover"` crop the photo into it — photos arrive at every size and ratio, so one left to its own proportions breaks the layout. Keep `contain` for art whose whole subject must stay visible (a logo, a diagram), inside a fixed frame.
684
760
  - **Design the empty, loading, and error states.** A blank box on a fresh install reads as broken — show a short helper line when a list is empty, a calm loading line, and a single human sentence in `colors.danger` on error.
685
761
 
686
762
  **Honest ceilings:** the styling surface is React Native style objects, not full CSS. Gradients come from the `<Gradient>` primitive (not a CSS `linear-gradient` string), depth comes from `theme.elevation` (not arbitrary `box-shadow` stacks), and there are no custom CSS keyframe animations or `transition` strings, no `filter` / `backdrop-filter` / `clip-path` / `mask` / blend modes, and no opacity-faked tints (that's what `primarySoft` is for). Aim for clean, confident, professional polish within those bounds — lifted surfaces, generous corners, one accent moment.
package/dist/contract.cjs CHANGED
@@ -72,6 +72,9 @@ const DEFAULT_THEME_TOKENS = Object.freeze({
72
72
  }),
73
73
  elevation: ELEVATION,
74
74
  spacing: Object.freeze({ xs: 4, sm: 8, md: 16, lg: 24, xl: 32 }),
75
+ // REQ-THEME-LOOK: multiplies every layout spacing value at render. 1 is
76
+ // unchanged, so a theme that never sets it renders exactly as before.
77
+ spacingScale: 1,
75
78
  radii: Object.freeze({ sm: 4, md: 8, lg: 16, pill: 9999 }),
76
79
  typography: Object.freeze({
77
80
  fontFamily:
@@ -86,6 +89,12 @@ const DEFAULT_THEME_TOKENS = Object.freeze({
86
89
  // host so ONE channel carries them to the Player and the export. Empty by
87
90
  // default — an unconfigured theme resolves to no component overrides.
88
91
  components: Object.freeze({}),
92
+ // REQ-THEME-ELEMENT: the tenant's per-WIDGET-TYPE style values, keyed by
93
+ // manifest id. `components` above restyles a whole scope through a shared
94
+ // vocabulary, which only reaches a widget the vocabulary knows about; this
95
+ // reaches ANY widget by naming it, using that widget's OWN styleSchema field
96
+ // names. Empty by default.
97
+ widgetStyles: Object.freeze({}),
89
98
  });
90
99
 
91
100
  // REQ-THEME-15 (sc-1497) — per-component style tokens. The global palette is a
@@ -130,6 +139,32 @@ const THEME_COMPONENT_GRADIENT = Object.freeze({
130
139
  defaultAngle: 180,
131
140
  });
132
141
 
142
+ // REQ-THEME-LOOK: the app-wide SPACING MULTIPLIER. Layout spacing lives on the
143
+ // NODES -- a container states its own `padding` / `gap` / `margin` -- so a plain
144
+ // theme key could never make an existing app breathe: every node already
145
+ // carried a value and there was no default left to change. This scales those
146
+ // node values at RENDER time instead, on both hosts, which is why it moves a
147
+ // page that was authored long ago. SPACING only -- never radii, font sizes or
148
+ // minHeight -- so a look keeps its shape while its air moves, and the author’s
149
+ // relative proportions survive: a tight table stays tighter than the card
150
+ // beside it.
151
+ // REQ-THEME-ELEMENT: bounds on the per-widget-type style map. `theme_config` is
152
+ // an unbounded JSON bag that an UNAUTHENTICATED GET /tenant/config returns on
153
+ // every cold Player start and that the compiler bakes verbatim into the native
154
+ // export -- so a map that grows with the widget catalog needs a stated ceiling.
155
+ // Declared here so the coercer, the Studio control and the planner prompt agree.
156
+ const THEME_WIDGET_STYLES = Object.freeze({
157
+ // One entry per widget TYPE, not per instance, so this is generous.
158
+ maxWidgets: 200,
159
+ // Matches the styleSchema field cap the widget agent is held to.
160
+ maxFieldsPerWidget: 12,
161
+ });
162
+ const THEME_SPACING_SCALE = Object.freeze({
163
+ min: 0.5,
164
+ max: 2,
165
+ default: 1,
166
+ });
167
+
133
168
  // The card-surface field names shared by every widget that paints its own card
134
169
  // (frontend/src/components/widgets/_shared/cardStyle.js CARD_STYLE_SCHEMA).
135
170
  const CARD_SURFACE_FIELDS = Object.freeze({
@@ -159,6 +194,23 @@ const FORM_SUBMIT_FIELDS = Object.freeze({
159
194
  gradient: "submitGradient",
160
195
  });
161
196
 
197
+ // REQ-THEME-WIDGET: the card fields whose NAMES are unambiguous, so they bind to
198
+ // ANY widget that reads them -- including a Mason-generated one, whose id can
199
+ // never appear in a hand-maintained allowlist. That allowlist is why "make the
200
+ // cards darker" reached the nine built-ins and nothing else.
201
+ //
202
+ // `shadow` is deliberately ABSENT: its name is bare and shared with the button
203
+ // scope, so binding it by name would cross the scopes. The bare names stay on
204
+ // the allowlist for exactly that reason -- `appstudio.image` also reads a
205
+ // `background` field, and the button scope must not leak into it.
206
+ const CARD_UNIVERSAL_FIELDS = Object.freeze({
207
+ background: "cardBackground",
208
+ borderColor: "cardBorderColor",
209
+ radius: "cardRadius",
210
+ padding: "cardPadding",
211
+ gradient: "cardGradient",
212
+ });
213
+
162
214
  const THEME_COMPONENTS = Object.freeze({
163
215
  button: Object.freeze({
164
216
  label: "Buttons",
@@ -187,6 +239,7 @@ const THEME_COMPONENTS = Object.freeze({
187
239
  }),
188
240
  card: Object.freeze({
189
241
  label: "Cards",
242
+ universalFields: CARD_UNIVERSAL_FIELDS,
190
243
  tokens: Object.freeze({
191
244
  background: Object.freeze({ type: "color", uiDefault: "colors.surface" }),
192
245
  borderColor: Object.freeze({ type: "color", uiDefault: "colors.border" }),
@@ -243,8 +296,18 @@ const HOOKS = [
243
296
  signature: "useTheme()",
244
297
  returnShape: {
245
298
  colors:
246
- "{ primary, onPrimary, secondary, onSecondary, surface, onSurface, surfaceMuted, onSurfaceMuted, border, danger, success, warning, info }",
299
+ "{ primary, onPrimary, secondary, onSecondary, surface, onSurface, surfaceMuted, onSurfaceMuted, border, danger, success, warning, info }" +
300
+ "REQ-THEME-SURFACE: the surface group (surface / surfaceMuted / onSurface / " +
301
+ "onSurfaceMuted / border) describes the surface your widget SITS ON, not the " +
302
+ "page: a container painting its own background re-derives them for its " +
303
+ "subtree. Read them and your text is readable wherever the widget lands; " +
304
+ "there is nothing to opt into.",
247
305
  spacing: "{ xs, sm, md, lg, xl }",
306
+ spacingScale:
307
+ "number — the app-wide spacing multiplier (REQ-THEME-LOOK, default 1). " +
308
+ "HOST-OWNED: the host already scales layout spacing by it. Read it only " +
309
+ "if your widget draws its own internal spacing and wants to breathe with " +
310
+ "the rest of the app.",
248
311
  radii: "{ sm, md, lg, pill }",
249
312
  typography: "{ fontFamily, sizes: { xs, sm, md, lg, xl, xxl } }",
250
313
  components:
@@ -436,6 +499,7 @@ const HOOKS = [
436
499
  signature: "useNavigation()",
437
500
  returnShape: {
438
501
  goTo: "(pageId: string, params?: object) => void",
502
+ openLink: "(link: string) => boolean",
439
503
  goBack: "() => void",
440
504
  push: "(pageId: string, params?: object) => void",
441
505
  replace: "(pageId: string, params?: object) => void",
@@ -650,7 +714,7 @@ const HOOKS = [
650
714
  signedAt: "string | null",
651
715
  verdict: "{ valid, checks, content_status, ... } | null",
652
716
  loading: "boolean",
653
- error: "PermissionError | null",
717
+ error: "PermissionError | null // { code, message, retryable }",
654
718
  initiate: "() => Promise<{ signature_id, qr, auto_start_token, status }>",
655
719
  refresh: "() => Promise<void>",
656
720
  cancel: "() => Promise<void>",
@@ -760,9 +824,12 @@ const HOOKS = [
760
824
  name: "useDatastoreMutation",
761
825
  signature: "useDatastoreMutation(tableId)",
762
826
  returnShape: {
763
- create: "(record) => Promise<Record> // rejects with DatastoreError",
764
- update: "(id, partial) => Promise<Record> // rejects with DatastoreError",
765
- delete: "(id) => Promise<void> // rejects with DatastoreError",
827
+ create:
828
+ "(record) => Promise<Record> // rejects with DatastoreError { code, message, retryable } — render the message when retryable is false, never 'try again'",
829
+ update:
830
+ "(id, partial) => Promise<Record> // rejects with DatastoreError { code, message, retryable } — render the message when retryable is false, never 'try again'",
831
+ delete:
832
+ "(id) => Promise<void> // rejects with DatastoreError { code, message, retryable } — render the message when retryable is false, never 'try again'",
766
833
  },
767
834
  requiredContextSlice: ["datastore.records"],
768
835
  scopes: ["datastore.write:*"],
@@ -878,7 +945,7 @@ const HOOKS = [
878
945
  returnShape: {
879
946
  users: "Array<{ id, name, email?, role, is_active }> // snake_case rows; unwrapped from { data, meta }",
880
947
  loading: "boolean",
881
- error: "DirectoryError | null",
948
+ error: "DirectoryError | null // { code, message, retryable }",
882
949
  refetch: "() => Promise<void>",
883
950
  invite:
884
951
  "({ email, name, group_ids? }) => Promise<Invite> // rejects with DirectoryError",
@@ -907,7 +974,7 @@ const HOOKS = [
907
974
  returnShape: {
908
975
  groups: "Array<{ id, name, member_count }> // snake_case rows; unwrapped from { data, meta }",
909
976
  loading: "boolean",
910
- error: "DirectoryError | null",
977
+ error: "DirectoryError | null // { code, message, retryable }",
911
978
  refetch: "() => Promise<void>",
912
979
  create:
913
980
  "({ name }) => Promise<Group> // rejects with DirectoryError",
@@ -946,7 +1013,7 @@ const HOOKS = [
946
1013
  message: "string | null",
947
1014
  loading: "boolean",
948
1015
  statusLoading: "boolean",
949
- error: "DirectoryError | null",
1016
+ error: "DirectoryError | null // { code, message, retryable }",
950
1017
  startLink: "() => Promise<{ order_ref, qr, auto_start_token, status }>",
951
1018
  refresh: "() => Promise<void>",
952
1019
  cancel: "() => Promise<void>",
@@ -1028,7 +1095,7 @@ const HOOKS = [
1028
1095
  permissions:
1029
1096
  "Array<{ id, user_id, group_id, can_read, can_write, can_delete, can_grant }> // snake_case rows; unwrapped from { data, meta }",
1030
1097
  loading: "boolean",
1031
- error: "PermissionError | null",
1098
+ error: "PermissionError | null // { code, message, retryable }",
1032
1099
  grant:
1033
1100
  "({ user_id?, group_id?, can_read?, can_write?, can_delete?, can_grant? }) => Promise<RecordPermission> // rejects with PermissionError",
1034
1101
  revoke:
@@ -1091,10 +1158,12 @@ const HOOKS = [
1091
1158
  description:
1092
1159
  "Surfaces a short auto-dismissing notification. Returns { showToast }. " +
1093
1160
  "showToast({ kind: 'success' | 'error' | 'info' | 'warning', message }) " +
1094
- "asks the host to render a workspace-themed toast. If the host hasn't " +
1095
- "wired a renderer, the web variant dispatches an 'appstudio:widget-toast' " +
1096
- "CustomEvent on window; native logs to the console. The widget never " +
1097
- "owns the toast UI that's the host's responsibility.",
1161
+ "renders a workspace-themed toast. Both shipping hosts paint it — the " +
1162
+ "web Player and the exported Expo app so a confirmation you raise IS " +
1163
+ "seen by the user; use it to confirm every write. The widget never owns " +
1164
+ "the toast UI, so never build your own banner or call Alert.alert for a " +
1165
+ "routine save. An authoring preview (the Studio canvas) wires no " +
1166
+ "renderer, and there the call is simply a no-op.",
1098
1167
  returnShape: {
1099
1168
  showToast: "({ kind, message }) => void",
1100
1169
  },
@@ -1658,9 +1727,10 @@ const WIDGET_CONTEXT_SHAPE = {
1658
1727
  description:
1659
1728
  "Optional host toast slot. { showToast({ kind, message }): void }. " +
1660
1729
  "The host populates this to render workspace-themed notifications " +
1661
- "from any widget that calls useToast(). When omitted the SDK falls " +
1662
- "back to dispatching an 'appstudio:widget-toast' CustomEvent on web " +
1663
- "and console.log on native.",
1730
+ "from any widget that calls useToast(). Both rendering hosts wire it " +
1731
+ "(the web Player and the compiler's native WidgetHost); authoring " +
1732
+ "surfaces omit it, and the SDK then falls back to dispatching an " +
1733
+ "'appstudio:widget-toast' CustomEvent on web and console.log on native.",
1664
1734
  required: false,
1665
1735
  fields: { showToast: "function" },
1666
1736
  },
@@ -2635,6 +2705,28 @@ const CONTRACT = deepFreeze({
2635
2705
  // public endpoint instead, which skips the cache, the metering and the
2636
2706
  // workspace's provider. Publishing the host list here keeps the linter,
2637
2707
  // the Developer guide and the agent prompt reading one source.
2708
+ // 1.52.0: additive (REQ-THEME-LOOK) -- `themeTokens.spacingScale` (default 1)
2709
+ // and `themeSpacingScale`, its clamp bounds. A spacing control in the
2710
+ // Studio could reach nothing that mattered, because layout spacing is
2711
+ // authored ONTO each node (`padding` / `gap` / `margin`) rather than
2712
+ // inherited from the theme -- so no theme key could make a built app
2713
+ // breathe. Both hosts now multiply a node’s resolved spacing by this scale
2714
+ // at render. SPACING only: radii, font sizes and minHeight are untouched,
2715
+ // so a look keeps its shape and the author’s proportions hold. Additive:
2716
+ // no export changed signature and a theme without the key resolves to 1,
2717
+ // rendering identically to before.
2718
+ // 1.53.0: fix (REQ-THEME-17) -- `isHexColor` accepts the 8-digit
2719
+ // `#RRGGBBAA` form. The Studio has put an opacity row on every colour
2720
+ // field since sc-4158, so a brand colour or a page background routinely
2721
+ // arrives with alpha -- and this predicate rejecting it made
2722
+ // `themeConfigToTokens` DROP the key, so a translucent dark background
2723
+ // stopped reaching deriveSurfaceTokens and every panel fell back to white.
2724
+ // A second, alpha-aware predicate already existed beside it for gradients,
2725
+ // which is why the asymmetry kept being rediscovered surface by surface;
2726
+ // there is now one. `hexChannels` ignores the alpha pair, so contrast and
2727
+ // the derived tints still reason about the opaque colour while the value
2728
+ // keeps its transparency. Widening only: every input accepted before is
2729
+ // accepted now, and unchanged.
2638
2730
  // 1.54.0: additive (sc-4399, epic 4395) — `useContainerWidth()` +
2639
2731
  // `isNarrowWidth(width)` / `NARROW_WIDTH_PX`. Built-in widgets laid
2640
2732
  // themselves out at a fixed size — UserManagement's rows alone carried
@@ -2666,7 +2758,36 @@ const CONTRACT = deepFreeze({
2666
2758
  // Developer guide have always said, so a widget written against the
2667
2759
  // declared shape destructured a function and threw on first interaction.
2668
2760
  // Declared as a bare callable now; no runtime behaviour changed.
2669
- version: "1.60.1",
2761
+ // 1.61.0: additive (REQ-THEME-SURFACE / -CARD / -WIDGET / -ELEMENT) -- the
2762
+ // theme reaches the elements an app is built from. Four things it could
2763
+ // not touch before, and one mechanism each:
2764
+ // * `deriveSurfaceTokens` (host export) -- the surface/text/border set is
2765
+ // derived per PAINTED SURFACE, not once per page, so an UNSET text
2766
+ // colour is readable inside a coloured container. It was a hand-mirrored
2767
+ // copy per host; now one symmetric implementation (a light fill resolves
2768
+ // to the light tokens instead of returning null).
2769
+ // * `themeComponents.card.universalFields` -- the card scope's unambiguous
2770
+ // field NAMES bind to any widget that declares them, so a widget whose id
2771
+ // can never appear in a hand-maintained allowlist still follows "Cards".
2772
+ // The bare names (`background`, `textColor`, `color`, `fontSize`,
2773
+ // `shadow`) keep the allowlist: they mean different things per scope.
2774
+ // `applyThemeComponentStyle` takes an optional 4th `styleSchema` so the
2775
+ // name-bound fields land only on a widget that reads them.
2776
+ // * `themeTokens.widgetStyles` + `themeWidgetStyles` bounds +
2777
+ // `normaliseWidgetStyles` (host export) -- app-wide values keyed by
2778
+ // widget MANIFEST ID and then by that widget's OWN styleSchema field
2779
+ // names, so `panelFill` is as reachable as `cardBackground`: no shared
2780
+ // vocabulary, no allowlist, no naming requirement. Validated
2781
+ // structurally, because the key space is a workspace's widget catalog
2782
+ // rather than this contract, and bounded because `theme_config` is
2783
+ // unbounded, read unauthenticated on every cold Player start, and baked
2784
+ // verbatim into the native export.
2785
+ // Precedence: contract default -> palette -> `components.<scope>` ->
2786
+ // `widgetStyles[manifestId]` -> the author's per-instance `props.style`.
2787
+ // Naming one widget is strictly more specific than restyling a scope, and
2788
+ // the Properties Panel stays the final word. Additive throughout: a theme
2789
+ // that sets none of it resolves exactly as before.
2790
+ version: "1.62.0",
2670
2791
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
2671
2792
  hooks: HOOKS,
2672
2793
  primitives: PRIMITIVES,
@@ -2681,6 +2802,8 @@ const CONTRACT = deepFreeze({
2681
2802
  themeComponentShadows: THEME_COMPONENT_SHADOWS,
2682
2803
  themeComponentTextTransforms: THEME_COMPONENT_TEXT_TRANSFORMS,
2683
2804
  themeComponentGradient: THEME_COMPONENT_GRADIENT,
2805
+ themeSpacingScale: THEME_SPACING_SCALE,
2806
+ themeWidgetStyles: THEME_WIDGET_STYLES,
2684
2807
  widgetContextShape: WIDGET_CONTEXT_SHAPE,
2685
2808
  bundleExportContract: BUNDLE_EXPORT_CONTRACT,
2686
2809
  bannedApis: BANNED_APIS,
@@ -2720,12 +2843,31 @@ function requiredContextKeys() {
2720
2843
  // one source removes that drift (CLAUDE.md §3).
2721
2844
  // ---------------------------------------------------------------------------
2722
2845
 
2723
- const HEX_RE = /^#[0-9a-f]{3}([0-9a-f]{3})?$/i;
2846
+ // REQ-THEME-17 / sc-4158 — 3, 6 or 8 digits. The 8-digit form carries alpha,
2847
+ // and this predicate accepting it is load-bearing: the Studio puts an opacity
2848
+ // row on every colour field, so `primaryColor` and `backgroundColor` routinely
2849
+ // arrive as `#RRGGBBAA`. While this rejected them, `themeConfigToTokens` DROPPED
2850
+ // the key outright — a translucent page background stopped reaching
2851
+ // deriveSurfaceTokens and every panel in the app fell back to white.
2852
+ //
2853
+ // There used to be a second, alpha-aware predicate beside this one for
2854
+ // gradients, which is how the asymmetry kept being rediscovered: each new
2855
+ // alpha-carrying surface met the strict one first. There is now only this.
2856
+ const HEX_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
2724
2857
 
2725
2858
  function isHexColor(value) {
2726
2859
  return typeof value === "string" && HEX_RE.test(value);
2727
2860
  }
2728
2861
 
2862
+ /**
2863
+ * The R/G/B bytes, with any alpha pair IGNORED.
2864
+ *
2865
+ * Deliberate: everything downstream of this is luminance maths — contrast,
2866
+ * readable text, derived tints — and none of it can composite without knowing
2867
+ * the backdrop, which a token table does not have. Alpha survives in the VALUE
2868
+ * (the host hands `#RRGGBBAA` straight to the renderer); it just takes no part
2869
+ * in deciding whether a colour reads as light or dark.
2870
+ */
2729
2871
  function hexChannels(hex) {
2730
2872
  let h = hex.slice(1);
2731
2873
  if (h.length === 3) {
@@ -2810,6 +2952,54 @@ function deriveAccentTints(primary, surface, onSurface) {
2810
2952
  };
2811
2953
  }
2812
2954
 
2955
+ // REQ-THEME-SURFACE: how far a derived surface travels toward white, and the
2956
+ // light-on-dark text pair a dark surface carries.
2957
+ const SURFACE_LIFT = Object.freeze({ surface: 0.1, surfaceMuted: 0.05, border: 0.18 });
2958
+ const DARK_SURFACE_TEXT = Object.freeze({
2959
+ onSurface: "#f8fafc",
2960
+ onSurfaceMuted: "#cbd5e1",
2961
+ });
2962
+
2963
+ /**
2964
+ * REQ-THEME-DARK: the coherent surface / text / border set one background wants.
2965
+ * A dark background lifts its panels toward white and goes light-on-dark; a
2966
+ * light one resolves to the contract's own light tokens.
2967
+ *
2968
+ * REQ-THEME-SURFACE: applied to the PAGE background and — because every surface
2969
+ * a page is built from may paint its own fill — to a CONTAINER background too.
2970
+ * That is what makes an UNSET text colour readable inside a dark card on a light
2971
+ * page, which is in turn what lets a built app follow its theme instead of
2972
+ * carrying a baked-in hex for every heading.
2973
+ *
2974
+ * Returns all five keys together, never a subset: layering a dark card's text
2975
+ * colour over a light ancestor's surface is exactly how light-on-light happens.
2976
+ * `null` only when the colour is unusable, letting the caller keep what it had.
2977
+ */
2978
+ function deriveSurfaceTokens(backgroundColor) {
2979
+ if (!isHexColor(backgroundColor)) return null;
2980
+ // "Dark" = the background wants light text (same luminance test as the
2981
+ // on-color contrast picker).
2982
+ const wantsLightText =
2983
+ readableTextColor(backgroundColor, "__dark__", "__light__") === "__light__";
2984
+ if (!wantsLightText) {
2985
+ const base = DEFAULT_THEME_TOKENS.colors;
2986
+ return {
2987
+ surface: base.surface,
2988
+ surfaceMuted: base.surfaceMuted,
2989
+ onSurface: base.onSurface,
2990
+ onSurfaceMuted: base.onSurfaceMuted,
2991
+ border: base.border,
2992
+ };
2993
+ }
2994
+ return {
2995
+ surface: mixHex(backgroundColor, "#ffffff", SURFACE_LIFT.surface),
2996
+ surfaceMuted: mixHex(backgroundColor, "#ffffff", SURFACE_LIFT.surfaceMuted),
2997
+ onSurface: DARK_SURFACE_TEXT.onSurface,
2998
+ onSurfaceMuted: DARK_SURFACE_TEXT.onSurfaceMuted,
2999
+ border: mixHex(backgroundColor, "#ffffff", SURFACE_LIFT.border),
3000
+ };
3001
+ }
3002
+
2813
3003
  /**
2814
3004
  * Map a CSS-style gradient angle (0 = to top, 90 = to right) to the
2815
3005
  * `{ start, end }` unit vectors `expo-linear-gradient` expects (origin at
@@ -2828,9 +3018,10 @@ function gradientAngleToVector(angle) {
2828
3018
  };
2829
3019
  }
2830
3020
 
2831
- // Alpha is allowed here (unlike HEX_RE) because the Mason build runner already
2832
- // persists 8-digit component colours; the host must not drop what it accepted.
2833
- const GRADIENT_HEX_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
3021
+ // Gradients used to need their own alpha-aware predicate because HEX_RE was not.
3022
+ // HEX_RE is now, so this is the same check by another name kept only as a
3023
+ // local alias so the call sites below read as before.
3024
+ const GRADIENT_HEX_RE = HEX_RE;
2834
3025
 
2835
3026
  /**
2836
3027
  * sc-3727 — normalise a component `gradient` to `{ from, to, angle }`, or `null`.
@@ -2855,8 +3046,33 @@ function normaliseComponentGradient(raw) {
2855
3046
  return { from, to, angle: ((deg % 360) + 360) % 360 };
2856
3047
  }
2857
3048
 
3049
+ // REQ-THEME-LOOK: coerce a theme's spacing scale into the usable band. Shared
3050
+ // because BOTH hosts multiply node spacing by it and a disagreement here would
3051
+ // re-space an exported page against the Player. Anything absent, non-finite or
3052
+ // out of band resolves to 1 (unchanged) rather than throwing -- `theme_config`
3053
+ // is a JSON bag a workspace admin can PUT verbatim.
3054
+ function clampSpacingScale(value) {
3055
+ // Absent means UNSET, not "as tight as possible" — Number(null) and Number("")
3056
+ // are both 0, which would otherwise clamp an untouched theme to the minimum.
3057
+ if (value === null || value === undefined || value === "") {
3058
+ return THEME_SPACING_SCALE.default;
3059
+ }
3060
+ const n = typeof value === "number" ? value : Number(value);
3061
+ if (!Number.isFinite(n)) return THEME_SPACING_SCALE.default;
3062
+ return Math.min(Math.max(n, THEME_SPACING_SCALE.min), THEME_SPACING_SCALE.max);
3063
+ }
3064
+
3065
+ // REQ-THEME-LOOK: apply that scale to ONE spacing value. Rounded to whole
3066
+ // pixels so a scaled gap stays on the same pixel grid as an unscaled one.
3067
+ function scaleSpacing(value, scale) {
3068
+ if (typeof value !== "number" || !Number.isFinite(value)) return value;
3069
+ return Math.round(value * clampSpacingScale(scale));
3070
+ }
3071
+
2858
3072
  module.exports = {
2859
3073
  CONTRACT,
3074
+ clampSpacingScale,
3075
+ scaleSpacing,
2860
3076
  isHookAllowed,
2861
3077
  requiredContextKeys,
2862
3078
  isHexColor,
@@ -2864,6 +3080,7 @@ module.exports = {
2864
3080
  contrastRatio,
2865
3081
  readableTextColor,
2866
3082
  deriveAccentTints,
3083
+ deriveSurfaceTokens,
2867
3084
  gradientAngleToVector,
2868
3085
  normaliseComponentGradient,
2869
3086
  formatMoneyIn,