@lunora/server 1.0.0-alpha.276 → 1.0.0-alpha.277
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/dist/data-model.d.mts +108 -108
- package/dist/data-model.d.ts +108 -108
- package/dist/in-process.d.mts +1 -1
- package/dist/in-process.d.ts +1 -1
- package/dist/index.d.mts +8 -8
- package/dist/index.d.ts +8 -8
- package/dist/index.mjs +1 -1
- package/dist/otel.d.mts +1 -1
- package/dist/otel.d.ts +1 -1
- package/dist/packem_shared/assertShapesDeclareReadPolicies-C09SMvM4.mjs +1 -0
- package/dist/packem_shared/{defineShape-CAIsX21I.mjs → defineShape-H-0IbZlb.mjs} +1 -1
- package/dist/packem_shared/mask-DHJtsP7t.mjs +1 -0
- package/dist/packem_shared/middleware-CHYtnvZP.mjs +1 -0
- package/dist/packem_shared/{rls-C74k6tmE.mjs → rls-CvWnjgtq.mjs} +1 -1
- package/dist/packem_shared/{storageRules-BZgB67oS.mjs → storageRules-BVIXkoRg.mjs} +1 -1
- package/dist/packem_shared/{types.d-MMTv520I.d.mts → types.d-BTY_1dJ8.d.mts} +1 -1
- package/dist/packem_shared/{types.d-MMTv520I.d.ts → types.d-BTY_1dJ8.d.ts} +1 -1
- package/dist/rls/testing.mjs +1 -1
- package/dist/types.d.mts +1 -1
- package/dist/types.d.ts +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/assertShapesDeclareReadPolicies-CWrMYcqw.mjs +0 -1
- package/dist/packem_shared/mask--ZXtzCj7.mjs +0 -1
- package/dist/packem_shared/middleware-CdoC33P7.mjs +0 -1
package/dist/data-model.d.mts
CHANGED
|
@@ -20,23 +20,6 @@
|
|
|
20
20
|
* so this module needs no reference to the project-local `OneRelation` /
|
|
21
21
|
* `ManyRelation` aliases the codegen still emits.
|
|
22
22
|
*/
|
|
23
|
-
/** A branded id for table `TName`. Structurally a `string` at runtime. */
|
|
24
|
-
type Id<TName extends string> = string & {
|
|
25
|
-
readonly __table: TName;
|
|
26
|
-
};
|
|
27
|
-
/** Field-level operators for the typed `where` DSL (see `@lunora/do`'s compiler). */
|
|
28
|
-
interface WhereOperators<T> {
|
|
29
|
-
contains?: string;
|
|
30
|
-
eq?: T;
|
|
31
|
-
gt?: T;
|
|
32
|
-
gte?: T;
|
|
33
|
-
in?: T[];
|
|
34
|
-
isNull?: boolean;
|
|
35
|
-
lt?: T;
|
|
36
|
-
lte?: T;
|
|
37
|
-
ne?: T;
|
|
38
|
-
notIn?: T[];
|
|
39
|
-
}
|
|
40
23
|
/**
|
|
41
24
|
* A value stored as a plain JS object: not a scalar (an `Id<T>` is a branded string, which is an `object` to
|
|
42
25
|
* TypeScript but has no keys worth offering), an array, a date, bytes, a bigint or a function.
|
|
@@ -66,6 +49,113 @@ type ScalarPaths<Doc> = { [P in ColumnPaths<Doc>]: [DocPathValue<Doc, P>] extend
|
|
|
66
49
|
type PathWhere<Doc, Paths extends string = ScalarPaths<Doc>> = [Paths] extends [never] ? unknown : { [P in Paths]?: DocPathValue<Doc, P> | WhereOperators<DocPathValue<Doc, P>>; };
|
|
67
50
|
/** `patch` keys that set one value inside an object column, keeping its siblings: `{ "profile.plan": "pro" }`. */
|
|
68
51
|
type PathPatch<Doc, Paths extends string = ColumnPaths<Doc>> = [Paths] extends [never] ? unknown : { [P in Paths]?: DocPathValue<Doc, P>; };
|
|
52
|
+
/**
|
|
53
|
+
* The relation-predicate portion of {@link WhereOf}: each declared relation on
|
|
54
|
+
* `T` contributes a kind-dispatched node — `one` → `{ is?; isNot? }`, `many` →
|
|
55
|
+
* `{ some?; none?; every? }` — whose inner type is the target table's own
|
|
56
|
+
* relation-aware `where` (so multi-hop predicates type-check inside-out).
|
|
57
|
+
*/
|
|
58
|
+
type RelationWhere<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = { [K in keyof REL[T]]?: REL[T][K] extends {
|
|
59
|
+
__relationKind: "one";
|
|
60
|
+
__target: infer Target extends keyof DM;
|
|
61
|
+
} ? OneRelationWhere<WhereOf<DM, REL, Target>> : REL[T][K] extends {
|
|
62
|
+
__relationKind: "many";
|
|
63
|
+
__target: infer Target extends keyof DM;
|
|
64
|
+
} ? ManyRelationWhere<WhereOf<DM, REL, Target>> : never; };
|
|
65
|
+
/** The nested `with` sub-argument inside a relation's with-value, or `{}`. */
|
|
66
|
+
type NestedWithArgument<WK> = WK extends {
|
|
67
|
+
with: infer NW;
|
|
68
|
+
} ? NW : {};
|
|
69
|
+
/** The nested `select` tuple inside a relation's with-value, or `undefined` (no projection). */
|
|
70
|
+
type NestedSelectArgument<WK> = WK extends {
|
|
71
|
+
select: infer S;
|
|
72
|
+
} ? S : undefined;
|
|
73
|
+
/**
|
|
74
|
+
* Resolve a single relation descriptor + its with-value to the loaded type,
|
|
75
|
+
* threading the nested `select` tuple into the projected child shape (the 5th
|
|
76
|
+
* `LoadWith` arg) so `with: { author: { select: ["name"] } }` narrows the loaded
|
|
77
|
+
* `author` to the selected columns + system fields.
|
|
78
|
+
*/
|
|
79
|
+
type LoadRelation<DM, REL extends Record<keyof DM, object>, R, WK> = R extends {
|
|
80
|
+
__relationKind: "one";
|
|
81
|
+
__target: infer Target extends keyof DM;
|
|
82
|
+
} ? LoadWith<DM, REL, Target, NestedWithArgument<WK>, NestedSelectArgument<WK>> | null : R extends {
|
|
83
|
+
__relationKind: "many";
|
|
84
|
+
__target: infer Target extends keyof DM;
|
|
85
|
+
} ? LoadWith<DM, REL, Target, NestedWithArgument<WK>, NestedSelectArgument<WK>>[] : never;
|
|
86
|
+
/** The relation keys of `W` that were actually requested (not `false`/`undefined`). */
|
|
87
|
+
type LoadedRelations<DM, REL extends Record<keyof DM, object>, T extends keyof DM, W> = { [K in keyof W as K extends keyof REL[T] ? (W[K] extends false | undefined ? never : K) : never]: K extends keyof REL[T] ? LoadRelation<DM, REL, REL[T][K], W[K]> : never; };
|
|
88
|
+
/** The `_count` projection of `W`, if any. */
|
|
89
|
+
type LoadedCount<W> = W extends {
|
|
90
|
+
_count: infer C;
|
|
91
|
+
} ? {
|
|
92
|
+
_count: { [K in keyof C]: number; };
|
|
93
|
+
} : {};
|
|
94
|
+
/** System columns a `select` projection always retains, so cursors and by-id reuse keep working. */
|
|
95
|
+
type SelectAlwaysKeep<DM, T extends keyof DM> = ("_creationTime" | "_id") & keyof DM[T];
|
|
96
|
+
/**
|
|
97
|
+
* `DM[T]` narrowed to the columns named by a `select` tuple `S` (plus the system
|
|
98
|
+
* fields). `undefined` (the default — no `select`) keeps the full document.
|
|
99
|
+
*/
|
|
100
|
+
type ProjectDoc<DM, T extends keyof DM, S> = S extends ReadonlyArray<infer K> ? (K extends keyof DM[T] ? Pick<DM[T], (K & keyof DM[T]) | SelectAlwaysKeep<DM, T>> : DM[T]) : DM[T];
|
|
101
|
+
/**
|
|
102
|
+
* An atomic update for a number column, applied to the value the row holds when the
|
|
103
|
+
* write runs: `{ increment: 1 }`, `{ decrement: 1 }`, `{ multiply: 2 }`, `{ divide: 2 }`.
|
|
104
|
+
* The column must already hold a finite number; a result that is not finite is rejected.
|
|
105
|
+
*/
|
|
106
|
+
type NumberFieldOperator = {
|
|
107
|
+
decrement: number;
|
|
108
|
+
divide?: never;
|
|
109
|
+
increment?: never;
|
|
110
|
+
multiply?: never;
|
|
111
|
+
} | {
|
|
112
|
+
decrement?: never;
|
|
113
|
+
divide: number;
|
|
114
|
+
increment?: never;
|
|
115
|
+
multiply?: never;
|
|
116
|
+
} | {
|
|
117
|
+
decrement?: never;
|
|
118
|
+
divide?: never;
|
|
119
|
+
increment: number;
|
|
120
|
+
multiply?: never;
|
|
121
|
+
} | {
|
|
122
|
+
decrement?: never;
|
|
123
|
+
divide?: never;
|
|
124
|
+
increment?: never;
|
|
125
|
+
multiply: number;
|
|
126
|
+
};
|
|
127
|
+
/** An atomic update for a boolean column: `{ toggle: true }` flips the stored value. */
|
|
128
|
+
interface BooleanFieldOperator {
|
|
129
|
+
toggle: true;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The operator a column of type `T` takes: arithmetic when `T` is exactly `number` (so a literal union
|
|
133
|
+
* such as `1 | 2` is out — the result could leave the set — and so is `number | string`, which the
|
|
134
|
+
* store does not treat as a number column), `{ toggle: true }` when it is exactly `boolean`.
|
|
135
|
+
*/
|
|
136
|
+
type OperatorFor<T> = [T] extends [number] ? [number] extends [T] ? NumberFieldOperator : never : [T] extends [boolean] ? [boolean] extends [T] ? BooleanFieldOperator : never : never;
|
|
137
|
+
/** The foreign-key columns of a table's to-one relations — the keys a nested `connect` supplies. */
|
|
138
|
+
type OneRelationFields<RelT> = { [K in keyof RelT]: RelT[K] extends {
|
|
139
|
+
__field: infer Field extends string;
|
|
140
|
+
__relationKind: "one";
|
|
141
|
+
} ? Field : never; }[keyof RelT];
|
|
142
|
+
/** A branded id for table `TName`. Structurally a `string` at runtime. */
|
|
143
|
+
type Id<TName extends string> = string & {
|
|
144
|
+
readonly __table: TName;
|
|
145
|
+
};
|
|
146
|
+
/** Field-level operators for the typed `where` DSL (see `@lunora/do`'s compiler). */
|
|
147
|
+
interface WhereOperators<T> {
|
|
148
|
+
contains?: string;
|
|
149
|
+
eq?: T;
|
|
150
|
+
gt?: T;
|
|
151
|
+
gte?: T;
|
|
152
|
+
in?: T[];
|
|
153
|
+
isNull?: boolean;
|
|
154
|
+
lt?: T;
|
|
155
|
+
lte?: T;
|
|
156
|
+
ne?: T;
|
|
157
|
+
notIn?: T[];
|
|
158
|
+
}
|
|
69
159
|
/** A typed `where` tree over a document's columns. */
|
|
70
160
|
type Where<TDocument> = PathWhere<TDocument> & { [K in keyof TDocument]?: TDocument[K] | WhereOperators<TDocument[K]>; } & {
|
|
71
161
|
AND?: Where<TDocument>[];
|
|
@@ -116,19 +206,6 @@ interface ManyRelationWhere<W> {
|
|
|
116
206
|
none?: W;
|
|
117
207
|
some?: W;
|
|
118
208
|
}
|
|
119
|
-
/**
|
|
120
|
-
* The relation-predicate portion of {@link WhereOf}: each declared relation on
|
|
121
|
-
* `T` contributes a kind-dispatched node — `one` → `{ is?; isNot? }`, `many` →
|
|
122
|
-
* `{ some?; none?; every? }` — whose inner type is the target table's own
|
|
123
|
-
* relation-aware `where` (so multi-hop predicates type-check inside-out).
|
|
124
|
-
*/
|
|
125
|
-
type RelationWhere<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = { [K in keyof REL[T]]?: REL[T][K] extends {
|
|
126
|
-
__relationKind: "one";
|
|
127
|
-
__target: infer Target extends keyof DM;
|
|
128
|
-
} ? OneRelationWhere<WhereOf<DM, REL, Target>> : REL[T][K] extends {
|
|
129
|
-
__relationKind: "many";
|
|
130
|
-
__target: infer Target extends keyof DM;
|
|
131
|
-
} ? ManyRelationWhere<WhereOf<DM, REL, Target>> : never; };
|
|
132
209
|
/**
|
|
133
210
|
* Relation-aware `where` tree — the column predicates of {@link Where} plus
|
|
134
211
|
* Prisma-style relation predicates resolved by the `@lunora/do` pre-resolver.
|
|
@@ -181,14 +258,6 @@ interface QueryPage<TDocument> {
|
|
|
181
258
|
*/
|
|
182
259
|
splitRequired?: boolean;
|
|
183
260
|
}
|
|
184
|
-
/** The nested `with` sub-argument inside a relation's with-value, or `{}`. */
|
|
185
|
-
type NestedWithArgument<WK> = WK extends {
|
|
186
|
-
with: infer NW;
|
|
187
|
-
} ? NW : {};
|
|
188
|
-
/** The nested `select` tuple inside a relation's with-value, or `undefined` (no projection). */
|
|
189
|
-
type NestedSelectArgument<WK> = WK extends {
|
|
190
|
-
select: infer S;
|
|
191
|
-
} ? S : undefined;
|
|
192
261
|
/**
|
|
193
262
|
* The `with` argument for table `T`: each relation can be `true` (load with no
|
|
194
263
|
* refinements) or an object. `many` relations accept `where`/`orderBy`/`limit`/
|
|
@@ -209,34 +278,6 @@ type WithArg<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = { [
|
|
|
209
278
|
} : never; } & {
|
|
210
279
|
_count?: { [K in keyof REL[T]]?: true; };
|
|
211
280
|
};
|
|
212
|
-
/**
|
|
213
|
-
* Resolve a single relation descriptor + its with-value to the loaded type,
|
|
214
|
-
* threading the nested `select` tuple into the projected child shape (the 5th
|
|
215
|
-
* `LoadWith` arg) so `with: { author: { select: ["name"] } }` narrows the loaded
|
|
216
|
-
* `author` to the selected columns + system fields.
|
|
217
|
-
*/
|
|
218
|
-
type LoadRelation<DM, REL extends Record<keyof DM, object>, R, WK> = R extends {
|
|
219
|
-
__relationKind: "one";
|
|
220
|
-
__target: infer Target extends keyof DM;
|
|
221
|
-
} ? LoadWith<DM, REL, Target, NestedWithArgument<WK>, NestedSelectArgument<WK>> | null : R extends {
|
|
222
|
-
__relationKind: "many";
|
|
223
|
-
__target: infer Target extends keyof DM;
|
|
224
|
-
} ? LoadWith<DM, REL, Target, NestedWithArgument<WK>, NestedSelectArgument<WK>>[] : never;
|
|
225
|
-
/** The relation keys of `W` that were actually requested (not `false`/`undefined`). */
|
|
226
|
-
type LoadedRelations<DM, REL extends Record<keyof DM, object>, T extends keyof DM, W> = { [K in keyof W as K extends keyof REL[T] ? (W[K] extends false | undefined ? never : K) : never]: K extends keyof REL[T] ? LoadRelation<DM, REL, REL[T][K], W[K]> : never; };
|
|
227
|
-
/** The `_count` projection of `W`, if any. */
|
|
228
|
-
type LoadedCount<W> = W extends {
|
|
229
|
-
_count: infer C;
|
|
230
|
-
} ? {
|
|
231
|
-
_count: { [K in keyof C]: number; };
|
|
232
|
-
} : {};
|
|
233
|
-
/** System columns a `select` projection always retains, so cursors and by-id reuse keep working. */
|
|
234
|
-
type SelectAlwaysKeep<DM, T extends keyof DM> = ("_creationTime" | "_id") & keyof DM[T];
|
|
235
|
-
/**
|
|
236
|
-
* `DM[T]` narrowed to the columns named by a `select` tuple `S` (plus the system
|
|
237
|
-
* fields). `undefined` (the default — no `select`) keeps the full document.
|
|
238
|
-
*/
|
|
239
|
-
type ProjectDoc<DM, T extends keyof DM, S> = S extends ReadonlyArray<infer K> ? (K extends keyof DM[T] ? Pick<DM[T], (K & keyof DM[T]) | SelectAlwaysKeep<DM, T>> : DM[T]) : DM[T];
|
|
240
281
|
/**
|
|
241
282
|
* `Doc<T>` narrowed to exactly the relations requested in the with-arg `W` and,
|
|
242
283
|
* when a `select` tuple `S` is supplied, to its projected columns. `S` defaults
|
|
@@ -404,7 +445,7 @@ interface TableReaderFacade<DM, REL extends Record<keyof DM, object>, RANK exten
|
|
|
404
445
|
* Count rows. The planner routes `where` keys that match a declared
|
|
405
446
|
* `aggregateIndex.by` set to the indexed counter (no scan); otherwise
|
|
406
447
|
* falls back to a SCAN. Accepts either a bare `where` tree or the broader
|
|
407
|
-
*
|
|
448
|
+
* RestrictableQueryOptions shape; the latter is the seam the RLS layer
|
|
408
449
|
* uses to inject `baseWhere` and `restrictsCounts`.
|
|
409
450
|
*/
|
|
410
451
|
count: (where?: RestrictableQueryOptionsOf<DM, REL, T> | WhereOf<DM, REL, T>) => Promise<number>;
|
|
@@ -594,47 +635,11 @@ interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends
|
|
|
594
635
|
}
|
|
595
636
|
/** Conflict target for `upsert`/`upsertMany`: one column of table `T`, or a tuple of them. */
|
|
596
637
|
type UpsertTargetOf<DM, T extends keyof DM> = ReadonlyArray<keyof DM[T] & string> | (keyof DM[T] & string);
|
|
597
|
-
/**
|
|
598
|
-
* An atomic update for a number column, applied to the value the row holds when the
|
|
599
|
-
* write runs: `{ increment: 1 }`, `{ decrement: 1 }`, `{ multiply: 2 }`, `{ divide: 2 }`.
|
|
600
|
-
* The column must already hold a finite number; a result that is not finite is rejected.
|
|
601
|
-
*/
|
|
602
|
-
type NumberFieldOperator = {
|
|
603
|
-
decrement: number;
|
|
604
|
-
divide?: never;
|
|
605
|
-
increment?: never;
|
|
606
|
-
multiply?: never;
|
|
607
|
-
} | {
|
|
608
|
-
decrement?: never;
|
|
609
|
-
divide: number;
|
|
610
|
-
increment?: never;
|
|
611
|
-
multiply?: never;
|
|
612
|
-
} | {
|
|
613
|
-
decrement?: never;
|
|
614
|
-
divide?: never;
|
|
615
|
-
increment: number;
|
|
616
|
-
multiply?: never;
|
|
617
|
-
} | {
|
|
618
|
-
decrement?: never;
|
|
619
|
-
divide?: never;
|
|
620
|
-
increment?: never;
|
|
621
|
-
multiply: number;
|
|
622
|
-
};
|
|
623
|
-
/** An atomic update for a boolean column: `{ toggle: true }` flips the stored value. */
|
|
624
|
-
interface BooleanFieldOperator {
|
|
625
|
-
toggle: true;
|
|
626
|
-
}
|
|
627
638
|
/**
|
|
628
639
|
* The values a `patch` accepts: any column's own type, and for a number or boolean
|
|
629
640
|
* column also an atomic operator ({@link NumberFieldOperator}, {@link BooleanFieldOperator}).
|
|
630
641
|
*/
|
|
631
642
|
type PatchValues<Row> = PathPatch<Row> & { [K in keyof Row]?: Row[K] | OperatorFor<NonNullable<Row[K]>>; };
|
|
632
|
-
/**
|
|
633
|
-
* The operator a column of type `T` takes: arithmetic when `T` is exactly `number` (so a literal union
|
|
634
|
-
* such as `1 | 2` is out — the result could leave the set — and so is `number | string`, which the
|
|
635
|
-
* store does not treat as a number column), `{ toggle: true }` when it is exactly `boolean`.
|
|
636
|
-
*/
|
|
637
|
-
type OperatorFor<T> = [T] extends [number] ? [number] extends [T] ? NumberFieldOperator : never : [T] extends [boolean] ? [boolean] extends [T] ? BooleanFieldOperator : never : never;
|
|
638
643
|
/** What `explain` returns: the SQL a read compiles to, its bound parameters, and the database's plan for it. */
|
|
639
644
|
interface QueryPlan {
|
|
640
645
|
/** The bound parameters, in order. */
|
|
@@ -681,11 +686,6 @@ type RelationWrites<DM, REL extends Record<keyof DM, object>, T extends keyof DM
|
|
|
681
686
|
__relationKind: "many";
|
|
682
687
|
__target: infer Target extends keyof DM;
|
|
683
688
|
} ? ToManyRelationWrite<Id<string & Target>> : never; };
|
|
684
|
-
/** The foreign-key columns of a table's to-one relations — the keys a nested `connect` supplies. */
|
|
685
|
-
type OneRelationFields<RelT> = { [K in keyof RelT]: RelT[K] extends {
|
|
686
|
-
__field: infer Field extends string;
|
|
687
|
-
__relationKind: "one";
|
|
688
|
-
} ? Field : never; }[keyof RelT];
|
|
689
689
|
/**
|
|
690
690
|
* What `insert` accepts: the row as it is, or the row without its to-one foreign keys plus the nested writes that
|
|
691
691
|
* supply them. Leaving a key out with no `connect` to supply it is not caught by the type — the store's own
|
package/dist/data-model.d.ts
CHANGED
|
@@ -20,23 +20,6 @@
|
|
|
20
20
|
* so this module needs no reference to the project-local `OneRelation` /
|
|
21
21
|
* `ManyRelation` aliases the codegen still emits.
|
|
22
22
|
*/
|
|
23
|
-
/** A branded id for table `TName`. Structurally a `string` at runtime. */
|
|
24
|
-
type Id<TName extends string> = string & {
|
|
25
|
-
readonly __table: TName;
|
|
26
|
-
};
|
|
27
|
-
/** Field-level operators for the typed `where` DSL (see `@lunora/do`'s compiler). */
|
|
28
|
-
interface WhereOperators<T> {
|
|
29
|
-
contains?: string;
|
|
30
|
-
eq?: T;
|
|
31
|
-
gt?: T;
|
|
32
|
-
gte?: T;
|
|
33
|
-
in?: T[];
|
|
34
|
-
isNull?: boolean;
|
|
35
|
-
lt?: T;
|
|
36
|
-
lte?: T;
|
|
37
|
-
ne?: T;
|
|
38
|
-
notIn?: T[];
|
|
39
|
-
}
|
|
40
23
|
/**
|
|
41
24
|
* A value stored as a plain JS object: not a scalar (an `Id<T>` is a branded string, which is an `object` to
|
|
42
25
|
* TypeScript but has no keys worth offering), an array, a date, bytes, a bigint or a function.
|
|
@@ -66,6 +49,113 @@ type ScalarPaths<Doc> = { [P in ColumnPaths<Doc>]: [DocPathValue<Doc, P>] extend
|
|
|
66
49
|
type PathWhere<Doc, Paths extends string = ScalarPaths<Doc>> = [Paths] extends [never] ? unknown : { [P in Paths]?: DocPathValue<Doc, P> | WhereOperators<DocPathValue<Doc, P>>; };
|
|
67
50
|
/** `patch` keys that set one value inside an object column, keeping its siblings: `{ "profile.plan": "pro" }`. */
|
|
68
51
|
type PathPatch<Doc, Paths extends string = ColumnPaths<Doc>> = [Paths] extends [never] ? unknown : { [P in Paths]?: DocPathValue<Doc, P>; };
|
|
52
|
+
/**
|
|
53
|
+
* The relation-predicate portion of {@link WhereOf}: each declared relation on
|
|
54
|
+
* `T` contributes a kind-dispatched node — `one` → `{ is?; isNot? }`, `many` →
|
|
55
|
+
* `{ some?; none?; every? }` — whose inner type is the target table's own
|
|
56
|
+
* relation-aware `where` (so multi-hop predicates type-check inside-out).
|
|
57
|
+
*/
|
|
58
|
+
type RelationWhere<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = { [K in keyof REL[T]]?: REL[T][K] extends {
|
|
59
|
+
__relationKind: "one";
|
|
60
|
+
__target: infer Target extends keyof DM;
|
|
61
|
+
} ? OneRelationWhere<WhereOf<DM, REL, Target>> : REL[T][K] extends {
|
|
62
|
+
__relationKind: "many";
|
|
63
|
+
__target: infer Target extends keyof DM;
|
|
64
|
+
} ? ManyRelationWhere<WhereOf<DM, REL, Target>> : never; };
|
|
65
|
+
/** The nested `with` sub-argument inside a relation's with-value, or `{}`. */
|
|
66
|
+
type NestedWithArgument<WK> = WK extends {
|
|
67
|
+
with: infer NW;
|
|
68
|
+
} ? NW : {};
|
|
69
|
+
/** The nested `select` tuple inside a relation's with-value, or `undefined` (no projection). */
|
|
70
|
+
type NestedSelectArgument<WK> = WK extends {
|
|
71
|
+
select: infer S;
|
|
72
|
+
} ? S : undefined;
|
|
73
|
+
/**
|
|
74
|
+
* Resolve a single relation descriptor + its with-value to the loaded type,
|
|
75
|
+
* threading the nested `select` tuple into the projected child shape (the 5th
|
|
76
|
+
* `LoadWith` arg) so `with: { author: { select: ["name"] } }` narrows the loaded
|
|
77
|
+
* `author` to the selected columns + system fields.
|
|
78
|
+
*/
|
|
79
|
+
type LoadRelation<DM, REL extends Record<keyof DM, object>, R, WK> = R extends {
|
|
80
|
+
__relationKind: "one";
|
|
81
|
+
__target: infer Target extends keyof DM;
|
|
82
|
+
} ? LoadWith<DM, REL, Target, NestedWithArgument<WK>, NestedSelectArgument<WK>> | null : R extends {
|
|
83
|
+
__relationKind: "many";
|
|
84
|
+
__target: infer Target extends keyof DM;
|
|
85
|
+
} ? LoadWith<DM, REL, Target, NestedWithArgument<WK>, NestedSelectArgument<WK>>[] : never;
|
|
86
|
+
/** The relation keys of `W` that were actually requested (not `false`/`undefined`). */
|
|
87
|
+
type LoadedRelations<DM, REL extends Record<keyof DM, object>, T extends keyof DM, W> = { [K in keyof W as K extends keyof REL[T] ? (W[K] extends false | undefined ? never : K) : never]: K extends keyof REL[T] ? LoadRelation<DM, REL, REL[T][K], W[K]> : never; };
|
|
88
|
+
/** The `_count` projection of `W`, if any. */
|
|
89
|
+
type LoadedCount<W> = W extends {
|
|
90
|
+
_count: infer C;
|
|
91
|
+
} ? {
|
|
92
|
+
_count: { [K in keyof C]: number; };
|
|
93
|
+
} : {};
|
|
94
|
+
/** System columns a `select` projection always retains, so cursors and by-id reuse keep working. */
|
|
95
|
+
type SelectAlwaysKeep<DM, T extends keyof DM> = ("_creationTime" | "_id") & keyof DM[T];
|
|
96
|
+
/**
|
|
97
|
+
* `DM[T]` narrowed to the columns named by a `select` tuple `S` (plus the system
|
|
98
|
+
* fields). `undefined` (the default — no `select`) keeps the full document.
|
|
99
|
+
*/
|
|
100
|
+
type ProjectDoc<DM, T extends keyof DM, S> = S extends ReadonlyArray<infer K> ? (K extends keyof DM[T] ? Pick<DM[T], (K & keyof DM[T]) | SelectAlwaysKeep<DM, T>> : DM[T]) : DM[T];
|
|
101
|
+
/**
|
|
102
|
+
* An atomic update for a number column, applied to the value the row holds when the
|
|
103
|
+
* write runs: `{ increment: 1 }`, `{ decrement: 1 }`, `{ multiply: 2 }`, `{ divide: 2 }`.
|
|
104
|
+
* The column must already hold a finite number; a result that is not finite is rejected.
|
|
105
|
+
*/
|
|
106
|
+
type NumberFieldOperator = {
|
|
107
|
+
decrement: number;
|
|
108
|
+
divide?: never;
|
|
109
|
+
increment?: never;
|
|
110
|
+
multiply?: never;
|
|
111
|
+
} | {
|
|
112
|
+
decrement?: never;
|
|
113
|
+
divide: number;
|
|
114
|
+
increment?: never;
|
|
115
|
+
multiply?: never;
|
|
116
|
+
} | {
|
|
117
|
+
decrement?: never;
|
|
118
|
+
divide?: never;
|
|
119
|
+
increment: number;
|
|
120
|
+
multiply?: never;
|
|
121
|
+
} | {
|
|
122
|
+
decrement?: never;
|
|
123
|
+
divide?: never;
|
|
124
|
+
increment?: never;
|
|
125
|
+
multiply: number;
|
|
126
|
+
};
|
|
127
|
+
/** An atomic update for a boolean column: `{ toggle: true }` flips the stored value. */
|
|
128
|
+
interface BooleanFieldOperator {
|
|
129
|
+
toggle: true;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The operator a column of type `T` takes: arithmetic when `T` is exactly `number` (so a literal union
|
|
133
|
+
* such as `1 | 2` is out — the result could leave the set — and so is `number | string`, which the
|
|
134
|
+
* store does not treat as a number column), `{ toggle: true }` when it is exactly `boolean`.
|
|
135
|
+
*/
|
|
136
|
+
type OperatorFor<T> = [T] extends [number] ? [number] extends [T] ? NumberFieldOperator : never : [T] extends [boolean] ? [boolean] extends [T] ? BooleanFieldOperator : never : never;
|
|
137
|
+
/** The foreign-key columns of a table's to-one relations — the keys a nested `connect` supplies. */
|
|
138
|
+
type OneRelationFields<RelT> = { [K in keyof RelT]: RelT[K] extends {
|
|
139
|
+
__field: infer Field extends string;
|
|
140
|
+
__relationKind: "one";
|
|
141
|
+
} ? Field : never; }[keyof RelT];
|
|
142
|
+
/** A branded id for table `TName`. Structurally a `string` at runtime. */
|
|
143
|
+
type Id<TName extends string> = string & {
|
|
144
|
+
readonly __table: TName;
|
|
145
|
+
};
|
|
146
|
+
/** Field-level operators for the typed `where` DSL (see `@lunora/do`'s compiler). */
|
|
147
|
+
interface WhereOperators<T> {
|
|
148
|
+
contains?: string;
|
|
149
|
+
eq?: T;
|
|
150
|
+
gt?: T;
|
|
151
|
+
gte?: T;
|
|
152
|
+
in?: T[];
|
|
153
|
+
isNull?: boolean;
|
|
154
|
+
lt?: T;
|
|
155
|
+
lte?: T;
|
|
156
|
+
ne?: T;
|
|
157
|
+
notIn?: T[];
|
|
158
|
+
}
|
|
69
159
|
/** A typed `where` tree over a document's columns. */
|
|
70
160
|
type Where<TDocument> = PathWhere<TDocument> & { [K in keyof TDocument]?: TDocument[K] | WhereOperators<TDocument[K]>; } & {
|
|
71
161
|
AND?: Where<TDocument>[];
|
|
@@ -116,19 +206,6 @@ interface ManyRelationWhere<W> {
|
|
|
116
206
|
none?: W;
|
|
117
207
|
some?: W;
|
|
118
208
|
}
|
|
119
|
-
/**
|
|
120
|
-
* The relation-predicate portion of {@link WhereOf}: each declared relation on
|
|
121
|
-
* `T` contributes a kind-dispatched node — `one` → `{ is?; isNot? }`, `many` →
|
|
122
|
-
* `{ some?; none?; every? }` — whose inner type is the target table's own
|
|
123
|
-
* relation-aware `where` (so multi-hop predicates type-check inside-out).
|
|
124
|
-
*/
|
|
125
|
-
type RelationWhere<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = { [K in keyof REL[T]]?: REL[T][K] extends {
|
|
126
|
-
__relationKind: "one";
|
|
127
|
-
__target: infer Target extends keyof DM;
|
|
128
|
-
} ? OneRelationWhere<WhereOf<DM, REL, Target>> : REL[T][K] extends {
|
|
129
|
-
__relationKind: "many";
|
|
130
|
-
__target: infer Target extends keyof DM;
|
|
131
|
-
} ? ManyRelationWhere<WhereOf<DM, REL, Target>> : never; };
|
|
132
209
|
/**
|
|
133
210
|
* Relation-aware `where` tree — the column predicates of {@link Where} plus
|
|
134
211
|
* Prisma-style relation predicates resolved by the `@lunora/do` pre-resolver.
|
|
@@ -181,14 +258,6 @@ interface QueryPage<TDocument> {
|
|
|
181
258
|
*/
|
|
182
259
|
splitRequired?: boolean;
|
|
183
260
|
}
|
|
184
|
-
/** The nested `with` sub-argument inside a relation's with-value, or `{}`. */
|
|
185
|
-
type NestedWithArgument<WK> = WK extends {
|
|
186
|
-
with: infer NW;
|
|
187
|
-
} ? NW : {};
|
|
188
|
-
/** The nested `select` tuple inside a relation's with-value, or `undefined` (no projection). */
|
|
189
|
-
type NestedSelectArgument<WK> = WK extends {
|
|
190
|
-
select: infer S;
|
|
191
|
-
} ? S : undefined;
|
|
192
261
|
/**
|
|
193
262
|
* The `with` argument for table `T`: each relation can be `true` (load with no
|
|
194
263
|
* refinements) or an object. `many` relations accept `where`/`orderBy`/`limit`/
|
|
@@ -209,34 +278,6 @@ type WithArg<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = { [
|
|
|
209
278
|
} : never; } & {
|
|
210
279
|
_count?: { [K in keyof REL[T]]?: true; };
|
|
211
280
|
};
|
|
212
|
-
/**
|
|
213
|
-
* Resolve a single relation descriptor + its with-value to the loaded type,
|
|
214
|
-
* threading the nested `select` tuple into the projected child shape (the 5th
|
|
215
|
-
* `LoadWith` arg) so `with: { author: { select: ["name"] } }` narrows the loaded
|
|
216
|
-
* `author` to the selected columns + system fields.
|
|
217
|
-
*/
|
|
218
|
-
type LoadRelation<DM, REL extends Record<keyof DM, object>, R, WK> = R extends {
|
|
219
|
-
__relationKind: "one";
|
|
220
|
-
__target: infer Target extends keyof DM;
|
|
221
|
-
} ? LoadWith<DM, REL, Target, NestedWithArgument<WK>, NestedSelectArgument<WK>> | null : R extends {
|
|
222
|
-
__relationKind: "many";
|
|
223
|
-
__target: infer Target extends keyof DM;
|
|
224
|
-
} ? LoadWith<DM, REL, Target, NestedWithArgument<WK>, NestedSelectArgument<WK>>[] : never;
|
|
225
|
-
/** The relation keys of `W` that were actually requested (not `false`/`undefined`). */
|
|
226
|
-
type LoadedRelations<DM, REL extends Record<keyof DM, object>, T extends keyof DM, W> = { [K in keyof W as K extends keyof REL[T] ? (W[K] extends false | undefined ? never : K) : never]: K extends keyof REL[T] ? LoadRelation<DM, REL, REL[T][K], W[K]> : never; };
|
|
227
|
-
/** The `_count` projection of `W`, if any. */
|
|
228
|
-
type LoadedCount<W> = W extends {
|
|
229
|
-
_count: infer C;
|
|
230
|
-
} ? {
|
|
231
|
-
_count: { [K in keyof C]: number; };
|
|
232
|
-
} : {};
|
|
233
|
-
/** System columns a `select` projection always retains, so cursors and by-id reuse keep working. */
|
|
234
|
-
type SelectAlwaysKeep<DM, T extends keyof DM> = ("_creationTime" | "_id") & keyof DM[T];
|
|
235
|
-
/**
|
|
236
|
-
* `DM[T]` narrowed to the columns named by a `select` tuple `S` (plus the system
|
|
237
|
-
* fields). `undefined` (the default — no `select`) keeps the full document.
|
|
238
|
-
*/
|
|
239
|
-
type ProjectDoc<DM, T extends keyof DM, S> = S extends ReadonlyArray<infer K> ? (K extends keyof DM[T] ? Pick<DM[T], (K & keyof DM[T]) | SelectAlwaysKeep<DM, T>> : DM[T]) : DM[T];
|
|
240
281
|
/**
|
|
241
282
|
* `Doc<T>` narrowed to exactly the relations requested in the with-arg `W` and,
|
|
242
283
|
* when a `select` tuple `S` is supplied, to its projected columns. `S` defaults
|
|
@@ -404,7 +445,7 @@ interface TableReaderFacade<DM, REL extends Record<keyof DM, object>, RANK exten
|
|
|
404
445
|
* Count rows. The planner routes `where` keys that match a declared
|
|
405
446
|
* `aggregateIndex.by` set to the indexed counter (no scan); otherwise
|
|
406
447
|
* falls back to a SCAN. Accepts either a bare `where` tree or the broader
|
|
407
|
-
*
|
|
448
|
+
* RestrictableQueryOptions shape; the latter is the seam the RLS layer
|
|
408
449
|
* uses to inject `baseWhere` and `restrictsCounts`.
|
|
409
450
|
*/
|
|
410
451
|
count: (where?: RestrictableQueryOptionsOf<DM, REL, T> | WhereOf<DM, REL, T>) => Promise<number>;
|
|
@@ -594,47 +635,11 @@ interface TableWriterFacade<DM, IM extends Record<keyof DM, object>, REL extends
|
|
|
594
635
|
}
|
|
595
636
|
/** Conflict target for `upsert`/`upsertMany`: one column of table `T`, or a tuple of them. */
|
|
596
637
|
type UpsertTargetOf<DM, T extends keyof DM> = ReadonlyArray<keyof DM[T] & string> | (keyof DM[T] & string);
|
|
597
|
-
/**
|
|
598
|
-
* An atomic update for a number column, applied to the value the row holds when the
|
|
599
|
-
* write runs: `{ increment: 1 }`, `{ decrement: 1 }`, `{ multiply: 2 }`, `{ divide: 2 }`.
|
|
600
|
-
* The column must already hold a finite number; a result that is not finite is rejected.
|
|
601
|
-
*/
|
|
602
|
-
type NumberFieldOperator = {
|
|
603
|
-
decrement: number;
|
|
604
|
-
divide?: never;
|
|
605
|
-
increment?: never;
|
|
606
|
-
multiply?: never;
|
|
607
|
-
} | {
|
|
608
|
-
decrement?: never;
|
|
609
|
-
divide: number;
|
|
610
|
-
increment?: never;
|
|
611
|
-
multiply?: never;
|
|
612
|
-
} | {
|
|
613
|
-
decrement?: never;
|
|
614
|
-
divide?: never;
|
|
615
|
-
increment: number;
|
|
616
|
-
multiply?: never;
|
|
617
|
-
} | {
|
|
618
|
-
decrement?: never;
|
|
619
|
-
divide?: never;
|
|
620
|
-
increment?: never;
|
|
621
|
-
multiply: number;
|
|
622
|
-
};
|
|
623
|
-
/** An atomic update for a boolean column: `{ toggle: true }` flips the stored value. */
|
|
624
|
-
interface BooleanFieldOperator {
|
|
625
|
-
toggle: true;
|
|
626
|
-
}
|
|
627
638
|
/**
|
|
628
639
|
* The values a `patch` accepts: any column's own type, and for a number or boolean
|
|
629
640
|
* column also an atomic operator ({@link NumberFieldOperator}, {@link BooleanFieldOperator}).
|
|
630
641
|
*/
|
|
631
642
|
type PatchValues<Row> = PathPatch<Row> & { [K in keyof Row]?: Row[K] | OperatorFor<NonNullable<Row[K]>>; };
|
|
632
|
-
/**
|
|
633
|
-
* The operator a column of type `T` takes: arithmetic when `T` is exactly `number` (so a literal union
|
|
634
|
-
* such as `1 | 2` is out — the result could leave the set — and so is `number | string`, which the
|
|
635
|
-
* store does not treat as a number column), `{ toggle: true }` when it is exactly `boolean`.
|
|
636
|
-
*/
|
|
637
|
-
type OperatorFor<T> = [T] extends [number] ? [number] extends [T] ? NumberFieldOperator : never : [T] extends [boolean] ? [boolean] extends [T] ? BooleanFieldOperator : never : never;
|
|
638
643
|
/** What `explain` returns: the SQL a read compiles to, its bound parameters, and the database's plan for it. */
|
|
639
644
|
interface QueryPlan {
|
|
640
645
|
/** The bound parameters, in order. */
|
|
@@ -681,11 +686,6 @@ type RelationWrites<DM, REL extends Record<keyof DM, object>, T extends keyof DM
|
|
|
681
686
|
__relationKind: "many";
|
|
682
687
|
__target: infer Target extends keyof DM;
|
|
683
688
|
} ? ToManyRelationWrite<Id<string & Target>> : never; };
|
|
684
|
-
/** The foreign-key columns of a table's to-one relations — the keys a nested `connect` supplies. */
|
|
685
|
-
type OneRelationFields<RelT> = { [K in keyof RelT]: RelT[K] extends {
|
|
686
|
-
__field: infer Field extends string;
|
|
687
|
-
__relationKind: "one";
|
|
688
|
-
} ? Field : never; }[keyof RelT];
|
|
689
689
|
/**
|
|
690
690
|
* What `insert` accepts: the row as it is, or the row without its to-one foreign keys plus the nested writes that
|
|
691
691
|
* supply them. Leaving a key out with no `connect` to supply it is not caught by the type — the store's own
|
package/dist/in-process.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TransactionHeadroomTracker, SqlExec } from '@lunora/shard-engine';
|
|
2
|
-
import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-
|
|
2
|
+
import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-BTY_1dJ8.mjs";
|
|
3
3
|
import '@lunora/values';
|
|
4
4
|
/** Where the current dispatch's tracker lives: an `AsyncLocalStorage` fits, and so does any stand-in. */
|
|
5
5
|
interface HeadroomScope {
|
package/dist/in-process.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { TransactionHeadroomTracker, SqlExec } from '@lunora/shard-engine';
|
|
2
|
-
import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-
|
|
2
|
+
import { D as DatabaseWriter, S as Schema } from "./packem_shared/types.d-BTY_1dJ8.js";
|
|
3
3
|
import '@lunora/values';
|
|
4
4
|
/** Where the current dispatch's tracker lives: an `AsyncLocalStorage` fits, and so does any stand-in. */
|
|
5
5
|
interface HeadroomScope {
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Validator, Infer, ColumnValidator, Id, StringColumnValidator, ValidatorMap, InferValidatorMap } from '@lunora/values';
|
|
2
2
|
export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
|
|
3
|
-
import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, c as RegisteredInternalAction, M as MutationCtx, d as RegisteredInternalMutation, Q as QueryCtx, e as RegisteredInternalQuery, f as DurableStreamOptions, g as RegisteredInternalStream, h as RegisteredMutation, i as RegisteredQuery, j as RegisteredStream, F as FunctionKind, T as TableDefinition, k as RegisteredFunction, V as VectorIndexDefinition, S as Schema, l as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, m as RelationThrough, n as ThroughRelationDefinition, O as OnDeleteAction, o as RelationDefinition, p as SearchLanguage, q as SearchStrategy, r as ExternalSourceDefinition, s as TriggerBuilder, t as TriggerDefinition, u as VectorEmbedder, v as VectorMetric, w as DurableObjectJurisdiction, x as AggregateIndexDefinition, y as RankIndexDefinition, z as Secrets, B as LiveTopicRef, C as LifecycleEvent, H as ShardInitEvent, J as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-
|
|
4
|
-
export type { N as AuthState, P as CachePurge, U as DatabaseReader, D as DatabaseWriter, Y as FunctionVisibility, Z as GeoBoundingBox, _ as GeoFilterBuilder, $ as GeoIndexDefinition, a0 as GeoPointInput, a1 as IndexDefinition, a2 as IndexRangeBuilder, a3 as LifecycleEventKind, a4 as LogFields, a5 as LunoraLogMethod, a6 as LunoraLogger, a7 as LunoraMetrics, L as LunoraTracer, a8 as LunoraWideEvent, a9 as MutationStorage, aa as PaginationOptions, ab as PaginationResult, ac as PatchIfResult, ad as RankSortKey, ae as ReadOnlyStorage, af as RelatedDirection, ag as RelatedNode, ah as RelatedOptions, ai as RelatedPage, aj as RelatedStart, ak as RelatedStartReference, al as RestCacheConfig, am as RetryPolicy, an as RunQueryOptions, ao as ScheduleRunOptions, ap as ScheduledFunctionDoc, aq as ScheduledJob, ar as ScheduledJobState, as as ScheduledJobView, at as Scheduler, au as SearchFilterBuilder, av as SearchIndexDefinition, aw as ShardMode, ax as SpanContextIds, ay as SpanEvaluation, a as SpanHandle, az as SpanIdentity, aA as SpanKind, aB as SpanLink, aC as SpanOptions, aD as Storage, aE as StorageListOptions, aF as StorageListResult, aG as StorageMetadata, aH as StorageMultipartUpload, aI as StorageMultipartUploadOptions, aJ as StorageObjectBody, aK as StorageObjectHead, aL as StorageRange, aM as StorageUploadBody, aN as StorageUploadOptions, aO as StorageUploadResult, aP as StorageUploadedPart, aQ as SystemDatabaseReader, aR as SystemDoc, aS as SystemQuery, aT as SystemTableName, aU as TableReader, aV as TableVectorIndex, aW as TriggerAggregateOptions, aX as TriggerCtx, aY as TriggerDatabase, aZ as TriggerDeleteEvent, a_ as TriggerEvent, a$ as TriggerGroupByEntry, b0 as TriggerGroupByOptions, b1 as TriggerHandler, b2 as TriggerInsertEvent, b3 as TriggerOp, b4 as TriggerQueryArgs, b5 as TriggerQueryPage, b6 as TriggerRankOptions, b7 as TriggerRankPageOptions, b8 as TriggerRankResult, b9 as TriggerRow, ba as TriggerTiming, bb as TriggerUpdateEvent, bc as TtlDefinition, bd as VectorMatch, be as VectorMatches, bf as VectorQueryInput, bg as VectorRecord, bh as VectorSearch, bi as VectorSearchReader, bj as VectorUpsertInput, bk as WorkflowCreateOptions, bl as WorkflowEventDefinition, bm as WorkflowHandle, bn as WorkflowInstance, bo as WorkflowInstanceEvent, bp as WorkflowInstanceStatus, bq as WorkflowStatusResult, br as Workflows } from "./packem_shared/types.d-
|
|
3
|
+
import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, c as RegisteredInternalAction, M as MutationCtx, d as RegisteredInternalMutation, Q as QueryCtx, e as RegisteredInternalQuery, f as DurableStreamOptions, g as RegisteredInternalStream, h as RegisteredMutation, i as RegisteredQuery, j as RegisteredStream, F as FunctionKind, T as TableDefinition, k as RegisteredFunction, V as VectorIndexDefinition, S as Schema, l as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, m as RelationThrough, n as ThroughRelationDefinition, O as OnDeleteAction, o as RelationDefinition, p as SearchLanguage, q as SearchStrategy, r as ExternalSourceDefinition, s as TriggerBuilder, t as TriggerDefinition, u as VectorEmbedder, v as VectorMetric, w as DurableObjectJurisdiction, x as AggregateIndexDefinition, y as RankIndexDefinition, z as Secrets, B as LiveTopicRef, C as LifecycleEvent, H as ShardInitEvent, J as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-BTY_1dJ8.mjs";
|
|
4
|
+
export type { N as AuthState, P as CachePurge, U as DatabaseReader, D as DatabaseWriter, Y as FunctionVisibility, Z as GeoBoundingBox, _ as GeoFilterBuilder, $ as GeoIndexDefinition, a0 as GeoPointInput, a1 as IndexDefinition, a2 as IndexRangeBuilder, a3 as LifecycleEventKind, a4 as LogFields, a5 as LunoraLogMethod, a6 as LunoraLogger, a7 as LunoraMetrics, L as LunoraTracer, a8 as LunoraWideEvent, a9 as MutationStorage, aa as PaginationOptions, ab as PaginationResult, ac as PatchIfResult, ad as RankSortKey, ae as ReadOnlyStorage, af as RelatedDirection, ag as RelatedNode, ah as RelatedOptions, ai as RelatedPage, aj as RelatedStart, ak as RelatedStartReference, al as RestCacheConfig, am as RetryPolicy, an as RunQueryOptions, ao as ScheduleRunOptions, ap as ScheduledFunctionDoc, aq as ScheduledJob, ar as ScheduledJobState, as as ScheduledJobView, at as Scheduler, au as SearchFilterBuilder, av as SearchIndexDefinition, aw as ShardMode, ax as SpanContextIds, ay as SpanEvaluation, a as SpanHandle, az as SpanIdentity, aA as SpanKind, aB as SpanLink, aC as SpanOptions, aD as Storage, aE as StorageListOptions, aF as StorageListResult, aG as StorageMetadata, aH as StorageMultipartUpload, aI as StorageMultipartUploadOptions, aJ as StorageObjectBody, aK as StorageObjectHead, aL as StorageRange, aM as StorageUploadBody, aN as StorageUploadOptions, aO as StorageUploadResult, aP as StorageUploadedPart, aQ as SystemDatabaseReader, aR as SystemDoc, aS as SystemQuery, aT as SystemTableName, aU as TableReader, aV as TableVectorIndex, aW as TriggerAggregateOptions, aX as TriggerCtx, aY as TriggerDatabase, aZ as TriggerDeleteEvent, a_ as TriggerEvent, a$ as TriggerGroupByEntry, b0 as TriggerGroupByOptions, b1 as TriggerHandler, b2 as TriggerInsertEvent, b3 as TriggerOp, b4 as TriggerQueryArgs, b5 as TriggerQueryPage, b6 as TriggerRankOptions, b7 as TriggerRankPageOptions, b8 as TriggerRankResult, b9 as TriggerRow, ba as TriggerTiming, bb as TriggerUpdateEvent, bc as TtlDefinition, bd as VectorMatch, be as VectorMatches, bf as VectorQueryInput, bg as VectorRecord, bh as VectorSearch, bi as VectorSearchReader, bj as VectorUpsertInput, bk as WorkflowCreateOptions, bl as WorkflowEventDefinition, bm as WorkflowHandle, bn as WorkflowInstance, bo as WorkflowInstanceEvent, bp as WorkflowInstanceStatus, bq as WorkflowStatusResult, br as Workflows } from "./packem_shared/types.d-BTY_1dJ8.mjs";
|
|
5
5
|
import { LunoraError } from '@lunora/errors';
|
|
6
6
|
export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
|
|
7
7
|
import { Context, Hono, ExecutionContext } from 'hono';
|
|
@@ -3411,7 +3411,7 @@ declare const mask: <Context extends MaskContextIn = MaskContextIn>(policies: Ma
|
|
|
3411
3411
|
type MaskRegistry = ReadonlyMap<string, ReadonlySet<string>>;
|
|
3412
3412
|
/**
|
|
3413
3413
|
* Build the project-wide masked-column registry from the registered functions
|
|
3414
|
-
* (pass `
|
|
3414
|
+
* (pass the values of `LUNORA_FUNCTIONS`) — the mask-column twin of
|
|
3415
3415
|
* `buildRlsReadRegistry`. Unions every function's `.use(mask(...))` columns
|
|
3416
3416
|
* per table: a column masked by ANY registered function counts as masked in
|
|
3417
3417
|
* the registry — there is no "which procedure would this shape have gone
|
|
@@ -4034,10 +4034,11 @@ interface ShapeReadWhereRequest {
|
|
|
4034
4034
|
* de-duplicated within a tag). The same tag listed twice (a shared
|
|
4035
4035
|
* `const guard = rls(...)`) is folded once. Within a group this mirrors the
|
|
4036
4036
|
* request-time `rls()` path: a policy's `auth.can(...)` resolves against the
|
|
4037
|
-
* roles of the middleware that declared it, never a union.
|
|
4037
|
+
* roles of the middleware that declared it, never a union. Across groups the
|
|
4038
|
+
* guards AND, as `.use(rls(...))` steps do on a query.
|
|
4038
4039
|
*
|
|
4039
4040
|
* Do NOT hand this every registered function in the project — see the SCOPE
|
|
4040
|
-
* paragraph in the module docblock
|
|
4041
|
+
* paragraph in the module docblock.
|
|
4041
4042
|
*/
|
|
4042
4043
|
declare const buildRlsReadRegistry: (guards: Iterable<unknown>) => RlsReadRegistry;
|
|
4043
4044
|
/** One entry of the generated `LUNORA_SHAPES` registry, as {@link assertShapesDeclareReadPolicies} reads it. */
|
|
@@ -4053,9 +4054,8 @@ interface ShapeGuardDeclaration {
|
|
|
4053
4054
|
* Fail a project's startup closed when a shape would replicate AROUND the read
|
|
4054
4055
|
* policies its table is governed by.
|
|
4055
4056
|
*
|
|
4056
|
-
* Scoping shape RLS to `defineShape({ use })`
|
|
4057
|
-
*
|
|
4058
|
-
* every tenant shape) and opened the other: under the OPT-IN default a shape that
|
|
4057
|
+
* Scoping shape RLS to `defineShape({ use })` keeps a shape's filter to its own
|
|
4058
|
+
* guards, and opens the other direction: under the OPT-IN default a shape that
|
|
4059
4059
|
* names no guard has an empty registry, `resolveReadBaseWhere` returns
|
|
4060
4060
|
* `undefined`, and the shape replicates on its own `where` alone. An app whose
|
|
4061
4061
|
* `messages` table is tenant-scoped on its queries and exposes
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Validator, Infer, ColumnValidator, Id, StringColumnValidator, ValidatorMap, InferValidatorMap } from '@lunora/values';
|
|
2
2
|
export { type ColumnValidator, type GeoPoint, type Id, type Infer, ValidationError, type Validator, type ValidatorKind, v } from '@lunora/values';
|
|
3
|
-
import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, c as RegisteredInternalAction, M as MutationCtx, d as RegisteredInternalMutation, Q as QueryCtx, e as RegisteredInternalQuery, f as DurableStreamOptions, g as RegisteredInternalStream, h as RegisteredMutation, i as RegisteredQuery, j as RegisteredStream, F as FunctionKind, T as TableDefinition, k as RegisteredFunction, V as VectorIndexDefinition, S as Schema, l as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, m as RelationThrough, n as ThroughRelationDefinition, O as OnDeleteAction, o as RelationDefinition, p as SearchLanguage, q as SearchStrategy, r as ExternalSourceDefinition, s as TriggerBuilder, t as TriggerDefinition, u as VectorEmbedder, v as VectorMetric, w as DurableObjectJurisdiction, x as AggregateIndexDefinition, y as RankIndexDefinition, z as Secrets, B as LiveTopicRef, C as LifecycleEvent, H as ShardInitEvent, J as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-
|
|
4
|
-
export type { N as AuthState, P as CachePurge, U as DatabaseReader, D as DatabaseWriter, Y as FunctionVisibility, Z as GeoBoundingBox, _ as GeoFilterBuilder, $ as GeoIndexDefinition, a0 as GeoPointInput, a1 as IndexDefinition, a2 as IndexRangeBuilder, a3 as LifecycleEventKind, a4 as LogFields, a5 as LunoraLogMethod, a6 as LunoraLogger, a7 as LunoraMetrics, L as LunoraTracer, a8 as LunoraWideEvent, a9 as MutationStorage, aa as PaginationOptions, ab as PaginationResult, ac as PatchIfResult, ad as RankSortKey, ae as ReadOnlyStorage, af as RelatedDirection, ag as RelatedNode, ah as RelatedOptions, ai as RelatedPage, aj as RelatedStart, ak as RelatedStartReference, al as RestCacheConfig, am as RetryPolicy, an as RunQueryOptions, ao as ScheduleRunOptions, ap as ScheduledFunctionDoc, aq as ScheduledJob, ar as ScheduledJobState, as as ScheduledJobView, at as Scheduler, au as SearchFilterBuilder, av as SearchIndexDefinition, aw as ShardMode, ax as SpanContextIds, ay as SpanEvaluation, a as SpanHandle, az as SpanIdentity, aA as SpanKind, aB as SpanLink, aC as SpanOptions, aD as Storage, aE as StorageListOptions, aF as StorageListResult, aG as StorageMetadata, aH as StorageMultipartUpload, aI as StorageMultipartUploadOptions, aJ as StorageObjectBody, aK as StorageObjectHead, aL as StorageRange, aM as StorageUploadBody, aN as StorageUploadOptions, aO as StorageUploadResult, aP as StorageUploadedPart, aQ as SystemDatabaseReader, aR as SystemDoc, aS as SystemQuery, aT as SystemTableName, aU as TableReader, aV as TableVectorIndex, aW as TriggerAggregateOptions, aX as TriggerCtx, aY as TriggerDatabase, aZ as TriggerDeleteEvent, a_ as TriggerEvent, a$ as TriggerGroupByEntry, b0 as TriggerGroupByOptions, b1 as TriggerHandler, b2 as TriggerInsertEvent, b3 as TriggerOp, b4 as TriggerQueryArgs, b5 as TriggerQueryPage, b6 as TriggerRankOptions, b7 as TriggerRankPageOptions, b8 as TriggerRankResult, b9 as TriggerRow, ba as TriggerTiming, bb as TriggerUpdateEvent, bc as TtlDefinition, bd as VectorMatch, be as VectorMatches, bf as VectorQueryInput, bg as VectorRecord, bh as VectorSearch, bi as VectorSearchReader, bj as VectorUpsertInput, bk as WorkflowCreateOptions, bl as WorkflowEventDefinition, bm as WorkflowHandle, bn as WorkflowInstance, bo as WorkflowInstanceEvent, bp as WorkflowInstanceStatus, bq as WorkflowStatusResult, br as Workflows } from "./packem_shared/types.d-
|
|
3
|
+
import { A as ArgsValidator, I as InferArgs, R as RegisteredAction, E as ExposeConfig, X as X402ProcedureConfig, b as ActionCtx, c as RegisteredInternalAction, M as MutationCtx, d as RegisteredInternalMutation, Q as QueryCtx, e as RegisteredInternalQuery, f as DurableStreamOptions, g as RegisteredInternalStream, h as RegisteredMutation, i as RegisteredQuery, j as RegisteredStream, F as FunctionKind, T as TableDefinition, k as RegisteredFunction, V as VectorIndexDefinition, S as Schema, l as AggregateOp, G as GlobalBackend, K as KeyedRelationDefinition, m as RelationThrough, n as ThroughRelationDefinition, O as OnDeleteAction, o as RelationDefinition, p as SearchLanguage, q as SearchStrategy, r as ExternalSourceDefinition, s as TriggerBuilder, t as TriggerDefinition, u as VectorEmbedder, v as VectorMetric, w as DurableObjectJurisdiction, x as AggregateIndexDefinition, y as RankIndexDefinition, z as Secrets, B as LiveTopicRef, C as LifecycleEvent, H as ShardInitEvent, J as RegisteredLifecycleHook, W as WhisperEvent } from "./packem_shared/types.d-BTY_1dJ8.js";
|
|
4
|
+
export type { N as AuthState, P as CachePurge, U as DatabaseReader, D as DatabaseWriter, Y as FunctionVisibility, Z as GeoBoundingBox, _ as GeoFilterBuilder, $ as GeoIndexDefinition, a0 as GeoPointInput, a1 as IndexDefinition, a2 as IndexRangeBuilder, a3 as LifecycleEventKind, a4 as LogFields, a5 as LunoraLogMethod, a6 as LunoraLogger, a7 as LunoraMetrics, L as LunoraTracer, a8 as LunoraWideEvent, a9 as MutationStorage, aa as PaginationOptions, ab as PaginationResult, ac as PatchIfResult, ad as RankSortKey, ae as ReadOnlyStorage, af as RelatedDirection, ag as RelatedNode, ah as RelatedOptions, ai as RelatedPage, aj as RelatedStart, ak as RelatedStartReference, al as RestCacheConfig, am as RetryPolicy, an as RunQueryOptions, ao as ScheduleRunOptions, ap as ScheduledFunctionDoc, aq as ScheduledJob, ar as ScheduledJobState, as as ScheduledJobView, at as Scheduler, au as SearchFilterBuilder, av as SearchIndexDefinition, aw as ShardMode, ax as SpanContextIds, ay as SpanEvaluation, a as SpanHandle, az as SpanIdentity, aA as SpanKind, aB as SpanLink, aC as SpanOptions, aD as Storage, aE as StorageListOptions, aF as StorageListResult, aG as StorageMetadata, aH as StorageMultipartUpload, aI as StorageMultipartUploadOptions, aJ as StorageObjectBody, aK as StorageObjectHead, aL as StorageRange, aM as StorageUploadBody, aN as StorageUploadOptions, aO as StorageUploadResult, aP as StorageUploadedPart, aQ as SystemDatabaseReader, aR as SystemDoc, aS as SystemQuery, aT as SystemTableName, aU as TableReader, aV as TableVectorIndex, aW as TriggerAggregateOptions, aX as TriggerCtx, aY as TriggerDatabase, aZ as TriggerDeleteEvent, a_ as TriggerEvent, a$ as TriggerGroupByEntry, b0 as TriggerGroupByOptions, b1 as TriggerHandler, b2 as TriggerInsertEvent, b3 as TriggerOp, b4 as TriggerQueryArgs, b5 as TriggerQueryPage, b6 as TriggerRankOptions, b7 as TriggerRankPageOptions, b8 as TriggerRankResult, b9 as TriggerRow, ba as TriggerTiming, bb as TriggerUpdateEvent, bc as TtlDefinition, bd as VectorMatch, be as VectorMatches, bf as VectorQueryInput, bg as VectorRecord, bh as VectorSearch, bi as VectorSearchReader, bj as VectorUpsertInput, bk as WorkflowCreateOptions, bl as WorkflowEventDefinition, bm as WorkflowHandle, bn as WorkflowInstance, bo as WorkflowInstanceEvent, bp as WorkflowInstanceStatus, bq as WorkflowStatusResult, br as Workflows } from "./packem_shared/types.d-BTY_1dJ8.js";
|
|
5
5
|
import { LunoraError } from '@lunora/errors';
|
|
6
6
|
export { LunoraError, type LunoraErrorCode } from '@lunora/errors';
|
|
7
7
|
import { Context, Hono, ExecutionContext } from 'hono';
|
|
@@ -3411,7 +3411,7 @@ declare const mask: <Context extends MaskContextIn = MaskContextIn>(policies: Ma
|
|
|
3411
3411
|
type MaskRegistry = ReadonlyMap<string, ReadonlySet<string>>;
|
|
3412
3412
|
/**
|
|
3413
3413
|
* Build the project-wide masked-column registry from the registered functions
|
|
3414
|
-
* (pass `
|
|
3414
|
+
* (pass the values of `LUNORA_FUNCTIONS`) — the mask-column twin of
|
|
3415
3415
|
* `buildRlsReadRegistry`. Unions every function's `.use(mask(...))` columns
|
|
3416
3416
|
* per table: a column masked by ANY registered function counts as masked in
|
|
3417
3417
|
* the registry — there is no "which procedure would this shape have gone
|
|
@@ -4034,10 +4034,11 @@ interface ShapeReadWhereRequest {
|
|
|
4034
4034
|
* de-duplicated within a tag). The same tag listed twice (a shared
|
|
4035
4035
|
* `const guard = rls(...)`) is folded once. Within a group this mirrors the
|
|
4036
4036
|
* request-time `rls()` path: a policy's `auth.can(...)` resolves against the
|
|
4037
|
-
* roles of the middleware that declared it, never a union.
|
|
4037
|
+
* roles of the middleware that declared it, never a union. Across groups the
|
|
4038
|
+
* guards AND, as `.use(rls(...))` steps do on a query.
|
|
4038
4039
|
*
|
|
4039
4040
|
* Do NOT hand this every registered function in the project — see the SCOPE
|
|
4040
|
-
* paragraph in the module docblock
|
|
4041
|
+
* paragraph in the module docblock.
|
|
4041
4042
|
*/
|
|
4042
4043
|
declare const buildRlsReadRegistry: (guards: Iterable<unknown>) => RlsReadRegistry;
|
|
4043
4044
|
/** One entry of the generated `LUNORA_SHAPES` registry, as {@link assertShapesDeclareReadPolicies} reads it. */
|
|
@@ -4053,9 +4054,8 @@ interface ShapeGuardDeclaration {
|
|
|
4053
4054
|
* Fail a project's startup closed when a shape would replicate AROUND the read
|
|
4054
4055
|
* policies its table is governed by.
|
|
4055
4056
|
*
|
|
4056
|
-
* Scoping shape RLS to `defineShape({ use })`
|
|
4057
|
-
*
|
|
4058
|
-
* every tenant shape) and opened the other: under the OPT-IN default a shape that
|
|
4057
|
+
* Scoping shape RLS to `defineShape({ use })` keeps a shape's filter to its own
|
|
4058
|
+
* guards, and opens the other direction: under the OPT-IN default a shape that
|
|
4059
4059
|
* names no guard has an empty registry, `resolveReadBaseWhere` returns
|
|
4060
4060
|
* `undefined`, and the shape replicates on its own `where` alone. An app whose
|
|
4061
4061
|
* `messages` table is tenant-scoped on its queries and exposes
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-Dv4DKrj0.mjs";import{initLunora as s}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as S,withDeferredDeletes as D}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as R}from"./packem_shared/beginDeferredSchedules--FVDtp-M.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as g,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as _,documentHistoryExtension as I}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs";import{LunoraEnvError as M,defineEnv as P}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as y,bindTableFacade as O,defineLazyFacade as F}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as N,httpRoute as U,httpRouter as H,lastEventId as k,sseEvent as w}from"./packem_shared/httpAction-Bfw3qwLG.mjs";import{serveStorageObject as V}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as j}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as z}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as J,onDisconnect as K,onShardInit as Q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as q,DEFAULT_MAX_LIMIT as Z,clampLimit as $,defineListArgs as ee}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as oe,liveStreamRouter as te}from"./packem_shared/defineLiveStream-q9yO3wl6.mjs";import{defineMigration as ne}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as ae}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as se}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as pe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as ce,d as le,a as Ee,b as ue,e as Se,f as De,g as he,h as Te,i as Re,j as Ae,k as ge,m as Le}from"./packem_shared/plugin-CyLqvCB9.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ie,PRESENCE_TABLE as Ce,definePresence as Me,presenceExtension as Pe}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-TXTxGfEA.mjs";import{PROCEDURE_META as ye,UNLOADED_META as Oe,procedureMeta as Fe}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as Ne}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as He}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as we}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as Ve}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as je}from"./packem_shared/defineShape-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as i,actionCacheExtension as n,cacheKeyFor as f,defineActionCache as a}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-Dv4DKrj0.mjs";import{initLunora as s}from"./packem_shared/initLunora-DcvCGLL_.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as x}from"./packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs";import{createSecrets as l}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{beginDeferredDeletes as u,flushDeferredDeletes as S,withDeferredDeletes as D}from"./packem_shared/beginDeferredDeletes-DhwFBbvs.mjs";import{beginDeferredSchedules as T,withDeferredSchedules as R}from"./packem_shared/beginDeferredSchedules--FVDtp-M.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as g,DOCUMENT_HISTORY_TABLE as L,defineDocumentHistory as _,documentHistoryExtension as I}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs";import{LunoraEnvError as M,defineEnv as P}from"./packem_shared/LunoraEnvError-06_Zc4yc.mjs";import{bindOrm as y,bindTableFacade as O,defineLazyFacade as F}from"./packem_shared/bindOrm-D5mVDvbi.mjs";import{httpAction as N,httpRoute as U,httpRouter as H,lastEventId as k,sseEvent as w}from"./packem_shared/httpAction-Bfw3qwLG.mjs";import{serveStorageObject as V}from"./packem_shared/serveStorageObject-CLz3qhNI.mjs";import{defineIdentity as j}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{default as z}from"./packem_shared/defineIdentityGuard-Bt8N65Zs.mjs";import{onConnect as J,onDisconnect as K,onShardInit as Q}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as q,DEFAULT_MAX_LIMIT as Z,clampLimit as $,defineListArgs as ee}from"./packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs";import{defineLiveStream as oe,liveStreamRouter as te}from"./packem_shared/defineLiveStream-q9yO3wl6.mjs";import{defineMigration as ne}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineModule as ae}from"./packem_shared/defineModule-OecXWM3U.mjs";import{defineMutator as se}from"./packem_shared/defineMutator-DlLFSWbO.mjs";import{platformAdmin as pe}from"./packem_shared/platformAdmin-kczXQme8.mjs";import{c as ce,d as le,a as Ee,b as ue,e as Se,f as De,g as he,h as Te,i as Re,j as Ae,k as ge,m as Le}from"./packem_shared/plugin-CyLqvCB9.mjs";import{PRESENCE_DEFAULT_TTL_MS as Ie,PRESENCE_TABLE as Ce,definePresence as Me,presenceExtension as Pe}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-TXTxGfEA.mjs";import{PROCEDURE_META as ye,UNLOADED_META as Oe,procedureMeta as Fe}from"./packem_shared/PROCEDURE_META-DVzrXpfa.mjs";import{protectPublic as Ne}from"./packem_shared/protectPublic-Bi5_95aP.mjs";import{onQueryChange as He}from"./packem_shared/onQueryChange-iuLzmyPs.mjs";import{defineRoom as we}from"./packem_shared/defineRoom-CoGi-xwm.mjs";import{createServices as Ve}from"./packem_shared/createServices-IJvoqi0e.mjs";import{defineShape as je}from"./packem_shared/defineShape-H-0IbZlb.mjs";import{defineWebSocket as ze}from"./packem_shared/defineWebSocket-BHoy6_ox.mjs";import{onWhisper as Je}from"./packem_shared/onWhisper-CfDbFLQh.mjs";import{LunoraError as Qe}from"@lunora/errors";import{cronJobs as qe}from"@lunora/scheduler";import{ValidationError as $e,v as er}from"@lunora/values";import{allowAll as or,deny as tr,isDeny as ir,toWhereInput as nr}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ar}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as sr,buildRlsReadRegistry as mr,composeShapeReadWhere as pr}from"./packem_shared/assertShapesDeclareReadPolicies-C09SMvM4.mjs";import{buildMaskRegistry as cr}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Er,definePermission as ur,definePolicies as Sr,definePolicy as Dr,defineRole as hr}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Rr,defineStorageRules as Ar}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{isSafeHeaderValue as Lr}from"./packem_shared/isSafeHeaderValue-DswDADFy.mjs";import{mask as Ir}from"./packem_shared/mask-DHJtsP7t.mjs";import{r as Mr}from"./packem_shared/redact-secrets-BpatNz48.mjs";import{r as br}from"./packem_shared/middleware-CHYtnvZP.mjs";import{storageRules as Or}from"./packem_shared/storageRules-BVIXkoRg.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,i as ACTION_CACHE_TABLE,q as DEFAULT_LIMIT,Z as DEFAULT_MAX_LIMIT,g as DOCUMENT_HISTORY_REDACTED_FIELDS,L as DOCUMENT_HISTORY_TABLE,M as LunoraEnvError,Qe as LunoraError,Ie as PRESENCE_DEFAULT_TTL_MS,Ce as PRESENCE_TABLE,ye as PROCEDURE_META,Oe as UNLOADED_META,e as VERSION,$e as ValidationError,n as actionCacheExtension,or as allowAll,ar as asBucketStorage,sr as assertShapesDeclareReadPolicies,u as beginDeferredDeletes,T as beginDeferredSchedules,y as bindOrm,O as bindTableFacade,cr as buildMaskRegistry,mr as buildRlsReadRegistry,f as cacheKeyFor,$ as clampLimit,ce as composePluginMiddleware,pr as composeShapeReadWhere,Er as createPolicyDsl,l as createSecrets,Ve as createServices,qe as cronJobs,a as defineActionCache,le as defineAggregateIndex,Ee as defineComponent,_ as defineDocumentHistory,P as defineEnv,j as defineIdentity,z as defineIdentityGuard,F as defineLazyFacade,ee as defineListArgs,oe as defineLiveStream,ne as defineMigration,ae as defineModule,se as defineMutator,ur as definePermission,ue as definePlugin,Sr as definePolicies,Dr as definePolicy,Me as definePresence,Se as defineRankIndex,hr as defineRole,we as defineRoom,De as defineSchema,he as defineSchemaExtension,je as defineShape,Rr as defineStorageRule,Ar as defineStorageRules,Te as defineTable,Re as defineVectorIndex,ze as defineWebSocket,tr as deny,I as documentHistoryExtension,S as flushDeferredDeletes,N as httpAction,U as httpRoute,H as httpRouter,Ae as indexFieldsFromSchema,s as initLunora,ge as installPlugins,ir as isDeny,p as isPerDispatchMiddleware,Lr as isSafeHeaderValue,k as lastEventId,te as liveStreamRouter,Ir as mask,Le as mergeSchemaExtension,J as onConnect,K as onDisconnect,He as onQueryChange,Q as onShardInit,Je as onWhisper,pe as platformAdmin,Pe as presenceExtension,Fe as procedureMeta,Ne as protectPublic,Mr as redactSecrets,br as rls,V as serveStorageObject,w as sseEvent,Or as storageRules,x as tagPerDispatchMiddleware,nr as toWhereInput,er as v,D as withDeferredDeletes,R as withDeferredSchedules};
|
package/dist/otel.d.mts
CHANGED
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
* `@opentelemetry/api` is a PEER dependency: it keeps a module-global registry,
|
|
42
42
|
* so a second copy in the tree would silently split it.
|
|
43
43
|
*/
|
|
44
|
-
import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-
|
|
44
|
+
import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-BTY_1dJ8.mjs";
|
|
45
45
|
import '@lunora/values';
|
|
46
46
|
/**
|
|
47
47
|
* @since 1.0.0
|
package/dist/otel.d.ts
CHANGED
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
* `@opentelemetry/api` is a PEER dependency: it keeps a module-global registry,
|
|
42
42
|
* so a second copy in the tree would silently split it.
|
|
43
43
|
*/
|
|
44
|
-
import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-
|
|
44
|
+
import { a as SpanHandle, L as LunoraTracer } from "./packem_shared/types.d-BTY_1dJ8.js";
|
|
45
45
|
import '@lunora/values';
|
|
46
46
|
/**
|
|
47
47
|
* @since 1.0.0
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-CHYtnvZP.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},A=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},S=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=A(n,e);if(s!==void 0){if(d(s))return h;o.push(s)}}if(o.length!==0)return o.length===1?o[0]:{AND:o}},W=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},$=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},B=(t,e)=>T(S(t,e),e.shapeWhere);export{$ as assertShapesDeclareReadPolicies,W as buildRlsReadRegistry,B as composeShapeReadWhere};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{c as m}from"./context-identity-B2XYGA0B.mjs";import{v as p,a as u}from"./functions-QFoBUe9t.mjs";import{toWhereInput as d,deny as c}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as b}from"./assertShapesDeclareReadPolicies-
|
|
1
|
+
import{LunoraError as r}from"@lunora/errors";import{c as m}from"./context-identity-B2XYGA0B.mjs";import{v as p,a as u}from"./functions-QFoBUe9t.mjs";import{toWhereInput as d,deny as c}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as b}from"./assertShapesDeclareReadPolicies-C09SMvM4.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(t,w,n)=>{const s=p(e.args??{},w);u(t,e.args??{},s);const o=e.where?d(e.where(t,s)):void 0;if(e.owner===void 0)return o;const a=e.owner===!0?n?.ownerField:e.owner;if(a===void 0||a==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const h=m(t);if(h===void 0)return c();const l={[a]:h};return o===void 0?l:{AND:[l,o]}},rlsRegistry:b(e.use??[])}};export{I as defineShape};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{f as L}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as x,b as T,c as C,d as H}from"./middleware-CHYtnvZP.mjs";import{defineLazyFacade as J,bindOrm as Y}from"./bindOrm-D5mVDvbi.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const D=Symbol.for("lunora.ctxdb.rls-relation-gate"),V=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?L(i.toString()):L(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},d=(s,i,c)=>{const u={...s};for(const[w,p]of Object.entries(i))w in u&&(u[w]=V(p,s[w],{...c,column:w,row:s}));return u},E=(s,i,c)=>({...s,page:s.page.map(u=>d(u,i,c))}),P=(s,i)=>{const c=C(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},G=(s,i,c,u)=>{if(typeof s!="function")return;const w=new Set,p=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&w.add(f),p())});s(p());for(const f of w)if(P(i,f))throw new S("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${f}" is not supported`)},X=(s,i,c,u)=>{const w=s.rankBefore,p=s.rankPageRows,f=(r,t)=>{const n=i.get(r);return n?t.map(o=>d(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?f:(n,o)=>t(n,f(n,o))}},y=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=u?.[r]?.[o]?.[t];if(!a)return;const g=a.find(I=>P(e,I));if(g!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${g}" — use an index whose declared fields are all unmasked, or unmask the column`)},O=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield d(o,t,c)},collect:async()=>(await r.collect()).map(e=>d(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=d(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>O(r.filter(e=>o(d(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?d(o,t,c):null},order:o=>O(r.order(o),t,n),paginate:async o=>E(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>d(a,t,c)),unique:async()=>{const o=await r.unique();return o?d(o,t,c):null},withIndex:(o,e)=>(y(n,o,"withIndex","index"),G(e,t,n,"withIndex"),O(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(G(e,t,n,"withSearchIndex"),O(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(y(n,o,"withGeoIndex","geo"),O(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&P(o,a));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},l=new Set;for(const r of i.values())for(const t of Object.keys(r))l.add(t);const A=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,a]of Object.entries(r))K(e,a,t,n,o)},K=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const a of Array.isArray(t)?t:[])A(a,n,o,e);return}if(r==="NOT"){A(t,n,o,e);return}if(!r.startsWith("__")){if(P(n,r))throw new S("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(H(t))for(const a of Object.values(t))A(a,l,`${o}.${r}`,e)}},F=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{l.size===0||t===void 0||A(t,F(r),r,n)},v=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(P(n,a))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},j=(r,t,n)=>{if(!(l.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,g=`${r}.${o}`;A(a.where,l,g,n),v(g,a.orderBy,l,n),j(g,a.with,n)}},M=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),v(r,t?.orderBy,F(r),n),j(r,t?.with,n)},_=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,W=(r,t,n)=>{const o=_(t);h(r,o?.where,n),h(r,o?.baseWhere,n),j(r,o?.with,n)},$=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,B={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[a,g]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?$(e.through.table,e.through.from)??$(e.through.table,e.through.to):$(a,e.field)??$(g,e.references);return[o,I===void 0?e:{...e,refusal:`"${I}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:d(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return R(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=_(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){M(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?d(n,o,c):n},async findFirstOrThrow(r,t){M(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?d(n,o,c):n},async explain(r,t){return M(r,t,"explain"),s.explain(r,t)},async findMany(r,t){M(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?E(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:d(n,o,c)},related:s.related?async(r,t)=>await s.related(r,k(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?d(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?O(t,n,r):t},async rank(r,t,n){return W(r,n,"rank"),y(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){W(r,n,"rankPage"),y(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?E(o,e,c):o},...x("rankBefore",w,r=>(t,n,o)=>(W(t,o,"rankBefore"),y(t,n,"rankBefore","rank"),r(t,n,o))),...x("rankPageRows",p,r=>async(t,n,o)=>{W(t,o,"rankPageRows"),y(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(g=>({...g,doc:d(g.doc,a,c)}))}:e})};if(l.size>0)for(const[r,t]of Object.entries(s))T(t)&&J(B,r);const U=s[D];return U!==void 0&&Object.defineProperty(B,D,{configurable:!0,enumerable:!1,value:U,writable:!1}),B},nr=(s,i={})=>{const c=new Map(Object.entries(s)),u=q(i.roles),w=async({ctx:f,next:k})=>{const y=f,O={auth:await z(y.auth??{},u),ctx:y};if(i.bypass?.(O)===!0)return k();const R=X(y.db,c,O,i.indexFields),l={db:R},{orm:A}=y;return A!==null&&typeof A=="object"&&(l.orm=Y(R)),k({ctx:l})},p=new Map;for(const[f,k]of c)p.set(f,new Set(Object.keys(k)));return Q(w,{columns:p})};export{nr as mask};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p,isLunoraError as Be}from"@lunora/errors";import{findRelated as Ee,whereFilter as Se}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{defineLazyFacade as Ae,bindOrm as Te}from"./bindOrm-D5mVDvbi.mjs";import{t as ke}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ie}from"./allowAll-DkRAgItV.mjs";const J=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},re=4;class m extends Error{}const N=e=>e.includes("."),Wt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},fe=e=>{const t=e.split(".");if(t.length>re||t.includes(""))throw new m(`field path "${e}" must have 1 to ${String(re)} non-empty segments`);return t},_e=(e,t)=>{if(!N(t))return e[t];let r=e;for(const i of fe(t)){if(!J(r)||!Object.hasOwn(r,i))return;r=r[i]}return r},de=(e,t,r,i)=>{const[a,...f]=t;if(a===void 0)throw new m(`field path "${i}" is empty`);if(e!=null&&!J(e))throw new m(`cannot set "${i}": "${a}" sits inside a value that is not an object`);const u=e??{};return{...u,[a]:f.length===0?r:de(u[a],f,r,i)}},me=(e,t)=>{const r=Object.keys(e).filter(a=>N(a));if(r.length===0)return e;for(const a of r){const f=r.find(u=>u!==a&&u.startsWith(`${a}.`));if(f!==void 0)throw new m(`patch sets both "${a}" and "${f}", which overlap; set one or the other`)}const i={};for(const[a,f]of Object.entries(e))N(a)||(i[a]=f);for(const a of r){const[f="",...u]=fe(a);if(Object.hasOwn(e,f))throw new m(`patch sets both "${f}" and "${a}"; set one or the other`);i[f]=de(Object.hasOwn(i,f)?i[f]:t[f],u,e[a],a)}return i},Pe=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},$e=["every","is","isNot","none","some"],De=new Set($e),Fe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>De.has(r))},oe=(e,t,r)=>t?{[e]:r(t)}:{},ue=500,K=(e,t,r)=>{if(e!==void 0&&e!==Number.POSITIVE_INFINITY&&(!Number.isInteger(e)||e<0))throw r(`${t}: batch limit must be a non-negative integer`);return e??ue},Q=(e,t,r,i)=>{if(e>t)throw i(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},Z={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class B extends Error{}const he=e=>{if(!J(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(Z,r)))return{operand:e[r],operator:r}},Me=e=>he(e)!==void 0,Le=(e,t,r,i)=>{const a=Z[t];if(a.apply===void 0){if(r!==!0)throw new B(`patch: use { toggle: true } on "${e}".`);if(typeof i!="boolean")throw new B(`patch: cannot toggle "${e}" — its current value is ${String(i)}; set a boolean first.`);return!i}if(typeof r!="number"||!Number.isFinite(r))throw new B(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof i!="number"||!Number.isFinite(i))throw new B(`patch: cannot ${t} "${e}" — its current value is ${String(i)}; set a number first.`);if(t==="divide"&&r===0)throw new B(`patch: cannot divide "${e}" by zero.`);const f=a.apply(i,r);if(!Number.isFinite(f))throw new B(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},ye=(e,t)=>{const r=new Set;for(const[i,a]of Object.entries(e))t(i)!==void 0&&Me(a)&&r.add(i);return r},je=(e,t,r)=>{let i;for(const a of ye(e,r)){const{operand:f,operator:u}=he(e[a]),g=r(a);if(Z[u].kind!==g)throw new B(`patch: "${u}" does not apply to the ${String(g)} column "${a}".`);i??={...e},i[a]=Le(a,u,f,t[a])}return i??e},Ce=(e,t)=>{const r=a=>{const f=t[a];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},i={...e};for(const a of ye(e,r))try{Object.assign(i,je({[a]:e[a]},t,r))}catch(f){if(!(f instanceof B))throw f}try{return me(i,t)}catch(a){if(a instanceof m)return i;throw a}},Ue=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],S=-1,A=0,E=1,P=e=>e?E:S,w=(e,t)=>e<t?e:t,xe=(e,t)=>e>t?e:t,pe=e=>e===A?A:P(e===S),se=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},T=e=>e==null,F=(e,t,r)=>{if(r===void 0)throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Ne={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},qe=(e,t,r)=>{let i=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const f=r[a];F(e,a,f);const u=N(e);if(u?Pe(f)===void 0:!se(f))i=w(i,S);else if(T(t))i=w(i,A);else{const g=Ne[a],y=u?typeof t==typeof f:se(t);i=w(i,P(y&&g(t,f)))}}return i},ie=(e,t,r)=>{if(!Array.isArray(r))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},ae=(e,t)=>t.length===0?S:T(e)?A:t.includes(e)?E:t.some(r=>T(r))?A:S,Ye=(e,t,r)=>{let i=E;if("in"in r&&(i=w(i,ae(t,ie(e,"in",r.in)))),"notIn"in r&&(i=w(i,pe(ae(t,ie(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;F(e,"contains",a),i=T(t)?w(i,A):w(i,P(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(i=w(i,P(r.isNull===!0===T(t)))),i},G=(e,t,r)=>t===null?P(r===T(e)):T(e)?A:P(r===(e===t)),ze=(e,t,r)=>{let i=E;return"eq"in r&&(F(e,"eq",r.eq),i=w(i,G(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),i=w(i,G(t,r.ne,!1))),i},He=(e,t,r)=>w(ze(e,t,r),w(Ye(e,t,r),qe(e,t,r))),Ke=(e,t,r,i)=>{if(t==="NOT")return pe(i(e,r??{}));if(!Array.isArray(r))return S;let a=t==="AND"?E:S;for(const f of r){const u=i(e,f);a=t==="AND"?w(a,u):xe(a,u)}return a},we=e=>e==="AND"||e==="OR"||e==="NOT",Qe=e=>X(e)&&Object.keys(e).every(t=>Ue.includes(t)),q=e=>Object.keys(e).some(t=>{const r=e[t];return we(t)?t==="NOT"?q(r??{}):Array.isArray(r)&&r.some(i=>q(i??{})):Fe(r)}),ge=(e,t)=>{let r=E;for(const i of Object.keys(t)){const a=t[i];if(we(i)){r=w(r,Ke(e,i,a,ge));continue}const f=_e(e,i);if(Qe(a)){r=w(r,He(i,f,a));continue}F(i,"eq",a),r=w(r,G(f,a,!0))}return r},Y=(e,t)=>ge(e,t)===E,ce=(e,t)=>e===void 0||t===void 0?e??t:(r,i)=>e(r,i)&&t(r,i),_=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{Q(e,K(t,r,_),r,_)},Ge=Ie(),Xe=Symbol.for("lunora.ctxdb.rls-unwrap"),Je=Symbol.for("lunora.ctxdb.rls-relation-gate"),be=Symbol.for("lunora.rls.wrapped-chain"),H=new WeakMap,Ze=e=>e[be],Ve=e=>{const t=new Map;for(const r of e){const i=t.get(r.table)??[];i.push(r),t.set(r.table,i)}return t},et=(e,t)=>{const r=[];let i=!1;for(const a of e){if(a.on!=="read")continue;const f=a.when(t);if(f!==void 0){if(f===!0){i=!0;break}f!==!1&&r.push(f)}}if(!i)return r.length===0?Ge:r.length===1?r[0]:{OR:r}},tt=(e,t,r)=>{const i=e.when({...t,row:r});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return Y(r,i)},nt=(e,t,r)=>{const i=e.when(t);if(i===void 0||i===!0)return r===void 0||tt(e,t,r);if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!Y(t.row,i)?!1:r===void 0||Y(r,i)},rt=(e,t,r,i)=>{let a=!1;for(const f of e)if(f.on===t&&(a=!0,!nt(f,r,i)))return!1;return a},ot=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),st=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),it=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>ot.has(r)&&st(r,e[r]))},at=e=>e===void 0?{}:X(e)&&it(e)?e:{where:e},x=e=>e!==void 0&&Object.keys(e).length>0,le=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>x(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ct=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},lt=(e,t,r)=>{const[i]=r,a=r.length===1&&i!==void 0?i.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const s=[];let c=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;c=!0;const O=et(h,d.context);O!==void 0&&s.push(O)}const l={baseWhere:le(s),restricts:c};return f.set(n,l),l},g=(n,o,s,c)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!rt(d,o,{...l.context,row:s},c))return!1}return!0},y=n=>u(n).restricts?t:e,k=e[Je],b=n=>{const{baseWhere:o,restricts:s}=u(n);return s||k?.gate(n),o};k?.trust(b),H.set(b,u);const v=n=>{const o=typeof n=="function"?H.get(n):void 0;if(o===void 0)return b;const s=l=>{const d=u(l),h=o(l);return{baseWhere:le([d.baseWhere,h.baseWhere].filter(O=>x(O))),restricts:d.restricts||h.restricts}},c=l=>{const{baseWhere:d,restricts:h}=s(l);return h||k?.gate(l),d};return k?.trust(c),H.set(c,s),c},$=async(n,o)=>{const s=await t.get(n,o);return s?{row:s,tableName:a.has(n)?n:void 0}:{row:null,tableName:void 0}},z=async n=>{if(t.lookupById){const l=await t.lookupById(n);if(l)return{row:l.row,tableName:a.has(l.tableName)?l.tableName:void 0}}const o=[...a.keys()],c=(await Promise.all(o.map(async l=>{const d=await t.findFirst(l,{limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:l}:void 0}))).find(l=>l!==void 0);return c?{row:c.row,tableName:c.tableName}:{row:null,tableName:void 0}},M=async(n,o)=>{const s=await $(n,o);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},R=async(n,o,s,c,l)=>{const d=await M(n,o);if(!d)return c(e);const h=l?l(d.row):void 0;if(!g(d.tableName,s,d.row,h))throw new p("FORBIDDEN",`${s} denied by policy`);return c(t,d.tableName)},L=(n,o,s)=>{if(s?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},ve=async(n,o,s,c,l)=>{const d=s?t:e,h=await d.findFirst(o,{...s?{baseWhere:u(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:W(l,{_id:n})});if(!h||L(o,h,c))return!1;if(s&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,c),!0},V=async(n,o,s,c)=>{const l=a.has(n),d=l?t:e,h=s===void 0?void 0:{hard:s},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const te of o){const ne=String(te._id);if(O){await ve(ne,n,l,h,c)&&(D+=1);continue}if(l&&!g(n,"delete",te))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ne,h),D+=1}return D},j=(n,o,s,c)=>R(n,o,"update",(l,d)=>c(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...Ce(s,l)})),C=(n,o)=>{const{baseWhere:s}=u(n);if(x(s))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},We=e.rankBefore,Re=e.rankPageRows,{relationEdges:ee}=e,I={...e,async count(n,o){const{baseWhere:s}=u(n),c=at(o);return y(n).count(n,{...c,baseWhere:W(c.baseWhere,s),relationBaseWhere:v(c.relationBaseWhere),restrictsCounts:(c.restrictsCounts??!1)||x(s)})},delete:(n,o,s)=>R(n,o,"delete",c=>c.delete(n,o,s)),async deleteAll(n,o){const s=Math.max(1,o?.chunkSize??ue),{baseWhere:c}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:c,limit:s,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await V(n,h,o?.hard),h.length<s))break}return{deleted:l}},async deleteMany(n,o,s){U(o.length,s?.limit,"deleteMany");for(const c of o)await R(n,c,"delete",l=>l.delete(n,c));return{deleted:o.length}},async deleteWhere(n,o,s){const{baseWhere:c}=u(n),l=K(s?.limit,"deleteWhere",_),d=await y(n).findMany(n,{baseWhere:W(o,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return Q(h.length,l,"deleteWhere",_),{deleted:await V(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:s}=u(n);return y(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findFirstOrThrow(n,o){const{baseWhere:s}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async explain(n,o){const{baseWhere:s}=u(n);return y(n).explain(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findMany(n,o){const{baseWhere:s}=u(n);return y(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async get(n,o){const s=await $(n,o);if(!s.row)return null;if(s.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:l}=u(s.tableName);if(!l)return e.get(n,o);if(!c)return s.row;const d=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const s=o===void 0?await z(n):await $(o,n);if(!s.row)return null;if(s.tableName===void 0||!u(s.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=u(s.tableName);if(!c)return{row:s.row,tableName:s.tableName};const l=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:s.tableName}:null},async insert(n,o,s){if(a.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,s)}return e.insert(n,o,s)},async insertMany(n,o,s){if(U(o.length,s?.limit,"insertMany"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,s)}return e.insertMany(n,o,s)},async insertManyUnsafe(n,o,s){if(U(o.length,s?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,s)}return e.insertManyUnsafe(n,o,s)},patch:(n,o,s,c)=>j(n,o,s,(l,d)=>l.patch(n,o,s,{...c,verify:ce(c?.verify,d.verify)})),assertPatchAllowed:(n,o)=>j(n,o,{},()=>Promise.resolve()),async patchIf(n,o,s){const c=await j(n,o,s.patch,async(d,h)=>{if(d.patchIf===void 0)throw new p("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return d.patchIf(n,o,{...s,verify:ce(s.verify,h.verify)})});return c.doc===null||await I.get(n,o).then(d=>d!==null,d=>{if(Be(d)&&d.code==="RLS_REQUIRED")return!1;throw d})?c:{applied:c.applied,doc:null}},async patchMany(n,o,s){U(o.length,s?.limit,"patchMany");for(const c of o)await j(n,c.id,c.patch,(l,d)=>l.patch(n,c.id,c.patch,d));return{patched:o.length}},async patchWhere(n,o,s){const{baseWhere:c}=u(n),l=K(s?.limit,"patchWhere",_),h=(await y(n).findMany(n,{baseWhere:W(o.where,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return Q(h.length,l,"patchWhere",_),I.patchMany(n,h,s)},query(n){const{baseWhere:o}=u(n),s=y(n).query(n);return o?s.filter(Se(o,c=>Y(c,o))):s},related:ee===void 0?void 0:async(n,o)=>Ee({findMany:async(s,c)=>I.findMany(s,c),lookupById:async s=>t.lookupById?.(s)},ee,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>R(n,o,"update",async s=>{const c=s.restore??t.restore;if(!c)throw new p("BAD_REQUEST","restore is not supported by this writer");await c(n,o)}),replace:(n,o,s)=>R(n,o,"update",c=>c.replace(n,o,s),c=>({...s,_creationTime:s._creationTime??c._creationTime,_id:c._id})),aggregate(n,o){const{baseWhere:s}=u(n);return y(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},groupBy(n,o){const{baseWhere:s}=u(n);return y(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},rank(n,o,s){return C(n,"rank"),y(n).rank(n,o,s)},rankPage(n,o,s){return C(n,"rankPage"),y(n).rankPage(n,o,s)},wipeShard(){throw new p("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...oe("rankBefore",We,n=>(o,s,c)=>(C(o,"rankBefore"),(y(o).rankBefore??n)(o,s,c))),...oe("rankPageRows",Re,n=>(o,s,c)=>(C(o,"rankPageRows"),(y(o).rankPageRows??n)(o,s,c)))};if(a.size>0)for(const[n,o]of Object.entries(e))ct(o)&&Ae(I,n);return Object.defineProperty(I,be,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),I},Oe=e=>typeof e=="string"?e:e.name,ft=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(i=>Oe(i))));return t},dt=(e,t)=>{const r=new Set;for(const i of e)for(const a of t.get(i)??[])r.add(a);return i=>r.has(Oe(i))},ut=["roles","role"],ht=e=>{for(const t of ut){const r=e?.[t];if(typeof r=="string"){const i=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(i.length>0)return i}if(Array.isArray(r)){const i=r.filter(a=>typeof a=="string"&&a.length>0);if(i.length>0)return i}}return[]},yt=async(e,t)=>{const r=await e.getIdentity?.()??null,i=[...new Set([...ht(r),...e.roles??[]])];return{can:dt(i,t),identity:r,roles:i,userId:e.userId??null}},Rt=(e,t={})=>{const r=e,i=Ve(r),a=ft(t.roles);return ke(async({ctx:u,next:g})=>{const y=u,k={auth:await yt(y.auth??{},a),ctx:y},b=y.db,v=Ze(b),$=v?.base??b,z=v?.raw??b[Xe]??b,M=lt($,z,[...v?.steps??[],{context:k,perTable:i}]),R={db:M},{orm:L}=y;return L!==null&&typeof L=="object"&&(R.orm=Te(M)),g({ctx:R})},[{policies:r,roles:t.roles??[]}])};export{yt as a,ct as b,Wt as c,Fe as d,ht as e,et as f,dt as g,rt as h,ft as i,Y as m,oe as o,Rt as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-
|
|
1
|
+
import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-CHYtnvZP.mjs";import"./bindOrm-D5mVDvbi.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,p as resolvePolicyAuth,c as rls};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-
|
|
1
|
+
import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-CHYtnvZP.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
|
|
@@ -1040,7 +1040,7 @@ interface FunctionHandle<Kind extends "action" | "mutation" | "query" | "stream"
|
|
|
1040
1040
|
* ctx object must annotate its `(reference, args)` explicitly — see
|
|
1041
1041
|
* `@lunora/testing`'s harness). It does not work: a concrete
|
|
1042
1042
|
* `RegisteredQuery<{…}, number>` is not assignable to a
|
|
1043
|
-
* `RegisteredFunction
|
|
1043
|
+
* `RegisteredFunction` constraint over `ArgsValidator`, because `handler`'s args
|
|
1044
1044
|
* are in a contravariant position. Two inference sites it is.
|
|
1045
1045
|
*/
|
|
1046
1046
|
/**
|
|
@@ -1040,7 +1040,7 @@ interface FunctionHandle<Kind extends "action" | "mutation" | "query" | "stream"
|
|
|
1040
1040
|
* ctx object must annotate its `(reference, args)` explicitly — see
|
|
1041
1041
|
* `@lunora/testing`'s harness). It does not work: a concrete
|
|
1042
1042
|
* `RegisteredQuery<{…}, number>` is not assignable to a
|
|
1043
|
-
* `RegisteredFunction
|
|
1043
|
+
* `RegisteredFunction` constraint over `ArgsValidator`, because `handler`'s args
|
|
1044
1044
|
* are in a contravariant position. Two inference sites it is.
|
|
1045
1045
|
*/
|
|
1046
1046
|
/**
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-
|
|
1
|
+
import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-CHYtnvZP.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
|
package/dist/types.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export type { b as ActionCtx, x as AggregateIndexDefinition, l as AggregateOp, A as ArgsValidator, N as AuthState, P as CachePurge, U as DatabaseReader, D as DatabaseWriter, w as DurableObjectJurisdiction, f as DurableStreamOptions, E as ExposeConfig, bs as ExternalSourceCursor, r as ExternalSourceDefinition, bt as ExternalSourceMode, bu as ExternalSourceRefresh, F as FunctionKind, Y as FunctionVisibility, Z as GeoBoundingBox, _ as GeoFilterBuilder, $ as GeoIndexDefinition, a0 as GeoPointInput, G as GlobalBackend, a1 as IndexDefinition, a2 as IndexRangeBuilder, I as InferArgs, K as KeyedRelationDefinition, C as LifecycleEvent, a3 as LifecycleEventKind, a4 as LogFields, a5 as LunoraLogMethod, a6 as LunoraLogger, a7 as LunoraMetrics, L as LunoraTracer, a8 as LunoraWideEvent, M as MutationCtx, a9 as MutationStorage, O as OnDeleteAction, aa as PaginationOptions, ab as PaginationResult, ac as PatchIfResult, Q as QueryCtx, y as RankIndexDefinition, ad as RankSortKey, ae as ReadOnlyStorage, R as RegisteredAction, k as RegisteredFunction, c as RegisteredInternalAction, d as RegisteredInternalMutation, e as RegisteredInternalQuery, g as RegisteredInternalStream, J as RegisteredLifecycleHook, h as RegisteredMutation, i as RegisteredQuery, j as RegisteredStream, af as RelatedDirection, ag as RelatedNode, ah as RelatedOptions, ai as RelatedPage, aj as RelatedStart, ak as RelatedStartReference, o as RelationDefinition, m as RelationThrough, al as RestCacheConfig, am as RetryPolicy, an as RunQueryOptions, ao as ScheduleRunOptions, ap as ScheduledFunctionDoc, aq as ScheduledJob, ar as ScheduledJobState, as as ScheduledJobView, at as Scheduler, S as Schema, au as SearchFilterBuilder, av as SearchIndexDefinition, p as SearchLanguage, q as SearchStrategy, z as Secrets, bv as SecretsStoreSecretLike, H as ShardInitEvent, aw as ShardMode, ax as SpanContextIds, ay as SpanEvaluation, a as SpanHandle, az as SpanIdentity, aA as SpanKind, aB as SpanLink, aC as SpanOptions, aD as Storage, aE as StorageListOptions, aF as StorageListResult, aG as StorageMetadata, aH as StorageMultipartUpload, aI as StorageMultipartUploadOptions, aJ as StorageObjectBody, aK as StorageObjectHead, aL as StorageRange, aM as StorageUploadBody, aN as StorageUploadOptions, aO as StorageUploadResult, aP as StorageUploadedPart, aQ as SystemDatabaseReader, aR as SystemDoc, aS as SystemQuery, aT as SystemTableName, T as TableDefinition, aU as TableReader, aV as TableVectorIndex, n as ThroughRelationDefinition, aW as TriggerAggregateOptions, s as TriggerBuilder, aX as TriggerCtx, aY as TriggerDatabase, t as TriggerDefinition, aZ as TriggerDeleteEvent, a_ as TriggerEvent, a$ as TriggerGroupByEntry, b0 as TriggerGroupByOptions, b1 as TriggerHandler, b2 as TriggerInsertEvent, b3 as TriggerOp, b4 as TriggerQueryArgs, b5 as TriggerQueryPage, b6 as TriggerRankOptions, b7 as TriggerRankPageOptions, b8 as TriggerRankResult, b9 as TriggerRow, ba as TriggerTiming, bb as TriggerUpdateEvent, bc as TtlDefinition, u as VectorEmbedder, V as VectorIndexDefinition, bd as VectorMatch, be as VectorMatches, v as VectorMetric, bf as VectorQueryInput, bg as VectorRecord, bh as VectorSearch, bi as VectorSearchReader, bj as VectorUpsertInput, W as WhisperEvent, bk as WorkflowCreateOptions, bl as WorkflowEventDefinition, bm as WorkflowHandle, bn as WorkflowInstance, bo as WorkflowInstanceEvent, bp as WorkflowInstanceStatus, bq as WorkflowStatusResult, br as Workflows, X as X402ProcedureConfig } from "./packem_shared/types.d-
|
|
1
|
+
export type { b as ActionCtx, x as AggregateIndexDefinition, l as AggregateOp, A as ArgsValidator, N as AuthState, P as CachePurge, U as DatabaseReader, D as DatabaseWriter, w as DurableObjectJurisdiction, f as DurableStreamOptions, E as ExposeConfig, bs as ExternalSourceCursor, r as ExternalSourceDefinition, bt as ExternalSourceMode, bu as ExternalSourceRefresh, F as FunctionKind, Y as FunctionVisibility, Z as GeoBoundingBox, _ as GeoFilterBuilder, $ as GeoIndexDefinition, a0 as GeoPointInput, G as GlobalBackend, a1 as IndexDefinition, a2 as IndexRangeBuilder, I as InferArgs, K as KeyedRelationDefinition, C as LifecycleEvent, a3 as LifecycleEventKind, a4 as LogFields, a5 as LunoraLogMethod, a6 as LunoraLogger, a7 as LunoraMetrics, L as LunoraTracer, a8 as LunoraWideEvent, M as MutationCtx, a9 as MutationStorage, O as OnDeleteAction, aa as PaginationOptions, ab as PaginationResult, ac as PatchIfResult, Q as QueryCtx, y as RankIndexDefinition, ad as RankSortKey, ae as ReadOnlyStorage, R as RegisteredAction, k as RegisteredFunction, c as RegisteredInternalAction, d as RegisteredInternalMutation, e as RegisteredInternalQuery, g as RegisteredInternalStream, J as RegisteredLifecycleHook, h as RegisteredMutation, i as RegisteredQuery, j as RegisteredStream, af as RelatedDirection, ag as RelatedNode, ah as RelatedOptions, ai as RelatedPage, aj as RelatedStart, ak as RelatedStartReference, o as RelationDefinition, m as RelationThrough, al as RestCacheConfig, am as RetryPolicy, an as RunQueryOptions, ao as ScheduleRunOptions, ap as ScheduledFunctionDoc, aq as ScheduledJob, ar as ScheduledJobState, as as ScheduledJobView, at as Scheduler, S as Schema, au as SearchFilterBuilder, av as SearchIndexDefinition, p as SearchLanguage, q as SearchStrategy, z as Secrets, bv as SecretsStoreSecretLike, H as ShardInitEvent, aw as ShardMode, ax as SpanContextIds, ay as SpanEvaluation, a as SpanHandle, az as SpanIdentity, aA as SpanKind, aB as SpanLink, aC as SpanOptions, aD as Storage, aE as StorageListOptions, aF as StorageListResult, aG as StorageMetadata, aH as StorageMultipartUpload, aI as StorageMultipartUploadOptions, aJ as StorageObjectBody, aK as StorageObjectHead, aL as StorageRange, aM as StorageUploadBody, aN as StorageUploadOptions, aO as StorageUploadResult, aP as StorageUploadedPart, aQ as SystemDatabaseReader, aR as SystemDoc, aS as SystemQuery, aT as SystemTableName, T as TableDefinition, aU as TableReader, aV as TableVectorIndex, n as ThroughRelationDefinition, aW as TriggerAggregateOptions, s as TriggerBuilder, aX as TriggerCtx, aY as TriggerDatabase, t as TriggerDefinition, aZ as TriggerDeleteEvent, a_ as TriggerEvent, a$ as TriggerGroupByEntry, b0 as TriggerGroupByOptions, b1 as TriggerHandler, b2 as TriggerInsertEvent, b3 as TriggerOp, b4 as TriggerQueryArgs, b5 as TriggerQueryPage, b6 as TriggerRankOptions, b7 as TriggerRankPageOptions, b8 as TriggerRankResult, b9 as TriggerRow, ba as TriggerTiming, bb as TriggerUpdateEvent, bc as TtlDefinition, u as VectorEmbedder, V as VectorIndexDefinition, bd as VectorMatch, be as VectorMatches, v as VectorMetric, bf as VectorQueryInput, bg as VectorRecord, bh as VectorSearch, bi as VectorSearchReader, bj as VectorUpsertInput, W as WhisperEvent, bk as WorkflowCreateOptions, bl as WorkflowEventDefinition, bm as WorkflowHandle, bn as WorkflowInstance, bo as WorkflowInstanceEvent, bp as WorkflowInstanceStatus, bq as WorkflowStatusResult, br as Workflows, X as X402ProcedureConfig } from "./packem_shared/types.d-BTY_1dJ8.mjs";
|
|
2
2
|
import '@lunora/values';
|
package/dist/types.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export type { b as ActionCtx, x as AggregateIndexDefinition, l as AggregateOp, A as ArgsValidator, N as AuthState, P as CachePurge, U as DatabaseReader, D as DatabaseWriter, w as DurableObjectJurisdiction, f as DurableStreamOptions, E as ExposeConfig, bs as ExternalSourceCursor, r as ExternalSourceDefinition, bt as ExternalSourceMode, bu as ExternalSourceRefresh, F as FunctionKind, Y as FunctionVisibility, Z as GeoBoundingBox, _ as GeoFilterBuilder, $ as GeoIndexDefinition, a0 as GeoPointInput, G as GlobalBackend, a1 as IndexDefinition, a2 as IndexRangeBuilder, I as InferArgs, K as KeyedRelationDefinition, C as LifecycleEvent, a3 as LifecycleEventKind, a4 as LogFields, a5 as LunoraLogMethod, a6 as LunoraLogger, a7 as LunoraMetrics, L as LunoraTracer, a8 as LunoraWideEvent, M as MutationCtx, a9 as MutationStorage, O as OnDeleteAction, aa as PaginationOptions, ab as PaginationResult, ac as PatchIfResult, Q as QueryCtx, y as RankIndexDefinition, ad as RankSortKey, ae as ReadOnlyStorage, R as RegisteredAction, k as RegisteredFunction, c as RegisteredInternalAction, d as RegisteredInternalMutation, e as RegisteredInternalQuery, g as RegisteredInternalStream, J as RegisteredLifecycleHook, h as RegisteredMutation, i as RegisteredQuery, j as RegisteredStream, af as RelatedDirection, ag as RelatedNode, ah as RelatedOptions, ai as RelatedPage, aj as RelatedStart, ak as RelatedStartReference, o as RelationDefinition, m as RelationThrough, al as RestCacheConfig, am as RetryPolicy, an as RunQueryOptions, ao as ScheduleRunOptions, ap as ScheduledFunctionDoc, aq as ScheduledJob, ar as ScheduledJobState, as as ScheduledJobView, at as Scheduler, S as Schema, au as SearchFilterBuilder, av as SearchIndexDefinition, p as SearchLanguage, q as SearchStrategy, z as Secrets, bv as SecretsStoreSecretLike, H as ShardInitEvent, aw as ShardMode, ax as SpanContextIds, ay as SpanEvaluation, a as SpanHandle, az as SpanIdentity, aA as SpanKind, aB as SpanLink, aC as SpanOptions, aD as Storage, aE as StorageListOptions, aF as StorageListResult, aG as StorageMetadata, aH as StorageMultipartUpload, aI as StorageMultipartUploadOptions, aJ as StorageObjectBody, aK as StorageObjectHead, aL as StorageRange, aM as StorageUploadBody, aN as StorageUploadOptions, aO as StorageUploadResult, aP as StorageUploadedPart, aQ as SystemDatabaseReader, aR as SystemDoc, aS as SystemQuery, aT as SystemTableName, T as TableDefinition, aU as TableReader, aV as TableVectorIndex, n as ThroughRelationDefinition, aW as TriggerAggregateOptions, s as TriggerBuilder, aX as TriggerCtx, aY as TriggerDatabase, t as TriggerDefinition, aZ as TriggerDeleteEvent, a_ as TriggerEvent, a$ as TriggerGroupByEntry, b0 as TriggerGroupByOptions, b1 as TriggerHandler, b2 as TriggerInsertEvent, b3 as TriggerOp, b4 as TriggerQueryArgs, b5 as TriggerQueryPage, b6 as TriggerRankOptions, b7 as TriggerRankPageOptions, b8 as TriggerRankResult, b9 as TriggerRow, ba as TriggerTiming, bb as TriggerUpdateEvent, bc as TtlDefinition, u as VectorEmbedder, V as VectorIndexDefinition, bd as VectorMatch, be as VectorMatches, v as VectorMetric, bf as VectorQueryInput, bg as VectorRecord, bh as VectorSearch, bi as VectorSearchReader, bj as VectorUpsertInput, W as WhisperEvent, bk as WorkflowCreateOptions, bl as WorkflowEventDefinition, bm as WorkflowHandle, bn as WorkflowInstance, bo as WorkflowInstanceEvent, bp as WorkflowInstanceStatus, bq as WorkflowStatusResult, br as Workflows, X as X402ProcedureConfig } from "./packem_shared/types.d-
|
|
1
|
+
export type { b as ActionCtx, x as AggregateIndexDefinition, l as AggregateOp, A as ArgsValidator, N as AuthState, P as CachePurge, U as DatabaseReader, D as DatabaseWriter, w as DurableObjectJurisdiction, f as DurableStreamOptions, E as ExposeConfig, bs as ExternalSourceCursor, r as ExternalSourceDefinition, bt as ExternalSourceMode, bu as ExternalSourceRefresh, F as FunctionKind, Y as FunctionVisibility, Z as GeoBoundingBox, _ as GeoFilterBuilder, $ as GeoIndexDefinition, a0 as GeoPointInput, G as GlobalBackend, a1 as IndexDefinition, a2 as IndexRangeBuilder, I as InferArgs, K as KeyedRelationDefinition, C as LifecycleEvent, a3 as LifecycleEventKind, a4 as LogFields, a5 as LunoraLogMethod, a6 as LunoraLogger, a7 as LunoraMetrics, L as LunoraTracer, a8 as LunoraWideEvent, M as MutationCtx, a9 as MutationStorage, O as OnDeleteAction, aa as PaginationOptions, ab as PaginationResult, ac as PatchIfResult, Q as QueryCtx, y as RankIndexDefinition, ad as RankSortKey, ae as ReadOnlyStorage, R as RegisteredAction, k as RegisteredFunction, c as RegisteredInternalAction, d as RegisteredInternalMutation, e as RegisteredInternalQuery, g as RegisteredInternalStream, J as RegisteredLifecycleHook, h as RegisteredMutation, i as RegisteredQuery, j as RegisteredStream, af as RelatedDirection, ag as RelatedNode, ah as RelatedOptions, ai as RelatedPage, aj as RelatedStart, ak as RelatedStartReference, o as RelationDefinition, m as RelationThrough, al as RestCacheConfig, am as RetryPolicy, an as RunQueryOptions, ao as ScheduleRunOptions, ap as ScheduledFunctionDoc, aq as ScheduledJob, ar as ScheduledJobState, as as ScheduledJobView, at as Scheduler, S as Schema, au as SearchFilterBuilder, av as SearchIndexDefinition, p as SearchLanguage, q as SearchStrategy, z as Secrets, bv as SecretsStoreSecretLike, H as ShardInitEvent, aw as ShardMode, ax as SpanContextIds, ay as SpanEvaluation, a as SpanHandle, az as SpanIdentity, aA as SpanKind, aB as SpanLink, aC as SpanOptions, aD as Storage, aE as StorageListOptions, aF as StorageListResult, aG as StorageMetadata, aH as StorageMultipartUpload, aI as StorageMultipartUploadOptions, aJ as StorageObjectBody, aK as StorageObjectHead, aL as StorageRange, aM as StorageUploadBody, aN as StorageUploadOptions, aO as StorageUploadResult, aP as StorageUploadedPart, aQ as SystemDatabaseReader, aR as SystemDoc, aS as SystemQuery, aT as SystemTableName, T as TableDefinition, aU as TableReader, aV as TableVectorIndex, n as ThroughRelationDefinition, aW as TriggerAggregateOptions, s as TriggerBuilder, aX as TriggerCtx, aY as TriggerDatabase, t as TriggerDefinition, aZ as TriggerDeleteEvent, a_ as TriggerEvent, a$ as TriggerGroupByEntry, b0 as TriggerGroupByOptions, b1 as TriggerHandler, b2 as TriggerInsertEvent, b3 as TriggerOp, b4 as TriggerQueryArgs, b5 as TriggerQueryPage, b6 as TriggerRankOptions, b7 as TriggerRankPageOptions, b8 as TriggerRankResult, b9 as TriggerRow, ba as TriggerTiming, bb as TriggerUpdateEvent, bc as TtlDefinition, u as VectorEmbedder, V as VectorIndexDefinition, bd as VectorMatch, be as VectorMatches, v as VectorMetric, bf as VectorQueryInput, bg as VectorRecord, bh as VectorSearch, bi as VectorSearchReader, bj as VectorUpsertInput, W as WhisperEvent, bk as WorkflowCreateOptions, bl as WorkflowEventDefinition, bm as WorkflowHandle, bn as WorkflowInstance, bo as WorkflowInstanceEvent, bp as WorkflowInstanceStatus, bq as WorkflowStatusResult, br as Workflows, X as X402ProcedureConfig } from "./packem_shared/types.d-BTY_1dJ8.js";
|
|
2
2
|
import '@lunora/values';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.277",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -74,7 +74,7 @@
|
|
|
74
74
|
"dependencies": {
|
|
75
75
|
"@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
|
|
76
76
|
"@lunora/scheduler": "^1.0.0-alpha.170",
|
|
77
|
-
"@lunora/shard-engine": "^1.0.0-alpha.
|
|
77
|
+
"@lunora/shard-engine": "^1.0.0-alpha.204",
|
|
78
78
|
"@lunora/values": "^1.0.0-alpha.95",
|
|
79
79
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
80
80
|
"drizzle-orm": "1.0.0-rc.5",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{i as p,e as g,f as b,g as y}from"./middleware-CdoC33P7.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as K,a as q,o as _,b as z,c as G,d as C}from"./middleware-CdoC33P7.mjs";import{defineLazyFacade as H,bindOrm as J}from"./bindOrm-D5mVDvbi.mjs";import{tagMaskMiddleware as T}from"./buildMaskRegistry-DpWMtalG.mjs";const Q=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},a=(s,i,c)=>{const u={...s};for(const[w,l]of Object.entries(i))w in u&&(u[w]=Q(l,s[w],{...c,column:w,row:s}));return u},B=(s,i,c)=>({...s,page:s.page.map(u=>a(u,i,c))}),P=(s,i)=>{const c=G(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},x=(s,i,c,u)=>{if(typeof s!="function")return;const w=new Set,l=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&w.add(f),l())});s(l());for(const f of w)if(P(i,f))throw new S("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${f}" is not supported`)},V=(s,i,c,u)=>{const w=s.rankBefore,l=s.rankPageRows,f=(r,t)=>{const n=i.get(r);return n?t.map(o=>a(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?f:(n,o)=>t(n,f(n,o))}},y=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const d=u?.[r]?.[o]?.[t];if(!d)return;const g=d.find(I=>P(e,I));if(g!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${g}" — use an index whose declared fields are all unmasked, or unmask the column`)},A=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield a(o,t,c)},collect:async()=>(await r.collect()).map(e=>a(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const d=a(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:d}:{document:d,score:e.score}}),filter:o=>A(r.filter(e=>o(a(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?a(o,t,c):null},order:o=>A(r.order(o),t,n),paginate:async o=>B(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(d=>a(d,t,c)),unique:async()=>{const o=await r.unique();return o?a(o,t,c):null},withIndex:(o,e)=>(y(n,o,"withIndex","index"),x(e,t,n,"withIndex"),A(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(x(e,t,n,"withSearchIndex"),A(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(y(n,o,"withGeoIndex","geo"),A(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(d=>typeof d=="string"&&P(o,d));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},p=new Set;for(const r of i.values())for(const t of Object.keys(r))p.add(t);const O=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,d]of Object.entries(r))L(e,d,t,n,o)},L=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const d of Array.isArray(t)?t:[])O(d,n,o,e);return}if(r==="NOT"){O(t,n,o,e);return}if(!r.startsWith("__")){if(P(n,r))throw new S("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(C(t))for(const d of Object.values(t))O(d,p,`${o}.${r}`,e)}},F=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{p.size===0||t===void 0||O(t,F(r),r,n)},E=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const d of Object.keys(e))if(P(n,d))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${d}" is not supported`)}}},j=(r,t,n)=>{if(!(p.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const d=e,g=`${r}.${o}`;O(d.where,p,g,n),E(g,d.orderBy,p,n),j(g,d.with,n)}},W=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),E(r,t?.orderBy,F(r),n),j(r,t?.with,n)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,$=(r,t,n)=>{const o=v(t);h(r,o?.where,n),h(r,o?.baseWhere,n),j(r,o?.with,n)},M=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,U={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[d,g]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?M(e.through.table,e.through.from)??M(e.through.table,e.through.to):M(d,e.field)??M(g,e.references);return[o,I===void 0?e:{...e,refusal:`"${I}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:a(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return R(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=v(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){W(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?a(n,o,c):n},async findFirstOrThrow(r,t){W(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?a(n,o,c):n},async explain(r,t){return W(r,t,"explain"),s.explain(r,t)},async findMany(r,t){W(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?B(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:a(n,o,c)},related:s.related?async(r,t)=>await s.related(r,k(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?a(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?A(t,n,r):t},async rank(r,t,n){return $(r,n,"rank"),y(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){$(r,n,"rankPage"),y(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?B(o,e,c):o},..._("rankBefore",w,r=>(t,n,o)=>($(t,o,"rankBefore"),y(t,n,"rankBefore","rank"),r(t,n,o))),..._("rankPageRows",l,r=>async(t,n,o)=>{$(t,o,"rankPageRows"),y(t,n,"rankPageRows","rank");const e=await r(t,n,o),d=i.get(t);return d?{...e,rows:e.rows.map(g=>({...g,doc:a(g.doc,d,c)}))}:e})};if(p.size>0)for(const[r,t]of Object.entries(s))z(t)&&H(U,r);return U},rr=(s,i={})=>{const c=new Map(Object.entries(s)),u=K(i.roles),w=async({ctx:f,next:k})=>{const y=f,A={auth:await q(y.auth??{},u),ctx:y};if(i.bypass?.(A)===!0)return k();const R=V(y.db,c,A,i.indexFields),p={db:R},{orm:O}=y;return O!==null&&typeof O=="object"&&(p.orm=J(R)),k({ctx:p})},l=new Map;for(const[f,k]of c)l.set(f,new Set(Object.keys(k)));return T(w,{columns:l})};export{rr as mask};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p,isLunoraError as Oe}from"@lunora/errors";import{findRelated as ve,whereFilter as We}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{defineLazyFacade as Re,bindOrm as Ee}from"./bindOrm-D5mVDvbi.mjs";import{t as Ae}from"./policy-tag-V0lqFzgS.mjs";import{deny as Be}from"./allowAll-DkRAgItV.mjs";const G=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},te=4;class P extends Error{}const x=e=>e.includes("."),gt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},ce=e=>{const t=e.split(".");if(t.length>te||t.includes(""))throw new P(`field path "${e}" must have 1 to ${String(te)} non-empty segments`);return t},Se=(e,t)=>{if(!x(t))return e[t];let r=e;for(const s of ce(t)){if(!G(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},ae=(e,t,r,s)=>{const[c,...f]=t;if(c===void 0)throw new P(`field path "${s}" is empty`);if(e!=null&&!G(e))throw new P(`cannot set "${s}": "${c}" sits inside a value that is not an object`);const u=e??{};return{...u,[c]:f.length===0?r:ae(u[c],f,r,s)}},Te=(e,t)=>{const r=Object.keys(e).filter(c=>x(c));if(r.length===0)return e;for(const c of r){const f=r.find(u=>u!==c&&u.startsWith(`${c}.`));if(f!==void 0)throw new P(`patch sets both "${c}" and "${f}", which overlap; set one or the other`)}const s={};for(const[c,f]of Object.entries(e))x(c)||(s[c]=f);for(const c of r){const[f="",...u]=ce(c);if(Object.hasOwn(e,f))throw new P(`patch sets both "${f}" and "${c}"; set one or the other`);s[f]=ae(Object.hasOwn(s,f)?s[f]:t[f],u,e[c],c)}return s},ke=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},Ie=["every","is","isNot","none","some"],Pe=new Set(Ie),me=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Pe.has(r))},ne=(e,t,r)=>t?{[e]:r(t)}:{},le=500,z=(e,t,r)=>{if(e!==void 0&&e!==Number.POSITIVE_INFINITY&&(!Number.isInteger(e)||e<0))throw r(`${t}: batch limit must be a non-negative integer`);return e??le},H=(e,t,r,s)=>{if(e>t)throw s(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},J={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class R extends Error{}const fe=e=>{if(!G(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(J,r)))return{operand:e[r],operator:r}},_e=e=>fe(e)!==void 0,$e=(e,t,r,s)=>{const c=J[t];if(c.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const f=c.apply(s,r);if(!Number.isFinite(f))throw new R(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},de=(e,t)=>{const r=new Set;for(const[s,c]of Object.entries(e))t(s)!==void 0&&_e(c)&&r.add(s);return r},De=(e,t,r)=>{let s;for(const c of de(e,r)){const{operand:f,operator:u}=fe(e[c]),g=r(c);if(J[u].kind!==g)throw new R(`patch: "${u}" does not apply to the ${String(g)} column "${c}".`);s??={...e},s[c]=$e(c,u,f,t[c])}return s??e},Fe=(e,t)=>{const r=c=>{const f=t[c];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},s={...e};for(const c of de(e,r))try{Object.assign(s,De({[c]:e[c]},t,r))}catch(f){if(!(f instanceof R))throw f}try{return Te(s,t)}catch(c){if(c instanceof P)return s;throw c}},Me=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,S=0,E=1,m=e=>e?E:B,w=(e,t)=>e<t?e:t,Le=(e,t)=>e>t?e:t,ue=e=>e===S?S:m(e===B),re=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},T=e=>e==null,F=(e,t,r)=>{if(r===void 0)throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},je={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},Ce=(e,t,r)=>{let s=E;for(const c of["gt","gte","lt","lte"]){if(!(c in r))continue;const f=r[c];F(e,c,f);const u=x(e);if(u?ke(f)===void 0:!re(f))s=w(s,B);else if(T(t))s=w(s,S);else{const g=je[c],y=u?typeof t==typeof f:re(t);s=w(s,m(y&&g(t,f)))}}return s},oe=(e,t,r)=>{if(!Array.isArray(r))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},se=(e,t)=>t.length===0?B:T(e)?S:t.includes(e)?E:t.some(r=>T(r))?S:B,Ue=(e,t,r)=>{let s=E;if("in"in r&&(s=w(s,se(t,oe(e,"in",r.in)))),"notIn"in r&&(s=w(s,ue(se(t,oe(e,"notIn",r.notIn))))),"contains"in r){const c=r.contains;F(e,"contains",c),s=T(t)?w(s,S):w(s,m(typeof t=="string"&&typeof c=="string"&&t.includes(c)))}return"isNull"in r&&(s=w(s,m(r.isNull===!0===T(t)))),s},K=(e,t,r)=>t===null?m(r===T(e)):T(e)?S:m(r===(e===t)),xe=(e,t,r)=>{let s=E;return"eq"in r&&(F(e,"eq",r.eq),s=w(s,K(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),s=w(s,K(t,r.ne,!1))),s},Ne=(e,t,r)=>w(xe(e,t,r),w(Ue(e,t,r),Ce(e,t,r))),qe=(e,t,r,s)=>{if(t==="NOT")return ue(s(e,r??{}));if(!Array.isArray(r))return B;let c=t==="AND"?E:B;for(const f of r){const u=s(e,f);c=t==="AND"?w(c,u):Le(c,u)}return c},he=e=>e==="AND"||e==="OR"||e==="NOT",Ye=e=>X(e)&&Object.keys(e).every(t=>Me.includes(t)),N=e=>Object.keys(e).some(t=>{const r=e[t];return he(t)?t==="NOT"?N(r??{}):Array.isArray(r)&&r.some(s=>N(s??{})):me(r)}),ye=(e,t)=>{let r=E;for(const s of Object.keys(t)){const c=t[s];if(he(s)){r=w(r,qe(e,s,c,ye));continue}const f=Se(e,s);if(Ye(c)){r=w(r,Ne(s,f,c));continue}F(s,"eq",c),r=w(r,K(f,c,!0))}return r},q=(e,t)=>ye(e,t)===E,ie=(e,t)=>e===void 0||t===void 0?e??t:(r,s)=>e(r,s)&&t(r,s),I=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{H(e,z(t,r,I),r,I)},ze=Be(),He=Symbol.for("lunora.ctxdb.rls-unwrap"),pe=Symbol.for("lunora.rls.wrapped-chain"),Ke=e=>e[pe],Qe=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},Xe=(e,t)=>{const r=[];let s=!1;for(const c of e){if(c.on!=="read")continue;const f=c.when(t);if(f!==void 0){if(f===!0){s=!0;break}f!==!1&&r.push(f)}}if(!s)return r.length===0?ze:r.length===1?r[0]:{OR:r}},Ge=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(N(s))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return q(r,s)},Je=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||Ge(e,t,r);if(s===!1)return!1;if(N(s))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!q(t.row,s)?!1:r===void 0||q(r,s)},Ze=(e,t,r,s)=>{let c=!1;for(const f of e)if(f.on===t&&(c=!0,!Je(f,r,s)))return!1;return c},Ve=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),et=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),tt=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Ve.has(r)&&et(r,e[r]))},nt=e=>e===void 0?{}:X(e)&&tt(e)?e:{where:e},Q=e=>e!==void 0&&Object.keys(e).length>0,rt=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},v=(e,t)=>Q(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ot=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},st=(e,t,r)=>{const[s]=r,c=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const i=[];let a=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;a=!0;const O=Xe(h,d.context);O!==void 0&&i.push(O)}const l={baseWhere:rt(i),restricts:a};return f.set(n,l),l},g=(n,o,i,a)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!Ze(d,o,{...l.context,row:i},a))return!1}return!0},y=n=>u(n).restricts?t:e,b=n=>u(n).baseWhere,W=async(n,o)=>{const i=await t.get(n,o);return i?{row:i,tableName:c.has(n)?n:void 0}:{row:null,tableName:void 0}},_=async n=>{if(t.lookupById){const l=await t.lookupById(n);if(l)return{row:l.row,tableName:c.has(l.tableName)?l.tableName:void 0}}const o=[...c.keys()],a=(await Promise.all(o.map(async l=>{const d=await t.findFirst(l,{limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:l}:void 0}))).find(l=>l!==void 0);return a?{row:a.row,tableName:a.tableName}:{row:null,tableName:void 0}},Y=async(n,o)=>{const i=await W(n,o);return i.row&&i.tableName!==void 0?{row:i.row,tableName:i.tableName}:void 0},A=async(n,o,i,a,l)=>{const d=await Y(n,o);if(!d)return a(e);const h=l?l(d.row):void 0;if(!g(d.tableName,i,d.row,h))throw new p("FORBIDDEN",`${i} denied by policy`);return a(t,d.tableName)},M=(n,o,i)=>{if(i?.hard===!0)return!1;const a=e.softDeleteFields?.get(n);return a!==void 0&&o[a]!==null&&o[a]!==void 0},L=async(n,o,i,a,l)=>{const d=i?t:e,h=await d.findFirst(o,{...i?{baseWhere:u(o).baseWhere}:{},...a?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:v(l,{_id:n})});if(!h||M(o,h,a))return!1;if(i&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,a),!0},$=async(n,o,i,a)=>{const l=c.has(n),d=l?t:e,h=i===void 0?void 0:{hard:i},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const V of o){const ee=String(V._id);if(O){await L(ee,n,l,h,a)&&(D+=1);continue}if(l&&!g(n,"delete",V))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ee,h),D+=1}return D},j=(n,o,i,a)=>A(n,o,"update",(l,d)=>a(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...Fe(i,l)})),C=(n,o)=>{const{baseWhere:i}=u(n);if(Q(i))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},ge=e.rankBefore,be=e.rankPageRows,{relationEdges:Z}=e,k={...e,async count(n,o){const{baseWhere:i}=u(n),a=nt(o);return y(n).count(n,{...a,baseWhere:v(a.baseWhere,i),relationBaseWhere:b,restrictsCounts:(a.restrictsCounts??!1)||Q(i)})},delete:(n,o,i)=>A(n,o,"delete",a=>a.delete(n,o,i)),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??le),{baseWhere:a}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:a,limit:i,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await $(n,h,o?.hard),h.length<i))break}return{deleted:l}},async deleteMany(n,o,i){U(o.length,i?.limit,"deleteMany");for(const a of o)await A(n,a,"delete",l=>l.delete(n,a));return{deleted:o.length}},async deleteWhere(n,o,i){const{baseWhere:a}=u(n),l=z(i?.limit,"deleteWhere",I),d=await y(n).findMany(n,{baseWhere:v(o,a),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return H(h.length,l,"deleteWhere",I),{deleted:await $(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:i}=u(n);return y(n).findFirst(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async findFirstOrThrow(n,o){const{baseWhere:i}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async explain(n,o){const{baseWhere:i}=u(n);return y(n).explain(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async findMany(n,o){const{baseWhere:i}=u(n);return y(n).findMany(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:b})},async get(n,o){const i=await W(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:a,restricts:l}=u(i.tableName);if(!l)return e.get(n,o);if(!a)return i.row;const d=await t.findFirst(i.tableName,{baseWhere:a,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const i=o===void 0?await _(n):await W(o,n);if(!i.row)return null;if(i.tableName===void 0||!u(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:a}=u(i.tableName);if(!a)return{row:i.row,tableName:i.tableName};const l=await t.findFirst(i.tableName,{baseWhere:a,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:i.tableName}:null},async insert(n,o,i){if(c.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(U(o.length,i?.limit,"insertMany"),c.has(n)){for(const a of o)if(!g(n,"insert",a))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(U(o.length,i?.limit,"insertManyUnsafe"),c.has(n)){for(const a of o)if(!g(n,"insert",a))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i,a)=>j(n,o,i,(l,d)=>l.patch(n,o,i,{...a,verify:ie(a?.verify,d.verify)})),assertPatchAllowed:(n,o)=>j(n,o,{},()=>Promise.resolve()),async patchIf(n,o,i){const a=await j(n,o,i.patch,async(d,h)=>{if(d.patchIf===void 0)throw new p("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return d.patchIf(n,o,{...i,verify:ie(i.verify,h.verify)})});return a.doc===null||await k.get(n,o).then(d=>d!==null,d=>{if(Oe(d)&&d.code==="RLS_REQUIRED")return!1;throw d})?a:{applied:a.applied,doc:null}},async patchMany(n,o,i){U(o.length,i?.limit,"patchMany");for(const a of o)await j(n,a.id,a.patch,(l,d)=>l.patch(n,a.id,a.patch,d));return{patched:o.length}},async patchWhere(n,o,i){const{baseWhere:a}=u(n),l=z(i?.limit,"patchWhere",I),h=(await y(n).findMany(n,{baseWhere:v(o.where,a),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return H(h.length,l,"patchWhere",I),k.patchMany(n,h,i)},query(n){const{baseWhere:o}=u(n),i=y(n).query(n);return o?i.filter(We(o,a=>q(a,o))):i},related:Z===void 0?void 0:async(n,o)=>ve({findMany:async(i,a)=>k.findMany(i,a),lookupById:async i=>t.lookupById?.(i)},Z,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>A(n,o,"update",async i=>{const a=i.restore??t.restore;if(!a)throw new p("BAD_REQUEST","restore is not supported by this writer");await a(n,o)}),replace:(n,o,i)=>A(n,o,"update",a=>a.replace(n,o,i),a=>({...i,_creationTime:i._creationTime??a._creationTime,_id:a._id})),aggregate(n,o){const{baseWhere:i}=u(n);return y(n).aggregate(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:b})},groupBy(n,o){const{baseWhere:i}=u(n);return y(n).groupBy(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:b})},rank(n,o,i){return C(n,"rank"),y(n).rank(n,o,i)},rankPage(n,o,i){return C(n,"rankPage"),y(n).rankPage(n,o,i)},wipeShard(){throw new p("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...ne("rankBefore",ge,n=>(o,i,a)=>(C(o,"rankBefore"),(y(o).rankBefore??n)(o,i,a))),...ne("rankPageRows",be,n=>(o,i,a)=>(C(o,"rankPageRows"),(y(o).rankPageRows??n)(o,i,a)))};if(c.size>0)for(const[n,o]of Object.entries(e))ot(o)&&Re(k,n);return Object.defineProperty(k,pe,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),k},we=e=>typeof e=="string"?e:e.name,it=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>we(s))));return t},ct=(e,t)=>{const r=new Set;for(const s of e)for(const c of t.get(s)??[])r.add(c);return s=>r.has(we(s))},at=["roles","role"],lt=e=>{for(const t of at){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(c=>typeof c=="string"&&c.length>0);if(s.length>0)return s}}return[]},ft=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...lt(r),...e.roles??[]])];return{can:ct(s,t),identity:r,roles:s,userId:e.userId??null}},bt=(e,t={})=>{const r=e,s=Qe(r),c=it(t.roles);return Ae(async({ctx:u,next:g})=>{const y=u,b={auth:await ft(y.auth??{},c),ctx:y},W=y.db,_=Ke(W),Y=_?.base??W,A=_?.raw??W[He]??W,M=st(Y,A,[..._?.steps??[],{context:b,perTable:s}]),L={db:M},{orm:$}=y;return $!==null&&typeof $=="object"&&(L.orm=Ee(M)),g({ctx:L})},[{policies:r,roles:t.roles??[]}])};export{ft as a,ot as b,gt as c,me as d,lt as e,Xe as f,ct as g,Ze as h,it as i,q as m,ne as o,bt as r};
|