@ultimat3/entity 31.38.1 → 31.40.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/CLAUDE.md CHANGED
@@ -74,7 +74,7 @@ A rule marked `†` has its full text in [`docs/history/entity-rules.md`](../../
74
74
  `groupColumnOf` before the statement and `countsFrom` after the rows. The bound is a REFUSAL at
75
75
  `MAX_GROUPS + 1`, never a truncation; it names a groupable column of THIS entity, never
76
76
  `x entity explain`. Full rule: `docs/history/entity.md`.
77
- - **The cursor codec is core's**; `assertSeekable` runs in `planFor`; a bad cursor is
77
+ - **The cursor codec is core's, and so is the scope's value form** — `planScope` renders each predicate value with `canonicalJson` (injective: `1` ≠ `'1'`), never a local serializer (`cursor-scope.test.ts`); `assertSeekable` runs in `planFor`; a bad cursor is
78
78
  `X_CURSOR_INVALID`, never "from the top". †
79
79
  - **A NULLABLE sort key orders** `asc nulls last` / `desc nulls first`; the cursor tags NULL. †
80
80
  - **A `timestamp` cursor carries MICROSECONDS** (`seekPrecision`, `instant.ts`). Full rule: `docs/history/entity.md`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/entity",
3
- "version": "31.38.1",
3
+ "version": "31.40.0",
4
4
  "description": "A table + its domain type + invariants the database also enforces",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -44,9 +44,9 @@
44
44
  "test": "bun test"
45
45
  },
46
46
  "dependencies": {
47
- "@ultimat3/core": "31.38.1",
48
- "@ultimat3/db": "31.38.1",
49
- "@ultimat3/schema": "31.38.1",
50
- "@ultimat3/time": "31.38.1"
47
+ "@ultimat3/core": "31.40.0",
48
+ "@ultimat3/db": "31.40.0",
49
+ "@ultimat3/schema": "31.40.0",
50
+ "@ultimat3/time": "31.40.0"
51
51
  }
52
52
  }
package/src/cursor.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  // to both. The cursor carries the sort VALUES, not just an id: seeking by id alone needs the row
7
7
  // to still exist, and a row deleted between two pages would silently restart pagination.
8
8
 
9
- import { CursorInvalidError, decodeCursor, encodeCursor } from '@ultimat3/core';
9
+ import { CursorInvalidError, canonicalJson, decodeCursor, encodeCursor } from '@ultimat3/core';
10
10
  import { columnFor, columnName } from './column';
11
11
  import type { EntityCore } from './entity';
12
12
  import { invariantViolated } from './errors';
