spacetimedb 2.6.0 → 2.6.1

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 (172) hide show
  1. package/README.md +211 -211
  2. package/dist/angular/index.cjs.map +1 -1
  3. package/dist/angular/index.mjs.map +1 -1
  4. package/dist/browser/angular/index.mjs.map +1 -1
  5. package/dist/browser/react/index.mjs.map +1 -1
  6. package/dist/browser/solid/index.mjs.map +1 -1
  7. package/dist/browser/svelte/index.mjs.map +1 -1
  8. package/dist/browser/vue/index.mjs.map +1 -1
  9. package/dist/index.browser.mjs.map +1 -1
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/lib/type_builders.d.ts +18 -3
  13. package/dist/lib/type_builders.d.ts.map +1 -1
  14. package/dist/min/index.browser.mjs.map +1 -1
  15. package/dist/min/react/index.mjs.map +1 -1
  16. package/dist/min/sdk/index.browser.mjs.map +1 -1
  17. package/dist/react/index.cjs.map +1 -1
  18. package/dist/react/index.mjs.map +1 -1
  19. package/dist/sdk/db_connection_impl.d.ts.map +1 -1
  20. package/dist/sdk/event_context.d.ts +3 -3
  21. package/dist/sdk/event_context.d.ts.map +1 -1
  22. package/dist/sdk/index.browser.mjs.map +1 -1
  23. package/dist/sdk/index.cjs.map +1 -1
  24. package/dist/sdk/index.mjs.map +1 -1
  25. package/dist/sdk/procedures.d.ts +2 -2
  26. package/dist/sdk/procedures.d.ts.map +1 -1
  27. package/dist/sdk/reducers.d.ts +3 -4
  28. package/dist/sdk/reducers.d.ts.map +1 -1
  29. package/dist/sdk/table_cache.d.ts.map +1 -1
  30. package/dist/sdk/type_utils.d.ts +3 -3
  31. package/dist/sdk/type_utils.d.ts.map +1 -1
  32. package/dist/server/index.mjs.map +1 -1
  33. package/dist/server/runtime.d.ts.map +1 -1
  34. package/dist/server/views.d.ts +4 -2
  35. package/dist/server/views.d.ts.map +1 -1
  36. package/dist/solid/index.cjs.map +1 -1
  37. package/dist/solid/index.mjs.map +1 -1
  38. package/dist/svelte/index.cjs.map +1 -1
  39. package/dist/svelte/index.mjs.map +1 -1
  40. package/dist/svelte/useReducer.d.ts +2 -2
  41. package/dist/svelte/useReducer.d.ts.map +1 -1
  42. package/dist/tanstack/index.cjs.map +1 -1
  43. package/dist/tanstack/index.mjs.map +1 -1
  44. package/dist/vue/index.cjs.map +1 -1
  45. package/dist/vue/index.mjs.map +1 -1
  46. package/package.json +22 -21
  47. package/src/angular/connection_state.ts +19 -19
  48. package/src/angular/index.ts +3 -3
  49. package/src/angular/injectors/index.ts +4 -4
  50. package/src/angular/injectors/inject-reducer.ts +62 -62
  51. package/src/angular/injectors/inject-spacetimedb-connected.ts +13 -13
  52. package/src/angular/injectors/inject-spacetimedb.ts +10 -10
  53. package/src/angular/injectors/inject-table.ts +234 -234
  54. package/src/angular/providers/index.ts +1 -1
  55. package/src/angular/providers/provide-spacetimedb.ts +96 -96
  56. package/src/index.ts +16 -16
  57. package/src/lib/algebraic_type.ts +819 -819
  58. package/src/lib/algebraic_type_variants.ts +26 -26
  59. package/src/lib/algebraic_value.ts +10 -10
  60. package/src/lib/autogen/types.ts +746 -746
  61. package/src/lib/binary_reader.ts +188 -188
  62. package/src/lib/binary_writer.ts +213 -213
  63. package/src/lib/connection_id.ts +102 -102
  64. package/src/lib/constraints.ts +48 -48
  65. package/src/lib/errors.ts +26 -26
  66. package/src/lib/filter.ts +195 -195
  67. package/src/lib/identity.ts +83 -83
  68. package/src/lib/indexes.ts +251 -251
  69. package/src/lib/option.ts +34 -34
  70. package/src/lib/query.ts +1019 -1019
  71. package/src/lib/reducer_schema.ts +38 -38
  72. package/src/lib/reducers.ts +116 -116
  73. package/src/lib/result.ts +36 -36
  74. package/src/lib/schedule_at.ts +86 -86
  75. package/src/lib/schema.ts +420 -420
  76. package/src/lib/table.ts +548 -548
  77. package/src/lib/table_schema.ts +64 -64
  78. package/src/lib/time_duration.ts +77 -77
  79. package/src/lib/timestamp.ts +148 -148
  80. package/src/lib/type_builders.test-d.ts +130 -128
  81. package/src/lib/type_builders.ts +4050 -4014
  82. package/src/lib/type_util.ts +124 -124
  83. package/src/lib/util.ts +196 -196
  84. package/src/lib/uuid.ts +337 -337
  85. package/src/react/SpacetimeDBProvider.ts +84 -84
  86. package/src/react/connection_state.ts +6 -6
  87. package/src/react/index.ts +5 -5
  88. package/src/react/useProcedure.ts +60 -60
  89. package/src/react/useReducer.ts +53 -53
  90. package/src/react/useSpacetimeDB.ts +18 -18
  91. package/src/react/useTable.ts +256 -256
  92. package/src/sdk/client_api/index.ts +114 -114
  93. package/src/sdk/client_api/types/procedures.ts +8 -8
  94. package/src/sdk/client_api/types/reducers.ts +8 -8
  95. package/src/sdk/client_api/types.ts +288 -288
  96. package/src/sdk/client_cache.ts +129 -129
  97. package/src/sdk/client_table.ts +179 -179
  98. package/src/sdk/connection_manager.ts +352 -352
  99. package/src/sdk/db_connection_builder.ts +290 -290
  100. package/src/sdk/db_connection_impl.ts +1363 -1356
  101. package/src/sdk/db_context.ts +28 -28
  102. package/src/sdk/db_view.ts +12 -12
  103. package/src/sdk/decompress.ts +51 -51
  104. package/src/sdk/event.ts +18 -18
  105. package/src/sdk/event_context.ts +51 -51
  106. package/src/sdk/event_emitter.ts +32 -32
  107. package/src/sdk/index.ts +14 -14
  108. package/src/sdk/internal.ts +2 -2
  109. package/src/sdk/json_api.ts +46 -46
  110. package/src/sdk/logger.ts +134 -134
  111. package/src/sdk/message_types.ts +46 -46
  112. package/src/sdk/procedures.ts +87 -83
  113. package/src/sdk/reducer_event.ts +20 -20
  114. package/src/sdk/reducer_handle.ts +12 -12
  115. package/src/sdk/reducers.ts +158 -159
  116. package/src/sdk/schema.ts +45 -45
  117. package/src/sdk/spacetime_module.ts +28 -28
  118. package/src/sdk/subscription_builder_impl.ts +275 -275
  119. package/src/sdk/table_cache.ts +582 -581
  120. package/src/sdk/type_utils.ts +19 -19
  121. package/src/sdk/version.ts +133 -133
  122. package/src/sdk/websocket_decompress_adapter.ts +63 -63
  123. package/src/sdk/websocket_protocols.ts +25 -25
  124. package/src/sdk/websocket_test_adapter.ts +107 -107
  125. package/src/sdk/websocket_v3_frames.ts +126 -126
  126. package/src/sdk/ws.ts +105 -105
  127. package/src/server/console.ts +81 -81
  128. package/src/server/db_view.ts +21 -21
  129. package/src/server/errors.ts +138 -138
  130. package/src/server/http.test-d.ts +80 -80
  131. package/src/server/http.ts +14 -14
  132. package/src/server/http_handlers.ts +413 -413
  133. package/src/server/http_internal.ts +79 -79
  134. package/src/server/http_shared.ts +186 -186
  135. package/src/server/index.ts +37 -37
  136. package/src/server/polyfills.ts +4 -4
  137. package/src/server/procedures.ts +239 -239
  138. package/src/server/query.ts +1 -1
  139. package/src/server/range.ts +53 -53
  140. package/src/server/reducers.ts +113 -113
  141. package/src/server/rng.ts +113 -113
  142. package/src/server/runtime.ts +1102 -1102
  143. package/src/server/schema.test-d.ts +99 -99
  144. package/src/server/schema.ts +663 -663
  145. package/src/server/sys.d.ts +125 -125
  146. package/src/server/view.test-d.ts +194 -194
  147. package/src/server/views.ts +343 -340
  148. package/src/solid/SpacetimeDBProvider.ts +97 -97
  149. package/src/solid/connection_state.ts +6 -6
  150. package/src/solid/index.ts +5 -5
  151. package/src/solid/useProcedure.ts +57 -57
  152. package/src/solid/useReducer.ts +50 -50
  153. package/src/solid/useSpacetimeDB.ts +18 -18
  154. package/src/solid/useTable.ts +203 -203
  155. package/src/svelte/SpacetimeDBProvider.ts +101 -101
  156. package/src/svelte/connection_state.ts +16 -16
  157. package/src/svelte/index.ts +4 -4
  158. package/src/svelte/useReducer.ts +61 -61
  159. package/src/svelte/useSpacetimeDB.ts +22 -22
  160. package/src/svelte/useTable.ts +218 -218
  161. package/src/tanstack/SpacetimeDBQueryClient.ts +330 -330
  162. package/src/tanstack/hooks.ts +83 -83
  163. package/src/tanstack/index.ts +16 -16
  164. package/src/util-stub.ts +1 -1
  165. package/src/vue/SpacetimeDBProvider.ts +157 -157
  166. package/src/vue/connection_state.ts +19 -19
  167. package/src/vue/index.ts +5 -5
  168. package/src/vue/useProcedure.ts +62 -62
  169. package/src/vue/useReducer.ts +55 -55
  170. package/src/vue/useSpacetimeDB.ts +18 -18
  171. package/src/vue/useTable.ts +229 -229
  172. package/LICENSE.txt +0 -759
