@restura/core 0.1.0-alpha.6 → 0.1.0-alpha.7

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.mjs CHANGED
@@ -1,5 +1,20 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __spreadValues = (a, b) => {
8
+ for (var prop in b || (b = {}))
9
+ if (__hasOwnProp.call(b, prop))
10
+ __defNormalProp(a, prop, b[prop]);
11
+ if (__getOwnPropSymbols)
12
+ for (var prop of __getOwnPropSymbols(b)) {
13
+ if (__propIsEnum.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ }
16
+ return a;
17
+ };
3
18
  var __decorateClass = (decorators, target, key, kind) => {
4
19
  var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
20
  for (var i = decorators.length - 1, decorator; i >= 0; i--)
@@ -9,6 +24,62 @@ var __decorateClass = (decorators, target, key, kind) => {
9
24
  return result;
10
25
  };
11
26
 
27
+ // src/logger/logger.ts
28
+ import { config } from "@restura/internal";
29
+ import winston from "winston";
30
+ import { format } from "logform";
31
+
32
+ // src/config.schema.ts
33
+ import { z } from "zod";
34
+ var loggerConfigSchema = z.object({
35
+ level: z.enum(["info", "warn", "error", "debug"]).default("info")
36
+ });
37
+ var resturaConfigSchema = z.object({
38
+ authToken: z.string().min(1, "Missing Restura Auth Token"),
39
+ sendErrorStackTrace: z.boolean().default(false),
40
+ schemaFilePath: z.string().default(process.cwd() + "/restura.schema.json"),
41
+ generatedTypesPath: z.string().default(process.cwd() + "/src/@types")
42
+ });
43
+
44
+ // src/logger/logger.ts
45
+ var loggerConfig = config.validate("logger", loggerConfigSchema);
46
+ var consoleFormat = format.combine(
47
+ format.timestamp({
48
+ format: "YYYY-MM-DD HH:mm:ss.sss"
49
+ }),
50
+ format.errors({ stack: true }),
51
+ format.padLevels(),
52
+ format.colorize({ all: true }),
53
+ format.printf((info) => {
54
+ return `[${info.timestamp}] ${info.level} ${info.message}`;
55
+ })
56
+ );
57
+ var logger = winston.createLogger({
58
+ level: loggerConfig.level,
59
+ format: format.combine(
60
+ format.timestamp({
61
+ format: "YYYY-MM-DD HH:mm:ss.sss"
62
+ }),
63
+ format.errors({ stack: true }),
64
+ format.json()
65
+ ),
66
+ //defaultMeta: { service: 'user-service' },
67
+ transports: [
68
+ //
69
+ // - Write to all logs with level `info` and below to `combined.log`
70
+ // - Write all logs error (and below) to `error.log`.
71
+ // - Write all logs to standard out.
72
+ //
73
+ // new winston.transports.File({ filename: 'error.log', level: 'error' }),
74
+ // new winston.transports.File({ filename: 'combined.log' }),
75
+ new winston.transports.Console({ format: consoleFormat })
76
+ ]
77
+ });
78
+
79
+ // src/restura/restura.ts
80
+ import { ObjectUtils as ObjectUtils3 } from "@redskytech/core-utils";
81
+ import { config as config2 } from "@restura/internal";
82
+
12
83
  // ../../node_modules/.pnpm/autobind-decorator@2.4.0/node_modules/autobind-decorator/lib/esm/index.js
13
84
  function _typeof(obj) {
14
85
  if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
@@ -55,21 +126,1166 @@ function boundMethod(target, key, descriptor) {
55
126
  };
56
127
  }
57
128
 
129
+ // src/restura/restura.ts
130
+ import bodyParser from "body-parser";
131
+ import compression from "compression";
132
+ import cookieParser from "cookie-parser";
133
+ import { createHash } from "crypto";
134
+ import * as express from "express";
135
+ import fs from "fs";
136
+ import path from "path";
137
+ import * as prettier3 from "prettier";
138
+
139
+ // src/restura/errors.ts
140
+ var RsError = class _RsError {
141
+ constructor(errCode, message) {
142
+ this.err = errCode;
143
+ this.msg = message || "";
144
+ this.status = _RsError.htmlStatus(errCode);
145
+ this.stack = new Error().stack || "";
146
+ }
147
+ static htmlStatus(code) {
148
+ return htmlStatusMap[code];
149
+ }
150
+ };
151
+ var htmlStatusMap = {
152
+ UNKNOWN_ERROR: 500 /* SERVER_ERROR */,
153
+ NOT_FOUND: 404 /* NOT_FOUND */,
154
+ EMAIL_TAKEN: 409 /* CONFLICT */,
155
+ FORBIDDEN: 403 /* FORBIDDEN */,
156
+ CONFLICT: 409 /* CONFLICT */,
157
+ UNAUTHORIZED: 401 /* UNAUTHORIZED */,
158
+ UPDATE_FORBIDDEN: 403 /* FORBIDDEN */,
159
+ CREATE_FORBIDDEN: 403 /* FORBIDDEN */,
160
+ DELETE_FORBIDDEN: 403 /* FORBIDDEN */,
161
+ DELETE_FAILURE: 500 /* SERVER_ERROR */,
162
+ BAD_REQUEST: 400 /* BAD_REQUEST */,
163
+ INVALID_TOKEN: 401 /* UNAUTHORIZED */,
164
+ INCORRECT_EMAIL_OR_PASSWORD: 401 /* UNAUTHORIZED */,
165
+ DUPLICATE_TOKEN: 409 /* CONFLICT */,
166
+ DUPLICATE_USERNAME: 409 /* CONFLICT */,
167
+ DUPLICATE_EMAIL: 409 /* CONFLICT */,
168
+ DUPLICATE: 409 /* CONFLICT */,
169
+ EMAIL_NOT_VERIFIED: 400 /* BAD_REQUEST */,
170
+ UPDATE_WITHOUT_ID: 400 /* BAD_REQUEST */,
171
+ CONNECTION_ERROR: 599 /* NETWORK_CONNECT_TIMEOUT */,
172
+ INVALID_PAYMENT: 403 /* FORBIDDEN */,
173
+ DECLINED_PAYMENT: 403 /* FORBIDDEN */,
174
+ INTEGRATION_ERROR: 500 /* SERVER_ERROR */,
175
+ CANNOT_RESERVE: 403 /* FORBIDDEN */,
176
+ REFUND_FAILURE: 403 /* FORBIDDEN */,
177
+ INVALID_INVOICE: 403 /* FORBIDDEN */,
178
+ INVALID_COUPON: 403 /* FORBIDDEN */,
179
+ SERVICE_UNAVAILABLE: 503 /* SERVICE_UNAVAILABLE */,
180
+ METHOD_UNALLOWED: 405 /* METHOD_NOT_ALLOWED */,
181
+ LOGIN_EXPIRED: 401 /* UNAUTHORIZED */,
182
+ THIRD_PARTY_ERROR: 400 /* BAD_REQUEST */,
183
+ ACCESS_DENIED: 403 /* FORBIDDEN */,
184
+ DATABASE_ERROR: 500 /* SERVER_ERROR */,
185
+ SCHEMA_ERROR: 500 /* SERVER_ERROR */
186
+ };
187
+
188
+ // src/restura/SqlUtils.ts
189
+ var SqlUtils = class _SqlUtils {
190
+ static convertDatabaseTypeToTypescript(type, value) {
191
+ type = type.toLocaleLowerCase();
192
+ if (type.startsWith("tinyint") || type.startsWith("boolean")) return "boolean";
193
+ if (type.indexOf("int") > -1 || type.startsWith("decimal") || type.startsWith("double") || type.startsWith("float"))
194
+ return "number";
195
+ if (type === "json") {
196
+ if (!value) return "object";
197
+ return value.split(",").map((val) => {
198
+ return val.replace(/['"]/g, "");
199
+ }).join(" | ");
200
+ }
201
+ if (type.startsWith("varchar") || type.indexOf("text") > -1 || type.startsWith("char") || type.indexOf("blob") > -1 || type.startsWith("binary"))
202
+ return "string";
203
+ if (type.startsWith("date") || type.startsWith("time")) return "string";
204
+ if (type.startsWith("enum")) return _SqlUtils.convertDatabaseEnumToStringUnion(value || type);
205
+ return "any";
206
+ }
207
+ static convertDatabaseEnumToStringUnion(type) {
208
+ return type.replace(/^enum\(|\)/g, "").split(",").map((value) => {
209
+ return `'${value.replace(/'/g, "")}'`;
210
+ }).join(" | ");
211
+ }
212
+ };
213
+
214
+ // src/restura/ResponseValidator.ts
215
+ var ResponseValidator = class _ResponseValidator {
216
+ constructor(schema) {
217
+ this.database = schema.database;
218
+ this.rootMap = {};
219
+ for (const endpoint of schema.endpoints) {
220
+ const endpointMap = {};
221
+ for (const route of endpoint.routes) {
222
+ if (_ResponseValidator.isCustomRoute(route)) {
223
+ endpointMap[`${route.method}:${route.path}`] = { validator: "any" };
224
+ continue;
225
+ }
226
+ endpointMap[`${route.method}:${route.path}`] = this.getRouteResponseType(route);
227
+ }
228
+ const endpointUrl = endpoint.baseUrl.endsWith("/") ? endpoint.baseUrl.slice(0, -1) : endpoint.baseUrl;
229
+ this.rootMap[endpointUrl] = { validator: endpointMap };
230
+ }
231
+ }
232
+ validateResponseParams(data, endpointUrl, routeData) {
233
+ if (!this.rootMap) {
234
+ throw new RsError("BAD_REQUEST", "Cannot validate response without type maps");
235
+ }
236
+ const routeMap = this.rootMap[endpointUrl].validator[`${routeData.method}:${routeData.path}`];
237
+ data = this.validateAndCoerceMap("_base", data, routeMap);
238
+ }
239
+ getRouteResponseType(route) {
240
+ const map = {};
241
+ for (const field of route.response) {
242
+ map[field.name] = this.getFieldResponseType(field, route.table);
243
+ }
244
+ if (route.type === "PAGED") {
245
+ return {
246
+ validator: {
247
+ data: { validator: map, isArray: true },
248
+ total: { validator: "number" }
249
+ }
250
+ };
251
+ }
252
+ if (route.method === "DELETE") {
253
+ return {
254
+ validator: "boolean"
255
+ };
256
+ }
257
+ return { validator: map, isArray: route.type === "ARRAY" };
258
+ }
259
+ getFieldResponseType(field, tableName) {
260
+ if (field.selector) {
261
+ return this.getTypeFromTable(field.selector, tableName);
262
+ } else if (field.subquery) {
263
+ const table = this.database.find((t) => t.name == tableName);
264
+ if (!table) return { isArray: true, validator: "any" };
265
+ const isOptional = table.roles.length > 0;
266
+ const validator = {};
267
+ for (const prop of field.subquery.properties) {
268
+ validator[prop.name] = this.getFieldResponseType(prop, field.subquery.table);
269
+ }
270
+ return {
271
+ isArray: true,
272
+ isOptional,
273
+ validator
274
+ };
275
+ }
276
+ return { validator: "any" };
277
+ }
278
+ getTypeFromTable(selector, name) {
279
+ const path2 = selector.split(".");
280
+ if (path2.length === 0 || path2.length > 2 || path2[0] === "") return { validator: "any", isOptional: false };
281
+ const tableName = path2.length == 2 ? path2[0] : name, columnName = path2.length == 2 ? path2[1] : path2[0];
282
+ const table = this.database.find((t) => t.name == tableName);
283
+ const column = table == null ? void 0 : table.columns.find((c) => c.name == columnName);
284
+ if (!table || !column) return { validator: "any", isOptional: false };
285
+ let validator = SqlUtils.convertDatabaseTypeToTypescript(
286
+ column.type,
287
+ column.value
288
+ );
289
+ if (!_ResponseValidator.validatorIsValidString(validator)) validator = this.parseValidationEnum(validator);
290
+ return {
291
+ validator,
292
+ isOptional: column.roles.length > 0 || column.isNullable
293
+ };
294
+ }
295
+ parseValidationEnum(validator) {
296
+ let terms = validator.split("|");
297
+ terms = terms.map((v) => v.replace(/'/g, "").trim());
298
+ return terms;
299
+ }
300
+ validateAndCoerceMap(name, value, { isOptional, isArray, validator }) {
301
+ if (validator === "any") return value;
302
+ const valueType = typeof value;
303
+ if (value == null) {
304
+ if (isOptional) return value;
305
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is required`);
306
+ }
307
+ if (isArray) {
308
+ if (!Array.isArray(value)) {
309
+ throw new RsError(
310
+ "DATABASE_ERROR",
311
+ `Response param (${name}) is a/an ${valueType} instead of an array`
312
+ );
313
+ }
314
+ value.forEach((v, i) => this.validateAndCoerceMap(`${name}[${i}]`, v, { validator }));
315
+ return value;
316
+ }
317
+ if (typeof validator === "string") {
318
+ if (validator === "boolean" && valueType === "number") {
319
+ if (value !== 0 && value !== 1)
320
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is of the wrong type (${valueType})`);
321
+ return value === 1;
322
+ } else if (validator === "string" && valueType === "string") {
323
+ if (typeof value === "string" && value.match(
324
+ /^\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}$/
325
+ )) {
326
+ const date = new Date(value);
327
+ if (date.toISOString() === "1970-01-01T00:00:00.000Z") return null;
328
+ const timezoneOffset = date.getTimezoneOffset() * 6e4;
329
+ return new Date(date.getTime() - timezoneOffset * 2).toISOString();
330
+ }
331
+ return value;
332
+ } else if (valueType === validator) {
333
+ return value;
334
+ } else if (valueType === "object") {
335
+ return value;
336
+ }
337
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is of the wrong type (${valueType})`);
338
+ }
339
+ if (Array.isArray(validator) && typeof value === "string") {
340
+ if (validator.includes(value)) return value;
341
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is not one of the enum options (${value})`);
342
+ }
343
+ if (valueType !== "object") {
344
+ throw new RsError("DATABASE_ERROR", `Response param (${name}) is of the wrong type (${valueType})`);
345
+ }
346
+ for (const prop in value) {
347
+ if (!validator[prop])
348
+ throw new RsError("DATABASE_ERROR", `Response param (${name}.${prop}) is not allowed`);
349
+ }
350
+ for (const prop in validator) {
351
+ value[prop] = this.validateAndCoerceMap(`${name}.${prop}`, value[prop], validator[prop]);
352
+ }
353
+ return value;
354
+ }
355
+ static isCustomRoute(route) {
356
+ return route.type === "CUSTOM_ONE" || route.type === "CUSTOM_ARRAY" || route.type === "CUSTOM_PAGED";
357
+ }
358
+ static validatorIsValidString(validator) {
359
+ return !validator.includes("|");
360
+ }
361
+ };
362
+
363
+ // src/restura/apiGenerator.ts
364
+ import { ObjectUtils, StringUtils } from "@redskytech/core-utils";
365
+ import prettier from "prettier";
366
+ var ApiTree = class _ApiTree {
367
+ constructor(namespace, database) {
368
+ this.database = database;
369
+ this.data = [];
370
+ this.namespace = namespace;
371
+ this.children = /* @__PURE__ */ new Map();
372
+ }
373
+ static createRootNode(database) {
374
+ return new _ApiTree(null, database);
375
+ }
376
+ static isRouteData(data) {
377
+ return data.method !== void 0;
378
+ }
379
+ static isEndpointData(data) {
380
+ return data.routes !== void 0;
381
+ }
382
+ addData(namespaces, route) {
383
+ if (ObjectUtils.isEmpty(namespaces)) {
384
+ this.data.push(route);
385
+ return;
386
+ }
387
+ const childName = namespaces[0];
388
+ this.children.set(childName, this.children.get(childName) || new _ApiTree(childName, this.database));
389
+ this.children.get(childName).addData(namespaces.slice(1), route);
390
+ }
391
+ createApiModels() {
392
+ let result = "";
393
+ for (const child of this.children.values()) {
394
+ result += child.createApiModelImpl(true);
395
+ }
396
+ return result;
397
+ }
398
+ createApiModelImpl(isBase) {
399
+ let result = ``;
400
+ for (const data of this.data) {
401
+ if (_ApiTree.isEndpointData(data)) {
402
+ result += _ApiTree.generateEndpointComments(data);
403
+ }
404
+ }
405
+ result += isBase ? `
406
+ declare namespace ${this.namespace} {` : `
407
+ export namespace ${this.namespace} {`;
408
+ for (const data of this.data) {
409
+ if (_ApiTree.isRouteData(data)) {
410
+ result += this.generateRouteModels(data);
411
+ }
412
+ }
413
+ for (const child of this.children.values()) {
414
+ result += child.createApiModelImpl(false);
415
+ }
416
+ result += "}";
417
+ return result;
418
+ }
419
+ static generateEndpointComments(endpoint) {
420
+ return `
421
+ // ${endpoint.name}
422
+ // ${endpoint.description}`;
423
+ }
424
+ generateRouteModels(route) {
425
+ let modelString = ``;
426
+ modelString += `
427
+ // ${route.name}
428
+ // ${route.description}
429
+ export namespace ${StringUtils.capitalizeFirst(route.method.toLowerCase())} {
430
+ ${this.generateRequestParameters(route)}
431
+ ${this.generateResponseParameters(route)}
432
+ }`;
433
+ return modelString;
434
+ }
435
+ generateRequestParameters(route) {
436
+ let modelString = ``;
437
+ if (ResponseValidator.isCustomRoute(route) && route.requestType) {
438
+ modelString += `
439
+ export type Req = CustomTypes.${route.requestType}`;
440
+ return modelString;
441
+ }
442
+ if (!route.request) return modelString;
443
+ modelString += `
444
+ export interface Req{
445
+ ${route.request.map((p) => {
446
+ let requestType = "any";
447
+ const oneOfValidator = p.validator.find((v) => v.type === "ONE_OF");
448
+ const typeCheckValidator = p.validator.find((v) => v.type === "TYPE_CHECK");
449
+ if (oneOfValidator && ObjectUtils.isArrayWithData(oneOfValidator.value)) {
450
+ requestType = oneOfValidator.value.map((v) => `'${v}'`).join(" | ");
451
+ } else if (typeCheckValidator) {
452
+ switch (typeCheckValidator.value) {
453
+ case "string":
454
+ case "number":
455
+ case "boolean":
456
+ case "string[]":
457
+ case "number[]":
458
+ case "any[]":
459
+ requestType = typeCheckValidator.value;
460
+ break;
461
+ }
462
+ }
463
+ return `'${p.name}'${p.required ? "" : "?"}:${requestType}`;
464
+ }).join(";\n")}${ObjectUtils.isArrayWithData(route.request) ? ";" : ""}
465
+ `;
466
+ modelString += `}`;
467
+ return modelString;
468
+ }
469
+ generateResponseParameters(route) {
470
+ if (ResponseValidator.isCustomRoute(route)) {
471
+ if (["number", "string", "boolean"].includes(route.responseType))
472
+ return `export type Res = ${route.responseType}`;
473
+ else if (["CUSTOM_ARRAY", "CUSTOM_PAGED"].includes(route.type))
474
+ return `export type Res = CustomTypes.${route.responseType}[]`;
475
+ else return `export type Res = CustomTypes.${route.responseType}`;
476
+ }
477
+ return `export interface Res ${this.getFields(route.response)}`;
478
+ }
479
+ getFields(fields) {
480
+ const nameFields = fields.map((f) => this.getNameAndType(f));
481
+ const nested = `{
482
+ ${nameFields.join(";\n ")}${ObjectUtils.isArrayWithData(nameFields) ? ";" : ""}
483
+ }`;
484
+ return nested;
485
+ }
486
+ getNameAndType(p) {
487
+ let responseType = "any", optional = false, array = false;
488
+ if (p.selector) {
489
+ ({ responseType, optional } = this.getTypeFromTable(p.selector, p.name));
490
+ } else if (p.subquery) {
491
+ responseType = this.getFields(p.subquery.properties);
492
+ array = true;
493
+ }
494
+ return `${p.name}${optional ? "?" : ""}:${responseType}${array ? "[]" : ""}`;
495
+ }
496
+ getTypeFromTable(selector, name) {
497
+ const path2 = selector.split(".");
498
+ if (path2.length === 0 || path2.length > 2 || path2[0] === "") return { responseType: "any", optional: false };
499
+ let tableName = path2.length == 2 ? path2[0] : name;
500
+ const columnName = path2.length == 2 ? path2[1] : path2[0];
501
+ let table = this.database.find((t) => t.name == tableName);
502
+ if (!table && tableName.includes("_")) {
503
+ const tableAliasSplit = tableName.split("_");
504
+ tableName = tableAliasSplit[1];
505
+ table = this.database.find((t) => t.name == tableName);
506
+ }
507
+ const column = table == null ? void 0 : table.columns.find((c) => c.name == columnName);
508
+ if (!table || !column) return { responseType: "any", optional: false };
509
+ return {
510
+ responseType: SqlUtils.convertDatabaseTypeToTypescript(column.type, column.value),
511
+ optional: column.roles.length > 0 || column.isNullable
512
+ };
513
+ }
514
+ };
515
+ function pathToNamespaces(path2) {
516
+ return path2.split("/").map((e) => StringUtils.toPascalCasing(e)).filter((e) => e);
517
+ }
518
+ function apiGenerator(schema, schemaHash) {
519
+ let apiString = `/** Auto generated file from Schema Hash (${schemaHash}). DO NOT MODIFY **/`;
520
+ const rootNamespace = ApiTree.createRootNode(schema.database);
521
+ for (const endpoint of schema.endpoints) {
522
+ const endpointNamespaces = pathToNamespaces(endpoint.baseUrl);
523
+ rootNamespace.addData(endpointNamespaces, endpoint);
524
+ for (const route of endpoint.routes) {
525
+ const fullNamespace = [...endpointNamespaces, ...pathToNamespaces(route.path)];
526
+ rootNamespace.addData(fullNamespace, route);
527
+ }
528
+ }
529
+ apiString += rootNamespace.createApiModels();
530
+ if (schema.customTypes.length > 0) {
531
+ apiString += `
532
+
533
+ declare namespace CustomTypes {
534
+ ${schema.customTypes}
535
+ }`;
536
+ }
537
+ return prettier.format(apiString, __spreadValues({
538
+ parser: "typescript"
539
+ }, {
540
+ trailingComma: "none",
541
+ tabWidth: 4,
542
+ useTabs: true,
543
+ endOfLine: "lf",
544
+ printWidth: 120,
545
+ singleQuote: true
546
+ }));
547
+ }
548
+
549
+ // src/restura/middleware/addApiResponseFunctions.ts
550
+ function addApiResponseFunctions(req, res, next) {
551
+ res.sendData = function(data, statusCode = 200) {
552
+ res.status(statusCode).send({ data });
553
+ };
554
+ res.sendNoWrap = function(dataNoWrap, statusCode = 200) {
555
+ res.status(statusCode).send(dataNoWrap);
556
+ };
557
+ res.sendPaginated = function(pagedData, statusCode = 200) {
558
+ res.status(statusCode).send({ data: pagedData.data, total: pagedData.total });
559
+ };
560
+ res.sendError = function(shortError, msg, htmlStatusCode, stack) {
561
+ if (htmlStatusCode === void 0) {
562
+ if (RsError.htmlStatus(shortError) !== void 0) {
563
+ htmlStatusCode = RsError.htmlStatus(shortError);
564
+ } else {
565
+ htmlStatusCode = 500;
566
+ }
567
+ }
568
+ const errorData = __spreadValues({
569
+ err: shortError,
570
+ msg
571
+ }, restura.resturaConfig.sendErrorStackTrace && stack ? { stack } : {});
572
+ res.status(htmlStatusCode).send(errorData);
573
+ };
574
+ next();
575
+ }
576
+
577
+ // src/restura/validateRequestParams.ts
578
+ import { ObjectUtils as ObjectUtils2 } from "@redskytech/core-utils";
579
+ import jsonschema from "jsonschema";
580
+ function getRequestData(req) {
581
+ let body = "";
582
+ if (req.method === "GET" || req.method === "DELETE") {
583
+ body = "query";
584
+ } else {
585
+ body = "body";
586
+ }
587
+ const bodyData = req[body];
588
+ if (bodyData) {
589
+ for (const attr in bodyData) {
590
+ if (attr === "token") {
591
+ delete bodyData[attr];
592
+ continue;
593
+ }
594
+ if (bodyData[attr] instanceof Array) {
595
+ const attrList = [];
596
+ for (const value of bodyData[attr]) {
597
+ if (isNaN(Number(value))) continue;
598
+ attrList.push(Number(value));
599
+ }
600
+ if (ObjectUtils2.isArrayWithData(attrList)) {
601
+ bodyData[attr] = attrList;
602
+ }
603
+ } else {
604
+ bodyData[attr] = ObjectUtils2.safeParse(bodyData[attr]);
605
+ if (isNaN(Number(bodyData[attr]))) continue;
606
+ bodyData[attr] = Number(bodyData[attr]);
607
+ }
608
+ }
609
+ }
610
+ return bodyData;
611
+ }
612
+
613
+ // src/restura/restura.schema.ts
614
+ import { z as z2 } from "zod";
615
+ var orderBySchema = z2.object({
616
+ columnName: z2.string(),
617
+ order: z2.enum(["ASC", "DESC"]),
618
+ tableName: z2.string()
619
+ }).strict();
620
+ var groupBySchema = z2.object({
621
+ columnName: z2.string(),
622
+ tableName: z2.string()
623
+ }).strict();
624
+ var whereDataSchema = z2.object({
625
+ tableName: z2.string().optional(),
626
+ columnName: z2.string().optional(),
627
+ operator: z2.enum(["=", "<", ">", "<=", ">=", "!=", "LIKE", "IN", "NOT IN", "STARTS WITH", "ENDS WITH"]).optional(),
628
+ value: z2.string().optional(),
629
+ custom: z2.string().optional(),
630
+ conjunction: z2.enum(["AND", "OR"]).optional()
631
+ }).strict();
632
+ var assignmentDataSchema = z2.object({
633
+ name: z2.string(),
634
+ value: z2.string()
635
+ }).strict();
636
+ var joinDataSchema = z2.object({
637
+ table: z2.string(),
638
+ localColumnName: z2.string().optional(),
639
+ foreignColumnName: z2.string().optional(),
640
+ custom: z2.string().optional(),
641
+ type: z2.enum(["LEFT", "INNER"]),
642
+ alias: z2.string().optional()
643
+ }).strict();
644
+ var validatorDataSchema = z2.object({
645
+ type: z2.enum(["TYPE_CHECK", "MIN", "MAX", "ONE_OF"]),
646
+ value: z2.union([z2.string(), z2.array(z2.string()), z2.number(), z2.array(z2.number())])
647
+ }).strict();
648
+ var requestDataSchema = z2.object({
649
+ name: z2.string(),
650
+ required: z2.boolean(),
651
+ validator: z2.array(validatorDataSchema)
652
+ }).strict();
653
+ var responseDataSchema = z2.object({
654
+ name: z2.string(),
655
+ selector: z2.string().optional(),
656
+ subquery: z2.object({
657
+ table: z2.string(),
658
+ joins: z2.array(joinDataSchema),
659
+ where: z2.array(whereDataSchema),
660
+ properties: z2.array(z2.lazy(() => responseDataSchema)),
661
+ // Explicit type for the lazy schema
662
+ groupBy: groupBySchema.optional(),
663
+ orderBy: orderBySchema.optional()
664
+ }).optional()
665
+ }).strict();
666
+ var routeDataBaseSchema = z2.object({
667
+ method: z2.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]),
668
+ name: z2.string(),
669
+ description: z2.string(),
670
+ path: z2.string(),
671
+ roles: z2.array(z2.string())
672
+ }).strict();
673
+ var standardRouteSchema = routeDataBaseSchema.extend({
674
+ type: z2.enum(["ONE", "ARRAY", "PAGED"]),
675
+ table: z2.string(),
676
+ joins: z2.array(joinDataSchema),
677
+ assignments: z2.array(assignmentDataSchema),
678
+ where: z2.array(whereDataSchema),
679
+ request: z2.array(requestDataSchema),
680
+ response: z2.array(responseDataSchema),
681
+ groupBy: groupBySchema.optional(),
682
+ orderBy: orderBySchema.optional()
683
+ }).strict();
684
+ var customRouteSchema = routeDataBaseSchema.extend({
685
+ type: z2.enum(["CUSTOM_ONE", "CUSTOM_ARRAY", "CUSTOM_PAGED"]),
686
+ responseType: z2.union([z2.string(), z2.enum(["string", "number", "boolean"])]),
687
+ requestType: z2.string().optional(),
688
+ request: z2.array(requestDataSchema).optional(),
689
+ fileUploadType: z2.enum(["SINGLE", "MULTIPLE"]).optional()
690
+ }).strict();
691
+ var postgresColumnNumericTypesSchema = z2.enum([
692
+ "SMALLINT",
693
+ // 2 bytes, -32,768 to 32,767
694
+ "INTEGER",
695
+ // 4 bytes, -2,147,483,648 to 2,147,483,647
696
+ "BIGINT",
697
+ // 8 bytes, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
698
+ "DECIMAL",
699
+ // user-specified precision, exact numeric
700
+ "NUMERIC",
701
+ // same as DECIMAL
702
+ "REAL",
703
+ // 4 bytes, 6 decimal digits precision (single precision)
704
+ "DOUBLE PRECISION",
705
+ // 8 bytes, 15 decimal digits precision (double precision)
706
+ "SERIAL",
707
+ // auto-incrementing integer
708
+ "BIGSERIAL"
709
+ // auto-incrementing big integer
710
+ ]);
711
+ var postgresColumnStringTypesSchema = z2.enum([
712
+ "CHAR",
713
+ // fixed-length, blank-padded
714
+ "VARCHAR",
715
+ // variable-length with limit
716
+ "TEXT",
717
+ // variable-length without limit
718
+ "BYTEA"
719
+ // binary data
720
+ ]);
721
+ var postgresColumnDateTypesSchema = z2.enum([
722
+ "DATE",
723
+ // calendar date (year, month, day)
724
+ "TIMESTAMP",
725
+ // both date and time (without time zone)
726
+ "TIMESTAMPTZ",
727
+ // both date and time (with time zone)
728
+ "TIME",
729
+ // time of day (without time zone)
730
+ "INTERVAL"
731
+ // time span
732
+ ]);
733
+ var mariaDbColumnNumericTypesSchema = z2.enum([
734
+ "BOOLEAN",
735
+ // 1-byte A synonym for "TINYINT(1)". Supported from version 1.2.0 onwards.
736
+ "TINYINT",
737
+ // 1-byte A very small integer. Numeric value with scale 0. Signed: -126 to +127. Unsigned: 0 to 253.
738
+ "SMALLINT",
739
+ // 2-bytes A small integer. Signed: -32,766 to 32,767. Unsigned: 0 to 65,533.
740
+ "MEDIUMINT",
741
+ // 3-bytes A medium integer. Signed: -8388608 to 8388607. Unsigned: 0 to 16777215. Supported starting with MariaDB ColumnStore 1.4.2.
742
+ "INTEGER",
743
+ // 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
744
+ "BIGINT",
745
+ // 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
746
+ "DECIMAL",
747
+ // 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.
748
+ "FLOAT",
749
+ // 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.
750
+ "DOUBLE"
751
+ // 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.
752
+ ]);
753
+ var mariaDbColumnStringTypesSchema = z2.enum([
754
+ "CHAR",
755
+ // 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.
756
+ "VARCHAR",
757
+ // 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.
758
+ "TINYTEXT",
759
+ // 255 bytes Holds a small amount of letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
760
+ "TINYBLOB",
761
+ // 255 bytes Holds a small amount of binary data of variable length. Supported from version 1.1.0 onwards.
762
+ "TEXT",
763
+ // 64 KB Holds letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
764
+ "BLOB",
765
+ // 64 KB Holds binary data of variable length. Supported from version 1.1.0 onwards.
766
+ "MEDIUMTEXT",
767
+ // 16 MB Holds a medium amount of letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
768
+ "MEDIUMBLOB",
769
+ // 16 MB Holds a medium amount of binary data of variable length. Supported from version 1.1.0 onwards.
770
+ "LONGTEXT",
771
+ // 1.96 GB Holds a large amount of letters, numbers, and special characters of variable length. Supported from version 1.1.0 onwards.
772
+ "JSON",
773
+ // Alias for LONGTEXT, creates a CONSTRAINT for JSON_VALID, holds a JSON-formatted string of plain text.
774
+ "LONGBLOB",
775
+ // 1.96 GB Holds a large amount of binary data of variable length. Supported from version 1.1.0 onwards.
776
+ "ENUM"
777
+ // Enum type
778
+ ]);
779
+ var mariaDbColumnDateTypesSchema = z2.enum([
780
+ "DATE",
781
+ // 4-bytes Date has year, month, and day.
782
+ "DATETIME",
783
+ // 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.
784
+ "TIME",
785
+ // 8-bytes Holds hour, minute, second and optionally microseconds for time.
786
+ "TIMESTAMP"
787
+ // 4-bytes Values are stored as the number of seconds since 1970-01-01 00:00:00 UTC, and optionally microseconds.
788
+ ]);
789
+ var columnDataSchema = z2.object({
790
+ name: z2.string(),
791
+ type: z2.union([
792
+ postgresColumnNumericTypesSchema,
793
+ postgresColumnStringTypesSchema,
794
+ postgresColumnDateTypesSchema,
795
+ mariaDbColumnNumericTypesSchema,
796
+ mariaDbColumnStringTypesSchema,
797
+ mariaDbColumnDateTypesSchema
798
+ ]),
799
+ isNullable: z2.boolean(),
800
+ roles: z2.array(z2.string()),
801
+ comment: z2.string().optional(),
802
+ default: z2.string().optional(),
803
+ value: z2.string().optional(),
804
+ isPrimary: z2.boolean().optional(),
805
+ isUnique: z2.boolean().optional(),
806
+ hasAutoIncrement: z2.boolean().optional(),
807
+ length: z2.number().optional()
808
+ }).strict();
809
+ var indexDataSchema = z2.object({
810
+ name: z2.string(),
811
+ columns: z2.array(z2.string()),
812
+ isUnique: z2.boolean(),
813
+ isPrimaryKey: z2.boolean(),
814
+ order: z2.enum(["ASC", "DESC"])
815
+ }).strict();
816
+ var foreignKeyActionsSchema = z2.enum([
817
+ "CASCADE",
818
+ // CASCADE action for foreign keys
819
+ "SET NULL",
820
+ // SET NULL action for foreign keys
821
+ "RESTRICT",
822
+ // RESTRICT action for foreign keys
823
+ "NO ACTION",
824
+ // NO ACTION for foreign keys
825
+ "SET DEFAULT"
826
+ // SET DEFAULT action for foreign keys
827
+ ]);
828
+ var foreignKeyDataSchema = z2.object({
829
+ name: z2.string(),
830
+ column: z2.string(),
831
+ refTable: z2.string(),
832
+ refColumn: z2.string(),
833
+ onDelete: foreignKeyActionsSchema,
834
+ onUpdate: foreignKeyActionsSchema
835
+ }).strict();
836
+ var checkConstraintDataSchema = z2.object({
837
+ name: z2.string(),
838
+ check: z2.string()
839
+ }).strict();
840
+ var tableDataSchema = z2.object({
841
+ name: z2.string(),
842
+ columns: z2.array(columnDataSchema),
843
+ indexes: z2.array(indexDataSchema),
844
+ foreignKeys: z2.array(foreignKeyDataSchema),
845
+ checkConstraints: z2.array(checkConstraintDataSchema),
846
+ roles: z2.array(z2.string())
847
+ }).strict();
848
+ var endpointDataSchema = z2.object({
849
+ name: z2.string(),
850
+ description: z2.string(),
851
+ baseUrl: z2.string(),
852
+ routes: z2.array(z2.union([standardRouteSchema, customRouteSchema]))
853
+ }).strict();
854
+ var resturaZodSchema = z2.object({
855
+ database: z2.array(tableDataSchema),
856
+ endpoints: z2.array(endpointDataSchema),
857
+ globalParams: z2.array(z2.string()),
858
+ roles: z2.array(z2.string()),
859
+ customTypes: z2.string()
860
+ }).strict();
861
+ async function isSchemaValid(schemaToCheck) {
862
+ try {
863
+ resturaZodSchema.parse(schemaToCheck);
864
+ return true;
865
+ } catch (error) {
866
+ logger.error(error);
867
+ return false;
868
+ }
869
+ }
870
+
871
+ // src/restura/middleware/schemaValidation.ts
872
+ async function schemaValidation(req, res, next) {
873
+ req.data = getRequestData(req);
874
+ try {
875
+ resturaZodSchema.parse(req.data);
876
+ next();
877
+ } catch (error) {
878
+ logger.error(error);
879
+ res.sendError("BAD_REQUEST", error, 400 /* BAD_REQUEST */);
880
+ }
881
+ }
882
+
883
+ // src/restura/modelGenerator.ts
884
+ import { StringUtils as StringUtils2 } from "@redskytech/core-utils";
885
+ import prettier2 from "prettier";
886
+ function modelGenerator(schema, schemaHash) {
887
+ let modelString = `/** Auto generated file from Schema Hash (${schemaHash}). DO NOT MODIFY **/
888
+ `;
889
+ modelString += `declare namespace Model {
890
+ `;
891
+ for (const table of schema.database) {
892
+ modelString += convertTable(table);
893
+ }
894
+ modelString += `}`;
895
+ return prettier2.format(modelString, __spreadValues({
896
+ parser: "typescript"
897
+ }, {
898
+ trailingComma: "none",
899
+ tabWidth: 4,
900
+ useTabs: true,
901
+ endOfLine: "lf",
902
+ printWidth: 120,
903
+ singleQuote: true
904
+ }));
905
+ }
906
+ function convertTable(table) {
907
+ let modelString = ` export interface ${StringUtils2.capitalizeFirst(table.name)} {
908
+ `;
909
+ for (const column of table.columns) {
910
+ modelString += ` ${column.name}${column.isNullable ? "?" : ""}: ${SqlUtils.convertDatabaseTypeToTypescript(column.type, column.value)};
911
+ `;
912
+ }
913
+ modelString += ` }
914
+ `;
915
+ return modelString;
916
+ }
917
+
918
+ // src/restura/middleware/authenticateUser.ts
919
+ async function authenticateUser(applicationAuthenticateHandler) {
920
+ return (req, res, next) => {
921
+ applicationAuthenticateHandler(
922
+ req,
923
+ (userDetails) => {
924
+ req.requesterDetails = __spreadValues(__spreadValues({}, req.requesterDetails), userDetails);
925
+ next();
926
+ },
927
+ (errorMessage) => {
928
+ res.sendError("UNAUTHORIZED", errorMessage);
929
+ }
930
+ );
931
+ };
932
+ }
933
+
58
934
  // src/restura/restura.ts
