@colixsystems/widget-sdk 0.337.1 → 0.338.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
@@ -60,7 +60,7 @@ The data layer lives in **four separate domain-client packages**, each instantia
60
60
  | **DATASTORE** | `useInterpretDraft(tableId)` | `{ interpret, interpreting, error, result, available }` | `interpret(tableId, body)` — `datastore.read:<table>`. Turns ONE sentence a user typed ("walk at 11 am tomorrow") into DRAFT column values so a form can prefill itself. IMPERATIVE: call `interpret(text, { fields?, timeZone? })` from an event handler, never on mount. It DRAFTS and writes nothing — show the values for review, then submit through `useDatastoreMutation().create`. Resolves to `{ values, unresolved }`; `values` is keyed by column NAME (the shape `create()` takes) and `unresolved` names the fields the sentence did not state. Only text / number / boolean / date / datetime / array columns are drafted — `FILE`, `RELATION`, `USER` and `USER_GROUP` carry ids and are never guessed. Fails closed to an empty draft. **Every call spends the workspace's AI credits** and is rate-limited per actor, so call it once per user action (never on mount or in a render loop); once the workspace runs out the call is refused with a generic 429 — an app user is deliberately **not** told the workspace's billing state, since they have never heard of an AI credit and cannot buy one. Never surface a raw error to the person filling the form: say drafting is unavailable and keep every field editable by hand. `available` is false where the host brokers no interpreter. |
61
61
  | **AGENTS** | `useAgent(agentRef, { files }?)` | `{ send, cancel, reset, messages, sending, resuming, error, available, acceptsFiles, fileLimits }` | `ctx.agents` — `ai.invoke:*`. Hold a conversation with one of the WORKSPACE's own AI agents (an author-written name + system prompt). Sending is IMPERATIVE: call `send(text)` from an event handler, never on mount — the first send opens the conversation, so a widget nobody types into costs nothing. On mount the hook DOES reopen the caller's most recent thread with this agent, so a refresh or a navigation keeps the conversation instead of starting a blank one; that resume only READS and spends no credit. `resuming` is true while it runs — render a loading state, not an empty thread. `messages` is the running transcript, oldest first. You **cannot** set or read the system prompt, replay an edited transcript, or pick a model: the server assembles every turn from the stored prompt plus the stored history, and `content` is the only thing that reaches the wire. `reset()` drops the thread (a "new chat" affordance), and the new thread is the one a later mount resumes. **Every send spends the workspace's AI credits** and is rate-limited per caller AND per workspace. Rejects with `AgentError`; branch on `.code` — `AI_QUOTA_EXCEEDED` (429) is the workspace's credit ceiling and will NOT clear on a retry, unlike `RATE_LIMITED`, so never offer "try again" for it, and `AGENT_DISABLED` (409) means the author turned it off, so hide the affordance. Never surface a raw error or the workspace's billing state to an app user. `available` is false when no agent is bound or the host brokers none — render a visible unbound state, never a blank box. An assistant message that used a tool also carries **`activity`** — what the agent DID with the user's data: the table it read (with the `search` text and `filters` it read with), or the table and columns it CHANGED (never the values, and never a row the permissions refused). **Render a write.** A reply saying "done!" is not evidence a row was written, and if the agent got it wrong the user has no other way to notice. A talk-only turn omits the key entirely. **Files:** with `{ files: true }` the hook asks once (no credit) whether the agent reads files — `acceptsFiles`, `fileLimits` — and `send(text, { files })` sends Filestore images or PDFs with the turn. |
62
62
  | **ACTIONS** | `useAction(actionRef)` | `{ available, run, enqueue, running, result, error }` | `ctx.actions` — `actions.run:*`. Run one of the workspace's Actions from an event handler (never on mount) and read the value it passed to `respond()`, or `enqueue` it to run later with its normal limits and no answer. The Action needs the app trigger. `available` is false when nothing is bound or the host brokers no client. Errors are `ActionError` with a stable `code`. |
