akanjs 3.2.0 → 3.2.1-rc.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.
Files changed (46) hide show
  1. package/document/dataLoader.ts +55 -25
  2. package/package.json +1 -1
  3. package/server/akanApp.ts +13 -2
  4. package/server/akanServer.ts +4 -0
  5. package/server/contentEncoding.ts +39 -9
  6. package/server/flightSanitizeRecorded.fixture.json +545 -0
  7. package/server/gateway/gatewayHttpProxy.ts +2 -2
  8. package/server/hmr/devBaseArtifact.ts +40 -0
  9. package/server/htmlResultCache.ts +11 -10
  10. package/server/routing/routeHosts.ts +4 -0
  11. package/server/rscFlightStream.ts +34 -2
  12. package/server/rscHostRequests.ts +27 -2
  13. package/server/rscRenderControl.ts +2 -0
  14. package/server/rscRenderHandler.ts +17 -18
  15. package/server/rscRenderManifest.ts +13 -0
  16. package/server/rscResultCaches.ts +2 -2
  17. package/server/rscWorker.tsx +14 -2
  18. package/server/rscWorkerCache.ts +13 -15
  19. package/server/rscWorkerHost.ts +3 -0
  20. package/service/predefinedAdaptor/solidCache.adaptor.ts +57 -15
  21. package/service/predefinedAdaptor/sql/AggregateQuery.ts +66 -0
  22. package/service/predefinedAdaptor/sql/BoundList.ts +34 -0
  23. package/service/predefinedAdaptor/sql/QueryCompiler.ts +27 -4
  24. package/service/predefinedAdaptor/sql/QueryScope.ts +41 -7
  25. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +7 -1
  26. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +45 -42
  27. package/service/predefinedAdaptor/sql/SqlTableSchema.ts +2 -2
  28. package/service/predefinedAdaptor/sql/types.ts +2 -0
  29. package/types/document/dataLoader.d.ts +1 -0
  30. package/types/server/contentEncoding.d.ts +3 -2
  31. package/types/server/gateway/gatewayHttpProxy.d.ts +1 -0
  32. package/types/server/hmr/devBaseArtifact.d.ts +10 -0
  33. package/types/server/htmlResultCache.d.ts +3 -2
  34. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  35. package/types/server/routing/routeHosts.d.ts +1 -0
  36. package/types/server/rscHostRequests.d.ts +1 -0
  37. package/types/server/rscRenderControl.d.ts +2 -0
  38. package/types/server/rscRenderManifest.d.ts +5 -0
  39. package/types/server/rscWorkerCache.d.ts +4 -5
  40. package/types/service/predefinedAdaptor/sql/AggregateQuery.d.ts +16 -0
  41. package/types/service/predefinedAdaptor/sql/BoundList.d.ts +10 -0
  42. package/types/service/predefinedAdaptor/sql/QueryCompiler.d.ts +1 -0
  43. package/types/service/predefinedAdaptor/sql/QueryScope.d.ts +2 -2
  44. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +1 -1
  45. package/types/service/predefinedAdaptor/sql/SqlTableSchema.d.ts +1 -1
  46. package/types/service/predefinedAdaptor/sql/types.d.ts +2 -0
