@hamur/db 0.0.0-stage → 0.0.2

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 (125) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +38 -2
  3. package/dist/chunks/browser-bun-sql-2yeva2qv.js +53 -0
  4. package/dist/chunks/browser-bun-sqlite-xxptm4db.js +72 -0
  5. package/dist/chunks/browser-client-ehmpv0kf.js +130 -0
  6. package/dist/chunks/browser-d1-a16d23f0.js +8 -0
  7. package/dist/chunks/browser-index-3t2ajr9m.js +510 -0
  8. package/dist/chunks/browser-index-kf697bfy.js +113 -0
  9. package/dist/chunks/browser-index-ppkx8k0t.js +28 -0
  10. package/dist/chunks/bun-bun-sql-vaz9ggc8.js +54 -0
  11. package/dist/chunks/bun-bun-sqlite-qcd011rm.js +73 -0
  12. package/dist/chunks/bun-client-cnt1ddnf.js +131 -0
  13. package/dist/chunks/bun-d1-d36z1pyr.js +9 -0
  14. package/dist/chunks/bun-index-06tj00dn.js +11 -0
  15. package/dist/chunks/bun-index-9na2zkqq.js +224 -0
  16. package/dist/chunks/bun-index-b47nngck.js +352 -0
  17. package/dist/chunks/bun-index-hrx1eqma.js +29 -0
  18. package/dist/chunks/bun-index-pd6k99dv.js +114 -0
  19. package/dist/src/cli.js +1692 -0
  20. package/dist/src/devtools.js +153 -0
  21. package/dist/src/index.js +1491 -0
  22. package/dist/src/server/index.js +584 -0
  23. package/dist/src/storage/define.js +7 -0
  24. package/dist/types/src/build/connections.d.ts +8 -0
  25. package/dist/types/src/build/databases.d.ts +20 -0
  26. package/dist/types/src/build/factories.d.ts +6 -0
  27. package/dist/types/src/build/migrations.d.ts +21 -0
  28. package/dist/types/src/build/queue.d.ts +7 -0
  29. package/dist/types/src/build/schema.d.ts +50 -0
  30. package/dist/types/src/build/tables.d.ts +7 -0
  31. package/dist/types/src/build/types.d.ts +4 -0
  32. package/dist/types/src/cli.d.ts +26 -0
  33. package/dist/types/src/connectors/bun-sql.d.ts +3 -0
  34. package/dist/types/src/connectors/bun-sqlite.d.ts +3 -0
  35. package/dist/types/src/connectors/client-fakes.d.ts +57 -0
  36. package/dist/types/src/connectors/client.d.ts +3 -0
  37. package/dist/types/src/connectors/d1-fake.d.ts +32 -0
  38. package/dist/types/src/connectors/d1.d.ts +26 -0
  39. package/dist/types/src/connectors/node-sqlite.d.ts +3 -0
  40. package/dist/types/src/connectors/node-test.d.ts +17 -0
  41. package/dist/types/src/connectors/suite.d.ts +13 -0
  42. package/dist/types/src/devtools.d.ts +6 -0
  43. package/dist/types/src/index.d.ts +25 -0
  44. package/dist/types/src/module.d.ts +6 -0
  45. package/dist/types/src/options.d.ts +9 -0
  46. package/dist/types/src/runtime/connector.d.ts +53 -0
  47. package/dist/types/src/runtime/database.d.ts +15 -0
  48. package/dist/types/src/runtime/migrate.d.ts +56 -0
  49. package/dist/types/src/runtime/query.d.ts +12 -0
  50. package/dist/types/src/runtime/queue-process.d.ts +1 -0
  51. package/dist/types/src/runtime/queue.d.ts +85 -0
  52. package/dist/types/src/runtime/registry.d.ts +16 -0
  53. package/dist/types/src/server/client.d.ts +3 -0
  54. package/dist/types/src/server/databases.d.ts +4 -0
  55. package/dist/types/src/server/define-factory.d.ts +9 -0
  56. package/dist/types/src/server/devtools-routes.d.ts +4 -0
  57. package/dist/types/src/server/devtools.d.ts +26 -0
  58. package/dist/types/src/server/door-dev.d.ts +3 -0
  59. package/dist/types/src/server/door.d.ts +2 -0
  60. package/dist/types/src/server/factory-core.d.ts +12 -0
  61. package/dist/types/src/server/factory.d.ts +6 -0
  62. package/dist/types/src/server/fake.d.ts +35 -0
  63. package/dist/types/src/server/index.d.ts +12 -0
  64. package/dist/types/src/server/migrations.d.ts +5 -0
  65. package/dist/types/src/server/page.d.ts +26 -0
  66. package/dist/types/src/server/plugin.d.ts +1 -0
  67. package/dist/types/src/server/queue.d.ts +6 -0
  68. package/dist/types/src/server/table-entities.d.ts +33 -0
  69. package/dist/types/src/server/task.d.ts +6 -0
  70. package/dist/types/src/storage/define.d.ts +12 -0
  71. package/dist/types/src/storage/driver.d.ts +36 -0
  72. package/dist/types/src/storage/index.d.ts +3 -0
  73. package/dist/types/src/types.d.ts +103 -0
  74. package/package.json +55 -4
  75. package/src/build/connections.ts +225 -0
  76. package/src/build/databases.ts +101 -0
  77. package/src/build/factories.ts +135 -0
  78. package/src/build/migrations.ts +247 -0
  79. package/src/build/queue.ts +29 -0
  80. package/src/build/schema.ts +636 -0
  81. package/src/build/tables.ts +20 -0
  82. package/src/build/types.ts +46 -0
  83. package/src/cli.ts +153 -0
  84. package/src/connectors/bun-sql.ts +68 -0
  85. package/src/connectors/bun-sqlite.ts +69 -0
  86. package/src/connectors/client-fakes.ts +257 -0
  87. package/src/connectors/client.ts +161 -0
  88. package/src/connectors/d1-fake.ts +92 -0
  89. package/src/connectors/d1.ts +151 -0
  90. package/src/connectors/node-sqlite.ts +83 -0
  91. package/src/connectors/node-test.ts +31 -0
  92. package/src/connectors/suite.ts +406 -0
  93. package/src/devtools.ts +264 -0
  94. package/src/env.d.ts +28 -0
  95. package/src/index.ts +46 -0
  96. package/src/module.ts +36 -0
  97. package/src/options.ts +104 -0
  98. package/src/runtime/connector.ts +87 -0
  99. package/src/runtime/database.ts +353 -0
  100. package/src/runtime/migrate.ts +307 -0
  101. package/src/runtime/query.ts +82 -0
  102. package/src/runtime/queue-process.ts +39 -0
  103. package/src/runtime/queue.ts +380 -0
  104. package/src/runtime/registry.ts +61 -0
  105. package/src/server/client.ts +6 -0
  106. package/src/server/databases.ts +24 -0
  107. package/src/server/define-factory.ts +22 -0
  108. package/src/server/devtools-routes.ts +34 -0
  109. package/src/server/devtools.ts +205 -0
  110. package/src/server/door-dev.ts +6 -0
  111. package/src/server/door.ts +4 -0
  112. package/src/server/factory-core.ts +91 -0
  113. package/src/server/factory.ts +19 -0
  114. package/src/server/fake.ts +348 -0
  115. package/src/server/index.ts +17 -0
  116. package/src/server/migrations.ts +26 -0
  117. package/src/server/page.ts +181 -0
  118. package/src/server/plugin.ts +14 -0
  119. package/src/server/queue.ts +38 -0
  120. package/src/server/table-entities.ts +29 -0
  121. package/src/server/task.ts +15 -0
  122. package/src/storage/define.ts +12 -0
  123. package/src/storage/driver.ts +419 -0
  124. package/src/storage/index.ts +7 -0
  125. package/src/types.ts +101 -0
