@voltro/protocol 0.3.0 → 0.4.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/CHANGELOG.md CHANGED
@@ -39,6 +39,35 @@ _Changes staged for the next release accumulate here (rolled up from
39
39
 
40
40
  ---
41
41
 
42
+ ## [0.4.0] — 2026-07-18
43
+
44
+ ### ⚠ BREAKING
45
+
46
+ - **@voltro/protocol, @voltro/plugin-rbac, @voltro/runtime** — **Resource-aware declarative guards + one denial tag.** `guards: [{ scope, resource }]` now actually scopes to a resource. Register a resolver — either `setResourceScopeResolver((req) => Effect<boolean>)` from `@voltro/protocol`, or `rbacPlugin({ resolveResourceRoles: (subject, resourceId) => roleSlugs })` — and the framework asks it, per request, whether the caller holds the scope **on the extracted resource** (a team, workspace, document), before the executor runs (mutations: before the transaction opens). A globally-held scope or `admin:full` still short-circuits without a resolver call; a resolver error fails **closed**. With no resolver registered, `resource` stays advisory (global check) exactly as before, so single-tenant apps are unaffected. **BREAKING — `@voltro/plugin-rbac` no longer exports `Forbidden`.** rbac's `permission()` / `assertPermission()` / `anyPermission()` now fail with protocol's `ScopeError` — the SAME typed error the declarative `guards:` enforcement already raised. One denial tag across the framework: a client that matches `_tag === 'ScopeError'` (or `errorTag(err)`) recognizes both a descriptor-guard denial and a `permission()` denial with one branch. The `@voltro/plugin-rbac/errors` subpath is removed. Migration (the `voltro update` codemod rewrites the mechanical part): - `import { Forbidden } from '@voltro/plugin-rbac/errors'` → `import { ScopeError } from '@voltro/protocol'`; `import { Forbidden } from '@voltro/plugin-rbac'` → `import { ScopeError } from '@voltro/plugin-rbac'` (re-exported from the root). - Every `Forbidden` identifier → `ScopeError` (incl. `error: Forbidden` on a descriptor). - By hand: a constructed `new Forbidden({ required, reason })` becomes `new ScopeError({ required, message })` (the field is `message` and is REQUIRED); and any `Effect.catchTag('Forbidden', …)` / `err._tag === 'Forbidden'` string becomes `'ScopeError'`. Guards are normally caught, not constructed, so most apps only need the import rewrite the codemod does. Also note: `requireScope` / declarative `guards:` enforcement is now async-capable (it awaits the resource resolver when one is registered) — no change to handler code, which never called the internal enforcement directly.
47
+ - **@voltro/client, @voltro/plugin-rbac** — **`@voltro/plugin-rbac/web` is removed — the UI permission gate lives in `@voltro/client`.** The framework shipped `useCan` TWICE, with the same name and the same semantics, over two different React contexts. An app that mounted `<PermissionProvider>` and imported the plugin's `useCan` got an empty scope set and silently hid every gated affordance — no error, just a UI where nothing is permitted. One of the two had to go. `@voltro/client` survives because scopes are a FRAMEWORK concept: `@voltro/protocol` owns `ScopeError`, `guards: [{ scope }]` and `ctx.access`, and rbac is only one way to PRODUCE scopes — an app can register its own `setResourceScopeResolver` over its own tables and never install the plugin. The hook consumes scopes, which is generic; producing them is rbac-specific. Keeping the hook behind the plugin would force an rbac dependency on apps that deliberately don't use rbac, purely to gate a button. `@voltro/plugin-rbac` keeps everything that IS rbac: the roles map, role→scope compilation, the `permission()` / `assertPermission()` / `anyPermission()` server guards, the role tables, and `resolveResourceRoles`. The codemod rewrites every mechanical site: `RbacScopeProvider` → `PermissionProvider`, `canFromScopes` → `canCall`, `canAnyFromScopes` → `canCallAny`, and repoints `useCan` / `useCanAny` / `ADMIN_SCOPE` to `@voltro/client`. A raw `useContext(RbacScopeContext)` is ANNOTATED rather than rewritten — the client equivalent is `usePermissions()`, which returns `{ scopes }` instead of the bare array, so a silent rewrite would compile and then hand back the wrong shape.
48
+
49
+ ### Added
50
+
51
+ - **@voltro/runtime, @voltro/cli** — **`read({ where })` on aggregates.** Aggregate reads were all-or-nothing, so every consumer that wanted one slice pulled the whole materialised set over the wire and filtered in the component — the cost scaling with the aggregate, not the slice. `where` entries are ANDed; a scalar means strict equality, an array means IN; filtering runs before `orderBy`/`limit`. Deliberately a data filter over already materialised rows, not a predicate language — aggregates stay aggregates.
52
+ - **@voltro/client** — **Two ergonomics that remove the two most-repeated shapes in a Voltro frontend.** - **`mutate(input, options)` — `onSuccess` / `onError` / `notify`.** Every write site used to re-type `try { await mutate() } catch { toast.error(…) } finally { setSubmitting(false) }`. `pending` already replaced the `finally`; these replace the rest. Load-bearing semantic: supplying an error handler (`onError` or `notify.error`) marks the failure HANDLED — `mutate` resolves with `undefined` instead of rejecting, which is what actually deletes the try/catch. With no handler it rejects exactly as before, so unhandled failures stay loud. `notify` routes to an app-registered sink (`setMutationNotifier`) — the framework stays unbound to any toast library. - **`useSubscription` now returns `loading` and `isEmpty`, and accepts `fallback`.** Call sites branched on `data === undefined`, conflating "no snapshot yet" with "zero rows" — the cause of a flash of empty-state before the first snapshot. They are now distinct, derived once. `fallback` fills `data` while loading without lying about `loading`. Also documented: `error` carries a COLD-START stream failure (check it to avoid an infinite skeleton); a failure after data arrived deliberately does not blank good data — those reach the error bus (`useOnRpcError`).
53
+ - **@voltro/cli** — **Make the client hook surface discoverable — and keep it that way.** A downstream app built its whole frontend on three transport hooks (`useSubscription` / `useMutation` / `useAction`) and hand-rolled forms, tables, upload, permission gates, debounce and pagination, because the agent guide documented ~none of the ~40 client hooks that already ship. Three changes: - **The always-loaded core now carries a "Pick the CLIENT primitive" rubric** — the same decision-rubric treatment the backend primitives get, plus a "you're about to write X → reach for Y" table (per-field `useState` → `useFormBinding`, hand-rolled table → `useDataTable`, `FileReader` → `useUpload`, `useMemo` fan-in → `useDerived`, …). - **The hook reference is complete.** `reference/hooks-overview.md` presented itself as "the client-side hook surface" while documenting 13 of 44 hooks; it now enumerates the schema-driven-UI, files/permissions/utilities, and AI families (en + de). - **A coverage GATE** (`agentsMdTemplate.test.ts`): every exported `use*` hook of `@voltro/client` must appear in the composed agent-docs corpus, or the test fails with the list. Docs can no longer silently fall behind the export surface. Plus **`voltro doctor` now flags hand-rolls**: it scans an app's source for the patterns a shipped primitive covers (hand-rolled form/table, `FileReader` upload, `setTimeout` debounce, `useMemo` fan-in, local Next.js compat shims, hand-rolled presence) and names the primitive to use. Advisory, never fatal — a false-positive lecture must not fail a build.
54
+ - **@voltro/cli** — **Generated `matchError` / `AppError` / `AppErrorTag`.** Codegen now emits a per-app exhaustive error matcher into `rpcGroup.generated.ts`, derived BY REFERENCE from every descriptor's `error:` schema plus the cross-cutting plugin errors. `matchError(err, { [tag]: handler }, fallback?)` dispatches on `_tag` with the handler keys constrained to the app's ACTUAL error tags — so a hand-maintained tag list that silently drifts (dead/renamed tags) is gone; a stale tag is a compile error. Browser-safe (reads `_tag` structurally, no runtime dep). Workflows keep their existing `WorkflowErrors`.
55
+ - **@voltro/cli** — **`voltro doctor` + `voltro update --codemods-only`/`--from`** — two upgrade-path ergonomics from AWB adoption feedback: - **`voltro doctor [app]`** (and **`voltro serve --preflight`**) preflights an API app for production serve: it verifies the precompiled serve bundle exists and, if not, prints the exact fix and exits 1 — so a Dockerfile / CI step catches "prod `voltro serve` with no `voltro build`" at BUILD time instead of at cold-start (0.3.0 made an unbuilt production serve fatal). - **`voltro update --codemods-only` (alias `--run-codemods`) + `--from <version>`** — re-apply the codemods + manual notes for an explicit `[from, to]` delta WITHOUT bumping `package.json` or installing. The recovery path for a hand-edited version bump (`bump package.json` + install first), which otherwise makes `voltro update` report "already on X — nothing to do" and silently skip the codemods. `--from` also overrides the auto-detected source version on a normal update.
56
+ - **@voltro/runtime** — **`encryptField` / `decryptField` — standalone field cipher for raw-SQL paths.** `.encrypted()` columns encrypt/decrypt transparently inside the `ctx.store` middleware, so a code path that reaches the DB by RAW SQL (an auth strategy with no store handle reading/writing a session token, a one-off backfill) bypasses it. `@voltro/runtime` now exposes the SAME registered cipher standalone: `encryptField` encrypts a value; `decryptField` decrypts an `enc:v1:…` value and passes a non-ciphertext value through unchanged (so a raw-SQL path can adopt encryption while pre-existing plaintext rows keep working). Both throw a clear error when no cipher is registered. Encryption stops being all-or-nothing tied to going through `ctx.store`.
57
+ - **@voltro/testing** — **`makeVoltroTestClient` — the missing half of the test story.** The framework shipped a strong BACKEND test story (`makeTestContext`, `mockStore`, `mockAi`, the workflow runner) and nothing for the client. A Voltro frontend is a reactive-data app: with no way to render a component against mocked `useSubscription` / `useMutation` — and to inject a loading state, a stream error, or a failing write — it is structurally untestable, which is why real apps end up with zero frontend tests. `import { makeVoltroTestClient } from '@voltro/testing/client'` returns a `Provider` plus `setSubscription` / `failSubscription` / `resetSubscription` and a `calls` log of every write with its input. A tag ABSENT from the fixture stays in the loading state — the distinction from an empty result is exactly what you want to assert. Deliberately NOT a renderer: it hands you a Provider, so it works with `react-dom/client` + `act`, testing-library, or your own harness, and locks you into none of them.
58
+ - **@voltro/i18n** — **Plurals, Intl formatters, and catalogs a bundler can actually split.** - **`plural(locale, count, forms)` + `usePlural`** — real CLDR categories via `Intl.PluralRules`. Replaces the hardcoded `"{count} epic(s)"` pattern, whose literal `(s)` is simply wrong outside English, and which cannot express languages that distinguish few from many (Polish 2–4 vs 5+). An explicit `zero` form is honoured for exactly 0; ordinals via `{ type: 'ordinal' }`. - **`useFormatDate` / `useRelativeTime` / `useFormatNumber` / `useFormatCurrency` / `useFormatters`** — locale-bound `Intl` wrappers, so an app stops carrying several divergent hand-rolled "X minutes ago" helpers that each round differently. - **`defineCatalogs` + `LazyI18nProvider`** — code-split catalogs. `pickCatalog({ en, de })` is a STATIC import map: every locale is a value-level import, so the bundler must emit them in one chunk and a German-only visitor downloads English too, growing linearly per locale. A map of `() => import()` loaders is the only shape a bundler treats as a chunk boundary. `preload(locale)` before hydration keeps first paint synchronous via `peek()`; the provider's `fallback` is for a locale SWITCH, not first paint. Unknown locales degrade to the base catalog, and a failed chunk load stays retryable.
59
+ - **@voltro/protocol, @voltro/client** — **Nested optimistic: `shapeItem` + bulk (multi-item) targets.** Two additive improvements to path-targeted auto-optimistic: - **`shapeItem`** — the nested counterpart of `shape`, typed to the ITEM of the nested array (not the mutation's output), so a path-target patch reads/returns the item without casting `current`. (Previously the nested shaper was the flat `shape`, pinned to the output row — every adopter had to cast. `shape` stays bound to the output for flat targets; a single field can't be both, so the nested shaper is its own.) - **Bulk `identify`** — a target's `identify` may now return `string[]` to patch/delete MANY items (or top-level rows) in one mutation — the group-drag / batch-edit case where per-item parallel writes used to race. Each patched item keeps its own key. Runtime-compatible: a nested target that still uses `shape` falls back transparently. No codemod — additive.
60
+ - **@voltro/web, @voltro/client** — **Two hooks apps kept hand-rolling, because nothing shipped them.** - **`useTheme` (`@voltro/web`)** — returns `{ theme, resolvedTheme, setTheme }` over the framework's own `voltro:theme` cookie and the `html.dark` class. The bug it removes is specific: an app that hand-rolls a second theme store ends up with two writers on one class, so the toggle's state and the rendered theme can disagree, and the pre-paint script flashes the wrong one. `'system'` resolves through `matchMedia` and tracks live OS changes. - **`useConnectionStatus` (`@voltro/client`)** — `'connected' | 'degraded' | 'offline'`, derived from the only two signals the client honestly has: `navigator.onLine` (browser says the network is gone) and the rpc error bus (a call actually failed). `degraded` means "we saw a failure and no success since"; coming back online clears it, because the failures counted during an offline window ARE that window. Deliberately no polling ping just to colour an indicator.
61
+ - **@voltro/database** — **`.uniqueActive([cols])` now works on mysql / mariadb** (it previously failed loud at migrate — those engines have no partial index). It lowers automatically to a STORED generated column per key column — `CASE WHEN <predicate> THEN CAST(<col> AS CHAR(255)) ELSE NULL END` — plus a UNIQUE over them. NULL-distinct uniqueness means a soft-deleted row's generated columns are all NULL and never collide, so re-creating the key just works — the same resurrection-safe semantics the partial index gives on postgres/sqlite/mssql. The lowering is applied identically on the emit side and the declared-snapshot side, so it round-trips through the declarative differ (verified live on MariaDB: declare→migrate→introspect→re-plan is a no-diff, and a duplicate among active rows is rejected while soft-deleting one frees the key). You write the same `.uniqueActive([...])` on every dialect.
62
+
63
+ ### Fixed
64
+
65
+ - **@voltro/cli** — **Standalone `voltro codegen` now emits the SAME `rpcGroup.generated.ts` as `voltro dev` / `voltro build`.** Previously the standalone command skipped the app's plugins, so it dropped every plugin's cross-cutting error union AND its client RPC routes — an inconsistent generated file (typed plugin errors gone, plugin route tags unresolved) vs the dev/serve boot path. The command now loads `app.config` and gathers the plugins' codegen inputs through the SAME `gatherCodegenPluginImports` the boot path uses (single-sourced, so the three paths can't drift).
66
+ - **@voltro/cli** — **The hook-coverage gate was too weak, and it let dead documentation through.** It asked only whether a hook's NAME appeared in the agent-docs corpus — which a one-line row in a link table satisfies. Ten client hooks had exactly that, and six of those rows linked to a page that never mentions the hook, so a reader following the link learned nothing. Two sharper checks replace it: - **Substance** (`agentsMdTemplate.test.ts`): a hook must appear at least once OUTSIDE a table row, so a bare row no longer counts as documentation. - **Dead references** (`gen-agent-docs.mjs`): a row promising `[`useX`](/docs/…)` must point at a page that actually mentions `useX`. This lives in the generator because that is the only thing which reads the docs tree — and it walks BOTH language trees, since an en-only check leaves every German dead link invisible.
67
+ - **@voltro/cli** — - **Serve bundle: inline the pure-JS SQL drivers (`pg`/`mysql2`/`tedious`) instead of runtime-shimming them.** A production `voltro serve` with a postgres/mysql/mssql store crashed at boot with `Pg.Pool is not a constructor` (and the mysql/mssql equivalents): the driver's `@effect/sql-*` consumer links its leaf as a namespace (`import * as Pg from 'pg'; new Pg.Pool()`), but the native-leaf CJS shim (`module.exports = <leaf>`) did not surface the named members through esbuild's `import * as` interop, so `Pg.Pool` was `undefined`. These drivers are pure JS (no `.node`), so they are now inlined into the serve bundle like the rest of the framework — esbuild links the real module and the namespace resolves correctly. Only genuinely-native leaves (`better-sqlite3`, the turso/libsql addons, `pg-native`) and the dynamically-imported `ioredis`/`nodemailer` still resolve via the runtime shim. Verified end-to-end from a relocated prod tree (a real `POST /rpc` through the inlined `pg`).
68
+
69
+ ---
70
+
42
71
  ## [0.3.0] — 2026-07-18
