@event-driven-io/dumbo 0.13.0-beta.35 → 0.13.0-beta.36

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 (87) hide show
  1. package/dist/cloudflare.cjs +379 -434
  2. package/dist/cloudflare.cjs.map +1 -1
  3. package/dist/cloudflare.d.cts +36 -29
  4. package/dist/cloudflare.d.ts +36 -29
  5. package/dist/cloudflare.js +343 -434
  6. package/dist/cloudflare.js.map +1 -1
  7. package/dist/core-BeyC5tHn.js +519 -0
  8. package/dist/core-BeyC5tHn.js.map +1 -0
  9. package/dist/core-Bf2ujUFy.js +379 -0
  10. package/dist/core-Bf2ujUFy.js.map +1 -0
  11. package/dist/core-BgYtAxCm.cjs +3237 -0
  12. package/dist/core-BgYtAxCm.cjs.map +1 -0
  13. package/dist/core-DDo4m0Z_.js +2262 -0
  14. package/dist/core-DDo4m0Z_.js.map +1 -0
  15. package/dist/core-DmbB4qMn.cjs +656 -0
  16. package/dist/core-DmbB4qMn.cjs.map +1 -0
  17. package/dist/core-Go_IA78L.cjs +450 -0
  18. package/dist/core-Go_IA78L.cjs.map +1 -0
  19. package/dist/{connectionString-Dch_MIRU.d.cts → index-BDSQvDH2.d.cts} +1010 -922
  20. package/dist/index-BdWFmDhJ.d.cts +68 -0
  21. package/dist/index-D1jryNqo.d.ts +198 -0
  22. package/dist/index-DaP2fTEX.d.ts +67 -0
  23. package/dist/index-DqVvUav9.d.cts +198 -0
  24. package/dist/index-S_wp0Eaf.d.cts +67 -0
  25. package/dist/index-cxtbLiju.d.ts +68 -0
  26. package/dist/{connectionString-Dch_MIRU.d.ts → index-zkszkJqP.d.ts} +1010 -922
  27. package/dist/index.cjs +212 -359
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +3 -132
  30. package/dist/index.d.ts +3 -132
  31. package/dist/index.js +52 -361
  32. package/dist/index.js.map +1 -1
  33. package/dist/pg.cjs +366 -431
  34. package/dist/pg.cjs.map +1 -1
  35. package/dist/pg.d.cts +83 -72
  36. package/dist/pg.d.ts +83 -72
  37. package/dist/pg.js +320 -431
  38. package/dist/pg.js.map +1 -1
  39. package/dist/postgreSQLMetadata-LqX-Z_wo.cjs +118 -0
  40. package/dist/postgreSQLMetadata-LqX-Z_wo.cjs.map +1 -0
  41. package/dist/postgreSQLMetadata-zMq8yJo_.js +65 -0
  42. package/dist/postgreSQLMetadata-zMq8yJo_.js.map +1 -0
  43. package/dist/postgresql.cjs +25 -50
  44. package/dist/postgresql.d.cts +3 -61
  45. package/dist/postgresql.d.ts +3 -61
  46. package/dist/postgresql.js +4 -50
  47. package/dist/sqlite.cjs +30 -60
  48. package/dist/sqlite.d.cts +3 -190
  49. package/dist/sqlite.d.ts +3 -190
  50. package/dist/sqlite.js +4 -60
  51. package/dist/sqlite3.cjs +312 -380
  52. package/dist/sqlite3.cjs.map +1 -1
  53. package/dist/sqlite3.d.cts +79 -77
  54. package/dist/sqlite3.d.ts +79 -77
  55. package/dist/sqlite3.js +276 -378
  56. package/dist/sqlite3.js.map +1 -1
  57. package/dist/sqliteMetadata-BoQ7Sc9I.js +29 -0
  58. package/dist/sqliteMetadata-BoQ7Sc9I.js.map +1 -0
  59. package/dist/sqliteMetadata-D_2pKeCC.cjs +46 -0
  60. package/dist/sqliteMetadata-D_2pKeCC.cjs.map +1 -0
  61. package/package.json +12 -12
  62. package/dist/chunk-33P5766L.js +0 -83
  63. package/dist/chunk-33P5766L.js.map +0 -1
  64. package/dist/chunk-4MMMEDQ7.cjs +0 -2944
  65. package/dist/chunk-4MMMEDQ7.cjs.map +0 -1
  66. package/dist/chunk-6HAHSSPW.js +0 -701
  67. package/dist/chunk-6HAHSSPW.js.map +0 -1
  68. package/dist/chunk-GNH5XC6D.cjs +0 -481
  69. package/dist/chunk-GNH5XC6D.cjs.map +0 -1
  70. package/dist/chunk-H2JBS7HM.js +0 -2944
  71. package/dist/chunk-H2JBS7HM.js.map +0 -1
  72. package/dist/chunk-JIZGCEPE.cjs +0 -701
  73. package/dist/chunk-JIZGCEPE.cjs.map +0 -1
  74. package/dist/chunk-NJI6PJFZ.cjs +0 -83
  75. package/dist/chunk-NJI6PJFZ.cjs.map +0 -1
  76. package/dist/chunk-RQ3KKMTP.cjs +0 -34
  77. package/dist/chunk-RQ3KKMTP.cjs.map +0 -1
  78. package/dist/chunk-UK7MXVS2.js +0 -34
  79. package/dist/chunk-UK7MXVS2.js.map +0 -1
  80. package/dist/chunk-Y5TD53QE.js +0 -481
  81. package/dist/chunk-Y5TD53QE.js.map +0 -1
  82. package/dist/columnProcessors-Be2uMYjS.d.cts +0 -8
  83. package/dist/columnProcessors-D0ivj_SU.d.ts +0 -8
  84. package/dist/postgresql.cjs.map +0 -1
  85. package/dist/postgresql.js.map +0 -1
  86. package/dist/sqlite.cjs.map +0 -1
  87. package/dist/sqlite.js.map +0 -1