@@ -0,0 +1,584 @@
1
+ // @bun
2
+ import {
3
+ createDatabases
4
+ } from "../../chunks/bun-index-b47nngck.js";
5
+
6
+ // packages/db/src/server/databases.ts
7
+ import { clients, connections, connectors } from "#hamur/db/connections";
8
+ import { envValue } from "hamur/server/internal";
9
+ var handed = import.meta.prerender ? globalThis.__HAMUR_DB_PRERENDER__ : undefined;
10
+ var active = { ...connections, ...handed?.connections };
11
+ var databases = createDatabases(active, { ...connectors, ...handed?.loaders }, envValue, {
12
+ ...clients,
13
+ ...handed?.clients
14
+ });
15
+
16
+ // packages/db/src/server/client.ts
17
+ function defineDatabaseClient(factory) {
18
+ return factory;
19
+ }
20
+ // packages/db/src/server/page.ts
21
+ import { createError } from "hamur/server";
22
+ import { createSqlFragment, fromBase64Url, toBase64Url } from "hamur/server/internal";
23
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/;
24
+ function columnsOf(orderBy) {
25
+ if (orderBy.length === 0)
26
+ throw new TypeError("cursorQuery orderBy needs at least one column");
27
+ return orderBy.map(([column, direction]) => {
28
+ if (typeof column !== "string" || !IDENTIFIER.test(column))
29
+ throw new TypeError(`cursorQuery orderBy column ${JSON.stringify(column)} is not an identifier`);
30
+ if (direction !== "asc" && direction !== "desc")
31
+ throw new TypeError(`cursorQuery orderBy direction of "${column}" must be "asc" or "desc"`);
32
+ const segments = column.split(".");
33
+ return { segments, name: segments[segments.length - 1], direction };
34
+ });
35
+ }
36
+ var quote = (dialect, segments) => segments.map((segment) => dialect === "mysql" ? `\`${segment}\`` : `"${segment}"`).join(".");
37
+ function badCursor() {
38
+ return createError({
39
+ status: 400,
40
+ message: "Validation failed",
41
+ data: { issues: [{ in: "query", path: ["cursor"], message: "cursor must be a cursor this API returned" }] }
42
+ });
43
+ }
44
+ function decode(cursor, length) {
45
+ let key;
46
+ try {
47
+ const bytes = fromBase64Url(cursor);
48
+ if (!bytes)
49
+ throw badCursor();
50
+ key = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
51
+ } catch {
52
+ throw badCursor();
53
+ }
54
+ if (!Array.isArray(key) || key.length !== length)
55
+ throw badCursor();
56
+ return key.map((value) => {
57
+ if (value === null || typeof value === "string" || typeof value === "boolean")
58
+ return value;
59
+ if (typeof value === "number" && Number.isFinite(value))
60
+ return value;
61
+ if (isBigintTag(value))
62
+ return BigInt(value.bigint);
63
+ throw badCursor();
64
+ });
65
+ }
66
+ function isBigintTag(value) {
67
+ if (typeof value !== "object" || value === null || Array.isArray(value))
68
+ return false;
69
+ const keys = Object.keys(value);
70
+ const text = value.bigint;
71
+ return keys.length === 1 && keys[0] === "bigint" && typeof text === "string" && /^-?\d{1,40}$/.test(text);
72
+ }
73
+ function keyValue(column, value) {
74
+ if (value === null)
75
+ return null;
76
+ if (value instanceof Date)
77
+ throw new TypeError(`cursorQuery: "${column}" is a Date, which keeps milliseconds only; end orderBy with a unique column and select the timestamp as text, or order by a column that is not a timestamp`);
78
+ if (typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value))
79
+ return value;
80
+ if (typeof value === "bigint")
81
+ return value;
82
+ throw new TypeError(`cursorQuery: the value of "${column}" cannot be put in a cursor`);
83
+ }
84
+ function keyOf(columns, row) {
85
+ return columns.map(({ name }) => {
86
+ if (!(name in row) || row[name] === undefined)
87
+ throw new TypeError(`cursorQuery: the row has no "${name}"; select every orderBy column`);
88
+ return keyValue(name, row[name]);
89
+ });
90
+ }
91
+ function keyset(columns, key, dialect, firstIndex) {
92
+ const values = [];
93
+ const bind = (value) => {
94
+ values.push(value);
95
+ return dialect === "postgres" ? `$${firstIndex + values.length - 1}` : "?";
96
+ };
97
+ const nullsLow = dialect !== "postgres";
98
+ const equal = (name, value) => value === null ? `${name} IS NULL` : `${name} = ${bind(value)}`;
99
+ const after = (name, direction, value) => {
100
+ const ascending = direction === "asc";
101
+ if (value === null)
102
+ return ascending === nullsLow ? `${name} IS NOT NULL` : "1 = 0";
103
+ const comparison = `${name} ${ascending ? ">" : "<"} ${bind(value)}`;
104
+ return ascending !== nullsLow ? `(${comparison} OR ${name} IS NULL)` : comparison;
105
+ };
106
+ const terms = columns.map((column, index) => {
107
+ const parts = columns.slice(0, index).map((earlier, at) => equal(quote(dialect, earlier.segments), key[at]));
108
+ parts.push(after(quote(dialect, column.segments), column.direction, key[index]));
109
+ return parts.length === 1 && parts[0].startsWith("(") ? parts[0] : `(${parts.join(" AND ")})`;
110
+ });
111
+ return { text: `(${terms.join(" OR ")})`, values };
112
+ }
113
+ var show = (value) => typeof value === "bigint" ? value.toString() : JSON.stringify(value);
114
+ function warnTies(rows, columns) {
115
+ let previous;
116
+ for (const row of rows) {
117
+ const key = keyOf(columns, row);
118
+ const text = key.map(show).join(", ");
119
+ if (text === previous) {
120
+ console.warn(`cursorQuery: two rows share the key [${text}]; end orderBy with a unique column`);
121
+ return;
122
+ }
123
+ previous = text;
124
+ }
125
+ }
126
+ function cursorQuery(input, options) {
127
+ const columns = columnsOf(options.orderBy);
128
+ if (!Number.isSafeInteger(input.limit) || input.limit < 1)
129
+ throw new TypeError("cursorQuery limit must be an integer from 1");
130
+ const key = input.cursor === undefined ? undefined : decode(input.cursor, columns.length);
131
+ return {
132
+ where: createSqlFragment((dialect, firstIndex) => key ? keyset(columns, key, dialect, firstIndex) : { text: "(1 = 1)", values: [] }),
133
+ orderBy: createSqlFragment((dialect) => ({
134
+ text: columns.map((column) => `${quote(dialect, column.segments)} ${column.direction === "asc" ? "ASC" : "DESC"}`).join(", "),
135
+ values: []
136
+ })),
137
+ limit: input.limit + 1,
138
+ page(rows) {
139
+ if (import.meta.dev)
140
+ warnTies(rows, columns);
141
+ if (rows.length <= input.limit)
142
+ return { items: rows, nextCursor: null };
143
+ const items = rows.slice(0, input.limit);
144
+ const last = items[items.length - 1];
145
+ const encoded = toBase64Url(new TextEncoder().encode(JSON.stringify(keyOf(columns, last), (_name, value) => typeof value === "bigint" ? { bigint: value.toString() } : value)));
146
+ return { items, nextCursor: encoded };
147
+ }
148
+ };
149
+ }
150
+ function offsetQuery(input) {
151
+ if (!Number.isSafeInteger(input.page) || input.page < 1)
152
+ throw new TypeError("offsetQuery page must be an integer from 1");
153
+ if (!Number.isSafeInteger(input.perPage) || input.perPage < 1)
154
+ throw new TypeError("offsetQuery perPage must be an integer from 1");
155
+ return {
156
+ limit: input.perPage,
157
+ offset: (input.page - 1) * input.perPage,
158
+ page: (rows, total) => ({
159
+ items: rows,
160
+ page: input.page,
161
+ perPage: input.perPage,
162
+ total,
163
+ pages: Math.ceil(total / input.perPage)
164
+ })
165
+ };
166
+ }
167
+ // packages/db/src/server/table-entities.ts
168
+ import { createTableSource } from "hamur/server/internal";
169
+ function tableEntities(options) {
170
+ return createTableSource(options, () => databases.use(options.connection));
171
+ }
172
+ // packages/db/src/server/define-factory.ts
173
+ var defined = new WeakSet;
174
+ function defineFactory(make) {
175
+ if (typeof make !== "function")
176
+ throw new TypeError("defineFactory takes a function (n, fake) => row");
177
+ const factory = Object.freeze({ make });
178
+ defined.add(factory);
179
+ return factory;
180
+ }
181
+ var isFactory = (value) => typeof value === "object" && value !== null && defined.has(value);
182
+ // packages/db/src/server/factory.ts
183
+ import { factories } from "#hamur/db/factories";
184
+
185
+ // packages/db/src/server/fake.ts
186
+ var FIRST_NAMES = [
187
+ "Ada",
188
+ "Alan",
189
+ "Amara",
190
+ "Anders",
191
+ "Beatriz",
192
+ "Bruno",
193
+ "Carla",
194
+ "Chidi",
195
+ "Dara",
196
+ "Diego",
197
+ "Elif",
198
+ "Emil",
199
+ "Farah",
200
+ "Felix",
201
+ "Greta",
202
+ "Hana",
203
+ "Hugo",
204
+ "Ines",
205
+ "Ivan",
206
+ "Jana",
207
+ "Jonas",
208
+ "Kai",
209
+ "Leila",
210
+ "Liam",
211
+ "Maya",
212
+ "Mateo",
213
+ "Nadia",
214
+ "Noah",
215
+ "Olga",
216
+ "Omar",
217
+ "Priya",
218
+ "Quinn",
219
+ "Rosa",
220
+ "Ravi",
221
+ "Sara",
222
+ "Sven",
223
+ "Tara",
224
+ "Theo",
225
+ "Uma",
226
+ "Viktor",
227
+ "Wren",
228
+ "Xavier",
229
+ "Yara",
230
+ "Yusuf",
231
+ "Zoe",
232
+ "Zane",
233
+ "Mira",
234
+ "Luca",
235
+ "Nina",
236
+ "Oscar"
237
+ ];
238
+ var LAST_NAMES = [
239
+ "Almeida",
240
+ "Andersen",
241
+ "Bauer",
242
+ "Bianchi",
243
+ "Castillo",
244
+ "Chen",
245
+ "Dubois",
246
+ "Eriksen",
247
+ "Fischer",
248
+ "Garcia",
249
+ "Haddad",
250
+ "Ivanov",
251
+ "Jensen",
252
+ "Kaya",
253
+ "Kowalski",
254
+ "Larsen",
255
+ "Lopez",
256
+ "Moreau",
257
+ "Nakamura",
258
+ "Novak",
259
+ "Okafor",
260
+ "Petrov",
261
+ "Quist",
262
+ "Rossi",
263
+ "Santos",
264
+ "Silva",
265
+ "Tanaka",
266
+ "Ulrich",
267
+ "Varga",
268
+ "Weber",
269
+ "Yilmaz",
270
+ "Zhang",
271
+ "Brandt",
272
+ "Costa",
273
+ "Demir",
274
+ "Evans",
275
+ "Foster",
276
+ "Grant",
277
+ "Hughes",
278
+ "Iqbal",
279
+ "Jones",
280
+ "Keller",
281
+ "Lindgren",
282
+ "Mendes",
283
+ "Nolan",
284
+ "Ortega",
285
+ "Patel",
286
+ "Reyes",
287
+ "Singh",
288
+ "Walker"
289
+ ];
290
+ var WORDS = [
291
+ "able",
292
+ "acorn",
293
+ "amber",
294
+ "anchor",
295
+ "apple",
296
+ "arrow",
297
+ "autumn",
298
+ "badge",
299
+ "basket",
300
+ "beacon",
301
+ "bridge",
302
+ "bright",
303
+ "brook",
304
+ "candle",
305
+ "canvas",
306
+ "cedar",
307
+ "cherry",
308
+ "cliff",
309
+ "cloud",
310
+ "clover",
311
+ "copper",
312
+ "coral",
313
+ "crystal",
314
+ "dawn",
315
+ "delta",
316
+ "desert",
317
+ "dove",
318
+ "dream",
319
+ "eagle",
320
+ "ember",
321
+ "falcon",
322
+ "feather",
323
+ "field",
324
+ "flint",
325
+ "forest",
326
+ "fox",
327
+ "garden",
328
+ "glacier",
329
+ "granite",
330
+ "harbor",
331
+ "hazel",
332
+ "hill",
333
+ "horizon",
334
+ "island",
335
+ "ivory",
336
+ "jade",
337
+ "jasmine",
338
+ "juniper",
339
+ "kettle",
340
+ "lake",
341
+ "lantern",
342
+ "lemon",
343
+ "lily",
344
+ "maple",
345
+ "meadow",
346
+ "mist",
347
+ "moon",
348
+ "morning",
349
+ "moss",
350
+ "mountain",
351
+ "needle",
352
+ "north",
353
+ "oak",
354
+ "ocean",
355
+ "olive",
356
+ "orchard",
357
+ "paper",
358
+ "pearl",
359
+ "pebble",
360
+ "pine",
361
+ "planet",
362
+ "pond",
363
+ "prairie",
364
+ "quartz",
365
+ "rain",
366
+ "raven",
367
+ "reef",
368
+ "ridge",
369
+ "river",
370
+ "robin",
371
+ "saffron",
372
+ "sage",
373
+ "sand",
374
+ "silver",
375
+ "sky",
376
+ "slate",
377
+ "snow",
378
+ "spark",
379
+ "spring",
380
+ "stone",
381
+ "storm",
382
+ "summer",
383
+ "sun",
384
+ "thistle",
385
+ "thunder",
386
+ "tide",
387
+ "timber",
388
+ "tulip",
389
+ "valley",
390
+ "velvet",
391
+ "violet",
392
+ "water",
393
+ "willow",
394
+ "wind",
395
+ "winter",
396
+ "wolf",
397
+ "yarrow",
398
+ "zephyr",
399
+ "quiet",
400
+ "swift"
401
+ ];
402
+ var rotl = (value, shift) => (value << shift | value >>> 32 - shift) >>> 0;
403
+ function xoshiro(seed) {
404
+ let mix = seed >>> 0;
405
+ const split = () => {
406
+ mix = mix + 2654435769 >>> 0;
407
+ let z = mix;
408
+ z = Math.imul(z ^ z >>> 16, 2246822507);
409
+ z = Math.imul(z ^ z >>> 13, 3266489909);
410
+ return (z ^ z >>> 16) >>> 0;
411
+ };
412
+ const state = new Uint32Array([split(), split(), split(), split()]);
413
+ return () => {
414
+ const result = Math.imul(rotl(Math.imul(state[1], 5), 7), 9) >>> 0;
415
+ const shifted = state[1] << 9;
416
+ state[2] ^= state[0];
417
+ state[3] ^= state[1];
418
+ state[1] ^= state[2];
419
+ state[0] ^= state[3];
420
+ state[2] ^= shifted;
421
+ state[3] = rotl(state[3], 11);
422
+ return result;
423
+ };
424
+ }
425
+ function instant(name, value) {
426
+ const time = value instanceof Date ? value.getTime() : new Date(value).getTime();
427
+ if (Number.isNaN(time))
428
+ throw new TypeError(`fake.date ${name} is not a date`);
429
+ return time;
430
+ }
431
+ var capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
432
+ function createFake(seed) {
433
+ const next = xoshiro(seed);
434
+ const unit = () => next() / 4294967296;
435
+ const int = (min, max) => {
436
+ if (!Number.isSafeInteger(min) || !Number.isSafeInteger(max))
437
+ throw new TypeError("fake.int takes integers");
438
+ if (min > max)
439
+ throw new TypeError("fake.int min must not exceed max");
440
+ return min + Math.floor(unit() * (max - min + 1));
441
+ };
442
+ const pick = (list) => {
443
+ if (list.length === 0)
444
+ throw new TypeError("fake.pick needs a non-empty list");
445
+ return list[int(0, list.length - 1)];
446
+ };
447
+ const word = () => pick(WORDS);
448
+ const words = (k) => {
449
+ if (!Number.isSafeInteger(k) || k < 1)
450
+ throw new TypeError("fake.words k must be an integer from 1");
451
+ return Array.from({ length: k }, word).join(" ");
452
+ };
453
+ const sentence = () => `${capitalize(words(int(5, 10)))}.`;
454
+ const slug = () => words(3).replaceAll(" ", "-");
455
+ const hex = (digits) => Array.from({ length: digits }, () => int(0, 15).toString(16)).join("");
456
+ return {
457
+ name: () => `${pick(FIRST_NAMES)} ${pick(LAST_NAMES)}`,
458
+ firstName: () => pick(FIRST_NAMES),
459
+ lastName: () => pick(LAST_NAMES),
460
+ email: (n) => `${word()}${n ?? ""}@example.com`,
461
+ word,
462
+ words,
463
+ sentence,
464
+ paragraph: () => Array.from({ length: int(3, 6) }, sentence).join(" "),
465
+ int,
466
+ float(min, max) {
467
+ if (!Number.isFinite(min) || !Number.isFinite(max))
468
+ throw new TypeError("fake.float takes finite numbers");
469
+ if (min > max)
470
+ throw new TypeError("fake.float min must not exceed max");
471
+ return min + unit() * (max - min);
472
+ },
473
+ bool: (p = 0.5) => unit() < p,
474
+ pick,
475
+ date(range) {
476
+ const from = instant("from", range.from);
477
+ const to = instant("to", range.to);
478
+ if (from > to)
479
+ throw new TypeError("fake.date from must not be after to");
480
+ return new Date(from + Math.floor(unit() * (to - from + 1)));
481
+ },
482
+ uuid: () => `${hex(8)}-${hex(4)}-4${hex(3)}-${pick(["8", "9", "a", "b"])}${hex(3)}-${hex(12)}`,
483
+ slug,
484
+ url: () => `https://example.com/${slug()}`
485
+ };
486
+ }
487
+ var SEED_ENV = "HAMUR_FAKE_SEED";
488
+ function fakeSeed() {
489
+ const env = globalThis.process?.env;
490
+ const text = env?.[SEED_ENV];
491
+ if (text === undefined || text === "")
492
+ return 1;
493
+ const seed = Number(text);
494
+ if (!Number.isSafeInteger(seed))
495
+ throw new TypeError(`${SEED_ENV} must be an integer (got ${JSON.stringify(text)})`);
496
+ return seed;
497
+ }
498
+ function seedOf(seed, key) {
499
+ let hash = (seed ^ 2166136261) >>> 0;
500
+ for (let i = 0;i < key.length; i++)
501
+ hash = Math.imul(hash ^ key.charCodeAt(i), 16777619) >>> 0;
502
+ return hash;
503
+ }
504
+
505
+ // packages/db/src/server/factory-core.ts
506
+ var IDENTIFIER2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
507
+ function template(head, glue, tail, slots) {
508
+ const parts = slots === 0 ? [head + tail] : [head, ...Array(slots - 1).fill(glue), tail];
509
+ return Object.assign(parts, { raw: parts });
510
+ }
511
+ function insertOf(db, table, row) {
512
+ const columns = Object.keys(row).filter((column) => row[column] !== undefined);
513
+ for (const column of columns) {
514
+ if (!IDENTIFIER2.test(column))
515
+ throw new TypeError(`factory("${table}"): "${column}" is not a column name`);
516
+ }
517
+ const into = `INSERT INTO ${quote(db.dialect, [table])}`;
518
+ const returning = db.dialect === "mysql" ? "" : " RETURNING *";
519
+ const strings = columns.length ? template(`${into} (${columns.map((column) => quote(db.dialect, [column])).join(", ")}) VALUES (`, ", ", `)${returning}`, columns.length) : template(db.dialect === "mysql" ? `${into} () VALUES ()` : `${into} DEFAULT VALUES`, "", returning, 0);
520
+ const values = columns.map((column) => row[column]);
521
+ return db.dialect === "mysql" ? db.run(strings, ...values) : db.sql(strings, ...values);
522
+ }
523
+ async function insertRows(db, table, rows) {
524
+ const results = await db.batch(rows.map((row) => insertOf(db, table, row)));
525
+ if (db.dialect !== "mysql")
526
+ return results.flat();
527
+ const ids = results.map((result, index) => {
528
+ const id = rows[index].id ?? result.lastInsertId;
529
+ if (id === undefined || id === null || id === 0)
530
+ throw new Error(`factory("${table}").create: row ${index + 1} has no id to select it by; give it an id`);
531
+ return id;
532
+ });
533
+ const found = await db.sql(template(`SELECT * FROM ${quote(db.dialect, [table])} WHERE ${quote(db.dialect, ["id"])} IN (`, ", ", ")", ids.length), ...ids);
534
+ const byId = new Map(found.map((row) => [String(row.id), row]));
535
+ return ids.map((id) => byId.get(String(id)));
536
+ }
537
+ function createFactory(table, connection, definition, open) {
538
+ const fake = createFake(seedOf(fakeSeed(), `${connection}\x00${table}`));
539
+ let made = 0;
540
+ const make = (count = 1, overrides) => {
541
+ if (!Number.isSafeInteger(count) || count < 0)
542
+ throw new TypeError(`factory("${table}") count must be an integer from 0`);
543
+ return Array.from({ length: count }, () => {
544
+ const n = ++made;
545
+ const given = typeof overrides === "function" ? overrides(n) : overrides;
546
+ return { ...definition.make(n, fake), ...given };
547
+ });
548
+ };
549
+ return {
550
+ make,
551
+ async create(count, overrides) {
552
+ const rows = make(count, overrides);
553
+ if (rows.length === 0)
554
+ return [];
555
+ return await insertRows(open(), table, rows);
556
+ }
557
+ };
558
+ }
559
+
560
+ // packages/db/src/server/factory.ts
561
+ function factory(table, options) {
562
+ const connection = options?.connection ?? "default";
563
+ const file = `server/db/factories/${connection === "default" ? "" : `${connection}/`}${table}.ts`;
564
+ const definition = factories[connection]?.[table];
565
+ if (definition === undefined)
566
+ throw new Error(`No factory for "${table}" in db "${connection}"; write ${file}`);
567
+ if (!isFactory(definition))
568
+ throw new TypeError(`${file} must export default defineFactory(...)`);
569
+ return createFactory(table, connection, definition, () => databases.use(connection));
570
+ }
571
+
572
+ // packages/db/src/server/index.ts
573
+ function useDatabase(name) {
574
+ return databases.use(name);
575
+ }
576
+ export {
577
+ cursorQuery,
578
+ defineDatabaseClient,
579
+ defineFactory,
580
+ factory,
581
+ offsetQuery,
582
+ tableEntities,
583
+ useDatabase
584
+ };
@@ -0,0 +1,7 @@
1
+ // @bun
2
+ import {
3
+ dbStorage2
4
+ } from "../../chunks/bun-index-06tj00dn.js";
5
+ export {
6
+ dbStorage2 as dbStorage
7
+ };
@@ -0,0 +1,8 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import type { DbSetup } from "../types.ts";
3
+ /** `cloudflare.bindings.<NAME>.id`, else env `HAMUR_CF_<NAME>_ID` with the name upper-cased and each character outside `A-Z0-9_` turned into `_`. */
4
+ export declare const cloudflareId: (hamur: HamurContext, binding: string) => string | undefined;
5
+ /** The top-level key of the finalized `.output/wrangler.json` that names `name` as a binding (`binding`, a durable object's `name`, a `vars` key), as `bindingKey` of the preset finds it. */
6
+ export declare function bindingKey(config: Record<string, unknown>, name: string): string | undefined;
7
+ /** The preset's own `default`, each connection's `dev` under `hamur dev` and in the prerender, `node-sqlite` as `bun-sqlite` under `hamur dev`, the connector and binding checks, the import guard, `#hamur/db/connections` and the close plugin. */
8
+ export declare const setupConnections: DbSetup;
@@ -0,0 +1,20 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import { type ClientLoaders, type Databases } from "../runtime/registry.ts";
3
+ import type { ResolvedConnection, ResolvedDbOptions } from "../types.ts";
4
+ export declare const LOADERS: {
5
+ "bun-sql": () => Promise<typeof import("../connectors/bun-sql.ts")>;
6
+ "bun-sqlite": () => Promise<typeof import("../connectors/bun-sqlite.ts")>;
7
+ "node-sqlite": () => Promise<typeof import("../connectors/bun-sqlite.ts")>;
8
+ d1: () => Promise<typeof import("../connectors/d1.ts")>;
9
+ client: () => Promise<typeof import("../connectors/client.ts")>;
10
+ };
11
+ /** A `client` file, relative to `rootDir`, as the bundler finds it; `undefined` when nothing is there. */
12
+ export declare function clientFile(rootDir: string, client: string): string | undefined;
13
+ /** The client file of each `client` connection, for the build's own process (`hamur db`, the migration runs, the prerender's `dev`). */
14
+ export declare function clientLoaders(hamur: HamurContext, connections: Record<string, ResolvedConnection>): ClientLoaders;
15
+ /** The build runs on Bun, where node-sqlite is bun-sqlite on the same file. */
16
+ export declare const asBun: (connection: ResolvedConnection) => ResolvedConnection;
17
+ /** The `dev` connection of every connection that has one, as the build's Bun process runs it. */
18
+ export declare function devConnections(connections: Record<string, ResolvedConnection>): Record<string, ResolvedConnection>;
19
+ /** The connections opened by the build process itself (`hamur db`, `db.migrate: "build"`, the dev watcher), not the server's. */
20
+ export declare function openDatabases(hamur: HamurContext, options: ResolvedDbOptions): Databases;
@@ -0,0 +1,6 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import type { Dialect, ResolvedDbOptions } from "../types.ts";
3
+ /** The app's and each layer's `server/db/factories` (`default` at its top, another connection in its own folder), the app's file first; `connection` then table name to the file. */
4
+ export declare function scanFactories(hamur: HamurContext, options: ResolvedDbOptions, dialects: Record<string, Dialect>): Promise<Record<string, Record<string, string>>>;
5
+ /** `#hamur/db/factories`, every factory file by connection and table, for `factory(table)`; a bad file fails the build. */
6
+ export declare function setupFactories(options: ResolvedDbOptions, hamur: HamurContext, dialects: Record<string, Dialect>): void;
@@ -0,0 +1,21 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import { type Migration } from "../runtime/migrate.ts";
3
+ import type { DbSetup, ResolvedDbOptions } from "../types.ts";
4
+ export interface MigrationDir {
5
+ connection: string;
6
+ dir: string;
7
+ }
8
+ export declare const shown: (rootDir: string, path: string) => string;
9
+ /** The app's and each layer's `server/db/migrations` (`default` at its top, another connection in its own folder), then the modules' (`db:migrations:dirs`). */
10
+ export declare function migrationDirs(hamur: HamurContext, options: ResolvedDbOptions): Promise<MigrationDir[]>;
11
+ /** Each connection's migrations in number order, or the build error of a bad name, a shared number or a file in two directories. */
12
+ export declare function loadMigrations(hamur: HamurContext, options: ResolvedDbOptions): Promise<Record<string, Migration[]>>;
13
+ /** Applies every connection's pending migrations through connections the build opens itself, logging each file. */
14
+ export declare function applyAll(hamur: HamurContext, options: ResolvedDbOptions, names?: string[]): Promise<void>;
15
+ /** The connections whose migrations Hamur applies; wrangler applies a d1 connection's. */
16
+ export declare const notD1: (options: ResolvedDbOptions) => string[];
17
+ /**
18
+ * `#hamur/db/migrations` (every connection's files, for the task `db:migrate`, and `apply` for the server's own run under
19
+ * `hamur dev` and at a built server's start with `migrate: "start"`), the task, the start check, the build's run, the dev watcher.
20
+ */
21
+ export declare const setupMigrations: DbSetup;
@@ -0,0 +1,7 @@
1
+ import { type HamurContext } from "hamur/kit";
2
+ import { type QueueOptions } from "../runtime/queue.ts";
3
+ import type { DbSetup } from "../types.ts";
4
+ /** `tasks.queue` when it is `{ driver: "db" }`, its defaults filled; `undefined` for another queue or none. */
5
+ export declare function queueOptions(hamur: HamurContext): QueueOptions | undefined;
6
+ /** `#hamur/db/queue`, which the server door reads to start the worker; the queue's connection must be one of `db.connections`. */
7
+ export declare const setupQueue: DbSetup;