@lunora/server 1.0.0-alpha.184 → 1.0.0-alpha.186

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/dist/in-process.d.mts +101 -0
  2. package/dist/in-process.d.ts +101 -0
  3. package/dist/in-process.mjs +1 -0
  4. package/dist/index.d.mts +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.mjs +1 -1
  7. package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-DQO-8M6x.mjs → ACTION_CACHE_DEFAULT_TTL_MS-DITNUhX1.mjs} +1 -1
  8. package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-CUBxWEZF.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-BYeHnULU.mjs} +1 -1
  9. package/dist/packem_shared/{assertShapesDeclareReadPolicies-C-Ncahac.mjs → assertShapesDeclareReadPolicies-mKiSAI2N.mjs} +1 -1
  10. package/dist/packem_shared/{beginDeferredSchedules-ZhE6eeuQ.mjs → beginDeferredSchedules-CmmdpWRS.mjs} +1 -1
  11. package/dist/packem_shared/{defineShape-DfP6fQ_u.mjs → defineShape-B8U-uTeQ.mjs} +1 -1
  12. package/dist/packem_shared/{httpAction-xizRL75J.mjs → httpAction-CsKNC6op.mjs} +1 -1
  13. package/dist/packem_shared/{mask-DTh0I6lT.mjs → mask-BwK_5ndJ.mjs} +1 -1
  14. package/dist/packem_shared/{middleware-3-gbLgdd.mjs → middleware-C1CfQMYn.mjs} +1 -1
  15. package/dist/packem_shared/{rls-D04_2R1V.mjs → rls-B5WKMHyP.mjs} +1 -1
  16. package/dist/packem_shared/{serveStorageObject-BGH5iwBR.mjs → serveStorageObject-SPHQyLa4.mjs} +1 -1
  17. package/dist/packem_shared/{storageRules-wDDGnvpp.mjs → storageRules-nxlI5c15.mjs} +1 -1
  18. package/dist/packem_shared/{wire-codec-CU5bvJwQ.mjs → wire-codec-CZ4obM6q.mjs} +1 -1
  19. package/dist/rls/testing.mjs +1 -1
  20. package/dist/types.d.mts +2 -8
  21. package/dist/types.d.ts +2 -8
  22. package/dist/types.mjs +0 -1
  23. package/package.json +9 -5
@@ -0,0 +1,101 @@
1
+ import { SqlExec } from '@lunora/shard-engine';
2
+ import { DatabaseWriter, Schema } from "./types.mjs";
3
+ import '@lunora/values';
4
+ /** The kind of a registered Lunora function. */
5
+ type FunctionKind = "action" | "mutation" | "query";
6
+ /**
7
+ * A caller-supplied identity. `userId` is the subject a handler reads from
8
+ * `ctx.auth.userId`; every other field is returned from
9
+ * `ctx.auth.getIdentity()` (mirroring a decoded JWT's claims).
10
+ */
11
+ interface InProcessIdentity extends Record<string, unknown> {
12
+ userId?: null | string;
13
+ }
14
+ /** The `userId` + claims a dispatch runs under, after production's normalisation. */
15
+ interface ResolvedIdentity {
16
+ readonly claims: Record<string, unknown> | null;
17
+ readonly userId: null | string;
18
+ }
19
+ /**
20
+ * Reduce a caller-supplied {@link InProcessIdentity} to what production would
21
+ * actually hand a shard.
22
+ *
23
+ * Mirrors `@lunora/runtime`'s `create-worker.ts` identity forwarding: an identity
24
+ * whose `userId` is not a non-empty string is dropped to anonymous outright, and
25
+ * the forwarded claims are the identity MINUS `userId` (`null` when nothing is
26
+ * left), because the shard reads the subject from its own header and surfaces
27
+ * only the remaining claims through `ctx.auth.getIdentity()`.
28
+ * @param identity the caller-supplied identity, or `null` for anonymous
29
+ * @returns the identity production would forward
30
+ */
31
+ declare const resolveInProcessIdentity: (identity: InProcessIdentity | null) => ResolvedIdentity;
32
+ /** Options accepted by {@link createInProcessRuntime}. */
33
+ interface InProcessRuntimeOptions {
34
+ /**
35
+ * Enforce the secure-by-default RLS guard on {@link InProcessRuntime.createWriters}'s
36
+ * `database` — the same `enforceRls: true` production's generated
37
+ * `buildCtx` always passes. A no-op unless the schema is `.rls("required")`.
38
+ * @default true
39
+ */
40
+ enforceRls?: boolean;
41
+ /**
42
+ * The `ctx.scheduler` the consumer installs, when it installs one. A
43
+ * scheduler wrapped with `withDeferredSchedules` has the jobs a mutation
44
+ * schedules held until its COMMIT and dropped on its ROLLBACK, exactly as the
45
+ * generated shard's `runMutationTransaction` does.
46
+ */
47
+ scheduler?: unknown;
48
+ /** The synchronous SQLite engine the store runs on. */
49
+ sql: SqlExec;
50
+ }
51
+ /** The engine-bound half of a function dispatch, shared by every identity view. */
52
+ interface InProcessRuntime {
53
+ /**
54
+ * The guarded `ctx.db` writer for one identity, plus the trusted, UNGUARDED
55
+ * writer behind it (`rawDatabase` — what production's admin/migration paths
56
+ * use). Both carry the per-table facade (`ctx.db.<table>`).
57
+ */
58
+ createWriters: (identity: ResolvedIdentity) => {
59
+ database: DatabaseWriter;
60
+ rawDatabase: DatabaseWriter;
61
+ };
62
+ /** Start a new top-level dispatch with a full resource budget. Call before every query/action entry. */
63
+ resetHeadroom: () => void;
64
+ /**
65
+ * Run `body` as one top-level entry: serialized behind every other entry that
66
+ * came through here, inside a BEGIN/COMMIT span that rolls back on a throw,
67
+ * with a fresh resource budget. Every mutation entry must use it; a read that
68
+ * must not observe another entry's uncommitted writes may use it too.
69
+ */
70
+ runInTransaction: <R>(body: () => Promise<R> | R) => Promise<R>;
71
+ }
72
+ /**
73
+ * Migrate `schema` onto `options.sql` and return the dispatch wiring around it.
74
+ * @param schema the app schema from `defineSchema`
75
+ * @param options the engine, plus the RLS and scheduler settings
76
+ * @returns the writer factory and the mutation transaction runner
77
+ */
78
+ declare const createInProcessRuntime: (schema: Schema, options: InProcessRuntimeOptions) => InProcessRuntime;
79
+ /**
80
+ * The kind of a registered function object, or `undefined` for anything else
81
+ * (an inline callback, a plain value).
82
+ * @param value the candidate reference
83
+ * @returns its kind, when it is a registered function
84
+ */
85
+ declare const registeredFunctionKind: (value: unknown) => FunctionKind | undefined;
86
+ /**
87
+ * Invoke a registered function's handler, refusing a reference of the wrong
88
+ * kind and — unless `allowInternal` — an `internal*` function, which is
89
+ * unreachable from the external RPC boundary in production.
90
+ * @param expected which kind of function the call site dispatches
91
+ * @param reference the registered function object
92
+ * @param reference.handler its handler, invoked with `(context, args)`
93
+ * @param context the `ctx` to hand the handler
94
+ * @param args the call's arguments (`{}` when absent)
95
+ * @param allowInternal whether this is a server-to-server (`ctx.run*`) dispatch
96
+ * @returns the handler's result
97
+ */
98
+ declare const runRegisteredFunction: (expected: FunctionKind, reference: {
99
+ handler: (context: unknown, args: never) => unknown;
100
+ }, context: unknown, args: unknown, allowInternal: boolean) => Promise<unknown>;
101
+ export { type FunctionKind, type InProcessIdentity, type InProcessRuntime, type InProcessRuntimeOptions, type ResolvedIdentity, createInProcessRuntime, registeredFunctionKind, resolveInProcessIdentity, runRegisteredFunction };
@@ -0,0 +1,101 @@
1
+ import { SqlExec } from '@lunora/shard-engine';
2
+ import { DatabaseWriter, Schema } from "./types.js";
3
+ import '@lunora/values';
4
+ /** The kind of a registered Lunora function. */
5
+ type FunctionKind = "action" | "mutation" | "query";
6
+ /**
7
+ * A caller-supplied identity. `userId` is the subject a handler reads from
8
+ * `ctx.auth.userId`; every other field is returned from
9
+ * `ctx.auth.getIdentity()` (mirroring a decoded JWT's claims).
10
+ */
11
+ interface InProcessIdentity extends Record<string, unknown> {
12
+ userId?: null | string;
13
+ }
14
+ /** The `userId` + claims a dispatch runs under, after production's normalisation. */
15
+ interface ResolvedIdentity {
16
+ readonly claims: Record<string, unknown> | null;
17
+ readonly userId: null | string;
18
+ }
19
+ /**
20
+ * Reduce a caller-supplied {@link InProcessIdentity} to what production would
21
+ * actually hand a shard.
22
+ *
23
+ * Mirrors `@lunora/runtime`'s `create-worker.ts` identity forwarding: an identity
24
+ * whose `userId` is not a non-empty string is dropped to anonymous outright, and
25
+ * the forwarded claims are the identity MINUS `userId` (`null` when nothing is
26
+ * left), because the shard reads the subject from its own header and surfaces
27
+ * only the remaining claims through `ctx.auth.getIdentity()`.
28
+ * @param identity the caller-supplied identity, or `null` for anonymous
29
+ * @returns the identity production would forward
30
+ */
31
+ declare const resolveInProcessIdentity: (identity: InProcessIdentity | null) => ResolvedIdentity;
32
+ /** Options accepted by {@link createInProcessRuntime}. */
33
+ interface InProcessRuntimeOptions {
34
+ /**
35
+ * Enforce the secure-by-default RLS guard on {@link InProcessRuntime.createWriters}'s
36
+ * `database` — the same `enforceRls: true` production's generated
37
+ * `buildCtx` always passes. A no-op unless the schema is `.rls("required")`.
38
+ * @default true
39
+ */
40
+ enforceRls?: boolean;
41
+ /**
42
+ * The `ctx.scheduler` the consumer installs, when it installs one. A
43
+ * scheduler wrapped with `withDeferredSchedules` has the jobs a mutation
44
+ * schedules held until its COMMIT and dropped on its ROLLBACK, exactly as the
45
+ * generated shard's `runMutationTransaction` does.
46
+ */
47
+ scheduler?: unknown;
48
+ /** The synchronous SQLite engine the store runs on. */
49
+ sql: SqlExec;
50
+ }
51
+ /** The engine-bound half of a function dispatch, shared by every identity view. */
52
+ interface InProcessRuntime {
53
+ /**
54
+ * The guarded `ctx.db` writer for one identity, plus the trusted, UNGUARDED
55
+ * writer behind it (`rawDatabase` — what production's admin/migration paths
56
+ * use). Both carry the per-table facade (`ctx.db.<table>`).
57
+ */
58
+ createWriters: (identity: ResolvedIdentity) => {
59
+ database: DatabaseWriter;
60
+ rawDatabase: DatabaseWriter;
61
+ };
62
+ /** Start a new top-level dispatch with a full resource budget. Call before every query/action entry. */
63
+ resetHeadroom: () => void;
64
+ /**
65
+ * Run `body` as one top-level entry: serialized behind every other entry that
66
+ * came through here, inside a BEGIN/COMMIT span that rolls back on a throw,
67
+ * with a fresh resource budget. Every mutation entry must use it; a read that
68
+ * must not observe another entry's uncommitted writes may use it too.
69
+ */
70
+ runInTransaction: <R>(body: () => Promise<R> | R) => Promise<R>;
71
+ }
72
+ /**
73
+ * Migrate `schema` onto `options.sql` and return the dispatch wiring around it.
74
+ * @param schema the app schema from `defineSchema`
75
+ * @param options the engine, plus the RLS and scheduler settings
76
+ * @returns the writer factory and the mutation transaction runner
77
+ */
78
+ declare const createInProcessRuntime: (schema: Schema, options: InProcessRuntimeOptions) => InProcessRuntime;
79
+ /**
80
+ * The kind of a registered function object, or `undefined` for anything else
81
+ * (an inline callback, a plain value).
82
+ * @param value the candidate reference
83
+ * @returns its kind, when it is a registered function
84
+ */
85
+ declare const registeredFunctionKind: (value: unknown) => FunctionKind | undefined;
86
+ /**
87
+ * Invoke a registered function's handler, refusing a reference of the wrong
88
+ * kind and — unless `allowInternal` — an `internal*` function, which is
89
+ * unreachable from the external RPC boundary in production.
90
+ * @param expected which kind of function the call site dispatches
91
+ * @param reference the registered function object
92
+ * @param reference.handler its handler, invoked with `(context, args)`
93
+ * @param context the `ctx` to hand the handler
94
+ * @param args the call's arguments (`{}` when absent)
95
+ * @param allowInternal whether this is a server-to-server (`ctx.run*`) dispatch
96
+ * @returns the handler's result
97
+ */
98
+ declare const runRegisteredFunction: (expected: FunctionKind, reference: {
99
+ handler: (context: unknown, args: never) => unknown;
100
+ }, context: unknown, args: unknown, allowInternal: boolean) => Promise<unknown>;
101
+ export { type FunctionKind, type InProcessIdentity, type InProcessRuntime, type InProcessRuntimeOptions, type ResolvedIdentity, createInProcessRuntime, registeredFunctionKind, resolveInProcessIdentity, runRegisteredFunction };
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{runShardMigrations as w,TransactionHeadroomTracker as d,createShardCtxDb as R,RLS_UNWRAP_SYMBOL as T}from"@lunora/shard-engine";import{beginDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CmmdpWRS.mjs";import{bindTableFacade as y}from"./packem_shared/bindOrm-D_hFUjmr.mjs";const k=r=>{if(r===null||typeof r.userId!="string"||r.userId.length===0)return{claims:null,userId:null};const{userId:e,...s}=r;return{claims:Object.keys(s).length>0?s:null,userId:e}};class S extends d{current=new d;reset(){this.current=new d}headroom(){return this.current.headroom()}recordRead(e){this.current.recordRead(e)}recordWrite(e){this.current.recordWrite(e)}}const x=(r,e)=>{const{scheduler:s,sql:a}=e,i=r;w(a,i);const c=new S,h=t=>{const n=t;for(const o of Object.keys(i.tables))n[o]=y(t,o);return t},I=t=>{const n=R({auth:{identity:t.claims,userId:t.userId},enforceRls:e.enforceRls??!0,headroom:c,schema:i,sql:a}),o=n[T]??n;return{database:h(n),rawDatabase:h(o)}},u=t=>{a.exec.call(a,t)};let m=Promise.resolve();return{createWriters:I,resetHeadroom:()=>{c.reset()},runInTransaction:t=>{const n=async()=>{const f=g({scheduler:s});c.reset(),u("BEGIN");try{const l=await t();return u("COMMIT"),await f(!0),l}catch(l){try{u("ROLLBACK")}catch{}throw await f(!1),l}},o=m.then(n);return m=o.then(()=>{},()=>{}),o}}},p=r=>{if(typeof r!="object"||r===null)return;const{kind:e}=r;if(e==="query"||e==="mutation"||e==="action")return e},A=(r,e,s,a,i)=>{const c=p(e);if(c!==r)throw new b("INTERNAL",`expected a registered ${r}, received a ${c??"non-function"} reference`);if(!i&&e.visibility==="internal")throw new b("INTERNAL",`This ${r} is an internal function — it is unreachable from the external RPC boundary in production. Call it through ctx.run${r.charAt(0).toUpperCase()}${r.slice(1)} from another function instead.`);return Promise.resolve(e.handler(s,a??{}))};export{x as createInProcessRuntime,p as registeredFunctionKind,k as resolveInProcessIdentity,A as runRegisteredFunction};
package/dist/index.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } from '@lunora/values';
2
2
  export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
