spacetimedb 2.4.1 → 2.6.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 (194) hide show
  1. package/LICENSE.txt +759 -759
  2. package/README.md +211 -120
  3. package/dist/angular/index.cjs.map +1 -1
  4. package/dist/angular/index.mjs.map +1 -1
  5. package/dist/browser/angular/index.mjs.map +1 -1
  6. package/dist/browser/react/index.mjs +129 -57
  7. package/dist/browser/react/index.mjs.map +1 -1
  8. package/dist/browser/solid/index.mjs +1933 -0
  9. package/dist/browser/solid/index.mjs.map +1 -0
  10. package/dist/browser/svelte/index.mjs.map +1 -1
  11. package/dist/browser/vue/index.mjs.map +1 -1
  12. package/dist/index.browser.mjs +10 -2
  13. package/dist/index.browser.mjs.map +1 -1
  14. package/dist/index.cjs +10 -2
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.mjs +10 -2
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/min/index.browser.mjs +1 -1
  19. package/dist/min/index.browser.mjs.map +1 -1
  20. package/dist/min/react/index.mjs +1 -1
  21. package/dist/min/react/index.mjs.map +1 -1
  22. package/dist/min/sdk/index.browser.mjs +1 -1
  23. package/dist/min/sdk/index.browser.mjs.map +1 -1
  24. package/dist/react/index.cjs +129 -57
  25. package/dist/react/index.cjs.map +1 -1
  26. package/dist/react/index.mjs +129 -57
  27. package/dist/react/index.mjs.map +1 -1
  28. package/dist/react/useTable.d.ts.map +1 -1
  29. package/dist/sdk/connection_manager.d.ts +8 -0
  30. package/dist/sdk/connection_manager.d.ts.map +1 -1
  31. package/dist/sdk/db_connection_impl.d.ts +7 -0
  32. package/dist/sdk/db_connection_impl.d.ts.map +1 -1
  33. package/dist/sdk/index.browser.mjs +10 -2
  34. package/dist/sdk/index.browser.mjs.map +1 -1
  35. package/dist/sdk/index.cjs +10 -2
  36. package/dist/sdk/index.cjs.map +1 -1
  37. package/dist/sdk/index.mjs +10 -2
  38. package/dist/sdk/index.mjs.map +1 -1
  39. package/dist/sdk/websocket_test_adapter.d.ts +2 -1
  40. package/dist/sdk/websocket_test_adapter.d.ts.map +1 -1
  41. package/dist/server/index.mjs.map +1 -1
  42. package/dist/server/runtime.d.ts.map +1 -1
  43. package/dist/solid/SpacetimeDBProvider.d.ts +7 -0
  44. package/dist/solid/SpacetimeDBProvider.d.ts.map +1 -0
  45. package/dist/solid/connection_state.d.ts +6 -0
  46. package/dist/solid/connection_state.d.ts.map +1 -0
  47. package/dist/solid/index.cjs +1939 -0
  48. package/dist/solid/index.cjs.map +1 -0
  49. package/dist/solid/index.d.ts +6 -0
  50. package/dist/solid/index.d.ts.map +1 -0
  51. package/dist/solid/index.mjs +1933 -0
  52. package/dist/solid/index.mjs.map +1 -0
  53. package/dist/solid/useProcedure.d.ts +4 -0
  54. package/dist/solid/useProcedure.d.ts.map +1 -0
  55. package/dist/solid/useReducer.d.ts +4 -0
  56. package/dist/solid/useReducer.d.ts.map +1 -0
  57. package/dist/solid/useSpacetimeDB.d.ts +4 -0
  58. package/dist/solid/useSpacetimeDB.d.ts.map +1 -0
  59. package/dist/solid/useTable.d.ts +32 -0
  60. package/dist/solid/useTable.d.ts.map +1 -0
  61. package/dist/svelte/index.cjs.map +1 -1
  62. package/dist/svelte/index.mjs.map +1 -1
  63. package/dist/tanstack/index.cjs +120 -50
  64. package/dist/tanstack/index.cjs.map +1 -1
  65. package/dist/tanstack/index.mjs +120 -50
  66. package/dist/tanstack/index.mjs.map +1 -1
  67. package/dist/vue/index.cjs.map +1 -1
  68. package/dist/vue/index.mjs.map +1 -1
  69. package/package.json +13 -3
  70. package/src/angular/connection_state.ts +19 -19
  71. package/src/angular/index.ts +3 -3
  72. package/src/angular/injectors/index.ts +4 -4
  73. package/src/angular/injectors/inject-reducer.ts +62 -62
  74. package/src/angular/injectors/inject-spacetimedb-connected.ts +13 -13
  75. package/src/angular/injectors/inject-spacetimedb.ts +10 -10
  76. package/src/angular/injectors/inject-table.ts +234 -234
  77. package/src/angular/providers/index.ts +1 -1
  78. package/src/angular/providers/provide-spacetimedb.ts +96 -96
  79. package/src/index.ts +16 -16
  80. package/src/lib/algebraic_type.ts +819 -819
  81. package/src/lib/algebraic_type_variants.ts +26 -26
  82. package/src/lib/algebraic_value.ts +10 -10
  83. package/src/lib/autogen/types.ts +746 -746
  84. package/src/lib/binary_reader.ts +188 -188
  85. package/src/lib/binary_writer.ts +213 -213
  86. package/src/lib/connection_id.ts +102 -102
  87. package/src/lib/constraints.ts +48 -48
  88. package/src/lib/errors.ts +26 -26
  89. package/src/lib/filter.ts +195 -195
  90. package/src/lib/identity.ts +83 -83
  91. package/src/lib/indexes.ts +251 -251
  92. package/src/lib/option.ts +34 -34
  93. package/src/lib/query.ts +1019 -1019
  94. package/src/lib/reducer_schema.ts +38 -38
  95. package/src/lib/reducers.ts +116 -116
  96. package/src/lib/result.ts +36 -36
  97. package/src/lib/schedule_at.ts +86 -86
  98. package/src/lib/schema.ts +420 -420
  99. package/src/lib/table.ts +548 -548
  100. package/src/lib/table_schema.ts +64 -64
  101. package/src/lib/time_duration.ts +77 -77
  102. package/src/lib/timestamp.ts +148 -148
  103. package/src/lib/type_builders.test-d.ts +128 -128
  104. package/src/lib/type_builders.ts +4014 -4014
  105. package/src/lib/type_util.ts +124 -124
  106. package/src/lib/util.ts +196 -196
  107. package/src/lib/uuid.ts +337 -337
  108. package/src/react/SpacetimeDBProvider.ts +84 -84
  109. package/src/react/connection_state.ts +6 -6
  110. package/src/react/index.ts +5 -5
  111. package/src/react/useProcedure.ts +60 -60
  112. package/src/react/useReducer.ts +53 -53
  113. package/src/react/useSpacetimeDB.ts +18 -18
  114. package/src/react/useTable.ts +256 -251
  115. package/src/sdk/client_api/index.ts +114 -114
  116. package/src/sdk/client_api/types/procedures.ts +8 -8
  117. package/src/sdk/client_api/types/reducers.ts +8 -8
  118. package/src/sdk/client_api/types.ts +288 -288
  119. package/src/sdk/client_cache.ts +129 -129
  120. package/src/sdk/client_table.ts +179 -179
  121. package/src/sdk/connection_manager.ts +352 -237
  122. package/src/sdk/db_connection_builder.ts +290 -290
  123. package/src/sdk/db_connection_impl.ts +1356 -1347
  124. package/src/sdk/db_context.ts +28 -28
  125. package/src/sdk/db_view.ts +12 -12
  126. package/src/sdk/decompress.ts +51 -51
  127. package/src/sdk/event.ts +18 -18
  128. package/src/sdk/event_context.ts +51 -51
  129. package/src/sdk/event_emitter.ts +32 -32
  130. package/src/sdk/index.ts +14 -14
  131. package/src/sdk/internal.ts +2 -2
  132. package/src/sdk/json_api.ts +46 -46
  133. package/src/sdk/logger.ts +134 -134
  134. package/src/sdk/message_types.ts +46 -46
  135. package/src/sdk/procedures.ts +83 -83
  136. package/src/sdk/reducer_event.ts +20 -20
  137. package/src/sdk/reducer_handle.ts +12 -12
  138. package/src/sdk/reducers.ts +159 -159
  139. package/src/sdk/schema.ts +45 -45
  140. package/src/sdk/spacetime_module.ts +28 -28
  141. package/src/sdk/subscription_builder_impl.ts +275 -275
  142. package/src/sdk/table_cache.ts +581 -581
  143. package/src/sdk/type_utils.ts +19 -19
  144. package/src/sdk/version.ts +133 -133
  145. package/src/sdk/websocket_decompress_adapter.ts +63 -63
  146. package/src/sdk/websocket_protocols.ts +25 -25
  147. package/src/sdk/websocket_test_adapter.ts +107 -100
  148. package/src/sdk/websocket_v3_frames.ts +126 -126
  149. package/src/sdk/ws.ts +105 -105
  150. package/src/server/console.ts +81 -81
  151. package/src/server/db_view.ts +21 -21
  152. package/src/server/errors.ts +138 -138
  153. package/src/server/http.test-d.ts +80 -80
  154. package/src/server/http.ts +14 -14
  155. package/src/server/http_handlers.ts +413 -413
  156. package/src/server/http_internal.ts +79 -79
  157. package/src/server/http_shared.ts +186 -186
  158. package/src/server/index.ts +37 -37
  159. package/src/server/polyfills.ts +4 -4
  160. package/src/server/procedures.ts +239 -239
  161. package/src/server/query.ts +1 -1
  162. package/src/server/range.ts +53 -53
  163. package/src/server/reducers.ts +113 -113
  164. package/src/server/rng.ts +113 -113
  165. package/src/server/runtime.ts +1102 -1102
  166. package/src/server/schema.test-d.ts +99 -99
  167. package/src/server/schema.ts +663 -663
  168. package/src/server/sys.d.ts +125 -125
  169. package/src/server/view.test-d.ts +194 -194
  170. package/src/server/views.ts +340 -340
  171. package/src/solid/SpacetimeDBProvider.ts +97 -0
  172. package/src/solid/connection_state.ts +6 -0
  173. package/src/solid/index.ts +5 -0
  174. package/src/solid/useProcedure.ts +57 -0
  175. package/src/solid/useReducer.ts +50 -0
  176. package/src/solid/useSpacetimeDB.ts +18 -0
  177. package/src/solid/useTable.ts +203 -0
  178. package/src/svelte/SpacetimeDBProvider.ts +101 -101
  179. package/src/svelte/connection_state.ts +16 -16
  180. package/src/svelte/index.ts +4 -4
  181. package/src/svelte/useReducer.ts +61 -61
  182. package/src/svelte/useSpacetimeDB.ts +22 -22
  183. package/src/svelte/useTable.ts +218 -218
  184. package/src/tanstack/SpacetimeDBQueryClient.ts +330 -330
  185. package/src/tanstack/hooks.ts +83 -83
  186. package/src/tanstack/index.ts +16 -16
  187. package/src/util-stub.ts +1 -1
  188. package/src/vue/SpacetimeDBProvider.ts +157 -157
  189. package/src/vue/connection_state.ts +19 -19
  190. package/src/vue/index.ts +5 -5
  191. package/src/vue/useProcedure.ts +62 -62
  192. package/src/vue/useReducer.ts +55 -55
  193. package/src/vue/useSpacetimeDB.ts +18 -18
  194. package/src/vue/useTable.ts +229 -229