@@ -252,20 +252,6 @@ export const assertSeekable = <Row>(
252
252
  export const isNullableKey = <Row>(entity: EntityCore<Row>, path: string): boolean =>
253
253
  !columnAt(entity, path).$meta.notNull;
254
254
 
255
- /** Deterministic, and total over the value shapes a predicate can hold. */
256
- const renderValue = (value: unknown): string => {
257
- if (value === null || value === undefined) return 'null';
258
- if (value instanceof Date) return value.toISOString();
259
- if (typeof value === 'bigint') return `${value}n`;
260
- if (Array.isArray(value)) return `[${value.map(renderValue).join(',')}]`;
261
- if (typeof value === 'object') {
262
- const record = value as Readonly<Record<string, unknown>>;
263
- const keys = Object.keys(record).sort();
264
- return `{${keys.map((key) => `${key}:${renderValue(record[key])}`).join(',')}}`;
265
- }
266
- return JSON.stringify(String(value));
267
- };
268
-
269
255
  /**
270
256
  * What a cursor is bound to: this entity, these filters, this sort order. Not the page size — a
271
257
  * client may legitimately ask for a bigger next page — and not the projection, which cannot move
@@ -274,10 +260,15 @@ const renderValue = (value: unknown): string => {
274
260
  *
275
261
  * Hashed rather than spelled out: a cursor is base64, not encrypted, and the caller's filter
276
262
  * values are not the client's to read.
263
+ *
264
+ * Each value is core's `canonicalJson` — INJECTIVE, so `1` and `'1'` are two scopes. The local
265
+ * serializer it replaced quoted every scalar, and a cursor minted under `eq 1` was honoured under
266
+ * `eq '1'`. A string, a list of strings and a null test render as they did, so a plan holding only
267
+ * those keeps its scope across the upgrade (`cursor-scope.test.ts`).
277
268
  */
278
269
  export const planScope = (plan: QueryPlan): string => {
279
270
  const where = plan.where
280
- .map((predicate) => `${predicate.column} ${predicate.op} ${renderValue(predicate.value)}`)
271
+ .map((predicate) => `${predicate.column} ${predicate.op} ${canonicalJson(predicate.value)}`)
281
272
  .sort()
282
273
  .join('&');
283
274
  const order = plan.orderBy.map((key) => `${key.column} ${key.direction}`).join(',');
@@ -1,8 +1,9 @@
1
1
  // One `indexes: [...]` entry of `entity(name, { indexes })` turned into the `IndexDef` it declares,
2
2
  // refusing what Postgres would refuse later. Split out of `entity.ts` at the 500-line ceiling.
3
3
 
4
+ import { describeValue } from '@ultimat3/core';
4
5
  import { declaredKeyPartsOf } from './declared-index-keys';
5
- import { invariantViolated } from './errors';
6
+ import { EntityError, invariantViolated } from './errors';
6
7
  import type { InvariantColumns, Resolve } from './expr';
7
8
  import type { IndexInit } from './index-init';
8
9
  import { indexName } from './index-name';
@@ -15,6 +16,24 @@ export interface DeclaredIndexContext<C extends ColumnMap> {
15
16
  readonly columns: InvariantColumns<C>;
16
17
  }
17
18
 
19
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
20
+
21
+ /**
22
+ * `where:` given as anything but a callback — usually the SQL string it reads like. Calling it
23
+ * raised an uncoded TypeError at declaration, which every `x` command loading the app reported as
24
+ * `X_CLI_UNEXPECTED`. Its own fix, not `invariantViolated`'s `x entities show`: that command loads
25
+ * the app, and this throw is what stops the load.
26
+ */
27
+ const whereNotCallback = (name: string, on: readonly unknown[], where: unknown): EntityError => {
28
+ const first = on[0];
29
+ const column = typeof first === 'string' && IDENTIFIER.test(first) ? first : 'status';
30
+ return new EntityError({
31
+ code: 'X_INVARIANT_VIOLATED',
32
+ cause: `${name}.index: index.where must be a callback over the columns, got ${describeValue(where)}`,
33
+ fix: `where: (c) => c.${column}.eq('x') # edit the indexes: entry on ${name}, in the file this finding names`,
34
+ });
35
+ };
36
+
18
37
  export const declaredIndexOf = <C extends ColumnMap>(
19
38
  index: IndexInit<C>,
20
39
  context: DeclaredIndexContext<C>,
@@ -27,6 +46,9 @@ export const declaredIndexOf = <C extends ColumnMap>(
27
46
  if (columns.length === 0) {
28
47
  throw invariantViolated(name, 'index', 'an index must name at least one column');
29
48
  }
49
+ if (index.where !== undefined && typeof index.where !== 'function') {
50
+ throw whereNotCallback(name, index.on, index.where);
51
+ }
30
52
  const where = index.where?.(columnsExpr).toSql(resolve) ?? null;
31
53
  if (index.where !== undefined && where === null) {
32
54
  throw invariantViolated(
@@ -6,6 +6,7 @@ import {
6
6
  isFixShellSafe,
7
7
  registerErrorCodes,
8
8
  registerErrorRetry,
9
+ renderFixLiteral,
9
10
  renderFixShellArg,
10
11
  UltimateError,
11
12
  } from '@ultimat3/core';
@@ -191,18 +192,26 @@ export const invariantViolated = (
191
192
  /**
192
193
  * A `$view` key naming no column. Its own fix, never `describeCommand`: `x entities show` loads the
193
194
  * app, and this throw is what stops the load, so that line re-failed with this finding. The file
194
- * is the loader's to name (`Finding.at`): a view is built with no idea where it was called.
195
+ * is the loader's to name (`Finding.at`): a view is built with no idea where it was called. The fix
196
+ * removes the ONE bad key — with `keys`, the corrected list itself; a list cut to the first column
197
+ * deleted every valid key applied verbatim.
195
198
  */
196
199
  export const viewKeyUnknown = (
197
200
  entityName: string,
198
201
  key: string,
199
202
  columns: readonly string[],
200
- ): EntityError =>
201
- new EntityError({
203
+ keys?: readonly string[],
204
+ ): EntityError => {
205
+ const bad = renderFixLiteral(key, '<key>');
206
+ const kept = keys?.filter((one) => one !== key).map((one) => renderFixLiteral(one, '<key>'));
207
+ const list =
208
+ kept === undefined || kept.length === 0 ? `/* the same keys, minus ${bad} */` : kept.join(', ');
209
+ return new EntityError({
202
210
  code: 'X_INVARIANT_VIOLATED',
203
211
  cause: `${entityName}.view: $view(['${key}']) names no column — pick from: ${columns.join(', ')}`,
204
- fix: `$view(['${columns[0] ?? ''}']) # edit the call on ${entityName}, in the file this finding names; pick from: ${columns.join(', ')}`,
212
+ fix: `$view([${list}]) # edit the call on ${entityName}, in the file this finding names: delete ${bad} and keep every other key, or rename it — pick from: ${columns.join(', ')}`,
205
213
  });
214
+ };
206
215
 
207
216
  export const entityDuplicate = (name: string, existingTable: string): EntityError =>
208
217
  new EntityError({
package/src/view.ts CHANGED
@@ -111,7 +111,7 @@ export const viewFor = <Row, K extends keyof Row & string>(
111
111
  const picked: readonly (readonly [K, AnyColumn])[] = keys.map((key) => {
112
112
  const column = columns[key];
113
113
  if (column === undefined) {
114
- throw viewKeyUnknown(entityName, key, Object.keys(columns));
114
+ throw viewKeyUnknown(entityName, key, Object.keys(columns), keys);
115
115
  }
116
116
  return [key, column] as const;
117
117
  });