@ultimat3/entity 0.0.1 → 1.1.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/src/tenancy.ts CHANGED
@@ -1,8 +1,9 @@
1
- // Multi-tenancy is a guard, not a convention. An entity with an `orgId` column can
2
- // only be queried through a plan that carries an org predicate; building one without
3
- // it throws `X_TENANCY_UNSCOPED` at the seam instead of leaking another tenant's rows.
4
- import { tenancyUnscoped } from './errors';
5
- import type { TableDef } from './types';
1
+ // Multi-tenancy is a guard, not a convention. An entity with a tenant column can only be read
2
+ // through a plan that carries an org predicate; building one without it throws
3
+ // `X_TENANCY_UNSCOPED` at the seam instead of leaking another tenant's rows.
4
+
5
+ import { EntityError, tenancyUnscoped } from './errors';
6
+ import type { ColumnMap } from './types';
6
7
 
7
8
  export type Operator =
8
9
  | 'eq'
@@ -24,18 +25,62 @@ export interface Predicate {
24
25
 
25
26
  export type SortDirection = 'asc' | 'desc';
26
27
 
28
+ export interface SortKey {
29
+ readonly column: string;
30
+ readonly direction: SortDirection;
31
+ }
32
+
27
33
  export interface QueryPlan {
28
34
  readonly entity: string;
29
35
  readonly where: readonly Predicate[];
30
- readonly orderBy: readonly { readonly column: string; readonly direction: SortDirection }[];
36
+ readonly orderBy: readonly SortKey[];
31
37
  readonly limit: number;
38
+ /** Keyset position. There is no `offset` and there will not be one — see `repo.ts`. */
32
39
  readonly cursor?: string;
40
+ readonly select?: readonly string[];
33
41
  }
34
42
 
43
+ /** The property key a tenant column takes when it is not marked explicitly. */
35
44
  export const ORG_COLUMN = 'orgId';
36
45
 
37
- /** True when the table declares an `orgId` column — presence is the switch. */
38
- export const isOrgScoped = (table: TableDef): boolean => Object.hasOwn(table.columns, ORG_COLUMN);
46
+ /**
47
+ * `.tenant()` is the switch; a column literally named `orgId` counts too, so an entity cannot
48
+ * become unscoped by forgetting one call.
49
+ */
50
+ export const tenantColumnOf = (columns: ColumnMap): string | null => {
51
+ for (const [property, column] of Object.entries(columns)) {
52
+ if (column.$meta.tenant) return property;
53
+ }
54
+ return Object.hasOwn(columns, ORG_COLUMN) ? ORG_COLUMN : null;
55
+ };
56
+
57
+ export const isOrgScoped = (columns: ColumnMap): boolean => tenantColumnOf(columns) !== null;
58
+
59
+ /**
60
+ * `entity(name, { tenant: 'workspaceId' })` wins over inference — a tenant column need not be
61
+ * called `orgId` and need not carry `.tenant()`. Omitting it keeps the inference, so an entity
62
+ * cannot become unscoped by forgetting the key; naming a column that does not exist is a
63
+ * declaration error, because the alternative is a silently unscoped table.
64
+ */
65
+ export const resolveTenantColumn = (
66
+ entityName: string,
67
+ columns: ColumnMap,
68
+ declared: string | undefined,
69
+ ): string | null => {
70
+ if (declared === undefined) return tenantColumnOf(columns);
71
+ if (!Object.hasOwn(columns, declared)) {
72
+ const available = Object.keys(columns).join(', ');
73
+ // Not `invariantViolated`: its fix points at `x entity explain`, which describes invariants
74
+ // the author never wrote. What repairs this is one edit to the declaration, so the error
75
+ // carries that edit and both ways out of it.
76
+ throw new EntityError({
77
+ code: 'X_INVARIANT_VIOLATED',
78
+ cause: `${entityName}.tenant: tenant: '${declared}' names no column — pick from: ${available}`,
79
+ fix: `set tenant to one of ${available} in entity('${entityName}'), or remove the tenant key — inference then takes the .tenant() column, else one named ${ORG_COLUMN}`,
80
+ });
81
+ }
82
+ return declared;
83
+ };
39
84
 
40
85
  export const emptyPlan = (entity: string, limit = 50): QueryPlan => ({
41
86
  entity,
@@ -44,31 +89,35 @@ export const emptyPlan = (entity: string, limit = 50): QueryPlan => ({
44
89
  limit,
45
90
  });
46
91
 
47
- export const hasOrgPredicate = (plan: QueryPlan): boolean =>
48
- plan.where.some((predicate) => predicate.column === ORG_COLUMN);
92
+ export const hasOrgPredicate = (plan: QueryPlan, column: string = ORG_COLUMN): boolean =>
93
+ plan.where.some((predicate) => predicate.column === column);
49
94
 
50
95
  /** Adds the org predicate exactly once; calling it twice is not an error. */
51
- export const orgScoped = (plan: QueryPlan, orgId: string): QueryPlan =>
52
- hasOrgPredicate(plan)
96
+ export const orgScoped = (
97
+ plan: QueryPlan,
98
+ orgId: string,
99
+ column: string = ORG_COLUMN,
100
+ ): QueryPlan =>
101
+ hasOrgPredicate(plan, column)
53
102
  ? plan
54
- : { ...plan, where: [...plan.where, { column: ORG_COLUMN, op: 'eq', value: orgId }] };
103
+ : { ...plan, where: [...plan.where, { column, op: 'eq', value: orgId }] };
55
104
 
56
105
  /**
57
- * Called by every repository operation. Runtime here, and a build-time check in
58
- * `x verify` that no query for a tenant-scoped entity is constructed without it.
106
+ * Called by every repository operation. Runtime here, and a build-time check in `x verify`
107
+ * that no query for a tenant-scoped entity is constructed without it.
59
108
  */
60
109
  export const assertScoped = (
61
110
  entityName: string,
62
- table: TableDef,
111
+ tenantColumn: string | null,
63
112
  operation: string,
64
113
  plan: QueryPlan,
65
114
  ): void => {
66
- if (!isOrgScoped(table)) return;
67
- if (hasOrgPredicate(plan)) return;
115
+ if (tenantColumn === null) return;
116
+ if (hasOrgPredicate(plan, tenantColumn)) return;
68
117
  throw tenancyUnscoped(entityName, operation);
69
118
  };
70
119
 
71
- /** Debug/`x db explain` rendering. Values stay out: a plan is safe to log. */
120
+ /** Debug and `x db explain` rendering. Values stay out: a plan is safe to log. */
72
121
  export const describePlan = (plan: QueryPlan): string => {
73
122
  const where = plan.where
74
123
  .map((predicate) => `${predicate.column} ${predicate.op} ?`)
package/src/types.ts CHANGED
@@ -1,9 +1,12 @@
1
- // The narrow structural types this package consumes. Drizzle is the production
2
- // backing for `TableDef`/`ColumnDef` (see README), but declaring the shape we use
3
- // instead of depending on the ORM keeps the generated SQL readable and keeps this
4
- // package free of a dependency an agent would have to learn to read.
1
+ // The structural vocabulary of a column. The physical layer is this package's own hand-written
2
+ // `postgresDriver()` (`pg-driver.ts` / `pg-sql.ts`), not an ORM; declaring the narrow shape we
3
+ // consume keeps the emitted SQL readable and keeps this package free of a dependency an agent
4
+ // must learn to read.
5
+ //
6
+ // A column carries its TypeScript type in `$parse`, which is what lets the row type be derived
7
+ // from the column set instead of being written a second time as a hand-maintained schema.
5
8
 
6
- /** Postgres types the blessed column helpers emit. No `float` for money, ever. */
9
+ /** Postgres types the blessed builders emit. `money` expands to `bigint` + `char(3)`. */
7
10
  export type ColumnKind =
8
11
  | 'uuid'
9
12
  | 'text'
@@ -11,67 +14,114 @@ export type ColumnKind =
11
14
  | 'boolean'
12
15
  | 'integer'
13
16
  | 'bigint'
14
- | 'numeric'
15
17
  | 'timestamptz'
16
- | 'date'
17
- | 'jsonb';
18
+ | 'jsonb'
19
+ | 'money';
18
20
 
19
21
  export type ColumnDefault =
20
- | { readonly kind: 'sql'; readonly expression: string }
21
22
  | { readonly kind: 'value'; readonly value: string | number | boolean | null }
22
23
  | { readonly kind: 'generated'; readonly by: 'uuid-v7' | 'now' };
23
24
 
24
- export interface ReferenceDef {
25
- readonly table: string;
26
- readonly column: string;
27
- readonly onDelete?: 'cascade' | 'restrict' | 'set null';
25
+ export type OnDelete = 'cascade' | 'restrict' | 'set null';
26
+
27
+ export interface ReferenceOptions {
28
+ readonly onDelete?: OnDelete;
28
29
  }
29
30
 
30
- export interface ColumnDef<T> {
31
- /** snake_case physical name; the property key is the camelCase domain name. */
32
- readonly name: string;
31
+ /** The single value a money column puts on the row. Two physical columns back it. */
32
+ export interface MoneyValue {
33
+ readonly minor: bigint;
34
+ readonly currency: string;
35
+ }
36
+
37
+ /** What a writer may hand a money column. An integer `number` widens; a float throws. */
38
+ export interface MoneyInput {
39
+ readonly minor: bigint | number;
40
+ readonly currency: string;
41
+ }
42
+
43
+ /**
44
+ * What the author declared. Where it landed — table, property key, physical name — is the
45
+ * binding `entity()` records (see `column.ts`), so a name is never written twice.
46
+ */
47
+ export interface ColumnMeta {
33
48
  readonly kind: ColumnKind;
34
49
  readonly notNull: boolean;
35
50
  readonly primaryKey: boolean;
36
51
  readonly unique: boolean;
52
+ readonly index: boolean;
53
+ /** Presence of a tenant column is what turns tenancy on. See `tenancy.ts`. */
54
+ readonly tenant: boolean;
37
55
  readonly length?: number;
56
+ readonly values?: readonly string[];
38
57
  readonly default?: ColumnDefault;
39
- /** SQL expression emitted as a CHECK next to the column. */
40
- readonly check?: string;
41
- readonly references?: ReferenceDef;
42
- readonly index: boolean;
43
- readonly comment?: string;
44
- /**
45
- * Runtime guard AND the carrier of the column's TypeScript type. Every write goes
46
- * through it, which is how `money()` can refuse a float instead of rounding it.
47
- */
48
- readonly parse: (value: unknown) => T;
58
+ readonly onUpdate?: ColumnDefault;
59
+ /** Takes the physical name, so a CHECK can be written before that name is known. */
60
+ readonly check?: (column: string) => string;
61
+ /** A thunk: schema modules reference each other in a cycle. */
62
+ readonly references?: () => AnyColumn;
63
+ readonly onDelete?: OnDelete;
49
64
  }
50
65
 
51
- export type ColumnMap = Readonly<Record<string, ColumnDef<unknown>>>;
66
+ /**
67
+ * `Optional` is the phantom that says "this column has a default", so an insert may omit it.
68
+ * It is a real boolean at runtime too, so nothing has to be re-derived to check it.
69
+ */
70
+ export interface Column<T, Optional extends boolean = false> {
71
+ readonly $meta: ColumnMeta;
72
+ /** Runtime guard AND the carrier of the column's TypeScript type. */
73
+ readonly $parse: (value: unknown) => T;
74
+ readonly $optional: Optional;
75
+ /** `boolean`: only a uuid key carries a generated default, so only it becomes optional. */
76
+ primaryKey(): Column<T, boolean>;
77
+ nullable(): Column<T | null, Optional>;
78
+ unique(): Column<T, Optional>;
79
+ /** Marks the tenant column; a query without an org predicate then throws. */
80
+ tenant(): Column<T, Optional>;
81
+ references(target: () => AnyColumn, options?: ReferenceOptions): Column<T, Optional>;
82
+ default(value: T): Column<T, true>;
83
+ }
52
84
 
53
- export interface IndexDef {
54
- readonly name: string;
55
- readonly columns: readonly string[];
56
- readonly unique: boolean;
57
- /** Partial index predicate — soft-deleted rows are excluded with this. */
58
- readonly where?: string;
85
+ /** A uuid primary key is generated (v7) when omitted, which is why it narrows to `true`. */
86
+ export interface UuidColumn<Optional extends boolean = false> extends Column<string, Optional> {
87
+ primaryKey(): Column<string, true>;
59
88
  }
60
89
 
61
- export interface TableDef<C extends ColumnMap = ColumnMap> {
62
- readonly name: string;
63
- readonly columns: C;
64
- readonly primaryKey: readonly string[];
65
- readonly indexes: readonly IndexDef[];
90
+ export interface TimestampColumn<Optional extends boolean = false> extends Column<Date, Optional> {
91
+ defaultNow(): TimestampColumn<true>;
92
+ onUpdateNow(): TimestampColumn<Optional>;
66
93
  }
67
94
 
68
- /** The row type a table describes, derived from its columns' parse signatures. */
95
+ export type AnyColumn = Column<unknown, boolean>;
96
+
97
+ export type ColumnMap = Readonly<Record<string, AnyColumn>>;
98
+
99
+ export type TypeOf<C> = C extends Column<infer T, boolean> ? T : never;
100
+
101
+ /** The row type a column set describes. This derivation is why the package exists. */
69
102
  export type RowOf<C extends ColumnMap> = {
70
- readonly [K in keyof C]: C[K] extends ColumnDef<infer T> ? T : never;
103
+ readonly [K in keyof C]: TypeOf<C[K]>;
71
104
  };
72
105
 
73
- export const columnNames = (table: TableDef): readonly string[] =>
74
- Object.values(table.columns).map((column) => column.name);
106
+ type DefaultedKeys<C extends ColumnMap> = {
107
+ [K in keyof C]-?: C[K]['$optional'] extends true ? K : never;
108
+ }[keyof C];
109
+
110
+ /** Money is the one column whose write shape is wider than its row shape. */
111
+ type InputOf<T> = T extends MoneyValue ? MoneyInput : T;
112
+
113
+ /** What an insert must supply: every column except the ones carrying a default. */
114
+ export type Insertable<C extends ColumnMap> = {
115
+ readonly [K in Exclude<keyof C, DefaultedKeys<C>>]: InputOf<TypeOf<C[K]>>;
116
+ } & {
117
+ readonly [K in DefaultedKeys<C>]?: InputOf<TypeOf<C[K]>>;
118
+ };
75
119
 
76
- export const hasColumn = (table: TableDef, property: string): boolean =>
77
- Object.hasOwn(table.columns, property);
120
+ export interface IndexDef {
121
+ readonly name: string;
122
+ readonly columns: readonly string[];
123
+ readonly unique: boolean;
124
+ readonly order?: 'asc' | 'desc';
125
+ /** Partial index predicate — a soft-deleted row is excluded with this. */
126
+ readonly where?: string;
127
+ }
package/src/view.ts ADDED
@@ -0,0 +1,97 @@
1
+ // `posts.$view(['id', 'title'])` — the hop between an entity and an action's `output`: a Standard
2
+ // Schema over a subset of the row, so `output: PostView` never re-declares a shape the columns
3
+ // already describe. Values are validated by the entity's own column parsers; an unknown key is a
4
+ // declaration-time failure, not a surprise on the first request.
5
+
6
+ import type { StandardSchemaV1 } from '@ultimat3/schema';
7
+ import { invariantViolated } from './errors';
8
+ import type { AnyColumn, ColumnMap } from './types';
9
+
10
+ /**
11
+ * A row projection, usable anywhere a schema is. `$row` is the phantom that carries the type
12
+ * (`type PostView = typeof PostView.$row`); `$name` is how a manifest or an OpenAPI document
13
+ * identifies it.
14
+ */
15
+ export interface EntityView<Row, K extends keyof Row & string>
16
+ extends StandardSchemaV1<unknown, Pick<Row, K>> {
17
+ readonly $name: string;
18
+ readonly $keys: readonly K[];
19
+ /** Phantom: `type PostView = typeof PostView.$row`. Reading it at runtime throws. */
20
+ readonly $row: Pick<Row, K>;
21
+ }
22
+
23
+ /** Dots and underscores only, so the name is a legal `components.schemas` key unescaped. */
24
+ const viewName = (entityName: string, keys: readonly string[]): string =>
25
+ `${entityName}.view.${keys.join('_')}`;
26
+
27
+ /**
28
+ * Bound to an entity as `$view`; never exported as a free `view(entity, keys)`, because two ways
29
+ * to write the same projection is exactly the ambiguity the `$`-prefixed surface exists to avoid.
30
+ */
31
+ export const viewFor = <Row, K extends keyof Row & string>(
32
+ entityName: string,
33
+ columns: ColumnMap,
34
+ keys: readonly K[],
35
+ ): EntityView<Row, K> => {
36
+ // Resolved once, at declaration: a key naming no column is the author's typo, and the columns
37
+ // are listed because the agent reading the error is the one that has to pick the right key.
38
+ const picked: readonly (readonly [K, AnyColumn])[] = keys.map((key) => {
39
+ const column = columns[key];
40
+ if (column === undefined) {
41
+ throw invariantViolated(
42
+ entityName,
43
+ 'view',
44
+ `$view(['${key}']) names no column — pick from: ${Object.keys(columns).join(', ')}`,
45
+ );
46
+ }
47
+ return [key, column] as const;
48
+ });
49
+ const name = viewName(entityName, keys);
50
+
51
+ const parse = (value: unknown): Pick<Row, K> => {
52
+ if (typeof value !== 'object' || value === null) {
53
+ throw invariantViolated(entityName, 'view', `expected an object, got ${String(value)}`);
54
+ }
55
+ const input = value as Readonly<Record<string, unknown>>;
56
+ const projected = {} as Record<K, unknown>;
57
+ for (const [key, column] of picked) {
58
+ const given = input[key];
59
+ if (given === undefined || given === null) {
60
+ // No default is filled in: a view projects a row that already exists, so an absent
61
+ // required column is missing data, never a value the projection may invent.
62
+ if (column.$meta.notNull) throw invariantViolated(entityName, `view.${key}`, 'is required');
63
+ projected[key] = null;
64
+ continue;
65
+ }
66
+ projected[key] = column.$parse(given);
67
+ }
68
+ // Every picked key went through its own column's parser, so this is the derived projection.
69
+ return projected as Pick<Row, K>;
70
+ };
71
+
72
+ return {
73
+ '~standard': {
74
+ version: 1,
75
+ vendor: 'ultimate',
76
+ validate: (value) => {
77
+ try {
78
+ return { value: parse(value) };
79
+ } catch (error) {
80
+ return {
81
+ issues: [{ message: error instanceof Error ? error.message : String(error) }],
82
+ };
83
+ }
84
+ },
85
+ },
86
+ $name: name,
87
+ $keys: keys,
88
+ get $row(): Pick<Row, K> {
89
+ // Type-only, exactly as on the entity. Reading it means a type was meant.
90
+ throw invariantViolated(
91
+ entityName,
92
+ 'view.$row',
93
+ '$row is a type, not a value — use typeof x.$row',
94
+ );
95
+ },
96
+ };
97
+ };