43
72
 
44
73
  ### ⚠ BREAKING
package/dist/index.d.ts CHANGED
@@ -173,6 +173,23 @@ export declare const checkFrameworkCompat: (pluginName: string, range: string |
173
173
  */
174
174
  export declare const checkGuards: (subject: Subject, guards: ReadonlyArray<GuardCheckSpec> | undefined) => ScopeError | null;
175
175
 
176
+ /**
177
+ * The resource-aware counterpart of `checkGuards`. Identical semantics when no
178
+ * resource-scope resolver is registered (or no guard carries a `resource`
179
+ * extractor) — it delegates to the pure `checkGuards` and succeeds/denies
180
+ * exactly the same, allocation-light. When BOTH a resolver is registered AND a
181
+ * guard has a `resource`, it extracts the resource id from `input` and asks the
182
+ * resolver whether the caller holds each scope on THAT resource. A globally-held
183
+ * scope (or the `admin:full` bypass) still satisfies without a resolver call;
184
+ * only the gap ("no global grant") falls through to the resolver. A failed
185
+ * resolver Effect is treated as a denial (fail-closed).
186
+ *
187
+ * Returns a typed `ScopeError` naming the first unmet scope, or `null` when
188
+ * every guard passes. The runtime calls this in the dispatch spine BEFORE the
189
+ * executor (mutations: before the transaction opens).
190
+ */
191
+ export declare const checkGuardsEffect: (subject: Subject, guards: ReadonlyArray<GuardCheckSpec> | undefined, input: unknown) => Effect.Effect<ScopeError | null>;
192
+
176
193
  export declare interface ClientDescriptor {
177
194
  readonly kind: 'query' | 'mutation' | 'action' | 'stream' | 'workflow';
178
195
  /** Query only: table(s) the cache should match this subscription against. */
@@ -202,7 +219,7 @@ export declare interface ClientTarget {
202
219
  readonly op: 'insert' | 'update' | 'delete';
203
220
  readonly order?: 'prepend' | 'append' | undefined;
204
221
  readonly shape?: ((input: Record<string, unknown>, optimisticIdOrCurrent?: unknown) => Record<string, unknown>) | undefined;
205
- readonly identify?: ((input: Record<string, unknown>) => string) | undefined;
222
+ readonly identify?: ((input: Record<string, unknown>) => string | ReadonlyArray<string>) | undefined;
206
223
  /** Nested/path-targeted optimistic (see `NestedTargetFields`). Carried to the
207
224
  * client so item-level patches into a JSON array / computed value happen
208
225
  * automatically. Functions survive because the codegen references the live
@@ -210,6 +227,10 @@ export declare interface ClientTarget {
210
227
  readonly path?: string | undefined;
211
228
  readonly by?: string | undefined;
212
229
  readonly match?: ((value: unknown, input: Record<string, unknown>) => boolean) | undefined;
230
+ /** Nested-item shaper (erased). The client uses this instead of `shape` when
231
+ * `path` is set. 2nd arg is the optimistic id (insert) or the current item
232
+ * (update) — `unknown` here since the erased view spans both; normalize casts. */
233
+ readonly shapeItem?: ((input: Record<string, unknown>, currentOrOptimisticId: unknown) => Record<string, unknown>) | undefined;
213
234
  }
214
235
 
215
236
  /** Compose multiple strategies into a single resolver function. The
@@ -417,8 +438,9 @@ export declare const defineStream: <const Name extends string, Input extends Sch
417
438
  export declare interface DeleteTarget<Input = unknown> extends NestedTargetFields<Input> {
418
439
  readonly table: string;
419
440
  readonly op: 'delete';
420
- /** Identify the row to remove. Default: `input.id`. */
421
- readonly identify?: ((input: Input) => string) | undefined;
441
+ /** Identify the row(s) to remove. Default: `input.id`. Return an ARRAY to
442
+ * remove MANY rows/items in one mutation. */
443
+ readonly identify?: ((input: Input) => string | ReadonlyArray<string>) | undefined;
422
444
  }
423
445
 
424
446
  /**
@@ -477,9 +499,20 @@ export declare const failIdempotent: (store: IdempotencyStore, scope: string, ke
477
499
  /** Record a completed response for replay. */
478
500
  export declare const finishIdempotent: (store: IdempotencyStore, scope: string, key: string, response: IdempotencyResponse, now: number) => Promise<void>;
479
501
 
502
+ /** The currently-registered resource-scope resolver, or `undefined`. */
503
+ export declare const getResourceScopeResolver: () => ResourceScopeResolver | undefined;
504
+
480
505
  export declare interface GuardCheckSpec {
481
506
  readonly scope: string | ReadonlyArray<string>;
482
507
  readonly mode?: 'all' | 'any';
508
+ /**
509
+ * PURE `input → resource id` extractor (the erased runtime form of
510
+ * `GuardSpec.resource`). When present AND a resource-aware resolver is
511
+ * registered (`setResourceScopeResolver`), the guard is checked against THAT
512
+ * resource, not just the caller's global scopes. Absent / no resolver →
513
+ * global-scope check (the extractor is advisory), exactly as before.
514
+ */
515
+ readonly resource?: (input: unknown) => string | undefined;
483
516
  }
484
517
 
485
518
  /** One or more declarative guards on a descriptor. All must pass (AND across
@@ -617,7 +650,7 @@ export declare interface IdempotencyStore {
617
650
  * corrupt the pointer. */
618
651
  export declare const idToPath: (id: RowId) => string;
619
652
 
620
- export declare interface InsertTarget<Input = unknown, Row = unknown> extends NestedTargetFields<Input> {
653
+ export declare interface InsertTarget<Input = unknown, Row = unknown, Item = Record<string, unknown>> extends NestedTargetFields<Input> {
621
654
  readonly table: string;
622
655
  readonly op: 'insert';
623
656
  readonly order?: 'prepend' | 'append' | undefined;
@@ -635,9 +668,13 @@ export declare interface InsertTarget<Input = unknown, Row = unknown> extends Ne
635
668
  *
636
669
  * The `optimisticId` parameter is exposed for rare cases where the
637
670
  * shape function needs to reference it (e.g., setting a foreign key
638
- * on a child row spread in the same optimistic insert).
671
+ * on a child row spread in the same optimistic insert). For a NESTED
672
+ * (`path`) insert, use `shapeItem` instead — it is typed to the item.
639
673
  */
640
674
  readonly shape?: ((input: Input, optimisticId: string) => Omit<Row, 'id' | 'optimistic'>) | undefined;
675
+ /** NESTED (`path`) insert: build the ITEM to insert, typed to the item (not
676
+ * the output). 2nd arg is the optimistic id. */
677
+ readonly shapeItem?: ((input: Input, optimisticId: string) => Item) | undefined;
641
678
  }
642
679
 
643
680
  /** True when every row in the set carries an `id`. The dispatcher uses
@@ -1440,6 +1477,25 @@ export declare const queryToRpc: <Name extends string, Input extends Schema.Sche
1440
1477
  * Checks the EFFECTIVE set so role-derived scopes count. */
1441
1478
  export declare const requireScope: (subject: Subject, scope: string) => Effect.Effect<void, ScopeError>;
1442
1479
 
1480
+ /** The question the runtime asks a registered resource-scope resolver. */
1481
+ export declare interface ResourceScopeRequest {
1482
+ /** The authenticated caller. */
1483
+ readonly subject: Subject;
1484
+ /** The single scope being checked (guards with a scope array ask once per scope). */
1485
+ readonly scope: string;
1486
+ /** The resource id the guard's `resource` extractor produced (e.g. a teamId). */
1487
+ readonly resource: string;
1488
+ }
1489
+
1490
+ /**
1491
+ * A process-global resolver that answers "does `subject` hold `scope` on
1492
+ * `resource`". Registered once at boot via `setResourceScopeResolver`. Returns
1493
+ * an Effect so it can read the app's role tables. It should NOT leak errors —
1494
+ * `checkGuardsEffect` treats a failed resolver as a DENIAL (fail-closed), so a
1495
+ * resolver that wants a different posture must catch its own errors.
1496
+ */
1497
+ export declare type ResourceScopeResolver = (req: ResourceScopeRequest) => Effect.Effect<boolean, unknown>;
1498
+
1443
1499
  /** The id of a row, addressed in op paths as `/<id>`. */
1444
1500
  export declare type RowId = string | number;
1445
1501
 
@@ -1680,6 +1736,14 @@ export declare type ServerErrorSource = 'rest' | 'aggregate' | 'subscriber' | 'r
1680
1736
  */
1681
1737
  export declare const setEffectiveScopes: (subject: Subject, scopes: ReadonlyArray<string>) => void;
1682
1738
 
1739
+ /**
1740
+ * Register (or clear, with `undefined`) the process-global resource-scope
1741
+ * resolver. Call once at boot — from `@voltro/plugin-rbac`'s wiring, or directly
1742
+ * from an app that resolves per-resource permissions against its own tables.
1743
+ * Last write wins.
1744
+ */
1745
+ export declare const setResourceScopeResolver: (resolver: ResourceScopeResolver | undefined) => void;
1746
+
1683
1747
  /** A strategy's verdict on a request.
1684
1748
  * - `matched`: this strategy claims the request; here's the Subject.
1685
1749
  * - `skip`: not my request (e.g. cookie absent); try next strategy.
@@ -2028,13 +2092,19 @@ export declare const undoRedoDescriptor: MutationProcedureDescriptor<"__voltro.u
2028
2092
  ok: typeof Schema.Boolean;
2029
2093
  }>, Schema.Union<[typeof UndoNotFound, typeof UndoForbidden, typeof UndoConflict]>>;
2030
2094
 
2031
- export declare interface UpdateTarget<Input = unknown, Row = unknown> extends NestedTargetFields<Input> {
2095
+ export declare interface UpdateTarget<Input = unknown, Row = unknown, Item = Record<string, unknown>> extends NestedTargetFields<Input> {
2032
2096
  readonly table: string;
2033
2097
  readonly op: 'update';
2034
- /** Identify the row to patch. Default: `input.id`. */
2035
- readonly identify?: ((input: Input) => string) | undefined;
2036
- /** Build the patch. Default: merges input over current. */
2098
+ /** Identify the row(s) to patch. Default: `input.id`. Return an ARRAY to patch
2099
+ * MANY rows/items in one mutation (a bulk edit where the per-item
2100
+ * parallel-write race lived). */
2101
+ readonly identify?: ((input: Input) => string | ReadonlyArray<string>) | undefined;
2102
+ /** Build the patch for a FLAT target (`current` is the OUTPUT row). Default:
2103
+ * merges input over current. For a NESTED (`path`) target use `shapeItem`. */
2037
2104
  readonly shape?: ((input: Input, current: Row) => Row) | undefined;
2105
+ /** NESTED (`path`) update: build the item patch. `current` is the existing
2106
+ * ITEM (not the mutation output), so no cast is needed. */
2107
+ readonly shapeItem?: ((input: Input, current: Item) => Item) | undefined;
2038
2108
  }
