@restura/core 0.1.0-alpha.3 → 0.1.0-alpha.30

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/dist/index.js CHANGED
@@ -1,10 +1,2911 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __objRest = (source, exclude) => {
26
+ var target = {};
27
+ for (var prop in source)
28
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
+ target[prop] = source[prop];
30
+ if (source != null && __getOwnPropSymbols)
31
+ for (var prop of __getOwnPropSymbols(source)) {
32
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
+ target[prop] = source[prop];
34
+ }
35
+ return target;
36
+ };
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, { get: all[name], enumerable: true });
40
+ };
41
+ var __copyProps = (to, from, except, desc) => {
42
+ if (from && typeof from === "object" || typeof from === "function") {
43
+ for (let key of __getOwnPropNames(from))
44
+ if (!__hasOwnProp.call(to, key) && key !== except)
45
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
+ }
47
+ return to;
48
+ };
49
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
+ // If the importer is in node compatibility mode or this is not an ESM
51
+ // file that has been converted to a CommonJS file using a Babel-
52
+ // compatible transform (i.e. "__esModule" has not been set), then set
53
+ // "default" to the CommonJS "module.exports" for node compatibility.
54
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
+ mod
56
+ ));
57
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
+ var __decorateClass = (decorators, target, key, kind) => {
59
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
60
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
61
+ if (decorator = decorators[i])
62
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
63
+ if (kind && result) __defProp(target, key, result);
64
+ return result;
65
+ };
66
+
1
67
  // src/index.ts