@@ -0,0 +1,66 @@
1
+ import { type DocumentQuery, documentQueryHelper } from "akanjs/document";
2
+ import { DocumentStoreError } from "../../documentStoreError";
3
+ import type { QueryCompiler } from "./QueryCompiler";
4
+ import type { QueryScope } from "./QueryScope";
5
+ import { BASE_COLUMNS, type SqlDialect, type SqlFrag } from "./types";
6
+ import { quoteIdent } from "./values";
7
+
8
+ /** One field of an insight: a count, or the sum of `sum`, over the rows `condition` also matches. */
9
+ export interface AccumulatedField {
10
+ sum?: string;
11
+ condition?: DocumentQuery;
12
+ }
13
+
14
+ export class AggregateQuery {
15
+ readonly #table: string;
16
+ readonly #dialect: SqlDialect;
17
+ readonly #compiler: QueryCompiler;
18
+ readonly #scope: QueryScope;
19
+
20
+ constructor(table: string, dialect: SqlDialect, compiler: QueryCompiler, scope: QueryScope) {
21
+ this.#table = table;
22
+ this.#dialect = dialect;
23
+ this.#compiler = compiler;
24
+ this.#scope = scope;
25
+ }
26
+
27
+ sumOf(path: string) {
28
+ if (BASE_COLUMNS.has(path) || path.startsWith("_"))
29
+ throw new DocumentStoreError("invalidQuery", `sum reads a model field, not "${path}"`);
30
+ this.#compiler.fieldExpr(path);
31
+ return this.#dialect.sumOf(path);
32
+ }
33
+
34
+ /** One statement answering every field over the live rows `query` matches, the n-th as column `f<n>`. */
35
+ insight(fields: AccumulatedField[], query?: DocumentQuery): SqlFrag {
36
+
37
+ const readsDocuments = fields.some(({ sum, condition }) => sum !== undefined && !condition);
38
+ const columns = fields.map((field) => this.#column(field, query, readsDocuments));
39
+ const select = `SELECT ${columns.map(({ sql }, idx) => `${sql} AS ${quoteIdent(`f${idx}`)}`).join(", ")}`;
40
+ const params = columns.flatMap((column) => column.params);
41
+ const rows = columns.find((column) => column.rows)?.rows;
42
+ return rows ? { sql: `${select} ${rows.sql}`, params: [...params, ...rows.params] } : { sql: select, params };
43
+ }
44
+
45
+ #column(
46
+ field: AccumulatedField,
47
+ query: DocumentQuery | undefined,
48
+ readsDocuments: boolean,
49
+ ): SqlFrag & { rows?: SqlFrag } {
50
+ const aggregate = field.sum === undefined ? "count(*)" : this.sumOf(field.sum);
51
+ if (!field.condition) return { sql: aggregate, params: [], rows: this.#rows(query, field) };
52
+ const rows = this.#rows(documentQueryHelper.all(query ?? {}, field.condition), field);
53
+ const condition = this.#compiler.compile(field.condition);
54
+ if (readsDocuments && field.sum === undefined && !condition.joins.length)
55
+ return { sql: `count(*) FILTER (WHERE ${condition.where})`, params: condition.params };
56
+ return { sql: `(SELECT ${aggregate} ${rows.sql})`, params: rows.params };
57
+ }
58
+
59
+ #rows(query: DocumentQuery | undefined, { sum }: AccumulatedField): SqlFrag {
60
+ const { where, params, joins } = this.#scope.safeQuery(query, sum === undefined ? "count" : "sum", {});
61
+ return {
62
+ sql: `FROM ${quoteIdent(this.#table)}${this.#scope.joinSql(joins)} WHERE ${where}`,
63
+ params: [...this.#scope.joinParams(joins), ...params],
64
+ };
65
+ }
66
+ }
@@ -0,0 +1,34 @@
1
+ import { BASE_COLUMNS, type PathKind, type SqlDialect, type SqlFrag } from "./types";
2
+ import { encodeSqlValue, jsonStr, quoteIdent } from "./values";
3
+
4
+ export interface BoundListOptions {
5
+ kind?: PathKind;
6
+ negated?: boolean;
7
+ }
8
+
9
+ export class BoundList {
10
+ readonly #dialect: SqlDialect;
11
+
12
+ constructor(dialect: SqlDialect) {
13
+ this.#dialect = dialect;
14
+ }
15
+
16
+ compare(path: string, values: unknown[], { kind = "json", negated = false }: BoundListOptions = {}): SqlFrag | null {
17
+ if (this.#dialect.name !== "postgres" || values.length < 2) return null;
18
+ if (BASE_COLUMNS.has(path)) {
19
+ const items = values.map(encodeSqlValue).map((value) => (value == null ? null : String(value)));
20
+ return BoundList.#array(quoteIdent(path), path === "id" ? "text" : "bigint", items, negated);
21
+ }
22
+
23
+ if (kind === "text" && values.every((value) => typeof value === "string"))
24
+ return BoundList.#array(this.#dialect.extract(path, "text"), "text", values.map(String), negated);
25
+ return BoundList.#array(this.#dialect.extract(path, "json"), "jsonb", values.map(jsonStr), negated);
26
+ }
27
+
28
+ static #array(expr: string, type: "text" | "jsonb" | "bigint", items: (string | null)[], negated: boolean): SqlFrag {
29
+ const literal = items.map((item) =>
30
+ item === null ? "NULL" : `"${item.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`,
31
+ );
32
+ return { sql: `${expr} ${negated ? "<> ALL" : "= ANY"}(?::${type}[])`, params: [`{${literal.join(",")}}`] };
33
+ }
34
+ }
@@ -9,6 +9,7 @@ import {
9
9
  } from "akanjs/document";
10
10
  import { DocumentStoreError } from "../../documentStoreError";
11
11
  import { DEFAULT_SEARCH_WEIGHTS, type SearchIndex } from "../searchIndex";
12
+ import { BoundList } from "./BoundList";
12
13
  import {
13
14
  BASE_COLUMNS,
14
15
  type CompileContext,
@@ -30,25 +31,39 @@ const isPlainRecord = (value: unknown) => {
30
31
  return proto === Object.prototype || proto === null;
31
32
  };
32
33
 
34
+ let compileWrittenOut: (compiler: QueryCompiler, where: DocumentQuery) => CompiledQuery;
35
+
33
36
  export class QueryCompiler {
37
+ readonly #lists: BoundList;
38
+
39
+ static {
40
+ compileWrittenOut = (compiler, where) => compiler.#compile(where, true);
41
+ }
42
+
34
43
  constructor(
35
44
  private readonly fields: FieldMap,
36
45
  private readonly dialect: SqlDialect,
37
46
  private readonly ref: string,
38
47
  private readonly searchIndex: () => SearchIndex | null,
39
- ) {}
48
+ ) {
49
+ this.#lists = new BoundList(dialect);
50
+ }
40
51
 
41
52
  #leaf(path: string): QueryLeafOps {
42
53
  return BASE_COLUMNS.has(path) ? BASE_COLUMN_LEAF : this.dialect;
43
54
  }
44
55
 
45
56
  compile(query?: DocumentQuery): CompiledQuery {
57
+ return this.#compile(query, false);
58
+ }
59
+
60
+ #compile(query: DocumentQuery | undefined, writtenLists: boolean): CompiledQuery {
46
61
  const joins: SearchJoin[] = [];
47
62
  const memberTests: string[] = [];
48
63
  if (!query || (typeof query === "object" && !Array.isArray(query) && Object.keys(query).length === 0)) {
49
64
  return { where: "1 = 1", params: [], joins, memberTests };
50
65
  }
51
- const compiled = this.compileNode(query, { joins, memberTests, conjunctive: true });
66
+ const compiled = this.compileNode(query, { joins, memberTests, conjunctive: true, writtenLists });
52
67
  return { where: compiled.sql || "1 = 1", params: compiled.params, joins, memberTests };
53
68
  }