59
935
  var ResturaEngine = class {
60
- init(app) {
936
+ constructor() {
937
+ this.publicEndpoints = {
938
+ GET: [],
939
+ POST: [],
940
+ PUT: [],
941
+ PATCH: [],
942
+ DELETE: []
943
+ };
944
+ }
945
+ // private customTypeValidation!: ValidationDictionary;
946
+ /**
947
+ * Initializes the Restura engine with the provided Express application.
948
+ *
949
+ * @param app - The Express application instance to initialize with Restura.
950
+ * @returns A promise that resolves when the initialization is complete.
951
+ */
952
+ async init(app, authenticationHandler) {
953
+ this.resturaConfig = config2.validate("restura", resturaConfigSchema);
954
+ this.authenticationHandler = authenticationHandler;
955
+ app.use(compression());
956
+ app.use(bodyParser.json({ limit: "32mb" }));
957
+ app.use(bodyParser.urlencoded({ limit: "32mb", extended: false }));
958
+ app.use(cookieParser());
959
+ app.disable("x-powered-by");
960
+ app.use("/", addApiResponseFunctions);
961
+ app.use("/api/", authenticateUser);
61
962
  app.use("/restura", this.resturaAuthentication);
62
- console.log("Restura Engine Initialized");
963
+ app.put(
964
+ "/restura/v1/schema",
965
+ schemaValidation,
966
+ this.updateSchema
967
+ );
968
+ app.post(
969
+ "/restura/v1/schema/preview",
970
+ schemaValidation,
971
+ this.previewCreateSchema
972
+ );
973
+ app.get("/restura/v1/schema", this.getSchema);
974
+ app.get("/restura/v1/schema/types", this.getSchemaAndTypes);
975
+ this.expressApp = app;
976
+ await this.reloadEndpoints();
977
+ this.validateGeneratedTypesFolder();
978
+ logger.info("Restura Engine Initialized");
979
+ }
980
+ /**
981
+ * Determines if a given endpoint is public based on the HTTP method and full URL. This
982
+ * is determined on whether the endpoint in the schema has no roles assigned to it.
983
+ *
984
+ * @param method - The HTTP method (e.g., 'GET', 'POST', 'PUT', 'PATCH', 'DELETE').
985
+ * @param fullUrl - The full URL of the endpoint.
986
+ * @returns A boolean indicating whether the endpoint is public.
987
+ */
988
+ isEndpointPublic(method, fullUrl) {
989
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE"].includes(method)) return false;
990
+ return this.publicEndpoints[method].includes(fullUrl);
991
+ }
992
+ /**
993
+ * Checks if an endpoint exists for a given HTTP method and full URL.
994
+ *
995
+ * @param method - The HTTP method to check (e.g., 'GET', 'POST', 'PUT', 'PATCH', 'DELETE').
996
+ * @param fullUrl - The full URL of the endpoint to check.
997
+ * @returns `true` if the endpoint exists, otherwise `false`.
998
+ */
999
+ doesEndpointExist(method, fullUrl) {
1000
+ return this.schema.endpoints.some((endpoint) => {
1001
+ if (!fullUrl.startsWith(endpoint.baseUrl)) return false;
1002
+ const pathWithoutBaseUrl = fullUrl.replace(endpoint.baseUrl, "");
1003
+ return endpoint.routes.some((route) => {
1004
+ return route.method === method && route.path === pathWithoutBaseUrl;
1005
+ });
1006
+ });
1007
+ }
1008
+ /**
1009
+ * Generates an API from the provided schema and writes it to the specified output file.
1010
+ *
1011
+ * @param outputFile - The path to the file where the generated API will be written.
1012
+ * @param providedSchema - The schema from which the API will be generated.
1013
+ * @returns A promise that resolves when the API has been successfully generated and written to the output file.
1014
+ */
1015
+ async generateApiFromSchema(outputFile, providedSchema) {
1016
+ fs.writeFileSync(
1017
+ outputFile,
1018
+ await apiGenerator(providedSchema, await this.generateHashForSchema(providedSchema))
1019
+ );
1020
+ }
1021
+ /**
1022
+ * Generates a model from the provided schema and writes it to the specified output file.
1023
+ *
1024
+ * @param outputFile - The path to the file where the generated model will be written.
1025
+ * @param providedSchema - The schema from which the model will be generated.
1026
+ * @returns A promise that resolves when the model has been successfully written to the output file.
1027
+ */
1028
+ async generateModelFromSchema(outputFile, providedSchema) {
1029
+ fs.writeFileSync(
1030
+ outputFile,
1031
+ await modelGenerator(providedSchema, await this.generateHashForSchema(providedSchema))
1032
+ );
1033
+ }
1034
+ /**
1035
+ * Retrieves the latest file system schema for Restura.
1036
+ *
1037
+ * @returns {Promise<ResturaSchema>} A promise that resolves to the latest Restura schema.
1038
+ * @throws {Error} If the schema file is missing or the schema is not valid.
1039
+ */
1040
+ async getLatestFileSystemSchema() {
1041
+ if (!fs.existsSync(this.resturaConfig.schemaFilePath)) {
1042
+ logger.error(`Missing restura schema file, expected path: ${this.resturaConfig.schemaFilePath}`);
1043
+ throw new Error("Missing restura schema file");
1044
+ }
1045
+ const schemaFileData = fs.readFileSync(this.resturaConfig.schemaFilePath, { encoding: "utf8" });
1046
+ const schema = ObjectUtils3.safeParse(schemaFileData);
1047
+ const isValid = await isSchemaValid(schema);
1048
+ if (!isValid) {
1049
+ logger.error("Schema is not valid");
1050
+ throw new Error("Schema is not valid");
1051
+ }
1052
+ return schema;
1053
+ }
1054
+ /**
1055
+ * Asynchronously generates and retrieves hashes for the provided schema and related generated files.
1056
+ *
1057
+ * @param providedSchema - The schema for which hashes need to be generated.
1058
+ * @returns A promise that resolves to an object containing:
1059
+ * - `schemaHash`: The hash of the provided schema.
1060
+ * - `apiCreatedSchemaHash`: The hash extracted from the generated `api.d.ts` file.
1061
+ * - `modelCreatedSchemaHash`: The hash extracted from the generated `models.d.ts` file.
1062
+ */
1063
+ async getHashes(providedSchema) {
1064
+ var _a, _b, _c, _d;
1065
+ const schemaHash = await this.generateHashForSchema(providedSchema);
1066
+ const apiFile = fs.readFileSync(path.join(this.resturaConfig.generatedTypesPath, "api.d.ts"));
1067
+ const apiCreatedSchemaHash = (_b = (_a = apiFile.toString().match(/\((.*)\)/)) == null ? void 0 : _a[1]) != null ? _b : "";
1068
+ const modelFile = fs.readFileSync(path.join(this.resturaConfig.generatedTypesPath, "models.d.ts"));
1069
+ const modelCreatedSchemaHash = (_d = (_c = modelFile.toString().match(/\((.*)\)/)) == null ? void 0 : _c[1]) != null ? _d : "";
1070
+ return {
1071
+ schemaHash,
1072
+ apiCreatedSchemaHash,
1073
+ modelCreatedSchemaHash
1074
+ };
1075
+ }
1076
+ async reloadEndpoints() {
1077
+ this.schema = await this.getLatestFileSystemSchema();
1078
+ this.resturaRouter = express.Router();
1079
+ this.resetPublicEndpoints();
1080
+ let routeCount = 0;
1081
+ for (const endpoint of this.schema.endpoints) {
1082
+ const baseUrl = endpoint.baseUrl.endsWith("/") ? endpoint.baseUrl.slice(0, -1) : endpoint.baseUrl;
1083
+ this.expressApp.use(baseUrl, (req, res, next) => {
1084
+ this.resturaRouter(req, res, next);
1085
+ });
1086
+ for (const route of endpoint.routes) {
1087
+ route.path = route.path.startsWith("/") ? route.path : `/${route.path}`;
1088
+ route.path = route.path.endsWith("/") ? route.path.slice(0, -1) : route.path;
1089
+ const fullUrl = `${baseUrl}${route.path}`;
1090
+ if (route.roles.length === 0) this.publicEndpoints[route.method].push(fullUrl);
1091
+ this.resturaRouter[route.method.toLowerCase()](
1092
+ route.path,
1093
+ // <-- Notice we only use path here since the baseUrl is already added to the router.
1094
+ this.executeRouteLogic
1095
+ );
1096
+ routeCount++;
1097
+ }
1098
+ }
1099
+ this.responseValidator = new ResponseValidator(this.schema);
1100
+ logger.info(`Restura loaded (${routeCount}) endpoint${routeCount > 1 ? "s" : ""}`);
1101
+ }
1102
+ async validateGeneratedTypesFolder() {
1103
+ if (!fs.existsSync(this.resturaConfig.generatedTypesPath)) {
1104
+ fs.mkdirSync(this.resturaConfig.generatedTypesPath, { recursive: true });
1105
+ }
1106
+ const hasApiFile = fs.existsSync(path.join(this.resturaConfig.generatedTypesPath, "api.d.ts"));
1107
+ const hasModelsFile = fs.existsSync(path.join(this.resturaConfig.generatedTypesPath, "models.d.ts"));
1108
+ if (!hasApiFile) {
1109
+ await this.generateApiFromSchema(path.join(this.resturaConfig.generatedTypesPath, "api.d.ts"), this.schema);
1110
+ }
1111
+ if (!hasModelsFile) {
1112
+ await this.generateModelFromSchema(
1113
+ path.join(this.resturaConfig.generatedTypesPath, "models.d.ts"),
1114
+ this.schema
1115
+ );
1116
+ }
1117
+ const hashes = await this.getHashes(this.schema);
1118
+ if (hashes.schemaHash !== hashes.apiCreatedSchemaHash) {
1119
+ await this.generateApiFromSchema(path.join(this.resturaConfig.generatedTypesPath, "api.d.ts"), this.schema);
1120
+ }
1121
+ if (hashes.schemaHash !== hashes.modelCreatedSchemaHash) {
1122
+ await this.generateModelFromSchema(
1123
+ path.join(this.resturaConfig.generatedTypesPath, "models.d.ts"),
1124
+ this.schema
1125
+ );
1126
+ }
63
1127
  }
64
1128
  resturaAuthentication(req, res, next) {
65
- next();
1129
+ if (req.headers["x-auth-token"] !== this.resturaConfig.authToken) res.status(401).send("Unauthorized");
1130
+ else next();
1131
+ }
1132
+ async previewCreateSchema(req, res) {
1133
+ try {
1134
+ const schemaDiff = { commands: "", endPoints: [], globalParams: [], roles: [], customTypes: false };
1135
+ res.send({ data: schemaDiff });
1136
+ } catch (err) {
1137
+ res.status(400).send(err);
1138
+ }
1139
+ }
1140
+ async updateSchema(req, res) {
1141
+ try {
1142
+ this.schema = req.data;
1143
+ await this.storeFileSystemSchema();
1144
+ await this.reloadEndpoints();
1145
+ await this.updateTypes();
1146
+ res.send({ data: "success" });
1147
+ } catch (err) {
1148
+ if (err instanceof Error) res.status(400).send(err.message);
1149
+ else res.status(400).send("Unknown error");
1150
+ }
1151
+ }
1152
+ async updateTypes() {
1153
+ await this.generateApiFromSchema(path.join(this.resturaConfig.generatedTypesPath, "api.d.ts"), this.schema);
1154
+ await this.generateModelFromSchema(
1155
+ path.join(this.resturaConfig.generatedTypesPath, "models.d.ts"),
1156
+ this.schema
1157
+ );
1158
+ }
1159
+ async getSchema(req, res) {
1160
+ res.send({ data: this.schema });
1161
+ }
1162
+ async getSchemaAndTypes(req, res) {
1163
+ try {
1164
+ const schema = await this.getLatestFileSystemSchema();
1165
+ const schemaHash = await this.generateHashForSchema(schema);
1166
+ const apiText = await apiGenerator(schema, schemaHash);
1167
+ const modelsText = await modelGenerator(schema, schemaHash);
1168
+ res.send({ schema, api: apiText, models: modelsText });
1169
+ } catch (err) {
1170
+ res.status(400).send({ error: err });
1171
+ }
1172
+ }
1173
+ async executeRouteLogic(req, res, next) {
1174
+ try {
1175
+ const routeData = this.getRouteData(req.method, req.baseUrl, req.path);
1176
+ this.validateAuthorization(req, routeData);
1177
+ } catch (e) {
1178
+ next(e);
1179
+ }
1180
+ }
1181
+ isCustomRoute(route) {
1182
+ return route.type === "CUSTOM_ONE" || route.type === "CUSTOM_ARRAY" || route.type === "CUSTOM_PAGED";
1183
+ }
1184
+ // @boundMethod
1185
+ // private async runCustomRouteLogic<T>(req: RsRequest<T>, res: RsResponse<T>, routeData: RouteData) {
1186
+ // const version = req.baseUrl.split('/')[2];
1187
+ // let domain = routeData.path.split('/')[1];
1188
+ // domain = domain.split('-').reduce((acc, value, index) => {
1189
+ // if (index === 0) acc = value;
1190
+ // else acc += StringUtils.capitalizeFirst(value);
1191
+ // return acc;
1192
+ // }, '');
1193
+ // const customApiName = `${StringUtils.capitalizeFirst(domain)}Api${StringUtils.capitalizeFirst(version)}`;
1194
+ // const customApi = apiFactory.getCustomApi(customApiName);
1195
+ // if (!customApi) throw new RsError('NOT_FOUND', `API domain ${domain}-${version} not found`);
1196
+ // const functionName = `${routeData.method.toLowerCase()}${routeData.path
1197
+ // .replace(new RegExp('-', 'g'), '/')
1198
+ // .split('/')
1199
+ // .reduce((acc, cur) => {
1200
+ // if (cur === '') return acc;
1201
+ // return acc + StringUtils.capitalizeFirst(cur);
1202
+ // }, '')}`;
1203
+ // // @ts-expect-error - Here we are dynamically calling the function from a custom class, not sure how to typescript this
1204
+ // const customFunction = customApi[functionName] as (
1205
+ // req: RsRequest<T>,
1206
+ // res: RsResponse<T>,
1207
+ // routeData: RouteData
1208
+ // ) => Promise<void>;
1209
+ // if (!customFunction) throw new RsError('NOT_FOUND', `API path ${routeData.path} not implemented`);
1210
+ // await customFunction(req, res, routeData);
1211
+ // }
1212
+ async generateHashForSchema(providedSchema) {
1213
+ const schemaPrettyStr = await prettier3.format(JSON.stringify(providedSchema), __spreadValues({
1214
+ parser: "json"
1215
+ }, {
1216
+ trailingComma: "none",
1217
+ tabWidth: 4,
1218
+ useTabs: true,
1219
+ endOfLine: "lf",
1220
+ printWidth: 120,
1221
+ singleQuote: true
1222
+ }));
1223
+ return createHash("sha256").update(schemaPrettyStr).digest("hex");
1224
+ }
1225
+ async storeFileSystemSchema() {
1226
+ const schemaPrettyStr = await prettier3.format(JSON.stringify(this.schema), __spreadValues({
1227
+ parser: "json"
1228
+ }, {
1229
+ trailingComma: "none",
1230
+ tabWidth: 4,
1231
+ useTabs: true,
1232
+ endOfLine: "lf",
1233
+ printWidth: 120,
1234
+ singleQuote: true
1235
+ }));
1236
+ fs.writeFileSync(this.resturaConfig.schemaFilePath, schemaPrettyStr);
1237
+ }
1238
+ resetPublicEndpoints() {
1239
+ this.publicEndpoints = {
1240
+ GET: [],
1241
+ POST: [],
1242
+ PUT: [],
1243
+ PATCH: [],
1244
+ DELETE: []
1245
+ };
1246
+ }
1247
+ validateAuthorization(req, routeData) {
1248
+ const role = req.requesterDetails.role;
1249
+ if (routeData.roles.length === 0 || !role) return;
1250
+ if (!routeData.roles.includes(role))
1251
+ throw new RsError("UNAUTHORIZED", "Not authorized to access this endpoint");
1252
+ }
1253
+ getRouteData(method, baseUrl, path2) {
1254
+ const endpoint = this.schema.endpoints.find((item) => {
1255
+ return item.baseUrl === baseUrl;
1256
+ });
1257
+ if (!endpoint) throw new RsError("NOT_FOUND", "Route not found");
1258
+ const route = endpoint.routes.find((item) => {
1259
+ return item.method === method && item.path === path2;
1260
+ });
1261
+ if (!route) throw new RsError("NOT_FOUND", "Route not found");
1262
+ return route;
66
1263
  }
67
1264
  };
68
1265
  __decorateClass([
69
1266
  boundMethod
70
1267
  ], ResturaEngine.prototype, "resturaAuthentication", 1);
1268
+ __decorateClass([
1269
+ boundMethod
1270
+ ], ResturaEngine.prototype, "previewCreateSchema", 1);
1271
+ __decorateClass([
1272
+ boundMethod
1273
+ ], ResturaEngine.prototype, "updateSchema", 1);
1274
+ __decorateClass([
1275
+ boundMethod
1276
+ ], ResturaEngine.prototype, "getSchema", 1);
1277
+ __decorateClass([
1278
+ boundMethod
1279
+ ], ResturaEngine.prototype, "getSchemaAndTypes", 1);
1280
+ __decorateClass([
1281
+ boundMethod
1282
+ ], ResturaEngine.prototype, "executeRouteLogic", 1);
1283
+ __decorateClass([
1284
+ boundMethod
1285
+ ], ResturaEngine.prototype, "isCustomRoute", 1);
71
1286
  var restura = new ResturaEngine();
72
1287
  export {
1288
+ logger,
73
1289
  restura
74
1290
  };
75
1291
  //# sourceMappingURL=index.mjs.map