2
- import { log } from "@restura/internal";
3
- function isEven(value) {
4
- log("isEven called");
5
- return value % 2 === 0;
68
+ var src_exports = {};
69
+ __export(src_exports, {
70
+ HtmlStatusCodes: () => HtmlStatusCodes,
71
+ PsqlConnection: () => PsqlConnection,
72
+ PsqlEngine: () => PsqlEngine,
73
+ PsqlPool: () => PsqlPool,
74
+ PsqlTransaction: () => PsqlTransaction,
75
+ RsError: () => RsError,
76
+ SQL: () => SQL,
77
+ escapeColumnName: () => escapeColumnName,
78
+ eventManager: () => eventManager_default,
79
+ insertObjectQuery: () => insertObjectQuery,
80
+ isValueNumber: () => isValueNumber2,
81
+ logger: () => logger,
82
+ questionMarksToOrderedParams: () => questionMarksToOrderedParams,
83
+ restura: () => restura,
84
+ updateObjectQuery: () => updateObjectQuery
85
+ });
86
+ module.exports = __toCommonJS(src_exports);
87
+
88
+ // src/logger/logger.ts
89
+ var import_internal = require("@restura/internal");
90
+ var import_winston = __toESM(require("winston"));
91
+ var import_logform = require("logform");
92
+
93
+ // src/logger/loggerConfigSchema.ts
94
+ var import_zod = require("zod");
95
+ var loggerConfigSchema = import_zod.z.object({
96
+ level: import_zod.z.enum(["info", "warn", "error", "debug", "silly"]).default("info")
97
+ });
98
+
99
+ // src/logger/logger.ts
100
+ var loggerConfig = import_internal.config.validate("logger", loggerConfigSchema);
101
+ var consoleFormat = import_logform.format.combine(
102
+ import_logform.format.timestamp({
103
+ format: "YYYY-MM-DD HH:mm:ss.sss"
104
+ }),
105
+ import_logform.format.errors({ stack: true }),
106
+ import_logform.format.padLevels(),
107
+ import_logform.format.colorize({ all: true }),
108
+ import_logform.format.printf((info) => {
109
+ return `[${info.timestamp}] ${info.level} ${info.message}`;
110
+ })
111
+ );
112
+ var logger = import_winston.default.createLogger({
113
+ level: loggerConfig.level,
114
+ format: import_logform.format.combine(
115
+ import_logform.format.timestamp({
116
+ format: "YYYY-MM-DD HH:mm:ss.sss"
117
+ }),
118
+ import_logform.format.errors({ stack: true }),
119
+ import_logform.format.json()
120
+ ),
121
+ //defaultMeta: { service: 'user-service' },
122
+ transports: [
123
+ //
124
+ // - Write to all logs with level `info` and below to `combined.log`
125
+ // - Write all logs error (and below) to `error.log`.
126
+ // - Write all logs to standard out.
127
+ //
128
+ // new winston.transports.File({ filename: 'error.log', level: 'error' }),
129
+ // new winston.transports.File({ filename: 'combined.log' }),
130
+ new import_winston.default.transports.Console({ format: consoleFormat })
131
+ ]
132
+ });
133
+
134
+ // src/restura/eventManager.ts
135
+ var import_bluebird = __toESM(require("bluebird"));
136
+ var EventManager = class {
137
+ constructor() {
138
+ this.actionHandlers = {
139
+ DATABASE_ROW_DELETE: [],
140
+ DATABASE_ROW_INSERT: [],
141
+ DATABASE_COLUMN_UPDATE: []
142
+ };
143
+ }
144
+ addRowInsertHandler(onInsert, filter) {
145
+ this.actionHandlers.DATABASE_ROW_INSERT.push({
146
+ callback: onInsert,
147
+ filter
148
+ });
149
+ }
150
+ addColumnChangeHandler(onUpdate, filter) {
151
+ this.actionHandlers.DATABASE_COLUMN_UPDATE.push({
152
+ callback: onUpdate,
153
+ filter
154
+ });
155
+ }
156
+ addRowDeleteHandler(onDelete, filter) {
157
+ this.actionHandlers.DATABASE_ROW_DELETE.push({
158
+ callback: onDelete,
159
+ filter
160
+ });
161
+ }
162
+ async fireActionFromDbTrigger(sqlMutationData, result) {
163
+ if (sqlMutationData.mutationType === "INSERT") {
164
+ await this.fireInsertActions(sqlMutationData, result);
165
+ } else if (sqlMutationData.mutationType === "UPDATE") {
166
+ await this.fireUpdateActions(sqlMutationData, result);
167
+ } else if (sqlMutationData.mutationType === "DELETE") {
168
+ await this.fireDeleteActions(sqlMutationData, result);
169
+ }
170
+ }
171
+ async fireInsertActions(data, triggerResult) {
172
+ await import_bluebird.default.map(
173
+ this.actionHandlers.DATABASE_ROW_INSERT,
174
+ ({ callback, filter }) => {
175
+ if (!this.hasHandlersForEventType("DATABASE_ROW_INSERT", filter, triggerResult)) return;
176
+ const insertData = {
177
+ tableName: triggerResult.table,
178
+ insertId: triggerResult.record.id,
179
+ insertObject: triggerResult.record,
180
+ queryMetadata: data.queryMetadata
181
+ };
182
+ callback(insertData, data.queryMetadata);
183
+ },
184
+ { concurrency: 10 }
185
+ );
186
+ }
187
+ async fireDeleteActions(data, triggerResult) {
188
+ await import_bluebird.default.map(
189
+ this.actionHandlers.DATABASE_ROW_DELETE,
190
+ ({ callback, filter }) => {
191
+ if (!this.hasHandlersForEventType("DATABASE_ROW_DELETE", filter, triggerResult)) return;
192
+ const deleteData = {
193
+ tableName: triggerResult.table,
194
+ deletedRow: triggerResult.previousRecord,
195
+ queryMetadata: data.queryMetadata
196
+ };
197
+ callback(deleteData, data.queryMetadata);
198
+ },
199
+ { concurrency: 10 }
200
+ );
201
+ }
202
+ async fireUpdateActions(data, triggerResult) {
203
+ await import_bluebird.default.map(
204
+ this.actionHandlers.DATABASE_COLUMN_UPDATE,
205
+ ({ callback, filter }) => {
206
+ if (!this.hasHandlersForEventType("DATABASE_COLUMN_UPDATE", filter, triggerResult)) return;
207
+ const columnChangeData = {
208
+ tableName: triggerResult.table,
209
+ rowId: triggerResult.record.id,
210
+ newData: triggerResult.record,
211
+ oldData: triggerResult.previousRecord,
212
+ queryMetadata: data.queryMetadata
213
+ };
214
+ callback(columnChangeData, data.queryMetadata);
215
+ },
216
+ { concurrency: 10 }
217
+ );
218
+ }
219
+ hasHandlersForEventType(eventType, filter, triggerResult) {
220
+ if (filter) {
221
+ switch (eventType) {
222
+ case "DATABASE_ROW_INSERT":
223
+ case "DATABASE_ROW_DELETE":
224
+ if (filter.tableName && filter.tableName !== triggerResult.table) return false;
225
+ break;
226
+ case "DATABASE_COLUMN_UPDATE":
227
+ const filterColumnChange = filter;
228
+ if (filterColumnChange.tableName !== triggerResult.table) return false;
229
+ if (filterColumnChange.columns.length === 1) {
230
+ const firstColumn = filterColumnChange.columns[0];
231
+ if (firstColumn === "*") return true;
232
+ }
233
+ if (!filterColumnChange.columns.some((item) => {
234
+ const updatedColumns = Object.keys(
235
+ changedValues(triggerResult.record, triggerResult.previousRecord)
236
+ );
237
+ return updatedColumns.includes(item);
238
+ }))
239
+ return false;
240
+ break;
241
+ }
242
+ }
243
+ return true;
244
+ }
245
+ };
246
+ var eventManager = new EventManager();
247
+ var eventManager_default = eventManager;
248
+ function changedValues(record, previousRecord) {
249
+ const changed = {};
250
+ for (const i in previousRecord) {
251
+ if (previousRecord[i] !== record[i]) {
252
+ if (typeof previousRecord[i] === "object" && typeof record[i] === "object") {
253
+ const nestedChanged = changedValues(record[i], previousRecord[i]);
254
+ if (Object.keys(nestedChanged).length > 0) {
255
+ changed[i] = record[i];
256
+ }
257
+ } else {
258
+ changed[i] = record[i];
259
+ }
260
+ }
261
+ }
262
+ return changed;
263
+ }
264
+
265
+ // src/restura/restura.ts
266
+ var import_core_utils7 = require("@redskytech/core-utils");
267
+ var import_internal4 = require("@restura/internal");
268
+
269
+ // ../../node_modules/.pnpm/autobind-decorator@2.4.0/node_modules/autobind-decorator/lib/esm/index.js
270
+ function _typeof(obj) {
271
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
272
+ _typeof = function _typeof2(obj2) {
273
+ return typeof obj2;
274
+ };
275
+ } else {
276
+ _typeof = function _typeof2(obj2) {
277
+ return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
278
+ };
279
+ }
280
+ return _typeof(obj);
281
+ }
282
+ function boundMethod(target, key, descriptor) {
283
+ var fn = descriptor.value;
284
+ if (typeof fn !== "function") {
285
+ throw new TypeError("@boundMethod decorator can only be applied to methods not: ".concat(_typeof(fn)));
286
+ }
287
+ var definingProperty = false;
288
+ return {
289
+ configurable: true,
290
+ get: function get() {
291
+ if (definingProperty || this === target.prototype || this.hasOwnProperty(key) || typeof fn !== "function") {
292
+ return fn;
293
+ }
294
+ var boundFn = fn.bind(this);
295
+ definingProperty = true;
296
+ Object.defineProperty(this, key, {
297
+ configurable: true,
298
+ get: function get2() {
299
+ return boundFn;
300
+ },
301
+ set: function set(value) {
302
+ fn = value;
303
+ delete this[key];
304
+ }
305
+ });
306
+ definingProperty = false;
307
+ return boundFn;
308
+ },
309
+ set: function set(value) {
310
+ fn = value;
311
+ }
312
+ };
313
+ }
314
+
315
+ // src/restura/restura.ts
316
+ var import_body_parser = __toESM(require("body-parser"));
317
+ var import_compression = __toESM(require("compression"));
318
+ var import_cookie_parser = __toESM(require("cookie-parser"));
319
+ var express = __toESM(require("express"));
320
+ var import_fs4 = __toESM(require("fs"));
321
+ var import_path5 = __toESM(require("path"));
322
+ var prettier3 = __toESM(require("prettier"));
323
+
324
+ // src/restura/RsError.ts
325
+ var HtmlStatusCodes = /* @__PURE__ */ ((HtmlStatusCodes2) => {
326
+ HtmlStatusCodes2[HtmlStatusCodes2["BAD_REQUEST"] = 400] = "BAD_REQUEST";
327
+ HtmlStatusCodes2[HtmlStatusCodes2["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
328
+ HtmlStatusCodes2[HtmlStatusCodes2["FORBIDDEN"] = 403] = "FORBIDDEN";
329
+ HtmlStatusCodes2[HtmlStatusCodes2["NOT_FOUND"] = 404] = "NOT_FOUND";
330
+ HtmlStatusCodes2[HtmlStatusCodes2["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
331
+ HtmlStatusCodes2[HtmlStatusCodes2["CONFLICT"] = 409] = "CONFLICT";
332
+ HtmlStatusCodes2[HtmlStatusCodes2["VERSION_OUT_OF_DATE"] = 418] = "VERSION_OUT_OF_DATE";
333
+ HtmlStatusCodes2[HtmlStatusCodes2["SERVER_ERROR"] = 500] = "SERVER_ERROR";
334
+ HtmlStatusCodes2[HtmlStatusCodes2["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
335
+ HtmlStatusCodes2[HtmlStatusCodes2["NETWORK_CONNECT_TIMEOUT"] = 599] = "NETWORK_CONNECT_TIMEOUT";
336
+ return HtmlStatusCodes2;
337
+ })(HtmlStatusCodes || {});
338
+ var RsError = class _RsError {
339
+ constructor(errCode, message) {
340
+ this.err = errCode;
341
+ this.msg = message || "";
342
+ this.status = _RsError.htmlStatus(errCode);
343
+ this.stack = new Error().stack || "";
344
+ }
345
+ static htmlStatus(code) {
346
+ return htmlStatusMap[code];
347
+ }
348
+ static isRsError(error) {
349
+ return error instanceof _RsError;
350
+ }
351
+ };
352
+ var htmlStatusMap = {
353
+ UNKNOWN_ERROR: 500 /* SERVER_ERROR */,
354
+ NOT_FOUND: 404 /* NOT_FOUND */,
355
+ EMAIL_TAKEN: 409 /* CONFLICT */,
356
+ FORBIDDEN: 403 /* FORBIDDEN */,
357
+ CONFLICT: 409 /* CONFLICT */,
358
+ UNAUTHORIZED: 401 /* UNAUTHORIZED */,
359
+ UPDATE_FORBIDDEN: 403 /* FORBIDDEN */,
360
+ CREATE_FORBIDDEN: 403 /* FORBIDDEN */,
361
+ DELETE_FORBIDDEN: 403 /* FORBIDDEN */,
362
+ DELETE_FAILURE: 500 /* SERVER_ERROR */,
363
+ BAD_REQUEST: 400 /* BAD_REQUEST */,
364
+ INVALID_TOKEN: 401 /* UNAUTHORIZED */,
365
+ INCORRECT_EMAIL_OR_PASSWORD: 401 /* UNAUTHORIZED */,
366
+ DUPLICATE_TOKEN: 409 /* CONFLICT */,
367
+ DUPLICATE_USERNAME: 409 /* CONFLICT */,
368
+ DUPLICATE_EMAIL: 409 /* CONFLICT */,
369
+ DUPLICATE: 409 /* CONFLICT */,
370
+ EMAIL_NOT_VERIFIED: 400 /* BAD_REQUEST */,
371
+ UPDATE_WITHOUT_ID: 400 /* BAD_REQUEST */,
372
+ CONNECTION_ERROR: 599 /* NETWORK_CONNECT_TIMEOUT */,
373
+ INVALID_PAYMENT: 403 /* FORBIDDEN */,
374
+ DECLINED_PAYMENT: 403 /* FORBIDDEN */,
375
+ INTEGRATION_ERROR: 500 /* SERVER_ERROR */,
376
+ CANNOT_RESERVE: 403 /* FORBIDDEN */,
377
+ REFUND_FAILURE: 403 /* FORBIDDEN */,
378
+ INVALID_INVOICE: 403 /* FORBIDDEN */,
379
+ INVALID_COUPON: 403 /* FORBIDDEN */,
380
+ SERVICE_UNAVAILABLE: 503 /* SERVICE_UNAVAILABLE */,
381
+ METHOD_UNALLOWED: 405 /* METHOD_NOT_ALLOWED */,
382
+ LOGIN_EXPIRED: 401 /* UNAUTHORIZED */,
383
+ THIRD_PARTY_ERROR: 400 /* BAD_REQUEST */,
384
+ ACCESS_DENIED: 403 /* FORBIDDEN */,
385
+ DATABASE_ERROR: 500 /* SERVER_ERROR */,
386
+ SCHEMA_ERROR: 500 /* SERVER_ERROR */
387
+ };
388
+
389
+ // src/restura/compareSchema.ts
390
+ var import_lodash = __toESM(require("lodash.clonedeep"));
391
+ var CompareSchema = class {
392
+ async diffSchema(newSchema, latestSchema, psqlEngine) {
393
+ const endPoints = this.diffEndPoints(newSchema.endpoints[0].routes, latestSchema.endpoints[0].routes);
394
+ const globalParams = this.diffStringArray(newSchema.globalParams, latestSchema.globalParams);
395
+ const roles = this.diffStringArray(newSchema.roles, latestSchema.roles);
396
+ let commands = "";
397
+ if (JSON.stringify(newSchema.database) !== JSON.stringify(latestSchema.database))
398
+ commands = await psqlEngine.diffDatabaseToSchema(newSchema);
399
+ const customTypes = newSchema.customTypes !== latestSchema.customTypes;
400
+ const schemaPreview = { endPoints, globalParams, roles, commands, customTypes };
401
+ return schemaPreview;
402
+ }
403
+ diffStringArray(newArray, originalArray) {
404
+ const stringsDiff = [];
405
+ const originalClone = new Set(originalArray);
406
+ newArray.forEach((item) => {
407
+ const originalIndex = originalClone.has(item);
408
+ if (!originalIndex) {
409
+ stringsDiff.push({
410
+ name: item,
411
+ changeType: "NEW"
412
+ });
413
+ } else {
414
+ originalClone.delete(item);
415
+ }
416
+ });
417
+ originalClone.forEach((item) => {
418
+ stringsDiff.push({
419
+ name: item,
420
+ changeType: "DELETED"
421
+ });
422
+ });
423
+ return stringsDiff;
424
+ }
425
+ diffEndPoints(newEndPoints, originalEndpoints) {
426
+ const originalClone = (0, import_lodash.default)(originalEndpoints);
427
+ const diffObj = [];
428
+ newEndPoints.forEach((endPoint) => {
429
+ const { path: path5, method } = endPoint;
430
+ const endPointIndex = originalClone.findIndex((original) => {
431
+ return original.path === endPoint.path && original.method === endPoint.method;
432
+ });
433
+ if (endPointIndex === -1) {
434
+ diffObj.push({
435
+ name: `${method} ${path5}`,
436
+ changeType: "NEW"
437
+ });
438
+ } else {
439
+ const original = originalClone.findIndex((original2) => {
440
+ return this.compareEndPoints(endPoint, original2);
441
+ });
442
+ if (original === -1) {
443
+ diffObj.push({
444
+ name: `${method} ${path5}`,
445
+ changeType: "MODIFIED"
446
+ });
447
+ }
448
+ originalClone.splice(endPointIndex, 1);
449
+ }
450
+ });
451
+ originalClone.forEach((original) => {
452
+ const { path: path5, method } = original;
453
+ diffObj.push({
454
+ name: `${method} ${path5}`,
455
+ changeType: "DELETED"
456
+ });
457
+ });
458
+ return diffObj;
459
+ }
460
+ compareEndPoints(endPoint1, endPoint2) {
461
+ return JSON.stringify(endPoint1) === JSON.stringify(endPoint2);
462
+ }
463
+ };
464
+ __decorateClass([
465
+ boundMethod
466
+ ], CompareSchema.prototype, "diffSchema", 1);
467
+ __decorateClass([
468
+ boundMethod
469
+ ], CompareSchema.prototype, "diffStringArray", 1);
470
+ __decorateClass([
471
+ boundMethod
472
+ ], CompareSchema.prototype, "diffEndPoints", 1);
473
+ __decorateClass([
474
+ boundMethod
475
+ ], CompareSchema.prototype, "compareEndPoints", 1);
476
+ var compareSchema = new CompareSchema();
477
+ var compareSchema_default = compareSchema;
478
+
479
+ // src/restura/customApiFactory.ts
480
+ var import_bluebird2 = __toESM(require("bluebird"));
481
+ var import_fs = __toESM(require("fs"));
482
+ var import_path = __toESM(require("path"));
483
+ var import_internal2 = require("@restura/internal");
484
+ var CustomApiFactory = class {
485
+ constructor() {
486
+ this.customApis = {};
487
+ }
488
+ async loadApiFiles(baseFolderPath) {
489
+ const apiVersions = ["v1"];
490
+ for (const apiVersion of apiVersions) {
491
+ const apiVersionFolderPath = import_path.default.join(baseFolderPath, apiVersion);
492
+ const directoryExists = await import_internal2.FileUtils.existDir(apiVersionFolderPath);
493
+ if (!directoryExists) continue;
494
+ await this.addDirectory(apiVersionFolderPath, apiVersion);
495
+ }
496
+ }
497
+ getCustomApi(customApiName) {
498
+ return this.customApis[customApiName];
499
+ }
500
+ async addDirectory(directoryPath, apiVersion) {
501
+ var _a2;
502
+ const entries = await import_fs.default.promises.readdir(directoryPath, {
503
+ withFileTypes: true
504
+ });
505
+ const isTsx2 = (_a2 = process.argv[1]) == null ? void 0 : _a2.endsWith(".ts");
506
+ const isTsNode2 = process.env.TS_NODE_DEV || process.env.TS_NODE_PROJECT;
507
+ const extension = isTsx2 || isTsNode2 ? "ts" : "js";
508
+ const shouldEndWith = `.api.${apiVersion}.${extension}`;
509
+ await import_bluebird2.default.map(entries, async (entry) => {
510
+ if (entry.isFile()) {
511
+ if (entry.name.endsWith(shouldEndWith) === false) return;
512
+ try {
513
+ const importPath = `${import_path.default.join(directoryPath, entry.name)}`;
514
+ const ApiImport = await import(importPath);
515
+ const customApiClass = new ApiImport.default();
516
+ logger.info(`Registering custom API: ${ApiImport.default.name}`);
517
+ this.bindMethodsToInstance(customApiClass);
518
+ this.customApis[ApiImport.default.name] = customApiClass;
519
+ } catch (e) {
520
+ console.error(e);
521
+ }
522
+ }
523
+ });
524
+ }
525
+ bindMethodsToInstance(instance) {
526
+ const proto = Object.getPrototypeOf(instance);
527
+ Object.getOwnPropertyNames(proto).forEach((key) => {
528
+ const property = instance[key];
529
+ if (typeof property === "function" && key !== "constructor") {
530
+ instance[key] = property.bind(instance);
531
+ }
532
+ });
533
+ }
534
+ };
535
+ var customApiFactory = new CustomApiFactory();
536
+ var customApiFactory_default = customApiFactory;
537
+
538
+ // src/restura/generators/apiGenerator.ts
539
+ var import_core_utils = require("@redskytech/core-utils");
540
+ var import_prettier = __toESM(require("prettier"));
541
+
542
+ // src/restura/sql/SqlUtils.ts
543
+ var SqlUtils = class _SqlUtils {
544
+ static convertDatabaseTypeToTypescript(type, value) {
545
+ type = type.toLocaleLowerCase();
546
+ if (type.startsWith("tinyint") || type.startsWith("boolean")) return "boolean";
547
+ if (type.indexOf("int") > -1 || type.startsWith("decimal") || type.startsWith("double") || type.startsWith("float"))
548
+ return "number";
549
+ if (type === "json") {
550
+ if (!value) return "object";
551
+ return value.split(",").map((val) => {
552
+ return val.replace(/['"]/g, "");
553
+ }).join(" | ");
554
+ }
555
+ if (type.startsWith("varchar") || type.indexOf("text") > -1 || type.startsWith("char") || type.indexOf("blob") > -1 || type.startsWith("binary"))
556
+ return "string";
557
+ if (type.startsWith("date") || type.startsWith("time")) return "string";
558
+ if (type.startsWith("enum")) return _SqlUtils.convertDatabaseEnumToStringUnion(value || type);
559
+ return "any";
560
+ }
561
+ static convertDatabaseEnumToStringUnion(type) {
562
+ return type.replace(/^enum\(|\)/g, "").split(",").map((value) => {
563
+ return `'${value.replace(/'/g, "")}'`;
564
+ }).join(" | ");
565
+ }
566
+ };
567
+
568
+ // src/restura/validators/ResponseValidator.ts
569
+ var ResponseValidator = class _ResponseValidator {
570
+ constructor(schema) {
571
+ this.database = schema.database;
572
+ this.rootMap = {};
573
+ for (const endpoint of schema.endpoints) {
574
+ const endpointMap = {};
575
+ for (const route of endpoint.routes) {
576
+ if (_ResponseValidator.isCustomRoute(route)) {
577
+ endpointMap[`${route.method}:${route.path}`] = { validator: "any" };
578
+ continue;
579
+ }
580
+ endpointMap[`${route.method}:${route.path}`] = this.getRouteResponseType(route);
581
+ }
582
+ const endpointUrl = endpoint.baseUrl.endsWith("/") ? endpoint.baseUrl.slice(0, -1) : endpoint.baseUrl;
583
+ this.rootMap[endpointUrl] = { validator: endpointMap };
584
+ }
585
+ }
586
+ validateResponseParams(data, endpointUrl, routeData) {
587
+ if (!this.rootMap) {
588
+ throw new RsError("BAD_REQUEST", "Cannot validate response without type maps");
589
+ }
590
+ const routeMap = this.rootMap[endpointUrl].validator[`${routeData.method}:${routeData.path}`];
591
+ data = this.validateAndCoerceMap("_base", data, routeMap);
592
+ }
593
+ getRouteResponseType(route) {
594
+ const map = {};
595
+ for (const field of route.response) {
596
+ map[field.name] = this.getFieldResponseType(field, route.table);
597
+ }
598
+ if (route.type === "PAGED") {
599
+ return {
600
+ validator: {
601
+ data: { validator: map, isArray: true },
602
+ total: { validator: "number" }
603
+ }
604
+ };
605
+ }
606
+ if (route.method === "DELETE") {
607
+ return {
608
+ validator: "boolean"
609
+ };
610
+ }
611
+ return { validator: map, isArray: route.type === "ARRAY" };
612
+ }
613
+ getFieldResponseType(field, tableName) {
614
+ if (field.selector) {
615
+ return this.getTypeFromTable(field.selector, tableName);
616
+ } else if (field.subquery) {
617
+ const table = this.database.find((t) => t.name == tableName);
618
+ if (!table) return { isArray: true, validator: "any" };
619
+ const isOptional = table.roles.length > 0;
620
+ const validator = {};
621
+ for (const prop of field.subquery.properties) {
622
+ validator[prop.name] = this.getFieldResponseType(prop, field.subquery.table);
623
+ }
624
+ return {
625
+ isArray: true,
626
+ isOptional,
627
+ validator
628
+ };
629
+ }
630
+ return { validator: "any" };
631
+ }
632
+ getTypeFromTable(selector, name) {
633
+ const path5 = selector.split(".");
634
+ if (path5.length === 0 || path5.length > 2 || path5[0] === "") return { validator: "any", isOptional: false };
635
+ const tableName = path5.length == 2 ? path5[0] : name, columnName = path5.length == 2 ? path5[1] : path5[0];
636
+ const table = this.database.find((t) => t.name == tableName);
637
+ const column = table == null ? void 0 : table.columns.find((c) => c.name == columnName);
638
+ if (!table || !column) return { validator: "any", isOptional: false };
639
+ let validator = SqlUtils.convertDatabaseTypeToTypescript(
640
+ column.type,
641
+ column.value
642
+ );
643
+ if (!_ResponseValidator.validatorIsValidString(validator)) validator = this.parseValidationEnum(validator);
644
+ return {
645
+ validator,
646
+ isOptional: column.roles.length > 0 || column.isNullable
647
+ };
648
+ }
649
+ parseValidationEnum(validator) {
650
+ let terms = validator.split("|");
651
+ terms = terms.map((v) => v.replace(/'/g, "").trim());
652
+ return terms;
653
+ }
654
+ validateAndCoerceMap(name, value, { isOptional, isArray, validator }) {
655
+ if (validator === "any") return value;
656
+ const valueType = typeof value;
657
+ if (value == null) {
658
+ if (isOptional) return value;
659
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is required`);
660
+ }
661
+ if (isArray) {
662
+ if (!Array.isArray(value)) {
663
+ throw new RsError(
664
+ "DATABASE_ERROR",
665
+ `Response param (${name}) is a/an ${valueType} instead of an array`
666
+ );
667
+ }
668
+ value.forEach((v, i) => this.validateAndCoerceMap(`${name}[${i}]`, v, { validator }));
669
+ return value;
670
+ }
671
+ if (typeof validator === "string") {
672
+ if (validator === "boolean" && valueType === "number") {
673
+ if (value !== 0 && value !== 1)
674
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is of the wrong type (${valueType})`);
675
+ return value === 1;
676
+ } else if (validator === "string" && valueType === "string") {
677
+ if (typeof value === "string" && value.match(
678
+ /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.?\d*$|\d{2}:\d{2}:\d{2}.?\d*$|^\d{4}-\d{2}-\d{2}$/
679
+ )) {
680
+ const date = new Date(value);
681
+ if (date.toISOString() === "1970-01-01T00:00:00.000Z") return null;
682
+ const timezoneOffset = date.getTimezoneOffset() * 6e4;
683
+ return new Date(date.getTime() - timezoneOffset * 2).toISOString();
684
+ }
685
+ return value;
686
+ } else if (valueType === validator) {
687
+ return value;
688
+ } else if (valueType === "object") {
689
+ return value;
690
+ }
691
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is of the wrong type (${valueType})`);
692
+ }
693
+ if (Array.isArray(validator) && typeof value === "string") {
694
+ if (validator.includes(value)) return value;
695
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is not one of the enum options (${value})`);
696
+ }
697
+ if (valueType !== "object") {
698
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is of the wrong type (${valueType})`);
699
+ }
700
+ for (const prop in value) {
701
+ if (!validator[prop])
702
+ throw new RsError("DATABASE_ERROR", `Response param (${name}.${prop}) is not allowed`);
703
+ }
704
+ for (const prop in validator) {
705
+ value[prop] = this.validateAndCoerceMap(`${name}.${prop}`, value[prop], validator[prop]);
706
+ }
707
+ return value;
708
+ }
709
+ static isCustomRoute(route) {
710
+ return route.type === "CUSTOM_ONE" || route.type === "CUSTOM_ARRAY" || route.type === "CUSTOM_PAGED";
711
+ }
712
+ static validatorIsValidString(validator) {
713
+ return !validator.includes("|");
714
+ }
715
+ };
716
+
717
+ // src/restura/generators/apiGenerator.ts
718
+ var ApiTree = class _ApiTree {
719
+ constructor(namespace, database) {
720
+ this.database = database;
721
+ this.data = [];
722
+ this.namespace = namespace;
723
+ this.children = /* @__PURE__ */ new Map();
724
+ }
725
+ static createRootNode(database) {
726
+ return new _ApiTree(null, database);
727
+ }
728
+ static isRouteData(data) {
729
+ return data.method !== void 0;
730
+ }
731
+ static isEndpointData(data) {
732
+ return data.routes !== void 0;
733
+ }
734
+ addData(namespaces, route) {
735
+ if (import_core_utils.ObjectUtils.isEmpty(namespaces)) {
736
+ this.data.push(route);
737
+ return;
738
+ }
739
+ const childName = namespaces[0];
740
+ this.children.set(childName, this.children.get(childName) || new _ApiTree(childName, this.database));
741
+ this.children.get(childName).addData(namespaces.slice(1), route);
742
+ }
743
+ createApiModels() {
744
+ let result = "";
745
+ for (const child of this.children.values()) {
746
+ result += child.createApiModelImpl(true);
747
+ }
748
+ return result;
749
+ }
750
+ createApiModelImpl(isBase) {
751
+ let result = ``;
752
+ for (const data of this.data) {
753
+ if (_ApiTree.isEndpointData(data)) {
754
+ result += _ApiTree.generateEndpointComments(data);
755
+ }
756
+ }
757
+ result += isBase ? `
758
+ declare namespace ${this.namespace} {` : `
759
+ export namespace ${this.namespace} {`;
760
+ for (const data of this.data) {
761
+ if (_ApiTree.isRouteData(data)) {
762
+ result += this.generateRouteModels(data);
763
+ }
764
+ }
765
+ for (const child of this.children.values()) {
766
+ result += child.createApiModelImpl(false);
767
+ }
768
+ result += "}";
769
+ return result;
770
+ }
771
+ static generateEndpointComments(endpoint) {
772
+ return `
773
+ // ${endpoint.name}
774
+ // ${endpoint.description}`;
775
+ }
776
+ generateRouteModels(route) {
777
+ let modelString = ``;
778
+ modelString += `
779
+ // ${route.name}
780
+ // ${route.description}
781
+ export namespace ${import_core_utils.StringUtils.capitalizeFirst(route.method.toLowerCase())} {
782
+ ${this.generateRequestParameters(route)}
783
+ ${this.generateResponseParameters(route)}
784
+ }`;
785
+ return modelString;
786
+ }
787
+ generateRequestParameters(route) {
788
+ let modelString = ``;
789
+ if (ResponseValidator.isCustomRoute(route) && route.requestType) {
790
+ modelString += `
791
+ export type Req = CustomTypes.${route.requestType}`;
792
+ return modelString;
793
+ }
794
+ if (!route.request) return modelString;
795
+ modelString += `
796
+ export interface Req{
797
+ ${route.request.map((p) => {
798
+ let requestType = "any";
799
+ const oneOfValidator = p.validator.find((v) => v.type === "ONE_OF");
800
+ const typeCheckValidator = p.validator.find((v) => v.type === "TYPE_CHECK");
801
+ if (oneOfValidator && import_core_utils.ObjectUtils.isArrayWithData(oneOfValidator.value)) {
802
+ requestType = oneOfValidator.value.map((v) => `'${v}'`).join(" | ");
803
+ } else if (typeCheckValidator) {
804
+ switch (typeCheckValidator.value) {
805
+ case "string":
806
+ case "number":
807
+ case "boolean":
808
+ case "string[]":
809
+ case "number[]":
810
+ case "any[]":
811
+ requestType = typeCheckValidator.value;
812
+ break;
813
+ }
814
+ }
815
+ return `'${p.name}'${p.required ? "" : "?"}:${requestType}${p.isNullable ? " | null" : ""}`;
816
+ }).join(";\n")}${import_core_utils.ObjectUtils.isArrayWithData(route.request) ? ";" : ""}
817
+ `;
818
+ modelString += `}`;
819
+ return modelString;
820
+ }
821
+ generateResponseParameters(route) {
822
+ if (ResponseValidator.isCustomRoute(route)) {
823
+ if (["number", "string", "boolean"].includes(route.responseType))
824
+ return `export type Res = ${route.responseType}`;
825
+ else if (["CUSTOM_ARRAY", "CUSTOM_PAGED"].includes(route.type))
826
+ return `export type Res = CustomTypes.${route.responseType}[]`;
827
+ else return `export type Res = CustomTypes.${route.responseType}`;
828
+ }
829
+ return `export interface Res ${this.getFields(route.response)}`;
830
+ }
831
+ getFields(fields) {
832
+ const nameFields = fields.map((f) => this.getNameAndType(f));
833
+ const nested = `{
834
+ ${nameFields.join(";\n ")}${import_core_utils.ObjectUtils.isArrayWithData(nameFields) ? ";" : ""}
835
+ }`;
836
+ return nested;
837
+ }
838
+ getNameAndType(p) {
839
+ let responseType = "any", isNullable = false, array = false;
840
+ if (p.selector) {
841
+ ({ responseType, isNullable } = this.getTypeFromTable(p.selector, p.name));
842
+ } else if (p.subquery) {
843
+ responseType = this.getFields(p.subquery.properties);
844
+ array = true;
845
+ }
846
+ return `${p.name}:${responseType}${array ? "[]" : ""}${isNullable ? " | null" : ""}`;
847
+ }
848
+ getTypeFromTable(selector, name) {
849
+ const path5 = selector.split(".");
850
+ if (path5.length === 0 || path5.length > 2 || path5[0] === "") return { responseType: "any", isNullable: false };
851
+ let tableName = path5.length == 2 ? path5[0] : name;
852
+ const columnName = path5.length == 2 ? path5[1] : path5[0];
853
+ let table = this.database.find((t) => t.name == tableName);
854
+ if (!table && tableName.includes("_")) {
855
+ const tableAliasSplit = tableName.split("_");
856
+ tableName = tableAliasSplit[1];
857
+ table = this.database.find((t) => t.name == tableName);
858
+ }
859
+ const column = table == null ? void 0 : table.columns.find((c) => c.name == columnName);
860
+ if (!table || !column) return { responseType: "any", isNullable: false };
861
+ return {
862
+ responseType: SqlUtils.convertDatabaseTypeToTypescript(column.type, column.value),
863
+ isNullable: column.roles.length > 0 || column.isNullable
864
+ };
865
+ }
866
+ };
867
+ function pathToNamespaces(path5) {
868
+ return path5.split("/").map((e) => import_core_utils.StringUtils.toPascalCasing(e)).filter((e) => e);
869
+ }
870
+ function apiGenerator(schema) {
871
+ let apiString = `/** Auto generated file. DO NOT MODIFY **/
872
+ `;
873
+ const rootNamespace = ApiTree.createRootNode(schema.database);
874
+ for (const endpoint of schema.endpoints) {
875
+ const endpointNamespaces = pathToNamespaces(endpoint.baseUrl);
876
+ rootNamespace.addData(endpointNamespaces, endpoint);
877
+ for (const route of endpoint.routes) {
878
+ const fullNamespace = [...endpointNamespaces, ...pathToNamespaces(route.path)];
879
+ rootNamespace.addData(fullNamespace, route);
880
+ }
881
+ }
882
+ apiString += rootNamespace.createApiModels();
883
+ if (schema.customTypes.length > 0) {
884
+ apiString += `
885
+
886
+ declare namespace CustomTypes {
887
+ ${schema.customTypes}
888
+ }`;
889
+ }
890
+ return import_prettier.default.format(apiString, __spreadValues({
891
+ parser: "typescript"
892
+ }, {
893
+ trailingComma: "none",
894
+ tabWidth: 4,
895
+ useTabs: true,
896
+ endOfLine: "lf",
897
+ printWidth: 120,
898
+ singleQuote: true
899
+ }));
900
+ }
901
+
902
+ // src/restura/generators/customTypeValidationGenerator.ts
903
+ var import_fs2 = __toESM(require("fs"));
904
+ var import_path2 = __toESM(require("path"));
905
+ var import_tmp = __toESM(require("tmp"));
906
+ var TJS = __toESM(require("typescript-json-schema"));
907
+ function customTypeValidationGenerator(currentSchema) {
908
+ const schemaObject = {};
909
+ const customInterfaceNames = currentSchema.customTypes.match(new RegExp("(?<=interface\\s)(\\w+)|(?<=type\\s)(\\w+)", "g"));
910
+ if (!customInterfaceNames) return {};
911
+ const temporaryFile = import_tmp.default.fileSync({ mode: 420, prefix: "prefix-", postfix: ".ts" });
912
+ import_fs2.default.writeFileSync(temporaryFile.name, currentSchema.customTypes);
913
+ const compilerOptions = {
914
+ strictNullChecks: true,
915
+ skipLibCheck: true
916
+ // Needed if we are processing ES modules
917
+ };
918
+ const program = TJS.getProgramFromFiles(
919
+ [
920
+ (0, import_path2.resolve)(temporaryFile.name),
921
+ import_path2.default.join(restura.resturaConfig.generatedTypesPath, "restura.d.ts"),
922
+ import_path2.default.join(restura.resturaConfig.generatedTypesPath, "models.d.ts"),
923
+ import_path2.default.join(restura.resturaConfig.generatedTypesPath, "api.d.ts")
924
+ ],
925
+ compilerOptions
926
+ );
927
+ customInterfaceNames.forEach((item) => {
928
+ const ddlSchema = TJS.generateSchema(program, item, {
929
+ required: true
930
+ });
931
+ schemaObject[item] = ddlSchema || {};
932
+ });
933
+ temporaryFile.removeCallback();
934
+ return schemaObject;
935
+ }
936
+
937
+ // src/restura/generators/modelGenerator.ts
938
+ var import_core_utils2 = require("@redskytech/core-utils");
939
+ var import_prettier2 = __toESM(require("prettier"));
940
+ function modelGenerator(schema) {
941
+ let modelString = `/** Auto generated file. DO NOT MODIFY **/
942
+
943
+ `;
944
+ modelString += `declare namespace Model {
945
+ `;
946
+ for (const table of schema.database) {
947
+ modelString += convertTable(table);
948
+ }
949
+ modelString += `}`;
950
+ return import_prettier2.default.format(modelString, __spreadValues({
951
+ parser: "typescript"
952
+ }, {
953
+ trailingComma: "none",
954
+ tabWidth: 4,
955
+ useTabs: true,
956
+ endOfLine: "lf",
957
+ printWidth: 120,
958
+ singleQuote: true
959
+ }));
960
+ }
961
+ function convertTable(table) {
962
+ let modelString = ` export interface ${import_core_utils2.StringUtils.capitalizeFirst(table.name)} {
963
+ `;
964
+ for (const column of table.columns) {
965
+ modelString += ` ${column.name}${column.isNullable ? "?" : ""}: ${SqlUtils.convertDatabaseTypeToTypescript(column.type, column.value)};
966
+ `;
967
+ }
968
+ modelString += ` }
969
+ `;
970
+ return modelString;
971
+ }
972
+
973
+ // src/restura/generators/resturaGlobalTypesGenerator.ts
974
+ function resturaGlobalTypesGenerator() {
975
+ return `/** Auto generated file. DO NOT MODIFY **/
976
+ /** This file contains types that may be used in the CustomTypes of Restura **/
977
+ /** For example export interface MyPagedQuery extends Restura.PageQuery { } **/
978
+
979
+ declare namespace Restura {
980
+ export type StandardOrderTypes = 'ASC' | 'DESC' | 'RAND' | 'NONE';
981
+ export interface PageQuery {
982
+ page?: number;
983
+ perPage?: number;
984
+ sortBy?: string;
985
+ sortOrder?: StandardOrderTypes;
986
+ filter?: string;
987
+ }
988
+ }
989
+ `;
990
+ }
991
+
992
+ // src/restura/middleware/addApiResponseFunctions.ts
993
+ function addApiResponseFunctions(req, res, next) {
994
+ res.sendData = function(data, statusCode = 200) {
995
+ res.status(statusCode).send({ data });
996
+ };
997
+ res.sendNoWrap = function(dataNoWrap, statusCode = 200) {
998
+ res.status(statusCode).send(dataNoWrap);
999
+ };
1000
+ res.sendPaginated = function(pagedData, statusCode = 200) {
1001
+ res.status(statusCode).send({ data: pagedData.data, total: pagedData.total });
1002
+ };
1003
+ res.sendError = function(shortError, msg, htmlStatusCode, stack) {
1004
+ if (htmlStatusCode === void 0) {
1005
+ if (RsError.htmlStatus(shortError) !== void 0) {
1006
+ htmlStatusCode = RsError.htmlStatus(shortError);
1007
+ } else {
1008
+ htmlStatusCode = 500;
1009
+ }
1010
+ }
1011
+ const errorData = __spreadValues({
1012
+ err: shortError,
1013
+ msg
1014
+ }, restura.resturaConfig.sendErrorStackTrace && stack ? { stack } : {});
1015
+ res.status(htmlStatusCode).send(errorData);
1016
+ };
1017
+ next();
1018
+ }
1019
+
1020
+ // src/restura/middleware/authenticateUser.ts
1021
+ function authenticateUser(applicationAuthenticateHandler) {
1022
+ return (req, res, next) => {
1023
+ applicationAuthenticateHandler(req, res, (userDetails) => {
1024
+ req.requesterDetails = __spreadValues({ host: req.hostname, ipAddress: req.ip || "" }, userDetails);
1025
+ next();
1026
+ });
1027
+ };
1028
+ }
1029
+
1030
+ // src/restura/middleware/getMulterUpload.ts
1031
+ var import_multer = __toESM(require("multer"));
1032
+ var os = __toESM(require("os"));
1033
+ var import_path3 = require("path");
1034
+ var OneHundredMB = 100 * 1024 * 1024;
1035
+ var commonUpload = null;
1036
+ var getMulterUpload = (directory) => {
1037
+ if (commonUpload) return commonUpload;
1038
+ const storage = import_multer.default.diskStorage({
1039
+ destination: directory || os.tmpdir(),
1040
+ filename: function(request, file, cb) {
1041
+ const extension = (0, import_path3.extname)(file.originalname);
1042
+ const uniqueName = Date.now() + "-" + Math.round(Math.random() * 1e3);
1043
+ cb(null, `${uniqueName}${extension}`);
1044
+ }
1045
+ });
1046
+ commonUpload = (0, import_multer.default)({
1047
+ storage,
1048
+ limits: {
1049
+ fileSize: OneHundredMB
1050
+ }
1051
+ });
1052
+ return commonUpload;
1053
+ };
1054
+
1055
+ // src/restura/schemas/resturaSchema.ts
1056
+ var import_zod3 = require("zod");
1057
+
1058
+ // src/restura/schemas/validatorDataSchema.ts
1059
+ var import_zod2 = require("zod");
1060
+ var validatorDataSchemeValue = import_zod2.z.union([import_zod2.z.string(), import_zod2.z.array(import_zod2.z.string()), import_zod2.z.number(), import_zod2.z.array(import_zod2.z.number())]);
1061
+ var validatorDataSchema = import_zod2.z.object({
1062
+ type: import_zod2.z.enum(["TYPE_CHECK", "MIN", "MAX", "ONE_OF"]),
1063
+ value: validatorDataSchemeValue
1064
+ }).strict();
1065
+
1066
+ // src/restura/schemas/resturaSchema.ts
1067
+ var orderBySchema = import_zod3.z.object({
1068
+ columnName: import_zod3.z.string(),
1069
+ order: import_zod3.z.enum(["ASC", "DESC"]),
1070
+ tableName: import_zod3.z.string()
1071
+ }).strict();
1072
+ var groupBySchema = import_zod3.z.object({
1073
+ columnName: import_zod3.z.string(),
1074
+ tableName: import_zod3.z.string()
1075
+ }).strict();
1076
+ var whereDataSchema = import_zod3.z.object({
1077
+ tableName: import_zod3.z.string().optional(),
1078
+ columnName: import_zod3.z.string().optional(),
1079
+ operator: import_zod3.z.enum(["=", "<", ">", "<=", ">=", "!=", "LIKE", "IN", "NOT IN", "STARTS WITH", "ENDS WITH"]).optional(),
1080
+ value: import_zod3.z.string().or(import_zod3.z.number()).optional(),
1081
+ custom: import_zod3.z.string().optional(),
1082
+ conjunction: import_zod3.z.enum(["AND", "OR"]).optional()
1083
+ }).strict();
1084
+ var assignmentDataSchema = import_zod3.z.object({
1085
+ name: import_zod3.z.string(),
1086
+ value: import_zod3.z.string()
1087
+ }).strict();
1088
+ var joinDataSchema = import_zod3.z.object({
1089
+ table: import_zod3.z.string(),
1090
+ localColumnName: import_zod3.z.string().optional(),
1091
+ foreignColumnName: import_zod3.z.string().optional(),
1092
+ custom: import_zod3.z.string().optional(),
1093
+ type: import_zod3.z.enum(["LEFT", "INNER"]),
1094
+ alias: import_zod3.z.string().optional()
1095
+ }).strict();
1096
+ var requestDataSchema = import_zod3.z.object({
1097
+ name: import_zod3.z.string(),
1098
+ required: import_zod3.z.boolean(),
1099
+ isNullable: import_zod3.z.boolean().optional(),
1100
+ validator: import_zod3.z.array(validatorDataSchema)
1101
+ }).strict();
1102
+ var responseDataSchema = import_zod3.z.object({
1103
+ name: import_zod3.z.string(),
1104
+ selector: import_zod3.z.string().optional(),
1105
+ subquery: import_zod3.z.object({
1106
+ table: import_zod3.z.string(),
1107
+ joins: import_zod3.z.array(joinDataSchema),
1108
+ where: import_zod3.z.array(whereDataSchema),
1109
+ properties: import_zod3.z.array(import_zod3.z.lazy(() => responseDataSchema)),
1110
+ // Explicit type for the lazy schema
1111
+ groupBy: groupBySchema.optional(),
1112
+ orderBy: orderBySchema.optional()
1113
+ }).optional()
1114
+ }).strict();
1115
+ var routeDataBaseSchema = import_zod3.z.object({
1116
+ method: import_zod3.z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
1117
+ name: import_zod3.z.string(),
1118
+ description: import_zod3.z.string(),
1119
+ path: import_zod3.z.string(),
1120
+ roles: import_zod3.z.array(import_zod3.z.string())
1121
+ }).strict();
1122
+ var standardRouteSchema = routeDataBaseSchema.extend({
1123
+ type: import_zod3.z.enum(["ONE", "ARRAY", "PAGED"]),
1124
+ table: import_zod3.z.string(),
1125
+ joins: import_zod3.z.array(joinDataSchema),
1126
+ assignments: import_zod3.z.array(assignmentDataSchema),
1127
+ where: import_zod3.z.array(whereDataSchema),
1128
+ request: import_zod3.z.array(requestDataSchema),
1129
+ response: import_zod3.z.array(responseDataSchema),
1130
+ groupBy: groupBySchema.optional(),
1131
+ orderBy: orderBySchema.optional()
1132
+ }).strict();
1133
+ var customRouteSchema = routeDataBaseSchema.extend({
1134
+ type: import_zod3.z.enum(["CUSTOM_ONE", "CUSTOM_ARRAY", "CUSTOM_PAGED"]),
1135
+ responseType: import_zod3.z.union([import_zod3.z.string(), import_zod3.z.enum(["string", "number", "boolean"])]),
1136
+ requestType: import_zod3.z.string().optional(),
1137
+ request: import_zod3.z.array(requestDataSchema).optional(),
1138
+ table: import_zod3.z.undefined(),
1139
+ joins: import_zod3.z.undefined(),
1140
+ assignments: import_zod3.z.undefined(),
1141
+ fileUploadType: import_zod3.z.enum(["SINGLE", "MULTIPLE"]).optional()
1142
+ }).strict();
1143
+ var postgresColumnNumericTypesSchema = import_zod3.z.enum([
1144
+ "SMALLINT",
1145
+ // 2 bytes, -32,768 to 32,767
1146
+ "INTEGER",
1147
+ // 4 bytes, -2,147,483,648 to 2,147,483,647
1148
+ "BIGINT",
1149
+ // 8 bytes, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
1150
+ "DECIMAL",
1151
+ // user-specified precision, exact numeric
1152
+ "NUMERIC",
1153
+ // same as DECIMAL
1154
+ "REAL",
1155
+ // 4 bytes, 6 decimal digits precision (single precision)
1156
+ "DOUBLE PRECISION",
1157
+ // 8 bytes, 15 decimal digits precision (double precision)
1158
+ "SERIAL",
1159
+ // auto-incrementing integer
1160
+ "BIGSERIAL"
1161
+ // auto-incrementing big integer
1162
+ ]);
1163
+ var postgresColumnStringTypesSchema = import_zod3.z.enum([
1164
+ "CHAR",
1165
+ // fixed-length, blank-padded
1166
+ "VARCHAR",
1167
+ // variable-length with limit
1168
+ "TEXT",
1169
+ // variable-length without limit
1170
+ "BYTEA"
1171
+ // binary data
1172
+ ]);
1173
+ var postgresColumnDateTypesSchema = import_zod3.z.enum([
1174
+ "DATE",
1175
+ // calendar date (year, month, day)
1176
+ "TIMESTAMP",
1177
+ // both date and time (without time zone)
1178
+ "TIMESTAMPTZ",
1179
+ // both date and time (with time zone)
1180
+ "TIME",
1181
+ // time of day (without time zone)
1182
+ "INTERVAL"
1183
+ // time span
1184
+ ]);
1185
+ var postgresColumnJsonTypesSchema = import_zod3.z.enum([
1186
+ "JSON",
1187
+ // stores JSON data as raw text
1188
+ "JSONB"
1189
+ // stores JSON data in a binary format, optimized for query performance
1190
+ ]);
1191
+ var mariaDbColumnNumericTypesSchema = import_zod3.z.enum([
1192
+ "BOOLEAN",
1193
+ // 1-byte A synonym for "TINYINT(1)". Supported from version 1.2.0 onwards.
1194
+ "TINYINT",
1195
+ // 1-byte A very small integer. Numeric value with scale 0. Signed: -126 to +127. Unsigned: 0 to 253.
1196
+ "SMALLINT",
1197
+ // 2-bytes A small integer. Signed: -32,766 to 32,767. Unsigned: 0 to 65,533.
1198
+ "MEDIUMINT",
1199
+ // 3-bytes A medium integer. Signed: -8388608 to 8388607. Unsigned: 0 to 16777215. Supported starting with MariaDB ColumnStore 1.4.2.
1200
+ "INTEGER",
1201
+ // 4-bytes A normal-size integer. Numeric value with scale 0. Signed: -2,147,483,646 to 2,147,483,647. Unsigned: 0 to 4,294,967,293
1202
+ "BIGINT",
1203
+ // 8-bytes A large integer. Numeric value with scale 0. Signed: -9,223,372,036,854,775,806 to +9,223,372,036,854,775,807 Unsigned: 0 to +18,446,744,073,709,551,613
1204
+ "DECIMAL",
1205
+ // 2, 4, or 8 bytes A packed fixed-point number that can have a specific total number of digits and with a set number of digits after a decimal. The maximum precision (total number of digits) that can be specified is 18.
1206
+ "FLOAT",
1207
+ // 4 bytes Stored in 32-bit IEEE-754 floating point format. As such, the number of significant digits is about 6, and the range of values is approximately +/- 1e38.
1208
+ "DOUBLE"
1209
+ // 8 bytes Stored in 64-bit IEEE-754 floating point format. As such, the number of significant digits is about 15 and the range of values is approximately +/-1e308.
1210
+ ]);
1211
+ var mariaDbColumnStringTypesSchema = import_zod3.z.enum([
1212
+ "CHAR",
1213
+ // 1, 2, 4, or 8 bytes Holds letters and special characters of fixed length. Max length is 255. Default and minimum size is 1 byte.
1214
+ "VARCHAR",
1215
+ // 1, 2, 4, or 8 bytes or 8-byte token Holds letters, numbers, and special characters of variable length. Max length = 8000 bytes or characters and minimum length = 1 byte or character.
1216
+ "TINYTEXT",
1217
+ // 255 bytes Holds a small amount of letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
1218
+ "TINYBLOB",
1219
+ // 255 bytes Holds a small amount of binary data of variable length. Supported from version 1.1.0 onwards.
1220
+ "TEXT",
1221
+ // 64 KB Holds letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
1222
+ "BLOB",
1223
+ // 64 KB Holds binary data of variable length. Supported from version 1.1.0 onwards.
1224
+ "MEDIUMTEXT",
1225
+ // 16 MB Holds a medium amount of letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
1226
+ "MEDIUMBLOB",
1227
+ // 16 MB Holds a medium amount of binary data of variable length. Supported from version 1.1.0 onwards.
1228
+ "LONGTEXT",
1229
+ // 1.96 GB Holds a large amount of letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
1230
+ "JSON",
1231
+ // Alias for LONGTEXT, creates a CONSTRAINT for JSON_VALID, holds a JSON-formatted string of plain text.
1232
+ "LONGBLOB",
1233
+ // 1.96 GB Holds a large amount of binary data of variable length. Supported from version 1.1.0 onwards.
1234
+ "ENUM"
1235
+ // Enum type
1236
+ ]);
1237
+ var mariaDbColumnDateTypesSchema = import_zod3.z.enum([
1238
+ "DATE",
1239
+ // 4-bytes Date has year, month, and day.
1240
+ "DATETIME",
1241
+ // 8-bytes A date and time combination. Supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59. From version 1.2.0 microseconds are also supported.
1242
+ "TIME",
1243
+ // 8-bytes Holds hour, minute, second and optionally microseconds for time.
1244
+ "TIMESTAMP"
1245
+ // 4-bytes Values are stored as the number of seconds since 1970-01-01 00:00:00 UTC, and optionally microseconds.
1246
+ ]);
1247
+ var columnDataSchema = import_zod3.z.object({
1248
+ name: import_zod3.z.string(),
1249
+ type: import_zod3.z.union([
1250
+ postgresColumnNumericTypesSchema,
1251
+ postgresColumnStringTypesSchema,
1252
+ postgresColumnDateTypesSchema,
1253
+ postgresColumnJsonTypesSchema,
1254
+ mariaDbColumnNumericTypesSchema,
1255
+ mariaDbColumnStringTypesSchema,
1256
+ mariaDbColumnDateTypesSchema
1257
+ ]),
1258
+ isNullable: import_zod3.z.boolean(),
1259
+ roles: import_zod3.z.array(import_zod3.z.string()),
1260
+ comment: import_zod3.z.string().optional(),
1261
+ default: import_zod3.z.string().optional(),
1262
+ value: import_zod3.z.string().optional(),
1263
+ isPrimary: import_zod3.z.boolean().optional(),
1264
+ isUnique: import_zod3.z.boolean().optional(),
1265
+ hasAutoIncrement: import_zod3.z.boolean().optional(),
1266
+ length: import_zod3.z.number().optional()
1267
+ }).strict();
1268
+ var indexDataSchema = import_zod3.z.object({
1269
+ name: import_zod3.z.string(),
1270
+ columns: import_zod3.z.array(import_zod3.z.string()),
1271
+ isUnique: import_zod3.z.boolean(),
1272
+ isPrimaryKey: import_zod3.z.boolean(),
1273
+ order: import_zod3.z.enum(["ASC", "DESC"])
1274
+ }).strict();
1275
+ var foreignKeyActionsSchema = import_zod3.z.enum([
1276
+ "CASCADE",
1277
+ // CASCADE action for foreign keys
1278
+ "SET NULL",
1279
+ // SET NULL action for foreign keys
1280
+ "RESTRICT",
1281
+ // RESTRICT action for foreign keys
1282
+ "NO ACTION",
1283
+ // NO ACTION for foreign keys
1284
+ "SET DEFAULT"
1285
+ // SET DEFAULT action for foreign keys
1286
+ ]);
1287
+ var foreignKeyDataSchema = import_zod3.z.object({
1288
+ name: import_zod3.z.string(),
1289
+ column: import_zod3.z.string(),
1290
+ refTable: import_zod3.z.string(),
1291
+ refColumn: import_zod3.z.string(),
1292
+ onDelete: foreignKeyActionsSchema,
1293
+ onUpdate: foreignKeyActionsSchema
1294
+ }).strict();
1295
+ var checkConstraintDataSchema = import_zod3.z.object({
1296
+ name: import_zod3.z.string(),
1297
+ check: import_zod3.z.string()
1298
+ }).strict();
1299
+ var tableDataSchema = import_zod3.z.object({
1300
+ name: import_zod3.z.string(),
1301
+ columns: import_zod3.z.array(columnDataSchema),
1302
+ indexes: import_zod3.z.array(indexDataSchema),
1303
+ foreignKeys: import_zod3.z.array(foreignKeyDataSchema),
1304
+ checkConstraints: import_zod3.z.array(checkConstraintDataSchema),
1305
+ roles: import_zod3.z.array(import_zod3.z.string())
1306
+ }).strict();
1307
+ var endpointDataSchema = import_zod3.z.object({
1308
+ name: import_zod3.z.string(),
1309
+ description: import_zod3.z.string(),
1310
+ baseUrl: import_zod3.z.string(),
1311
+ routes: import_zod3.z.array(import_zod3.z.union([standardRouteSchema, customRouteSchema]))
1312
+ }).strict();
1313
+ var resturaSchema = import_zod3.z.object({
1314
+ database: import_zod3.z.array(tableDataSchema),
1315
+ endpoints: import_zod3.z.array(endpointDataSchema),
1316
+ globalParams: import_zod3.z.array(import_zod3.z.string()),
1317
+ roles: import_zod3.z.array(import_zod3.z.string()),
1318
+ customTypes: import_zod3.z.string()
1319
+ }).strict();
1320
+ async function isSchemaValid(schemaToCheck) {
1321
+ try {
1322
+ resturaSchema.parse(schemaToCheck);
1323
+ return true;
1324
+ } catch (error) {
1325
+ logger.error(error);
1326
+ return false;
1327
+ }
1328
+ }
1329
+
1330
+ // src/restura/validators/requestValidator.ts
1331
+ var import_core_utils3 = require("@redskytech/core-utils");
1332
+ var import_jsonschema = __toESM(require("jsonschema"));
1333
+ var import_zod4 = require("zod");
1334
+
1335
+ // src/restura/utils/utils.ts
1336
+ function addQuotesToStrings(variable) {
1337
+ if (typeof variable === "string") {
1338
+ return `'${variable}'`;
1339
+ } else if (Array.isArray(variable)) {
1340
+ const arrayWithQuotes = variable.map(addQuotesToStrings);
1341
+ return arrayWithQuotes;
1342
+ } else {
1343
+ return variable;
1344
+ }
1345
+ }
1346
+ function sortObjectKeysAlphabetically(obj) {
1347
+ if (Array.isArray(obj)) {
1348
+ return obj.map(sortObjectKeysAlphabetically);
1349
+ } else if (obj !== null && typeof obj === "object") {
1350
+ return Object.keys(obj).sort().reduce((sorted, key) => {
1351
+ sorted[key] = sortObjectKeysAlphabetically(obj[key]);
1352
+ return sorted;
1353
+ }, {});
1354
+ }
1355
+ return obj;
6
1356
  }
7
- export {
8
- isEven
1357
+
1358
+ // src/restura/validators/requestValidator.ts
1359
+ function requestValidator(req, routeData, validationSchema) {
1360
+ const requestData = getRequestData(req);
1361
+ req.data = requestData;
1362
+ if (routeData.request === void 0) {
1363
+ if (routeData.type !== "CUSTOM_ONE" && routeData.type !== "CUSTOM_ARRAY" && routeData.type !== "CUSTOM_PAGED")
1364
+ throw new RsError("BAD_REQUEST", `No request parameters provided for standard request.`);
1365
+ if (!routeData.responseType) throw new RsError("BAD_REQUEST", `No response type defined for custom request.`);
1366
+ if (!routeData.requestType) throw new RsError("BAD_REQUEST", `No request type defined for custom request.`);
1367
+ const currentInterface = validationSchema[routeData.requestType];
1368
+ const validator = new import_jsonschema.default.Validator();
1369
+ const executeValidation = validator.validate(req.data, currentInterface);
1370
+ if (!executeValidation.valid) {
1371
+ throw new RsError(
1372
+ "BAD_REQUEST",
1373
+ `Request custom setup has failed the following check: (${executeValidation.errors})`
1374
+ );
1375
+ }
1376
+ return;
1377
+ }
1378
+ Object.keys(req.data).forEach((requestParamName) => {
1379
+ const requestParam = routeData.request.find((param) => param.name === requestParamName);
1380
+ if (!requestParam) {
1381
+ throw new RsError("BAD_REQUEST", `Request param (${requestParamName}) is not allowed`);
1382
+ }
1383
+ });
1384
+ routeData.request.forEach((requestParam) => {
1385
+ const requestValue = requestData[requestParam.name];
1386
+ if (requestParam.required && requestValue === void 0)
1387
+ throw new RsError("BAD_REQUEST", `Request param (${requestParam.name}) is required but missing`);
1388
+ else if (!requestParam.required && requestValue === void 0) return;
1389
+ validateRequestSingleParam(requestValue, requestParam);
1390
+ });
1391
+ }
1392
+ function validateRequestSingleParam(requestValue, requestParam) {
1393
+ if (requestParam.isNullable && requestValue === null) return;
1394
+ requestParam.validator.forEach((validator) => {
1395
+ switch (validator.type) {
1396
+ case "TYPE_CHECK":
1397
+ performTypeCheck(requestValue, validator, requestParam.name);
1398
+ break;
1399
+ case "MIN":
1400
+ performMinCheck(requestValue, validator, requestParam.name);
1401
+ break;
1402
+ case "MAX":
1403
+ performMaxCheck(requestValue, validator, requestParam.name);
1404
+ break;
1405
+ case "ONE_OF":
1406
+ performOneOfCheck(requestValue, validator, requestParam.name);
1407
+ break;
1408
+ }
1409
+ });
1410
+ }
1411
+ function isValidType(type, requestValue) {
1412
+ try {
1413
+ expectValidType(type, requestValue);
1414
+ return true;
1415
+ } catch (e) {
1416
+ return false;
1417
+ }
1418
+ }
1419
+ function expectValidType(type, requestValue) {
1420
+ if (type === "number") {
1421
+ return import_zod4.z.number().parse(requestValue);
1422
+ }
1423
+ if (type === "string") {
1424
+ return import_zod4.z.string().parse(requestValue);
1425
+ }
1426
+ if (type === "boolean") {
1427
+ return import_zod4.z.boolean().parse(requestValue);
1428
+ }
1429
+ if (type === "string[]") {
1430
+ return import_zod4.z.array(import_zod4.z.string()).parse(requestValue);
1431
+ }
1432
+ if (type === "number[]") {
1433
+ return import_zod4.z.array(import_zod4.z.number()).parse(requestValue);
1434
+ }
1435
+ if (type === "any[]") {
1436
+ return import_zod4.z.array(import_zod4.z.any()).parse(requestValue);
1437
+ }
1438
+ if (type === "object") {
1439
+ return import_zod4.z.object({}).strict().parse(requestValue);
1440
+ }
1441
+ }
1442
+ function performTypeCheck(requestValue, validator, requestParamName) {
1443
+ if (!isValidType(validator.value, requestValue)) {
1444
+ throw new RsError(
1445
+ "BAD_REQUEST",
1446
+ `Request param (${requestParamName}) with value (${addQuotesToStrings(requestValue)}) is not of type (${validator.value})`
1447
+ );
1448
+ }
1449
+ try {
1450
+ validatorDataSchemeValue.parse(validator.value);
1451
+ } catch (e) {
1452
+ throw new RsError("SCHEMA_ERROR", `Schema validator value (${validator.value}) is not a valid type`);
1453
+ }
1454
+ }
1455
+ function expectOnlyNumbers(requestValue, validator, requestParamName) {
1456
+ if (!isValueNumber(requestValue))
1457
+ throw new RsError(
1458
+ "BAD_REQUEST",
1459
+ `Request param (${requestParamName}) with value (${requestValue}) is not of type number`
1460
+ );
1461
+ if (!isValueNumber(validator.value))
1462
+ throw new RsError("SCHEMA_ERROR", `Schema validator value (${validator.value} is not of type number`);
1463
+ }
1464
+ function performMinCheck(requestValue, validator, requestParamName) {
1465
+ expectOnlyNumbers(requestValue, validator, requestParamName);
1466
+ if (requestValue < validator.value)
1467
+ throw new RsError(
1468
+ "BAD_REQUEST",
1469
+ `Request param (${requestParamName}) with value (${requestValue}) is less than (${validator.value})`
1470
+ );
1471
+ }
1472
+ function performMaxCheck(requestValue, validator, requestParamName) {
1473
+ expectOnlyNumbers(requestValue, validator, requestParamName);
1474
+ if (requestValue > validator.value)
1475
+ throw new RsError(
1476
+ "BAD_REQUEST",
1477
+ `Request param (${requestParamName}) with value (${requestValue}) is more than (${validator.value})`
1478
+ );
1479
+ }
1480
+ function performOneOfCheck(requestValue, validator, requestParamName) {
1481
+ if (!import_core_utils3.ObjectUtils.isArrayWithData(validator.value))
1482
+ throw new RsError("SCHEMA_ERROR", `Schema validator value (${validator.value}) is not of type array`);
1483
+ if (typeof requestValue === "object")
1484
+ throw new RsError("BAD_REQUEST", `Request param (${requestParamName}) is not of type string or number`);
1485
+ if (!validator.value.includes(requestValue))
1486
+ throw new RsError(
1487
+ "BAD_REQUEST",
1488
+ `Request param (${requestParamName}) with value (${requestValue}) is not one of (${validator.value.join(", ")})`
1489
+ );
1490
+ }
1491
+ function isValueNumber(value) {
1492
+ return !isNaN(Number(value));
1493
+ }
1494
+ function getRequestData(req) {
1495
+ let body = "";
1496
+ if (req.method === "GET" || req.method === "DELETE") {
1497
+ body = "query";
1498
+ } else {
1499
+ body = "body";
1500
+ }
1501
+ const bodyData = req[body];
1502
+ if (bodyData && body === "query") {
1503
+ for (const attr in bodyData) {
1504
+ if (bodyData[attr] instanceof Array) {
1505
+ const attrList = [];
1506
+ for (const value of bodyData[attr]) {
1507
+ if (isNaN(Number(value))) continue;
1508
+ attrList.push(Number(value));
1509
+ }
1510
+ if (import_core_utils3.ObjectUtils.isArrayWithData(attrList)) {
1511
+ bodyData[attr] = attrList;
1512
+ }
1513
+ } else {
1514
+ bodyData[attr] = import_core_utils3.ObjectUtils.safeParse(bodyData[attr]);
1515
+ if (isNaN(Number(bodyData[attr]))) continue;
1516
+ bodyData[attr] = Number(bodyData[attr]);
1517
+ }
1518
+ }
1519
+ }
1520
+ return bodyData;
1521
+ }
1522
+
1523
+ // src/restura/middleware/schemaValidation.ts
1524
+ async function schemaValidation(req, res, next) {
1525
+ req.data = getRequestData(req);
1526
+ try {
1527
+ resturaSchema.parse(req.data);
1528
+ next();
1529
+ } catch (error) {
1530
+ logger.error(error);
1531
+ res.sendError("BAD_REQUEST", error, 400 /* BAD_REQUEST */);
1532
+ }
1533
+ }
1534
+
1535
+ // src/restura/schemas/resturaConfigSchema.ts
1536
+ var import_zod5 = require("zod");
1537
+ var _a;
1538
+ var isTsx = (_a = process.argv[1]) == null ? void 0 : _a.endsWith(".ts");
1539
+ var isTsNode = process.env.TS_NODE_DEV || process.env.TS_NODE_PROJECT;
1540
+ var customApiFolderPath = isTsx || isTsNode ? "/src/api" : "/dist/api";
1541
+ var resturaConfigSchema = import_zod5.z.object({
1542
+ authToken: import_zod5.z.string().min(1, "Missing Restura Auth Token"),
1543
+ sendErrorStackTrace: import_zod5.z.boolean().default(false),
1544
+ schemaFilePath: import_zod5.z.string().default(process.cwd() + "/restura.schema.json"),
1545
+ customApiFolderPath: import_zod5.z.string().default(process.cwd() + customApiFolderPath),
1546
+ generatedTypesPath: import_zod5.z.string().default(process.cwd() + "/src/@types"),
1547
+ fileTempCachePath: import_zod5.z.string().optional()
1548
+ });
1549
+
1550
+ // src/restura/sql/PsqlEngine.ts
1551
+ var import_core_utils5 = require("@redskytech/core-utils");
1552
+ var import_pg_diff_sync = __toESM(require("@wmfs/pg-diff-sync"));
1553
+ var import_pg_info = __toESM(require("@wmfs/pg-info"));
1554
+ var import_pg2 = __toESM(require("pg"));
1555
+
1556
+ // src/restura/sql/PsqlPool.ts
1557
+ var import_pg = __toESM(require("pg"));
1558
+
1559
+ // src/restura/sql/PsqlConnection.ts
1560
+ var import_crypto = __toESM(require("crypto"));
1561
+ var import_pg_format2 = __toESM(require("pg-format"));
1562
+
1563
+ // src/restura/sql/PsqlUtils.ts
1564
+ var import_pg_format = __toESM(require("pg-format"));
1565
+ function escapeColumnName(columnName) {
1566
+ if (columnName === void 0) return "";
1567
+ return `"${columnName.replace(/"/g, "")}"`.replace(".", '"."');
1568
+ }
1569
+ function questionMarksToOrderedParams(query) {
1570
+ let count = 1;
1571
+ let inSingleQuote = false;
1572
+ let inDoubleQuote = false;
1573
+ return query.replace(/('|"|\?)/g, (char) => {
1574
+ if (char === "'") {
1575
+ inSingleQuote = !inSingleQuote && !inDoubleQuote;
1576
+ return char;
1577
+ }
1578
+ if (char === '"') {
1579
+ inDoubleQuote = !inDoubleQuote && !inSingleQuote;
1580
+ return char;
1581
+ }
1582
+ if (char === "?" && !inSingleQuote && !inDoubleQuote) {
1583
+ return `$${count++}`;
1584
+ }
1585
+ return char;
1586
+ });
1587
+ }
1588
+ function insertObjectQuery(table, obj) {
1589
+ const keys = Object.keys(obj);
1590
+ const params = Object.values(obj);
1591
+ const columns = keys.map((column) => escapeColumnName(column)).join(", ");
1592
+ const values = params.map((value) => SQL`${value}`).join(", ");
1593
+ const query = `
1594
+ INSERT INTO "${table}" (${columns})
1595
+ VALUES (${values})
1596
+ RETURNING *`;
1597
+ return query;
1598
+ }
1599
+ function updateObjectQuery(table, obj, whereStatement) {
1600
+ const setArray = [];
1601
+ for (const i in obj) {
1602
+ setArray.push(`${escapeColumnName(i)} = ` + SQL`${obj[i]}`);
1603
+ }
1604
+ return `
1605
+ UPDATE ${escapeColumnName(table)}
1606
+ SET ${setArray.join(", ")} ${whereStatement}
1607
+ RETURNING *`;
1608
+ }
1609
+ function isValueNumber2(value) {
1610
+ return !isNaN(Number(value));
1611
+ }
1612
+ function SQL(strings, ...values) {
1613
+ let query = strings[0];
1614
+ values.forEach((value, index) => {
1615
+ if (typeof value === "boolean") {
1616
+ query += value;
1617
+ } else if (typeof value === "number") {
1618
+ query += value;
1619
+ } else if (Array.isArray(value)) {
1620
+ query += import_pg_format.default.literal(JSON.stringify(value)) + "::jsonb";
1621
+ } else {
1622
+ query += import_pg_format.default.literal(value);
1623
+ }
1624
+ query += strings[index + 1];
1625
+ });
1626
+ return query;
1627
+ }
1628
+
1629
+ // src/restura/sql/PsqlConnection.ts
1630
+ var PsqlConnection = class {
1631
+ constructor() {
1632
+ this.instanceId = import_crypto.default.randomUUID();
1633
+ }
1634
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1635
+ async queryOne(query, options, requesterDetails) {
1636
+ const formattedQuery = questionMarksToOrderedParams(query);
1637
+ const meta = __spreadValues({ connectionInstanceId: this.instanceId }, requesterDetails);
1638
+ this.logSqlStatement(formattedQuery, options, meta);
1639
+ const queryMetadata = `--QUERY_METADATA(${JSON.stringify(meta)})
1640
+ `;
1641
+ try {
1642
+ const response = await this.query(queryMetadata + formattedQuery, options);
1643
+ if (response.rows.length === 0) throw new RsError("NOT_FOUND", "No results found");
1644
+ else if (response.rows.length > 1) throw new RsError("DUPLICATE", "More than one result found");
1645
+ return response.rows[0];
1646
+ } catch (error) {
1647
+ console.error(error, query, options);
1648
+ if (RsError.isRsError(error)) throw error;
1649
+ if ((error == null ? void 0 : error.routine) === "_bt_check_unique") {
1650
+ throw new RsError("DUPLICATE", error.message);
1651
+ }
1652
+ throw new RsError("DATABASE_ERROR", `${error.message}`);
1653
+ }
1654
+ }
1655
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1656
+ async runQuery(query, options, requesterDetails) {
1657
+ const formattedQuery = questionMarksToOrderedParams(query);
1658
+ const meta = __spreadValues({ connectionInstanceId: this.instanceId }, requesterDetails);
1659
+ this.logSqlStatement(formattedQuery, options, meta);
1660
+ const queryMetadata = `--QUERY_METADATA(${JSON.stringify(meta)})
1661
+ `;
1662
+ try {
1663
+ const response = await this.query(queryMetadata + formattedQuery, options);
1664
+ return response.rows;
1665
+ } catch (error) {
1666
+ console.error(error, query, options);
1667
+ if ((error == null ? void 0 : error.routine) === "_bt_check_unique") {
1668
+ throw new RsError("DUPLICATE", error.message);
1669
+ }
1670
+ throw new RsError("DATABASE_ERROR", `${error.message}`);
1671
+ }
1672
+ }
1673
+ logSqlStatement(query, options, queryMetadata, prefix = "") {
1674
+ if (logger.level !== "silly") return;
1675
+ let sqlStatement = "";
1676
+ if (options.length === 0) {
1677
+ sqlStatement = query;
1678
+ } else {
1679
+ let stringIndex = 0;
1680
+ sqlStatement = query.replace(/\$\d+/g, () => {
1681
+ const value = options[stringIndex++];
1682
+ if (typeof value === "number") return value.toString();
1683
+ return import_pg_format2.default.literal(value);
1684
+ });
1685
+ }
1686
+ let initiator = "Anonymous";
1687
+ if ("userId" in queryMetadata && queryMetadata.userId)
1688
+ initiator = `User Id (${queryMetadata.userId.toString()})`;
1689
+ if ("isSystemUser" in queryMetadata && queryMetadata.isSystemUser) initiator = "SYSTEM";
1690
+ logger.silly(`${prefix}query by ${initiator}, Query ->
1691
+ ${sqlStatement}`);
1692
+ }
1693
+ };
1694
+
1695
+ // src/restura/sql/PsqlPool.ts
1696
+ var { Pool } = import_pg.default;
1697
+ var PsqlPool = class extends PsqlConnection {
1698
+ constructor(poolConfig) {
1699
+ super();
1700
+ this.poolConfig = poolConfig;
1701
+ this.pool = new Pool(poolConfig);
1702
+ this.queryOne("SELECT NOW();", [], { isSystemUser: true, role: "", host: "localhost", ipAddress: "" }).then(() => {
1703
+ logger.info("Connected to PostgreSQL database");
1704
+ }).catch((error) => {
1705
+ logger.error("Error connecting to database", error);
1706
+ process.exit(1);
1707
+ });
1708
+ }
1709
+ async query(query, values) {
1710
+ return this.pool.query(query, values);
1711
+ }
1712
+ };
1713
+
1714
+ // src/restura/sql/SqlEngine.ts
1715
+ var import_core_utils4 = require("@redskytech/core-utils");
1716
+ var SqlEngine = class {
1717
+ async runQueryForRoute(req, routeData, schema) {
1718
+ if (!this.doesRoleHavePermissionToTable(req.requesterDetails.role, schema, routeData.table))
1719
+ throw new RsError("UNAUTHORIZED", "You do not have permission to access this table");
1720
+ switch (routeData.method) {
1721
+ case "POST":
1722
+ return this.executeCreateRequest(req, routeData, schema);
1723
+ case "GET":
1724
+ return this.executeGetRequest(req, routeData, schema);
1725
+ case "PUT":
1726
+ case "PATCH":
1727
+ return this.executeUpdateRequest(req, routeData, schema);
1728
+ case "DELETE":
1729
+ return this.executeDeleteRequest(req, routeData, schema);
1730
+ }
1731
+ }
1732
+ getTableSchema(schema, tableName) {
1733
+ const tableSchema = schema.database.find((item) => item.name === tableName);
1734
+ if (!tableSchema) throw new RsError("SCHEMA_ERROR", `Table ${tableName} not found in schema`);
1735
+ return tableSchema;
1736
+ }
1737
+ doesRoleHavePermissionToColumn(role, schema, item, joins) {
1738
+ if (item.selector) {
1739
+ let tableName = item.selector.split(".")[0];
1740
+ const columnName = item.selector.split(".")[1];
1741
+ let tableSchema = schema.database.find((item2) => item2.name === tableName);
1742
+ if (!tableSchema) {
1743
+ const join = joins.find((join2) => join2.alias === tableName);
1744
+ if (!join) throw new RsError("SCHEMA_ERROR", `Table ${tableName} not found in schema`);
1745
+ tableName = join.table;
1746
+ tableSchema = schema.database.find((item2) => item2.name === tableName);
1747
+ }
1748
+ if (!tableSchema) throw new RsError("SCHEMA_ERROR", `Table ${tableName} not found in schema`);
1749
+ const columnSchema = tableSchema.columns.find((item2) => item2.name === columnName);
1750
+ if (!columnSchema)
1751
+ throw new RsError("SCHEMA_ERROR", `Column ${columnName} not found in table ${tableName}`);
1752
+ const doesColumnHaveRoles = import_core_utils4.ObjectUtils.isArrayWithData(columnSchema.roles);
1753
+ if (!doesColumnHaveRoles) return true;
1754
+ if (!role) return false;
1755
+ return columnSchema.roles.includes(role);
1756
+ }
1757
+ if (item.subquery) {
1758
+ return import_core_utils4.ObjectUtils.isArrayWithData(
1759
+ item.subquery.properties.filter((nestedItem) => {
1760
+ return this.doesRoleHavePermissionToColumn(role, schema, nestedItem, joins);
1761
+ })
1762
+ );
1763
+ }
1764
+ return false;
1765
+ }
1766
+ doesRoleHavePermissionToTable(userRole, schema, tableName) {
1767
+ const tableSchema = this.getTableSchema(schema, tableName);
1768
+ const doesTableHaveRoles = import_core_utils4.ObjectUtils.isArrayWithData(tableSchema.roles);
1769
+ if (!doesTableHaveRoles) return true;
1770
+ if (!userRole) return false;
1771
+ return tableSchema.roles.includes(userRole);
1772
+ }
1773
+ replaceParamKeywords(value, routeData, req, sqlParams) {
1774
+ let returnValue = value;
1775
+ returnValue = this.replaceLocalParamKeywords(returnValue, routeData, req, sqlParams);
1776
+ returnValue = this.replaceGlobalParamKeywords(returnValue, routeData, req, sqlParams);
1777
+ return returnValue;
1778
+ }
1779
+ replaceLocalParamKeywords(value, routeData, req, sqlParams) {
1780
+ var _a2;
1781
+ if (!routeData.request) return value;
1782
+ const data = req.data;
1783
+ if (typeof value === "string") {
1784
+ (_a2 = value.match(/\$[a-zA-Z][a-zA-Z0-9_]+/g)) == null ? void 0 : _a2.forEach((param) => {
1785
+ const requestParam = routeData.request.find((item) => {
1786
+ return item.name === param.replace("$", "");
1787
+ });
1788
+ if (!requestParam)
1789
+ throw new RsError("SCHEMA_ERROR", `Invalid route keyword in route ${routeData.name}`);
1790
+ sqlParams.push(data[requestParam.name]);
1791
+ });
1792
+ return value.replace(new RegExp(/\$[a-zA-Z][a-zA-Z0-9_]+/g), "?");
1793
+ }
1794
+ return value;
1795
+ }
1796
+ replaceGlobalParamKeywords(value, routeData, req, sqlParams) {
1797
+ var _a2;
1798
+ if (typeof value === "string") {
1799
+ (_a2 = value.match(/#[a-zA-Z][a-zA-Z0-9_]+/g)) == null ? void 0 : _a2.forEach((param) => {
1800
+ param = param.replace("#", "");
1801
+ const globalParamValue = req.requesterDetails[param];
1802
+ if (!globalParamValue)
1803
+ throw new RsError(
1804
+ "SCHEMA_ERROR",
1805
+ `Invalid global keyword clause in route (${routeData.path}) when looking for (#${param})`
1806
+ );
1807
+ sqlParams.push(globalParamValue);
1808
+ });
1809
+ return value.replace(new RegExp(/#[a-zA-Z][a-zA-Z0-9_]+/g), "?");
1810
+ }
1811
+ return value;
1812
+ }
1813
+ };
1814
+
1815
+ // src/restura/sql/filterPsqlParser.ts
1816
+ var import_pegjs = __toESM(require("pegjs"));
1817
+ var filterSqlGrammar = `
1818
+ {
1819
+ // ported from pg-format but intentionally will add double quotes to every column
1820
+ function quoteSqlIdentity(value) {
1821
+ if (value === undefined || value === null) {
1822
+ throw new Error('SQL identifier cannot be null or undefined');
1823
+ } else if (value === false) {
1824
+ return '"f"';
1825
+ } else if (value === true) {
1826
+ return '"t"';
1827
+ } else if (value instanceof Date) {
1828
+ // return '"' + formatDate(value.toISOString()) + '"';
1829
+ } else if (value instanceof Buffer) {
1830
+ throw new Error('SQL identifier cannot be a buffer');
1831
+ } else if (Array.isArray(value) === true) {
1832
+ var temp = [];
1833
+ for (var i = 0; i < value.length; i++) {
1834
+ if (Array.isArray(value[i]) === true) {
1835
+ throw new Error('Nested array to grouped list conversion is not supported for SQL identifier');
1836
+ } else {
1837
+ // temp.push(quoteIdent(value[i]));
1838
+ }
1839
+ }
1840
+ return temp.toString();
1841
+ } else if (value === Object(value)) {
1842
+ throw new Error('SQL identifier cannot be an object');
1843
+ }
1844
+
1845
+ var ident = value.toString().slice(0); // create copy
1846
+
1847
+ // do not quote a valid, unquoted identifier
1848
+ // if (/^[a-z_][a-z0-9_$]*$/.test(ident) === true && isReserved(ident) === false) {
1849
+ // return ident;
1850
+ // }
1851
+
1852
+ var quoted = '"';
1853
+
1854
+ for (var i = 0; i < ident.length; i++) {
1855
+ var c = ident[i];
1856
+ if (c === '"') {
1857
+ quoted += c + c;
1858
+ } else {
1859
+ quoted += c;
1860
+ }
1861
+ }
1862
+
1863
+ quoted += '"';
1864
+
1865
+ return quoted;
1866
+ };
1867
+ }
1868
+
1869
+ start = expressionList
1870
+
1871
+ _ = [ \\t\\r\\n]* // Matches spaces, tabs, and line breaks
1872
+
1873
+ expressionList =
1874
+ leftExpression:expression _ operator:operator _ rightExpression:expressionList
1875
+ { return \`\${leftExpression} \${operator} \${rightExpression}\`;}
1876
+ / expression
1877
+
1878
+ expression =
1879
+ negate:negate? _ "(" _ "column" _ ":" column:column _ ","? _ value:value? ","? _ type:type? _ ")"_
1880
+ {return \`\${negate? " NOT " : ""}(\${type? type(column, value) : \`\${column} = \${format.literal(value)}\`})\`;}
1881
+ /
1882
+ negate:negate?"("expression:expressionList")" { return \`\${negate? " NOT " : ""}(\${expression})\`; }
1883
+
1884
+ negate = "!"
1885
+
1886
+ operator = "and"i / "or"i
1887
+
1888
+
1889
+ column = left:text "." right:text { return \`\${quoteSqlIdentity(left)}.\${quoteSqlIdentity(right)}\`; }
1890
+ /
1891
+ text:text { return quoteSqlIdentity(text); }
1892
+
1893
+
1894
+ text = text:[a-z0-9 \\t\\r\\n\\-_:@]i+ { return text.join(""); }
1895
+
1896
+ type = "type" _ ":" _ type:typeString { return type; }
1897
+ typeString = text:"startsWith" { return function(column, value) { return \`\${column} ILIKE '\${format.literal(value).slice(1,-1)}%'\`; } } /
1898
+ text:"endsWith" { return function(column, value) { return \`\${column} ILIKE '%\${format.literal(value).slice(1,-1)}'\`; } } /
1899
+ text:"contains" { return function(column, value) { return \`\${column} ILIKE '%\${format.literal(value).slice(1,-1)}%'\`; } } /
1900
+ text:"exact" { return function(column, value) { return \`\${column} = '\${format.literal(value).slice(1,-1)}'\`; } } /
1901
+ text:"greaterThanEqual" { return function(column, value) { return \`\${column} >= '\${format.literal(value).slice(1,-1)}'\`; } } /
1902
+ text:"greaterThan" { return function(column, value) { return \`\${column} > '\${format.literal(value).slice(1,-1)}'\`; } } /
1903
+ text:"lessThanEqual" { return function(column, value) { return \`\${column} <= '\${format.literal(value).slice(1,-1)}'\`; } } /
1904
+ text:"lessThan" { return function(column, value) { return \`\${column} < '\${format.literal(value).slice(1,-1)}'\`; } } /
1905
+ text:"isNull" { return function(column, value) { return \`isNull(\${column})\`; } }
1906
+
1907
+ value = "value" _ ":" value:text { return value; }
1908
+
1909
+
1910
+ `;
1911
+ var filterPsqlParser = import_pegjs.default.generate(filterSqlGrammar, {
1912
+ format: "commonjs",
1913
+ dependencies: { format: "pg-format" }
1914
+ });
1915
+ var filterPsqlParser_default = filterPsqlParser;
1916
+
1917
+ // src/restura/sql/PsqlEngine.ts
1918
+ var { Client, types } = import_pg2.default;
1919
+ var systemUser = {
1920
+ role: "",
1921
+ host: "",
1922
+ ipAddress: "",
1923
+ isSystemUser: true
1924
+ };
1925
+ var PsqlEngine = class extends SqlEngine {
1926
+ constructor(psqlConnectionPool, shouldListenForDbTriggers = false) {
1927
+ super();
1928
+ this.psqlConnectionPool = psqlConnectionPool;
1929
+ this.setupPgReturnTypes();
1930
+ if (shouldListenForDbTriggers) {
1931
+ this.setupTriggerListeners = this.listenForDbTriggers();
1932
+ }
1933
+ }
1934
+ async close() {
1935
+ if (this.triggerClient) {
1936
+ await this.triggerClient.end();
1937
+ }
1938
+ }
1939
+ setupPgReturnTypes() {
1940
+ const TIMESTAMPTZ_OID = 1184;
1941
+ types.setTypeParser(TIMESTAMPTZ_OID, (val) => {
1942
+ return val === null ? null : new Date(val).toISOString();
1943
+ });
1944
+ const BIGINT_OID = 20;
1945
+ types.setTypeParser(BIGINT_OID, (val) => {
1946
+ return val === null ? null : Number(val);
1947
+ });
1948
+ }
1949
+ async listenForDbTriggers() {
1950
+ this.triggerClient = new Client({
1951
+ user: this.psqlConnectionPool.poolConfig.user,
1952
+ host: this.psqlConnectionPool.poolConfig.host,
1953
+ database: this.psqlConnectionPool.poolConfig.database,
1954
+ password: this.psqlConnectionPool.poolConfig.password,
1955
+ port: this.psqlConnectionPool.poolConfig.port,
1956
+ connectionTimeoutMillis: this.psqlConnectionPool.poolConfig.connectionTimeoutMillis
1957
+ });
1958
+ await this.triggerClient.connect();
1959
+ const promises = [];
1960
+ promises.push(this.triggerClient.query("LISTEN insert"));
1961
+ promises.push(this.triggerClient.query("LISTEN update"));
1962
+ promises.push(this.triggerClient.query("LISTEN delete"));
1963
+ await Promise.all(promises);
1964
+ this.triggerClient.on("notification", async (msg) => {
1965
+ if (msg.channel === "insert" || msg.channel === "update" || msg.channel === "delete") {
1966
+ const payload = import_core_utils5.ObjectUtils.safeParse(msg.payload);
1967
+ await this.handleTrigger(payload, msg.channel.toUpperCase());
1968
+ }
1969
+ });
1970
+ }
1971
+ async handleTrigger(payload, mutationType) {
1972
+ const findRequesterDetailsRegex = /^--QUERY_METADATA\(\{.*\}\)/;
1973
+ const match = payload.query.match(findRequesterDetailsRegex);
1974
+ if (match) {
1975
+ const jsonString = match[0].slice(match[0].indexOf("{"), match[0].lastIndexOf("}") + 1);
1976
+ const queryMetadata = import_core_utils5.ObjectUtils.safeParse(jsonString);
1977
+ const triggerFromThisInstance = queryMetadata.connectionInstanceId === this.psqlConnectionPool.instanceId;
1978
+ if (!triggerFromThisInstance) {
1979
+ return;
1980
+ }
1981
+ await eventManager_default.fireActionFromDbTrigger({ queryMetadata, mutationType }, payload);
1982
+ }
1983
+ }
1984
+ async createDatabaseFromSchema(schema, connection) {
1985
+ const sqlFullStatement = this.generateDatabaseSchemaFromSchema(schema);
1986
+ await connection.runQuery(sqlFullStatement, [], systemUser);
1987
+ return sqlFullStatement;
1988
+ }
1989
+ generateDatabaseSchemaFromSchema(schema) {
1990
+ const sqlStatements = [];
1991
+ const indexes = [];
1992
+ const triggers = [];
1993
+ for (const table of schema.database) {
1994
+ triggers.push(this.createInsertTriggers(table.name));
1995
+ triggers.push(this.createUpdateTrigger(table.name));
1996
+ triggers.push(this.createDeleteTrigger(table.name));
1997
+ let sql = `CREATE TABLE "${table.name}"
1998
+ ( `;
1999
+ const tableColumns = [];
2000
+ for (const column of table.columns) {
2001
+ let columnSql = "";
2002
+ columnSql += ` "${column.name}" ${this.schemaToPsqlType(column)}`;
2003
+ let value = column.value;
2004
+ if (column.type === "JSON") value = "";
2005
+ if (column.type === "JSONB") value = "";
2006
+ if (column.type === "DECIMAL" && value) {
2007
+ value = value.replace("-", ",").replace(/['"]/g, "");
2008
+ }
2009
+ if (value && column.type !== "ENUM") {
2010
+ columnSql += `(${value})`;
2011
+ } else if (column.length) columnSql += `(${column.length})`;
2012
+ if (column.isPrimary) {
2013
+ columnSql += " PRIMARY KEY ";
2014
+ }
2015
+ if (column.isUnique) {
2016
+ columnSql += ` CONSTRAINT "${table.name}_${column.name}_unique_index" UNIQUE `;
2017
+ }
2018
+ if (column.isNullable) columnSql += " NULL";
2019
+ else columnSql += " NOT NULL";
2020
+ if (column.default) columnSql += ` DEFAULT ${column.default}`;
2021
+ if (value && column.type === "ENUM") {
2022
+ columnSql += ` CHECK ("${column.name}" IN (${value}))`;
2023
+ }
2024
+ tableColumns.push(columnSql);
2025
+ }
2026
+ sql += tableColumns.join(", \n");
2027
+ for (const index of table.indexes) {
2028
+ if (!index.isPrimaryKey) {
2029
+ let unique = " ";
2030
+ if (index.isUnique) unique = "UNIQUE ";
2031
+ indexes.push(
2032
+ ` CREATE ${unique}INDEX "${index.name}" ON "${table.name}" (${index.columns.map((item) => {
2033
+ return `"${item}" ${index.order}`;
2034
+ }).join(", ")});`
2035
+ );
2036
+ }
2037
+ }
2038
+ sql += "\n);";
2039
+ sqlStatements.push(sql);
2040
+ }
2041
+ for (const table of schema.database) {
2042
+ if (!table.foreignKeys.length) continue;
2043
+ const sql = `ALTER TABLE "${table.name}" `;
2044
+ const constraints = [];
2045
+ for (const foreignKey of table.foreignKeys) {
2046
+ let constraint = ` ADD CONSTRAINT "${foreignKey.name}"
2047
+ FOREIGN KEY ("${foreignKey.column}") REFERENCES "${foreignKey.refTable}" ("${foreignKey.refColumn}")`;
2048
+ constraint += ` ON DELETE ${foreignKey.onDelete}`;
2049
+ constraint += ` ON UPDATE ${foreignKey.onUpdate}`;
2050
+ constraints.push(constraint);
2051
+ }
2052
+ sqlStatements.push(sql + constraints.join(",\n") + ";");
2053
+ }
2054
+ for (const table of schema.database) {
2055
+ if (!table.checkConstraints.length) continue;
2056
+ const sql = `ALTER TABLE "${table.name}" `;
2057
+ const constraints = [];
2058
+ for (const check of table.checkConstraints) {
2059
+ const constraint = `ADD CONSTRAINT "${check.name}" CHECK (${check.check})`;
2060
+ constraints.push(constraint);
2061
+ }
2062
+ sqlStatements.push(sql + constraints.join(",\n") + ";");
2063
+ }
2064
+ sqlStatements.push(indexes.join("\n"));
2065
+ sqlStatements.push(triggers.join("\n"));
2066
+ return sqlStatements.join("\n\n");
2067
+ }
2068
+ async getScratchPool() {
2069
+ var _a2, _b;
2070
+ const scratchDbExists = await this.psqlConnectionPool.runQuery(
2071
+ `SELECT *
2072
+ FROM pg_database
2073
+ WHERE datname = '${this.psqlConnectionPool.poolConfig.database}_scratch';`,
2074
+ [],
2075
+ systemUser
2076
+ );
2077
+ if (scratchDbExists.length === 0) {
2078
+ await this.psqlConnectionPool.runQuery(
2079
+ `CREATE DATABASE ${this.psqlConnectionPool.poolConfig.database}_scratch;`,
2080
+ [],
2081
+ systemUser
2082
+ );
2083
+ }
2084
+ const scratchPool = new PsqlPool({
2085
+ host: this.psqlConnectionPool.poolConfig.host,
2086
+ port: this.psqlConnectionPool.poolConfig.port,
2087
+ user: this.psqlConnectionPool.poolConfig.user,
2088
+ database: this.psqlConnectionPool.poolConfig.database + "_scratch",
2089
+ password: this.psqlConnectionPool.poolConfig.password,
2090
+ max: this.psqlConnectionPool.poolConfig.max,
2091
+ idleTimeoutMillis: this.psqlConnectionPool.poolConfig.idleTimeoutMillis,
2092
+ connectionTimeoutMillis: this.psqlConnectionPool.poolConfig.connectionTimeoutMillis
2093
+ });
2094
+ await scratchPool.runQuery(`DROP SCHEMA public CASCADE;`, [], systemUser);
2095
+ await scratchPool.runQuery(
2096
+ `CREATE SCHEMA public AUTHORIZATION ${this.psqlConnectionPool.poolConfig.user};`,
2097
+ [],
2098
+ systemUser
2099
+ );
2100
+ const schemaComment = await this.psqlConnectionPool.runQuery(
2101
+ `SELECT pg_description.description
2102
+ FROM pg_description
2103
+ JOIN pg_namespace ON pg_namespace.oid = pg_description.objoid
2104
+ WHERE pg_namespace.nspname = 'public';`,
2105
+ [],
2106
+ systemUser
2107
+ );
2108
+ if ((_a2 = schemaComment[0]) == null ? void 0 : _a2.description) {
2109
+ await scratchPool.runQuery(
2110
+ `COMMENT ON SCHEMA public IS '${(_b = schemaComment[0]) == null ? void 0 : _b.description}';`,
2111
+ [],
2112
+ systemUser
2113
+ );
2114
+ }
2115
+ return scratchPool;
2116
+ }
2117
+ async diffDatabaseToSchema(schema) {
2118
+ const scratchPool = await this.getScratchPool();
2119
+ await this.createDatabaseFromSchema(schema, scratchPool);
2120
+ const originalClient = new Client({
2121
+ database: this.psqlConnectionPool.poolConfig.database,
2122
+ user: this.psqlConnectionPool.poolConfig.user,
2123
+ password: this.psqlConnectionPool.poolConfig.password,
2124
+ host: this.psqlConnectionPool.poolConfig.host,
2125
+ port: this.psqlConnectionPool.poolConfig.port
2126
+ });
2127
+ const scratchClient = new Client({
2128
+ database: this.psqlConnectionPool.poolConfig.database + "_scratch",
2129
+ user: this.psqlConnectionPool.poolConfig.user,
2130
+ password: this.psqlConnectionPool.poolConfig.password,
2131
+ host: this.psqlConnectionPool.poolConfig.host,
2132
+ port: this.psqlConnectionPool.poolConfig.port
2133
+ });
2134
+ const promises = [originalClient.connect(), scratchClient.connect()];
2135
+ await Promise.all(promises);
2136
+ const infoPromises = [(0, import_pg_info.default)({ client: originalClient }), (0, import_pg_info.default)({ client: scratchClient })];
2137
+ const [info1, info2] = await Promise.all(infoPromises);
2138
+ const diff = (0, import_pg_diff_sync.default)(info1, info2);
2139
+ const endPromises = [originalClient.end(), scratchClient.end()];
2140
+ await Promise.all(endPromises);
2141
+ return diff.join("\n");
2142
+ }
2143
+ createNestedSelect(req, schema, item, routeData, userRole, sqlParams) {
2144
+ if (!item.subquery) return "";
2145
+ if (!import_core_utils5.ObjectUtils.isArrayWithData(
2146
+ item.subquery.properties.filter((nestedItem) => {
2147
+ return this.doesRoleHavePermissionToColumn(req.requesterDetails.role, schema, nestedItem, [
2148
+ ...routeData.joins,
2149
+ ...item.subquery.joins
2150
+ ]);
2151
+ })
2152
+ )) {
2153
+ return "'[]'";
2154
+ }
2155
+ return `COALESCE((SELECT JSON_AGG(JSON_BUILD_OBJECT(
2156
+ ${item.subquery.properties.map((nestedItem) => {
2157
+ if (!this.doesRoleHavePermissionToColumn(req.requesterDetails.role, schema, nestedItem, [
2158
+ ...routeData.joins,
2159
+ ...item.subquery.joins
2160
+ ])) {
2161
+ return;
2162
+ }
2163
+ if (nestedItem.subquery) {
2164
+ return `'${nestedItem.name}', ${this.createNestedSelect(
2165
+ // recursion
2166
+ req,
2167
+ schema,
2168
+ nestedItem,
2169
+ routeData,
2170
+ userRole,
2171
+ sqlParams
2172
+ )}`;
2173
+ }
2174
+ return `'${nestedItem.name}', ${escapeColumnName(nestedItem.selector)}`;
2175
+ }).filter(Boolean).join(", ")}
2176
+ ))
2177
+ FROM
2178
+ "${item.subquery.table}"
2179
+ ${this.generateJoinStatements(req, item.subquery.joins, item.subquery.table, routeData, schema, userRole, sqlParams)}
2180
+ ${this.generateWhereClause(req, item.subquery.where, routeData, sqlParams)}
2181
+ ), '[]')`;
2182
+ }
2183
+ async executeCreateRequest(req, routeData, schema) {
2184
+ const sqlParams = [];
2185
+ const parameterObj = {};
2186
+ (routeData.assignments || []).forEach((assignment) => {
2187
+ parameterObj[assignment.name] = this.replaceParamKeywords(assignment.value, routeData, req, sqlParams);
2188
+ });
2189
+ const query = insertObjectQuery(routeData.table, __spreadValues(__spreadValues({}, req.data), parameterObj));
2190
+ const createdItem = await this.psqlConnectionPool.queryOne(
2191
+ query,
2192
+ sqlParams,
2193
+ req.requesterDetails
2194
+ );
2195
+ const insertId = createdItem.id;
2196
+ const whereId = {
2197
+ tableName: routeData.table,
2198
+ value: insertId,
2199
+ columnName: "id",
2200
+ operator: "="
2201
+ };
2202
+ const whereData = [whereId];
2203
+ req.data = { id: insertId };
2204
+ return this.executeGetRequest(req, __spreadProps(__spreadValues({}, routeData), { where: whereData }), schema);
2205
+ }
2206
+ async executeGetRequest(req, routeData, schema) {
2207
+ const DEFAULT_PAGED_PAGE_NUMBER = 0;
2208
+ const DEFAULT_PAGED_PER_PAGE_NUMBER = 25;
2209
+ const sqlParams = [];
2210
+ const userRole = req.requesterDetails.role;
2211
+ let sqlStatement = "";
2212
+ const selectColumns = [];
2213
+ routeData.response.forEach((item) => {
2214
+ if (item.subquery || this.doesRoleHavePermissionToColumn(userRole, schema, item, routeData.joins))
2215
+ selectColumns.push(item);
2216
+ });
2217
+ if (!selectColumns.length) throw new RsError("UNAUTHORIZED", `You do not have permission to access this data.`);
2218
+ let selectStatement = "SELECT \n";
2219
+ selectStatement += ` ${selectColumns.map((item) => {
2220
+ if (item.subquery) {
2221
+ return `${this.createNestedSelect(req, schema, item, routeData, userRole, sqlParams)} AS ${escapeColumnName(
2222
+ item.name
2223
+ )}`;
2224
+ }
2225
+ return `${escapeColumnName(item.selector)} AS ${escapeColumnName(item.name)}`;
2226
+ }).join(",\n ")}
2227
+ `;
2228
+ sqlStatement += `FROM "${routeData.table}"
2229
+ `;
2230
+ sqlStatement += this.generateJoinStatements(
2231
+ req,
2232
+ routeData.joins,
2233
+ routeData.table,
2234
+ routeData,
2235
+ schema,
2236
+ userRole,
2237
+ sqlParams
2238
+ );
2239
+ sqlStatement += this.generateWhereClause(req, routeData.where, routeData, sqlParams);
2240
+ let groupByOrderByStatement = this.generateGroupBy(routeData);
2241
+ groupByOrderByStatement += this.generateOrderBy(req, routeData);
2242
+ if (routeData.type === "ONE") {
2243
+ return this.psqlConnectionPool.queryOne(
2244
+ `${selectStatement}${sqlStatement}${groupByOrderByStatement};`,
2245
+ sqlParams,
2246
+ req.requesterDetails
2247
+ );
2248
+ } else if (routeData.type === "ARRAY") {
2249
+ return this.psqlConnectionPool.runQuery(
2250
+ `${selectStatement}${sqlStatement}${groupByOrderByStatement};`,
2251
+ sqlParams,
2252
+ req.requesterDetails
2253
+ );
2254
+ } else if (routeData.type === "PAGED") {
2255
+ const data = req.data;
2256
+ const pagePromise = this.psqlConnectionPool.runQuery(
2257
+ `${selectStatement}${sqlStatement}${groupByOrderByStatement}` + SQL`LIMIT ${data.perPage || DEFAULT_PAGED_PER_PAGE_NUMBER} OFFSET ${(data.page - 1) * data.perPage || DEFAULT_PAGED_PAGE_NUMBER};`,
2258
+ sqlParams,
2259
+ req.requesterDetails
2260
+ );
2261
+ const totalQuery = `SELECT COUNT(${routeData.groupBy ? `DISTINCT ${routeData.groupBy.tableName}.${routeData.groupBy.columnName}` : "*"}) AS total
2262
+ ${sqlStatement};`;
2263
+ const totalPromise = this.psqlConnectionPool.runQuery(
2264
+ totalQuery,
2265
+ sqlParams,
2266
+ req.requesterDetails
2267
+ );
2268
+ const [pageResults, totalResponse] = await Promise.all([pagePromise, totalPromise]);
2269
+ let total = 0;
2270
+ if (import_core_utils5.ObjectUtils.isArrayWithData(totalResponse)) {
2271
+ total = totalResponse[0].total;
2272
+ }
2273
+ return { data: pageResults, total };
2274
+ } else {
2275
+ throw new RsError("UNKNOWN_ERROR", "Unknown route type.");
2276
+ }
2277
+ }
2278
+ async executeUpdateRequest(req, routeData, schema) {
2279
+ const sqlParams = [];
2280
+ const _a2 = req.body, { id } = _a2, bodyNoId = __objRest(_a2, ["id"]);
2281
+ const table = schema.database.find((item) => {
2282
+ return item.name === routeData.table;
2283
+ });
2284
+ if (!table) throw new RsError("UNKNOWN_ERROR", "Unknown table.");
2285
+ if (table.columns.find((column) => column.name === "modifiedOn")) {
2286
+ bodyNoId.modifiedOn = (/* @__PURE__ */ new Date()).toISOString();
2287
+ }
2288
+ for (const assignment of routeData.assignments) {
2289
+ const column = table.columns.find((column2) => column2.name === assignment.name);
2290
+ if (!column) continue;
2291
+ const assignmentWithPrefix = escapeColumnName(`${routeData.table}.${assignment.name}`);
2292
+ if (SqlUtils.convertDatabaseTypeToTypescript(column.type) === "number")
2293
+ bodyNoId[assignmentWithPrefix] = Number(assignment.value);
2294
+ else bodyNoId[assignmentWithPrefix] = assignment.value;
2295
+ }
2296
+ const whereClause = this.generateWhereClause(req, routeData.where, routeData, sqlParams);
2297
+ const query = updateObjectQuery(routeData.table, bodyNoId, whereClause);
2298
+ await this.psqlConnectionPool.queryOne(query, [...sqlParams], req.requesterDetails);
2299
+ return this.executeGetRequest(req, routeData, schema);
2300
+ }
2301
+ async executeDeleteRequest(req, routeData, schema) {
2302
+ const sqlParams = [];
2303
+ const joinStatement = this.generateJoinStatements(
2304
+ req,
2305
+ routeData.joins,
2306
+ routeData.table,
2307
+ routeData,
2308
+ schema,
2309
+ req.requesterDetails.role,
2310
+ sqlParams
2311
+ );
2312
+ const whereClause = this.generateWhereClause(req, routeData.where, routeData, sqlParams);
2313
+ if (whereClause.replace(/\s/g, "") === "") {
2314
+ throw new RsError("DELETE_FORBIDDEN", "Deletes need a where clause");
2315
+ }
2316
+ const deleteStatement = `
2317
+ DELETE FROM "${routeData.table}" ${joinStatement} ${whereClause}`;
2318
+ await this.psqlConnectionPool.runQuery(deleteStatement, sqlParams, req.requesterDetails);
2319
+ return true;
2320
+ }
2321
+ generateJoinStatements(req, joins, baseTable, routeData, schema, userRole, sqlParams) {
2322
+ let joinStatements = "";
2323
+ joins.forEach((item) => {
2324
+ if (!this.doesRoleHavePermissionToTable(userRole, schema, item.table))
2325
+ throw new RsError("UNAUTHORIZED", "You do not have permission to access this table");
2326
+ if (item.custom) {
2327
+ const customReplaced = this.replaceParamKeywords(item.custom, routeData, req, sqlParams);
2328
+ joinStatements += ` ${item.type} JOIN ${escapeColumnName(item.table)} ON ${customReplaced}
2329
+ `;
2330
+ } else {
2331
+ joinStatements += ` ${item.type} JOIN ${escapeColumnName(item.table)}${item.alias ? `AS "${item.alias}"` : ""} ON "${baseTable}"."${item.localColumnName}" = ${escapeColumnName(item.alias ? item.alias : item.table)}.${escapeColumnName(
2332
+ item.foreignColumnName
2333
+ )}
2334
+ `;
2335
+ }
2336
+ });
2337
+ return joinStatements;
2338
+ }
2339
+ generateGroupBy(routeData) {
2340
+ let groupBy = "";
2341
+ if (routeData.groupBy) {
2342
+ groupBy = `GROUP BY ${escapeColumnName(routeData.groupBy.tableName)}.${escapeColumnName(routeData.groupBy.columnName)}
2343
+ `;
2344
+ }
2345
+ return groupBy;
2346
+ }
2347
+ generateOrderBy(req, routeData) {
2348
+ let orderBy = "";
2349
+ const orderOptions = {
2350
+ ASC: "ASC",
2351
+ DESC: "DESC"
2352
+ };
2353
+ const data = req.data;
2354
+ if (routeData.type === "PAGED" && "sortBy" in data) {
2355
+ const sortOrder = orderOptions[data.sortOrder] || "ASC";
2356
+ orderBy = `ORDER BY ${escapeColumnName(data.sortBy)} ${sortOrder}
2357
+ `;
2358
+ } else if (routeData.orderBy) {
2359
+ const sortOrder = orderOptions[routeData.orderBy.order] || "ASC";
2360
+ orderBy = `ORDER BY ${escapeColumnName(routeData.orderBy.tableName)}.${escapeColumnName(routeData.orderBy.columnName)} ${sortOrder}
2361
+ `;
2362
+ }
2363
+ return orderBy;
2364
+ }
2365
+ generateWhereClause(req, where, routeData, sqlParams) {
2366
+ let whereClause = "";
2367
+ where.forEach((item, index) => {
2368
+ if (index === 0) whereClause = "WHERE ";
2369
+ if (item.custom) {
2370
+ whereClause += this.replaceParamKeywords(item.custom, routeData, req, sqlParams);
2371
+ return;
2372
+ }
2373
+ if (item.operator === void 0 || item.value === void 0 || item.columnName === void 0 || item.tableName === void 0)
2374
+ throw new RsError(
2375
+ "SCHEMA_ERROR",
2376
+ `Invalid where clause in route ${routeData.name}, missing required fields if not custom`
2377
+ );
2378
+ let operator = item.operator;
2379
+ if (operator === "LIKE") {
2380
+ item.value = `'%${item.value}%'`;
2381
+ } else if (operator === "STARTS WITH") {
2382
+ operator = "LIKE";
2383
+ item.value = `'${item.value}%'`;
2384
+ } else if (operator === "ENDS WITH") {
2385
+ operator = "LIKE";
2386
+ item.value = `'%${item.value}'`;
2387
+ }
2388
+ const replacedValue = this.replaceParamKeywords(item.value, routeData, req, sqlParams);
2389
+ whereClause += ` ${item.conjunction || ""} "${item.tableName}"."${item.columnName}" ${operator.replace("LIKE", "ILIKE")} ${["IN", "NOT IN"].includes(operator) ? `(${replacedValue})` : replacedValue}
2390
+ `;
2391
+ });
2392
+ const data = req.data;
2393
+ if (routeData.type === "PAGED" && !!(data == null ? void 0 : data.filter)) {
2394
+ let statement = data.filter.replace(/\$[a-zA-Z][a-zA-Z0-9_]+/g, (value) => {
2395
+ var _a2;
2396
+ const requestParam = routeData.request.find((item) => {
2397
+ return item.name === value.replace("$", "");
2398
+ });
2399
+ if (!requestParam)
2400
+ throw new RsError("SCHEMA_ERROR", `Invalid route keyword in route ${routeData.name}`);
2401
+ return ((_a2 = data[requestParam.name]) == null ? void 0 : _a2.toString()) || "";
2402
+ });
2403
+ statement = statement.replace(/#[a-zA-Z][a-zA-Z0-9_]+/g, (value) => {
2404
+ var _a2;
2405
+ const requestParam = routeData.request.find((item) => {
2406
+ return item.name === value.replace("#", "");
2407
+ });
2408
+ if (!requestParam)
2409
+ throw new RsError("SCHEMA_ERROR", `Invalid route keyword in route ${routeData.name}`);
2410
+ return ((_a2 = data[requestParam.name]) == null ? void 0 : _a2.toString()) || "";
2411
+ });
2412
+ statement = filterPsqlParser_default.parse(statement);
2413
+ if (whereClause.startsWith("WHERE")) {
2414
+ whereClause += ` AND (${statement})
2415
+ `;
2416
+ } else {
2417
+ whereClause += `WHERE ${statement}
2418
+ `;
2419
+ }
2420
+ }
2421
+ return whereClause;
2422
+ }
2423
+ createUpdateTrigger(tableName) {
2424
+ return `
2425
+ CREATE OR REPLACE FUNCTION notify_${tableName}_update()
2426
+ RETURNS TRIGGER AS $$
2427
+ BEGIN
2428
+ PERFORM pg_notify('update', JSON_BUILD_OBJECT('table', '${tableName}', 'query', current_query(), 'record', NEW, 'previousRecord', OLD)::text);
2429
+ RETURN NEW;
2430
+ END;
2431
+ $$ LANGUAGE plpgsql;
2432
+
2433
+ CREATE OR REPLACE TRIGGER ${tableName}_update
2434
+ AFTER UPDATE ON "${tableName}"
2435
+ FOR EACH ROW
2436
+ EXECUTE FUNCTION notify_${tableName}_update();
2437
+ `;
2438
+ }
2439
+ createDeleteTrigger(tableName) {
2440
+ return `
2441
+ CREATE OR REPLACE FUNCTION notify_${tableName}_delete()
2442
+ RETURNS TRIGGER AS $$
2443
+ BEGIN
2444
+ PERFORM pg_notify('delete', JSON_BUILD_OBJECT('table', '${tableName}', 'query', current_query(), 'record', NEW, 'previousRecord', OLD)::text);
2445
+ RETURN NEW;
2446
+ END;
2447
+ $$ LANGUAGE plpgsql;
2448
+
2449
+ CREATE OR REPLACE TRIGGER "${tableName}_delete"
2450
+ AFTER DELETE ON "${tableName}"
2451
+ FOR EACH ROW
2452
+ EXECUTE FUNCTION notify_${tableName}_delete();
2453
+ `;
2454
+ }
2455
+ createInsertTriggers(tableName) {
2456
+ return `
2457
+ CREATE OR REPLACE FUNCTION notify_${tableName}_insert()
2458
+ RETURNS TRIGGER AS $$
2459
+ BEGIN
2460
+ PERFORM pg_notify('insert', JSON_BUILD_OBJECT('table', '${tableName}', 'query', current_query(), 'record', NEW, 'previousRecord', OLD)::text);
2461
+ RETURN NEW;
2462
+ END;
2463
+ $$ LANGUAGE plpgsql;
2464
+
2465
+ CREATE TRIGGER "${tableName}_insert"
2466
+ AFTER INSERT ON "${tableName}"
2467
+ FOR EACH ROW
2468
+ EXECUTE FUNCTION notify_${tableName}_insert();
2469
+ `;
2470
+ }
2471
+ schemaToPsqlType(column) {
2472
+ if (column.hasAutoIncrement) return "BIGSERIAL";
2473
+ if (column.type === "ENUM") return `TEXT`;
2474
+ if (column.type === "DATETIME") return "TIMESTAMPTZ";
2475
+ if (column.type === "MEDIUMINT") return "INT";
2476
+ return column.type;
2477
+ }
2478
+ };
2479
+ __decorateClass([
2480
+ boundMethod
2481
+ ], PsqlEngine.prototype, "createUpdateTrigger", 1);
2482
+ __decorateClass([
2483
+ boundMethod
2484
+ ], PsqlEngine.prototype, "createDeleteTrigger", 1);
2485
+ __decorateClass([
2486
+ boundMethod
2487
+ ], PsqlEngine.prototype, "createInsertTriggers", 1);
2488
+
2489
+ // src/restura/utils/TempCache.ts
2490
+ var import_fs3 = __toESM(require("fs"));
2491
+ var import_path4 = __toESM(require("path"));
2492
+ var import_core_utils6 = require("@redskytech/core-utils");
2493
+ var import_internal3 = require("@restura/internal");
2494
+ var import_bluebird3 = __toESM(require("bluebird"));
2495
+ var os2 = __toESM(require("os"));
2496
+ var TempCache = class {
2497
+ constructor(location) {
2498
+ this.maxDurationDays = 7;
2499
+ this.location = location || os2.tmpdir();
2500
+ import_internal3.FileUtils.ensureDir(this.location).catch((e) => {
2501
+ throw e;
2502
+ });
2503
+ }
2504
+ async cleanup() {
2505
+ const fileList = await import_fs3.default.promises.readdir(this.location);
2506
+ await import_bluebird3.default.map(
2507
+ fileList,
2508
+ async (file) => {
2509
+ const fullFilePath = import_path4.default.join(this.location, file);
2510
+ const fileStats = await import_fs3.default.promises.stat(fullFilePath);
2511
+ if (import_core_utils6.DateUtils.daysBetweenStartAndEndDates(new Date(fileStats.mtimeMs), /* @__PURE__ */ new Date()) > this.maxDurationDays) {
2512
+ logger.info(`Deleting old temp file: ${file}`);
2513
+ await import_fs3.default.promises.unlink(fullFilePath);
2514
+ }
2515
+ },
2516
+ { concurrency: 10 }
2517
+ );
2518
+ }
2519
+ };
2520
+
2521
+ // src/restura/restura.ts
2522
+ var ResturaEngine = class {
2523
+ constructor() {
2524
+ this.publicEndpoints = {
2525
+ GET: [],
2526
+ POST: [],
2527
+ PUT: [],
2528
+ PATCH: [],
2529
+ DELETE: []
2530
+ };
2531
+ }
2532
+ /**
2533
+ * Initializes the Restura engine with the provided Express application.
2534
+ *
2535
+ * @param app - The Express application instance to initialize with Restura.
2536
+ * @returns A promise that resolves when the initialization is complete.
2537
+ */
2538
+ async init(app, authenticationHandler, psqlConnectionPool) {
2539
+ this.resturaConfig = import_internal4.config.validate("restura", resturaConfigSchema);
2540
+ this.multerCommonUpload = getMulterUpload(this.resturaConfig.fileTempCachePath);
2541
+ new TempCache(this.resturaConfig.fileTempCachePath);
2542
+ this.psqlConnectionPool = psqlConnectionPool;
2543
+ this.psqlEngine = new PsqlEngine(this.psqlConnectionPool, true);
2544
+ await customApiFactory_default.loadApiFiles(this.resturaConfig.customApiFolderPath);
2545
+ this.authenticationHandler = authenticationHandler;
2546
+ app.use((0, import_compression.default)());
2547
+ app.use(import_body_parser.default.json({ limit: "32mb" }));
2548
+ app.use(import_body_parser.default.urlencoded({ limit: "32mb", extended: false }));
2549
+ app.use((0, import_cookie_parser.default)());
2550
+ app.disable("x-powered-by");
2551
+ app.use("/", addApiResponseFunctions);
2552
+ app.use("/api/", authenticateUser(this.authenticationHandler));
2553
+ app.use("/restura", this.resturaAuthentication);
2554
+ app.put(
2555
+ "/restura/v1/schema",
2556
+ schemaValidation,
2557
+ this.updateSchema
2558
+ );
2559
+ app.post(
2560
+ "/restura/v1/schema/preview",
2561
+ schemaValidation,
2562
+ this.previewCreateSchema
2563
+ );
2564
+ app.get("/restura/v1/schema", this.getSchema);
2565
+ app.get("/restura/v1/schema/types", this.getSchemaAndTypes);
2566
+ this.expressApp = app;
2567
+ await this.reloadEndpoints();
2568
+ await this.validateGeneratedTypesFolder();
2569
+ logger.info("Restura Engine Initialized");
2570
+ }
2571
+ /**
2572
+ * Determines if a given endpoint is public based on the HTTP method and full URL. This
2573
+ * is determined on whether the endpoint in the schema has no roles assigned to it.
2574
+ *
2575
+ * @param method - The HTTP method (e.g., 'GET', 'POST', 'PUT', 'PATCH', 'DELETE').
2576
+ * @param fullUrl - The full URL of the endpoint.
2577
+ * @returns A boolean indicating whether the endpoint is public.
2578
+ */
2579
+ isEndpointPublic(method, fullUrl) {
2580
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) return false;
2581
+ return this.publicEndpoints[method].includes(fullUrl);
2582
+ }
2583
+ /**
2584
+ * Checks if an endpoint exists for a given HTTP method and full URL.
2585
+ *
2586
+ * @param method - The HTTP method to check (e.g., 'GET', 'POST', 'PUT', 'PATCH', 'DELETE').
2587
+ * @param fullUrl - The full URL of the endpoint to check.
2588
+ * @returns `true` if the endpoint exists, otherwise `false`.
2589
+ */
2590
+ doesEndpointExist(method, fullUrl) {
2591
+ return this.schema.endpoints.some((endpoint) => {
2592
+ if (!fullUrl.startsWith(endpoint.baseUrl)) return false;
2593
+ const pathWithoutBaseUrl = fullUrl.replace(endpoint.baseUrl, "");
2594
+ return endpoint.routes.some((route) => {
2595
+ return route.method === method && route.path === pathWithoutBaseUrl;
2596
+ });
2597
+ });
2598
+ }
2599
+ /**
2600
+ * Generates an API from the provided schema and writes it to the specified output file.
2601
+ *
2602
+ * @param outputFile - The path to the file where the generated API will be written.
2603
+ * @param providedSchema - The schema from which the API will be generated.
2604
+ * @returns A promise that resolves when the API has been successfully generated and written to the output file.
2605
+ */
2606
+ async generateApiFromSchema(outputFile, providedSchema) {
2607
+ import_fs4.default.writeFileSync(outputFile, await apiGenerator(providedSchema));
2608
+ }
2609
+ /**
2610
+ * Generates a model from the provided schema and writes it to the specified output file.
2611
+ *
2612
+ * @param outputFile - The path to the file where the generated model will be written.
2613
+ * @param providedSchema - The schema from which the model will be generated.
2614
+ * @returns A promise that resolves when the model has been successfully written to the output file.
2615
+ */
2616
+ async generateModelFromSchema(outputFile, providedSchema) {
2617
+ import_fs4.default.writeFileSync(outputFile, await modelGenerator(providedSchema));
2618
+ }
2619
+ /**
2620
+ * Generates the ambient module declaration for Restura global types and writes it to the specified output file.
2621
+ * These types are used sometimes in the CustomTypes
2622
+ * @param outputFile
2623
+ */
2624
+ generateResturaGlobalTypes(outputFile) {
2625
+ import_fs4.default.writeFileSync(outputFile, resturaGlobalTypesGenerator());
2626
+ }
2627
+ /**
2628
+ * Retrieves the latest file system schema for Restura.
2629
+ *
2630
+ * @returns {Promise<ResturaSchema>} A promise that resolves to the latest Restura schema.
2631
+ * @throws {Error} If the schema file is missing or the schema is not valid.
2632
+ */
2633
+ async getLatestFileSystemSchema() {
2634
+ if (!import_fs4.default.existsSync(this.resturaConfig.schemaFilePath)) {
2635
+ logger.error(`Missing restura schema file, expected path: ${this.resturaConfig.schemaFilePath}`);
2636
+ throw new Error("Missing restura schema file");
2637
+ }
2638
+ const schemaFileData = import_fs4.default.readFileSync(this.resturaConfig.schemaFilePath, { encoding: "utf8" });
2639
+ const schema = import_core_utils7.ObjectUtils.safeParse(schemaFileData);
2640
+ const isValid = await isSchemaValid(schema);
2641
+ if (!isValid) {
2642
+ logger.error("Schema is not valid");
2643
+ throw new Error("Schema is not valid");
2644
+ }
2645
+ return schema;
2646
+ }
2647
+ async reloadEndpoints() {
2648
+ this.schema = await this.getLatestFileSystemSchema();
2649
+ this.customTypeValidation = customTypeValidationGenerator(this.schema);
2650
+ this.resturaRouter = express.Router();
2651
+ this.resetPublicEndpoints();
2652
+ let routeCount = 0;
2653
+ for (const endpoint of this.schema.endpoints) {
2654
+ const baseUrl = endpoint.baseUrl.endsWith("/") ? endpoint.baseUrl.slice(0, -1) : endpoint.baseUrl;
2655
+ this.expressApp.use(baseUrl, (req, res, next) => {
2656
+ this.resturaRouter(req, res, next);
2657
+ });
2658
+ for (const route of endpoint.routes) {
2659
+ route.path = route.path.startsWith("/") ? route.path : `/${route.path}`;
2660
+ route.path = route.path.endsWith("/") ? route.path.slice(0, -1) : route.path;
2661
+ const fullUrl = `${baseUrl}${route.path}`;
2662
+ if (route.roles.length === 0) this.publicEndpoints[route.method].push(fullUrl);
2663
+ this.resturaRouter[route.method.toLowerCase()](
2664
+ route.path,
2665
+ // <-- Notice we only use path here since the baseUrl is already added to the router.
2666
+ this.executeRouteLogic
2667
+ );
2668
+ routeCount++;
2669
+ }
2670
+ }
2671
+ this.responseValidator = new ResponseValidator(this.schema);
2672
+ logger.info(`Restura loaded (${routeCount}) endpoint${routeCount > 1 ? "s" : ""}`);
2673
+ }
2674
+ async validateGeneratedTypesFolder() {
2675
+ if (!import_fs4.default.existsSync(this.resturaConfig.generatedTypesPath)) {
2676
+ import_fs4.default.mkdirSync(this.resturaConfig.generatedTypesPath, { recursive: true });
2677
+ }
2678
+ this.updateTypes();
2679
+ }
2680
+ resturaAuthentication(req, res, next) {
2681
+ if (req.headers["x-auth-token"] !== this.resturaConfig.authToken) res.status(401).send("Unauthorized");
2682
+ else next();
2683
+ }
2684
+ async previewCreateSchema(req, res) {
2685
+ try {
2686
+ const schemaDiff = await compareSchema_default.diffSchema(req.data, this.schema, this.psqlEngine);
2687
+ res.send({ data: schemaDiff });
2688
+ } catch (err) {
2689
+ res.status(400).send(err);
2690
+ }
2691
+ }
2692
+ async updateSchema(req, res) {
2693
+ try {
2694
+ this.schema = sortObjectKeysAlphabetically(req.data);
2695
+ await this.storeFileSystemSchema();
2696
+ await this.reloadEndpoints();
2697
+ await this.updateTypes();
2698
+ res.send({ data: "success" });
2699
+ } catch (err) {
2700
+ if (err instanceof Error) res.status(400).send(err.message);
2701
+ else res.status(400).send("Unknown error");
2702
+ }
2703
+ }
2704
+ async updateTypes() {
2705
+ await this.generateApiFromSchema(import_path5.default.join(this.resturaConfig.generatedTypesPath, "api.d.ts"), this.schema);
2706
+ await this.generateModelFromSchema(
2707
+ import_path5.default.join(this.resturaConfig.generatedTypesPath, "models.d.ts"),
2708
+ this.schema
2709
+ );
2710
+ this.generateResturaGlobalTypes(import_path5.default.join(this.resturaConfig.generatedTypesPath, "restura.d.ts"));
2711
+ }
2712
+ async getSchema(req, res) {
2713
+ res.send({ data: this.schema });
2714
+ }
2715
+ async getSchemaAndTypes(req, res) {
2716
+ try {
2717
+ const schema = await this.getLatestFileSystemSchema();
2718
+ const apiText = await apiGenerator(schema);
2719
+ const modelsText = await modelGenerator(schema);
2720
+ res.send({ schema, api: apiText, models: modelsText });
2721
+ } catch (err) {
2722
+ res.status(400).send({ error: err });
2723
+ }
2724
+ }
2725
+ async getMulterFilesIfAny(req, res, routeData) {
2726
+ var _a2;
2727
+ if (!((_a2 = req.header("content-type")) == null ? void 0 : _a2.includes("multipart/form-data"))) return;
2728
+ if (!this.isCustomRoute(routeData)) return;
2729
+ if (!routeData.fileUploadType) {
2730
+ throw new RsError("BAD_REQUEST", "File upload type not defined for route");
2731
+ }
2732
+ const multerFileUploadFunction = routeData.fileUploadType === "MULTIPLE" ? this.multerCommonUpload.array("files") : this.multerCommonUpload.single("file");
2733
+ return new Promise((resolve2, reject) => {
2734
+ multerFileUploadFunction(req, res, (err) => {
2735
+ if (err) {
2736
+ logger.warn("Multer error: " + err);
2737
+ reject(err);
2738
+ }
2739
+ if (req.body["data"]) req.body = JSON.parse(req.body["data"]);
2740
+ resolve2();
2741
+ });
2742
+ });
2743
+ }
2744
+ async executeRouteLogic(req, res, next) {
2745
+ try {
2746
+ const routeData = this.getRouteData(req.method, req.baseUrl, req.path);
2747
+ this.validateAuthorization(req, routeData);
2748
+ await this.getMulterFilesIfAny(req, res, routeData);
2749
+ requestValidator(req, routeData, this.customTypeValidation);
2750
+ if (this.isCustomRoute(routeData)) {
2751
+ await this.runCustomRouteLogic(req, res, routeData);
2752
+ return;
2753
+ }
2754
+ const data = await this.psqlEngine.runQueryForRoute(
2755
+ req,
2756
+ routeData,
2757
+ this.schema
2758
+ );
2759
+ this.responseValidator.validateResponseParams(data, req.baseUrl, routeData);
2760
+ if (routeData.type === "PAGED") res.sendNoWrap(data);
2761
+ else res.sendData(data);
2762
+ } catch (e) {
2763
+ next(e);
2764
+ }
2765
+ }
2766
+ isCustomRoute(route) {
2767
+ return route.type === "CUSTOM_ONE" || route.type === "CUSTOM_ARRAY" || route.type === "CUSTOM_PAGED";
2768
+ }
2769
+ async runCustomRouteLogic(req, res, routeData) {
2770
+ const version = req.baseUrl.split("/")[2];
2771
+ let domain = routeData.path.split("/")[1];
2772
+ domain = domain.split("-").reduce((acc, value, index) => {
2773
+ if (index === 0) acc = value;
2774
+ else acc += import_core_utils7.StringUtils.capitalizeFirst(value);
2775
+ return acc;
2776
+ }, "");
2777
+ const customApiName = `${import_core_utils7.StringUtils.capitalizeFirst(domain)}Api${import_core_utils7.StringUtils.capitalizeFirst(version)}`;
2778
+ const customApi = customApiFactory_default.getCustomApi(customApiName);
2779
+ if (!customApi) throw new RsError("NOT_FOUND", `API domain ${domain}-${version} not found`);
2780
+ const functionName = `${routeData.method.toLowerCase()}${routeData.path.replace(new RegExp("-", "g"), "/").split("/").reduce((acc, cur) => {
2781
+ if (cur === "") return acc;
2782
+ return acc + import_core_utils7.StringUtils.capitalizeFirst(cur);
2783
+ }, "")}`;
2784
+ const customFunction = customApi[functionName];
2785
+ if (!customFunction)
2786
+ throw new RsError("NOT_FOUND", `API path ${routeData.path} not implemented ${functionName}`);
2787
+ await customFunction(req, res, routeData);
2788
+ }
2789
+ async storeFileSystemSchema() {
2790
+ const schemaPrettyStr = await prettier3.format(JSON.stringify(this.schema), __spreadValues({
2791
+ parser: "json"
2792
+ }, {
2793
+ trailingComma: "none",
2794
+ tabWidth: 4,
2795
+ useTabs: true,
2796
+ endOfLine: "lf",
2797
+ printWidth: 120,
2798
+ singleQuote: true
2799
+ }));
2800
+ import_fs4.default.writeFileSync(this.resturaConfig.schemaFilePath, schemaPrettyStr);
2801
+ }
2802
+ resetPublicEndpoints() {
2803
+ this.publicEndpoints = {
2804
+ GET: [],
2805
+ POST: [],
2806
+ PUT: [],
2807
+ PATCH: [],
2808
+ DELETE: []
2809
+ };
2810
+ }
2811
+ validateAuthorization(req, routeData) {
2812
+ const role = req.requesterDetails.role;
2813
+ if (routeData.roles.length === 0 || !role) return;
2814
+ if (!routeData.roles.includes(role))
2815
+ throw new RsError("UNAUTHORIZED", "Not authorized to access this endpoint");
2816
+ }
2817
+ getRouteData(method, baseUrl, path5) {
2818
+ const endpoint = this.schema.endpoints.find((item) => {
2819
+ return item.baseUrl === baseUrl;
2820
+ });
2821
+ if (!endpoint) throw new RsError("NOT_FOUND", "Route not found");
2822
+ const route = endpoint.routes.find((item) => {
2823
+ return item.method === method && item.path === path5;
2824
+ });
2825
+ if (!route) throw new RsError("NOT_FOUND", "Route not found");
2826
+ return route;
2827
+ }
2828
+ };
2829
+ __decorateClass([
2830
+ boundMethod
2831
+ ], ResturaEngine.prototype, "resturaAuthentication", 1);
2832
+ __decorateClass([
2833
+ boundMethod
2834
+ ], ResturaEngine.prototype, "previewCreateSchema", 1);
2835
+ __decorateClass([
2836
+ boundMethod
2837
+ ], ResturaEngine.prototype, "updateSchema", 1);
2838
+ __decorateClass([
2839
+ boundMethod
2840
+ ], ResturaEngine.prototype, "getSchema", 1);
2841
+ __decorateClass([
2842
+ boundMethod
2843
+ ], ResturaEngine.prototype, "getSchemaAndTypes", 1);
2844
+ __decorateClass([
2845
+ boundMethod
2846
+ ], ResturaEngine.prototype, "getMulterFilesIfAny", 1);
2847
+ __decorateClass([
2848
+ boundMethod
2849
+ ], ResturaEngine.prototype, "executeRouteLogic", 1);
2850
+ __decorateClass([
2851
+ boundMethod
2852
+ ], ResturaEngine.prototype, "isCustomRoute", 1);
2853
+ __decorateClass([
2854
+ boundMethod
2855
+ ], ResturaEngine.prototype, "runCustomRouteLogic", 1);
2856
+ var restura = new ResturaEngine();
2857
+
2858
+ // src/restura/sql/PsqlTransaction.ts
2859
+ var import_pg3 = __toESM(require("pg"));
2860
+ var { Client: Client2 } = import_pg3.default;
2861
+ var PsqlTransaction = class extends PsqlConnection {
2862
+ constructor(clientConfig) {
2863
+ super();
2864
+ this.clientConfig = clientConfig;
2865
+ this.client = new Client2(clientConfig);
2866
+ this.connectPromise = this.client.connect();
2867
+ this.beginTransactionPromise = this.beginTransaction();
2868
+ }
2869
+ async close() {
2870
+ if (this.client) {
2871
+ await this.client.end();
2872
+ }
2873
+ }
2874
+ async beginTransaction() {
2875
+ await this.connectPromise;
2876
+ return this.client.query("BEGIN");
2877
+ }
2878
+ async rollback() {
2879
+ return this.query("ROLLBACK");
2880
+ }
2881
+ async commit() {
2882
+ return this.query("COMMIT");
2883
+ }
2884
+ async release() {
2885
+ return this.client.end();
2886
+ }
2887
+ async query(query, values) {
2888
+ await this.connectPromise;
2889
+ await this.beginTransactionPromise;
2890
+ return this.client.query(query, values);
2891
+ }
9
2892
  };
2893
+ // Annotate the CommonJS export names for ESM import in node:
2894
+ 0 && (module.exports = {
2895
+ HtmlStatusCodes,
2896
+ PsqlConnection,
2897
+ PsqlEngine,
2898
+ PsqlPool,
2899
+ PsqlTransaction,
2900
+ RsError,
2901
+ SQL,
2902
+ escapeColumnName,
2903
+ eventManager,
2904
+ insertObjectQuery,
2905
+ isValueNumber,
2906
+ logger,
2907
+ questionMarksToOrderedParams,
2908
+ restura,
2909
+ updateObjectQuery
2910
+ });
10
2911
  //# sourceMappingURL=index.js.map