@lunora/server 1.0.0-alpha.241 → 1.0.0-alpha.242

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.
Files changed (27) hide show
  1. package/dist/in-process.d.mts +1 -1
  2. package/dist/in-process.d.ts +1 -1
  3. package/dist/in-process.mjs +1 -1
  4. package/dist/index.d.mts +30 -33
  5. package/dist/index.d.ts +30 -33
  6. package/dist/index.mjs +1 -1
  7. package/dist/otel.d.mts +44 -1
  8. package/dist/otel.d.ts +44 -1
  9. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-D5N5n__-.mjs +1 -0
  10. package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-xyn3tFOE.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-B5yKLX8M.mjs} +1 -1
  11. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-n_AOEus6.mjs +1 -0
  12. package/dist/packem_shared/{assertShapesDeclareReadPolicies-CZ4i2Kw6.mjs → assertShapesDeclareReadPolicies-Bft5Rref.mjs} +1 -1
  13. package/dist/packem_shared/{bindOrm-DHtlrqCg.mjs → bindOrm-BaLnyMcd.mjs} +1 -1
  14. package/dist/packem_shared/{defineShape-XGyajryg.mjs → defineShape-DY-Pxhna.mjs} +1 -1
  15. package/dist/packem_shared/{mask-BS6m1DOh.mjs → mask-CoC2g3YT.mjs} +1 -1
  16. package/dist/packem_shared/middleware-B0gy8zjo.mjs +1 -0
  17. package/dist/packem_shared/{rls-C7NWAXH5.mjs → rls-B6clW04g.mjs} +1 -1
  18. package/dist/packem_shared/{storageRules-b8Kx8yAw.mjs → storageRules-UARYjKO0.mjs} +1 -1
  19. package/dist/packem_shared/{types.d-DYL1koQt.d.mts → types.d-BO1zQAnk.d.mts} +9 -9
  20. package/dist/packem_shared/{types.d-DYL1koQt.d.ts → types.d-BO1zQAnk.d.ts} +9 -9
  21. package/dist/rls/testing.mjs +1 -1
  22. package/dist/types.d.mts +1 -1
  23. package/dist/types.d.ts +1 -1
  24. package/package.json +2 -2
  25. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-9W5_vf8H.mjs +0 -1
  26. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-CKKVL22B.mjs +0 -1
  27. package/dist/packem_shared/middleware-uLdnmn8f.mjs +0 -1
@@ -1,5 +1,5 @@
1
1
  import { SqlExec } from '@lunora/shard-engine';
2
- import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-DYL1koQt.mjs";
2
+ import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-BO1zQAnk.mjs";
3
3
  import '@lunora/values';
4
4
  /** The kind of a registered Lunora function. */
5
5
  type FunctionKind = "action" | "mutation" | "query";
@@ -1,5 +1,5 @@
1
1
  import { SqlExec } from '@lunora/shard-engine';
2
- import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-DYL1koQt.js";
2
+ import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-BO1zQAnk.js";
3
3
  import '@lunora/values';
4
4
  /** The kind of a registered Lunora function. */
5
5
  type FunctionKind = "action" | "mutation" | "query";
@@ -1 +1 @@
1
- import{LunoraError as I}from"@lunora/errors";import{runShardMigrations as R,TransactionHeadroomTracker as h,createShardCtxDb as T,RLS_UNWRAP_SYMBOL as g}from"@lunora/shard-engine";import{beginDeferredSchedules as p}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{bindTableFacade as y}from"./packem_shared/bindOrm-DHtlrqCg.mjs";const k=e=>{if(e===null||typeof e.userId!="string"||e.userId.length===0)return{claims:null,userId:null};const{userId:r,...s}=e;return{claims:Object.keys(s).length>0?s:null,userId:r}};class S extends h{current=new h;reset(){this.current=new h}headroom(){return this.current.headroom()}recordRead(r){this.current.recordRead(r)}recordWrite(r){this.current.recordWrite(r)}}const x=(e,r)=>{const{scheduler:s,sql:a}=r,i=e;R(a,i);const c=new S,m=t=>{const n=t;for(const o of Object.keys(i.tables))n[o]=y(t,o);return t};let u=!1;const w=t=>{const n=T({auth:{identity:t.claims,userId:t.userId},enforceRls:r.enforceRls??!0,headroom:c,inTransaction:()=>u,schema:i,sql:a}),o=n[g]??n;return{database:m(n),rawDatabase:m(o)}},l=t=>{a.exec.call(a,t)};let f=Promise.resolve();return{createWriters:w,resetHeadroom:()=>{c.reset()},runInTransaction:t=>{const n=async()=>{const b=p({scheduler:s});c.reset(),l("BEGIN"),u=!0;try{const d=await t();return l("COMMIT"),u=!1,await b(!0),d}catch(d){u=!1;try{l("ROLLBACK")}catch{}throw await b(!1),d}},o=f.then(n);return f=o.then(()=>{},()=>{}),o}}},v=e=>{if(typeof e!="object"||e===null)return;const{kind:r}=e;if(r==="query"||r==="mutation"||r==="action")return r},A=(e,r,s,a,i)=>{const c=v(r);if(c!==e)throw new I("INTERNAL",`expected a registered ${e}, received a ${c??"non-function"} reference`);if(!i&&r.visibility==="internal")throw new I("INTERNAL",`This ${e} is an internal function — it is unreachable from the external RPC boundary in production. Call it through ctx.run${e.charAt(0).toUpperCase()}${e.slice(1)} from another function instead.`);return Promise.resolve(r.handler(s,a??{}))};export{x as createInProcessRuntime,v as registeredFunctionKind,k as resolveInProcessIdentity,A as runRegisteredFunction};
1
+ import{LunoraError as I}from"@lunora/errors";import{runShardMigrations as R,TransactionHeadroomTracker as h,createShardCtxDb as T,RLS_UNWRAP_SYMBOL as g}from"@lunora/shard-engine";import{beginDeferredSchedules as p}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{bindTableFacade as y}from"./packem_shared/bindOrm-BaLnyMcd.mjs";const k=e=>{if(e===null||typeof e.userId!="string"||e.userId.length===0)return{claims:null,userId:null};const{userId:r,...s}=e;return{claims:Object.keys(s).length>0?s:null,userId:r}};class S extends h{current=new h;reset(){this.current=new h}headroom(){return this.current.headroom()}recordRead(r){this.current.recordRead(r)}recordWrite(r){this.current.recordWrite(r)}}const x=(e,r)=>{const{scheduler:s,sql:a}=r,i=e;R(a,i);const c=new S,m=t=>{const n=t;for(const o of Object.keys(i.tables))n[o]=y(t,o);return t};let u=!1;const w=t=>{const n=T({auth:{identity:t.claims,userId:t.userId},enforceRls:r.enforceRls??!0,headroom:c,inTransaction:()=>u,schema:i,sql:a}),o=n[g]??n;return{database:m(n),rawDatabase:m(o)}},l=t=>{a.exec.call(a,t)};let f=Promise.resolve();return{createWriters:w,resetHeadroom:()=>{c.reset()},runInTransaction:t=>{const n=async()=>{const b=p({scheduler:s});c.reset(),l("BEGIN"),u=!0;try{const d=await t();return l("COMMIT"),u=!1,await b(!0),d}catch(d){u=!1;try{l("ROLLBACK")}catch{}throw await b(!1),d}},o=f.then(n);return f=o.then(()=>{},()=>{}),o}}},v=e=>{if(typeof e!="object"||e===null)return;const{kind:r}=e;if(r==="query"||r==="mutation"||r==="action")return r},A=(e,r,s,a,i)=>{const c=v(r);if(c!==e)throw new I("INTERNAL",`expected a registered ${e}, received a ${c??"non-function"} reference`);if(!i&&r.visibility==="internal")throw new I("INTERNAL",`This ${e} is an internal function — it is unreachable from the external RPC boundary in production. Call it through ctx.run${e.charAt(0).toUpperCase()}${e.slice(1)} from another function instead.`);return Promise.resolve(r.handler(s,a??{}))};export{x as createInProcessRuntime,v as registeredFunctionKind,k as resolveInProcessIdentity,A as runRegisteredFunction};
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, ColumnValidator, v, Id, ValidatorMap, InferValidatorMap } from '@lunora/values';
2
2
  export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