63
- | **DATASTORE** | `useDatastoreMutation(table)` | `{ create, update, delete }` | `records(table).{ create, update (PATCH), delete }` — `datastore.write:*`. A successful write re-reads every query, record, figure and aggregate on that table in every widget on the screen (a run of writes at most once a second, always once more after the last), so never refetch after it, and never write from an effect that re-runs on the data it reads unless a ref or Set marks what it already wrote. **To CLEAR a cell, pass it empty** — `update(id, { when: null })` (also `""` or `[]`) empties that cell and it reads back as `null` (`[]` on an array column). There is no separate clear call, so never write a sentinel such as `0` or a placeholder date to mean "no value". `false` and `0` are values, not clears, and a REQUIRED column cannot be cleared. |
63
+ | **DATASTORE** | `useDatastoreMutation(table)` | `{ create, update, delete }` | `records(table).{ create, update (PATCH), delete }` — `datastore.write:*`. A successful write re-reads every query, record, figure and aggregate on that table in every widget on the screen (a run of writes at most once a second, always once more after the last), so never refetch after it, and never write from an effect that re-runs on the data it reads unless a ref or Set marks what it already wrote. **To CLEAR a cell, pass it empty** — `update(id, { when: null })` (also `""` or `[]`) empties that cell and it reads back as `null` (`[]` on an array column). There is no separate clear call, so never write a sentinel such as `0` or a placeholder date to mean "no value". `false` and `0` are values, not clears, and a REQUIRED column cannot be cleared. The result has only create, update and delete; the checker refuses a call to any other key (`datastore-method-unknown`). |
64
64
  | **DATASTORE** | `useDatastoreSubscription(table, handlers, options)` (optional: options) | `{ status }` — `"connecting" \| "live" \| "reconnecting" \| "fallback"` | `records(table).subscribe` — `datastore.read:<table>`. To keep a list, record or figure current, pass `live: true` to its read hook instead (*Live lists*); this hook is for acting on each change. Live `onCreated` / `onUpdated` / `onDeleted` off the realtime socket; never throws, resolving to `{ status: "fallback" }` so the widget polls instead. A whole-table subscribe is gated on read-EVERY-row, because one envelope reaches every subscriber of the table — so for a table governed by per-record grants pass `options.scope`: `{ kind: "record", record_id }` for one row, or `{ kind: "parent", relation_column, record_id }` for the rows whose RELATION column points at that parent (the column must carry `inheritAcl`, else the subscribe reports `"fallback"`). For a live list of the signed-in user's own rows pass `{ kind: "granted" }`: every row they read through a grant to them or one of their groups, plus `onAccessGained(record)` / `onAccessLost({ id })` as rows enter and leave that set. Re-subscribes on the scope's VALUES, so a fresh object literal each render is fine. |
65
65
  | **DATASTORE** | `useTyping(tableId, recordId)` | `{ typingUserIds, setTyping, status }` — status `"connecting" \| "live" \| "unavailable"` | `records(table).typing` — `datastore.read:<table>`. Who else is typing in one record, over the same socket as `useDatastoreSubscription`. Call `setTyping(true)` on every keystroke (throttled to one signal per 3 s; `false` is sent after 5 s idle) and `setTyping(false)` on send, clear or blur. `typingUserIds` lists the OTHER users' ids; each drops out 6 s after their last signal. Needs a signed-in user who can read the record. Never throws: an anonymous visitor, a refused subscription or a host whose client lacks `typing` reads `{ typingUserIds: [], status: "unavailable" }`. Re-subscribes when either id changes. |
66
66
  | **DATASTORE** | `useRecordPermissions(tableId, recordId)` | `{ permissions, loading, error, grant, revoke, update, refetch }` | `records(table).permissions(record).{ list, grant, update, revoke }` — `acl.write:records` (+ `can_grant` on the record) |
@@ -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.337.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.338.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.338.0 (contract 1.276.0)
97
+
98
+ **The linter refuses a call to a method `useDatastoreMutation` does not return.** The hook returns `create`, `update` and `delete`, nothing else, so a widget calling `upsert` or `remove` on it published cleanly and threw only when the user pressed the button. The publish-blocking `datastore-method-unknown` finding names the key and the ones that exist: `useDatastoreMutation(...).upsert does not exist; available: create, update, delete`. It judges a key only where the widget just calls it, on a named result (`m.upsert(row)`) or through a destructured name (`const { upsert } = useDatastoreMutation(tableId)`). A key the widget also reads, feature-tests (`typeof m.upsert === "function"`, `"upsert" in m`) or assigns first, a computed key, a default value in the destructure, an optional call (`m.upsert?.(row)`), a method definition or JSX text that shares the name, and a result handed to other code (an argument, an array or object it is listed in) give no finding. A result listed in a hook's dependency list (`useCallback(…, [m])`) is still judged.
99
+
100
+ ### What's new in 0.337.2 (contract 1.275.0)
101
+
102
+ **A `mode="datetime"` `<DateTimePicker>` works on Android.** Android has no combined date-and-time dialog, so the field opens the date dialog and then the time dialog, and emits once both are answered. Before, it showed only the date dialog, kept the time of day it opened with, and the widget crashed as the dialog closed (`Cannot read property 'dismiss' of undefined`). Cancelling either dialog changes nothing. iOS keeps its single date-and-time picker. Fix-only: no prop or export changed.
95
103
 
96
104
  ### What's new in 0.337.1 (contract 1.275.0)
97
105
 