2039
2109
 
2040
2110
  export declare interface VoltroPlugin {
package/dist/index.js CHANGED
@@ -1,30 +1,30 @@
1
- import { a as e, c as t, d as n, f as r, g as i, h as a, i as o, l as s, m as ee, n as te, o as ne, p as re, r as ie, s as ae, t as oe, u as se } from "./serverErrorBus-BrqfEV84.js";
2
- import { a as ce, c as le, d as ue, f as de, i as fe, l as pe, n as me, o as he, r as ge, s as c, t as _e, u as ve } from "./auth-DCE6m7Bo.js";
3
- import { Context as ye, Layer as be, Schema as l } from "effect";
4
- import { Rpc as u } from "@effect/rpc";
1
+ import { _ as e, a as t, c as n, d as r, f as i, g as a, h as o, i as ee, l as s, m as te, n as ne, o as re, p as ie, r as ae, s as oe, t as c, u as se, v as ce, y as le } from "./serverErrorBus-0wjvKwGO.js";
2
+ import { a as ue, c as de, d as fe, f as pe, i as me, l as he, n as ge, o as _e, r as ve, s as ye, t as be, u as l } from "./auth-DCE6m7Bo.js";
3
+ import { Context as u, Layer as xe, Schema as d } from "effect";
4
+ import { Rpc as f } from "@effect/rpc";
5
5
  //#region src/rowPatch.ts
6
- var xe = l.Union(l.String, l.Number), d = l.Record({
7
- key: l.String,
8
- value: l.Unknown
9
- }).pipe(l.filter((e) => "id" in e, { message: () => "patch row must carry an id" })), f = l.Union(l.Struct({
10
- op: l.Literal("add"),
11
- path: l.String,
12
- value: d
13
- }), l.Struct({
14
- op: l.Literal("replace"),
15
- path: l.String,
16
- value: d
17
- }), l.Struct({
18
- op: l.Literal("remove"),
19
- path: l.String
20
- })), p = l.Struct({
21
- ops: l.Array(f),
22
- order: l.Array(xe)
23
- }), m = (e) => `/${String(e).replace(/~/g, "~0").replace(/\//g, "~1")}`, Se = (e) => (e.startsWith("/") ? e.slice(1) : e).replace(/~1/g, "/").replace(/~0/g, "~"), h = (e) => {
6
+ var Se = d.Union(d.String, d.Number), p = d.Record({
7
+ key: d.String,
8
+ value: d.Unknown
9
+ }).pipe(d.filter((e) => "id" in e, { message: () => "patch row must carry an id" })), m = d.Union(d.Struct({
10
+ op: d.Literal("add"),
11
+ path: d.String,
12
+ value: p
13
+ }), d.Struct({
14
+ op: d.Literal("replace"),
15
+ path: d.String,
16
+ value: p
17
+ }), d.Struct({
18
+ op: d.Literal("remove"),
19
+ path: d.String
20
+ })), h = d.Struct({
21
+ ops: d.Array(m),
22
+ order: d.Array(Se)
23
+ }), g = (e) => `/${String(e).replace(/~/g, "~0").replace(/\//g, "~1")}`, Ce = (e) => (e.startsWith("/") ? e.slice(1) : e).replace(/~1/g, "/").replace(/~0/g, "~"), _ = (e) => {
24
24
  let t = Object.keys(e).sort(), n = {};
25
25
  for (let r of t) n[r] = e[r];
26
26
  return JSON.stringify(n);
27
- }, Ce = (e, t) => h(e) === h(t), g = (e, t) => {
27
+ }, we = (e, t) => _(e) === _(t), Te = (e, t) => {
28
28
  let n = /* @__PURE__ */ new Map();
29
29
  for (let t of e) n.set(t.id, t);
30
30
  let r = [], i = [], a = /* @__PURE__ */ new Set();
@@ -33,26 +33,26 @@ var xe = l.Union(l.String, l.Number), d = l.Record({
33
33
  let t = n.get(e.id);
34
34
  t === void 0 ? r.push({
35
35
  op: "add",
36
- path: m(e.id),
36
+ path: g(e.id),
37
37
  value: e
38
- }) : Ce(t, e) || r.push({
38
+ }) : we(t, e) || r.push({
39
39
  op: "replace",
40
- path: m(e.id),
40
+ path: g(e.id),
41
41
  value: e
42
42
  });
43
43
  }
44
44
  for (let t of e) a.has(t.id) || r.push({
45
45
  op: "remove",
46
- path: m(t.id)
46
+ path: g(t.id)
47
47
  });
48
48
  return {
49
49
  ops: r,
50
50
  order: i
51
51
  };
52
- }, we = (e) => e.every((e) => {
52
+ }, Ee = (e) => e.every((e) => {
53
53
  let t = e.id;
54
54
  return typeof t == "string" || typeof t == "number";
55
- }), Te = (e, t) => {
55
+ }), De = (e, t) => {
56
56
  let n = /* @__PURE__ */ new Map();
57
57
  for (let t of e) n.set(t.id, t);
58
58
  for (let e of t.ops) (e.op === "add" || e.op === "replace") && n.set(e.value.id, e.value);
@@ -62,82 +62,82 @@ var xe = l.Union(l.String, l.Number), d = l.Record({
62
62
  t !== void 0 && r.push(t);
63
63
  }
64
64
  return r;
65
- }, _ = (e) => l.Union(l.Struct({
66
- _tag: l.Literal("snapshot"),
67
- revision: l.Number,
65
+ }, v = (e) => d.Union(d.Struct({
66
+ _tag: d.Literal("snapshot"),
67
+ revision: d.Number,
68
68
  data: e,
69
- computed: l.optional(l.Boolean)
70
- }), l.Struct({
71
- _tag: l.Literal("delta"),
72
- revision: l.Number,
73
- emittedAt: l.Number,
74
- patch: p
75
- }), l.Struct({
76
- _tag: l.Literal("error"),
77
- error: l.Unknown,
78
- revision: l.optional(l.Number)
79
- })), v = (e) => ({
69
+ computed: d.optional(d.Boolean)
70
+ }), d.Struct({
71
+ _tag: d.Literal("delta"),
72
+ revision: d.Number,
73
+ emittedAt: d.Number,
74
+ patch: h
75
+ }), d.Struct({
76
+ _tag: d.Literal("error"),
77
+ error: d.Unknown,
78
+ revision: d.optional(d.Number)
79
+ })), y = (e) => ({
80
80
  kind: "query",
81
81
  name: e.name,
82
82
  input: e.input,
83
83
  output: e.output,
84
- error: e.error ?? l.Never,
84
+ error: e.error ?? d.Never,
85
85
  source: e.source,
86
86
  cache: e.cache,
87
87
  guards: e.guards,
88
88
  publicApi: e.publicApi,
89
89
  exposeAsTool: e.exposeAsTool
90
- }), y = (e) => ({
90
+ }), b = (e) => ({
91
91
  kind: "mutation",
92
92
  name: e.name,
93
93
  input: e.input,
94
94
  output: e.output,
95
- error: e.error ?? l.Never,
95
+ error: e.error ?? d.Never,
96
96
  target: e.target,
97
97
  guards: e.guards,
98
98
  publicApi: e.publicApi,
99
99
  exposeAsTool: e.exposeAsTool
100
- }), b = (e) => ({
100
+ }), x = (e) => ({
101
101
  kind: "action",
102
102
  name: e.name,
103
103
  input: e.input,
104
104
  output: e.output,
105
- error: e.error ?? l.Never,
105
+ error: e.error ?? d.Never,
106
106
  guards: e.guards,
107
107
  publicApi: e.publicApi,
108
108
  exposeAsTool: e.exposeAsTool
109
- }), Ee = (e) => ({
109
+ }), Oe = (e) => ({
110
110
  kind: "stream",
111
111
  name: e.name,
112
112
  input: e.input,
113
113
  element: e.element,
114
- error: e.error ?? l.Never
115
- }), x = (e, t) => t && t.length > 0 ? l.Union(e, ...t) : e, S = (e, t) => t && t.length > 0 ? l.Union(e, s) : e, C = (e, t) => u.make(e.name, {
114
+ error: e.error ?? d.Never
115
+ }), S = (e, t) => t && t.length > 0 ? d.Union(e, ...t) : e, C = (e, t) => t && t.length > 0 ? d.Union(e, s) : e, w = (e, t) => f.make(e.name, {
116
116
  payload: e.input,
117
- success: _(e.output),
118
- error: x(S(e.error, e.guards), t),
117
+ success: v(e.output),
118
+ error: S(C(e.error, e.guards), t),
119
119
  stream: !0
120
- }), w = (e, t) => u.make(e.name, {
120
+ }), T = (e, t) => f.make(e.name, {
121
121
  payload: e.input,
122
122
  success: e.output,
123
- error: x(S(e.error, e.guards), t)
124
- }), T = (e, t) => u.make(e.name, {
123
+ error: S(C(e.error, e.guards), t)
124
+ }), E = (e, t) => f.make(e.name, {
125
125
  payload: e.input,
126
126
  success: e.output,
127
- error: x(S(e.error, e.guards), t)
128
- }), E = (e, t) => u.make(e.name, {
127
+ error: S(C(e.error, e.guards), t)
128
+ }), D = (e, t) => f.make(e.name, {
129
129
  payload: e.input,
130
130
  success: e.element,
131
- error: x(e.error, t),
131
+ error: S(e.error, t),
132
132
  stream: !0
133
- }), D = (e) => {
133
+ }), ke = (e) => {
134
134
  switch (e.kind) {
135
- case "query": return C(e);
136
- case "mutation": return w(e);
137
- case "action": return T(e);
138
- case "stream": return E(e);
135
+ case "query": return w(e);
136
+ case "mutation": return T(e);
137
+ case "action": return E(e);
138
+ case "stream": return D(e);
139
139
  }
140
- }, De = (e) => {
140
+ }, Ae = (e) => {
141
141
  let t = e.input, n = t === void 0 ? {} : { input: t }, r = e.output, i = r === void 0 ? {} : { output: r };
142
142
  if (e.kind === "query") return {
143
143
  kind: "query",
@@ -174,18 +174,19 @@ var xe = l.Union(l.String, l.Number), d = l.Record({
174
174
  ..."identify" in e && e.identify !== void 0 ? { identify: e.identify } : {},
175
175
  ..."path" in e && e.path !== void 0 ? { path: e.path } : {},
176
176
  ..."by" in e && e.by !== void 0 ? { by: e.by } : {},
177
- ..."match" in e && e.match !== void 0 ? { match: e.match } : {}
177
+ ..."match" in e && e.match !== void 0 ? { match: e.match } : {},
178
+ ..."shapeItem" in e && e.shapeItem !== void 0 ? { shapeItem: e.shapeItem } : {}
178
179
  }))
179
180
  };
180
- }, Oe = (e) => e, ke = (e) => e, Ae = (e) => {
181
+ }, je = (e) => e, Me = (e) => e, Ne = (e) => {
181
182
  if (e.length !== 0) return (t, n) => e.reduceRight((e, t) => t(e, n), t);
182
- }, je = (e, t) => {
183
- let n = ye.GenericTag(e);
183
+ }, Pe = (e, t) => {
184
+ let n = u.GenericTag(e);
184
185
  return {
185
186
  Tag: n,
186
- Live: be.succeed(n, t)
187
+ Live: xe.succeed(n, t)
187
188
  };
188
- }, Me = (e, t, n) => {
189
+ }, Fe = (e, t, n) => {
189
190
  if (!t) return { ok: !0 };
190
191
  let r = O(n);
191
192
  if (!r) return {
@@ -195,7 +196,7 @@ var xe = l.Union(l.String, l.Number), d = l.Record({
195
196
  let i = t.trim();
196
197
  if (i === "*" || i === "") return { ok: !0 };
197
198
  let a = i.split(/\s+/).filter((e) => e.length > 0);
198
- for (let i of a) if (!Ne(i, r)) return {
199
+ for (let i of a) if (!Ie(i, r)) return {
199
200
  ok: !1,
200
201
  reason: `plugin "${e}" requires framework ${t}, running ${n}`
201
202
  };
@@ -208,7 +209,7 @@ var xe = l.Union(l.String, l.Number), d = l.Record({
208
209
  patch: Number(t[3]),
209
210
  pre: t[4] ?? ""
210
211
  } : null;
211
- }, k = (e, t) => e.major === t.major ? e.minor === t.minor ? e.patch === t.patch ? e.pre && !t.pre ? -1 : !e.pre && t.pre ? 1 : e.pre && t.pre ? e.pre < t.pre ? -1 : +(e.pre > t.pre) : 0 : e.patch - t.patch : e.minor - t.minor : e.major - t.major, Ne = (e, t) => {
212
+ }, k = (e, t) => e.major === t.major ? e.minor === t.minor ? e.patch === t.patch ? e.pre && !t.pre ? -1 : !e.pre && t.pre ? 1 : e.pre && t.pre ? e.pre < t.pre ? -1 : +(e.pre > t.pre) : 0 : e.patch - t.patch : e.minor - t.minor : e.major - t.major, Ie = (e, t) => {
212
213
  if (e === "*") return !0;
213
214
  if (e.startsWith("^")) {
214
215
  let n = O(e.slice(1));
@@ -230,173 +231,173 @@ var xe = l.Union(l.String, l.Number), d = l.Record({
230
231
  }
231
232
  let r = O(e);
232
233
  return r ? k(t, r) === 0 : !1;
233
- }, A = l.Literal("running", "succeeded", "failed", "cancelled", "suspended"), j = l.Literal("cancel", "terminate", "abandon"), Pe = l.Struct({
234
- id: l.String,
235
- workflowName: l.String,
236
- executionId: l.String,
237
- status: l.Literal("running")
238
- }), M = l.Struct({
239
- id: l.String,
240
- tag: l.String,
241
- executionId: l.String,
234
+ }, A = d.Literal("running", "succeeded", "failed", "cancelled", "suspended"), j = d.Literal("cancel", "terminate", "abandon"), Le = d.Struct({
235
+ id: d.String,
236
+ workflowName: d.String,
237
+ executionId: d.String,
238
+ status: d.Literal("running")
239
+ }), M = d.Struct({
240
+ id: d.String,
241
+ tag: d.String,
242
+ executionId: d.String,
242
243
  status: A,
243
- payload: l.Unknown,
244
- workflowVersion: l.NullOr(l.String),
245
- workflowPatches: l.NullOr(l.Unknown),
246
- output: l.NullOr(l.Unknown),
247
- subject: l.NullOr(l.Unknown),
248
- source: l.NullOr(l.String),
249
- errorTag: l.NullOr(l.String),
250
- errorMessage: l.NullOr(l.String),
251
- cancelled: l.Boolean,
252
- startedAt: l.Date,
253
- completedAt: l.NullOr(l.Date),
254
- durationMs: l.NullOr(l.Number),
255
- traceId: l.NullOr(l.String),
256
- parentExecutionId: l.NullOr(l.String),
257
- parentClosePolicy: l.NullOr(j)
258
- }), N = l.Struct({
259
- tag: l.optional(l.String),
260
- status: l.optional(A),
261
- limit: l.optional(l.Number)
262
- }), P = l.Struct({
263
- id: l.String,
264
- runId: l.String,
265
- stepName: l.String,
266
- attempt: l.Number,
267
- status: l.Literal("running", "succeeded", "failed"),
268
- input: l.NullOr(l.Unknown),
269
- retryPolicy: l.NullOr(l.Unknown),
270
- output: l.NullOr(l.Unknown),
271
- errorTag: l.NullOr(l.String),
272
- errorMessage: l.NullOr(l.String),
273
- errorCause: l.NullOr(l.Unknown),
274
- startedAt: l.Date,
275
- completedAt: l.NullOr(l.Date),
276
- durationMs: l.NullOr(l.Number)
277
- }), F = l.Struct({
278
- id: l.String,
279
- runId: l.String,
280
- eventType: l.String,
281
- payload: l.NullOr(l.Unknown),
282
- occurredAt: l.Date,
283
- stepName: l.NullOr(l.String),
284
- attempt: l.NullOr(l.Number)
285
- }), I = l.Struct({
286
- id: l.String,
287
- name: l.String,
288
- payload: l.Unknown,
289
- source: l.String,
290
- subject: l.NullOr(l.Unknown),
291
- traceId: l.NullOr(l.String),
292
- occurredAt: l.Date
293
- }), L = l.Struct({
294
- id: l.String,
295
- eventId: l.String,
296
- eventName: l.String,
297
- triggerId: l.String,
298
- workflowName: l.String,
299
- executionId: l.NullOr(l.String),
300
- status: l.Literal("starting", "started", "skipped", "failed"),
301
- idempotencyKey: l.String,
302
- skipped: l.Boolean,
303
- errorMessage: l.NullOr(l.String),
304
- createdAt: l.Date,
305
- completedAt: l.NullOr(l.Date)
306
- }), R = l.Struct({ id: l.String }), z = l.Struct({ runId: l.String }), B = l.Struct({
307
- name: l.optional(l.String),
308
- limit: l.optional(l.Number)
309
- }), V = l.Struct({ eventId: l.String }), H = l.Struct({
310
- workflowName: l.String,
311
- executionId: l.String
312
- }), U = l.Struct({
313
- id: l.String,
314
- signalName: l.String,
315
- payload: l.optional(l.Unknown)
316
- }), W = l.Struct({
317
- id: l.String,
318
- updateName: l.String,
319
- payload: l.optional(l.Unknown),
320
- timeoutMs: l.optional(l.Number)
321
- }), G = l.Struct({
322
- eventId: l.String,
323
- updateId: l.String,
324
- completedEventId: l.String,
325
- result: l.Unknown
326
- }), Fe = v({
244
+ payload: d.Unknown,
245
+ workflowVersion: d.NullOr(d.String),
246
+ workflowPatches: d.NullOr(d.Unknown),
247
+ output: d.NullOr(d.Unknown),
248
+ subject: d.NullOr(d.Unknown),
249
+ source: d.NullOr(d.String),
250
+ errorTag: d.NullOr(d.String),
251
+ errorMessage: d.NullOr(d.String),
252
+ cancelled: d.Boolean,
253
+ startedAt: d.Date,
254
+ completedAt: d.NullOr(d.Date),
255
+ durationMs: d.NullOr(d.Number),
256
+ traceId: d.NullOr(d.String),
257
+ parentExecutionId: d.NullOr(d.String),
258
+ parentClosePolicy: d.NullOr(j)
259
+ }), N = d.Struct({
260
+ tag: d.optional(d.String),
261
+ status: d.optional(A),
262
+ limit: d.optional(d.Number)
263
+ }), P = d.Struct({
264
+ id: d.String,
265
+ runId: d.String,
266
+ stepName: d.String,
267
+ attempt: d.Number,
268
+ status: d.Literal("running", "succeeded", "failed"),
269
+ input: d.NullOr(d.Unknown),
270
+ retryPolicy: d.NullOr(d.Unknown),
271
+ output: d.NullOr(d.Unknown),
272
+ errorTag: d.NullOr(d.String),
273
+ errorMessage: d.NullOr(d.String),
274
+ errorCause: d.NullOr(d.Unknown),
275
+ startedAt: d.Date,
276
+ completedAt: d.NullOr(d.Date),
277
+ durationMs: d.NullOr(d.Number)
278
+ }), F = d.Struct({
279
+ id: d.String,
280
+ runId: d.String,
281
+ eventType: d.String,
282
+ payload: d.NullOr(d.Unknown),
283
+ occurredAt: d.Date,
284
+ stepName: d.NullOr(d.String),
285
+ attempt: d.NullOr(d.Number)
286
+ }), I = d.Struct({
287
+ id: d.String,
288
+ name: d.String,
289
+ payload: d.Unknown,
290
+ source: d.String,
291
+ subject: d.NullOr(d.Unknown),
292
+ traceId: d.NullOr(d.String),
293
+ occurredAt: d.Date
294
+ }), L = d.Struct({
295
+ id: d.String,
296
+ eventId: d.String,
297
+ eventName: d.String,
298
+ triggerId: d.String,
299
+ workflowName: d.String,
300
+ executionId: d.NullOr(d.String),
301
+ status: d.Literal("starting", "started", "skipped", "failed"),
302
+ idempotencyKey: d.String,
303
+ skipped: d.Boolean,
304
+ errorMessage: d.NullOr(d.String),
305
+ createdAt: d.Date,
306
+ completedAt: d.NullOr(d.Date)
307
+ }), R = d.Struct({ id: d.String }), z = d.Struct({ runId: d.String }), B = d.Struct({
308
+ name: d.optional(d.String),
309
+ limit: d.optional(d.Number)
310
+ }), V = d.Struct({ eventId: d.String }), H = d.Struct({
311
+ workflowName: d.String,
312
+ executionId: d.String
313
+ }), U = d.Struct({
314
+ id: d.String,
315
+ signalName: d.String,
316
+ payload: d.optional(d.Unknown)
317
+ }), W = d.Struct({
318
+ id: d.String,
319
+ updateName: d.String,
320
+ payload: d.optional(d.Unknown),
321
+ timeoutMs: d.optional(d.Number)
322
+ }), G = d.Struct({
323
+ eventId: d.String,
324
+ updateId: d.String,
325
+ completedEventId: d.String,
326
+ result: d.Unknown
327
+ }), Re = y({
327
328
  name: "__voltro.workflow.run",
328
329
  source: "_voltro_workflow_runs",
329
330
  input: R,
330
- output: l.Array(M)
331
- }), Ie = v({
331
+ output: d.Array(M)
332
+ }), ze = y({
332
333
  name: "__voltro.workflow.runs",
333
334
  source: "_voltro_workflow_runs",
334
335
  input: N,
335
- output: l.Array(M)
336
- }), Le = v({
336
+ output: d.Array(M)
337
+ }), Be = y({
337
338
  name: "__voltro.workflow.run.steps",
338
339
  source: "_voltro_workflow_run_steps",
339
340
  input: z,
340
- output: l.Array(P)
341
- }), Re = v({
341
+ output: d.Array(P)
342
+ }), Ve = y({
342
343
  name: "__voltro.workflow.run.events",
343
344
  source: "_voltro_workflow_run_events",
344
345
  input: z,
345
- output: l.Array(F)
346
- }), ze = v({
346
+ output: d.Array(F)
347
+ }), He = y({
347
348
  name: "__voltro.workflow.domainEvents",
348
349
  source: "_voltro_workflow_events",
349
350
  input: B,
350
- output: l.Array(I)
351
- }), Be = v({
351
+ output: d.Array(I)
352
+ }), Ue = y({
352
353
  name: "__voltro.workflow.event.deliveries",
353
354
  source: "_voltro_workflow_event_deliveries",
354
355
  input: V,
355
- output: l.Array(L)
356
- }), Ve = b({
356
+ output: d.Array(L)
357
+ }), We = x({
357
358
  name: "__voltro.workflow.cancel",
358
359
  input: H,
359
- output: l.Struct({ ok: l.Boolean })
360
- }), He = b({
360
+ output: d.Struct({ ok: d.Boolean })
361
+ }), Ge = x({
361
362
  name: "__voltro.workflow.resume",
362
363
  input: H,
363
- output: l.Struct({ ok: l.Boolean })
364
- }), Ue = b({
364
+ output: d.Struct({ ok: d.Boolean })
365
+ }), Ke = x({
365
366
  name: "__voltro.workflow.signal",
366
367
  input: U,
367
- output: l.Struct({ eventId: l.String })
368
- }), We = b({
368
+ output: d.Struct({ eventId: d.String })
369
+ }), qe = x({
369
370
  name: "__voltro.workflow.update",
370
371
  input: W,
371
372
  output: G
372
- }), K = "__voltro.undo.log", q = "__voltro.undo.apply", J = "__voltro.undo.redo", Y = l.Struct({
373
- id: l.String,
374
- tag: l.String,
375
- label: l.NullOr(l.String),
376
- undone: l.Boolean,
377
- crossesAction: l.Boolean,
378
- createdAt: l.String
379
- }), X = class extends l.TaggedError()("UndoNotFound", { invocationId: l.String }) {}, Z = class extends l.TaggedError()("UndoForbidden", { invocationId: l.String }) {}, Q = class extends l.TaggedError()("UndoConflict", {
380
- invocationId: l.String,
381
- reason: l.Literal("conflict", "action")
382
- }) {}, $ = l.Union(X, Z, Q), Ge = v({
373
+ }), K = "__voltro.undo.log", q = "__voltro.undo.apply", J = "__voltro.undo.redo", Y = d.Struct({
374
+ id: d.String,
375
+ tag: d.String,
376
+ label: d.NullOr(d.String),
377
+ undone: d.Boolean,
378
+ crossesAction: d.Boolean,
379
+ createdAt: d.String
380
+ }), X = class extends d.TaggedError()("UndoNotFound", { invocationId: d.String }) {}, Z = class extends d.TaggedError()("UndoForbidden", { invocationId: d.String }) {}, Q = class extends d.TaggedError()("UndoConflict", {
381
+ invocationId: d.String,
382
+ reason: d.Literal("conflict", "action")
383
+ }) {}, $ = d.Union(X, Z, Q), Je = y({
383
384
  name: K,
384
385
  source: "_voltro_undo_log",
385
- input: l.Struct({ limit: l.optional(l.Number) }),
386
- output: l.Array(Y)
387
- }), Ke = y({
386
+ input: d.Struct({ limit: d.optional(d.Number) }),
387
+ output: d.Array(Y)
388
+ }), Ye = b({
388
389
  name: q,
389
- input: l.Struct({ invocationId: l.String }),
390
- output: l.Struct({ ok: l.Boolean }),
390
+ input: d.Struct({ invocationId: d.String }),
391
+ output: d.Struct({ ok: d.Boolean }),
391
392
  error: $
392
- }), qe = y({
393
+ }), Xe = b({
393
394
  name: J,
394
- input: l.Struct({ invocationId: l.String }),
395
- output: l.Struct({ ok: l.Boolean }),
395
+ input: d.Struct({ invocationId: d.String }),
396
+ output: d.Struct({ ok: d.Boolean }),
396
397
  error: $
397
- }), Je = (e) => {
398
+ }), Ze = (e) => {
398
399
  let t = e instanceof Date ? e.getTime() : typeof e == "number" ? e : typeof e == "string" ? new Date(e).getTime() : 0;
399
400
  return Number.isNaN(t) ? 0 : t;
400
- }, Ye = 1;
401
+ }, Qe = 1;
401
402
  //#endregion
402
- export { t as ADMIN_SCOPE, _e as AuthMiddleware, me as ConnectionInfo, ge as ConnectionInfoMiddleware, Ye as PROTOCOL_VERSION, s as ScopeError, fe as Subject, ce as SubjectService, q as UNDO_APPLY_TAG, K as UNDO_LOG_TAG, J as UNDO_REDO_TAG, he as Unauthenticated, Q as UndoConflict, Z as UndoForbidden, Y as UndoLogEntry, X as UndoNotFound, H as WorkflowControlInputSchema, I as WorkflowDomainEventRowSchema, B as WorkflowDomainEventsInputSchema, V as WorkflowEventDeliveriesInputSchema, L as WorkflowEventDeliveryRowSchema, j as WorkflowParentClosePolicySchema, F as WorkflowRunEventRowSchema, Pe as WorkflowRunHandleSchema, R as WorkflowRunRefSchema, M as WorkflowRunRowSchema, A as WorkflowRunStatusSchema, P as WorkflowRunStepRowSchema, z as WorkflowRunTableRefSchema, N as WorkflowRunsInputSchema, U as WorkflowSignalInputSchema, W as WorkflowUpdateInputSchema, G as WorkflowUpdateResultSchema, T as actionToRpc, c as anonymousSubject, Te as applyRowPatch, le as assertAuthenticated, ie as beginIdempotent, Me as checkFrameworkCompat, se as checkGuards, pe as composeAuthStrategies, Ae as composeRpcInterceptors, b as defineAction, y as defineMutation, Oe as definePlugin, ke as definePluginRoute, je as definePluginService, v as defineQuery, Ee as defineStream, g as diffRows, n as effectiveScopes, o as failIdempotent, e as finishIdempotent, ve as hasCallbackRoutes, r as hasEffectiveScope, re as hasScope, m as idToPath, ne as idempotencyScope, we as isIdKeyed, ue as isSystemSubject, ae as memoryIdempotencyStore, w as mutationToRpc, De as normalizeDescriptor, Se as pathToId, oe as publishServerError, C as queryToRpc, ee as requireScope, f as rowPatchOpSchema, p as rowPatchSchema, a as setEffectiveScopes, E as streamToRpc, i as subjectScopes, te as subscribeServerErrors, _ as subscriptionEvent, de as systemSubject, D as toRpc, Je as tsMs, Ke as undoApplyDescriptor, Ge as undoLogQueryDescriptor, qe as undoRedoDescriptor, Ve as workflowCancelDescriptor, ze as workflowDomainEventsQueryDescriptor, Be as workflowEventDeliveriesQueryDescriptor, He as workflowResumeDescriptor, Re as workflowRunEventsQueryDescriptor, Fe as workflowRunQueryDescriptor, Le as workflowRunStepsQueryDescriptor, Ie as workflowRunsQueryDescriptor, Ue as workflowSignalDescriptor, We as workflowUpdateDescriptor };
403
+ export { n as ADMIN_SCOPE, be as AuthMiddleware, ge as ConnectionInfo, ve as ConnectionInfoMiddleware, Qe as PROTOCOL_VERSION, s as ScopeError, me as Subject, ue as SubjectService, q as UNDO_APPLY_TAG, K as UNDO_LOG_TAG, J as UNDO_REDO_TAG, _e as Unauthenticated, Q as UndoConflict, Z as UndoForbidden, Y as UndoLogEntry, X as UndoNotFound, H as WorkflowControlInputSchema, I as WorkflowDomainEventRowSchema, B as WorkflowDomainEventsInputSchema, V as WorkflowEventDeliveriesInputSchema, L as WorkflowEventDeliveryRowSchema, j as WorkflowParentClosePolicySchema, F as WorkflowRunEventRowSchema, Le as WorkflowRunHandleSchema, R as WorkflowRunRefSchema, M as WorkflowRunRowSchema, A as WorkflowRunStatusSchema, P as WorkflowRunStepRowSchema, z as WorkflowRunTableRefSchema, N as WorkflowRunsInputSchema, U as WorkflowSignalInputSchema, W as WorkflowUpdateInputSchema, G as WorkflowUpdateResultSchema, E as actionToRpc, ye as anonymousSubject, De as applyRowPatch, de as assertAuthenticated, ae as beginIdempotent, Fe as checkFrameworkCompat, se as checkGuards, r as checkGuardsEffect, he as composeAuthStrategies, Ne as composeRpcInterceptors, x as defineAction, b as defineMutation, je as definePlugin, Me as definePluginRoute, Pe as definePluginService, y as defineQuery, Oe as defineStream, Te as diffRows, i as effectiveScopes, ee as failIdempotent, t as finishIdempotent, ie as getResourceScopeResolver, l as hasCallbackRoutes, te as hasEffectiveScope, o as hasScope, g as idToPath, re as idempotencyScope, Ee as isIdKeyed, fe as isSystemSubject, oe as memoryIdempotencyStore, T as mutationToRpc, Ae as normalizeDescriptor, Ce as pathToId, c as publishServerError, w as queryToRpc, a as requireScope, m as rowPatchOpSchema, h as rowPatchSchema, e as setEffectiveScopes, ce as setResourceScopeResolver, D as streamToRpc, le as subjectScopes, ne as subscribeServerErrors, v as subscriptionEvent, pe as systemSubject, ke as toRpc, Ze as tsMs, Ye as undoApplyDescriptor, Je as undoLogQueryDescriptor, Xe as undoRedoDescriptor, We as workflowCancelDescriptor, He as workflowDomainEventsQueryDescriptor, Ue as workflowEventDeliveriesQueryDescriptor, Ge as workflowResumeDescriptor, Ve as workflowRunEventsQueryDescriptor, Re as workflowRunQueryDescriptor, Be as workflowRunStepsQueryDescriptor, ze as workflowRunsQueryDescriptor, Ke as workflowSignalDescriptor, qe as workflowUpdateDescriptor };
package/dist/rest.d.ts CHANGED
@@ -32,8 +32,9 @@ export declare const defineRestRoute: <I, O>(descriptor: RestRouteDescriptor<I,
32
32
  declare interface DeleteTarget<Input = unknown> extends NestedTargetFields<Input> {
33
33
  readonly table: string;
34
34
  readonly op: 'delete';
35
- /** Identify the row to remove. Default: `input.id`. */
36
- readonly identify?: ((input: Input) => string) | undefined;
35
+ /** Identify the row(s) to remove. Default: `input.id`. Return an ARRAY to
36
+ * remove MANY rows/items in one mutation. */
37
+ readonly identify?: ((input: Input) => string | ReadonlyArray<string>) | undefined;
37
38
  }
38
39
 
39
40
  /** query→GET, mutation/action→POST, unless the spec overrides. */
@@ -129,7 +130,7 @@ declare interface IdempotencyStore {
129
130
  readonly release: (scope: string, key: string) => Promise<void>;
130
131
  }
131
132
 
132
- declare interface InsertTarget<Input = unknown, Row = unknown> extends NestedTargetFields<Input> {
133
+ declare interface InsertTarget<Input = unknown, Row = unknown, Item = Record<string, unknown>> extends NestedTargetFields<Input> {
133
134
  readonly table: string;
134
135
  readonly op: 'insert';
135
136
  readonly order?: 'prepend' | 'append' | undefined;
@@ -147,9 +148,13 @@ declare interface InsertTarget<Input = unknown, Row = unknown> extends NestedTar
147
148
  *
148
149
  * The `optimisticId` parameter is exposed for rare cases where the
149
150
  * shape function needs to reference it (e.g., setting a foreign key
150
- * on a child row spread in the same optimistic insert).
151
+ * on a child row spread in the same optimistic insert). For a NESTED
152
+ * (`path`) insert, use `shapeItem` instead — it is typed to the item.
151
153
  */
152
154
  readonly shape?: ((input: Input, optimisticId: string) => Omit<Row, 'id' | 'optimistic'>) | undefined;
155
+ /** NESTED (`path`) insert: build the ITEM to insert, typed to the item (not
156
+ * the output). 2nd arg is the optimistic id. */
157
+ readonly shapeItem?: ((input: Input, optimisticId: string) => Item) | undefined;
153
158
  }
154
159
 
155
160
  /** Extract `:name` path params by aligning the route PATTERN with the request
@@ -486,13 +491,19 @@ declare type Target<Input = unknown, Row = unknown> = TargetSpec<Input, Row> | R
486
491
 
487
492
  declare type TargetSpec<Input = unknown, Row = unknown> = InsertTarget<Input, Row> | UpdateTarget<Input, Row> | DeleteTarget<Input>;
488
493
 
489
- declare interface UpdateTarget<Input = unknown, Row = unknown> extends NestedTargetFields<Input> {
494
+ declare interface UpdateTarget<Input = unknown, Row = unknown, Item = Record<string, unknown>> extends NestedTargetFields<Input> {
490
495
  readonly table: string;
491
496
  readonly op: 'update';
492
- /** Identify the row to patch. Default: `input.id`. */
493
- readonly identify?: ((input: Input) => string) | undefined;
494
- /** Build the patch. Default: merges input over current. */
497
+ /** Identify the row(s) to patch. Default: `input.id`. Return an ARRAY to patch
498
+ * MANY rows/items in one mutation (a bulk edit where the per-item
499
+ * parallel-write race lived). */
500
+ readonly identify?: ((input: Input) => string | ReadonlyArray<string>) | undefined;
501
+ /** Build the patch for a FLAT target (`current` is the OUTPUT row). Default:
502
+ * merges input over current. For a NESTED (`path`) target use `shapeItem`. */
495
503
  readonly shape?: ((input: Input, current: Row) => Row) | undefined;
504
+ /** NESTED (`path`) update: build the item patch. `current` is the existing
505
+ * ITEM (not the mutation output), so no cast is needed. */
506
+ readonly shapeItem?: ((input: Input, current: Item) => Item) | undefined;
496
507
  }
497
508
 
498
509
  export { }
package/dist/rest.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as e, i as t, o as n, r, t as i } from "./serverErrorBus-BrqfEV84.js";
1
+ import { a as e, i as t, o as n, r, t as i } from "./serverErrorBus-0wjvKwGO.js";
2
2
  import { s as a } from "./auth-DCE6m7Bo.js";
3
3
  import { Effect as o, Schema as s } from "effect";
4
4
  //#region src/publicApi.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/protocol",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "The Voltro wire + plugin contract — defineQuery/Mutation/Action/Stream, definePlugin, sessions / JWT / API-keys, and the RPC protocol.",
5
5
  "keywords": [
6
6
  "voltro",
@@ -53,7 +53,7 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@effect/sql": "^0.51.1",
56
- "@voltro/database": "0.3.0",
56
+ "@voltro/database": "0.4.0",
57
57
  "jose": "^6.2.3"
58
58
  },
59
59
  "peerDependencies": {