@lunora/server 1.0.0-alpha.120 → 1.0.0-alpha.122
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -11
- package/dist/index.d.mts +128 -4
- package/dist/index.d.ts +128 -4
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-BUng3KOy.mjs → ACTION_CACHE_DEFAULT_TTL_MS-COBng51i.mjs} +1 -1
- package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-g-fdcytr.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-C8sDYzqZ.mjs} +1 -1
- package/dist/packem_shared/{PRESENCE_DEFAULT_TTL_MS-DheiApL3.mjs → PRESENCE_DEFAULT_TTL_MS-BzZ7xnmQ.mjs} +1 -1
- package/dist/packem_shared/{assertShapesDeclareReadPolicies-BCyJRmhj.mjs → assertShapesDeclareReadPolicies-DHLO-AVP.mjs} +1 -1
- package/dist/packem_shared/beginDeferredDeletes-DhwFBbvs.mjs +1 -0
- package/dist/packem_shared/{composePluginMiddleware-D4tocdAs.mjs → composePluginMiddleware-CTx6hU3r.mjs} +1 -1
- package/dist/packem_shared/{defineAggregateIndex-COm6F0QJ.mjs → defineAggregateIndex-DGuYQrYn.mjs} +1 -1
- package/dist/packem_shared/{defineShape-P9JuGPRq.mjs → defineShape-DtBuu6Yh.mjs} +1 -1
- package/dist/packem_shared/mask-rh0M0XlH.mjs +1 -0
- package/dist/packem_shared/middleware-DciZ1Q3A.mjs +1 -0
- package/dist/packem_shared/plugin-CqXQ2s-i.mjs +1 -0
- package/dist/packem_shared/{rls-DJSGDVQX.mjs → rls-DCBTL6B2.mjs} +1 -1
- package/dist/packem_shared/{storageRules-CZOzWcxr.mjs → storageRules-DvM18uSL.mjs} +1 -1
- package/dist/rls/testing.mjs +1 -1
- package/dist/types.d.mts +101 -6
- package/dist/types.d.ts +101 -6
- package/package.json +5 -4
- package/dist/packem_shared/flushDeferredDeletes-DEJXlhop.mjs +0 -1
- package/dist/packem_shared/mask-MQFwprP0.mjs +0 -1
- package/dist/packem_shared/middleware-BZcRFqUp.mjs +0 -1
- package/dist/packem_shared/plugin-DY0N7ZWx.mjs +0 -1
package/README.md
CHANGED
|
@@ -91,7 +91,7 @@ export const send = mutation
|
|
|
91
91
|
|
|
92
92
|
The builder chain is `<builder>.input(validators).<kind>(handler)`, plus `.use(middleware)` and `.output(validator)`. `internalQuery` / `internalMutation` / `internalAction` are the same builders but kept off the public `api`. Run `lunora codegen` (or the Vite plugin) to (re)generate `_generated/` after a schema change.
|
|
93
93
|
|
|
94
|
-
> **Determinism:** `query` and `mutation` handlers must be deterministic — they may be re-run on OCC
|
|
94
|
+
> **Determinism:** `query` and `mutation` handlers must be deterministic — they may be re-run on subscription re-evaluation (an OCC conflict surfaces as a `409` to the caller, not an internal retry). Read the current time from **`ctx.now`** (epoch ms, captured once per execution — also on `ActionCtx`) instead of `Date.now()`; compute randomness and network results in an `action` (`crypto.randomUUID()`, `fetch`) and pass them into the mutation as arguments. The `nondeterministic_query_mutation` advisor flags `Date.now()`/`Math.random()`/`fetch` in query/mutation handlers.
|
|
95
95
|
|
|
96
96
|
### Local-first sync engine
|
|
97
97
|
|
|
@@ -128,22 +128,28 @@ export const getProduct = httpRoute
|
|
|
128
128
|
});
|
|
129
129
|
```
|
|
130
130
|
|
|
131
|
-
**Purge cache by tag** from an action handler:
|
|
131
|
+
**Purge cache by tag** from an HTTP action handler:
|
|
132
132
|
|
|
133
133
|
```ts
|
|
134
|
-
import {
|
|
134
|
+
import { httpAction, httpRouter } from "@lunora/server";
|
|
135
135
|
|
|
136
|
-
export const
|
|
137
|
-
if (!ctx.cache) {
|
|
138
|
-
throw new Error("Workers Cache is not enabled in wrangler.jsonc");
|
|
139
|
-
}
|
|
136
|
+
export const app = httpRouter();
|
|
140
137
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
138
|
+
app.post(
|
|
139
|
+
"/admin/refresh-products",
|
|
140
|
+
httpAction(async (ctx) => {
|
|
141
|
+
if (!ctx.cache) {
|
|
142
|
+
return new Response("Workers Cache is not enabled in wrangler.jsonc", { status: 501 });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
await ctx.cache.purge({ tags: ["products"] });
|
|
146
|
+
|
|
147
|
+
return Response.json({ ok: true });
|
|
148
|
+
}),
|
|
149
|
+
);
|
|
144
150
|
```
|
|
145
151
|
|
|
146
|
-
The `ctx.cache.purge` API accepts `{ tags?: string[]; purgeEverything?: boolean }`. Only action handlers expose `ctx.cache
|
|
152
|
+
The `ctx.cache.purge` API accepts `{ tags?: string[]; purgeEverything?: boolean }`. Only **HTTP action** handlers expose `ctx.cache`: the Worker holds the cache binding and builds `HttpActionCtx`. Queries, mutations, and actions reached over RPC all run inside the Durable Object, where `ctx.cache` is `undefined`.
|
|
147
153
|
|
|
148
154
|
## Related
|
|
149
155
|
|
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 } 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 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 StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, 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 WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } 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 StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, 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 WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } 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';
|
|
@@ -1146,6 +1146,28 @@ declare const createSecrets: (env: Record<string, unknown>) => Secrets;
|
|
|
1146
1146
|
* @param storage the bucket-aware facade from `asBucketStorage`
|
|
1147
1147
|
*/
|
|
1148
1148
|
declare const withDeferredDeletes: (storage: unknown) => unknown;
|
|
1149
|
+
/**
|
|
1150
|
+
* Open a deferral window on `context.storage` and return its settle function.
|
|
1151
|
+
*
|
|
1152
|
+
* Call it around a transaction, then settle with `true` once the commit has
|
|
1153
|
+
* landed — the keys queued inside become flushable — or `false` when it rolled
|
|
1154
|
+
* back, which DROPS them. An R2 delete cannot be undone, so a key whose queuing
|
|
1155
|
+
* transaction never committed must never reach {@link flushDeferredDeletes}: the
|
|
1156
|
+
* row that points at the object is still there.
|
|
1157
|
+
*
|
|
1158
|
+
* The window owns the keys queued while IT was the innermost open one, so a
|
|
1159
|
+
* rollback drops those and nothing else; on a commit an enclosing window takes
|
|
1160
|
+
* them over, which is how a `ctx.runMutation` inside an open transaction hands
|
|
1161
|
+
* its keys to the span that actually commits them.
|
|
1162
|
+
*
|
|
1163
|
+
* Synchronous, and it never throws: it only moves entries between lists, and it
|
|
1164
|
+
* runs on the rollback path of a dispatch that is already failing.
|
|
1165
|
+
*
|
|
1166
|
+
* A context whose storage was never wrapped gets an inert settle, so a caller
|
|
1167
|
+
* needs no branch.
|
|
1168
|
+
* @param context the dispatch context whose `storage` carries the queue
|
|
1169
|
+
*/
|
|
1170
|
+
declare const beginDeferredDeletes: (context: unknown) => ((committed: boolean) => void);
|
|
1149
1171
|
/** How a flush ended, so a caller can assert on it without this module owning a logger. */
|
|
1150
1172
|
interface DeferredDeleteFlushResult {
|
|
1151
1173
|
/** How many keys were attempted. */
|
|
@@ -1157,8 +1179,13 @@ interface DeferredDeleteFlushResult {
|
|
|
1157
1179
|
}[];
|
|
1158
1180
|
}
|
|
1159
1181
|
/**
|
|
1160
|
-
* Delete everything queued on `context.storage
|
|
1161
|
-
* and report each failure through
|
|
1182
|
+
* Delete everything queued on `context.storage` that belongs to no open
|
|
1183
|
+
* transaction, draining the queue as it goes, and report each failure through
|
|
1184
|
+
* `context.log`.
|
|
1185
|
+
*
|
|
1186
|
+
* Keys still inside an OPEN window are left where they are: their transaction
|
|
1187
|
+
* has not resolved, so whether they may be deleted is not yet known. Settling
|
|
1188
|
+
* that window (see {@link beginDeferredDeletes}) is what makes them flushable.
|
|
1162
1189
|
*
|
|
1163
1190
|
* Draining first means a second flush of the same dispatch is a no-op rather than
|
|
1164
1191
|
* a second round of deletes.
|
|
@@ -2264,6 +2291,56 @@ interface RankPageArgs {
|
|
|
2264
2291
|
take?: number;
|
|
2265
2292
|
where?: WhereInput;
|
|
2266
2293
|
}
|
|
2294
|
+
/**
|
|
2295
|
+
* Structural mirror of `@lunora/shard-engine`'s `RelatedStart`.
|
|
2296
|
+
*
|
|
2297
|
+
* The document arm requires `_id` for the same reason the mirrored type does:
|
|
2298
|
+
* against a bare `Record<string, unknown>` the union collapses, because
|
|
2299
|
+
* `{ table, id }` is assignable to it.
|
|
2300
|
+
*/
|
|
2301
|
+
type RelatedStartLike = (Record<string, unknown> & {
|
|
2302
|
+
_id: string;
|
|
2303
|
+
}) | {
|
|
2304
|
+
id: string;
|
|
2305
|
+
table: string;
|
|
2306
|
+
};
|
|
2307
|
+
/** Structural mirror of `@lunora/shard-engine`'s `RelationEdge` — one directed foreign-key edge. */
|
|
2308
|
+
interface RelationEdgeLike {
|
|
2309
|
+
readonly array: boolean;
|
|
2310
|
+
readonly column: string;
|
|
2311
|
+
readonly name: string;
|
|
2312
|
+
readonly sourceTable: string;
|
|
2313
|
+
readonly targetTable: string;
|
|
2314
|
+
}
|
|
2315
|
+
/** Structural mirror of `@lunora/shard-engine`'s `RelatedOptions` — only the fields the wrapper forwards or fills. */
|
|
2316
|
+
interface RelatedArgs {
|
|
2317
|
+
cursor?: null | string;
|
|
2318
|
+
depth?: number;
|
|
2319
|
+
direction?: "both" | "in" | "out";
|
|
2320
|
+
edges?: ReadonlyArray<string>;
|
|
2321
|
+
limit?: number;
|
|
2322
|
+
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
2323
|
+
/**
|
|
2324
|
+
* Per-hop column mask. Declared because an OUTER `mask()` step hands it to
|
|
2325
|
+
* this wrapper's `related` (see `../mask/middleware`), and this wrapper now
|
|
2326
|
+
* runs the walk itself — so it has to forward the hook rather than let a
|
|
2327
|
+
* spread carry it to a delegate.
|
|
2328
|
+
*/
|
|
2329
|
+
relationMask?: (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
|
|
2330
|
+
}
|
|
2331
|
+
/** Structural mirror of `@lunora/shard-engine`'s `RelatedPage`. */
|
|
2332
|
+
interface RelatedPageLike {
|
|
2333
|
+
continueCursor: null | string;
|
|
2334
|
+
isDone: boolean;
|
|
2335
|
+
nodes: {
|
|
2336
|
+
depth: number;
|
|
2337
|
+
document: Record<string, unknown>;
|
|
2338
|
+
path: ReadonlyArray<string>;
|
|
2339
|
+
pathIds: ReadonlyArray<string>;
|
|
2340
|
+
score: number;
|
|
2341
|
+
table: string;
|
|
2342
|
+
}[];
|
|
2343
|
+
}
|
|
2267
2344
|
interface QueryPage$1 {
|
|
2268
2345
|
continueCursor: null | string;
|
|
2269
2346
|
isDone: boolean;
|
|
@@ -2399,6 +2476,24 @@ interface DatabaseWriterLike {
|
|
|
2399
2476
|
* policy for the identical reason (see `rankPage` above).
|
|
2400
2477
|
*/
|
|
2401
2478
|
rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
|
|
2479
|
+
/**
|
|
2480
|
+
* Relation-graph traversal. Declared so the `...base` spread's shape is
|
|
2481
|
+
* typed, but never CALLED by the wrapper: the walk it performs is bound to
|
|
2482
|
+
* whatever writer this closure came from, and the wrapper has to route each
|
|
2483
|
+
* hop itself. It re-binds the traversal over {@link DatabaseWriterLike.relationEdges}
|
|
2484
|
+
* instead — see the `related` entry on the wrapper.
|
|
2485
|
+
*/
|
|
2486
|
+
related?: (start: RelatedStartLike, options?: RelatedArgs) => Promise<RelatedPageLike>;
|
|
2487
|
+
/**
|
|
2488
|
+
* The schema's foreign-key edge set — what `related` walks. Published by the
|
|
2489
|
+
* writer (see `@lunora/shard-engine`'s `DatabaseWriterLike`) precisely so a
|
|
2490
|
+
* wrapper that must route the traversal per hop can run the walk itself
|
|
2491
|
+
* instead of delegating into a closure already bound to one writer.
|
|
2492
|
+
*
|
|
2493
|
+
* Present exactly when `related` is, so it is what this wrapper keys the
|
|
2494
|
+
* traversal off.
|
|
2495
|
+
*/
|
|
2496
|
+
relationEdges?: ReadonlyArray<RelationEdgeLike>;
|
|
2402
2497
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
2403
2498
|
restore?: (id: string, expectedTable?: string) => Promise<void>;
|
|
2404
2499
|
/**
|
|
@@ -2684,6 +2779,22 @@ interface MaskDatabase {
|
|
|
2684
2779
|
rankPage: (tableName: string, indexName: string, options?: unknown) => Promise<QueryPage>;
|
|
2685
2780
|
/** Cross-shard companion to `rankPage`, gated the same way `rankPage` is masked below. */
|
|
2686
2781
|
rankPageRows?: (tableName: string, indexName: string, options?: unknown) => Promise<ShardRankPageResultLike>;
|
|
2782
|
+
/**
|
|
2783
|
+
* Relation-graph traversal. Its rows come from tables the caller never
|
|
2784
|
+
* names, at every hop — exactly the `with`-hop problem — so it is masked
|
|
2785
|
+
* through the same `relationMask` hook rather than by a per-table wrapper
|
|
2786
|
+
* here. Structural mirror of `@lunora/shard-engine`'s `RelatedOptions` /
|
|
2787
|
+
* `RelatedPage`, narrowed to what this wrapper touches.
|
|
2788
|
+
*/
|
|
2789
|
+
related?: (start: Record<string, unknown>, options?: {
|
|
2790
|
+
relationMask?: (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
|
|
2791
|
+
}) => Promise<{
|
|
2792
|
+
continueCursor: null | string;
|
|
2793
|
+
isDone: boolean;
|
|
2794
|
+
nodes: {
|
|
2795
|
+
document: Record<string, unknown>;
|
|
2796
|
+
}[];
|
|
2797
|
+
}>;
|
|
2687
2798
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
2688
2799
|
}
|
|
2689
2800
|
interface MaskContextIn {
|
|
@@ -2958,6 +3069,19 @@ type PresenceComponent = Component<{
|
|
|
2958
3069
|
declare const presenceExtension: SchemaExtension<{
|
|
2959
3070
|
[PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
|
|
2960
3071
|
}>;
|
|
3072
|
+
/**
|
|
3073
|
+
* Build a presence {@link Component} — schema extension + heartbeat / listPresent
|
|
3074
|
+
* / sweep functions — wired to a single TTL. Re-export `component.functions`
|
|
3075
|
+
* from your `lunora/` module so codegen exposes them, and `.extend(component.
|
|
3076
|
+
* extension)` to merge the table.
|
|
3077
|
+
*
|
|
3078
|
+
* Deviations from the brief: `sweep` is shipped as an **internal** mutation
|
|
3079
|
+
* (callable only server-side, e.g. from a cron) since hard-deletes shouldn't be
|
|
3080
|
+
* client triggered. `listPresent` stays a plain public query so the client can
|
|
3081
|
+
* subscribe to it.
|
|
3082
|
+
* @param options presence configuration (TTL).
|
|
3083
|
+
* @returns a component bundling the extension and the presence functions.
|
|
3084
|
+
*/
|
|
2961
3085
|
declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
|
|
2962
3086
|
/**
|
|
2963
3087
|
* The middlewares `protectPublic` chains, in the order they run. Every field is
|
|
@@ -3438,4 +3562,4 @@ interface StorageContextIn {
|
|
|
3438
3562
|
}
|
|
3439
3563
|
declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
|
|
3440
3564
|
declare const VERSION = "0.0.0";
|
|
3441
|
-
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
|
3565
|
+
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
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 } 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 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 StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, 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 WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } 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 StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, 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 WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, anyApi } 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';
|
|
@@ -1146,6 +1146,28 @@ declare const createSecrets: (env: Record<string, unknown>) => Secrets;
|
|
|
1146
1146
|
* @param storage the bucket-aware facade from `asBucketStorage`
|
|
1147
1147
|
*/
|
|
1148
1148
|
declare const withDeferredDeletes: (storage: unknown) => unknown;
|
|
1149
|
+
/**
|
|
1150
|
+
* Open a deferral window on `context.storage` and return its settle function.
|
|
1151
|
+
*
|
|
1152
|
+
* Call it around a transaction, then settle with `true` once the commit has
|
|
1153
|
+
* landed — the keys queued inside become flushable — or `false` when it rolled
|
|
1154
|
+
* back, which DROPS them. An R2 delete cannot be undone, so a key whose queuing
|
|
1155
|
+
* transaction never committed must never reach {@link flushDeferredDeletes}: the
|
|
1156
|
+
* row that points at the object is still there.
|
|
1157
|
+
*
|
|
1158
|
+
* The window owns the keys queued while IT was the innermost open one, so a
|
|
1159
|
+
* rollback drops those and nothing else; on a commit an enclosing window takes
|
|
1160
|
+
* them over, which is how a `ctx.runMutation` inside an open transaction hands
|
|
1161
|
+
* its keys to the span that actually commits them.
|
|
1162
|
+
*
|
|
1163
|
+
* Synchronous, and it never throws: it only moves entries between lists, and it
|
|
1164
|
+
* runs on the rollback path of a dispatch that is already failing.
|
|
1165
|
+
*
|
|
1166
|
+
* A context whose storage was never wrapped gets an inert settle, so a caller
|
|
1167
|
+
* needs no branch.
|
|
1168
|
+
* @param context the dispatch context whose `storage` carries the queue
|
|
1169
|
+
*/
|
|
1170
|
+
declare const beginDeferredDeletes: (context: unknown) => ((committed: boolean) => void);
|
|
1149
1171
|
/** How a flush ended, so a caller can assert on it without this module owning a logger. */
|
|
1150
1172
|
interface DeferredDeleteFlushResult {
|
|
1151
1173
|
/** How many keys were attempted. */
|
|
@@ -1157,8 +1179,13 @@ interface DeferredDeleteFlushResult {
|
|
|
1157
1179
|
}[];
|
|
1158
1180
|
}
|
|
1159
1181
|
/**
|
|
1160
|
-
* Delete everything queued on `context.storage
|
|
1161
|
-
* and report each failure through
|
|
1182
|
+
* Delete everything queued on `context.storage` that belongs to no open
|
|
1183
|
+
* transaction, draining the queue as it goes, and report each failure through
|
|
1184
|
+
* `context.log`.
|
|
1185
|
+
*
|
|
1186
|
+
* Keys still inside an OPEN window are left where they are: their transaction
|
|
1187
|
+
* has not resolved, so whether they may be deleted is not yet known. Settling
|
|
1188
|
+
* that window (see {@link beginDeferredDeletes}) is what makes them flushable.
|
|
1162
1189
|
*
|
|
1163
1190
|
* Draining first means a second flush of the same dispatch is a no-op rather than
|
|
1164
1191
|
* a second round of deletes.
|
|
@@ -2264,6 +2291,56 @@ interface RankPageArgs {
|
|
|
2264
2291
|
take?: number;
|
|
2265
2292
|
where?: WhereInput;
|
|
2266
2293
|
}
|
|
2294
|
+
/**
|
|
2295
|
+
* Structural mirror of `@lunora/shard-engine`'s `RelatedStart`.
|
|
2296
|
+
*
|
|
2297
|
+
* The document arm requires `_id` for the same reason the mirrored type does:
|
|
2298
|
+
* against a bare `Record<string, unknown>` the union collapses, because
|
|
2299
|
+
* `{ table, id }` is assignable to it.
|
|
2300
|
+
*/
|
|
2301
|
+
type RelatedStartLike = (Record<string, unknown> & {
|
|
2302
|
+
_id: string;
|
|
2303
|
+
}) | {
|
|
2304
|
+
id: string;
|
|
2305
|
+
table: string;
|
|
2306
|
+
};
|
|
2307
|
+
/** Structural mirror of `@lunora/shard-engine`'s `RelationEdge` — one directed foreign-key edge. */
|
|
2308
|
+
interface RelationEdgeLike {
|
|
2309
|
+
readonly array: boolean;
|
|
2310
|
+
readonly column: string;
|
|
2311
|
+
readonly name: string;
|
|
2312
|
+
readonly sourceTable: string;
|
|
2313
|
+
readonly targetTable: string;
|
|
2314
|
+
}
|
|
2315
|
+
/** Structural mirror of `@lunora/shard-engine`'s `RelatedOptions` — only the fields the wrapper forwards or fills. */
|
|
2316
|
+
interface RelatedArgs {
|
|
2317
|
+
cursor?: null | string;
|
|
2318
|
+
depth?: number;
|
|
2319
|
+
direction?: "both" | "in" | "out";
|
|
2320
|
+
edges?: ReadonlyArray<string>;
|
|
2321
|
+
limit?: number;
|
|
2322
|
+
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
2323
|
+
/**
|
|
2324
|
+
* Per-hop column mask. Declared because an OUTER `mask()` step hands it to
|
|
2325
|
+
* this wrapper's `related` (see `../mask/middleware`), and this wrapper now
|
|
2326
|
+
* runs the walk itself — so it has to forward the hook rather than let a
|
|
2327
|
+
* spread carry it to a delegate.
|
|
2328
|
+
*/
|
|
2329
|
+
relationMask?: (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
|
|
2330
|
+
}
|
|
2331
|
+
/** Structural mirror of `@lunora/shard-engine`'s `RelatedPage`. */
|
|
2332
|
+
interface RelatedPageLike {
|
|
2333
|
+
continueCursor: null | string;
|
|
2334
|
+
isDone: boolean;
|
|
2335
|
+
nodes: {
|
|
2336
|
+
depth: number;
|
|
2337
|
+
document: Record<string, unknown>;
|
|
2338
|
+
path: ReadonlyArray<string>;
|
|
2339
|
+
pathIds: ReadonlyArray<string>;
|
|
2340
|
+
score: number;
|
|
2341
|
+
table: string;
|
|
2342
|
+
}[];
|
|
2343
|
+
}
|
|
2267
2344
|
interface QueryPage$1 {
|
|
2268
2345
|
continueCursor: null | string;
|
|
2269
2346
|
isDone: boolean;
|
|
@@ -2399,6 +2476,24 @@ interface DatabaseWriterLike {
|
|
|
2399
2476
|
* policy for the identical reason (see `rankPage` above).
|
|
2400
2477
|
*/
|
|
2401
2478
|
rankPageRows?: (tableName: string, indexName: string, options?: RankPageArgs) => Promise<ShardRankPageResultLike>;
|
|
2479
|
+
/**
|
|
2480
|
+
* Relation-graph traversal. Declared so the `...base` spread's shape is
|
|
2481
|
+
* typed, but never CALLED by the wrapper: the walk it performs is bound to
|
|
2482
|
+
* whatever writer this closure came from, and the wrapper has to route each
|
|
2483
|
+
* hop itself. It re-binds the traversal over {@link DatabaseWriterLike.relationEdges}
|
|
2484
|
+
* instead — see the `related` entry on the wrapper.
|
|
2485
|
+
*/
|
|
2486
|
+
related?: (start: RelatedStartLike, options?: RelatedArgs) => Promise<RelatedPageLike>;
|
|
2487
|
+
/**
|
|
2488
|
+
* The schema's foreign-key edge set — what `related` walks. Published by the
|
|
2489
|
+
* writer (see `@lunora/shard-engine`'s `DatabaseWriterLike`) precisely so a
|
|
2490
|
+
* wrapper that must route the traversal per hop can run the walk itself
|
|
2491
|
+
* instead of delegating into a closure already bound to one writer.
|
|
2492
|
+
*
|
|
2493
|
+
* Present exactly when `related` is, so it is what this wrapper keys the
|
|
2494
|
+
* traversal off.
|
|
2495
|
+
*/
|
|
2496
|
+
relationEdges?: ReadonlyArray<RelationEdgeLike>;
|
|
2402
2497
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
2403
2498
|
restore?: (id: string, expectedTable?: string) => Promise<void>;
|
|
2404
2499
|
/**
|
|
@@ -2684,6 +2779,22 @@ interface MaskDatabase {
|
|
|
2684
2779
|
rankPage: (tableName: string, indexName: string, options?: unknown) => Promise<QueryPage>;
|
|
2685
2780
|
/** Cross-shard companion to `rankPage`, gated the same way `rankPage` is masked below. */
|
|
2686
2781
|
rankPageRows?: (tableName: string, indexName: string, options?: unknown) => Promise<ShardRankPageResultLike>;
|
|
2782
|
+
/**
|
|
2783
|
+
* Relation-graph traversal. Its rows come from tables the caller never
|
|
2784
|
+
* names, at every hop — exactly the `with`-hop problem — so it is masked
|
|
2785
|
+
* through the same `relationMask` hook rather than by a per-table wrapper
|
|
2786
|
+
* here. Structural mirror of `@lunora/shard-engine`'s `RelatedOptions` /
|
|
2787
|
+
* `RelatedPage`, narrowed to what this wrapper touches.
|
|
2788
|
+
*/
|
|
2789
|
+
related?: (start: Record<string, unknown>, options?: {
|
|
2790
|
+
relationMask?: (table: string, rows: Record<string, unknown>[]) => Record<string, unknown>[];
|
|
2791
|
+
}) => Promise<{
|
|
2792
|
+
continueCursor: null | string;
|
|
2793
|
+
isDone: boolean;
|
|
2794
|
+
nodes: {
|
|
2795
|
+
document: Record<string, unknown>;
|
|
2796
|
+
}[];
|
|
2797
|
+
}>;
|
|
2687
2798
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string) => Promise<void>;
|
|
2688
2799
|
}
|
|
2689
2800
|
interface MaskContextIn {
|
|
@@ -2958,6 +3069,19 @@ type PresenceComponent = Component<{
|
|
|
2958
3069
|
declare const presenceExtension: SchemaExtension<{
|
|
2959
3070
|
[PRESENCE_BARE_TABLE]: ReturnType<typeof defineTable>;
|
|
2960
3071
|
}>;
|
|
3072
|
+
/**
|
|
3073
|
+
* Build a presence {@link Component} — schema extension + heartbeat / listPresent
|
|
3074
|
+
* / sweep functions — wired to a single TTL. Re-export `component.functions`
|
|
3075
|
+
* from your `lunora/` module so codegen exposes them, and `.extend(component.
|
|
3076
|
+
* extension)` to merge the table.
|
|
3077
|
+
*
|
|
3078
|
+
* Deviations from the brief: `sweep` is shipped as an **internal** mutation
|
|
3079
|
+
* (callable only server-side, e.g. from a cron) since hard-deletes shouldn't be
|
|
3080
|
+
* client triggered. `listPresent` stays a plain public query so the client can
|
|
3081
|
+
* subscribe to it.
|
|
3082
|
+
* @param options presence configuration (TTL).
|
|
3083
|
+
* @returns a component bundling the extension and the presence functions.
|
|
3084
|
+
*/
|
|
2961
3085
|
declare const definePresence: (options?: DefinePresenceOptions) => PresenceComponent;
|
|
2962
3086
|
/**
|
|
2963
3087
|
* The middlewares `protectPublic` chains, in the order they run. Every field is
|
|
@@ -3438,4 +3562,4 @@ interface StorageContextIn {
|
|
|
3438
3562
|
}
|
|
3439
3563
|
declare const storageRules: <Context extends StorageContextIn = StorageContextIn>(rules: ReadonlyArray<StorageRule<Context>>, options?: StorageRulesOptions) => Middleware<Context, Context>;
|
|
3440
3564
|
declare const VERSION = "0.0.0";
|
|
3441
|
-
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
|
3565
|
+
export { DEFAULT_ACTION_CACHE_TTL_MS as ACTION_CACHE_DEFAULT_TTL_MS, ACTION_CACHE_TABLE, type ActionBuilder, type ActionCacheComponent, type ActionCacheContext, type ActionCacheDatabase, type ActionCacheFunctions, type ActionCtx, type AggregateIndexDefinition, type AggregateIndexOptions, type AggregateOp, type ArgsValidator, type Component, type ComponentFunctions, type CreateOptions, DEFAULT_LIMIT, DEFAULT_MAX_LIMIT, DEFAULT_REDACTED_FIELDS as DOCUMENT_HISTORY_REDACTED_FIELDS, DOCUMENT_HISTORY_TABLE, type DataModelInit, type DeferredDeleteFlushResult, type DefineActionCacheOptions, type DefineComponentOptions, type DefineDocumentHistoryOptions, type DefineIdentityOptions, type DefineListArgsConfig, type DefinePluginOptions, type DefinePolicyInput, type DefinePresenceOptions, type DefineStorageRuleInput, type DocumentHistoryComponent, type DocumentHistoryEntry, type DocumentHistoryFunctions, type DurableObjectJurisdiction, type DurableStreamOptions, type EmptyArgs, type EnvAccessor, type EnvKeyFailure, type EnvShape, type ExposeConfig, type ExtendableSchema, type FacadeEntry, type FacadeWriterLike, type FunctionKind, type HttpActionCtx, type HttpActionHandler, type HttpMethod, type HttpRoute, type HttpRouteBuilder, type HttpRouteFactory, type HttpRouteHandlerOptions, type HttpRunners, type HttpStreamHandlerOptions, type IdentityContract, type IdentityRejectMode, type IdentityValidation, type IndexFieldsByTable, type InferArgs, type InferEnv, type InferIdentity, type InlineAggregateIndexOptions, type InlineRankIndexOptions, type InternalActionBuilder, type InternalMutationBuilder, type InternalQueryBuilder, type LifecycleEvent, type LifecycleHandler, type ListArgsSpec, type ListArgsValidators, type ListArgsValue, type ListFilterOperators, type ListOrderByEntry, type ListWhere, type LunoraBuilders, LunoraEnvError, type LunoraHttpApp, type LunoraHttpEnv, type LunoraRouteHandler, type ManyRelation, type MaskColumns, type MaskContext, type MaskFn, type MaskOptions, type MaskPolicies, type MaskRegistry, type MaskStrategy, type Middleware, type MiddlewareContext, type MiddlewareNext, type MigrationCtx, type MigrationDefinition, type MigrationDocument, type MigrationReader, type MigrationTransform, type MutationBuilder, type MutationCtx, type MutatorDefinition, type OnDeleteAction, type OneRelation, type OrmLike, DEFAULT_TTL_MS as PRESENCE_DEFAULT_TTL_MS, PRESENCE_TABLE, type Permission, type Plugin, type Policy, type PrefixedTables, type PresenceComponent, type PresenceFunctions, type PresenceMember, type ProtectPublicOptions, type QueryBuilder, type QueryCtx, type RankIndexDefinition, type RankIndexOptions, type ReactorHandler, type ReactorOutcome, type ReactorSelect, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMigration, type RegisteredMutation, type RegisteredMutator, type RegisteredQuery, type RegisteredReactor, type RegisteredShape, type RegisteredStream, type RelationBuilder, type RelationDefinition, type RlsOptions, type RlsReadRegistry, type Role, type Schema, type SchemaExtension, type ShapeDefinition, type ShapeGuardDeclaration, type ShapeReadWhereRequest, type ShardInitEvent, type ShardInitHandler, type StorageOperation, type StorageRule, type StorageRuleContext, type StorageRuleDecision, type StorageRulesOptions, type StorageServeAuthorizer, type StorageServeAuthzContext, type TableBuilder, type TableDefinition, type TerminalKind, type TriggerBuilder, type TriggerDefinition, type TypedDefinePolicyInput, VERSION, type VectorEmbedder, type VectorIndexDefinition, type VectorIndexOptions, type VectorMetric, type VectorizeOptions, type WhereInput, actionCacheExtension, allowAll, asBucketStorage, assertShapesDeclareReadPolicies, beginDeferredDeletes, beginDeferredSchedules, bindOrm, bindTableFacade, buildMaskRegistry, buildRlsReadRegistry, cacheKeyFor, clampLimit, composePluginMiddleware, composeShapeReadWhere, createPolicyDsl, createSecrets, defineActionCache, defineAggregateIndex, defineComponent, defineDocumentHistory, defineEnv, defineIdentity, defineListArgs, defineMigration, defineMutator, definePermission, definePlugin, definePolicies, definePolicy, definePresence, defineRankIndex, defineRole, defineSchema, defineSchemaExtension, defineShape, defineStorageRule, defineStorageRules, defineTable, defineVectorIndex, deny, documentHistoryExtension, flushDeferredDeletes, httpAction, httpRoute, httpRouter, indexFieldsFromSchema, initLunora, installPlugins, isDeny, isSafeHeaderValue, mask, mergeSchemaExtension, onConnect, onDisconnect, onQueryChange, onShardInit, presenceExtension, protectPublic, redactSecrets, rls, serveStorageObject, storageRules, toWhereInput, withDeferredDeletes, withDeferredSchedules };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-COBng51i.mjs";import{initLunora as d}from"./packem_shared/initLunora-BzC2zEfH.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as c,flushDeferredDeletes as l,withDeferredDeletes as E}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as u,withDeferredSchedules as h}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as g,defineDocumentHistory as A,documentHistoryExtension as R}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-C8sDYzqZ.mjs";import{LunoraEnvError as L,defineEnv as C,redactSecrets as I}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as P}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as F,httpRoute as O,httpRouter as H,isSafeHeaderValue as N}from"./packem_shared/httpAction-DfKw8ZZt.mjs";import{serveStorageObject as k}from"./packem_shared/serveStorageObject-BzZEP-B5.mjs";import{defineIdentity as w}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as V,onDisconnect as j,onShardInit as W}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as J,DEFAULT_MAX_LIMIT as K,clampLimit as Q,defineListArgs as X}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as z}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as Z}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as ee,d as re,a as oe,b as te,e as ne,f as ie,g as ae,h as fe,i as se,j as de,k as me,m as pe}from"./packem_shared/plugin-CqXQ2s-i.mjs";import{PRESENCE_DEFAULT_TTL_MS as ce,PRESENCE_TABLE as le,definePresence as Ee,presenceExtension as Se}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-BzZ7xnmQ.mjs";import{protectPublic as he}from"./packem_shared/protectPublic-C-STrTgA.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as Ae}from"./packem_shared/defineShape-DtBuu6Yh.mjs";import{anyApi as _e}from"./types.mjs";import{LunoraError as Ce}from"@lunora/errors";import{cronJobs as be}from"@lunora/scheduler";import{ValidationError as Pe,v as Me}from"@lunora/values";import{allowAll as Oe,deny as He,isDeny as Ne,toWhereInput as Ue}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ve}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as Be,buildRlsReadRegistry as Ve,composeShapeReadWhere as je}from"./packem_shared/assertShapesDeclareReadPolicies-DHLO-AVP.mjs";import{buildMaskRegistry as Ye}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Ke,definePermission as Qe,definePolicies as Xe,definePolicy as qe,defineRole as ze}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ze,defineStorageRules as $e}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as rr}from"./packem_shared/mask-rh0M0XlH.mjs";import{r as tr}from"./packem_shared/middleware-DciZ1Q3A.mjs";import{storageRules as ir}from"./packem_shared/storageRules-DvM18uSL.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,J as DEFAULT_LIMIT,K as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,g as DOCUMENT_HISTORY_TABLE,L as LunoraEnvError,Ce as LunoraError,ce as PRESENCE_DEFAULT_TTL_MS,le as PRESENCE_TABLE,e as VERSION,Pe as ValidationError,i as actionCacheExtension,Oe as allowAll,_e as anyApi,ve as asBucketStorage,Be as assertShapesDeclareReadPolicies,c as beginDeferredDeletes,u as beginDeferredSchedules,y as bindOrm,P as bindTableFacade,Ye as buildMaskRegistry,Ve as buildRlsReadRegistry,a as cacheKeyFor,Q as clampLimit,ee as composePluginMiddleware,je as composeShapeReadWhere,Ke as createPolicyDsl,p as createSecrets,be as cronJobs,f as defineActionCache,re as defineAggregateIndex,oe as defineComponent,A as defineDocumentHistory,C as defineEnv,w as defineIdentity,X as defineListArgs,z as defineMigration,Z as defineMutator,Qe as definePermission,te as definePlugin,Xe as definePolicies,qe as definePolicy,Ee as definePresence,ne as defineRankIndex,ze as defineRole,ie as defineSchema,ae as defineSchemaExtension,Ae as defineShape,Ze as defineStorageRule,$e as defineStorageRules,fe as defineTable,se as defineVectorIndex,He as deny,R as documentHistoryExtension,l as flushDeferredDeletes,F as httpAction,O as httpRoute,H as httpRouter,de as indexFieldsFromSchema,d as initLunora,me as installPlugins,Ne as isDeny,N as isSafeHeaderValue,rr as mask,pe as mergeSchemaExtension,V as onConnect,j as onDisconnect,Te as onQueryChange,W as onShardInit,Se as presenceExtension,he as protectPublic,I as redactSecrets,tr as rls,k as serveStorageObject,ir as storageRules,Ue as toWhereInput,Me as v,E as withDeferredDeletes,h as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
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-CH4vwdFT.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-BzC2zEfH.mjs";import{g as k,h as q,a as B}from"./plugin-
|
|
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-CH4vwdFT.mjs";import{s as D}from"./stable-key-B_BlboiY.mjs";import{initLunora as F}from"./initLunora-BzC2zEfH.mjs";import{g as k,h as q,a as B}from"./plugin-CqXQ2s-i.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,e as h}from"./wire-codec-CH4vwdFT.mjs";import{initLunora as x}from"./initLunora-BzC2zEfH.mjs";import{g as v,h as R,a as U}from"./plugin-
|
|
1
|
+
import{v as r}from"@lunora/values";import{d as E,e as h}from"./wire-codec-CH4vwdFT.mjs";import{initLunora as x}from"./initLunora-BzC2zEfH.mjs";import{g as v,h as R,a as U}from"./plugin-CqXQ2s-i.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 b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-BzC2zEfH.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-BzC2zEfH.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-CqXQ2s-i.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-DciZ1Q3A.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const c=new WeakMap,u=s=>{let e=s;for(;e!==void 0&&!e.open;)e=e.parent;return e},f=s=>{const e={flushable:[],innermost:void 0},t=n=>{const o=n??{},r={...o,deleteAfterCommit:i=>{(e.innermost?.pending??e.flushable).push({key:i,storage:o})}};return Object.setPrototypeOf(r,Object.getPrototypeOf(o)),typeof o.bucket=="function"&&(r.bucket=i=>t(o.bucket?.(i))),c.set(r,e),r};return t(s)},d=s=>{const{storage:e}=s??{},t=typeof e=="object"&&e!==null?c.get(e):void 0;if(!t)return()=>{};const n={open:!0,parent:t.innermost,pending:[]};return t.innermost=n,o=>{n.open=!1,t.innermost===n&&(t.innermost=u(n.parent));const r=n.pending.splice(0);!o||r.length===0||(u(n.parent)?.pending??t.flushable).push(...r)}},p=async s=>{const{log:e,storage:t}=s??{},n=typeof t=="object"&&t!==null?c.get(t):void 0;if(!n||n.flushable.length===0)return{attempted:0,failures:[]};const o=n.flushable.splice(0),i=(await Promise.allSettled(o.map(async({key:a,storage:l})=>{if(typeof l.delete!="function")throw new TypeError("ctx.storage: no storage configured, so the object was not deleted");await l.delete(a)}))).flatMap((a,l)=>a.status==="rejected"?[{error:a.reason,key:o[l]?.key??""}]:[]);for(const a of i)e?.warn("ctx.storage.deleteAfterCommit: delete failed, object leaked",{error:String(a.error),key:a.key});return{attempted:o.length,failures:i}};export{d as beginDeferredDeletes,p as flushDeferredDeletes,f as withDeferredDeletes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./compose-middleware-MCpZZKh7.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-
|
|
1
|
+
import"./compose-middleware-MCpZZKh7.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-CqXQ2s-i.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
|
package/dist/packem_shared/{defineAggregateIndex-COm6F0QJ.mjs → defineAggregateIndex-DGuYQrYn.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-
|
|
1
|
+
import{d,e as n,f as i,h as s,i as f,j as x,v as r}from"./plugin-CqXQ2s-i.mjs";export{d as defineAggregateIndex,n as defineRankIndex,i as defineSchema,s as defineTable,f as defineVectorIndex,x as indexFieldsFromSchema,r as validateIndexFields};
|
|
@@ -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-
|
|
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-DHLO-AVP.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};
|
|
@@ -0,0 +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-DciZ1Q3A.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as W}from"@lunora/errors";import{findRelated as V}from"@lunora/shard-engine";import{i as j}from"./wire-codec-CH4vwdFT.mjs";import{bindTableFacade as ee,bindOrm as te}from"./bindOrm-D_hFUjmr.mjs";import{t as re}from"./policy-tag-V0lqFzgS.mjs";import{deny as ne}from"./allowAll-DkRAgItV.mjs";const se=["every","is","isNot","none","some"],oe=new Set(se),ie=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>oe.has(n))},q=(e,r,n)=>r?{[e]:n(r)}:{},ae=["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,ce=(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`)},le={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},fe=(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=le[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,de=(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)),ue=(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},he=(e,r,n)=>p(ue(e,r,n),p(de(e,r,n),fe(e,r,n))),ye=(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):ce(c,f)}return c},H=e=>e==="AND"||e==="OR"||e==="NOT",we=e=>j(e)&&Object.keys(e).every(r=>ae.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??{})):ie(n)}),G=(e,r)=>{let n=b;for(const i of Object.keys(r)){const c=r[i];if(H(i)){n=p(n,ye(e,i,c,G));continue}const h=e[i];if(we(c)){n=p(n,he(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})},pe=ne(),ge=Symbol.for("lunora.ctxdb.rls-unwrap"),J=Symbol.for("lunora.rls.wrapped-chain"),We=e=>e[J],Oe=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},Re=(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?pe:n.length===1?n[0]:{OR:n}},be=(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)},Ae=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||be(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)},Ee=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!Ae(h,n,i)))return!1;return c},Be=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),ve=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),Se=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>Be.has(n)&&ve(n,e[n]))},_e=e=>e===void 0?{}:j(e)&&Se(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,ke=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,Ie=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Te=(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=Re(u,y.context);d!==void 0&&o.push(d)}const l={baseWhere:ke(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&&!Ee(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=_e(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(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))Ie(s)&&(x[t]=ee(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,Me=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>Z(i))));return r},De=(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))},Pe=["roles","role"],me=e=>{for(const r of Pe){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[]},Ce=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...me(n),...e.roles??[]])];return{can:De(i,r),identity:n,roles:i,userId:e.userId??null}},qe=(e,r={})=>{const n=e,i=Oe(n),c=Me(r.roles);return re(async({ctx:f,next:_})=>{const w={auth:await Ce(f.auth??{},c),ctx:f},g=f.db,A=We(g),U=A?.base??g,O=A?.raw??g[ge]??g,E=Te(U,O,[...A?.steps??[],{context:w,perTable:i}]),D={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(D.orm=te(E)),_({ctx:D})},[{policies:n,roles:r.roles??[]}])};export{Ce as a,Ie as b,ie as c,me as d,De as e,Re as f,Ee as g,Me as i,L as m,q as o,Z as p,qe as r};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{c as z}from"./compose-middleware-MCpZZKh7.mjs";import{v as B}from"@lunora/values";const _=["de","en","es","fr","it","nl","none","pt"],q=["native","portable"],H=e=>q.includes(e),Q=e=>_.includes(e),F=e=>{if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?F(t):e.kind},D=16,X={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),U=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),P=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},ce=e=>{const t={...e},n=[],r=[],i=[],d=[],u={},l=[],f={},h=U(),b=[];let w={kind:"root"},S=!1,N=!1,$=!1,T=!1,L,M,A,O;const R=a=>{if(w.kind!=="root"&&w.kind!==a.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");w=a},c={aggregateIndex(a,o){const m=o?.op??"count";if(m!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${a}": op "${m}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:a,on:"",op:m,where:o?.where}),c},get aggregateIndexes(){return n},get externalSource(){return O},commitOrdered(){return S=!0,c},get commitOrderedMode(){return S},externallyManaged(){return N=!0,c},geoIndex(a,o){return r.push({field:o.field,name:a,precision:o.precision}),c},get geoIndexes(){return r},global(a){return R({backend:a?.backend??"d1",kind:"global"}),c},get isExternallyManaged(){return N},get isPublic(){return T},index(a,o,m){return i.push({fields:o,name:a,unique:m?.unique??!1}),c},get indexes(){return i},memory(){return $=!0,c},get memoryMode(){return $},ownedBy(a){return L=a,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(a,o){return d.push({name:a,on:"",partitionBy:o.partitionBy,sortBy:P(a,o.sortBy),where:o.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(a){return Object.assign(u,a(X)),c},searchIndex(a,o){if(o.filterFields&&o.filterFields.length>D)throw new s("INTERNAL",`searchIndex "${a}": at most ${String(D)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:m}=o;if(m!==void 0&&!Q(m))throw new s("INTERNAL",`searchIndex "${a}": unknown language "${m}" (supported: ${_.join(", ")})`);const{strategy:p}=o;if(p!==void 0&&!H(p))throw new s("INTERNAL",`searchIndex "${a}": unknown strategy "${p}" (supported: ${q.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:a,staged:o.staged,strategy:o.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(a){return R({field:a,kind:"shardBy"}),c},get shardMode(){return w},get softDeleteMode(){return M},source(a){if(!a.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!a.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return O=a,N=!0,c},softDelete(a){const o=a?.field??"deletedAt";return M={field:o},o in t||(t[o]=B.optional(B.number().nullable())),c},get triggerMap(){return f},triggers(a){return Object.assign(f,a(h)),c},ttl(a,o){return A={after:o?.after,field:a},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(a,o){return b.push({dimensions:o.dimensions,embed:o.embed,field:a,metadata:o.metadata,metric:o.metric,name:o.index}),c}};return c},ue=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),fe=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},he=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:P(e,t.sortBy),where:t.where}),I=e=>({...e,extend(t){return I(K(e,t))},jurisdiction(t){return I(e)},rls(t){return I({...e,rlsMode:t})}}),V=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},Y=(e,t,n)=>{for(const r of Object.values(t)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);i.aggregateIndexes.push(r)}for(const r of Object.values(n)){const i=e[r.on];if(!i)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);i.rankIndexes.push(r)}},G=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},J=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=G(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},W=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);J(t,r)}}},Z=["_commitSeq","_creationTime","_id"],j="_commitSeq",ee=new Set(Z),x=(e,t,n,r)=>{if(!(ee.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},v=(e,t,n,r)=>{const i=new Set;for(const d of n){if(i.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);i.add(d.name),r(d)}},C=e=>{for(const[t,n]of Object.entries(e))v(t,"index",n.indexes,r=>{for(const i of r.fields)x(t,r.name,i,n)}),v(t,"rank index",n.rankIndexes,r=>{for(const i of r.sortBy)x(t,r.name,i.field,n);for(const i of r.partitionBy??[])x(t,r.name,i,n)}),v(t,"geo index",n.geoIndexes,r=>{x(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const i of e)r[t(i)]=n(i);return r},te=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},me=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const i=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,te);(i||d||u)&&(t[n]={...i?{geo:i}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},ne=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const i=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(i!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${i}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},re=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,i]of Object.entries(n.shape))if(F(i)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},ae=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(j))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${j}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},ge=(e,t={},n={},r={})=>(V(e),Y(e,n,r),W(e),ae(e),re(e),ne(e),C(e),I({tables:e,vectorIndexes:t})),y=(e,t)=>`${e}_${t}`,k=(e,t,n)=>n.has(e)?y(t,e):e,oe=(e,t,n,r)=>{const i=y(t,r),d=h=>h===""?i:k(h,t,n),u={};for(const[h,b]of Object.entries(e.relationMap))u[h]={...b,table:k(b.table,t,n)};const l=e.aggregateIndexes.map(h=>({...h,on:d(h.on)})),f=e.rankIndexes.map(h=>({...h,on:d(h.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},be=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},ie=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),we=(e,t)=>({...ie(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),K=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),i={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=y(n,u);if(Object.hasOwn(i,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);i[f]=oe(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=y(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:k(l.table,n,r)}}return C(i),{rlsMode:e.rlsMode,tables:i,vectorIndexes:d}},xe=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=K(n,r.extension));return n},Ie=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return z(t)};export{we as a,ie as b,Ie as c,fe as d,he as e,ge as f,be as g,ce as h,ue as i,me as j,xe as k,K as m,C as v};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./wire-codec-CH4vwdFT.mjs";import"./bindOrm-D_hFUjmr.mjs";import{f as t,g as m,i as p,b as l,m as d,p as n,d as c,e as h,a as u,r as v}from"./middleware-
|
|
1
|
+
import"./wire-codec-CH4vwdFT.mjs";import"./bindOrm-D_hFUjmr.mjs";import{f as t,g as m,i as p,b as l,m as d,p as n,d as c,e as h,a as u,r as v}from"./middleware-DciZ1Q3A.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,n as permissionName,c as readIdentityRoles,h as resolveCan,u as resolvePolicyAuth,v as rls};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-DciZ1Q3A.mjs";const N=(e,t,o)=>{const a=s=>o.isAllowed("list",s,t)&&o.isAllowed("read",s,t),{get:r,query:b}=e,l={...e},w=s=>s.filter(n=>typeof n.key=="string"&&a(n.key));return typeof r=="function"&&(l.get=async(s,n)=>(s==="_storage"&&o.assertAllowed("read",n,t),r(s,n))),typeof b=="function"&&(l.query=s=>{const n=b(s),{collect:p}=n;return s!=="_storage"||typeof p!="function"?n:{...n,collect:async()=>w(await p())}}),l},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},D=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",D],["getUrl","read"],["head","read"],["store","write"]],M=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},P=(e,t)=>{const o=e.bucketName??"default",{bucket:a}=e;for(const r of new Set(t))if(!(r===o||typeof a=="function"&&M(a,r)))throw new A("INTERNAL",`storageRules: rule for bucket "${r}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${r}" 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 })\`.`)},C=(e,t={})=>{const o=U(t.roles);return async({ctx:a,next:r})=>{const b=await $(a.auth??{},o),l=(c,u,d)=>{const h=e.filter(i=>i.on===c&&i.bucket===d);if(h.length===0)return!0;const f={auth:b,ctx:a,key:u};return h.some(i=>S(i.prefix,u)&&i.when(f)===!0)},w=(c,u,d)=>{if(!l(c,u,d))throw new A("FORBIDDEN",`storage ${c} on "${u}" in bucket "${d}" denied by access rule`)},s=c=>{const u=c.bucketName??"default",d={bucketName:u};for(const[f,i]of E){const k=c[f];typeof k=="function"&&(d[f]=(...y)=>{const R=typeof y[0]=="string"?y[0]:"",v=typeof i=="function"?i(y):i;return w(v,R,u),k(...y)})}const{bucket:h}=c;return typeof h=="function"&&(d.bucket=f=>s(h(f))),d},n=a.storage;if(n===void 0)return r();P(n,e.map(c=>c.bucket));const p={storage:s(n)},g=a.db,m=g?.system;return g!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...g,system:N(m,n.bucketName??"default",{assertAllowed:w,isAllowed:l})}),r({ctx:p})}};export{C as storageRules};
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -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-
|
|
1
|
+
import{i as y,d as P,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-DciZ1Q3A.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
|
@@ -888,6 +888,29 @@ interface DatabaseReader {
|
|
|
888
888
|
*/
|
|
889
889
|
normalizeId: <T extends string>(tableName: T, id: string) => Id<T> | null;
|
|
890
890
|
query: (tableName: string) => TableReader;
|
|
891
|
+
/**
|
|
892
|
+
* Walk the relation graph out of one row: follow the foreign keys the
|
|
893
|
+
* schema's `v.id("target")` columns already declare, breadth-first, and
|
|
894
|
+
* return each reached row with its `depth`, the edge names walked to reach
|
|
895
|
+
* it (`path`), the ids along the way (`pathIds`), and a depth-decaying
|
|
896
|
+
* `score`.
|
|
897
|
+
*
|
|
898
|
+
* This is the read a keyword or vector search cannot do: "everything
|
|
899
|
+
* connected to this customer" is a property of the edges, not of the text.
|
|
900
|
+
* Depth 1 (the default) is the direct neighbourhood; a multi-hop expansion
|
|
901
|
+
* is the same call with a higher `depth`.
|
|
902
|
+
*
|
|
903
|
+
* ```ts
|
|
904
|
+
* const { nodes } = await ctx.db.related({ table: "customers", id }, { depth: 2 });
|
|
905
|
+
* ```
|
|
906
|
+
*
|
|
907
|
+
* Every hop is a normal `ctx.db` read, so row-level security, column
|
|
908
|
+
* masking, soft-delete scoping and subscription dependency tracking all
|
|
909
|
+
* apply per hop. `depth` is capped at 4 and `limit` at 200; a
|
|
910
|
+
* `v.array(v.id(...))` column is followed outward only (there is no
|
|
911
|
+
* array-containment filter to find its holders with).
|
|
912
|
+
*/
|
|
913
|
+
related: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
|
|
891
914
|
/**
|
|
892
915
|
* Best-effort, read-only reader over Lunora's system tables
|
|
893
916
|
* (`_scheduled_functions`, `_storage`). Eventually consistent and **not**
|
|
@@ -926,6 +949,76 @@ interface PaginationResult<T = Record<string, unknown>> {
|
|
|
926
949
|
*/
|
|
927
950
|
splitCursor?: null | string;
|
|
928
951
|
}
|
|
952
|
+
/** Which way foreign-key edges are followed by {@link DatabaseReader.related}. */
|
|
953
|
+
type RelatedDirection = "both" | "in" | "out";
|
|
954
|
+
/** An explicit `{ table, id }` start node for {@link DatabaseReader.related}. */
|
|
955
|
+
interface RelatedStartReference {
|
|
956
|
+
id: string;
|
|
957
|
+
table: string;
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Where a traversal starts: a loaded document (recognised by its `_id`, whose
|
|
961
|
+
* table the reader resolves), or an explicit `{ table, id }`.
|
|
962
|
+
*
|
|
963
|
+
* The document arm requires `_id`, which is what makes the two arms actually
|
|
964
|
+
* distinguishable: against a bare `Record<string, unknown>` the union collapses
|
|
965
|
+
* — `{ table, id }` is assignable to it — so a misspelled `{ tabel, id }` used
|
|
966
|
+
* to type-check and fail only at runtime.
|
|
967
|
+
*/
|
|
968
|
+
type RelatedStart = (Record<string, unknown> & {
|
|
969
|
+
_id: string;
|
|
970
|
+
}) | RelatedStartReference;
|
|
971
|
+
/** Options for {@link DatabaseReader.related}. */
|
|
972
|
+
interface RelatedOptions {
|
|
973
|
+
/** Opaque cursor from a prior page's `continueCursor`; `null`/omitted starts at the first page. */
|
|
974
|
+
cursor?: null | string;
|
|
975
|
+
/**
|
|
976
|
+
* How many hops to expand. `1` (the default) is the direct neighbourhood.
|
|
977
|
+
* Must be an integer in `1 … 4`; anything else is refused rather than
|
|
978
|
+
* clamped, because a silently-shortened walk looks like a graph with fewer
|
|
979
|
+
* edges than it has.
|
|
980
|
+
*/
|
|
981
|
+
depth?: number;
|
|
982
|
+
/**
|
|
983
|
+
* Which way foreign keys are followed. `"out"` follows the ids the start
|
|
984
|
+
* row HOLDS (ticket → customer), `"in"` the rows that point AT it (customer
|
|
985
|
+
* → tickets), `"both"` (the default) does both.
|
|
986
|
+
*/
|
|
987
|
+
direction?: RelatedDirection;
|
|
988
|
+
/**
|
|
989
|
+
* Restrict the walk to these edge-type names — `"<table>.<column>"`, e.g.
|
|
990
|
+
* `"tickets.customerId"`. Omitted ⇒ every `v.id(...)` column the schema
|
|
991
|
+
* declares. An unknown name is refused, so a typo cannot silently widen the
|
|
992
|
+
* traversal.
|
|
993
|
+
*/
|
|
994
|
+
edges?: ReadonlyArray<string>;
|
|
995
|
+
/** Maximum nodes per page. Default 50, capped at 200. */
|
|
996
|
+
limit?: number;
|
|
997
|
+
}
|
|
998
|
+
/** One row reached by {@link DatabaseReader.related}, with how it was reached. */
|
|
999
|
+
interface RelatedNode<T = Record<string, unknown>> {
|
|
1000
|
+
/** Hops from the start node; always `>= 1`. */
|
|
1001
|
+
depth: number;
|
|
1002
|
+
/** The reached row. */
|
|
1003
|
+
document: T;
|
|
1004
|
+
/** Edge-type names walked from the start node to this one, in order. Length equals `depth`. */
|
|
1005
|
+
path: ReadonlyArray<string>;
|
|
1006
|
+
/** Document ids from the start node to this one inclusive. Length equals `depth + 1`. */
|
|
1007
|
+
pathIds: ReadonlyArray<string>;
|
|
1008
|
+
/** Depth-decaying relevance: `1` at depth 1, halving each hop (`0.5 ** (depth - 1)`). */
|
|
1009
|
+
score: number;
|
|
1010
|
+
/** The table {@link RelatedNode.document} lives in. */
|
|
1011
|
+
table: string;
|
|
1012
|
+
}
|
|
1013
|
+
/** One page of a {@link DatabaseReader.related} traversal — the {@link PaginationResult} envelope, with `nodes` instead of `page`. */
|
|
1014
|
+
interface RelatedPage<T = Record<string, unknown>> {
|
|
1015
|
+
/** Cursor to pass back for the next page, or `null` once `isDone`. */
|
|
1016
|
+
continueCursor: null | string;
|
|
1017
|
+
/** `true` when this page is the last one. */
|
|
1018
|
+
isDone: boolean;
|
|
1019
|
+
/** The reached nodes, nearest first. */
|
|
1020
|
+
nodes: RelatedNode<T>[];
|
|
1021
|
+
}
|
|
929
1022
|
/**
|
|
930
1023
|
* The fluent `ctx.db.query(table)` reader. Generic over the document type
|
|
931
1024
|
* `Row` so the generated `ctx.db` can bind it to `Doc<table>` (the chain and
|
|
@@ -2117,7 +2210,7 @@ interface SpanOptions {
|
|
|
2117
2210
|
* @param name Span name, e.g. `"stripe.charge"`. Prefer a low-cardinality name
|
|
2118
2211
|
* and put the varying part in `attributes` — a name built from an id makes every
|
|
2119
2212
|
* span its own group in a collector.
|
|
2120
|
-
* @param
|
|
2213
|
+
* @param function_ The body to time, receiving a tracer bound to this span for any
|
|
2121
2214
|
* nested spans and the enclosing span's {@link SpanHandle} for post-hoc
|
|
2122
2215
|
* attributes. May be sync or async; the result is awaited.
|
|
2123
2216
|
* @param attributes Either a plain attribute bag to stamp on the span at start
|
|
@@ -2275,7 +2368,8 @@ interface QueryCtx {
|
|
|
2275
2368
|
/**
|
|
2276
2369
|
* Wall-clock time (epoch ms) the function began, captured once so the whole
|
|
2277
2370
|
* handler sees a single stable value. Query/mutation handlers must be
|
|
2278
|
-
* deterministic — they may be re-run on
|
|
2371
|
+
* deterministic — they may be re-run on subscription re-evaluation (an OCC
|
|
2372
|
+
* conflict surfaces as a `409` to the caller, not an internal retry) — so
|
|
2279
2373
|
* read time through `ctx.now` instead of `Date.now()` (the latter is flagged
|
|
2280
2374
|
* by the `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
|
|
2281
2375
|
*/
|
|
@@ -2330,9 +2424,10 @@ interface MutationCtx {
|
|
|
2330
2424
|
/**
|
|
2331
2425
|
* Wall-clock time (epoch ms) the function began, captured once so the whole
|
|
2332
2426
|
* handler sees a single stable value. Mutation handlers must be deterministic
|
|
2333
|
-
* —
|
|
2334
|
-
*
|
|
2335
|
-
*
|
|
2427
|
+
* — an OCC conflict surfaces as a `409` to the caller rather than an internal
|
|
2428
|
+
* retry, but a caller's own retry is a fresh dispatch — so read time through
|
|
2429
|
+
* `ctx.now` instead of `Date.now()` (the latter is flagged by the
|
|
2430
|
+
* `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
|
|
2336
2431
|
*/
|
|
2337
2432
|
readonly now: number;
|
|
2338
2433
|
/**
|
|
@@ -2431,4 +2526,4 @@ interface ActionCtx {
|
|
|
2431
2526
|
*/
|
|
2432
2527
|
type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
|
|
2433
2528
|
declare const anyApi: AnyApi;
|
|
2434
|
-
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 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 StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, 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 WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|
|
2529
|
+
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 StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, 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 WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|
package/dist/types.d.ts
CHANGED
|
@@ -888,6 +888,29 @@ interface DatabaseReader {
|
|
|
888
888
|
*/
|
|
889
889
|
normalizeId: <T extends string>(tableName: T, id: string) => Id<T> | null;
|
|
890
890
|
query: (tableName: string) => TableReader;
|
|
891
|
+
/**
|
|
892
|
+
* Walk the relation graph out of one row: follow the foreign keys the
|
|
893
|
+
* schema's `v.id("target")` columns already declare, breadth-first, and
|
|
894
|
+
* return each reached row with its `depth`, the edge names walked to reach
|
|
895
|
+
* it (`path`), the ids along the way (`pathIds`), and a depth-decaying
|
|
896
|
+
* `score`.
|
|
897
|
+
*
|
|
898
|
+
* This is the read a keyword or vector search cannot do: "everything
|
|
899
|
+
* connected to this customer" is a property of the edges, not of the text.
|
|
900
|
+
* Depth 1 (the default) is the direct neighbourhood; a multi-hop expansion
|
|
901
|
+
* is the same call with a higher `depth`.
|
|
902
|
+
*
|
|
903
|
+
* ```ts
|
|
904
|
+
* const { nodes } = await ctx.db.related({ table: "customers", id }, { depth: 2 });
|
|
905
|
+
* ```
|
|
906
|
+
*
|
|
907
|
+
* Every hop is a normal `ctx.db` read, so row-level security, column
|
|
908
|
+
* masking, soft-delete scoping and subscription dependency tracking all
|
|
909
|
+
* apply per hop. `depth` is capped at 4 and `limit` at 200; a
|
|
910
|
+
* `v.array(v.id(...))` column is followed outward only (there is no
|
|
911
|
+
* array-containment filter to find its holders with).
|
|
912
|
+
*/
|
|
913
|
+
related: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
|
|
891
914
|
/**
|
|
892
915
|
* Best-effort, read-only reader over Lunora's system tables
|
|
893
916
|
* (`_scheduled_functions`, `_storage`). Eventually consistent and **not**
|
|
@@ -926,6 +949,76 @@ interface PaginationResult<T = Record<string, unknown>> {
|
|
|
926
949
|
*/
|
|
927
950
|
splitCursor?: null | string;
|
|
928
951
|
}
|
|
952
|
+
/** Which way foreign-key edges are followed by {@link DatabaseReader.related}. */
|
|
953
|
+
type RelatedDirection = "both" | "in" | "out";
|
|
954
|
+
/** An explicit `{ table, id }` start node for {@link DatabaseReader.related}. */
|
|
955
|
+
interface RelatedStartReference {
|
|
956
|
+
id: string;
|
|
957
|
+
table: string;
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Where a traversal starts: a loaded document (recognised by its `_id`, whose
|
|
961
|
+
* table the reader resolves), or an explicit `{ table, id }`.
|
|
962
|
+
*
|
|
963
|
+
* The document arm requires `_id`, which is what makes the two arms actually
|
|
964
|
+
* distinguishable: against a bare `Record<string, unknown>` the union collapses
|
|
965
|
+
* — `{ table, id }` is assignable to it — so a misspelled `{ tabel, id }` used
|
|
966
|
+
* to type-check and fail only at runtime.
|
|
967
|
+
*/
|
|
968
|
+
type RelatedStart = (Record<string, unknown> & {
|
|
969
|
+
_id: string;
|
|
970
|
+
}) | RelatedStartReference;
|
|
971
|
+
/** Options for {@link DatabaseReader.related}. */
|
|
972
|
+
interface RelatedOptions {
|
|
973
|
+
/** Opaque cursor from a prior page's `continueCursor`; `null`/omitted starts at the first page. */
|
|
974
|
+
cursor?: null | string;
|
|
975
|
+
/**
|
|
976
|
+
* How many hops to expand. `1` (the default) is the direct neighbourhood.
|
|
977
|
+
* Must be an integer in `1 … 4`; anything else is refused rather than
|
|
978
|
+
* clamped, because a silently-shortened walk looks like a graph with fewer
|
|
979
|
+
* edges than it has.
|
|
980
|
+
*/
|
|
981
|
+
depth?: number;
|
|
982
|
+
/**
|
|
983
|
+
* Which way foreign keys are followed. `"out"` follows the ids the start
|
|
984
|
+
* row HOLDS (ticket → customer), `"in"` the rows that point AT it (customer
|
|
985
|
+
* → tickets), `"both"` (the default) does both.
|
|
986
|
+
*/
|
|
987
|
+
direction?: RelatedDirection;
|
|
988
|
+
/**
|
|
989
|
+
* Restrict the walk to these edge-type names — `"<table>.<column>"`, e.g.
|
|
990
|
+
* `"tickets.customerId"`. Omitted ⇒ every `v.id(...)` column the schema
|
|
991
|
+
* declares. An unknown name is refused, so a typo cannot silently widen the
|
|
992
|
+
* traversal.
|
|
993
|
+
*/
|
|
994
|
+
edges?: ReadonlyArray<string>;
|
|
995
|
+
/** Maximum nodes per page. Default 50, capped at 200. */
|
|
996
|
+
limit?: number;
|
|
997
|
+
}
|
|
998
|
+
/** One row reached by {@link DatabaseReader.related}, with how it was reached. */
|
|
999
|
+
interface RelatedNode<T = Record<string, unknown>> {
|
|
1000
|
+
/** Hops from the start node; always `>= 1`. */
|
|
1001
|
+
depth: number;
|
|
1002
|
+
/** The reached row. */
|
|
1003
|
+
document: T;
|
|
1004
|
+
/** Edge-type names walked from the start node to this one, in order. Length equals `depth`. */
|
|
1005
|
+
path: ReadonlyArray<string>;
|
|
1006
|
+
/** Document ids from the start node to this one inclusive. Length equals `depth + 1`. */
|
|
1007
|
+
pathIds: ReadonlyArray<string>;
|
|
1008
|
+
/** Depth-decaying relevance: `1` at depth 1, halving each hop (`0.5 ** (depth - 1)`). */
|
|
1009
|
+
score: number;
|
|
1010
|
+
/** The table {@link RelatedNode.document} lives in. */
|
|
1011
|
+
table: string;
|
|
1012
|
+
}
|
|
1013
|
+
/** One page of a {@link DatabaseReader.related} traversal — the {@link PaginationResult} envelope, with `nodes` instead of `page`. */
|
|
1014
|
+
interface RelatedPage<T = Record<string, unknown>> {
|
|
1015
|
+
/** Cursor to pass back for the next page, or `null` once `isDone`. */
|
|
1016
|
+
continueCursor: null | string;
|
|
1017
|
+
/** `true` when this page is the last one. */
|
|
1018
|
+
isDone: boolean;
|
|
1019
|
+
/** The reached nodes, nearest first. */
|
|
1020
|
+
nodes: RelatedNode<T>[];
|
|
1021
|
+
}
|
|
929
1022
|
/**
|
|
930
1023
|
* The fluent `ctx.db.query(table)` reader. Generic over the document type
|
|
931
1024
|
* `Row` so the generated `ctx.db` can bind it to `Doc<table>` (the chain and
|
|
@@ -2117,7 +2210,7 @@ interface SpanOptions {
|
|
|
2117
2210
|
* @param name Span name, e.g. `"stripe.charge"`. Prefer a low-cardinality name
|
|
2118
2211
|
* and put the varying part in `attributes` — a name built from an id makes every
|
|
2119
2212
|
* span its own group in a collector.
|
|
2120
|
-
* @param
|
|
2213
|
+
* @param function_ The body to time, receiving a tracer bound to this span for any
|
|
2121
2214
|
* nested spans and the enclosing span's {@link SpanHandle} for post-hoc
|
|
2122
2215
|
* attributes. May be sync or async; the result is awaited.
|
|
2123
2216
|
* @param attributes Either a plain attribute bag to stamp on the span at start
|
|
@@ -2275,7 +2368,8 @@ interface QueryCtx {
|
|
|
2275
2368
|
/**
|
|
2276
2369
|
* Wall-clock time (epoch ms) the function began, captured once so the whole
|
|
2277
2370
|
* handler sees a single stable value. Query/mutation handlers must be
|
|
2278
|
-
* deterministic — they may be re-run on
|
|
2371
|
+
* deterministic — they may be re-run on subscription re-evaluation (an OCC
|
|
2372
|
+
* conflict surfaces as a `409` to the caller, not an internal retry) — so
|
|
2279
2373
|
* read time through `ctx.now` instead of `Date.now()` (the latter is flagged
|
|
2280
2374
|
* by the `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
|
|
2281
2375
|
*/
|
|
@@ -2330,9 +2424,10 @@ interface MutationCtx {
|
|
|
2330
2424
|
/**
|
|
2331
2425
|
* Wall-clock time (epoch ms) the function began, captured once so the whole
|
|
2332
2426
|
* handler sees a single stable value. Mutation handlers must be deterministic
|
|
2333
|
-
* —
|
|
2334
|
-
*
|
|
2335
|
-
*
|
|
2427
|
+
* — an OCC conflict surfaces as a `409` to the caller rather than an internal
|
|
2428
|
+
* retry, but a caller's own retry is a fresh dispatch — so read time through
|
|
2429
|
+
* `ctx.now` instead of `Date.now()` (the latter is flagged by the
|
|
2430
|
+
* `nondeterministic_query_mutation` advisor). Actions may use `Date.now()`.
|
|
2336
2431
|
*/
|
|
2337
2432
|
readonly now: number;
|
|
2338
2433
|
/**
|
|
@@ -2431,4 +2526,4 @@ interface ActionCtx {
|
|
|
2431
2526
|
*/
|
|
2432
2527
|
type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
|
|
2433
2528
|
declare const anyApi: AnyApi;
|
|
2434
|
-
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 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 StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, 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 WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|
|
2529
|
+
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 StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, 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 WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.122",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -66,9 +66,10 @@
|
|
|
66
66
|
"access": "public"
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
70
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
71
|
-
"@lunora/
|
|
69
|
+
"@lunora/errors": "1.0.0-alpha.36",
|
|
70
|
+
"@lunora/scheduler": "1.0.0-alpha.71",
|
|
71
|
+
"@lunora/shard-engine": "1.0.0-alpha.64",
|
|
72
|
+
"@lunora/values": "1.0.0-alpha.46",
|
|
72
73
|
"drizzle-orm": "^0.45.2",
|
|
73
74
|
"hono": "^4.13.7"
|
|
74
75
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const l=new WeakMap,i=f=>{const a=[],o=n=>{const e=n??{},s={...e,deleteAfterCommit:r=>{a.push({key:r,storage:e})}};return Object.setPrototypeOf(s,Object.getPrototypeOf(e)),typeof e.bucket=="function"&&(s.bucket=r=>o(e.bucket?.(r))),l.set(s,a),s};return o(f)},u=async f=>{const{log:a,storage:o}=f??{},n=typeof o=="object"&&o!==null?l.get(o):void 0;if(!n||n.length===0)return{attempted:0,failures:[]};const e=n.splice(0),r=(await Promise.allSettled(e.map(async({key:t,storage:c})=>{if(typeof c.delete!="function")throw new TypeError("ctx.storage: no storage configured, so the object was not deleted");await c.delete(t)}))).flatMap((t,c)=>t.status==="rejected"?[{error:t.reason,key:e[c]?.key??""}]:[]);for(const t of r)a?.warn("ctx.storage.deleteAfterCommit: delete failed, object leaked",{error:String(t.error),key:t.key});return{attempted:e.length,failures:r}};export{u as flushDeferredDeletes,i as withDeferredDeletes};
|
|
@@ -1 +0,0 @@
|
|
|
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-BZcRFqUp.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,f)=>{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,f)}catch{return null}},u=(e,i,f)=>{const d={...e};for(const[y,g]of Object.entries(i))y in d&&(d[y]=V(g,e[y],{...f,column:y,row:e}));return d},j=(e,i,f)=>({...e,page:e.page.map(d=>u(d,i,f))}),D=(e,i,f,d)=>{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",`${d}() filtering "${f}" by masked column "${w}" is not supported`)},X=(e,i,f,d)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,f)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},k=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=d?.[r]?.[o]?.[n];if(!c)return;const a=c.find(E=>E in s);if(a!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${a}" — use an index whose declared fields are all unmasked, or unmask the column`)},p=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,f)},collect:async()=>(await r.collect()).map(s=>u(s,n,f)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=u(s.document,n,f);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>p(r.filter(s=>o(u(s,n,f))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,f):null},order:o=>p(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,f),take:async o=>(await r.take(o)).map(c=>u(c,n,f)),unique:async()=>{const o=await r.unique();return o?u(o,n,f):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),D(s,n,t,"withIndex"),p(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),p(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),p(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const a=await e.lookupById(r,n);if(a)return{row:a.row,tableName:i.has(a.tableName)?a.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 a=>(await e.findFirst(a,{limit:1,where:{_id:r}}))?._id===r?a:void 0));return{row:t,tableName:c.find(a=>a!==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,a=`${r}.${o}`;R(c.where,A,a,t),F(a,c.orderBy,A,t),$(a,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,l(n)),o=i.get(r);return t&&o?u(t,o,f):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,f):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,l(n)),o=i.get(r);return o?j(t,o,f):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:u(t,s,f)},async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,f):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?p(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),k(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,f):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(a=>({...a,doc:u(a.doc,c,f)}))}: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 f=new Map(Object.entries(e)),d=L(i.roles),y=async({ctx:w,next:l})=>{const k={auth:await z(w.auth??{},d),ctx:w};if(i.bypass?.(k)===!0)return l();const p=X(w.db,f,k,i.indexFields),O={db:p},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(p)),l({ctx:O})},g=new Map;for(const[w,l]of f)g.set(w,new Set(Object.keys(l)));return Q(y,{columns:g})};export{b as mask};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as W}from"@lunora/errors";import{i as j}from"./wire-codec-CH4vwdFT.mjs";import{bindTableFacade as x,bindOrm as V}from"./bindOrm-D_hFUjmr.mjs";import{t as ee}from"./policy-tag-V0lqFzgS.mjs";import{deny as te}from"./allowAll-DkRAgItV.mjs";const re=["every","is","isNot","none","some"],ne=new Set(re),se=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ne.has(n))},N=(e,r,n)=>r?{[e]:n(r)}:{},oe=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,R=1,k=e=>e?R:B,p=(e,r)=>e<r?e:r,ie=(e,r)=>e>r?e:r,Q=e=>e===v?v:k(e===B),q=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,D=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},ae={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},ce=(e,r,n)=>{let i=R;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(D(e,c,h),!q(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=ae[c];i=p(i,k(q(r)&&f(r,h)))}}return i},Y=(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},K=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?R:r.some(n=>S(n))?v:B,le=(e,r,n)=>{let i=R;if("in"in n&&(i=p(i,K(r,Y(e,"in",n.in)))),"notIn"in n&&(i=p(i,Q(K(r,Y(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;D(e,"contains",c),i=S(r)?p(i,v):p(i,k(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,k(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?k(n===S(e)):S(e)?v:k(n===(e===r)),fe=(e,r,n)=>{let i=R;return"eq"in n&&(D(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(D(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},ue=(e,r,n)=>p(fe(e,r,n),p(le(e,r,n),ce(e,r,n))),de=(e,r,n,i)=>{if(r==="NOT")return Q(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?R:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):ie(c,f)}return c},z=e=>e==="AND"||e==="OR"||e==="NOT",he=e=>j(e)&&Object.keys(e).every(r=>oe.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return z(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):se(n)}),H=(e,r)=>{let n=R;for(const i of Object.keys(r)){const c=r[i];if(z(i)){n=p(n,de(e,i,c,H));continue}const h=e[i];if(he(c)){n=p(n,ue(i,h,c));continue}D(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>H(e,r)===R,G=500,T=(e,r,n)=>{const i=r??G;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})},ye=te(),we=Symbol.for("lunora.ctxdb.rls-unwrap"),X=Symbol.for("lunora.rls.wrapped-chain"),pe=e=>e[X],ge=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},We=(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?ye:n.length===1?n[0]:{OR:n}},Oe=(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)},be=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||Oe(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)},Re=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!be(h,n,i)))return!1;return c},Ae=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ee=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),Be=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>Ae.has(n)&&Ee(n,e[n]))},ve=e=>e===void 0?{}:j(e)&&Be(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Se=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},b=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,_e=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Te=(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 d=y.perTable.get(t);if(!d||d.length===0||!d.some(m=>m.on==="read"))continue;a=!0;const u=We(d,y.context);u!==void 0&&o.push(u)}const l={baseWhere:Se(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&&!Re(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 u=await r.lookupById(t,s);if(u)return{row:u.row,tableName:c.has(u.tableName)?u.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(u=>c.has(u)),d=await Promise.all(y.map(async u=>(await r.findFirst(u,{limit:1,where:{_id:t}}))?._id===t?u:void 0));return{row:a,tableName:d.find(u=>u!==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 d=await U(t,l,y);if(!d)return o(e);const u=a?a(d.row):void 0;if(!_(d.tableName,s,d.row,u))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`)},M=e.rankBefore,P=e.rankPageRows,I={...e,async count(t,s){const{baseWhere:o}=f(t),a=ve(s);return w(t).count(t,{...a,baseWhere:b(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??G),{baseWhere:a}=f(t);let l=0;for(;;){const d=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(u=>String(u._id));if(d.length===0)break;for(const u of d)await O(u,"delete",m=>m.delete(u,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(d.length<o)break}return{deleted:l}},async deleteMany(t,s,o){T(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:b(s,a),relationBaseWhere:g})).page.map(d=>String(d._id));T(y.length,o?.limit,"deleteWhere");for(const d of y)await O(d,"delete",u=>u.delete(d),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:b(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:b(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:b(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(T(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(T(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){T(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:b(s.where,a),relationBaseWhere:g})).page.map(d=>({id:String(d._id),patch:s.patch}));return T(y.length,o?.limit,"patchWhere"),I.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(a=>L(a,s)):o},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:b(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:b(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})},...N("rankBefore",M,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...N("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},Z=I;if(c.size>0)for(const[t,s]of Object.entries(e))_e(s)&&(Z[t]=x(I,t));return Object.defineProperty(I,X,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),I},J=e=>typeof e=="string"?e:e.name,ke=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>J(i))));return r},Ie=(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(J(i))},De=["roles","role"],Me=e=>{for(const r of De){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[]},Pe=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...Me(n),...e.roles??[]])];return{can:Ie(i,r),identity:n,roles:i,userId:e.userId??null}},$e=(e,r={})=>{const n=e,i=ge(n),c=ke(r.roles);return ee(async({ctx:f,next:_})=>{const w={auth:await Pe(f.auth??{},c),ctx:f},g=f.db,A=pe(g),U=A?.base??g,O=A?.raw??g[we]??g,E=Te(U,O,[...A?.steps??[],{context:w,perTable:i}]),M={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(M.orm=V(E)),_({ctx:M})},[{policies:n,roles:r.roles??[]}])};export{Pe as a,_e as b,se as c,Me as d,Ie as e,We as f,Re as g,ke as i,L as m,N as o,J as p,$e as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{c as K}from"./compose-middleware-MCpZZKh7.mjs";import{v as R}from"@lunora/values";const j=["de","en","es","fr","it","nl","none","pt"],_=["native","portable"],z=e=>_.includes(e),H=e=>j.includes(e),q=e=>{if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?q(t):e.kind},B=16,Q={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),X=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),F=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},le=e=>{const t={...e},n=[],r=[],o=[],d=[],u={},l=[],f={},m=X(),b=[];let y={kind:"root"},$=!1,N=!1,k=!1,T=!1,L,M,A,O;const c={aggregateIndex(i,a){const h=a?.op??"count";if(h!=="count"&&!a?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${h}" requires a "field"`);return n.push({by:a?.by,field:a?.field,name:i,on:"",op:h,where:a?.where}),c},get aggregateIndexes(){return n},get externalSource(){return O},commitOrdered(){return $=!0,c},get commitOrderedMode(){return $},externallyManaged(){return N=!0,c},geoIndex(i,a){return r.push({field:a.field,name:i,precision:a.precision}),c},get geoIndexes(){return r},global(i){return y={backend:i?.backend??"d1",kind:"global"},c},get isExternallyManaged(){return N},get isPublic(){return T},index(i,a,h){return o.push({fields:a,name:i,unique:h?.unique??!1}),c},get indexes(){return o},memory(){return k=!0,c},get memoryMode(){return k},ownedBy(i){return L=i,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(i,a){return d.push({name:i,on:"",partitionBy:a.partitionBy,sortBy:F(i,a.sortBy),where:a.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(i){return Object.assign(u,i(Q)),c},searchIndex(i,a){if(a.filterFields&&a.filterFields.length>B)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(B)} filterFields are supported (got ${String(a.filterFields.length)})`);const{language:h}=a;if(h!==void 0&&!H(h))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${h}" (supported: ${j.join(", ")})`);const{strategy:v}=a;if(v!==void 0&&!z(v))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${v}" (supported: ${_.join(", ")})`);return l.push({field:a.field,filterFields:a.filterFields,language:a.language,name:i,staged:a.staged,strategy:a.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(i){return y={field:i,kind:"shardBy"},c},get shardMode(){return y},get softDeleteMode(){return M},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return O=i,N=!0,c},softDelete(i){const a=i?.field??"deletedAt";return M={field:a},a in t||(t[a]=R.optional(R.number().nullable())),c},get triggerMap(){return f},triggers(i){return Object.assign(f,i(m)),c},ttl(i,a){return A={after:a?.after,field:i},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(i,a){return b.push({dimensions:a.dimensions,embed:a.embed,field:i,metadata:a.metadata,metric:a.metric,name:a.index}),c}};return c},ce=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),ue=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},fe=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:F(e,t.sortBy),where:t.where}),x=e=>({...e,extend(t){return x(C(e,t))},jurisdiction(t){return x(e)},rls(t){return x({...e,rlsMode:t})}}),U=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},V=(e,t,n)=>{for(const r of Object.values(t)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);o.aggregateIndexes.push(r)}for(const r of Object.values(n)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);o.rankIndexes.push(r)}},Y=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},G=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=Y(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},J=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);G(t,r)}}},W=["_commitSeq","_creationTime","_id"],D="_commitSeq",Z=new Set(W),w=(e,t,n,r)=>{if(!(Z.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},p=(e,t,n,r)=>{const o=new Set;for(const d of n){if(o.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);o.add(d.name),r(d)}},P=e=>{for(const[t,n]of Object.entries(e))p(t,"index",n.indexes,r=>{for(const o of r.fields)w(t,r.name,o,n)}),p(t,"rank index",n.rankIndexes,r=>{for(const o of r.sortBy)w(t,r.name,o.field,n);for(const o of r.partitionBy??[])w(t,r.name,o,n)}),p(t,"geo index",n.geoIndexes,r=>{w(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const o of e)r[t(o)]=n(o);return r},ee=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},me=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const o=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,ee);(o||d||u)&&(t[n]={...o?{geo:o}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},te=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const o=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(o!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${o}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},ne=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,o]of Object.entries(n.shape))if(q(o)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},re=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(D))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${D}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},he=(e,t={},n={},r={})=>(U(e),V(e,n,r),J(e),re(e),ne(e),te(e),P(e),x({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,S=(e,t,n)=>n.has(e)?I(t,e):e,ae=(e,t,n,r)=>{const o=I(t,r),d=m=>m===""?o:S(m,t,n),u={};for(const[m,b]of Object.entries(e.relationMap))u[m]={...b,table:S(b.table,t,n)};const l=e.aggregateIndexes.map(m=>({...m,on:d(m.on)})),f=e.rankIndexes.map(m=>({...m,on:d(m.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},ge=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},oe=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),be=(e,t)=>({...oe(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),C=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),o={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=I(n,u);if(Object.hasOwn(o,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);o[f]=ae(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=I(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:S(l.table,n,r)}}return P(o),{rlsMode:e.rlsMode,tables:o,vectorIndexes:d}},we=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=C(n,r.extension));return n},xe=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return K(t)};export{be as a,oe as b,xe as c,ue as d,fe as e,he as f,ge as g,le as h,ce as i,me as j,we as k,C as m,P as v};
|