- import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, M as MutationCtx, c as RegisteredMutation, Q as QueryCtx, d as RegisteredQuery, e as DurableStreamOptions, f as RegisteredStream, F as FunctionKind, T as TableDefinition, g as RegisteredFunction, V as VectorIndexDefinition, S as Schema, h as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, i as RelationThrough, j as ThroughRelationDefinition, O as OnDeleteAction, k as RelationDefinition, l as SearchLanguage, m as SearchStrategy, n as ExternalSourceDefinition, o as TriggerBuilder, p as TriggerDefinition, q as VectorEmbedder, r as VectorMetric, s as DurableObjectJurisdiction, t as AggregateIndexDefinition, u as RankIndexDefinition, v as Secrets, w as LiveTopicRef, x as LifecycleEvent, y as ShardInitEvent, z as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-DYL1koQt.mjs";
4
- export type { B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, Z as IndexDefinition, _ as IndexRangeBuilder, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, a5 as MutationStorage, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, a9 as RankSortKey, aa as ReadOnlyStorage, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, an as SearchFilterBuilder, ao as SearchIndexDefinition, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, aN as TableReader, aO as TableVectorIndex, aP as TriggerAggregateOptions, aQ as TriggerCtx, aR as TriggerDatabase, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, b6 as VectorMatch, b7 as VectorMatches, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows } from "./packem_shared/types.d-DYL1koQt.mjs";
3
+ import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, M as MutationCtx, c as RegisteredMutation, Q as QueryCtx, d as RegisteredQuery, e as DurableStreamOptions, f as RegisteredStream, F as FunctionKind, T as TableDefinition, g as RegisteredFunction, V as VectorIndexDefinition, S as Schema, h as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, i as RelationThrough, j as ThroughRelationDefinition, O as OnDeleteAction, k as RelationDefinition, l as SearchLanguage, m as SearchStrategy, n as ExternalSourceDefinition, o as TriggerBuilder, p as TriggerDefinition, q as VectorEmbedder, r as VectorMetric, s as DurableObjectJurisdiction, t as AggregateIndexDefinition, u as RankIndexDefinition, v as Secrets, w as LiveTopicRef, x as LifecycleEvent, y as ShardInitEvent, z as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-BO1zQAnk.mjs";
4
+ export type { B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, Z as IndexDefinition, _ as IndexRangeBuilder, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, a5 as MutationStorage, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, a9 as RankSortKey, aa as ReadOnlyStorage, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, an as SearchFilterBuilder, ao as SearchIndexDefinition, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, aN as TableReader, aO as TableVectorIndex, aP as TriggerAggregateOptions, aQ as TriggerCtx, aR as TriggerDatabase, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, b6 as VectorMatch, b7 as VectorMatches, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows } from "./packem_shared/types.d-BO1zQAnk.mjs";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono, ExecutionContext } from 'hono';
@@ -1110,9 +1110,9 @@ interface ActionCacheQuery {
1110
1110
  * directly.
1111
1111
  */
1112
1112
  interface ActionCacheDatabase {
1113
- delete: <T extends string>(id: Id<T>) => Promise<void>;
1113
+ delete: <T extends string>(table: T, id: Id<T>) => Promise<void>;
1114
1114
  insert: (table: string, document: Record<string, unknown>) => Promise<unknown>;
1115
- patch: <T extends string>(id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1115
+ patch: <T extends string>(table: T, id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1116
1116
  query: (table: string) => ActionCacheQuery;
1117
1117
  }
1118
1118
  /** The slice of a function context the helpers need — just its writer. */
@@ -1666,12 +1666,12 @@ type RelationWriteInfosLike = Readonly<Record<string, RelationWriteInfoLike>>;
1666
1666
  interface FacadeWriterLike {
1667
1667
  aggregate(tableName: string, options: unknown): Promise<unknown>;
1668
1668
  count(tableName: string, where?: unknown): Promise<number>;
1669
- delete(id: string, expectedTable?: string, options?: {
1669
+ delete(table: string, id: string, options?: {
1670
1670
  hard?: boolean;
1671
1671
  }): Promise<void>;
1672
- deleteMany?(ids: ReadonlyArray<string>, options?: {
1672
+ deleteMany?(table: string, ids: ReadonlyArray<string>, options?: {
1673
1673
  limit?: number;
1674
- }, expectedTable?: string): Promise<{
1674
+ }): Promise<{
1675
1675
  deleted: number;
1676
1676
  }>;
1677
1677
  deleteWhere?(tableName: string, where: Record<string, unknown>, options?: {
@@ -1690,13 +1690,13 @@ interface FacadeWriterLike {
1690
1690
  limit?: number;
1691
1691
  skipDuplicates?: boolean;
1692
1692
  }): Promise<(string | null)[]>;
1693
- patch(id: string, patch: Record<string, unknown>, expectedTable?: string): Promise<void>;
1694
- patchMany?(patches: ReadonlyArray<{
1693
+ patch(table: string, id: string, patch: Record<string, unknown>): Promise<void>;
1694
+ patchMany?(table: string, patches: ReadonlyArray<{
1695
1695
  id: string;
1696
1696
  patch: Record<string, unknown>;
1697
1697
  }>, options?: {
1698
1698
  limit?: number;
1699
- }, expectedTable?: string): Promise<{
1699
+ }): Promise<{
1700
1700
  patched: number;
1701
1701
  }>;
1702
1702
  patchWhere?(tableName: string, args: {
@@ -1715,8 +1715,8 @@ interface FacadeWriterLike {
1715
1715
  rankPage(tableName: string, indexName: string, options?: unknown): Promise<unknown>;
1716
1716
  /** Per-relation facts for nested relation writes, published by the engine's writer; absent on a writer that declares none. */
1717
1717
  readonly relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
1718
- replace(id: string, document: Record<string, unknown>, expectedTable?: string): Promise<void>;
1719
- restore?(id: string, expectedTable?: string): Promise<void>;
1718
+ replace(table: string, id: string, document: Record<string, unknown>): Promise<void>;
1719
+ restore?(table: string, id: string): Promise<void>;
1720
1720
  }
1721
1721
  /** The per-table accessor object returned for the `ctx.db` table form. */
1722
1722
  interface FacadeEntry {
@@ -1826,14 +1826,11 @@ interface UpsertManyArgs {
1826
1826
  /**
1827
1827
  * Bind a structural writer to one table, producing its `ctx.db` table accessor.
1828
1828
  *
1829
- * The by-id accessors (`get`/`delete`/`patch`/`replace`) forward the bound
1830
- * `tableName` as `expectedTable` so the underlying writer scopes its id lookup
1829
+ * The by-id accessors (`get`/`delete`/`patch`/`replace`) pass the bound
1830
+ * `tableName` as the writer's table argument, so the writer scopes its id lookup
1831
1831
  * to this table. Without it, a branded `Id<"posts">` carrying another table's
1832
- * id would resolve cross-table (the writer probes every table by id), letting
1833
- * `ctx.db.posts.get(foreignId)` read — or `.delete`/`.patch`/`.replace`
1834
- * mutate — a row in an unrelated table (IDOR). Writers that ignore the second
1835
- * argument keep their previous global behaviour; the scoping is opt-in via this
1836
- * forwarded name.
1832
+ * id would resolve cross-table, letting `ctx.db.posts.get(foreignId)` read — or
1833
+ * `.delete`/`.patch`/`.replace` mutate — a row in an unrelated table (IDOR).
1837
1834
  *
1838
1835
  * Cost: on a `.global()` table, `ctx.db.<table>.get(id)` probes only `tableName`,
1839
1836
  * and so does the root `ctx.db.get(table, id)`; neither form probes every table.
@@ -2851,9 +2848,9 @@ interface DatabaseWriterLike {
2851
2848
  */
2852
2849
  aggregate: (tableName: string, options: AggregateArgs$1) => Promise<null | number>;
2853
2850
  /** Update-policy check on row `id` with no write; see `@lunora/shard-engine`'s `DatabaseWriterLike.assertPatchAllowed`. */
2854
- assertPatchAllowed?: (id: string, expectedTable?: string) => Promise<void>;
2851
+ assertPatchAllowed?: (table: string, id: string) => Promise<void>;
2855
2852
  count: (tableName: string, whereOrArgs?: CountArgs | WhereInput) => Promise<number>;
2856
- delete: (id: string, expectedTable?: string, options?: {
2853
+ delete: (table: string, id: string, options?: {
2857
2854
  hard?: boolean;
2858
2855
  }) => Promise<void>;
2859
2856
  /** Uncapped, chunked erase of a whole table. The RLS wrapper gates each row like a single delete. */
@@ -2863,9 +2860,9 @@ interface DatabaseWriterLike {
2863
2860
  }) => Promise<{
2864
2861
  deleted: number;
2865
2862
  }>;
2866
- deleteMany: (ids: ReadonlyArray<string>, options?: {
2863
+ deleteMany: (table: string, ids: ReadonlyArray<string>, options?: {
2867
2864
  limit?: number;
2868
- }, expectedTable?: string) => Promise<{
2865
+ }) => Promise<{
2869
2866
  deleted: number;
2870
2867
  }>;
2871
2868
  /**
@@ -2923,7 +2920,7 @@ interface DatabaseWriterLike {
2923
2920
  row: Record<string, unknown>;
2924
2921
  tableName: string;
2925
2922
  }>;
2926
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string, options?: PatchWriteOptions) => Promise<void>;
2923
+ patch: (table: string, id: string, patch: Record<string, unknown>, options?: PatchWriteOptions) => Promise<void>;
2927
2924
  /** Conditional patch. Optional: a writer without an atomic conditional write omits it, and the wrapper refuses. */
2928
2925
  patchIf?: (tableName: string, id: string, args: {
2929
2926
  patch: Record<string, unknown>;
@@ -2933,12 +2930,12 @@ interface DatabaseWriterLike {
2933
2930
  applied: boolean;
2934
2931
  doc: Record<string, unknown> | null;
2935
2932
  }>;
2936
- patchMany: (patches: ReadonlyArray<{
2933
+ patchMany: (table: string, patches: ReadonlyArray<{
2937
2934
  id: string;
2938
2935
  patch: Record<string, unknown>;
2939
2936
  }>, options?: {
2940
2937
  limit?: number;
2941
- }, expectedTable?: string) => Promise<{
2938
+ }) => Promise<{
2942
2939
  patched: number;
2943
2940
  }>;
2944
2941
  patchWhere?: (tableName: string, args: {
@@ -2998,8 +2995,8 @@ interface DatabaseWriterLike {
2998
2995
  * traversal off.
2999
2996
  */
3000
2997
  relationEdges?: ReadonlyArray<RelationEdgeLike>;
3001
- replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
3002
- restore?: (id: string, expectedTable?: string) => Promise<void>;
2998
+ replace: (table: string, id: string, document: Record<string, unknown>) => Promise<void>;
2999
+ restore?: (table: string, id: string) => Promise<void>;
3003
3000
  /**
3004
3001
  * Soft-delete marker column per table, for tables declared `.softDelete()`. Published by the writer
3005
3002
  * (see `@lunora/shard-engine`'s `DatabaseWriterLike`). A re-located row whose marker is already set is
@@ -3233,8 +3230,8 @@ interface TableReaderLike {
3233
3230
  interface MaskDatabase {
3234
3231
  aggregate: (tableName: string, options: AggregateArgs) => Promise<null | number>;
3235
3232
  count: (tableName: string, whereOrArgs?: unknown) => Promise<number>;
3236
- delete: (id: string, expectedTable?: string) => Promise<void>;
3237
- deleteMany: (ids: ReadonlyArray<string>, options?: {
3233
+ delete: (table: string, id: string) => Promise<void>;
3234
+ deleteMany: (table: string, ids: ReadonlyArray<string>, options?: {
3238
3235
  limit?: number;
3239
3236
  }) => Promise<{
3240
3237
  deleted: number;
@@ -3262,7 +3259,7 @@ interface MaskDatabase {
3262
3259
  row: Record<string, unknown>;
3263
3260
  tableName: string;
3264
3261
  }>;
3265
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
3262
+ patch: (table: string, id: string, patch: Record<string, unknown>) => Promise<void>;
3266
3263
  patchIf?: (tableName: string, id: string, args: {
3267
3264
  patch: Record<string, unknown>;
3268
3265
  where: Record<string, unknown>;
@@ -3270,7 +3267,7 @@ interface MaskDatabase {
3270
3267
  applied: boolean;
3271
3268
  doc: Record<string, unknown> | null;
3272
3269
  }>;
3273
- patchMany: (patches: ReadonlyArray<{
3270
+ patchMany: (table: string, patches: ReadonlyArray<{
3274
3271
  id: string;
3275
3272
  patch: Record<string, unknown>;
3276
3273
  }>, options?: {
@@ -3315,7 +3312,7 @@ interface MaskDatabase {
3315
3312
  }[];
3316
3313
  }>;
3317
3314
  relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
3318
- replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
3315
+ replace: (table: string, id: string, document: Record<string, unknown>) => Promise<void>;
3319
3316
  }
3320
3317
  interface MaskContextIn {
3321
3318
  auth?: AuthLike;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, ColumnValidator, v, Id, ValidatorMap, InferValidatorMap } from '@lunora/values';
2
2
  export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
- import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, M as MutationCtx, c as RegisteredMutation, Q as QueryCtx, d as RegisteredQuery, e as DurableStreamOptions, f as RegisteredStream, F as FunctionKind, T as TableDefinition, g as RegisteredFunction, V as VectorIndexDefinition, S as Schema, h as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, i as RelationThrough, j as ThroughRelationDefinition, O as OnDeleteAction, k as RelationDefinition, l as SearchLanguage, m as SearchStrategy, n as ExternalSourceDefinition, o as TriggerBuilder, p as TriggerDefinition, q as VectorEmbedder, r as VectorMetric, s as DurableObjectJurisdiction, t as AggregateIndexDefinition, u as RankIndexDefinition, v as Secrets, w as LiveTopicRef, x as LifecycleEvent, y as ShardInitEvent, z as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-DYL1koQt.js";
4
- export type { B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, Z as IndexDefinition, _ as IndexRangeBuilder, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, a5 as MutationStorage, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, a9 as RankSortKey, aa as ReadOnlyStorage, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, an as SearchFilterBuilder, ao as SearchIndexDefinition, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, aN as TableReader, aO as TableVectorIndex, aP as TriggerAggregateOptions, aQ as TriggerCtx, aR as TriggerDatabase, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, b6 as VectorMatch, b7 as VectorMatches, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows } from "./packem_shared/types.d-DYL1koQt.js";
3
+ import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, M as MutationCtx, c as RegisteredMutation, Q as QueryCtx, d as RegisteredQuery, e as DurableStreamOptions, f as RegisteredStream, F as FunctionKind, T as TableDefinition, g as RegisteredFunction, V as VectorIndexDefinition, S as Schema, h as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, i as RelationThrough, j as ThroughRelationDefinition, O as OnDeleteAction, k as RelationDefinition, l as SearchLanguage, m as SearchStrategy, n as ExternalSourceDefinition, o as TriggerBuilder, p as TriggerDefinition, q as VectorEmbedder, r as VectorMetric, s as DurableObjectJurisdiction, t as AggregateIndexDefinition, u as RankIndexDefinition, v as Secrets, w as LiveTopicRef, x as LifecycleEvent, y as ShardInitEvent, z as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-BO1zQAnk.js";
4
+ export type { B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, Z as IndexDefinition, _ as IndexRangeBuilder, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, a5 as MutationStorage, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, a9 as RankSortKey, aa as ReadOnlyStorage, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, an as SearchFilterBuilder, ao as SearchIndexDefinition, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, aN as TableReader, aO as TableVectorIndex, aP as TriggerAggregateOptions, aQ as TriggerCtx, aR as TriggerDatabase, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, b6 as VectorMatch, b7 as VectorMatches, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows } from "./packem_shared/types.d-BO1zQAnk.js";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono, ExecutionContext } from 'hono';
@@ -1110,9 +1110,9 @@ interface ActionCacheQuery {
1110
1110
  * directly.
1111
1111
  */
1112
1112
  interface ActionCacheDatabase {
1113
- delete: <T extends string>(id: Id<T>) => Promise<void>;
1113
+ delete: <T extends string>(table: T, id: Id<T>) => Promise<void>;
1114
1114
  insert: (table: string, document: Record<string, unknown>) => Promise<unknown>;
1115
- patch: <T extends string>(id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1115
+ patch: <T extends string>(table: T, id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1116
1116
  query: (table: string) => ActionCacheQuery;
1117
1117
  }
1118
1118
  /** The slice of a function context the helpers need — just its writer. */
@@ -1666,12 +1666,12 @@ type RelationWriteInfosLike = Readonly<Record<string, RelationWriteInfoLike>>;
1666
1666
  interface FacadeWriterLike {
1667
1667
  aggregate(tableName: string, options: unknown): Promise<unknown>;
1668
1668
  count(tableName: string, where?: unknown): Promise<number>;
1669
- delete(id: string, expectedTable?: string, options?: {
1669
+ delete(table: string, id: string, options?: {
1670
1670
  hard?: boolean;
1671
1671
  }): Promise<void>;
1672
- deleteMany?(ids: ReadonlyArray<string>, options?: {
1672
+ deleteMany?(table: string, ids: ReadonlyArray<string>, options?: {
1673
1673
  limit?: number;
1674
- }, expectedTable?: string): Promise<{
1674
+ }): Promise<{
1675
1675
  deleted: number;
1676
1676
  }>;
1677
1677
  deleteWhere?(tableName: string, where: Record<string, unknown>, options?: {
@@ -1690,13 +1690,13 @@ interface FacadeWriterLike {
1690
1690
  limit?: number;
1691
1691
  skipDuplicates?: boolean;
1692
1692
  }): Promise<(string | null)[]>;
1693
- patch(id: string, patch: Record<string, unknown>, expectedTable?: string): Promise<void>;
1694
- patchMany?(patches: ReadonlyArray<{
1693
+ patch(table: string, id: string, patch: Record<string, unknown>): Promise<void>;
1694
+ patchMany?(table: string, patches: ReadonlyArray<{
1695
1695
  id: string;
1696
1696
  patch: Record<string, unknown>;
1697
1697
  }>, options?: {
1698
1698
  limit?: number;
1699
- }, expectedTable?: string): Promise<{
1699
+ }): Promise<{
1700
1700
  patched: number;
1701
1701
  }>;
1702
1702
  patchWhere?(tableName: string, args: {
@@ -1715,8 +1715,8 @@ interface FacadeWriterLike {
1715
1715
  rankPage(tableName: string, indexName: string, options?: unknown): Promise<unknown>;
1716
1716
  /** Per-relation facts for nested relation writes, published by the engine's writer; absent on a writer that declares none. */
1717
1717
  readonly relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
1718
- replace(id: string, document: Record<string, unknown>, expectedTable?: string): Promise<void>;
1719
- restore?(id: string, expectedTable?: string): Promise<void>;
1718
+ replace(table: string, id: string, document: Record<string, unknown>): Promise<void>;
1719
+ restore?(table: string, id: string): Promise<void>;
1720
1720
  }
1721
1721
  /** The per-table accessor object returned for the `ctx.db` table form. */
1722
1722
  interface FacadeEntry {
@@ -1826,14 +1826,11 @@ interface UpsertManyArgs {
1826
1826
  /**
1827
1827
  * Bind a structural writer to one table, producing its `ctx.db` table accessor.
1828
1828
  *
1829
- * The by-id accessors (`get`/`delete`/`patch`/`replace`) forward the bound
1830
- * `tableName` as `expectedTable` so the underlying writer scopes its id lookup
1829
+ * The by-id accessors (`get`/`delete`/`patch`/`replace`) pass the bound
1830
+ * `tableName` as the writer's table argument, so the writer scopes its id lookup
1831
1831
  * to this table. Without it, a branded `Id<"posts">` carrying another table's
1832
- * id would resolve cross-table (the writer probes every table by id), letting
1833
- * `ctx.db.posts.get(foreignId)` read — or `.delete`/`.patch`/`.replace`
1834
- * mutate — a row in an unrelated table (IDOR). Writers that ignore the second
1835
- * argument keep their previous global behaviour; the scoping is opt-in via this
1836
- * forwarded name.
1832
+ * id would resolve cross-table, letting `ctx.db.posts.get(foreignId)` read — or
1833
+ * `.delete`/`.patch`/`.replace` mutate — a row in an unrelated table (IDOR).
1837
1834
  *
1838
1835
  * Cost: on a `.global()` table, `ctx.db.<table>.get(id)` probes only `tableName`,
1839
1836
  * and so does the root `ctx.db.get(table, id)`; neither form probes every table.
@@ -2851,9 +2848,9 @@ interface DatabaseWriterLike {
2851
2848
  */
2852
2849
  aggregate: (tableName: string, options: AggregateArgs$1) => Promise<null | number>;
2853
2850
  /** Update-policy check on row `id` with no write; see `@lunora/shard-engine`'s `DatabaseWriterLike.assertPatchAllowed`. */
2854
- assertPatchAllowed?: (id: string, expectedTable?: string) => Promise<void>;
2851
+ assertPatchAllowed?: (table: string, id: string) => Promise<void>;
2855
2852
  count: (tableName: string, whereOrArgs?: CountArgs | WhereInput) => Promise<number>;
2856
- delete: (id: string, expectedTable?: string, options?: {
2853
+ delete: (table: string, id: string, options?: {
2857
2854
  hard?: boolean;
2858
2855
  }) => Promise<void>;
2859
2856
  /** Uncapped, chunked erase of a whole table. The RLS wrapper gates each row like a single delete. */
@@ -2863,9 +2860,9 @@ interface DatabaseWriterLike {
2863
2860
  }) => Promise<{
2864
2861
  deleted: number;
2865
2862
  }>;
2866
- deleteMany: (ids: ReadonlyArray<string>, options?: {
2863
+ deleteMany: (table: string, ids: ReadonlyArray<string>, options?: {
2867
2864
  limit?: number;
2868
- }, expectedTable?: string) => Promise<{
2865
+ }) => Promise<{
2869
2866
  deleted: number;
2870
2867
  }>;
2871
2868
  /**
@@ -2923,7 +2920,7 @@ interface DatabaseWriterLike {
2923
2920
  row: Record<string, unknown>;
2924
2921
  tableName: string;
2925
2922
  }>;
2926
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string, options?: PatchWriteOptions) => Promise<void>;
2923
+ patch: (table: string, id: string, patch: Record<string, unknown>, options?: PatchWriteOptions) => Promise<void>;
2927
2924
  /** Conditional patch. Optional: a writer without an atomic conditional write omits it, and the wrapper refuses. */
2928
2925
  patchIf?: (tableName: string, id: string, args: {
2929
2926
  patch: Record<string, unknown>;
@@ -2933,12 +2930,12 @@ interface DatabaseWriterLike {
2933
2930
  applied: boolean;
2934
2931
  doc: Record<string, unknown> | null;
2935
2932
  }>;
2936
- patchMany: (patches: ReadonlyArray<{
2933
+ patchMany: (table: string, patches: ReadonlyArray<{
2937
2934
  id: string;
2938
2935
  patch: Record<string, unknown>;
2939
2936
  }>, options?: {
2940
2937
  limit?: number;
2941
- }, expectedTable?: string) => Promise<{
2938
+ }) => Promise<{
2942
2939
  patched: number;
2943
2940
  }>;
2944
2941
  patchWhere?: (tableName: string, args: {
@@ -2998,8 +2995,8 @@ interface DatabaseWriterLike {
2998
2995
  * traversal off.
2999
2996
  */
3000
2997
  relationEdges?: ReadonlyArray<RelationEdgeLike>;
3001
- replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
3002
- restore?: (id: string, expectedTable?: string) => Promise<void>;
2998
+ replace: (table: string, id: string, document: Record<string, unknown>) => Promise<void>;
2999
+ restore?: (table: string, id: string) => Promise<void>;
3003
3000
  /**
3004
3001
  * Soft-delete marker column per table, for tables declared `.softDelete()`. Published by the writer
3005
3002
  * (see `@lunora/shard-engine`'s `DatabaseWriterLike`). A re-located row whose marker is already set is
@@ -3233,8 +3230,8 @@ interface TableReaderLike {
3233
3230
  interface MaskDatabase {
3234
3231
  aggregate: (tableName: string, options: AggregateArgs) => Promise<null | number>;
3235
3232
  count: (tableName: string, whereOrArgs?: unknown) => Promise<number>;
3236
- delete: (id: string, expectedTable?: string) => Promise<void>;
3237
- deleteMany: (ids: ReadonlyArray<string>, options?: {
3233
+ delete: (table: string, id: string) => Promise<void>;
3234
+ deleteMany: (table: string, ids: ReadonlyArray<string>, options?: {
3238
3235
  limit?: number;
3239
3236
  }) => Promise<{
3240
3237
  deleted: number;
@@ -3262,7 +3259,7 @@ interface MaskDatabase {
3262
3259
  row: Record<string, unknown>;
3263
3260
  tableName: string;
3264
3261
  }>;
3265
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string) => Promise<void>;
3262
+ patch: (table: string, id: string, patch: Record<string, unknown>) => Promise<void>;
3266
3263
  patchIf?: (tableName: string, id: string, args: {
3267
3264
  patch: Record<string, unknown>;
3268
3265
  where: Record<string, unknown>;
@@ -3270,7 +3267,7 @@ interface MaskDatabase {
3270
3267
  applied: boolean;
3271
3268
  doc: Record<string, unknown> | null;
3272
3269
  }>;
3273
- patchMany: (patches: ReadonlyArray<{
3270
+ patchMany: (table: string, patches: ReadonlyArray<{
3274
3271
  id: string;
3275
3272
  patch: Record<string, unknown>;
3276
3273
  }>, options?: {
@@ -3315,7 +3312,7 @@ interface MaskDatabase {
3315
3312
  }[];
3316
3313
  }>;
3317
3314
  relationWrites?: Readonly<Record<string, RelationWriteInfosLike>>;
3318
- replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
3315
+ replace: (table: string, id: string, document: Record<string, unknown>) => Promise<void>;
3319
3316
  }
3320
3317
  interface MaskContextIn {
3321
3318
  auth?: AuthLike;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-9W5_vf8H.mjs";import{initLunora as d}from"./packem_shared/initLunora-DH7k24N0.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as S,flushDeferredDeletes as u,withDeferredDeletes as h}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as A,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as L,documentHistoryExtension as _}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-xyn3tFOE.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as v,bindTableFacade as F}from"./packem_shared/bindOrm-DHtlrqCg.mjs";import{httpAction as H,httpRoute as N,httpRouter as k,isSafeHeaderValue as w,lastEventId as U,sseEvent as B}from"./packem_shared/httpAction-DplHzcUa.mjs";import{serveStorageObject as W}from"./packem_shared/serveStorageObject-B9GbK4qd.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as J}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as Q,onDisconnect as X,onShardInit as q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Z,DEFAULT_MAX_LIMIT as $,clampLimit as ee,defineListArgs as re}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as te,liveStreamRouter as ie}from"./packem_shared/defineLiveStream-DV3CtmGT.mjs";import{defineMigration as fe}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as se}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as me}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as xe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as le,d as Ee,a as Se,b as ue,e as he,f as De,g as Te,h as ge,i as Re,j as Ae,k as Ie,m as Le}from"./packem_shared/plugin-Bm9wIpiI.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ce,PRESENCE_TABLE as Me,definePresence as Pe,presenceExtension as be}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-CKKVL22B.mjs";import{protectPublic as ve}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Oe}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Ne}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as we}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Be}from"./packem_shared/defineShape-XGyajryg.mjs";import{defineWebSocket as We}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Ye}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Je}from"@lunora/errors";import{cronJobs as Qe}from"@lunora/scheduler";import{ValidationError as qe,v as ze}from"@lunora/values";import{allowAll as $e,deny as er,isDeny as rr,toWhereInput as or}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ir}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as fr,buildRlsReadRegistry as ar,composeShapeReadWhere as sr}from"./packem_shared/assertShapesDeclareReadPolicies-CZ4i2Kw6.mjs";import{buildMaskRegistry as mr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as xr,definePermission as cr,definePolicies as lr,definePolicy as Er,defineRole as Sr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as hr,defineStorageRules as Dr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as gr}from"./packem_shared/mask-BS6m1DOh.mjs";import{r as Ar}from"./packem_shared/middleware-uLdnmn8f.mjs";import{storageRules as Lr}from"./packem_shared/storageRules-b8Kx8yAw.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,Z as DEFAULT_LIMIT,$ as DEFAULT_MAX_LIMIT,A as DOCUMENT_HISTORY_REDACTED_FIELDS,I as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Je as LunoraError,Ce as PRESENCE_DEFAULT_TTL_MS,Me as PRESENCE_TABLE,e as VERSION,qe as ValidationError,n as actionCacheExtension,$e as allowAll,ir as asBucketStorage,fr as assertShapesDeclareReadPolicies,S as beginDeferredDeletes,T as beginDeferredSchedules,v as bindOrm,F as bindTableFacade,mr as buildMaskRegistry,ar as buildRlsReadRegistry,f as cacheKeyFor,ee as clampLimit,le as composePluginMiddleware,sr as composeShapeReadWhere,xr as createPolicyDsl,l as createSecrets,we as createServices,Qe as cronJobs,a as defineActionCache,Ee as defineAggregateIndex,Se as defineComponent,L as defineDocumentHistory,P as defineEnv,Y as defineIdentity,J as defineIdentityGuard,re as defineListArgs,te as defineLiveStream,fe as defineMigration,se as defineModule,me as defineMutator,cr as definePermission,ue as definePlugin,lr as definePolicies,Er as definePolicy,Pe as definePresence,he as defineRankIndex,Sr as defineRole,Ne as defineRoom,De as defineSchema,Te as defineSchemaExtension,Be as defineShape,hr as defineStorageRule,Dr as defineStorageRules,ge as defineTable,Re as defineVectorIndex,We as defineWebSocket,er as deny,_ as documentHistoryExtension,u as flushDeferredDeletes,H as httpAction,N as httpRoute,k as httpRouter,Ae as indexFieldsFromSchema,d as initLunora,Ie as installPlugins,rr as isDeny,p as isPerDispatchMiddleware,w as isSafeHeaderValue,U as lastEventId,ie as liveStreamRouter,gr as mask,Le as mergeSchemaExtension,Q as onConnect,X as onDisconnect,Oe as onQueryChange,q as onShardInit,Ye as onWhisper,xe as platformAdmin,be as presenceExtension,ve as protectPublic,b as redactSecrets,Ar as rls,W as serveStorageObject,B as sseEvent,Lr as storageRules,x as tagPerDispatchMiddleware,or as toWhereInput,ze as v,h as withDeferredDeletes,g as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-D5N5n__-.mjs";import{initLunora as d}from"./packem_shared/initLunora-DH7k24N0.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as S,flushDeferredDeletes as u,withDeferredDeletes as h}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-C7QLYr6C.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as A,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as L,documentHistoryExtension as _}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-B5yKLX8M.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as v,bindTableFacade as F}from"./packem_shared/bindOrm-BaLnyMcd.mjs";import{httpAction as H,httpRoute as N,httpRouter as k,isSafeHeaderValue as w,lastEventId as U,sseEvent as B}from"./packem_shared/httpAction-DplHzcUa.mjs";import{serveStorageObject as W}from"./packem_shared/serveStorageObject-B9GbK4qd.mjs";import{defineIdentity as Y}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as J}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as Q,onDisconnect as X,onShardInit as q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Z,DEFAULT_MAX_LIMIT as $,clampLimit as ee,defineListArgs as re}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as te,liveStreamRouter as ie}from"./packem_shared/defineLiveStream-DV3CtmGT.mjs";import{defineMigration as fe}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as se}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as me}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as xe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as le,d as Ee,a as Se,b as ue,e as he,f as De,g as Te,h as ge,i as Re,j as Ae,k as Ie,m as Le}from"./packem_shared/plugin-Bm9wIpiI.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ce,PRESENCE_TABLE as Me,definePresence as Pe,presenceExtension as be}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-n_AOEus6.mjs";import{protectPublic as ve}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Oe}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Ne}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as we}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Be}from"./packem_shared/defineShape-DY-Pxhna.mjs";import{defineWebSocket as We}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Ye}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Je}from"@lunora/errors";import{cronJobs as Qe}from"@lunora/scheduler";import{ValidationError as qe,v as ze}from"@lunora/values";import{allowAll as $e,deny as er,isDeny as rr,toWhereInput as or}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ir}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as fr,buildRlsReadRegistry as ar,composeShapeReadWhere as sr}from"./packem_shared/assertShapesDeclareReadPolicies-Bft5Rref.mjs";import{buildMaskRegistry as mr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as xr,definePermission as cr,definePolicies as lr,definePolicy as Er,defineRole as Sr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as hr,defineStorageRules as Dr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as gr}from"./packem_shared/mask-CoC2g3YT.mjs";import{r as Ar}from"./packem_shared/middleware-B0gy8zjo.mjs";import{storageRules as Lr}from"./packem_shared/storageRules-UARYjKO0.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,Z as DEFAULT_LIMIT,$ as DEFAULT_MAX_LIMIT,A as DOCUMENT_HISTORY_REDACTED_FIELDS,I as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Je as LunoraError,Ce as PRESENCE_DEFAULT_TTL_MS,Me as PRESENCE_TABLE,e as VERSION,qe as ValidationError,n as actionCacheExtension,$e as allowAll,ir as asBucketStorage,fr as assertShapesDeclareReadPolicies,S as beginDeferredDeletes,T as beginDeferredSchedules,v as bindOrm,F as bindTableFacade,mr as buildMaskRegistry,ar as buildRlsReadRegistry,f as cacheKeyFor,ee as clampLimit,le as composePluginMiddleware,sr as composeShapeReadWhere,xr as createPolicyDsl,l as createSecrets,we as createServices,Qe as cronJobs,a as defineActionCache,Ee as defineAggregateIndex,Se as defineComponent,L as defineDocumentHistory,P as defineEnv,Y as defineIdentity,J as defineIdentityGuard,re as defineListArgs,te as defineLiveStream,fe as defineMigration,se as defineModule,me as defineMutator,cr as definePermission,ue as definePlugin,lr as definePolicies,Er as definePolicy,Pe as definePresence,he as defineRankIndex,Sr as defineRole,Ne as defineRoom,De as defineSchema,Te as defineSchemaExtension,Be as defineShape,hr as defineStorageRule,Dr as defineStorageRules,ge as defineTable,Re as defineVectorIndex,We as defineWebSocket,er as deny,_ as documentHistoryExtension,u as flushDeferredDeletes,H as httpAction,N as httpRoute,k as httpRouter,Ae as indexFieldsFromSchema,d as initLunora,Ie as installPlugins,rr as isDeny,p as isPerDispatchMiddleware,w as isSafeHeaderValue,U as lastEventId,ie as liveStreamRouter,gr as mask,Le as mergeSchemaExtension,Q as onConnect,X as onDisconnect,Oe as onQueryChange,q as onShardInit,Ye as onWhisper,xe as platformAdmin,be as presenceExtension,ve as protectPublic,b as redactSecrets,Ar as rls,W as serveStorageObject,B as sseEvent,Lr as storageRules,x as tagPerDispatchMiddleware,or as toWhereInput,ze as v,h as withDeferredDeletes,g as withDeferredSchedules};
package/dist/otel.d.mts CHANGED
@@ -1,4 +1,47 @@
1
- import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-DYL1koQt.mjs";
1
+ /**
2
+ * `@lunora/server/otel` — hand a Lunora `ctx` to anything that speaks
3
+ * `@opentelemetry/api`.
4
+ *
5
+ * **The problem.** Lunora's tracing is hand-rolled and zero-dependency, which is
6
+ * the right call for a runtime that has to boot in a Workers isolate. The cost
7
+ * is that a library instrumented against `@opentelemetry/api` — the Vercel AI
8
+ * SDK's `experimental_telemetry`, a database driver's instrumentation, an
9
+ * in-house shared package — cannot see Lunora's trace. Its spans go to whatever
10
+ * global provider is registered, which in a Worker is the no-op one. They vanish.
11
+ *
12
+ * **The fix.** {@link createOtelTracer} adapts a `ctx` into an OTel `Tracer`, so
13
+ * the library's spans become real `ctx.trace` spans in the request's trace:
14
+ *
15
+ * ```ts
16
+ * import { createOtelTracer } from "@lunora/server/otel";
17
+ *
18
+ * export const summarize = action.action(async ({ args, ctx }) =>
19
+ * generateText({
20
+ * model: openai("gpt-4o"),
21
+ * prompt: args.prompt,
22
+ * experimental_telemetry: { isEnabled: true, tracer: createOtelTracer(ctx) },
23
+ * }),
24
+ * );
25
+ * ```
26
+ *
27
+ * **Why passing the tracer explicitly is the supported path.** OTel's ambient
28
+ * `context` API (`trace.getActiveSpan()`, implicit parenting inside
29
+ * `startActiveSpan`) needs `AsyncLocalStorage` to track the current span across
30
+ * `await`s. Durable Objects run under a slimmer compatibility profile than
31
+ * `nodejs_compat`, and `@lunora/do` deliberately avoids ALS for that reason —
32
+ * the same reason `ctx.trace` threads its parent explicitly instead of keeping
33
+ * an ambient stack. So this bridge implements the `Tracer` surface faithfully
34
+ * and parents each span to the `Context` its caller THREADED (falling back to
35
+ * the dispatch when none was), never to a dynamically-scoped "current" span:
36
+ * nesting is flatter than a full SDK would give for a library that relies on
37
+ * ambient context, but every span lands in the right trace, under the parent it
38
+ * was told about, with the right timings, and none are lost. See
39
+ * {@link createOtelTracer} for the precise semantics.
40
+ *
41
+ * `@opentelemetry/api` is a PEER dependency: it keeps a module-global registry,
42
+ * so a second copy in the tree would silently split it.
43
+ */
44
+ import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-BO1zQAnk.mjs";
2
45
  import '@lunora/values';
3
46
  /**
4
47
  * @since 1.0.0
package/dist/otel.d.ts CHANGED
@@ -1,4 +1,47 @@
1
- import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-DYL1koQt.js";
1
+ /**
2
+ * `@lunora/server/otel` — hand a Lunora `ctx` to anything that speaks
3
+ * `@opentelemetry/api`.
4
+ *
5
+ * **The problem.** Lunora's tracing is hand-rolled and zero-dependency, which is
6
+ * the right call for a runtime that has to boot in a Workers isolate. The cost
7
+ * is that a library instrumented against `@opentelemetry/api` — the Vercel AI
8
+ * SDK's `experimental_telemetry`, a database driver's instrumentation, an
9
+ * in-house shared package — cannot see Lunora's trace. Its spans go to whatever
10
+ * global provider is registered, which in a Worker is the no-op one. They vanish.
11
+ *
12
+ * **The fix.** {@link createOtelTracer} adapts a `ctx` into an OTel `Tracer`, so
13
+ * the library's spans become real `ctx.trace` spans in the request's trace:
14
+ *
15
+ * ```ts
16
+ * import { createOtelTracer } from "@lunora/server/otel";
17
+ *
18
+ * export const summarize = action.action(async ({ args, ctx }) =>
19
+ * generateText({
20
+ * model: openai("gpt-4o"),
21
+ * prompt: args.prompt,
22
+ * experimental_telemetry: { isEnabled: true, tracer: createOtelTracer(ctx) },
23
+ * }),
24
+ * );
25
+ * ```
26
+ *
27
+ * **Why passing the tracer explicitly is the supported path.** OTel's ambient
28
+ * `context` API (`trace.getActiveSpan()`, implicit parenting inside
29
+ * `startActiveSpan`) needs `AsyncLocalStorage` to track the current span across
30
+ * `await`s. Durable Objects run under a slimmer compatibility profile than
31
+ * `nodejs_compat`, and `@lunora/do` deliberately avoids ALS for that reason —
32
+ * the same reason `ctx.trace` threads its parent explicitly instead of keeping
33
+ * an ambient stack. So this bridge implements the `Tracer` surface faithfully
34
+ * and parents each span to the `Context` its caller THREADED (falling back to
35
+ * the dispatch when none was), never to a dynamically-scoped "current" span:
36
+ * nesting is flatter than a full SDK would give for a library that relies on
37
+ * ambient context, but every span lands in the right trace, under the parent it
38
+ * was told about, with the right timings, and none are lost. See
39
+ * {@link createOtelTracer} for the precise semantics.
40
+ *
41
+ * `@opentelemetry/api` is a PEER dependency: it keeps a module-global registry,
42
+ * so a second copy in the tree would silently split it.
43
+ */
44
+ import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-BO1zQAnk.js";
2
45
  import '@lunora/values';
3
46
  /**
4
47
  * @since 1.0.0
@@ -0,0 +1 @@
1
+ import{isLunoraError as O}from"@lunora/errors";import{v as d}from"@lunora/values";import{decodeWire as U,encodeWire as D,stableWireKey as S}from"@lunora/wire";import{initLunora as F}from"./initLunora-DH7k24N0.mjs";import{g as k,h as q,a as B}from"./plugin-Bm9wIpiI.mjs";const P=3600*1e3,R=512*1024,H=8,b=64,V=64,K=256,W=4096,u="actionCache",h="entries",r=`${u}_${h}`,T=o=>o===void 0?"":S(o),x=async(o,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${o}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},$=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:G}=F.dataModel().create(),Z=(o={})=>{const m=o.ttlMs!==void 0&&Number.isFinite(o.ttlMs)?Math.max(1,Math.floor(o.ttlMs)):P,A=o.maxValueBytes!==void 0&&Number.isFinite(o.maxValueBytes)?Math.max(1,Math.floor(o.maxValueBytes)):R,y=async(e,t)=>{const n=(await e.db.query(r).withIndex("byExpiresAt").order("asc").take(H)).filter(s=>s.expiresAt<=t);await Promise.all(n.map(async s=>e.db.delete(r,s._id)))},C=async(e,t)=>e.db.query(r).withIndex("byKey",a=>a.eq("key",t)).first(),f=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),N=async(e,t,a)=>{try{await(t?e.db.patch(r,t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(r,a))}catch(n){if(O(n)&&f.has(n.code))return;throw n}},I=async(e,t,a,n)=>{const s=T(a),i=await x(t,s),l=Date.now(),c=await C(e,i);if(c&&c.expiresAt>l)return U(JSON.parse(c.value)).v;const p=await n(),w=JSON.stringify(D({v:p})),E=Date.now(),g=E+m;return new TextEncoder().encode(w).length<=A?await N(e,c,{expiresAt:g,key:i,name:t,value:w}):c&&await e.db.delete(r,c._id),await y(e,E),p},M=async(e,t,a)=>{const n=await x(t,T(a)),s=await e.db.query(r).withIndex("byKey",i=>i.eq("key",n)).take(b);await Promise.all(s.map(async i=>e.db.delete(r,i._id)))},_=async(e,t,a,n)=>{if(n>=V)return{complete:!1,deleted:a};const s=await e.db.query(r).withIndex("byName",i=>i.eq("name",t)).take(b);return s.length===0?{complete:!0,deleted:a}:(await Promise.all(s.map(async i=>e.db.delete(r,i._id))),_(e,t,a+s.length,n+1))},L=async(e,t)=>_(e,t,0,0),v=G.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(W,Math.max(1,Math.floor(e.limit))):K,i=(await t.db.query(r).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(i.map(async l=>t.db.delete(r,l._id))),{deleted:i.length}});return{...B(u,{extension:$,functions:{purgeExpired:v}}),invalidate:M,invalidateAll:L,wrap:I}};export{P as ACTION_CACHE_DEFAULT_TTL_MS,r as ACTION_CACHE_TABLE,$ as actionCacheExtension,x as cacheKeyFor,Z as defineActionCache};
@@ -1 +1 @@
1
- import{v as r}from"@lunora/values";import{decodeWire as I,encodeWire as h}from"@lunora/wire";import{initLunora as x}from"./initLunora-DH7k24N0.mjs";import{g as v,h as R,a as U}from"./plugin-Bm9wIpiI.mjs";const H=2160*60*60*1e3,L=64*1024,y=200,q=1e3,C=64,F=512,u=16,g=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],b="documentHistory",T="versions",f=`${b}_${T}`,w=v(b,{tables:{[T]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:P,internalQuery:Y}=x.dataModel().create(),V=(d={})=>{const _=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,l=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,A=new Set([...B,...d.redact??[]]);let M=0;const S=()=>(M+=1,M),a=(e,t=0)=>{if(Array.isArray(e))return t>=u?void 0:e.map(o=>a(o,t+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return t>=u?void 0:new Map([...e.entries()].filter(([o])=>typeof o!="string"||!A.has(o)).map(([o,i])=>[o,a(i,t+1)]));if(e instanceof Set)return t>=u?void 0:new Set([...e].map(o=>a(o,t+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=u))return Object.fromEntries(Object.entries(e).filter(([o])=>!A.has(o)).map(([o,i])=>[o,a(i,t+1)]))},E=e=>{if(e===void 0)return;const t=JSON.stringify(h(a(e)));if(!(t.length>l))return 3*t.length<=l?t:new TextEncoder().encode(t).length>l?void 0:t},p=async(e,t)=>{const o=E(t.doc),i=E(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(f,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:S(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>p(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>p(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>p(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),N=Y.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):y,i=await t.db.query(f).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,m)=>{for(const c of g){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:I(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:I(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=P.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-_,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await t.db.query(f).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(y,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(b,{extension:w,functions:{listForDocument:N,vacuum:O}}),record:D}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,f as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,w as documentHistoryExtension};
1
+ import{v as r}from"@lunora/values";import{decodeWire as I,encodeWire as h}from"@lunora/wire";import{initLunora as x}from"./initLunora-DH7k24N0.mjs";import{g as v,h as R,a as U}from"./plugin-Bm9wIpiI.mjs";const H=2160*60*60*1e3,L=64*1024,y=200,q=1e3,C=64,F=512,u=16,g=["_commitSeq","seq"],B=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],b="documentHistory",T="versions",l=`${b}_${T}`,w=v(b,{tables:{[T]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:P,internalQuery:Y}=x.dataModel().create(),V=(d={})=>{const _=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,p=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,A=new Set([...B,...d.redact??[]]);let M=0;const S=()=>(M+=1,M),a=(e,t=0)=>{if(Array.isArray(e))return t>=u?void 0:e.map(o=>a(o,t+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return t>=u?void 0:new Map([...e.entries()].filter(([o])=>typeof o!="string"||!A.has(o)).map(([o,i])=>[o,a(i,t+1)]));if(e instanceof Set)return t>=u?void 0:new Set([...e].map(o=>a(o,t+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(t>=u))return Object.fromEntries(Object.entries(e).filter(([o])=>!A.has(o)).map(([o,i])=>[o,a(i,t+1)]))},E=e=>{if(e===void 0)return;const t=JSON.stringify(h(a(e)));if(!(t.length>p))return 3*t.length<=p?t:new TextEncoder().encode(t).length>p?void 0:t},f=async(e,t)=>{const o=E(t.doc),i=E(t.previous),n=t.doc!==void 0&&o===void 0||t.previous!==void 0&&i===void 0;await e.db.insert(l,{documentId:t.documentId,op:t.op,recordedAt:Date.now(),seq:S(),tableName:t.tableName,...n?{truncated:!0}:{},...o===void 0?{}:{doc:o},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(t,o)=>f(t,{documentId:o.id,op:"delete",previous:o.previous,tableName:o.table})),documentHistoryInsert:e.afterInsert(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"insert",tableName:o.table})),documentHistoryUpdate:e.afterUpdate(async(t,o)=>f(t,{doc:o.doc,documentId:o.id,op:"update",previous:o.previous,tableName:o.table}))}),N=Y.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:t})=>{const o=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):y,i=await t.db.query(l).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(o);return i.sort((n,m)=>{for(const c of g){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:I(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:I(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=P.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:t})=>{const o=Date.now()-_,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await t.db.query(l).withIndex("byRecordedAt",s=>s.lt("recordedAt",o)).order("asc").take(Math.min(y,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>t.db.delete(l,s._id))),n+=c.length}return{deleted:n}});return{...U(b,{extension:w,functions:{listForDocument:N,vacuum:O}}),record:D}};export{B as DOCUMENT_HISTORY_REDACTED_FIELDS,l as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,w as documentHistoryExtension};
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DH7k24N0.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-Bm9wIpiI.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",r=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const I=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,I)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const d=Date.now(),a=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(r).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==a)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const c={lastSeen:d,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...a===void 0?{}:{userId:a}};await(e?s.db.patch(r,e._id,c):s.db.insert(r,c));const l=d-I-Math.max(f,I),m=(await s.db.query(r).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=l);return await Promise.all(m.map(i=>s.db.delete(r,i._id))),{lastSeen:d}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const d=Date.now()-I,e=(await s.db.query(r).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>d),c=new Set,l=[];for(const n of e){const m=n.userId;if(m!==void 0){if(c.has(m))continue;c.add(m)}const i={lastSeen:n.lastSeen,roomId:n.roomId};m!==void 0&&(i.userId=m),n.data!==void 0&&(i.data=n.data),l.push(i)}return l}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const d=Date.now()-I,a=await s.db.query(r).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=d).collect();return await Promise.all(a.map(e=>s.db.delete(r,e._id))),{deleted:a.length}}),visibility:"internal"},q=T(async(o,s)=>{const d=s.context?.roomId,a=s.context?.sessionId;if(typeof d!="string"||typeof a!="string")return;const e=await o.db.query(r).withIndex("byRoomSession",n=>n.eq("roomId",d).eq("sessionId",a)).first();if(!e)return;const c=s.userId??void 0;if((e.userId??void 0)!==c)return;if(f===0){await o.db.delete(r,e._id);return}const l=Math.min(e.lastSeen,Date.now()+f-I);await o.db.patch(r,e._id,{lastSeen:l})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,r as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
@@ -1 +1 @@
1
- import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-uLdnmn8f.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
1
+ import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-B0gy8zjo.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
@@ -1 +1 @@
1
- import{LunoraError as p}from"@lunora/errors";import{isPlainObject as x}from"@lunora/wire";const M=new Set(["connect","disconnect","set"]),y=500,I=(t,n,e)=>t!==void 0&&Object.hasOwn(t,n)&&x(e),v=t=>typeof t=="object"&&t!==null&&t.code==="CONFLICT"&&t.kind==="unique",u=(t,n)=>{throw new p(t,n)},R=(t,n)=>{if(!Array.isArray(t)||t.some(s=>typeof s!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const e=[...new Set(t)];return e.length>y&&u("VALIDATION_ERROR",`${n} names ${String(e.length)} rows; at most ${String(y)} per list`),e},E=(t,n,e)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${e}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,e)=>{const{connect:s,disconnect:i,set:c}=e;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),s!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),s!==void 0?(typeof s!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:s,info:n,name:t}):(i!==!0&&u("VALIDATION_ERROR",`${t}.disconnect must be true`),E(t,n,"disconnect"),{info:n,name:t})},A=(t,n,e)=>{n.through===void 0&&E(t,n,e)},k=(t,n,e)=>{const{connect:s,disconnect:i,set:c}=e;if(c!==void 0)return(s!==void 0||i!==void 0)&&u("VALIDATION_ERROR",`${t}: set replaces the whole list and cannot be combined with connect or disconnect`),A(t,n,"set"),{attach:[],info:n,name:t,release:[],replace:R(c,`${t}.set`)};i!==void 0&&A(t,n,"disconnect");const a=s===void 0?[]:R(s,`${t}.connect`),r=i===void 0?[]:R(i,`${t}.disconnect`),o=a.find(d=>r.includes(d));return o!==void 0&&u("VALIDATION_ERROR",`${t}: "${o}" is in both connect and disconnect, which is ambiguous`),{attach:a,info:n,name:t,release:r}},j=(t,n,e,s)=>{const i=Object.fromEntries(Object.entries(s).filter(([,r])=>r!==void 0)),c=Object.keys(i).find(r=>!M.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}: "${n}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(i).length===0)return;const a=e.refusal??e.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),e.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${e.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),e.kind==="one"?D(n,e,i):k(n,e,i)},W=t=>t.info.kind==="one",T=(t,n,e)=>{if(n===void 0)return{columns:e,manys:[],ones:[]};const s={},i=[],c=[];for(const[a,r]of Object.entries(e)){if(!I(n,a,r)){s[a]=r;continue}const o=j(t,a,n[a],r);o!==void 0&&(W(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(s,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:s,manys:i,ones:c}},w=(t,n,e,s)=>{const i=Object.entries(e).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${s}: "${i}" is a relation write, which ${s} does not support; use insert or patch`)},O=async(t,n,e,s,i)=>{const c=await t.get(s,i);return c===null&&u("NOT_FOUND",`${n}.${e}: no "${s}" row with id "${i}"`),c},b=async(t,n)=>{const e={...n.columns};for(const{connect:s,info:i,name:c}of n.ones){let a=null;s!==void 0&&(a=(await O(t,c,"connect",i.table,s))[i.references]),e[i.field]=a}return e},F=async(t,{info:n,name:e},s,i)=>{(await O(t,e,"connect",n.table,s))[n.field]!==i&&await t.patch(s,{[n.field]:i},n.table)},P=async(t,{info:n},e,s)=>{e[n.field]===s&&await t.patch(String(e._id),{[n.field]:null},n.table)},U=async(t,{info:n,name:e},s)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:s}});return i.length>y&&u("VALIDATION_ERROR",`${e}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const e=new Set(t),s=new Set(n);return{attach:n.filter(i=>!e.has(i)),release:new Set(t.filter(i=>!s.has(i)))}},$=async(t,{name:n},{from:e,table:s,to:i},c,a)=>{const r=a===void 0?{[e]:c}:{[e]:c,[i]:{in:a}},{page:o}=await t.findMany(s,{limit:y+1,where:r});return o.length>y&&u("VALIDATION_ERROR",`${n}: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},V=async(t,n,e)=>{if(e.length===0)return new Set;const{page:s}=await t.findMany(n,{limit:e.length,where:{_id:{in:e}}});return new Set(s.map(i=>String(i._id)))},C=async(t,n,e)=>{const{info:s,name:i}=n,{from:c,table:a,to:r}=s.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(h=>O(t,i,"disconnect",s.table,h))),d=n.release.length===0?[]:await $(t,n,s.through,e,n.release);const l=n.attach.length===0?[]:await $(t,n,s.through,e,n.attach),f=new Set(l.map(h=>String(h[r])));o=n.attach.filter(h=>!f.has(h))}else{const l=await $(t,n,s.through,e,void 0),f=L(l.map(g=>String(g[r])),n.replace),h=await V(t,s.table,[...f.release]);({attach:o}=f),d=l.filter(g=>f.release.has(String(g[r]))&&h.has(String(g[r])))}await Promise.all(o.map(l=>O(t,i,"connect",s.table,l)));for(const l of d)await t.delete(String(l._id),a);for(const l of o)try{await t.insert(a,{[c]:e,[r]:l})}catch(f){if(!v(f)||!s.pairIsOnlyUnique)throw f}},q=async(t,n,e)=>{let{attach:s}=n,i;if(n.replace===void 0)i=await Promise.all(n.release.map(c=>O(t,n.name,"disconnect",n.info.table,c)));else{const c=await U(t,n,e),a=L(c.map(r=>String(r._id)),n.replace);({attach:s}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await P(t,n,c,e);for(const c of s)await F(t,n,c,e)},_=async(t,n,e,s)=>{for(const i of e.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await s(a);if(r==null&&u("VALIDATION_ERROR",`ctx.db.${n}: ${i.name} is keyed on "${a}", which this row has no value for`),c.through!==void 0){await C(t,{...i,info:c},r);continue}await q(t,{...i,info:c},r)}},S=(t,n,e,s)=>async i=>i==="_id"?e:Object.hasOwn(s,i)?s[i]:(await t.get(n,e))?.[i],B=async(t,n,e,s,i)=>{const c=T(n,e,s);if(c.ones.length===0&&c.manys.length===0)return i(c.columns);const a=await b(t,c),r=await i(a);return r!==null&&await _(t,n,c,S(t,n,r,a)),r},m=async(t,n,e,s,i)=>{const c=T(n,e,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(s,c.columns,n);return}const a=await b(t,c);if(Object.keys(a).length>0)await t.patch(s,a,n);else{if(await t.get(n,s)===null)throw new p("NOT_FOUND",`document not found: ${s}`);await t.assertPatchAllowed?.(s,n)}await _(t,n,c,S(t,n,s,a))},G=(t,n,e,s)=>{const i=typeof n=="string"?[n]:n;if(i.length===0)throw new p("INTERNAL",`ctx.db.${t}.upsert: "target" must name at least one field`);const c={};for(const a of i){if(!(a in e)){const r=Object.entries(s??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in e)?.[0];throw r!==void 0?new p("VALIDATION_ERROR",`ctx.db.${t}.upsert: target field "${a}" is supplied by the "${r}" relation write; pass "${a}" itself so the existing row can be found`):new p("INTERNAL",`ctx.db.${t}.upsert: target field "${a}" is missing from the create document`)}c[a]=e[a]}return c},z=(t,n)=>{const e=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(l){if(v(l))return null;throw l}},s=t.relationWrites?.[n],i=(o,d)=>B(t,n,s,o,l=>e(l,d)),c=(o,d)=>m(t,n,s,o,d),a=async o=>{const d=o??{},l=await t.findMany(n,{...d,limit:2});if(l.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return l.page[0]??null},r=async({create:o,target:d,update:l})=>{const f=G(n,d,o,s),h=await t.findFirst(n,{where:f});return h&&typeof h._id=="string"?(await c(h._id,l??o),{created:!1,id:h._id}):{created:!0,id:await i(o)}};return{aggregate:o=>t.aggregate(n,o),count:o=>t.count(n,o),delete:o=>t.delete(o,n),deleteMany:(o,d)=>{if(Array.isArray(o)){if(t.deleteMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany is unavailable: this writer has no batch delete`);return t.deleteMany(o,d,n)}if(t.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const l=o;return t.deleteWhere(n,l.where,{limit:l.limit})},exists:async o=>await t.findFirst(n,o===void 0?void 0:{where:o})!==null,explain:o=>t.explain(n,o),findFirst:o=>t.findFirst(n,o),findFirstOrThrow:o=>t.findFirstOrThrow(n,o),findMany:o=>t.findMany(n,o),findUnique:a,get:o=>t.get(n,o),groupBy:o=>t.groupBy(n,o),hardDelete:o=>t.delete(o,n,{hard:!0}),insert:i,insertMany:(o,d)=>{for(const l of o)w(n,s,l,"insertMany");if(t.insertMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.insertMany is unavailable: this writer has no batch insert`);return t.insertMany(n,o,d)},patch:c,patchMany:(o,d)=>{const l=Array.isArray(o)?o.map(h=>h.values):[o.values];for(const h of l)w(n,s,h,"patchMany");if(Array.isArray(o)){if(t.patchMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany is unavailable: this writer has no batch patch`);return t.patchMany(o.map(h=>({id:h.id,patch:h.values})),d,n)}if(t.patchWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=o;return t.patchWhere(n,{patch:f.values,where:f.where},{limit:f.limit})},rank:(o,d)=>t.rank(n,o,d),rankPage:(o,d)=>t.rankPage(n,o,d),replace:(o,d)=>(w(n,s,d,"replace"),t.replace(o,d,n)),restore:async o=>{if(!t.restore)throw new p("INTERNAL",`ctx.db.${n}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await t.restore(o,n)},upsert:r,upsertMany:async({rows:o,target:d})=>{const l=[];for(const f of o)l.push(await r({create:f.create,target:d,update:f.update}));return l},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},X=(t,n)=>{Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){const e=z(t,n);return Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:e,writable:!1}),e}})},H=t=>{const n=e=>{const s=t[e];if(!s)throw new p("INTERNAL",`unknown table: ${e}`);return s};return{delete:(e,s)=>n(e).delete(s),insert:e=>({values:s=>n(e).insert(s)}),query:t,replace:(e,s)=>({with:i=>n(e).replace(s,i)}),update:(e,s)=>({set:i=>n(e).patch(s,i)})}};export{H as bindOrm,z as bindTableFacade,X as defineLazyFacade};
1
+ import{LunoraError as p}from"@lunora/errors";import{isPlainObject as x}from"@lunora/wire";const M=new Set(["connect","disconnect","set"]),y=500,I=(t,n,e)=>t!==void 0&&Object.hasOwn(t,n)&&x(e),v=t=>typeof t=="object"&&t!==null&&t.code==="CONFLICT"&&t.kind==="unique",u=(t,n)=>{throw new p(t,n)},R=(t,n)=>{if(!Array.isArray(t)||t.some(s=>typeof s!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const e=[...new Set(t)];return e.length>y&&u("VALIDATION_ERROR",`${n} names ${String(e.length)} rows; at most ${String(y)} per list`),e},E=(t,n,e)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${e}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,e)=>{const{connect:s,disconnect:i,set:c}=e;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),s!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),s!==void 0?(typeof s!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:s,info:n,name:t}):(i!==!0&&u("VALIDATION_ERROR",`${t}.disconnect must be true`),E(t,n,"disconnect"),{info:n,name:t})},A=(t,n,e)=>{n.through===void 0&&E(t,n,e)},k=(t,n,e)=>{const{connect:s,disconnect:i,set:c}=e;if(c!==void 0)return(s!==void 0||i!==void 0)&&u("VALIDATION_ERROR",`${t}: set replaces the whole list and cannot be combined with connect or disconnect`),A(t,n,"set"),{attach:[],info:n,name:t,release:[],replace:R(c,`${t}.set`)};i!==void 0&&A(t,n,"disconnect");const a=s===void 0?[]:R(s,`${t}.connect`),r=i===void 0?[]:R(i,`${t}.disconnect`),o=a.find(d=>r.includes(d));return o!==void 0&&u("VALIDATION_ERROR",`${t}: "${o}" is in both connect and disconnect, which is ambiguous`),{attach:a,info:n,name:t,release:r}},j=(t,n,e,s)=>{const i=Object.fromEntries(Object.entries(s).filter(([,r])=>r!==void 0)),c=Object.keys(i).find(r=>!M.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}: "${n}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(i).length===0)return;const a=e.refusal??e.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),e.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${e.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),e.kind==="one"?D(n,e,i):k(n,e,i)},W=t=>t.info.kind==="one",T=(t,n,e)=>{if(n===void 0)return{columns:e,manys:[],ones:[]};const s={},i=[],c=[];for(const[a,r]of Object.entries(e)){if(!I(n,a,r)){s[a]=r;continue}const o=j(t,a,n[a],r);o!==void 0&&(W(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(s,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:s,manys:i,ones:c}},w=(t,n,e,s)=>{const i=Object.entries(e).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${s}: "${i}" is a relation write, which ${s} does not support; use insert or patch`)},O=async(t,n,e,s,i)=>{const c=await t.get(s,i);return c===null&&u("NOT_FOUND",`${n}.${e}: no "${s}" row with id "${i}"`),c},b=async(t,n)=>{const e={...n.columns};for(const{connect:s,info:i,name:c}of n.ones){let a=null;s!==void 0&&(a=(await O(t,c,"connect",i.table,s))[i.references]),e[i.field]=a}return e},F=async(t,{info:n,name:e},s,i)=>{(await O(t,e,"connect",n.table,s))[n.field]!==i&&await t.patch(n.table,s,{[n.field]:i})},P=async(t,{info:n},e,s)=>{e[n.field]===s&&await t.patch(n.table,String(e._id),{[n.field]:null})},U=async(t,{info:n,name:e},s)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:s}});return i.length>y&&u("VALIDATION_ERROR",`${e}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const e=new Set(t),s=new Set(n);return{attach:n.filter(i=>!e.has(i)),release:new Set(t.filter(i=>!s.has(i)))}},$=async(t,{name:n},{from:e,table:s,to:i},c,a)=>{const r=a===void 0?{[e]:c}:{[e]:c,[i]:{in:a}},{page:o}=await t.findMany(s,{limit:y+1,where:r});return o.length>y&&u("VALIDATION_ERROR",`${n}: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},V=async(t,n,e)=>{if(e.length===0)return new Set;const{page:s}=await t.findMany(n,{limit:e.length,where:{_id:{in:e}}});return new Set(s.map(i=>String(i._id)))},C=async(t,n,e)=>{const{info:s,name:i}=n,{from:c,table:a,to:r}=s.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(h=>O(t,i,"disconnect",s.table,h))),d=n.release.length===0?[]:await $(t,n,s.through,e,n.release);const l=n.attach.length===0?[]:await $(t,n,s.through,e,n.attach),f=new Set(l.map(h=>String(h[r])));o=n.attach.filter(h=>!f.has(h))}else{const l=await $(t,n,s.through,e,void 0),f=L(l.map(g=>String(g[r])),n.replace),h=await V(t,s.table,[...f.release]);({attach:o}=f),d=l.filter(g=>f.release.has(String(g[r]))&&h.has(String(g[r])))}await Promise.all(o.map(l=>O(t,i,"connect",s.table,l)));for(const l of d)await t.delete(a,String(l._id));for(const l of o)try{await t.insert(a,{[c]:e,[r]:l})}catch(f){if(!v(f)||!s.pairIsOnlyUnique)throw f}},q=async(t,n,e)=>{let{attach:s}=n,i;if(n.replace===void 0)i=await Promise.all(n.release.map(c=>O(t,n.name,"disconnect",n.info.table,c)));else{const c=await U(t,n,e),a=L(c.map(r=>String(r._id)),n.replace);({attach:s}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await P(t,n,c,e);for(const c of s)await F(t,n,c,e)},_=async(t,n,e,s)=>{for(const i of e.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await s(a);if(r==null&&u("VALIDATION_ERROR",`ctx.db.${n}: ${i.name} is keyed on "${a}", which this row has no value for`),c.through!==void 0){await C(t,{...i,info:c},r);continue}await q(t,{...i,info:c},r)}},S=(t,n,e,s)=>async i=>i==="_id"?e:Object.hasOwn(s,i)?s[i]:(await t.get(n,e))?.[i],B=async(t,n,e,s,i)=>{const c=T(n,e,s);if(c.ones.length===0&&c.manys.length===0)return i(c.columns);const a=await b(t,c),r=await i(a);return r!==null&&await _(t,n,c,S(t,n,r,a)),r},m=async(t,n,e,s,i)=>{const c=T(n,e,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(n,s,c.columns);return}const a=await b(t,c);if(Object.keys(a).length>0)await t.patch(n,s,a);else{if(await t.get(n,s)===null)throw new p("NOT_FOUND",`document not found: ${s}`);await t.assertPatchAllowed?.(n,s)}await _(t,n,c,S(t,n,s,a))},G=(t,n,e,s)=>{const i=typeof n=="string"?[n]:n;if(i.length===0)throw new p("INTERNAL",`ctx.db.${t}.upsert: "target" must name at least one field`);const c={};for(const a of i){if(!(a in e)){const r=Object.entries(s??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in e)?.[0];throw r!==void 0?new p("VALIDATION_ERROR",`ctx.db.${t}.upsert: target field "${a}" is supplied by the "${r}" relation write; pass "${a}" itself so the existing row can be found`):new p("INTERNAL",`ctx.db.${t}.upsert: target field "${a}" is missing from the create document`)}c[a]=e[a]}return c},z=(t,n)=>{const e=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(l){if(v(l))return null;throw l}},s=t.relationWrites?.[n],i=(o,d)=>B(t,n,s,o,l=>e(l,d)),c=(o,d)=>m(t,n,s,o,d),a=async o=>{const d=o??{},l=await t.findMany(n,{...d,limit:2});if(l.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return l.page[0]??null},r=async({create:o,target:d,update:l})=>{const f=G(n,d,o,s),h=await t.findFirst(n,{where:f});return h&&typeof h._id=="string"?(await c(h._id,l??o),{created:!1,id:h._id}):{created:!0,id:await i(o)}};return{aggregate:o=>t.aggregate(n,o),count:o=>t.count(n,o),delete:o=>t.delete(n,o),deleteMany:(o,d)=>{if(Array.isArray(o)){if(t.deleteMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany is unavailable: this writer has no batch delete`);return t.deleteMany(n,o,d)}if(t.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const l=o;return t.deleteWhere(n,l.where,{limit:l.limit})},exists:async o=>await t.findFirst(n,o===void 0?void 0:{where:o})!==null,explain:o=>t.explain(n,o),findFirst:o=>t.findFirst(n,o),findFirstOrThrow:o=>t.findFirstOrThrow(n,o),findMany:o=>t.findMany(n,o),findUnique:a,get:o=>t.get(n,o),groupBy:o=>t.groupBy(n,o),hardDelete:o=>t.delete(n,o,{hard:!0}),insert:i,insertMany:(o,d)=>{for(const l of o)w(n,s,l,"insertMany");if(t.insertMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.insertMany is unavailable: this writer has no batch insert`);return t.insertMany(n,o,d)},patch:c,patchMany:(o,d)=>{const l=Array.isArray(o)?o.map(h=>h.values):[o.values];for(const h of l)w(n,s,h,"patchMany");if(Array.isArray(o)){if(t.patchMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany is unavailable: this writer has no batch patch`);return t.patchMany(n,o.map(h=>({id:h.id,patch:h.values})),d)}if(t.patchWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=o;return t.patchWhere(n,{patch:f.values,where:f.where},{limit:f.limit})},rank:(o,d)=>t.rank(n,o,d),rankPage:(o,d)=>t.rankPage(n,o,d),replace:(o,d)=>(w(n,s,d,"replace"),t.replace(n,o,d)),restore:async o=>{if(!t.restore)throw new p("INTERNAL",`ctx.db.${n}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await t.restore(n,o)},upsert:r,upsertMany:async({rows:o,target:d})=>{const l=[];for(const f of o)l.push(await r({create:f.create,target:d,update:f.update}));return l},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},X=(t,n)=>{Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){const e=z(t,n);return Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:e,writable:!1}),e}})},H=t=>{const n=e=>{const s=t[e];if(!s)throw new p("INTERNAL",`unknown table: ${e}`);return s};return{delete:(e,s)=>n(e).delete(s),insert:e=>({values:s=>n(e).insert(s)}),query:t,replace:(e,s)=>({with:i=>n(e).replace(s,i)}),update:(e,s)=>({set:i=>n(e).patch(s,i)})}};export{H as bindOrm,z as bindTableFacade,X as defineLazyFacade};
@@ -1 +1 @@
1
- import{LunoraError as r}from"@lunora/errors";import{c as m}from"./context-identity-B2XYGA0B.mjs";import{v as p,a as u}from"./functions-QFoBUe9t.mjs";import{toWhereInput as d,deny as c}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as b}from"./assertShapesDeclareReadPolicies-CZ4i2Kw6.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(t,w,n)=>{const s=p(e.args??{},w);u(t,e.args??{},s);const o=e.where?d(e.where(t,s)):void 0;if(e.owner===void 0)return o;const a=e.owner===!0?n?.ownerField:e.owner;if(a===void 0||a==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const h=m(t);if(h===void 0)return c();const l={[a]:h};return o===void 0?l:{AND:[l,o]}},rlsRegistry:b(e.use??[])}};export{I as defineShape};
1
+ import{LunoraError as r}from"@lunora/errors";import{c as m}from"./context-identity-B2XYGA0B.mjs";import{v as p,a as u}from"./functions-QFoBUe9t.mjs";import{toWhereInput as d,deny as c}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as b}from"./assertShapesDeclareReadPolicies-Bft5Rref.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(t,w,n)=>{const s=p(e.args??{},w);u(t,e.args??{},s);const o=e.where?d(e.where(t,s)):void 0;if(e.owner===void 0)return o;const a=e.owner===!0?n?.ownerField:e.owner;if(a===void 0||a==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const h=m(t);if(h===void 0)return c();const l={[a]:h};return o===void 0?l:{AND:[l,o]}},rlsRegistry:b(e.use??[])}};export{I as defineShape};
@@ -1 +1 @@
1
- import{LunoraError as O}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as _,b as G,c as x,d as C}from"./middleware-uLdnmn8f.mjs";import{defineLazyFacade as H,bindOrm as J}from"./bindOrm-DHtlrqCg.mjs";import{tagMaskMiddleware as T}from"./buildMaskRegistry-DpWMtalG.mjs";const Q=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},f=(s,i,c)=>{const u={...s};for(const[w,p]of Object.entries(i))w in u&&(u[w]=Q(p,s[w],{...c,column:w,row:s}));return u},B=(s,i,c)=>({...s,page:s.page.map(u=>f(u,i,c))}),P=(s,i)=>{const c=x(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},L=(s,i,c,u)=>{if(typeof s!="function")return;const w=new Set,p=()=>new Proxy({},{get:()=>a=>(typeof a=="string"&&w.add(a),p())});s(p());for(const a of w)if(P(i,a))throw new O("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${a}" is not supported`)},V=(s,i,c,u)=>{const w=s.rankBefore,p=s.rankPageRows,a=(r,n)=>{const t=i.get(r);return t?n.map(o=>f(o,t,c)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?a:(t,o)=>n(t,a(t,o))}},k=(r,n,t,o)=>{const e=i.get(r);if(!e)return;const d=u?.[r]?.[o]?.[n];if(!d)return;const h=d.find(I=>P(e,I));if(h!==void 0)throw new O("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${h}" — use an index whose declared fields are all unmasked, or unmask the column`)},A=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield f(o,n,c)},collect:async()=>(await r.collect()).map(e=>f(e,n,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const d=f(e.document,n,c);return"distanceMeters"in e?{distanceMeters:null,document:d}:{document:d,score:e.score}}),filter:o=>A(r.filter(e=>o(f(e,n,c))),n,t),first:async()=>{const o=await r.first();return o?f(o,n,c):null},order:o=>A(r.order(o),n,t),paginate:async o=>B(await r.paginate(o),n,c),take:async o=>(await r.take(o)).map(d=>f(d,n,c)),unique:async()=>{const o=await r.unique();return o?f(o,n,c):null},withIndex:(o,e)=>(k(t,o,"withIndex","index"),L(e,n,t,"withIndex"),A(r.withIndex(o,e),n,t)),withSearchIndex:(o,e)=>(L(e,n,t,"withSearchIndex"),A(r.withSearchIndex(o,e),n,t)),withGeoIndex:(o,e)=>(k(t,o,"withGeoIndex","geo"),A(r.withGeoIndex(o,e),n,t))}),S=(r,n,t)=>{const o=i.get(r);if(!o)return;const e=n.find(d=>typeof d=="string"&&P(o,d));if(e!==void 0)throw new O("MASK_UNSUPPORTED",`${t}() over masked column "${e}" on "${r}" is not supported`)},g=new Set;for(const r of i.values())for(const n of Object.keys(r))g.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,d]of Object.entries(r))K(e,d,n,t,o)},K=(r,n,t,o,e)=>{if(r==="AND"||r==="OR"){for(const d of Array.isArray(n)?n:[])R(d,t,o,e);return}if(r==="NOT"){R(n,t,o,e);return}if(!r.startsWith("__")){if(P(t,r))throw new O("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const d of Object.values(n))R(d,g,`${o}.${r}`,e)}},F=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},y=(r,n,t)=>{g.size===0||n===void 0||R(n,F(r),r,t)},E=(r,n,t,o)=>{if(Array.isArray(n)){for(const e of n)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const d of Object.keys(e))if(P(t,d))throw new O("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${d}" is not supported`)}}},j=(r,n,t)=>{if(!(g.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,e]of Object.entries(n)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const d=e,h=`${r}.${o}`;R(d.where,g,h,t),E(h,d.orderBy,g,t),j(h,d.with,t)}},W=(r,n,t)=>{y(r,n?.where,t),y(r,n?.baseWhere,t),E(r,n?.orderBy,F(r),t),j(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,$=(r,n,t)=>{const o=v(n);y(r,o?.where,t),y(r,o?.baseWhere,t),j(r,o?.with,t)},M=(r,n)=>Object.hasOwn(i.get(r)??{},n)?n:void 0,U={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[n,t]of Object.entries(s.relationWrites))r[n]=Object.fromEntries(Object.entries(t).map(([o,e])=>{const[d,h]=e.kind==="one"?[n,e.table]:[e.table,n],I=e.through?M(e.through.table,e.through.from)??M(e.through.table,e.through.to):M(d,e.field)??M(h,e.references);return[o,I===void 0?e:{...e,refusal:`"${I}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,n,t){if(y(r,n,"deleteMany({ where })"),s.deleteWhere===void 0)throw new O("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,n,t)},async patchIf(r,n,t){if(y(r,t.where,"patchIf"),s.patchIf===void 0)throw new O("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,n,t),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:f(o.doc,e,c)}:o},async patchWhere(r,n,t){if(y(r,n.where,"patchMany({ where })"),s.patchWhere===void 0)throw new O("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,n,t)},aggregate(r,n){return S(r,[n.field],"aggregate"),y(r,n.where,"aggregate"),s.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return y(r,o,"count"),t&&y(r,t.baseWhere,"count"),s.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await s.findFirst(r,l(n)),o=i.get(r);return t&&o?f(t,o,c):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await s.findFirstOrThrow(r,l(n)),o=i.get(r);return o?f(t,o,c):t},async explain(r,n){return W(r,n,"explain"),s.explain(r,n)},async findMany(r,n){W(r,n,"findMany");const t=await s.findMany(r,l(n)),o=i.get(r);return o?B(t,o,c):t},async get(r,n){const t=await s.get(r,n),o=i.get(r);return!t||!o?t:f(t,o,c)},related:s.related?async(r,n)=>await s.related(r,l(n)):void 0,async lookupById(r,n){const t=await s.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?f(t.row,o,c):t.row,tableName:t.tableName}},groupBy(r,n){return S(r,[...n.by,n.agg?.field],"groupBy"),y(r,n.where,"groupBy"),s.groupBy(r,n)},query(r){const n=s.query(r),t=i.get(r);return t?A(n,t,r):n},async rank(r,n,t){return $(r,t,"rank"),k(r,n,"rank","rank"),s.rank(r,n,t)},async rankPage(r,n,t){$(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await s.rankPage(r,n,t),e=i.get(r);return e?B(o,e,c):o},..._("rankBefore",w,r=>(n,t,o)=>($(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",p,r=>async(n,t,o)=>{$(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const e=await r(n,t,o),d=i.get(n);return d?{...e,rows:e.rows.map(h=>({...h,doc:f(h.doc,d,c)}))}:e})};if(g.size>0)for(const[r,n]of Object.entries(s))G(n)&&H(U,r);return U},rr=(s,i={})=>{const c=new Map(Object.entries(s)),u=q(i.roles),w=async({ctx:a,next:l})=>{const k={auth:await z(a.auth??{},u),ctx:a};if(i.bypass?.(k)===!0)return l();const A=V(a.db,c,k,i.indexFields),S={db:A},{orm:g}=a;return g!==null&&typeof g=="object"&&(S.orm=J(A)),l({ctx:S})},p=new Map;for(const[a,l]of c)p.set(a,new Set(Object.keys(l)));return T(w,{columns:p})};export{rr as mask};
1
+ import{LunoraError as O}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as _,b as G,c as x,d as C}from"./middleware-B0gy8zjo.mjs";import{defineLazyFacade as H,bindOrm as J}from"./bindOrm-BaLnyMcd.mjs";import{tagMaskMiddleware as T}from"./buildMaskRegistry-DpWMtalG.mjs";const Q=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},f=(s,i,c)=>{const u={...s};for(const[w,p]of Object.entries(i))w in u&&(u[w]=Q(p,s[w],{...c,column:w,row:s}));return u},B=(s,i,c)=>({...s,page:s.page.map(u=>f(u,i,c))}),P=(s,i)=>{const c=x(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},L=(s,i,c,u)=>{if(typeof s!="function")return;const w=new Set,p=()=>new Proxy({},{get:()=>a=>(typeof a=="string"&&w.add(a),p())});s(p());for(const a of w)if(P(i,a))throw new O("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${a}" is not supported`)},V=(s,i,c,u)=>{const w=s.rankBefore,p=s.rankPageRows,a=(r,n)=>{const t=i.get(r);return t?n.map(o=>f(o,t,c)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?a:(t,o)=>n(t,a(t,o))}},k=(r,n,t,o)=>{const e=i.get(r);if(!e)return;const d=u?.[r]?.[o]?.[n];if(!d)return;const h=d.find(I=>P(e,I));if(h!==void 0)throw new O("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${h}" — use an index whose declared fields are all unmasked, or unmask the column`)},A=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield f(o,n,c)},collect:async()=>(await r.collect()).map(e=>f(e,n,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const d=f(e.document,n,c);return"distanceMeters"in e?{distanceMeters:null,document:d}:{document:d,score:e.score}}),filter:o=>A(r.filter(e=>o(f(e,n,c))),n,t),first:async()=>{const o=await r.first();return o?f(o,n,c):null},order:o=>A(r.order(o),n,t),paginate:async o=>B(await r.paginate(o),n,c),take:async o=>(await r.take(o)).map(d=>f(d,n,c)),unique:async()=>{const o=await r.unique();return o?f(o,n,c):null},withIndex:(o,e)=>(k(t,o,"withIndex","index"),L(e,n,t,"withIndex"),A(r.withIndex(o,e),n,t)),withSearchIndex:(o,e)=>(L(e,n,t,"withSearchIndex"),A(r.withSearchIndex(o,e),n,t)),withGeoIndex:(o,e)=>(k(t,o,"withGeoIndex","geo"),A(r.withGeoIndex(o,e),n,t))}),S=(r,n,t)=>{const o=i.get(r);if(!o)return;const e=n.find(d=>typeof d=="string"&&P(o,d));if(e!==void 0)throw new O("MASK_UNSUPPORTED",`${t}() over masked column "${e}" on "${r}" is not supported`)},g=new Set;for(const r of i.values())for(const n of Object.keys(r))g.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,d]of Object.entries(r))K(e,d,n,t,o)},K=(r,n,t,o,e)=>{if(r==="AND"||r==="OR"){for(const d of Array.isArray(n)?n:[])R(d,t,o,e);return}if(r==="NOT"){R(n,t,o,e);return}if(!r.startsWith("__")){if(P(t,r))throw new O("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const d of Object.values(n))R(d,g,`${o}.${r}`,e)}},F=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},y=(r,n,t)=>{g.size===0||n===void 0||R(n,F(r),r,t)},E=(r,n,t,o)=>{if(Array.isArray(n)){for(const e of n)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const d of Object.keys(e))if(P(t,d))throw new O("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${d}" is not supported`)}}},j=(r,n,t)=>{if(!(g.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,e]of Object.entries(n)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const d=e,h=`${r}.${o}`;R(d.where,g,h,t),E(h,d.orderBy,g,t),j(h,d.with,t)}},W=(r,n,t)=>{y(r,n?.where,t),y(r,n?.baseWhere,t),E(r,n?.orderBy,F(r),t),j(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,$=(r,n,t)=>{const o=v(n);y(r,o?.where,t),y(r,o?.baseWhere,t),j(r,o?.with,t)},M=(r,n)=>Object.hasOwn(i.get(r)??{},n)?n:void 0,U={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[n,t]of Object.entries(s.relationWrites))r[n]=Object.fromEntries(Object.entries(t).map(([o,e])=>{const[d,h]=e.kind==="one"?[n,e.table]:[e.table,n],I=e.through?M(e.through.table,e.through.from)??M(e.through.table,e.through.to):M(d,e.field)??M(h,e.references);return[o,I===void 0?e:{...e,refusal:`"${I}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,n,t){if(y(r,n,"deleteMany({ where })"),s.deleteWhere===void 0)throw new O("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,n,t)},async patchIf(r,n,t){if(y(r,t.where,"patchIf"),s.patchIf===void 0)throw new O("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,n,t),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:f(o.doc,e,c)}:o},async patchWhere(r,n,t){if(y(r,n.where,"patchMany({ where })"),s.patchWhere===void 0)throw new O("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,n,t)},aggregate(r,n){return S(r,[n.field],"aggregate"),y(r,n.where,"aggregate"),s.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return y(r,o,"count"),t&&y(r,t.baseWhere,"count"),s.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await s.findFirst(r,l(n)),o=i.get(r);return t&&o?f(t,o,c):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await s.findFirstOrThrow(r,l(n)),o=i.get(r);return o?f(t,o,c):t},async explain(r,n){return W(r,n,"explain"),s.explain(r,n)},async findMany(r,n){W(r,n,"findMany");const t=await s.findMany(r,l(n)),o=i.get(r);return o?B(t,o,c):t},async get(r,n){const t=await s.get(r,n),o=i.get(r);return!t||!o?t:f(t,o,c)},related:s.related?async(r,n)=>await s.related(r,l(n)):void 0,async lookupById(r,n){const t=await s.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?f(t.row,o,c):t.row,tableName:t.tableName}},groupBy(r,n){return S(r,[...n.by,n.agg?.field],"groupBy"),y(r,n.where,"groupBy"),s.groupBy(r,n)},query(r){const n=s.query(r),t=i.get(r);return t?A(n,t,r):n},async rank(r,n,t){return $(r,t,"rank"),k(r,n,"rank","rank"),s.rank(r,n,t)},async rankPage(r,n,t){$(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await s.rankPage(r,n,t),e=i.get(r);return e?B(o,e,c):o},..._("rankBefore",w,r=>(n,t,o)=>($(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",p,r=>async(n,t,o)=>{$(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const e=await r(n,t,o),d=i.get(n);return d?{...e,rows:e.rows.map(h=>({...h,doc:f(h.doc,d,c)}))}:e})};if(g.size>0)for(const[r,n]of Object.entries(s))G(n)&&H(U,r);return U},rr=(s,i={})=>{const c=new Map(Object.entries(s)),u=q(i.roles),w=async({ctx:a,next:l})=>{const k={auth:await z(a.auth??{},u),ctx:a};if(i.bypass?.(k)===!0)return l();const A=V(a.db,c,k,i.indexFields),S={db:A},{orm:g}=a;return g!==null&&typeof g=="object"&&(S.orm=J(A)),l({ctx:S})},p=new Map;for(const[a,l]of c)p.set(a,new Set(Object.keys(l)));return T(w,{columns:p})};export{rr as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as w,isLunoraError as be}from"@lunora/errors";import{findRelated as Oe,whereFilter as ve}from"@lunora/shard-engine";import{isPlainObject as Q}from"@lunora/wire";import{defineLazyFacade as We,bindOrm as Re}from"./bindOrm-BaLnyMcd.mjs";import{t as Ee}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ae}from"./allowAll-DkRAgItV.mjs";const X=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},te=4;class P extends Error{}const C=e=>e.includes("."),wt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},ie=e=>{const t=e.split(".");if(t.length>te||t.includes(""))throw new P(`field path "${e}" must have 1 to ${String(te)} non-empty segments`);return t},Be=(e,t)=>{if(!C(t))return e[t];let r=e;for(const s of ie(t)){if(!X(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},ae=(e,t,r,s)=>{const[a,...f]=t;if(a===void 0)throw new P(`field path "${s}" is empty`);if(e!=null&&!X(e))throw new P(`cannot set "${s}": "${a}" sits inside a value that is not an object`);const u=e??{};return{...u,[a]:f.length===0?r:ae(u[a],f,r,s)}},Se=(e,t)=>{const r=Object.keys(e).filter(a=>C(a));if(r.length===0)return e;for(const a of r){const f=r.find(u=>u!==a&&u.startsWith(`${a}.`));if(f!==void 0)throw new P(`patch sets both "${a}" and "${f}", which overlap; set one or the other`)}const s={};for(const[a,f]of Object.entries(e))C(a)||(s[a]=f);for(const a of r){const[f="",...u]=ie(a);if(Object.hasOwn(e,f))throw new P(`patch sets both "${f}" and "${a}"; set one or the other`);s[f]=ae(Object.hasOwn(s,f)?s[f]:t[f],u,e[a],a)}return s},Te=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},ke=["every","is","isNot","none","some"],Ie=new Set(ke),Pe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Ie.has(r))},ne=(e,t,r)=>t?{[e]:r(t)}:{},ce=500,Y=(e,t,r)=>{if(e!==void 0&&e!==Number.POSITIVE_INFINITY&&(!Number.isInteger(e)||e<0))throw r(`${t}: batch limit must be a non-negative integer`);return e??ce},z=(e,t,r,s)=>{if(e>t)throw s(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},G={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const le=e=>{if(!X(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(G,r)))return{operand:e[r],operator:r}},me=e=>le(e)!==void 0,_e=(e,t,r,s)=>{const a=G[t];if(a.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const f=a.apply(s,r);if(!Number.isFinite(f))throw new R(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},fe=(e,t)=>{const r=new Set;for(const[s,a]of Object.entries(e))t(s)!==void 0&&me(a)&&r.add(s);return r},$e=(e,t,r)=>{let s;for(const a of fe(e,r)){const{operand:f,operator:u}=le(e[a]),b=r(a);if(G[u].kind!==b)throw new R(`patch: "${u}" does not apply to the ${String(b)} column "${a}".`);s??={...e},s[a]=_e(a,u,f,t[a])}return s??e},De=(e,t)=>{const r=a=>{const f=t[a];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},s={...e};for(const a of fe(e,r))try{Object.assign(s,$e({[a]:e[a]},t,r))}catch(f){if(!(f instanceof R))throw f}try{return Se(s,t)}catch(a){if(a instanceof P)return s;throw a}},Fe=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,S=0,E=1,m=e=>e?E:B,g=(e,t)=>e<t?e:t,Me=(e,t)=>e>t?e:t,de=e=>e===S?S:m(e===B),re=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},T=e=>e==null,$=(e,t,r)=>{if(r===void 0)throw new w("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Le={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},je=(e,t,r)=>{let s=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const f=r[a];$(e,a,f);const u=C(e);if(u?Te(f)===void 0:!re(f))s=g(s,B);else if(T(t))s=g(s,S);else{const b=Le[a],y=u?typeof t==typeof f:re(t);s=g(s,m(y&&b(t,f)))}}return s},oe=(e,t,r)=>{if(!Array.isArray(r))throw new w("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new w("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},se=(e,t)=>t.length===0?B:T(e)?S:t.includes(e)?E:t.some(r=>T(r))?S:B,Ce=(e,t,r)=>{let s=E;if("in"in r&&(s=g(s,se(t,oe(e,"in",r.in)))),"notIn"in r&&(s=g(s,de(se(t,oe(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;$(e,"contains",a),s=T(t)?g(s,S):g(s,m(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(s=g(s,m(r.isNull===!0===T(t)))),s},H=(e,t,r)=>t===null?m(r===T(e)):T(e)?S:m(r===(e===t)),Ue=(e,t,r)=>{let s=E;return"eq"in r&&($(e,"eq",r.eq),s=g(s,H(t,r.eq,!0))),"ne"in r&&($(e,"ne",r.ne),s=g(s,H(t,r.ne,!1))),s},Ne=(e,t,r)=>g(Ue(e,t,r),g(Ce(e,t,r),je(e,t,r))),xe=(e,t,r,s)=>{if(t==="NOT")return de(s(e,r??{}));if(!Array.isArray(r))return B;let a=t==="AND"?E:B;for(const f of r){const u=s(e,f);a=t==="AND"?g(a,u):Me(a,u)}return a},ue=e=>e==="AND"||e==="OR"||e==="NOT",qe=e=>Q(e)&&Object.keys(e).every(t=>Fe.includes(t)),U=e=>Object.keys(e).some(t=>{const r=e[t];return ue(t)?t==="NOT"?U(r??{}):Array.isArray(r)&&r.some(s=>U(s??{})):Pe(r)}),he=(e,t)=>{let r=E;for(const s of Object.keys(t)){const a=t[s];if(ue(s)){r=g(r,xe(e,s,a,he));continue}const f=Be(e,s);if(qe(a)){r=g(r,Ne(s,f,a));continue}$(s,"eq",a),r=g(r,H(f,a,!0))}return r},N=(e,t)=>he(e,t)===E,I=e=>new w("BATCH_LIMIT_EXCEEDED",e,{status:400}),j=(e,t,r)=>{z(e,Y(t,r,I),r,I)},Ye=Ae(),ze=Symbol.for("lunora.ctxdb.rls-unwrap"),ye=Symbol.for("lunora.rls.wrapped-chain"),He=e=>e[ye],Ke=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Qe=(e,t)=>{const r=[];let s=!1;for(const a of e){if(a.on!=="read")continue;const f=a.when(t);if(f!==void 0){if(f===!0){s=!0;break}f!==!1&&r.push(f)}}if(!s)return r.length===0?Ye:r.length===1?r[0]:{OR:r}},Xe=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(U(s))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return N(r,s)},Ge=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||Xe(e,t,r);if(s===!1)return!1;if(U(s))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!N(t.row,s)?!1:r===void 0||N(r,s)},Je=(e,t,r,s)=>{let a=!1;for(const f of e)if(f.on===t&&(a=!0,!Ge(f,r,s)))return!1;return a},Ze=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ve=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":Q(t),et=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ze.has(r)&&Ve(r,e[r]))},tt=e=>e===void 0?{}:Q(e)&&et(e)?e:{where:e},K=e=>e!==void 0&&Object.keys(e).length>0,nt=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},v=(e,t)=>K(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,rt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},ot=(e,t,r)=>{const[s]=r,a=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const i=[];let c=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(_=>_.on==="read"))continue;c=!0;const O=Qe(h,d.context);O!==void 0&&i.push(O)}const l={baseWhere:nt(i),restricts:c};return f.set(n,l),l},b=(n,o,i,c)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!Je(d,o,{...l.context,row:i},c))return!1}return!0},y=n=>u(n).restricts?t:e,p=n=>u(n).baseWhere,A=async(n,o)=>{const i=await t.get(n,o);return i?{row:i,tableName:a.has(n)?n:void 0}:{row:null,tableName:void 0}},x=async n=>{if(t.lookupById){const l=await t.lookupById(n);if(l)return{row:l.row,tableName:a.has(l.tableName)?l.tableName:void 0}}const o=[...a.keys()],c=(await Promise.all(o.map(async l=>{const d=await t.findFirst(l,{limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:l}:void 0}))).find(l=>l!==void 0);return c?{row:c.row,tableName:c.tableName}:{row:null,tableName:void 0}},q=async(n,o)=>{const i=await A(n,o);return i.row&&i.tableName!==void 0?{row:i.row,tableName:i.tableName}:void 0},W=async(n,o,i,c,l)=>{const d=await q(n,o);if(!d)return c(e);const h=l?l(d.row):void 0;if(!b(d.tableName,i,d.row,h))throw new w("FORBIDDEN",`${i} denied by policy`);return c(t,d.tableName)},D=(n,o,i)=>{if(i?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},F=async(n,o,i,c,l)=>{const d=i?t:e,h=await d.findFirst(o,{...i?{baseWhere:u(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:p,where:l===void 0?{_id:n}:v(l,{_id:n})});if(!h||D(o,h,c))return!1;if(i&&!b(o,"delete",h))throw new w("FORBIDDEN","delete denied by policy");return await d.delete(o,n,c),!0},J=async(n,o,i,c)=>{const l=a.has(n),d=l?t:e,h=i===void 0?void 0:{hard:i},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let _=0;for(const V of o){const ee=String(V._id);if(O){await F(ee,n,l,h,c)&&(_+=1);continue}if(l&&!b(n,"delete",V))throw new w("FORBIDDEN","delete denied by policy");await d.delete(n,ee,h),_+=1}return _},M=(n,o,i,c)=>W(n,o,"update",(l,d)=>c(l,{verify:d===void 0?void 0:(h,O)=>b(d,"update",h,O)}),l=>({...l,...De(i,l)})),L=(n,o)=>{const{baseWhere:i}=u(n);if(K(i))throw new w("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},we=e.rankBefore,ge=e.rankPageRows,{relationEdges:Z}=e,k={...e,async count(n,o){const{baseWhere:i}=u(n),c=tt(o);return y(n).count(n,{...c,baseWhere:v(c.baseWhere,i),relationBaseWhere:p,restrictsCounts:(c.restrictsCounts??!1)||K(i)})},delete:(n,o,i)=>W(n,o,"delete",c=>c.delete(n,o,i)),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??ce),{baseWhere:c}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:c,limit:i,relationBaseWhere:p}),{page:h}=d;if(h.length===0||(l+=await J(n,h,o?.hard),h.length<i))break}return{deleted:l}},async deleteMany(n,o,i){j(o.length,i?.limit,"deleteMany");for(const c of o)await W(n,c,"delete",l=>l.delete(n,c));return{deleted:o.length}},async deleteWhere(n,o,i){const{baseWhere:c}=u(n),l=Y(i?.limit,"deleteWhere",I),d=await y(n).findMany(n,{baseWhere:v(o,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:p}),h=d.page.map(O=>String(O._id));return z(h.length,l,"deleteWhere",I),{deleted:await J(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:i}=u(n);return y(n).findFirst(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:p})},async findFirstOrThrow(n,o){const{baseWhere:i}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:p})},async explain(n,o){const{baseWhere:i}=u(n);return y(n).explain(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:p})},async findMany(n,o){const{baseWhere:i}=u(n);return y(n).findMany(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:p})},async get(n,o){const i=await A(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:l}=u(i.tableName);if(!l)return e.get(n,o);if(!c)return i.row;const d=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const i=o===void 0?await x(n):await A(o,n);if(!i.row)return null;if(i.tableName===void 0||!u(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=u(i.tableName);if(!c)return{row:i.row,tableName:i.tableName};const l=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:i.tableName}:null},async insert(n,o,i){if(a.has(n)){if(!b(n,"insert",o))throw new w("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(j(o.length,i?.limit,"insertMany"),a.has(n)){for(const c of o)if(!b(n,"insert",c))throw new w("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(j(o.length,i?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!b(n,"insert",c))throw new w("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i,c)=>M(n,o,i,(l,d)=>l.patch(n,o,i,{...c,...d})),assertPatchAllowed:(n,o)=>M(n,o,{},()=>Promise.resolve()),async patchIf(n,o,i){const c=await M(n,o,i.patch,async(d,h)=>{if(d.patchIf===void 0)throw new w("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return d.patchIf(n,o,{...i,verify:h.verify})});return c.doc===null||await k.get(n,o).then(d=>d!==null,d=>{if(be(d)&&d.code==="RLS_REQUIRED")return!1;throw d})?c:{applied:c.applied,doc:null}},async patchMany(n,o,i){j(o.length,i?.limit,"patchMany");for(const c of o)await M(n,c.id,c.patch,(l,d)=>l.patch(n,c.id,c.patch,d));return{patched:o.length}},async patchWhere(n,o,i){const{baseWhere:c}=u(n),l=Y(i?.limit,"patchWhere",I),h=(await y(n).findMany(n,{baseWhere:v(o.where,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:p})).page.map(O=>({id:String(O._id),patch:o.patch}));return z(h.length,l,"patchWhere",I),k.patchMany(n,h,i)},query(n){const{baseWhere:o}=u(n),i=y(n).query(n);return o?i.filter(ve(o,c=>N(c,o))):i},related:Z===void 0?void 0:async(n,o)=>Oe({findMany:async(i,c)=>k.findMany(i,c),lookupById:async i=>t.lookupById?.(i)},Z,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>W(n,o,"update",async i=>{const c=i.restore??t.restore;if(!c)throw new w("BAD_REQUEST","restore is not supported by this writer");await c(n,o)}),replace:(n,o,i)=>W(n,o,"update",c=>c.replace(n,o,i),c=>({...i,_creationTime:i._creationTime??c._creationTime,_id:c._id})),aggregate(n,o){const{baseWhere:i}=u(n);return y(n).aggregate(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:p})},groupBy(n,o){const{baseWhere:i}=u(n);return y(n).groupBy(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:p})},rank(n,o,i){return L(n,"rank"),y(n).rank(n,o,i)},rankPage(n,o,i){return L(n,"rankPage"),y(n).rankPage(n,o,i)},wipeShard(){throw new w("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...ne("rankBefore",we,n=>(o,i,c)=>(L(o,"rankBefore"),(y(o).rankBefore??n)(o,i,c))),...ne("rankPageRows",ge,n=>(o,i,c)=>(L(o,"rankPageRows"),(y(o).rankPageRows??n)(o,i,c)))};if(a.size>0)for(const[n,o]of Object.entries(e))rt(o)&&We(k,n);return Object.defineProperty(k,ye,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),k},pe=e=>typeof e=="string"?e:e.name,st=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>pe(s))));return t},it=(e,t)=>{const r=new Set;for(const s of e)for(const a of t.get(s)??[])r.add(a);return s=>r.has(pe(s))},at=["roles","role"],ct=e=>{for(const t of at){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(a=>typeof a=="string"&&a.length>0);if(s.length>0)return s}}return[]},lt=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...ct(r),...e.roles??[]])];return{can:it(s,t),identity:r,roles:s,userId:e.userId??null}},gt=(e,t={})=>{const r=e,s=Ke(r),a=st(t.roles);return Ee(async({ctx:u,next:b})=>{const y={auth:await lt(u.auth??{},a),ctx:u},p=u.db,A=He(p),x=A?.base??p,q=A?.raw??p[ze]??p,W=ot(x,q,[...A?.steps??[],{context:y,perTable:s}]),D={db:W},{orm:F}=u;return F!==null&&typeof F=="object"&&(D.orm=Re(W)),b({ctx:D})},[{policies:r,roles:t.roles??[]}])};export{lt as a,rt as b,wt as c,Pe as d,ct as e,Qe as f,it as g,Je as h,st as i,N as m,ne as o,gt as r};
@@ -1 +1 @@
1
- import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-uLdnmn8f.mjs";import"./bindOrm-DHtlrqCg.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,p as resolvePolicyAuth,c as rls};
1
+ import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-B0gy8zjo.mjs";import"./bindOrm-BaLnyMcd.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,p as resolvePolicyAuth,c as rls};
@@ -1 +1 @@
1
- import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-uLdnmn8f.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
1
+ import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-B0gy8zjo.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
@@ -1301,7 +1301,7 @@ interface DatabaseReader {
1301
1301
  *
1302
1302
  * ```ts
1303
1303
  * for (const patch of plan.patches) {
1304
- * await ctx.db.patch(ctx.db.asId("nodes", patch.id), patch.fields);
1304
+ * await ctx.db.patch("nodes", ctx.db.asId("nodes", patch.id), patch.fields);
1305
1305
  * }
1306
1306
  * ```
1307
1307
  *
@@ -1625,7 +1625,7 @@ interface PatchIfResult {
1625
1625
  doc: Record<string, unknown> | null;
1626
1626
  }
1627
1627
  interface DatabaseWriter extends DatabaseReader {
1628
- delete: <T extends string>(id: Id<T>) => Promise<void>;
1628
+ delete: <T extends string>(table: T, id: Id<T>) => Promise<void>;
1629
1629
  /**
1630
1630
  * Delete EVERY row in `tableName`, chunking internally until the table is
1631
1631
  * empty — the erasure primitive.
@@ -1655,7 +1655,7 @@ interface DatabaseWriter extends DatabaseReader {
1655
1655
  * error) rolls back the whole mutation. (In an action there is no transaction
1656
1656
  * span, so the prior deletes persist; the in-memory test harness mirrors the span.)
1657
1657
  */
1658
- deleteMany: <T extends string>(ids: ReadonlyArray<Id<T>>, options?: BatchWriteOptions) => Promise<{
1658
+ deleteMany: <T extends string>(table: T, ids: ReadonlyArray<Id<T>>, options?: BatchWriteOptions) => Promise<{
1659
1659
  deleted: number;
1660
1660
  }>;
1661
1661
  /**
@@ -1718,7 +1718,7 @@ interface DatabaseWriter extends DatabaseReader {
1718
1718
  insertManyUnsafe: <T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options?: BatchWriteOptions & {
1719
1719
  allowExplicitId?: boolean;
1720
1720
  }) => Promise<Id<T>[]>;
1721
- patch: <T extends string>(id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1721
+ patch: <T extends string>(table: T, id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1722
1722
  /**
1723
1723
  * Conditional patch: apply `args.patch` to row `id` of `tableName` only while
1724
1724
  * the row as currently stored matches `args.where`, decided atomically with
@@ -1760,7 +1760,7 @@ interface DatabaseWriter extends DatabaseReader {
1760
1760
  * (In an action there is no transaction span, so the prior patches persist;
1761
1761
  * the in-memory test harness mirrors the span.)
1762
1762
  */
1763
- patchMany: <T extends string>(patches: ReadonlyArray<{
1763
+ patchMany: <T extends string>(table: T, patches: ReadonlyArray<{
1764
1764
  id: Id<T>;
1765
1765
  patch: Record<string, unknown>;
1766
1766
  }>, options?: BatchWriteOptions) => Promise<{
@@ -1781,7 +1781,7 @@ interface DatabaseWriter extends DatabaseReader {
1781
1781
  }, options?: BatchWriteOptions) => Promise<{
1782
1782
  patched: number;
1783
1783
  }>;
1784
- replace: <T extends string>(id: Id<T>, document: Record<string, unknown>) => Promise<void>;
1784
+ replace: <T extends string>(table: T, id: Id<T>, document: Record<string, unknown>) => Promise<void>;
1785
1785
  /**
1786
1786
  * Erase every shard-local table — the account-deletion / tenant-teardown
1787
1787
  * primitive. Sweeps the schema's non-`.global()` tables with
@@ -2194,16 +2194,16 @@ interface TriggerRankPageOptions {
2194
2194
  interface TriggerDatabase {
2195
2195
  aggregate: (tableName: string, options: TriggerAggregateOptions) => Promise<null | number>;
2196
2196
  count: (tableName: string, where?: Record<string, unknown>) => Promise<number>;
2197
- delete: (id: string) => Promise<void>;
2197
+ delete: (table: string, id: string) => Promise<void>;
2198
2198
  findFirst: (tableName: string, args?: TriggerQueryArgs) => Promise<Record<string, unknown> | null>;
2199
2199
  findMany: (tableName: string, args?: TriggerQueryArgs) => Promise<TriggerQueryPage>;
2200
2200
  get: (table: string, id: string) => Promise<Record<string, unknown> | null>;
2201
2201
  groupBy: (tableName: string, options: TriggerGroupByOptions) => Promise<ReadonlyArray<TriggerGroupByEntry>>;
2202
2202
  insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
2203
- patch: (id: string, patch: Record<string, unknown>) => Promise<void>;
2203
+ patch: (table: string, id: string, patch: Record<string, unknown>) => Promise<void>;
2204
2204
  rank: (tableName: string, indexName: string, options: TriggerRankOptions) => Promise<null | TriggerRankResult>;
2205
2205
  rankPage: (tableName: string, indexName: string, options?: TriggerRankPageOptions) => Promise<TriggerQueryPage>;
2206
- replace: (id: string, document: Record<string, unknown>) => Promise<void>;
2206
+ replace: (table: string, id: string, document: Record<string, unknown>) => Promise<void>;
2207
2207
  }
2208
2208
  /**
2209
2209
  * Handle injected into every trigger handler. `db` is the portable ORM writer;
@@ -1301,7 +1301,7 @@ interface DatabaseReader {
1301
1301
  *
1302
1302
  * ```ts
1303
1303
  * for (const patch of plan.patches) {
1304
- * await ctx.db.patch(ctx.db.asId("nodes", patch.id), patch.fields);
1304
+ * await ctx.db.patch("nodes", ctx.db.asId("nodes", patch.id), patch.fields);
1305
1305
  * }
1306
1306
  * ```
1307
1307
  *
@@ -1625,7 +1625,7 @@ interface PatchIfResult {
1625
1625
  doc: Record<string, unknown> | null;
1626
1626
  }
1627
1627
  interface DatabaseWriter extends DatabaseReader {
1628
- delete: <T extends string>(id: Id<T>) => Promise<void>;
1628
+ delete: <T extends string>(table: T, id: Id<T>) => Promise<void>;
1629
1629
  /**
1630
1630
  * Delete EVERY row in `tableName`, chunking internally until the table is
1631
1631
  * empty — the erasure primitive.
@@ -1655,7 +1655,7 @@ interface DatabaseWriter extends DatabaseReader {
1655
1655
  * error) rolls back the whole mutation. (In an action there is no transaction
1656
1656
  * span, so the prior deletes persist; the in-memory test harness mirrors the span.)
1657
1657
  */
1658
- deleteMany: <T extends string>(ids: ReadonlyArray<Id<T>>, options?: BatchWriteOptions) => Promise<{
1658
+ deleteMany: <T extends string>(table: T, ids: ReadonlyArray<Id<T>>, options?: BatchWriteOptions) => Promise<{
1659
1659
  deleted: number;
1660
1660
  }>;
1661
1661
  /**
@@ -1718,7 +1718,7 @@ interface DatabaseWriter extends DatabaseReader {
1718
1718
  insertManyUnsafe: <T extends string>(tableName: T, documents: ReadonlyArray<Record<string, unknown>>, options?: BatchWriteOptions & {
1719
1719
  allowExplicitId?: boolean;
1720
1720
  }) => Promise<Id<T>[]>;
1721
- patch: <T extends string>(id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1721
+ patch: <T extends string>(table: T, id: Id<T>, patch: Record<string, unknown>) => Promise<void>;
1722
1722
  /**
1723
1723
  * Conditional patch: apply `args.patch` to row `id` of `tableName` only while
1724
1724
  * the row as currently stored matches `args.where`, decided atomically with
@@ -1760,7 +1760,7 @@ interface DatabaseWriter extends DatabaseReader {
1760
1760
  * (In an action there is no transaction span, so the prior patches persist;
1761
1761
  * the in-memory test harness mirrors the span.)
1762
1762
  */
1763
- patchMany: <T extends string>(patches: ReadonlyArray<{
1763
+ patchMany: <T extends string>(table: T, patches: ReadonlyArray<{
1764
1764
  id: Id<T>;
1765
1765
  patch: Record<string, unknown>;
1766
1766
  }>, options?: BatchWriteOptions) => Promise<{
@@ -1781,7 +1781,7 @@ interface DatabaseWriter extends DatabaseReader {
1781
1781
  }, options?: BatchWriteOptions) => Promise<{
1782
1782
  patched: number;
1783
1783
  }>;
1784
- replace: <T extends string>(id: Id<T>, document: Record<string, unknown>) => Promise<void>;
1784
+ replace: <T extends string>(table: T, id: Id<T>, document: Record<string, unknown>) => Promise<void>;
1785
1785
  /**
1786
1786
  * Erase every shard-local table — the account-deletion / tenant-teardown
1787
1787
  * primitive. Sweeps the schema's non-`.global()` tables with
@@ -2194,16 +2194,16 @@ interface TriggerRankPageOptions {
2194
2194
  interface TriggerDatabase {
2195
2195
  aggregate: (tableName: string, options: TriggerAggregateOptions) => Promise<null | number>;
2196
2196
  count: (tableName: string, where?: Record<string, unknown>) => Promise<number>;
2197
- delete: (id: string) => Promise<void>;
2197
+ delete: (table: string, id: string) => Promise<void>;
2198
2198
  findFirst: (tableName: string, args?: TriggerQueryArgs) => Promise<Record<string, unknown> | null>;
2199
2199
  findMany: (tableName: string, args?: TriggerQueryArgs) => Promise<TriggerQueryPage>;
2200
2200
  get: (table: string, id: string) => Promise<Record<string, unknown> | null>;
2201
2201
  groupBy: (tableName: string, options: TriggerGroupByOptions) => Promise<ReadonlyArray<TriggerGroupByEntry>>;
2202
2202
  insert: (tableName: string, document: Record<string, unknown>) => Promise<string>;
2203
- patch: (id: string, patch: Record<string, unknown>) => Promise<void>;
2203
+ patch: (table: string, id: string, patch: Record<string, unknown>) => Promise<void>;
2204
2204
  rank: (tableName: string, indexName: string, options: TriggerRankOptions) => Promise<null | TriggerRankResult>;
2205
2205
  rankPage: (tableName: string, indexName: string, options?: TriggerRankPageOptions) => Promise<TriggerQueryPage>;
2206
- replace: (id: string, document: Record<string, unknown>) => Promise<void>;
2206
+ replace: (table: string, id: string, document: Record<string, unknown>) => Promise<void>;
2207
2207
  }
2208
2208
  /**
2209
2209
  * Handle injected into every trigger handler. `db` is the portable ORM writer;
@@ -1 +1 @@
1
- import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-uLdnmn8f.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
1
+ import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-B0gy8zjo.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
package/dist/types.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- export type { b as ActionCtx, t as AggregateIndexDefinition, h as AggregateOp, A as ArgsValidator, B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, s as DurableObjectJurisdiction, e as DurableStreamOptions, E as ExposeConfig, bl as ExternalSourceCursor, n as ExternalSourceDefinition, bm as ExternalSourceMode, bn as ExternalSourceRefresh, F as FunctionKind, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, G as GlobalBackend, Z as IndexDefinition, _ as IndexRangeBuilder, I as InferArgs, K as KeyedRelationDefinition, x as LifecycleEvent, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, M as MutationCtx, a5 as MutationStorage, O as OnDeleteAction, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, Q as QueryCtx, u as RankIndexDefinition, a9 as RankSortKey, aa as ReadOnlyStorage, R as RegisteredAction, g as RegisteredFunction, z as RegisteredLifecycleHook, c as RegisteredMutation, d as RegisteredQuery, f as RegisteredStream, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, k as RelationDefinition, i as RelationThrough, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, S as Schema, an as SearchFilterBuilder, ao as SearchIndexDefinition, l as SearchLanguage, m as SearchStrategy, v as Secrets, bo as SecretsStoreSecretLike, y as ShardInitEvent, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, T as TableDefinition, aN as TableReader, aO as TableVectorIndex, j as ThroughRelationDefinition, aP as TriggerAggregateOptions, o as TriggerBuilder, aQ as TriggerCtx, aR as TriggerDatabase, p as TriggerDefinition, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, q as VectorEmbedder, V as VectorIndexDefinition, b6 as VectorMatch, b7 as VectorMatches, r as VectorMetric, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, W as WhisperEvent, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows, X as X402ProcedureConfig } from "./packem_shared/types.d-DYL1koQt.mjs";
1
+ export type { b as ActionCtx, t as AggregateIndexDefinition, h as AggregateOp, A as ArgsValidator, B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, s as DurableObjectJurisdiction, e as DurableStreamOptions, E as ExposeConfig, bl as ExternalSourceCursor, n as ExternalSourceDefinition, bm as ExternalSourceMode, bn as ExternalSourceRefresh, F as FunctionKind, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, G as GlobalBackend, Z as IndexDefinition, _ as IndexRangeBuilder, I as InferArgs, K as KeyedRelationDefinition, x as LifecycleEvent, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, M as MutationCtx, a5 as MutationStorage, O as OnDeleteAction, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, Q as QueryCtx, u as RankIndexDefinition, a9 as RankSortKey, aa as ReadOnlyStorage, R as RegisteredAction, g as RegisteredFunction, z as RegisteredLifecycleHook, c as RegisteredMutation, d as RegisteredQuery, f as RegisteredStream, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, k as RelationDefinition, i as RelationThrough, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, S as Schema, an as SearchFilterBuilder, ao as SearchIndexDefinition, l as SearchLanguage, m as SearchStrategy, v as Secrets, bo as SecretsStoreSecretLike, y as ShardInitEvent, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, T as TableDefinition, aN as TableReader, aO as TableVectorIndex, j as ThroughRelationDefinition, aP as TriggerAggregateOptions, o as TriggerBuilder, aQ as TriggerCtx, aR as TriggerDatabase, p as TriggerDefinition, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, q as VectorEmbedder, V as VectorIndexDefinition, b6 as VectorMatch, b7 as VectorMatches, r as VectorMetric, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, W as WhisperEvent, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows, X as X402ProcedureConfig } from "./packem_shared/types.d-BO1zQAnk.mjs";
2
2
  import '@lunora/values';
package/dist/types.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export type { b as ActionCtx, t as AggregateIndexDefinition, h as AggregateOp, A as ArgsValidator, B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, s as DurableObjectJurisdiction, e as DurableStreamOptions, E as ExposeConfig, bl as ExternalSourceCursor, n as ExternalSourceDefinition, bm as ExternalSourceMode, bn as ExternalSourceRefresh, F as FunctionKind, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, G as GlobalBackend, Z as IndexDefinition, _ as IndexRangeBuilder, I as InferArgs, K as KeyedRelationDefinition, x as LifecycleEvent, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, M as MutationCtx, a5 as MutationStorage, O as OnDeleteAction, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, Q as QueryCtx, u as RankIndexDefinition, a9 as RankSortKey, aa as ReadOnlyStorage, R as RegisteredAction, g as RegisteredFunction, z as RegisteredLifecycleHook, c as RegisteredMutation, d as RegisteredQuery, f as RegisteredStream, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, k as RelationDefinition, i as RelationThrough, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, S as Schema, an as SearchFilterBuilder, ao as SearchIndexDefinition, l as SearchLanguage, m as SearchStrategy, v as Secrets, bo as SecretsStoreSecretLike, y as ShardInitEvent, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, T as TableDefinition, aN as TableReader, aO as TableVectorIndex, j as ThroughRelationDefinition, aP as TriggerAggregateOptions, o as TriggerBuilder, aQ as TriggerCtx, aR as TriggerDatabase, p as TriggerDefinition, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, q as VectorEmbedder, V as VectorIndexDefinition, b6 as VectorMatch, b7 as VectorMatches, r as VectorMetric, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, W as WhisperEvent, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows, X as X402ProcedureConfig } from "./packem_shared/types.d-DYL1koQt.js";
1
+ export type { b as ActionCtx, t as AggregateIndexDefinition, h as AggregateOp, A as ArgsValidator, B as AuthState, C as CachePurge, H as DatabaseReader, D as DatabaseWriter, s as DurableObjectJurisdiction, e as DurableStreamOptions, E as ExposeConfig, bl as ExternalSourceCursor, n as ExternalSourceDefinition, bm as ExternalSourceMode, bn as ExternalSourceRefresh, F as FunctionKind, J as FunctionVisibility, N as GeoBoundingBox, P as GeoFilterBuilder, U as GeoIndexDefinition, Y as GeoPointInput, G as GlobalBackend, Z as IndexDefinition, _ as IndexRangeBuilder, I as InferArgs, K as KeyedRelationDefinition, x as LifecycleEvent, $ as LifecycleEventKind, a0 as LogFields, a1 as LunoraLogMethod, a2 as LunoraLogger, a3 as LunoraMetrics, L as LunoraTracer, a4 as LunoraWideEvent, M as MutationCtx, a5 as MutationStorage, O as OnDeleteAction, a6 as PaginationOptions, a7 as PaginationResult, a8 as PatchIfResult, Q as QueryCtx, u as RankIndexDefinition, a9 as RankSortKey, aa as ReadOnlyStorage, R as RegisteredAction, g as RegisteredFunction, z as RegisteredLifecycleHook, c as RegisteredMutation, d as RegisteredQuery, f as RegisteredStream, ab as RelatedDirection, ac as RelatedNode, ad as RelatedOptions, ae as RelatedPage, af as RelatedStart, ag as RelatedStartReference, k as RelationDefinition, i as RelationThrough, ah as RestCacheConfig, ai as RetryPolicy, aj as RunQueryOptions, ak as ScheduledFunctionDoc, al as ScheduledJob, am as Scheduler, S as Schema, an as SearchFilterBuilder, ao as SearchIndexDefinition, l as SearchLanguage, m as SearchStrategy, v as Secrets, bo as SecretsStoreSecretLike, y as ShardInitEvent, ap as ShardMode, aq as SpanContextIds, ar as SpanEvaluation, a as SpanHandle, as as SpanIdentity, at as SpanKind, au as SpanLink, av as SpanOptions, aw as Storage, ax as StorageListOptions, ay as StorageListResult, az as StorageMetadata, aA as StorageMultipartUpload, aB as StorageMultipartUploadOptions, aC as StorageObjectBody, aD as StorageObjectHead, aE as StorageRange, aF as StorageUploadBody, aG as StorageUploadOptions, aH as StorageUploadResult, aI as StorageUploadedPart, aJ as SystemDatabaseReader, aK as SystemDoc, aL as SystemQuery, aM as SystemTableName, T as TableDefinition, aN as TableReader, aO as TableVectorIndex, j as ThroughRelationDefinition, aP as TriggerAggregateOptions, o as TriggerBuilder, aQ as TriggerCtx, aR as TriggerDatabase, p as TriggerDefinition, aS as TriggerDeleteEvent, aT as TriggerEvent, aU as TriggerGroupByEntry, aV as TriggerGroupByOptions, aW as TriggerHandler, aX as TriggerInsertEvent, aY as TriggerOp, aZ as TriggerQueryArgs, a_ as TriggerQueryPage, a$ as TriggerRankOptions, b0 as TriggerRankPageOptions, b1 as TriggerRankResult, b2 as TriggerRow, b3 as TriggerTiming, b4 as TriggerUpdateEvent, b5 as TtlDefinition, q as VectorEmbedder, V as VectorIndexDefinition, b6 as VectorMatch, b7 as VectorMatches, r as VectorMetric, b8 as VectorQueryInput, b9 as VectorRecord, ba as VectorSearch, bb as VectorSearchReader, bc as VectorUpsertInput, W as WhisperEvent, bd as WorkflowCreateOptions, be as WorkflowEventDefinition, bf as WorkflowHandle, bg as WorkflowInstance, bh as WorkflowInstanceEvent, bi as WorkflowInstanceStatus, bj as WorkflowStatusResult, bk as Workflows, X as X402ProcedureConfig } from "./packem_shared/types.d-BO1zQAnk.js";
2
2
  import '@lunora/values';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.241",
3
+ "version": "1.0.0-alpha.242",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -72,7 +72,7 @@
72
72
  "dependencies": {
73
73
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
74
74
  "@lunora/scheduler": "1.0.0-alpha.152",
75
- "@lunora/shard-engine": "1.0.0-alpha.162",
75
+ "@lunora/shard-engine": "1.0.0-alpha.163",
76
76
  "@lunora/values": "1.0.0-alpha.82",
77
77
  "@lunora/wire": "1.0.0-alpha.2",
78
78
  "drizzle-orm": "1.0.0-rc.5",
@@ -1 +0,0 @@
1
- import{isLunoraError as O}from"@lunora/errors";import{v as d}from"@lunora/values";import{decodeWire as U,encodeWire as D,stableWireKey as S}from"@lunora/wire";import{initLunora as F}from"./initLunora-DH7k24N0.mjs";import{g as k,h as q,a as B}from"./plugin-Bm9wIpiI.mjs";const P=3600*1e3,R=512*1024,H=8,b=64,V=64,K=256,W=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=r=>r===void 0?"":S(r),x=async(r,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${r}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},$=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:G}=F.dataModel().create(),Z=(r={})=>{const m=r.ttlMs!==void 0&&Number.isFinite(r.ttlMs)?Math.max(1,Math.floor(r.ttlMs)):P,A=r.maxValueBytes!==void 0&&Number.isFinite(r.maxValueBytes)?Math.max(1,Math.floor(r.maxValueBytes)):R,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(H)).filter(s=>s.expiresAt<=t);await Promise.all(n.map(async s=>e.db.delete(s._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),f=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),N=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(O(n)&&f.has(n.code))return;throw n}},I=async(e,t,a,n)=>{const s=T(a),i=await x(t,s),l=Date.now(),o=await C(e,i);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(D({v:p})),E=Date.now(),g=E+m;return new TextEncoder().encode(w).length<=A?await N(e,o,{expiresAt:g,key:i,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},M=async(e,t,a)=>{const n=await x(t,T(a)),s=await e.db.query(c).withIndex("byKey",i=>i.eq("key",n)).take(b);await Promise.all(s.map(async i=>e.db.delete(i._id)))},_=async(e,t,a,n)=>{if(n>=V)return{complete:!1,deleted:a};const s=await e.db.query(c).withIndex("byName",i=>i.eq("name",t)).take(b);return s.length===0?{complete:!0,deleted:a}:(await Promise.all(s.map(async i=>e.db.delete(i._id))),_(e,t,a+s.length,n+1))},L=async(e,t)=>_(e,t,0,0),v=G.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(W,Math.max(1,Math.floor(e.limit))):K,i=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(i.map(async l=>t.db.delete(l._id))),{deleted:i.length}});return{...B(u,{extension:$,functions:{purgeExpired:v}}),invalidate:M,invalidateAll:L,wrap:I}};export{P as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,$ as actionCacheExtension,x as cacheKeyFor,Z as defineActionCache};
@@ -1 +0,0 @@
1
- import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-DH7k24N0.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-Bm9wIpiI.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
@@ -1 +0,0 @@
1
- import{LunoraError as w,isLunoraError as ge}from"@lunora/errors";import{findRelated as be,whereFilter as Oe}from"@lunora/shard-engine";import{isPlainObject as Q}from"@lunora/wire";import{defineLazyFacade as ve,bindOrm as We}from"./bindOrm-DHtlrqCg.mjs";import{t as Re}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ee}from"./allowAll-DkRAgItV.mjs";const X=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},ee=4;class m extends Error{}const U=e=>e.includes("."),pt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},se=e=>{const t=e.split(".");if(t.length>ee||t.includes(""))throw new m(`field path "${e}" must have 1 to ${String(ee)} non-empty segments`);return t},Be=(e,t)=>{if(!U(t))return e[t];let r=e;for(const s of se(t)){if(!X(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},ie=(e,t,r,s)=>{const[a,...l]=t;if(a===void 0)throw new m(`field path "${s}" is empty`);if(e!=null&&!X(e))throw new m(`cannot set "${s}": "${a}" sits inside a value that is not an object`);const u=e??{};return{...u,[a]:l.length===0?r:ie(u[a],l,r,s)}},Se=(e,t)=>{const r=Object.keys(e).filter(a=>U(a));if(r.length===0)return e;for(const a of r){const l=r.find(u=>u!==a&&u.startsWith(`${a}.`));if(l!==void 0)throw new m(`patch sets both "${a}" and "${l}", which overlap; set one or the other`)}const s={};for(const[a,l]of Object.entries(e))U(a)||(s[a]=l);for(const a of r){const[l="",...u]=se(a);if(Object.hasOwn(e,l))throw new m(`patch sets both "${l}" and "${a}"; set one or the other`);s[l]=ie(Object.hasOwn(s,l)?s[l]:t[l],u,e[a],a)}return s},Ae=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},ke=["every","is","isNot","none","some"],Ie=new Set(ke),Pe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Ie.has(r))},te=(e,t,r)=>t?{[e]:r(t)}:{},ae=500,x=(e,t,r)=>{if(e!==void 0&&e!==Number.POSITIVE_INFINITY&&(!Number.isInteger(e)||e<0))throw r(`${t}: batch limit must be a non-negative integer`);return e??ae},z=(e,t,r,s)=>{if(e>t)throw s(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},G={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class W extends Error{}const ce=e=>{if(!X(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(G,r)))return{operand:e[r],operator:r}},me=e=>ce(e)!==void 0,_e=(e,t,r,s)=>{const a=G[t];if(a.apply===void 0){if(r!==!0)throw new W(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new W(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new W(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new W(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new W(`patch: cannot divide "${e}" by zero.`);const l=a.apply(s,r);if(!Number.isFinite(l))throw new W(`patch: "${t}" on "${e}" overflows to ${String(l)}.`);return l},le=(e,t)=>{const r=new Set;for(const[s,a]of Object.entries(e))t(s)!==void 0&&me(a)&&r.add(s);return r},Te=(e,t,r)=>{let s;for(const a of le(e,r)){const{operand:l,operator:u}=ce(e[a]),O=r(a);if(G[u].kind!==O)throw new W(`patch: "${u}" does not apply to the ${String(O)} column "${a}".`);s??={...e},s[a]=_e(a,u,l,t[a])}return s??e},$e=(e,t)=>{const r=a=>{const l=t[a];return typeof l=="number"||typeof l=="boolean"?typeof l:void 0},s={...e};for(const a of le(e,r))try{Object.assign(s,Te({[a]:e[a]},t,r))}catch(l){if(!(l instanceof W))throw l}try{return Se(s,t)}catch(a){if(a instanceof m)return s;throw a}},De=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],S=-1,A=0,R=1,_=e=>e?R:S,g=(e,t)=>e<t?e:t,Fe=(e,t)=>e>t?e:t,fe=e=>e===A?A:_(e===S),ne=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},k=e=>e==null,D=(e,t,r)=>{if(r===void 0)throw new w("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Me={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},Le=(e,t,r)=>{let s=R;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const l=r[a];D(e,a,l);const u=U(e);if(u?Ae(l)===void 0:!ne(l))s=g(s,S);else if(k(t))s=g(s,A);else{const O=Me[a],y=u?typeof t==typeof l:ne(t);s=g(s,_(y&&O(t,l)))}}return s},re=(e,t,r)=>{if(!Array.isArray(r))throw new w("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new w("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},oe=(e,t)=>t.length===0?S:k(e)?A:t.includes(e)?R:t.some(r=>k(r))?A:S,je=(e,t,r)=>{let s=R;if("in"in r&&(s=g(s,oe(t,re(e,"in",r.in)))),"notIn"in r&&(s=g(s,fe(oe(t,re(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;D(e,"contains",a),s=k(t)?g(s,A):g(s,_(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(s=g(s,_(r.isNull===!0===k(t)))),s},H=(e,t,r)=>t===null?_(r===k(e)):k(e)?A:_(r===(e===t)),Ce=(e,t,r)=>{let s=R;return"eq"in r&&(D(e,"eq",r.eq),s=g(s,H(t,r.eq,!0))),"ne"in r&&(D(e,"ne",r.ne),s=g(s,H(t,r.ne,!1))),s},Ue=(e,t,r)=>g(Ce(e,t,r),g(je(e,t,r),Le(e,t,r))),Ne=(e,t,r,s)=>{if(t==="NOT")return fe(s(e,r??{}));if(!Array.isArray(r))return S;let a=t==="AND"?R:S;for(const l of r){const u=s(e,l);a=t==="AND"?g(a,u):Fe(a,u)}return a},de=e=>e==="AND"||e==="OR"||e==="NOT",qe=e=>Q(e)&&Object.keys(e).every(t=>De.includes(t)),N=e=>Object.keys(e).some(t=>{const r=e[t];return de(t)?t==="NOT"?N(r??{}):Array.isArray(r)&&r.some(s=>N(s??{})):Pe(r)}),ue=(e,t)=>{let r=R;for(const s of Object.keys(t)){const a=t[s];if(de(s)){r=g(r,Ne(e,s,a,ue));continue}const l=Be(e,s);if(qe(a)){r=g(r,Ue(s,l,a));continue}D(s,"eq",a),r=g(r,H(l,a,!0))}return r},q=(e,t)=>ue(e,t)===R,P=e=>new w("BATCH_LIMIT_EXCEEDED",e,{status:400}),C=(e,t,r)=>{z(e,x(t,r,P),r,P)},Ye=Ee(),xe=Symbol.for("lunora.ctxdb.rls-unwrap"),he=Symbol.for("lunora.rls.wrapped-chain"),ze=e=>e[he],He=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Ke=(e,t)=>{const r=[];let s=!1;for(const a of e){if(a.on!=="read")continue;const l=a.when(t);if(l!==void 0){if(l===!0){s=!0;break}l!==!1&&r.push(l)}}if(!s)return r.length===0?Ye:r.length===1?r[0]:{OR:r}},Qe=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(N(s))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return q(r,s)},Xe=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||Qe(e,t,r);if(s===!1)return!1;if(N(s))throw new w("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!q(t.row,s)?!1:r===void 0||q(r,s)},Ge=(e,t,r,s)=>{let a=!1;for(const l of e)if(l.on===t&&(a=!0,!Xe(l,r,s)))return!1;return a},Je=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ze=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":Q(t),Ve=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Je.has(r)&&Ze(r,e[r]))},et=e=>e===void 0?{}:Q(e)&&Ve(e)?e:{where:e},K=e=>e!==void 0&&Object.keys(e).length>0,tt=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},v=(e,t)=>K(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,nt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},rt=(e,t,r)=>{const[s]=r,a=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),l=new Map,u=n=>{const o=l.get(n);if(o)return o;const i=[];let c=!1;for(const h of r){const d=h.perTable.get(n);if(!d||d.length===0||!d.some($=>$.on==="read"))continue;c=!0;const b=Ke(d,h.context);b!==void 0&&i.push(b)}const f={baseWhere:tt(i),restricts:c};return l.set(n,f),f},O=(n,o,i,c)=>{for(const f of r){const h=f.perTable.get(n);if(h&&!Ge(h,o,{...f.context,row:i},c))return!1}return!0},y=n=>u(n).restricts?t:e,p=n=>u(n).baseWhere,E=async(n,o,i)=>{if(o!==void 0){const d=await t.get(o,n);return d?{row:d,tableName:a.has(o)?o:void 0}:{row:null,tableName:void 0}}if(t.lookupById){const d=await t.lookupById(n);if(d)return{row:d.row,tableName:a.has(d.tableName)?d.tableName:void 0}}const c=[...a.keys()],h=(await Promise.all(c.map(async d=>{const b=await t.findFirst(d,{limit:1,where:{_id:n}});return b?._id===n?{row:b,tableName:d}:void 0}))).find(d=>d!==void 0);return h?{row:h.row,tableName:h.tableName}:{row:null,tableName:void 0}},Y=async(n,o,i)=>{const c=await E(n,o);return c.row&&c.tableName!==void 0?{row:c.row,tableName:c.tableName}:void 0},B=async(n,o,i,c,f,h)=>{const d=await Y(n,f);if(!d)return i(e);const b=c?c(d.row):void 0;if(!O(d.tableName,o,d.row,b))throw new w("FORBIDDEN",`${o} denied by policy`);return i(t,d.tableName)},F=(n,o,i)=>{if(i?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},M=async(n,o,i,c,f)=>{const h=i?t:e,d=await h.findFirst(o,{...i?{baseWhere:u(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:p,where:f===void 0?{_id:n}:v(f,{_id:n})});if(!d||F(o,d,c))return!1;if(i&&!O(o,"delete",d))throw new w("FORBIDDEN","delete denied by policy");return await h.delete(n,o,c),!0},T=async(n,o,i,c)=>{const f=a.has(n),h=f?t:e,d=i===void 0?void 0:{hard:i},b=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let $=0;for(const Z of o){const V=String(Z._id);if(b){await M(V,n,f,d,c)&&($+=1);continue}if(f&&!O(n,"delete",Z))throw new w("FORBIDDEN","delete denied by policy");await h.delete(V,n,d),$+=1}return $},L=(n,o,i,c)=>B(n,"update",(f,h)=>i(f,{verify:h===void 0?void 0:(d,b)=>O(h,"update",d,b)}),f=>({...f,...$e(o,f)}),c),j=(n,o)=>{const{baseWhere:i}=u(n);if(K(i))throw new w("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},pe=e.rankBefore,we=e.rankPageRows,{relationEdges:J}=e,I={...e,async count(n,o){const{baseWhere:i}=u(n),c=et(o);return y(n).count(n,{...c,baseWhere:v(c.baseWhere,i),relationBaseWhere:p,restrictsCounts:(c.restrictsCounts??!1)||K(i)})},delete:(n,o,i)=>B(n,"delete",c=>c.delete(n,o,i),void 0,o),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??ae),{baseWhere:c}=u(n);let f=0;for(;;){const h=await y(n).findMany(n,{baseWhere:c,limit:i,relationBaseWhere:p}),{page:d}=h;if(d.length===0||(f+=await T(n,d,o?.hard),d.length<i))break}return{deleted:f}},async deleteMany(n,o,i){C(n.length,o?.limit,"deleteMany");for(const c of n)await B(c,"delete",f=>f.delete(c,i),void 0,i);return{deleted:n.length}},async deleteWhere(n,o,i){const{baseWhere:c}=u(n),f=x(i?.limit,"deleteWhere",P),h=await y(n).findMany(n,{baseWhere:v(o,c),...Number.isFinite(f)?{limit:f+1}:{},relationBaseWhere:p}),d=h.page.map(b=>String(b._id));return z(d.length,f,"deleteWhere",P),{deleted:await T(n,h.page,void 0,o)}},async findFirst(n,o){const{baseWhere:i}=u(n);return y(n).findFirst(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:p})},async findFirstOrThrow(n,o){const{baseWhere:i}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:p})},async explain(n,o){const{baseWhere:i}=u(n);return y(n).explain(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:p})},async findMany(n,o){const{baseWhere:i}=u(n);return y(n).findMany(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:p})},async get(n,o){const i=await E(o,n);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:f}=u(i.tableName);if(!f)return e.get(n,o);if(!c)return i.row;const h=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:o}});return h?._id===o?h:null},async lookupById(n,o){const i=await E(n,o);if(!i.row)return null;if(i.tableName===void 0||!u(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=u(i.tableName);if(!c)return{row:i.row,tableName:i.tableName};const f=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return f?._id===n?{row:f,tableName:i.tableName}:null},async insert(n,o,i){if(a.has(n)){if(!O(n,"insert",o))throw new w("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(C(o.length,i?.limit,"insertMany"),a.has(n)){for(const c of o)if(!O(n,"insert",c))throw new w("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(C(o.length,i?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!O(n,"insert",c))throw new w("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i)=>L(n,o,(c,f)=>c.patch(n,o,i,f),i),assertPatchAllowed:(n,o)=>L(n,{},()=>Promise.resolve(),o),async patchIf(n,o,i){const c=await L(o,i.patch,async(h,d)=>{if(h.patchIf===void 0)throw new w("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return h.patchIf(n,o,{...i,verify:d.verify})},n);return c.doc===null||await I.get(n,o).then(h=>h!==null,h=>{if(ge(h)&&h.code==="RLS_REQUIRED")return!1;throw h})?c:{applied:c.applied,doc:null}},async patchMany(n,o,i){C(n.length,o?.limit,"patchMany");for(const c of n)await L(c.id,c.patch,(f,h)=>f.patch(c.id,c.patch,i,h),i);return{patched:n.length}},async patchWhere(n,o,i){const{baseWhere:c}=u(n),f=x(i?.limit,"patchWhere",P),d=(await y(n).findMany(n,{baseWhere:v(o.where,c),...Number.isFinite(f)?{limit:f+1}:{},relationBaseWhere:p})).page.map(b=>({id:String(b._id),patch:o.patch}));return z(d.length,f,"patchWhere",P),I.patchMany(d,i)},query(n){const{baseWhere:o}=u(n),i=y(n).query(n);return o?i.filter(Oe(o,c=>q(c,o))):i},related:J===void 0?void 0:async(n,o)=>be({findMany:async(i,c)=>I.findMany(i,c),lookupById:async i=>t.lookupById?.(i)},J,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>B(n,"update",async i=>{const c=i.restore??t.restore;if(!c)throw new w("BAD_REQUEST","restore is not supported by this writer");await c(n,o)},void 0,o),replace:(n,o,i)=>B(n,"update",c=>c.replace(n,o,i),c=>({...o,_creationTime:o._creationTime??c._creationTime,_id:c._id}),i),aggregate(n,o){const{baseWhere:i}=u(n);return y(n).aggregate(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:p})},groupBy(n,o){const{baseWhere:i}=u(n);return y(n).groupBy(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:p})},rank(n,o,i){return j(n,"rank"),y(n).rank(n,o,i)},rankPage(n,o,i){return j(n,"rankPage"),y(n).rankPage(n,o,i)},wipeShard(){throw new w("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...te("rankBefore",pe,n=>(o,i,c)=>(j(o,"rankBefore"),(y(o).rankBefore??n)(o,i,c))),...te("rankPageRows",we,n=>(o,i,c)=>(j(o,"rankPageRows"),(y(o).rankPageRows??n)(o,i,c)))};if(a.size>0)for(const[n,o]of Object.entries(e))nt(o)&&ve(I,n);return Object.defineProperty(I,he,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),I},ye=e=>typeof e=="string"?e:e.name,ot=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>ye(s))));return t},st=(e,t)=>{const r=new Set;for(const s of e)for(const a of t.get(s)??[])r.add(a);return s=>r.has(ye(s))},it=["roles","role"],at=e=>{for(const t of it){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(a=>typeof a=="string"&&a.length>0);if(s.length>0)return s}}return[]},ct=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...at(r),...e.roles??[]])];return{can:st(s,t),identity:r,roles:s,userId:e.userId??null}},wt=(e,t={})=>{const r=e,s=He(r),a=ot(t.roles);return Re(async({ctx:u,next:O})=>{const y={auth:await ct(u.auth??{},a),ctx:u},p=u.db,E=ze(p),Y=E?.base??p,B=E?.raw??p[xe]??p,F=rt(Y,B,[...E?.steps??[],{context:y,perTable:s}]),M={db:F},{orm:T}=u;return T!==null&&typeof T=="object"&&(M.orm=We(F)),O({ctx:M})},[{policies:r,roles:t.roles??[]}])};export{ct as a,nt as b,pt as c,Pe as d,at as e,Ke as f,st as g,Ge as h,ot as i,q as m,te as o,wt as r};