54
69
 
@@ -192,7 +207,7 @@ export class QueryCompiler {
192
207
  params: parts.flatMap((part) => part.params),
193
208
  };
194
209
  }
195
- return leaf.inList(path, values, kind);
210
+ return this.#inList(leaf, path, values, kind, ctx, false);
196
211
  }
197
212
  case "notOneOf": {
198
213
  const values = (value.value as unknown[]) ?? [];
@@ -204,7 +219,7 @@ export class QueryCompiler {
204
219
  params: parts.flatMap((part) => part.params),
205
220
  };
206
221
  }
207
- return leaf.notInList(path, values, kind);
222
+ return this.#inList(leaf, path, values, kind, ctx, true);
208
223
  }
209
224
  case "gt":
210
225
  case "gte":
@@ -261,6 +276,11 @@ export class QueryCompiler {
261
276
  return !!field && !field.isArray && !field.isMap && singleValueRefs.has(field.modelRef);
262
277
  }
263
278
 
279
+ #inList(leaf: QueryLeafOps, path: string, values: unknown[], kind: PathKind, ctx: CompileContext, negated: boolean) {
280
+ const bound = ctx.writtenLists ? null : this.#lists.compare(path, values, { kind, negated });
281
+ return bound ?? (negated ? leaf.notInList(path, values, kind) : leaf.inList(path, values, kind));
282
+ }
283
+
264
284
  #arrayHas(leaf: QueryLeafOps, path: string, value: unknown, ctx: CompileContext) {
265
285
  if (!ctx.memberTests.includes(path)) ctx.memberTests.push(path);
266
286
  return leaf.arrayHas(path, value);
@@ -285,3 +305,6 @@ export class QueryCompiler {
285
305
  }
286
306
  }
287
307
  }
308
+
309
+ export const compileIndexPredicate = (compiler: QueryCompiler, where: DocumentQuery) =>
310
+ compileWrittenOut(compiler, where);
@@ -1,16 +1,24 @@
1
- import { type DocumentQuery, type DocumentScopeOptions, documentQueryHelper, LiveRowScope } from "akanjs/document";
1
+ import {
2
+ type DocumentQuery,
3
+ type DocumentScopeOptions,
4
+ documentQueryHelper,
5
+ isDocumentQueryNode,
6
+ LiveRowScope,
7
+ } from "akanjs/document";
2
8
  import { DocumentStoreError } from "../../documentStoreError";
3
9
  import type { QueryCompiler } from "./QueryCompiler";
4
- import type { FindManyOptions, SearchJoin, SortOption } from "./types";
10
+ import type { FindManyOptions, SearchJoin, SortOption, SqlDialect, SqlFrag } from "./types";
5
11
  import { quoteIdent } from "./values";
6
12
 