3
  import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, RelationDefinition, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook, WhisperEvent } from "./types.mjs";
4
- export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageListOptions, type StorageListResult, type StorageMetadata, type StorageMultipartUpload, type StorageMultipartUploadOptions, type StorageObjectBody, type StorageObjectHead, type StorageRange, type StorageUploadBody, type StorageUploadOptions, type StorageUploadResult, type StorageUploadedPart, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceEvent, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.mjs";
4
+ export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, RankSortKey, ReadOnlyStorage, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, SearchFilterBuilder, SearchIndexDefinition, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerCtx, TriggerDatabase, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorMatch, VectorMatches, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows } from "./types.mjs";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono } from 'hono';
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Validator, Infer, v, Id, ValidatorMap, InferValidatorMap, ColumnValidator } from '@lunora/values';
2
2
  export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
3
3
  import { ArgsValidator, InferArgs, RegisteredAction, ExposeConfig, X402ProcedureConfig, ActionCtx, MutationCtx, RegisteredMutation, QueryCtx, RegisteredQuery, DurableStreamOptions, RegisteredStream, FunctionKind, TableDefinition, RegisteredFunction, VectorIndexDefinition, Schema, AggregateOp, GlobalBackend, RelationDefinition, OnDeleteAction, SearchLanguage, SearchStrategy, ExternalSourceDefinition, TriggerBuilder, TriggerDefinition, VectorEmbedder, VectorMetric, DurableObjectJurisdiction, AggregateIndexDefinition, RankIndexDefinition, Secrets, LifecycleEvent, ShardInitEvent, RegisteredLifecycleHook, WhisperEvent } from "./types.js";
4
- export { type AnyApi, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type IndexDefinition, type IndexRangeBuilder, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationStorage, type PaginationOptions, type PaginationResult, type RankSortKey, type ReadOnlyStorage, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type SearchFilterBuilder, type SearchIndexDefinition, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageListOptions, type StorageListResult, type StorageMetadata, type StorageMultipartUpload, type StorageMultipartUploadOptions, type StorageObjectBody, type StorageObjectHead, type StorageRange, type StorageUploadBody, type StorageUploadOptions, type StorageUploadResult, type StorageUploadedPart, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerCtx, type TriggerDatabase, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorMatch, type VectorMatches, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceEvent, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } from "./types.js";
4
+ export type { AuthState, CachePurge, DatabaseReader, DatabaseWriter, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, IndexDefinition, IndexRangeBuilder, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationStorage, PaginationOptions, PaginationResult, RankSortKey, ReadOnlyStorage, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, SearchFilterBuilder, SearchIndexDefinition, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerCtx, TriggerDatabase, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorMatch, VectorMatches, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows } from "./types.js";
5
5
  import { LunoraError } from '@lunora/errors';
6
6
  export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
