@devbro/pashmak 0.1.11 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/app/console/migrate/make_migration.tpl +5 -5
  2. package/dist/app/console/queue/GenerateMigrateCommand.d.mts +9 -0
  3. package/dist/app/console/queue/GenerateMigrateCommand.mjs +51 -0
  4. package/dist/app/console/queue/GenerateMigrateCommand.mjs.map +1 -0
  5. package/dist/app/console/queue/queue_migration.tpl +19 -0
  6. package/dist/bin/app/console/DefaultCommand.cjs +160 -21
  7. package/dist/bin/app/console/KeyGenerateCommand.cjs +160 -21
  8. package/dist/bin/app/console/StartCommand.cjs +163 -24
  9. package/dist/bin/app/console/generate/GenerateControllerCommand.cjs +160 -21
  10. package/dist/bin/app/console/generate/index.cjs +160 -21
  11. package/dist/bin/app/console/index.cjs +162 -23
  12. package/dist/bin/app/console/migrate/GenerateMigrateCommand.cjs +160 -21
  13. package/dist/bin/app/console/migrate/MigrateCommand.cjs +161 -22
  14. package/dist/bin/app/console/migrate/MigrateRollbackCommand.cjs +160 -21
  15. package/dist/bin/app/console/migrate/index.cjs +160 -21
  16. package/dist/bin/app/console/queue/GenerateMigrateCommand.cjs +752 -0
  17. package/dist/bin/facades.cjs +163 -22
  18. package/dist/bin/factories.cjs +707 -0
  19. package/dist/bin/index.cjs +178 -28
  20. package/dist/bin/middlewares.cjs +161 -22
  21. package/dist/bin/queue.cjs +99 -0
  22. package/dist/facades.d.mts +3 -1
  23. package/dist/facades.mjs +15 -27
  24. package/dist/facades.mjs.map +1 -1
  25. package/dist/factories.d.mts +20 -0
  26. package/dist/factories.mjs +83 -0
  27. package/dist/factories.mjs.map +1 -0
  28. package/dist/queue.d.mts +15 -0
  29. package/dist/queue.mjs +73 -0
  30. package/dist/queue.mjs.map +1 -0
  31. package/package.json +7 -1
