miqro 6.0.10 → 6.0.12

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.
package/build/lib.cjs CHANGED
@@ -7068,2114 +7068,2112 @@ function createFrame(payload) {
7068
7068
  return buffer;
7069
7069
  }
7070
7070
 
7071
- // src/services/utils/cluster-ws.ts
7072
- var ClusterWebSocketServer2MessageType = "$$$$ClusterWebSocketServer2Message$$$$$";
7073
- var ClusterWebSocketServer2 = class extends WebSocketServer {
7074
- constructor(name, options) {
7075
- super({
7076
- ...options,
7077
- validate: (req) => {
7078
- if (this.options.maxConnections !== void 0 && this.clients.size + this.remoteClients.size >= this.options.maxConnections) {
7079
- return false;
7080
- } else {
7081
- return options.validate ? options.validate(req) : true;
7082
- }
7083
- },
7084
- onError: (req, error2) => {
7085
- if (process.send) {
7086
- process.send({
7087
- type: ClusterWebSocketServer2MessageType,
7088
- action: "error",
7089
- target: this.name,
7090
- clientUUID: req.uuid,
7091
- fromPID: String(process.pid),
7092
- errorMessage: error2.message
7093
- });
7094
- }
7095
- if (options.onError) {
7096
- options.onError(req, error2);
7097
- }
7098
- },
7099
- onConnection: (req) => {
7100
- if (process.send) {
7101
- process.send({
7102
- type: ClusterWebSocketServer2MessageType,
7103
- action: "connection",
7104
- target: this.name,
7105
- fromPID: String(process.pid),
7106
- clientUUID: req.uuid
7107
- });
7108
- }
7109
- if (options.onConnection) {
7110
- options.onConnection(req);
7111
- }
7112
- },
7113
- onDisconnect: (req) => {
7114
- if (process.send) {
7115
- process.send({
7116
- type: ClusterWebSocketServer2MessageType,
7117
- action: "disconnection",
7118
- target: this.name,
7119
- fromPID: String(process.pid),
7120
- clientUUID: req.uuid
7121
- });
7122
- }
7123
- if (options.onDisconnect) {
7124
- options.onDisconnect(req);
7125
- }
7071
+ // node_modules/@miqro/query/build/executors/sqlite3/utils.js
7072
+ function sqlite3ExecutorPrepare(args) {
7073
+ switch (args._type) {
7074
+ case "delete": {
7075
+ const q = args;
7076
+ const where = getWhereStatement(q);
7077
+ const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
7078
+ const whereSQL = where.sql !== "" ? ` WHERE ${where.sql}` : "";
7079
+ const sql = `DELETE FROM ${q._table}${whereSQL}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)} RETURNING ${returing}`;
7080
+ return {
7081
+ sql,
7082
+ values: where.values
7083
+ };
7084
+ }
7085
+ case "create-database": {
7086
+ const q = args;
7087
+ const sql = `CREATE DATABASE ${q._dbName}`;
7088
+ return sql;
7089
+ }
7090
+ case "create-table": {
7091
+ const q = args;
7092
+ const sql = `CREATE TABLE${q._ignoreDuplicate ? " IF NOT EXISTS" : ""} ${q._table}${getCreateTableColumns(q._definition)}`;
7093
+ return sql;
7094
+ }
7095
+ case "drop-database": {
7096
+ const q = args;
7097
+ const sql = `DROP DATABASE${q._ignoreDuplicate ? " IF EXISTS" : ""} ${q._dbName}`;
7098
+ return sql;
7099
+ }
7100
+ case "drop-table": {
7101
+ const q = args;
7102
+ const sql = `DROP TABLE${q._ignoreDuplicate ? " IF EXISTS" : ""} ${q._table}`;
7103
+ return sql;
7104
+ }
7105
+ case "alter-table": {
7106
+ const q = args;
7107
+ let alters = [];
7108
+ if (q._renameTable) {
7109
+ alters.push({
7110
+ sql: `ALTER TABLE ${q._table} RENAME TO ?`,
7111
+ values: [q._renameTable]
7112
+ });
7126
7113
  }
7127
- });
7128
- this.name = name;
7129
- this.listener = async (data) => {
7130
- try {
7131
- const msg = data;
7132
- if (msg && msg.type === ClusterWebSocketServer2MessageType && msg.target === this.name && msg.action) {
7133
- switch (msg.action) {
7134
- case "sync":
7135
- if (process.send) {
7136
- for (const clientUUID of this.clients.keys()) {
7137
- process.send({
7138
- type: ClusterWebSocketServer2MessageType,
7139
- action: "connection",
7140
- target: this.name,
7141
- fromPID: String(process.pid),
7142
- clientUUID
7143
- });
7144
- }
7145
- }
7146
- break;
7147
- case "connection":
7148
- if (!msg.clientUUID) {
7149
- throw new Error(`action [${msg.action}] without clientUUID`);
7150
- }
7151
- if (!this.remoteClients.has(msg.clientUUID)) {
7152
- this.remoteClients.add(msg.clientUUID);
7153
- }
7154
- break;
7155
- case "disconnection":
7156
- if (!msg.clientUUID) {
7157
- throw new Error(`action [${msg.action}] without clientUUID`);
7158
- }
7159
- if (this.remoteClients.has(msg.clientUUID)) {
7160
- this.remoteClients.delete(msg.clientUUID);
7161
- }
7162
- break;
7163
- case "sendMessage": {
7164
- const payload = String(msg.payload);
7165
- if (!msg.clientUUID) {
7166
- await super.broadcast(payload, msg.fromUUID);
7167
- } else if (this.isConnected(msg.clientUUID)) {
7168
- await super.writeTo(msg.clientUUID, payload);
7169
- }
7170
- break;
7114
+ for (let l of q._changes) {
7115
+ switch (l._action) {
7116
+ case "add":
7117
+ if (!l._definition) {
7118
+ throw new Error("unsupported alter action add without definition");
7171
7119
  }
7172
- default:
7173
- throw new Error(`action [${msg.action}] not supported`);
7174
- }
7120
+ alters.push({
7121
+ sql: `ALTER TABLE ${q._table} ADD COLUMN ${getCreateTableColumn(l._column, l._definition, [])}`
7122
+ });
7123
+ break;
7124
+ case "drop":
7125
+ alters.push({
7126
+ sql: `ALTER TABLE ${q._table} DROP COLUMN ${l._column}`
7127
+ });
7128
+ break;
7129
+ case "rename":
7130
+ alters.push({
7131
+ sql: `ALTER TABLE ${q._table} RENAME COLUMN ${l._column} TO ${l._newName}`
7132
+ });
7133
+ break;
7134
+ default:
7135
+ throw new Error("unsupported alter action");
7175
7136
  }
7176
- } catch (e) {
7177
- console.error(e);
7178
7137
  }
7179
- };
7180
- this.connect();
7181
- }
7182
- remoteClients = /* @__PURE__ */ new Set();
7183
- listener;
7184
- connect() {
7185
- if (process.send) {
7186
- process.removeListener("message", this.listener);
7187
- process.on("message", this.listener);
7188
- process.send({
7189
- type: ClusterWebSocketServer2MessageType,
7190
- action: "sync",
7191
- fromPID: String(process.pid),
7192
- target: this.name
7193
- });
7138
+ return alters;
7194
7139
  }
7195
- }
7196
- dispose() {
7197
- process.removeListener("message", this.listener);
7198
- }
7199
- async broadcast(payload, fromUUID) {
7200
- if (process.send) {
7201
- process.send({
7202
- type: ClusterWebSocketServer2MessageType,
7203
- action: "sendMessage",
7204
- payload,
7205
- target: this.name,
7206
- fromPID: String(process.pid),
7207
- fromUUID
7208
- });
7140
+ case "insert": {
7141
+ const q = args;
7142
+ const rows = getInsertValues(q._columns, q._values);
7143
+ const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
7144
+ const sql = `INSERT${q._ignoreDuplicate ? " OR IGNORE" : ""} INTO ${q._table}${getInsertColumns(q._columns)}${rows.sql} RETURNING ${returing}`;
7145
+ return [{
7146
+ sql,
7147
+ values: rows.values
7148
+ }];
7209
7149
  }
7210
- return super.broadcast(payload, fromUUID);
7211
- }
7212
- async writeTo(clientUUID, payload) {
7213
- if (this.remoteClients.has(clientUUID)) {
7214
- if (process.send) {
7215
- process.send({
7216
- type: ClusterWebSocketServer2MessageType,
7217
- action: "sendMessage",
7218
- clientUUID,
7219
- target: this.name,
7220
- fromPID: String(process.pid),
7221
- payload
7222
- });
7223
- return;
7150
+ case "count":
7151
+ case "select": {
7152
+ const isSelect = args._type === "select";
7153
+ const q = isSelect ? args : args;
7154
+ const where = getWhereStatement(q);
7155
+ const columnsSQL = isSelect ? `SELECT ${renderNameAS(q._columns)}` : "SELECT count(*) as count";
7156
+ const whereSQL = where.sql !== "" ? ` WHERE ${where.sql}` : "";
7157
+ const fromSQL = ` FROM ${renderNameAS(q._selectFrom)}`;
7158
+ const join9 = q._joins.map((j) => getJoin(j));
7159
+ const joinValues = join9.reduce(function(ret, current) {
7160
+ ret = ret.concat(current.values);
7161
+ return ret;
7162
+ }, []);
7163
+ const joinSQL = join9.map((j) => j.sql).join(" ");
7164
+ const sql = `${columnsSQL}${fromSQL}${joinSQL}${whereSQL}${getGroupBy(q._groupBy)}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)}`;
7165
+ return [{
7166
+ sql,
7167
+ values: joinValues.concat(where.values)
7168
+ }];
7169
+ }
7170
+ case "update": {
7171
+ const q = args;
7172
+ if (!q._sets || !q._table) {
7173
+ throw new Error(`invalid ${args._type} with [${q._table}] and [${q._sets.join(",")}]`);
7224
7174
  }
7175
+ if (q._sets.length === 0) {
7176
+ throw new Error(`invalid ${args._type} with [${q._table}] and [${q._sets.join(",")}]`);
7177
+ }
7178
+ const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
7179
+ const where = getWhereStatement(q);
7180
+ const whereSQL = where.sql !== "" ? ` WHERE ${where.sql}` : "";
7181
+ const setSQL = ` SET ${q._sets.map((set) => `${set.column}=?`)}`;
7182
+ const sql = `UPDATE ${q._table}${setSQL}${whereSQL}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)} RETURNING ${returing}`;
7183
+ return [{
7184
+ sql,
7185
+ values: q._sets.map((set) => set.value).concat(where.values)
7186
+ }];
7225
7187
  }
7226
- if (this.clients.has(clientUUID)) {
7227
- return super.writeTo(clientUUID, payload);
7228
- }
7188
+ default:
7189
+ throw new Error(`unsupported ${args}`);
7229
7190
  }
7230
- isUUIDValid(uuid) {
7231
- return !this.clients.has(uuid) && !this.remoteClients.has(uuid);
7191
+ }
7192
+ function getJoin(join9) {
7193
+ const wherePrepare = getWhereStatement(join9._on);
7194
+ return {
7195
+ sql: ` ${join9._verb ? `${join9._verb} ` : ""}JOIN ${renderNameAS(join9._table)} ON ${wherePrepare.sql}`,
7196
+ values: wherePrepare.values
7197
+ };
7198
+ }
7199
+ function getWhereFilterColumnName(filter) {
7200
+ if (filter._column === void 0 || filter._value === void 0) {
7201
+ throw new Error(`unsupported where filter ${filter._type} with ${filter._column} and ${filter._value}`);
7232
7202
  }
7233
- };
7234
-
7235
- // src/services/utils/cluster-cache.ts
7236
- var ClusterCacheType = "$$$$$$$$$$$ClusterCacheType$$$$$$$$$$$";
7237
- var ClusterCache = class {
7238
- constructor(name, logger) {
7239
- this.name = name;
7240
- this.logger = logger;
7241
- this.listener = async (data) => {
7242
- try {
7243
- const msg = data;
7244
- if (msg && msg.key && msg.action && msg.type === ClusterCacheType && msg.fromPID !== process.pid, (msg.action === "set_add" || msg.action === "set" || msg.action === "unset" || msg.action === "set_delete" || msg.action === "array_push") && msg.target === this.name) {
7245
- this.logger?.debug("remote cluster cache message from [%s] [%s] [%s] [%s]", msg.fromPID, msg.target, msg.action, msg.key);
7246
- switch (msg.action) {
7247
- case "unset":
7248
- this.localCache.delete(msg.key);
7249
- break;
7250
- case "set":
7251
- this.localCache.set(msg.key, msg.value);
7252
- break;
7253
- case "set_add": {
7254
- const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
7255
- if (!(list instanceof Set)) {
7256
- throw new Error("cannot apply push on non array");
7257
- }
7258
- if (list.has(msg.value)) {
7259
- list.add(msg.value);
7260
- }
7261
- this.localCache.set(msg.key, list);
7262
- break;
7263
- }
7264
- case "set_delete": {
7265
- const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
7266
- if (!(list instanceof Set)) {
7267
- throw new Error("cannot apply push on non array");
7268
- }
7269
- if (list.has(msg.value)) {
7270
- list.delete(msg.value);
7271
- }
7272
- this.localCache.set(msg.key, list);
7273
- break;
7274
- }
7275
- case "array_push": {
7276
- const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : [];
7277
- if (!(list instanceof Array)) {
7278
- throw new Error("cannot apply push on non array");
7279
- }
7280
- list.push(msg.value);
7281
- this.localCache.set(msg.key, list);
7282
- break;
7283
- }
7284
- }
7203
+ return filter;
7204
+ }
7205
+ function getWhereStatement(where) {
7206
+ const filters = where._filters;
7207
+ let ret = {
7208
+ sql: "",
7209
+ values: []
7210
+ };
7211
+ filters.map((filter) => {
7212
+ const where2 = filter._where;
7213
+ switch (filter._type) {
7214
+ case "where":
7215
+ case "and": {
7216
+ if (where2 === void 0) {
7217
+ throw new Error(`unsupported where filter ${filter._type} with ${where2}`);
7285
7218
  }
7286
- } catch (e) {
7287
- this.logger?.error(e);
7219
+ const prepare = mergePrepareArgs({
7220
+ sql: "",
7221
+ values: []
7222
+ }, (where2 instanceof Array ? where2 : [where2]).map((w) => getWhereStatement(w)));
7223
+ if (prepare.sql !== "") {
7224
+ ret = mergePrepareArgs(ret, {
7225
+ sql: `(${prepare.sql})`,
7226
+ values: prepare.values
7227
+ });
7228
+ }
7229
+ break;
7288
7230
  }
7289
- };
7290
- this.connect();
7291
- }
7292
- localCache = /* @__PURE__ */ new Map();
7293
- //private logger: Logger;
7294
- listener;
7295
- connect() {
7296
- if (process.send) {
7297
- process.removeListener("message", this.listener);
7298
- process.on("message", this.listener);
7299
- }
7300
- }
7301
- disconnect() {
7302
- process.removeListener("message", this.listener);
7303
- }
7304
- get(key) {
7305
- this.logger?.trace("get(%s)", key);
7306
- return this.localCache.get(key);
7307
- }
7308
- set(key, value) {
7309
- this.localCache.set(key, value);
7310
- this.logger?.trace("set(%s, ...)", key);
7311
- if (process.send) {
7312
- setTimeout(() => {
7313
- process.send({
7314
- type: ClusterCacheType,
7315
- action: "set",
7316
- target: this.name,
7317
- fromPID: process.pid,
7318
- key,
7319
- value
7231
+ case "literal": {
7232
+ const literal = filter._literal;
7233
+ if (literal === void 0) {
7234
+ throw new Error(`unsupported where filter ${filter._type} with ${literal}`);
7235
+ }
7236
+ ret = mergePrepareArgs(ret, {
7237
+ sql: `${literal}`,
7238
+ values: []
7320
7239
  });
7321
- }, 10);
7322
- }
7323
- }
7324
- unset(key) {
7325
- this.logger?.trace("unset(%s)", key);
7326
- this.localCache.delete(key);
7327
- if (process.send) {
7328
- setTimeout(() => {
7329
- process.send({
7330
- type: ClusterCacheType,
7331
- target: this.name,
7332
- action: "unset",
7333
- fromPID: process.pid,
7334
- key
7240
+ break;
7241
+ }
7242
+ case "or": {
7243
+ if (where2 === void 0) {
7244
+ throw new Error(`unsupported where filter ${filter._type} with ${where2}`);
7245
+ }
7246
+ const prepare = mergePrepareArgs({
7247
+ sql: "",
7248
+ values: []
7249
+ }, (where2 instanceof Array ? where2 : [where2]).map((w) => getWhereStatement(w)), " OR ");
7250
+ ret = mergePrepareArgs(ret, {
7251
+ sql: `(${prepare.sql})`,
7252
+ values: prepare.values
7335
7253
  });
7336
- }, 10);
7337
- }
7338
- }
7339
- has(key) {
7340
- this.logger?.trace("has(%s)", key);
7341
- return this.localCache.has(key);
7342
- }
7343
- set_add(key, value) {
7344
- this.logger?.trace("push(%s)", key);
7345
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7346
- if (!(list instanceof Set)) {
7347
- throw new Error("cannot apply on non Set");
7348
- }
7349
- if (list.has(value)) {
7350
- list.add(value);
7351
- }
7352
- this.localCache.set(key, list);
7353
- if (process.send) {
7354
- setTimeout(() => {
7355
- process.send({
7356
- type: ClusterCacheType,
7357
- target: this.name,
7358
- action: "set_add",
7359
- fromPID: process.pid,
7360
- key,
7361
- value
7254
+ break;
7255
+ }
7256
+ case "nin": {
7257
+ const { _column, _value } = getWhereFilterColumnName(filter);
7258
+ ret = mergePrepareArgs(ret, {
7259
+ sql: `${renderColumn(_column)} not in (${_value.map((v) => "?").join(",")})`,
7260
+ values: _value
7362
7261
  });
7363
- }, 10);
7364
- }
7365
- }
7366
- set_delete(key, value) {
7367
- this.logger?.trace("delete(%s)", key);
7368
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7369
- if (!(list instanceof Set)) {
7370
- throw new Error("cannot apply on non Set");
7371
- }
7372
- if (list.has(value)) {
7373
- list.delete(value);
7374
- }
7375
- this.localCache.set(key, list);
7376
- if (process.send) {
7377
- setTimeout(() => {
7378
- process.send({
7379
- type: ClusterCacheType,
7380
- target: this.name,
7381
- action: "set_delete",
7382
- fromPID: process.pid,
7383
- key,
7384
- value
7262
+ break;
7263
+ }
7264
+ case "in": {
7265
+ const { _column, _value } = getWhereFilterColumnName(filter);
7266
+ ret = mergePrepareArgs(ret, {
7267
+ sql: `${renderColumn(_column)} in (${_value.map((v) => "?").join(",")})`,
7268
+ values: _value
7385
7269
  });
7386
- }, 10);
7387
- }
7388
- }
7389
- set_has(key, value) {
7390
- this.logger?.trace("set_has(%s)", key);
7391
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7392
- if (!(list instanceof Set)) {
7393
- throw new Error("cannot apply on non Set");
7394
- }
7395
- const ret = list.has(value);
7396
- this.localCache.set(key, list);
7397
- return ret;
7398
- }
7399
- set_clear(key) {
7400
- this.logger?.trace("set_clear(%s)", key);
7401
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7402
- if (!(list instanceof Set)) {
7403
- throw new Error("cannot apply on non Set");
7404
- }
7405
- list.clear();
7406
- this.localCache.set(key, list);
7407
- }
7408
- array_push(key, value) {
7409
- this.logger?.trace("array_push(%s)", key);
7410
- const list = this.localCache.has(key) ? this.localCache.get(key) : [];
7411
- if (!(list instanceof Array)) {
7412
- throw new Error("cannot apply on non Array");
7413
- }
7414
- list.push(value);
7415
- this.localCache.set(key, list);
7416
- if (process.send) {
7417
- setTimeout(() => {
7418
- process.send({
7419
- type: ClusterCacheType,
7420
- target: this.name,
7421
- action: "array_push",
7422
- fromPID: process.pid,
7423
- key,
7424
- value
7270
+ break;
7271
+ }
7272
+ case "equal": {
7273
+ const { _column, _value } = getWhereFilterColumnName(filter);
7274
+ ret = mergePrepareArgs(ret, {
7275
+ sql: `${renderColumn(_column)}=?`,
7276
+ values: [_value]
7425
7277
  });
7426
- }, 10);
7278
+ break;
7279
+ }
7280
+ case "gt": {
7281
+ const { _column, _value } = getWhereFilterColumnName(filter);
7282
+ ret = mergePrepareArgs(ret, {
7283
+ sql: `${renderColumn(_column)}>?`,
7284
+ values: [_value]
7285
+ });
7286
+ break;
7287
+ }
7288
+ case "gte": {
7289
+ const { _column, _value } = getWhereFilterColumnName(filter);
7290
+ ret = mergePrepareArgs(ret, {
7291
+ sql: `${renderColumn(_value)}>=?`,
7292
+ values: [_value]
7293
+ });
7294
+ break;
7295
+ }
7296
+ case "lt": {
7297
+ const { _column, _value } = getWhereFilterColumnName(filter);
7298
+ ret = mergePrepareArgs(ret, {
7299
+ sql: `${renderColumn(_column)}<?`,
7300
+ values: [_value]
7301
+ });
7302
+ break;
7303
+ }
7304
+ case "lte": {
7305
+ const { _column, _value } = getWhereFilterColumnName(filter);
7306
+ ret = mergePrepareArgs(ret, {
7307
+ sql: `${renderColumn(_column)}<=?`,
7308
+ values: [_value]
7309
+ });
7310
+ break;
7311
+ }
7312
+ case "neq": {
7313
+ const { _column, _value } = getWhereFilterColumnName(filter);
7314
+ ret = mergePrepareArgs(ret, {
7315
+ sql: `${renderColumn(_column)}<>?`,
7316
+ values: [_value]
7317
+ });
7318
+ break;
7319
+ }
7320
+ case "like": {
7321
+ const { _column, _value } = getWhereFilterColumnName(filter);
7322
+ ret = mergePrepareArgs(ret, {
7323
+ sql: `${renderColumn(_column)} LIKE ?`,
7324
+ values: [_value]
7325
+ });
7326
+ break;
7327
+ }
7328
+ default:
7329
+ throw new Error(`unsupported where filter ${filter._type}`);
7427
7330
  }
7331
+ });
7332
+ return ret;
7333
+ }
7334
+ function getCreateTableColumns(definition) {
7335
+ const columnNames = Object.keys(definition);
7336
+ const primaryKeyColumns = columnNames.filter((columnName) => definition[columnName].primaryKey);
7337
+ return `(${columnNames.map((columnName) => {
7338
+ const def = definition[columnName];
7339
+ return getCreateTableColumn(columnName, def, primaryKeyColumns);
7340
+ }).concat(primaryKeyColumns.length > 1 ? [
7341
+ `PRIMARY KEY( ${primaryKeyColumns.join(",")} )`
7342
+ ] : []).join(", ")})`;
7343
+ }
7344
+ function getCreateTableColumn(columnName, def, primaryKeyColumns) {
7345
+ const primaryKey = primaryKeyColumns.length === 1 && columnName === primaryKeyColumns[0] ? " PRIMARY KEY" : "";
7346
+ const notNull = `${def.allowNull == false ? " NOT NULL" : ""}`;
7347
+ const defaultValue = `${def.defaultValue !== void 0 ? ` DEFAULT '${def.defaultValue}'` : ""}`;
7348
+ const autoIncrement = `${def.autoIncrement !== void 0 && def.autoIncrement === true ? ` AUTOINCREMENT` : ""}`;
7349
+ switch (def.type) {
7350
+ case "datetime":
7351
+ return `${columnName} DATETIME${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7352
+ case "boolean":
7353
+ return `${columnName} TINYINT${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7354
+ case "json":
7355
+ case "string":
7356
+ return `${columnName} TEXT${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7357
+ case "real":
7358
+ return `${columnName} REAL${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7359
+ case "bigint":
7360
+ case "integer":
7361
+ return `${columnName} INTEGER${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7362
+ default:
7363
+ throw new Error("unsupported type " + def.type);
7428
7364
  }
7429
- array_clear(key) {
7430
- this.logger?.trace("array_clear(%s)", key);
7431
- if (this.localCache.has(key) && !(this.localCache.get(key) instanceof Array)) {
7432
- throw new Error("cannot apply on non Array");
7433
- }
7434
- this.localCache.set(key, []);
7365
+ }
7366
+ function getInsertColumns(columns) {
7367
+ return `(${columns.join(",")})`;
7368
+ }
7369
+ function getInsertValues(columns, values) {
7370
+ let args = [];
7371
+ for (const v of values) {
7372
+ args = args.concat(columns.map((c) => v[c]));
7435
7373
  }
7436
- };
7374
+ return {
7375
+ sql: ` VALUES ${values.map(() => `(${columns.map(() => "?").join(", ")})`)}`,
7376
+ values: args
7377
+ };
7378
+ }
7379
+ function renderNameAS(input, join9 = ", ") {
7380
+ const list = input instanceof Array ? input : [input];
7381
+ return list.map((i) => typeof i === "string" ? i : `${i.name} AS ${i.as}`).join(join9);
7382
+ }
7383
+ function getGroupBy(groupBy) {
7384
+ return groupBy.length > 0 ? ` GROUP BY ${groupBy.join(",")}` : "";
7385
+ }
7386
+ function getOrderBy(orderBy) {
7387
+ return orderBy.length > 0 ? ` ORDER BY ${orderBy.map((o) => `${o.column} ${o.mode}`).join(",")}` : "";
7388
+ }
7389
+ function getLimit(limit, offsetBy) {
7390
+ return `${limit !== void 0 ? ` LIMIT ${limit}` : ""}${offsetBy ? ` OFFSET ${offsetBy}` : ""}`;
7391
+ }
7392
+ function renderColumn(column) {
7393
+ return column;
7394
+ }
7395
+ function mergePrepareArgs(to, merge, concatOperator = " AND ") {
7396
+ return (merge instanceof Array ? merge : [merge]).reduce((current, value) => {
7397
+ if (current.sql !== "") {
7398
+ current.sql += concatOperator;
7399
+ }
7400
+ current.sql += value.sql;
7401
+ current.values = !value.values ? current.values : (current.values ? current.values : []).concat(value.values);
7402
+ return current;
7403
+ }, to);
7404
+ }
7437
7405
 
7438
- // src/services/utils/cache.ts
7439
- var LocalCache = class {
7440
- constructor(name, logger) {
7441
- this.name = name;
7442
- this.logger = logger;
7443
- }
7444
- localCache = /* @__PURE__ */ new Map();
7445
- dispose() {
7446
- }
7447
- get(key) {
7448
- this.logger?.trace("get(%s)", key);
7449
- return this.localCache.get(key);
7450
- }
7451
- set(key, value) {
7452
- this.localCache.set(key, value);
7453
- this.logger?.trace("set(%s, ...)", key);
7406
+ // node_modules/@miqro/query/build/executors/parser.js
7407
+ var parser = new Parser();
7408
+ function assertNotUndefined2(obj) {
7409
+ if (obj === void 0) {
7410
+ throw new Error("validation failed");
7454
7411
  }
7455
- unset(key) {
7456
- this.logger?.trace("unset(%s)", key);
7457
- this.localCache.delete(key);
7412
+ return obj;
7413
+ }
7414
+ var DATABASE_CONFIG_SCHEMA = {
7415
+ type: "object",
7416
+ properties: {
7417
+ executor: {
7418
+ type: "object?",
7419
+ mode: "add_extra",
7420
+ properties: {
7421
+ prepare: "function",
7422
+ query: "function",
7423
+ disconnect: "function"
7424
+ }
7425
+ },
7426
+ logger: {
7427
+ type: "object?",
7428
+ mode: "add_extra",
7429
+ properties: {
7430
+ log: "function?",
7431
+ error: "function?"
7432
+ }
7433
+ },
7434
+ storage: "string?",
7435
+ connectionString: "string?",
7436
+ dialect: {
7437
+ type: "enum?",
7438
+ enumValues: ["node:sqlite", "sqlite3-cli", "sqlite3", "pg"]
7439
+ }
7458
7440
  }
7459
- has(key) {
7460
- this.logger?.trace("has(%s)", key);
7461
- return this.localCache.has(key);
7441
+ };
7442
+ var ColumnDefinitionTypeSchema = {
7443
+ type: "enum",
7444
+ enumValues: ["string", "integer", "boolean", "datetime", "json", "real", "bigint"]
7445
+ };
7446
+ var ColumnDefinitionSchema = {
7447
+ type: "object",
7448
+ properties: {
7449
+ type: ColumnDefinitionTypeSchema,
7450
+ primaryKey: "boolean?",
7451
+ autoIncrement: "boolean?",
7452
+ allowNull: "boolean?",
7453
+ defaultValue: "any?"
7462
7454
  }
7463
- set_add(key, value) {
7464
- this.logger?.trace("set_add(%s)", key);
7465
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7466
- if (!(list instanceof Set)) {
7467
- throw new Error("cannot apply on non Set");
7468
- }
7469
- if (list.has(value)) {
7470
- list.add(value);
7471
- }
7472
- this.localCache.set(key, list);
7455
+ };
7456
+ parser.register("ColumnDefinition", ColumnDefinitionSchema);
7457
+ var TableSchemaSchema = {
7458
+ type: "dict",
7459
+ dictType: "ColumnDefinition"
7460
+ };
7461
+
7462
+ // node_modules/@miqro/query/build/executors/sqlite3/lib.js
7463
+ var SQLITE_CONFIG_SCHEMA = {
7464
+ type: "object",
7465
+ mode: "remove_extra",
7466
+ properties: {
7467
+ storage: "string"
7473
7468
  }
7474
- set_delete(key, value) {
7475
- this.logger?.trace("set_delete(%s)", key);
7476
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7477
- if (!(list instanceof Set)) {
7478
- throw new Error("cannot apply on non Set");
7479
- }
7480
- if (list.has(value)) {
7481
- list.delete(value);
7482
- }
7483
- this.localCache.set(key, list);
7469
+ };
7470
+ async function sqlite3Executor(config) {
7471
+ const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA);
7472
+ if (!databaseOptions) {
7473
+ throw new Error("config not valid");
7484
7474
  }
7485
- set_has(key, value) {
7486
- this.logger?.trace("set_has(%s)", key);
7487
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7488
- if (!(list instanceof Set)) {
7489
- throw new Error("cannot apply on non Set");
7490
- }
7491
- const ret = list.has(value);
7492
- this.localCache.set(key, list);
7493
- return ret;
7494
- }
7495
- set_clear(key) {
7496
- this.logger?.trace("set_clear(%s)", key);
7497
- const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
7498
- if (!(list instanceof Set)) {
7499
- throw new Error("cannot apply on non Set");
7500
- }
7501
- list.clear();
7502
- this.localCache.set(key, list);
7503
- }
7504
- array_push(key, value) {
7505
- this.logger?.trace("array_push(%s)", key);
7506
- const list = this.localCache.has(key) ? this.localCache.get(key) : [];
7507
- if (!(list instanceof Array)) {
7508
- throw new Error("cannot apply on non Array");
7509
- }
7510
- list.push(value);
7511
- this.localCache.set(key, list);
7512
- }
7513
- array_clear(key) {
7514
- this.logger?.trace("array_clear(%s)", key);
7515
- if (this.localCache.has(key) && !(this.localCache.get(key) instanceof Array)) {
7516
- throw new Error("cannot apply on non Array");
7475
+ const sqlite3 = await import("sqlite3");
7476
+ const driver = new sqlite3.default.Database(databaseOptions.storage);
7477
+ return {
7478
+ disconnect: async function sqlite3ExecutorDisconnect() {
7479
+ await driver.close();
7480
+ },
7481
+ prepare: sqlite3ExecutorPrepare,
7482
+ query: async function sqlite3Executor2(sql, values) {
7483
+ return new Promise((resolve20, reject) => {
7484
+ const st = driver.prepare(sql, values, function(error2) {
7485
+ if (error2) {
7486
+ reject(error2);
7487
+ } else {
7488
+ st.all(function(error3, rows) {
7489
+ if (error3) {
7490
+ reject(error3);
7491
+ } else {
7492
+ st.finalize((error4) => {
7493
+ if (error4) {
7494
+ reject(error4);
7495
+ } else {
7496
+ resolve20(rows);
7497
+ }
7498
+ });
7499
+ }
7500
+ });
7501
+ }
7502
+ });
7503
+ });
7517
7504
  }
7518
- this.localCache.set(key, []);
7519
- }
7520
- };
7505
+ };
7506
+ }
7521
7507
 
7522
- // src/services/utils/websocketmanager.ts
7523
- init_constants();
7524
- var WebSocketManager = class {
7525
- runningGlobalWSMap = /* @__PURE__ */ new Map();
7526
- logger = null;
7527
- name;
7528
- avoidLogSocket;
7529
- constructor(options) {
7530
- this.onUpgrade = this.onUpgrade.bind(this);
7531
- this.logger = options && options.logger ? options.logger : null;
7532
- this.name = options && options.name ? options.name : "WebSocketManager";
7533
- this.avoidLogSocket = options && options.avoidLogSocket ? options.avoidLogSocket : false;
7534
- }
7535
- deleteWS(path) {
7536
- const ws = this.runningGlobalWSMap.get(path);
7537
- this.disconnectAllFrom(path);
7538
- ws.dispose();
7539
- this.runningGlobalWSMap.delete(path);
7540
- }
7541
- deleteAllWS() {
7542
- for (const path of this.runningGlobalWSMap.keys()) {
7543
- this.deleteWS(path);
7544
- }
7508
+ // node_modules/@miqro/query/build/executors/pg/lib.js
7509
+ var PG_DATABASE_CONFIG_SCHEMA = {
7510
+ type: "object",
7511
+ mode: "remove_extra",
7512
+ properties: {
7513
+ connectionString: "string"
7545
7514
  }
7546
- getWS(path) {
7547
- return this.runningGlobalWSMap.get(path);
7515
+ };
7516
+ async function postgresExecutor(config) {
7517
+ const databaseOptions = parser.parse(config, PG_DATABASE_CONFIG_SCHEMA);
7518
+ if (!databaseOptions) {
7519
+ throw new Error("bad options");
7548
7520
  }
7549
- replaceALLWS(list) {
7550
- this.deleteAllWS();
7551
- for (const wsConfig of list) {
7552
- if (!wsConfig.disabled) {
7553
- if (this.runningGlobalWSMap.has(wsConfig.path)) {
7554
- throw new Error(`ws on path ${wsConfig.path} already setup!`);
7521
+ const pg = await import("pg");
7522
+ const driver = new pg.default.Client({
7523
+ connectionString: databaseOptions.connectionString
7524
+ // "postgresql://postgres:password@localhost:5432/db"
7525
+ });
7526
+ await driver.connect();
7527
+ return {
7528
+ disconnect: async function postgresExecutorDisconnect() {
7529
+ await driver.end();
7530
+ },
7531
+ prepare: function postgresExecutorPrepare(args) {
7532
+ switch (args._type) {
7533
+ case "create-table": {
7534
+ const q = args;
7535
+ const sql = `CREATE TABLE${q._ignoreDuplicate ? " IF NOT EXISTS" : ""} ${q._table}${getCreateTableColumns2(q._definition)}`;
7536
+ return sql;
7555
7537
  }
7556
- this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
7557
- const server2 = new ClusterWebSocketServer2(wsConfig.path, wsConfig);
7558
- this.runningGlobalWSMap.set(wsConfig.path, server2);
7559
- }
7560
- }
7561
- }
7562
- replaceALLWSBuLOGSocket(list) {
7563
- for (const path of this.runningGlobalWSMap.keys()) {
7564
- if (path !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
7565
- this.deleteWS(path);
7566
- }
7567
- }
7568
- for (const wsConfig of list) {
7569
- if (!wsConfig.disabled) {
7570
- if (wsConfig.path !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
7571
- if (this.runningGlobalWSMap.has(wsConfig.path)) {
7572
- throw new Error(`ws on path ${wsConfig.path} already setup!`);
7573
- }
7574
- this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
7575
- const server2 = new ClusterWebSocketServer2(this.name + wsConfig.path, wsConfig);
7576
- this.runningGlobalWSMap.set(wsConfig.path, server2);
7538
+ case "insert": {
7539
+ const q = args;
7540
+ const rows = getInsertValues(q._columns, q._values);
7541
+ const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
7542
+ const sql = `INSERT INTO ${q._table}${getInsertColumns(q._columns)}${rows.sql} ${q._ignoreDuplicate ? "ON CONFLICT DO NOTHING " : ""}RETURNING ${returing}`;
7543
+ return {
7544
+ sql,
7545
+ values: rows.values
7546
+ };
7577
7547
  }
7578
- }
7579
- }
7580
- }
7581
- /*public setupWS(path: string, server: ClusterWebSocketServer2) {
7582
- if (this.runningGlobalWSMap.has(path)) {
7583
- throw new Error(`ws on path ${path} already setup!`);
7584
- }
7585
- this.runningGlobalWSMap.set(path, server);
7586
- }*/
7587
- disconnectAllFrom(path) {
7588
- try {
7589
- this.logger?.debug("disconnect all from [%s]", path);
7590
- const ws = this.getWS(path);
7591
- if (ws) {
7592
- const clients = ws.clients.values();
7593
- if (clients) {
7594
- for (const client of clients) {
7595
- try {
7596
- client.socket.destroy();
7597
- } catch (e2) {
7598
- this.logger?.error("error disconnecting web socket client");
7599
- this.logger?.error(e2);
7548
+ case "alter-table": {
7549
+ const q = args;
7550
+ let alters = [];
7551
+ if (q._renameTable) {
7552
+ alters.push({
7553
+ sql: `ALTER TABLE ${q._table} RENAME TO ?`,
7554
+ values: [q._renameTable]
7555
+ });
7556
+ }
7557
+ for (let l of q._changes) {
7558
+ switch (l._action) {
7559
+ case "add":
7560
+ if (!l._definition) {
7561
+ throw new Error("unsupported alter action add without definition");
7562
+ }
7563
+ alters.push({
7564
+ sql: `ALTER TABLE ${q._table} ADD COLUMN ${getCreateTableColumn2(l._column, l._definition, [])}`
7565
+ });
7566
+ break;
7567
+ case "drop":
7568
+ alters.push({
7569
+ sql: `ALTER TABLE ${q._table} DROP COLUMN ${l._column}`
7570
+ });
7571
+ break;
7572
+ case "rename":
7573
+ alters.push({
7574
+ sql: `ALTER TABLE ${q._table} RENAME COLUMN ${l._column} TO ${l._newName}`
7575
+ });
7576
+ break;
7577
+ default:
7578
+ throw new Error("unsupported alter action");
7600
7579
  }
7601
7580
  }
7581
+ return alters;
7602
7582
  }
7583
+ default:
7584
+ return sqlite3ExecutorPrepare(args);
7603
7585
  }
7604
- } catch (e) {
7605
- this.logger?.error("error disconnecting web socket clients");
7606
- this.logger?.error(e.message);
7607
- }
7608
- }
7609
- disconnectAllButLOGSocket() {
7610
- try {
7611
- for (const wsPath of this.runningGlobalWSMap.keys()) {
7612
- if (wsPath !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
7613
- this.disconnectAllFrom(wsPath);
7614
- }
7586
+ },
7587
+ query: async function postgresExecutor2(sql, values) {
7588
+ try {
7589
+ const result = await driver.query(tokens2Postgres(sql, values), values);
7590
+ return result.rows;
7591
+ } catch (e) {
7592
+ throw e;
7615
7593
  }
7616
- } catch (e) {
7617
- this.logger?.error("error disconnecting web socket clients");
7618
- this.logger?.error(e.message);
7619
7594
  }
7595
+ };
7596
+ }
7597
+ function getCreateTableColumns2(definition) {
7598
+ const columnNames = Object.keys(definition);
7599
+ const primaryKeyColumns = columnNames.filter((columnName) => definition[columnName].primaryKey);
7600
+ return `(${columnNames.map((columnName) => {
7601
+ const def = definition[columnName];
7602
+ return getCreateTableColumn2(columnName, def, primaryKeyColumns);
7603
+ }).concat(primaryKeyColumns.length > 1 ? [
7604
+ `PRIMARY KEY( ${primaryKeyColumns.join(",")} )`
7605
+ ] : []).join(", ")})`;
7606
+ }
7607
+ function getCreateTableColumn2(columnName, def, primaryKeyColumns) {
7608
+ const primaryKey = primaryKeyColumns.length === 1 && columnName === primaryKeyColumns[0] ? " PRIMARY KEY" : "";
7609
+ const notNull = `${def.allowNull == false ? " NOT NULL" : ""}`;
7610
+ const defaultValue = `${def.defaultValue !== void 0 ? ` DEFAULT '${def.defaultValue}'` : ""}`;
7611
+ if (def.autoIncrement) {
7612
+ return `${columnName} BIGSERIAL${primaryKey}`;
7620
7613
  }
7621
- disconnectAll() {
7622
- try {
7623
- for (const wsPath of this.runningGlobalWSMap.keys()) {
7624
- this.disconnectAllFrom(wsPath);
7625
- }
7626
- } catch (e) {
7627
- this.logger?.error("error disconnecting web socket clients");
7628
- this.logger?.error(e.message);
7629
- }
7614
+ switch (def.type) {
7615
+ case "datetime":
7616
+ return `${columnName} TIMESTAMP${primaryKey}${notNull}${defaultValue}`;
7617
+ case "boolean":
7618
+ return `${columnName} BOOLEAN${primaryKey}${notNull}${defaultValue}`;
7619
+ case "real":
7620
+ return `${columnName} REAL${primaryKey}${notNull}${defaultValue}`;
7621
+ case "json":
7622
+ case "string":
7623
+ return `${columnName} TEXT${primaryKey}${notNull}${defaultValue}`;
7624
+ case "bigint":
7625
+ return `${columnName} bigint${primaryKey}${notNull}${defaultValue}`;
7626
+ case "integer":
7627
+ return `${columnName} INTEGER${primaryKey}${notNull}${defaultValue}`;
7628
+ default:
7629
+ throw new Error("unsupported type " + def.type);
7630
7630
  }
7631
- onUpgrade(req, socket, head) {
7632
- try {
7633
- const wsServer = this.getWS(req.path);
7634
- if (wsServer) {
7635
- return wsServer.onUpgrade(req, socket, head);
7636
- } else {
7637
- socket.destroy();
7638
- }
7639
- } catch (e) {
7640
- this.logger?.error(e);
7631
+ }
7632
+ function tokens2Postgres(inSql, values) {
7633
+ let i = 0;
7634
+ const sql = inSql.replaceAll("?", (string) => {
7635
+ i++;
7636
+ return `$${i}`;
7637
+ });
7638
+ if (i !== (values ? values.length : 0)) {
7639
+ throw new Error("invalid char '?'");
7640
+ }
7641
+ let iSum = 0;
7642
+ for (const c of sql) {
7643
+ if (c === "$") {
7644
+ iSum++;
7641
7645
  }
7642
7646
  }
7643
- };
7644
-
7645
- // src/services/utils/db-manager.ts
7646
- var import_node_cluster = __toESM(require("node:cluster"), 1);
7647
+ if (iSum !== i) {
7648
+ throw new Error("invalid char '$'");
7649
+ }
7650
+ return sql;
7651
+ }
7647
7652
 
7648
- // node_modules/@miqro/query/build/executors/sqlite3/utils.js
7649
- function sqlite3ExecutorPrepare(args) {
7650
- switch (args._type) {
7651
- case "delete": {
7652
- const q = args;
7653
- const where = getWhereStatement(q);
7654
- const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
7655
- const whereSQL = where.sql !== "" ? ` WHERE ${where.sql}` : "";
7656
- const sql = `DELETE FROM ${q._table}${whereSQL}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)} RETURNING ${returing}`;
7657
- return {
7658
- sql,
7659
- values: where.values
7660
- };
7661
- }
7662
- case "create-database": {
7663
- const q = args;
7664
- const sql = `CREATE DATABASE ${q._dbName}`;
7665
- return sql;
7666
- }
7667
- case "create-table": {
7668
- const q = args;
7669
- const sql = `CREATE TABLE${q._ignoreDuplicate ? " IF NOT EXISTS" : ""} ${q._table}${getCreateTableColumns(q._definition)}`;
7670
- return sql;
7671
- }
7672
- case "drop-database": {
7673
- const q = args;
7674
- const sql = `DROP DATABASE${q._ignoreDuplicate ? " IF EXISTS" : ""} ${q._dbName}`;
7675
- return sql;
7676
- }
7677
- case "drop-table": {
7678
- const q = args;
7679
- const sql = `DROP TABLE${q._ignoreDuplicate ? " IF EXISTS" : ""} ${q._table}`;
7680
- return sql;
7681
- }
7682
- case "alter-table": {
7683
- const q = args;
7684
- let alters = [];
7685
- if (q._renameTable) {
7686
- alters.push({
7687
- sql: `ALTER TABLE ${q._table} RENAME TO ?`,
7688
- values: [q._renameTable]
7689
- });
7690
- }
7691
- for (let l of q._changes) {
7692
- switch (l._action) {
7693
- case "add":
7694
- if (!l._definition) {
7695
- throw new Error("unsupported alter action add without definition");
7696
- }
7697
- alters.push({
7698
- sql: `ALTER TABLE ${q._table} ADD COLUMN ${getCreateTableColumn(l._column, l._definition, [])}`
7699
- });
7700
- break;
7701
- case "drop":
7702
- alters.push({
7703
- sql: `ALTER TABLE ${q._table} DROP COLUMN ${l._column}`
7704
- });
7705
- break;
7706
- case "rename":
7707
- alters.push({
7708
- sql: `ALTER TABLE ${q._table} RENAME COLUMN ${l._column} TO ${l._newName}`
7709
- });
7710
- break;
7711
- default:
7712
- throw new Error("unsupported alter action");
7713
- }
7714
- }
7715
- return alters;
7716
- }
7717
- case "insert": {
7718
- const q = args;
7719
- const rows = getInsertValues(q._columns, q._values);
7720
- const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
7721
- const sql = `INSERT${q._ignoreDuplicate ? " OR IGNORE" : ""} INTO ${q._table}${getInsertColumns(q._columns)}${rows.sql} RETURNING ${returing}`;
7722
- return [{
7723
- sql,
7724
- values: rows.values
7725
- }];
7726
- }
7727
- case "count":
7728
- case "select": {
7729
- const isSelect = args._type === "select";
7730
- const q = isSelect ? args : args;
7731
- const where = getWhereStatement(q);
7732
- const columnsSQL = isSelect ? `SELECT ${renderNameAS(q._columns)}` : "SELECT count(*) as count";
7733
- const whereSQL = where.sql !== "" ? ` WHERE ${where.sql}` : "";
7734
- const fromSQL = ` FROM ${renderNameAS(q._selectFrom)}`;
7735
- const join9 = q._joins.map((j) => getJoin(j));
7736
- const joinValues = join9.reduce(function(ret, current) {
7737
- ret = ret.concat(current.values);
7738
- return ret;
7739
- }, []);
7740
- const joinSQL = join9.map((j) => j.sql).join(" ");
7741
- const sql = `${columnsSQL}${fromSQL}${joinSQL}${whereSQL}${getGroupBy(q._groupBy)}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)}`;
7742
- return [{
7743
- sql,
7744
- values: joinValues.concat(where.values)
7745
- }];
7746
- }
7747
- case "update": {
7748
- const q = args;
7749
- if (!q._sets || !q._table) {
7750
- throw new Error(`invalid ${args._type} with [${q._table}] and [${q._sets.join(",")}]`);
7751
- }
7752
- if (q._sets.length === 0) {
7753
- throw new Error(`invalid ${args._type} with [${q._table}] and [${q._sets.join(",")}]`);
7754
- }
7755
- const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
7756
- const where = getWhereStatement(q);
7757
- const whereSQL = where.sql !== "" ? ` WHERE ${where.sql}` : "";
7758
- const setSQL = ` SET ${q._sets.map((set) => `${set.column}=?`)}`;
7759
- const sql = `UPDATE ${q._table}${setSQL}${whereSQL}${getOrderBy(q._orderBy)}${getLimit(q._limitBy, q._offsetBy)} RETURNING ${returing}`;
7760
- return [{
7761
- sql,
7762
- values: q._sets.map((set) => set.value).concat(where.values)
7763
- }];
7764
- }
7765
- default:
7766
- throw new Error(`unsupported ${args}`);
7653
+ // node_modules/@miqro/query/build/query/utils.js
7654
+ function getStatements(stmts) {
7655
+ if (stmts instanceof Array) {
7656
+ return stmts;
7657
+ } else {
7658
+ return [
7659
+ typeof stmts === "string" ? {
7660
+ sql: stmts
7661
+ } : stmts
7662
+ ];
7767
7663
  }
7768
7664
  }
7769
- function getJoin(join9) {
7770
- const wherePrepare = getWhereStatement(join9._on);
7771
- return {
7772
- sql: ` ${join9._verb ? `${join9._verb} ` : ""}JOIN ${renderNameAS(join9._table)} ON ${wherePrepare.sql}`,
7773
- values: wherePrepare.values
7774
- };
7665
+ async function runStatementsInTransaction(db, stmts, logger) {
7666
+ return db.transaction(async function runStatementsInTransaction2(db2, logger2) {
7667
+ return runStatements(db2, stmts, logger2);
7668
+ }, logger);
7775
7669
  }
7776
- function getWhereFilterColumnName(filter) {
7777
- if (filter._column === void 0 || filter._value === void 0) {
7778
- throw new Error(`unsupported where filter ${filter._type} with ${filter._column} and ${filter._value}`);
7670
+ async function runStatements(db, stmts, logger) {
7671
+ if (stmts instanceof Array) {
7672
+ let lastResult = void 0;
7673
+ for (const stmt of stmts) {
7674
+ lastResult = await db.query(stmt.sql, stmt.values, logger);
7675
+ }
7676
+ return lastResult;
7677
+ } else if (typeof stmts === "string") {
7678
+ return db.query(stmts, void 0, logger);
7679
+ } else {
7680
+ return db.query(stmts.sql, stmts.values, logger);
7779
7681
  }
7780
- return filter;
7781
7682
  }
7782
- function getWhereStatement(where) {
7783
- const filters = where._filters;
7784
- let ret = {
7785
- sql: "",
7786
- values: []
7787
- };
7788
- filters.map((filter) => {
7789
- const where2 = filter._where;
7790
- switch (filter._type) {
7791
- case "where":
7792
- case "and": {
7793
- if (where2 === void 0) {
7794
- throw new Error(`unsupported where filter ${filter._type} with ${where2}`);
7795
- }
7796
- const prepare = mergePrepareArgs({
7797
- sql: "",
7798
- values: []
7799
- }, (where2 instanceof Array ? where2 : [where2]).map((w) => getWhereStatement(w)));
7800
- if (prepare.sql !== "") {
7801
- ret = mergePrepareArgs(ret, {
7802
- sql: `(${prepare.sql})`,
7803
- values: prepare.values
7804
- });
7805
- }
7806
- break;
7807
- }
7808
- case "literal": {
7809
- const literal = filter._literal;
7810
- if (literal === void 0) {
7811
- throw new Error(`unsupported where filter ${filter._type} with ${literal}`);
7812
- }
7813
- ret = mergePrepareArgs(ret, {
7814
- sql: `${literal}`,
7815
- values: []
7816
- });
7817
- break;
7818
- }
7819
- case "or": {
7820
- if (where2 === void 0) {
7821
- throw new Error(`unsupported where filter ${filter._type} with ${where2}`);
7822
- }
7823
- const prepare = mergePrepareArgs({
7824
- sql: "",
7825
- values: []
7826
- }, (where2 instanceof Array ? where2 : [where2]).map((w) => getWhereStatement(w)), " OR ");
7827
- ret = mergePrepareArgs(ret, {
7828
- sql: `(${prepare.sql})`,
7829
- values: prepare.values
7830
- });
7831
- break;
7832
- }
7833
- case "nin": {
7834
- const { _column, _value } = getWhereFilterColumnName(filter);
7835
- ret = mergePrepareArgs(ret, {
7836
- sql: `${renderColumn(_column)} not in (${_value.map((v) => "?").join(",")})`,
7837
- values: _value
7838
- });
7839
- break;
7840
- }
7841
- case "in": {
7842
- const { _column, _value } = getWhereFilterColumnName(filter);
7843
- ret = mergePrepareArgs(ret, {
7844
- sql: `${renderColumn(_column)} in (${_value.map((v) => "?").join(",")})`,
7845
- values: _value
7846
- });
7847
- break;
7848
- }
7849
- case "equal": {
7850
- const { _column, _value } = getWhereFilterColumnName(filter);
7851
- ret = mergePrepareArgs(ret, {
7852
- sql: `${renderColumn(_column)}=?`,
7853
- values: [_value]
7854
- });
7855
- break;
7856
- }
7857
- case "gt": {
7858
- const { _column, _value } = getWhereFilterColumnName(filter);
7859
- ret = mergePrepareArgs(ret, {
7860
- sql: `${renderColumn(_column)}>?`,
7861
- values: [_value]
7862
- });
7863
- break;
7864
- }
7865
- case "gte": {
7866
- const { _column, _value } = getWhereFilterColumnName(filter);
7867
- ret = mergePrepareArgs(ret, {
7868
- sql: `${renderColumn(_value)}>=?`,
7869
- values: [_value]
7870
- });
7871
- break;
7872
- }
7873
- case "lt": {
7874
- const { _column, _value } = getWhereFilterColumnName(filter);
7875
- ret = mergePrepareArgs(ret, {
7876
- sql: `${renderColumn(_column)}<?`,
7877
- values: [_value]
7878
- });
7879
- break;
7880
- }
7881
- case "lte": {
7882
- const { _column, _value } = getWhereFilterColumnName(filter);
7883
- ret = mergePrepareArgs(ret, {
7884
- sql: `${renderColumn(_column)}<=?`,
7885
- values: [_value]
7886
- });
7887
- break;
7888
- }
7889
- case "neq": {
7890
- const { _column, _value } = getWhereFilterColumnName(filter);
7891
- ret = mergePrepareArgs(ret, {
7892
- sql: `${renderColumn(_column)}<>?`,
7893
- values: [_value]
7894
- });
7895
- break;
7896
- }
7897
- case "like": {
7898
- const { _column, _value } = getWhereFilterColumnName(filter);
7899
- ret = mergePrepareArgs(ret, {
7900
- sql: `${renderColumn(_column)} LIKE ?`,
7901
- values: [_value]
7902
- });
7903
- break;
7904
- }
7905
- default:
7906
- throw new Error(`unsupported where filter ${filter._type}`);
7683
+
7684
+ // node_modules/@miqro/query/build/query/create-database.js
7685
+ var CreateDatabase = class _CreateDatabase {
7686
+ constructor(db, _dbName) {
7687
+ this.db = db;
7688
+ this._dbName = _dbName;
7689
+ this._type = "create-database";
7690
+ }
7691
+ async yield(logger) {
7692
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
7693
+ }
7694
+ clone() {
7695
+ const ret = new _CreateDatabase(this.db, this._dbName);
7696
+ return ret;
7697
+ }
7698
+ prepare() {
7699
+ return getStatements(this.db.getExecutor().prepare(this));
7700
+ }
7701
+ };
7702
+
7703
+ // node_modules/@miqro/query/build/query/create-table.js
7704
+ var CreateTable = class _CreateTable {
7705
+ constructor(db, _table, _definition = {}) {
7706
+ this.db = db;
7707
+ this._table = _table;
7708
+ this._definition = _definition;
7709
+ this._ignoreDuplicate = false;
7710
+ this._type = "create-table";
7711
+ this._definition = assertNotUndefined2(parser.parse(_definition, TableSchemaSchema));
7712
+ }
7713
+ column(column, definition) {
7714
+ if (!definition) {
7715
+ throw new Error("bad column definition");
7716
+ }
7717
+ if (this._definition[column] !== void 0) {
7718
+ throw new Error("already defined!");
7719
+ }
7720
+ const columnDef = assertNotUndefined2(parser.parse(typeof definition === "string" ? {
7721
+ type: definition
7722
+ } : definition, ColumnDefinitionSchema));
7723
+ this._definition[column] = columnDef;
7724
+ return this;
7725
+ }
7726
+ prepare() {
7727
+ return getStatements(this.db.getExecutor().prepare(this));
7728
+ }
7729
+ async yield(logger) {
7730
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
7731
+ }
7732
+ ignoreDuplicates(ignore = true) {
7733
+ this._ignoreDuplicate = ignore;
7734
+ return this;
7735
+ }
7736
+ clone() {
7737
+ const ret = new _CreateTable(this.db, this._table, this._definition);
7738
+ ret._ignoreDuplicate = this._ignoreDuplicate;
7739
+ return ret;
7740
+ }
7741
+ };
7742
+
7743
+ // node_modules/@miqro/query/build/query/drop-table.js
7744
+ var DropTable = class _DropTable {
7745
+ constructor(db, _table) {
7746
+ this.db = db;
7747
+ this._table = _table;
7748
+ this._type = "drop-table";
7749
+ this._ignoreDuplicate = false;
7750
+ }
7751
+ prepare() {
7752
+ return getStatements(this.db.getExecutor().prepare(this));
7753
+ }
7754
+ ignoreDuplicates(ignore = true) {
7755
+ this._ignoreDuplicate = ignore;
7756
+ return this;
7757
+ }
7758
+ async yield(logger) {
7759
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
7760
+ }
7761
+ clone() {
7762
+ const ret = new _DropTable(this.db, this._table);
7763
+ ret._ignoreDuplicate = this._ignoreDuplicate;
7764
+ return ret;
7765
+ }
7766
+ };
7767
+
7768
+ // node_modules/@miqro/query/build/query/alter-table.js
7769
+ var AlterTable = class _AlterTable {
7770
+ constructor(db, _table, _inTransaction = false) {
7771
+ this.db = db;
7772
+ this._table = _table;
7773
+ this._inTransaction = _inTransaction;
7774
+ this._type = "alter-table";
7775
+ this._changes = [];
7776
+ }
7777
+ rename(name) {
7778
+ this._renameTable = name;
7779
+ return this;
7780
+ }
7781
+ renameColumn(name, to) {
7782
+ this._changes.push({
7783
+ _action: "rename",
7784
+ _column: name,
7785
+ _newName: to
7786
+ });
7787
+ return this;
7788
+ }
7789
+ addColumn(name, definition) {
7790
+ this._changes.push({
7791
+ _action: "add",
7792
+ _column: name,
7793
+ _definition: assertNotUndefined2(parser.parse(definition, ColumnDefinitionSchema))
7794
+ });
7795
+ return this;
7796
+ }
7797
+ dropColumn(name) {
7798
+ this._changes.push({
7799
+ _action: "drop",
7800
+ _column: name
7801
+ });
7802
+ return this;
7803
+ }
7804
+ clone() {
7805
+ const ret = new _AlterTable(this.db, this._table);
7806
+ ret._changes = structuredClone(this._changes);
7807
+ ret._renameTable = this._renameTable;
7808
+ return ret;
7809
+ }
7810
+ prepare() {
7811
+ return getStatements(this.db.getExecutor().prepare(this));
7812
+ }
7813
+ yield(logger) {
7814
+ return this._inTransaction ? runStatementsInTransaction(this.db, this.db.getExecutor().prepare(this), logger) : runStatements(this.db, this.db.getExecutor().prepare(this), logger);
7815
+ }
7816
+ };
7817
+
7818
+ // node_modules/@miqro/query/build/query/insert.js
7819
+ var Insert = class _Insert {
7820
+ constructor(db, _table) {
7821
+ this.db = db;
7822
+ this._table = _table;
7823
+ this._type = "insert";
7824
+ this._columns = [];
7825
+ this._returning = [];
7826
+ this._values = [];
7827
+ this._ignoreDuplicate = false;
7828
+ }
7829
+ value(value) {
7830
+ this._values = this._values.concat(value);
7831
+ return this;
7832
+ }
7833
+ values(value) {
7834
+ return this.value(value);
7835
+ }
7836
+ returning(column) {
7837
+ this._returning = this._returning.concat(column);
7838
+ return this;
7839
+ }
7840
+ column(column) {
7841
+ this._columns = this._columns.concat(column);
7842
+ return this;
7843
+ }
7844
+ columns(column) {
7845
+ return this.column(column);
7846
+ }
7847
+ prepare() {
7848
+ return getStatements(this.db.getExecutor().prepare(this));
7849
+ }
7850
+ async yield(logger) {
7851
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
7852
+ }
7853
+ ignoreDuplicates(ignore = true) {
7854
+ this._ignoreDuplicate = ignore;
7855
+ return this;
7856
+ }
7857
+ clone() {
7858
+ const ret = new _Insert(this.db, this._table);
7859
+ ret._columns = structuredClone(this._columns);
7860
+ ret._values = structuredClone(this._values);
7861
+ ret._returning = structuredClone(this._returning);
7862
+ ret._ignoreDuplicate = this._ignoreDuplicate;
7863
+ return ret;
7864
+ }
7865
+ };
7866
+
7867
+ // node_modules/@miqro/query/build/executors/where.js
7868
+ var Where = class {
7869
+ constructor() {
7870
+ this._orderBy = [];
7871
+ this._filters = [];
7872
+ }
7873
+ order(column, mode) {
7874
+ this._orderBy.push({ column, mode });
7875
+ return this;
7876
+ }
7877
+ limit(limit) {
7878
+ this._limitBy = limit;
7879
+ return this;
7880
+ }
7881
+ offset(offset) {
7882
+ this._offsetBy = offset;
7883
+ return this;
7884
+ }
7885
+ and(where) {
7886
+ this._filters.push({
7887
+ _type: "and",
7888
+ _where: where
7889
+ });
7890
+ return this;
7891
+ }
7892
+ or(where) {
7893
+ this._filters.push({
7894
+ _type: "or",
7895
+ _where: where
7896
+ });
7897
+ return this;
7898
+ }
7899
+ where(where) {
7900
+ this._filters.push({
7901
+ _type: "where",
7902
+ _where: where
7903
+ });
7904
+ if (where._orderBy.length > 0) {
7905
+ this._orderBy.push(...where._orderBy);
7907
7906
  }
7908
- });
7909
- return ret;
7910
- }
7911
- function getCreateTableColumns(definition) {
7912
- const columnNames = Object.keys(definition);
7913
- const primaryKeyColumns = columnNames.filter((columnName) => definition[columnName].primaryKey);
7914
- return `(${columnNames.map((columnName) => {
7915
- const def = definition[columnName];
7916
- return getCreateTableColumn(columnName, def, primaryKeyColumns);
7917
- }).concat(primaryKeyColumns.length > 1 ? [
7918
- `PRIMARY KEY( ${primaryKeyColumns.join(",")} )`
7919
- ] : []).join(", ")})`;
7920
- }
7921
- function getCreateTableColumn(columnName, def, primaryKeyColumns) {
7922
- const primaryKey = primaryKeyColumns.length === 1 && columnName === primaryKeyColumns[0] ? " PRIMARY KEY" : "";
7923
- const notNull = `${def.allowNull == false ? " NOT NULL" : ""}`;
7924
- const defaultValue = `${def.defaultValue !== void 0 ? ` DEFAULT '${def.defaultValue}'` : ""}`;
7925
- const autoIncrement = `${def.autoIncrement !== void 0 && def.autoIncrement === true ? ` AUTOINCREMENT` : ""}`;
7926
- switch (def.type) {
7927
- case "datetime":
7928
- return `${columnName} DATETIME${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7929
- case "boolean":
7930
- return `${columnName} TINYINT${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7931
- case "json":
7932
- case "string":
7933
- return `${columnName} TEXT${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7934
- case "real":
7935
- return `${columnName} REAL${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7936
- case "bigint":
7937
- case "integer":
7938
- return `${columnName} INTEGER${primaryKey}${notNull}${defaultValue}${autoIncrement}`;
7939
- default:
7940
- throw new Error("unsupported type " + def.type);
7907
+ if (where._limitBy) {
7908
+ this._limitBy = where._limitBy;
7909
+ }
7910
+ if (where._offsetBy) {
7911
+ this._offsetBy = where._offsetBy;
7912
+ }
7913
+ return this;
7941
7914
  }
7942
- }
7943
- function getInsertColumns(columns) {
7944
- return `(${columns.join(",")})`;
7945
- }
7946
- function getInsertValues(columns, values) {
7947
- let args = [];
7948
- for (const v of values) {
7949
- args = args.concat(columns.map((c) => v[c]));
7915
+ nin(column, value) {
7916
+ {
7917
+ this._filters.push({
7918
+ _type: "nin",
7919
+ _column: column,
7920
+ _value: value
7921
+ });
7922
+ return this;
7923
+ }
7950
7924
  }
7951
- return {
7952
- sql: ` VALUES ${values.map(() => `(${columns.map(() => "?").join(", ")})`)}`,
7953
- values: args
7954
- };
7955
- }
7956
- function renderNameAS(input, join9 = ", ") {
7957
- const list = input instanceof Array ? input : [input];
7958
- return list.map((i) => typeof i === "string" ? i : `${i.name} AS ${i.as}`).join(join9);
7959
- }
7960
- function getGroupBy(groupBy) {
7961
- return groupBy.length > 0 ? ` GROUP BY ${groupBy.join(",")}` : "";
7962
- }
7963
- function getOrderBy(orderBy) {
7964
- return orderBy.length > 0 ? ` ORDER BY ${orderBy.map((o) => `${o.column} ${o.mode}`).join(",")}` : "";
7965
- }
7966
- function getLimit(limit, offsetBy) {
7967
- return `${limit !== void 0 ? ` LIMIT ${limit}` : ""}${offsetBy ? ` OFFSET ${offsetBy}` : ""}`;
7968
- }
7969
- function renderColumn(column) {
7970
- return column;
7971
- }
7972
- function mergePrepareArgs(to, merge, concatOperator = " AND ") {
7973
- return (merge instanceof Array ? merge : [merge]).reduce((current, value) => {
7974
- if (current.sql !== "") {
7975
- current.sql += concatOperator;
7925
+ in(column, value) {
7926
+ {
7927
+ this._filters.push({
7928
+ _type: "in",
7929
+ _column: column,
7930
+ _value: value
7931
+ });
7932
+ return this;
7976
7933
  }
7977
- current.sql += value.sql;
7978
- current.values = !value.values ? current.values : (current.values ? current.values : []).concat(value.values);
7979
- return current;
7980
- }, to);
7981
- }
7934
+ }
7935
+ eq(column, value) {
7936
+ this._filters.push({
7937
+ _type: "equal",
7938
+ _column: column,
7939
+ _value: value
7940
+ });
7941
+ return this;
7942
+ }
7943
+ like(column, value) {
7944
+ this._filters.push({
7945
+ _type: "like",
7946
+ _column: column,
7947
+ _value: value
7948
+ });
7949
+ return this;
7950
+ }
7951
+ gte(column, value) {
7952
+ this._filters.push({
7953
+ _type: "gte",
7954
+ _column: column,
7955
+ _value: value
7956
+ });
7957
+ return this;
7958
+ }
7959
+ gt(column, value) {
7960
+ this._filters.push({
7961
+ _type: "gt",
7962
+ _column: column,
7963
+ _value: value
7964
+ });
7965
+ return this;
7966
+ }
7967
+ lte(column, value) {
7968
+ this._filters.push({
7969
+ _type: "lte",
7970
+ _column: column,
7971
+ _value: value
7972
+ });
7973
+ return this;
7974
+ }
7975
+ lt(column, value) {
7976
+ this._filters.push({
7977
+ _type: "lt",
7978
+ _column: column,
7979
+ _value: value
7980
+ });
7981
+ return this;
7982
+ }
7983
+ neq(column, value) {
7984
+ this._filters.push({
7985
+ _type: "neq",
7986
+ _column: column,
7987
+ _value: value
7988
+ });
7989
+ return this;
7990
+ }
7991
+ literal(literal) {
7992
+ this._filters.push({
7993
+ _type: "literal",
7994
+ _literal: literal
7995
+ });
7996
+ return this;
7997
+ }
7998
+ };
7982
7999
 
7983
- // node_modules/@miqro/query/build/executors/parser.js
7984
- var parser = new Parser();
7985
- function assertNotUndefined2(obj) {
7986
- if (obj === void 0) {
7987
- throw new Error("validation failed");
8000
+ // node_modules/@miqro/query/build/query/select.js
8001
+ var Select = class _Select extends Where {
8002
+ constructor(db) {
8003
+ super();
8004
+ this.db = db;
8005
+ this._type = "select";
8006
+ this._columns = [];
8007
+ this._selectFrom = [];
8008
+ this._groupBy = [];
8009
+ this._joins = [];
8010
+ this._orderBy = [];
7988
8011
  }
7989
- return obj;
7990
- }
7991
- var DATABASE_CONFIG_SCHEMA = {
7992
- type: "object",
7993
- properties: {
7994
- executor: {
7995
- type: "object?",
7996
- mode: "add_extra",
7997
- properties: {
7998
- prepare: "function",
7999
- query: "function",
8000
- disconnect: "function"
8001
- }
8002
- },
8003
- logger: {
8004
- type: "object?",
8005
- mode: "add_extra",
8006
- properties: {
8007
- log: "function?",
8008
- error: "function?"
8009
- }
8010
- },
8011
- storage: "string?",
8012
- connectionString: "string?",
8013
- dialect: {
8014
- type: "enum?",
8015
- enumValues: ["node:sqlite", "sqlite3-cli", "sqlite3", "pg"]
8012
+ prepare() {
8013
+ return getStatements(this.db.getExecutor().prepare(this));
8014
+ }
8015
+ clone() {
8016
+ const ret = new _Select(this.db);
8017
+ ret._filters = structuredClone(this._filters);
8018
+ ret._columns = structuredClone(this._columns);
8019
+ ret._groupBy = structuredClone(this._groupBy);
8020
+ ret._selectFrom = structuredClone(this._selectFrom);
8021
+ ret._orderBy = structuredClone(this._orderBy);
8022
+ ret._joins = structuredClone(this._joins);
8023
+ ret._limitBy = this._limitBy;
8024
+ ret._offsetBy = this._offsetBy;
8025
+ return ret;
8026
+ }
8027
+ async yield(logger) {
8028
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8029
+ }
8030
+ column(column) {
8031
+ if (column instanceof Array) {
8032
+ this._columns = this._columns.concat(column);
8033
+ } else {
8034
+ this._columns.push(column);
8016
8035
  }
8036
+ return this;
8017
8037
  }
8018
- };
8019
- var ColumnDefinitionTypeSchema = {
8020
- type: "enum",
8021
- enumValues: ["string", "integer", "boolean", "datetime", "json", "real", "bigint"]
8022
- };
8023
- var ColumnDefinitionSchema = {
8024
- type: "object",
8025
- properties: {
8026
- type: ColumnDefinitionTypeSchema,
8027
- primaryKey: "boolean?",
8028
- autoIncrement: "boolean?",
8029
- allowNull: "boolean?",
8030
- defaultValue: "any?"
8038
+ columns(column) {
8039
+ return this.column(column);
8040
+ }
8041
+ from(from) {
8042
+ if (from instanceof Array) {
8043
+ this._selectFrom = this._selectFrom.concat(from);
8044
+ } else {
8045
+ this._selectFrom.push(from);
8046
+ }
8047
+ return this;
8048
+ }
8049
+ join(table, on, verb) {
8050
+ this._joins.push({
8051
+ _table: table,
8052
+ _on: on,
8053
+ _verb: verb
8054
+ });
8055
+ return this;
8056
+ }
8057
+ left(table, on) {
8058
+ return this.join(table, on, "LEFT");
8059
+ }
8060
+ right(table, on) {
8061
+ return this.join(table, on, "RIGHT");
8062
+ }
8063
+ group(column) {
8064
+ this._groupBy.push(column);
8065
+ return this;
8031
8066
  }
8032
- };
8033
- parser.register("ColumnDefinition", ColumnDefinitionSchema);
8034
- var TableSchemaSchema = {
8035
- type: "dict",
8036
- dictType: "ColumnDefinition"
8037
8067
  };
8038
8068
 
8039
- // node_modules/@miqro/query/build/executors/sqlite3/lib.js
8040
- var SQLITE_CONFIG_SCHEMA = {
8041
- type: "object",
8042
- mode: "remove_extra",
8043
- properties: {
8044
- storage: "string"
8069
+ // node_modules/@miqro/query/build/query/count.js
8070
+ var Count = class _Count extends Where {
8071
+ constructor(db) {
8072
+ super();
8073
+ this.db = db;
8074
+ this._type = "count";
8075
+ this._selectFrom = [];
8076
+ this._groupBy = [];
8077
+ this._joins = [];
8045
8078
  }
8046
- };
8047
- async function sqlite3Executor(config) {
8048
- const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA);
8049
- if (!databaseOptions) {
8050
- throw new Error("config not valid");
8079
+ clone() {
8080
+ const ret = new _Count(this.db);
8081
+ ret._filters = structuredClone(this._filters);
8082
+ ret._groupBy = structuredClone(this._groupBy);
8083
+ ret._joins = structuredClone(this._joins);
8084
+ ret._selectFrom = structuredClone(this._selectFrom);
8085
+ ret._orderBy = structuredClone(this._orderBy);
8086
+ ret._limitBy = this._limitBy;
8087
+ ret._offsetBy = this._offsetBy;
8088
+ return ret;
8051
8089
  }
8052
- const sqlite3 = await import("sqlite3");
8053
- const driver = new sqlite3.default.Database(databaseOptions.storage);
8054
- return {
8055
- disconnect: async function sqlite3ExecutorDisconnect() {
8056
- await driver.close();
8057
- },
8058
- prepare: sqlite3ExecutorPrepare,
8059
- query: async function sqlite3Executor2(sql, values) {
8060
- return new Promise((resolve20, reject) => {
8061
- const st = driver.prepare(sql, values, function(error2) {
8062
- if (error2) {
8063
- reject(error2);
8064
- } else {
8065
- st.all(function(error3, rows) {
8066
- if (error3) {
8067
- reject(error3);
8068
- } else {
8069
- st.finalize((error4) => {
8070
- if (error4) {
8071
- reject(error4);
8072
- } else {
8073
- resolve20(rows);
8074
- }
8075
- });
8076
- }
8077
- });
8078
- }
8079
- });
8080
- });
8081
- }
8082
- };
8083
- }
8084
-
8085
- // node_modules/@miqro/query/build/executors/pg/lib.js
8086
- var PG_DATABASE_CONFIG_SCHEMA = {
8087
- type: "object",
8088
- mode: "remove_extra",
8089
- properties: {
8090
- connectionString: "string"
8090
+ from(from) {
8091
+ this._selectFrom = this._selectFrom.concat(from);
8092
+ return this;
8091
8093
  }
8092
- };
8093
- async function postgresExecutor(config) {
8094
- const databaseOptions = parser.parse(config, PG_DATABASE_CONFIG_SCHEMA);
8095
- if (!databaseOptions) {
8096
- throw new Error("bad options");
8094
+ join(table, on, verb) {
8095
+ this._joins.push({
8096
+ _table: table,
8097
+ _on: on,
8098
+ _verb: verb
8099
+ });
8100
+ return this;
8097
8101
  }
8098
- const pg = await import("pg");
8099
- const driver = new pg.default.Client({
8100
- connectionString: databaseOptions.connectionString
8101
- // "postgresql://postgres:password@localhost:5432/db"
8102
- });
8103
- await driver.connect();
8104
- return {
8105
- disconnect: async function postgresExecutorDisconnect() {
8106
- await driver.end();
8107
- },
8108
- prepare: function postgresExecutorPrepare(args) {
8109
- switch (args._type) {
8110
- case "create-table": {
8111
- const q = args;
8112
- const sql = `CREATE TABLE${q._ignoreDuplicate ? " IF NOT EXISTS" : ""} ${q._table}${getCreateTableColumns2(q._definition)}`;
8113
- return sql;
8114
- }
8115
- case "insert": {
8116
- const q = args;
8117
- const rows = getInsertValues(q._columns, q._values);
8118
- const returing = q._returning.length === 0 ? "*" : q._returning.join(",");
8119
- const sql = `INSERT INTO ${q._table}${getInsertColumns(q._columns)}${rows.sql} ${q._ignoreDuplicate ? "ON CONFLICT DO NOTHING " : ""}RETURNING ${returing}`;
8120
- return {
8121
- sql,
8122
- values: rows.values
8123
- };
8124
- }
8125
- case "alter-table": {
8126
- const q = args;
8127
- let alters = [];
8128
- if (q._renameTable) {
8129
- alters.push({
8130
- sql: `ALTER TABLE ${q._table} RENAME TO ?`,
8131
- values: [q._renameTable]
8132
- });
8133
- }
8134
- for (let l of q._changes) {
8135
- switch (l._action) {
8136
- case "add":
8137
- if (!l._definition) {
8138
- throw new Error("unsupported alter action add without definition");
8139
- }
8140
- alters.push({
8141
- sql: `ALTER TABLE ${q._table} ADD COLUMN ${getCreateTableColumn2(l._column, l._definition, [])}`
8142
- });
8143
- break;
8144
- case "drop":
8145
- alters.push({
8146
- sql: `ALTER TABLE ${q._table} DROP COLUMN ${l._column}`
8147
- });
8148
- break;
8149
- case "rename":
8150
- alters.push({
8151
- sql: `ALTER TABLE ${q._table} RENAME COLUMN ${l._column} TO ${l._newName}`
8152
- });
8153
- break;
8154
- default:
8155
- throw new Error("unsupported alter action");
8156
- }
8157
- }
8158
- return alters;
8159
- }
8160
- default:
8161
- return sqlite3ExecutorPrepare(args);
8162
- }
8163
- },
8164
- query: async function postgresExecutor2(sql, values) {
8165
- try {
8166
- const result = await driver.query(tokens2Postgres(sql, values), values);
8167
- return result.rows;
8168
- } catch (e) {
8169
- throw e;
8170
- }
8171
- }
8172
- };
8173
- }
8174
- function getCreateTableColumns2(definition) {
8175
- const columnNames = Object.keys(definition);
8176
- const primaryKeyColumns = columnNames.filter((columnName) => definition[columnName].primaryKey);
8177
- return `(${columnNames.map((columnName) => {
8178
- const def = definition[columnName];
8179
- return getCreateTableColumn2(columnName, def, primaryKeyColumns);
8180
- }).concat(primaryKeyColumns.length > 1 ? [
8181
- `PRIMARY KEY( ${primaryKeyColumns.join(",")} )`
8182
- ] : []).join(", ")})`;
8183
- }
8184
- function getCreateTableColumn2(columnName, def, primaryKeyColumns) {
8185
- const primaryKey = primaryKeyColumns.length === 1 && columnName === primaryKeyColumns[0] ? " PRIMARY KEY" : "";
8186
- const notNull = `${def.allowNull == false ? " NOT NULL" : ""}`;
8187
- const defaultValue = `${def.defaultValue !== void 0 ? ` DEFAULT '${def.defaultValue}'` : ""}`;
8188
- if (def.autoIncrement) {
8189
- return `${columnName} BIGSERIAL${primaryKey}`;
8102
+ left(table, on) {
8103
+ return this.join(table, on, "LEFT");
8190
8104
  }
8191
- switch (def.type) {
8192
- case "datetime":
8193
- return `${columnName} TIMESTAMP${primaryKey}${notNull}${defaultValue}`;
8194
- case "boolean":
8195
- return `${columnName} BOOLEAN${primaryKey}${notNull}${defaultValue}`;
8196
- case "real":
8197
- return `${columnName} REAL${primaryKey}${notNull}${defaultValue}`;
8198
- case "json":
8199
- case "string":
8200
- return `${columnName} TEXT${primaryKey}${notNull}${defaultValue}`;
8201
- case "bigint":
8202
- return `${columnName} bigint${primaryKey}${notNull}${defaultValue}`;
8203
- case "integer":
8204
- return `${columnName} INTEGER${primaryKey}${notNull}${defaultValue}`;
8205
- default:
8206
- throw new Error("unsupported type " + def.type);
8105
+ right(table, on) {
8106
+ return this.join(table, on, "RIGHT");
8107
+ }
8108
+ group(column) {
8109
+ this._groupBy.push(column);
8110
+ return this;
8111
+ }
8112
+ prepare() {
8113
+ return getStatements(this.db.getExecutor().prepare(this));
8114
+ }
8115
+ async yield(logger) {
8116
+ return parseCountResult(await runStatements(this.db, this.db.getExecutor().prepare(this), logger));
8207
8117
  }
8118
+ };
8119
+ async function parseCountResult(rows) {
8120
+ return {
8121
+ count: parseInt(rows[0].count, 10)
8122
+ };
8208
8123
  }
8209
- function tokens2Postgres(inSql, values) {
8210
- let i = 0;
8211
- const sql = inSql.replaceAll("?", (string) => {
8212
- i++;
8213
- return `$${i}`;
8214
- });
8215
- if (i !== (values ? values.length : 0)) {
8216
- throw new Error("invalid char '?'");
8124
+
8125
+ // node_modules/@miqro/query/build/query/update.js
8126
+ var Update = class _Update extends Where {
8127
+ constructor(db, _table) {
8128
+ super();
8129
+ this.db = db;
8130
+ this._table = _table;
8131
+ this._type = "update";
8132
+ this._sets = [];
8133
+ this._returning = [];
8217
8134
  }
8218
- let iSum = 0;
8219
- for (const c of sql) {
8220
- if (c === "$") {
8221
- iSum++;
8222
- }
8135
+ prepare() {
8136
+ return getStatements(this.db.getExecutor().prepare(this));
8223
8137
  }
8224
- if (iSum !== i) {
8225
- throw new Error("invalid char '$'");
8138
+ async yield(logger) {
8139
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8226
8140
  }
8227
- return sql;
8228
- }
8141
+ clone() {
8142
+ const ret = new _Update(this.db, this._table);
8143
+ ret._filters = structuredClone(this._filters);
8144
+ ret._orderBy = structuredClone(this._orderBy);
8145
+ ret._sets = structuredClone(this._sets);
8146
+ ret._returning = structuredClone(this._returning);
8147
+ ret._limitBy = this._limitBy;
8148
+ ret._offsetBy = this._offsetBy;
8149
+ return ret;
8150
+ }
8151
+ returning(column) {
8152
+ this._returning = this._returning.concat(column);
8153
+ return this;
8154
+ }
8155
+ set(column, value) {
8156
+ this._sets.push({
8157
+ column,
8158
+ value
8159
+ });
8160
+ return this;
8161
+ }
8162
+ };
8229
8163
 
8230
- // node_modules/@miqro/query/build/query/utils.js
8231
- function getStatements(stmts) {
8232
- if (stmts instanceof Array) {
8233
- return stmts;
8234
- } else {
8235
- return [
8236
- typeof stmts === "string" ? {
8237
- sql: stmts
8238
- } : stmts
8239
- ];
8164
+ // node_modules/@miqro/query/build/query/delete.js
8165
+ var Delete = class _Delete extends Where {
8166
+ constructor(db, _table) {
8167
+ super();
8168
+ this.db = db;
8169
+ this._table = _table;
8170
+ this._type = "delete";
8171
+ this._returning = [];
8240
8172
  }
8241
- }
8242
- async function runStatementsInTransaction(db, stmts, logger) {
8243
- return db.transaction(async function runStatementsInTransaction2(db2, logger2) {
8244
- return runStatements(db2, stmts, logger2);
8245
- }, logger);
8246
- }
8247
- async function runStatements(db, stmts, logger) {
8248
- if (stmts instanceof Array) {
8249
- let lastResult = void 0;
8250
- for (const stmt of stmts) {
8251
- lastResult = await db.query(stmt.sql, stmt.values, logger);
8252
- }
8253
- return lastResult;
8254
- } else if (typeof stmts === "string") {
8255
- return db.query(stmts, void 0, logger);
8256
- } else {
8257
- return db.query(stmts.sql, stmts.values, logger);
8173
+ prepare() {
8174
+ return getStatements(this.db.getExecutor().prepare(this));
8258
8175
  }
8259
- }
8176
+ async yield(logger) {
8177
+ return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8178
+ }
8179
+ clone() {
8180
+ const ret = new _Delete(this.db, this._table);
8181
+ ret._filters = structuredClone(this._filters);
8182
+ ret._orderBy = structuredClone(this._orderBy);
8183
+ ret._returning = structuredClone(this._returning);
8184
+ ret._limitBy = this._limitBy;
8185
+ ret._offsetBy = this._offsetBy;
8186
+ return ret;
8187
+ }
8188
+ returning(column) {
8189
+ this._returning = this._returning.concat(column);
8190
+ return this;
8191
+ }
8192
+ };
8260
8193
 
8261
- // node_modules/@miqro/query/build/query/create-database.js
8262
- var CreateDatabase = class _CreateDatabase {
8194
+ // node_modules/@miqro/query/build/query/drop-database.js
8195
+ var DropDatabase = class _DropDatabase {
8263
8196
  constructor(db, _dbName) {
8264
8197
  this.db = db;
8265
8198
  this._dbName = _dbName;
8266
- this._type = "create-database";
8199
+ this._type = "drop-database";
8200
+ this._ignoreDuplicate = false;
8201
+ }
8202
+ prepare() {
8203
+ return getStatements(this.db.getExecutor().prepare(this));
8204
+ }
8205
+ ignoreDuplicates(ignore = true) {
8206
+ this._ignoreDuplicate = ignore;
8207
+ return this;
8267
8208
  }
8268
8209
  async yield(logger) {
8269
8210
  return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8270
8211
  }
8271
8212
  clone() {
8272
- const ret = new _CreateDatabase(this.db, this._dbName);
8213
+ const ret = new _DropDatabase(this.db, this._dbName);
8214
+ ret._ignoreDuplicate = this._ignoreDuplicate;
8273
8215
  return ret;
8274
8216
  }
8275
- prepare() {
8276
- return getStatements(this.db.getExecutor().prepare(this));
8217
+ };
8218
+
8219
+ // node_modules/@miqro/query/build/executors/sqlite3-cli/lib.js
8220
+ var import_child_process = require("child_process");
8221
+ var SQLITE_CONFIG_SCHEMA2 = {
8222
+ type: "object",
8223
+ mode: "remove_extra",
8224
+ properties: {
8225
+ storage: "string"
8277
8226
  }
8278
8227
  };
8228
+ async function sqlite3CLIExecutor(config) {
8229
+ const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA2);
8230
+ if (!databaseOptions) {
8231
+ throw new Error("config not valid");
8232
+ }
8233
+ (config.logger ? config.logger : console).error(`sqlite3-cli is affected by sql injection. do not use! only for testing!`);
8234
+ return {
8235
+ // we just use the sqlite3Executor prepare function
8236
+ prepare: sqlite3ExecutorPrepare,
8237
+ disconnect: async function sqlite3ExecutorDisconnect() {
8238
+ },
8239
+ query: async function sqlite3Executor2(sql, values) {
8240
+ return new Promise((resolve20, reject) => {
8241
+ try {
8242
+ let i = 0;
8243
+ const raw = sql.replaceAll("?", (sub) => {
8244
+ const value = values ? values[i] : void 0;
8245
+ if (value === void 0) {
8246
+ throw new Error("cannot convert query");
8247
+ }
8248
+ i++;
8249
+ return `'${value}'`;
8250
+ });
8251
+ if (values && i !== values.length) {
8252
+ throw new Error("cannot convert query");
8253
+ }
8254
+ (0, import_child_process.exec)(`sqlite3 -json "${databaseOptions.storage}" "${raw}"`, (error2, stdout, stderr) => {
8255
+ try {
8256
+ if (error2) {
8257
+ if (stderr) {
8258
+ reject(new Error(stderr));
8259
+ } else {
8260
+ reject(error2);
8261
+ }
8262
+ } else {
8263
+ if (stderr) {
8264
+ reject(new Error(stderr));
8265
+ } else {
8266
+ if (stdout) {
8267
+ resolve20(JSON.parse(stdout));
8268
+ } else {
8269
+ resolve20([]);
8270
+ }
8271
+ }
8272
+ }
8273
+ } catch (e2) {
8274
+ reject(e2);
8275
+ }
8276
+ });
8277
+ } catch (e) {
8278
+ reject(e);
8279
+ }
8280
+ });
8281
+ }
8282
+ };
8283
+ }
8279
8284
 
8280
- // node_modules/@miqro/query/build/query/create-table.js
8281
- var CreateTable = class _CreateTable {
8282
- constructor(db, _table, _definition = {}) {
8283
- this.db = db;
8284
- this._table = _table;
8285
- this._definition = _definition;
8286
- this._ignoreDuplicate = false;
8287
- this._type = "create-table";
8288
- this._definition = assertNotUndefined2(parser.parse(_definition, TableSchemaSchema));
8285
+ // node_modules/@miqro/query/build/executors/sqlite-native/lib.js
8286
+ var SQLITE_CONFIG_SCHEMA3 = {
8287
+ type: "object",
8288
+ mode: "remove_extra",
8289
+ properties: {
8290
+ storage: "string"
8291
+ }
8292
+ };
8293
+ async function nativeSqlite(config) {
8294
+ const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA3);
8295
+ if (!databaseOptions) {
8296
+ throw new Error("config not valid");
8297
+ }
8298
+ const sqliteModule = await import("node:sqlite");
8299
+ const driver = new sqliteModule.DatabaseSync(databaseOptions.storage);
8300
+ return {
8301
+ // we just use the sqlite3Executor prepare function
8302
+ prepare: sqlite3ExecutorPrepare,
8303
+ disconnect: async function sqlite3ExecutorDisconnect() {
8304
+ return driver.close();
8305
+ },
8306
+ query: async function sqlite3Executor2(sql, values) {
8307
+ return new Promise((resolve20, reject) => {
8308
+ try {
8309
+ if (values) {
8310
+ for (let i = 0; i < values.length; i++) {
8311
+ switch (typeof values[i]) {
8312
+ case "object":
8313
+ if (values[i] instanceof Date) {
8314
+ values[i] = values[i].toString();
8315
+ }
8316
+ break;
8317
+ case "boolean":
8318
+ values[i] = values[i] ? 1 : 0;
8319
+ break;
8320
+ }
8321
+ }
8322
+ }
8323
+ const stmt = driver.prepare(sql);
8324
+ stmt.setReadBigInts(true);
8325
+ if (values && values.length > 0) {
8326
+ const ret = stmt.all(...values);
8327
+ resolve20(ret);
8328
+ } else {
8329
+ const ret = stmt.all();
8330
+ resolve20(ret);
8331
+ }
8332
+ } catch (e) {
8333
+ reject(e);
8334
+ }
8335
+ });
8336
+ }
8337
+ };
8338
+ }
8339
+
8340
+ // node_modules/@miqro/query/build/db.js
8341
+ var Database = class {
8342
+ constructor(config) {
8343
+ this.config = config;
8344
+ this.status = "disconnected";
8345
+ this.executor = null;
8346
+ parser.parse(config, DATABASE_CONFIG_SCHEMA, "no_extra");
8347
+ this.executor = null;
8289
8348
  }
8290
- column(column, definition) {
8291
- if (!definition) {
8292
- throw new Error("bad column definition");
8349
+ async connect() {
8350
+ if (this.status !== "disconnected") {
8351
+ throw new Error(`cannot connect while ${this.status}`);
8293
8352
  }
8294
- if (this._definition[column] !== void 0) {
8295
- throw new Error("already defined!");
8353
+ if (this.executor !== null) {
8354
+ throw new Error(`cannot connect executor exists!`);
8355
+ }
8356
+ this.status = "connecting";
8357
+ try {
8358
+ this.executor = await getExecutor(this.config);
8359
+ this.status = "connected";
8360
+ } catch (e) {
8361
+ this.status = "error";
8362
+ throw e;
8296
8363
  }
8297
- const columnDef = assertNotUndefined2(parser.parse(typeof definition === "string" ? {
8298
- type: definition
8299
- } : definition, ColumnDefinitionSchema));
8300
- this._definition[column] = columnDef;
8301
- return this;
8302
- }
8303
- prepare() {
8304
- return getStatements(this.db.getExecutor().prepare(this));
8305
- }
8306
- async yield(logger) {
8307
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8308
8364
  }
8309
- ignoreDuplicates(ignore = true) {
8310
- this._ignoreDuplicate = ignore;
8311
- return this;
8365
+ async disconnect() {
8366
+ if (this.status !== "connected") {
8367
+ throw new Error(`cannot disconnect while ${this.status}`);
8368
+ }
8369
+ this.status = "disconnecting";
8370
+ try {
8371
+ await this.getExecutor().disconnect();
8372
+ this.executor = null;
8373
+ this.status = "disconnected";
8374
+ } catch (e) {
8375
+ this.status = "error";
8376
+ throw e;
8377
+ }
8312
8378
  }
8313
- clone() {
8314
- const ret = new _CreateTable(this.db, this._table, this._definition);
8315
- ret._ignoreDuplicate = this._ignoreDuplicate;
8316
- return ret;
8379
+ getExecutor() {
8380
+ if (!this.executor) {
8381
+ throw new Error("executor not initialized!");
8382
+ }
8383
+ return this.executor;
8317
8384
  }
8318
- };
8319
-
8320
- // node_modules/@miqro/query/build/query/drop-table.js
8321
- var DropTable = class _DropTable {
8322
- constructor(db, _table) {
8323
- this.db = db;
8324
- this._table = _table;
8325
- this._type = "drop-table";
8326
- this._ignoreDuplicate = false;
8385
+ async query(sql, values, logger) {
8386
+ const l = logger ? logger : this.config.logger ? this.config.logger : void 0;
8387
+ try {
8388
+ l?.log(sql);
8389
+ const result = await this.getExecutor().query(sql, values);
8390
+ return result;
8391
+ } catch (e) {
8392
+ l?.error(e);
8393
+ throw e;
8394
+ }
8327
8395
  }
8328
- prepare() {
8329
- return getStatements(this.db.getExecutor().prepare(this));
8396
+ async transaction(transactionCB, logger) {
8397
+ try {
8398
+ await this.query("BEGIN", void 0, logger);
8399
+ const ret = await transactionCB(this, logger);
8400
+ await this.query("COMMIT", void 0, logger);
8401
+ return ret;
8402
+ } catch (e) {
8403
+ await this.query("ROLLBACK", void 0, logger);
8404
+ throw e;
8405
+ }
8330
8406
  }
8331
- ignoreDuplicates(ignore = true) {
8332
- this._ignoreDuplicate = ignore;
8333
- return this;
8407
+ createDatabase(dbName) {
8408
+ return new CreateDatabase(this, dbName);
8334
8409
  }
8335
- async yield(logger) {
8336
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8410
+ createTable(table, definition) {
8411
+ return new CreateTable(this, table, definition);
8337
8412
  }
8338
- clone() {
8339
- const ret = new _DropTable(this.db, this._table);
8340
- ret._ignoreDuplicate = this._ignoreDuplicate;
8341
- return ret;
8413
+ dropTable(table) {
8414
+ return new DropTable(this, table);
8342
8415
  }
8343
- };
8344
-
8345
- // node_modules/@miqro/query/build/query/alter-table.js
8346
- var AlterTable = class _AlterTable {
8347
- constructor(db, _table, _inTransaction = false) {
8348
- this.db = db;
8349
- this._table = _table;
8350
- this._inTransaction = _inTransaction;
8351
- this._type = "alter-table";
8352
- this._changes = [];
8416
+ dropDatabase(dbname) {
8417
+ return new DropDatabase(this, dbname);
8353
8418
  }
8354
- rename(name) {
8355
- this._renameTable = name;
8356
- return this;
8419
+ alterTable(table, inTransaction) {
8420
+ return new AlterTable(this, table, inTransaction);
8357
8421
  }
8358
- renameColumn(name, to) {
8359
- this._changes.push({
8360
- _action: "rename",
8361
- _column: name,
8362
- _newName: to
8363
- });
8364
- return this;
8422
+ insert(table) {
8423
+ return new Insert(this, table);
8365
8424
  }
8366
- addColumn(name, definition) {
8367
- this._changes.push({
8368
- _action: "add",
8369
- _column: name,
8370
- _definition: assertNotUndefined2(parser.parse(definition, ColumnDefinitionSchema))
8371
- });
8372
- return this;
8425
+ select() {
8426
+ return new Select(this);
8373
8427
  }
8374
- dropColumn(name) {
8375
- this._changes.push({
8376
- _action: "drop",
8377
- _column: name
8378
- });
8379
- return this;
8428
+ count() {
8429
+ return new Count(this);
8380
8430
  }
8381
- clone() {
8382
- const ret = new _AlterTable(this.db, this._table);
8383
- ret._changes = structuredClone(this._changes);
8384
- ret._renameTable = this._renameTable;
8385
- return ret;
8431
+ update(table) {
8432
+ return new Update(this, table);
8386
8433
  }
8387
- prepare() {
8388
- return getStatements(this.db.getExecutor().prepare(this));
8434
+ delete(table) {
8435
+ return new Delete(this, table);
8389
8436
  }
8390
- yield(logger) {
8391
- return this._inTransaction ? runStatementsInTransaction(this.db, this.db.getExecutor().prepare(this), logger) : runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8437
+ where() {
8438
+ return new Where();
8392
8439
  }
8393
8440
  };
8394
-
8395
- // node_modules/@miqro/query/build/query/insert.js
8396
- var Insert = class _Insert {
8397
- constructor(db, _table) {
8398
- this.db = db;
8399
- this._table = _table;
8400
- this._type = "insert";
8401
- this._columns = [];
8402
- this._returning = [];
8403
- this._values = [];
8404
- this._ignoreDuplicate = false;
8405
- }
8406
- value(value) {
8407
- this._values = this._values.concat(value);
8408
- return this;
8409
- }
8410
- values(value) {
8411
- return this.value(value);
8412
- }
8413
- returning(column) {
8414
- this._returning = this._returning.concat(column);
8415
- return this;
8416
- }
8417
- column(column) {
8418
- this._columns = this._columns.concat(column);
8419
- return this;
8420
- }
8421
- columns(column) {
8422
- return this.column(column);
8423
- }
8424
- prepare() {
8425
- return getStatements(this.db.getExecutor().prepare(this));
8426
- }
8427
- async yield(logger) {
8428
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8441
+ async function getExecutor(config) {
8442
+ switch (config.dialect) {
8443
+ case "node:sqlite":
8444
+ return await nativeSqlite(config);
8445
+ case "sqlite3-cli":
8446
+ return await sqlite3CLIExecutor(config);
8447
+ case "pg":
8448
+ return await postgresExecutor(config);
8449
+ case "sqlite3":
8450
+ return await sqlite3Executor(config);
8451
+ default:
8452
+ if (config.executor) {
8453
+ return config.executor;
8454
+ }
8455
+ throw new Error("dialect [" + config.dialect + "] not defined");
8429
8456
  }
8430
- ignoreDuplicates(ignore = true) {
8431
- this._ignoreDuplicate = ignore;
8432
- return this;
8457
+ }
8458
+
8459
+ // node_modules/@miqro/query/build/migrations/lib.js
8460
+ var lib_exports = {};
8461
+ __export(lib_exports, {
8462
+ down: () => down,
8463
+ getSortedMigrations: () => getMigrationFolderSortedFiles,
8464
+ init: () => initMigrationsTable,
8465
+ up: () => up
8466
+ });
8467
+
8468
+ // node_modules/@miqro/query/build/migrations/utils.js
8469
+ var import_fs = require("fs");
8470
+ var import_path = require("path");
8471
+
8472
+ // node_modules/@miqro/query/build/migrations/constants.js
8473
+ var MIGRATIONS_TABLE_NAME = "migrations";
8474
+ var MIGRATIONS_SCHEMA = {
8475
+ name: {
8476
+ type: "string",
8477
+ primaryKey: true,
8478
+ allowNull: false
8433
8479
  }
8434
- clone() {
8435
- const ret = new _Insert(this.db, this._table);
8436
- ret._columns = structuredClone(this._columns);
8437
- ret._values = structuredClone(this._values);
8438
- ret._returning = structuredClone(this._returning);
8439
- ret._ignoreDuplicate = this._ignoreDuplicate;
8440
- return ret;
8480
+ };
8481
+ var NULL_LOGGER = {
8482
+ error: (...args) => {
8483
+ },
8484
+ log: (...args) => {
8441
8485
  }
8442
8486
  };
8443
8487
 
8444
- // node_modules/@miqro/query/build/executors/where.js
8445
- var Where = class {
8446
- constructor() {
8447
- this._orderBy = [];
8448
- this._filters = [];
8449
- }
8450
- order(column, mode) {
8451
- this._orderBy.push({ column, mode });
8452
- return this;
8453
- }
8454
- limit(limit) {
8455
- this._limitBy = limit;
8456
- return this;
8457
- }
8458
- offset(offset) {
8459
- this._offsetBy = offset;
8460
- return this;
8461
- }
8462
- and(where) {
8463
- this._filters.push({
8464
- _type: "and",
8465
- _where: where
8466
- });
8467
- return this;
8488
+ // node_modules/@miqro/query/build/migrations/utils.js
8489
+ async function upMigrationFolder(db, migrationsFolderPath, logger, importFN) {
8490
+ const startMS = Date.now();
8491
+ logger?.log("\n\n====== [running migrations folder] ======\n====== [%s] ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath));
8492
+ await initMigrationsTable(db, NULL_LOGGER);
8493
+ const migrations = getMigrationFolderSortedFiles(migrationsFolderPath);
8494
+ for (const migrationName of migrations) {
8495
+ const migrationPath = (0, import_path.resolve)(migrationsFolderPath, migrationName);
8496
+ await upMigration(db, migrationPath, logger, importFN);
8468
8497
  }
8469
- or(where) {
8470
- this._filters.push({
8471
- _type: "or",
8472
- _where: where
8473
- });
8474
- return this;
8498
+ const took = Date.now() - startMS;
8499
+ logger?.log("\n\n====== [running migrations folder done] ======\n====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath), took);
8500
+ return migrations;
8501
+ }
8502
+ async function downMigrationFolder(db, migrationsFolderPath, logger, importFN) {
8503
+ const startMS = Date.now();
8504
+ logger?.log("\n\n====== [running migrations folder] ======\n====== [%s] ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath));
8505
+ await initMigrationsTable(db, NULL_LOGGER);
8506
+ const migrations = getMigrationFolderSortedFiles(migrationsFolderPath).reverse();
8507
+ for (const migrationName of migrations) {
8508
+ const migrationPath = (0, import_path.resolve)(migrationsFolderPath, migrationName);
8509
+ await downMigration(db, migrationPath, logger, importFN);
8475
8510
  }
8476
- where(where) {
8477
- this._filters.push({
8478
- _type: "where",
8479
- _where: where
8480
- });
8481
- if (where._orderBy.length > 0) {
8482
- this._orderBy.push(...where._orderBy);
8511
+ const took = Date.now() - startMS;
8512
+ logger?.log("\n\n====== [running migrations folder done] ======\n====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath), took);
8513
+ return migrations;
8514
+ }
8515
+ async function upMigration(db, migrationPath, logger, importFN) {
8516
+ return runMigration(db, migrationPath, false, logger ? logger : db.config.logger, importFN);
8517
+ }
8518
+ async function upMigrationModule(db, migrationName, migrationModule, logger) {
8519
+ return runMigrationModule(db, migrationName, migrationModule, false, logger ? logger : db.config.logger);
8520
+ }
8521
+ async function downMigrationModule(db, migrationName, migrationModule, logger) {
8522
+ return runMigrationModule(db, migrationName, migrationModule, true, logger ? logger : db.config.logger);
8523
+ }
8524
+ async function downMigration(db, migrationPath, logger, importFN) {
8525
+ return runMigration(db, migrationPath, true, logger ? logger : db.config.logger, importFN);
8526
+ }
8527
+ async function initMigrationsTable(db, logger) {
8528
+ return db.createTable(MIGRATIONS_TABLE_NAME, MIGRATIONS_SCHEMA).ignoreDuplicates(true).yield(logger);
8529
+ }
8530
+ function getMigrationFolderSortedFiles(migrationsFolderPath) {
8531
+ const files = (0, import_fs.readdirSync)(migrationsFolderPath);
8532
+ return files.map((file) => {
8533
+ const ext = (0, import_path.extname)(file);
8534
+ if (ext === ".js" || ext === ".mjs" || ext === ".ts" || ext === ".tsx" || ext === ".tsx") {
8535
+ const firstDash = file.indexOf("-");
8536
+ if (firstDash !== -1) {
8537
+ const number = parseInt(file.substring(0, firstDash), 10);
8538
+ if (!isNaN(number)) {
8539
+ return {
8540
+ number,
8541
+ file
8542
+ };
8543
+ }
8544
+ }
8483
8545
  }
8484
- if (where._limitBy) {
8485
- this._limitBy = where._limitBy;
8546
+ return {
8547
+ number: 0,
8548
+ file: ""
8549
+ };
8550
+ }).filter((file) => file.file !== "").sort((a, b) => {
8551
+ return a.number - b.number;
8552
+ }).map((file) => file.file);
8553
+ }
8554
+ async function runMigrationModule(db, migrationName, migrationModule, down2 = false, logger) {
8555
+ const startMS = Date.now();
8556
+ const alreadyRun = (await db.select().from(MIGRATIONS_TABLE_NAME).column("name").limit(1).eq("name", migrationName).yield(NULL_LOGGER)).length > 0;
8557
+ if (down2) {
8558
+ if (alreadyRun) {
8559
+ logger?.log(" ====== [%s] ======", (0, import_path.relative)(process.cwd(), migrationName));
8560
+ await migrationModule.down(db, logger);
8561
+ await db.delete(MIGRATIONS_TABLE_NAME).eq("name", migrationName).yield(NULL_LOGGER);
8562
+ const took = Date.now() - startMS;
8563
+ logger?.log(" ====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
8564
+ } else {
8565
+ const took = Date.now() - startMS;
8566
+ logger?.log(" ====== skipping down [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
8486
8567
  }
8487
- if (where._offsetBy) {
8488
- this._offsetBy = where._offsetBy;
8568
+ } else {
8569
+ if (alreadyRun) {
8570
+ const took = Date.now() - startMS;
8571
+ logger?.log(" ====== skipping up [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
8572
+ } else {
8573
+ logger?.log(" ====== [%s] ======", (0, import_path.relative)(process.cwd(), migrationName));
8574
+ await migrationModule.up(db, logger);
8575
+ await db.insert(MIGRATIONS_TABLE_NAME).column("name").value([{
8576
+ name: migrationName
8577
+ }]).ignoreDuplicates(true).yield(NULL_LOGGER);
8578
+ const took = Date.now() - startMS;
8579
+ logger?.log(" ====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
8489
8580
  }
8490
- return this;
8491
8581
  }
8492
- nin(column, value) {
8493
- {
8494
- this._filters.push({
8495
- _type: "nin",
8496
- _column: column,
8497
- _value: value
8582
+ }
8583
+ async function runMigration(db, migrationPath, down2 = false, logger, importFN) {
8584
+ const migrationName = (0, import_path.basename)(migrationPath).substring(0, (0, import_path.basename)(migrationPath).length - (0, import_path.extname)(migrationPath).length);
8585
+ const migrationModule = (await (importFN ? importFN(migrationPath) : import(migrationPath))).default;
8586
+ return runMigrationModule(db, migrationName, migrationModule, down2, logger);
8587
+ }
8588
+
8589
+ // node_modules/@miqro/query/build/migrations/lib.js
8590
+ var up = {
8591
+ file: upMigration,
8592
+ module: upMigrationModule,
8593
+ folder: upMigrationFolder
8594
+ };
8595
+ var down = {
8596
+ file: downMigration,
8597
+ module: downMigrationModule,
8598
+ folder: downMigrationFolder
8599
+ };
8600
+
8601
+ // src/services/utils/cluster-ws.ts
8602
+ var ClusterWebSocketServer2MessageType = "$$$$ClusterWebSocketServer2Message$$$$$";
8603
+ var ClusterWebSocketServer2 = class extends WebSocketServer {
8604
+ constructor(name, options) {
8605
+ super({
8606
+ ...options,
8607
+ validate: (req) => {
8608
+ if (this.options.maxConnections !== void 0 && this.clients.size + this.remoteClients.size >= this.options.maxConnections) {
8609
+ return false;
8610
+ } else {
8611
+ return options.validate ? options.validate(req) : true;
8612
+ }
8613
+ },
8614
+ onError: (req, error2) => {
8615
+ if (process.send) {
8616
+ process.send({
8617
+ type: ClusterWebSocketServer2MessageType,
8618
+ action: "error",
8619
+ target: this.name,
8620
+ clientUUID: req.uuid,
8621
+ fromPID: String(process.pid),
8622
+ errorMessage: error2.message
8623
+ });
8624
+ }
8625
+ if (options.onError) {
8626
+ options.onError(req, error2);
8627
+ }
8628
+ },
8629
+ onConnection: (req) => {
8630
+ if (process.send) {
8631
+ process.send({
8632
+ type: ClusterWebSocketServer2MessageType,
8633
+ action: "connection",
8634
+ target: this.name,
8635
+ fromPID: String(process.pid),
8636
+ clientUUID: req.uuid
8637
+ });
8638
+ }
8639
+ if (options.onConnection) {
8640
+ options.onConnection(req);
8641
+ }
8642
+ },
8643
+ onDisconnect: (req) => {
8644
+ if (process.send) {
8645
+ process.send({
8646
+ type: ClusterWebSocketServer2MessageType,
8647
+ action: "disconnection",
8648
+ target: this.name,
8649
+ fromPID: String(process.pid),
8650
+ clientUUID: req.uuid
8651
+ });
8652
+ }
8653
+ if (options.onDisconnect) {
8654
+ options.onDisconnect(req);
8655
+ }
8656
+ }
8657
+ });
8658
+ this.name = name;
8659
+ this.listener = async (data) => {
8660
+ try {
8661
+ const msg = data;
8662
+ if (msg && msg.type === ClusterWebSocketServer2MessageType && msg.target === this.name && msg.action) {
8663
+ switch (msg.action) {
8664
+ case "sync":
8665
+ if (process.send) {
8666
+ for (const clientUUID of this.clients.keys()) {
8667
+ process.send({
8668
+ type: ClusterWebSocketServer2MessageType,
8669
+ action: "connection",
8670
+ target: this.name,
8671
+ fromPID: String(process.pid),
8672
+ clientUUID
8673
+ });
8674
+ }
8675
+ }
8676
+ break;
8677
+ case "connection":
8678
+ if (!msg.clientUUID) {
8679
+ throw new Error(`action [${msg.action}] without clientUUID`);
8680
+ }
8681
+ if (!this.remoteClients.has(msg.clientUUID)) {
8682
+ this.remoteClients.add(msg.clientUUID);
8683
+ }
8684
+ break;
8685
+ case "disconnection":
8686
+ if (!msg.clientUUID) {
8687
+ throw new Error(`action [${msg.action}] without clientUUID`);
8688
+ }
8689
+ if (this.remoteClients.has(msg.clientUUID)) {
8690
+ this.remoteClients.delete(msg.clientUUID);
8691
+ }
8692
+ break;
8693
+ case "sendMessage": {
8694
+ const payload = String(msg.payload);
8695
+ if (!msg.clientUUID) {
8696
+ await super.broadcast(payload, msg.fromUUID);
8697
+ } else if (this.isConnected(msg.clientUUID)) {
8698
+ await super.writeTo(msg.clientUUID, payload);
8699
+ }
8700
+ break;
8701
+ }
8702
+ default:
8703
+ throw new Error(`action [${msg.action}] not supported`);
8704
+ }
8705
+ }
8706
+ } catch (e) {
8707
+ console.error(e);
8708
+ }
8709
+ };
8710
+ this.connect();
8711
+ }
8712
+ remoteClients = /* @__PURE__ */ new Set();
8713
+ listener;
8714
+ connect() {
8715
+ if (process.send) {
8716
+ process.removeListener("message", this.listener);
8717
+ process.on("message", this.listener);
8718
+ process.send({
8719
+ type: ClusterWebSocketServer2MessageType,
8720
+ action: "sync",
8721
+ fromPID: String(process.pid),
8722
+ target: this.name
8498
8723
  });
8499
- return this;
8500
8724
  }
8501
8725
  }
8502
- in(column, value) {
8503
- {
8504
- this._filters.push({
8505
- _type: "in",
8506
- _column: column,
8507
- _value: value
8726
+ dispose() {
8727
+ process.removeListener("message", this.listener);
8728
+ }
8729
+ async broadcast(payload, fromUUID) {
8730
+ if (process.send) {
8731
+ process.send({
8732
+ type: ClusterWebSocketServer2MessageType,
8733
+ action: "sendMessage",
8734
+ payload,
8735
+ target: this.name,
8736
+ fromPID: String(process.pid),
8737
+ fromUUID
8508
8738
  });
8509
- return this;
8510
8739
  }
8740
+ return super.broadcast(payload, fromUUID);
8511
8741
  }
8512
- eq(column, value) {
8513
- this._filters.push({
8514
- _type: "equal",
8515
- _column: column,
8516
- _value: value
8517
- });
8518
- return this;
8519
- }
8520
- like(column, value) {
8521
- this._filters.push({
8522
- _type: "like",
8523
- _column: column,
8524
- _value: value
8525
- });
8526
- return this;
8527
- }
8528
- gte(column, value) {
8529
- this._filters.push({
8530
- _type: "gte",
8531
- _column: column,
8532
- _value: value
8533
- });
8534
- return this;
8535
- }
8536
- gt(column, value) {
8537
- this._filters.push({
8538
- _type: "gt",
8539
- _column: column,
8540
- _value: value
8541
- });
8542
- return this;
8543
- }
8544
- lte(column, value) {
8545
- this._filters.push({
8546
- _type: "lte",
8547
- _column: column,
8548
- _value: value
8549
- });
8550
- return this;
8551
- }
8552
- lt(column, value) {
8553
- this._filters.push({
8554
- _type: "lt",
8555
- _column: column,
8556
- _value: value
8557
- });
8558
- return this;
8559
- }
8560
- neq(column, value) {
8561
- this._filters.push({
8562
- _type: "neq",
8563
- _column: column,
8564
- _value: value
8565
- });
8566
- return this;
8567
- }
8568
- literal(literal) {
8569
- this._filters.push({
8570
- _type: "literal",
8571
- _literal: literal
8572
- });
8573
- return this;
8574
- }
8575
- };
8576
-
8577
- // node_modules/@miqro/query/build/query/select.js
8578
- var Select = class _Select extends Where {
8579
- constructor(db) {
8580
- super();
8581
- this.db = db;
8582
- this._type = "select";
8583
- this._columns = [];
8584
- this._selectFrom = [];
8585
- this._groupBy = [];
8586
- this._joins = [];
8587
- this._orderBy = [];
8588
- }
8589
- prepare() {
8590
- return getStatements(this.db.getExecutor().prepare(this));
8591
- }
8592
- clone() {
8593
- const ret = new _Select(this.db);
8594
- ret._filters = structuredClone(this._filters);
8595
- ret._columns = structuredClone(this._columns);
8596
- ret._groupBy = structuredClone(this._groupBy);
8597
- ret._selectFrom = structuredClone(this._selectFrom);
8598
- ret._orderBy = structuredClone(this._orderBy);
8599
- ret._joins = structuredClone(this._joins);
8600
- ret._limitBy = this._limitBy;
8601
- ret._offsetBy = this._offsetBy;
8602
- return ret;
8603
- }
8604
- async yield(logger) {
8605
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8606
- }
8607
- column(column) {
8608
- if (column instanceof Array) {
8609
- this._columns = this._columns.concat(column);
8610
- } else {
8611
- this._columns.push(column);
8742
+ async writeTo(clientUUID, payload) {
8743
+ if (this.remoteClients.has(clientUUID)) {
8744
+ if (process.send) {
8745
+ process.send({
8746
+ type: ClusterWebSocketServer2MessageType,
8747
+ action: "sendMessage",
8748
+ clientUUID,
8749
+ target: this.name,
8750
+ fromPID: String(process.pid),
8751
+ payload
8752
+ });
8753
+ return;
8754
+ }
8612
8755
  }
8613
- return this;
8614
- }
8615
- columns(column) {
8616
- return this.column(column);
8617
- }
8618
- from(from) {
8619
- if (from instanceof Array) {
8620
- this._selectFrom = this._selectFrom.concat(from);
8621
- } else {
8622
- this._selectFrom.push(from);
8756
+ if (this.clients.has(clientUUID)) {
8757
+ return super.writeTo(clientUUID, payload);
8623
8758
  }
8624
- return this;
8625
- }
8626
- join(table, on, verb) {
8627
- this._joins.push({
8628
- _table: table,
8629
- _on: on,
8630
- _verb: verb
8631
- });
8632
- return this;
8633
- }
8634
- left(table, on) {
8635
- return this.join(table, on, "LEFT");
8636
- }
8637
- right(table, on) {
8638
- return this.join(table, on, "RIGHT");
8639
8759
  }
8640
- group(column) {
8641
- this._groupBy.push(column);
8642
- return this;
8760
+ isUUIDValid(uuid) {
8761
+ return !this.clients.has(uuid) && !this.remoteClients.has(uuid);
8643
8762
  }
8644
8763
  };
8645
8764
 
8646
- // node_modules/@miqro/query/build/query/count.js
8647
- var Count = class _Count extends Where {
8648
- constructor(db) {
8649
- super();
8650
- this.db = db;
8651
- this._type = "count";
8652
- this._selectFrom = [];
8653
- this._groupBy = [];
8654
- this._joins = [];
8655
- }
8656
- clone() {
8657
- const ret = new _Count(this.db);
8658
- ret._filters = structuredClone(this._filters);
8659
- ret._groupBy = structuredClone(this._groupBy);
8660
- ret._joins = structuredClone(this._joins);
8661
- ret._selectFrom = structuredClone(this._selectFrom);
8662
- ret._orderBy = structuredClone(this._orderBy);
8663
- ret._limitBy = this._limitBy;
8664
- ret._offsetBy = this._offsetBy;
8665
- return ret;
8666
- }
8667
- from(from) {
8668
- this._selectFrom = this._selectFrom.concat(from);
8669
- return this;
8670
- }
8671
- join(table, on, verb) {
8672
- this._joins.push({
8673
- _table: table,
8674
- _on: on,
8675
- _verb: verb
8676
- });
8677
- return this;
8765
+ // src/services/utils/cluster-cache.ts
8766
+ var ClusterCacheType = "$$$$$$$$$$$ClusterCacheType$$$$$$$$$$$";
8767
+ var ClusterCache = class {
8768
+ constructor(name, logger) {
8769
+ this.name = name;
8770
+ this.logger = logger;
8771
+ this.listener = async (data) => {
8772
+ try {
8773
+ const msg = data;
8774
+ if (msg && msg.key && msg.action && msg.type === ClusterCacheType && msg.fromPID !== process.pid, (msg.action === "set_add" || msg.action === "set" || msg.action === "unset" || msg.action === "set_delete" || msg.action === "array_push") && msg.target === this.name) {
8775
+ this.logger?.debug("remote cluster cache message from [%s] [%s] [%s] [%s]", msg.fromPID, msg.target, msg.action, msg.key);
8776
+ switch (msg.action) {
8777
+ case "unset":
8778
+ this.localCache.delete(msg.key);
8779
+ break;
8780
+ case "set":
8781
+ this.localCache.set(msg.key, msg.value);
8782
+ break;
8783
+ case "set_add": {
8784
+ const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
8785
+ if (!(list instanceof Set)) {
8786
+ throw new Error("cannot apply push on non array");
8787
+ }
8788
+ if (list.has(msg.value)) {
8789
+ list.add(msg.value);
8790
+ }
8791
+ this.localCache.set(msg.key, list);
8792
+ break;
8793
+ }
8794
+ case "set_delete": {
8795
+ const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : /* @__PURE__ */ new Set();
8796
+ if (!(list instanceof Set)) {
8797
+ throw new Error("cannot apply push on non array");
8798
+ }
8799
+ if (list.has(msg.value)) {
8800
+ list.delete(msg.value);
8801
+ }
8802
+ this.localCache.set(msg.key, list);
8803
+ break;
8804
+ }
8805
+ case "array_push": {
8806
+ const list = this.localCache.has(msg.key) ? this.localCache.get(msg.key) : [];
8807
+ if (!(list instanceof Array)) {
8808
+ throw new Error("cannot apply push on non array");
8809
+ }
8810
+ list.push(msg.value);
8811
+ this.localCache.set(msg.key, list);
8812
+ break;
8813
+ }
8814
+ }
8815
+ }
8816
+ } catch (e) {
8817
+ this.logger?.error(e);
8818
+ }
8819
+ };
8820
+ this.connect();
8678
8821
  }
8679
- left(table, on) {
8680
- return this.join(table, on, "LEFT");
8822
+ localCache = /* @__PURE__ */ new Map();
8823
+ //private logger: Logger;
8824
+ listener;
8825
+ connect() {
8826
+ if (process.send) {
8827
+ process.removeListener("message", this.listener);
8828
+ process.on("message", this.listener);
8829
+ }
8681
8830
  }
8682
- right(table, on) {
8683
- return this.join(table, on, "RIGHT");
8831
+ disconnect() {
8832
+ process.removeListener("message", this.listener);
8684
8833
  }
8685
- group(column) {
8686
- this._groupBy.push(column);
8687
- return this;
8834
+ get(key) {
8835
+ this.logger?.trace("get(%s)", key);
8836
+ return this.localCache.get(key);
8688
8837
  }
8689
- prepare() {
8690
- return getStatements(this.db.getExecutor().prepare(this));
8838
+ set(key, value) {
8839
+ this.localCache.set(key, value);
8840
+ this.logger?.trace("set(%s, ...)", key);
8841
+ if (process.send) {
8842
+ setTimeout(() => {
8843
+ process.send({
8844
+ type: ClusterCacheType,
8845
+ action: "set",
8846
+ target: this.name,
8847
+ fromPID: process.pid,
8848
+ key,
8849
+ value
8850
+ });
8851
+ }, 10);
8852
+ }
8691
8853
  }
8692
- async yield(logger) {
8693
- return parseCountResult(await runStatements(this.db, this.db.getExecutor().prepare(this), logger));
8854
+ unset(key) {
8855
+ this.logger?.trace("unset(%s)", key);
8856
+ this.localCache.delete(key);
8857
+ if (process.send) {
8858
+ setTimeout(() => {
8859
+ process.send({
8860
+ type: ClusterCacheType,
8861
+ target: this.name,
8862
+ action: "unset",
8863
+ fromPID: process.pid,
8864
+ key
8865
+ });
8866
+ }, 10);
8867
+ }
8694
8868
  }
8695
- };
8696
- async function parseCountResult(rows) {
8697
- return {
8698
- count: parseInt(rows[0].count, 10)
8699
- };
8700
- }
8701
-
8702
- // node_modules/@miqro/query/build/query/update.js
8703
- var Update = class _Update extends Where {
8704
- constructor(db, _table) {
8705
- super();
8706
- this.db = db;
8707
- this._table = _table;
8708
- this._type = "update";
8709
- this._sets = [];
8710
- this._returning = [];
8869
+ has(key) {
8870
+ this.logger?.trace("has(%s)", key);
8871
+ return this.localCache.has(key);
8711
8872
  }
8712
- prepare() {
8713
- return getStatements(this.db.getExecutor().prepare(this));
8873
+ set_add(key, value) {
8874
+ this.logger?.trace("push(%s)", key);
8875
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8876
+ if (!(list instanceof Set)) {
8877
+ throw new Error("cannot apply on non Set");
8878
+ }
8879
+ if (list.has(value)) {
8880
+ list.add(value);
8881
+ }
8882
+ this.localCache.set(key, list);
8883
+ if (process.send) {
8884
+ setTimeout(() => {
8885
+ process.send({
8886
+ type: ClusterCacheType,
8887
+ target: this.name,
8888
+ action: "set_add",
8889
+ fromPID: process.pid,
8890
+ key,
8891
+ value
8892
+ });
8893
+ }, 10);
8894
+ }
8714
8895
  }
8715
- async yield(logger) {
8716
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8896
+ set_delete(key, value) {
8897
+ this.logger?.trace("delete(%s)", key);
8898
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8899
+ if (!(list instanceof Set)) {
8900
+ throw new Error("cannot apply on non Set");
8901
+ }
8902
+ if (list.has(value)) {
8903
+ list.delete(value);
8904
+ }
8905
+ this.localCache.set(key, list);
8906
+ if (process.send) {
8907
+ setTimeout(() => {
8908
+ process.send({
8909
+ type: ClusterCacheType,
8910
+ target: this.name,
8911
+ action: "set_delete",
8912
+ fromPID: process.pid,
8913
+ key,
8914
+ value
8915
+ });
8916
+ }, 10);
8917
+ }
8717
8918
  }
8718
- clone() {
8719
- const ret = new _Update(this.db, this._table);
8720
- ret._filters = structuredClone(this._filters);
8721
- ret._orderBy = structuredClone(this._orderBy);
8722
- ret._sets = structuredClone(this._sets);
8723
- ret._returning = structuredClone(this._returning);
8724
- ret._limitBy = this._limitBy;
8725
- ret._offsetBy = this._offsetBy;
8919
+ set_has(key, value) {
8920
+ this.logger?.trace("set_has(%s)", key);
8921
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8922
+ if (!(list instanceof Set)) {
8923
+ throw new Error("cannot apply on non Set");
8924
+ }
8925
+ const ret = list.has(value);
8926
+ this.localCache.set(key, list);
8726
8927
  return ret;
8727
8928
  }
8728
- returning(column) {
8729
- this._returning = this._returning.concat(column);
8730
- return this;
8929
+ set_clear(key) {
8930
+ this.logger?.trace("set_clear(%s)", key);
8931
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8932
+ if (!(list instanceof Set)) {
8933
+ throw new Error("cannot apply on non Set");
8934
+ }
8935
+ list.clear();
8936
+ this.localCache.set(key, list);
8731
8937
  }
8732
- set(column, value) {
8733
- this._sets.push({
8734
- column,
8735
- value
8736
- });
8737
- return this;
8938
+ array_push(key, value) {
8939
+ this.logger?.trace("array_push(%s)", key);
8940
+ const list = this.localCache.has(key) ? this.localCache.get(key) : [];
8941
+ if (!(list instanceof Array)) {
8942
+ throw new Error("cannot apply on non Array");
8943
+ }
8944
+ list.push(value);
8945
+ this.localCache.set(key, list);
8946
+ if (process.send) {
8947
+ setTimeout(() => {
8948
+ process.send({
8949
+ type: ClusterCacheType,
8950
+ target: this.name,
8951
+ action: "array_push",
8952
+ fromPID: process.pid,
8953
+ key,
8954
+ value
8955
+ });
8956
+ }, 10);
8957
+ }
8958
+ }
8959
+ array_clear(key) {
8960
+ this.logger?.trace("array_clear(%s)", key);
8961
+ if (this.localCache.has(key) && !(this.localCache.get(key) instanceof Array)) {
8962
+ throw new Error("cannot apply on non Array");
8963
+ }
8964
+ this.localCache.set(key, []);
8738
8965
  }
8739
8966
  };
8740
8967
 
8741
- // node_modules/@miqro/query/build/query/delete.js
8742
- var Delete = class _Delete extends Where {
8743
- constructor(db, _table) {
8744
- super();
8745
- this.db = db;
8746
- this._table = _table;
8747
- this._type = "delete";
8748
- this._returning = [];
8968
+ // src/services/utils/cache.ts
8969
+ var LocalCache = class {
8970
+ constructor(name, logger) {
8971
+ this.name = name;
8972
+ this.logger = logger;
8749
8973
  }
8750
- prepare() {
8751
- return getStatements(this.db.getExecutor().prepare(this));
8974
+ localCache = /* @__PURE__ */ new Map();
8975
+ dispose() {
8752
8976
  }
8753
- async yield(logger) {
8754
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
8977
+ get(key) {
8978
+ this.logger?.trace("get(%s)", key);
8979
+ return this.localCache.get(key);
8755
8980
  }
8756
- clone() {
8757
- const ret = new _Delete(this.db, this._table);
8758
- ret._filters = structuredClone(this._filters);
8759
- ret._orderBy = structuredClone(this._orderBy);
8760
- ret._returning = structuredClone(this._returning);
8761
- ret._limitBy = this._limitBy;
8762
- ret._offsetBy = this._offsetBy;
8763
- return ret;
8981
+ set(key, value) {
8982
+ this.localCache.set(key, value);
8983
+ this.logger?.trace("set(%s, ...)", key);
8764
8984
  }
8765
- returning(column) {
8766
- this._returning = this._returning.concat(column);
8767
- return this;
8985
+ unset(key) {
8986
+ this.logger?.trace("unset(%s)", key);
8987
+ this.localCache.delete(key);
8768
8988
  }
8769
- };
8770
-
8771
- // node_modules/@miqro/query/build/query/drop-database.js
8772
- var DropDatabase = class _DropDatabase {
8773
- constructor(db, _dbName) {
8774
- this.db = db;
8775
- this._dbName = _dbName;
8776
- this._type = "drop-database";
8777
- this._ignoreDuplicate = false;
8989
+ has(key) {
8990
+ this.logger?.trace("has(%s)", key);
8991
+ return this.localCache.has(key);
8992
+ }
8993
+ set_add(key, value) {
8994
+ this.logger?.trace("set_add(%s)", key);
8995
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
8996
+ if (!(list instanceof Set)) {
8997
+ throw new Error("cannot apply on non Set");
8998
+ }
8999
+ if (list.has(value)) {
9000
+ list.add(value);
9001
+ }
9002
+ this.localCache.set(key, list);
8778
9003
  }
8779
- prepare() {
8780
- return getStatements(this.db.getExecutor().prepare(this));
9004
+ set_delete(key, value) {
9005
+ this.logger?.trace("set_delete(%s)", key);
9006
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
9007
+ if (!(list instanceof Set)) {
9008
+ throw new Error("cannot apply on non Set");
9009
+ }
9010
+ if (list.has(value)) {
9011
+ list.delete(value);
9012
+ }
9013
+ this.localCache.set(key, list);
8781
9014
  }
8782
- ignoreDuplicates(ignore = true) {
8783
- this._ignoreDuplicate = ignore;
8784
- return this;
9015
+ set_has(key, value) {
9016
+ this.logger?.trace("set_has(%s)", key);
9017
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
9018
+ if (!(list instanceof Set)) {
9019
+ throw new Error("cannot apply on non Set");
9020
+ }
9021
+ const ret = list.has(value);
9022
+ this.localCache.set(key, list);
9023
+ return ret;
8785
9024
  }
8786
- async yield(logger) {
8787
- return runStatements(this.db, this.db.getExecutor().prepare(this), logger);
9025
+ set_clear(key) {
9026
+ this.logger?.trace("set_clear(%s)", key);
9027
+ const list = this.localCache.has(key) ? this.localCache.get(key) : /* @__PURE__ */ new Set();
9028
+ if (!(list instanceof Set)) {
9029
+ throw new Error("cannot apply on non Set");
9030
+ }
9031
+ list.clear();
9032
+ this.localCache.set(key, list);
8788
9033
  }
8789
- clone() {
8790
- const ret = new _DropDatabase(this.db, this._dbName);
8791
- ret._ignoreDuplicate = this._ignoreDuplicate;
8792
- return ret;
9034
+ array_push(key, value) {
9035
+ this.logger?.trace("array_push(%s)", key);
9036
+ const list = this.localCache.has(key) ? this.localCache.get(key) : [];
9037
+ if (!(list instanceof Array)) {
9038
+ throw new Error("cannot apply on non Array");
9039
+ }
9040
+ list.push(value);
9041
+ this.localCache.set(key, list);
9042
+ }
9043
+ array_clear(key) {
9044
+ this.logger?.trace("array_clear(%s)", key);
9045
+ if (this.localCache.has(key) && !(this.localCache.get(key) instanceof Array)) {
9046
+ throw new Error("cannot apply on non Array");
9047
+ }
9048
+ this.localCache.set(key, []);
8793
9049
  }
8794
9050
  };
8795
9051
 
8796
- // node_modules/@miqro/query/build/executors/sqlite3-cli/lib.js
8797
- var import_child_process = require("child_process");
8798
- var SQLITE_CONFIG_SCHEMA2 = {
8799
- type: "object",
8800
- mode: "remove_extra",
8801
- properties: {
8802
- storage: "string"
9052
+ // src/services/utils/websocketmanager.ts
9053
+ init_constants();
9054
+ var WebSocketManager = class {
9055
+ runningGlobalWSMap = /* @__PURE__ */ new Map();
9056
+ logger = null;
9057
+ name;
9058
+ avoidLogSocket;
9059
+ constructor(options) {
9060
+ this.onUpgrade = this.onUpgrade.bind(this);
9061
+ this.logger = options && options.logger ? options.logger : null;
9062
+ this.name = options && options.name ? options.name : "WebSocketManager";
9063
+ this.avoidLogSocket = options && options.avoidLogSocket ? options.avoidLogSocket : false;
8803
9064
  }
8804
- };
8805
- async function sqlite3CLIExecutor(config) {
8806
- const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA2);
8807
- if (!databaseOptions) {
8808
- throw new Error("config not valid");
9065
+ deleteWS(path) {
9066
+ const ws = this.runningGlobalWSMap.get(path);
9067
+ this.disconnectAllFrom(path);
9068
+ ws.dispose();
9069
+ this.runningGlobalWSMap.delete(path);
8809
9070
  }
8810
- (config.logger ? config.logger : console).error(`sqlite3-cli is affected by sql injection. do not use! only for testing!`);
8811
- return {
8812
- // we just use the sqlite3Executor prepare function
8813
- prepare: sqlite3ExecutorPrepare,
8814
- disconnect: async function sqlite3ExecutorDisconnect() {
8815
- },
8816
- query: async function sqlite3Executor2(sql, values) {
8817
- return new Promise((resolve20, reject) => {
8818
- try {
8819
- let i = 0;
8820
- const raw = sql.replaceAll("?", (sub) => {
8821
- const value = values ? values[i] : void 0;
8822
- if (value === void 0) {
8823
- throw new Error("cannot convert query");
8824
- }
8825
- i++;
8826
- return `'${value}'`;
8827
- });
8828
- if (values && i !== values.length) {
8829
- throw new Error("cannot convert query");
8830
- }
8831
- (0, import_child_process.exec)(`sqlite3 -json "${databaseOptions.storage}" "${raw}"`, (error2, stdout, stderr) => {
8832
- try {
8833
- if (error2) {
8834
- if (stderr) {
8835
- reject(new Error(stderr));
8836
- } else {
8837
- reject(error2);
8838
- }
8839
- } else {
8840
- if (stderr) {
8841
- reject(new Error(stderr));
8842
- } else {
8843
- if (stdout) {
8844
- resolve20(JSON.parse(stdout));
8845
- } else {
8846
- resolve20([]);
8847
- }
8848
- }
8849
- }
8850
- } catch (e2) {
8851
- reject(e2);
8852
- }
8853
- });
8854
- } catch (e) {
8855
- reject(e);
8856
- }
8857
- });
9071
+ deleteAllWS() {
9072
+ for (const path of this.runningGlobalWSMap.keys()) {
9073
+ this.deleteWS(path);
8858
9074
  }
8859
- };
8860
- }
8861
-
8862
- // node_modules/@miqro/query/build/executors/sqlite-native/lib.js
8863
- var SQLITE_CONFIG_SCHEMA3 = {
8864
- type: "object",
8865
- mode: "remove_extra",
8866
- properties: {
8867
- storage: "string"
8868
9075
  }
8869
- };
8870
- async function nativeSqlite(config) {
8871
- const databaseOptions = parser.parse(config, SQLITE_CONFIG_SCHEMA3);
8872
- if (!databaseOptions) {
8873
- throw new Error("config not valid");
9076
+ getWS(path) {
9077
+ return this.runningGlobalWSMap.get(path);
8874
9078
  }
8875
- const sqliteModule = await import("node:sqlite");
8876
- const driver = new sqliteModule.DatabaseSync(databaseOptions.storage);
8877
- return {
8878
- // we just use the sqlite3Executor prepare function
8879
- prepare: sqlite3ExecutorPrepare,
8880
- disconnect: async function sqlite3ExecutorDisconnect() {
8881
- return driver.close();
8882
- },
8883
- query: async function sqlite3Executor2(sql, values) {
8884
- return new Promise((resolve20, reject) => {
8885
- try {
8886
- if (values) {
8887
- for (let i = 0; i < values.length; i++) {
8888
- switch (typeof values[i]) {
8889
- case "object":
8890
- if (values[i] instanceof Date) {
8891
- values[i] = values[i].toString();
8892
- }
8893
- break;
8894
- case "boolean":
8895
- values[i] = values[i] ? 1 : 0;
8896
- break;
8897
- }
8898
- }
8899
- }
8900
- const stmt = driver.prepare(sql);
8901
- stmt.setReadBigInts(true);
8902
- if (values && values.length > 0) {
8903
- const ret = stmt.all(...values);
8904
- resolve20(ret);
8905
- } else {
8906
- const ret = stmt.all();
8907
- resolve20(ret);
8908
- }
8909
- } catch (e) {
8910
- reject(e);
9079
+ replaceALLWS(list) {
9080
+ this.deleteAllWS();
9081
+ for (const wsConfig of list) {
9082
+ if (!wsConfig.disabled) {
9083
+ if (this.runningGlobalWSMap.has(wsConfig.path)) {
9084
+ throw new Error(`ws on path ${wsConfig.path} already setup!`);
8911
9085
  }
8912
- });
8913
- }
8914
- };
8915
- }
8916
-
8917
- // node_modules/@miqro/query/build/db.js
8918
- var Database = class {
8919
- constructor(config) {
8920
- this.config = config;
8921
- this.status = "disconnected";
8922
- this.executor = null;
8923
- parser.parse(config, DATABASE_CONFIG_SCHEMA, "no_extra");
8924
- this.executor = null;
8925
- }
8926
- async connect() {
8927
- if (this.status !== "disconnected") {
8928
- throw new Error(`cannot connect while ${this.status}`);
8929
- }
8930
- if (this.executor !== null) {
8931
- throw new Error(`cannot connect executor exists!`);
8932
- }
8933
- this.status = "connecting";
8934
- try {
8935
- this.executor = await getExecutor(this.config);
8936
- this.status = "connected";
8937
- } catch (e) {
8938
- this.status = "error";
8939
- throw e;
9086
+ this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
9087
+ const server2 = new ClusterWebSocketServer2(wsConfig.path, wsConfig);
9088
+ this.runningGlobalWSMap.set(wsConfig.path, server2);
9089
+ }
8940
9090
  }
8941
9091
  }
8942
- async disconnect() {
8943
- if (this.status !== "connected") {
8944
- throw new Error(`cannot disconnect while ${this.status}`);
9092
+ replaceALLWSBuLOGSocket(list) {
9093
+ for (const path of this.runningGlobalWSMap.keys()) {
9094
+ if (path !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
9095
+ this.deleteWS(path);
9096
+ }
8945
9097
  }
8946
- this.status = "disconnecting";
8947
- try {
8948
- await this.getExecutor().disconnect();
8949
- this.executor = null;
8950
- this.status = "disconnected";
8951
- } catch (e) {
8952
- this.status = "error";
8953
- throw e;
9098
+ for (const wsConfig of list) {
9099
+ if (!wsConfig.disabled) {
9100
+ if (wsConfig.path !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
9101
+ if (this.runningGlobalWSMap.has(wsConfig.path)) {
9102
+ throw new Error(`ws on path ${wsConfig.path} already setup!`);
9103
+ }
9104
+ this.logger?.debug("setting up websocket on [%s]", wsConfig.path);
9105
+ const server2 = new ClusterWebSocketServer2(this.name + wsConfig.path, wsConfig);
9106
+ this.runningGlobalWSMap.set(wsConfig.path, server2);
9107
+ }
9108
+ }
8954
9109
  }
8955
9110
  }
8956
- getExecutor() {
8957
- if (!this.executor) {
8958
- throw new Error("executor not initialized!");
9111
+ /*public setupWS(path: string, server: ClusterWebSocketServer2) {
9112
+ if (this.runningGlobalWSMap.has(path)) {
9113
+ throw new Error(`ws on path ${path} already setup!`);
8959
9114
  }
8960
- return this.executor;
8961
- }
8962
- async query(sql, values, logger) {
8963
- const l = logger ? logger : this.config.logger ? this.config.logger : void 0;
9115
+ this.runningGlobalWSMap.set(path, server);
9116
+ }*/
9117
+ disconnectAllFrom(path) {
8964
9118
  try {
8965
- l?.log(sql);
8966
- const result = await this.getExecutor().query(sql, values);
8967
- return result;
9119
+ this.logger?.debug("disconnect all from [%s]", path);
9120
+ const ws = this.getWS(path);
9121
+ if (ws) {
9122
+ const clients = ws.clients.values();
9123
+ if (clients) {
9124
+ for (const client of clients) {
9125
+ try {
9126
+ client.socket.destroy();
9127
+ } catch (e2) {
9128
+ this.logger?.error("error disconnecting web socket client");
9129
+ this.logger?.error(e2);
9130
+ }
9131
+ }
9132
+ }
9133
+ }
8968
9134
  } catch (e) {
8969
- l?.error(e);
8970
- throw e;
9135
+ this.logger?.error("error disconnecting web socket clients");
9136
+ this.logger?.error(e.message);
8971
9137
  }
8972
9138
  }
8973
- async transaction(transactionCB, logger) {
9139
+ disconnectAllButLOGSocket() {
8974
9140
  try {
8975
- await this.query("BEGIN", void 0, logger);
8976
- const ret = await transactionCB(this, logger);
8977
- await this.query("COMMIT", void 0, logger);
8978
- return ret;
9141
+ for (const wsPath of this.runningGlobalWSMap.keys()) {
9142
+ if (wsPath !== LOG_SOCKET_PATH || !this.avoidLogSocket) {
9143
+ this.disconnectAllFrom(wsPath);
9144
+ }
9145
+ }
8979
9146
  } catch (e) {
8980
- await this.query("ROLLBACK", void 0, logger);
8981
- throw e;
9147
+ this.logger?.error("error disconnecting web socket clients");
9148
+ this.logger?.error(e.message);
8982
9149
  }
8983
9150
  }
8984
- createDatabase(dbName) {
8985
- return new CreateDatabase(this, dbName);
8986
- }
8987
- createTable(table, definition) {
8988
- return new CreateTable(this, table, definition);
8989
- }
8990
- dropTable(table) {
8991
- return new DropTable(this, table);
8992
- }
8993
- dropDatabase(dbname) {
8994
- return new DropDatabase(this, dbname);
8995
- }
8996
- alterTable(table, inTransaction) {
8997
- return new AlterTable(this, table, inTransaction);
8998
- }
8999
- insert(table) {
9000
- return new Insert(this, table);
9001
- }
9002
- select() {
9003
- return new Select(this);
9004
- }
9005
- count() {
9006
- return new Count(this);
9007
- }
9008
- update(table) {
9009
- return new Update(this, table);
9010
- }
9011
- delete(table) {
9012
- return new Delete(this, table);
9013
- }
9014
- where() {
9015
- return new Where();
9016
- }
9017
- };
9018
- async function getExecutor(config) {
9019
- switch (config.dialect) {
9020
- case "node:sqlite":
9021
- return await nativeSqlite(config);
9022
- case "sqlite3-cli":
9023
- return await sqlite3CLIExecutor(config);
9024
- case "pg":
9025
- return await postgresExecutor(config);
9026
- case "sqlite3":
9027
- return await sqlite3Executor(config);
9028
- default:
9029
- if (config.executor) {
9030
- return config.executor;
9151
+ disconnectAll() {
9152
+ try {
9153
+ for (const wsPath of this.runningGlobalWSMap.keys()) {
9154
+ this.disconnectAllFrom(wsPath);
9031
9155
  }
9032
- throw new Error("dialect [" + config.dialect + "] not defined");
9033
- }
9034
- }
9035
-
9036
- // node_modules/@miqro/query/build/migrations/lib.js
9037
- var lib_exports = {};
9038
- __export(lib_exports, {
9039
- down: () => down,
9040
- getSortedMigrations: () => getMigrationFolderSortedFiles,
9041
- init: () => initMigrationsTable,
9042
- up: () => up
9043
- });
9044
-
9045
- // node_modules/@miqro/query/build/migrations/utils.js
9046
- var import_fs = require("fs");
9047
- var import_path = require("path");
9048
-
9049
- // node_modules/@miqro/query/build/migrations/constants.js
9050
- var MIGRATIONS_TABLE_NAME = "migrations";
9051
- var MIGRATIONS_SCHEMA = {
9052
- name: {
9053
- type: "string",
9054
- primaryKey: true,
9055
- allowNull: false
9056
- }
9057
- };
9058
- var NULL_LOGGER = {
9059
- error: (...args) => {
9060
- },
9061
- log: (...args) => {
9062
- }
9063
- };
9064
-
9065
- // node_modules/@miqro/query/build/migrations/utils.js
9066
- async function upMigrationFolder(db, migrationsFolderPath, logger, importFN) {
9067
- const startMS = Date.now();
9068
- logger?.log("\n\n====== [running migrations folder] ======\n====== [%s] ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath));
9069
- await initMigrationsTable(db, NULL_LOGGER);
9070
- const migrations = getMigrationFolderSortedFiles(migrationsFolderPath);
9071
- for (const migrationName of migrations) {
9072
- const migrationPath = (0, import_path.resolve)(migrationsFolderPath, migrationName);
9073
- await upMigration(db, migrationPath, logger, importFN);
9074
- }
9075
- const took = Date.now() - startMS;
9076
- logger?.log("\n\n====== [running migrations folder done] ======\n====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath), took);
9077
- return migrations;
9078
- }
9079
- async function downMigrationFolder(db, migrationsFolderPath, logger, importFN) {
9080
- const startMS = Date.now();
9081
- logger?.log("\n\n====== [running migrations folder] ======\n====== [%s] ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath));
9082
- await initMigrationsTable(db, NULL_LOGGER);
9083
- const migrations = getMigrationFolderSortedFiles(migrationsFolderPath).reverse();
9084
- for (const migrationName of migrations) {
9085
- const migrationPath = (0, import_path.resolve)(migrationsFolderPath, migrationName);
9086
- await downMigration(db, migrationPath, logger, importFN);
9156
+ } catch (e) {
9157
+ this.logger?.error("error disconnecting web socket clients");
9158
+ this.logger?.error(e.message);
9159
+ }
9087
9160
  }
9088
- const took = Date.now() - startMS;
9089
- logger?.log("\n\n====== [running migrations folder done] ======\n====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationsFolderPath), took);
9090
- return migrations;
9091
- }
9092
- async function upMigration(db, migrationPath, logger, importFN) {
9093
- return runMigration(db, migrationPath, false, logger ? logger : db.config.logger, importFN);
9094
- }
9095
- async function upMigrationModule(db, migrationName, migrationModule, logger) {
9096
- return runMigrationModule(db, migrationName, migrationModule, false, logger ? logger : db.config.logger);
9097
- }
9098
- async function downMigrationModule(db, migrationName, migrationModule, logger) {
9099
- return runMigrationModule(db, migrationName, migrationModule, true, logger ? logger : db.config.logger);
9100
- }
9101
- async function downMigration(db, migrationPath, logger, importFN) {
9102
- return runMigration(db, migrationPath, true, logger ? logger : db.config.logger, importFN);
9103
- }
9104
- async function initMigrationsTable(db, logger) {
9105
- return db.createTable(MIGRATIONS_TABLE_NAME, MIGRATIONS_SCHEMA).ignoreDuplicates(true).yield(logger);
9106
- }
9107
- function getMigrationFolderSortedFiles(migrationsFolderPath) {
9108
- const files = (0, import_fs.readdirSync)(migrationsFolderPath);
9109
- return files.map((file) => {
9110
- const ext = (0, import_path.extname)(file);
9111
- if (ext === ".js" || ext === ".mjs" || ext === ".ts" || ext === ".tsx" || ext === ".tsx") {
9112
- const firstDash = file.indexOf("-");
9113
- if (firstDash !== -1) {
9114
- const number = parseInt(file.substring(0, firstDash), 10);
9115
- if (!isNaN(number)) {
9116
- return {
9117
- number,
9118
- file
9119
- };
9120
- }
9161
+ onUpgrade(req, socket, head) {
9162
+ try {
9163
+ const wsServer = this.getWS(req.path);
9164
+ if (wsServer) {
9165
+ return wsServer.onUpgrade(req, socket, head);
9166
+ } else {
9167
+ socket.destroy();
9121
9168
  }
9122
- }
9123
- return {
9124
- number: 0,
9125
- file: ""
9126
- };
9127
- }).filter((file) => file.file !== "").sort((a, b) => {
9128
- return a.number - b.number;
9129
- }).map((file) => file.file);
9130
- }
9131
- async function runMigrationModule(db, migrationName, migrationModule, down2 = false, logger) {
9132
- const startMS = Date.now();
9133
- const alreadyRun = (await db.select().from(MIGRATIONS_TABLE_NAME).column("name").limit(1).eq("name", migrationName).yield(NULL_LOGGER)).length > 0;
9134
- if (down2) {
9135
- if (alreadyRun) {
9136
- logger?.log(" ====== [%s] ======", (0, import_path.relative)(process.cwd(), migrationName));
9137
- await migrationModule.down(db, logger);
9138
- await db.delete(MIGRATIONS_TABLE_NAME).eq("name", migrationName).yield(NULL_LOGGER);
9139
- const took = Date.now() - startMS;
9140
- logger?.log(" ====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
9141
- } else {
9142
- const took = Date.now() - startMS;
9143
- logger?.log(" ====== skipping down [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
9144
- }
9145
- } else {
9146
- if (alreadyRun) {
9147
- const took = Date.now() - startMS;
9148
- logger?.log(" ====== skipping up [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
9149
- } else {
9150
- logger?.log(" ====== [%s] ======", (0, import_path.relative)(process.cwd(), migrationName));
9151
- await migrationModule.up(db, logger);
9152
- await db.insert(MIGRATIONS_TABLE_NAME).column("name").value([{
9153
- name: migrationName
9154
- }]).ignoreDuplicates(true).yield(NULL_LOGGER);
9155
- const took = Date.now() - startMS;
9156
- logger?.log(" ====== [%s] took [%s]ms ======\n", (0, import_path.relative)(process.cwd(), migrationName), took);
9169
+ } catch (e) {
9170
+ this.logger?.error(e);
9157
9171
  }
9158
9172
  }
9159
- }
9160
- async function runMigration(db, migrationPath, down2 = false, logger, importFN) {
9161
- const migrationName = (0, import_path.basename)(migrationPath).substring(0, (0, import_path.basename)(migrationPath).length - (0, import_path.extname)(migrationPath).length);
9162
- const migrationModule = (await (importFN ? importFN(migrationPath) : import(migrationPath))).default;
9163
- return runMigrationModule(db, migrationName, migrationModule, down2, logger);
9164
- }
9165
-
9166
- // node_modules/@miqro/query/build/migrations/lib.js
9167
- var up = {
9168
- file: upMigration,
9169
- module: upMigrationModule,
9170
- folder: upMigrationFolder
9171
- };
9172
- var down = {
9173
- file: downMigration,
9174
- module: downMigrationModule,
9175
- folder: downMigrationFolder
9176
9173
  };
9177
9174
 
9178
9175
  // src/services/utils/db-manager.ts
9176
+ var import_node_cluster = __toESM(require("node:cluster"), 1);
9179
9177
  var DBManager = class {
9180
9178
  map = /* @__PURE__ */ new Map();
9181
9179
  options;
@@ -12784,6 +12782,7 @@ async function main() {
12784
12782
  localCache,
12785
12783
  logProvider,
12786
12784
  wsManager: webSocketManager,
12785
+ logger: logProvider.getLogger("server"),
12787
12786
  dbManager,
12788
12787
  port: PORT
12789
12788
  });
@@ -12796,7 +12795,7 @@ async function main() {
12796
12795
  onUpgrade: webSocketManager.onUpgrade
12797
12796
  });
12798
12797
  ${SERVERCONFIGLIST ? `
12799
- await Promise.all([${SERVERCONFIGLIST}].map(config=>config.preload(serverInterface)));
12798
+ await Promise.all([${SERVERCONFIGLIST}].filter(config=>config.preload).map(config=>config.preload(serverInterface)));
12800
12799
  ` : ""}
12801
12800
  app.use(ServerRequestHandler(serverInterface));
12802
12801
  app.use(LoggerHandler());
@@ -12812,13 +12811,13 @@ async function main() {
12812
12811
  app.use(await (await import("./${(0, import_node_path12.join)(service, "api-router.js")}")).setupRouter());
12813
12812
  app.use(await (await import("./${(0, import_node_path12.join)(service, "static-router.js")}")).setupRouter())`).join("\n")}
12814
12813
  ${SERVERCONFIGLIST ? `
12815
- await Promise.all([${SERVERCONFIGLIST}].map(config=>config.load(serverInterface)));
12814
+ await Promise.all([${SERVERCONFIGLIST}].filter(config=>config.load).map(config=>config.load(serverInterface)));
12816
12815
  ` : ""}
12817
12816
 
12818
12817
 
12819
12818
  await app.listen(PORT);
12820
12819
  ${SERVERCONFIGLIST ? `
12821
- await Promise.all([${SERVERCONFIGLIST}].map(config=>config.start(serverInterface)));` : ""}
12820
+ await Promise.all([${SERVERCONFIGLIST}].filter(config=>config.start).map(config=>config.start(serverInterface)));` : ""}
12822
12821
  }
12823
12822
  main().catch(e=>console.error(e));
12824
12823
  `
@@ -13387,7 +13386,7 @@ var ServerInterfaceImpl = class {
13387
13386
  constructor(options) {
13388
13387
  this.cache = options.cache;
13389
13388
  this.localCache = options.localCache;
13390
- this.logger = options.logger;
13389
+ this.logger = options.logger ? options.logger : options.loggerProvider ? options.loggerProvider.getLogger("server") : void 0;
13391
13390
  this.port = options.port;
13392
13391
  const dbManager = options.dbManager;
13393
13392
  const wsManager = options.wsManager;