palgres 0.52.4 → 0.54.0
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/chunks/DMGBXJWT.js +309 -0
- package/dist/chunks/MMDAYJKI.js +2 -0
- package/dist/chunks/Q7U5AW6L.js +5 -0
- package/dist/dsl.js +2 -2
- package/dist/index.js +156 -125
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/types/access/src/apply.d.ts +96 -0
- package/types/access/src/base.d.ts +49 -0
- package/types/access/src/catalog.d.ts +53 -0
- package/types/access/src/compile.d.ts +120 -0
- package/types/access/src/errors.d.ts +7 -0
- package/types/access/src/index.d.ts +10 -0
- package/types/access/src/model.d.ts +87 -0
- package/types/access/src/reference.d.ts +12 -0
- package/types/access/src/text.d.ts +104 -0
- package/types/access/src/validation.d.ts +22 -0
- package/types/access/src/world.d.ts +43 -0
- package/types/palgres/src/access.d.ts +63 -0
- package/types/palgres/src/connect.d.ts +10 -1
- package/types/palgres/src/dsl/policy.d.ts +24 -0
- package/types/palgres/src/dsl/to-model.d.ts +11 -1
- package/types/palgres/src/forget.d.ts +6 -6
- package/types/palgres/src/index.d.ts +1 -1
- package/types/palgres/src/model.d.ts +8 -0
- package/types/palgres/src/plan.d.ts +5 -1
- package/types/palgres/src/query/access.d.ts +140 -0
- package/types/palgres/src/query/env-gen.d.ts +2 -0
- package/types/palgres/src/query/index.d.ts +9 -7
- package/types/palgres/src/query/surface.d.ts +6 -1
- package/types/palgres/src/query/typed.d.ts +13 -5
- package/dist/chunks/BY3RTSEH.js +0 -5
- package/dist/chunks/K6ULZX24.js +0 -2
- package/dist/chunks/MT46TNAQ.js +0 -2
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export interface ValidationFailure {
|
|
2
|
+
/** The expectation, as a sentence. */
|
|
3
|
+
expectation: string;
|
|
4
|
+
/** What the schema answers instead. */
|
|
5
|
+
answer: string;
|
|
6
|
+
}
|
|
7
|
+
export interface ValidationResult {
|
|
8
|
+
passed: number;
|
|
9
|
+
failed: ValidationFailure[];
|
|
10
|
+
}
|
|
11
|
+
/** What is wrong with the validation file itself (not with the schema's answers). */
|
|
12
|
+
export declare class ValidationFileError extends Error {
|
|
13
|
+
constructor(message: string);
|
|
14
|
+
}
|
|
15
|
+
/** The schema's text a validation file names, when it does not carry it: the path, for whoever reads files. */
|
|
16
|
+
export declare function schemaPathOf(doc: unknown): string | null;
|
|
17
|
+
/**
|
|
18
|
+
* Answers a validation file's expectations from its own rows and relationships. `schemaText` is the schema it
|
|
19
|
+
* names (read by the caller) — ignored when the file carries its own. Throws AccessError for a schema that does not
|
|
20
|
+
* hold together and ValidationFileError for a file that cannot be read as one.
|
|
21
|
+
*/
|
|
22
|
+
export declare function runValidation(doc: unknown, schemaText: string | null): ValidationResult;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** How a column's values compare, which is all a schema needs to know of its type. */
|
|
2
|
+
export type Family =
|
|
3
|
+
/** text, varchar and an enum: equal when the same characters. */
|
|
4
|
+
'text'
|
|
5
|
+
/** uuid: 8-4-4-4-12 hexadecimal digits, equal whatever the letters' case. */
|
|
6
|
+
| 'uuid'
|
|
7
|
+
/** smallint, integer, bigint: equal when the same number ("07" is 7). */
|
|
8
|
+
| 'int' | 'bool'
|
|
9
|
+
/** numeric and the floating types: a `where` may compare them; they are no key and no id. */
|
|
10
|
+
| 'numeric';
|
|
11
|
+
export interface TableShape {
|
|
12
|
+
/** The column whose value is the object's id. */
|
|
13
|
+
key: string;
|
|
14
|
+
/** Every column the schema reads, the key among them. */
|
|
15
|
+
columns: Record<string, Family>;
|
|
16
|
+
}
|
|
17
|
+
/** A column's value. An integer is a number or a bigint; a uuid and a text are strings. */
|
|
18
|
+
export type Value = string | number | bigint | boolean | null;
|
|
19
|
+
/** One stored relationship: `subjectType` is 'user' or a type's name. */
|
|
20
|
+
export interface Relationship {
|
|
21
|
+
objectType: string;
|
|
22
|
+
objectId: string;
|
|
23
|
+
relation: string;
|
|
24
|
+
subjectType: string;
|
|
25
|
+
subjectId: string;
|
|
26
|
+
}
|
|
27
|
+
export interface World {
|
|
28
|
+
/** By type name, for each type that names a table. */
|
|
29
|
+
tables: Map<string, {
|
|
30
|
+
shape: TableShape;
|
|
31
|
+
rows: Record<string, Value>[];
|
|
32
|
+
}>;
|
|
33
|
+
relationships: Relationship[];
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* An id as its type writes it, or null when the text is no value of that type: an integer's digits without a sign's
|
|
37
|
+
* zero or leading zeros, a uuid in lower case, a text as it is. Two ids are the same when this is the same — the
|
|
38
|
+
* database compares them the same way. An integer is at most 18 digits here, so that none overflows a bigint; a uuid
|
|
39
|
+
* is the hyphenated form alone.
|
|
40
|
+
*/
|
|
41
|
+
export declare function canonicalId(family: Family, text: string): string | null;
|
|
42
|
+
/** A column's value as an id's text: what `column::text` is in the database. Null stays null. */
|
|
43
|
+
export declare function idOf(family: Family, value: Value): string | null;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { type Compiled } from '../../access/src/index.js';
|
|
2
|
+
import type { Schema } from './model.js';
|
|
3
|
+
export declare const accessToken: (name: string) => string;
|
|
4
|
+
export declare const namesAccess: (text: string | undefined) => boolean;
|
|
5
|
+
/** A name as a policy may say it. */
|
|
6
|
+
export declare const ACCESS_NAME: RegExp;
|
|
7
|
+
/**
|
|
8
|
+
* What a version keeps of its compiled access schema (in its layout), so that the version after it can stand
|
|
9
|
+
* beside it and then take its place without compiling it again: a later compiler may write it otherwise, and what
|
|
10
|
+
* is in the database is what this one wrote.
|
|
11
|
+
*/
|
|
12
|
+
export interface RecordedAccess {
|
|
13
|
+
digest: string;
|
|
14
|
+
/** The compiled schema's name in the database: access_<digest>. */
|
|
15
|
+
schema: string;
|
|
16
|
+
names: {
|
|
17
|
+
type: string;
|
|
18
|
+
name: string;
|
|
19
|
+
view: string;
|
|
20
|
+
idType: string;
|
|
21
|
+
}[];
|
|
22
|
+
tables: {
|
|
23
|
+
type: string;
|
|
24
|
+
schema: string;
|
|
25
|
+
name: string;
|
|
26
|
+
key: string;
|
|
27
|
+
}[];
|
|
28
|
+
/** "The asker holds it on this row", for each name of a type with a table. */
|
|
29
|
+
predicates: {
|
|
30
|
+
type: string;
|
|
31
|
+
name: string;
|
|
32
|
+
sql: string;
|
|
33
|
+
}[];
|
|
34
|
+
/** The relations whose relationships are kept, each with the kinds of subject it takes: type, relation, subject. */
|
|
35
|
+
stored: [string, string, string][];
|
|
36
|
+
}
|
|
37
|
+
export interface AccessRoles {
|
|
38
|
+
authenticated: string;
|
|
39
|
+
service: string;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* The model's access schema, compiled against the model's own tables; null when it has none. Throws AccessError when
|
|
43
|
+
* the schema does not hold together or names a table or a column the model does not declare as it says.
|
|
44
|
+
*/
|
|
45
|
+
export declare function compileAccess(schema: Schema, roles: AccessRoles, aliases?: {
|
|
46
|
+
name: string;
|
|
47
|
+
type: string;
|
|
48
|
+
}[]): Compiled | null;
|
|
49
|
+
/** The digest a model's access schema compiles to: what the model carries, so that a compiler that writes it otherwise is another version. */
|
|
50
|
+
export declare function accessDigest(schema: Omit<Schema, 'access'>, text: string, roles: AccessRoles): string;
|
|
51
|
+
export declare function recordAccess(c: Compiled, text: string): RecordedAccess;
|
|
52
|
+
/**
|
|
53
|
+
* A policy's text with each name it reads replaced by that name's predicate on the table's rows. Answers what is
|
|
54
|
+
* wrong instead when the table is no type's, or the type has no such name.
|
|
55
|
+
*/
|
|
56
|
+
export declare function resolvePolicy(text: string, table: {
|
|
57
|
+
schema: string;
|
|
58
|
+
name: string;
|
|
59
|
+
}, access: Pick<RecordedAccess, 'tables' | 'predicates'> | null): {
|
|
60
|
+
sql: string;
|
|
61
|
+
} | {
|
|
62
|
+
refused: string;
|
|
63
|
+
};
|
|
@@ -18,6 +18,15 @@ export interface Binding {
|
|
|
18
18
|
pooled?: boolean;
|
|
19
19
|
/** Where a table of Postgres schema `name` is read by this version: the schema itself, or its version's views. */
|
|
20
20
|
schema(name: string): string;
|
|
21
|
+
/**
|
|
22
|
+
* The compiled access schema this version asks (its digest), when the app has one: what the app asks
|
|
23
|
+
* (access_<digest>.can, …) is asked of its own. Which version a transaction is, it says as it opens
|
|
24
|
+
* (palgres.version in the bind statement), so that while a migration is open a row policy answers each version
|
|
25
|
+
* by its own rules.
|
|
26
|
+
*/
|
|
27
|
+
access?: string;
|
|
28
|
+
/** That schema's text: what the engine reads the names an app may ask by from (Database.$access). */
|
|
29
|
+
accessText?: string;
|
|
21
30
|
}
|
|
22
31
|
/** The binding, for connections a transaction-mode pooler lends (Binding.pooled). */
|
|
23
32
|
export declare function pooledBinding(b: Binding): Binding;
|
|
@@ -28,7 +37,7 @@ export declare function pooledBinding(b: Binding): Binding;
|
|
|
28
37
|
* (applicationName). A pooled app (Binding.pooled) holds one such.
|
|
29
38
|
*/
|
|
30
39
|
export declare function sayRunning(b: Binding): string;
|
|
31
|
-
export declare function binding(version: number, direct: boolean): Binding;
|
|
40
|
+
export declare function binding(version: number, direct: boolean, access?: string, accessText?: string): Binding;
|
|
32
41
|
export declare class VersionNotMigrated extends Error {
|
|
33
42
|
readonly digest: string;
|
|
34
43
|
constructor(d: string);
|
|
@@ -61,6 +61,15 @@ export type PolicyExpr = {
|
|
|
61
61
|
kind: "isNull";
|
|
62
62
|
expr: PolicyExpr;
|
|
63
63
|
negated: boolean;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* "The asker holds this relation or permission on the row", as the app's
|
|
67
|
+
* access schema says it. The plan writes the compiled predicate in its
|
|
68
|
+
* place; until then it is a name.
|
|
69
|
+
*/
|
|
70
|
+
| {
|
|
71
|
+
kind: "access";
|
|
72
|
+
name: string;
|
|
64
73
|
} | {
|
|
65
74
|
/**
|
|
66
75
|
* A correlated `EXISTS (SELECT 1 FROM <table> <alias> WHERE <predicate>)`
|
|
@@ -234,6 +243,21 @@ export interface PolicyExprCtx<Cols extends string = string> {
|
|
|
234
243
|
auth: {
|
|
235
244
|
uid(): PolicyExprRef;
|
|
236
245
|
};
|
|
246
|
+
/**
|
|
247
|
+
* The asker holds a relation or a permission on this row, as the app's
|
|
248
|
+
* access schema defines it for the type this table carries:
|
|
249
|
+
*
|
|
250
|
+
* ```ts
|
|
251
|
+
* policy("members read").for("select").using(p.can("view"))
|
|
252
|
+
* ```
|
|
253
|
+
*
|
|
254
|
+
* It can stand beside other conditions (`p.or(p.can("view"), …)`). The
|
|
255
|
+
* schema is the app's (`db.access`); a name it does not have, or a table no
|
|
256
|
+
* type of it names, is refused when the migration is planned. Not allowed
|
|
257
|
+
* in a CHECK constraint, nor inside `existsIn` (it is about this table's
|
|
258
|
+
* row).
|
|
259
|
+
*/
|
|
260
|
+
can(name: string): PolicyExprRef;
|
|
237
261
|
/** A plain value, for saying explicitly that one side of a comparison is a literal. */
|
|
238
262
|
lit(v: string | number | boolean | null): PolicyExprRef;
|
|
239
263
|
and(...parts: PolicyExprRef[]): PolicyExprRef;
|
|
@@ -1,6 +1,16 @@
|
|
|
1
1
|
import { type Policy, type Schema, type Table } from '../model.js';
|
|
2
|
+
import { type AccessRoles } from '../access.js';
|
|
2
3
|
import type { SchemaDef } from './schema.js';
|
|
3
4
|
/** One or more schemas (db/public.ts, db/billing.ts, …) as the model. */
|
|
4
|
-
|
|
5
|
+
/**
|
|
6
|
+
* The schema files as the model. `access` is the app's access schema, as its text: it is compiled here against the
|
|
7
|
+
* tables declared (a schema that does not hold together, or names a table or a column they do not have as it says,
|
|
8
|
+
* throws AccessError), and the model carries what it compiled to. `roles` are the database's roles the app's
|
|
9
|
+
* requests take, when they are not the usual two.
|
|
10
|
+
*/
|
|
11
|
+
export declare function toModel(schemas: SchemaDef | SchemaDef[], options?: {
|
|
12
|
+
access?: string;
|
|
13
|
+
roles?: AccessRoles;
|
|
14
|
+
}): Schema;
|
|
5
15
|
/** The columns of `t` a policy's SQL names quoted — as the renderer writes a column; a hand-written policy that quotes nothing names none. */
|
|
6
16
|
export declare function policyColumns(t: Table, p: Policy): string[];
|
|
@@ -9,10 +9,13 @@ interface Begin {
|
|
|
9
9
|
interface Runs {
|
|
10
10
|
query(sql: string, params?: unknown[]): PromiseLike<unknown>;
|
|
11
11
|
}
|
|
12
|
-
|
|
12
|
+
/** What forgetting a user took: rows deleted, rows that forgot them, and — of an app with an access schema — the relationships they held. */
|
|
13
|
+
export interface Forgotten {
|
|
13
14
|
deleted: number;
|
|
14
15
|
detached: number;
|
|
15
|
-
|
|
16
|
+
relationships?: number;
|
|
17
|
+
}
|
|
18
|
+
export declare function forgetUser(sql: Begin, binding: Binding, schema: Schema, userId: string, serviceRole?: string): Promise<Forgotten>;
|
|
16
19
|
/**
|
|
17
20
|
* The same, in a transaction already open as service_role — a delivery's own ($asService(): all its handlers' work, or
|
|
18
21
|
* none, within the request's share of connections): in a savepoint of it, so a failure leaves the rest of the
|
|
@@ -21,8 +24,5 @@ export declare function forgetUser(sql: Begin, binding: Binding, schema: Schema,
|
|
|
21
24
|
*/
|
|
22
25
|
export declare function forgetUserIn(service: {
|
|
23
26
|
attempt<T>(fn: (tx: Runs) => Promise<T>): Promise<T>;
|
|
24
|
-
}, binding: Binding, schema: Schema, userId: string): Promise<
|
|
25
|
-
deleted: number;
|
|
26
|
-
detached: number;
|
|
27
|
-
}>;
|
|
27
|
+
}, binding: Binding, schema: Schema, userId: string): Promise<Forgotten>;
|
|
28
28
|
export {};
|
|
@@ -6,7 +6,7 @@ export { applicationName, cutOff, DEFAULT_ROLES, isDirect, MigrationOpen, Migrat
|
|
|
6
6
|
export type { Adoption, MigratorOptions, Pool, Reserved, StartResult, Status, Version } from './migrate.js';
|
|
7
7
|
export { bind, binding, bindStatement, pooledBinding, sayRunning, VersionNotMigrated } from './connect.js';
|
|
8
8
|
export type { Binding } from './connect.js';
|
|
9
|
-
export { forgetUser, forgetUserIn } from './forget.js';
|
|
9
|
+
export { forgetUser, forgetUserIn, type Forgotten } from './forget.js';
|
|
10
10
|
export { adoptionBaseline, drift, type Baseline } from './adopt.js';
|
|
11
11
|
export { introspect, type Introspected } from './introspect.js';
|
|
12
12
|
export { pullSchema, type Pulled } from './pull.js';
|
|
@@ -5,6 +5,14 @@ export interface Schema {
|
|
|
5
5
|
extensions: string[];
|
|
6
6
|
/** Named SQL the typed schema cannot say (an expression unique index, a function): applied once by name. */
|
|
7
7
|
raw: Raw[];
|
|
8
|
+
/**
|
|
9
|
+
* The app's access schema (who may do what on which object): its text, and the digest it compiles to — carried
|
|
10
|
+
* so that a compiler which writes it otherwise makes another version, and the database is compiled again.
|
|
11
|
+
*/
|
|
12
|
+
access?: {
|
|
13
|
+
text: string;
|
|
14
|
+
compiled: string;
|
|
15
|
+
};
|
|
8
16
|
}
|
|
9
17
|
export interface Table {
|
|
10
18
|
/** The Postgres schema; "public" unless given. */
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type RecordedAccess } from './access.js';
|
|
1
2
|
import { type Raw, type Schema } from './model.js';
|
|
2
3
|
import { type SearchGeneration } from './search.js';
|
|
3
4
|
/** A version's names: each visible table and column of the schema, and where it is in the database. */
|
|
@@ -11,6 +12,8 @@ export interface Layout {
|
|
|
11
12
|
physical: string;
|
|
12
13
|
}[];
|
|
13
14
|
}[];
|
|
15
|
+
/** The version's access schema as it was compiled into the database: what the version after it stands beside, then replaces. */
|
|
16
|
+
access?: RecordedAccess;
|
|
14
17
|
}
|
|
15
18
|
export type Step =
|
|
16
19
|
/** One transaction, under the migrator's lock timeout; tried again as a whole. */
|
|
@@ -111,10 +114,11 @@ export interface Roles {
|
|
|
111
114
|
service: string;
|
|
112
115
|
}
|
|
113
116
|
export interface PlanInput {
|
|
114
|
-
/** The version serving now, or null for a database Palgres has not migrated yet. */
|
|
117
|
+
/** The version serving now, or null for a database Palgres has not migrated yet; `access` is what its layout recorded of its access schema. */
|
|
115
118
|
from: {
|
|
116
119
|
n: number;
|
|
117
120
|
schema: Schema;
|
|
121
|
+
access?: RecordedAccess | null;
|
|
118
122
|
} | null;
|
|
119
123
|
/** The new version's number: past every version the database has recorded, an abandoned one too. */
|
|
120
124
|
next: number;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/** An object's id: text in the database; a number is written as its digits. */
|
|
2
|
+
export type AccessId = string | number | bigint;
|
|
3
|
+
/** One object of the access schema: its type and its id. */
|
|
4
|
+
export interface AccessObject<K extends string = string> {
|
|
5
|
+
type: K;
|
|
6
|
+
id: AccessId;
|
|
7
|
+
}
|
|
8
|
+
/** Who holds a relation: a user by id (a bare string is one), or an object — `{ type: "team", id }`. */
|
|
9
|
+
export type AccessSubject = string | {
|
|
10
|
+
user: string;
|
|
11
|
+
} | AccessObject;
|
|
12
|
+
export interface AccessRelationship {
|
|
13
|
+
object: {
|
|
14
|
+
type: string;
|
|
15
|
+
id: string;
|
|
16
|
+
};
|
|
17
|
+
relation: string;
|
|
18
|
+
subject: {
|
|
19
|
+
type: string;
|
|
20
|
+
id: string;
|
|
21
|
+
};
|
|
22
|
+
/** When it was given, ISO 8601. */
|
|
23
|
+
since: string;
|
|
24
|
+
}
|
|
25
|
+
export interface AccessHistoryEntry {
|
|
26
|
+
/** ISO 8601. */
|
|
27
|
+
at: string;
|
|
28
|
+
action: 'grant' | 'revoke';
|
|
29
|
+
object: {
|
|
30
|
+
type: string;
|
|
31
|
+
id: string;
|
|
32
|
+
};
|
|
33
|
+
relation: string;
|
|
34
|
+
subject: {
|
|
35
|
+
type: string;
|
|
36
|
+
id: string;
|
|
37
|
+
};
|
|
38
|
+
/** Who did it: what the app said (`by`), else the request's user, else the database login. */
|
|
39
|
+
by: string | null;
|
|
40
|
+
}
|
|
41
|
+
export interface AccessFilter {
|
|
42
|
+
/** Of this object; without an id, of every object of the type. */
|
|
43
|
+
object?: {
|
|
44
|
+
type: string;
|
|
45
|
+
id?: AccessId;
|
|
46
|
+
};
|
|
47
|
+
relation?: string;
|
|
48
|
+
subject?: AccessSubject;
|
|
49
|
+
/** At most this many (default 100, at most 1000). */
|
|
50
|
+
limit?: number;
|
|
51
|
+
}
|
|
52
|
+
export type AccessRefusal = 'no_schema' | 'unknown_type' | 'unknown_name' | 'not_kept' | 'bad_id' | 'no_object' | 'too_many' | 'not_the_service';
|
|
53
|
+
/** What an access question or change was refused for. Thrown before anything is sent wherever the schema alone says so. */
|
|
54
|
+
export declare class AccessRefused extends Error {
|
|
55
|
+
readonly code: AccessRefusal;
|
|
56
|
+
constructor(code: AccessRefusal, message: string, options?: {
|
|
57
|
+
cause?: unknown;
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
type Known<A> = [keyof A] extends [never] ? false : true;
|
|
61
|
+
/** A type of the schema. */
|
|
62
|
+
export type AccessTypeOf<A> = Known<A> extends true ? keyof A & string : string;
|
|
63
|
+
/** A relation or a permission a user can hold on a `K`. */
|
|
64
|
+
export type AccessNameOf<A, K> = K extends keyof A ? (A[K] extends {
|
|
65
|
+
names: infer N extends string;
|
|
66
|
+
} ? N : string) : string;
|
|
67
|
+
/** A relation a `K` keeps relationships of. */
|
|
68
|
+
export type AccessRelationOf<A, K> = K extends keyof A ? (A[K] extends {
|
|
69
|
+
relations: infer R;
|
|
70
|
+
} ? keyof R & string : string) : string;
|
|
71
|
+
/** What holds relation `R` of a `K`: a user (a bare id, or `{ user }`), or an object of a type the relation takes. */
|
|
72
|
+
export type AccessSubjectOf<A, K, R> = K extends keyof A ? A[K] extends {
|
|
73
|
+
relations: infer M;
|
|
74
|
+
} ? R extends keyof M ? M[R] extends infer S extends string ? (S extends 'user' ? string | {
|
|
75
|
+
user: string;
|
|
76
|
+
} : {
|
|
77
|
+
type: S;
|
|
78
|
+
id: AccessId;
|
|
79
|
+
}) : AccessSubject : AccessSubject : AccessSubject : AccessSubject;
|
|
80
|
+
/**
|
|
81
|
+
* `Database.$access`: the app's access schema, asked and changed.
|
|
82
|
+
*
|
|
83
|
+
* `can`, `objects` and `held` are about the request's caller. The rest name a subject or change who holds what, and
|
|
84
|
+
* are the service role's: `Database.$asService().$access` — where those three are still about the caller.
|
|
85
|
+
*/
|
|
86
|
+
export interface AccessOps<A = unknown> {
|
|
87
|
+
/** Whether the caller holds `name` — a relation or a permission — on the object. Nobody is signed in: no. */
|
|
88
|
+
can<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<boolean>;
|
|
89
|
+
/** The ids of the objects of `type` the caller holds `name` on. */
|
|
90
|
+
objects<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, type: K): Promise<string[]>;
|
|
91
|
+
/** Every relation and permission the caller holds on the object, sorted: what a screen shows or hides, in one statement. */
|
|
92
|
+
held<K extends AccessTypeOf<A>>(object: AccessObject<K>): Promise<AccessNameOf<A, K>[]>;
|
|
93
|
+
/** Whether `subject` (a user's id) holds `name` on the object. The service role's. */
|
|
94
|
+
check<K extends AccessTypeOf<A>>(subject: string, name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<boolean>;
|
|
95
|
+
/** The ids of the objects of `type` that `subject` holds `name` on. The service role's. */
|
|
96
|
+
objectsOf<K extends AccessTypeOf<A>>(subject: string, name: AccessNameOf<A, K>, type: K): Promise<string[]>;
|
|
97
|
+
/** The users who hold `name` on the object, sorted. Refused past 10,000 related subjects: ask `check` then. The service role's. */
|
|
98
|
+
subjects<K extends AccessTypeOf<A>>(name: AccessNameOf<A, K>, object: AccessObject<K>): Promise<string[]>;
|
|
99
|
+
/**
|
|
100
|
+
* Gives `subject` the relation on the object; false when they had it. The object must exist (a type with a table).
|
|
101
|
+
* `by` is who did it, kept in the history: the request's user when it is not said. The service role's.
|
|
102
|
+
*/
|
|
103
|
+
grant<K extends AccessTypeOf<A>, R extends AccessRelationOf<A, K>>(object: AccessObject<K>, relation: R, subject: AccessSubjectOf<A, K, R>, options?: {
|
|
104
|
+
by?: string;
|
|
105
|
+
}): Promise<boolean>;
|
|
106
|
+
/** Takes the relation back; false when they did not have it. In force from the next statement on. The service role's. */
|
|
107
|
+
revoke<K extends AccessTypeOf<A>, R extends AccessRelationOf<A, K>>(object: AccessObject<K>, relation: R, subject: AccessSubjectOf<A, K, R>, options?: {
|
|
108
|
+
by?: string;
|
|
109
|
+
}): Promise<boolean>;
|
|
110
|
+
/** The relationships kept, by object, relation and subject. The service role's. */
|
|
111
|
+
relationships(filter?: AccessFilter): Promise<AccessRelationship[]>;
|
|
112
|
+
/** What was given and taken, the latest first: who, to whom, when. The service role's. */
|
|
113
|
+
history(filter?: AccessFilter): Promise<AccessHistoryEntry[]>;
|
|
114
|
+
}
|
|
115
|
+
/** What a version's access schema lets the app say, read from its text once. */
|
|
116
|
+
export interface AccessNames {
|
|
117
|
+
/** The compiled schema's name in the database. */
|
|
118
|
+
schema: string;
|
|
119
|
+
types: Map<string, {
|
|
120
|
+
names: Set<string>;
|
|
121
|
+
kept: Map<string, Set<string>>;
|
|
122
|
+
}>;
|
|
123
|
+
}
|
|
124
|
+
/** The names of an access schema's text, for the version that compiled it to `digest`. */
|
|
125
|
+
export declare function accessNames(text: string, digest: string): AccessNames;
|
|
126
|
+
/** The app's access schema as an augmentation's body: a type an entry, its names and what its relations take. */
|
|
127
|
+
export declare function accessTypesBlock(text: string, indent: string): string;
|
|
128
|
+
interface Asks {
|
|
129
|
+
query<T = unknown>(sql: string, params?: unknown[]): Promise<T[]>;
|
|
130
|
+
}
|
|
131
|
+
/** Whose transaction asks: nobody's (no one is signed in), a signed-in user's, or the service role's. */
|
|
132
|
+
export type AccessAsker = 'anon' | 'authenticated' | 'service';
|
|
133
|
+
/**
|
|
134
|
+
* The access operations over what asks (`raw`: the transaction current when each is called), for the version whose
|
|
135
|
+
* access schema `names` are — undefined when the app declares none: every operation then says so. `as` is whose
|
|
136
|
+
* transaction it is: nobody (anon) holds nothing and is not the database's to ask, and only the service role's
|
|
137
|
+
* names a subject or changes who holds what — said here, since the database's refusal would end the transaction.
|
|
138
|
+
*/
|
|
139
|
+
export declare function accessOps(raw: () => Asks, names: AccessNames | undefined, as: AccessAsker, unanswered?: string): AccessOps;
|
|
140
|
+
export {};
|
|
@@ -11,6 +11,7 @@ export declare const ENV_BLOCK_END = "// palbase:env:end";
|
|
|
11
11
|
*/
|
|
12
12
|
export declare function makeEnvDts(schemas: readonly SchemaDef[], options?: {
|
|
13
13
|
module?: string;
|
|
14
|
+
access?: string;
|
|
14
15
|
}): string;
|
|
15
16
|
/**
|
|
16
17
|
* The same types as a block of their own, between the markers and holding the
|
|
@@ -20,4 +21,5 @@ export declare function makeEnvDts(schemas: readonly SchemaDef[], options?: {
|
|
|
20
21
|
*/
|
|
21
22
|
export declare function envBlock(schemas: readonly SchemaDef[], options?: {
|
|
22
23
|
module?: string;
|
|
24
|
+
access?: string;
|
|
23
25
|
}): string;
|
|
@@ -55,10 +55,10 @@ export interface DatabaseOptions {
|
|
|
55
55
|
*/
|
|
56
56
|
prepare?: boolean;
|
|
57
57
|
}
|
|
58
|
-
/** One request's — or one job's — database. `T`, `S`: the project's tables (the framework's `Tables`, `Schemas`). */
|
|
59
|
-
export interface RequestDatabase<T, S> {
|
|
60
|
-
/** What a handler reaches as `Database`: typed tables, the `$` operations, $atomic, $asService(). */
|
|
61
|
-
readonly database: EnvTypedDatabase<T, S>;
|
|
58
|
+
/** One request's — or one job's — database. `T`, `S`: the project's tables (the framework's `Tables`, `Schemas`); `A`: its access schema (`Access`). */
|
|
59
|
+
export interface RequestDatabase<T, S, A = unknown> {
|
|
60
|
+
/** What a handler reaches as `Database`: typed tables, the `$` operations, $access, $atomic, $asService(). */
|
|
61
|
+
readonly database: EnvTypedDatabase<T, S, A>;
|
|
62
62
|
/** The string-keyed client the typed surface is built on. */
|
|
63
63
|
readonly client: DBClient;
|
|
64
64
|
/** Commits what was opened — nothing, if nothing was. Once, after the handler returns. */
|
|
@@ -66,9 +66,9 @@ export interface RequestDatabase<T, S> {
|
|
|
66
66
|
/** Rolls back what was opened. Once, when the handler throws. */
|
|
67
67
|
rollback(reason: unknown): Promise<void>;
|
|
68
68
|
}
|
|
69
|
-
export interface AppDatabase<T, S> {
|
|
69
|
+
export interface AppDatabase<T, S, A = unknown> {
|
|
70
70
|
readonly binding: Binding;
|
|
71
|
-
request(identity: Identity, options?: RequestOptions): RequestDatabase<T, S>;
|
|
71
|
+
request(identity: Identity, options?: RequestOptions): RequestDatabase<T, S, A>;
|
|
72
72
|
/**
|
|
73
73
|
* Seals again, with the key in force, every encrypted value sealed with an
|
|
74
74
|
* older one — what follows a rotation of the project's field keys, once the
|
|
@@ -85,9 +85,11 @@ export interface AppDatabase<T, S> {
|
|
|
85
85
|
}[]>;
|
|
86
86
|
}
|
|
87
87
|
/** The engine over `binding`'s version, its `Database` typed by `T` (public's tables) and `S` (the other schemas'). */
|
|
88
|
-
export declare function createDatabase<T = Record<never, never>, S = Record<never, never
|
|
88
|
+
export declare function createDatabase<T = Record<never, never>, S = Record<never, never>, A = unknown>(options: DatabaseOptions): Promise<AppDatabase<T, S, A>>;
|
|
89
89
|
export type { DatabaseAdmissionOptions } from './admission.js';
|
|
90
90
|
export { fieldAddress, type FieldCipher, type FieldsSource } from '../fields.js';
|
|
91
|
+
export { AccessRefused, accessNames, accessTypesBlock } from './access.js';
|
|
92
|
+
export type { AccessFilter, AccessHistoryEntry, AccessId, AccessNameOf, AccessNames, AccessObject, AccessOps, AccessRefusal, AccessRelationOf, AccessRelationship, AccessSubject, AccessSubjectOf, AccessTypeOf } from './access.js';
|
|
91
93
|
export type { AtomicClient, DBClient, DBOps, FindManyOptions, RowLock, SearchOptions } from './client.js';
|
|
92
94
|
export type { Embed } from './search.js';
|
|
93
95
|
export type { DatabaseBudget, DatabaseDiagnostics, DatabaseDiagnosticsOptions, DatabaseQueryEvent } from './diagnostics.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type AccessAsker, type AccessNames } from './access.js';
|
|
1
2
|
import type { DBClient } from './client.js';
|
|
2
3
|
import type { EnvTypedDatabase } from './typed.js';
|
|
3
4
|
/**
|
|
@@ -6,4 +7,8 @@ import type { EnvTypedDatabase } from './typed.js';
|
|
|
6
7
|
* `S` the other schemas'). `$asService()` is built on each call, over the
|
|
7
8
|
* request's one service transaction.
|
|
8
9
|
*/
|
|
9
|
-
export declare function typedDatabase<T, S>(client: DBClient
|
|
10
|
+
export declare function typedDatabase<T, S, A = unknown>(client: DBClient, options?: {
|
|
11
|
+
access?: AccessNames;
|
|
12
|
+
as?: AccessAsker;
|
|
13
|
+
unanswered?: string;
|
|
14
|
+
}): EnvTypedDatabase<T, S, A>;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ColIsOptionalOnInsert, ColumnBuilder, ColumnType, ColValue } from '../dsl/columns.js';
|
|
2
2
|
import { type SchemaDef, type TableDef, type UniqueKeysOf } from '../dsl/schema.js';
|
|
3
|
+
import type { AccessOps } from './access.js';
|
|
3
4
|
import type { AtomicClient, DBClient, DBOps, RowLock, SearchOptions } from './client.js';
|
|
4
5
|
import type { Search } from '../model.js';
|
|
5
6
|
import { isColRef } from './guards.js';
|
|
@@ -469,9 +470,16 @@ export type DollarOps<T> = {
|
|
|
469
470
|
[K in keyof T as `$${string & K}`]: T[K];
|
|
470
471
|
};
|
|
471
472
|
/** The service_role sibling, and an $atomic scope's handle: the same surface, without $asService. */
|
|
472
|
-
export type EnvServiceDatabase<T, S> = EnvSchemaSurface<T, S> & {
|
|
473
|
+
export type EnvServiceDatabase<T, S, A = unknown> = EnvSchemaSurface<T, S> & {
|
|
473
474
|
/** Commits independently of the request; every retry is a new BEGIN … COMMIT. */
|
|
474
|
-
$atomic<R>(fn: (tx: AtomicDatabase<T, S>) => Promise<R>, options?: AtomicOptions): Promise<R>;
|
|
475
|
+
$atomic<R>(fn: (tx: AtomicDatabase<T, S, A>) => Promise<R>, options?: AtomicOptions): Promise<R>;
|
|
476
|
+
/**
|
|
477
|
+
* The app's access schema, on this transaction: whether the caller holds a
|
|
478
|
+
* permission on an object, and the objects they hold it on; as the service
|
|
479
|
+
* role, the same of any user, who holds one, and giving and taking
|
|
480
|
+
* relationships. `A` is the schema as types (the framework's `Access`).
|
|
481
|
+
*/
|
|
482
|
+
$access: AccessOps<A>;
|
|
475
483
|
$query: DBClient['query'];
|
|
476
484
|
$insert: DBClient['insert'];
|
|
477
485
|
$insertMany: DBClient['insertMany'];
|
|
@@ -505,12 +513,12 @@ export type EnvServiceDatabase<T, S> = EnvSchemaSurface<T, S> & {
|
|
|
505
513
|
* with their claims, anyone else `anon`; `$asService()` is the explicit,
|
|
506
514
|
* greppable way past it (service_role).
|
|
507
515
|
*/
|
|
508
|
-
export type EnvTypedDatabase<T, S> = EnvServiceDatabase<T, S> & {
|
|
516
|
+
export type EnvTypedDatabase<T, S, A = unknown> = EnvServiceDatabase<T, S, A> & {
|
|
509
517
|
/** The RLS-bypassing sibling; it has no $asService of its own. */
|
|
510
|
-
$asService(): EnvServiceDatabase<T, S>;
|
|
518
|
+
$asService(): EnvServiceDatabase<T, S, A>;
|
|
511
519
|
};
|
|
512
520
|
/** One root transaction's handle. */
|
|
513
|
-
export type AtomicDatabase<T, S> = Omit<EnvServiceDatabase<T, S>, '$atomic'>;
|
|
521
|
+
export type AtomicDatabase<T, S, A = unknown> = Omit<EnvServiceDatabase<T, S, A>, '$atomic'>;
|
|
514
522
|
/** A table of a SchemaDef: `search()` where its declaration has one. */
|
|
515
523
|
export type TypedTable<T extends TableDef> = TypedTableOps<T> & (T extends {
|
|
516
524
|
search: Search;
|
package/dist/chunks/BY3RTSEH.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
/*! palgres 0.52.4 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{createHash as z}from"node:crypto";function de(n){return`${n}_lookup`}function me(n,e){let t=r=>r==="cascade"||r==="set null"||r==="set default";return t(n)||t(e)}var L=class extends Error{problems;constructor(e){super(`the schema is not valid:
|
|
3
|
-
- ${e.join(`
|
|
4
|
-
- `)}`),this.name="SchemaError",this.problems=e}},pe=()=>({tables:[],enums:[],extensions:[],raw:[]}),b=n=>`${n.schema}.${n.name}`,J={int:"integer",int4:"integer",int2:"smallint",int8:"bigint",float4:"real",float8:"double precision",bool:"boolean",timestamptz:"timestamp with time zone",timestamp:"timestamp without time zone","timestamp without time zone":"timestamp without time zone",timetz:"time with time zone",time:"time without time zone",varchar:"character varying",char:"character",decimal:"numeric"};function D(n){let e=n.trim().replace(/\s+/g," "),t="";for(;e.endsWith("[]");)t+="[]",e=e.slice(0,-2).trim();let r=/^((?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_ ]*?)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*))?)\s*(\(.*\))?$/.exec(e);if(!r)return n.trim()+t;let a=r[2]?r[2].replace(/\s+/g,""):"",o=Q(r[1]);return o===void 0?n.trim()+t:o.length===1&&o[0].quoted?`"${o[0].name.replace(/"/g,'""')}"${a}${t}`:o.length===1?`${J[o[0].name]??o[0].name}${a}${t}`:`${o.map(l=>N(l.name)).join(".")}${a}${t}`}var N=n=>/^[a-z_][a-z0-9_$]*$/.test(n)?n:`"${n.replace(/"/g,'""')}"`,he=(n,e)=>`${N(n)}.${N(e)}`;function Q(n){let e=[],t=0;for(;t<n.length;){if(n[t]==='"'){let r=t+1,a="";for(;;){if(r>=n.length)return;if(n[r]==='"'){if(n[r+1]==='"'){a+='"',r+=2;continue}break}a+=n[r++]}e.push({name:a,quoted:!0}),t=r+1}else{let r=/^[A-Za-z_][A-Za-z0-9_ ]*/.exec(n.slice(t));if(!r)return;e.push({name:r[0].trim().toLowerCase(),quoted:!1}),t+=r[0].length}if(t<n.length){if(n[t]!==".")return;t++}}return e}var W=/^[A-Za-z_][A-Za-z0-9_$]*$/,Z=63;function g(n,e,t=!1){if(typeof e!="string"||e==="")return`${n} has no name`;if(t?e.includes("\0"):!W.test(e))return`${n} "${e}": a name is letters, digits and _ (starting with a letter or _)`;if(Buffer.byteLength(e)>Z)return`${n} "${e}": longer than Postgres' 63 bytes, it would be cut`;if(e.startsWith("palgres_")||e.startsWith("_palgres"))return`${n} "${e}": names starting with palgres_ are Palgres' own`}var V="vector",F=["cosine","euclidean","inner_product"],q=1536,G=2e3,R=4e3,X=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function A(n,e,t){let r=[];e.primaryKey.length!==1&&r.push(`${n} declares search and has ${e.primaryKey.length===0?"no primary key":`a primary key of ${e.primaryKey.length} columns`}: a row's vector is kept by its key \u2014 give the table a single-column primary key (uuid().primaryKey())`),(!Array.isArray(t.from)||t.from.length===0)&&r.push(`${n}: search.from is empty \u2014 name the text columns a row is found by (search: { from: ['title', 'body'], model })`);let a=new Set;for(let o of Array.isArray(t.from)?t.from:[]){a.has(o)&&r.push(`${n}: search.from names "${o}" twice \u2014 name each column once`),a.add(o);let l=e.columns.find(i=>i.name===o);l?l.ignored?r.push(`${n}: search.from names "${o}", which is ignored \u2014 take it out of search.from, or keep the column`):X.test(D(l.type))?l.generated&&r.push(`${n}: search.from names "${o}", a generated column \u2014 no write names it, so nothing would say when to embed the row again: name the columns it is computed from`):r.push(`${n}: search.from names "${o}", which is ${l.type} \u2014 search reads text (text, varchar, citext): name a text column, or keep the text in one`):r.push(`${n}: search.from names "${o}", which the table does not have \u2014 name its text columns`)}return(typeof t.model!="string"||t.model.trim()==="")&&r.push(`${n}: search.model is empty \u2014 name the embedding model (search: { from, model: 'embedding' })`),F.includes(t.metric)||r.push(`${n}: search.metric is ${JSON.stringify(t.metric)} \u2014 it is ${F.map(o=>`'${o}'`).join(", ")}`),(!Number.isInteger(t.dimensions)||t.dimensions<1||t.dimensions>R)&&r.push(`${n}: search.dimensions is ${String(t.dimensions)} \u2014 it is 1 to ${R}: pgvector indexes a vector of at most ${G} dimensions and a half-precision one of at most ${R}; ask the model for fewer (search: { dimensions: ${q} })`),t.staleness!=="null"&&t.staleness!=="keep"&&r.push(`${n}: search.staleness is ${JSON.stringify(t.staleness)} \u2014 it is 'null' (a changed row is not found by its old meaning) or 'keep' (it is, until embedded again)`),e.columns.some(o=>o.name==="_score"&&!o.ignored)&&r.push(`${n} declares search and has a column "_score": search() answers each row with its _score \u2014 rename the column`),r}function ye(n){let e=[],t=i=>i&&e.push(i),r=new Map,a=new Map,o=(i,c,f)=>{let u=`${i}.${c}`,d=a.get(u);d?e.push(`${f} "${c}" has the name of ${d} in schema ${i}`):a.set(u,f)};for(let i of n.enums)t(g("an enum",i.name)),i.values.length===0&&e.push(`enum ${i.schema}.${i.name} has no values`),new Set(i.values).size!==i.values.length&&e.push(`enum ${i.schema}.${i.name} names a value twice`);for(let i of n.tables){let c=b(i);t(g("a schema",i.schema)),t(g("a table",i.name)),r.has(c)&&e.push(`table ${c} is declared twice`),r.set(c,i),o(i.schema,i.name,`table ${c}`);let f=new Map,u=(s,m)=>{let C=f.get(s);C?e.push(`${m} "${s}" has the name of a ${C} of table ${c}`):f.set(s,m)},d=new Map;for(let s of i.columns)t(g(`column ${c}.${s.name}`,s.name)),d.has(s.name)&&e.push(`column ${c}.${s.name} is declared twice`),d.set(s.name,s),s.identity&&s.default!==void 0&&e.push(`column ${c}.${s.name}: an identity column has no default`),s.generated&&(s.default!==void 0||s.identity||s.fill!==void 0)&&e.push(`column ${c}.${s.name}: a generated column has no default, identity or fill`),s.generated&&!s.generated.expr.trim()&&e.push(`column ${c}.${s.name}: a generated column's expression is empty`),s.identity&&!["smallint","integer","bigint"].includes(D(s.type))&&e.push(`column ${c}.${s.name}: an identity column is smallint, integer or bigint`),s.identity&&s.nullable&&e.push(`column ${c}.${s.name}: an identity column is NOT NULL`);let h=(s,m)=>{let C=d.get(s);C?C.ignored&&e.push(`${m} names column "${s}", which is ignored`):e.push(`${m} names column "${s}", which ${c} does not have`)};for(let s of i.primaryKey)h(s,`the primary key of ${c}`);for(let s of i.primaryKey)d.get(s)?.nullable&&e.push(`column ${c}.${s} is in the primary key, so it is not nullable`);for(let s of i.uniques){t(g(`a unique constraint of ${c}`,s.name,!0)),o(i.schema,s.name,`unique constraint ${c}.${s.name}`),u(s.name,"unique constraint"),s.columns.length===0&&e.push(`unique constraint ${s.name} names no column`);for(let m of s.columns)h(m,`unique constraint ${s.name}`)}for(let s of i.indexes){t(g(`an index of ${c}`,s.name,!0)),o(i.schema,s.name,`index ${c}.${s.name}`),s.keys.length===0&&e.push(`index ${s.name} has no key`);for(let m of s.keys)"column"in m&&h(m.column,`index ${s.name}`);for(let m of s.include??[])h(m,`index ${s.name}`)}for(let s of i.checks)t(g(`a check of ${c}`,s.name,!0)),u(s.name,"check"),s.expr.trim()||e.push(`check ${s.name} has no expression`);for(let s of i.foreignKeys){t(g(`a foreign key of ${c}`,s.name,!0)),u(s.name,"foreign key"),(s.columns.length===0||s.columns.length!==s.refColumns.length)&&e.push(`foreign key ${s.name} names ${s.columns.length} column(s) and references ${s.refColumns.length}`);for(let m of s.columns)h(m,`foreign key ${s.name}`)}let E=new Set;for(let s of i.policies)t(g(`a policy of ${c}`,s.name,!0)),E.has(s.name)&&e.push(`policy ${c}.${s.name} is declared twice`),E.add(s.name),s.to.length===0&&e.push(`policy ${c}.${s.name} names no role`),s.for==="insert"&&s.using!==void 0&&e.push(`policy ${c}.${s.name}: an insert policy has only withCheck`),(s.for==="select"||s.for==="delete")&&s.withCheck!==void 0&&e.push(`policy ${c}.${s.name}: a ${s.for} policy has only using`);i.policies.length>0&&!i.rls&&e.push(`table ${c} has policies but row-level security off: they would do nothing`),i.search!==void 0&&e.push(...A(`table ${c}`,i,i.search))}for(let i of n.tables)for(let c of i.foreignKeys){let f=r.get(`${c.refSchema}.${c.refTable}`);if(!f){e.push(`foreign key ${c.name} of ${b(i)} references ${c.refSchema}.${c.refTable}, which is not declared`);continue}f.ignored&&e.push(`foreign key ${c.name} of ${b(i)} references ${b(f)}, which is ignored`);for(let u of c.refColumns)f.columns.some(d=>d.name===u&&!d.ignored)||e.push(`foreign key ${c.name} references ${b(f)}.${u}, which it does not have`)}let l=new Set;for(let i of n.raw)t(g("a raw unit",i.name)),l.has(i.name)&&e.push(`raw unit ${i.name} is declared twice`),l.add(i.name),i.sql.trim()||e.push(`raw unit ${i.name} has no SQL`),i.before&&i.table!==void 0&&e.push(`raw unit ${i.name}: before is for a schema's unit, not a table's \u2014 a table's is made after its table`);return e}function j(n){let e=t=>[...t].sort((r,a)=>r.name<a.name?-1:r.name>a.name?1:0);return{tables:[...n.tables].map(t=>({...t,schema:t.schema||"public",columns:t.columns.map(r=>({...r,type:D(r.type)})),uniques:e(t.uniques),indexes:e(t.indexes),checks:e(t.checks),foreignKeys:e(t.foreignKeys),policies:e(t.policies).map(r=>({...r,to:[...r.to].sort()}))})).sort((t,r)=>b(t)<b(r)?-1:b(t)>b(r)?1:0),enums:[...n.enums].sort((t,r)=>`${t.schema}.${t.name}`<`${r.schema}.${r.name}`?-1:1),extensions:[...new Set([...n.extensions,...n.tables.some(t=>t.search!==void 0)?[V]:[]])].sort(),raw:e(n.raw)}}function ge(n){let e=j(n),t=new Map(n.raw.map((r,a)=>[r.name,a]));return e.raw.sort((r,a)=>(t.get(r.name)??0)-(t.get(a.name)??0)),e}function O(n){return Array.isArray(n)?`[${n.map(O).join(",")}]`:n&&typeof n=="object"?`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:1).map(([t,r])=>`${JSON.stringify(t)}:${O(r)}`).join(",")}}`:JSON.stringify(n)}function be(n){return z("sha256").update(O(j(n))).digest("hex").slice(0,32)}var v=Symbol.for("palbase.table.meta"),x=Symbol.for("palbase.ref.target"),P=class{_def;constructor(e){if(e.trim()==="")throw new Error("foreignKey(name): a foreign key's name cannot be empty \u2014 Palbase reconciles constraints by name.");this._def={name:e,columns:[],refTable:"",refColumns:[]}}on(...e){return this._def.columns=e.map(t=>{let r=t.expr;if(r.kind!=="col")throw new Error(`foreignKey(${this._def.name}).on(): takes column references only \u2014 an expression cannot be part of a foreign key.`);return r.name}),this}references(e,...t){if(t.length===0)throw new Error(`foreignKey(${this._def.name}).references(): needs at least one target column.`);return this._def.refColumns=[...t],typeof e=="function"?(Object.defineProperty(this._def,x,{value:()=>e()[v],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[v].name,Object.defineProperty(this._def,x,{value:e[v],enumerable:!1,configurable:!0}),this)}onUpdate(e){return this._def.onUpdate=e,this}onDelete(e){return this._def.onDelete=e,this}match(e){return this._def.match=e,this}index(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).index(): only index(false) \u2014 an index is made unasked`);return this._def.index=!1,this}deferrable(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).deferrable(): only deferrable(false) \u2014 a key with an action is deferrable unasked`);return this._def.deferrable=!1,this}};function Y(n){return new P(n)}function B(n){let e=n instanceof P?n._def:n;if(e.columns.length===0)throw new Error(`foreignKey(${e.name}): needs at least one local column \u2014 call .on(...).`);let t=typeof e[x]=="function";if(e.refColumns.length===0||e.refTable===""&&!t)throw new Error(`foreignKey(${e.name}): needs the target table and its columns \u2014 call .references(...).`);if(e.columns.length!==e.refColumns.length)throw new Error(`foreignKey(${e.name}): ${e.columns.length} local column(s) (${e.columns.join(", ")}) but ${e.refColumns.length} target column(s) (${e.refColumns.join(", ")}) \u2014 the two lists must be the same length.`);return e}var y=class n{expr;constructor(e){this.expr=e}bin(e,t){return new n({kind:"binop",op:e,left:this.expr,right:ee(t)})}eq(e){return this.bin("eq",e)}neq(e){return this.bin("neq",e)}gt(e){return this.bin("gt",e)}gte(e){return this.bin("gte",e)}lt(e){return this.bin("lt",e)}lte(e){return this.bin("lte",e)}isNull(e=!1){return new n({kind:"isNull",expr:this.expr,negated:e})}and(...e){return new n({kind:"and",parts:[this.expr,...e.map(t=>t.expr)]})}or(...e){return new n({kind:"or",parts:[this.expr,...e.map(t=>t.expr)]})}not(){return new n({kind:"not",expr:this.expr})}};function ee(n){return n instanceof y?n.expr:{kind:"lit",value:n}}function k(n,e=0,t=""){let r=`pb_e${e}`;return{col:a=>new y(e===0?{kind:"col",name:a}:{kind:"col",name:a,alias:r}),auth:{uid:()=>new y({kind:"authUid"})},lit:a=>new y({kind:"lit",value:a}),and:(...a)=>new y({kind:"and",parts:a.map(o=>o.expr)}),or:(...a)=>new y({kind:"or",parts:a.map(o=>o.expr)}),not:a=>new y({kind:"not",expr:a.expr}),existsIn:(a,o)=>{let l=a[_],i=k(Object.keys(l.columns),e+1,t),c={kind:"exists",table:l.name,alias:`pb_e${e+1}`,outer:t,predicate:o(i).expr};return Object.defineProperty(c,x,{value:l,enumerable:!1,configurable:!0}),new y(c)}}}function p(n){return`"${n.replace(/"/g,'""')}"`}var S=class{_def;constructor(e){this._def={name:e,command:"all",roles:["authenticated"],using:null,withCheck:null,permissive:!0}}for(e){return this._def.command=e,this}to(...e){return this._def.roles=e,this}using(e){return this._def.using=e instanceof y?e.expr:e,this}memberOf(e,t,r={}){if(this._def.using!==null)throw new Error(`policy(${this._def.name}).memberOf(): this policy already has a using() expression. Write one or the other \u2014 memberOf IS the using expression.`);let a=r.column??"id",o=r.userColumn??"user_id";return this._def.using=`${p(a)} IN (SELECT ${p(t)} FROM ${p(e)} WHERE ${p(o)} = (select auth.uid()))`,this}withCheck(e){return this._def.withCheck=e instanceof y?e.expr:e,this}withoutIndexes(){return this._def.indexes=!1,this}as(e){return this._def.permissive=e==="permissive",this}};function Ee(n){return new S(n)}function T(n,e){switch(n.kind){case"exists":throw new Error(`check(${e}): \`existsIn(...)\` is a subquery and PostgreSQL forbids subqueries in a CHECK constraint \u2014 express a cross-table rule as a composite FOREIGN KEY (foreignKeys), or as a guard.`);case"authUid":throw new Error(`check(${e}): \`auth.uid()\` renders as a subquery \`(SELECT auth.uid())\` and PostgreSQL forbids subqueries in a CHECK constraint \u2014 a caller-dependent rule belongs in an RLS policy, not a CHECK.`);case"binop":T(n.left,e),T(n.right,e);return;case"and":case"or":for(let t of n.parts)T(t,e);return;case"not":case"isNull":T(n.expr,e);return;default:return}}var ne={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function U(n){if(n===null)return"NULL";if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error(`check(): ${n} is not an SQL number literal.`);return String(n)}return`'${n.replace(/'/g,"''")}'`}function $(n,e){switch(n.kind){case"col":return p(n.name);case"lit":return U(n.value);case"binop":{let t=ne[n.op];if(t===void 0)throw new Error(`check(${e}): \`${n.op}\` is not supported in a CHECK expression.`);return`(${$(n.left,e)} ${t} ${$(n.right,e)})`}case"and":case"or":{if(n.parts.length===0)return n.kind==="and"?"(true)":"(false)";let t=n.kind==="and"?" AND ":" OR ";return`(${n.parts.map(r=>$(r,e)).join(t)})`}case"not":return`(NOT ${$(n.expr,e)})`;case"isNull":return`(${$(n.expr,e)} IS ${n.negated?"NOT NULL":"NULL"})`;default:{let t=n.kind;throw new Error(`check(${e}): a \`${t}\` node is not one a CHECK expression takes.`)}}}function te(n,e){if(n.trim()==="")throw new Error("check(): the constraint's name cannot be empty \u2014 Palbase reconciles CHECKs by name.");return T(e.expr,n),{name:n,expr:$(e.expr,n)}}function Ce(n){if(n!==null)return typeof n=="string"?n:w(n,"")}var re={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function H(n){let e=n.indexOf(".");return e<0?`${p("public")}.${p(n)}`:`${p(n.slice(0,e))}.${p(n.slice(e+1))}`}function w(n,e){switch(n.kind){case"col":return n.alias!==void 0?`${p(n.alias)}.${p(n.name)}`:e===""?p(n.name):`${H(e)}.${p(n.name)}`;case"authUid":return"(SELECT auth.uid())";case"lit":return U(n.value);case"binop":{let t=re[n.op];if(t===void 0)throw new Error(`policy expression: \`${n.op}\` is not an operator a policy can use`);return`(${w(n.left,e)} ${t} ${w(n.right,e)})`}case"and":case"or":return n.parts.length===0?n.kind==="and"?"(true)":"(false)":`(${n.parts.map(t=>w(t,e)).join(n.kind==="and"?" AND ":" OR ")})`;case"not":return`(NOT ${w(n.expr,e)})`;case"isNull":return`(${w(n.expr,e)} IS ${n.negated?"NOT NULL":"NULL"})`;case"exists":if(n.outer==="")throw new Error("policy expression: an existsIn carries no outer table \u2014 its correlation would collapse to x = x and filter nothing");return`EXISTS (SELECT 1 FROM ${H(n.table)} ${p(n.alias)} WHERE (${w(n.predicate,n.outer)}))`}}function M(n,e){return n===""||n==="public"?e:`${n}.${e}`}var K=class{_def;constructor(e){if(e.trim()==="")throw new Error("index(name): an index's name cannot be empty \u2014 Palbase reconciles indexes by name.");this._def={name:e}}unique(){return this._def.unique=!0,this}on(...e){return this._def.columns=e.map(t=>{let r=t.expr;if(r.kind!=="col")throw new Error(`index(${this._def.name}).on(): takes column references only \u2014 for an expression, use onExpression("\u2026").`);return r.name}),this}onExpression(e){return this._def.expression=e,this}where(e){return this._def.where=e.expr,this}desc(){return this._def.sort="desc",this}asc(){return this._def.sort="asc",this}nulls(e){return this._def.nulls=e,this}include(e){return this._def.include=e,this}};function Re(n){return new K(n)}function ie(n){return n instanceof S?n._def:n}var _=Symbol.for("palbase.table.meta");function Ne(n,e){if(n.trim()==="")throw new Error("defineTable(name, \u2026): name must not be empty");let t=(e.policies?.(k(Object.keys(e.columns),0,n))??[]).map(ie),r=t.length>0||e.rls!==!1,a={};for(let[u,d]of Object.entries(e.columns)){let h=d;ce(n,u,h._def),ae(n,u,h._def,e.columns);let E=Object.create(Object.getPrototypeOf(h));Object.defineProperty(E,"_def",{value:{...h._def},enumerable:!0,writable:!0}),a[u]=E}let o={name:n,columns:a,rls:r,policies:t};if(e.primaryKey!==void 0&&(o.primaryKey=[...e.primaryKey]),e.search!==void 0&&(o.search=se(n,e.search,a,o.primaryKey)),e.unique!==void 0&&(o.unique=e.unique.map(u=>({name:u.name,columns:[...u.columns]}))),e.raw!==void 0&&e.raw.length>0){for(let u of e.raw)if(u.drop!==void 0)throw new Error(`defineTable(${JSON.stringify(n)}): raw ${JSON.stringify(u.name)} carries a drop, but a table-level raw() has no teardown \u2014 a drop is run only for a schema-level unit: defineSchema(name, { tables, raw: [raw(name, up, { drop })] })`);o.raw=e.raw.slice()}let l=typeof e.checks=="function"?e.checks(k(Object.keys(e.columns),0,n)):e.checks?.slice()??[];l.length>0&&(o.checks=l);let i=(e.indexes?.(k(Object.keys(e.columns),0,n))??[]).map(u=>u instanceof K?u._def:u);i.length>0&&(o.indexes=i);let c=(e.foreignKeys?.(k(Object.keys(e.columns),0,n))??[]).map(B);c.length>0&&(o.foreignKeys=c),e.ignored===!0&&(o.ignored=!0),le(n,o);for(let u of Object.values(a))u._def.ownerTable=o;let f={...a};return Object.defineProperty(f,_,{value:o,enumerable:!1}),f}function se(n,e,t,r){if(e===null||typeof e!="object")throw new Error(`defineTable(${JSON.stringify(n)}): search is { from: [...columns], model } \u2014 got ${e===null?"null":typeof e}`);let a={from:Array.isArray(e.from)?[...e.from]:e.from,model:e.model,dimensions:e.dimensions??q,metric:e.metric??"cosine",staleness:e.staleness??"null"},o=Object.entries(t).map(([i,c])=>({name:i,def:c._def})),l=A(`defineTable(${JSON.stringify(n)})`,{columns:o.map(({name:i,def:c})=>({name:i,type:c.type==="sql"?c.sqlType??"sql":c.type,...c.ignored?{ignored:!0}:{},...c.generated?{generated:c.generated}:{}})),primaryKey:r??o.filter(({def:i})=>i.primaryKey===!0).map(({name:i})=>i)},a);if(l.length>0)throw new Error(l.join(`
|
|
5
|
-
`));return a}var I=new WeakMap;function oe(n,e){for(let t of Object.values(n))ue(t,`table "${t.name}"`,e);for(let t of Object.values(n))for(let[r,a]of Object.entries(t.columns)){let o=a._def;if(o.selfRefColumn!==void 0){if(!(o.selfRefColumn in t.columns))throw new Error(`table "${t.name}" column "${r}": selfReferences("${o.selfRefColumn}") \u2014 no such column on this table`);o.references={table:M(e,t.name),column:o.selfRefColumn};continue}if(o.referencesThunk===void 0)continue;let l=o.referencesThunk(),i=l?._def?.ownerTable;if(i===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) must point at a column of a table declared with defineTable(...)`);let c=Object.entries(i.columns).find(([,u])=>u._def===l._def)?.[0];if(c===void 0)throw new Error(`table "${t.name}" column "${r}": the referenced column was not found on table "${i.name}"`);let f=I.get(i);if(f===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) points at table "${i.name}", which no defineSchema(...) has claimed yet \u2014 a foreign key cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);o.references={table:M(f,i.name),column:c}}}function ae(n,e,t,r){if(t.encrypted===void 0)return;let a=`${e}_lookup`,o=t.defaultValue!==void 0||t.defaultSql!==void 0||t.defaultRandom===!0||t.defaultNow===!0?"it has a default \u2014 the database would write it in plain text; give the value in the write":t.fill!==void 0?".fillWith() is SQL over the row in plain text; give the value in the write":t.primaryKey===!0?"it is the primary key \u2014 a key the database matches rows by cannot be ciphertext; keep an id, and the encrypted value beside it":t.references!==void 0||t.referencesThunk!==void 0?"it references another table \u2014 a foreign key compares values the database cannot read":t.identity!==void 0||t.generated!==void 0?"the database makes its value":t.user!==void 0?"it holds a user's id, which the platform matches rows by":t.codec!==void 0||t.transform!==void 0?"it has a codec or a transform \u2014 encryption is its transform":t.unique===!0&&!t.encrypted.lookup?".unique() needs { lookup: true } \u2014 what equality is kept by is the lookup":a in r?`the table has a column "${a}" of its own, where the lookup is kept`:null;if(o!==null)throw new Error(`defineTable(${JSON.stringify(n)}): column "${e}" \u2014 .encrypted(): ${o}`)}function le(n,e){let t=a=>e.columns[a]?._def.encrypted,r=a=>{throw new Error(`defineTable(${JSON.stringify(n)}): ${a}`)};for(let a of e.primaryKey??[])t(a)&&r(`the primary key names "${a}", which is .encrypted() \u2014 keep an id, and the encrypted value beside it`);for(let a of e.unique??[])for(let o of a.columns){let l=t(o);l&&!l.lookup&&r(`unique ${JSON.stringify(a.name)} names "${o}", which is .encrypted() without { lookup: true } \u2014 what equality is kept by is the lookup`)}for(let a of e.indexes??[]){let o=JSON.stringify([a.keys??[],a.columns??[]]);for(let l of Object.keys(e.columns))t(l)&&o.includes(JSON.stringify(l))&&r(`index ${JSON.stringify(a.name)} names "${l}", which is .encrypted() \u2014 an index of ciphertext orders nothing; equality is found by { lookup: true }, which is indexed`)}for(let a of e.search?.from??[])t(a)&&r(`search reads "${a}", which is .encrypted() \u2014 its text is not in the database to embed`)}function ce(n,e,t){if(t.fill===void 0)return;let r=t.defaultValue!==void 0||t.defaultRandom===!0||t.defaultNow===!0||t.defaultSql!==void 0?"the column has a default \u2014 the default already fills every row; keep one of the two":null;if(r!==null)throw new Error(`defineTable(${JSON.stringify(n)}): column "${e}" \u2014 .fillWith(): ${r}`)}function Oe(n,e){if(typeof n!="string")throw new Error(`defineSchema(...) takes the schema NAME first: defineSchema("public", { tables: [todos, lists] }). The one-argument form defineSchema({ tables: { \u2026 } }) is gone \u2014 a schema that does not say its own name cannot be told apart from another schema's table of the same name, which is what a cross-schema foreign key has to do. Migrate db/public.ts (one file per schema: db/public.ts, db/billing.ts \u2026): name the schema, and lift each table key onto the table itself with defineTable("todos", { columns: { \u2026 } }), then list the tables in the array.`);if(n.trim()==="")throw new Error("defineSchema(name, \u2026): name must not be empty");let t={};for(let l of e.tables){let i=l[_];if(t[i.name]!==void 0)throw new Error(`defineSchema("${n}"): two tables declare the name "${i.name}" \u2014 table names must be unique within a schema`);t[i.name]=i,I.set(i,n)}oe(t,n);let r=[...new Set(e.extensions??[])],a=(e.raw??[]).slice(),o=new Set;for(let l of a){if(typeof l.name!="string"||l.name.trim()==="")throw new Error(`defineSchema("${n}"): a raw unit needs a name`);if(o.has(l.name))throw new Error(`defineSchema("${n}"): two raw units are named "${l.name}" \u2014 a unit's name identifies it`);o.add(l.name)}return{name:n,tables:t,extensions:r,raw:a}}function ue(n,e,t){let r=(l,i)=>{let c=l[x];if(c===void 0)return;let f;try{f=typeof c=="function"?c():c}catch(h){throw new Error(`${e}: ${i} names its target through a callback that failed: ${h.message}`)}if(f==null||typeof f.name!="string")throw new Error(`${e}: ${i}'s callback does not answer a table \u2014 write references(() => otherTable, \u2026)`);let u=I.get(f);if(u===void 0)throw new Error(`${e}: ${i} points at table "${f.name}", which no defineSchema(...) has claimed yet \u2014 a cross-table reference cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);let d=M(u,f.name);l.refTable!==void 0&&(l.refTable=d),l.table!==void 0&&(l.table=d)};for(let l of n.foreignKeys??[])r(l,`foreignKey("${l.name}")`);let a=`${t}.${n.name}`,o=(l,i)=>{if(!(l==null||typeof l=="string"))switch(l.kind){case"exists":r(l,i),l.table.includes(".")||(l.table=`public.${l.table}`),l.outer=a,o(l.predicate,i);return;case"binop":o(l.left,i),o(l.right,i);return;case"and":case"or":for(let c of l.parts)o(c,i);return;case"not":case"isNull":o(l.expr,i);return;default:return}};for(let l of n.policies)o(l.using,`policy("${l.name}")`),o(l.withCheck,`policy("${l.name}")`);for(let l of n.indexes??[])o(l.where,`index("${l.name}")`)}export{de as a,me as b,L as c,pe as d,b as e,D as f,he as g,G as h,A as i,ye as j,j as k,ge as l,be as m,P as n,Y as o,M as p,K as q,Re as r,_ as s,Ne as t,Oe as u,y as v,k as w,S as x,Ee as y,te as z,Ce as A};
|