@@ -0,0 +1,2262 @@
1
+ import ansis from "ansis";
2
+ import { v7 } from "uuid";
3
+
4
+ //#region src/core/schema/schemaComponent.ts
5
+ const schemaComponent = (key, options) => {
6
+ const componentsMap = new Map(options.components?.map((comp) => [comp.schemaComponentKey, comp]));
7
+ const migrations = [...options.migrations ?? []];
8
+ return {
9
+ schemaComponentKey: key,
10
+ components: componentsMap,
11
+ get migrations() {
12
+ return [...migrations, ...Array.from(componentsMap.values()).flatMap((c) => c.migrations)];
13
+ },
14
+ addComponent: (component) => {
15
+ componentsMap.set(component.schemaComponentKey, component);
16
+ migrations.push(...component.migrations);
17
+ return component;
18
+ },
19
+ addMigration: (migration) => {
20
+ migrations.push(migration);
21
+ }
22
+ };
23
+ };
24
+ const isSchemaComponentOfType = (component, prefix) => component.schemaComponentKey.startsWith(prefix);
25
+ const filterSchemaComponentsOfType = (components, prefix) => mapSchemaComponentsOfType(components, prefix);
26
+ const mapSchemaComponentsOfType = (components, prefix, keyMapper) => new Map(Array.from(components.entries()).filter(([urn]) => urn.startsWith(prefix)).map(([urn, component]) => [keyMapper ? keyMapper(component) : urn, component]));
27
+ const findSchemaComponentsOfType = (root, prefix) => {
28
+ const results = [];
29
+ const traverse = (component) => {
30
+ if (component.schemaComponentKey.startsWith(prefix)) results.push(component);
31
+ for (const child of component.components.values()) traverse(child);
32
+ };
33
+ traverse(root);
34
+ return results;
35
+ };
36
+
37
+ //#endregion
38
+ //#region src/core/schema/components/columnSchemaComponent.ts
39
+ const ColumnURNType = "sc:dumbo:column";
40
+ const ColumnURN = ({ name }) => `${ColumnURNType}:${name}`;
41
+ const columnSchemaComponent = (params) => {
42
+ const { columnName, type, notNull, unique, primaryKey, default: defaultValue, ...schemaOptions } = params;
43
+ return {
44
+ ...schemaComponent(ColumnURN({ name: columnName }), schemaOptions),
45
+ columnName,
46
+ notNull,
47
+ unique,
48
+ primaryKey,
49
+ defaultValue,
50
+ sqlTokenType: "SQL_COLUMN",
51
+ name: columnName,
52
+ type
53
+ };
54
+ };
55
+
56
+ //#endregion
57
+ //#region src/core/schema/components/indexSchemaComponent.ts
58
+ const IndexURNType = "sc:dumbo:index";
59
+ const IndexURN = ({ name }) => `${IndexURNType}:${name}`;
60
+ const indexSchemaComponent = ({ indexName, columnNames, isUnique, ...migrationsOrComponents }) => {
61
+ return {
62
+ ...schemaComponent(IndexURN({ name: indexName }), {
63
+ migrations: migrationsOrComponents.migrations ?? [],
64
+ components: [...migrationsOrComponents.components ?? []]
65
+ }),
66
+ indexName,
67
+ get columnNames() {
68
+ return columnNames;
69
+ },
70
+ addColumn: (column) => columnNames.push(typeof column === "string" ? column : column.columnName),
71
+ isUnique
72
+ };
73
+ };
74
+
75
+ //#endregion
76
+ //#region src/core/schema/components/tableSchemaComponent.ts
77
+ const TableURNType = "sc:dumbo:table";
78
+ const TableURN = ({ name }) => `${TableURNType}:${name}`;
79
+ const tableSchemaComponent = ({ tableName, columns, primaryKey, relationships, ...migrationsOrComponents }) => {
80
+ columns ??= {};
81
+ relationships ??= {};
82
+ const base = schemaComponent(TableURN({ name: tableName }), {
83
+ migrations: migrationsOrComponents.migrations ?? [],
84
+ components: [...migrationsOrComponents.components ?? [], ...Object.values(columns)]
85
+ });
86
+ return {
87
+ ...base,
88
+ tableName,
89
+ primaryKey: primaryKey ?? [],
90
+ relationships,
91
+ get columns() {
92
+ const columnsMap = mapSchemaComponentsOfType(base.components, ColumnURNType, (c) => c.columnName);
93
+ return Object.assign(columnsMap, columns);
94
+ },
95
+ get indexes() {
96
+ return mapSchemaComponentsOfType(base.components, IndexURNType, (c) => c.indexName);
97
+ },
98
+ addColumn: (column) => base.addComponent(column),
99
+ addIndex: (index) => base.addComponent(index)
100
+ };
101
+ };
102
+
103
+ //#endregion
104
+ //#region src/core/schema/components/databaseSchemaSchemaComponent.ts
105
+ const DatabaseSchemaURNType = "sc:dumbo:database_schema";
106
+ const DatabaseSchemaURN = ({ name }) => `${DatabaseSchemaURNType}:${name}`;
107
+ const databaseSchemaSchemaComponent = ({ schemaName, tables, ...migrationsOrComponents }) => {
108
+ const base = schemaComponent(DatabaseSchemaURN({ name: schemaName }), {
109
+ migrations: migrationsOrComponents.migrations ?? [],
110
+ components: [...migrationsOrComponents.components ?? [], ...Object.values(tables ?? {})]
111
+ });
112
+ return {
113
+ ...base,
114
+ schemaName,
115
+ get tables() {
116
+ const tablesMap = mapSchemaComponentsOfType(base.components, TableURNType, (c) => c.tableName);
117
+ return Object.assign(tablesMap, tables);
118
+ },
119
+ addTable: (table) => base.addComponent(typeof table === "string" ? tableSchemaComponent({ tableName: table }) : table)
120
+ };
121
+ };
122
+
123
+ //#endregion
124
+ //#region src/core/schema/components/databaseSchemaComponent.ts
125
+ const DatabaseURNType = "sc:dumbo:database";
126
+ const DatabaseURN = ({ name }) => `${DatabaseURNType}:${name}`;
127
+ const databaseSchemaComponent = ({ databaseName, schemas, ...migrationsOrComponents }) => {
128
+ schemas ??= {};
129
+ const base = schemaComponent(DatabaseURN({ name: databaseName }), {
130
+ migrations: migrationsOrComponents.migrations ?? [],
131
+ components: [...migrationsOrComponents.components ?? [], ...Object.values(schemas)]
132
+ });
133
+ return {
134
+ ...base,
135
+ databaseName,
136
+ get schemas() {
137
+ const schemasMap = mapSchemaComponentsOfType(base.components, DatabaseSchemaURNType, (c) => c.schemaName);
138
+ return Object.assign(schemasMap, schemas);
139
+ },
140
+ addSchema: (schema) => base.addComponent(typeof schema === "string" ? databaseSchemaSchemaComponent({ schemaName: schema }) : schema)
141
+ };
142
+ };
143
+
144
+ //#endregion
145
+ //#region src/core/schema/components/index.ts
146
+ const schemaComponentURN = {
147
+ database: DatabaseURN,
148
+ schema: DatabaseSchemaURN,
149
+ table: TableURN,
150
+ column: ColumnURN,
151
+ index: IndexURN,
152
+ extractName: (urn) => {
153
+ const parts = urn.split(":");
154
+ return parts[parts.length - 1] || "";
155
+ }
156
+ };
157
+
158
+ //#endregion
159
+ //#region src/core/drivers/databaseDriver.ts
160
+ const canHandleDriverWithConnectionString = (driver, tryParseConnectionString) => (options) => {
161
+ if ("driverType" in options) return options.driverType === driver;
162
+ if ("connectionString" in options && typeof options.connectionString === "string") return tryParseConnectionString(options.connectionString) !== null;
163
+ return false;
164
+ };
165
+ const DumboDatabaseDriverRegistry = () => {
166
+ const drivers = /* @__PURE__ */ new Map();
167
+ const register = (driverType, plugin) => {
168
+ const entry = drivers.get(driverType);
169
+ if (entry && (typeof entry !== "function" || typeof plugin === "function")) return;
170
+ drivers.set(driverType, plugin);
171
+ };
172
+ const getDriver = (options) => options.driverType ? drivers.get(options.driverType) : [...drivers.values()].find((d) => typeof d !== "function" && d.canHandle(options));
173
+ const tryResolve = async (options) => {
174
+ const driver = getDriver(options);
175
+ if (!driver) return null;
176
+ if (typeof driver !== "function") return driver;
177
+ const plugin = await driver();
178
+ register(plugin.driverType, plugin);
179
+ return plugin;
180
+ };
181
+ const tryGet = (options) => {
182
+ const driver = getDriver(options);
183
+ return driver && typeof driver !== "function" ? driver : null;
184
+ };
185
+ const has = (driverType) => drivers.has(driverType);
186
+ return {
187
+ register,
188
+ tryResolve,
189
+ tryGet,
190
+ has,
191
+ get databaseDriverTypes() {
192
+ return Array.from(drivers.keys());
193
+ }
194
+ };
195
+ };
196
+ const dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry = globalThis.dumboDatabaseDriverRegistry ?? DumboDatabaseDriverRegistry();
197
+
198
+ //#endregion
199
+ //#region src/core/drivers/index.ts
200
+ /**
201
+ * Accepts a `databaseType` (e.g. PostgreSQL, SQLite) and a `driverName`
202
+ * (the library name, e.g. pg, sqlite3) and combines them to a singular
203
+ * `databaseDriverType` which can be used in database handling.
204
+ */
205
+ function toDatabaseDriverType(databaseType, driverName) {
206
+ return `${databaseType}:${driverName}`;
207
+ }
208
+ /**
209
+ * Accepts a fully formatted `driverType` and returns the broken down
210
+ * `databaseType` and `driverName`.
211
+ */
212
+ function fromDatabaseDriverType(databaseDriverType) {
213
+ const parts = databaseDriverType.split(":");
214
+ return {
215
+ databaseType: parts[0],
216
+ driverName: parts[1]
217
+ };
218
+ }
219
+ /**
220
+ * Accepts a fully formatted `databaseDriverType` and returns the `driverName`.
221
+ */
222
+ function getDatabaseDriverName(databaseDriverType) {
223
+ const { driverName } = fromDatabaseDriverType(databaseDriverType);
224
+ return driverName;
225
+ }
226
+ /**
227
+ * Accepts a fully formatted `databaseDriverType` and returns the `databaseType`.
228
+ */
229
+ function getDatabaseType(databaseDriverType) {
230
+ const { databaseType } = fromDatabaseDriverType(databaseDriverType);
231
+ return databaseType;
232
+ }
233
+
234
+ //#endregion
235
+ //#region src/core/schema/databaseMetadata/databaseMetadata.ts
236
+ const DumboDatabaseMetadataRegistry = () => {
237
+ const infos = /* @__PURE__ */ new Map();
238
+ const register = (databaseType, info) => {
239
+ const entry = infos.get(databaseType);
240
+ if (entry && (typeof entry !== "function" || typeof info === "function")) return;
241
+ infos.set(databaseType, info);
242
+ };
243
+ const tryResolve = async (databaseType) => {
244
+ const entry = infos.get(databaseType);
245
+ if (!entry) return null;
246
+ if (typeof entry !== "function") return entry;
247
+ const resolved = await entry();
248
+ register(databaseType, resolved);
249
+ return resolved;
250
+ };
251
+ const tryGet = (databaseType) => {
252
+ const entry = infos.get(databaseType);
253
+ return entry && typeof entry !== "function" ? entry : null;
254
+ };
255
+ const has = (databaseType) => infos.has(databaseType);
256
+ return {
257
+ register,
258
+ tryResolve,
259
+ tryGet,
260
+ has,
261
+ get databaseTypes() {
262
+ return Array.from(infos.keys());
263
+ }
264
+ };
265
+ };
266
+ const dumboDatabaseMetadataRegistry = globalThis.dumboDatabaseMetadataRegistry = globalThis.dumboDatabaseMetadataRegistry ?? DumboDatabaseMetadataRegistry();
267
+ const getDatabaseMetadata = (driverType) => {
268
+ const { databaseType } = fromDatabaseDriverType(driverType);
269
+ return dumboDatabaseMetadataRegistry.tryGet(databaseType);
270
+ };
271
+ const resolveDatabaseMetadata = async (driverType, driverOverride) => {
272
+ if (driverOverride) return driverOverride;
273
+ const { databaseType } = fromDatabaseDriverType(driverType);
274
+ return dumboDatabaseMetadataRegistry.tryResolve(databaseType);
275
+ };
276
+ const getDefaultDatabase = (driverType) => {
277
+ return getDatabaseMetadata(driverType)?.defaultDatabaseName;
278
+ };
279
+ const getDefaultDatabaseAsync = async (driverType) => {
280
+ return (await resolveDatabaseMetadata(driverType))?.defaultDatabaseName;
281
+ };
282
+
283
+ //#endregion
284
+ //#region src/core/schema/dumboSchema/dumboSchema.ts
285
+ const DEFAULT_DATABASE_NAME = "__default_database__";
286
+ const DEFAULT_DATABASE_SCHEMA_NAME = "__default_database_schema__";
287
+ const dumboColumn = (name, type, options) => columnSchemaComponent({
288
+ columnName: name,
289
+ type,
290
+ ...options
291
+ });
292
+ const dumboIndex = (name, columnNames, options) => indexSchemaComponent({
293
+ indexName: name,
294
+ columnNames,
295
+ isUnique: options?.unique ?? false,
296
+ ...options
297
+ });
298
+ const dumboTable = (name, definition) => {
299
+ const { columns, indexes, primaryKey, relationships, ...options } = definition;
300
+ const components = [...indexes ? Object.values(indexes) : []];
301
+ return tableSchemaComponent({
302
+ tableName: name,
303
+ columns: columns ?? {},
304
+ primaryKey: primaryKey ?? [],
305
+ ...relationships !== void 0 ? { relationships } : {},
306
+ components,
307
+ ...options
308
+ });
309
+ };
310
+ function dumboDatabaseSchema(nameOrTables, tables, options) {
311
+ return databaseSchemaSchemaComponent({
312
+ schemaName: typeof nameOrTables === "string" ? nameOrTables : DEFAULT_DATABASE_SCHEMA_NAME,
313
+ tables: (typeof nameOrTables === "string" ? tables : nameOrTables) ?? {},
314
+ ...options
315
+ });
316
+ }
317
+ dumboDatabaseSchema.from = (schemaName, tableNames) => {
318
+ const tables = tableNames.reduce((acc, tableName) => {
319
+ acc[tableName] = dumboTable(tableName, {});
320
+ return acc;
321
+ }, {});
322
+ return schemaName ? dumboDatabaseSchema(schemaName, tables) : dumboDatabaseSchema(tables);
323
+ };
324
+ function dumboDatabase(nameOrSchemas, schemasOrOptions, options) {
325
+ const databaseName = typeof nameOrSchemas === "string" ? nameOrSchemas : DEFAULT_DATABASE_NAME;
326
+ const schemasOrSchema = typeof nameOrSchemas === "string" ? schemasOrOptions ?? {} : nameOrSchemas;
327
+ return databaseSchemaComponent({
328
+ databaseName,
329
+ schemas: "schemaComponentKey" in schemasOrSchema && isSchemaComponentOfType(schemasOrSchema, "sc:dumbo:database_schema") ? { [DEFAULT_DATABASE_SCHEMA_NAME]: schemasOrSchema } : schemasOrSchema,
330
+ ...typeof nameOrSchemas === "string" ? options : schemasOrOptions
331
+ });
332
+ }
333
+ dumboDatabase.from = (databaseName, schemaNames) => {
334
+ const schemas = schemaNames.reduce((acc, schemaName) => {
335
+ acc[schemaName] = dumboDatabaseSchema(schemaName, {});
336
+ return acc;
337
+ }, {});
338
+ return databaseName ? dumboDatabase(databaseName, schemas) : dumboDatabase(schemas);
339
+ };
340
+ dumboDatabase.defaultName = DEFAULT_DATABASE_NAME;
341
+ dumboDatabaseSchema.defaultName = DEFAULT_DATABASE_SCHEMA_NAME;
342
+ const dumboSchema = {
343
+ database: dumboDatabase,
344
+ schema: dumboDatabaseSchema,
345
+ table: dumboTable,
346
+ column: dumboColumn,
347
+ index: dumboIndex
348
+ };
349
+
350
+ //#endregion
351
+ //#region src/core/locks/databaseLock.ts
352
+ const defaultDatabaseLockOptions = { timeoutMs: 1e4 };
353
+ const NoDatabaseLock = {
354
+ acquire: () => Promise.resolve(),
355
+ tryAcquire: () => Promise.resolve(true),
356
+ release: () => Promise.resolve(true),
357
+ withAcquire: (_execute, handle, _options) => handle()
358
+ };
359
+
360
+ //#endregion
361
+ //#region src/core/query/selectors.ts
362
+ const firstOrNull = async (getResult) => {
363
+ const result = await getResult;
364
+ return result.rows.length > 0 ? result.rows[0] ?? null : null;
365
+ };
366
+ const first = async (getResult) => {
367
+ const result = await getResult;
368
+ if (result.rows.length === 0) throw new Error("Query didn't return any result");
369
+ return result.rows[0];
370
+ };
371
+ const singleOrNull = async (getResult) => {
372
+ const result = await getResult;
373
+ if (result.rows.length > 1) throw new Error("Query had more than one result");
374
+ return result.rows.length > 0 ? result.rows[0] ?? null : null;
375
+ };
376
+ const single = async (getResult) => {
377
+ const result = await getResult;
378
+ if (result.rows.length === 0) throw new Error("Query didn't return any result");
379
+ if (result.rows.length > 1) throw new Error("Query had more than one result");
380
+ return result.rows[0];
381
+ };
382
+ const count = async (getResult) => {
383
+ const result = await single(getResult);
384
+ return Number(result.count);
385
+ };
386
+ const exists = async (getResult) => {
387
+ const result = await single(getResult);
388
+ return result.exists === true || result.exists === 1;
389
+ };
390
+
391
+ //#endregion
392
+ //#region src/core/serializer/json/index.ts
393
+ const bigIntReplacer = (_key, value) => {
394
+ return typeof value === "bigint" ? value.toString() : value;
395
+ };
396
+ const dateReplacer = (_key, value) => {
397
+ return value instanceof Date ? value.toISOString() : value;
398
+ };
399
+ const isFirstLetterNumeric = (str) => {
400
+ const c = str.charCodeAt(0);
401
+ return c >= 48 && c <= 57;
402
+ };
403
+ const isFirstLetterNumericOrMinus = (str) => {
404
+ const c = str.charCodeAt(0);
405
+ return c >= 48 && c <= 57 || c === 45;
406
+ };
407
+ const bigIntReviver = (_key, value, context) => {
408
+ if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) try {
409
+ return BigInt(context?.source ?? value.toString());
410
+ } catch {
411
+ return value;
412
+ }
413
+ if (typeof value === "string" && value.length > 15) {
414
+ if (isFirstLetterNumericOrMinus(value)) {
415
+ const num = Number(value);
416
+ if (Number.isFinite(num) && !Number.isSafeInteger(num)) try {
417
+ return BigInt(value);
418
+ } catch {}
419
+ }
420
+ }
421
+ return value;
422
+ };
423
+ const dateReviver = (_key, value) => {
424
+ if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
425
+ const date = new Date(value);
426
+ if (!isNaN(date.getTime())) return date;
427
+ }
428
+ return value;
429
+ };
430
+ const composeJSONReplacers = (...replacers) => {
431
+ const filteredReplacers = replacers.filter((r) => r !== void 0);
432
+ if (filteredReplacers.length === 0) return void 0;
433
+ return (key, value) => filteredReplacers.reduce((accValue, replacer) => replacer(key, accValue), value);
434
+ };
435
+ const composeJSONRevivers = (...revivers) => {
436
+ const filteredRevivers = revivers.filter((r) => r !== void 0);
437
+ if (filteredRevivers.length === 0) return void 0;
438
+ return (key, value, context) => filteredRevivers.reduce((accValue, reviver) => reviver(key, accValue, context), value);
439
+ };
440
+ const JSONReplacer = (opts) => composeJSONReplacers(opts?.replacer, opts?.failOnBigIntSerialization !== true ? JSONReplacers.bigInt : void 0, opts?.useDefaultDateSerialization !== true ? JSONReplacers.date : void 0);
441
+ const JSONReviver = (opts) => composeJSONRevivers(opts?.reviver, opts?.parseBigInts === true ? JSONRevivers.bigInt : void 0, opts?.parseDates === true ? JSONRevivers.date : void 0);
442
+ const JSONReplacers = {
443
+ bigInt: bigIntReplacer,
444
+ date: dateReplacer
445
+ };
446
+ const JSONRevivers = {
447
+ bigInt: bigIntReviver,
448
+ date: dateReviver
449
+ };
450
+ const jsonSerializer = (options) => {
451
+ const defaultReplacer = JSONReplacer(options);
452
+ const defaultReviver = JSONReviver(options);
453
+ return {
454
+ serialize: (object, serializerOptions) => JSON.stringify(object, serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer),
455
+ deserialize: (payload, deserializerOptions) => JSON.parse(payload, deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver)
456
+ };
457
+ };
458
+ const JSONSerializer = Object.assign(jsonSerializer(), { from: (options) => options?.serialization?.serializer ?? (options?.serialization?.options ? jsonSerializer(options?.serialization?.options) : JSONSerializer) });
459
+ const JSONCodec = (options) => {
460
+ const serializer = "serializer" in options ? options.serializer : jsonSerializer("serializerOptions" in options ? options.serializerOptions : void 0);
461
+ const upcast = options.upcast ?? ((doc) => doc);
462
+ const downcast = options.downcast ?? ((doc) => doc);
463
+ return {
464
+ decode: (payload, decodeOptions) => {
465
+ return upcast(decodeOptions ? serializer.deserialize(payload, decodeOptions) : serializer.deserialize(payload));
466
+ },
467
+ encode: (object, encodeOptions) => {
468
+ const downcasted = downcast(object);
469
+ return encodeOptions ? serializer.serialize(downcasted, encodeOptions) : serializer.serialize(downcasted);
470
+ }
471
+ };
472
+ };
473
+
474
+ //#endregion
475
+ //#region src/core/sql/parametrizedSQL/parametrizedSQL.ts
476
+ const ParametrizedSQLBuilder = ({ mapParamPlaceholder }) => {
477
+ const sql = [];
478
+ const params = [];
479
+ return {
480
+ addSQL(str) {
481
+ sql.push(str);
482
+ return this;
483
+ },
484
+ addParam(value) {
485
+ sql.push(mapParamPlaceholder(params.length, value));
486
+ params.push(value);
487
+ return this;
488
+ },
489
+ addParams(values) {
490
+ const placeholders = values.map((value, i) => mapParamPlaceholder(params.length + i, value));
491
+ this.addSQL(`${placeholders.join(", ")}`);
492
+ params.push(...values);
493
+ return this;
494
+ },
495
+ build() {
496
+ return {
497
+ query: sql.join(""),
498
+ params
499
+ };
500
+ }
501
+ };
502
+ };
503
+
504
+ //#endregion
505
+ //#region src/core/sql/tokens/sqlToken.ts
506
+ const SQLToken = (sqlTokenType, map) => {
507
+ const factory = (input) => {
508
+ let props;
509
+ if (map !== void 0) props = map(input);
510
+ else if (input === void 0 || input === null) props = {};
511
+ else if (typeof input === "object" && !Array.isArray(input)) props = input;
512
+ else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
513
+ return {
514
+ sqlTokenType,
515
+ [sqlTokenType]: true,
516
+ ...props
517
+ };
518
+ };
519
+ const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
520
+ return {
521
+ from: factory,
522
+ check,
523
+ type: sqlTokenType
524
+ };
525
+ };
526
+ SQLToken.check = (token) => token !== null && typeof token === "object" && "sqlTokenType" in token;
527
+ const SQLIdentifier = SQLToken("SQL_IDENTIFIER", (value) => ({ value }));
528
+ const SQLPlain = SQLToken("SQL_RAW", (value) => ({ value }));
529
+ const SQLLiteral = SQLToken("SQL_LITERAL", (value) => ({ value }));
530
+ const SQLArray = SQLToken("SQL_ARRAY", (input) => {
531
+ if (Array.isArray(input)) return { value: input };
532
+ return input.mode !== void 0 ? {
533
+ value: input.value,
534
+ mode: input.mode
535
+ } : { value: input.value };
536
+ });
537
+ const SQLIn = SQLToken("SQL_IN", ({ column, values, mode }) => mode !== void 0 ? {
538
+ column: SQLIdentifier.from(column),
539
+ values: SQLArray.from(values),
540
+ mode
541
+ } : {
542
+ column: SQLIdentifier.from(column),
543
+ values: SQLArray.from(values)
544
+ });
545
+
546
+ //#endregion
547
+ //#region src/core/sql/tokens/columnTokens.ts
548
+ const ColumnTypeToken = (sqlTokenType, jsTypeName, map) => {
549
+ const factory = (input) => {
550
+ let props;
551
+ if (map !== void 0) props = map(input);
552
+ else if (input === void 0 || input === null) props = {};
553
+ else if (typeof input === "object" && !Array.isArray(input)) props = input;
554
+ else throw new Error(`Cannot create SQLToken of type ${sqlTokenType} with input: ${input}`);
555
+ return {
556
+ sqlTokenType,
557
+ [sqlTokenType]: true,
558
+ jsTypeName,
559
+ ...props
560
+ };
561
+ };
562
+ const check = (token) => SQLToken.check(token) && token.sqlTokenType === sqlTokenType;
563
+ return {
564
+ from: factory,
565
+ check,
566
+ type: sqlTokenType
567
+ };
568
+ };
569
+ const SerialToken = ColumnTypeToken("SQL_COLUMN_SERIAL", "value_type:js:number");
570
+ const BigSerialToken = ColumnTypeToken("SQL_COLUMN_BIGSERIAL", "value_type:js:bigint");
571
+ const IntegerToken = ColumnTypeToken("SQL_COLUMN_INTEGER", "value_type:js:number");
572
+ const BigIntegerToken = ColumnTypeToken("SQL_COLUMN_BIGINT", "value_type:js:bigint");
573
+ const JSONBToken = {
574
+ type: "SQL_COLUMN_JSONB",
575
+ from: () => {
576
+ return {
577
+ sqlTokenType: "SQL_COLUMN_JSONB",
578
+ ["SQL_COLUMN_JSONB"]: true
579
+ };
580
+ },
581
+ check: (token) => SQLToken.check(token) && token.sqlTokenType === "SQL_COLUMN_JSONB"
582
+ };
583
+ const TimestampToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMP", "value_type:js:date");
584
+ const TimestamptzToken = ColumnTypeToken("SQL_COLUMN_TIMESTAMPTZ", "value_type:js:date");
585
+ const VarcharToken = ColumnTypeToken("SQL_COLUMN_VARCHAR", "value_type:js:string", (length) => ({
586
+ length: length ?? "max",
587
+ jsTypeName: "value_type:js:string"
588
+ }));
589
+ const AutoIncrementSQLColumnToken = ColumnTypeToken("SQL_COLUMN_AUTO_INCREMENT", "value_type:js:bigint");
590
+ const SQLColumnTypeTokens = {
591
+ AutoIncrement: AutoIncrementSQLColumnToken,
592
+ BigInteger: BigIntegerToken,
593
+ BigSerial: BigSerialToken,
594
+ Integer: IntegerToken,
595
+ JSONB: JSONBToken,
596
+ Serial: SerialToken,
597
+ Timestamp: TimestampToken,
598
+ Timestamptz: TimestamptzToken,
599
+ Varchar: VarcharToken
600
+ };
601
+ const SQLColumnTypeTokensFactory = {
602
+ AutoIncrement: AutoIncrementSQLColumnToken.from,
603
+ BigInteger: BigIntegerToken.from(),
604
+ BigSerial: BigSerialToken.from(),
605
+ Integer: IntegerToken.from(),
606
+ JSONB: JSONBToken.from,
607
+ Serial: SerialToken.from(),
608
+ Timestamp: TimestampToken.from(),
609
+ Timestamptz: TimestamptzToken.from(),
610
+ Varchar: VarcharToken.from
611
+ };
612
+ const SQLColumnToken = SQLToken("SQL_COLUMN");
613
+
614
+ //#endregion
615
+ //#region src/core/sql/processors/sqlProcessor.ts
616
+ const SQLProcessor = (options) => options;
617
+
618
+ //#endregion
619
+ //#region src/core/sql/processors/defaultProcessors.ts
620
+ const ExpandArrayProcessor = SQLProcessor({
621
+ canHandle: "SQL_ARRAY",
622
+ handle: (token, { builder, serializer, mapper }) => {
623
+ if (token.value.length === 0) throw new Error("Empty arrays are not supported. If you're using it with SELECT IN statement Use SQL.in(column, array) helper instead.");
624
+ builder.addParams(mapper.mapValue(token.value, serializer));
625
+ }
626
+ });
627
+ const ExpandSQLInProcessor = SQLProcessor({
628
+ canHandle: "SQL_IN",
629
+ handle: (token, context) => {
630
+ const { builder, mapper, processorsRegistry, serializer } = context;
631
+ const { values: inValues, column } = token;
632
+ if (inValues.value.length === 0) {
633
+ builder.addParam(mapper.mapValue(false, serializer));
634
+ return;
635
+ }
636
+ builder.addSQL(mapper.mapValue(column.value, serializer));
637
+ builder.addSQL(` IN (`);
638
+ const arrayProcessor = processorsRegistry.get(SQLArray.type);
639
+ if (!arrayProcessor) throw new Error("No sql processor registered for an array. Cannot expand IN statement");
640
+ arrayProcessor.handle(inValues, {
641
+ builder,
642
+ mapper,
643
+ processorsRegistry,
644
+ serializer
645
+ });
646
+ builder.addSQL(`)`);
647
+ }
648
+ });
649
+ const FormatIdentifierProcessor = SQLProcessor({
650
+ canHandle: "SQL_IDENTIFIER",
651
+ handle: (token, { builder, mapper, serializer }) => {
652
+ builder.addSQL(mapper.mapValue(token, serializer));
653
+ }
654
+ });
655
+ const MapLiteralProcessor = SQLProcessor({
656
+ canHandle: "SQL_LITERAL",
657
+ handle: (token, { builder, mapper, serializer }) => builder.addParam(mapper.mapValue(token.value, serializer))
658
+ });
659
+
660
+ //#endregion
661
+ //#region src/core/sql/processors/sqlProcessorRegistry.ts
662
+ const SQLProcessorsRegistry = (options) => {
663
+ const processors = options ? new Map(options.from.all()) : /* @__PURE__ */ new Map();
664
+ function register(...args) {
665
+ if (args.length === 1 && typeof args[0] === "object" && !Array.isArray(args[0])) Object.entries(args[0]).forEach(([_, processor]) => {
666
+ processors.set(processor.canHandle, processor);
667
+ });
668
+ else args.forEach((p) => processors.set(p.canHandle, p));
669
+ return registry;
670
+ }
671
+ const registry = {
672
+ register,
673
+ get: (tokenType) => {
674
+ return processors.get(tokenType) ?? null;
675
+ },
676
+ all: () => processors
677
+ };
678
+ return registry;
679
+ };
680
+
681
+ //#endregion
682
+ //#region src/core/sql/processors/columnProcessors.ts
683
+ const mapDefaultSQLColumnProcessors = (mapColumnType) => ({
684
+ AutoIncrement: SQLProcessor({
685
+ canHandle: "SQL_COLUMN_AUTO_INCREMENT",
686
+ handle: (token, context) => {
687
+ mapColumnType(token, context);
688
+ }
689
+ }),
690
+ BigInteger: SQLProcessor({
691
+ canHandle: "SQL_COLUMN_BIGINT",
692
+ handle: (token, context) => mapColumnType(token, context)
693
+ }),
694
+ BigSerial: SQLProcessor({
695
+ canHandle: "SQL_COLUMN_BIGSERIAL",
696
+ handle: (token, context) => mapColumnType(token, context)
697
+ }),
698
+ Serial: SQLProcessor({
699
+ canHandle: "SQL_COLUMN_SERIAL",
700
+ handle: (token, context) => mapColumnType(token, context)
701
+ }),
702
+ Integer: SQLProcessor({
703
+ canHandle: "SQL_COLUMN_INTEGER",
704
+ handle: (token, context) => mapColumnType(token, context)
705
+ }),
706
+ JSONB: SQLProcessor({
707
+ canHandle: "SQL_COLUMN_JSONB",
708
+ handle: (token, context) => mapColumnType(token, context)
709
+ }),
710
+ Timestamp: SQLProcessor({
711
+ canHandle: "SQL_COLUMN_TIMESTAMP",
712
+ handle: (token, context) => mapColumnType(token, context)
713
+ }),
714
+ Timestamptz: SQLProcessor({
715
+ canHandle: "SQL_COLUMN_TIMESTAMPTZ",
716
+ handle: (token, context) => mapColumnType(token, context)
717
+ }),
718
+ Varchar: SQLProcessor({
719
+ canHandle: "SQL_COLUMN_VARCHAR",
720
+ handle: (token, context) => mapColumnType(token, context)
721
+ })
722
+ });
723
+
724
+ //#endregion
725
+ //#region src/core/sql/processors/index.ts
726
+ const defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry = globalThis.defaultProcessorsRegistry ?? SQLProcessorsRegistry().register(FormatIdentifierProcessor, MapLiteralProcessor, ExpandArrayProcessor, ExpandSQLInProcessor);
727
+
728
+ //#endregion
729
+ //#region src/core/sql/tokenizedSQL/tokenizedSQL.ts
730
+ const TokenizedSQLBuilder = () => {
731
+ const sqlChunks = [];
732
+ const sqlTokens = [];
733
+ return {
734
+ addSQL(str) {
735
+ sqlChunks.push(str);
736
+ },
737
+ addSQLs(str) {
738
+ sqlChunks.push(...str);
739
+ },
740
+ addToken(value) {
741
+ sqlTokens.push(value);
742
+ },
743
+ addTokens(vals) {
744
+ sqlTokens.push(...vals);
745
+ },
746
+ build() {
747
+ return sqlChunks.length > 0 ? {
748
+ __brand: "tokenized-sql",
749
+ sqlChunks,
750
+ sqlTokens
751
+ } : TokenizedSQL.empty;
752
+ }
753
+ };
754
+ };
755
+ const TokenizedSQL = (strings, values) => {
756
+ const builder = TokenizedSQLBuilder();
757
+ for (let i = 0; i < strings.length; i++) {
758
+ if (strings[i] !== "") builder.addSQL(strings[i]);
759
+ if (i >= values.length) break;
760
+ const value = values[i];
761
+ if (isTokenizedSQL(value)) {
762
+ builder.addSQLs(value.sqlChunks);
763
+ builder.addTokens(value.sqlTokens);
764
+ } else if (SQLPlain.check(value)) builder.addSQL(value.value);
765
+ else {
766
+ builder.addSQL(TokenizedSQL.paramPlaceholder);
767
+ builder.addToken(SQLToken.check(value) ? value : Array.isArray(value) ? SQLArray.from(value) : SQLLiteral.from(value));
768
+ }
769
+ }
770
+ return builder.build();
771
+ };
772
+ const isTokenizedSQL = (value) => {
773
+ return value !== null && typeof value === "object" && "__brand" in value && value.__brand === "tokenized-sql";
774
+ };
775
+ TokenizedSQL.paramPlaceholder = `__P__`;
776
+ TokenizedSQL.empty = {
777
+ __brand: "tokenized-sql",
778
+ sqlChunks: [""],
779
+ sqlTokens: []
780
+ };
781
+
782
+ //#endregion
783
+ //#region src/core/sql/sql.ts
784
+ function SQL(strings, ...values) {
785
+ return TokenizedSQL(strings, values);
786
+ }
787
+ function RawSQL(strings, ...values) {
788
+ let result = "";
789
+ for (let i = 0; i < strings.length; i++) {
790
+ result += strings[i];
791
+ if (i < values.length) result += String(values[i]);
792
+ }
793
+ return {
794
+ __brand: "tokenized-sql",
795
+ sqlChunks: [result],
796
+ sqlTokens: []
797
+ };
798
+ }
799
+ const isSQL = (value) => {
800
+ if (value === void 0 || value === null) return false;
801
+ return isTokenizedSQL(value);
802
+ };
803
+ const emptySQL = {
804
+ __brand: "tokenized-sql",
805
+ sqlChunks: [""],
806
+ sqlTokens: []
807
+ };
808
+ const mergeSQL = (sqls, separator = " ") => {
809
+ const parametrized = sqls.filter((sql) => !isEmpty(sql)).map((sql) => sql);
810
+ const params = parametrized.flatMap((p) => p.sqlTokens);
811
+ const sqlChunks = parametrized.flatMap((p, i) => i == parametrized.length - 1 || separator === "" ? p.sqlChunks : [...p.sqlChunks, separator]);
812
+ return sqlChunks.length > 0 ? {
813
+ __brand: "tokenized-sql",
814
+ sqlChunks,
815
+ sqlTokens: params
816
+ } : TokenizedSQL.empty;
817
+ };
818
+ const concatSQL = (...sqls) => mergeSQL(sqls, "");
819
+ const isEmpty = (sql) => {
820
+ if (isTokenizedSQL(sql)) {
821
+ const parametrized = sql;
822
+ return parametrized.sqlChunks.every((chunk) => chunk.trim() === "") && parametrized.sqlTokens.length === 0;
823
+ }
824
+ return false;
825
+ };
826
+ SQL.EMPTY = emptySQL;
827
+ SQL.concat = concatSQL;
828
+ SQL.merge = mergeSQL;
829
+ SQL.format = (sql, formatter, options) => formatSQL(sql, formatter, options?.serializer ?? JSONSerializer, options);
830
+ SQL.describe = (sql, formatter, options) => describeSQL(sql, formatter, options?.serializer ?? JSONSerializer, options);
831
+ SQL.in = (column, values, options) => options?.mode ? SQLIn.from({
832
+ column,
833
+ values,
834
+ mode: options.mode
835
+ }) : SQLIn.from({
836
+ column,
837
+ values
838
+ });
839
+ SQL.array = (values, options) => SQLArray.from(options?.mode ? {
840
+ value: values,
841
+ mode: options.mode
842
+ } : values);
843
+ SQL.identifier = SQLIdentifier.from;
844
+ SQL.plain = SQLPlain.from;
845
+ SQL.check = {
846
+ isSQL,
847
+ isTokenizedSQL: (value) => isTokenizedSQL(value),
848
+ isEmpty,
849
+ isIdentifier: SQLIdentifier.check,
850
+ isPlain: SQLPlain.check,
851
+ isSQLIn: SQLIn.check
852
+ };
853
+ const columnFactory = SQLColumnToken.from;
854
+ columnFactory.type = SQLColumnTypeTokensFactory;
855
+ SQL.column = columnFactory;
856
+
857
+ //#endregion
858
+ //#region src/core/sql/valueMappers/reservedSqlWords.ts
859
+ const ansiSqlReservedMap = {
860
+ ALL: true,
861
+ AND: true,
862
+ ANY: true,
863
+ ARRAY: true,
864
+ AS: true,
865
+ ASC: true,
866
+ AUTHORIZATION: true,
867
+ BETWEEN: true,
868
+ BINARY: true,
869
+ BOTH: true,
870
+ CASE: true,
871
+ CAST: true,
872
+ CHECK: true,
873
+ COLLATE: true,
874
+ COLUMN: true,
875
+ CONSTRAINT: true,
876
+ CREATE: true,
877
+ CROSS: true,
878
+ CURRENT_DATE: true,
879
+ CURRENT_TIME: true,
880
+ CURRENT_TIMESTAMP: true,
881
+ CURRENT_USER: true,
882
+ DEFAULT: true,
883
+ DEFERRABLE: true,
884
+ DESC: true,
885
+ DISTINCT: true,
886
+ DO: true,
887
+ ELSE: true,
888
+ END: true,
889
+ EXCEPT: true,
890
+ FALSE: true,
891
+ FOR: true,
892
+ FOREIGN: true,
893
+ FROM: true,
894
+ FULL: true,
895
+ GRANT: true,
896
+ GROUP: true,
897
+ HAVING: true,
898
+ IN: true,
899
+ INITIALLY: true,
900
+ INNER: true,
901
+ INTERSECT: true,
902
+ INTO: true,
903
+ IS: true,
904
+ JOIN: true,
905
+ LEADING: true,
906
+ LEFT: true,
907
+ LIKE: true,
908
+ LOCALTIME: true,
909
+ LOCALTIMESTAMP: true,
910
+ NATURAL: true,
911
+ NEW: true,
912
+ NOT: true,
913
+ NULL: true,
914
+ NULLS: true,
915
+ OLD: true,
916
+ ON: true,
917
+ ONLY: true,
918
+ OPEN: true,
919
+ OR: true,
920
+ ORDER: true,
921
+ OUTER: true,
922
+ OVERLAPS: true,
923
+ PARTITION: true,
924
+ PLACING: true,
925
+ PRIMARY: true,
926
+ REFERENCES: true,
927
+ RIGHT: true,
928
+ SELECT: true,
929
+ SESSION_USER: true,
930
+ SIMILAR: true,
931
+ SOME: true,
932
+ TABLE: true,
933
+ THEN: true,
934
+ TO: true,
935
+ TRAILING: true,
936
+ TRUE: true,
937
+ UNION: true,
938
+ UNIQUE: true,
939
+ USER: true,
940
+ USING: true,
941
+ WHEN: true,
942
+ WHERE: true,
943
+ WITH: true,
944
+ WITHOUT: true,
945
+ ADD: true,
946
+ ALTER: true,
947
+ ARE: true,
948
+ AT: true,
949
+ BEGIN: true,
950
+ BY: true,
951
+ CASCADE: true,
952
+ CLOSE: true,
953
+ COMMIT: true,
954
+ CONNECT: true,
955
+ CONTINUE: true,
956
+ CORRESPONDING: true,
957
+ CURSOR: true,
958
+ DEALLOCATE: true,
959
+ DECLARE: true,
960
+ DELETE: true,
961
+ DESCRIBE: true,
962
+ DISCONNECT: true,
963
+ DROP: true,
964
+ ESCAPE: true,
965
+ EXECUTE: true,
966
+ EXISTS: true,
967
+ FETCH: true,
968
+ FIRST: true,
969
+ FLOAT: true,
970
+ GET: true,
971
+ GLOBAL: true,
972
+ GO: true,
973
+ GOTO: true,
974
+ HOUR: true,
975
+ IMMEDIATE: true,
976
+ INDICATOR: true,
977
+ INPUT: true,
978
+ INSERT: true,
979
+ INT: true,
980
+ INTEGER: true,
981
+ INTERVAL: true,
982
+ LANGUAGE: true,
983
+ LAST: true,
984
+ LOCAL: true,
985
+ MATCH: true,
986
+ MINUTE: true,
987
+ MODULE: true,
988
+ MONTH: true,
989
+ NATIONAL: true,
990
+ NEXT: true,
991
+ NO: true,
992
+ OF: true,
993
+ OUTPUT: true,
994
+ PARTIAL: true,
995
+ PREPARE: true,
996
+ PRESERVE: true,
997
+ PRIOR: true,
998
+ PRIVILEGES: true,
999
+ PROCEDURE: true,
1000
+ PUBLIC: true,
1001
+ READ: true,
1002
+ REAL: true,
1003
+ RESTRICT: true,
1004
+ REVOKE: true,
1005
+ ROLLBACK: true,
1006
+ ROWS: true,
1007
+ SCHEMA: true,
1008
+ SCROLL: true,
1009
+ SECOND: true,
1010
+ SECTION: true,
1011
+ SET: true,
1012
+ SIZE: true,
1013
+ SMALLINT: true,
1014
+ SQL: true,
1015
+ SQLCODE: true,
1016
+ SQLERROR: true,
1017
+ SQLSTATE: true,
1018
+ TEMPORARY: true,
1019
+ TIMEZONE_HOUR: true,
1020
+ TIMEZONE_MINUTE: true,
1021
+ TRANSACTION: true,
1022
+ TRANSLATE: true,
1023
+ TRANSLATION: true,
1024
+ UNKNOWN: true,
1025
+ UPDATE: true,
1026
+ VALUE: true,
1027
+ VALUES: true,
1028
+ VARCHAR: true,
1029
+ VARYING: true,
1030
+ VIEW: true,
1031
+ WHENEVER: true,
1032
+ WORK: true,
1033
+ WRITE: true,
1034
+ YEAR: true,
1035
+ ZONE: true
1036
+ };
1037
+
1038
+ //#endregion
1039
+ //#region src/core/sql/valueMappers/sqlValueMapper.ts
1040
+ const ANSISQLParamPlaceholder = "?";
1041
+ const ANSISQLIdentifierQuote = "\"";
1042
+ const mapANSISQLParamPlaceholder = () => "?";
1043
+ const isReserved = (value, reserved) => !!reserved[value.toUpperCase()];
1044
+ const mapSQLIdentifier = (value, options) => {
1045
+ if (value === void 0 || value === null) throw new Error("SQL identifier cannot be null or undefined");
1046
+ const ident = value.toString().slice(0);
1047
+ const quoteSign = options?.quote ?? "\"";
1048
+ if (/^[a-z_][a-z0-9_$]*$/.test(ident) && !isReserved(ident, options?.reservedWords ?? ansiSqlReservedMap)) return ident;
1049
+ let quoted = quoteSign;
1050
+ for (let i = 0; i < ident.length; i++) {
1051
+ const c = ident[i];
1052
+ quoted += c === quoteSign ? c + c : c;
1053
+ }
1054
+ quoted += quoteSign;
1055
+ return quoted;
1056
+ };
1057
+ const DefaultMapSQLParamValueOptions = {
1058
+ mapPlaceholder: mapANSISQLParamPlaceholder,
1059
+ mapIdentifier: mapSQLIdentifier
1060
+ };
1061
+ const SQLValueMapper = (options) => {
1062
+ const mapSQLParamValueOptions = {
1063
+ ...DefaultMapSQLParamValueOptions,
1064
+ ...options ?? {}
1065
+ };
1066
+ return {
1067
+ mapValue: (value, serializer, mapOptions) => mapSQLParamValue(value, serializer, {
1068
+ ...mapSQLParamValueOptions,
1069
+ ...mapOptions
1070
+ }),
1071
+ mapPlaceholder: mapSQLParamValueOptions.mapPlaceholder,
1072
+ mapIdentifier: mapSQLParamValueOptions.mapIdentifier
1073
+ };
1074
+ };
1075
+ function mapSQLParamValue(value, serializer, options) {
1076
+ if (value === null || value === void 0) return null;
1077
+ else if (typeof value === "number") return value;
1078
+ else if (typeof value === "string") return value;
1079
+ else if (Array.isArray(value)) {
1080
+ const mapValue = options?.mapValue ?? mapSQLParamValue;
1081
+ return options?.mapArray ? options.mapArray(value, mapValue) : value.map((item) => mapValue(item, serializer, options));
1082
+ } else if (typeof value === "boolean") return options?.mapBoolean ? options.mapBoolean(value) : value;
1083
+ else if (typeof value === "bigint") return options?.mapBigInt ? options.mapBigInt(value) : value.toString();
1084
+ else if (value instanceof Date) return options?.mapDate ? options.mapDate(value) : value.toISOString();
1085
+ else if (SQL.check.isIdentifier(value)) return (options?.mapIdentifier ?? mapSQLIdentifier)(value.value);
1086
+ else if (typeof value === "object") return options?.mapObject ? options.mapObject(value) : `${serializer.serialize(value).replace(/'/g, "''")}`;
1087
+ else return serializer.serialize(value);
1088
+ }
1089
+
1090
+ //#endregion
1091
+ //#region src/core/sql/formatters/sqlFormatter.ts
1092
+ const SQLFormatter = ({ format, describe, valueMapper: valueMapperOptions, processorsRegistry }) => {
1093
+ const valueMapper = SQLValueMapper(valueMapperOptions);
1094
+ const options = {
1095
+ builder: ParametrizedSQLBuilder({ mapParamPlaceholder: valueMapper.mapPlaceholder }),
1096
+ mapper: valueMapper,
1097
+ processorsRegistry: processorsRegistry ?? defaultProcessorsRegistry
1098
+ };
1099
+ const resultFormatter = {
1100
+ format: format ?? ((sql, methodOptions) => formatSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
1101
+ ...options,
1102
+ ...methodOptions ?? {}
1103
+ })),
1104
+ describe: describe ?? ((sql, methodOptions) => describeSQL(sql, resultFormatter, methodOptions?.serializer ?? JSONSerializer, {
1105
+ ...options,
1106
+ ...methodOptions ?? {}
1107
+ })),
1108
+ valueMapper
1109
+ };
1110
+ return resultFormatter;
1111
+ };
1112
+ const dumboSQLFormatters = globalThis.dumboSQLFormatters = globalThis.dumboSQLFormatters ?? {};
1113
+ const registerFormatter = (dialect, formatter) => {
1114
+ dumboSQLFormatters[dialect] = formatter;
1115
+ };
1116
+ const getFormatter = (dialect) => {
1117
+ const formatterKey = dialect;
1118
+ if (!dumboSQLFormatters[formatterKey]) throw new Error(`No SQL formatter registered for dialect: ${dialect}`);
1119
+ return dumboSQLFormatters[formatterKey];
1120
+ };
1121
+ function formatSQL(sql, formatter, serializer, context) {
1122
+ const mapper = context?.mapper == void 0 ? formatter.valueMapper : {
1123
+ ...formatter.valueMapper,
1124
+ ...context.mapper
1125
+ };
1126
+ const processorsRegistry = context?.processorsRegistry ?? defaultProcessorsRegistry;
1127
+ const merged = Array.isArray(sql) ? SQL.merge(sql, "\n") : sql;
1128
+ if (!isTokenizedSQL(merged)) throw new Error("Expected TokenizedSQL, got string-based SQL");
1129
+ const builder = ParametrizedSQLBuilder({ mapParamPlaceholder: mapper.mapPlaceholder });
1130
+ let paramIndex = 0;
1131
+ for (let i = 0; i < merged.sqlChunks.length; i++) {
1132
+ const sqlChunk = merged.sqlChunks[i];
1133
+ if (sqlChunk !== TokenizedSQL.paramPlaceholder) {
1134
+ builder.addSQL(sqlChunk);
1135
+ continue;
1136
+ }
1137
+ const token = merged.sqlTokens[paramIndex++];
1138
+ const processor = processorsRegistry.get(token.sqlTokenType);
1139
+ if (!processor) throw new Error(`No SQL processor registered for token type: ${token.sqlTokenType}`);
1140
+ processor.handle(token, {
1141
+ builder,
1142
+ processorsRegistry,
1143
+ serializer,
1144
+ mapper
1145
+ });
1146
+ }
1147
+ return builder.build();
1148
+ }
1149
+ const describeSQL = (sql, formatter, serializer, options) => formatSQL(sql, formatter, serializer, {
1150
+ ...options ?? {},
1151
+ mapper: { mapPlaceholder: (_, value) => serializer.serialize(value) }
1152
+ }).query;
1153
+
1154
+ //#endregion
1155
+ //#region src/core/tracing/printing/color.ts
1156
+ let enableColors = true;
1157
+ const color = {
1158
+ set level(value) {
1159
+ enableColors = value === 1;
1160
+ },
1161
+ hex: (value) => (text) => enableColors ? ansis.hex(value)(text) : text,
1162
+ red: (value) => enableColors ? ansis.red(value) : value,
1163
+ green: (value) => enableColors ? ansis.green(value) : value,
1164
+ blue: (value) => enableColors ? ansis.blue(value) : value,
1165
+ cyan: (value) => enableColors ? ansis.cyan(value) : value,
1166
+ yellow: (value) => enableColors ? ansis.yellow(value) : value
1167
+ };
1168
+
1169
+ //#endregion
1170
+ //#region src/core/tracing/printing/pretty.ts
1171
+ const TWO_SPACES = " ";
1172
+ const COLOR_STRING = color.hex("#98c379");
1173
+ const COLOR_KEY = color.hex("#61afef");
1174
+ const COLOR_NUMBER_OR_DATE = color.hex("#d19a66");
1175
+ const COLOR_BOOLEAN = color.hex("#c678dd");
1176
+ const COLOR_NULL_OR_UNDEFINED = color.hex("#c678dd");
1177
+ const COLOR_BRACKETS = color.hex("#abb2bf");
1178
+ const processString = (str, indent, handleMultiline) => {
1179
+ if (handleMultiline && str.includes("\n")) {
1180
+ const indentedLines = str.split("\n").map((line) => indent + TWO_SPACES + COLOR_STRING(line));
1181
+ return COLOR_STRING("\"") + "\n" + indentedLines.join("\n") + "\n" + indent + COLOR_STRING("\"");
1182
+ }
1183
+ return COLOR_STRING(`"${str}"`);
1184
+ };
1185
+ const shouldPrint = (obj) => typeof obj !== "function" && typeof obj !== "symbol";
1186
+ const formatJson = (obj, indentLevel = 0, handleMultiline = false) => {
1187
+ const indent = TWO_SPACES.repeat(indentLevel);
1188
+ if (obj === null) return COLOR_NULL_OR_UNDEFINED("null");
1189
+ if (obj === void 0) return COLOR_NULL_OR_UNDEFINED("undefined");
1190
+ if (typeof obj === "string") return processString(obj, indent, handleMultiline);
1191
+ if (typeof obj === "number" || typeof obj === "bigint" || obj instanceof Date) return COLOR_NUMBER_OR_DATE(String(obj));
1192
+ if (typeof obj === "boolean") return COLOR_BOOLEAN(String(obj));
1193
+ if (obj instanceof Error) {
1194
+ const errorObj = {};
1195
+ Object.getOwnPropertyNames(obj).forEach((key) => {
1196
+ errorObj[key] = obj[key];
1197
+ });
1198
+ return formatJson(errorObj, indentLevel, handleMultiline);
1199
+ }
1200
+ if (obj instanceof Promise) return COLOR_STRING("Promise {pending}");
1201
+ if (Array.isArray(obj)) {
1202
+ const arrayItems = obj.map((item) => formatJson(item, indentLevel + 1, handleMultiline));
1203
+ return `${COLOR_BRACKETS("[")}\n${indent} ${arrayItems.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("]")}`;
1204
+ }
1205
+ const entries = Object.entries(obj).filter(([_, value]) => shouldPrint(value)).map(([key, value]) => `${COLOR_KEY(`"${key}"`)}: ${formatJson(value, indentLevel + 1, handleMultiline)}`);
1206
+ return `${COLOR_BRACKETS("{")}\n${indent} ${entries.join(`,\n${indent} `)}\n${indent}${COLOR_BRACKETS("}")}`;
1207
+ };
1208
+ const prettyJson = (obj, options) => formatJson(obj, 0, options?.handleMultiline);
1209
+
1210
+ //#endregion
1211
+ //#region src/core/tracing/index.ts
1212
+ const tracer = () => {};
1213
+ const LogLevel = {
1214
+ DISABLED: "DISABLED",
1215
+ INFO: "INFO",
1216
+ LOG: "LOG",
1217
+ WARN: "WARN",
1218
+ ERROR: "ERROR"
1219
+ };
1220
+ const LogStyle = {
1221
+ RAW: "RAW",
1222
+ PRETTY: "PRETTY"
1223
+ };
1224
+ const getEnvVariable = (name) => {
1225
+ try {
1226
+ if (typeof process !== "undefined" && process.env) return process.env[name];
1227
+ return;
1228
+ } catch {
1229
+ return;
1230
+ }
1231
+ };
1232
+ const shouldLog = (logLevel) => {
1233
+ const definedLogLevel = getEnvVariable("DUMBO_LOG_LEVEL") ?? LogLevel.ERROR;
1234
+ if (definedLogLevel === LogLevel.ERROR && logLevel === LogLevel.ERROR) return true;
1235
+ if (definedLogLevel === LogLevel.WARN && [LogLevel.ERROR, LogLevel.WARN].includes(logLevel)) return true;
1236
+ if (definedLogLevel === LogLevel.LOG && [
1237
+ LogLevel.ERROR,
1238
+ LogLevel.WARN,
1239
+ LogLevel.LOG
1240
+ ].includes(logLevel)) return true;
1241
+ if (definedLogLevel === LogLevel.INFO && [
1242
+ LogLevel.ERROR,
1243
+ LogLevel.WARN,
1244
+ LogLevel.LOG,
1245
+ LogLevel.INFO
1246
+ ].includes(logLevel)) return true;
1247
+ return false;
1248
+ };
1249
+ const nulloTraceEventRecorder = () => {};
1250
+ const getTraceEventFormatter = (logStyle, serializer = JSONSerializer) => (event) => {
1251
+ switch (logStyle) {
1252
+ case "RAW": return serializer.serialize(event);
1253
+ case "PRETTY": return prettyJson(event, { handleMultiline: true });
1254
+ }
1255
+ };
1256
+ const getTraceEventRecorder = (logLevel, logStyle) => {
1257
+ const format = getTraceEventFormatter(logStyle);
1258
+ switch (logLevel) {
1259
+ case "DISABLED": return nulloTraceEventRecorder;
1260
+ case "INFO": return (event) => console.info(format(event));
1261
+ case "LOG": return (event) => console.log(format(event));
1262
+ case "WARN": return (event) => console.warn(format(event));
1263
+ case "ERROR": return (event) => console.error(format(event));
1264
+ }
1265
+ };
1266
+ const recordTraceEvent = (logLevel, eventName, attributes) => {
1267
+ if (!shouldLog(LogLevel.LOG)) return;
1268
+ const event = {
1269
+ name: eventName,
1270
+ timestamp: (/* @__PURE__ */ new Date()).getTime(),
1271
+ ...attributes
1272
+ };
1273
+ getTraceEventRecorder(logLevel, getEnvVariable("DUMBO_LOG_STYLE") ?? "RAW")(event);
1274
+ };
1275
+ tracer.info = (eventName, attributes) => recordTraceEvent(LogLevel.INFO, eventName, attributes);
1276
+ tracer.warn = (eventName, attributes) => recordTraceEvent(LogLevel.WARN, eventName, attributes);
1277
+ tracer.log = (eventName, attributes) => recordTraceEvent(LogLevel.LOG, eventName, attributes);
1278
+ tracer.error = (eventName, attributes) => recordTraceEvent(LogLevel.ERROR, eventName, attributes);
1279
+
1280
+ //#endregion
1281
+ //#region src/core/schema/sqlMigration.ts
1282
+ const sqlMigration = (name, sqls) => ({
1283
+ name,
1284
+ sqls
1285
+ });
1286
+
1287
+ //#endregion
1288
+ //#region src/core/schema/migrators/schemaComponentMigrator.ts
1289
+ const { AutoIncrement, Varchar, Timestamp } = SQL.column.type;
1290
+ const migrationTableSQL = SQL`
1291
+ CREATE TABLE IF NOT EXISTS dmb_migrations (
1292
+ id ${AutoIncrement({ primaryKey: true })},
1293
+ name ${Varchar(255)} NOT NULL UNIQUE,
1294
+ application ${Varchar(255)} NOT NULL DEFAULT 'default',
1295
+ sql_hash ${Varchar(64)} NOT NULL,
1296
+ timestamp ${Timestamp} NOT NULL DEFAULT CURRENT_TIMESTAMP
1297
+ );
1298
+ `;
1299
+ const migrationTableSchemaComponent = schemaComponent("dumbo:schema-component:migrations-table", { migrations: [sqlMigration("dumbo:migrationTable:001", [migrationTableSQL])] });
1300
+ const SchemaComponentMigrator = (component, dumbo) => {
1301
+ const completedMigrations = [];
1302
+ return {
1303
+ component,
1304
+ run: async (options) => {
1305
+ const pendingMigrations = component.migrations.filter((m) => !completedMigrations.includes(`${component.schemaComponentKey}:${m.name}`));
1306
+ if (pendingMigrations.length === 0) return;
1307
+ await runSQLMigrations(dumbo, pendingMigrations, options);
1308
+ completedMigrations.push(...pendingMigrations.map((m) => `${component.schemaComponentKey}:${m.name}`));
1309
+ }
1310
+ };
1311
+ };
1312
+
1313
+ //#endregion
1314
+ //#region src/core/schema/migrators/migrator.ts
1315
+ const MIGRATIONS_LOCK_ID = 999956789;
1316
+ const defaultMigratorOptions = globalThis.defaultMigratorOptions = globalThis.defaultMigratorOptions ?? {};
1317
+ const registerDefaultMigratorOptions = (databaseType, options) => {
1318
+ defaultMigratorOptions[databaseType] = options;
1319
+ };
1320
+ const getDefaultMigratorOptionsFromRegistry = (databaseType) => {
1321
+ if (!defaultMigratorOptions[databaseType]) throw new Error(`No default migrator options registered for database type: ${databaseType}`);
1322
+ return defaultMigratorOptions[databaseType];
1323
+ };
1324
+ const runSQLMigrations = (pool, migrations, partialOptions) => pool.withTransaction(async ({ execute }) => {
1325
+ const databaseType = fromDatabaseDriverType(pool.driverType).databaseType;
1326
+ const defaultOptions = getDefaultMigratorOptionsFromRegistry(databaseType);
1327
+ partialOptions ??= {};
1328
+ const options = {
1329
+ ...defaultOptions,
1330
+ ...partialOptions,
1331
+ schema: {
1332
+ ...defaultOptions.schema,
1333
+ ...partialOptions?.schema ?? {}
1334
+ },
1335
+ lock: {
1336
+ ...defaultOptions.lock,
1337
+ ...partialOptions?.lock,
1338
+ options: {
1339
+ lockId: MIGRATIONS_LOCK_ID,
1340
+ ...defaultOptions.lock?.options,
1341
+ ...partialOptions?.lock?.options
1342
+ }
1343
+ },
1344
+ dryRun: defaultOptions.dryRun ?? partialOptions?.dryRun,
1345
+ ignoreMigrationHashMismatch: defaultOptions.ignoreMigrationHashMismatch ?? partialOptions?.ignoreMigrationHashMismatch,
1346
+ migrationTimeoutMs: defaultOptions.migrationTimeoutMs ?? partialOptions?.migrationTimeoutMs
1347
+ };
1348
+ const { databaseLock: _, ...rest } = options.lock ?? {};
1349
+ const databaseLock = options.lock?.databaseLock ?? NoDatabaseLock;
1350
+ const lockOptions = {
1351
+ lockId: MIGRATIONS_LOCK_ID,
1352
+ ...rest
1353
+ };
1354
+ const coreMigrations = (options.schema?.migrationTable ?? migrationTableSchemaComponent).migrations;
1355
+ const result = {
1356
+ applied: [],
1357
+ skipped: []
1358
+ };
1359
+ await databaseLock.withAcquire(execute, async () => {
1360
+ for (const migration of coreMigrations) await execute.batchCommand(migration.sqls, { timeoutMs: options.migrationTimeoutMs });
1361
+ for (const migration of migrations) if (await runSQLMigration(databaseType, execute, migration, {
1362
+ ignoreMigrationHashMismatch: options.ignoreMigrationHashMismatch ?? false,
1363
+ migrationTimeoutMs: options.migrationTimeoutMs
1364
+ })) result.applied.push(migration);
1365
+ else result.skipped.push(migration);
1366
+ }, lockOptions);
1367
+ return {
1368
+ success: options.dryRun ? false : true,
1369
+ result
1370
+ };
1371
+ });
1372
+ const runSQLMigration = async (databaseType, execute, migration, options) => {
1373
+ const sqls = combineMigrations(migration);
1374
+ const sqlHash = await getMigrationHash(migration, getFormatter(databaseType));
1375
+ try {
1376
+ const newMigration = {
1377
+ name: migration.name,
1378
+ sqlHash
1379
+ };
1380
+ const checkResult = await ensureMigrationWasNotAppliedYet(execute, newMigration);
1381
+ if (checkResult.exists === true) {
1382
+ if (checkResult.hashesMatch === true) {
1383
+ tracer.info("migration-already-applied", { migrationName: migration.name });
1384
+ return false;
1385
+ }
1386
+ if (options?.ignoreMigrationHashMismatch !== true) throw new Error(`Migration hash mismatch for "${migration.name}". Aborting migration.`);
1387
+ tracer.warn("migration-hash-mismatch", {
1388
+ migrationName: migration.name,
1389
+ expectedHash: sqlHash,
1390
+ actualHash: checkResult.hashFromDB
1391
+ });
1392
+ await updateMigrationHash(execute, newMigration);
1393
+ return false;
1394
+ }
1395
+ await execute.batchCommand(sqls, { timeoutMs: options?.migrationTimeoutMs });
1396
+ await recordMigration(execute, newMigration);
1397
+ return true;
1398
+ } catch (error) {
1399
+ tracer.error("migration-error", {
1400
+ migationName: migration.name,
1401
+ error
1402
+ });
1403
+ throw error;
1404
+ }
1405
+ };
1406
+ const getMigrationHash = async (sqlMigration, sqlFormatter) => {
1407
+ const content = sqlFormatter.describe(sqlMigration.sqls, { serializer: JSONSerializer });
1408
+ const data = new TextEncoder().encode(content);
1409
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
1410
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
1411
+ };
1412
+ const combineMigrations = (...migration) => migration.flatMap((m) => m.sqls);
1413
+ const ensureMigrationWasNotAppliedYet = async (execute, migration) => {
1414
+ const result = await singleOrNull(execute.query(SQL`SELECT sql_hash as "sqlHash" FROM dmb_migrations WHERE name = ${migration.name}`));
1415
+ if (result === null) return { exists: false };
1416
+ const { sqlHash } = result;
1417
+ return {
1418
+ exists: true,
1419
+ hashesMatch: sqlHash === migration.sqlHash,
1420
+ hashFromDB: sqlHash
1421
+ };
1422
+ };
1423
+ const recordMigration = async (execute, migration) => {
1424
+ await execute.command(SQL`
1425
+ INSERT INTO dmb_migrations (name, sql_hash)
1426
+ VALUES (${migration.name}, ${migration.sqlHash})`);
1427
+ };
1428
+ const updateMigrationHash = async (execute, migration) => {
1429
+ await execute.command(SQL`
1430
+ UPDATE dmb_migrations
1431
+ SET sql_hash = ${migration.sqlHash}, timestamp = ${/* @__PURE__ */ new Date()}
1432
+ WHERE name = ${migration.name}
1433
+ `);
1434
+ };
1435
+
1436
+ //#endregion
1437
+ //#region src/core/errors/index.ts
1438
+ const isNumber = (val) => typeof val === "number" && val === val;
1439
+ const isString = (val) => typeof val === "string";
1440
+ var DumboError = class DumboError extends Error {
1441
+ static ErrorCode = 500;
1442
+ static ErrorType = "DumboError";
1443
+ errorCode;
1444
+ errorType;
1445
+ innerError;
1446
+ constructor(options) {
1447
+ const errorCode = options && typeof options === "object" && "errorCode" in options ? options.errorCode : isNumber(options) ? options : DumboError.ErrorCode;
1448
+ const errorType = options && typeof options === "object" && "errorType" in options ? options.errorType ?? DumboError.ErrorType : DumboError.ErrorType;
1449
+ const message = options && typeof options === "object" && "message" in options ? options.message : isString(options) ? options : `Error with status code '${errorCode}' ocurred during DumboError processing`;
1450
+ const innerError = options && typeof options === "object" && "innerError" in options ? options.innerError : void 0;
1451
+ super(message, { cause: innerError });
1452
+ this.errorCode = errorCode;
1453
+ this.errorType = errorType;
1454
+ this.innerError = innerError;
1455
+ Object.setPrototypeOf(this, DumboError.prototype);
1456
+ }
1457
+ static isInstanceOf(error, options) {
1458
+ if (typeof error !== "object" || error === null || !("errorCode" in error) || !isNumber(error.errorCode) || !("errorType" in error) || !isString(error.errorType)) return false;
1459
+ if (!options) return true;
1460
+ if (options.errorCode !== void 0 && error.errorCode !== options.errorCode) return false;
1461
+ if (options.errorType !== void 0 && error.errorType !== options.errorType) return false;
1462
+ return true;
1463
+ }
1464
+ };
1465
+ var ConcurrencyError = class ConcurrencyError extends DumboError {
1466
+ static ErrorCode = 412;
1467
+ static ErrorType = "ConcurrencyError";
1468
+ constructor(message, innerError) {
1469
+ super({
1470
+ errorCode: ConcurrencyError.ErrorCode,
1471
+ errorType: ConcurrencyError.ErrorType,
1472
+ message: message ?? `Expected document state does not match current one!`,
1473
+ innerError
1474
+ });
1475
+ Object.setPrototypeOf(this, ConcurrencyError.prototype);
1476
+ }
1477
+ };
1478
+ var TransientDatabaseError = class TransientDatabaseError extends DumboError {
1479
+ static ErrorCode = 503;
1480
+ static ErrorType = "TransientDatabaseError";
1481
+ constructor(message, innerError) {
1482
+ super({
1483
+ errorCode: TransientDatabaseError.ErrorCode,
1484
+ errorType: TransientDatabaseError.ErrorType,
1485
+ message: message ?? `A transient error occurred during database operation. Retrying the operation might succeed.`,
1486
+ innerError
1487
+ });
1488
+ Object.setPrototypeOf(this, TransientDatabaseError.prototype);
1489
+ }
1490
+ };
1491
+ var ConnectionError = class ConnectionError extends TransientDatabaseError {
1492
+ static ErrorCode = 503;
1493
+ static ErrorType = "ConnectionError";
1494
+ constructor(message, innerError) {
1495
+ super(message ?? `A connection error occurred during database operation.`, innerError);
1496
+ this.errorType = ConnectionError.ErrorType;
1497
+ Object.setPrototypeOf(this, ConnectionError.prototype);
1498
+ }
1499
+ };
1500
+ var SerializationError = class SerializationError extends TransientDatabaseError {
1501
+ static ErrorCode = 503;
1502
+ static ErrorType = "SerializationError";
1503
+ constructor(message, innerError) {
1504
+ super(message ?? `A serialization failure occurred. The transaction can be retried.`, innerError);
1505
+ this.errorType = SerializationError.ErrorType;
1506
+ Object.setPrototypeOf(this, SerializationError.prototype);
1507
+ }
1508
+ };
1509
+ var DeadlockError = class DeadlockError extends TransientDatabaseError {
1510
+ static ErrorCode = 503;
1511
+ static ErrorType = "DeadlockError";
1512
+ constructor(message, innerError) {
1513
+ super(message ?? `A deadlock was detected. The transaction can be retried.`, innerError);
1514
+ this.errorType = DeadlockError.ErrorType;
1515
+ Object.setPrototypeOf(this, DeadlockError.prototype);
1516
+ }
1517
+ };
1518
+ var LockNotAvailableError = class LockNotAvailableError extends TransientDatabaseError {
1519
+ static ErrorCode = 503;
1520
+ static ErrorType = "LockNotAvailableError";
1521
+ constructor(message, innerError) {
1522
+ super(message ?? `The requested lock is not available.`, innerError);
1523
+ this.errorType = LockNotAvailableError.ErrorType;
1524
+ Object.setPrototypeOf(this, LockNotAvailableError.prototype);
1525
+ }
1526
+ };
1527
+ var InsufficientResourcesError = class InsufficientResourcesError extends TransientDatabaseError {
1528
+ static ErrorCode = 503;
1529
+ static ErrorType = "InsufficientResourcesError";
1530
+ constructor(message, innerError) {
1531
+ super(message ?? `Insufficient resources to complete the database operation (e.g. disk full, out of memory, too many connections).`, innerError);
1532
+ this.errorType = InsufficientResourcesError.ErrorType;
1533
+ Object.setPrototypeOf(this, InsufficientResourcesError.prototype);
1534
+ }
1535
+ };
1536
+ var SystemError = class SystemError extends TransientDatabaseError {
1537
+ static ErrorCode = 503;
1538
+ static ErrorType = "SystemError";
1539
+ constructor(message, innerError) {
1540
+ super(message ?? `A system-level error occurred (e.g. I/O error).`, innerError);
1541
+ this.errorType = SystemError.ErrorType;
1542
+ Object.setPrototypeOf(this, SystemError.prototype);
1543
+ }
1544
+ };
1545
+ var AdminShutdownError = class AdminShutdownError extends TransientDatabaseError {
1546
+ static ErrorCode = 503;
1547
+ static ErrorType = "AdminShutdownError";
1548
+ constructor(message, innerError) {
1549
+ super(message ?? `The database server is shutting down or restarting.`, innerError);
1550
+ this.errorType = AdminShutdownError.ErrorType;
1551
+ Object.setPrototypeOf(this, AdminShutdownError.prototype);
1552
+ }
1553
+ };
1554
+ var QueryCanceledError = class QueryCanceledError extends TransientDatabaseError {
1555
+ static ErrorCode = 503;
1556
+ static ErrorType = "QueryCanceledError";
1557
+ constructor(message, innerError) {
1558
+ super(message ?? `The query was canceled, e.g. due to statement timeout or user request.`, innerError);
1559
+ this.errorType = QueryCanceledError.ErrorType;
1560
+ Object.setPrototypeOf(this, QueryCanceledError.prototype);
1561
+ }
1562
+ };
1563
+ var IntegrityConstraintViolationError = class IntegrityConstraintViolationError extends DumboError {
1564
+ static ErrorCode = 409;
1565
+ static ErrorType = "IntegrityConstraintViolationError";
1566
+ constructor(message, innerError) {
1567
+ super({
1568
+ errorCode: IntegrityConstraintViolationError.ErrorCode,
1569
+ errorType: IntegrityConstraintViolationError.ErrorType,
1570
+ message: message ?? `An integrity constraint violation occurred!`,
1571
+ innerError
1572
+ });
1573
+ Object.setPrototypeOf(this, IntegrityConstraintViolationError.prototype);
1574
+ }
1575
+ };
1576
+ var UniqueConstraintError = class UniqueConstraintError extends IntegrityConstraintViolationError {
1577
+ static ErrorCode = 409;
1578
+ static ErrorType = "UniqueConstraintError";
1579
+ constructor(message, innerError) {
1580
+ super(message ?? `Unique constraint violation occurred!`, innerError);
1581
+ this.errorType = UniqueConstraintError.ErrorType;
1582
+ Object.setPrototypeOf(this, UniqueConstraintError.prototype);
1583
+ }
1584
+ };
1585
+ var ForeignKeyViolationError = class ForeignKeyViolationError extends IntegrityConstraintViolationError {
1586
+ static ErrorCode = 409;
1587
+ static ErrorType = "ForeignKeyViolationError";
1588
+ constructor(message, innerError) {
1589
+ super(message ?? `Foreign key constraint violation occurred!`, innerError);
1590
+ this.errorType = ForeignKeyViolationError.ErrorType;
1591
+ Object.setPrototypeOf(this, ForeignKeyViolationError.prototype);
1592
+ }
1593
+ };
1594
+ var NotNullViolationError = class NotNullViolationError extends IntegrityConstraintViolationError {
1595
+ static ErrorCode = 409;
1596
+ static ErrorType = "NotNullViolationError";
1597
+ constructor(message, innerError) {
1598
+ super(message ?? `NOT NULL constraint violation occurred!`, innerError);
1599
+ this.errorType = NotNullViolationError.ErrorType;
1600
+ Object.setPrototypeOf(this, NotNullViolationError.prototype);
1601
+ }
1602
+ };
1603
+ var CheckViolationError = class CheckViolationError extends IntegrityConstraintViolationError {
1604
+ static ErrorCode = 409;
1605
+ static ErrorType = "CheckViolationError";
1606
+ constructor(message, innerError) {
1607
+ super(message ?? `CHECK constraint violation occurred!`, innerError);
1608
+ this.errorType = CheckViolationError.ErrorType;
1609
+ Object.setPrototypeOf(this, CheckViolationError.prototype);
1610
+ }
1611
+ };
1612
+ var ExclusionViolationError = class ExclusionViolationError extends IntegrityConstraintViolationError {
1613
+ static ErrorCode = 409;
1614
+ static ErrorType = "ExclusionViolationError";
1615
+ constructor(message, innerError) {
1616
+ super(message ?? `Exclusion constraint violation occurred!`, innerError);
1617
+ this.errorType = ExclusionViolationError.ErrorType;
1618
+ Object.setPrototypeOf(this, ExclusionViolationError.prototype);
1619
+ }
1620
+ };
1621
+ var DataError = class DataError extends DumboError {
1622
+ static ErrorCode = 400;
1623
+ static ErrorType = "DataError";
1624
+ constructor(message, innerError) {
1625
+ super({
1626
+ errorCode: DataError.ErrorCode,
1627
+ errorType: DataError.ErrorType,
1628
+ message: message ?? `A data error occurred (e.g. invalid value, type mismatch).`,
1629
+ innerError
1630
+ });
1631
+ Object.setPrototypeOf(this, DataError.prototype);
1632
+ }
1633
+ };
1634
+ var InvalidOperationError = class InvalidOperationError extends DumboError {
1635
+ static ErrorCode = 400;
1636
+ static ErrorType = "InvalidOperationError";
1637
+ constructor(message, innerError) {
1638
+ super({
1639
+ errorCode: InvalidOperationError.ErrorCode,
1640
+ errorType: InvalidOperationError.ErrorType,
1641
+ message: message ?? `Invalid operation (e.g. syntax error, insufficient privileges, undefined table).`,
1642
+ innerError
1643
+ });
1644
+ Object.setPrototypeOf(this, InvalidOperationError.prototype);
1645
+ }
1646
+ };
1647
+
1648
+ //#endregion
1649
+ //#region src/core/execute/execute.ts
1650
+ const mapColumnToJSON = (column, serializer, options) => ({ [column]: (value) => {
1651
+ if (typeof value === "string") try {
1652
+ return serializer.deserialize(value, options);
1653
+ } catch {}
1654
+ return value;
1655
+ } });
1656
+ const mapColumnToBigint = (column) => ({ [column]: (value) => {
1657
+ if (typeof value === "number" || typeof value === "string") return BigInt(value);
1658
+ return value;
1659
+ } });
1660
+ const mapColumnToDate = (column) => ({ [column]: (value) => {
1661
+ if (typeof value === "number" || typeof value === "string") return new Date(value);
1662
+ return value;
1663
+ } });
1664
+ const mapSQLQueryResult = (result, mapping) => {
1665
+ if (typeof result !== "object" || result === null) return result;
1666
+ const mappedResult = { ...result };
1667
+ for (const column of Object.keys(mapping)) if (column in mappedResult) mappedResult[column] = mapping[column](mappedResult[column]);
1668
+ return mappedResult;
1669
+ };
1670
+ var BatchCommandNoChangesError = class BatchCommandNoChangesError extends DumboError {
1671
+ statementIndex;
1672
+ constructor(statementIndex) {
1673
+ super({
1674
+ errorCode: 409,
1675
+ message: `Batch command at index ${statementIndex} affected no rows`
1676
+ });
1677
+ this.name = "BatchCommandNoChangesError";
1678
+ this.statementIndex = statementIndex;
1679
+ Object.setPrototypeOf(this, BatchCommandNoChangesError.prototype);
1680
+ }
1681
+ };
1682
+ const sqlExecutor = (sqlExecutor, options) => ({
1683
+ query: (sql, queryOptions) => executeInNewDbClient((client) => sqlExecutor.query(client, sql, queryOptions), options),
1684
+ batchQuery: (sqls, queryOptions) => executeInNewDbClient((client) => sqlExecutor.batchQuery(client, sqls, queryOptions), options),
1685
+ command: (sql, commandOptions) => executeInNewDbClient((client) => sqlExecutor.command(client, sql, commandOptions), options),
1686
+ batchCommand: (sqls, commandOptions) => executeInNewDbClient((client) => sqlExecutor.batchCommand(client, sqls, commandOptions), options)
1687
+ });
1688
+ const sqlExecutorInNewConnection = (options) => ({
1689
+ query: (sql, queryOptions) => executeInNewConnection((connection) => connection.execute.query(sql, queryOptions), options),
1690
+ batchQuery: (sqls, queryOptions) => executeInNewConnection((connection) => connection.execute.batchQuery(sqls, queryOptions), options),
1691
+ command: (sql, commandOptions) => executeInNewConnection((connection) => connection.execute.command(sql, commandOptions), options),
1692
+ batchCommand: (sqls, commandOptions) => executeInNewConnection((connection) => connection.execute.batchCommand(sqls, commandOptions), options)
1693
+ });
1694
+ const sqlExecutorInAmbientConnection = (options) => ({
1695
+ query: (sql, queryOptions) => executeInAmbientConnection((connection) => connection.execute.query(sql, queryOptions), options),
1696
+ batchQuery: (sqls, queryOptions) => executeInAmbientConnection((connection) => connection.execute.batchQuery(sqls, queryOptions), options),
1697
+ command: (sql, commandOptions) => executeInAmbientConnection((connection) => connection.execute.command(sql, commandOptions), options),
1698
+ batchCommand: (sqls, commandOptions) => executeInAmbientConnection((connection) => connection.execute.batchCommand(sqls, commandOptions), options)
1699
+ });
1700
+ const executeInNewDbClient = async (handle, options) => {
1701
+ const { connect, close } = options;
1702
+ const client = await connect();
1703
+ try {
1704
+ return await handle(client);
1705
+ } catch (error) {
1706
+ if (close) await close(client, error);
1707
+ throw error;
1708
+ }
1709
+ };
1710
+ const executeInNewConnection = async (handle, options) => {
1711
+ const connection = await options.connection();
1712
+ try {
1713
+ return await handle(connection);
1714
+ } finally {
1715
+ await connection.close();
1716
+ }
1717
+ };
1718
+ const executeInAmbientConnection = async (handle, options) => {
1719
+ const connection = await options.connection();
1720
+ try {
1721
+ return await handle(connection);
1722
+ } finally {}
1723
+ };
1724
+
1725
+ //#endregion
1726
+ //#region src/core/connections/transaction.ts
1727
+ const toTransactionResult = (transactionResult) => transactionResult !== void 0 && transactionResult !== null && typeof transactionResult === "object" && "success" in transactionResult ? transactionResult : {
1728
+ success: true,
1729
+ result: transactionResult
1730
+ };
1731
+ const executeInTransaction = async (transaction, handle) => {
1732
+ await transaction.begin();
1733
+ try {
1734
+ const { success, result } = toTransactionResult(await handle(transaction));
1735
+ if (success) await transaction.commit();
1736
+ else await transaction.rollback();
1737
+ return result;
1738
+ } catch (e) {
1739
+ await transaction.rollback();
1740
+ throw e;
1741
+ }
1742
+ };
1743
+ const transactionFactoryWithDbClient = (connect, initTransaction) => {
1744
+ let currentTransaction = void 0;
1745
+ const getOrInitCurrentTransaction = (options) => currentTransaction ?? (currentTransaction = initTransaction(connect(), {
1746
+ close: () => {
1747
+ currentTransaction = void 0;
1748
+ return Promise.resolve();
1749
+ },
1750
+ ...options ?? {}
1751
+ }));
1752
+ return {
1753
+ transaction: getOrInitCurrentTransaction,
1754
+ withTransaction: (handle, options) => executeInTransaction(getOrInitCurrentTransaction(options), handle)
1755
+ };
1756
+ };
1757
+ const wrapInConnectionClosure = async (connection, handle) => {
1758
+ try {
1759
+ return await handle();
1760
+ } finally {
1761
+ await connection.close();
1762
+ }
1763
+ };
1764
+ const transactionFactoryWithNewConnection = (connect) => ({
1765
+ transaction: (options) => {
1766
+ const connection = connect();
1767
+ const transaction = connection.transaction(options);
1768
+ return {
1769
+ ...transaction,
1770
+ commit: () => wrapInConnectionClosure(connection, () => transaction.commit()),
1771
+ rollback: () => wrapInConnectionClosure(connection, () => transaction.rollback())
1772
+ };
1773
+ },
1774
+ withTransaction: (handle, options) => {
1775
+ const connection = connect();
1776
+ const withTx = connection.withTransaction;
1777
+ return wrapInConnectionClosure(connection, () => withTx(handle, options));
1778
+ }
1779
+ });
1780
+ const transactionFactoryWithAmbientConnection = (connect) => ({
1781
+ transaction: (options) => {
1782
+ const transaction = connect().transaction(options);
1783
+ return {
1784
+ ...transaction,
1785
+ commit: () => transaction.commit(),
1786
+ rollback: () => transaction.rollback()
1787
+ };
1788
+ },
1789
+ withTransaction: (handle, options) => {
1790
+ const withTx = connect().withTransaction;
1791
+ return withTx(handle, options);
1792
+ }
1793
+ });
1794
+ const transactionFactoryWithAsyncAmbientConnection = (driverType, connect, close) => {
1795
+ close ??= () => Promise.resolve();
1796
+ return {
1797
+ transaction: (options) => {
1798
+ let conn = null;
1799
+ let innerTx = null;
1800
+ let connectingPromise = null;
1801
+ const ensureConnection = async () => {
1802
+ if (conn) return innerTx;
1803
+ if (!connectingPromise) connectingPromise = (async () => {
1804
+ conn = await connect();
1805
+ innerTx = conn.transaction(options);
1806
+ })();
1807
+ await connectingPromise;
1808
+ return innerTx;
1809
+ };
1810
+ return {
1811
+ driverType,
1812
+ get connection() {
1813
+ if (!conn) throw new Error("Transaction not started - call begin() first");
1814
+ return conn;
1815
+ },
1816
+ execute: {
1817
+ query: async (sql, queryOptions) => {
1818
+ return (await ensureConnection()).execute.query(sql, queryOptions);
1819
+ },
1820
+ batchQuery: async (sqls, queryOptions) => {
1821
+ return (await ensureConnection()).execute.batchQuery(sqls, queryOptions);
1822
+ },
1823
+ command: async (sql, commandOptions) => {
1824
+ return (await ensureConnection()).execute.command(sql, commandOptions);
1825
+ },
1826
+ batchCommand: async (sqls, commandOptions) => {
1827
+ return (await ensureConnection()).execute.batchCommand(sqls, commandOptions);
1828
+ }
1829
+ },
1830
+ begin: async () => {
1831
+ return (await ensureConnection()).begin();
1832
+ },
1833
+ commit: async () => {
1834
+ if (!innerTx) throw new Error("Transaction not started");
1835
+ try {
1836
+ return await innerTx.commit();
1837
+ } finally {
1838
+ if (conn) await close(conn);
1839
+ }
1840
+ },
1841
+ rollback: async (error) => {
1842
+ if (!innerTx) {
1843
+ if (conn) await close(conn);
1844
+ return;
1845
+ }
1846
+ try {
1847
+ return await innerTx.rollback(error);
1848
+ } finally {
1849
+ if (conn) await close(conn);
1850
+ }
1851
+ },
1852
+ _transactionOptions: void 0
1853
+ };
1854
+ },
1855
+ withTransaction: async (handle, options) => {
1856
+ const conn = await connect();
1857
+ try {
1858
+ const withTx = conn.withTransaction;
1859
+ return await withTx(handle, options);
1860
+ } finally {
1861
+ await close(conn);
1862
+ }
1863
+ }
1864
+ };
1865
+ };
1866
+
1867
+ //#endregion
1868
+ //#region src/core/connections/connection.ts
1869
+ const createAmbientConnection = (options) => {
1870
+ const { driverType, client, executor, initTransaction, serializer } = options;
1871
+ const clientPromise = Promise.resolve(client);
1872
+ const closePromise = Promise.resolve();
1873
+ const open = () => clientPromise;
1874
+ const close = () => closePromise;
1875
+ const typedConnection = {
1876
+ driverType,
1877
+ open,
1878
+ close,
1879
+ ...transactionFactoryWithDbClient(open, initTransaction(() => typedConnection)),
1880
+ execute: sqlExecutor(executor({ serializer }), { connect: open }),
1881
+ _transactionType: void 0
1882
+ };
1883
+ return typedConnection;
1884
+ };
1885
+ const createSingletonConnection = (options) => {
1886
+ const { driverType, connect, close, initTransaction, executor, serializer } = options;
1887
+ let client = null;
1888
+ let connectPromise = null;
1889
+ const getClient = async () => {
1890
+ if (client) return client;
1891
+ if (!connectPromise) connectPromise = connect().then((c) => {
1892
+ client = c;
1893
+ return c;
1894
+ });
1895
+ return connectPromise;
1896
+ };
1897
+ const typedConnection = {
1898
+ driverType,
1899
+ open: getClient,
1900
+ close: () => client ? close(client) : Promise.resolve(),
1901
+ ...transactionFactoryWithDbClient(getClient, initTransaction(() => typedConnection)),
1902
+ execute: sqlExecutor(executor({ serializer }), { connect: getClient }),
1903
+ _transactionType: void 0
1904
+ };
1905
+ return typedConnection;
1906
+ };
1907
+ const createTransientConnection = (options) => {
1908
+ const { driverType, open, close, initTransaction, executor, serializer } = options;
1909
+ const typedConnection = {
1910
+ driverType,
1911
+ open,
1912
+ close,
1913
+ ...transactionFactoryWithDbClient(open, initTransaction(() => typedConnection)),
1914
+ execute: sqlExecutor(executor({ serializer }), { connect: open }),
1915
+ _transactionType: void 0
1916
+ };
1917
+ return typedConnection;
1918
+ };
1919
+ const createConnection = (options) => {
1920
+ const { driverType, connect, close, initTransaction, executor, serializer } = options;
1921
+ let client = null;
1922
+ let connectPromise = null;
1923
+ const getClient = async () => {
1924
+ if (client) return client;
1925
+ if (!connectPromise) connectPromise = connect().then((c) => {
1926
+ client = c;
1927
+ return c;
1928
+ });
1929
+ return connectPromise;
1930
+ };
1931
+ const typedConnection = {
1932
+ driverType,
1933
+ open: getClient,
1934
+ close: () => client ? close(client) : Promise.resolve(),
1935
+ ...transactionFactoryWithDbClient(getClient, initTransaction(() => typedConnection)),
1936
+ execute: sqlExecutor(executor({ serializer }), { connect: getClient }),
1937
+ _transactionType: void 0
1938
+ };
1939
+ return typedConnection;
1940
+ };
1941
+
1942
+ //#endregion
1943
+ //#region src/core/taskProcessing/taskProcessor.ts
1944
+ var TaskProcessor = class {
1945
+ queue = [];
1946
+ isProcessing = false;
1947
+ activeTasks = 0;
1948
+ activeGroups = /* @__PURE__ */ new Set();
1949
+ options;
1950
+ stopped = false;
1951
+ constructor(options) {
1952
+ this.options = options;
1953
+ }
1954
+ enqueue(task, options) {
1955
+ if (this.stopped) return Promise.reject(new DumboError("TaskProcessor has been stopped"));
1956
+ if (this.queue.length >= this.options.maxQueueSize) return Promise.reject(new TransientDatabaseError("Too many pending connections. Please try again later."));
1957
+ return this.schedule(task, options);
1958
+ }
1959
+ waitForEndOfProcessing() {
1960
+ return this.schedule(({ ack }) => Promise.resolve(ack()));
1961
+ }
1962
+ async stop(options) {
1963
+ if (this.stopped) return;
1964
+ this.stopped = true;
1965
+ this.queue.length = 0;
1966
+ this.activeGroups.clear();
1967
+ if (!options?.force) await this.waitForEndOfProcessing();
1968
+ }
1969
+ schedule(task, options) {
1970
+ return promiseWithDeadline((resolve, reject) => {
1971
+ const taskWithContext = () => {
1972
+ return new Promise((resolveTask, failTask) => {
1973
+ task({ ack: resolveTask }).then(resolve).catch((err) => {
1974
+ failTask(err);
1975
+ reject(err);
1976
+ });
1977
+ });
1978
+ };
1979
+ this.queue.push({
1980
+ task: taskWithContext,
1981
+ options
1982
+ });
1983
+ if (!this.isProcessing) this.ensureProcessing();
1984
+ }, { deadline: this.options.maxTaskIdleTime });
1985
+ }
1986
+ ensureProcessing() {
1987
+ if (this.isProcessing) return;
1988
+ this.isProcessing = true;
1989
+ this.processQueue();
1990
+ }
1991
+ processQueue() {
1992
+ try {
1993
+ while (this.activeTasks < this.options.maxActiveTasks && this.queue.length > 0) {
1994
+ const item = this.takeFirstAvailableItem();
1995
+ if (item === null) return;
1996
+ const groupId = item.options?.taskGroupId;
1997
+ if (groupId) this.activeGroups.add(groupId);
1998
+ this.activeTasks++;
1999
+ this.executeItem(item);
2000
+ }
2001
+ } catch (error) {
2002
+ console.error(error);
2003
+ throw error;
2004
+ } finally {
2005
+ this.isProcessing = false;
2006
+ if (this.hasItemsToProcess() && this.activeTasks < this.options.maxActiveTasks) this.ensureProcessing();
2007
+ }
2008
+ }
2009
+ async executeItem({ task, options }) {
2010
+ try {
2011
+ await task();
2012
+ } finally {
2013
+ this.activeTasks--;
2014
+ if (options && options.taskGroupId) this.activeGroups.delete(options.taskGroupId);
2015
+ this.ensureProcessing();
2016
+ }
2017
+ }
2018
+ takeFirstAvailableItem = () => {
2019
+ const taskIndex = this.queue.findIndex((item) => !item.options?.taskGroupId || !this.activeGroups.has(item.options.taskGroupId));
2020
+ if (taskIndex === -1) return null;
2021
+ const [item] = this.queue.splice(taskIndex, 1);
2022
+ return item ?? null;
2023
+ };
2024
+ hasItemsToProcess = () => this.queue.findIndex((item) => !item.options?.taskGroupId || !this.activeGroups.has(item.options.taskGroupId)) !== -1;
2025
+ };
2026
+ const DEFAULT_PROMISE_DEADLINE = 2147483647;
2027
+ const promiseWithDeadline = (executor, options) => {
2028
+ return new Promise((resolve, reject) => {
2029
+ let taskStarted = false;
2030
+ let timeoutId = null;
2031
+ const deadline = options.deadline ?? DEFAULT_PROMISE_DEADLINE;
2032
+ timeoutId = setTimeout(() => {
2033
+ if (!taskStarted) reject(/* @__PURE__ */ new Error("Task was not started within the maximum waiting time"));
2034
+ }, deadline);
2035
+ timeoutId.unref();
2036
+ executor((value) => {
2037
+ taskStarted = true;
2038
+ if (timeoutId) clearTimeout(timeoutId);
2039
+ timeoutId = null;
2040
+ resolve(value);
2041
+ }, (reason) => {
2042
+ if (timeoutId) clearTimeout(timeoutId);
2043
+ timeoutId = null;
2044
+ reject(reason);
2045
+ });
2046
+ });
2047
+ };
2048
+
2049
+ //#endregion
2050
+ //#region src/core/taskProcessing/executionGuards.ts
2051
+ const guardBoundedAccess = (getResource, options) => {
2052
+ let isStopped = false;
2053
+ const taskProcessor = new TaskProcessor({
2054
+ maxActiveTasks: options.maxResources,
2055
+ maxQueueSize: options.maxQueueSize ?? 1e3
2056
+ });
2057
+ const resourcePool = [];
2058
+ const allResources = /* @__PURE__ */ new Set();
2059
+ const ackCallbacks = /* @__PURE__ */ new Map();
2060
+ const acquire = async () => taskProcessor.enqueue(async ({ ack }) => {
2061
+ try {
2062
+ let resource;
2063
+ if (options.reuseResources) resource = resourcePool.pop();
2064
+ if (!resource) {
2065
+ resource = await getResource();
2066
+ allResources.add(resource);
2067
+ }
2068
+ ackCallbacks.set(resource, ack);
2069
+ return resource;
2070
+ } catch (e) {
2071
+ ack();
2072
+ throw e;
2073
+ }
2074
+ });
2075
+ const release = (resource) => {
2076
+ const ack = ackCallbacks.get(resource);
2077
+ if (ack) {
2078
+ ackCallbacks.delete(resource);
2079
+ if (options.reuseResources) resourcePool.push(resource);
2080
+ ack();
2081
+ }
2082
+ };
2083
+ const execute = async (operation) => {
2084
+ const resource = await acquire();
2085
+ try {
2086
+ return await operation(resource);
2087
+ } finally {
2088
+ release(resource);
2089
+ }
2090
+ };
2091
+ return {
2092
+ acquire,
2093
+ release,
2094
+ execute,
2095
+ waitForIdle: () => taskProcessor.waitForEndOfProcessing(),
2096
+ stop: async (stopOptions) => {
2097
+ if (isStopped) return;
2098
+ isStopped = true;
2099
+ if (options?.closeResource) {
2100
+ const resources = [...allResources];
2101
+ allResources.clear();
2102
+ resourcePool.length = 0;
2103
+ await Promise.all(resources.map(async (resource) => await options.closeResource(resource)));
2104
+ }
2105
+ await taskProcessor.stop(stopOptions);
2106
+ }
2107
+ };
2108
+ };
2109
+ const guardInitializedOnce = (initialize, options) => {
2110
+ let initPromise = null;
2111
+ const taskProcessor = new TaskProcessor({
2112
+ maxActiveTasks: 1,
2113
+ maxQueueSize: options?.maxQueueSize ?? 1e3
2114
+ });
2115
+ const ensureInitialized = async (retryCount = 0) => {
2116
+ if (initPromise !== null) return initPromise;
2117
+ return taskProcessor.enqueue(async ({ ack }) => {
2118
+ if (initPromise !== null) {
2119
+ ack();
2120
+ return initPromise;
2121
+ }
2122
+ try {
2123
+ const promise = initialize();
2124
+ initPromise = promise;
2125
+ const result = await promise;
2126
+ ack();
2127
+ return result;
2128
+ } catch (error) {
2129
+ initPromise = null;
2130
+ ack();
2131
+ if (retryCount < (options?.maxRetries ?? 3)) return ensureInitialized(retryCount + 1);
2132
+ throw error;
2133
+ }
2134
+ }, { taskGroupId: v7() });
2135
+ };
2136
+ return {
2137
+ ensureInitialized,
2138
+ reset: () => {
2139
+ initPromise = null;
2140
+ },
2141
+ stop: (options) => taskProcessor.stop(options)
2142
+ };
2143
+ };
2144
+
2145
+ //#endregion
2146
+ //#region src/core/connections/pool.ts
2147
+ const wrapPooledConnection = (conn, onClose) => ({
2148
+ ...conn,
2149
+ close: onClose
2150
+ });
2151
+ const createAmbientConnectionPool = (options) => {
2152
+ const { driverType, connection } = options;
2153
+ return createConnectionPool({
2154
+ driverType,
2155
+ getConnection: () => connection,
2156
+ execute: connection.execute,
2157
+ transaction: (options) => connection.transaction(options),
2158
+ withConnection: (handle, _options) => handle(connection),
2159
+ withTransaction: (handle, options) => {
2160
+ const withTx = connection.withTransaction;
2161
+ return withTx(handle, options);
2162
+ }
2163
+ });
2164
+ };
2165
+ const createSingletonConnectionPool = (options) => {
2166
+ const { driverType, getConnection } = options;
2167
+ let connectionPromise = null;
2168
+ const getExistingOrNewConnection = () => {
2169
+ if (!connectionPromise) connectionPromise ??= Promise.resolve(getConnection());
2170
+ return connectionPromise;
2171
+ };
2172
+ return {
2173
+ driverType,
2174
+ connection: () => getExistingOrNewConnection().then((conn) => wrapPooledConnection(conn, () => Promise.resolve())),
2175
+ execute: sqlExecutorInAmbientConnection({
2176
+ driverType,
2177
+ connection: getExistingOrNewConnection
2178
+ }),
2179
+ withConnection: (handle, _options) => executeInAmbientConnection(handle, { connection: getExistingOrNewConnection }),
2180
+ ...transactionFactoryWithAsyncAmbientConnection(options.driverType, getExistingOrNewConnection, options.closeConnection),
2181
+ close: async () => {
2182
+ if (!connectionPromise) return;
2183
+ await (await connectionPromise).close();
2184
+ }
2185
+ };
2186
+ };
2187
+ const createBoundedConnectionPool = (options) => {
2188
+ const { driverType, maxConnections } = options;
2189
+ const guardMaxConnections = guardBoundedAccess(options.getConnection, {
2190
+ maxResources: maxConnections,
2191
+ reuseResources: true
2192
+ });
2193
+ let closed = false;
2194
+ const executeWithPooling = async (operation) => {
2195
+ const conn = await guardMaxConnections.acquire();
2196
+ try {
2197
+ return await operation(conn);
2198
+ } finally {
2199
+ guardMaxConnections.release(conn);
2200
+ }
2201
+ };
2202
+ return {
2203
+ driverType,
2204
+ connection: async () => {
2205
+ const conn = await guardMaxConnections.acquire();
2206
+ return wrapPooledConnection(conn, () => Promise.resolve(guardMaxConnections.release(conn)));
2207
+ },
2208
+ execute: {
2209
+ query: (sql, opts) => executeWithPooling((c) => c.execute.query(sql, opts)),
2210
+ batchQuery: (sqls, opts) => executeWithPooling((c) => c.execute.batchQuery(sqls, opts)),
2211
+ command: (sql, opts) => executeWithPooling((c) => c.execute.command(sql, opts)),
2212
+ batchCommand: (sqls, opts) => executeWithPooling((c) => c.execute.batchCommand(sqls, opts))
2213
+ },
2214
+ withConnection: executeWithPooling,
2215
+ ...transactionFactoryWithAsyncAmbientConnection(driverType, guardMaxConnections.acquire, guardMaxConnections.release),
2216
+ close: async () => {
2217
+ if (closed) return;
2218
+ closed = true;
2219
+ await guardMaxConnections.stop({ force: true });
2220
+ }
2221
+ };
2222
+ };
2223
+ const createSingletonClientConnectionPool = (options) => {
2224
+ const { driverType, dbClient } = options;
2225
+ return createSingletonConnectionPool({
2226
+ getConnection: () => options.connectionFactory({ dbClient }),
2227
+ driverType
2228
+ });
2229
+ };
2230
+ const createAlwaysNewConnectionPool = (options) => {
2231
+ const { driverType, getConnection, connectionOptions } = options;
2232
+ return createConnectionPool({
2233
+ driverType,
2234
+ getConnection: () => connectionOptions ? getConnection(connectionOptions) : getConnection()
2235
+ });
2236
+ };
2237
+ const createConnectionPool = (pool) => {
2238
+ const { driverType, getConnection } = pool;
2239
+ const connection = "connection" in pool ? pool.connection : () => Promise.resolve(getConnection());
2240
+ return {
2241
+ driverType,
2242
+ connection,
2243
+ withConnection: "withConnection" in pool ? pool.withConnection : (handle, _options) => executeInNewConnection(handle, { connection }),
2244
+ close: "close" in pool ? pool.close : () => Promise.resolve(),
2245
+ execute: "execute" in pool ? pool.execute : sqlExecutorInNewConnection({
2246
+ driverType,
2247
+ connection
2248
+ }),
2249
+ ..."transaction" in pool && "withTransaction" in pool ? {
2250
+ transaction: pool.transaction,
2251
+ withTransaction: pool.withTransaction
2252
+ } : transactionFactoryWithNewConnection(getConnection)
2253
+ };
2254
+ };
2255
+
2256
+ //#endregion
2257
+ //#region src/core/index.ts
2258
+ SQL.columnN = Object.assign(dumboSchema.column, { type: SQLColumnTypeTokensFactory });
2259
+
2260
+ //#endregion
2261
+ export { migrationTableSchemaComponent as $, JSONReplacer as $t, ConcurrencyError as A, DatabaseURN as An, MapLiteralProcessor as At, LockNotAvailableError as B, IndexURNType as Bn, SQLColumnTypeTokensFactory as Bt, mapColumnToJSON as C, getDatabaseDriverName as Cn, isTokenizedSQL as Ct, sqlExecutorInNewConnection as D, canHandleDriverWithConnectionString as Dn, ExpandArrayProcessor as Dt, sqlExecutorInAmbientConnection as E, DumboDatabaseDriverRegistry as En, SQLProcessorsRegistry as Et, ExclusionViolationError as F, databaseSchemaSchemaComponent as Fn, ColumnTypeToken as Ft, TransientDatabaseError as G, filterSchemaComponentsOfType as Gn, SQLArray as Gt, QueryCanceledError as H, ColumnURN as Hn, TimestampToken as Ht, ForeignKeyViolationError as I, TableURN as In, IntegerToken as It, combineMigrations as J, mapSchemaComponentsOfType as Jn, SQLLiteral as Jt, UniqueConstraintError as K, findSchemaComponentsOfType as Kn, SQLIdentifier as Kt, InsufficientResourcesError as L, TableURNType as Ln, JSONBToken as Lt, DataError as M, databaseSchemaComponent as Mn, AutoIncrementSQLColumnToken as Mt, DeadlockError as N, DatabaseSchemaURN as Nn, BigIntegerToken as Nt, AdminShutdownError as O, dumboDatabaseDriverRegistry as On, ExpandSQLInProcessor as Ot, DumboError as P, DatabaseSchemaURNType as Pn, BigSerialToken as Pt, SchemaComponentMigrator as Q, JSONCodec as Qt, IntegrityConstraintViolationError as R, tableSchemaComponent as Rn, SQLColumnToken as Rt, mapColumnToDate as S, fromDatabaseDriverType as Sn, TokenizedSQL as St, sqlExecutor as T, toDatabaseDriverType as Tn, mapDefaultSQLColumnProcessors as Tt, SerializationError as U, ColumnURNType as Un, TimestamptzToken as Ut, NotNullViolationError as V, indexSchemaComponent as Vn, SerialToken as Vt, SystemError as W, columnSchemaComponent as Wn, VarcharToken as Wt, registerDefaultMigratorOptions as X, SQLToken as Xt, getDefaultMigratorOptionsFromRegistry as Y, schemaComponent as Yn, SQLPlain as Yt, runSQLMigrations as Z, ParametrizedSQLBuilder as Zt, BatchCommandNoChangesError as _, dumboDatabaseMetadataRegistry as _n, mapSQLParamValue as _t, createSingletonClientConnectionPool as a, composeJSONRevivers as an, color as at, executeInNewDbClient as b, getDefaultDatabaseAsync as bn, SQL as bt, createAmbientConnection as c, exists as cn, formatSQL as ct, createTransientConnection as d, single as dn, ANSISQLIdentifierQuote as dt, JSONReplacers as en, sqlMigration as et, executeInTransaction as f, singleOrNull as fn, ANSISQLParamPlaceholder as ft, transactionFactoryWithNewConnection as g, DumboDatabaseMetadataRegistry as gn, mapSQLIdentifier as gt, transactionFactoryWithDbClient as h, dumboSchema as hn, mapANSISQLParamPlaceholder as ht, createConnectionPool as i, composeJSONReplacers as in, prettyJson as it, ConnectionError as j, DatabaseURNType as jn, SQLProcessor as jt, CheckViolationError as k, schemaComponentURN as kn, FormatIdentifierProcessor as kt, createConnection as l, first as ln, getFormatter as lt, transactionFactoryWithAsyncAmbientConnection as m, defaultDatabaseLockOptions as mn, SQLValueMapper as mt, createAmbientConnectionPool as n, JSONRevivers as nn, LogStyle as nt, createSingletonConnectionPool as o, jsonSerializer as on, SQLFormatter as ot, transactionFactoryWithAmbientConnection as p, NoDatabaseLock as pn, DefaultMapSQLParamValueOptions as pt, MIGRATIONS_LOCK_ID as q, isSchemaComponentOfType as qn, SQLIn as qt, createBoundedConnectionPool as r, JSONSerializer as rn, tracer as rt, guardInitializedOnce as s, count as sn, describeSQL as st, createAlwaysNewConnectionPool as t, JSONReviver as tn, LogLevel as tt, createSingletonConnection as u, firstOrNull as un, registerFormatter as ut, executeInAmbientConnection as v, getDatabaseMetadata as vn, ansiSqlReservedMap as vt, mapSQLQueryResult as w, getDatabaseType as wn, defaultProcessorsRegistry as wt, mapColumnToBigint as x, resolveDatabaseMetadata as xn, isSQL as xt, executeInNewConnection as y, getDefaultDatabase as yn, RawSQL as yt, InvalidOperationError as z, IndexURN as zn, SQLColumnTypeTokens as zt };
2262
+ //# sourceMappingURL=core-DDo4m0Z_.js.map