7
13
  export class QueryScope {
8
14
  readonly #table: string;
9
15
  readonly #compiler: QueryCompiler;
16
+ readonly #dialect: SqlDialect;
10
17
 
11
- constructor(table: string, compiler: QueryCompiler) {
18
+ constructor(table: string, compiler: QueryCompiler, dialect: SqlDialect) {
12
19
  this.#table = table;
13
20
  this.#compiler = compiler;
21
+ this.#dialect = dialect;
14
22
  }
15
23
 
16
24
  listQuery(query: DocumentQuery | undefined, options: FindManyOptions, operation = "find") {
@@ -18,15 +26,25 @@ export class QueryScope {
18
26
  const limitValue = Number(options.limit ?? 0);
19
27
  const skipValue = Number(options.skip ?? 0);
20
28
  const order = options.sample ? "ORDER BY random()" : `ORDER BY ${this.#orderBy(options.sort, joins)}`;
21
- const page = `${limitValue ? ` LIMIT ${limitValue}` : ""}${skipValue ? ` OFFSET ${skipValue}` : ""}`;
29
+ const page = this.#page(limitValue, skipValue);
22
30
  return {
23
31
 
24
32
  star: joins.length ? `${quoteIdent(this.#table)}.*` : "*",
25
- tail: `FROM ${quoteIdent(this.#table)}${this.joinSql(joins)} WHERE ${where} ${order}${page}`,
26
- args: [...this.joinParams(joins), ...params],
33
+ tail: `FROM ${quoteIdent(this.#table)}${this.joinSql(joins)} WHERE ${where} ${order}${page.sql}`,
34
+ args: [...this.joinParams(joins), ...params, ...page.params],
27
35
  };
28
36
  }
29
37
 
38
+ #page(limit: number, skip: number): SqlFrag {
39
+ if (!limit && !skip) return { sql: "", params: [] };
40
+ return { sql: `${limit ? ` LIMIT ${limit}` : ""} OFFSET ?`, params: [this.#offset(skip)] };
41
+ }
42
+
43
+ #offset(skip: number) {
44
+ if (!skip) return 0;
45
+ return this.#dialect.name === "postgres" ? Math.sign(skip) * Math.round(Math.abs(skip)) : skip;
46
+ }
47
+
30
48
  safeQuery(query: DocumentQuery | undefined, operation: string, { withRemoved = false }: DocumentScopeOptions) {
31
49
  if (withRemoved) {
32
50
  const compiled = this.#compiler.compile(query ?? {});
@@ -41,7 +59,23 @@ export class QueryScope {
41
59
  "invalidQuery",
42
60
  `${operation} on "${this.#table}" can never match (${conflict}); ${operation.startsWith("remove") ? "a remove reaches live rows only" : "pass { withRemoved: true }"}`,
43
61
  );
44
- return this.#compiler.compile(documentQueryHelper.all(documentQueryHelper.empty("removedAt"), query ?? {}));
62
+ return this.#compiler.compile(documentQueryHelper.all(this.#live(query), query ?? {}));
63
+ }
64
+
65
+ #live(query: DocumentQuery | undefined) {
66
+ return this.#dialect.name === "sqlite" && QueryScope.#listsIds(query)
67
+ ? documentQueryHelper.raw('+"removedAt" IS NULL')
68
+ : documentQueryHelper.empty("removedAt");
69
+ }
70
+
71
+ static #listsIds(query: DocumentQuery | undefined): boolean {
72
+ if (!query) return false;
73
+ if (isDocumentQueryNode(query))
74
+ return query.kind === "all" && query.queries.some((sub) => QueryScope.#listsIds(sub));
75
+ const { id } = query as { id?: unknown };
76
+ return (
77
+ isDocumentQueryNode(id) && id.kind === "op" && id.op === "oneOf" && Array.isArray(id.value) && id.value.length > 0
78
+ );
45
79
  }
46
80
 
47
81
  writeQuery(query: DocumentQuery | undefined, operation: string, options: DocumentScopeOptions) {
@@ -1,4 +1,5 @@
1
1
  import { DocumentStoreError } from "../../documentStoreError";
2
+ import { BoundList } from "./BoundList";
2
3
  import {
3
4
  type AkanSqlClient,
4
5
  type QueryLeafOps,
@@ -45,6 +46,7 @@ export class RawDocumentTable {
45
46
  readonly name: string;
46
47
  readonly #connection: () => AkanSqlClient;
47
48
  readonly #dialect: SqlDialect;
49
+ readonly #lists: BoundList;
48
50
  #exists: boolean | undefined;
49
51
 
50
52
  constructor(name: string, connection: () => AkanSqlClient, dialect: SqlDialect) {
@@ -53,6 +55,7 @@ export class RawDocumentTable {
53
55
  this.name = name;
54
56
  this.#connection = connection;
55
57
  this.#dialect = dialect;
58
+ this.#lists = new BoundList(dialect);
56
59
  }
57
60
 
58
61
  async exists() {
@@ -174,7 +177,10 @@ export class RawDocumentTable {
174
177
  if (!Array.isArray(operand))
175
178
  throw new DocumentStoreError("invalidQuery", `Filter "${path}" ${operator} takes an array`);
176
179
  if (!operand.length) return { sql: operator === "$in" ? "0 = 1" : "1 = 1", params: [] };
177
- return operator === "$in" ? leaf.inList(path, operand) : leaf.notInList(path, operand);
180
+ return (
181
+ this.#lists.compare(path, operand, { negated: operator === "$nin" }) ??
182
+ (operator === "$in" ? leaf.inList(path, operand) : leaf.notInList(path, operand))
183
+ );
178
184
  }
179
185
  case "$exists":
180
186
  return operand ? leaf.exists(path) : leaf.missing(path);
@@ -9,10 +9,10 @@ import {
9
9
  type DocumentTouchOptions,
10
10
  type DocumentUpdateInput,
11
11
  type DocumentUpdateOptions,
12
- documentQueryHelper,
13
12
  NoDocumentError,
14
13
  } from "akanjs/document";
15
14
  import { DocumentStoreError } from "../../documentStoreError";
15
+ import { type AccumulatedField, AggregateQuery } from "./AggregateQuery";
16
16
  import { DocumentHydrator } from "./DocumentHydrator";
17
17
  import { DocumentRowCodec } from "./DocumentRowCodec";
18
18
  import { DocumentWriter } from "./DocumentWriter";
@@ -22,25 +22,24 @@ import { QueryScope } from "./QueryScope";
22
22
  import { QueryWriter } from "./QueryWriter";
23
23
  import { SqlTableSchema } from "./SqlTableSchema";
24
24
  import { type StoredRead, StoredRows } from "./StoredRows";
25
- import {
26
- type AkanSqlClient,
27
- type AkanSqlStatement,
28
- BASE_COLUMNS,
29
- type DocumentDatabaseOwner,
30
- type DocumentRecord,
31
- type DocumentWriteListener,
32
- type FieldMap,
33
- type FindIdOptions,
34
- type FindManyOptions,
35
- type FindOneOptions,
36
- type ProjectedSqliteDocumentRow,
37
- type PrunedIndex,
38
- type SqlDialect,
39
- type SqliteDocumentRow,
40
- type TransferRow,
41
- type UndeclaredIndex,
42
- type UpsertByIdOptions,
43
- type WriteHookOptions,
25
+ import type {
26
+ AkanSqlClient,
27
+ AkanSqlStatement,
28
+ DocumentDatabaseOwner,
29
+ DocumentRecord,
30
+ DocumentWriteListener,
31
+ FieldMap,
32
+ FindIdOptions,
33
+ FindManyOptions,
34
+ FindOneOptions,
35
+ ProjectedSqliteDocumentRow,
36
+ PrunedIndex,
37
+ SqlDialect,
38
+ SqliteDocumentRow,
39
+ TransferRow,
40
+ UndeclaredIndex,
41
+ UpsertByIdOptions,
42
+ WriteHookOptions,
44
43
  } from "./types";
45
44
  import { UpdateCompiler } from "./UpdateCompiler";
46
45
  import { assertStorableJson, decodeDateValue, quoteIdent } from "./values";
@@ -59,6 +58,7 @@ export class SqlDocumentStore {
59
58
  readonly #hydrator: DocumentHydrator;
60
59
  readonly #writer: DocumentWriter;
61
60
  readonly #queryWriter: QueryWriter;
61
+ readonly #aggregates: AggregateQuery;
62
62
  readonly #writeListeners = new Set<DocumentWriteListener>();
63
63
  static readonly #logger = new Logger("SqlDocumentStore");
64
64
 
@@ -87,7 +87,7 @@ export class SqlDocumentStore {
87
87
  logger,
88
88
  });
89
89
  this.#codec = new DocumentRowCodec(database, this.table, dialect, this.compiler);
90
- this.#scope = new QueryScope(this.table, this.compiler);
90
+ this.#scope = new QueryScope(this.table, this.compiler, dialect);
91
91
  this.#rows = new StoredRows(this, this.#codec, logger);
92
92
  this.#hydrator = new DocumentHydrator(this, this.#codec, this.#rows);
93
93
  this.#writer = new DocumentWriter({
@@ -101,6 +101,7 @@ export class SqlDocumentStore {
101
101
  written: (doc, previous) => this.#written({ doc, previous }),
102
102
  });
103
103
  this.#queryWriter = new QueryWriter(owner, this, dialect, this.#scope);
104
+ this.#aggregates = new AggregateQuery(this.table, dialect, this.compiler, this.#scope);
104
105
  }
105
106
 
106
107
  ensure() {
@@ -331,12 +332,10 @@ export class SqlDocumentStore {
331
332
 
332
333
  /** The stored numbers at `path` added up over the live rows the query matches; 0 when none. */
333
334
  async sum(path: string, query?: DocumentQuery) {
334
- if (BASE_COLUMNS.has(path) || path.startsWith("_"))
335
- throw new DocumentStoreError("invalidQuery", `sum reads a model field, not "${path}"`);
336
- this.compiler.fieldExpr(path);
335
+ const total = this.#aggregates.sumOf(path);
337
336
  const { where, params, joins } = this.#scope.safeQuery(query, "sum", {});
338
337
  const row = await this.prepareStmt(
339
- `SELECT ${this.dialect.sumOf(path)} as total FROM ${quoteIdent(this.table)}${this.#scope.joinSql(joins)} WHERE ${where}`,
338
+ `SELECT ${total} as total FROM ${quoteIdent(this.table)}${this.#scope.joinSql(joins)} WHERE ${where}`,
340
339
  ).get<{ total: number | string | null }>(...this.#scope.joinParams(joins), ...params);
341
340
  return Number(row?.total ?? 0);
342
341
  }
@@ -344,29 +343,33 @@ export class SqlDocumentStore {
344
343
  async insight(query?: DocumentQuery) {
345
344
  const insightFields = this.constant.insight[FIELD_META] as unknown as FieldMap;
346
345
  const result: DocumentRecord = {};
346
+ const accumulated: (AccumulatedField & { key: string })[] = [];
347
347
  for (const [key, field] of Object.entries(insightFields)) {
348
348
  const props = field.getProps();
349
- const { $sum: sumPath, ...condition } = (props.accumulate ?? {}) as Record<string, unknown>;
350
- if (!props.accumulate) {
351
- result[key] = props.default;
352
- } else if (typeof sumPath === "string") {
353
-
354
- const scoped = Object.keys(condition).length
355
- ? documentQueryHelper.all(query ?? {}, condition as DocumentQuery)
356
- : query;
357
- result[key] = await this.sum(sumPath, scoped);
358
- } else if (
359
- typeof props.accumulate === "object" &&
360
- !Object.keys(props.accumulate as Record<string, unknown>).some((key) => key.startsWith("$"))
361
- ) {
362
- result[key] = await this.count(documentQueryHelper.all(query ?? {}, props.accumulate as DocumentQuery));
363
- } else {
364
- result[key] = await this.count(query);
365
- }
349
+ result[key] = props.default;
350
+ if (!props.accumulate) continue;
351
+ const { $sum: sumPath, ...condition } = props.accumulate as { $sum?: unknown } & DocumentQuery;
352
+
353
+ if (typeof sumPath === "string")
354
+ accumulated.push({ key, sum: sumPath, condition: Object.keys(condition).length ? condition : undefined });
355
+ else if (typeof props.accumulate === "object" && SqlDocumentStore.#isCondition(props.accumulate))
356
+ accumulated.push({ key, condition: props.accumulate as DocumentQuery });
357
+ else accumulated.push({ key });
366
358
  }
359
+ if (!accumulated.length) return result;
360
+ const { sql, params } = this.#aggregates.insight(accumulated, query);
361
+ const row = await this.prepareStmt(sql).get<Record<string, number | string | null>>(...params);
362
+ accumulated.forEach(({ key }, idx) => {
363
+ result[key] = Number(row?.[`f${idx}`] ?? 0);
364
+ });
367
365
  return result;
368
366
  }
369
367
 
368
+ static #isCondition(accumulate: object) {
369
+ const keys = Object.keys(accumulate);
370
+ return keys.length > 0 && !keys.some((key) => key.startsWith("$"));
371
+ }
372
+
370
373
  /** `track` buys `isModified()` with a deep clone of the row; only the read paths opt out. */
371
374
  hydrate(data: DocumentRecord, originalData: DocumentRecord = data, { track = true }: { track?: boolean } = {}) {
372
375
  return this.#hydrator.hydrate(data, originalData, { track });
@@ -2,7 +2,7 @@ import type { Logger } from "akanjs/common";
2
2
  import type { ConstantModel } from "akanjs/constant";
3
3
  import type { DatabaseModel, DocumentIndexDescriptor, DocumentQuery, DocumentSchema } from "akanjs/document";
4
4
  import { DocumentStoreError } from "../../documentStoreError";
5
- import type { QueryCompiler } from "./QueryCompiler";
5
+ import { compileIndexPredicate, type QueryCompiler } from "./QueryCompiler";
6
6
  import {
7
7
  type CreateIndexProps,
8
8
  type DocumentDatabaseOwner,
@@ -315,7 +315,7 @@ export class SqlTableSchema {
315
315
  }
316
316
 
317
317
  #indexPredicate(where: DocumentQuery, name: string) {
318
- const { where: sql, params, joins, memberTests } = this.#compiler.compile(where);
318
+ const { where: sql, params, joins, memberTests } = compileIndexPredicate(this.#compiler, where);
319
319
  if (joins.length)
320
320
  throw new DocumentStoreError(
321
321
  "invalidSchema",
@@ -268,6 +268,8 @@ export interface CompileContext {
268
268
  joins: SearchJoin[];
269
269
  memberTests: string[];
270
270
  conjunctive: boolean;
271
+ /** Each list value gets its own placeholder, where a query binds the whole list as one. */
272
+ writtenLists: boolean;
271
273
  }
272
274
 
273
275
  /**
@@ -19,6 +19,7 @@ interface DataLoaderOptions<Key, Value, CacheKey> {
19
19
  batchScheduleFn?: (callback: () => void) => void;
20
20
  /** What a load belongs to, such as its open transaction: a scope's loads batch apart and never touch the cache. */
21
21
  scopeFn?: () => object | undefined;
22
+ /** How many distinct keys one call of the batch function takes (500 by default); a larger queue goes out as several. */
22
23
  maxBatchSize?: number;
23
24
  name?: string;
24
25
  }
@@ -25,8 +25,9 @@ export declare const encodedBodyResponse: (req: Request, body: EncodedBody, init
25
25
  headers: Headers;
26
26
  }) => Response;
27
27
  export interface EncodedSidecar {
28
- bytes: ArrayBuffer;
29
- encoding: string;
28
+ file: ReturnType<typeof Bun.file>;
29
+ size: number;
30
+ encoding: ContentEncoding;
30
31
  }
31
32
  export declare const resolveEncodedSidecar: (req: Request, filePath: string, contentType: string) => Promise<EncodedSidecar | null>;
32
33
  export declare const encodedFileResponse: (req: Request, filePath: string, contentType: string, headers: Headers) => Promise<Response>;
@@ -18,5 +18,6 @@ export declare class GatewayHttpProxy {
18
18
  constructor({ config, children, supervisor, status, limits, logger }: GatewayHttpProxyParts);
19
19
  serveImmutableArtifact(req: Request, url: URL): Promise<Response | null>;
20
20
  proxyHttp(req: Request, server: Bun.Server<GatewayWsData>): Promise<Response>;
21
+ respondWithUnavailable(req: Request): Response;
21
22
  }
22
23
  export {};
@@ -0,0 +1,10 @@
1
+ export declare class DevBaseArtifact {
2
+ #private;
3
+ static arrived({ artifactDir, env, stopped, warnAfterMs, warn, }?: {
4
+ artifactDir?: string;
5
+ env?: Record<string, string | undefined>;
6
+ stopped?: () => boolean;
7
+ warnAfterMs?: number;
8
+ warn?: (message: string) => void;
9
+ }): Promise<number>;
10
+ }
@@ -4,11 +4,12 @@ import { type RouteCacheEntry, type RouteCacheInvalidation, type RouteCacheRende
4
4
  import { type EncodedBody } from "./contentEncoding.d.ts";
5
5
  import type { SsrLateControl } from "./ssrTypes.d.ts";
6
6
  export declare const DEFAULT_HTML_RESULT_CACHE_MAX_BODY_BYTES: number;
7
- export declare function cacheHtmlWhileStreaming(stream: ReadableStream<Uint8Array>, onComplete: (html: string) => void, options?: {
7
+ interface HtmlCacheStreamOptions {
8
8
  shouldCache?: () => boolean | Promise<boolean>;
9
9
  maxBodyBytes?: number | null;
10
10
  onSkip?: (reason: "body-too-large" | "store-skip") => void;
11
- }): ReadableStream<Uint8Array>;
11
+ }
12
+ export declare function cacheHtmlWhileStreaming(stream: ReadableStream<Uint8Array>, onComplete: (body: Uint8Array<ArrayBuffer>) => void, options?: HtmlCacheStreamOptions): ReadableStream<Uint8Array>;
12
13
  export declare function resolveHtmlRouteCacheStoreTtl(input: {
13
14
  baseTtl: number;
14
15
  workerCacheState: RouteCacheRenderState;
@@ -19,5 +19,5 @@ export declare class RotatingLogWriter {
19
19
  static sanitizeFilePart(value: string): string;
20
20
  write(processKey: string, chunk: string): void;
21
21
  close(): Promise<void>;
22
- static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#157@#defaultWarn): number;
22
+ static fileMode(value?: string | undefined, warn?: typeof RotatingLogWriter.__#159@#defaultWarn): number;
23
23
  }
@@ -1,4 +1,5 @@
1
1
  export declare class RouteHosts {
2
2
  #private;
3
3
  static declare(artifactDir?: string, subRouteHostsEnv?: string | undefined): string[];
4
+ static written(artifactDir?: string): boolean;
4
5
  }
@@ -23,6 +23,7 @@ export declare class RscHostRequests {
23
23
  settleCall(requestId: string, fn: (call: RscCall) => void): boolean;
24
24
  resolvePending(requestId: string, fn: (p: RscPending) => void): void;
25
25
  static workerHeaders(req: Request, clientIp: string | null | undefined): Record<string, string>;
26
+ forgetManifest(): void;
26
27
  flushQueuedSends(): void;
27
28
  failRequests(err: AkanError<RscWorkerErrorCode>, which?: (requestId: string) => boolean): void;
28
29
  }
@@ -5,6 +5,8 @@ export interface RscRenderRequest {
5
5
  url: string;
6
6
  method?: string;
7
7
  headers?: Record<string, string>;
8
+ /** Names the manifest to render against; the host sends that manifest itself once per worker process. */
9
+ manifestRevision?: number;
8
10
  clientManifest?: ClientManifest;
9
11
  prefetch?: boolean;
10
12
  }
@@ -0,0 +1,5 @@
1
+ import type { RscRenderRequest } from "./rscRenderControl.d.ts";
2
+ export declare class RscRenderManifest {
3
+ #private;
4
+ admit<T extends RscRenderRequest>(msg: T): T | null;
5
+ }
@@ -3,8 +3,7 @@ import { type LruTtlCache, type RouteCacheEntry, type RouteCacheInvalidation, ty
3
3
  import { type AkanHeadSnapshotV1, type AkanRouterStateV1, type AkanRscPatchDecision, type AkanRscPatchMetadata } from "./routeState.d.ts";
4
4
  import type { RscTraceMetadata } from "./ssrTypes.d.ts";
5
5
  export interface CachedRscResult {
6
- chunks: Uint8Array[];
7
- bytes: number;
6
+ body: Uint8Array;
8
7
  chunksCount: number;
9
8
  pathname: string;
10
9
  routeId?: string;
@@ -112,16 +111,16 @@ export type CachedRscReplayMessage = {
112
111
  type: "end";
113
112
  requestId: string;
114
113
  };
114
+ export declare function joinRscChunks(chunks: readonly Uint8Array[]): Uint8Array;
115
115
  export declare function replayCachedRscResult(input: {
116
116
  requestId: string;
117
- chunks: readonly Uint8Array[];
117
+ body: Uint8Array;
118
118
  theme?: string;
119
119
  trace?: RscTraceMetadata;
120
120
  cacheState?: RouteCacheRenderState;
121
121
  send: (message: CachedRscReplayMessage) => void;
122
122
  isCancelled: () => boolean;
123
- yieldToHost?: () => Promise<void>;
124
- }): Promise<boolean>;
123
+ }): boolean;
125
124
  export declare function resolveAkanRscHeadSafePatchDecision({ partialCommitEnabled, patchDecision, pageConfig, routeHeadMounted, frameChange, headSnapshot, layoutsHeadChanged, }: {
126
125
  partialCommitEnabled: boolean;
127
126
  patchDecision: AkanRscPatchDecision;
@@ -0,0 +1,16 @@
1
+ import { type DocumentQuery } from "akanjs/document";
2
+ import type { QueryCompiler } from "./QueryCompiler.d.ts";
3
+ import type { QueryScope } from "./QueryScope.d.ts";
4
+ import { type SqlDialect, type SqlFrag } from "./types.d.ts";
5
+ /** One field of an insight: a count, or the sum of `sum`, over the rows `condition` also matches. */
6
+ export interface AccumulatedField {
7
+ sum?: string;
8
+ condition?: DocumentQuery;
9
+ }
10
+ export declare class AggregateQuery {
11
+ #private;
12
+ constructor(table: string, dialect: SqlDialect, compiler: QueryCompiler, scope: QueryScope);
13
+ sumOf(path: string): string;
14
+ /** One statement answering every field over the live rows `query` matches, the n-th as column `f<n>`. */
15
+ insight(fields: AccumulatedField[], query?: DocumentQuery): SqlFrag;
16
+ }
@@ -0,0 +1,10 @@
1
+ import { type PathKind, type SqlDialect, type SqlFrag } from "./types.d.ts";
2
+ export interface BoundListOptions {
3
+ kind?: PathKind;
4
+ negated?: boolean;
5
+ }
6
+ export declare class BoundList {
7
+ #private;
8
+ constructor(dialect: SqlDialect);
9
+ compare(path: string, values: unknown[], { kind, negated }?: BoundListOptions): SqlFrag | null;
10
+ }
@@ -23,3 +23,4 @@ export declare class QueryCompiler {
23
23
  */
24
24
  private assertPath;
25
25
  }
26
+ export declare const compileIndexPredicate: (compiler: QueryCompiler, where: DocumentQuery) => CompiledQuery;
@@ -1,9 +1,9 @@
1
1
  import { type DocumentQuery, type DocumentScopeOptions } from "akanjs/document";
2
2
  import type { QueryCompiler } from "./QueryCompiler.d.ts";
3
- import type { FindManyOptions, SearchJoin } from "./types.d.ts";
3
+ import type { FindManyOptions, SearchJoin, SqlDialect } from "./types.d.ts";
4
4
  export declare class QueryScope {
5
5
  #private;
6
- constructor(table: string, compiler: QueryCompiler);
6
+ constructor(table: string, compiler: QueryCompiler, dialect: SqlDialect);
7
7
  listQuery(query: DocumentQuery | undefined, options: FindManyOptions, operation?: string): {
8
8
  star: string;
9
9
  tail: string;