@@ -0,0 +1,752 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
+ // If the importer is in node compatibility mode or this is not an ESM
24
+ // file that has been converted to a CommonJS file using a Babel-
25
+ // compatible transform (i.e. "__esModule" has not been set), then set
26
+ // "default" to the CommonJS "module.exports" for node compatibility.
27
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
+ mod
29
+ ));
30
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
+
32
+ // src/app/console/queue/GenerateMigrateCommand.mts
33
+ var GenerateMigrateCommand_exports = {};
34
+ __export(GenerateMigrateCommand_exports, {
35
+ GenerateMigrateCommand: () => GenerateMigrateCommand
36
+ });
37
+ module.exports = __toCommonJS(GenerateMigrateCommand_exports);
38
+
39
+ // src/router.mts
40
+ var import_neko_context = require("@devbro/neko-context");
41
+ var import_errors = require("@devbro/neko-http/errors");
42
+
43
+ // ../neko-router/dist/CompiledRoute.mjs
44
+ var import_stream = require("stream");
45
+
46
+ // ../neko-router/dist/Middleware.mjs
47
+ var Middleware = class {
48
+ static {
49
+ __name(this, "Middleware");
50
+ }
51
+ constructor(params = {}) {
52
+ }
53
+ static getInstance(params) {
54
+ throw new Error("Method not implemented. Please implement a static getInstance method.");
55
+ }
56
+ };
57
+
58
+ // ../neko-router/dist/MiddlewareFactory.mjs
59
+ var MiddlewareFactory = class {
60
+ static {
61
+ __name(this, "MiddlewareFactory");
62
+ }
63
+ static create(func) {
64
+ const cls = class extends Middleware {
65
+ static {
66
+ __name(this, "cls");
67
+ }
68
+ call(req, res, next) {
69
+ return func(req, res, next);
70
+ }
71
+ constructor(params = {}) {
72
+ super(params);
73
+ }
74
+ };
75
+ return new cls();
76
+ }
77
+ };
78
+
79
+ // ../neko-router/dist/CompiledRoute.mjs
80
+ var CompiledRoute = class {
81
+ static {
82
+ __name(this, "CompiledRoute");
83
+ }
84
+ constructor(route, request, response, globalMiddlewares = []) {
85
+ this.route = route;
86
+ this.request = request;
87
+ this.response = response;
88
+ this.globalMiddlewares = globalMiddlewares;
89
+ this.prepareMiddlewares();
90
+ }
91
+ middlewares = [];
92
+ getMiddlewares() {
93
+ return this.middlewares;
94
+ }
95
+ prepareMiddlewares() {
96
+ this.middlewares = [];
97
+ for (const middleware of [...this.globalMiddlewares, ...this.route.getMiddlewares()]) {
98
+ if (middleware instanceof Middleware) {
99
+ this.middlewares.push(middleware);
100
+ } else if (this.isClass(middleware)) {
101
+ this.middlewares.push(middleware.getInstance({}));
102
+ } else if (typeof middleware === "function") {
103
+ this.middlewares.push(MiddlewareFactory.create(middleware));
104
+ } else {
105
+ throw new Error("Invalid middleware type");
106
+ }
107
+ }
108
+ }
109
+ isClass(func) {
110
+ return typeof func === "function" && /^class\s/.test(Function.prototype.toString.call(func));
111
+ }
112
+ async run() {
113
+ return await this.runMiddlewares(this.middlewares, this.request, this.response);
114
+ }
115
+ prepareOutputJsonFormat(obj) {
116
+ function traverse(value) {
117
+ if (!value || typeof value !== "object") {
118
+ return value;
119
+ }
120
+ if (typeof value.toJson === "function") {
121
+ return traverse(value.toJson());
122
+ }
123
+ if (typeof value.toJSON === "function") {
124
+ return traverse(value.toJSON());
125
+ }
126
+ if (Array.isArray(value)) {
127
+ return value.map(traverse);
128
+ }
129
+ const result = {};
130
+ for (const key in value) {
131
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
132
+ result[key] = traverse(value[key]);
133
+ }
134
+ }
135
+ return result;
136
+ }
137
+ __name(traverse, "traverse");
138
+ return traverse(obj);
139
+ }
140
+ convertToString(obj) {
141
+ if (typeof obj === "string") {
142
+ return obj;
143
+ } else if (obj instanceof Buffer) {
144
+ return obj.toString();
145
+ } else if (typeof obj === "object") {
146
+ return JSON.stringify(this.prepareOutputJsonFormat(obj));
147
+ }
148
+ return String(obj);
149
+ }
150
+ async processResponseBody(res, controller_rc) {
151
+ if (controller_rc && res.writableEnded) {
152
+ throw new Error("cannot write to response, response has already ended");
153
+ }
154
+ if (res.writableEnded) {
155
+ return;
156
+ }
157
+ if (controller_rc) {
158
+ const header_content_type = res.getHeader("Content-Type");
159
+ if (controller_rc instanceof import_stream.Stream || Buffer.isBuffer(controller_rc)) {
160
+ await this.writeAsync(res, controller_rc);
161
+ res.end();
162
+ } else if (!header_content_type && typeof controller_rc === "object") {
163
+ res.setHeader("Content-Type", "application/json");
164
+ res.end(this.convertToString(controller_rc));
165
+ } else if (!header_content_type) {
166
+ res.setHeader("Content-Type", "text/plain");
167
+ res.end(this.convertToString(controller_rc));
168
+ } else {
169
+ res.end(this.convertToString(controller_rc));
170
+ }
171
+ return;
172
+ } else {
173
+ res.statusCode = [200].includes(res.statusCode) ? 204 : res.statusCode;
174
+ res.end();
175
+ }
176
+ }
177
+ async writeAsync(res, chunk) {
178
+ return new Promise((resolve, reject) => {
179
+ const ok = res.write(chunk, (err) => {
180
+ if (err) reject(err);
181
+ });
182
+ if (ok) {
183
+ resolve(0);
184
+ } else {
185
+ res.once("drain", resolve);
186
+ }
187
+ });
188
+ }
189
+ async runMiddlewares(middlewares, req, res) {
190
+ let index = 0;
191
+ const me = this;
192
+ async function next() {
193
+ if (index >= middlewares.length) {
194
+ const controller_rc = await me.route.callHanlder(req, res);
195
+ await me.processResponseBody(res, controller_rc);
196
+ return;
197
+ }
198
+ const middleware = middlewares[index++];
199
+ if (middleware instanceof Middleware) {
200
+ await middleware.call(req, res, next);
201
+ } else if (typeof middleware === "function") {
202
+ await middleware(req, res, next);
203
+ } else {
204
+ throw new Error("does not know how to run middleware");
205
+ }
206
+ }
207
+ __name(next, "next");
208
+ await next();
209
+ }
210
+ };
211
+
212
+ // ../neko-router/dist/Route.mjs
213
+ var Route = class {
214
+ static {
215
+ __name(this, "Route");
216
+ }
217
+ constructor(methods, path3, handler) {
218
+ this.methods = methods;
219
+ this.path = path3;
220
+ this.handler = handler;
221
+ this.urlRegex = this.pathToRegex(path3);
222
+ }
223
+ middlewares = [];
224
+ urlRegex;
225
+ pathToRegex(path3) {
226
+ const lex = this.lexUrlPath(path3);
227
+ return this.tokensToRegex(lex);
228
+ }
229
+ lexUrlPath(path3) {
230
+ const tokens = [];
231
+ let i = 0;
232
+ while (i < path3.length) {
233
+ const char = path3[i];
234
+ if (char === "/") {
235
+ tokens.push({ type: "SLASH", value: "/" });
236
+ i++;
237
+ } else if (char === ":") {
238
+ let start = i + 1;
239
+ while (start < path3.length && /[a-zA-Z0-9_]/.test(path3[start])) {
240
+ start++;
241
+ }
242
+ tokens.push({ type: "PARAM", value: path3.slice(i + 1, start) });
243
+ i = start;
244
+ } else if (char === "*") {
245
+ let start = i + 1;
246
+ while (start < path3.length && /[a-zA-Z0-9_\.]/.test(path3[start])) {
247
+ start++;
248
+ }
249
+ tokens.push({ type: "WILDCARD", value: path3.slice(i + 1, start) });
250
+ i = start;
251
+ } else {
252
+ let start = i;
253
+ while (start < path3.length && !["/", ":", "*"].includes(path3[start])) {
254
+ start++;
255
+ }
256
+ tokens.push({ type: "TEXT", value: path3.slice(i, start) });
257
+ i = start;
258
+ }
259
+ }
260
+ return tokens;
261
+ }
262
+ tokensToRegex(tokens) {
263
+ const regexParts = [];
264
+ for (const token of tokens) {
265
+ if (token.type === "SLASH") {
266
+ regexParts.push("\\/");
267
+ } else if (token.type === "PARAM") {
268
+ regexParts.push(`(?<${token.value}>[^\\/]+)`);
269
+ } else if (token.type === "WILDCARD") {
270
+ regexParts.push("(.+)");
271
+ } else if (token.type === "TEXT") {
272
+ regexParts.push(token.value.replace(/[-\/\\^$.*+?()[\]{}|]/g, "\\$&"));
273
+ }
274
+ }
275
+ if (regexParts.length > 0 && regexParts[regexParts.length - 1] === "\\/") {
276
+ regexParts[regexParts.length - 1] = "\\/?";
277
+ } else {
278
+ regexParts.push("\\/?");
279
+ }
280
+ return new RegExp(`^${regexParts.join("")}$`);
281
+ }
282
+ /**
283
+ * to evaludate if request is a match for this route
284
+ * @param request http request
285
+ * @returns return true if route is a match for this request
286
+ */
287
+ test(request) {
288
+ if (this.methods.indexOf(request.method) === -1) {
289
+ return false;
290
+ }
291
+ const url = new URL(request.url || "/", "http://localhost");
292
+ return this.testPath(url.pathname);
293
+ }
294
+ testPath(pathname) {
295
+ return this.urlRegex.test(pathname);
296
+ }
297
+ /**
298
+ * returns details of the match, otherwise it returns false
299
+ * @param request the request to match
300
+ * @returns object cotaining details of match including matched params
301
+ */
302
+ match(request) {
303
+ if (this.methods.indexOf(request.method) === -1) {
304
+ return false;
305
+ }
306
+ const url = new URL(request.url || "/", "http://localhost");
307
+ const r = this.urlRegex.exec(url.pathname);
308
+ if (!r) {
309
+ return false;
310
+ }
311
+ return {
312
+ url,
313
+ params: r.groups || {}
314
+ };
315
+ }
316
+ prependMiddleware(middlewares) {
317
+ this.middlewares = [].concat(middlewares, this.middlewares);
318
+ return this;
319
+ }
320
+ addMiddleware(middlewares) {
321
+ this.middlewares = this.middlewares.concat(middlewares);
322
+ return this;
323
+ }
324
+ getMiddlewares() {
325
+ return this.middlewares;
326
+ }
327
+ callHanlder(request, response) {
328
+ return this.handler(request, response);
329
+ }
330
+ };
331
+
332
+ // ../neko-router/dist/Router.mjs
333
+ var import_path = __toESM(require("path"), 1);
334
+
335
+ // ../node_modules/url-join/lib/url-join.js
336
+ function normalize(strArray) {
337
+ var resultArray = [];
338
+ if (strArray.length === 0) {
339
+ return "";
340
+ }
341
+ if (typeof strArray[0] !== "string") {
342
+ throw new TypeError("Url must be a string. Received " + strArray[0]);
343
+ }
344
+ if (strArray[0].match(/^[^/:]+:\/*$/) && strArray.length > 1) {
345
+ var first = strArray.shift();
346
+ strArray[0] = first + strArray[0];
347
+ }
348
+ if (strArray[0].match(/^file:\/\/\//)) {
349
+ strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1:///");
350
+ } else {
351
+ strArray[0] = strArray[0].replace(/^([^/:]+):\/*/, "$1://");
352
+ }
353
+ for (var i = 0; i < strArray.length; i++) {
354
+ var component = strArray[i];
355
+ if (typeof component !== "string") {
356
+ throw new TypeError("Url must be a string. Received " + component);
357
+ }
358
+ if (component === "") {
359
+ continue;
360
+ }
361
+ if (i > 0) {
362
+ component = component.replace(/^[\/]+/, "");
363
+ }
364
+ if (i < strArray.length - 1) {
365
+ component = component.replace(/[\/]+$/, "");
366
+ } else {
367
+ component = component.replace(/[\/]+$/, "/");
368
+ }
369
+ resultArray.push(component);
370
+ }
371
+ var str = resultArray.join("/");
372
+ str = str.replace(/\/(\?|&|#[^!])/g, "$1");
373
+ var parts = str.split("?");
374
+ str = parts.shift() + (parts.length > 0 ? "?" : "") + parts.join("&");
375
+ return str;
376
+ }
377
+ __name(normalize, "normalize");
378
+ function urlJoin() {
379
+ var input;
380
+ if (typeof arguments[0] === "object") {
381
+ input = arguments[0];
382
+ } else {
383
+ input = [].slice.call(arguments);
384
+ }
385
+ return normalize(input);
386
+ }
387
+ __name(urlJoin, "urlJoin");
388
+
389
+ // ../neko-router/dist/Router.mjs
390
+ var Router = class {
391
+ static {
392
+ __name(this, "Router");
393
+ }
394
+ middlewares = [];
395
+ routes = [];
396
+ addRoute(methods, path22, handler) {
397
+ const route = new Route(methods, path22, handler);
398
+ this.routes.push(route);
399
+ return route;
400
+ }
401
+ getMiddlewares() {
402
+ return [...this.middlewares];
403
+ }
404
+ addController(controller) {
405
+ const basePath = controller.basePath || "";
406
+ for (const route of controller.routes) {
407
+ const urlPath = import_path.default.join(basePath, route.path);
408
+ this.addRoute(route.methods, urlPath, async (req, res) => {
409
+ const controllerInstance = controller.getInstance();
410
+ return await controllerInstance[route.handler]();
411
+ }).addMiddleware([...controller.baseMiddlewares, ...route.middlewares]);
412
+ }
413
+ }
414
+ addRouter(path22, router2) {
415
+ for (const route of router2.routes) {
416
+ let path222 = urlJoin("/", path22, route.path);
417
+ this.addRoute(route.methods, path222, route.handler).addMiddleware(router2.getMiddlewares()).addMiddleware(route.getMiddlewares());
418
+ }
419
+ }
420
+ addGlobalMiddleware(middlewares) {
421
+ this.middlewares = this.middlewares.concat(middlewares);
422
+ }
423
+ resolve(request) {
424
+ for (const route of this.routes) {
425
+ if (route.test(request)) {
426
+ return route;
427
+ }
428
+ }
429
+ return void 0;
430
+ }
431
+ resolveMultiple(request) {
432
+ const rc = [];
433
+ const url = new URL(request.url || "/", "http://localhost");
434
+ for (const route of this.routes) {
435
+ if (route.testPath(url.pathname)) {
436
+ rc.push(route);
437
+ }
438
+ }
439
+ return rc;
440
+ }
441
+ getCompiledRoute(request, response) {
442
+ const route = this.resolve(request);
443
+ if (!route) {
444
+ return void 0;
445
+ }
446
+ const match = route.match(request);
447
+ if (!match) {
448
+ return void 0;
449
+ }
450
+ request.params = match.params;
451
+ return new CompiledRoute(route, request, response, this.middlewares);
452
+ }
453
+ };
454
+
455
+ // src/facades.mts
456
+ var import_neko_scheduler = require("@devbro/neko-scheduler");
457
+ var import_neko_helper = require("@devbro/neko-helper");
458
+ var import_neko_context2 = require("@devbro/neko-context");
459
+ var import_neko_storage = require("@devbro/neko-storage");
460
+ var import_neko_mailer2 = require("@devbro/neko-mailer");
461
+ var import_neko_config = require("@devbro/neko-config");
462
+ var import_clipanion = require("clipanion");
463
+
464
+ // src/http.mts
465
+ var http_exports = {};
466
+ __reExport(http_exports, require("@devbro/neko-http"));
467
+
468
+ // src/facades.mts
469
+ var yup = __toESM(require("yup"), 1);
470
+ var import_neko_logger = require("@devbro/neko-logger");
471
+
472
+ // src/factories.mts
473
+ var import_neko_mailer = require("@devbro/neko-mailer");
474
+ var import_neko_queue = require("@devbro/neko-queue");
475
+ var import_neko_queue2 = require("@devbro/neko-queue");
476
+
477
+ // src/queue.mts
478
+ var queue_exports = {};
479
+ __export(queue_exports, {
480
+ DatabaseTransport: () => DatabaseTransport
481
+ });
482
+ __reExport(queue_exports, require("@devbro/neko-queue"));
483
+ var import_neko_sql = require("@devbro/neko-sql");
484
+ var DatabaseTransport = class {
485
+ // default to 100 messages per fetch
486
+ constructor(db_config) {
487
+ this.db_config = db_config;
488
+ }
489
+ static {
490
+ __name(this, "DatabaseTransport");
491
+ }
492
+ listenInterval = 6e4;
493
+ // default to 1 minute
494
+ messageLimit = 100;
495
+ setListenInterval(interval) {
496
+ this.listenInterval = interval;
497
+ }
498
+ setMessageLimit(limit) {
499
+ this.messageLimit = limit;
500
+ }
501
+ async dispatch(channel, message) {
502
+ const conn = new import_neko_sql.PostgresqlConnection(this.db_config);
503
+ try {
504
+ await conn.connect();
505
+ let q = conn.getQuery();
506
+ await q.table("queue_messages").insert({
507
+ channel,
508
+ message,
509
+ processed: false,
510
+ created_at: /* @__PURE__ */ new Date(),
511
+ updated_at: /* @__PURE__ */ new Date(),
512
+ last_tried_at: null,
513
+ process_message: ""
514
+ });
515
+ } finally {
516
+ await conn.disconnect();
517
+ }
518
+ }
519
+ async listen(channel, callback) {
520
+ return new Promise(async (resolve, reject) => {
521
+ setInterval(async () => {
522
+ const conn = new import_neko_sql.PostgresqlConnection(this.db_config);
523
+ try {
524
+ await conn.connect();
525
+ let q = conn.getQuery();
526
+ let messages = await q.table("queue_messages").whereOp("channel", "=", channel).whereOp("processed", "=", false).limit(this.messageLimit).orderBy("last_tried_at", "asc").get();
527
+ for (let msg of messages) {
528
+ try {
529
+ await callback(msg.message);
530
+ await q.table("queue_messages").whereOp("id", "=", msg.id).update({
531
+ processed: true,
532
+ updated_at: /* @__PURE__ */ new Date()
533
+ });
534
+ } catch (error) {
535
+ await q.table("queue_messages").whereOp("id", "=", msg.id).update({
536
+ processed: false,
537
+ last_tried_at: /* @__PURE__ */ new Date(),
538
+ process_message: error.message || "Error processing message"
539
+ });
540
+ }
541
+ }
542
+ } finally {
543
+ await conn.disconnect();
544
+ }
545
+ }, this.listenInterval);
546
+ });
547
+ }
548
+ };
549
+
550
+ // src/factories.mts
551
+ var FlexibleFactory = class {
552
+ static {
553
+ __name(this, "FlexibleFactory");
554
+ }
555
+ registry = /* @__PURE__ */ new Map();
556
+ register(key, ctor) {
557
+ this.registry.set(key, ctor);
558
+ }
559
+ create(key, ...args) {
560
+ const ctor = this.registry.get(key);
561
+ if (!ctor) {
562
+ throw new Error(`No factory registered for key: ${key}`);
563
+ }
564
+ return new ctor(...args);
565
+ }
566
+ };
567
+ var MailerFactory = class _MailerFactory {
568
+ static {
569
+ __name(this, "MailerFactory");
570
+ }
571
+ static instance = new FlexibleFactory();
572
+ static register(key, factory) {
573
+ _MailerFactory.instance.register(key, factory);
574
+ }
575
+ static create(key, ...args) {
576
+ return _MailerFactory.instance.create(key, ...args);
577
+ }
578
+ };
579
+ MailerFactory.register("logger", (opt) => {
580
+ return new import_neko_mailer.FunctionProvider((mail) => {
581
+ logger().info({
582
+ msg: "Sending email",
583
+ mail
584
+ });
585
+ });
586
+ });
587
+ MailerFactory.register("SES", (opt) => {
588
+ return new import_neko_mailer.SESProvider(opt);
589
+ });
590
+ MailerFactory.register("SMTP", (opt) => {
591
+ return new import_neko_mailer.SMTPProvider(opt);
592
+ });
593
+ MailerFactory.register("MEMORY", (opt) => {
594
+ return new import_neko_mailer.MemoryProvider();
595
+ });
596
+ var QueueFactory = class _QueueFactory {
597
+ static {
598
+ __name(this, "QueueFactory");
599
+ }
600
+ static instance = new FlexibleFactory();
601
+ static register(key, factory) {
602
+ _QueueFactory.instance.register(key, factory);
603
+ }
604
+ static create(key, ...args) {
605
+ return _QueueFactory.instance.create(key, ...args);
606
+ }
607
+ };
608
+ QueueFactory.register("database", (opt) => {
609
+ let transport = new DatabaseTransport(opt);
610
+ return new import_neko_queue.QueueConnection(transport);
611
+ });
612
+ QueueFactory.register("memory", (opt) => {
613
+ let transport = new import_neko_queue2.MemoryTransport(opt);
614
+ return new import_neko_queue.QueueConnection(transport);
615
+ });
616
+
617
+ // src/facades.mts
618
+ var router = (0, import_neko_helper.createSingleton)(() => new Router());
619
+ var scheduler = (0, import_neko_helper.createSingleton)(() => {
620
+ const rc = new import_neko_scheduler.Scheduler();
621
+ rc.setErrorHandler((err, job) => {
622
+ logger().error({
623
+ msg: "Scheduled job error",
624
+ err,
625
+ job_name: job.getName()
626
+ });
627
+ });
628
+ return rc;
629
+ });
630
+ var storage = (0, import_neko_helper.createSingleton)(
631
+ (label = "default") => import_neko_storage.StorageFactory.create(import_neko_config.config.get(["storages", label].join(".")))
632
+ );
633
+ var cli = (0, import_neko_helper.createSingleton)(() => {
634
+ const [node, app, ...args] = process.argv;
635
+ return new import_clipanion.Cli({
636
+ binaryLabel: `My Application`,
637
+ binaryName: `${node} ${app}`,
638
+ binaryVersion: `1.0.0`
639
+ });
640
+ });
641
+ var httpServer = (0, import_neko_helper.createSingleton)(() => {
642
+ const server = new http_exports.HttpServer();
643
+ server.setErrorHandler(async (err, req, res) => {
644
+ if (err instanceof http_exports.HttpError) {
645
+ res.writeHead(err.statusCode, { "Content-Type": "application/json" });
646
+ res.end(JSON.stringify({ message: err.message, error: err.code }));
647
+ logger().warn({ msg: "HttpError: " + err.message, err });
648
+ return;
649
+ } else if (err instanceof yup.ValidationError) {
650
+ res.writeHead(422, { "Content-Type": "application/json" });
651
+ const errs = {};
652
+ err.inner.forEach((e) => {
653
+ const sanitizedParams = { ...e.params };
654
+ if (/passw/i.test(e.path)) {
655
+ sanitizedParams.value = "******";
656
+ sanitizedParams.originalValue = "******";
657
+ }
658
+ errs[e.path] = {
659
+ type: e.type,
660
+ message: e.message,
661
+ params: sanitizedParams
662
+ };
663
+ });
664
+ res.end(JSON.stringify({ message: "validation error", errors: errs }));
665
+ logger().warn({ msg: "ValidationError: " + err.message, err });
666
+ return;
667
+ } else {
668
+ logger().error({ msg: "Error: " + err.message, err });
669
+ }
670
+ res.writeHead(500, { "Content-Type": "" });
671
+ res.end(JSON.stringify({ error: "Internal Server Error" }));
672
+ });
673
+ server.setRouter(router());
674
+ return server;
675
+ });
676
+ var logger = (0, import_neko_helper.createSingleton)((label) => {
677
+ const logger_config = import_neko_config.config.get(["loggers", label].join("."));
678
+ const rc = new import_neko_logger.Logger(logger_config);
679
+ rc.setExtrasFunction((message) => {
680
+ message.requestId = (0, import_neko_context2.ctxSafe)()?.get("requestId") || "N/A";
681
+ return message;
682
+ });
683
+ return rc;
684
+ });
685
+ var mailer = (0, import_neko_helper.createSingleton)((label) => {
686
+ const mailer_config = import_neko_config.config.get(["mailer", label].join("."));
687
+ let provider = MailerFactory.create(
688
+ mailer_config.provider,
689
+ mailer_config.config
690
+ );
691
+ const rc = new import_neko_mailer2.Mailer(provider);
692
+ return rc;
693
+ });
694
+ var queue = (0, import_neko_helper.createSingleton)(async (label) => {
695
+ const queue_config = import_neko_config.config.get(["queues", label].join("."));
696
+ if (!queue_config) {
697
+ throw new Error(`Queue configuration for '${label}' not found`);
698
+ }
699
+ const rc = await QueueFactory.create(queue_config.type, queue_config);
700
+ return rc;
701
+ });
702
+
703
+ // src/app/console/queue/GenerateMigrateCommand.mts
704
+ var import_clipanion2 = require("clipanion");
705
+ var import_change_case_all = require("change-case-all");
706
+ var import_path2 = __toESM(require("path"), 1);
707
+ var fs = __toESM(require("fs/promises"), 1);
708
+ var import_neko_config2 = require("@devbro/neko-config");
709
+ var import_handlebars = __toESM(require("handlebars"), 1);
710
+ var import_url = require("url");
711
+ var import_meta = {};
712
+ var GenerateMigrateCommand = class extends import_clipanion2.Command {
713
+ static {
714
+ __name(this, "GenerateMigrateCommand");
715
+ }
716
+ static paths = [[`generate`, `queue`, "migration"]];
717
+ name = import_clipanion2.Option.String({ required: true });
718
+ async execute() {
719
+ const date = /* @__PURE__ */ new Date();
720
+ const year = date.getFullYear();
721
+ const month = String(date.getMonth() + 1).padStart(2, "0");
722
+ const day = String(date.getDate()).padStart(2, "0");
723
+ const secondsOfDay = String(
724
+ date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()
725
+ ).padStart(5, "0");
726
+ const fixed_name = "queue_messages";
727
+ const filename = `${year}_${month}_${day}_${secondsOfDay}_${fixed_name}.ts`;
728
+ this.context.stdout.write(`creating migration file ${filename}
729
+ `);
730
+ await fs.mkdir(import_neko_config2.config.get("migration.path"), { recursive: true });
731
+ let dirname = typeof __dirname === "string" ? __dirname : void 0;
732
+ if (!dirname) {
733
+ dirname = import_path2.default.dirname((0, import_url.fileURLToPath)(import_meta.url));
734
+ }
735
+ const compiledTemplate = import_handlebars.default.compile(
736
+ (await fs.readFile(import_path2.default.join(dirname, "./queue_migration.tpl"))).toString()
737
+ );
738
+ const template = await compiledTemplate({
739
+ className: import_change_case_all.Case.pascal(this.name) + "Migration",
740
+ tableName: import_change_case_all.Case.snake(this.name)
741
+ });
742
+ await fs.writeFile(
743
+ import_path2.default.join(import_neko_config2.config.get("migration.path"), filename),
744
+ template
745
+ );
746
+ }
747
+ };
748
+ cli().register(GenerateMigrateCommand);
749
+ // Annotate the CommonJS export names for ESM import in node:
750
+ 0 && (module.exports = {
751
+ GenerateMigrateCommand
752
+ });