package/src/lib/schema.ts CHANGED
@@ -1,420 +1,420 @@
1
- import {
2
- AlgebraicType,
3
- ProductType,
4
- SumType,
5
- type AlgebraicTypeType,
6
- type AlgebraicTypeVariants,
7
- } from './algebraic_type';
8
- import type {
9
- CaseConversionPolicy,
10
- RawModuleDefV10,
11
- RawModuleDefV10Section,
12
- RawScopedTypeNameV10,
13
- RawTableDefV10,
14
- } from './autogen/types';
15
- import type { UntypedIndex } from './indexes';
16
- import type { UntypedTableDef } from './table';
17
- import type { UntypedTableSchema } from './table_schema';
18
- import {
19
- ArrayBuilder,
20
- OptionBuilder,
21
- ProductBuilder,
22
- RefBuilder,
23
- ResultBuilder,
24
- RowBuilder,
25
- SumBuilder,
26
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
27
- TypeBuilder,
28
- type ElementsObj,
29
- type Infer,
30
- type InferSpacetimeTypeOfTypeBuilder,
31
- type RowObj,
32
- type VariantsObj,
33
- } from './type_builders';
34
- import type { Values } from './type_util';
35
-
36
- export type TableNamesOf<S extends UntypedSchemaDef> = Values<
37
- S['tables']
38
- >['accessorName'];
39
-
40
- /**
41
- * An untyped representation of the database schema.
42
- */
43
- export type UntypedSchemaDef = {
44
- tables: Record<string, UntypedTableDef>;
45
- };
46
-
47
- /**
48
- * Helper type to convert an array of TableSchema into a schema definition
49
- */
50
- export interface TablesToSchema<T extends Record<string, UntypedTableSchema>>
51
- extends UntypedSchemaDef {
52
- tables: {
53
- readonly [AccName in keyof T & string]: TableToSchema<AccName, T[AccName]>;
54
- };
55
- }
56
-
57
- export interface TableToSchema<
58
- AccName extends string,
59
- T extends UntypedTableSchema,
60
- > extends UntypedTableDef {
61
- accessorName: AccName;
62
- columns: T['rowType']['row'];
63
- rowType: T['rowSpacetimeType'];
64
- // Declarative user-provided table-level indexes.
65
- indexes: T['idxs'];
66
- // Resolved runtime index metadata used by runtime consumers (e.g. TableCache).
67
- resolvedIndexes: readonly UntypedIndex<keyof T['rowType']['row'] & string>[];
68
- constraints: T['constraints'];
69
- }
70
-
71
- export function tablesToSchema<
72
- const T extends Record<string, UntypedTableSchema>,
73
- >(ctx: ModuleContext, tables: T): TablesToSchema<T> {
74
- // `TablesToSchema<T>['tables']` is intentionally readonly in the public type,
75
- // but we need a mutable builder while materializing it from entries.
76
- type MutableTableDefs = {
77
- -readonly [AccName in keyof TablesToSchema<T>['tables']]: TablesToSchema<T>['tables'][AccName];
78
- };
79
- const tableDefs = Object.create(null) as MutableTableDefs;
80
- for (const [accName, schema] of Object.entries(tables) as [
81
- keyof T & string,
82
- T[keyof T & string],
83
- ][]) {
84
- tableDefs[accName] = tableToSchema(
85
- accName,
86
- schema,
87
- schema.tableDef(ctx, accName)
88
- ) as TablesToSchema<T>['tables'][typeof accName];
89
- }
90
-
91
- return {
92
- tables: tableDefs as TablesToSchema<T>['tables'],
93
- };
94
- }
95
-
96
- export function tableToSchema<
97
- AccName extends string,
98
- const T extends UntypedTableSchema,
99
- >(
100
- accName: AccName,
101
- schema: T,
102
- tableDef: RawTableDefV10
103
- ): TableToSchema<AccName, T> {
104
- const getColName = (i: number) =>
105
- schema.rowType.algebraicType.value.elements[i].name;
106
-
107
- type AllowedCol = keyof T['rowType']['row'] & string;
108
- // Build fully-resolved runtime index metadata from the host-facing RawTableDef.
109
- // This is intentionally separate from `schema.idxs`, which keeps the original
110
- // user-declared `IndexOpts` shape for type-level inference.
111
- const resolvedIndexes: UntypedIndex<AllowedCol>[] = tableDef.indexes.map(
112
- idx => {
113
- const accessorName = idx.accessorName;
114
- if (typeof accessorName !== 'string' || accessorName.length === 0) {
115
- throw new TypeError(
116
- `Index '${idx.sourceName ?? '<unknown>'}' on table '${tableDef.sourceName}' is missing accessor name`
117
- );
118
- }
119
-
120
- const columnIds =
121
- idx.algorithm.tag === 'Direct'
122
- ? [idx.algorithm.value]
123
- : idx.algorithm.value;
124
-
125
- const unique = tableDef.constraints.some(
126
- c =>
127
- c.data.tag === 'Unique' &&
128
- c.data.value.columns.every(col => columnIds.includes(col))
129
- );
130
-
131
- const algorithm = (
132
- {
133
- BTree: 'btree',
134
- Hash: 'hash',
135
- Direct: 'direct',
136
- } as const
137
- )[idx.algorithm.tag];
138
-
139
- return {
140
- name: accessorName,
141
- unique,
142
- algorithm,
143
- columns: columnIds.map(getColName) as AllowedCol[],
144
- };
145
- }
146
- );
147
-
148
- return {
149
- // For client,`schama.tableName` will always be there as canonical name.
150
- // For module, if explicit name is not provided via `name`, accessor name will
151
- // be used, it is stored as alias in database, hence works in query builder.
152
- sourceName: schema.tableName || accName,
153
- accessorName: accName,
154
- columns: schema.rowType.row, // typed as T[i]['rowType']['row'] under TablesToSchema<T>
155
- rowType: schema.rowSpacetimeType,
156
- // Keep declarative indexes in their original shape for type-level consumers.
157
- indexes: schema.idxs,
158
- constraints: tableDef.constraints.map(c => ({
159
- name: c.sourceName,
160
- constraint: 'unique',
161
- columns: c.data.value.columns.map(getColName) as [string],
162
- })),
163
- // Expose resolved runtime indexes separately so runtime users don't have to
164
- // reinterpret `indexes` with unsafe casts.
165
- resolvedIndexes,
166
- tableDef,
167
- ...(tableDef.isEvent ? { isEvent: true } : {}),
168
- };
169
- }
170
-
171
- type CompoundTypeCache = Map<
172
- AlgebraicTypeVariants.Product | AlgebraicTypeVariants.Sum,
173
- RefBuilder<any, any>
174
- >;
175
-
176
- export type ModuleDef = {
177
- [S in RawModuleDefV10Section as Uncapitalize<S['tag']>]: S['value'];
178
- };
179
-
180
- type Section = RawModuleDefV10Section;
181
-
182
- export class ModuleContext {
183
- #compoundTypes: CompoundTypeCache = new Map();
184
-
185
- /**
186
- * The global module definition that gets populated by calls to `reducer()` and lifecycle hooks.
187
- */
188
- #moduleDef: ModuleDef = {
189
- typespace: { types: [] },
190
- tables: [],
191
- reducers: [],
192
- types: [],
193
- rowLevelSecurity: [],
194
- schedules: [],
195
- procedures: [],
196
- views: [],
197
- viewPrimaryKeys: [],
198
- lifeCycleReducers: [],
199
- httpHandlers: [],
200
- httpRoutes: [],
201
- caseConversionPolicy: { tag: 'SnakeCase' },
202
- explicitNames: {
203
- entries: [],
204
- },
205
- };
206
-
207
- get moduleDef(): ModuleDef {
208
- return this.#moduleDef;
209
- }
210
-
211
- rawModuleDefV10(): RawModuleDefV10 {
212
- const sections: Section[] = [];
213
-
214
- const push = <T extends Section>(s: T | undefined) => {
215
- if (s) sections.push(s);
216
- };
217
-
218
- const module = this.#moduleDef;
219
-
220
- push(module.typespace && { tag: 'Typespace', value: module.typespace });
221
- push(module.types && { tag: 'Types', value: module.types });
222
- push(module.tables && { tag: 'Tables', value: module.tables });
223
- push(module.reducers && { tag: 'Reducers', value: module.reducers });
224
- push(module.procedures && { tag: 'Procedures', value: module.procedures });
225
- push(module.views && { tag: 'Views', value: module.views });
226
- push(
227
- module.viewPrimaryKeys && {
228
- tag: 'ViewPrimaryKeys',
229
- value: module.viewPrimaryKeys,
230
- }
231
- );
232
- push(module.schedules && { tag: 'Schedules', value: module.schedules });
233
- push(
234
- module.lifeCycleReducers && {
235
- tag: 'LifeCycleReducers',
236
- value: module.lifeCycleReducers,
237
- }
238
- );
239
- push(
240
- module.httpHandlers && {
241
- tag: 'HttpHandlers',
242
- value: module.httpHandlers,
243
- }
244
- );
245
- push(
246
- module.httpRoutes && {
247
- tag: 'HttpRoutes',
248
- value: module.httpRoutes,
249
- }
250
- );
251
- push(
252
- module.rowLevelSecurity && {
253
- tag: 'RowLevelSecurity',
254
- value: module.rowLevelSecurity,
255
- }
256
- );
257
- push(
258
- module.explicitNames && {
259
- tag: 'ExplicitNames',
260
- value: module.explicitNames,
261
- }
262
- );
263
- push(
264
- module.caseConversionPolicy && {
265
- tag: 'CaseConversionPolicy',
266
- value: module.caseConversionPolicy,
267
- }
268
- );
269
- return { sections };
270
- }
271
-
272
- /**
273
- * Set the case conversion policy for this module.
274
- * Called by the settings mechanism.
275
- */
276
- setCaseConversionPolicy(policy: CaseConversionPolicy) {
277
- this.#moduleDef.caseConversionPolicy = policy;
278
- }
279
-
280
- get typespace() {
281
- return this.#moduleDef.typespace;
282
- }
283
-
284
- /**
285
- * Resolves the actual type of a TypeBuilder by following its references until it reaches a non-ref type.
286
- * @param typespace The typespace to resolve types against.
287
- * @param typeBuilder The TypeBuilder to resolve.
288
- * @returns The resolved algebraic type.
289
- */
290
- public resolveType<AT extends AlgebraicTypeType>(
291
- typeBuilder: RefBuilder<any, AT>
292
- ): AT {
293
- let ty: AlgebraicType = typeBuilder.algebraicType;
294
- while (ty.tag === 'Ref') {
295
- ty = this.typespace.types[ty.value];
296
- }
297
- return ty as AT;
298
- }
299
-
300
- /**
301
- * Adds a type to the module definition's typespace as a `Ref` if it is a named compound type (Product or Sum).
302
- * Otherwise, returns the type as is.
303
- * @param name
304
- * @param ty
305
- * @returns
306
- */
307
- public registerTypesRecursively<T extends TypeBuilder<any, AlgebraicType>>(
308
- typeBuilder: T
309
- ): T extends SumBuilder<any> | ProductBuilder<any> | RowBuilder<any>
310
- ? RefBuilder<Infer<T>, InferSpacetimeTypeOfTypeBuilder<T>>
311
- : T {
312
- if (
313
- (typeBuilder instanceof ProductBuilder && !isUnit(typeBuilder)) ||
314
- typeBuilder instanceof SumBuilder ||
315
- typeBuilder instanceof RowBuilder
316
- ) {
317
- return this.#registerCompoundTypeRecursively(typeBuilder) as any;
318
- } else if (typeBuilder instanceof OptionBuilder) {
319
- return new OptionBuilder(
320
- this.registerTypesRecursively(typeBuilder.value)
321
- ) as any;
322
- } else if (typeBuilder instanceof ResultBuilder) {
323
- return new ResultBuilder(
324
- this.registerTypesRecursively(typeBuilder.ok),
325
- this.registerTypesRecursively(typeBuilder.err)
326
- ) as any;
327
- } else if (typeBuilder instanceof ArrayBuilder) {
328
- return new ArrayBuilder(
329
- this.registerTypesRecursively(typeBuilder.element)
330
- ) as any;
331
- } else {
332
- return typeBuilder as any;
333
- }
334
- }
335
-
336
- #registerCompoundTypeRecursively<
337
- T extends
338
- | SumBuilder<VariantsObj>
339
- | ProductBuilder<ElementsObj>
340
- | RowBuilder<RowObj>,
341
- >(typeBuilder: T): RefBuilder<Infer<T>, InferSpacetimeTypeOfTypeBuilder<T>> {
342
- const ty = typeBuilder.algebraicType;
343
- // NB! You must ensure that all TypeBuilder passed into this function
344
- // have a name. This function ensures that nested types always have a
345
- // name by assigning them one if they are missing it.
346
- const name = typeBuilder.typeName;
347
- if (name === undefined) {
348
- throw new Error(
349
- `Missing type name for ${typeBuilder.constructor.name ?? 'TypeBuilder'} ${JSON.stringify(typeBuilder)}`
350
- );
351
- }
352
-
353
- let r = this.#compoundTypes.get(ty);
354
- if (r != null) {
355
- // Already added to typespace
356
- return r;
357
- }
358
-
359
- // Recursively register nested compound types
360
- const newTy =
361
- typeBuilder instanceof RowBuilder || typeBuilder instanceof ProductBuilder
362
- ? ({
363
- tag: 'Product',
364
- value: { elements: [] },
365
- } as AlgebraicTypeVariants.Product)
366
- : ({
367
- tag: 'Sum',
368
- value: { variants: [] },
369
- } as AlgebraicTypeVariants.Sum);
370
-
371
- r = new RefBuilder(this.#moduleDef.typespace.types.length);
372
- this.#moduleDef.typespace.types.push(newTy);
373
-
374
- this.#compoundTypes.set(ty, r);
375
-
376
- if (typeBuilder instanceof RowBuilder) {
377
- for (const [name, elem] of Object.entries(typeBuilder.row)) {
378
- (newTy.value as ProductType).elements.push({
379
- name,
380
- algebraicType: this.registerTypesRecursively(elem.typeBuilder)
381
- .algebraicType,
382
- });
383
- }
384
- } else if (typeBuilder instanceof ProductBuilder) {
385
- for (const [name, elem] of Object.entries(typeBuilder.elements)) {
386
- (newTy.value as ProductType).elements.push({
387
- name,
388
- algebraicType: this.registerTypesRecursively(elem).algebraicType,
389
- });
390
- }
391
- } else if (typeBuilder instanceof SumBuilder) {
392
- for (const [name, variant] of Object.entries(typeBuilder.variants)) {
393
- (newTy.value as SumType).variants.push({
394
- name,
395
- algebraicType: this.registerTypesRecursively(variant).algebraicType,
396
- });
397
- }
398
- }
399
-
400
- this.#moduleDef.types.push({
401
- sourceName: splitName(name),
402
- ty: r.ref,
403
- customOrdering: true,
404
- });
405
-
406
- return r;
407
- }
408
- }
409
-
410
- function isUnit(typeBuilder: ProductBuilder<ElementsObj>): boolean {
411
- return (
412
- typeBuilder.typeName == null &&
413
- typeBuilder.algebraicType.value.elements.length === 0
414
- );
415
- }
416
-
417
- export function splitName(name: string): RawScopedTypeNameV10 {
418
- const scope = name.split('.');
419
- return { sourceName: scope.pop()!, scope };
420
- }
1
+ import {
2
+ AlgebraicType,
3
+ ProductType,
4
+ SumType,
5
+ type AlgebraicTypeType,
6
+ type AlgebraicTypeVariants,
7
+ } from './algebraic_type';
8
+ import type {
9
+ CaseConversionPolicy,
10
+ RawModuleDefV10,
11
+ RawModuleDefV10Section,
12
+ RawScopedTypeNameV10,
13
+ RawTableDefV10,
14
+ } from './autogen/types';
15
+ import type { UntypedIndex } from './indexes';
16
+ import type { UntypedTableDef } from './table';
17
+ import type { UntypedTableSchema } from './table_schema';
18
+ import {
19
+ ArrayBuilder,
20
+ OptionBuilder,
21
+ ProductBuilder,
22
+ RefBuilder,
23
+ ResultBuilder,
24
+ RowBuilder,
25
+ SumBuilder,
26
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
27
+ TypeBuilder,
28
+ type ElementsObj,
29
+ type Infer,
30
+ type InferSpacetimeTypeOfTypeBuilder,
31
+ type RowObj,
32
+ type VariantsObj,
33
+ } from './type_builders';
34
+ import type { Values } from './type_util';
35
+
36
+ export type TableNamesOf<S extends UntypedSchemaDef> = Values<
37
+ S['tables']
38
+ >['accessorName'];
39
+
40
+ /**
41
+ * An untyped representation of the database schema.
42
+ */
43
+ export type UntypedSchemaDef = {
44
+ tables: Record<string, UntypedTableDef>;
45
+ };
46
+
47
+ /**
48
+ * Helper type to convert an array of TableSchema into a schema definition
49
+ */
50
+ export interface TablesToSchema<T extends Record<string, UntypedTableSchema>>
51
+ extends UntypedSchemaDef {
52
+ tables: {
53
+ readonly [AccName in keyof T & string]: TableToSchema<AccName, T[AccName]>;
54
+ };
55
+ }
56
+
57
+ export interface TableToSchema<
58
+ AccName extends string,
59
+ T extends UntypedTableSchema,
60
+ > extends UntypedTableDef {
61
+ accessorName: AccName;
62
+ columns: T['rowType']['row'];
63
+ rowType: T['rowSpacetimeType'];
64
+ // Declarative user-provided table-level indexes.
65
+ indexes: T['idxs'];
66
+ // Resolved runtime index metadata used by runtime consumers (e.g. TableCache).
67
+ resolvedIndexes: readonly UntypedIndex<keyof T['rowType']['row'] & string>[];
68
+ constraints: T['constraints'];
69
+ }
70
+
71
+ export function tablesToSchema<
72
+ const T extends Record<string, UntypedTableSchema>,
73
+ >(ctx: ModuleContext, tables: T): TablesToSchema<T> {
74
+ // `TablesToSchema<T>['tables']` is intentionally readonly in the public type,
75
+ // but we need a mutable builder while materializing it from entries.
76
+ type MutableTableDefs = {
77
+ -readonly [AccName in keyof TablesToSchema<T>['tables']]: TablesToSchema<T>['tables'][AccName];
78
+ };
79
+ const tableDefs = Object.create(null) as MutableTableDefs;
80
+ for (const [accName, schema] of Object.entries(tables) as [
81
+ keyof T & string,
82
+ T[keyof T & string],
83
+ ][]) {
84
+ tableDefs[accName] = tableToSchema(
85
+ accName,
86
+ schema,
87
+ schema.tableDef(ctx, accName)
88
+ ) as TablesToSchema<T>['tables'][typeof accName];
89
+ }
90
+
91
+ return {
92
+ tables: tableDefs as TablesToSchema<T>['tables'],
93
+ };
94
+ }
95
+
96
+ export function tableToSchema<
97
+ AccName extends string,
98
+ const T extends UntypedTableSchema,
99
+ >(
100
+ accName: AccName,
101
+ schema: T,
102
+ tableDef: RawTableDefV10
103
+ ): TableToSchema<AccName, T> {
104
+ const getColName = (i: number) =>
105
+ schema.rowType.algebraicType.value.elements[i].name;
106
+
107
+ type AllowedCol = keyof T['rowType']['row'] & string;
108
+ // Build fully-resolved runtime index metadata from the host-facing RawTableDef.
109
+ // This is intentionally separate from `schema.idxs`, which keeps the original
110
+ // user-declared `IndexOpts` shape for type-level inference.
111
+ const resolvedIndexes: UntypedIndex<AllowedCol>[] = tableDef.indexes.map(
112
+ idx => {
113
+ const accessorName = idx.accessorName;
114
+ if (typeof accessorName !== 'string' || accessorName.length === 0) {
115
+ throw new TypeError(
116
+ `Index '${idx.sourceName ?? '<unknown>'}' on table '${tableDef.sourceName}' is missing accessor name`
117
+ );
118
+ }
119
+
120
+ const columnIds =
121
+ idx.algorithm.tag === 'Direct'
122
+ ? [idx.algorithm.value]
123
+ : idx.algorithm.value;
124
+
125
+ const unique = tableDef.constraints.some(
126
+ c =>
127
+ c.data.tag === 'Unique' &&
128
+ c.data.value.columns.every(col => columnIds.includes(col))
129
+ );
130
+
131
+ const algorithm = (
132
+ {
133
+ BTree: 'btree',
134
+ Hash: 'hash',
135
+ Direct: 'direct',
136
+ } as const
137
+ )[idx.algorithm.tag];
138
+
139
+ return {
140
+ name: accessorName,
141
+ unique,
142
+ algorithm,
143
+ columns: columnIds.map(getColName) as AllowedCol[],
144
+ };
145
+ }
146
+ );
147
+
148
+ return {
149
+ // For client,`schama.tableName` will always be there as canonical name.
150
+ // For module, if explicit name is not provided via `name`, accessor name will
151
+ // be used, it is stored as alias in database, hence works in query builder.
152
+ sourceName: schema.tableName || accName,
153
+ accessorName: accName,
154
+ columns: schema.rowType.row, // typed as T[i]['rowType']['row'] under TablesToSchema<T>
155
+ rowType: schema.rowSpacetimeType,
156
+ // Keep declarative indexes in their original shape for type-level consumers.
157
+ indexes: schema.idxs,
158
+ constraints: tableDef.constraints.map(c => ({
159
+ name: c.sourceName,
160
+ constraint: 'unique',
161
+ columns: c.data.value.columns.map(getColName) as [string],
162
+ })),
163
+ // Expose resolved runtime indexes separately so runtime users don't have to
164
+ // reinterpret `indexes` with unsafe casts.
165
+ resolvedIndexes,
166
+ tableDef,
167
+ ...(tableDef.isEvent ? { isEvent: true } : {}),
168
+ };
169
+ }
170
+
171
+ type CompoundTypeCache = Map<
172
+ AlgebraicTypeVariants.Product | AlgebraicTypeVariants.Sum,
173
+ RefBuilder<any, any>
174
+ >;
175
+
176
+ export type ModuleDef = {
177
+ [S in RawModuleDefV10Section as Uncapitalize<S['tag']>]: S['value'];
178
+ };
179
+
180
+ type Section = RawModuleDefV10Section;
181
+
182
+ export class ModuleContext {
183
+ #compoundTypes: CompoundTypeCache = new Map();
184
+
185
+ /**
186
+ * The global module definition that gets populated by calls to `reducer()` and lifecycle hooks.
187
+ */
188
+ #moduleDef: ModuleDef = {
189
+ typespace: { types: [] },
190
+ tables: [],
191
+ reducers: [],
192
+ types: [],
193
+ rowLevelSecurity: [],
194
+ schedules: [],
195
+ procedures: [],
196
+ views: [],
197
+ viewPrimaryKeys: [],
198
+ lifeCycleReducers: [],
199
+ httpHandlers: [],
200
+ httpRoutes: [],
201
+ caseConversionPolicy: { tag: 'SnakeCase' },
202
+ explicitNames: {
203
+ entries: [],
204
+ },
205
+ };
206
+
207
+ get moduleDef(): ModuleDef {
208
+ return this.#moduleDef;
209
+ }
210
+
211
+ rawModuleDefV10(): RawModuleDefV10 {
212
+ const sections: Section[] = [];
213
+
214
+ const push = <T extends Section>(s: T | undefined) => {
215
+ if (s) sections.push(s);
216
+ };
217
+
218
+ const module = this.#moduleDef;
219
+
220
+ push(module.typespace && { tag: 'Typespace', value: module.typespace });
221
+ push(module.types && { tag: 'Types', value: module.types });
222
+ push(module.tables && { tag: 'Tables', value: module.tables });
223
+ push(module.reducers && { tag: 'Reducers', value: module.reducers });
224
+ push(module.procedures && { tag: 'Procedures', value: module.procedures });
225
+ push(module.views && { tag: 'Views', value: module.views });
226
+ push(
227
+ module.viewPrimaryKeys && {
228
+ tag: 'ViewPrimaryKeys',
229
+ value: module.viewPrimaryKeys,
230
+ }
231
+ );
232
+ push(module.schedules && { tag: 'Schedules', value: module.schedules });
233
+ push(
234
+ module.lifeCycleReducers && {
235
+ tag: 'LifeCycleReducers',
236
+ value: module.lifeCycleReducers,
237
+ }
238
+ );
239
+ push(
240
+ module.httpHandlers && {
241
+ tag: 'HttpHandlers',
242
+ value: module.httpHandlers,
243
+ }
244
+ );
245
+ push(
246
+ module.httpRoutes && {
247
+ tag: 'HttpRoutes',
248
+ value: module.httpRoutes,
249
+ }
250
+ );
251
+ push(
252
+ module.rowLevelSecurity && {
253
+ tag: 'RowLevelSecurity',
254
+ value: module.rowLevelSecurity,
255
+ }
256
+ );
257
+ push(
258
+ module.explicitNames && {
259
+ tag: 'ExplicitNames',
260
+ value: module.explicitNames,
261
+ }
262
+ );
263
+ push(
264
+ module.caseConversionPolicy && {
265
+ tag: 'CaseConversionPolicy',
266
+ value: module.caseConversionPolicy,
267
+ }
268
+ );
269
+ return { sections };
270
+ }
271
+
272
+ /**
273
+ * Set the case conversion policy for this module.
274
+ * Called by the settings mechanism.
275
+ */
276
+ setCaseConversionPolicy(policy: CaseConversionPolicy) {
277
+ this.#moduleDef.caseConversionPolicy = policy;
278
+ }
279
+
280
+ get typespace() {
281
+ return this.#moduleDef.typespace;
282
+ }
283
+
284
+ /**
285
+ * Resolves the actual type of a TypeBuilder by following its references until it reaches a non-ref type.
286
+ * @param typespace The typespace to resolve types against.
287
+ * @param typeBuilder The TypeBuilder to resolve.
288
+ * @returns The resolved algebraic type.
289
+ */
290
+ public resolveType<AT extends AlgebraicTypeType>(
291
+ typeBuilder: RefBuilder<any, AT>
292
+ ): AT {
293
+ let ty: AlgebraicType = typeBuilder.algebraicType;
294
+ while (ty.tag === 'Ref') {
295
+ ty = this.typespace.types[ty.value];
296
+ }
297
+ return ty as AT;
298
+ }
299
+
300
+ /**
301
+ * Adds a type to the module definition's typespace as a `Ref` if it is a named compound type (Product or Sum).
302
+ * Otherwise, returns the type as is.
303
+ * @param name
304
+ * @param ty
305
+ * @returns
306
+ */
307
+ public registerTypesRecursively<T extends TypeBuilder<any, AlgebraicType>>(
308
+ typeBuilder: T
309
+ ): T extends SumBuilder<any> | ProductBuilder<any> | RowBuilder<any>
310
+ ? RefBuilder<Infer<T>, InferSpacetimeTypeOfTypeBuilder<T>>
311
+ : T {
312
+ if (
313
+ (typeBuilder instanceof ProductBuilder && !isUnit(typeBuilder)) ||
314
+ typeBuilder instanceof SumBuilder ||
315
+ typeBuilder instanceof RowBuilder
316
+ ) {
317
+ return this.#registerCompoundTypeRecursively(typeBuilder) as any;
318
+ } else if (typeBuilder instanceof OptionBuilder) {
319
+ return new OptionBuilder(
320
+ this.registerTypesRecursively(typeBuilder.value)
321
+ ) as any;
322
+ } else if (typeBuilder instanceof ResultBuilder) {
323
+ return new ResultBuilder(
324
+ this.registerTypesRecursively(typeBuilder.ok),
325
+ this.registerTypesRecursively(typeBuilder.err)
326
+ ) as any;
327
+ } else if (typeBuilder instanceof ArrayBuilder) {
328
+ return new ArrayBuilder(
329
+ this.registerTypesRecursively(typeBuilder.element)
330
+ ) as any;
331
+ } else {
332
+ return typeBuilder as any;
333
+ }
334
+ }
335
+
336
+ #registerCompoundTypeRecursively<
337
+ T extends
338
+ | SumBuilder<VariantsObj>
339
+ | ProductBuilder<ElementsObj>
340
+ | RowBuilder<RowObj>,
341
+ >(typeBuilder: T): RefBuilder<Infer<T>, InferSpacetimeTypeOfTypeBuilder<T>> {
342
+ const ty = typeBuilder.algebraicType;
343
+ // NB! You must ensure that all TypeBuilder passed into this function
344
+ // have a name. This function ensures that nested types always have a
345
+ // name by assigning them one if they are missing it.
346
+ const name = typeBuilder.typeName;
347
+ if (name === undefined) {
348
+ throw new Error(
349
+ `Missing type name for ${typeBuilder.constructor.name ?? 'TypeBuilder'} ${JSON.stringify(typeBuilder)}`
350
+ );
351
+ }
352
+
353
+ let r = this.#compoundTypes.get(ty);
354
+ if (r != null) {
355
+ // Already added to typespace
356
+ return r;
357
+ }
358
+
359
+ // Recursively register nested compound types
360
+ const newTy =
361
+ typeBuilder instanceof RowBuilder || typeBuilder instanceof ProductBuilder
362
+ ? ({
363
+ tag: 'Product',
364
+ value: { elements: [] },
365
+ } as AlgebraicTypeVariants.Product)
366
+ : ({
367
+ tag: 'Sum',
368
+ value: { variants: [] },
369
+ } as AlgebraicTypeVariants.Sum);
370
+
371
+ r = new RefBuilder(this.#moduleDef.typespace.types.length);
372
+ this.#moduleDef.typespace.types.push(newTy);
373
+
374
+ this.#compoundTypes.set(ty, r);
375
+
376
+ if (typeBuilder instanceof RowBuilder) {
377
+ for (const [name, elem] of Object.entries(typeBuilder.row)) {
378
+ (newTy.value as ProductType).elements.push({
379
+ name,
380
+ algebraicType: this.registerTypesRecursively(elem.typeBuilder)
381
+ .algebraicType,
382
+ });
383
+ }
384
+ } else if (typeBuilder instanceof ProductBuilder) {
385
+ for (const [name, elem] of Object.entries(typeBuilder.elements)) {
386
+ (newTy.value as ProductType).elements.push({
387
+ name,
388
+ algebraicType: this.registerTypesRecursively(elem).algebraicType,
389
+ });
390
+ }
391
+ } else if (typeBuilder instanceof SumBuilder) {
392
+ for (const [name, variant] of Object.entries(typeBuilder.variants)) {
393
+ (newTy.value as SumType).variants.push({
394
+ name,
395
+ algebraicType: this.registerTypesRecursively(variant).algebraicType,
396
+ });
397
+ }
398
+ }
399
+
400
+ this.#moduleDef.types.push({
401
+ sourceName: splitName(name),
402
+ ty: r.ref,
403
+ customOrdering: true,
404
+ });
405
+
406
+ return r;
407
+ }
408
+ }
409
+
410
+ function isUnit(typeBuilder: ProductBuilder<ElementsObj>): boolean {
411
+ return (
412
+ typeBuilder.typeName == null &&
413
+ typeBuilder.algebraicType.value.elements.length === 0
414
+ );
415
+ }
416
+
417
+ export function splitName(name: string): RawScopedTypeNameV10 {
418
+ const scope = name.split('.');
419
+ return { sourceName: scope.pop()!, scope };
420
+ }