@lunora/server 1.0.0-alpha.285 → 1.0.0-alpha.287

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.
@@ -1 +1 @@
1
- import{LunoraError as R}from"@lunora/errors";import{TransactionHeadroomTracker as l,runShardMigrations as p,createShardCtxDb as w,RLS_UNWRAP_SYMBOL as T}from"@lunora/shard-engine";import{beginDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{bindTableFacade as S}from"./packem_shared/bindOrm-D5mVDvbi.mjs";class y extends l{fallback=new l;scope;constructor(r){super(),this.scope=r}run(r){return this.scope===void 0?(this.fallback=new l,r()):this.scope.run(new l,r)}headroom(){return this.current().headroom()}recordRead(r){this.current().recordRead(r)}recordReadBytes(r){this.current().recordReadBytes(r)}recordDocumentRead(r,n){this.current().recordDocumentRead(r,n)}recordWrite(r){this.current().recordWrite(r)}current(){return this.scope?.getStore()??this.fallback}}const C=e=>{if(e===null||typeof e.userId!="string"||e.userId.length===0)return{claims:null,userId:null};const{userId:r,...n}=e;return{claims:Object.keys(n).length>0?n:null,userId:r}},O=(e,r)=>{const{scheduler:n,sql:a}=r,i=e;p(a,i);const c=new y(r.headroomScope),m=t=>{const o=t;for(const s of Object.keys(i.tables))o[s]=S(t,s);return t};let u=!1;const I=t=>{const o=w({auth:{identity:t.claims,userId:t.userId},enforceRls:r.enforceRls??!0,headroom:c,inTransaction:()=>u,schema:i,sql:a}),s=o[T]??o;return{database:m(o),rawDatabase:m(s)}},d=t=>{a.exec.call(a,t)};let f=Promise.resolve();return{createWriters:I,runWithBudget:t=>c.run(t),runInTransaction:t=>{const o=async()=>{const b=g({scheduler:n});d("BEGIN"),u=!0;try{const h=await t();return d("COMMIT"),u=!1,await b(!0),h}catch(h){u=!1;try{d("ROLLBACK")}catch{}throw await b(!1),h}},s=f.then(()=>c.run(o));return f=s.then(()=>{},()=>{}),s}}},k=e=>{if(typeof e!="object"||e===null)return;const{kind:r}=e;if(r==="query"||r==="mutation"||r==="action")return r},P=(e,r,n,a,i)=>{const c=k(r);if(c!==e)throw new R("INTERNAL",`expected a registered ${e}, received a ${c??"non-function"} reference`);if(!i&&r.visibility==="internal")throw new R("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(n,a??{}))};export{O as createInProcessRuntime,k as registeredFunctionKind,C as resolveInProcessIdentity,P as runRegisteredFunction};
1
+ import{LunoraError as R}from"@lunora/errors";import{TransactionHeadroomTracker as l,runShardMigrations as p,createShardCtxDb as w,RLS_UNWRAP_SYMBOL as T}from"@lunora/shard-engine";import{beginDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{bindTableFacade as S}from"./packem_shared/bindOrm-DjpQXKLX.mjs";class y extends l{fallback=new l;scope;constructor(r){super(),this.scope=r}run(r){return this.scope===void 0?(this.fallback=new l,r()):this.scope.run(new l,r)}headroom(){return this.current().headroom()}recordRead(r){this.current().recordRead(r)}recordReadBytes(r){this.current().recordReadBytes(r)}recordDocumentRead(r,n){this.current().recordDocumentRead(r,n)}recordWrite(r){this.current().recordWrite(r)}current(){return this.scope?.getStore()??this.fallback}}const C=e=>{if(e===null||typeof e.userId!="string"||e.userId.length===0)return{claims:null,userId:null};const{userId:r,...n}=e;return{claims:Object.keys(n).length>0?n:null,userId:r}},O=(e,r)=>{const{scheduler:n,sql:a}=r,i=e;p(a,i);const c=new y(r.headroomScope),m=t=>{const o=t;for(const s of Object.keys(i.tables))o[s]=S(t,s);return t};let u=!1;const I=t=>{const o=w({auth:{identity:t.claims,userId:t.userId},enforceRls:r.enforceRls??!0,headroom:c,inTransaction:()=>u,schema:i,sql:a}),s=o[T]??o;return{database:m(o),rawDatabase:m(s)}},d=t=>{a.exec.call(a,t)};let f=Promise.resolve();return{createWriters:I,runWithBudget:t=>c.run(t),runInTransaction:t=>{const o=async()=>{const b=g({scheduler:n});d("BEGIN"),u=!0;try{const h=await t();return d("COMMIT"),u=!1,await b(!0),h}catch(h){u=!1;try{d("ROLLBACK")}catch{}throw await b(!1),h}},s=f.then(()=>c.run(o));return f=s.then(()=>{},()=>{}),s}}},k=e=>{if(typeof e!="object"||e===null)return;const{kind:r}=e;if(r==="query"||r==="mutation"||r==="action")return r},P=(e,r,n,a,i)=>{const c=k(r);if(c!==e)throw new R("INTERNAL",`expected a registered ${e}, received a ${c??"non-function"} reference`);if(!i&&r.visibility==="internal")throw new R("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(n,a??{}))};export{O as createInProcessRuntime,k as registeredFunctionKind,C as resolveInProcessIdentity,P as runRegisteredFunction};
package/dist/index.d.mts CHANGED
@@ -1907,12 +1907,21 @@ interface OrmLike {
1907
1907
  };
1908
1908
  }
1909
1909
  /**
1910
- * Re-point `target[tableName]` at a facade bound over `target` itself, but only
1911
- * build it on first read. The key stays an enumerable own property (spreads and
1912
- * `Object.keys` see it; a spread binds every table, as eager binding did), and
1913
- * the first read swaps the getter for the bound value so identity is stable.
1910
+ * One lazy accessor descriptor per table, built once per isolate and installed
1911
+ * on every `ctx.db` by {@link installTableFacades}. Each getter behaves as a
1912
+ * {@link defineLazyFacade} entry: on first read it binds the facade over the db
1913
+ * the accessors were installed on and swaps itself for the bound value.
1914
+ *
1915
+ * Null-prototype, so a table named `constructor` or `__proto__` is an ordinary key.
1916
+ */
1917
+ declare const tableFacadeDescriptors: (tableNames: ReadonlyArray<string>) => PropertyDescriptorMap;
1918
+ /**
1919
+ * Install the shared table accessors from {@link tableFacadeDescriptors} on `db`.
1920
+ * The owner is non-enumerable so spreads, `Object.keys` and
1921
+ * `copyDatabaseEntries` leave it behind. Through the telemetry proxy both
1922
+ * definitions land on the raw writer while the stored owner is the proxy.
1914
1923
  */
1915
- declare const defineLazyFacade: (target: FacadeWriterLike, tableName: string) => void;
1924
+ declare const installTableFacades: (database: FacadeWriterLike, descriptors: PropertyDescriptorMap) => void;
1916
1925
  /** Build `ctx.orm` over a per-table facade map (table name → FacadeEntry). */
1917
1926
  declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
1918
1927
  /**
@@ -3094,7 +3103,7 @@ interface DatabaseWriterLike {
3094
3103
  */
3095
3104
  rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
3096
3105
  /**
3097
- * Relation-graph traversal. Declared so the `...base` spread's shape is
3106
+ * Relation-graph traversal. Declared so the copied `base` entries' shape is
3098
3107
  * typed, but never CALLED by the wrapper: the walk it performs is bound to
3099
3108
  * whatever writer this closure came from, and the wrapper has to route each
3100
3109
  * hop itself. It re-binds the traversal over {@link DatabaseWriterLike.relationEdges}
@@ -4558,7 +4567,7 @@ type RegisteredWhisperAuthorizer = RegisteredFunction<Record<string, never>, boo
4558
4567
  */
4559
4568
  declare const onWhisper: (handler: WhisperAuthorizeHandler) => RegisteredWhisperAuthorizer;
4560
4569
  declare const VERSION = "0.0.0";
4561
- export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type AuthorizeCheck, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteCacheOptions, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LivePublishOptions, type LivePublisher, type LiveRouterApp, type LiveRouterFallback, type LiveStream, type LiveStreamConfig, type LiveStreamMount, type LiveSubscribeHandler, type LiveSubscribeOptions, type LiveTopicDeclaration, type LiveTopicKey, type LiveTopicPayload, type LiveTopicRef, type LiveTopics, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCovers, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, PROCEDURE_META, type Permission, type PlatformAdminCheck, type Plugin, type Policy, type PolicyMiddleware, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredInternalAction, type RegisteredInternalMutation, type RegisteredInternalQuery, type RegisteredInternalStream, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsContextIn, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, UNLOADED_META, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, authorize, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineLazyFacade, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
4570
+ export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type AuthorizeCheck, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteCacheOptions, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LivePublishOptions, type LivePublisher, type LiveRouterApp, type LiveRouterFallback, type LiveStream, type LiveStreamConfig, type LiveStreamMount, type LiveSubscribeHandler, type LiveSubscribeOptions, type LiveTopicDeclaration, type LiveTopicKey, type LiveTopicPayload, type LiveTopicRef, type LiveTopics, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCovers, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, PROCEDURE_META, type Permission, type PlatformAdminCheck, type Plugin, type Policy, type PolicyMiddleware, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredInternalAction, type RegisteredInternalMutation, type RegisteredInternalQuery, type RegisteredInternalStream, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsContextIn, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, UNLOADED_META, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, authorize, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
4562
4571
  /**
4563
4572
  * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4564
4573
  * NUL. Guards against response-header injection / `Headers`-construction throws
@@ -4585,7 +4594,7 @@ httpRoute,
4585
4594
  * handler can guard a request-derived header value before writing it — the fix the
4586
4595
  * `http_action_response_header_injection` advisor lint points to.
4587
4596
  */
4588
- httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isPerDispatchMiddleware, isSafeHeaderValue,
4597
+ httpRouter, indexFieldsFromSchema, initLunora, installPlugins, installTableFacades, isDeny, isPerDispatchMiddleware, isSafeHeaderValue,
4589
4598
  /**
4590
4599
  * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4591
4600
  * NUL. Guards against response-header injection / `Headers`-construction throws
@@ -4603,4 +4612,4 @@ lastEventId, liveStreamRouter, mask, mergeSchemaExtension, onConnect, onDisconne
4603
4612
  * handler can guard a request-derived header value before writing it — the fix the
4604
4613
  * `http_action_response_header_injection` advisor lint points to.
4605
4614
  */
4606
- sseEvent, storageRules, tagPerDispatchMiddleware, toWhereInput, withDeferredDeletes, withDeferredSchedules };
4615
+ sseEvent, storageRules, tableFacadeDescriptors, tagPerDispatchMiddleware, toWhereInput, withDeferredDeletes, withDeferredSchedules };
package/dist/index.d.ts CHANGED
@@ -1907,12 +1907,21 @@ interface OrmLike {
1907
1907
  };
1908
1908
  }
1909
1909
  /**
1910
- * Re-point `target[tableName]` at a facade bound over `target` itself, but only
1911
- * build it on first read. The key stays an enumerable own property (spreads and
1912
- * `Object.keys` see it; a spread binds every table, as eager binding did), and
1913
- * the first read swaps the getter for the bound value so identity is stable.
1910
+ * One lazy accessor descriptor per table, built once per isolate and installed
1911
+ * on every `ctx.db` by {@link installTableFacades}. Each getter behaves as a
1912
+ * {@link defineLazyFacade} entry: on first read it binds the facade over the db
1913
+ * the accessors were installed on and swaps itself for the bound value.
1914
+ *
1915
+ * Null-prototype, so a table named `constructor` or `__proto__` is an ordinary key.
1916
+ */
1917
+ declare const tableFacadeDescriptors: (tableNames: ReadonlyArray<string>) => PropertyDescriptorMap;
1918
+ /**
1919
+ * Install the shared table accessors from {@link tableFacadeDescriptors} on `db`.
1920
+ * The owner is non-enumerable so spreads, `Object.keys` and
1921
+ * `copyDatabaseEntries` leave it behind. Through the telemetry proxy both
1922
+ * definitions land on the raw writer while the stored owner is the proxy.
1914
1923
  */
1915
- declare const defineLazyFacade: (target: FacadeWriterLike, tableName: string) => void;
1924
+ declare const installTableFacades: (database: FacadeWriterLike, descriptors: PropertyDescriptorMap) => void;
1916
1925
  /** Build `ctx.orm` over a per-table facade map (table name → FacadeEntry). */
1917
1926
  declare const bindOrm: (facade: Record<string, FacadeEntry>) => OrmLike;
1918
1927
  /**
@@ -3094,7 +3103,7 @@ interface DatabaseWriterLike {
3094
3103
  */
3095
3104
  rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
3096
3105
  /**
3097
- * Relation-graph traversal. Declared so the `...base` spread's shape is
3106
+ * Relation-graph traversal. Declared so the copied `base` entries' shape is
3098
3107
  * typed, but never CALLED by the wrapper: the walk it performs is bound to
3099
3108
  * whatever writer this closure came from, and the wrapper has to route each
3100
3109
  * hop itself. It re-binds the traversal over {@link DatabaseWriterLike.relationEdges}
@@ -4558,7 +4567,7 @@ type RegisteredWhisperAuthorizer = RegisteredFunction<Record<string, never>, boo
4558
4567
  */
4559
4568
  declare const onWhisper: (handler: WhisperAuthorizeHandler) => RegisteredWhisperAuthorizer;
4560
4569
  declare const VERSION = "0.0.0";
4561
- export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type AuthorizeCheck, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteCacheOptions, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LivePublishOptions, type LivePublisher, type LiveRouterApp, type LiveRouterFallback, type LiveStream, type LiveStreamConfig, type LiveStreamMount, type LiveSubscribeHandler, type LiveSubscribeOptions, type LiveTopicDeclaration, type LiveTopicKey, type LiveTopicPayload, type LiveTopicRef, type LiveTopics, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCovers, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, PROCEDURE_META, type Permission, type PlatformAdminCheck, type Plugin, type Policy, type PolicyMiddleware, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredInternalAction, type RegisteredInternalMutation, type RegisteredInternalQuery, type RegisteredInternalStream, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsContextIn, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, UNLOADED_META, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, authorize, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineLazyFacade, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
4570
+ export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type AuthorizeCheck, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineRoomOptions, type DefineStorageRuleInput, type DefineWebSocketOptions, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteCacheOptions, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LivePublishOptions, type LivePublisher, type LiveRouterApp, type LiveRouterFallback, type LiveStream, type LiveStreamConfig, type LiveStreamMount, type LiveSubscribeHandler, type LiveSubscribeOptions, type LiveTopicDeclaration, type LiveTopicKey, type LiveTopicPayload, type LiveTopicRef, type LiveTopics, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCovers, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type ModuleConfig, type ModuleDefinition, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, PROCEDURE_META, type Permission, type PlatformAdminCheck, type Plugin, type Policy, type PolicyMiddleware, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredInternalAction, type RegisteredInternalMutation, type RegisteredInternalQuery, type RegisteredInternalStream, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredRoom, type RegisteredShape, type RegisteredStream, type RegisteredWebSocket, type RegisteredWhisperAuthorizer, type RelationBuilder, type RelationDefinition, type RelationThrough, type RlsContextIn, type RlsOptions, type RlsReadRegistry, type Role, type RoomJoinHandler, type RoomLeaveHandler, type RoomMessageHandler, type RoomMessageOf, type RoomSocket, type Schema, type SchemaExtension, type ServiceBindingSpec, type ServiceFetcher, type ServiceRpc, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardFetch, type ShardFetchInit, type ShardInitEvent, type ShardInitHandler, type SseEvent, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, UNLOADED_META, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WebSocketCloseHandler, type WebSocketHandle, type WebSocketMessageHandler, type WebSocketOpenHandler, type WhereInput, type WhisperAuthorizeHandler, type WhisperEvent, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, authorize, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, createServices, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineIdentityGuard, defineListArgs, defineLiveStream, defineMigration, defineModule, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineRoom, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, defineWebSocket, deny, documentHistoryExtension, flushDeferredDeletes,
4562
4571
  /**
4563
4572
  * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4564
4573
  * NUL. Guards against response-header injection / `Headers`-construction throws
@@ -4585,7 +4594,7 @@ httpRoute,
4585
4594
  * handler can guard a request-derived header value before writing it — the fix the
4586
4595
  * `http_action_response_header_injection` advisor lint points to.
4587
4596
  */
4588
- httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isPerDispatchMiddleware, isSafeHeaderValue,
4597
+ httpRouter, indexFieldsFromSchema, initLunora, installPlugins, installTableFacades, isDeny, isPerDispatchMiddleware, isSafeHeaderValue,
4589
4598
  /**
4590
4599
  * True when `value` is safe to use as an HTTP header field-value: no CR, LF, or
4591
4600
  * NUL. Guards against response-header injection / `Headers`-construction throws
@@ -4603,4 +4612,4 @@ lastEventId, liveStreamRouter, mask, mergeSchemaExtension, onConnect, onDisconne
4603
4612
  * handler can guard a request-derived header value before writing it — the fix the
4604
4613
  * `http_action_response_header_injection` advisor lint points to.
4605
4614
  */
4606
- sseEvent, storageRules, tagPerDispatchMiddleware, toWhereInput, withDeferredDeletes, withDeferredSchedules };
4615
+ sseEvent, storageRules, tableFacadeDescriptors, tagPerDispatchMiddleware, toWhereInput, withDeferredDeletes, withDeferredSchedules };
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-Dv4DKrj0.mjs";import{authorize as s}from"./packem_shared/authorize-CVLZJxf_.mjs";import{initLunora as p}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as c,tagPerDispatchMiddleware as l}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as u}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as D,withDeferredDeletes as T}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as A,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as _,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as C,documentHistoryExtension as M}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs";import{LunoraEnvError as b,defineEnv as y}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as F,bindTableFacade as v,defineLazyFacade as N}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as H,httpRoute as k,httpRouter as w,lastEventId as B,sseEvent as V}from"./packem_shared/httpAction-DD8h1jcf.mjs";import{serveStorageObject as j}from"./packem_shared/serveStorageObject-CLz3qhNI.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 $,DEFAULT_MAX_LIMIT as ee,clampLimit as re,defineListArgs as oe}from"./packem_shared/DEFAULT_LIMIT-z7HB19s7.mjs";import{defineLiveStream as ie,liveStreamRouter as ne}from"./packem_shared/defineLiveStream-D3xRvNDy.mjs";import{defineMigration as ae}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as se}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as pe}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as ce}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as Ee,d as ue,a as Se,b as he,e as De,f as Te,g as Re,h as Ae,i as ge,j as Le,k as _e,m as Ie}from"./packem_shared/plugin-CyLqvCB9.mjs";import{PRESENCE_DEFAULT_TTL_MS as Me,PRESENCE_TABLE as Pe,definePresence as be,presenceExtension as ye}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-aj9Ec70J.mjs";import{PROCEDURE_META as Fe,UNLOADED_META as ve,procedureMeta as Ne}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as He}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as we}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as Ve}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as je}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ye}from"./packem_shared/defineShape-H-0IbZlb.mjs";import{defineWebSocket as Je}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Qe}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as qe}from"@lunora/errors";import{cronJobs as $e}from"@lunora/scheduler";import{ValidationError as rr,v as or}from"@lunora/values";import{allowAll as ir,deny as nr,isDeny as fr,toWhereInput as ar}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as sr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as pr,buildRlsReadRegistry as xr,composeShapeReadWhere as cr}from"./packem_shared/assertShapesDeclareReadPolicies-C09SMvM4.mjs";import{buildMaskRegistry as Er}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Sr,definePermission as hr,definePolicies as Dr,definePolicy as Tr,defineRole as Rr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as gr,defineStorageRules as Lr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as Ir}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Mr}from"./packem_shared/mask-ocdNb1L3.mjs";import{r as br}from"./packem_shared/redact-secrets-BpatNz48.mjs";import{r as Or}from"./packem_shared/middleware-CHYtnvZP.mjs";import{storageRules as vr}from"./packem_shared/storageRules-BVIXkoRg.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,$ as DEFAULT_LIMIT,ee as DEFAULT_MAX_LIMIT,_ as DOCUMENT_HISTORY_REDACTED_FIELDS,I as DOCUMENT_HISTORY_TABLE,b as LunoraEnvError,qe as LunoraError,Me as PRESENCE_DEFAULT_TTL_MS,Pe as PRESENCE_TABLE,Fe as PROCEDURE_META,ve as UNLOADED_META,e as VERSION,rr as ValidationError,n as actionCacheExtension,ir as allowAll,sr as asBucketStorage,pr as assertShapesDeclareReadPolicies,s as authorize,h as beginDeferredDeletes,A as beginDeferredSchedules,F as bindOrm,v as bindTableFacade,Er as buildMaskRegistry,xr as buildRlsReadRegistry,f as cacheKeyFor,re as clampLimit,Ee as composePluginMiddleware,cr as composeShapeReadWhere,Sr as createPolicyDsl,u as createSecrets,je as createServices,$e as cronJobs,a as defineActionCache,ue as defineAggregateIndex,Se as defineComponent,C as defineDocumentHistory,y as defineEnv,Y as defineIdentity,J as defineIdentityGuard,N as defineLazyFacade,oe as defineListArgs,ie as defineLiveStream,ae as defineMigration,se as defineModule,pe as defineMutator,hr as definePermission,he as definePlugin,Dr as definePolicies,Tr as definePolicy,be as definePresence,De as defineRankIndex,Rr as defineRole,Ve as defineRoom,Te as defineSchema,Re as defineSchemaExtension,Ye as defineShape,gr as defineStorageRule,Lr as defineStorageRules,Ae as defineTable,ge as defineVectorIndex,Je as defineWebSocket,nr as deny,M as documentHistoryExtension,D as flushDeferredDeletes,H as httpAction,k as httpRoute,w as httpRouter,Le as indexFieldsFromSchema,p as initLunora,_e as installPlugins,fr as isDeny,c as isPerDispatchMiddleware,Ir as isSafeHeaderValue,B as lastEventId,ne as liveStreamRouter,Mr as mask,Ie as mergeSchemaExtension,Q as onConnect,X as onDisconnect,we as onQueryChange,q as onShardInit,Qe as onWhisper,ce as platformAdmin,ye as presenceExtension,Ne as procedureMeta,He as protectPublic,br as redactSecrets,Or as rls,j as serveStorageObject,V as sseEvent,vr as storageRules,l as tagPerDispatchMiddleware,ar as toWhereInput,or as v,T as withDeferredDeletes,g as withDeferredSchedules};
1
+ import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-Dv4DKrj0.mjs";import{authorize as d}from"./packem_shared/authorize-CVLZJxf_.mjs";import{initLunora as p}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as c,tagPerDispatchMiddleware as l}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as u}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as D,flushDeferredDeletes as h,withDeferredDeletes as T}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as A,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-BOsY07vZ.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as L,DOCUMENT_HISTORY_TABLE as I,defineDocumentHistory as C,documentHistoryExtension as M}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs";import{LunoraEnvError as P,defineEnv as y}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as O,bindTableFacade as v,installTableFacades as N,tableFacadeDescriptors as U}from"./packem_shared/bindOrm-DjpQXKLX.mjs";import{httpAction as k,httpRoute as w,httpRouter as B,lastEventId as V,sseEvent as W}from"./packem_shared/httpAction-DD8h1jcf.mjs";import{serveStorageObject as Y}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as G}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as K}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as X,onDisconnect as q,onShardInit as Z}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as ee,DEFAULT_MAX_LIMIT as re,clampLimit as oe,defineListArgs as te}from"./packem_shared/DEFAULT_LIMIT-z7HB19s7.mjs";import{defineLiveStream as ne,liveStreamRouter as ae}from"./packem_shared/defineLiveStream-D3xRvNDy.mjs";import{defineMigration as se}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as me}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as xe}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as le}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as ue,d as Se,a as De,b as he,e as Te,f as Re,g as Ae,h as ge,i as _e,j as Le,k as Ie,m as Ce}from"./packem_shared/plugin-CyLqvCB9.mjs";import{PRESENCE_DEFAULT_TTL_MS as be,PRESENCE_TABLE as Pe,definePresence as ye,presenceExtension as Fe}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-aj9Ec70J.mjs";import{PROCEDURE_META as ve,UNLOADED_META as Ne,procedureMeta as Ue}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as ke}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Be}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as We}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as Ye}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Ge}from"./packem_shared/defineShape-AovSNZ8n.mjs";import{defineWebSocket as Ke}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Xe}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ze}from"@lunora/errors";import{cronJobs as er}from"@lunora/scheduler";import{ValidationError as or,v as tr}from"@lunora/values";import{allowAll as nr,deny as ar,isDeny as fr,toWhereInput as sr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as mr}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as xr,buildRlsReadRegistry as cr,composeShapeReadWhere as lr}from"./packem_shared/assertShapesDeclareReadPolicies-BJgZisKR.mjs";import{buildMaskRegistry as ur}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Dr,definePermission as hr,definePolicies as Tr,definePolicy as Rr,defineRole as Ar}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as _r,defineStorageRules as Lr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as Cr}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as br}from"./packem_shared/mask-ZYUnKLM9.mjs";import{r as yr}from"./packem_shared/redact-secrets-BpatNz48.mjs";import{r as Or}from"./packem_shared/middleware-DwU2Sv_S.mjs";import{storageRules as Nr}from"./packem_shared/storageRules-BpvA-y9l.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,ee as DEFAULT_LIMIT,re as DEFAULT_MAX_LIMIT,L as DOCUMENT_HISTORY_REDACTED_FIELDS,I as DOCUMENT_HISTORY_TABLE,P as LunoraEnvError,Ze as LunoraError,be as PRESENCE_DEFAULT_TTL_MS,Pe as PRESENCE_TABLE,ve as PROCEDURE_META,Ne as UNLOADED_META,e as VERSION,or as ValidationError,n as actionCacheExtension,nr as allowAll,mr as asBucketStorage,xr as assertShapesDeclareReadPolicies,d as authorize,D as beginDeferredDeletes,A as beginDeferredSchedules,O as bindOrm,v as bindTableFacade,ur as buildMaskRegistry,cr as buildRlsReadRegistry,a as cacheKeyFor,oe as clampLimit,ue as composePluginMiddleware,lr as composeShapeReadWhere,Dr as createPolicyDsl,u as createSecrets,Ye as createServices,er as cronJobs,f as defineActionCache,Se as defineAggregateIndex,De as defineComponent,C as defineDocumentHistory,y as defineEnv,G as defineIdentity,K as defineIdentityGuard,te as defineListArgs,ne as defineLiveStream,se as defineMigration,me as defineModule,xe as defineMutator,hr as definePermission,he as definePlugin,Tr as definePolicies,Rr as definePolicy,ye as definePresence,Te as defineRankIndex,Ar as defineRole,We as defineRoom,Re as defineSchema,Ae as defineSchemaExtension,Ge as defineShape,_r as defineStorageRule,Lr as defineStorageRules,ge as defineTable,_e as defineVectorIndex,Ke as defineWebSocket,ar as deny,M as documentHistoryExtension,h as flushDeferredDeletes,k as httpAction,w as httpRoute,B as httpRouter,Le as indexFieldsFromSchema,p as initLunora,Ie as installPlugins,N as installTableFacades,fr as isDeny,c as isPerDispatchMiddleware,Cr as isSafeHeaderValue,V as lastEventId,ae as liveStreamRouter,br as mask,Ce as mergeSchemaExtension,X as onConnect,q as onDisconnect,Be as onQueryChange,Z as onShardInit,Xe as onWhisper,le as platformAdmin,Fe as presenceExtension,Ue as procedureMeta,ke as protectPublic,yr as redactSecrets,Or as rls,Y as serveStorageObject,W as sseEvent,Nr as storageRules,U as tableFacadeDescriptors,l as tagPerDispatchMiddleware,sr as toWhereInput,tr as v,T as withDeferredDeletes,g as withDeferredSchedules};
@@ -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-CHYtnvZP.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]},A=(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})},S=(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=A(n,e);if(s!==void 0){if(d(s))return h;o.push(s)}}if(o.length!==0)return o.length===1?o[0]:{AND:o}},W=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}},$=(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: []\`.`)},B=(t,e)=>T(S(t,e),e.shapeWhere);export{$ as assertShapesDeclareReadPolicies,W as buildRlsReadRegistry,B as composeShapeReadWhere};
1
+ import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,e as b,f as y}from"./middleware-DwU2Sv_S.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]},A=(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})},S=(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=A(n,e);if(s!==void 0){if(d(s))return h;o.push(s)}}if(o.length!==0)return o.length===1?o[0]:{AND:o}},W=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}},$=(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: []\`.`)},B=(t,e)=>T(S(t,e),e.shapeWhere);export{$ as assertShapesDeclareReadPolicies,W as buildRlsReadRegistry,B as composeShapeReadWhere};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{isPlainObject as F}from"@lunora/wire";const W=new Set(["connect","disconnect","set"]),p=500,T=(n,t,s)=>n!==void 0&&Object.hasOwn(n,t)&&F(s),L=n=>typeof n=="object"&&n!==null&&n.code==="CONFLICT"&&n.kind==="unique",u=(n,t)=>{throw new y(n,t)},A=(n,t)=>{if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return u("VALIDATION_ERROR",`${t} must be an array of ids`);const s=[...new Set(n)];return s.length>p&&u("VALIDATION_ERROR",`${t} names ${String(s.length)} rows; at most ${String(p)} per list`),s},_=(n,t,s)=>{t.nullable||u("VALIDATION_ERROR",`${n}.${s}: "${t.field}" cannot be empty; make it optional or nullable to allow it`)},C=(n,t,s)=>{const{connect:o,disconnect:e,set:i}=s;return i!==void 0&&u("VALIDATION_ERROR",`${n} is a to-one relation: use connect or disconnect, not set`),o!==void 0&&e!==void 0&&u("VALIDATION_ERROR",`${n}: connect and disconnect together are ambiguous`),o!==void 0?(typeof o!="string"&&u("VALIDATION_ERROR",`${n}.connect must be an id`),{connect:o,info:t,name:n}):(e!==!0&&u("VALIDATION_ERROR",`${n}.disconnect must be true`),_(n,t,"disconnect"),{info:t,name:n})},b=(n,t,s)=>{t.through===void 0&&_(n,t,s)},U=(n,t,s)=>{const{connect:o,disconnect:e,set:i}=s;if(i!==void 0)return(o!==void 0||e!==void 0)&&u("VALIDATION_ERROR",`${n}: set replaces the whole list and cannot be combined with connect or disconnect`),b(n,t,"set"),{attach:[],info:t,name:n,release:[],replace:A(i,`${n}.set`)};e!==void 0&&b(n,t,"disconnect");const r=o===void 0?[]:A(o,`${n}.connect`),a=e===void 0?[]:A(e,`${n}.disconnect`),c=r.find(d=>a.includes(d));return c!==void 0&&u("VALIDATION_ERROR",`${n}: "${c}" is in both connect and disconnect, which is ambiguous`),{attach:r,info:t,name:n,release:a}},V=(n,t,s,o)=>{const e=Object.fromEntries(Object.entries(o).filter(([,a])=>a!==void 0)),i=Object.keys(e).find(a=>!W.has(a));if(i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${n}: "${t}.${i}" is not a relation operator; use connect, disconnect or set`),Object.keys(e).length===0)return;const r=s.refusal??s.refusalNow?.();return r!==void 0&&u("UNPROCESSABLE",`ctx.db.${n}: relation "${t}" cannot be written: ${r}`),s.colocated||u("UNPROCESSABLE",`ctx.db.${n}: relation "${t}" crosses to "${s.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),s.kind==="one"?C(t,s,e):U(t,s,e)},q=n=>n.info.kind==="one",S=(n,t,s)=>{if(t===void 0)return{columns:s,manys:[],ones:[]};const o={},e=[],i=[];for(const[r,a]of Object.entries(s)){if(!T(t,r,a)){o[r]=a;continue}const c=V(n,r,t[r],a);c!==void 0&&(q(c)?i.push(c):e.push(c))}for(const{info:r,name:a}of i)Object.hasOwn(o,r.field)&&u("VALIDATION_ERROR",`ctx.db.${n}: ${a} and its key "${r.field}" are both set; set one or the other`);return{columns:o,manys:e,ones:i}},$=(n,t,s,o)=>{const e=Object.entries(s).find(([i,r])=>T(t,i,r))?.[0];e!==void 0&&u("VALIDATION_ERROR",`ctx.db.${n}.${o}: "${e}" is a relation write, which ${o} does not support; use insert or patch`)},g=async(n,t,s,o,e)=>{const i=await n.get(o,e);return i===null&&u("NOT_FOUND",`${t}.${s}: no "${o}" row with id "${e}"`),i},x=async(n,t)=>{const s={...t.columns};for(const{connect:o,info:e,name:i}of t.ones){let r=null;o!==void 0&&(r=(await g(n,i,"connect",e.table,o))[e.references]),s[e.field]=r}return s},m=async(n,{info:t,name:s},o,e)=>{(await g(n,s,"connect",t.table,o))[t.field]!==e&&await n.patch(t.table,o,{[t.field]:e})},B=async(n,{info:t},s,o)=>{s[t.field]===o&&await n.patch(t.table,String(s._id),{[t.field]:null})},z=async(n,{info:t,name:s},o)=>{const{page:e}=await n.findMany(t.table,{limit:p+1,where:{[t.field]:o}});return e.length>p&&u("VALIDATION_ERROR",`${s}.set: the relation already holds more than ${String(p)} rows; disconnect in batches first`),e},M=(n,t)=>{const s=new Set(n),o=new Set(t);return{attach:t.filter(e=>!s.has(e)),release:new Set(n.filter(e=>!o.has(e)))}},I=async(n,{name:t},{from:s,table:o,to:e},i,r)=>{const a=r===void 0?{[s]:i}:{[s]:i,[e]:{in:r}},{page:c}=await n.findMany(o,{limit:p+1,where:a});return c.length>p&&u("VALIDATION_ERROR",`${t}: the relation already holds more than ${String(p)} rows; disconnect in batches first`),c},G=async(n,t,s)=>{if(s.length===0)return new Set;const{page:o}=await n.findMany(t,{limit:s.length,where:{_id:{in:s}}});return new Set(o.map(e=>String(e._id)))},K=async(n,t,s)=>{const{info:o,name:e}=t,{from:i,table:r,to:a}=o.through;let c,d;if(t.replace===void 0){await Promise.all(t.release.map(h=>g(n,e,"disconnect",o.table,h))),d=t.release.length===0?[]:await I(n,t,o.through,s,t.release);const l=t.attach.length===0?[]:await I(n,t,o.through,s,t.attach),f=new Set(l.map(h=>String(h[a])));c=t.attach.filter(h=>!f.has(h))}else{const l=await I(n,t,o.through,s,void 0),f=M(l.map(O=>String(O[a])),t.replace),h=await G(n,o.table,[...f.release]);({attach:c}=f),d=l.filter(O=>f.release.has(String(O[a]))&&h.has(String(O[a])))}await Promise.all(c.map(l=>g(n,e,"connect",o.table,l)));for(const l of d)await n.delete(r,String(l._id));for(const l of c)try{await n.insert(r,{[i]:s,[a]:l})}catch(f){if(!L(f)||!o.pairIsOnlyUnique)throw f}},H=async(n,t,s)=>{let{attach:o}=t,e;if(t.replace===void 0)e=await Promise.all(t.release.map(i=>g(n,t.name,"disconnect",t.info.table,i)));else{const i=await z(n,t,s),r=M(i.map(a=>String(a._id)),t.replace);({attach:o}=r),e=i.filter(a=>r.release.has(String(a._id)))}for(const i of e)await B(n,t,i,s);for(const i of o)await m(n,t,i,s)},j=async(n,t,s,o)=>{for(const e of s.manys){const{info:i}=e,r=i.through===void 0?i.references:"_id",a=await o(r);if(a==null&&u("VALIDATION_ERROR",`ctx.db.${t}: ${e.name} is keyed on "${r}", which this row has no value for`),i.through!==void 0){await K(n,{...e,info:i},a);continue}await H(n,{...e,info:i},a)}},D=(n,t,s,o)=>async e=>e==="_id"?s:Object.hasOwn(o,e)?o[e]:(await n.get(t,s))?.[e],Q=async(n,t,s,o,e)=>{const i=S(t,s,o);if(i.ones.length===0&&i.manys.length===0)return e(i.columns);const r=await x(n,i),a=await e(r);return a!==null&&await j(n,t,i,D(n,t,a,r)),a},X=async(n,t,s,o,e)=>{const i=S(t,s,e);if(i.ones.length===0&&i.manys.length===0){await n.patch(t,o,i.columns);return}const r=await x(n,i);if(Object.keys(r).length>0)await n.patch(t,o,r);else{if(await n.get(t,o)===null)throw new y("NOT_FOUND",`document not found: ${o}`);await n.assertPatchAllowed?.(t,o)}await j(n,t,i,D(n,t,o,r))},J=(n,t,s,o)=>{const e=typeof t=="string"?[t]:t;if(e.length===0)throw new y("INTERNAL",`ctx.db.${n}.upsert: "target" must name at least one field`);const i={};for(const r of e){if(!(r in s)){const a=Object.entries(o??{}).find(([c,d])=>d.kind==="one"&&d.field===r&&c in s)?.[0];throw a!==void 0?new y("VALIDATION_ERROR",`ctx.db.${n}.upsert: target field "${r}" is supplied by the "${a}" relation write; pass "${r}" itself so the existing row can be found`):new y("INTERNAL",`ctx.db.${n}.upsert: target field "${r}" is missing from the create document`)}i[r]=s[r]}return i},R=n=>({configurable:!0,enumerable:!0,value:n,writable:!0}),w=Symbol("lunora.facadeOwner"),Y=n=>{let t=n;for(;t!==null;){if(Object.hasOwn(t,w))return t;t=Reflect.getPrototypeOf(t)}return n},v=new WeakSet,P=(n,t,s)=>{const o=()=>{const e=s();return Object.defineProperty(n,t,R(e)),e};v.add(o),Object.defineProperty(n,t,{configurable:!0,enumerable:!0,get:o,set(e){Object.defineProperty(this,t,R(e))}})},k=(n,t)=>{const s=async(c,d)=>{if(d?.skipDuplicates!==!0)return n.insert(t,c);try{return await n.insert(t,c)}catch(l){if(L(l))return null;throw l}},o=n.relationWrites?.[t],e=(c,d)=>Q(n,t,o,c,l=>s(l,d)),i=(c,d)=>X(n,t,o,c,d),r=async c=>{const d=c??{},l=await n.findMany(t,{...d,limit:2});if(l.page.length>1)throw new y("NOT_UNIQUE",`ctx.db.${t}.findUnique matched more than one document; expected at most one`);return l.page[0]??null},a=async({create:c,target:d,update:l})=>{const f=J(t,d,c,o),h=await n.findFirst(t,{where:f});return h&&typeof h._id=="string"?(await i(h._id,l??c),{created:!1,id:h._id}):{created:!0,id:await e(c)}};return{aggregate:c=>n.aggregate(t,c),count:c=>n.count(t,c),delete:c=>n.delete(t,c),deleteMany:(c,d)=>{if(Array.isArray(c)){if(n.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return n.deleteMany(t,c,d)}if(n.deleteWhere===void 0)throw new y("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const l=c;return n.deleteWhere(t,l.where,{limit:l.limit})},exists:async c=>await n.findFirst(t,c===void 0?void 0:{where:c})!==null,explain:c=>n.explain(t,c),findFirst:c=>n.findFirst(t,c),findFirstOrThrow:c=>n.findFirstOrThrow(t,c),findMany:c=>n.findMany(t,c),findUnique:r,get:c=>n.get(t,c),groupBy:c=>n.groupBy(t,c),hardDelete:c=>n.delete(t,c,{hard:!0}),insert:e,insertMany:(c,d)=>{for(const l of c)$(t,o,l,"insertMany");if(n.insertMany===void 0)throw new y("INTERNAL",`ctx.db.${t}.insertMany is unavailable: this writer has no batch insert`);return n.insertMany(t,c,d)},patch:i,patchMany:(c,d)=>{const l=Array.isArray(c)?c.map(h=>h.values):[c.values];for(const h of l)$(t,o,h,"patchMany");if(Array.isArray(c)){if(n.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return n.patchMany(t,c.map(h=>({id:h.id,patch:h.values})),d)}if(n.patchWhere===void 0)throw new y("INTERNAL",`ctx.db.${t}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=c;return n.patchWhere(t,{patch:f.values,where:f.where},{limit:f.limit})},rank:(c,d)=>n.rank(t,c,d),rankPage:(c,d)=>n.rankPage(t,c,d),replace:(c,d)=>($(t,o,d,"replace"),n.replace(t,c,d)),restore:async c=>{if(!n.restore)throw new y("INTERNAL",`ctx.db.${t}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await n.restore(t,c)},upsert:a,upsertMany:async({rows:c,target:d})=>{const l=[];for(const f of c)l.push(await a({create:f.create,target:d,update:f.update}));return l},withGeoIndex:(c,d)=>n.query(t).withGeoIndex(c,d),withSearchIndex:(c,d)=>n.query(t).withSearchIndex(c,d)}},E=(n,t)=>{P(n,t,()=>k(n,t))},nt=n=>{const t=Object.create(null);for(const s of n){const o=function(){const e=Y(this),i=Object.hasOwn(e,w)?e[w]:e,r=k(i,s);return Object.defineProperty(e,s,R(r)),r};v.add(o),t[s]={configurable:!0,enumerable:!0,get:o,set(e){Object.defineProperty(this,s,R(e))}}}return t},et=(n,t)=>{Object.defineProperty(n,w,{configurable:!0,enumerable:!1,value:n,writable:!0}),Object.defineProperties(n,t)},Z=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return!1;const t=n;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},ot=(n,t,s)=>{const o=t;for(const e of Reflect.ownKeys(t)){const i=Object.getOwnPropertyDescriptor(t,e);if(i?.enumerable!==!0)continue;const r=Object.hasOwn(n,e);if(typeof e=="string"&&typeof i.get=="function"&&v.has(i.get)){s?E(n,e):r||P(n,e,()=>o[e]);continue}const a=o[e];s&&typeof e=="string"&&Z(a)?E(n,e):r||Object.defineProperty(n,e,R(a))}},st=n=>{const t=s=>{const o=n[s];if(!o)throw new y("INTERNAL",`unknown table: ${s}`);return o};return{delete:(s,o)=>t(s).delete(o),insert:s=>({values:o=>t(s).insert(o)}),query:n,replace:(s,o)=>({with:e=>t(s).replace(o,e)}),update:(s,o)=>({set:e=>t(s).patch(o,e)})}};export{st as bindOrm,k as bindTableFacade,ot as copyDatabaseEntries,E as defineLazyFacade,et as installTableFacades,Z as isFacadeEntry,nt as tableFacadeDescriptors};
@@ -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-C09SMvM4.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-BJgZisKR.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};
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{f as F}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as x,b as H,c as C}from"./middleware-DwU2Sv_S.mjs";import{copyDatabaseEntries as J,bindOrm as X}from"./bindOrm-DjpQXKLX.mjs";import{tagMaskMiddleware as Y}from"./buildMaskRegistry-DpWMtalG.mjs";const L=Symbol.for("lunora.ctxdb.rls-relation-gate"),Q=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?F(i.toString()):F(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},d=(s,i,c)=>{const w={...s};for(const[y,p]of Object.entries(i))y in w&&(w[y]=Q(p,s[y],{...c,column:y,row:s}));return w},v=(s,i,c)=>({...s,page:s.page.map(w=>d(w,i,c))}),P=(s,i)=>{const c=H(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},K=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,p=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&y.add(f),p())});s(p());for(const f of y)if(P(i,f))throw new S("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${f}" is not supported`)},G=64,V=(s,i,c,w)=>{const y=s.rankBefore,p=s.rankPageRows,f=(r,t)=>{const n=i.get(r);return n?t.map(o=>d(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?f:(n,o)=>t(n,f(n,o))}},h=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[t];if(!a)return;const u=a.find(I=>P(e,I));if(u!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${u}" — use an index whose declared fields are all unmasked, or unmask the column`)},O=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield d(o,t,c)},collect:async()=>(await r.collect()).map(e=>d(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=d(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>O(r.filter(e=>o(d(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?d(o,t,c):null},order:o=>O(r.order(o),t,n),paginate:async o=>v(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>d(a,t,c)),unique:async()=>{const o=await r.unique();return o?d(o,t,c):null},withIndex:(o,e)=>(h(n,o,"withIndex","index"),K(e,t,n,"withIndex"),O(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(K(e,t,n,"withSearchIndex"),O(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(h(n,o,"withGeoIndex","geo"),O(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&P(o,a));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},l=new Set;for(const r of i.values())for(const t of Object.keys(r))l.add(t);const A=(r,t,n,o,e=0)=>{if(!(!r||typeof r!="object")){if(e>=G)throw new S("MASK_UNSUPPORTED",`${o}() filtering "${n}" with a where nested deeper than ${String(G)} levels is not supported`);if(Array.isArray(r)){for(const a of r)A(a,t,n,o,e+1);return}for(const[a,u]of Object.entries(r))T(a,u,t,n,o,e+1)}},T=(r,t,n,o,e,a)=>{if(r==="AND"||r==="OR"||r==="NOT"){A(t,n,o,e,a);return}if(!r.startsWith("__")){if(P(n,r))throw new S("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(C(t))for(const u of Object.values(t))A(u,l,`${o}.${r}`,e,a)}},B=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},g=(r,t,n)=>{l.size===0||t===void 0||A(t,B(r),r,n)},_=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(P(n,a))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},j=(r,t,n)=>{if(!(l.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,u=`${r}.${o}`;A(a.where,l,u,n),_(u,a.orderBy,l,n),j(u,a.with,n)}},$=(r,t,n)=>{g(r,t?.where,n),g(r,t?.baseWhere,n),_(r,t?.orderBy,B(r),n),j(r,t?.with,n)},U=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,t,n)=>{const o=U(t);g(r,o?.where,n),g(r,o?.baseWhere,n),j(r,o?.with,n)},W=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,E={relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[a,u]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?W(e.through.table,e.through.from)??W(e.through.table,e.through.to):W(a,e.field)??W(u,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,t,n){if(g(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(g(r,n.where,"patchIf"),s.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:d(o.doc,e,c)}:o},async patchWhere(r,t,n){if(g(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return R(r,[t.field],"aggregate"),g(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=U(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return g(r,o,"count"),n&&g(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){$(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?d(n,o,c):n},async findFirstOrThrow(r,t){$(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?d(n,o,c):n},async explain(r,t){return $(r,t,"explain"),s.explain(r,t)},async findMany(r,t){$(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?v(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:d(n,o,c)},related:s.related?async(r,t)=>await s.related(r,k(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?d(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),g(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?O(t,n,r):t},async rank(r,t,n){return M(r,n,"rank"),h(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){M(r,n,"rankPage"),h(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?v(o,e,c):o},...x("rankBefore",y,r=>(t,n,o)=>(M(t,o,"rankBefore"),h(t,n,"rankBefore","rank"),r(t,n,o))),...x("rankPageRows",p,r=>async(t,n,o)=>{M(t,o,"rankPageRows"),h(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(u=>({...u,doc:d(u.doc,a,c)}))}:e})};J(E,s,l.size>0);const D=s[L];return D!==void 0&&Object.defineProperty(E,L,{configurable:!0,enumerable:!1,value:D,writable:!1}),E},nr=(s,i={})=>{const c=new Map(Object.entries(s)),w=q(i.roles),y=async({ctx:f,next:k})=>{const h=f,O={auth:await z(h.auth??{},w),ctx:h};if(i.bypass?.(O)===!0)return k();const R=V(h.db,c,O,i.indexFields),l={db:R},{orm:A}=h;return A!==null&&typeof A=="object"&&(l.orm=X(R)),k({ctx:l})},p=new Map;for(const[f,k]of c)p.set(f,new Set(Object.keys(k)));return Y(y,{columns:p})};export{nr as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as p,isLunoraError as Be}from"@lunora/errors";import{findRelated as Ee,whereFilter as Se}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{copyDatabaseEntries as Te,bindOrm as Ae}from"./bindOrm-DjpQXKLX.mjs";import{t as ke}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ie}from"./allowAll-DkRAgItV.mjs";const J=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},re=4;class P extends Error{}const N=e=>e.includes("."),vt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},fe=e=>{const t=e.split(".");if(t.length>re||t.includes(""))throw new P(`field path "${e}" must have 1 to ${String(re)} non-empty segments`);return t},_e=(e,t)=>{if(!N(t))return e[t];let r=e;for(const i of fe(t)){if(!J(r)||!Object.hasOwn(r,i))return;r=r[i]}return r},de=(e,t,r,i)=>{const[a,...f]=t;if(a===void 0)throw new P(`field path "${i}" is empty`);if(e!=null&&!J(e))throw new P(`cannot set "${i}": "${a}" sits inside a value that is not an object`);const u=e??{};return{...u,[a]:f.length===0?r:de(u[a],f,r,i)}},Pe=(e,t)=>{const r=Object.keys(e).filter(a=>N(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 i={};for(const[a,f]of Object.entries(e))N(a)||(i[a]=f);for(const a of r){const[f="",...u]=fe(a);if(Object.hasOwn(e,f))throw new P(`patch sets both "${f}" and "${a}"; set one or the other`);i[f]=de(Object.hasOwn(i,f)?i[f]:t[f],u,e[a],a)}return i},me=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},$e=["every","is","isNot","none","some"],De=new Set($e),Fe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>De.has(r))},oe=(e,t,r)=>t?{[e]:r(t)}:{},ue=500,Q=(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??ue},z=(e,t,r,i)=>{if(e>t)throw i(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},Z={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 B extends Error{}const he=e=>{if(!J(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(Z,r)))return{operand:e[r],operator:r}},Me=e=>he(e)!==void 0,Le=(e,t,r,i)=>{const a=Z[t];if(a.apply===void 0){if(r!==!0)throw new B(`patch: use { toggle: true } on "${e}".`);if(typeof i!="boolean")throw new B(`patch: cannot toggle "${e}" — its current value is ${String(i)}; set a boolean first.`);return!i}if(typeof r!="number"||!Number.isFinite(r))throw new B(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof i!="number"||!Number.isFinite(i))throw new B(`patch: cannot ${t} "${e}" — its current value is ${String(i)}; set a number first.`);if(t==="divide"&&r===0)throw new B(`patch: cannot divide "${e}" by zero.`);const f=a.apply(i,r);if(!Number.isFinite(f))throw new B(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},ye=(e,t)=>{const r=new Set;for(const[i,a]of Object.entries(e))t(i)!==void 0&&Me(a)&&r.add(i);return r},Ce=(e,t,r)=>{let i;for(const a of ye(e,r)){const{operand:f,operator:u}=he(e[a]),g=r(a);if(Z[u].kind!==g)throw new B(`patch: "${u}" does not apply to the ${String(g)} column "${a}".`);i??={...e},i[a]=Le(a,u,f,t[a])}return i??e},je=(e,t)=>{const r=a=>{const f=t[a];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},i={...e};for(const a of ye(e,r))try{Object.assign(i,Ce({[a]:e[a]},t,r))}catch(f){if(!(f instanceof B))throw f}try{return Pe(i,t)}catch(a){if(a instanceof P)return i;throw a}},Ue=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],S=-1,T=0,E=1,m=e=>e?E:S,w=(e,t)=>e<t?e:t,xe=(e,t)=>e>t?e:t,pe=e=>e===T?T:m(e===S),se=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},A=e=>e==null,F=(e,t,r)=>{if(r===void 0)throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Ne={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},qe=(e,t,r)=>{let i=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const f=r[a];F(e,a,f);const u=N(e);if(u?me(f)===void 0:!se(f))i=w(i,S);else if(A(t))i=w(i,T);else{const g=Ne[a],y=u?typeof t==typeof f:se(t);i=w(i,m(y&&g(t,f)))}}return i},ie=(e,t,r)=>{if(!Array.isArray(r))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},ae=(e,t)=>t.length===0?S:A(e)?T:t.includes(e)?E:t.some(r=>A(r))?T:S,Ye=(e,t,r)=>{let i=E;if("in"in r&&(i=w(i,ae(t,ie(e,"in",r.in)))),"notIn"in r&&(i=w(i,pe(ae(t,ie(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;F(e,"contains",a),i=A(t)?w(i,T):w(i,m(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(i=w(i,m(r.isNull===!0===A(t)))),i},G=(e,t,r)=>t===null?m(r===A(e)):A(e)?T:m(r===(e===t)),He=(e,t,r)=>{let i=E;return"eq"in r&&(F(e,"eq",r.eq),i=w(i,G(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),i=w(i,G(t,r.ne,!1))),i},Ke=(e,t,r)=>w(He(e,t,r),w(Ye(e,t,r),qe(e,t,r))),Qe=(e,t,r,i)=>{if(t==="NOT")return pe(i(e,r??{}));if(!Array.isArray(r))return S;let a=t==="AND"?E:S;for(const f of r){const u=i(e,f);a=t==="AND"?w(a,u):xe(a,u)}return a},we=e=>e==="AND"||e==="OR"||e==="NOT",ze=e=>X(e)&&Object.keys(e).every(t=>Ue.includes(t)),q=e=>Object.keys(e).some(t=>{const r=e[t];return we(t)?t==="NOT"?q(r??{}):Array.isArray(r)&&r.some(i=>q(i??{})):Fe(r)}),ge=(e,t)=>{let r=E;for(const i of Object.keys(t)){const a=t[i];if(we(i)){r=w(r,Qe(e,i,a,ge));continue}const f=_e(e,i);if(ze(a)){r=w(r,Ke(i,f,a));continue}F(i,"eq",a),r=w(r,G(f,a,!0))}return r},Y=(e,t)=>ge(e,t)===E,ce=(e,t)=>e===void 0||t===void 0?e??t:(r,i)=>e(r,i)&&t(r,i),_=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{z(e,Q(t,r,_),r,_)},Ge=Ie(),Xe=Symbol.for("lunora.ctxdb.rls-unwrap"),Je=Symbol.for("lunora.ctxdb.rls-relation-gate"),be=Symbol.for("lunora.rls.wrapped-chain"),K=new WeakMap,Ze=e=>e[be],Ve=e=>{const t=new Map;for(const r of e){const i=t.get(r.table)??[];i.push(r),t.set(r.table,i)}return t},et=(e,t)=>{const r=[];let i=!1;for(const a of e){if(a.on!=="read")continue;const f=a.when(t);if(f!==void 0){if(f===!0){i=!0;break}f!==!1&&r.push(f)}}if(!i)return r.length===0?Ge:r.length===1?r[0]:{OR:r}},tt=(e,t,r)=>{const i=e.when({...t,row:r});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return Y(r,i)},nt=(e,t,r)=>{const i=e.when(t);if(i===void 0||i===!0)return r===void 0||tt(e,t,r);if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!Y(t.row,i)?!1:r===void 0||Y(r,i)},rt=(e,t,r,i)=>{let a=!1;for(const f of e)if(f.on===t&&(a=!0,!nt(f,r,i)))return!1;return a},ot=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),st=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),it=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>ot.has(r)&&st(r,e[r]))},at=e=>e===void 0?{}:X(e)&&it(e)?e:{where:e},x=e=>e!==void 0&&Object.keys(e).length>0,le=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>x(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ct=(e,t,r)=>{const[i]=r,a=r.length===1&&i!==void 0?i.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const s=[];let c=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;c=!0;const O=et(h,d.context);O!==void 0&&s.push(O)}const l={baseWhere:le(s),restricts:c};return f.set(n,l),l},g=(n,o,s,c)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!rt(d,o,{...l.context,row:s},c))return!1}return!0},y=n=>u(n).restricts?t:e,k=e[Je],b=n=>{const{baseWhere:o,restricts:s}=u(n);return s||k?.gate(n),o};k?.trust(b),K.set(b,u);const v=n=>{const o=typeof n=="function"?K.get(n):void 0;if(o===void 0)return b;const s=l=>{const d=u(l),h=o(l);return{baseWhere:le([d.baseWhere,h.baseWhere].filter(O=>x(O))),restricts:d.restricts||h.restricts}},c=l=>{const{baseWhere:d,restricts:h}=s(l);return h||k?.gate(l),d};return k?.trust(c),K.set(c,s),c},$=async(n,o)=>{const s=await t.get(n,o);return s?{row:s,tableName:a.has(n)?n:void 0}:{row:null,tableName:void 0}},H=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}},M=async(n,o)=>{const s=await $(n,o);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},R=async(n,o,s,c,l)=>{const d=await M(n,o);if(!d)return c(e);const h=l?l(d.row):void 0;if(!g(d.tableName,s,d.row,h))throw new p("FORBIDDEN",`${s} denied by policy`);return c(t,d.tableName)},L=(n,o,s)=>{if(s?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},ve=async(n,o,s,c,l)=>{const d=s?t:e,h=await d.findFirst(o,{...s?{baseWhere:u(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:W(l,{_id:n})});if(!h||L(o,h,c))return!1;if(s&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,c),!0},V=async(n,o,s,c)=>{const l=a.has(n),d=l?t:e,h=s===void 0?void 0:{hard:s},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const te of o){const ne=String(te._id);if(O){await ve(ne,n,l,h,c)&&(D+=1);continue}if(l&&!g(n,"delete",te))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ne,h),D+=1}return D},C=(n,o,s,c)=>R(n,o,"update",(l,d)=>c(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...je(s,l)})),j=(n,o)=>{const{baseWhere:s}=u(n);if(x(s))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},We=e.rankBefore,Re=e.rankPageRows,{relationEdges:ee}=e,I={async count(n,o){const{baseWhere:s}=u(n),c=at(o);return y(n).count(n,{...c,baseWhere:W(c.baseWhere,s),relationBaseWhere:v(c.relationBaseWhere),restrictsCounts:(c.restrictsCounts??!1)||x(s)})},delete:(n,o,s)=>R(n,o,"delete",c=>c.delete(n,o,s)),async deleteAll(n,o){const s=Math.max(1,o?.chunkSize??ue),{baseWhere:c}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:c,limit:s,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await V(n,h,o?.hard),h.length<s))break}return{deleted:l}},async deleteMany(n,o,s){U(o.length,s?.limit,"deleteMany");for(const c of o)await R(n,c,"delete",l=>l.delete(n,c));return{deleted:o.length}},async deleteWhere(n,o,s){const{baseWhere:c}=u(n),l=Q(s?.limit,"deleteWhere",_),d=await y(n).findMany(n,{baseWhere:W(o,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return z(h.length,l,"deleteWhere",_),{deleted:await V(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:s}=u(n);return y(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findFirstOrThrow(n,o){const{baseWhere:s}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async explain(n,o){const{baseWhere:s}=u(n);return y(n).explain(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findMany(n,o){const{baseWhere:s}=u(n);return y(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async get(n,o){const s=await $(n,o);if(!s.row)return null;if(s.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:l}=u(s.tableName);if(!l)return e.get(n,o);if(!c)return s.row;const d=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const s=o===void 0?await H(n):await $(o,n);if(!s.row)return null;if(s.tableName===void 0||!u(s.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=u(s.tableName);if(!c)return{row:s.row,tableName:s.tableName};const l=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:s.tableName}:null},async insert(n,o,s){if(a.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,s)}return e.insert(n,o,s)},async insertMany(n,o,s){if(U(o.length,s?.limit,"insertMany"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,s)}return e.insertMany(n,o,s)},async insertManyUnsafe(n,o,s){if(U(o.length,s?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,s)}return e.insertManyUnsafe(n,o,s)},patch:(n,o,s,c)=>C(n,o,s,(l,d)=>l.patch(n,o,s,{...c,verify:ce(c?.verify,d.verify)})),assertPatchAllowed:(n,o)=>C(n,o,{},()=>Promise.resolve()),async patchIf(n,o,s){const c=await C(n,o,s.patch,async(d,h)=>{if(d.patchIf===void 0)throw new p("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return d.patchIf(n,o,{...s,verify:ce(s.verify,h.verify)})});return c.doc===null||await I.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,s){U(o.length,s?.limit,"patchMany");for(const c of o)await C(n,c.id,c.patch,(l,d)=>l.patch(n,c.id,c.patch,d));return{patched:o.length}},async patchWhere(n,o,s){const{baseWhere:c}=u(n),l=Q(s?.limit,"patchWhere",_),h=(await y(n).findMany(n,{baseWhere:W(o.where,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return z(h.length,l,"patchWhere",_),I.patchMany(n,h,s)},query(n){const{baseWhere:o}=u(n),s=y(n).query(n);return o?s.filter(Se(o,c=>Y(c,o))):s},related:ee===void 0?void 0:async(n,o)=>Ee({findMany:async(s,c)=>I.findMany(s,c),lookupById:async s=>t.lookupById?.(s)},ee,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>R(n,o,"update",async s=>{const c=s.restore??t.restore;if(!c)throw new p("BAD_REQUEST","restore is not supported by this writer");await c(n,o)}),replace:(n,o,s)=>R(n,o,"update",c=>c.replace(n,o,s),c=>({...s,_creationTime:s._creationTime??c._creationTime,_id:c._id})),aggregate(n,o){const{baseWhere:s}=u(n);return y(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},groupBy(n,o){const{baseWhere:s}=u(n);return y(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},rank(n,o,s){return j(n,"rank"),y(n).rank(n,o,s)},rankPage(n,o,s){return j(n,"rankPage"),y(n).rankPage(n,o,s)},wipeShard(){throw new p("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})},...oe("rankBefore",We,n=>(o,s,c)=>(j(o,"rankBefore"),(y(o).rankBefore??n)(o,s,c))),...oe("rankPageRows",Re,n=>(o,s,c)=>(j(o,"rankPageRows"),(y(o).rankPageRows??n)(o,s,c)))};return Te(I,e,a.size>0),Object.defineProperty(I,be,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),I},Oe=e=>typeof e=="string"?e:e.name,lt=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(i=>Oe(i))));return t},ft=(e,t)=>{const r=new Set;for(const i of e)for(const a of t.get(i)??[])r.add(a);return i=>r.has(Oe(i))},dt=["roles","role"],ut=e=>{for(const t of dt){const r=e?.[t];if(typeof r=="string"){const i=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(i.length>0)return i}if(Array.isArray(r)){const i=r.filter(a=>typeof a=="string"&&a.length>0);if(i.length>0)return i}}return[]},ht=async(e,t)=>{const r=await e.getIdentity?.()??null,i=[...new Set([...ut(r),...e.roles??[]])];return{can:ft(i,t),identity:r,roles:i,userId:e.userId??null}},Wt=(e,t={})=>{const r=e,i=Ve(r),a=lt(t.roles);return ke(async({ctx:u,next:g})=>{const y=u,k={auth:await ht(y.auth??{},a),ctx:y},b=y.db,v=Ze(b),$=v?.base??b,H=v?.raw??b[Xe]??b,M=ct($,H,[...v?.steps??[],{context:k,perTable:i}]),R={db:M},{orm:L}=y;return L!==null&&typeof L=="object"&&(R.orm=Ae(M)),g({ctx:R})},[{policies:r,roles:t.roles??[]}])};export{ht as a,vt as b,Fe as c,ut as d,et as e,ft as f,rt as g,lt as i,Y as m,oe as o,Wt as r};
@@ -0,0 +1 @@
1
+ import{e as t,g as i,i as m,m as l,d,f as p,a as h,r as n}from"./middleware-DwU2Sv_S.mjs";import"./bindOrm-DjpQXKLX.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as matchesWhere,d as readIdentityRoles,p as resolveCan,h as resolvePolicyAuth,n as rls};
@@ -0,0 +1 @@
1
+ import{LunoraError as k}from"@lunora/errors";import{copyDatabaseEntries as A}from"./bindOrm-DjpQXKLX.mjs";import{i as D,a as E}from"./middleware-DwU2Sv_S.mjs";const N=(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},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},M=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},$=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",M],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],P=[["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.']],B=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},L=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&B(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 })\`.`)},x=(e,t={})=>{const o=D(t.roles);return async({ctx:i,next:c})=>{const g=await E(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=>S(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 $){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 P)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();L(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;if(y!==void 0&&m!==void 0&&typeof m=="object"){const s={system:N(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})};A(s,y,!1),p.db=s}return c({ctx:p})}};export{x as storageRules};
@@ -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-CHYtnvZP.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,d as P,f as W,e as v,m as I,g as R}from"../packem_shared/middleware-DwU2Sv_S.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.285",
3
+ "version": "1.0.0-alpha.287",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -1 +0,0 @@
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,s)=>t!==void 0&&Object.hasOwn(t,n)&&x(s),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(e=>typeof e!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const s=[...new Set(t)];return s.length>y&&u("VALIDATION_ERROR",`${n} names ${String(s.length)} rows; at most ${String(y)} per list`),s},E=(t,n,s)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${s}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),e!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),e!==void 0?(typeof e!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:e,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,s)=>{n.through===void 0&&E(t,n,s)},j=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;if(c!==void 0)return(e!==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=e===void 0?[]:R(e,`${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}},k=(t,n,s,e)=>{const i=Object.fromEntries(Object.entries(e).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=s.refusal??s.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),s.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${s.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),s.kind==="one"?D(n,s,i):j(n,s,i)},P=t=>t.info.kind==="one",T=(t,n,s)=>{if(n===void 0)return{columns:s,manys:[],ones:[]};const e={},i=[],c=[];for(const[a,r]of Object.entries(s)){if(!I(n,a,r)){e[a]=r;continue}const o=k(t,a,n[a],r);o!==void 0&&(P(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(e,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:e,manys:i,ones:c}},w=(t,n,s,e)=>{const i=Object.entries(s).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${e}: "${i}" is a relation write, which ${e} does not support; use insert or patch`)},O=async(t,n,s,e,i)=>{const c=await t.get(e,i);return c===null&&u("NOT_FOUND",`${n}.${s}: no "${e}" row with id "${i}"`),c},b=async(t,n)=>{const s={...n.columns};for(const{connect:e,info:i,name:c}of n.ones){let a=null;e!==void 0&&(a=(await O(t,c,"connect",i.table,e))[i.references]),s[i.field]=a}return s},W=async(t,{info:n,name:s},e,i)=>{(await O(t,s,"connect",n.table,e))[n.field]!==i&&await t.patch(n.table,e,{[n.field]:i})},F=async(t,{info:n},s,e)=>{s[n.field]===e&&await t.patch(n.table,String(s._id),{[n.field]:null})},U=async(t,{info:n,name:s},e)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:e}});return i.length>y&&u("VALIDATION_ERROR",`${s}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const s=new Set(t),e=new Set(n);return{attach:n.filter(i=>!s.has(i)),release:new Set(t.filter(i=>!e.has(i)))}},$=async(t,{name:n},{from:s,table:e,to:i},c,a)=>{const r=a===void 0?{[s]:c}:{[s]:c,[i]:{in:a}},{page:o}=await t.findMany(e,{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,s)=>{if(s.length===0)return new Set;const{page:e}=await t.findMany(n,{limit:s.length,where:{_id:{in:s}}});return new Set(e.map(i=>String(i._id)))},C=async(t,n,s)=>{const{info:e,name:i}=n,{from:c,table:a,to:r}=e.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(l=>O(t,i,"disconnect",e.table,l))),d=n.release.length===0?[]:await $(t,n,e.through,s,n.release);const h=n.attach.length===0?[]:await $(t,n,e.through,s,n.attach),f=new Set(h.map(l=>String(l[r])));o=n.attach.filter(l=>!f.has(l))}else{const h=await $(t,n,e.through,s,void 0),f=L(h.map(g=>String(g[r])),n.replace),l=await V(t,e.table,[...f.release]);({attach:o}=f),d=h.filter(g=>f.release.has(String(g[r]))&&l.has(String(g[r])))}await Promise.all(o.map(h=>O(t,i,"connect",e.table,h)));for(const h of d)await t.delete(a,String(h._id));for(const h of o)try{await t.insert(a,{[c]:s,[r]:h})}catch(f){if(!v(f)||!e.pairIsOnlyUnique)throw f}},q=async(t,n,s)=>{let{attach:e}=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,s),a=L(c.map(r=>String(r._id)),n.replace);({attach:e}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await F(t,n,c,s);for(const c of e)await W(t,n,c,s)},_=async(t,n,s,e)=>{for(const i of s.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await e(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,s,e)=>async i=>i==="_id"?s:Object.hasOwn(e,i)?e[i]:(await t.get(n,s))?.[i],B=async(t,n,s,e,i)=>{const c=T(n,s,e);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},G=async(t,n,s,e,i)=>{const c=T(n,s,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(n,e,c.columns);return}const a=await b(t,c);if(Object.keys(a).length>0)await t.patch(n,e,a);else{if(await t.get(n,e)===null)throw new p("NOT_FOUND",`document not found: ${e}`);await t.assertPatchAllowed?.(n,e)}await _(t,n,c,S(t,n,e,a))},m=(t,n,s,e)=>{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 s)){const r=Object.entries(e??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in s)?.[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]=s[a]}return c},z=(t,n)=>{const s=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(h){if(v(h))return null;throw h}},e=t.relationWrites?.[n],i=(o,d)=>B(t,n,e,o,h=>s(h,d)),c=(o,d)=>G(t,n,e,o,d),a=async o=>{const d=o??{},h=await t.findMany(n,{...d,limit:2});if(h.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return h.page[0]??null},r=async({create:o,target:d,update:h})=>{const f=m(n,d,o,e),l=await t.findFirst(n,{where:f});return l&&typeof l._id=="string"?(await c(l._id,h??o),{created:!1,id:l._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 h=o;return t.deleteWhere(n,h.where,{limit:h.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 h of o)w(n,e,h,"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 h=Array.isArray(o)?o.map(l=>l.values):[o.values];for(const l of h)w(n,e,l,"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(l=>({id:l.id,patch:l.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,e,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 h=[];for(const f of o)h.push(await r({create:f.create,target:d,update:f.update}));return h},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},X=(t,n)=>{const s=e=>({configurable:!0,enumerable:!0,value:e,writable:!0});Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){const e=z(t,n);return Object.defineProperty(t,n,s(e)),e},set(e){Object.defineProperty(this,n,s(e))}})},H=t=>{const n=s=>{const e=t[s];if(!e)throw new p("INTERNAL",`unknown table: ${s}`);return e};return{delete:(s,e)=>n(s).delete(e),insert:s=>({values:e=>n(s).insert(e)}),query:t,replace:(s,e)=>({with:i=>n(s).replace(e,i)}),update:(s,e)=>({set:i=>n(s).patch(e,i)})}};export{H as bindOrm,z as bindTableFacade,X as defineLazyFacade};
@@ -1 +0,0 @@
1
- import{LunoraError as S}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as L,b as H,c as C,d as J}from"./middleware-CHYtnvZP.mjs";import{defineLazyFacade as X,bindOrm as Y}from"./bindOrm-D5mVDvbi.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const x=Symbol.for("lunora.ctxdb.rls-relation-gate"),V=(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 w={...s};for(const[y,p]of Object.entries(i))y in w&&(w[y]=V(p,s[y],{...c,column:y,row:s}));return w},v=(s,i,c)=>({...s,page:s.page.map(w=>f(w,i,c))}),P=(s,i)=>{const c=C(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},K=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,p=()=>new Proxy({},{get:()=>u=>(typeof u=="string"&&y.add(u),p())});s(p());for(const u of y)if(P(i,u))throw new S("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${u}" is not supported`)},G=64,Z=(s,i,c,w)=>{const y=s.rankBefore,p=s.rankPageRows,u=(r,t)=>{const n=i.get(r);return n?t.map(o=>f(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?u:(n,o)=>t(n,u(n,o))}},h=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[t];if(!a)return;const d=a.find(I=>P(e,I));if(d!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${d}" — use an index whose declared fields are all unmasked, or unmask the column`)},O=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield f(o,t,c)},collect:async()=>(await r.collect()).map(e=>f(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=f(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>O(r.filter(e=>o(f(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?f(o,t,c):null},order:o=>O(r.order(o),t,n),paginate:async o=>v(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>f(a,t,c)),unique:async()=>{const o=await r.unique();return o?f(o,t,c):null},withIndex:(o,e)=>(h(n,o,"withIndex","index"),K(e,t,n,"withIndex"),O(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(K(e,t,n,"withSearchIndex"),O(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(h(n,o,"withGeoIndex","geo"),O(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&P(o,a));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},l=new Set;for(const r of i.values())for(const t of Object.keys(r))l.add(t);const A=(r,t,n,o,e=0)=>{if(!(!r||typeof r!="object")){if(e>=G)throw new S("MASK_UNSUPPORTED",`${o}() filtering "${n}" with a where nested deeper than ${String(G)} levels is not supported`);if(Array.isArray(r)){for(const a of r)A(a,t,n,o,e+1);return}for(const[a,d]of Object.entries(r))T(a,d,t,n,o,e+1)}},T=(r,t,n,o,e,a)=>{if(r==="AND"||r==="OR"||r==="NOT"){A(t,n,o,e,a);return}if(!r.startsWith("__")){if(P(n,r))throw new S("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(J(t))for(const d of Object.values(t))A(d,l,`${o}.${r}`,e,a)}},B=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},g=(r,t,n)=>{l.size===0||t===void 0||A(t,B(r),r,n)},_=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(P(n,a))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},j=(r,t,n)=>{if(!(l.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,d=`${r}.${o}`;A(a.where,l,d,n),_(d,a.orderBy,l,n),j(d,a.with,n)}},$=(r,t,n)=>{g(r,t?.where,n),g(r,t?.baseWhere,n),_(r,t?.orderBy,B(r),n),j(r,t?.with,n)},F=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,t,n)=>{const o=F(t);g(r,o?.where,n),g(r,o?.baseWhere,n),j(r,o?.with,n)},W=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,E={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[a,d]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?W(e.through.table,e.through.from)??W(e.through.table,e.through.to):W(a,e.field)??W(d,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,t,n){if(g(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(g(r,n.where,"patchIf"),s.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:f(o.doc,e,c)}:o},async patchWhere(r,t,n){if(g(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return R(r,[t.field],"aggregate"),g(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=F(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return g(r,o,"count"),n&&g(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){$(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?f(n,o,c):n},async findFirstOrThrow(r,t){$(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?f(n,o,c):n},async explain(r,t){return $(r,t,"explain"),s.explain(r,t)},async findMany(r,t){$(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?v(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:f(n,o,c)},related:s.related?async(r,t)=>await s.related(r,k(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?f(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),g(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?O(t,n,r):t},async rank(r,t,n){return M(r,n,"rank"),h(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){M(r,n,"rankPage"),h(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?v(o,e,c):o},...L("rankBefore",y,r=>(t,n,o)=>(M(t,o,"rankBefore"),h(t,n,"rankBefore","rank"),r(t,n,o))),...L("rankPageRows",p,r=>async(t,n,o)=>{M(t,o,"rankPageRows"),h(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(d=>({...d,doc:f(d.doc,a,c)}))}:e})};if(l.size>0)for(const[r,t]of Object.entries(s))H(t)&&X(E,r);const U=s[x];return U!==void 0&&Object.defineProperty(E,x,{configurable:!0,enumerable:!1,value:U,writable:!1}),E},or=(s,i={})=>{const c=new Map(Object.entries(s)),w=q(i.roles),y=async({ctx:u,next:k})=>{const h=u,O={auth:await z(h.auth??{},w),ctx:h};if(i.bypass?.(O)===!0)return k();const R=Z(h.db,c,O,i.indexFields),l={db:R},{orm:A}=h;return A!==null&&typeof A=="object"&&(l.orm=Y(R)),k({ctx:l})},p=new Map;for(const[u,k]of c)p.set(u,new Set(Object.keys(k)));return Q(y,{columns:p})};export{or as mask};
@@ -1 +0,0 @@
1
- import{LunoraError as p,isLunoraError as Be}from"@lunora/errors";import{findRelated as Ee,whereFilter as Se}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{defineLazyFacade as Ae,bindOrm as Te}from"./bindOrm-D5mVDvbi.mjs";import{t as ke}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ie}from"./allowAll-DkRAgItV.mjs";const J=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},re=4;class m extends Error{}const N=e=>e.includes("."),Wt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},fe=e=>{const t=e.split(".");if(t.length>re||t.includes(""))throw new m(`field path "${e}" must have 1 to ${String(re)} non-empty segments`);return t},_e=(e,t)=>{if(!N(t))return e[t];let r=e;for(const i of fe(t)){if(!J(r)||!Object.hasOwn(r,i))return;r=r[i]}return r},de=(e,t,r,i)=>{const[a,...f]=t;if(a===void 0)throw new m(`field path "${i}" is empty`);if(e!=null&&!J(e))throw new m(`cannot set "${i}": "${a}" sits inside a value that is not an object`);const u=e??{};return{...u,[a]:f.length===0?r:de(u[a],f,r,i)}},me=(e,t)=>{const r=Object.keys(e).filter(a=>N(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 m(`patch sets both "${a}" and "${f}", which overlap; set one or the other`)}const i={};for(const[a,f]of Object.entries(e))N(a)||(i[a]=f);for(const a of r){const[f="",...u]=fe(a);if(Object.hasOwn(e,f))throw new m(`patch sets both "${f}" and "${a}"; set one or the other`);i[f]=de(Object.hasOwn(i,f)?i[f]:t[f],u,e[a],a)}return i},Pe=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},$e=["every","is","isNot","none","some"],De=new Set($e),Fe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>De.has(r))},oe=(e,t,r)=>t?{[e]:r(t)}:{},ue=500,K=(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??ue},Q=(e,t,r,i)=>{if(e>t)throw i(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},Z={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 B extends Error{}const he=e=>{if(!J(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(Z,r)))return{operand:e[r],operator:r}},Me=e=>he(e)!==void 0,Le=(e,t,r,i)=>{const a=Z[t];if(a.apply===void 0){if(r!==!0)throw new B(`patch: use { toggle: true } on "${e}".`);if(typeof i!="boolean")throw new B(`patch: cannot toggle "${e}" — its current value is ${String(i)}; set a boolean first.`);return!i}if(typeof r!="number"||!Number.isFinite(r))throw new B(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof i!="number"||!Number.isFinite(i))throw new B(`patch: cannot ${t} "${e}" — its current value is ${String(i)}; set a number first.`);if(t==="divide"&&r===0)throw new B(`patch: cannot divide "${e}" by zero.`);const f=a.apply(i,r);if(!Number.isFinite(f))throw new B(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},ye=(e,t)=>{const r=new Set;for(const[i,a]of Object.entries(e))t(i)!==void 0&&Me(a)&&r.add(i);return r},je=(e,t,r)=>{let i;for(const a of ye(e,r)){const{operand:f,operator:u}=he(e[a]),g=r(a);if(Z[u].kind!==g)throw new B(`patch: "${u}" does not apply to the ${String(g)} column "${a}".`);i??={...e},i[a]=Le(a,u,f,t[a])}return i??e},Ce=(e,t)=>{const r=a=>{const f=t[a];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},i={...e};for(const a of ye(e,r))try{Object.assign(i,je({[a]:e[a]},t,r))}catch(f){if(!(f instanceof B))throw f}try{return me(i,t)}catch(a){if(a instanceof m)return i;throw a}},Ue=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],S=-1,A=0,E=1,P=e=>e?E:S,w=(e,t)=>e<t?e:t,xe=(e,t)=>e>t?e:t,pe=e=>e===A?A:P(e===S),se=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},T=e=>e==null,F=(e,t,r)=>{if(r===void 0)throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Ne={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},qe=(e,t,r)=>{let i=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const f=r[a];F(e,a,f);const u=N(e);if(u?Pe(f)===void 0:!se(f))i=w(i,S);else if(T(t))i=w(i,A);else{const g=Ne[a],y=u?typeof t==typeof f:se(t);i=w(i,P(y&&g(t,f)))}}return i},ie=(e,t,r)=>{if(!Array.isArray(r))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},ae=(e,t)=>t.length===0?S:T(e)?A:t.includes(e)?E:t.some(r=>T(r))?A:S,Ye=(e,t,r)=>{let i=E;if("in"in r&&(i=w(i,ae(t,ie(e,"in",r.in)))),"notIn"in r&&(i=w(i,pe(ae(t,ie(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;F(e,"contains",a),i=T(t)?w(i,A):w(i,P(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(i=w(i,P(r.isNull===!0===T(t)))),i},G=(e,t,r)=>t===null?P(r===T(e)):T(e)?A:P(r===(e===t)),ze=(e,t,r)=>{let i=E;return"eq"in r&&(F(e,"eq",r.eq),i=w(i,G(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),i=w(i,G(t,r.ne,!1))),i},He=(e,t,r)=>w(ze(e,t,r),w(Ye(e,t,r),qe(e,t,r))),Ke=(e,t,r,i)=>{if(t==="NOT")return pe(i(e,r??{}));if(!Array.isArray(r))return S;let a=t==="AND"?E:S;for(const f of r){const u=i(e,f);a=t==="AND"?w(a,u):xe(a,u)}return a},we=e=>e==="AND"||e==="OR"||e==="NOT",Qe=e=>X(e)&&Object.keys(e).every(t=>Ue.includes(t)),q=e=>Object.keys(e).some(t=>{const r=e[t];return we(t)?t==="NOT"?q(r??{}):Array.isArray(r)&&r.some(i=>q(i??{})):Fe(r)}),ge=(e,t)=>{let r=E;for(const i of Object.keys(t)){const a=t[i];if(we(i)){r=w(r,Ke(e,i,a,ge));continue}const f=_e(e,i);if(Qe(a)){r=w(r,He(i,f,a));continue}F(i,"eq",a),r=w(r,G(f,a,!0))}return r},Y=(e,t)=>ge(e,t)===E,ce=(e,t)=>e===void 0||t===void 0?e??t:(r,i)=>e(r,i)&&t(r,i),_=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{Q(e,K(t,r,_),r,_)},Ge=Ie(),Xe=Symbol.for("lunora.ctxdb.rls-unwrap"),Je=Symbol.for("lunora.ctxdb.rls-relation-gate"),be=Symbol.for("lunora.rls.wrapped-chain"),H=new WeakMap,Ze=e=>e[be],Ve=e=>{const t=new Map;for(const r of e){const i=t.get(r.table)??[];i.push(r),t.set(r.table,i)}return t},et=(e,t)=>{const r=[];let i=!1;for(const a of e){if(a.on!=="read")continue;const f=a.when(t);if(f!==void 0){if(f===!0){i=!0;break}f!==!1&&r.push(f)}}if(!i)return r.length===0?Ge:r.length===1?r[0]:{OR:r}},tt=(e,t,r)=>{const i=e.when({...t,row:r});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return Y(r,i)},nt=(e,t,r)=>{const i=e.when(t);if(i===void 0||i===!0)return r===void 0||tt(e,t,r);if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!Y(t.row,i)?!1:r===void 0||Y(r,i)},rt=(e,t,r,i)=>{let a=!1;for(const f of e)if(f.on===t&&(a=!0,!nt(f,r,i)))return!1;return a},ot=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),st=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),it=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>ot.has(r)&&st(r,e[r]))},at=e=>e===void 0?{}:X(e)&&it(e)?e:{where:e},x=e=>e!==void 0&&Object.keys(e).length>0,le=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>x(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ct=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},lt=(e,t,r)=>{const[i]=r,a=r.length===1&&i!==void 0?i.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const s=[];let c=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;c=!0;const O=et(h,d.context);O!==void 0&&s.push(O)}const l={baseWhere:le(s),restricts:c};return f.set(n,l),l},g=(n,o,s,c)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!rt(d,o,{...l.context,row:s},c))return!1}return!0},y=n=>u(n).restricts?t:e,k=e[Je],b=n=>{const{baseWhere:o,restricts:s}=u(n);return s||k?.gate(n),o};k?.trust(b),H.set(b,u);const v=n=>{const o=typeof n=="function"?H.get(n):void 0;if(o===void 0)return b;const s=l=>{const d=u(l),h=o(l);return{baseWhere:le([d.baseWhere,h.baseWhere].filter(O=>x(O))),restricts:d.restricts||h.restricts}},c=l=>{const{baseWhere:d,restricts:h}=s(l);return h||k?.gate(l),d};return k?.trust(c),H.set(c,s),c},$=async(n,o)=>{const s=await t.get(n,o);return s?{row:s,tableName:a.has(n)?n:void 0}:{row:null,tableName:void 0}},z=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}},M=async(n,o)=>{const s=await $(n,o);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},R=async(n,o,s,c,l)=>{const d=await M(n,o);if(!d)return c(e);const h=l?l(d.row):void 0;if(!g(d.tableName,s,d.row,h))throw new p("FORBIDDEN",`${s} denied by policy`);return c(t,d.tableName)},L=(n,o,s)=>{if(s?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},ve=async(n,o,s,c,l)=>{const d=s?t:e,h=await d.findFirst(o,{...s?{baseWhere:u(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:W(l,{_id:n})});if(!h||L(o,h,c))return!1;if(s&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,c),!0},V=async(n,o,s,c)=>{const l=a.has(n),d=l?t:e,h=s===void 0?void 0:{hard:s},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const te of o){const ne=String(te._id);if(O){await ve(ne,n,l,h,c)&&(D+=1);continue}if(l&&!g(n,"delete",te))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ne,h),D+=1}return D},j=(n,o,s,c)=>R(n,o,"update",(l,d)=>c(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...Ce(s,l)})),C=(n,o)=>{const{baseWhere:s}=u(n);if(x(s))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},We=e.rankBefore,Re=e.rankPageRows,{relationEdges:ee}=e,I={...e,async count(n,o){const{baseWhere:s}=u(n),c=at(o);return y(n).count(n,{...c,baseWhere:W(c.baseWhere,s),relationBaseWhere:v(c.relationBaseWhere),restrictsCounts:(c.restrictsCounts??!1)||x(s)})},delete:(n,o,s)=>R(n,o,"delete",c=>c.delete(n,o,s)),async deleteAll(n,o){const s=Math.max(1,o?.chunkSize??ue),{baseWhere:c}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:c,limit:s,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await V(n,h,o?.hard),h.length<s))break}return{deleted:l}},async deleteMany(n,o,s){U(o.length,s?.limit,"deleteMany");for(const c of o)await R(n,c,"delete",l=>l.delete(n,c));return{deleted:o.length}},async deleteWhere(n,o,s){const{baseWhere:c}=u(n),l=K(s?.limit,"deleteWhere",_),d=await y(n).findMany(n,{baseWhere:W(o,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return Q(h.length,l,"deleteWhere",_),{deleted:await V(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:s}=u(n);return y(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findFirstOrThrow(n,o){const{baseWhere:s}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async explain(n,o){const{baseWhere:s}=u(n);return y(n).explain(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findMany(n,o){const{baseWhere:s}=u(n);return y(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async get(n,o){const s=await $(n,o);if(!s.row)return null;if(s.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:l}=u(s.tableName);if(!l)return e.get(n,o);if(!c)return s.row;const d=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const s=o===void 0?await z(n):await $(o,n);if(!s.row)return null;if(s.tableName===void 0||!u(s.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=u(s.tableName);if(!c)return{row:s.row,tableName:s.tableName};const l=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:s.tableName}:null},async insert(n,o,s){if(a.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,s)}return e.insert(n,o,s)},async insertMany(n,o,s){if(U(o.length,s?.limit,"insertMany"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,s)}return e.insertMany(n,o,s)},async insertManyUnsafe(n,o,s){if(U(o.length,s?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,s)}return e.insertManyUnsafe(n,o,s)},patch:(n,o,s,c)=>j(n,o,s,(l,d)=>l.patch(n,o,s,{...c,verify:ce(c?.verify,d.verify)})),assertPatchAllowed:(n,o)=>j(n,o,{},()=>Promise.resolve()),async patchIf(n,o,s){const c=await j(n,o,s.patch,async(d,h)=>{if(d.patchIf===void 0)throw new p("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return d.patchIf(n,o,{...s,verify:ce(s.verify,h.verify)})});return c.doc===null||await I.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,s){U(o.length,s?.limit,"patchMany");for(const c of o)await j(n,c.id,c.patch,(l,d)=>l.patch(n,c.id,c.patch,d));return{patched:o.length}},async patchWhere(n,o,s){const{baseWhere:c}=u(n),l=K(s?.limit,"patchWhere",_),h=(await y(n).findMany(n,{baseWhere:W(o.where,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return Q(h.length,l,"patchWhere",_),I.patchMany(n,h,s)},query(n){const{baseWhere:o}=u(n),s=y(n).query(n);return o?s.filter(Se(o,c=>Y(c,o))):s},related:ee===void 0?void 0:async(n,o)=>Ee({findMany:async(s,c)=>I.findMany(s,c),lookupById:async s=>t.lookupById?.(s)},ee,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>R(n,o,"update",async s=>{const c=s.restore??t.restore;if(!c)throw new p("BAD_REQUEST","restore is not supported by this writer");await c(n,o)}),replace:(n,o,s)=>R(n,o,"update",c=>c.replace(n,o,s),c=>({...s,_creationTime:s._creationTime??c._creationTime,_id:c._id})),aggregate(n,o){const{baseWhere:s}=u(n);return y(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},groupBy(n,o){const{baseWhere:s}=u(n);return y(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},rank(n,o,s){return C(n,"rank"),y(n).rank(n,o,s)},rankPage(n,o,s){return C(n,"rankPage"),y(n).rankPage(n,o,s)},wipeShard(){throw new p("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})},...oe("rankBefore",We,n=>(o,s,c)=>(C(o,"rankBefore"),(y(o).rankBefore??n)(o,s,c))),...oe("rankPageRows",Re,n=>(o,s,c)=>(C(o,"rankPageRows"),(y(o).rankPageRows??n)(o,s,c)))};if(a.size>0)for(const[n,o]of Object.entries(e))ct(o)&&Ae(I,n);return Object.defineProperty(I,be,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),I},Oe=e=>typeof e=="string"?e:e.name,ft=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(i=>Oe(i))));return t},dt=(e,t)=>{const r=new Set;for(const i of e)for(const a of t.get(i)??[])r.add(a);return i=>r.has(Oe(i))},ut=["roles","role"],ht=e=>{for(const t of ut){const r=e?.[t];if(typeof r=="string"){const i=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(i.length>0)return i}if(Array.isArray(r)){const i=r.filter(a=>typeof a=="string"&&a.length>0);if(i.length>0)return i}}return[]},yt=async(e,t)=>{const r=await e.getIdentity?.()??null,i=[...new Set([...ht(r),...e.roles??[]])];return{can:dt(i,t),identity:r,roles:i,userId:e.userId??null}},Rt=(e,t={})=>{const r=e,i=Ve(r),a=ft(t.roles);return ke(async({ctx:u,next:g})=>{const y=u,k={auth:await yt(y.auth??{},a),ctx:y},b=y.db,v=Ze(b),$=v?.base??b,z=v?.raw??b[Xe]??b,M=lt($,z,[...v?.steps??[],{context:k,perTable:i}]),R={db:M},{orm:L}=y;return L!==null&&typeof L=="object"&&(R.orm=Te(M)),g({ctx:R})},[{policies:r,roles:t.roles??[]}])};export{yt as a,ct as b,Wt as c,Fe as d,ht as e,et as f,dt as g,rt as h,ft as i,Y as m,oe as o,Rt as r};
@@ -1 +0,0 @@
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-CHYtnvZP.mjs";import"./bindOrm-D5mVDvbi.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 +0,0 @@
1
- import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-CHYtnvZP.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};