package/src/lib/uuid.ts CHANGED
@@ -1,337 +1,337 @@
1
- import { Timestamp } from './timestamp';
2
- import { AlgebraicType } from './algebraic_type.ts';
3
-
4
- export type UuidAlgebraicType = {
5
- tag: 'Product';
6
- value: {
7
- elements: [
8
- {
9
- name: '__uuid__';
10
- algebraicType: { tag: 'U128' };
11
- },
12
- ];
13
- };
14
- };
15
-
16
- /**
17
- * Supported UUID versions.
18
- *
19
- * - `Nil` – The "Nil" UUID (all zeros)
20
- * - `V4` – Version 4: random
21
- * - `V7` – Version 7: timestamp + counter + random
22
- * - `Max` – The "Max" UUID (all ones)
23
- */
24
- type UuidVersion = 'Nil' | 'V4' | 'V7' | 'Max';
25
-
26
- /**
27
- * A universally unique identifier (UUID).
28
- *
29
- * Supports UUID `Nil`, `Max`, `V4` (random), and `V7`
30
- * (timestamp + counter + random).
31
- *
32
- * Internally represented as an unsigned 128-bit between 0 and `MAX_UUID_BIGINT`.
33
- */
34
- export class Uuid {
35
- __uuid__: bigint;
36
-
37
- /**
38
- * The nil UUID (all zeros).
39
- *
40
- * @example
41
- * ```ts
42
- * const uuid = Uuid.NIL;
43
- * console.assert(
44
- * uuid.toString() === "00000000-0000-0000-0000-000000000000"
45
- * );
46
- * ```
47
- */
48
- static readonly NIL = new Uuid(0n);
49
- static readonly MAX_UUID_BIGINT = 0xffffffffffffffffffffffffffffffffn;
50
- /**
51
- * The max UUID (all ones).
52
- *
53
- * @example
54
- * ```ts
55
- * const uuid = Uuid.MAX;
56
- * console.assert(
57
- * uuid.toString() === "ffffffff-ffff-ffff-ffff-ffffffffffff"
58
- * );
59
- * ```
60
- */
61
- static readonly MAX = new Uuid(Uuid.MAX_UUID_BIGINT);
62
-
63
- /**
64
- * Create a UUID from a raw 128-bit value.
65
- *
66
- * @param u - Unsigned 128-bit integer
67
- * @throws {Error} If the value is outside the valid UUID range
68
- */
69
- constructor(u: bigint) {
70
- // Must fit in exactly 16 bytes
71
- if (u < 0n || u > Uuid.MAX_UUID_BIGINT) {
72
- throw new Error('Invalid UUID: must be between 0 and `MAX_UUID_BIGINT`');
73
- }
74
- this.__uuid__ = u;
75
- }
76
-
77
- /**
78
- * Create a UUID `v4` from explicit random bytes.
79
- *
80
- * This method assumes the bytes are already sufficiently random.
81
- * It only sets the appropriate bits for the UUID version and variant.
82
- *
83
- * @param bytes - Exactly 16 random bytes
84
- * @returns A UUID `v4`
85
- * @throws {Error} If `bytes.length !== 16`
86
- *
87
- * @example
88
- * ```ts
89
- * const randomBytes = new Uint8Array(16);
90
- * const uuid = Uuid.fromRandomBytesV4(randomBytes);
91
- *
92
- * console.assert(
93
- * uuid.toString() === "00000000-0000-4000-8000-000000000000"
94
- * );
95
- * ```
96
- */
97
- static fromRandomBytesV4(bytes: Uint8Array): Uuid {
98
- if (bytes.length !== 16) throw new Error('UUID v4 requires 16 bytes');
99
- const arr = new Uint8Array(bytes);
100
- arr[6] = (arr[6] & 0x0f) | 0x40; // version 4
101
- arr[8] = (arr[8] & 0x3f) | 0x80; // variant
102
- return new Uuid(Uuid.bytesToBigInt(arr));
103
- }
104
-
105
- /**
106
- * Generate a UUID `v7` using a monotonic counter from `0` to `2^31 - 1`,
107
- * a timestamp, and 4 random bytes.
108
- *
109
- * The counter wraps around on overflow.
110
- *
111
- * The UUID `v7` is structured as follows:
112
- *
113
- * ```ascii
114
- * ┌───────────────────────────────────────────────┬───────────────────┐
115
- * | B0 | B1 | B2 | B3 | B4 | B5 | B6 |
116
- * ├───────────────────────────────────────────────┼───────────────────┤
117
- * | unix_ts_ms | version 7 |
118
- * └───────────────────────────────────────────────┴───────────────────┘
119
- * ┌──────────────┬─────────┬──────────────────┬───────────────────────┐
120
- * | B7 | B8 | B9 | B10 | B11 | B12 | B13 | B14 | B15 |
121
- * ├──────────────┼─────────┼──────────────────┼───────────────────────┤
122
- * | counter_high | variant | counter_low | random |
123
- * └──────────────┴─────────┴──────────────────┴───────────────────────┘
124
- * ```
125
- *
126
- * @param counter - Mutable monotonic counter (31-bit)
127
- * @param now - Timestamp since the Unix epoch
128
- * @param randomBytes - Exactly 4 random bytes
129
- * @returns A UUID `v7`
130
- *
131
- * @throws {Error} If the `counter` is negative
132
- * @throws {Error} If the `timestamp` is before the Unix epoch
133
- * @throws {Error} If `randomBytes.length !== 4`
134
- *
135
- * @example
136
- * ```ts
137
- * const now = Timestamp.fromMillis(1_686_000_000_000n);
138
- * const counter = { value: 1 };
139
- * const randomBytes = new Uint8Array(4);
140
- *
141
- * const uuid = Uuid.fromCounterV7(counter, now, randomBytes);
142
- *
143
- * console.assert(
144
- * uuid.toString() === "0000647e-5180-7000-8000-000200000000"
145
- * );
146
- * ```
147
- */
148
- static fromCounterV7(
149
- counter: { value: number },
150
- now: Timestamp,
151
- randomBytes: Uint8Array
152
- ): Uuid {
153
- if (randomBytes.length !== 4) {
154
- throw new Error('`fromCounterV7` requires `randomBytes.length == 4`');
155
- }
156
-
157
- if (counter.value < 0) {
158
- throw new Error('`fromCounterV7` uuid `counter` must be non-negative');
159
- }
160
-
161
- if (now.__timestamp_micros_since_unix_epoch__ < 0) {
162
- throw new Error('`fromCounterV7` `timestamp` before unix epoch');
163
- }
164
-
165
- // 31-bit monotonic counter with wraparound
166
- const counterVal = counter.value;
167
- counter.value = (counterVal + 1) & 0x7fff_ffff;
168
-
169
- // 48-bit unix timestamp (ms)
170
- const tsMs = now.toMillis() & 0xffff_ffff_ffffn;
171
-
172
- const bytes = new Uint8Array(16);
173
-
174
- // unix_ts_ms (48 bits)
175
- bytes[0] = Number((tsMs >> 40n) & 0xffn);
176
- bytes[1] = Number((tsMs >> 32n) & 0xffn);
177
- bytes[2] = Number((tsMs >> 24n) & 0xffn);
178
- bytes[3] = Number((tsMs >> 16n) & 0xffn);
179
- bytes[4] = Number((tsMs >> 8n) & 0xffn);
180
- bytes[5] = Number(tsMs & 0xffn);
181
-
182
- // Counter bits (31 bits total)
183
- bytes[7] = (counterVal >>> 23) & 0xff;
184
- bytes[9] = (counterVal >>> 15) & 0xff;
185
- bytes[10] = (counterVal >>> 7) & 0xff;
186
- bytes[11] = ((counterVal & 0x7f) << 1) & 0xff;
187
-
188
- // Random bytes
189
- bytes[12] |= randomBytes[0] & 0x7f;
190
- bytes[13] = randomBytes[1];
191
- bytes[14] = randomBytes[2];
192
- bytes[15] = randomBytes[3];
193
-
194
- // Version 7
195
- bytes[6] = (bytes[6] & 0x0f) | 0x70;
196
-
197
- // Variant RFC4122
198
- bytes[8] = (bytes[8] & 0x3f) | 0x80;
199
-
200
- return new Uuid(Uuid.bytesToBigInt(bytes));
201
- }
202
-
203
- /**
204
- * Parse a UUID from a string representation.
205
- *
206
- * @param s - UUID string
207
- * @returns Parsed UUID
208
- * @throws {Error} If the string is not a valid UUID
209
- *
210
- * @example
211
- * ```ts
212
- * const s = "01888d6e-5c00-7000-8000-000000000000";
213
- * const uuid = Uuid.parse(s);
214
- *
215
- * console.assert(uuid.toString() === s);
216
- * ```
217
- */
218
- static parse(s: string): Uuid {
219
- const hex = s.replace(/-/g, '');
220
- if (hex.length !== 32) throw new Error('Invalid hex UUID');
221
-
222
- let v = 0n;
223
- for (let i = 0; i < 32; i += 2) {
224
- v = (v << 8n) | BigInt(parseInt(hex.slice(i, i + 2), 16));
225
- }
226
- return new Uuid(v);
227
- }
228
-
229
- /** Convert to string (hyphenated form). */
230
- toString(): string {
231
- const bytes = Uuid.bigIntToBytes(this.__uuid__);
232
- const hex = [...bytes].map(b => b.toString(16).padStart(2, '0')).join('');
233
-
234
- // Format as 8-4-4-4-12
235
- return (
236
- hex.slice(0, 8) +
237
- '-' +
238
- hex.slice(8, 12) +
239
- '-' +
240
- hex.slice(12, 16) +
241
- '-' +
242
- hex.slice(16, 20) +
243
- '-' +
244
- hex.slice(20)
245
- );
246
- }
247
-
248
- /** Convert to bigint (u128). */
249
- asBigInt(): bigint {
250
- return this.__uuid__;
251
- }
252
-
253
- /** Return a `Uint8Array` of 16 bytes. */
254
- toBytes(): Uint8Array {
255
- return Uuid.bigIntToBytes(this.__uuid__);
256
- }
257
-
258
- private static bytesToBigInt(bytes: Uint8Array): bigint {
259
- let result = 0n;
260
- for (const b of bytes) result = (result << 8n) | BigInt(b);
261
- return result;
262
- }
263
-
264
- private static bigIntToBytes(value: bigint): Uint8Array {
265
- const bytes = new Uint8Array(16);
266
- for (let i = 15; i >= 0; i--) {
267
- bytes[i] = Number(value & 0xffn);
268
- value >>= 8n;
269
- }
270
- return bytes;
271
- }
272
-
273
- /**
274
- * Returns the version of this UUID.
275
- *
276
- * This represents the algorithm used to generate the value.
277
- *
278
- * @returns A `UuidVersion`
279
- * @throws {Error} If the version field is not recognized
280
- */
281
- getVersion(): UuidVersion {
282
- const version = (this.toBytes()[6] >> 4) & 0x0f;
283
-
284
- switch (version) {
285
- case 4:
286
- return 'V4';
287
- case 7:
288
- return 'V7';
289
- default:
290
- if (this == Uuid.NIL) {
291
- return 'Nil';
292
- }
293
- if (this == Uuid.MAX) {
294
- return 'Max';
295
- }
296
- throw new Error(`Unsupported UUID version: ${version}`);
297
- }
298
- }
299
-
300
- /**
301
- * Extract the monotonic counter from a UUIDv7.
302
- *
303
- * Intended for testing and diagnostics.
304
- * Behavior is undefined if called on a non-V7 UUID.
305
- *
306
- * @returns 31-bit counter value
307
- */
308
- getCounter(): number {
309
- const bytes = this.toBytes(); // big-endian, 16 bytes
310
-
311
- const high = bytes[7]; // bits 30..23
312
- const mid1 = bytes[9]; // bits 22..15
313
- const mid2 = bytes[10]; // bits 14..7
314
- const low = bytes[11] >>> 1; // bits 6..0
315
-
316
- // reconstruct 31-bit counter
317
- return (high << 23) | (mid1 << 15) | (mid2 << 7) | low | 0; // force 32-bit int
318
- }
319
-
320
- compareTo(other: Uuid): number {
321
- if (this.__uuid__ < other.__uuid__) return -1;
322
- if (this.__uuid__ > other.__uuid__) return 1;
323
-
324
- return 0;
325
- }
326
-
327
- static getAlgebraicType(): UuidAlgebraicType {
328
- return AlgebraicType.Product({
329
- elements: [
330
- {
331
- name: '__uuid__',
332
- algebraicType: AlgebraicType.U128,
333
- },
334
- ],
335
- });
336
- }
337
- }
1
+ import { Timestamp } from './timestamp';
2
+ import { AlgebraicType } from './algebraic_type.ts';
3
+
4
+ export type UuidAlgebraicType = {
5
+ tag: 'Product';
6
+ value: {
7
+ elements: [
8
+ {
9
+ name: '__uuid__';
10
+ algebraicType: { tag: 'U128' };
11
+ },
12
+ ];
13
+ };
14
+ };
15
+
16
+ /**
17
+ * Supported UUID versions.
18
+ *
19
+ * - `Nil` – The "Nil" UUID (all zeros)
20
+ * - `V4` – Version 4: random
21
+ * - `V7` – Version 7: timestamp + counter + random
22
+ * - `Max` – The "Max" UUID (all ones)
23
+ */
24
+ type UuidVersion = 'Nil' | 'V4' | 'V7' | 'Max';
25
+
26
+ /**
27
+ * A universally unique identifier (UUID).
28
+ *
29
+ * Supports UUID `Nil`, `Max`, `V4` (random), and `V7`
30
+ * (timestamp + counter + random).
31
+ *
32
+ * Internally represented as an unsigned 128-bit between 0 and `MAX_UUID_BIGINT`.
33
+ */
34
+ export class Uuid {
35
+ __uuid__: bigint;
36
+
37
+ /**
38
+ * The nil UUID (all zeros).
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * const uuid = Uuid.NIL;
43
+ * console.assert(
44
+ * uuid.toString() === "00000000-0000-0000-0000-000000000000"
45
+ * );
46
+ * ```
47
+ */
48
+ static readonly NIL = new Uuid(0n);
49
+ static readonly MAX_UUID_BIGINT = 0xffffffffffffffffffffffffffffffffn;
50
+ /**
51
+ * The max UUID (all ones).
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * const uuid = Uuid.MAX;
56
+ * console.assert(
57
+ * uuid.toString() === "ffffffff-ffff-ffff-ffff-ffffffffffff"
58
+ * );
59
+ * ```
60
+ */
61
+ static readonly MAX = new Uuid(Uuid.MAX_UUID_BIGINT);
62
+
63
+ /**
64
+ * Create a UUID from a raw 128-bit value.
65
+ *
66
+ * @param u - Unsigned 128-bit integer
67
+ * @throws {Error} If the value is outside the valid UUID range
68
+ */
69
+ constructor(u: bigint) {
70
+ // Must fit in exactly 16 bytes
71
+ if (u < 0n || u > Uuid.MAX_UUID_BIGINT) {
72
+ throw new Error('Invalid UUID: must be between 0 and `MAX_UUID_BIGINT`');
73
+ }
74
+ this.__uuid__ = u;
75
+ }
76
+
77
+ /**
78
+ * Create a UUID `v4` from explicit random bytes.
79
+ *
80
+ * This method assumes the bytes are already sufficiently random.
81
+ * It only sets the appropriate bits for the UUID version and variant.
82
+ *
83
+ * @param bytes - Exactly 16 random bytes
84
+ * @returns A UUID `v4`
85
+ * @throws {Error} If `bytes.length !== 16`
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * const randomBytes = new Uint8Array(16);
90
+ * const uuid = Uuid.fromRandomBytesV4(randomBytes);
91
+ *
92
+ * console.assert(
93
+ * uuid.toString() === "00000000-0000-4000-8000-000000000000"
94
+ * );
95
+ * ```
96
+ */
97
+ static fromRandomBytesV4(bytes: Uint8Array): Uuid {
98
+ if (bytes.length !== 16) throw new Error('UUID v4 requires 16 bytes');
99
+ const arr = new Uint8Array(bytes);
100
+ arr[6] = (arr[6] & 0x0f) | 0x40; // version 4
101
+ arr[8] = (arr[8] & 0x3f) | 0x80; // variant
102
+ return new Uuid(Uuid.bytesToBigInt(arr));
103
+ }
104
+
105
+ /**
106
+ * Generate a UUID `v7` using a monotonic counter from `0` to `2^31 - 1`,
107
+ * a timestamp, and 4 random bytes.
108
+ *
109
+ * The counter wraps around on overflow.
110
+ *
111
+ * The UUID `v7` is structured as follows:
112
+ *
113
+ * ```ascii
114
+ * ┌───────────────────────────────────────────────┬───────────────────┐
115
+ * | B0 | B1 | B2 | B3 | B4 | B5 | B6 |
116
+ * ├───────────────────────────────────────────────┼───────────────────┤
117
+ * | unix_ts_ms | version 7 |
118
+ * └───────────────────────────────────────────────┴───────────────────┘
119
+ * ┌──────────────┬─────────┬──────────────────┬───────────────────────┐
120
+ * | B7 | B8 | B9 | B10 | B11 | B12 | B13 | B14 | B15 |
121
+ * ├──────────────┼─────────┼──────────────────┼───────────────────────┤
122
+ * | counter_high | variant | counter_low | random |
123
+ * └──────────────┴─────────┴──────────────────┴───────────────────────┘
124
+ * ```
125
+ *
126
+ * @param counter - Mutable monotonic counter (31-bit)
127
+ * @param now - Timestamp since the Unix epoch
128
+ * @param randomBytes - Exactly 4 random bytes
129
+ * @returns A UUID `v7`
130
+ *
131
+ * @throws {Error} If the `counter` is negative
132
+ * @throws {Error} If the `timestamp` is before the Unix epoch
133
+ * @throws {Error} If `randomBytes.length !== 4`
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * const now = Timestamp.fromMillis(1_686_000_000_000n);
138
+ * const counter = { value: 1 };
139
+ * const randomBytes = new Uint8Array(4);
140
+ *
141
+ * const uuid = Uuid.fromCounterV7(counter, now, randomBytes);
142
+ *
143
+ * console.assert(
144
+ * uuid.toString() === "0000647e-5180-7000-8000-000200000000"
145
+ * );
146
+ * ```
147
+ */
148
+ static fromCounterV7(
149
+ counter: { value: number },
150
+ now: Timestamp,
151
+ randomBytes: Uint8Array
152
+ ): Uuid {
153
+ if (randomBytes.length !== 4) {
154
+ throw new Error('`fromCounterV7` requires `randomBytes.length == 4`');
155
+ }
156
+
157
+ if (counter.value < 0) {
158
+ throw new Error('`fromCounterV7` uuid `counter` must be non-negative');
159
+ }
160
+
161
+ if (now.__timestamp_micros_since_unix_epoch__ < 0) {
162
+ throw new Error('`fromCounterV7` `timestamp` before unix epoch');
163
+ }
164
+
165
+ // 31-bit monotonic counter with wraparound
166
+ const counterVal = counter.value;
167
+ counter.value = (counterVal + 1) & 0x7fff_ffff;
168
+
169
+ // 48-bit unix timestamp (ms)
170
+ const tsMs = now.toMillis() & 0xffff_ffff_ffffn;
171
+
172
+ const bytes = new Uint8Array(16);
173
+
174
+ // unix_ts_ms (48 bits)
175
+ bytes[0] = Number((tsMs >> 40n) & 0xffn);
176
+ bytes[1] = Number((tsMs >> 32n) & 0xffn);
177
+ bytes[2] = Number((tsMs >> 24n) & 0xffn);
178
+ bytes[3] = Number((tsMs >> 16n) & 0xffn);
179
+ bytes[4] = Number((tsMs >> 8n) & 0xffn);
180
+ bytes[5] = Number(tsMs & 0xffn);
181
+
182
+ // Counter bits (31 bits total)
183
+ bytes[7] = (counterVal >>> 23) & 0xff;
184
+ bytes[9] = (counterVal >>> 15) & 0xff;
185
+ bytes[10] = (counterVal >>> 7) & 0xff;
186
+ bytes[11] = ((counterVal & 0x7f) << 1) & 0xff;
187
+
188
+ // Random bytes
189
+ bytes[12] |= randomBytes[0] & 0x7f;
190
+ bytes[13] = randomBytes[1];
191
+ bytes[14] = randomBytes[2];
192
+ bytes[15] = randomBytes[3];
193
+
194
+ // Version 7
195
+ bytes[6] = (bytes[6] & 0x0f) | 0x70;
196
+
197
+ // Variant RFC4122
198
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
199
+
200
+ return new Uuid(Uuid.bytesToBigInt(bytes));
201
+ }
202
+
203
+ /**
204
+ * Parse a UUID from a string representation.
205
+ *
206
+ * @param s - UUID string
207
+ * @returns Parsed UUID
208
+ * @throws {Error} If the string is not a valid UUID
209
+ *
210
+ * @example
211
+ * ```ts
212
+ * const s = "01888d6e-5c00-7000-8000-000000000000";
213
+ * const uuid = Uuid.parse(s);
214
+ *
215
+ * console.assert(uuid.toString() === s);
216
+ * ```
217
+ */
218
+ static parse(s: string): Uuid {
219
+ const hex = s.replace(/-/g, '');
220
+ if (hex.length !== 32) throw new Error('Invalid hex UUID');
221
+
222
+ let v = 0n;
223
+ for (let i = 0; i < 32; i += 2) {
224
+ v = (v << 8n) | BigInt(parseInt(hex.slice(i, i + 2), 16));
225
+ }
226
+ return new Uuid(v);
227
+ }
228
+
229
+ /** Convert to string (hyphenated form). */
230
+ toString(): string {
231
+ const bytes = Uuid.bigIntToBytes(this.__uuid__);
232
+ const hex = [...bytes].map(b => b.toString(16).padStart(2, '0')).join('');
233
+
234
+ // Format as 8-4-4-4-12
235
+ return (
236
+ hex.slice(0, 8) +
237
+ '-' +
238
+ hex.slice(8, 12) +
239
+ '-' +
240
+ hex.slice(12, 16) +
241
+ '-' +
242
+ hex.slice(16, 20) +
243
+ '-' +
244
+ hex.slice(20)
245
+ );
246
+ }
247
+
248
+ /** Convert to bigint (u128). */
249
+ asBigInt(): bigint {
250
+ return this.__uuid__;
251
+ }
252
+
253
+ /** Return a `Uint8Array` of 16 bytes. */
254
+ toBytes(): Uint8Array {
255
+ return Uuid.bigIntToBytes(this.__uuid__);
256
+ }
257
+
258
+ private static bytesToBigInt(bytes: Uint8Array): bigint {
259
+ let result = 0n;
260
+ for (const b of bytes) result = (result << 8n) | BigInt(b);
261
+ return result;
262
+ }
263
+
264
+ private static bigIntToBytes(value: bigint): Uint8Array {
265
+ const bytes = new Uint8Array(16);
266
+ for (let i = 15; i >= 0; i--) {
267
+ bytes[i] = Number(value & 0xffn);
268
+ value >>= 8n;
269
+ }
270
+ return bytes;
271
+ }
272
+
273
+ /**
274
+ * Returns the version of this UUID.
275
+ *
276
+ * This represents the algorithm used to generate the value.
277
+ *
278
+ * @returns A `UuidVersion`
279
+ * @throws {Error} If the version field is not recognized
280
+ */
281
+ getVersion(): UuidVersion {
282
+ const version = (this.toBytes()[6] >> 4) & 0x0f;
283
+
284
+ switch (version) {
285
+ case 4:
286
+ return 'V4';
287
+ case 7:
288
+ return 'V7';
289
+ default:
290
+ if (this == Uuid.NIL) {
291
+ return 'Nil';
292
+ }
293
+ if (this == Uuid.MAX) {
294
+ return 'Max';
295
+ }
296
+ throw new Error(`Unsupported UUID version: ${version}`);
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Extract the monotonic counter from a UUIDv7.
302
+ *
303
+ * Intended for testing and diagnostics.
304
+ * Behavior is undefined if called on a non-V7 UUID.
305
+ *
306
+ * @returns 31-bit counter value
307
+ */
308
+ getCounter(): number {
309
+ const bytes = this.toBytes(); // big-endian, 16 bytes
310
+
311
+ const high = bytes[7]; // bits 30..23
312
+ const mid1 = bytes[9]; // bits 22..15
313
+ const mid2 = bytes[10]; // bits 14..7
314
+ const low = bytes[11] >>> 1; // bits 6..0
315
+
316
+ // reconstruct 31-bit counter
317
+ return (high << 23) | (mid1 << 15) | (mid2 << 7) | low | 0; // force 32-bit int
318
+ }
319
+
320
+ compareTo(other: Uuid): number {
321
+ if (this.__uuid__ < other.__uuid__) return -1;
322
+ if (this.__uuid__ > other.__uuid__) return 1;
323
+
324
+ return 0;
325
+ }
326
+
327
+ static getAlgebraicType(): UuidAlgebraicType {
328
+ return AlgebraicType.Product({
329
+ elements: [
330
+ {
331
+ name: '__uuid__',
332
+ algebraicType: AlgebraicType.U128,
333
+ },
334
+ ],
335
+ });
336
+ }
337
+ }