package/dist/contract.cjs CHANGED
@@ -2425,7 +2425,9 @@ const HOOKS = [
2425
2425
  "must name the table the same way (its id, as a tableRef property binds it). " +
2426
2426
  "A run of writes re-reads each reader at most once a second, always once " +
2427
2427
  "more after the last. Never write from a useEffect that re-runs on the data " +
2428
- "it reads unless a ref or Set marks each row as already written: it loops.",
2428
+ "it reads unless a ref or Set marks each row as already written: it loops. " +
2429
+ "The result has only create, update and delete; the checker refuses a " +
2430
+ "call to any other key (datastore-method-unknown).",
2429
2431
  returnShape: {
2430
2432
  create:
2431
2433
  "(record) => Promise<Record> // rejects with DatastoreError { code, message, retryable } — render the message when retryable is false, never 'try again'",
@@ -7112,7 +7114,10 @@ const CONTRACT = deepFreeze({
7112
7114
  // in to a server that asks for it, brokered by the host, and
7113
7115
  // `connections.signInResult` reports a web sign-in on the page's return.
7114
7116
  // Items gain status 'needs_sign_in' and auth_kind 'oauth'.
7115
- version: "1.275.0",
7117
+ // 1.276.0: stricter lint (sc-17764) — a widget that calls a key
7118
+ // useDatastoreMutation() does not return is the publish-blocking
7119
+ // `datastore-method-unknown` finding.
7120
+ version: "1.276.0",
7116
7121
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7117
7122
  hooks: HOOKS,
7118
7123
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -2420,7 +2420,9 @@ const HOOKS = [
2420
2420
  "must name the table the same way (its id, as a tableRef property binds it). " +
2421
2421
  "A run of writes re-reads each reader at most once a second, always once " +
2422
2422
  "more after the last. Never write from a useEffect that re-runs on the data " +
2423
- "it reads unless a ref or Set marks each row as already written: it loops.",
2423
+ "it reads unless a ref or Set marks each row as already written: it loops. " +
2424
+ "The result has only create, update and delete; the checker refuses a " +
2425
+ "call to any other key (datastore-method-unknown).",
2424
2426
  returnShape: {
2425
2427
  create:
2426
2428
  "(record) => Promise<Record> // rejects with DatastoreError { code, message, retryable } — render the message when retryable is false, never 'try again'",
@@ -7107,7 +7109,10 @@ const CONTRACT = deepFreeze({
7107
7109
  // in to a server that asks for it, brokered by the host, and
7108
7110
  // `connections.signInResult` reports a web sign-in on the page's return.
7109
7111
  // Items gain status 'needs_sign_in' and auth_kind 'oauth'.
7110
- version: "1.275.0",
7112
+ // 1.276.0: stricter lint (sc-17764) — a widget that calls a key
7113
+ // useDatastoreMutation() does not return is the publish-blocking
7114
+ // `datastore-method-unknown` finding.
7115
+ version: "1.276.0",
7111
7116
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7112
7117
  hooks: HOOKS,
7113
7118
  primitives: PRIMITIVES,
@@ -0,0 +1,29 @@
1
+ // REQ-WSDK-PLATFORM §6 — the dialogs the native `<DateTimePicker>` walks
2
+ // through. Pure, so it is unit-tested without React Native.
3
+
4
+ /**
5
+ * The OS dialog modes one pick opens, in order. Android has no combined
6
+ * dialog, and its picker library cannot dismiss a "datetime" one.
7
+ *
8
+ * @param {"date" | "time" | "datetime"} mode
9
+ * @param {string} os — `Platform.OS`.
10
+ * @returns {Array<"date" | "time" | "datetime">}
11
+ */
12
+ export function osDialogModes(mode, os) {
13
+ return mode === "datetime" && os === "android" ? ["date", "time"] : [mode];
14
+ }
15
+
16
+ /**
17
+ * The draft parts with the fields one dialog answered taken from `picked`.
18
+ *
19
+ * @param {{year: number, month: number, day: number, hours: number, minutes: number}} draft
20
+ * @param {Date} picked
21
+ * @param {"date" | "time" | "datetime"} dialogMode
22
+ */
23
+ export function applyDialogPick(draft, picked, dialogMode) {
24
+ const date = { year: picked.getFullYear(), month: picked.getMonth(), day: picked.getDate() };
25
+ const time = { hours: picked.getHours(), minutes: picked.getMinutes() };
26
+ if (dialogMode === "date") return { ...draft, ...date };
27
+ if (dialogMode === "time") return { ...draft, ...time };
28
+ return { ...draft, ...date, ...time };
29
+ }
@@ -9,7 +9,8 @@ import RNDateTimePicker from "@react-native-community/datetimepicker";
9
9
  import { View, Pressable, Platform } from "react-native";
10
10
  import { Text } from "./bounded-text.native.js";
11
11
  import { makeDateTimePicker } from "./datetimepicker-view.js";
12
- import { nowParts, partsToDate, valueToParts } from "./datetimepicker-format.js";
12
+ import { nowParts, partsToDate } from "./datetimepicker-format.js";
13
+ import { osDialogModes, applyDialogPick } from "./datetimepicker-os-steps.js";
13
14
  import { clampToBounds } from "./datetimepicker-calendar.js";
14
15
 
15
16
  function boundDate(parts, mode) {
@@ -17,23 +18,43 @@ function boundDate(parts, mode) {
17
18
  return partsToDate(parts);
18
19
  }
19
20
 
20
- function OsPicker({ open, onClose, mode, parts, bounds, onPick }) {
21
+ function OsPicker({ open, ...dialog }) {
21
22
  if (!open) return null;
22
- const start = parts ? { ...nowParts(), ...dropEmpty(parts) } : clampToBounds(nowParts(), bounds);
23
+ return React.createElement(OsDialogs, dialog);
24
+ }
25
+
26
+ // Mounted per pick, so each one starts from the field's current value.
27
+ function OsDialogs({ onClose, mode, parts, bounds, onPick }) {
28
+ const modes = osDialogModes(mode, Platform.OS);
29
+ const [step, setStep] = React.useState(0);
30
+ const [draft, setDraft] = React.useState(() =>
31
+ parts ? { ...nowParts(), ...dropEmpty(parts) } : clampToBounds(nowParts(), bounds),
32
+ );
33
+ const latest = React.useRef(null);
34
+ latest.current = { onClose, onPick, bounds, modes, step, draft };
35
+ // Stable: Android reopens its dialog whenever onChange changes.
36
+ const onChange = React.useCallback((event, picked) => {
37
+ const { onClose, onPick, bounds, modes, step, draft } = latest.current;
38
+ // Android reports a cancelled dialog as "dismissed".
39
+ const cancelled = (event && event.type === "dismissed") || !(picked instanceof Date);
40
+ const next = cancelled ? null : applyDialogPick(draft, picked, modes[step]);
41
+ if (next && step + 1 < modes.length) {
42
+ setDraft(next);
43
+ setStep(step + 1);
44
+ return;
45
+ }
46
+ onClose();
47
+ // Android's time dialog cannot be bounded, so a pick is clamped here.
48
+ if (next) onPick(clampToBounds(next, bounds));
49
+ }, []);
50
+ const dialogMode = modes[step];
23
51
  return React.createElement(RNDateTimePicker, {
24
- value: partsToDate(start),
25
- // iOS honours "datetime"; Android shows its date dialog for it.
26
- mode,
27
- minimumDate: boundDate(bounds.min, mode),
28
- maximumDate: boundDate(bounds.max, mode),
29
- onChange: (event, picked) => {
30
- onClose();
31
- // Android reports a cancelled dialog as "dismissed".
32
- if (event && event.type === "dismissed") return;
33
- if (!(picked instanceof Date)) return;
34
- // Android's time dialog cannot be bounded, so a pick is clamped here.
35
- onPick(clampToBounds(valueToParts(picked.toISOString(), "datetime"), bounds));
36
- },
52
+ key: dialogMode,
53
+ value: partsToDate(draft),
54
+ mode: dialogMode,
55
+ minimumDate: boundDate(bounds.min, dialogMode),
56
+ maximumDate: boundDate(bounds.max, dialogMode),
57
+ onChange,
37
58
  });
38
59
  }
39
60
 
package/dist/host.d.ts CHANGED
@@ -473,6 +473,13 @@ export function isDarkSurface(input?: {
473
473
  theme?: unknown;
474
474
  } | null): boolean;
475
475
 
476
+ /** sc-17703 — how the signed-in visitor's account button is drawn. */
477
+ export type AccountButtonStyle = "name" | "avatar";
478
+ export const ACCOUNT_BUTTON_STYLES: readonly AccountButtonStyle[];
479
+ export const DEFAULT_ACCOUNT_BUTTON_STYLE: AccountButtonStyle;
480
+ /** The account button's style from a whole `theme_config`; unset is "name". */
481
+ export function resolveAccountButtonStyle(theme: unknown): AccountButtonStyle;
482
+
476
483
  /** The logo a surface draws: the dark-surface variant only beside an app logo. */
477
484
  export function resolveAppLogo<T>(
478
485
  logo: T | null | undefined,
package/dist/host.js CHANGED
@@ -131,6 +131,9 @@ export {
131
131
  topNavigationPageIds,
132
132
  isDarkSurface,
133
133
  resolveAppLogo,
134
+ ACCOUNT_BUTTON_STYLES,
135
+ DEFAULT_ACCOUNT_BUTTON_STYLE,
136
+ resolveAccountButtonStyle,
134
137
  } from "./navigation.js";
135
138
 
136
139
  // sc-5717: the codec behind `useWidgetRoute()` — how a widget's own internal
package/dist/linter.cjs CHANGED
@@ -2400,6 +2400,153 @@ function _mutationHookCalls(code) {
2400
2400
  }
2401
2401
  }
2402
2402
 
2403
+ // sc-17764 — a missing mutation method throws only once pressed.
2404
+ const _MUTATION_METHODS = Object.keys(
2405
+ CONTRACT.hooks.find((hook) => hook.name === "useDatastoreMutation").returnShape,
2406
+ );
2407
+ const _MUTATION_ENTRY_RE = /^\s*([A-Za-z_$][\w$]*)\s*(?::\s*([A-Za-z_$][\w$]*)\s*)?$/;
2408
+ const _IDENTIFIER_RUN_RE = /(?<![\w$])[A-Za-z_$][\w$]*/g;
2409
+ const _CALL_PAREN_RE = /\s*\(/y;
2410
+ const _MEMBER_RE = /\s*\??\.\s*([A-Za-z_$][\w$]*)/y;
2411
+ const _BODY_BRACE_RE = /\s*\{/y;
2412
+ // A function or method definition, or JSX text, never a call.
2413
+ const _NOT_A_CALLEE_RE = /(?:\bfunction\s*\*?|\b(?:async|get|set|static)|[^=]>)\s*$/;
2414
+ // A last argument listing bare names: a hook's dependency list.
2415
+ const _DEPENDENCY_LIST_RE = /,\s*\[[\s\w$.?,]*\]\s*,?\s*\)/g;
2416
+
2417
+ const _isUnknownMutationKey = (key) => !_MUTATION_METHODS.includes(key) && !(key in Object.prototype);
2418
+
2419
+ const _followedBy = (re, code, index) => {
2420
+ re.lastIndex = index;
2421
+ return re.exec(code);
2422
+ };
2423
+
2424
+ // Whether `at` lies inside one of `ranges` (sorted, disjoint); `at` must only grow.
2425
+ function _rangeCursor(ranges) {
2426
+ let i = 0;
2427
+ return (at) => {
2428
+ while (i < ranges.length && ranges[i].close <= at) i += 1;
2429
+ return i < ranges.length && ranges[i].open < at ? ranges[i] : null;
2430
+ };
2431
+ }
2432
+
2433
+ function _matchingParens(code) {
2434
+ const closeOf = new Map();
2435
+ const open = [];
2436
+ for (const m of code.matchAll(/[()]/g)) {
2437
+ if (m[0] === "(") open.push(m.index);
2438
+ else if (open.length > 0) closeOf.set(open.pop(), m.index);
2439
+ }
2440
+ return closeOf;
2441
+ }
2442
+
2443
+ function _previousCodeChar(code, at) {
2444
+ let i = at - 1;
2445
+ while (i >= 0 && /\s/.test(code[i])) i -= 1;
2446
+ return i;
2447
+ }
2448
+
2449
+ // Locals destructured under an unknown key, their destructures, and named mutation objects.
2450
+ function _mutationBindings(code) {
2451
+ const locals = new Map();
2452
+ const objects = new Map();
2453
+ const spans = [];
2454
+ for (const call of _mutationHookCalls(code)) {
2455
+ if ("name" in call) {
2456
+ if (/[\w$.]/.test(code[call.index - 1] || "")) continue;
2457
+ objects.set(call.name, (objects.get(call.name) || new Set()).add(call.index));
2458
+ continue;
2459
+ }
2460
+ const span = { open: call.index, close: call.index + call.destructured.length + 1, names: new Set() };
2461
+ for (const entry of call.destructured.split(",")) {
2462
+ const m = _MUTATION_ENTRY_RE.exec(entry);
2463
+ if (!m || !_isUnknownMutationKey(m[1])) continue;
2464
+ if (!locals.has(m[2] || m[1])) locals.set(m[2] || m[1], m[1]);
2465
+ span.names.add(m[2] || m[1]);
2466
+ }
2467
+ if (span.names.size > 0) spans.push(span);
2468
+ }
2469
+ return { locals, objects, spans };
2470
+ }
2471
+
2472
+ function _isPlainCall(code, at, end, closeOf) {
2473
+ if (!_followedBy(_CALL_PAREN_RE, code, end)) return false;
2474
+ if (_NOT_A_CALLEE_RE.test(code.slice(Math.max(0, at - 40), at))) return false;
2475
+ const close = closeOf.get(_CALL_PAREN_RE.lastIndex - 1);
2476
+ return close !== undefined && !_followedBy(_BODY_BRACE_RE, code, close + 1);
2477
+ }
2478
+
2479
+ // One use of a judged binding, its `call` index null unless called; null when not judged.
2480
+ function _mutationKeyUse(code, name, at, { locals, objects }, closeOf) {
2481
+ if (locals.has(name)) {
2482
+ const called = _isPlainCall(code, at, at + name.length, closeOf);
2483
+ return { id: name, key: locals.get(name), call: called ? at : null };
2484
+ }
2485
+ if (objects.get(name).has(at)) return null;
2486
+ const member = _followedBy(_MEMBER_RE, code, at + name.length);
2487
+ if (!member) return { id: name, escaped: true };
2488
+ if (!_isUnknownMutationKey(member[1])) return null;
2489
+ const called = _isPlainCall(code, at, _MEMBER_RE.lastIndex, closeOf);
2490
+ return { id: `${name}.${member[1]}`, object: name, key: member[1], call: called ? at : null };
2491
+ }
2492
+
2493
+ // Whether the identifier at `at` is a use the rule reads at all.
2494
+ function _isJudgedUse(code, name, at, declarationAt, dependencyAt) {
2495
+ const before = _previousCodeChar(code, at);
2496
+ const spread = code.slice(before - 2, before + 1) === "...";
2497
+ if (code[before] === "." && !spread) return false;
2498
+ const declaration = declarationAt(at);
2499
+ if (declaration && declaration.names.has(name)) return false;
2500
+ return !dependencyAt(at);
2501
+ }
2502
+
2503
+ // Each judged key with the index of its first call, dropped once any use is not a call.
2504
+ function _calledUnknownMutationKeys(code, bindings) {
2505
+ const keys = new Map();
2506
+ const escaped = new Set();
2507
+ const closeOf = _matchingParens(code);
2508
+ const declarationAt = _rangeCursor(bindings.spans);
2509
+ const dependencyAt = _rangeCursor(
2510
+ [...code.matchAll(_DEPENDENCY_LIST_RE)].map((m) => ({ open: m.index, close: m.index + m[0].length })),
2511
+ );
2512
+ for (const m of code.matchAll(_IDENTIFIER_RUN_RE)) {
2513
+ const name = m[0];
2514
+ if (!bindings.locals.has(name) && !bindings.objects.has(name)) continue;
2515
+ if (!_isJudgedUse(code, name, m.index, declarationAt, dependencyAt)) continue;
2516
+ const use = _mutationKeyUse(code, name, m.index, bindings, closeOf);
2517
+ if (!use) continue;
2518
+ if (use.escaped) {
2519
+ escaped.add(use.id);
2520
+ continue;
2521
+ }
2522
+ const seen = keys.get(use.id);
2523
+ if (use.call === null || seen === null) keys.set(use.id, null);
2524
+ else if (!seen) keys.set(use.id, use);
2525
+ }
2526
+ return [...keys.values()].filter((use) => use && !escaped.has(use.object));
2527
+ }
2528
+
2529
+ function _unknownMutationMethodRules(source) {
2530
+ const code = _stripNonCode(source);
2531
+ if (!code.includes("useDatastoreMutation")) return [];
2532
+ const bindings = _mutationBindings(code);
2533
+ if (bindings.locals.size === 0 && bindings.objects.size === 0) return [];
2534
+ const lineAt = _lineCounter(code);
2535
+ const sourceLines = source.split(/\r?\n/);
2536
+ return _calledUnknownMutationKeys(code, bindings).map(({ key, call }) => {
2537
+ const line = lineAt(call);
2538
+ return {
2539
+ rule: "datastore-method-unknown",
2540
+ severity: "error",
2541
+ label:
2542
+ `useDatastoreMutation(...).${key} does not exist; available: ${_MUTATION_METHODS.join(", ")}. ` +
2543
+ "It is undefined, so the call throws when it runs.",
2544
+ line,
2545
+ snippet: (sourceLines[line - 1] || "").trim().slice(0, 200),
2546
+ };
2547
+ });
2548
+ }
2549
+
2403
2550
  function _imagePercentHeightRules(source) {
2404
2551
  const findings = [];
2405
2552
  // Comments are blanked (string contents kept) so a commented-out example —
@@ -3918,6 +4065,7 @@ function lintSource(source, options) {
3918
4065
  findings.push(..._handRolledWriteGateRules(source));
3919
4066
  findings.push(..._useAssetOnFileColumnRules(source));
3920
4067
  findings.push(..._rowActionGatingRules(source));
4068
+ findings.push(..._unknownMutationMethodRules(source));
3921
4069
  // REQ-USERMGMT / REQ-ACL-SYS M3 — scope-aware rules. Run after the
3922
4070
  // line-by-line scan so banned-identifier findings stay first in the
3923
4071
  // output.
package/dist/linter.js CHANGED
@@ -2395,6 +2395,153 @@ function _mutationHookCalls(code) {
2395
2395
  }
2396
2396
  }
2397
2397
 
2398
+ // sc-17764 — a missing mutation method throws only once pressed.
2399
+ const _MUTATION_METHODS = Object.keys(
2400
+ CONTRACT.hooks.find((hook) => hook.name === "useDatastoreMutation").returnShape,
2401
+ );
2402
+ const _MUTATION_ENTRY_RE = /^\s*([A-Za-z_$][\w$]*)\s*(?::\s*([A-Za-z_$][\w$]*)\s*)?$/;
2403
+ const _IDENTIFIER_RUN_RE = /(?<![\w$])[A-Za-z_$][\w$]*/g;
2404
+ const _CALL_PAREN_RE = /\s*\(/y;
2405
+ const _MEMBER_RE = /\s*\??\.\s*([A-Za-z_$][\w$]*)/y;
2406
+ const _BODY_BRACE_RE = /\s*\{/y;
2407
+ // A function or method definition, or JSX text, never a call.
2408
+ const _NOT_A_CALLEE_RE = /(?:\bfunction\s*\*?|\b(?:async|get|set|static)|[^=]>)\s*$/;
2409
+ // A last argument listing bare names: a hook's dependency list.
2410
+ const _DEPENDENCY_LIST_RE = /,\s*\[[\s\w$.?,]*\]\s*,?\s*\)/g;
2411
+
2412
+ const _isUnknownMutationKey = (key) => !_MUTATION_METHODS.includes(key) && !(key in Object.prototype);
2413
+
2414
+ const _followedBy = (re, code, index) => {
2415
+ re.lastIndex = index;
2416
+ return re.exec(code);
2417
+ };
2418
+
2419
+ // Whether `at` lies inside one of `ranges` (sorted, disjoint); `at` must only grow.
2420
+ function _rangeCursor(ranges) {
2421
+ let i = 0;
2422
+ return (at) => {
2423
+ while (i < ranges.length && ranges[i].close <= at) i += 1;
2424
+ return i < ranges.length && ranges[i].open < at ? ranges[i] : null;
2425
+ };
2426
+ }
2427
+
2428
+ function _matchingParens(code) {
2429
+ const closeOf = new Map();
2430
+ const open = [];
2431
+ for (const m of code.matchAll(/[()]/g)) {
2432
+ if (m[0] === "(") open.push(m.index);
2433
+ else if (open.length > 0) closeOf.set(open.pop(), m.index);
2434
+ }
2435
+ return closeOf;
2436
+ }
2437
+
2438
+ function _previousCodeChar(code, at) {
2439
+ let i = at - 1;
2440
+ while (i >= 0 && /\s/.test(code[i])) i -= 1;
2441
+ return i;
2442
+ }
2443
+
2444
+ // Locals destructured under an unknown key, their destructures, and named mutation objects.
2445
+ function _mutationBindings(code) {
2446
+ const locals = new Map();
2447
+ const objects = new Map();
2448
+ const spans = [];
2449
+ for (const call of _mutationHookCalls(code)) {
2450
+ if ("name" in call) {
2451
+ if (/[\w$.]/.test(code[call.index - 1] || "")) continue;
2452
+ objects.set(call.name, (objects.get(call.name) || new Set()).add(call.index));
2453
+ continue;
2454
+ }
2455
+ const span = { open: call.index, close: call.index + call.destructured.length + 1, names: new Set() };
2456
+ for (const entry of call.destructured.split(",")) {
2457
+ const m = _MUTATION_ENTRY_RE.exec(entry);
2458
+ if (!m || !_isUnknownMutationKey(m[1])) continue;
2459
+ if (!locals.has(m[2] || m[1])) locals.set(m[2] || m[1], m[1]);
2460
+ span.names.add(m[2] || m[1]);
2461
+ }
2462
+ if (span.names.size > 0) spans.push(span);
2463
+ }
2464
+ return { locals, objects, spans };
2465
+ }
2466
+
2467
+ function _isPlainCall(code, at, end, closeOf) {
2468
+ if (!_followedBy(_CALL_PAREN_RE, code, end)) return false;
2469
+ if (_NOT_A_CALLEE_RE.test(code.slice(Math.max(0, at - 40), at))) return false;
2470
+ const close = closeOf.get(_CALL_PAREN_RE.lastIndex - 1);
2471
+ return close !== undefined && !_followedBy(_BODY_BRACE_RE, code, close + 1);
2472
+ }
2473
+
2474
+ // One use of a judged binding, its `call` index null unless called; null when not judged.
2475
+ function _mutationKeyUse(code, name, at, { locals, objects }, closeOf) {
2476
+ if (locals.has(name)) {
2477
+ const called = _isPlainCall(code, at, at + name.length, closeOf);
2478
+ return { id: name, key: locals.get(name), call: called ? at : null };
2479
+ }
2480
+ if (objects.get(name).has(at)) return null;
2481
+ const member = _followedBy(_MEMBER_RE, code, at + name.length);
2482
+ if (!member) return { id: name, escaped: true };
2483
+ if (!_isUnknownMutationKey(member[1])) return null;
2484
+ const called = _isPlainCall(code, at, _MEMBER_RE.lastIndex, closeOf);
2485
+ return { id: `${name}.${member[1]}`, object: name, key: member[1], call: called ? at : null };
2486
+ }
2487
+
2488
+ // Whether the identifier at `at` is a use the rule reads at all.
2489
+ function _isJudgedUse(code, name, at, declarationAt, dependencyAt) {
2490
+ const before = _previousCodeChar(code, at);
2491
+ const spread = code.slice(before - 2, before + 1) === "...";
2492
+ if (code[before] === "." && !spread) return false;
2493
+ const declaration = declarationAt(at);
2494
+ if (declaration && declaration.names.has(name)) return false;
2495
+ return !dependencyAt(at);
2496
+ }
2497
+
2498
+ // Each judged key with the index of its first call, dropped once any use is not a call.
2499
+ function _calledUnknownMutationKeys(code, bindings) {
2500
+ const keys = new Map();
2501
+ const escaped = new Set();
2502
+ const closeOf = _matchingParens(code);
2503
+ const declarationAt = _rangeCursor(bindings.spans);
2504
+ const dependencyAt = _rangeCursor(
2505
+ [...code.matchAll(_DEPENDENCY_LIST_RE)].map((m) => ({ open: m.index, close: m.index + m[0].length })),
2506
+ );
2507
+ for (const m of code.matchAll(_IDENTIFIER_RUN_RE)) {
2508
+ const name = m[0];
2509
+ if (!bindings.locals.has(name) && !bindings.objects.has(name)) continue;
2510
+ if (!_isJudgedUse(code, name, m.index, declarationAt, dependencyAt)) continue;
2511
+ const use = _mutationKeyUse(code, name, m.index, bindings, closeOf);
2512
+ if (!use) continue;
2513
+ if (use.escaped) {
2514
+ escaped.add(use.id);
2515
+ continue;
2516
+ }
2517
+ const seen = keys.get(use.id);
2518
+ if (use.call === null || seen === null) keys.set(use.id, null);
2519
+ else if (!seen) keys.set(use.id, use);
2520
+ }
2521
+ return [...keys.values()].filter((use) => use && !escaped.has(use.object));
2522
+ }
2523
+
2524
+ function _unknownMutationMethodRules(source) {
2525
+ const code = _stripNonCode(source);
2526
+ if (!code.includes("useDatastoreMutation")) return [];
2527
+ const bindings = _mutationBindings(code);
2528
+ if (bindings.locals.size === 0 && bindings.objects.size === 0) return [];
2529
+ const lineAt = _lineCounter(code);
2530
+ const sourceLines = source.split(/\r?\n/);
2531
+ return _calledUnknownMutationKeys(code, bindings).map(({ key, call }) => {
2532
+ const line = lineAt(call);
2533
+ return {
2534
+ rule: "datastore-method-unknown",
2535
+ severity: "error",
2536
+ label:
2537
+ `useDatastoreMutation(...).${key} does not exist; available: ${_MUTATION_METHODS.join(", ")}. ` +
2538
+ "It is undefined, so the call throws when it runs.",
2539
+ line,
2540
+ snippet: (sourceLines[line - 1] || "").trim().slice(0, 200),
2541
+ };
2542
+ });
2543
+ }
2544
+
2398
2545
  function _imagePercentHeightRules(source) {
2399
2546
  const findings = [];
2400
2547
  // Comments are blanked (string contents kept) so a commented-out example —
@@ -3913,6 +4060,7 @@ export function lintSource(source, options) {
3913
4060
  findings.push(..._handRolledWriteGateRules(source));
3914
4061
  findings.push(..._useAssetOnFileColumnRules(source));
3915
4062
  findings.push(..._rowActionGatingRules(source));
4063
+ findings.push(..._unknownMutationMethodRules(source));
3916
4064
  // REQ-USERMGMT / REQ-ACL-SYS M3 — scope-aware rules. Run after the
3917
4065
  // line-by-line scan so banned-identifier findings stay first in the
3918
4066
  // output.
@@ -918,6 +918,26 @@ function borderWidthOr(...values) {
918
918
  }
919
919
  return BORDER_WIDTH_MIN;
920
920
  }
921
+
922
+ // sc-17703: how the signed-in visitor's account button is drawn. `name` is the
923
+ // avatar, name and chevron pill. `avatar` is the bare avatar circle, which
924
+ // leaves the app's brand more room. Both open the same account menu.
925
+ const ACCOUNT_BUTTON_STYLES = ["name", "avatar"];
926
+ const DEFAULT_ACCOUNT_BUTTON_STYLE = "name";
927
+
928
+ /**
929
+ * The account button's style, resolved for every host.
930
+ *
931
+ * @param {unknown} theme — the whole `theme_config`.
932
+ * @returns {"name"|"avatar"}
933
+ */
934
+ function resolveAccountButtonStyle(theme) {
935
+ const config = isPlainObject(theme) ? theme : {};
936
+ const account = isPlainObject(config.account) ? config.account : {};
937
+ return ACCOUNT_BUTTON_STYLES.includes(account.buttonStyle)
938
+ ? account.buttonStyle
939
+ : DEFAULT_ACCOUNT_BUTTON_STYLE;
940
+ }
921
941
  module.exports = {
922
942
  normaliseNavigation,
923
943
  menuItemCap,
@@ -950,4 +970,7 @@ module.exports = {
950
970
  resolvePageBars,
951
971
  drawsTopNavigation,
952
972
  topNavigationPageIds,
973
+ ACCOUNT_BUTTON_STYLES,
974
+ DEFAULT_ACCOUNT_BUTTON_STYLE,
975
+ resolveAccountButtonStyle,
953
976
  };
@@ -913,3 +913,23 @@ function borderWidthOr(...values) {
913
913
  }
914
914
  return BORDER_WIDTH_MIN;
915
915
  }
916
+
917
+ // sc-17703: how the signed-in visitor's account button is drawn. `name` is the
918
+ // avatar, name and chevron pill. `avatar` is the bare avatar circle, which
919
+ // leaves the app's brand more room. Both open the same account menu.
920
+ export const ACCOUNT_BUTTON_STYLES = ["name", "avatar"];
921
+ export const DEFAULT_ACCOUNT_BUTTON_STYLE = "name";
922
+
923
+ /**
924
+ * The account button's style, resolved for every host.
925
+ *
926
+ * @param {unknown} theme — the whole `theme_config`.
927
+ * @returns {"name"|"avatar"}
928
+ */
929
+ export function resolveAccountButtonStyle(theme) {
930
+ const config = isPlainObject(theme) ? theme : {};
931
+ const account = isPlainObject(config.account) ? config.account : {};
932
+ return ACCOUNT_BUTTON_STYLES.includes(account.buttonStyle)
933
+ ? account.buttonStyle
934
+ : DEFAULT_ACCOUNT_BUTTON_STYLE;
935
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.337.1",
3
+ "version": "0.338.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
@@ -2420,7 +2420,9 @@ const HOOKS = [
2420
2420
  "must name the table the same way (its id, as a tableRef property binds it). " +
2421
2421
  "A run of writes re-reads each reader at most once a second, always once " +
2422
2422
  "more after the last. Never write from a useEffect that re-runs on the data " +
2423
- "it reads unless a ref or Set marks each row as already written: it loops.",
2423
+ "it reads unless a ref or Set marks each row as already written: it loops. " +
2424
+ "The result has only create, update and delete; the checker refuses a " +
2425
+ "call to any other key (datastore-method-unknown).",
2424
2426
  returnShape: {
2425
2427
  create:
2426
2428
  "(record) => Promise<Record> // rejects with DatastoreError { code, message, retryable } — render the message when retryable is false, never 'try again'",
@@ -7107,7 +7109,10 @@ const CONTRACT = deepFreeze({
7107
7109
  // in to a server that asks for it, brokered by the host, and
7108
7110
  // `connections.signInResult` reports a web sign-in on the page's return.
7109
7111
  // Items gain status 'needs_sign_in' and auth_kind 'oauth'.
7110
- version: "1.275.0",
7112
+ // 1.276.0: stricter lint (sc-17764) — a widget that calls a key
7113
+ // useDatastoreMutation() does not return is the publish-blocking
7114
+ // `datastore-method-unknown` finding.
7115
+ version: "1.276.0",
7111
7116
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7112
7117
  hooks: HOOKS,
7113
7118
  primitives: PRIMITIVES,