7
7
  import { Context, Hono } from 'hono';
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 a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-DQO-8M6x.mjs";import{initLunora as d}from"./packem_shared/initLunora-B-7Xs3Qq.mjs";import{isPerDispatchMiddleware as m,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as S,withDeferredDeletes as u}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-ZhE6eeuQ.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as R,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as L,documentHistoryExtension as C}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-CUBxWEZF.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-xizRL75J.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-BGH5iwBR.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as Y,onDisconnect as J,onShardInit as K}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as X,DEFAULT_MAX_LIMIT as q,clampLimit as z,defineListArgs as G}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineMigration as $}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as re}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as te}from"./packem_shared/defineMutator-B4ipDtDR.mjs";import{c as ne,d as ae,a as fe,b as se,e as de,f as pe,g as me,h as xe,i as ce,j as le,k as Ee,m as he}from"./packem_shared/plugin-xbEqjwqP.mjs";import{PRESENCE_DEFAULT_TTL_MS as ue,PRESENCE_TABLE as De,definePresence as Te,presenceExtension as ge}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-Bvno49rr.mjs";import{protectPublic as Re}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Le}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{createServices as Ie}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Pe}from"./packem_shared/defineShape-DfP6fQ_u.mjs";import{anyApi as ye}from"./types.mjs";import{onWhisper as Oe}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Ne}from"@lunora/errors";import{cronJobs as Ue}from"@lunora/scheduler";import{ValidationError as ve,v as Be}from"@lunora/values";import{allowAll as We,deny as je,isDeny as Ye,toWhereInput as Je}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Qe}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as qe,buildRlsReadRegistry as ze,composeShapeReadWhere as Ge}from"./packem_shared/assertShapesDeclareReadPolicies-C-Ncahac.mjs";import{buildMaskRegistry as $e}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as rr,definePermission as or,definePolicies as tr,definePolicy as ir,defineRole as nr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as fr,defineStorageRules as sr}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as pr}from"./packem_shared/mask-DTh0I6lT.mjs";import{r as xr}from"./packem_shared/middleware-3-gbLgdd.mjs";import{storageRules as lr}from"./packem_shared/storageRules-wDDGnvpp.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,X as DEFAULT_LIMIT,q as DEFAULT_MAX_LIMIT,R as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Ne as LunoraError,ue as PRESENCE_DEFAULT_TTL_MS,De as PRESENCE_TABLE,e as VERSION,ve as ValidationError,n as actionCacheExtension,We as allowAll,ye as anyApi,Qe as asBucketStorage,qe as assertShapesDeclareReadPolicies,h as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,$e as buildMaskRegistry,ze as buildRlsReadRegistry,a as cacheKeyFor,z as clampLimit,ne as composePluginMiddleware,Ge as composeShapeReadWhere,rr as createPolicyDsl,l as createSecrets,Ie as createServices,Ue as cronJobs,f as defineActionCache,ae as defineAggregateIndex,fe as defineComponent,L as defineDocumentHistory,P as defineEnv,W as defineIdentity,G as defineListArgs,$ as defineMigration,re as defineModule,te as defineMutator,or as definePermission,se as definePlugin,tr as definePolicies,ir as definePolicy,Te as definePresence,de as defineRankIndex,nr as defineRole,pe as defineSchema,me as defineSchemaExtension,Pe as defineShape,fr as defineStorageRule,sr as defineStorageRules,xe as defineTable,ce as defineVectorIndex,je as deny,C as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,le as indexFieldsFromSchema,d as initLunora,Ee as installPlugins,Ye as isDeny,m as isPerDispatchMiddleware,k as isSafeHeaderValue,pr as mask,he as mergeSchemaExtension,Y as onConnect,J as onDisconnect,Le as onQueryChange,K as onShardInit,Oe as onWhisper,ge as presenceExtension,Re as protectPublic,b as redactSecrets,xr as rls,B as serveStorageObject,lr as storageRules,x as tagPerDispatchMiddleware,Je as toWhereInput,Be as v,u 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-DITNUhX1.mjs";import{initLunora as d}from"./packem_shared/initLunora-B-7Xs3Qq.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as c}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as h,flushDeferredDeletes as S,withDeferredDeletes as u}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as g}from"./packem_shared/beginDeferredSchedules-CmmdpWRS.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as A,DOCUMENT_HISTORY_TABLE as _,defineDocumentHistory as L,documentHistoryExtension as C}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BYeHnULU.mjs";import{LunoraEnvError as M,defineEnv as P,redactSecrets as b}from"./packem_shared/LunoraEnvError-bkdMu_-N.mjs";import{bindOrm as F,bindTableFacade as O}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as N,httpRoute as w,httpRouter as U,isSafeHeaderValue as k}from"./packem_shared/httpAction-CsKNC6op.mjs";import{serveStorageObject as B}from"./packem_shared/serveStorageObject-SPHQyLa4.mjs";import{defineIdentity as W}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as Y,onDisconnect as J,onShardInit as K}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as X,DEFAULT_MAX_LIMIT as q,clampLimit as z,defineListArgs as G}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineMigration as $}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as re}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as te}from"./packem_shared/defineMutator-B4ipDtDR.mjs";import{c as ne,d as ae,a as fe,b as se,e as de,f as me,g as pe,h as ce,i as xe,j as le,k as Ee,m as he}from"./packem_shared/plugin-xbEqjwqP.mjs";import{PRESENCE_DEFAULT_TTL_MS as ue,PRESENCE_TABLE as De,definePresence as Te,presenceExtension as ge}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-Bvno49rr.mjs";import{protectPublic as Ae}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as Le}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{createServices as Ie}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as Pe}from"./packem_shared/defineShape-B8U-uTeQ.mjs";import{onWhisper as ye}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Oe}from"@lunora/errors";import{cronJobs as Ne}from"@lunora/scheduler";import{ValidationError as Ue,v as ke}from"@lunora/values";import{allowAll as Be,deny as Ve,isDeny as We,toWhereInput as je}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as Je}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as Qe,buildRlsReadRegistry as Xe,composeShapeReadWhere as qe}from"./packem_shared/assertShapesDeclareReadPolicies-mKiSAI2N.mjs";import{buildMaskRegistry as Ge}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as $e,definePermission as er,definePolicies as rr,definePolicy as or,defineRole as tr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as nr,defineStorageRules as ar}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as sr}from"./packem_shared/mask-BwK_5ndJ.mjs";import{r as mr}from"./packem_shared/middleware-C1CfQMYn.mjs";import{storageRules as cr}from"./packem_shared/storageRules-nxlI5c15.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,X as DEFAULT_LIMIT,q as DEFAULT_MAX_LIMIT,A as DOCUMENT_HISTORY_REDACTED_FIELDS,_ as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Oe as LunoraError,ue as PRESENCE_DEFAULT_TTL_MS,De as PRESENCE_TABLE,e as VERSION,Ue as ValidationError,n as actionCacheExtension,Be as allowAll,Je as asBucketStorage,Qe as assertShapesDeclareReadPolicies,h as beginDeferredDeletes,T as beginDeferredSchedules,F as bindOrm,O as bindTableFacade,Ge as buildMaskRegistry,Xe as buildRlsReadRegistry,a as cacheKeyFor,z as clampLimit,ne as composePluginMiddleware,qe as composeShapeReadWhere,$e as createPolicyDsl,l as createSecrets,Ie as createServices,Ne as cronJobs,f as defineActionCache,ae as defineAggregateIndex,fe as defineComponent,L as defineDocumentHistory,P as defineEnv,W as defineIdentity,G as defineListArgs,$ as defineMigration,re as defineModule,te as defineMutator,er as definePermission,se as definePlugin,rr as definePolicies,or as definePolicy,Te as definePresence,de as defineRankIndex,tr as defineRole,me as defineSchema,pe as defineSchemaExtension,Pe as defineShape,nr as defineStorageRule,ar as defineStorageRules,ce as defineTable,xe as defineVectorIndex,Ve as deny,C as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,w as httpRoute,U as httpRouter,le as indexFieldsFromSchema,d as initLunora,Ee as installPlugins,We as isDeny,p as isPerDispatchMiddleware,k as isSafeHeaderValue,sr as mask,he as mergeSchemaExtension,Y as onConnect,J as onDisconnect,Le as onQueryChange,K as onShardInit,ye as onWhisper,ge as presenceExtension,Ae as protectPublic,b as redactSecrets,mr as rls,B as serveStorageObject,cr as storageRules,c as tagPerDispatchMiddleware,je as toWhereInput,ke as v,u as withDeferredDeletes,g as withDeferredSchedules};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{a as f,d as U}from"./wire-codec-CU5bvJwQ.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-B-7Xs3Qq.mjs";import{g as k,h as q,a as B}from"./plugin-xbEqjwqP.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
1
+ import{isLunoraError as S}from"@lunora/errors";import{v as d}from"@lunora/values";import{e as f,d as U}from"./wire-codec-CZ4obM6q.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-B-7Xs3Qq.mjs";import{g as k,h as q,a as B}from"./plugin-xbEqjwqP.mjs";const P=i=>D(f(i)),R=3600*1e3,H=512*1024,V=8,b=64,K=64,W=256,$=4096,u="actionCache",h="entries",c=`${u}_${h}`,T=i=>i===void 0?"":P(i),x=async(i,m)=>{const A=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${i}\0${m}`));return[...new Uint8Array(A)].map(y=>y.toString(16).padStart(2,"0")).join("")},G=k(u,{tables:{[h]:q({expiresAt:d.number(),key:d.string(),name:d.string(),value:d.string()}).index("byKey",["key"],{unique:!0}).index("byName",["name"]).index("byExpiresAt",["expiresAt"])}}),{internalMutation:J}=F.dataModel().create(),te=(i={})=>{const m=i.ttlMs!==void 0&&Number.isFinite(i.ttlMs)?Math.max(1,Math.floor(i.ttlMs)):R,A=i.maxValueBytes!==void 0&&Number.isFinite(i.maxValueBytes)?Math.max(1,Math.floor(i.maxValueBytes)):H,y=async(e,t)=>{const n=(await e.db.query(c).withIndex("byExpiresAt").order("asc").take(V)).filter(r=>r.expiresAt<=t);await Promise.all(n.map(async r=>e.db.delete(r._id)))},C=async(e,t)=>e.db.query(c).withIndex("byKey",a=>a.eq("key",t)).first(),N=new Set(["CONFLICT","NOT_FOUND","NOT_UNIQUE"]),I=async(e,t,a)=>{try{await(t?e.db.patch(t._id,{expiresAt:a.expiresAt,value:a.value}):e.db.insert(c,a))}catch(n){if(S(n)&&N.has(n.code))return;throw n}},M=async(e,t,a,n)=>{const r=T(a),s=await x(t,r),l=Date.now(),o=await C(e,s);if(o&&o.expiresAt>l)return U(JSON.parse(o.value)).v;const p=await n(),w=JSON.stringify(f({v:p})),E=Date.now(),O=E+m;return new TextEncoder().encode(w).length<=A?await I(e,o,{expiresAt:O,key:s,name:t,value:w}):o&&await e.db.delete(o._id),await y(e,E),p},L=async(e,t,a)=>{const n=await x(t,T(a)),r=await e.db.query(c).withIndex("byKey",s=>s.eq("key",n)).take(b);await Promise.all(r.map(async s=>e.db.delete(s._id)))},_=async(e,t,a,n)=>{if(n>=K)return{complete:!1,deleted:a};const r=await e.db.query(c).withIndex("byName",s=>s.eq("name",t)).take(b);return r.length===0?{complete:!0,deleted:a}:(await Promise.all(r.map(async s=>e.db.delete(s._id))),_(e,t,a+r.length,n+1))},g=async(e,t)=>_(e,t,0,0),v=J.input({limit:d.optional(d.number())}).mutation(async({args:e,ctx:t})=>{const a=Date.now(),n=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min($,Math.max(1,Math.floor(e.limit))):W,s=(await t.db.query(c).withIndex("byExpiresAt").order("asc").take(n)).filter(l=>l.expiresAt<=a);return await Promise.all(s.map(async l=>t.db.delete(l._id))),{deleted:s.length}});return{...B(u,{extension:G,functions:{purgeExpired:v}}),invalidate:L,invalidateAll:g,wrap:M}};export{R as ACTION_CACHE_DEFAULT_TTL_MS,c as ACTION_CACHE_TABLE,G as actionCacheExtension,x as cacheKeyFor,te as defineActionCache};
@@ -1 +1 @@
1
- import{v as r}from"@lunora/values";import{d as E,a as h}from"./wire-codec-CU5bvJwQ.mjs";import{initLunora as x}from"./initLunora-B-7Xs3Qq.mjs";import{g as v,h as R,a as U}from"./plugin-xbEqjwqP.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
1
+ import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-CZ4obM6q.mjs";import{initLunora as x}from"./initLunora-B-7Xs3Qq.mjs";import{g as v,h as R,a as U}from"./plugin-xbEqjwqP.mjs";const H=2160*60*60*1e3,L=64*1024,I=200,q=1e3,C=64,F=512,u=16,B=["_commitSeq","seq"],w=["accessToken","apiKey","backupCodes","clientSecret","hashedPassword","password","privateKey","refreshToken","secret","totpSecret"],f="documentHistory",y="versions",p=`${f}_${y}`,P=v(f,{tables:{[y]:R({doc:r.optional(r.string()),documentId:r.string(),op:r.union(r.literal("delete"),r.literal("insert"),r.literal("update")),previous:r.optional(r.string()),recordedAt:r.number(),seq:r.number(),tableName:r.string(),truncated:r.optional(r.boolean())}).commitOrdered().index("byDocumentRecordedAt",["documentId","recordedAt","seq"]).index("byRecordedAt",["recordedAt"])}}),{internalMutation:Y,internalQuery:g}=x.dataModel().create(),V=(d={})=>{const T=d.retentionMs!==void 0&&Number.isFinite(d.retentionMs)?Math.max(1,Math.floor(d.retentionMs)):H,_=d.maxSnapshotBytes!==void 0&&Number.isFinite(d.maxSnapshotBytes)?Math.max(1,Math.floor(d.maxSnapshotBytes)):L,b=new Set([...w,...d.redact??[]]);let A=0;const S=()=>(A+=1,A),a=(e,o=0)=>{if(Array.isArray(e))return o>=u?void 0:e.map(t=>a(t,o+1));if(typeof e!="object"||e===null)return e;if(e instanceof Map)return o>=u?void 0:new Map([...e.entries()].filter(([t])=>typeof t!="string"||!b.has(t)).map(([t,i])=>[t,a(i,o+1)]));if(e instanceof Set)return o>=u?void 0:new Set([...e].map(t=>a(t,o+1)));if(Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)return e;if(!(o>=u))return Object.fromEntries(Object.entries(e).filter(([t])=>!b.has(t)).map(([t,i])=>[t,a(i,o+1)]))},M=e=>{if(e===void 0)return;const o=JSON.stringify(h(a(e)));return new TextEncoder().encode(o).length>_?void 0:o},l=async(e,o)=>{const t=M(o.doc),i=M(o.previous),n=o.doc!==void 0&&t===void 0||o.previous!==void 0&&i===void 0;await e.db.insert(p,{documentId:o.documentId,op:o.op,recordedAt:Date.now(),seq:S(),tableName:o.tableName,...n?{truncated:!0}:{},...t===void 0?{}:{doc:t},...i===void 0?{}:{previous:i}})},D=e=>({documentHistoryDelete:e.afterDelete(async(o,t)=>l(o,{documentId:t.id,op:"delete",previous:t.previous,tableName:t.table})),documentHistoryInsert:e.afterInsert(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"insert",tableName:t.table})),documentHistoryUpdate:e.afterUpdate(async(o,t)=>l(o,{doc:t.doc,documentId:t.id,op:"update",previous:t.previous,tableName:t.table}))}),N=g.input({before:r.optional(r.number()),documentId:r.string(),limit:r.optional(r.number())}).query(async({args:e,ctx:o})=>{const t=e.limit!==void 0&&Number.isFinite(e.limit)?Math.min(q,Math.max(1,Math.floor(e.limit))):I,i=await o.db.query(p).withIndex("byDocumentRecordedAt",n=>e.before===void 0?n.eq("documentId",e.documentId):n.eq("documentId",e.documentId).lte("recordedAt",e.before)).order("desc").take(t);return i.sort((n,m)=>{for(const c of B){const s=(m[c]??0)-(n[c]??0);if(s!==0)return s}return 0}),i.map(n=>({documentId:n.documentId,op:n.op,recordedAt:n.recordedAt,tableName:n.tableName,...n.doc===void 0?{}:{doc:E(JSON.parse(n.doc))},...n.previous===void 0?{}:{previous:E(JSON.parse(n.previous))},...n.truncated===!0?{truncated:!0}:{}}))}),O=Y.input({limit:r.optional(r.number())}).mutation(async({args:e,ctx:o})=>{const t=Date.now()-T,i=e.limit!==void 0&&Number.isFinite(e.limit)?Math.max(1,Math.floor(e.limit)):F;let n=0;for(let m=0;m<C&&n<i;m+=1){const c=await o.db.query(p).withIndex("byRecordedAt",s=>s.lt("recordedAt",t)).order("asc").take(Math.min(I,i-n));if(c.length===0)return{deleted:n};await Promise.all(c.map(async s=>o.db.delete(s._id))),n+=c.length}return{deleted:n}});return{...U(f,{extension:P,functions:{listForDocument:N,vacuum:O}}),record:D}};export{w as DOCUMENT_HISTORY_REDACTED_FIELDS,p as DOCUMENT_HISTORY_TABLE,V as defineDocumentHistory,P as documentHistoryExtension};
@@ -1 +1 @@
1
- import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-3-gbLgdd.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
1
+ import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,e as b,f as y}from"./middleware-C1CfQMYn.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
@@ -1 +1 @@
1
- import{assertScheduleInstant as b,assertScheduleDelay as w,resolveScheduleId as m}from"@lunora/scheduler";import{e as x}from"./wire-codec-CU5bvJwQ.mjs";const g=new WeakMap,y=u=>{if(typeof u=="string")return u;const r=u??{},n=r.__lunoraRef??r.binding;return typeof n=="string"?n:"<unknown>"},p=u=>{let r=u;for(;r!==void 0&&!r.open;)r=r.parent;return r},S=(u,r)=>{const n=u,s={innermost:void 0,outbox:r},l=(e,t,c,o,d)=>n[e].call(n,t,c,o,d),i=(e,t,c,o,d)=>{const a=s.innermost;if(a===void 0)return l(e,t,c,o,d);const h=m(d?.id);return s.outbox?.record(h,{args:x(`ctx.scheduler.${e}`,y(c),o),options:d,target:c,when:Math.ceil(e==="runAfter"?Date.now()+t:t)}),a.pending.push({id:h,run:async()=>l(e,t,c,o,{...d,id:h})}),Promise.resolve(h)},f={...n,runAfter:(e,t,c,o)=>(w(e,"ctx.scheduler.runAfter"),i("runAfter",e,t,c,o)),runAt:(e,t,c,o)=>(b(e,Date.now(),"ctx.scheduler.runAt"),i("runAt",e,t,c,o))};return Object.setPrototypeOf(f,Object.getPrototypeOf(n)),g.set(f,s),f},D=u=>{const{scheduler:r}=u,n=typeof r=="object"&&r!==null?g.get(r):void 0;if(!n)return async()=>{};const s={open:!0,parent:n.innermost,pending:[]};return n.innermost=s,async l=>{if(!s.open)return;s.open=!1,n.innermost===s&&(n.innermost=p(s.parent));const i=s.pending.splice(0);if(i.length===0)return;if(!l){for(const{id:o}of i)n.outbox?.forget(o);return}const f=p(s.parent);if(f!==void 0){f.pending.push(...i);return}const e=[];for(const{id:o,run:d}of i)try{await d(),n.outbox?.forget(o)}catch(a){e.push(a)}const[t,...c]=e;if(t!==void 0)throw n.outbox?.wake(),c.length===0?t:new AggregateError(e,`ctx.scheduler: ${String(e.length)} of ${String(i.length)} deferred jobs failed to reach the scheduler after the commit`)}};export{D as beginDeferredSchedules,S as withDeferredSchedules};
1
+ import{assertScheduleInstant as b,assertScheduleDelay as w,resolveScheduleId as m}from"@lunora/scheduler";import{a as x}from"./wire-codec-CZ4obM6q.mjs";const g=new WeakMap,y=u=>{if(typeof u=="string")return u;const r=u??{},n=r.__lunoraRef??r.binding;return typeof n=="string"?n:"<unknown>"},p=u=>{let r=u;for(;r!==void 0&&!r.open;)r=r.parent;return r},S=(u,r)=>{const n=u,s={innermost:void 0,outbox:r},l=(e,t,c,o,d)=>n[e].call(n,t,c,o,d),i=(e,t,c,o,d)=>{const a=s.innermost;if(a===void 0)return l(e,t,c,o,d);const h=m(d?.id);return s.outbox?.record(h,{args:x(`ctx.scheduler.${e}`,y(c),o),options:d,target:c,when:Math.ceil(e==="runAfter"?Date.now()+t:t)}),a.pending.push({id:h,run:async()=>l(e,t,c,o,{...d,id:h})}),Promise.resolve(h)},f={...n,runAfter:(e,t,c,o)=>(w(e,"ctx.scheduler.runAfter"),i("runAfter",e,t,c,o)),runAt:(e,t,c,o)=>(b(e,Date.now(),"ctx.scheduler.runAt"),i("runAt",e,t,c,o))};return Object.setPrototypeOf(f,Object.getPrototypeOf(n)),g.set(f,s),f},D=u=>{const{scheduler:r}=u,n=typeof r=="object"&&r!==null?g.get(r):void 0;if(!n)return async()=>{};const s={open:!0,parent:n.innermost,pending:[]};return n.innermost=s,async l=>{if(!s.open)return;s.open=!1,n.innermost===s&&(n.innermost=p(s.parent));const i=s.pending.splice(0);if(i.length===0)return;if(!l){for(const{id:o}of i)n.outbox?.forget(o);return}const f=p(s.parent);if(f!==void 0){f.pending.push(...i);return}const e=[];for(const{id:o,run:d}of i)try{await d(),n.outbox?.forget(o)}catch(a){e.push(a)}const[t,...c]=e;if(t!==void 0)throw n.outbox?.wake(),c.length===0?t:new AggregateError(e,`ctx.scheduler: ${String(e.length)} of ${String(i.length)} deferred jobs failed to reach the scheduler after the commit`)}};export{D as beginDeferredSchedules,S as withDeferredSchedules};
@@ -1 +1 @@
1
- import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-C-Ncahac.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:(a,l,n)=>{const w=u(e.args??{},l),o=e.where?m(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?n?.ownerField:e.owner;if(t===void 0||t==="")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 s=p(a);if(s===void 0)return d();const h={[t]:s};return o===void 0?h:{AND:[h,o]}},rlsRegistry:c(e.use??[])}};export{I as defineShape};
1
+ import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-mKiSAI2N.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:(a,l,n)=>{const w=u(e.args??{},l),o=e.where?m(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?n?.ownerField:e.owner;if(t===void 0||t==="")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 s=p(a);if(s===void 0)return d();const h={[t]:s};return o===void 0?h:{AND:[h,o]}},rlsRegistry:c(e.use??[])}};export{I as defineShape};
@@ -1,4 +1,4 @@
1
- import{LunoraError as E,toErrorBody as O,isLunoraError as N}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as _}from"@lunora/values";import{Hono as q}from"hono";import{a as x}from"./wire-codec-CU5bvJwQ.mjs";import{a as k}from"./apply-output-C5wZ5EAL.mjs";const U=e=>async r=>e(r.get("lunora"),r.req.raw),J=()=>{const e=new q;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},v=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},C=(e,r,o)=>{const n=v(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const d=n._meta?.inner;return a.map(i=>g(d?.kind??"string",i))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},S=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=C(t,r,n))}return R(e,o,"searchParams")},T=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const d=o[t];n[t]=d===void 0?void 0:g(v(a).kind,d)}return R(e,n,"params")},H=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return R(e,o,"body")},j=e=>{if(e instanceof _)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(N(e)){const{body:r,redacted:o,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},A=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},L=(e,r)=>async o=>{const n=A(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},d=Object.keys(e.params).length>0?T(e.params,o):{},i=Object.keys(e.body).length>0?await H(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?k(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const f=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:f?c:void 0,status:204}):Response.json(s,{headers:f?c:void 0})}catch(t){return j(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,r)=>{const o=JSON.stringify(r===void 0?x(e):e);return`${r?`event: ${r}
1
+ import{LunoraError as E,toErrorBody as O,isLunoraError as N}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as _}from"@lunora/values";import{Hono as q}from"hono";import{e as x}from"./wire-codec-CZ4obM6q.mjs";import{a as k}from"./apply-output-C5wZ5EAL.mjs";const U=e=>async r=>e(r.get("lunora"),r.req.raw),J=()=>{const e=new q;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new E("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},v=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},C=(e,r,o)=>{const n=v(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const d=n._meta?.inner;return a.map(i=>g(d?.kind??"string",i))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},S=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=C(t,r,n))}return R(e,o,"searchParams")},T=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const d=o[t];n[t]=d===void 0?void 0:g(v(a).kind,d)}return R(e,n,"params")},H=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new E("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new E("BAD_REQUEST","Expected a JSON object body");return R(e,o,"body")},j=e=>{if(e instanceof _)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(N(e)){const{body:r,redacted:o,status:n}=O(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},A=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},L=(e,r)=>async o=>{const n=A(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},d=Object.keys(e.params).length>0?T(e.params,o):{},i=Object.keys(e.body).length>0?await H(e.body,o):{},h=await r({body:i,ctx:t,params:d,searchParams:a}),s=e.output?k(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const f=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:f?c:void 0,status:204}):Response.json(s,{headers:f?c:void 0})}catch(t){return j(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,r)=>{const o=JSON.stringify(r===void 0?x(e):e);return`${r?`event: ${r}
2
2
  `:""}data: ${o}
3
3
 
4
4
  `},D=(e,r)=>(async o=>{const n=A(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?S(e.searchParams,o):{},a=Object.keys(e.params).length>0?T(e.params,o):{}}catch(m){return j(m)}const d=o.get("lunora"),i=o.req.raw,h=new TextEncoder,s=new AbortController;if(i.signal.aborted)return s.abort(),new Response("",{headers:w});const c=()=>{s.abort()};i.signal.addEventListener("abort",c,{once:!0});const f=new ReadableStream({cancel(){i.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const y=r({ctx:d,params:a,request:i,searchParams:t,signal:s.signal});for await(const p of y){if(s.signal.aborted)break;m.enqueue(h.encode(b(e.output?k(e.output,p):p)))}s.signal.aborted||m.enqueue(h.encode(b({},"complete")))}catch(y){const{body:p,redacted:P}=O(y,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});P&&console.error("[lunora] unhandled stream handler error:",y),s.signal.aborted||m.enqueue(h.encode(b({code:p.code,message:p.message},"error")))}finally{i.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(f,{headers:w})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>L(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>D(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),Q={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},W=e=>!(e.includes("\r")||e.includes(`
@@ -1 +1 @@
1
- import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-3-gbLgdd.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-D_hFUjmr.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},d=(e,i,a)=>{const u={...e};for(const[y,g]of Object.entries(i))y in u&&(u[y]=V(g,e[y],{...a,column:y,row:e}));return u},j=(e,i,a)=>({...e,page:e.page.map(u=>d(u,i,a))}),D=(e,i,a,u)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${u}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,u)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>d(o,t,a)):n},k=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},p=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=u?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},l=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield d(o,n,a)},collect:async()=>(await r.collect()).map(s=>d(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=d(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>l(r.filter(s=>o(d(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?d(o,n,a):null},order:o=>l(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>d(c,n,a)),unique:async()=>{const o=await r.unique();return o?d(o,n,a):null},withIndex:(o,s)=>(p(t,o,"withIndex","index"),D(s,n,t,"withIndex"),l(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),l(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(p(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);if(f)return{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,k(n)),o=i.get(r);return t&&o?d(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,k(n)),o=i.get(r);return o?d(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,k(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:d(t,s,a)},related:e.related?async(r,n)=>await e.related(r,k(n)):void 0,async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?d(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?l(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),p(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),p(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),p(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),p(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:d(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),u=L(i.roles),y=async({ctx:w,next:k})=>{const p={auth:await z(w.auth??{},u),ctx:w};if(i.bypass?.(p)===!0)return k();const l=X(w.db,a,p,i.indexFields),O={db:l},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(l)),k({ctx:O})},g=new Map;for(const[w,k]of a)g.set(w,new Set(Object.keys(k)));return Q(y,{columns:g})};export{b as mask};
1
+ import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-C1CfQMYn.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-D_hFUjmr.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,a)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,a)}catch{return null}},d=(e,i,a)=>{const u={...e};for(const[y,g]of Object.entries(i))y in u&&(u[y]=V(g,e[y],{...a,column:y,row:e}));return u},j=(e,i,a)=>({...e,page:e.page.map(u=>d(u,i,a))}),D=(e,i,a,u)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${u}() filtering "${a}" by masked column "${w}" is not supported`)},X=(e,i,a,u)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>d(o,t,a)):n},k=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},p=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=u?.[r]?.[o]?.[n];if(!c)return;const f=c.find(E=>E in s);if(f!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${f}" — use an index whose declared fields are all unmasked, or unmask the column`)},l=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield d(o,n,a)},collect:async()=>(await r.collect()).map(s=>d(s,n,a)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=d(s.document,n,a);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>l(r.filter(s=>o(d(s,n,a))),n,t),first:async()=>{const o=await r.first();return o?d(o,n,a):null},order:o=>l(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,a),take:async o=>(await r.take(o)).map(c=>d(c,n,a)),unique:async()=>{const o=await r.unique();return o?d(o,n,a):null},withIndex:(o,s)=>(p(t,o,"withIndex","index"),D(s,n,t,"withIndex"),l(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),l(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(p(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const f=await e.lookupById(r,n);if(f)return{row:f.row,tableName:i.has(f.tableName)?f.tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async f=>(await e.findFirst(f,{limit:1,where:{_id:r}}))?._id===r?f:void 0));return{row:t,tableName:c.find(f=>f!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,f=`${r}.${o}`;R(c.where,A,f,t),F(f,c.orderBy,A,t),$(f,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,k(n)),o=i.get(r);return t&&o?d(t,o,a):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,k(n)),o=i.get(r);return o?d(t,o,a):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,k(n)),o=i.get(r);return o?j(t,o,a):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:d(t,s,a)},related:e.related?async(r,n)=>await e.related(r,k(n)):void 0,async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?d(t.row,o,a):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?l(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),p(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),p(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,a):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),p(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),p(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(f=>({...f,doc:d(f.doc,c,a)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const a=new Map(Object.entries(e)),u=L(i.roles),y=async({ctx:w,next:k})=>{const p={auth:await z(w.auth??{},u),ctx:w};if(i.bypass?.(p)===!0)return k();const l=X(w.db,a,p,i.indexFields),O={db:l},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(l)),k({ctx:O})},g=new Map;for(const[w,k]of a)g.set(w,new Set(Object.keys(k)));return Q(y,{columns:g})};export{b as mask};
@@ -1 +1 @@
1
- import{LunoraError as W}from"@lunora/errors";import{findRelated as V,whereFilter as ee}from"@lunora/shard-engine";import{i as j}from"./wire-codec-CU5bvJwQ.mjs";import{bindTableFacade as te,bindOrm as re}from"./bindOrm-D_hFUjmr.mjs";import{t as ne}from"./policy-tag-V0lqFzgS.mjs";import{deny as se}from"./allowAll-DkRAgItV.mjs";const oe=["every","is","isNot","none","some"],ie=new Set(oe),ae=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ie.has(n))},q=(e,r,n)=>r?{[e]:n(r)}:{},ce=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,b=1,T=e=>e?b:B,p=(e,r)=>e<r?e:r,le=(e,r)=>e>r?e:r,z=e=>e===v?v:T(e===B),Y=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,M=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},fe={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},de=(e,r,n)=>{let i=b;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(M(e,c,h),!Y(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=fe[c];i=p(i,T(Y(r)&&f(r,h)))}}return i},K=(e,r,n)=>{if(!Array.isArray(n))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},Q=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?b:r.some(n=>S(n))?v:B,ue=(e,r,n)=>{let i=b;if("in"in n&&(i=p(i,Q(r,K(e,"in",n.in)))),"notIn"in n&&(i=p(i,z(Q(r,K(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;M(e,"contains",c),i=S(r)?p(i,v):p(i,T(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,T(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?T(n===S(e)):S(e)?v:T(n===(e===r)),he=(e,r,n)=>{let i=b;return"eq"in n&&(M(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(M(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},ye=(e,r,n)=>p(he(e,r,n),p(ue(e,r,n),de(e,r,n))),we=(e,r,n,i)=>{if(r==="NOT")return z(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?b:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):le(c,f)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",pe=e=>j(e)&&Object.keys(e).every(r=>ce.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return H(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):ae(n)}),G=(e,r)=>{let n=b;for(const i of Object.keys(r)){const c=r[i];if(H(i)){n=p(n,we(e,i,c,G));continue}const h=e[i];if(pe(c)){n=p(n,ye(i,h,c));continue}M(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>G(e,r)===b,X=500,I=(e,r,n)=>{const i=r??X;if(e>i)throw new W("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},ge=se(),We=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),Oe=e=>e[J],Re=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},be=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const h=c.when(r);if(h!==void 0){if(h===!0){i=!0;break}h!==!1&&n.push(h)}}if(!i)return n.length===0?ge:n.length===1?n[0]:{OR:n}},Ae=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return L(n,i)},Ee=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||Ae(e,r,n);if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!L(r.row,i)?!1:n===void 0||L(n,i)},Be=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!Ee(h,n,i)))return!1;return c},ve=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Se=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),_e=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>ve.has(n)&&Se(n,e[n]))},ke=e=>e===void 0?{}:j(e)&&_e(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Ie=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},R=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,Te=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Me=(e,r,n)=>{const[i]=n,c=n.length===1&&i!==void 0?i.perTable:new Set(n.flatMap(t=>[...t.perTable.keys()])),h=new Map,f=t=>{const s=h.get(t);if(s)return s;const o=[];let a=!1;for(const y of n){const u=y.perTable.get(t);if(!u||u.length===0||!u.some(m=>m.on==="read"))continue;a=!0;const d=be(u,y.context);d!==void 0&&o.push(d)}const l={baseWhere:Ie(o),restricts:a};return h.set(t,l),l},_=(t,s,o,a)=>{for(const l of n){const y=l.perTable.get(t);if(y&&!Be(y,s,{...l.context,row:o},a))return!1}return!0},w=t=>f(t).restricts?r:e,g=t=>f(t).baseWhere,A=async(t,s,o)=>{if(r.lookupById){const d=await r.lookupById(t,s);if(d)return{row:d.row,tableName:c.has(d.tableName)?d.tableName:void 0}}const a=await r.get(t,s);if(!a)return{row:null,tableName:void 0};const l=s??o,y=l===void 0?[...c.keys()]:[l].filter(d=>c.has(d)),u=await Promise.all(y.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:a,tableName:u.find(d=>d!==void 0)}},U=async(t,s,o)=>{const a=await A(t,s,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},O=async(t,s,o,a,l,y)=>{const u=await U(t,l,y);if(!u)return o(e);const d=a?a(u.row):void 0;if(!_(u.tableName,s,u.row,d))throw new W("FORBIDDEN",`${s} denied by policy`);return o(r)},E=(t,s)=>{const{baseWhere:o}=f(t);if($(o))throw new W("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`)},D=e.rankBefore,P=e.rankPageRows,{relationEdges:N}=e,k={...e,async count(t,s){const{baseWhere:o}=f(t),a=ke(s);return w(t).count(t,{...a,baseWhere:R(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,s,o)=>O(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??X),{baseWhere:a}=f(t);let l=0;for(;;){const u=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(d=>String(d._id));if(u.length===0)break;for(const d of u)await O(d,"delete",m=>m.delete(d,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(u.length<o)break}return{deleted:l}},async deleteMany(t,s,o){I(t.length,s?.limit,"deleteMany");for(const a of t)await O(a,"delete",l=>l.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s,a),relationBaseWhere:g})).page.map(u=>String(u._id));I(y.length,o?.limit,"deleteWhere");for(const u of y)await O(u,"delete",d=>d.delete(u),void 0,void 0,t);return{deleted:y.length}},async findFirst(t,s){const{baseWhere:o}=f(t);return w(t).findFirst(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:l}=f(o.tableName);if(!l)return e.get(t,s);if(!a)return o.row;const y=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return y?._id===t?y:null},async lookupById(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0||!f(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=f(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const l=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?{row:l,tableName:o.tableName}:null},async insert(t,s){if(c.has(t)){if(!_(t,"insert",s))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){if(I(s.length,o?.limit,"insertMany"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){if(I(s.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>O(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){I(t.length,s?.limit,"patchMany");for(const a of t)await O(a.id,"update",l=>l.patch(a.id,a.patch,o),l=>({...l,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s.where,a),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:s.patch}));return I(y.length,o?.limit,"patchWhere"),k.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(ee(s,a=>L(a,s))):o},related:N===void 0?void 0:async(t,s)=>V({findMany:async(o,a)=>k.findMany(o,a),lookupById:async o=>r.lookupById?.(o)},N,t,{cursor:s?.cursor,depth:s?.depth,direction:s?.direction,edges:s?.edges,limit:s?.limit,relationMask:s?.relationMask}),restore:(t,s)=>O(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new W("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>O(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=f(t);return w(t).aggregate(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){return E(t,"rank"),w(t).rank(t,s,o)},rankPage(t,s,o){return E(t,"rankPage"),w(t).rankPage(t,s,o)},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...q("rankBefore",D,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...q("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},x=k;if(c.size>0)for(const[t,s]of Object.entries(e))Te(s)&&(x[t]=te(k,t));return Object.defineProperty(k,J,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),k},Z=e=>typeof e=="string"?e:e.name,De=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>Z(i))));return r},Pe=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(Z(i))},me=["roles","role"],Ce=e=>{for(const r of me){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Le=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...Ce(n),...e.roles??[]])];return{can:Pe(i,r),identity:n,roles:i,userId:e.userId??null}},Ye=(e,r={})=>{const n=e,i=Re(n),c=De(r.roles);return ne(async({ctx:f,next:_})=>{const w={auth:await Le(f.auth??{},c),ctx:f},g=f.db,A=Oe(g),U=A?.base??g,O=A?.raw??g[We]??g,E=Me(U,O,[...A?.steps??[],{context:w,perTable:i}]),D={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(D.orm=re(E)),_({ctx:D})},[{policies:n,roles:r.roles??[]}])};export{Le as a,Te as b,ae as c,Ce as d,Pe as e,be as f,Be as g,De as i,L as m,q as o,Ye as r};
1
+ import{LunoraError as W}from"@lunora/errors";import{findRelated as V,whereFilter as ee}from"@lunora/shard-engine";import{i as j}from"./wire-codec-CZ4obM6q.mjs";import{bindTableFacade as te,bindOrm as re}from"./bindOrm-D_hFUjmr.mjs";import{t as ne}from"./policy-tag-V0lqFzgS.mjs";import{deny as se}from"./allowAll-DkRAgItV.mjs";const oe=["every","is","isNot","none","some"],ie=new Set(oe),ae=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ie.has(n))},q=(e,r,n)=>r?{[e]:n(r)}:{},ce=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,b=1,T=e=>e?b:B,p=(e,r)=>e<r?e:r,le=(e,r)=>e>r?e:r,z=e=>e===v?v:T(e===B),Y=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,M=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},fe={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},de=(e,r,n)=>{let i=b;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(M(e,c,h),!Y(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=fe[c];i=p(i,T(Y(r)&&f(r,h)))}}return i},K=(e,r,n)=>{if(!Array.isArray(n))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},Q=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?b:r.some(n=>S(n))?v:B,ue=(e,r,n)=>{let i=b;if("in"in n&&(i=p(i,Q(r,K(e,"in",n.in)))),"notIn"in n&&(i=p(i,z(Q(r,K(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;M(e,"contains",c),i=S(r)?p(i,v):p(i,T(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,T(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?T(n===S(e)):S(e)?v:T(n===(e===r)),he=(e,r,n)=>{let i=b;return"eq"in n&&(M(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(M(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},ye=(e,r,n)=>p(he(e,r,n),p(ue(e,r,n),de(e,r,n))),we=(e,r,n,i)=>{if(r==="NOT")return z(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?b:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):le(c,f)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",pe=e=>j(e)&&Object.keys(e).every(r=>ce.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return H(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):ae(n)}),G=(e,r)=>{let n=b;for(const i of Object.keys(r)){const c=r[i];if(H(i)){n=p(n,we(e,i,c,G));continue}const h=e[i];if(pe(c)){n=p(n,ye(i,h,c));continue}M(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>G(e,r)===b,X=500,I=(e,r,n)=>{const i=r??X;if(e>i)throw new W("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},ge=se(),We=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),Oe=e=>e[J],Re=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},be=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const h=c.when(r);if(h!==void 0){if(h===!0){i=!0;break}h!==!1&&n.push(h)}}if(!i)return n.length===0?ge:n.length===1?n[0]:{OR:n}},Ae=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return L(n,i)},Ee=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||Ae(e,r,n);if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!L(r.row,i)?!1:n===void 0||L(n,i)},Be=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!Ee(h,n,i)))return!1;return c},ve=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Se=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),_e=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>ve.has(n)&&Se(n,e[n]))},ke=e=>e===void 0?{}:j(e)&&_e(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Ie=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},R=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,Te=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Me=(e,r,n)=>{const[i]=n,c=n.length===1&&i!==void 0?i.perTable:new Set(n.flatMap(t=>[...t.perTable.keys()])),h=new Map,f=t=>{const s=h.get(t);if(s)return s;const o=[];let a=!1;for(const y of n){const u=y.perTable.get(t);if(!u||u.length===0||!u.some(m=>m.on==="read"))continue;a=!0;const d=be(u,y.context);d!==void 0&&o.push(d)}const l={baseWhere:Ie(o),restricts:a};return h.set(t,l),l},_=(t,s,o,a)=>{for(const l of n){const y=l.perTable.get(t);if(y&&!Be(y,s,{...l.context,row:o},a))return!1}return!0},w=t=>f(t).restricts?r:e,g=t=>f(t).baseWhere,A=async(t,s,o)=>{if(r.lookupById){const d=await r.lookupById(t,s);if(d)return{row:d.row,tableName:c.has(d.tableName)?d.tableName:void 0}}const a=await r.get(t,s);if(!a)return{row:null,tableName:void 0};const l=s??o,y=l===void 0?[...c.keys()]:[l].filter(d=>c.has(d)),u=await Promise.all(y.map(async d=>(await r.findFirst(d,{limit:1,where:{_id:t}}))?._id===t?d:void 0));return{row:a,tableName:u.find(d=>d!==void 0)}},U=async(t,s,o)=>{const a=await A(t,s,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},O=async(t,s,o,a,l,y)=>{const u=await U(t,l,y);if(!u)return o(e);const d=a?a(u.row):void 0;if(!_(u.tableName,s,u.row,d))throw new W("FORBIDDEN",`${s} denied by policy`);return o(r)},E=(t,s)=>{const{baseWhere:o}=f(t);if($(o))throw new W("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`)},D=e.rankBefore,P=e.rankPageRows,{relationEdges:N}=e,k={...e,async count(t,s){const{baseWhere:o}=f(t),a=ke(s);return w(t).count(t,{...a,baseWhere:R(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,s,o)=>O(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??X),{baseWhere:a}=f(t);let l=0;for(;;){const u=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(d=>String(d._id));if(u.length===0)break;for(const d of u)await O(d,"delete",m=>m.delete(d,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(u.length<o)break}return{deleted:l}},async deleteMany(t,s,o){I(t.length,s?.limit,"deleteMany");for(const a of t)await O(a,"delete",l=>l.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s,a),relationBaseWhere:g})).page.map(u=>String(u._id));I(y.length,o?.limit,"deleteWhere");for(const u of y)await O(u,"delete",d=>d.delete(u),void 0,void 0,t);return{deleted:y.length}},async findFirst(t,s){const{baseWhere:o}=f(t);return w(t).findFirst(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:R(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:l}=f(o.tableName);if(!l)return e.get(t,s);if(!a)return o.row;const y=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return y?._id===t?y:null},async lookupById(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0||!f(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=f(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const l=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?{row:l,tableName:o.tableName}:null},async insert(t,s){if(c.has(t)){if(!_(t,"insert",s))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){if(I(s.length,o?.limit,"insertMany"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){if(I(s.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>O(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){I(t.length,s?.limit,"patchMany");for(const a of t)await O(a.id,"update",l=>l.patch(a.id,a.patch,o),l=>({...l,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:R(s.where,a),relationBaseWhere:g})).page.map(u=>({id:String(u._id),patch:s.patch}));return I(y.length,o?.limit,"patchWhere"),k.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(ee(s,a=>L(a,s))):o},related:N===void 0?void 0:async(t,s)=>V({findMany:async(o,a)=>k.findMany(o,a),lookupById:async o=>r.lookupById?.(o)},N,t,{cursor:s?.cursor,depth:s?.depth,direction:s?.direction,edges:s?.edges,limit:s?.limit,relationMask:s?.relationMask}),restore:(t,s)=>O(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new W("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>O(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=f(t);return w(t).aggregate(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:R(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){return E(t,"rank"),w(t).rank(t,s,o)},rankPage(t,s,o){return E(t,"rankPage"),w(t).rankPage(t,s,o)},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...q("rankBefore",D,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...q("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},x=k;if(c.size>0)for(const[t,s]of Object.entries(e))Te(s)&&(x[t]=te(k,t));return Object.defineProperty(k,J,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),k},Z=e=>typeof e=="string"?e:e.name,De=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>Z(i))));return r},Pe=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(Z(i))},me=["roles","role"],Ce=e=>{for(const r of me){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Le=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...Ce(n),...e.roles??[]])];return{can:Pe(i,r),identity:n,roles:i,userId:e.userId??null}},Ye=(e,r={})=>{const n=e,i=Re(n),c=De(r.roles);return ne(async({ctx:f,next:_})=>{const w={auth:await Le(f.auth??{},c),ctx:f},g=f.db,A=Oe(g),U=A?.base??g,O=A?.raw??g[We]??g,E=Me(U,O,[...A?.steps??[],{context:w,perTable:i}]),D={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(D.orm=re(E)),_({ctx:D})},[{policies:n,roles:r.roles??[]}])};export{Le as a,Te as b,ae as c,Ce as d,be as e,Pe as f,Be as g,De as i,L as m,q as o,Ye as r};
@@ -1 +1 @@
1
- import"./wire-codec-CU5bvJwQ.mjs";import"./bindOrm-D_hFUjmr.mjs";import{f as i,g as m,i as l,b as d,m as p,d as n,e as c,a as h,r as u}from"./middleware-3-gbLgdd.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{i as computeReadBaseWhere,m as evaluateWrite,l as indexRolePermissions,d as isFacadeEntry,p as matchesWhere,n as readIdentityRoles,c as resolveCan,h as resolvePolicyAuth,u as rls};
1
+ import"./wire-codec-CZ4obM6q.mjs";import"./bindOrm-D_hFUjmr.mjs";import{e as i,g as m,i as l,b as d,m as p,d as n,f as c,a as h,r as u}from"./middleware-C1CfQMYn.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{i as computeReadBaseWhere,m as evaluateWrite,l as indexRolePermissions,d as isFacadeEntry,p as matchesWhere,n as readIdentityRoles,c as resolveCan,h as resolvePolicyAuth,u as rls};
@@ -1 +1 @@
1
- import{isSafeHeaderValue as l}from"./httpAction-xizRL75J.mjs";const h=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,f=(t,e)=>{if(t===null)return{kind:"full"};const n=h.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let o,r;if(s===""){const i=Number(a);if(i===0)return{kind:"unsatisfiable"};o=Math.max(0,e-i),r=e-1}else o=Number(s),r=a===""?e-1:Math.min(Number(a),e-1);return o>r||o>=e?{kind:"unsatisfiable"}:{end:r,kind:"partial",start:o}},m=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),p=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&l(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return m.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},w=t=>f(t,0).kind==="full",u=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...p(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},b=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},y=async(t,e,n,s,a="no-store")=>{if(!await b(s,e,n))return new Response("Forbidden",{status:403});const o=n.headers.get("range");if(w(o))return u(t,e,a);const r=await t.storage.head(e);if(!r)return new Response("Not Found",{status:404});const i=f(o,r.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(r.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(r.etag)},status:416});if(i.kind==="full")return u(t,e,a);const c=i.end-i.start+1,d=await t.storage.download(e,{range:{length:c,offset:i.start}});return d?new Response(d.body,{headers:{...p(r,a),"content-length":String(c),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(r.size)}`},status:206}):new Response("Not Found",{status:404})};export{y as serveStorageObject};
1
+ import{isSafeHeaderValue as l}from"./httpAction-CsKNC6op.mjs";const h=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,f=(t,e)=>{if(t===null)return{kind:"full"};const n=h.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let o,r;if(s===""){const i=Number(a);if(i===0)return{kind:"unsatisfiable"};o=Math.max(0,e-i),r=e-1}else o=Number(s),r=a===""?e-1:Math.min(Number(a),e-1);return o>r||o>=e?{kind:"unsatisfiable"}:{end:r,kind:"partial",start:o}},m=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),p=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&l(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return m.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},w=t=>f(t,0).kind==="full",u=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...p(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},b=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},y=async(t,e,n,s,a="no-store")=>{if(!await b(s,e,n))return new Response("Forbidden",{status:403});const o=n.headers.get("range");if(w(o))return u(t,e,a);const r=await t.storage.head(e);if(!r)return new Response("Not Found",{status:404});const i=f(o,r.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(r.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(r.etag)},status:416});if(i.kind==="full")return u(t,e,a);const c=i.end-i.start+1,d=await t.storage.download(e,{range:{length:c,offset:i.start}});return d?new Response(d.body,{headers:{...p(r,a),"content-length":String(c),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(r.size)}`},status:206}):new Response("Not Found",{status:404})};export{y as serveStorageObject};
@@ -1 +1 @@
1
- import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-3-gbLgdd.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
1
+ import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-C1CfQMYn.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
@@ -1 +1 @@
1
- const m=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},A=e=>{const t=atob(e),c=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)c[o]=t.codePointAt(o)??0;return c},i="$lunora.wire$";const w="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},p={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},u=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const c=typeof e;if(c==="bigint"){const r=e.toString();if(r.length>1024)throw new RangeError("wire-codec: over-long bigint (max 1024 digits)");return[i,"bigint",r]}if(c==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(c!=="object")return e;if(e instanceof Date)return[i,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n=u(Object.fromEntries(Object.keys(r).map(a=>[a,r[a]])),t+1),s=[i,"error",String(r.name),String(r.message),n];return r.cause!==void 0&&s.push(u(r.cause,t+1)),s}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>u(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",m(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",m(s)]:[i,"bytes",m(s),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!l(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,f={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const s=u(n,t+1);r===w?Object.defineProperty(f,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):f[r]=s}return f},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(p,r)?p[r]:void 0)??Error,a=new s(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const b=y(e[4],t+1);if(b===null||typeof b!="object"||Array.isArray(b))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(b))d===w?Object.defineProperty(a,d,{configurable:!0,enumerable:!0,value:b[d],writable:!0}):a[d]=b[d];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),a}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=A(r);if(m(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const a=Object.hasOwn(g,s)?g[s]:void 0;return a?new a(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(f=>y(f,t+1))}const c=e,o={};for(const f of Object.keys(c)){const r=y(c[f],t+1);f===w?Object.defineProperty(o,f,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[f]=r}return o},E=(e,t,c)=>{try{return u(c)}catch(o){throw new TypeError(`${e}: cannot encode args for '${t}' — ${o instanceof Error?o.message:String(o)}`,o instanceof Error?{cause:o}:void 0)}};export{u as a,y as d,E as e,l as i};
1
+ const m=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},A=e=>{const t=atob(e),c=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)c[o]=t.codePointAt(o)??0;return c},i="$lunora.wire$";const w="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},p={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},u=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const c=typeof e;if(c==="bigint"){const r=e.toString();if(r.length>1024)throw new RangeError("wire-codec: over-long bigint (max 1024 digits)");return[i,"bigint",r]}if(c==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(c!=="object")return e;if(e instanceof Date)return[i,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n=u(Object.fromEntries(Object.keys(r).map(a=>[a,r[a]])),t+1),s=[i,"error",String(r.name),String(r.message),n];return r.cause!==void 0&&s.push(u(r.cause,t+1)),s}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>u(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",m(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",m(s)]:[i,"bytes",m(s),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!l(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,f={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const s=u(n,t+1);r===w?Object.defineProperty(f,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):f[r]=s}return f},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(p,r)?p[r]:void 0)??Error,a=new s(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const b=y(e[4],t+1);if(b===null||typeof b!="object"||Array.isArray(b))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(b))d===w?Object.defineProperty(a,d,{configurable:!0,enumerable:!0,value:b[d],writable:!0}):a[d]=b[d];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),a}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=A(r);if(m(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const a=Object.hasOwn(g,s)?g[s]:void 0;return a?new a(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(f=>y(f,t+1))}const c=e,o={};for(const f of Object.keys(c)){const r=y(c[f],t+1);f===w?Object.defineProperty(o,f,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[f]=r}return o},E=(e,t,c)=>{try{return u(c)}catch(o){throw new TypeError(`${e}: cannot encode args for '${t}' — ${o instanceof Error?o.message:String(o)}`,o instanceof Error?{cause:o}:void 0)}};export{E as a,y as d,u as e,l as i};
@@ -1 +1 @@
1
- import{i as y,d as P,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-3-gbLgdd.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-C1CfQMYn.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
package/dist/types.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ValidatorMap, InferValidatorMap, Validator, Infer, Id } from '@lunora/values';
1
+ import { Id, Validator, Infer, ValidatorMap, InferValidatorMap } from '@lunora/values';
2
2
  /**
3
3
  * The set of languages a `.searchIndex()` can declare, in one place.
4
4
  *
@@ -2736,10 +2736,4 @@ interface ActionCtx {
2736
2736
  /** Start / resume / inspect durable workflows; see {@link Workflows}. */
2737
2737
  readonly workflows: Workflows;
2738
2738
  }
2739
- /**
2740
- * Stand-in returned by codegen so projects can `import { api } from "./_generated/api"`.
2741
- * The runtime value is opaque; the types are filled in by generated declarations.
2742
- */
2743
- type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
2744
- declare const anyApi: AnyApi;
2745
- export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageListOptions, type StorageListResult, type StorageMetadata, type StorageMultipartUpload, type StorageMultipartUploadOptions, type StorageObjectBody, type StorageObjectHead, type StorageRange, type StorageUploadBody, type StorageUploadOptions, type StorageUploadResult, type StorageUploadedPart, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WhisperEvent, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceEvent, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
2739
+ export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ValidatorMap, InferValidatorMap, Validator, Infer, Id } from '@lunora/values';
1
+ import { Id, Validator, Infer, ValidatorMap, InferValidatorMap } from '@lunora/values';
2
2
  /**
3
3
  * The set of languages a `.searchIndex()` can declare, in one place.
4
4
  *
@@ -2736,10 +2736,4 @@ interface ActionCtx {
2736
2736
  /** Start / resume / inspect durable workflows; see {@link Workflows}. */
2737
2737
  readonly workflows: Workflows;
2738
2738
  }
2739
- /**
2740
- * Stand-in returned by codegen so projects can `import { api } from "./_generated/api"`.
2741
- * The runtime value is opaque; the types are filled in by generated declarations.
2742
- */
2743
- type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
2744
- declare const anyApi: AnyApi;
2745
- export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinition, type RestCacheConfig, type RetryPolicy, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanContextIds, type SpanEvaluation, type SpanHandle, type SpanIdentity, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageListOptions, type StorageListResult, type StorageMetadata, type StorageMultipartUpload, type StorageMultipartUploadOptions, type StorageObjectBody, type StorageObjectHead, type StorageRange, type StorageUploadBody, type StorageUploadOptions, type StorageUploadResult, type StorageUploadedPart, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WhisperEvent, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceEvent, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
2739
+ export type { ActionCtx, AggregateIndexDefinition, AggregateOp, ArgsValidator, AuthState, CachePurge, DatabaseReader, DatabaseWriter, DurableObjectJurisdiction, DurableStreamOptions, ExposeConfig, ExternalSourceCursor, ExternalSourceDefinition, ExternalSourceMode, ExternalSourceRefresh, FunctionKind, FunctionVisibility, GeoBoundingBox, GeoFilterBuilder, GeoIndexDefinition, GeoPointInput, GlobalBackend, IndexDefinition, IndexRangeBuilder, InferArgs, LifecycleEvent, LifecycleEventKind, LogFields, LunoraLogMethod, LunoraLogger, LunoraMetrics, LunoraTracer, LunoraWideEvent, MutationCtx, MutationStorage, OnDeleteAction, PaginationOptions, PaginationResult, QueryCtx, RankIndexDefinition, RankSortKey, ReadOnlyStorage, RegisteredAction, RegisteredFunction, RegisteredLifecycleHook, RegisteredMutation, RegisteredQuery, RegisteredStream, RelatedDirection, RelatedNode, RelatedOptions, RelatedPage, RelatedStart, RelatedStartReference, RelationDefinition, RestCacheConfig, RetryPolicy, RunQueryOptions, ScheduledFunctionDoc, ScheduledJob, Scheduler, Schema, SearchFilterBuilder, SearchIndexDefinition, SearchLanguage, SearchStrategy, Secrets, SecretsStoreSecretLike, ShardInitEvent, ShardMode, SpanContextIds, SpanEvaluation, SpanHandle, SpanIdentity, SpanKind, SpanLink, SpanOptions, Storage, StorageListOptions, StorageListResult, StorageMetadata, StorageMultipartUpload, StorageMultipartUploadOptions, StorageObjectBody, StorageObjectHead, StorageRange, StorageUploadBody, StorageUploadOptions, StorageUploadResult, StorageUploadedPart, SystemDatabaseReader, SystemDoc, SystemQuery, SystemTableName, TableDefinition, TableReader, TableVectorIndex, TriggerAggregateOptions, TriggerBuilder, TriggerCtx, TriggerDatabase, TriggerDefinition, TriggerDeleteEvent, TriggerEvent, TriggerGroupByEntry, TriggerGroupByOptions, TriggerHandler, TriggerInsertEvent, TriggerOp, TriggerQueryArgs, TriggerQueryPage, TriggerRankOptions, TriggerRankPageOptions, TriggerRankResult, TriggerRow, TriggerTiming, TriggerUpdateEvent, TtlDefinition, VectorEmbedder, VectorIndexDefinition, VectorMatch, VectorMatches, VectorMetric, VectorQueryInput, VectorRecord, VectorSearch, VectorSearchReader, VectorUpsertInput, WhisperEvent, WorkflowCreateOptions, WorkflowEventDefinition, WorkflowHandle, WorkflowInstance, WorkflowInstanceEvent, WorkflowInstanceStatus, WorkflowStatusResult, Workflows, X402ProcedureConfig };
package/dist/types.mjs CHANGED
@@ -1 +0,0 @@
1
- const a=new Map,g=new Proxy({},{get(i,e){const r=a.get(e);if(r)return r;const t=new Map,c=new Proxy({},{get(p,n){const o=t.get(n);if(o)return o;const s={__lunoraRef:`${String(e)}:${String(n)}`};return t.set(n,s),s}});return a.set(e,c),c}}),y=g;export{y as anyApi};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.184",
3
+ "version": "1.0.0-alpha.186",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -60,16 +60,20 @@
60
60
  "types": "./dist/otel.d.ts",
61
61
  "import": "./dist/otel.mjs"
62
62
  },
63
+ "./in-process": {
64
+ "types": "./dist/in-process.d.ts",
65
+ "import": "./dist/in-process.mjs"
66
+ },
63
67
  "./package.json": "./package.json"
64
68
  },
65
69
  "publishConfig": {
66
70
  "access": "public"
67
71
  },
68
72
  "dependencies": {
69
- "@lunora/errors": "1.0.0-alpha.50",
70
- "@lunora/scheduler": "1.0.0-alpha.112",
71
- "@lunora/shard-engine": "1.0.0-alpha.116",
72
- "@lunora/values": "1.0.0-alpha.60",
73
+ "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
74
+ "@lunora/scheduler": "1.0.0-alpha.115",
75
+ "@lunora/shard-engine": "1.0.0-alpha.118",
76
+ "@lunora/values": "1.0.0-alpha.61",
73
77
  "drizzle-orm": "^0.45.3",
74
78
  "hono": "^4.13.13"
75
79
  },