@akanjs/document 0.0.38 → 0.0.40

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/index.js CHANGED
@@ -1,2062 +1,21 @@
1
- (() => {
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 __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
- }) : x)(function(x) {
11
- if (typeof require !== "undefined")
12
- return require.apply(this, arguments);
13
- throw Error('Dynamic require of "' + x + '" is not supported');
14
- });
15
- var __copyProps = (to, from, except, desc) => {
16
- if (from && typeof from === "object" || typeof from === "function") {
17
- for (let key of __getOwnPropNames(from))
18
- if (!__hasOwnProp.call(to, key) && key !== except)
19
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
- }
21
- return to;
22
- };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
- var __decorateClass = (decorators, target, key, kind) => {
32
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
33
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
34
- if (decorator = decorators[i])
35
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
36
- if (kind && result)
37
- __defProp(target, key, result);
38
- return result;
39
- };
40
- var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
41
- var __accessCheck = (obj, member, msg) => {
42
- if (!member.has(obj))
43
- throw TypeError("Cannot " + msg);
44
- };
45
- var __privateGet = (obj, member, getter) => {
46
- __accessCheck(obj, member, "read from private field");
47
- return getter ? getter.call(obj) : member.get(obj);
48
- };
49
- var __privateAdd = (obj, member, value) => {
50
- if (member.has(obj))
51
- throw TypeError("Cannot add the same private member more than once");
52
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
53
- };
54
- var __privateMethod = (obj, member, method) => {
55
- __accessCheck(obj, member, "access private method");
56
- return method;
57
- };
58
-
59
- // pkgs/@akanjs/constant/src/types.ts
60
- var DEFAULT_PAGE_SIZE = 20;
61
-
62
- // pkgs/@akanjs/base/src/base.ts
63
- var version = "0.9.0";
64
- var logo = `
65
- _ _ _
66
- / \\ | | ____ _ _ __ (_)___
67
- / _ \\ | |/ / _' | '_ \\ | / __|
68
- / ___ \\| < (_| | | | |_ | \\__ \\
69
- /_/ \\_\\_|\\_\\__,_|_| |_(_)/ |___/
70
- |__/ ver ${version}
71
- ? See more details on docs https://www.akanjs.com/docs
72
- \u2605 Star Akanjs on GitHub https://github.com/aka-bassman/akanjs
73
-
74
- `;
75
-
76
- // pkgs/@akanjs/base/src/baseEnv.ts
77
- var appName = process.env.NEXT_PUBLIC_APP_NAME ?? "unknown";
78
- var repoName = process.env.NEXT_PUBLIC_REPO_NAME ?? "unknown";
79
- var serveDomain = process.env.NEXT_PUBLIC_SERVE_DOMAIN ?? "unknown";
80
- if (appName === "unknown")
81
- throw new Error("environment variable NEXT_PUBLIC_APP_NAME is required");
82
- if (repoName === "unknown")
83
- throw new Error("environment variable NEXT_PUBLIC_REPO_NAME is required");
84
- if (serveDomain === "unknown")
85
- throw new Error("environment variable NEXT_PUBLIC_SERVE_DOMAIN is required");
86
- var environment = process.env.NEXT_PUBLIC_ENV ?? "debug";
87
- var operationType = typeof window !== "undefined" ? "client" : process.env.NEXT_RUNTIME ? "client" : "server";
88
- var operationMode = process.env.NEXT_PUBLIC_OPERATION_MODE ?? "cloud";
89
- var networkType = process.env.NEXT_PUBLIC_NETWORK_TYPE ?? (environment === "main" ? "mainnet" : environment === "develop" ? "testnet" : "debugnet");
90
- var tunnelUsername = process.env.SSU_TUNNEL_USERNAME ?? "root";
91
- var tunnelPassword = process.env.SSU_TUNNEL_PASSWORD ?? repoName;
92
- var baseEnv = {
93
- repoName,
94
- serveDomain,
95
- appName,
96
- environment,
97
- operationType,
98
- operationMode,
99
- networkType,
100
- tunnelUsername,
101
- tunnelPassword
102
- };
103
- var side = typeof window === "undefined" ? "server" : "client";
104
- var renderMode = process.env.RENDER_ENV ?? "ssr";
105
- var clientHost = process.env.NEXT_PUBLIC_CLIENT_HOST ?? (operationMode === "local" || side === "server" ? "localhost" : window.location.hostname);
106
- var clientPort = parseInt(
107
- process.env.NEXT_PUBLIC_CLIENT_PORT ?? (operationMode === "local" ? renderMode === "ssr" ? "4200" : "4201" : "443")
108
- );
109
- var clientHttpProtocol = side === "client" ? window.location.protocol : clientHost === "localhost" ? "http:" : "https:";
110
- var clientHttpUri = `${clientHttpProtocol}//${clientHost}${clientPort === 443 ? "" : `:${clientPort}`}`;
111
- var serverHost = process.env.SERVER_HOST ?? (operationMode === "local" ? typeof window === "undefined" ? "localhost" : window.location.host.split(":")[0] : renderMode === "csr" ? `${appName}-${environment}.${serveDomain}` : side === "client" ? window.location.host.split(":")[0] : operationMode === "cloud" ? `backend-svc.${appName}-${environment}.svc.cluster.local` : "localhost");
112
- var serverPort = parseInt(
113
- process.env.SERVER_PORT ?? (operationMode === "local" || side === "server" ? "8080" : "443")
114
- );
115
- var serverHttpProtocol = side === "client" ? window.location.protocol : "http:";
116
- var serverHttpUri = `${serverHttpProtocol}//${serverHost}${serverPort === 443 ? "" : `:${serverPort}`}/backend`;
117
- var serverGraphqlUri = `${serverHttpUri}/graphql`;
118
- var serverWsProtocol = serverHttpProtocol === "http:" ? "ws:" : "wss:";
119
- var serverWsUri = `${serverWsProtocol}//${serverHost}${serverPort === 443 ? "" : `:${serverPort}`}`;
120
- var baseClientEnv = {
121
- ...baseEnv,
122
- side,
123
- renderMode,
124
- websocket: true,
125
- clientHost,
126
- clientPort,
127
- clientHttpProtocol,
128
- clientHttpUri,
129
- serverHost,
130
- serverPort,
131
- serverHttpProtocol,
132
- serverHttpUri,
133
- serverGraphqlUri,
134
- serverWsProtocol,
135
- serverWsUri
136
- };
137
-
138
- // pkgs/@akanjs/base/src/scalar.ts
139
- var import_dayjs = __toESM(__require("dayjs"));
140
- var dayjs = import_dayjs.default;
141
- var Int = class {
142
- __Scalar__;
143
- };
144
- var Upload = class {
145
- __Scalar__;
146
- filename;
147
- mimetype;
148
- encoding;
149
- createReadStream;
150
- };
151
- var Float = class {
152
- __Scalar__;
153
- };
154
- var ID = class {
155
- __Scalar__;
156
- };
157
- var JSON2 = class {
158
- __Scalar__;
159
- };
160
- var getNonArrayModel = (arraiedModel2) => {
161
- let arrDepth = 0;
162
- let target = arraiedModel2;
163
- while (Array.isArray(target)) {
164
- target = target[0];
165
- arrDepth++;
166
- }
167
- return [target, arrDepth];
168
- };
169
- var scalarSet = /* @__PURE__ */ new Set([String, Boolean, Date, ID, Int, Float, Upload, JSON2, Map]);
170
- var scalarNameMap = /* @__PURE__ */ new Map([
171
- [ID, "ID"],
172
- [Int, "Int"],
173
- [Float, "Float"],
174
- [String, "String"],
175
- [Boolean, "Boolean"],
176
- [Date, "Date"],
177
- [Upload, "Upload"],
178
- [JSON2, "JSON"],
179
- [Map, "Map"]
180
- ]);
181
- var scalarArgMap = /* @__PURE__ */ new Map([
182
- [ID, null],
183
- [String, ""],
184
- [Boolean, false],
185
- [Date, dayjs(/* @__PURE__ */ new Date(-1))],
186
- [Int, 0],
187
- [Float, 0],
188
- [JSON2, {}],
189
- [Map, {}]
190
- ]);
191
- var scalarDefaultMap = /* @__PURE__ */ new Map([
192
- [ID, null],
193
- [String, ""],
194
- [Boolean, false],
195
- [Date, dayjs(/* @__PURE__ */ new Date(-1))],
196
- [Int, 0],
197
- [Float, 0],
198
- [JSON2, {}]
199
- ]);
200
- var isGqlScalar = (modelRef) => scalarSet.has(modelRef);
201
- var isGqlMap = (modelRef) => modelRef === Map;
202
-
203
- // pkgs/@akanjs/constant/src/scalar.ts
204
- var import_reflect_metadata = __require("reflect-metadata");
205
- var scalarExampleMap = /* @__PURE__ */ new Map([
206
- [ID, "1234567890abcdef12345678"],
207
- [Int, 0],
208
- [Float, 0],
209
- [String, "String"],
210
- [Boolean, true],
211
- [Date, (/* @__PURE__ */ new Date()).toISOString()],
212
- [Upload, "FileUpload"],
213
- [JSON2, {}],
214
- [Map, {}]
215
- ]);
216
- var getClassMeta = (modelRef) => {
217
- const [target] = getNonArrayModel(modelRef);
218
- const classMeta = Reflect.getMetadata("class", target.prototype);
219
- if (!classMeta)
220
- throw new Error(`No ClassMeta for this target ${target.name}`);
221
- return classMeta;
222
- };
223
- var getFieldMetas = (modelRef) => {
224
- const [target] = getNonArrayModel(modelRef);
225
- const metadataMap = Reflect.getMetadata("fields", target.prototype) ?? /* @__PURE__ */ new Map();
226
- const keySortMap = { id: -1, createdAt: 1, updatedAt: 2, removedAt: 3 };
227
- return [...metadataMap.values()].sort((a, b) => (keySortMap[a.key] ?? 0) - (keySortMap[b.key] ?? 0));
228
- };
229
- var getFieldMetaMap = (modelRef) => {
230
- const [target] = getNonArrayModel(modelRef);
231
- const metadataMap = Reflect.getMetadata("fields", target.prototype) ?? /* @__PURE__ */ new Map();
232
- return new Map(metadataMap);
233
- };
234
- var setFieldMetaMap = (modelRef, metadataMap) => {
235
- const [target] = getNonArrayModel(modelRef);
236
- Reflect.defineMetadata("fields", new Map(metadataMap), target.prototype);
237
- };
238
- var getFieldMetaMapOnPrototype = (prototype) => {
239
- const metadataMap = Reflect.getMetadata("fields", prototype) ?? /* @__PURE__ */ new Map();
240
- return new Map(metadataMap);
241
- };
242
- var setFieldMetaMapOnPrototype = (prototype, metadataMap) => {
243
- Reflect.defineMetadata("fields", new Map(metadataMap), prototype);
244
- };
245
-
246
- // pkgs/@akanjs/constant/src/fieldMeta.ts
247
- var applyFieldMeta = (modelRef, arrDepth, option, optionArrDepth) => {
248
- const isArray = arrDepth > 0;
249
- const isClass = !isGqlScalar(modelRef);
250
- const isMap = isGqlMap(modelRef);
251
- const { refName, type } = isClass ? getClassMeta(modelRef) : { refName: "", type: "scalar" };
252
- const name = isClass ? refName : scalarNameMap.get(modelRef) ?? "Unknown";
253
- if (isMap && !option.of)
254
- throw new Error("Map type must have 'of' option");
255
- return (prototype, key) => {
256
- const metadata = {
257
- nullable: option.nullable ?? false,
258
- ref: option.ref,
259
- refPath: option.refPath,
260
- refType: option.refType,
261
- default: option.default ?? (isArray ? [] : null),
262
- type: option.type,
263
- fieldType: option.fieldType ?? "property",
264
- immutable: option.immutable ?? false,
265
- min: option.min,
266
- max: option.max,
267
- enum: option.enum,
268
- select: option.select ?? true,
269
- minlength: option.minlength,
270
- maxlength: option.maxlength,
271
- query: option.query,
272
- accumulate: option.accumulate,
273
- example: option.example,
274
- validate: option.validate,
275
- key,
276
- name,
277
- isClass,
278
- isScalar: type === "scalar",
279
- modelRef,
280
- arrDepth,
281
- isArray,
282
- optArrDepth: optionArrDepth,
283
- isMap,
284
- of: option.of,
285
- text: option.text
286
- };
287
- const metadataMap = getFieldMetaMapOnPrototype(prototype);
288
- metadataMap.set(key, metadata);
289
- setFieldMetaMapOnPrototype(prototype, metadataMap);
290
- };
291
- };
292
- var makeField = (customOption) => (returns, fieldOption) => {
293
- const [modelRef, arrDepth] = getNonArrayModel(returns());
294
- if (!fieldOption)
295
- return applyFieldMeta(modelRef, arrDepth, { ...customOption }, arrDepth);
296
- const [opt, optArrDepth] = getNonArrayModel(fieldOption);
297
- return applyFieldMeta(modelRef, arrDepth, { ...opt, ...customOption }, optArrDepth);
298
- };
299
- var Field = {
300
- Prop: makeField({ fieldType: "property" }),
301
- Hidden: makeField({ fieldType: "hidden", nullable: true }),
302
- Secret: makeField({ fieldType: "hidden", select: false, nullable: true }),
303
- Resolve: makeField({ fieldType: "resolve" })
304
- };
305
-
306
- // pkgs/@akanjs/constant/src/constantDecorator.ts
307
- var import_reflect_metadata2 = __require("reflect-metadata");
308
-
309
- // pkgs/@akanjs/constant/src/filterMeta.ts
310
- var getFilterMeta = (filterRef) => {
311
- const filterMeta = Reflect.getMetadata("filter", filterRef.prototype);
312
- if (!filterMeta)
313
- throw new Error("filterMeta is not defined");
314
- return filterMeta;
315
- };
316
- var setFilterMeta = (filterRef, filterMeta) => {
317
- const existingFilterMeta = Reflect.getMetadata("filter", filterRef.prototype);
318
- if (existingFilterMeta)
319
- Object.assign(filterMeta.sort, existingFilterMeta.sort);
320
- Reflect.defineMetadata("filter", filterMeta, filterRef.prototype);
321
- };
322
- var getFilterKeyMetaMapOnPrototype = (prototype) => {
323
- const metadataMap = Reflect.getMetadata("filterKey", prototype) ?? /* @__PURE__ */ new Map();
324
- return new Map(metadataMap);
325
- };
326
- var setFilterKeyMetaMapOnPrototype = (prototype, metadataMap) => {
327
- Reflect.defineMetadata("filterKey", new Map(metadataMap), prototype);
328
- };
329
- var applyFilterKeyMeta = (option) => {
330
- return (prototype, key, descriptor) => {
331
- const metadata = { key, ...option, descriptor };
332
- const metadataMap = getFilterKeyMetaMapOnPrototype(prototype);
333
- metadataMap.set(key, metadata);
334
- setFilterKeyMetaMapOnPrototype(prototype, metadataMap);
335
- };
336
- };
337
- var makeFilter = (customOption) => (fieldOption) => {
338
- return applyFilterKeyMeta({ ...customOption, ...fieldOption });
339
- };
340
- var getFilterArgMetasOnPrototype = (prototype, key) => {
341
- const filterArgMetas = Reflect.getMetadata("filterArg", prototype, key) ?? [];
342
- return filterArgMetas;
343
- };
344
- var setFilterArgMetasOnPrototype = (prototype, key, filterArgMetas) => {
345
- Reflect.defineMetadata("filterArg", filterArgMetas, prototype, key);
346
- };
347
- var applyFilterArgMeta = (name, returns, argOption) => {
348
- return (prototype, key, idx) => {
349
- const [modelRef, arrDepth] = getNonArrayModel(returns());
350
- const [opt, optArrDepth] = getNonArrayModel(argOption ?? {});
351
- const filterArgMeta = { name, ...opt, modelRef, arrDepth, isArray: arrDepth > 0, optArrDepth };
352
- const filterArgMetas = getFilterArgMetasOnPrototype(prototype, key);
353
- filterArgMetas[idx] = filterArgMeta;
354
- setFilterArgMetasOnPrototype(prototype, key, filterArgMetas);
355
- };
356
- };
357
- var getFilterQuery = (filterRef, key) => {
358
- const filterKeyMetaMap = getFilterKeyMetaMapOnPrototype(filterRef.prototype);
359
- const filterKeyMeta = filterKeyMetaMap.get(key);
360
- if (!filterKeyMeta?.descriptor.value)
361
- throw new Error(`filterKeyMeta is not defined for key: ${key}`);
362
- return filterKeyMeta.descriptor.value;
363
- };
364
- var getFilterSort = (filterRef, key) => {
365
- const filterMeta = getFilterMeta(filterRef);
366
- const sort = filterMeta.sort[key];
367
- return sort;
368
- };
369
- var Filter = {
370
- Mongo: makeFilter({ type: "mongo" }),
371
- // Meili: makeFilter({ fieldType: "hidden", nullable: true }),
372
- Arg: applyFilterArgMeta
373
- };
374
-
375
- // pkgs/@akanjs/constant/src/baseGql.ts
376
- var import_reflect_metadata3 = __require("reflect-metadata");
377
-
378
- // pkgs/@akanjs/common/src/isDayjs.ts
379
- var import_dayjs2 = __require("dayjs");
380
-
381
- // pkgs/@akanjs/common/src/isQueryEqual.ts
382
- var import_dayjs3 = __toESM(__require("dayjs"));
383
-
384
- // pkgs/@akanjs/common/src/isValidDate.ts
385
- var import_dayjs4 = __toESM(__require("dayjs"));
386
- var import_customParseFormat = __toESM(__require("dayjs/plugin/customParseFormat"));
387
- import_dayjs4.default.extend(import_customParseFormat.default);
388
- var isValidDate = (d) => {
389
- const format = "YYYY-MM-DD";
390
- if (typeof d === "string") {
391
- return (0, import_dayjs4.default)(d, format).isValid();
392
- } else if ((0, import_dayjs2.isDayjs)(d))
393
- return d.isValid();
394
- else
395
- return d instanceof Date && !isNaN(d.getTime());
396
- };
397
-
398
- // pkgs/@akanjs/common/src/pluralize.ts
399
- var import_pluralize = __toESM(__require("pluralize"));
400
-
401
- // pkgs/@akanjs/common/src/capitalize.ts
402
- var capitalize = (str) => {
403
- return str.charAt(0).toUpperCase() + str.slice(1);
404
- };
405
-
406
- // pkgs/@akanjs/common/src/Logger.ts
407
- var import_dayjs5 = __toESM(__require("dayjs"));
408
- var logLevels = ["trace", "verbose", "debug", "log", "info", "warn", "error"];
409
- var clc = {
410
- bold: (text) => `\x1B[1m${text}\x1B[0m`,
411
- green: (text) => `\x1B[32m${text}\x1B[39m`,
412
- yellow: (text) => `\x1B[33m${text}\x1B[39m`,
413
- red: (text) => `\x1B[31m${text}\x1B[39m`,
414
- magentaBright: (text) => `\x1B[95m${text}\x1B[39m`,
415
- cyanBright: (text) => `\x1B[96m${text}\x1B[39m`
416
- };
417
- var colorizeMap = {
418
- trace: clc.bold,
419
- verbose: clc.cyanBright,
420
- debug: clc.magentaBright,
421
- log: clc.green,
422
- info: clc.green,
423
- warn: clc.yellow,
424
- error: clc.red
425
- };
426
- var Logger = class _Logger {
427
- static #ignoreCtxSet = /* @__PURE__ */ new Set([
428
- "InstanceLoader",
429
- "RoutesResolver",
430
- "RouterExplorer",
431
- "NestFactory",
432
- "WebSocketsController",
433
- "GraphQLModule",
434
- "NestApplication"
435
- ]);
436
- static level = process.env.NEXT_PUBLIC_LOG_LEVEL ?? "log";
437
- static #levelIdx = logLevels.findIndex((l) => l === process.env.NEXT_PUBLIC_LOG_LEVEL);
438
- static #startAt = (0, import_dayjs5.default)();
439
- static setLevel(level) {
440
- this.level = level;
441
- this.#levelIdx = logLevels.findIndex((l) => l === level);
442
- }
443
- name;
444
- constructor(name) {
445
- this.name = name;
446
- }
447
- trace(msg, context = "") {
448
- if (_Logger.#levelIdx <= 0)
449
- _Logger.#printMessages(this.name ?? "App", msg, context, "trace");
450
- }
451
- verbose(msg, context = "") {
452
- if (_Logger.#levelIdx <= 1)
453
- _Logger.#printMessages(this.name ?? "App", msg, context, "verbose");
454
- }
455
- debug(msg, context = "") {
456
- if (_Logger.#levelIdx <= 2)
457
- _Logger.#printMessages(this.name ?? "App", msg, context, "debug");
458
- }
459
- log(msg, context = "") {
460
- if (_Logger.#levelIdx <= 3)
461
- _Logger.#printMessages(this.name ?? "App", msg, context, "log");
462
- }
463
- info(msg, context = "") {
464
- if (_Logger.#levelIdx <= 4)
465
- _Logger.#printMessages(this.name ?? "App", msg, context, "info");
466
- }
467
- warn(msg, context = "") {
468
- if (_Logger.#levelIdx <= 5)
469
- _Logger.#printMessages(this.name ?? "App", msg, context, "warn");
470
- }
471
- error(msg, context = "") {
472
- if (_Logger.#levelIdx <= 6)
473
- _Logger.#printMessages(this.name ?? "App", msg, context, "error");
474
- }
475
- raw(msg, method) {
476
- _Logger.rawLog(msg, method);
477
- }
478
- rawLog(msg, method) {
479
- _Logger.rawLog(msg, method);
480
- }
481
- static trace(msg, context = "") {
482
- if (_Logger.#levelIdx <= 0)
483
- _Logger.#printMessages("App", msg, context, "trace");
484
- }
485
- static verbose(msg, context = "") {
486
- if (_Logger.#levelIdx <= 1)
487
- _Logger.#printMessages("App", msg, context, "verbose");
488
- }
489
- static debug(msg, context = "") {
490
- if (_Logger.#levelIdx <= 2)
491
- _Logger.#printMessages("App", msg, context, "debug");
492
- }
493
- static log(msg, context = "") {
494
- if (_Logger.#levelIdx <= 3)
495
- _Logger.#printMessages("App", msg, context, "log");
496
- }
497
- static info(msg, context = "") {
498
- if (_Logger.#levelIdx <= 4)
499
- _Logger.#printMessages("App", msg, context, "info");
500
- }
501
- static warn(msg, context = "") {
502
- if (_Logger.#levelIdx <= 5)
503
- _Logger.#printMessages("App", msg, context, "warn");
504
- }
505
- static error(msg, context = "") {
506
- if (_Logger.#levelIdx <= 6)
507
- _Logger.#printMessages("App", msg, context, "error");
508
- }
509
- static #colorize(msg, logLevel) {
510
- return colorizeMap[logLevel](msg);
511
- }
512
- static #printMessages(name, content, context, logLevel, writeStreamType = logLevel === "error" ? "stderr" : "stdout") {
513
- if (this.#ignoreCtxSet.has(context))
514
- return;
515
- const now = (0, import_dayjs5.default)();
516
- const processMsg = this.#colorize(
517
- `[${name ?? "App"}] ${global.process?.pid ?? "window"} -`,
518
- logLevel
519
- );
520
- const timestampMsg = now.format("MM/DD/YYYY, HH:mm:ss A");
521
- const logLevelMsg = this.#colorize(logLevel.toUpperCase().padStart(7, " "), logLevel);
522
- const contextMsg = context ? clc.yellow(`[${context}] `) : "";
523
- const contentMsg = this.#colorize(content, logLevel);
524
- const timeDiffMsg = clc.yellow(`+${now.diff(_Logger.#startAt, "ms")}ms`);
525
- if (typeof window === "undefined")
526
- process[writeStreamType].write(
527
- `${processMsg} ${timestampMsg} ${logLevelMsg} ${contextMsg} ${contentMsg} ${timeDiffMsg}
528
- `
529
- );
530
- else
531
- console.log(`${processMsg} ${timestampMsg} ${logLevelMsg} ${contextMsg} ${contentMsg} ${timeDiffMsg}
532
- `);
533
- }
534
- static rawLog(msg, method) {
535
- this.raw(`${msg}
536
- `, method);
537
- }
538
- static raw(msg, method) {
539
- if (typeof window === "undefined" && method !== "console" && global.process)
540
- global.process.stdout.write(msg);
541
- else
542
- console.log(msg);
543
- }
544
- };
545
-
546
- // pkgs/@akanjs/common/src/lowerlize.ts
547
- var lowerlize = (str) => {
548
- return str.charAt(0).toLowerCase() + str.slice(1);
549
- };
550
-
551
- // pkgs/@akanjs/common/src/sleep.ts
552
- var sleep = async (ms) => {
553
- return new Promise((resolve) => {
554
- setTimeout(() => {
555
- resolve(true);
556
- }, ms);
557
- });
558
- };
559
-
560
- // pkgs/@akanjs/constant/src/baseGql.ts
561
- var defaultFieldMeta = {
562
- fieldType: "property",
563
- immutable: false,
564
- select: true,
565
- isClass: false,
566
- isScalar: true,
567
- nullable: false,
568
- isArray: false,
569
- arrDepth: 0,
570
- optArrDepth: 0,
571
- default: null,
572
- isMap: false
573
- };
574
- var idFieldMeta = { ...defaultFieldMeta, key: "id", name: "ID", modelRef: ID };
575
- var createdAtFieldMeta = { ...defaultFieldMeta, key: "createdAt", name: "Date", modelRef: Date };
576
- var updatedAtFieldMeta = { ...defaultFieldMeta, key: "updatedAt", name: "Date", modelRef: Date };
577
- var removedAtFieldMeta = {
578
- ...defaultFieldMeta,
579
- key: "removedAt",
580
- name: "Date",
581
- modelRef: Date,
582
- nullable: true,
583
- default: null
584
- };
585
-
586
- // pkgs/@akanjs/constant/src/classMeta.ts
587
- var import_reflect_metadata4 = __require("reflect-metadata");
588
- var InputModelStorage = class {
589
- };
590
- var LightModelStorage = class {
591
- };
592
- var FullModelStorage = class {
593
- };
594
- var ScalarModelStorage = class {
595
- };
596
- var FilterModelStorage = class {
597
- };
598
- var hasTextField = (modelRef) => {
599
- const fieldMetas = getFieldMetas(modelRef);
600
- return fieldMetas.some(
601
- (fieldMeta) => !!fieldMeta.text || fieldMeta.isScalar && fieldMeta.isClass && fieldMeta.select && hasTextField(fieldMeta.modelRef)
602
- );
603
- };
604
- var applyClassMeta = (type, modelType, storage) => {
605
- return function(refName) {
606
- return function(target) {
607
- const modelRef = target;
608
- const classMeta = { refName, type, modelType, modelRef, hasTextField: hasTextField(modelRef) };
609
- Reflect.defineMetadata("class", classMeta, modelRef.prototype);
610
- Reflect.defineMetadata(refName, modelRef, storage.prototype);
611
- };
612
- };
613
- };
614
- var applyFilterMeta = (storage) => {
615
- return function(refName) {
616
- return function(target) {
617
- const modelRef = target;
618
- setFilterMeta(modelRef, { refName, sort: {} });
619
- Reflect.defineMetadata(refName, modelRef, storage.prototype);
620
- };
621
- };
622
- };
623
- var Model = {
624
- Light: applyClassMeta("light", "data", LightModelStorage),
625
- Object: applyClassMeta("full", "ephemeral", FullModelStorage),
626
- Full: applyClassMeta("full", "data", FullModelStorage),
627
- Input: applyClassMeta("input", "data", InputModelStorage),
628
- Scalar: applyClassMeta("scalar", "data", ScalarModelStorage),
629
- Summary: applyClassMeta("scalar", "summary", ScalarModelStorage),
630
- Insight: applyClassMeta("scalar", "insight", ScalarModelStorage),
631
- Filter: applyFilterMeta(FilterModelStorage)
632
- };
633
-
634
- // pkgs/@akanjs/document/src/dbDecorators.ts
635
- var dbOf = (refName, Input, Doc, Model3, Middleware, Obj, Insight, Filter2, Summary) => {
636
- return { refName, Input, Doc, Model: Model3, Middleware, Obj, Insight, Filter: Filter2, Summary };
637
- };
638
- var InputDatabaseStorage = class {
639
- };
640
- var DocumentDatabaseStorage = class {
641
- };
642
- var ModelDatabaseStorage = class {
643
- };
644
- var MiddlewareDatabaseStorage = class {
645
- };
646
- var getAllDatabaseModelNames = () => {
647
- const modelNames = Reflect.getMetadataKeys(ModelDatabaseStorage.prototype) ?? [];
648
- return modelNames;
649
- };
650
- var Database = {
651
- Input: (returns) => {
652
- return function(target) {
653
- const modelRef = returns();
654
- const classMeta = getClassMeta(modelRef);
655
- Reflect.defineMetadata(classMeta.refName, target, InputDatabaseStorage.prototype);
656
- };
657
- },
658
- Document: (returns) => {
659
- return function(target) {
660
- const modelRef = returns();
661
- const classMeta = getClassMeta(modelRef);
662
- Reflect.defineMetadata(classMeta.refName, target, DocumentDatabaseStorage.prototype);
663
- };
664
- },
665
- Model: (returns) => {
666
- return function(target) {
667
- const modelRef = returns();
668
- const classMeta = getClassMeta(modelRef);
669
- Reflect.defineMetadata(classMeta.refName, target, ModelDatabaseStorage.prototype);
670
- };
671
- },
672
- Middleware: (returns) => {
673
- return function(target) {
674
- const modelRef = returns();
675
- const classMeta = getClassMeta(modelRef);
676
- Reflect.defineMetadata(classMeta.refName, target, MiddlewareDatabaseStorage.prototype);
677
- };
678
- }
679
- };
680
- var Model2 = (docRef, cnst) => {
681
- class DefaultModel {
682
- }
683
- return DefaultModel;
684
- };
685
- var into = Model2;
686
- var AddModel = (modelRef, cnst) => {
687
- return modelRef;
688
- };
689
- var inside = AddModel;
690
- var by = (modelRef, addRef) => {
691
- if (!addRef)
692
- return InputOrDocument(modelRef);
693
- return AddInputOrDocument(modelRef, addRef);
694
- };
695
- var InputOrDocument = (inputRef) => {
696
- return inputRef;
697
- };
698
- var AddInputOrDocument = (modelRef, addRef) => {
699
- const fieldMetaMap = getFieldMetaMap(modelRef);
700
- const addFieldMetas = getFieldMetaMap(addRef);
701
- setFieldMetaMap(modelRef, new Map([...fieldMetaMap, ...addFieldMetas]));
702
- return modelRef;
703
- };
704
- var beyond = (model, doc) => {
705
- return class Middleware {
706
- onSchema(schema) {
707
- }
708
- };
709
- };
710
-
711
- // pkgs/@akanjs/document/src/schema.ts
712
- var import_mongoose = __require("mongoose");
713
- var getDefaultSchemaOptions = () => ({
714
- toJSON: { getters: false, virtuals: true },
715
- toObject: { getters: false, virtuals: true },
716
- _id: true,
717
- id: true,
718
- timestamps: true,
719
- methods: {
720
- refresh: async function() {
721
- Object.assign(this, await this.constructor.findById(this._id));
722
- return this;
723
- }
724
- },
725
- statics: {
726
- pickOne: async function(query, projection) {
727
- const doc = await this.findOne(query, projection);
728
- if (!doc)
729
- throw new Error("No Document");
730
- return doc;
731
- },
732
- pickById: async function(docId, projection) {
733
- if (!docId)
734
- throw new Error("No Document ID");
735
- const doc = await this.findById(docId, projection);
736
- if (!doc)
737
- throw new Error("No Document");
738
- return doc;
739
- },
740
- sample: async function(query, size = 1, aggregations = []) {
741
- const objs = await this.aggregate([
742
- { $match: convertAggregateMatch(query) },
743
- { $sample: { size } },
744
- ...aggregations
745
- ]);
746
- return objs.map((obj) => new this(obj));
747
- },
748
- sampleOne: async function(query, aggregations = []) {
749
- const obj = await this.aggregate([
750
- { $match: convertAggregateMatch(query) },
751
- { $sample: { size: 1 } },
752
- ...aggregations
753
- ]);
754
- return obj.length ? new this(obj[0]) : null;
755
- },
756
- addSummary: async function(prefix = "total", num = 1) {
757
- const update = Array.isArray(prefix) ? {
758
- $inc: {
759
- ...prefix.reduce((acc, cur) => ({ ...acc, [`${cur}${this.modelName}`]: num }), {})
760
- }
761
- } : { $inc: { [`${prefix}${this.modelName}`]: num } };
762
- await this.db.collection("summaries").updateOne({ status: "active" }, update);
763
- },
764
- moveSummary: async function(prev, next, num = 1) {
765
- await this.db.collection("summaries").updateOne(
766
- { status: "active" },
767
- {
768
- $inc: {
769
- [`${prev}${this.modelName}`]: -num,
770
- [`${next}${this.modelName}`]: num
771
- }
772
- }
773
- );
774
- },
775
- subSummary: async function(prefix = "total", num = 1) {
776
- const update = Array.isArray(prefix) ? {
777
- $inc: {
778
- ...prefix.reduce((acc, cur) => ({ ...acc, [`${cur}${this.modelName}`]: -num }), {})
779
- }
780
- } : { $inc: { [`${prefix}${this.modelName}`]: -num } };
781
- await this.db.collection("summaries").updateOne({ status: "active" }, update);
782
- }
783
- }
784
- });
785
- var convertOperatorValue = (value) => {
786
- if (Array.isArray(value))
787
- return value.map((v) => convertOperatorValue(v));
788
- else if (!value)
789
- return value;
790
- else if ((0, import_mongoose.isValidObjectId)(value))
791
- return new import_mongoose.Types.ObjectId(value);
792
- else if (isValidDate(value))
793
- return dayjs(value).toDate();
794
- else if (value.constructor !== Object)
795
- return value;
796
- else if (typeof value !== "object")
797
- return value;
798
- else
799
- return Object.fromEntries(
800
- Object.entries(value).map(([key, value2]) => [key, convertOperatorValue(value2)])
801
- );
802
- };
803
- var convertAggregateMatch = (query) => {
804
- return Object.fromEntries(
805
- Object.entries(query).map(([key, value]) => {
806
- return [key, convertOperatorValue(value)];
807
- })
808
- );
809
- };
810
-
811
- // pkgs/@akanjs/signal/src/client.ts
812
- var import_core = __require("@urql/core");
813
- var import_socket = __require("socket.io-client");
814
- var SocketIo = class {
815
- socket;
816
- roomSubscribeMap = /* @__PURE__ */ new Map();
817
- constructor(uri) {
818
- this.socket = (0, import_socket.io)(uri, { transports: ["websocket"] });
819
- this.socket.on("connect", () => {
820
- this.roomSubscribeMap.forEach((option) => {
821
- this.socket.emit(option.key, { ...option.message, __subscribe__: true });
822
- });
823
- });
824
- }
825
- on(event, callback) {
826
- this.socket.on(event, callback);
827
- }
828
- removeListener(event, callback) {
829
- this.socket.removeListener(event, callback);
830
- }
831
- removeAllListeners() {
832
- this.socket.removeAllListeners();
833
- }
834
- hasListeners(event) {
835
- return this.socket.hasListeners(event);
836
- }
837
- emit(key, data) {
838
- this.socket.emit(key, data);
839
- }
840
- subscribe(option) {
841
- if (!this.roomSubscribeMap.has(option.roomId)) {
842
- this.roomSubscribeMap.set(option.roomId, option);
843
- this.socket.emit(option.key, { ...option.message, __subscribe__: true });
844
- }
845
- this.socket.on(option.roomId, option.handleEvent);
846
- }
847
- unsubscribe(roomId, handleEvent) {
848
- this.socket.removeListener(roomId, handleEvent);
849
- const option = this.roomSubscribeMap.get(roomId);
850
- if (this.hasListeners(roomId) || !option)
851
- return;
852
- this.roomSubscribeMap.delete(roomId);
853
- this.socket.emit(option.key, { ...option.message, __subscribe__: false });
854
- }
855
- disconnect() {
856
- this.socket.disconnect();
857
- return this;
858
- }
859
- };
860
- var Client = class _Client {
861
- static globalIoMap = /* @__PURE__ */ new Map();
862
- static tokenStore = /* @__PURE__ */ new Map();
863
- async waitUntilWebSocketConnected(ws = baseClientEnv.serverWsUri) {
864
- if (baseClientEnv.side === "server")
865
- return true;
866
- while (!this.getIo(ws).socket.connected) {
867
- Logger.verbose("waiting for websocket to initialize...");
868
- await sleep(300);
869
- }
870
- }
871
- isInitialized = false;
872
- uri = baseClientEnv.serverGraphqlUri;
873
- ws = baseClientEnv.serverWsUri;
874
- udp = null;
875
- gql = (0, import_core.createClient)({ url: this.uri, fetch, exchanges: [import_core.cacheExchange, import_core.fetchExchange] });
876
- jwt = null;
877
- async getJwt() {
878
- const isNextServer = baseClientEnv.side === "server" && baseEnv.operationType === "client";
879
- if (isNextServer) {
880
- const nextHeaders = __require("next/headers");
881
- return (await nextHeaders.cookies?.())?.get("jwt")?.value ?? (await nextHeaders.headers?.())?.get("jwt") ?? this.jwt ?? null;
882
- } else
883
- return _Client.tokenStore.get(this) ?? null;
884
- }
885
- io = null;
886
- init(data = {}) {
887
- Object.assign(this, data);
888
- this.setLink(data.uri);
889
- this.setIo(data.ws);
890
- this.isInitialized = true;
891
- }
892
- setIo(ws = baseClientEnv.serverWsUri) {
893
- this.ws = ws;
894
- const existingIo = _Client.globalIoMap.get(ws);
895
- if (existingIo) {
896
- this.io = existingIo;
897
- return;
898
- }
899
- this.io = new SocketIo(ws);
900
- _Client.globalIoMap.set(ws, this.io);
901
- }
902
- getIo(ws = baseClientEnv.serverWsUri) {
903
- const existingIo = _Client.globalIoMap.get(ws);
904
- if (existingIo)
905
- return existingIo;
906
- const io2 = new SocketIo(ws);
907
- _Client.globalIoMap.set(ws, io2);
908
- return io2;
909
- }
910
- setLink(uri = baseClientEnv.serverGraphqlUri) {
911
- this.uri = uri;
912
- this.gql = (0, import_core.createClient)({
913
- url: this.uri,
914
- fetch,
915
- exchanges: [import_core.cacheExchange, import_core.fetchExchange],
916
- // requestPolicy: "network-only",
917
- fetchOptions: () => {
918
- return {
919
- headers: {
920
- "apollo-require-preflight": "true",
921
- ...this.jwt ? { authorization: `Bearer ${this.jwt}` } : {}
922
- }
923
- };
924
- }
925
- });
926
- }
927
- setJwt(jwt3) {
928
- _Client.tokenStore.set(this, jwt3);
929
- }
930
- reset() {
931
- this.io?.disconnect();
932
- this.io = null;
933
- this.jwt = null;
934
- }
935
- clone(data = {}) {
936
- const newClient = new _Client();
937
- newClient.init({ ...this, ...data });
938
- if (data.jwt)
939
- _Client.tokenStore.set(newClient, data.jwt);
940
- return newClient;
941
- }
942
- terminate() {
943
- this.reset();
944
- _Client.globalIoMap.forEach((io2) => io2.disconnect());
945
- this.isInitialized = false;
946
- }
947
- setUdp(udp) {
948
- this.udp = udp;
949
- }
950
- };
951
- var client = new Client();
952
-
953
- // pkgs/@akanjs/signal/src/immerify.ts
954
- var import_immer = __require("immer");
955
-
956
- // pkgs/@akanjs/signal/src/signalDecorators.ts
957
- var import_reflect_metadata5 = __require("reflect-metadata");
958
- var createArgMetaDecorator = (type) => {
959
- return function(option = {}) {
960
- return function(prototype, key, idx) {
961
- const argMetas = getArgMetasOnPrototype(prototype, key);
962
- argMetas[idx] = { key, idx, type, option };
963
- setArgMetasOnPrototype(prototype, key, argMetas);
964
- };
965
- };
966
- };
967
- var Account = createArgMetaDecorator("Account");
968
- var defaultAccount = {
969
- __InternalArg__: "Account",
970
- appName: baseEnv.appName,
971
- environment: baseEnv.environment
972
- };
973
- var Self = createArgMetaDecorator("Self");
974
- var Me = createArgMetaDecorator("Me");
975
- var UserIp = createArgMetaDecorator("UserIp");
976
- var Access = createArgMetaDecorator("Access");
977
- var Req = createArgMetaDecorator("Req");
978
- var Res = createArgMetaDecorator("Res");
979
- var Ws = createArgMetaDecorator("Ws");
980
- var Job = createArgMetaDecorator("Job");
981
- var getQuery = (allow2) => function(returns, signalOption = {}, guards = []) {
982
- return (prototype, key, descriptor) => {
983
- const metadataMap = getGqlMetaMapOnPrototype(prototype);
984
- metadataMap.set(key, {
985
- returns,
986
- signalOption,
987
- key,
988
- descriptor,
989
- guards: [allow2, ...guards],
990
- type: "Query"
991
- });
992
- setGqlMetaMapOnPrototype(prototype, metadataMap);
993
- };
994
- };
995
- var getMutation = (allow2) => function(returns, signalOption = {}, guards = []) {
996
- return (prototype, key, descriptor) => {
997
- const metadataMap = getGqlMetaMapOnPrototype(prototype);
998
- metadataMap.set(key, {
999
- returns,
1000
- signalOption,
1001
- key,
1002
- descriptor,
1003
- guards: [allow2, ...guards],
1004
- type: "Mutation"
1005
- });
1006
- setGqlMetaMapOnPrototype(prototype, metadataMap);
1007
- };
1008
- };
1009
- var getMessage = (allow2) => function(returns, signalOption = {}, guards = []) {
1010
- return (prototype, key, descriptor) => {
1011
- const metadataMap = getGqlMetaMapOnPrototype(prototype);
1012
- metadataMap.set(key, {
1013
- returns,
1014
- signalOption,
1015
- key,
1016
- descriptor,
1017
- guards: [allow2, ...guards],
1018
- type: "Message"
1019
- });
1020
- setGqlMetaMapOnPrototype(prototype, metadataMap);
1021
- };
1022
- };
1023
- var getPubsub = (allow2) => function(returns, signalOption = {}, guards = []) {
1024
- return (prototype, key, descriptor) => {
1025
- const metadataMap = getGqlMetaMapOnPrototype(prototype);
1026
- metadataMap.set(key, {
1027
- returns,
1028
- signalOption,
1029
- key,
1030
- descriptor,
1031
- guards: [allow2, ...guards],
1032
- type: "Pubsub"
1033
- });
1034
- setGqlMetaMapOnPrototype(prototype, metadataMap);
1035
- };
1036
- };
1037
- var getProcess = (serverType) => function(returns, signalOption = {}) {
1038
- return (prototype, key, descriptor) => {
1039
- const metadataMap = getGqlMetaMapOnPrototype(prototype);
1040
- metadataMap.set(key, {
1041
- returns,
1042
- signalOption: { ...signalOption, serverType: lowerlize(serverType) },
1043
- key,
1044
- descriptor,
1045
- guards: ["None"],
1046
- type: "Process"
1047
- });
1048
- setGqlMetaMapOnPrototype(prototype, metadataMap);
1049
- };
1050
- };
1051
- var Query = {
1052
- Public: getQuery("Public"),
1053
- Every: getQuery("Every"),
1054
- Admin: getQuery("Admin"),
1055
- User: getQuery("User"),
1056
- SuperAdmin: getQuery("SuperAdmin"),
1057
- None: getQuery("None"),
1058
- Owner: getQuery("Owner")
1059
- };
1060
- var Mutation = {
1061
- Public: getMutation("Public"),
1062
- Every: getMutation("Every"),
1063
- Admin: getMutation("Admin"),
1064
- User: getMutation("User"),
1065
- SuperAdmin: getMutation("SuperAdmin"),
1066
- None: getMutation("None"),
1067
- Owner: getMutation("Owner")
1068
- };
1069
- var Message = {
1070
- Public: getMessage("Public"),
1071
- Every: getMessage("Every"),
1072
- Admin: getMessage("Admin"),
1073
- User: getMessage("User"),
1074
- SuperAdmin: getMessage("SuperAdmin"),
1075
- None: getMessage("None"),
1076
- Owner: getMessage("Owner")
1077
- };
1078
- var Pubsub = {
1079
- Public: getPubsub("Public"),
1080
- Every: getPubsub("Every"),
1081
- Admin: getPubsub("Admin"),
1082
- User: getPubsub("User"),
1083
- SuperAdmin: getPubsub("SuperAdmin"),
1084
- None: getPubsub("None"),
1085
- Owner: getPubsub("Owner")
1086
- };
1087
- var Process = {
1088
- Federation: getProcess("Federation"),
1089
- Batch: getProcess("Batch"),
1090
- All: getProcess("All")
1091
- };
1092
- var getArg = (type) => function(name, returns, argsOption = {}) {
1093
- return function(prototype, key, idx) {
1094
- const argMetas = getArgMetasOnPrototype(prototype, key);
1095
- argMetas[idx] = { name, returns, argsOption, key, idx, type };
1096
- setArgMetasOnPrototype(prototype, key, argMetas);
1097
- };
1098
- };
1099
- var Arg = {
1100
- Body: getArg("Body"),
1101
- Param: getArg("Param"),
1102
- Query: getArg("Query"),
1103
- Upload: getArg("Upload"),
1104
- Msg: getArg("Msg"),
1105
- Room: getArg("Room")
1106
- };
1107
- var getGqlMeta = (sigRef, key) => {
1108
- const gqlMetaMap = Reflect.getMetadata("gql", sigRef.prototype);
1109
- if (!gqlMetaMap)
1110
- throw new Error(`No GqlMeta found for ${sigRef.name}`);
1111
- const gqlMeta = gqlMetaMap.get(key);
1112
- if (!gqlMeta)
1113
- throw new Error(`No GqlMeta found for ${key}`);
1114
- return gqlMeta;
1115
- };
1116
- var getGqlMetaMapOnPrototype = (prototype) => {
1117
- const gqlMetaMap = Reflect.getMetadata("gql", prototype);
1118
- return gqlMetaMap ?? /* @__PURE__ */ new Map();
1119
- };
1120
- var setGqlMetaMapOnPrototype = (prototype, gqlMetaMap) => {
1121
- Reflect.defineMetadata("gql", gqlMetaMap, prototype);
1122
- };
1123
- var getArgMetasOnPrototype = (prototype, key) => {
1124
- return Reflect.getMetadata("args", prototype, key) ?? [];
1125
- };
1126
- var setArgMetasOnPrototype = (prototype, key, argMetas) => {
1127
- Reflect.defineMetadata("args", argMetas, prototype, key);
1128
- };
1129
-
1130
- // pkgs/@akanjs/signal/src/baseFetch.ts
1131
- var nativeFetch = fetch;
1132
- var baseFetch = Object.assign(nativeFetch, {
1133
- client,
1134
- clone: function(option = {}) {
1135
- return {
1136
- ...this,
1137
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
1138
- client: this.client.clone(option)
1139
- };
1140
- }
1141
- });
1142
-
1143
- // pkgs/@akanjs/nest/src/authorization.ts
1144
- var import_apollo = __require("@nestjs/apollo");
1145
- var jwt = __toESM(__require("jsonwebtoken"));
1146
- var allow = (account, roles, userId) => {
1147
- if (!account)
1148
- throw new import_apollo.AuthenticationError("No Authentication Account");
1149
- for (const role of roles) {
1150
- if (role === "user" && account.self?.roles.includes("user"))
1151
- return true;
1152
- else if (role === "admin" && account.me?.roles.includes("admin"))
1153
- return true;
1154
- else if (role === "superAdmin" && account.me?.roles.includes("superAdmin"))
1155
- return true;
1156
- }
1157
- throw new import_apollo.AuthenticationError(
1158
- `No Authentication With Roles: ${roles.join(", ")}, Your roles are ${[
1159
- ...account.self?.roles ?? [],
1160
- ...account.me?.roles ?? []
1161
- ].join(", ")}${!account.self?.roles.length && !account.me?.roles.length ? " (No Roles)" : ""}`
1162
- );
1163
- };
1164
-
1165
- // pkgs/@akanjs/nest/src/authGuards.ts
1166
- var import_common7 = __require("@nestjs/common");
1167
- var import_graphql = __require("@nestjs/graphql");
1168
- var getRequest = (context) => {
1169
- const type = context.getType();
1170
- if (type === "ws")
1171
- throw new Error("Getting Request in Websocket is not allowed");
1172
- return type === "http" ? context.switchToHttp().getRequest() : import_graphql.GqlExecutionContext.create(context).getContext().req;
1173
- };
1174
- var getResponse = (context) => {
1175
- const type = context.getType();
1176
- if (type === "ws")
1177
- throw new Error("Getting Response in Websocket is not allowed");
1178
- return type === "http" ? context.switchToHttp().getResponse() : import_graphql.GqlExecutionContext.create(context).getContext().req.res;
1179
- };
1180
- var getArgs = (context) => {
1181
- const type = context.getType();
1182
- if (type === "ws")
1183
- throw new Error("Getting Args in Websocket is not allowed");
1184
- if (type === "graphql")
1185
- return import_graphql.GqlExecutionContext.create(context).getArgs();
1186
- else if (type === "http") {
1187
- const { params, query, body } = context.switchToHttp().getRequest();
1188
- return { ...params, ...query, ...body };
1189
- } else
1190
- throw new Error("Getting Args in Unknown context is not allowed");
1191
- };
1192
- var Public = class {
1193
- canActivate(context) {
1194
- return true;
1195
- }
1196
- };
1197
- Public = __decorateClass([
1198
- (0, import_common7.Injectable)()
1199
- ], Public);
1200
- var None = class {
1201
- canActivate() {
1202
- return false;
1203
- }
1204
- };
1205
- None = __decorateClass([
1206
- (0, import_common7.Injectable)()
1207
- ], None);
1208
- var Every = class {
1209
- canActivate(context) {
1210
- const { account } = getRequest(context);
1211
- return allow(account, ["user", "admin", "superAdmin"]);
1212
- }
1213
- };
1214
- Every = __decorateClass([
1215
- (0, import_common7.Injectable)()
1216
- ], Every);
1217
- var Owner = class {
1218
- canActivate(context) {
1219
- const { account } = getRequest(context);
1220
- return allow(account, ["user", "admin", "superAdmin"]);
1221
- }
1222
- };
1223
- Owner = __decorateClass([
1224
- (0, import_common7.Injectable)()
1225
- ], Owner);
1226
- var Admin = class {
1227
- canActivate(context) {
1228
- const { account } = getRequest(context);
1229
- return allow(account, ["admin", "superAdmin"]);
1230
- }
1231
- };
1232
- Admin = __decorateClass([
1233
- (0, import_common7.Injectable)()
1234
- ], Admin);
1235
- var SuperAdmin = class {
1236
- canActivate(context) {
1237
- const { account } = getRequest(context);
1238
- return allow(account, ["superAdmin"]);
1239
- }
1240
- };
1241
- SuperAdmin = __decorateClass([
1242
- (0, import_common7.Injectable)()
1243
- ], SuperAdmin);
1244
- var User = class {
1245
- canActivate(context) {
1246
- const { account } = getRequest(context);
1247
- return allow(account, ["user"]);
1248
- }
1249
- };
1250
- User = __decorateClass([
1251
- (0, import_common7.Injectable)()
1252
- ], User);
1253
-
1254
- // pkgs/@akanjs/nest/src/authentication.ts
1255
- var import_common8 = __require("@nestjs/common");
1256
- var import_ua_parser_js = __toESM(__require("ua-parser-js"));
1257
- var Account3 = (0, import_common8.createParamDecorator)((option, context) => {
1258
- const { account } = getRequest(context);
1259
- return account;
1260
- });
1261
- var Self2 = (0, import_common8.createParamDecorator)((option, context) => {
1262
- const { account } = getRequest(context);
1263
- const self = account.self;
1264
- if (!self && !option.nullable)
1265
- throw new import_common8.UnauthorizedException("No or Invalid Account in Self (User)");
1266
- return self;
1267
- });
1268
- var Me2 = (0, import_common8.createParamDecorator)((option, context) => {
1269
- const { account } = getRequest(context);
1270
- const me = account.me;
1271
- if (!me && !option.nullable)
1272
- throw new import_common8.UnauthorizedException("No or Invalid Account in Me (Admin)");
1273
- return me;
1274
- });
1275
- var UserIp2 = (0, import_common8.createParamDecorator)((option, context) => {
1276
- const req = getRequest(context);
1277
- const ip = req.ip;
1278
- if (!ip && !option.nullable)
1279
- throw new import_common8.UnauthorizedException("Invalid IP");
1280
- return { ip };
1281
- });
1282
- var Access2 = (0, import_common8.createParamDecorator)((option, context) => {
1283
- const req = getRequest(context);
1284
- const res = new import_ua_parser_js.default(req.userAgent).getResult();
1285
- if (!req.userAgent && !option.nullable)
1286
- throw new import_common8.UnauthorizedException("Invalid UserAgent");
1287
- return {
1288
- ...req.geolocation ? JSON.parse(req.geolocation) : {},
1289
- osName: res.os.name,
1290
- osVersion: res.os.version,
1291
- browserName: res.browser.name,
1292
- browserVersion: res.browser.version,
1293
- mobileModel: res.device.model,
1294
- mobileVendor: res.device.vendor,
1295
- deviceType: res.device.type ?? "desktop",
1296
- at: dayjs(),
1297
- period: 0
1298
- };
1299
- });
1300
- var Req2 = (0, import_common8.createParamDecorator)((option, context) => {
1301
- return getRequest(context);
1302
- });
1303
- var Res2 = (0, import_common8.createParamDecorator)((option, context) => {
1304
- return getResponse(context);
1305
- });
1306
- var Ws2 = (0, import_common8.createParamDecorator)((option, context) => {
1307
- const socket = context.getArgByIndex(0);
1308
- const { __subscribe__ } = context.getArgByIndex(1);
1309
- return {
1310
- socket,
1311
- subscribe: __subscribe__,
1312
- onDisconnect: (handler) => {
1313
- socket.on("disconnect", handler);
1314
- },
1315
- onSubscribe: (handler) => {
1316
- if (__subscribe__)
1317
- handler();
1318
- },
1319
- onUnsubscribe: (handler) => {
1320
- if (!__subscribe__)
1321
- handler();
1322
- }
1323
- };
1324
- });
1325
-
1326
- // pkgs/@akanjs/nest/src/interceptors.ts
1327
- var import_common10 = __require("@nestjs/common");
1328
- var import_graphql2 = __require("@nestjs/graphql");
1329
- var import_rxjs = __require("rxjs");
1330
- var import_operators = __require("rxjs/operators");
1331
- var _logger, _CACHE_PREFIX, _generateCacheKey, generateCacheKey_fn, _getCache, getCache_fn, _setCache, setCache_fn;
1332
- var CacheInterceptor = class {
1333
- constructor(redis) {
1334
- this.redis = redis;
1335
- __privateAdd(this, _generateCacheKey);
1336
- __privateAdd(this, _getCache);
1337
- __privateAdd(this, _setCache);
1338
- __privateAdd(this, _logger, new Logger("CacheInterceptor"));
1339
- __privateAdd(this, _CACHE_PREFIX, "signal:");
1340
- }
1341
- async intercept(context, next) {
1342
- const handler = context.getHandler();
1343
- const signalKey = handler.name;
1344
- const gqlMeta = getGqlMeta(context.getClass(), signalKey);
1345
- if (gqlMeta.type !== "Query" || !gqlMeta.signalOption.cache) {
1346
- if (gqlMeta.signalOption.cache)
1347
- __privateGet(this, _logger).warn(`CacheInterceptor: ${signalKey} is not Query endpoint or cache is not set`);
1348
- return next.handle();
1349
- }
1350
- const args = getArgs(context);
1351
- const cacheKey = __privateMethod(this, _generateCacheKey, generateCacheKey_fn).call(this, signalKey, args);
1352
- const cachedData = await __privateMethod(this, _getCache, getCache_fn).call(this, cacheKey);
1353
- if (cachedData) {
1354
- __privateGet(this, _logger).debug(`Cache hit for key: ${cacheKey}`);
1355
- return next.handle().pipe(
1356
- (0, import_operators.map)(() => cachedData),
1357
- (0, import_operators.catchError)((error) => {
1358
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1359
- __privateGet(this, _logger).error(`Error in cache interceptor for ${cacheKey}: ${errorMessage}`);
1360
- return (0, import_rxjs.throwError)(() => error);
1361
- })
1362
- );
1363
- }
1364
- return next.handle().pipe(
1365
- (0, import_operators.map)((data) => {
1366
- const cacheDuration = gqlMeta.signalOption.cache;
1367
- if (typeof cacheDuration === "number") {
1368
- void __privateMethod(this, _setCache, setCache_fn).call(this, cacheKey, data, cacheDuration);
1369
- __privateGet(this, _logger).debug(`Cache set for key: ${cacheKey}`);
1370
- }
1371
- return data;
1372
- }),
1373
- (0, import_operators.catchError)((error) => {
1374
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1375
- __privateGet(this, _logger).error(`Error in cache interceptor for ${cacheKey}: ${errorMessage}`);
1376
- return (0, import_rxjs.throwError)(() => error);
1377
- })
1378
- );
1379
- }
1380
- };
1381
- _logger = new WeakMap();
1382
- _CACHE_PREFIX = new WeakMap();
1383
- _generateCacheKey = new WeakSet();
1384
- generateCacheKey_fn = function(signalKey, args) {
1385
- return `${__privateGet(this, _CACHE_PREFIX)}${signalKey}:${JSON.stringify(args)}`;
1386
- };
1387
- _getCache = new WeakSet();
1388
- getCache_fn = async function(key) {
1389
- try {
1390
- const cached = await this.redis.get(key);
1391
- if (!cached)
1392
- return null;
1393
- const { data } = JSON.parse(cached);
1394
- return data;
1395
- } catch (error) {
1396
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1397
- __privateGet(this, _logger).error(`Error retrieving cache for key ${key}: ${errorMessage}`);
1398
- return null;
1399
- }
1400
- };
1401
- _setCache = new WeakSet();
1402
- setCache_fn = async function(key, data, ttlMs) {
1403
- try {
1404
- const cacheData = { data, timestamp: Date.now() };
1405
- await this.redis.set(key, JSON.stringify(cacheData), { PX: ttlMs });
1406
- } catch (error) {
1407
- const errorMessage = error instanceof Error ? error.message : "Unknown error";
1408
- __privateGet(this, _logger).error(`Error setting cache for key ${key}: ${errorMessage}`);
1409
- }
1410
- };
1411
- CacheInterceptor = __decorateClass([
1412
- (0, import_common10.Injectable)(),
1413
- __decorateParam(0, (0, import_common10.Inject)("REDIS_CLIENT"))
1414
- ], CacheInterceptor);
1415
- var TimeoutInterceptor = class {
1416
- intercept(context, next) {
1417
- const gqlMeta = getGqlMeta(context.getClass(), context.getHandler().name);
1418
- const timeoutMs = gqlMeta.signalOption.timeout ?? 3e4;
1419
- if (timeoutMs === 0)
1420
- return next.handle();
1421
- return next.handle().pipe(
1422
- (0, import_operators.timeout)(timeoutMs),
1423
- (0, import_operators.catchError)((err) => {
1424
- if (err instanceof import_rxjs.TimeoutError)
1425
- return (0, import_rxjs.throwError)(() => new import_common10.RequestTimeoutException());
1426
- return (0, import_rxjs.throwError)(() => err);
1427
- })
1428
- );
1429
- }
1430
- };
1431
- TimeoutInterceptor = __decorateClass([
1432
- (0, import_common10.Injectable)()
1433
- ], TimeoutInterceptor);
1434
- var LoggingInterceptor = class {
1435
- logger = new Logger("IO");
1436
- intercept(context, next) {
1437
- const gqlReq = context.getArgByIndex(3);
1438
- const req = getRequest(context);
1439
- const reqType = gqlReq?.parentType?.name ?? req.method;
1440
- const reqName = gqlReq?.fieldName ?? req.url;
1441
- const before = Date.now();
1442
- const ip = import_graphql2.GqlExecutionContext.create(context).getContext().req.ip;
1443
- this.logger.debug(`Before ${reqType}-${reqName} / ${ip} / ${before}`);
1444
- return next.handle().pipe(
1445
- (0, import_operators.tap)(() => {
1446
- const after = Date.now();
1447
- this.logger.debug(`After ${reqType}-${reqName} / ${ip} / ${after} (${after - before}ms)`);
1448
- })
1449
- );
1450
- }
1451
- };
1452
- LoggingInterceptor = __decorateClass([
1453
- (0, import_common10.Injectable)()
1454
- ], LoggingInterceptor);
1455
-
1456
- // pkgs/@akanjs/nest/src/redis-io.adapter.ts
1457
- var import_platform_socket = __require("@nestjs/platform-socket.io");
1458
- var import_redis_adapter = __require("@socket.io/redis-adapter");
1459
- var import_redis = __require("redis");
1460
-
1461
- // pkgs/@akanjs/nest/src/pipes.ts
1462
- var import_common12 = __require("@nestjs/common");
1463
- var import_stream = __require("stream");
1464
- var ArrayifyPipe = class {
1465
- transform(value, metadata) {
1466
- return Array.isArray(value) ? value : value.split(",");
1467
- }
1468
- };
1469
- ArrayifyPipe = __decorateClass([
1470
- (0, import_common12.Injectable)()
1471
- ], ArrayifyPipe);
1472
- var IntPipe = class {
1473
- transform(value, metadata) {
1474
- return Array.isArray(value) ? value.map(parseInt) : [parseInt(value)];
1475
- }
1476
- };
1477
- IntPipe = __decorateClass([
1478
- (0, import_common12.Injectable)()
1479
- ], IntPipe);
1480
- var FloatPipe = class {
1481
- transform(value, metadata) {
1482
- return Array.isArray(value) ? value.map(parseFloat) : [parseFloat(value)];
1483
- }
1484
- };
1485
- FloatPipe = __decorateClass([
1486
- (0, import_common12.Injectable)()
1487
- ], FloatPipe);
1488
- var BooleanPipe = class {
1489
- transform(value, metadata) {
1490
- return Array.isArray(value) ? value.map((v) => Boolean(v)) : [Boolean(value)];
1491
- }
1492
- };
1493
- BooleanPipe = __decorateClass([
1494
- (0, import_common12.Injectable)()
1495
- ], BooleanPipe);
1496
- var DayjsPipe = class {
1497
- transform(value, metadata) {
1498
- return Array.isArray(value) ? value.map(dayjs) : [dayjs(value)];
1499
- }
1500
- };
1501
- DayjsPipe = __decorateClass([
1502
- (0, import_common12.Injectable)()
1503
- ], DayjsPipe);
1504
- var JSONPipe = class {
1505
- transform(value, metadata) {
1506
- const transformable = typeof value === "string" && value.length;
1507
- const obj = transformable ? JSON.parse(atob(value)) : value;
1508
- return obj;
1509
- }
1510
- };
1511
- JSONPipe = __decorateClass([
1512
- (0, import_common12.Injectable)()
1513
- ], JSONPipe);
1514
- var convertToFileStream = (value) => ({
1515
- filename: value.originalname,
1516
- mimetype: value.mimetype,
1517
- encoding: value.encoding,
1518
- createReadStream: () => import_stream.Readable.from(value.buffer)
1519
- });
1520
- var MulterToUploadPipe = class {
1521
- transform(value, metadata) {
1522
- return Array.isArray(value) ? value.map(convertToFileStream) : convertToFileStream(value);
1523
- }
1524
- };
1525
- MulterToUploadPipe = __decorateClass([
1526
- (0, import_common12.Injectable)()
1527
- ], MulterToUploadPipe);
1528
-
1529
- // pkgs/@akanjs/nest/src/exporter.ts
1530
- var fs = __toESM(__require("fs"));
1531
-
1532
- // pkgs/@akanjs/nest/src/verifyPayment.ts
1533
- var import_iap = __toESM(__require("iap"));
1534
-
1535
- // pkgs/@akanjs/nest/src/sso.ts
1536
- var import_common13 = __require("@nestjs/common");
1537
- var import_passport = __require("@nestjs/passport");
1538
- var appleSignin = __toESM(__require("apple-signin"));
1539
- var jwt2 = __toESM(__require("jsonwebtoken"));
1540
- var import_passport_apple = __require("passport-apple");
1541
- var import_passport_facebook = __require("passport-facebook");
1542
- var import_passport_github = __require("passport-github");
1543
- var import_passport_google_oauth20 = __require("passport-google-oauth20");
1544
- var import_passport_kakao = __require("passport-kakao");
1545
- var import_passport_naver = __require("passport-naver");
1546
-
1547
- // pkgs/@akanjs/nest/src/exceptions.ts
1548
- var import_common15 = __require("@nestjs/common");
1549
- var AllExceptionsFilter = class {
1550
- logger = new Logger("Exception Filter");
1551
- catch(exception, host) {
1552
- if (host.getType() !== "http") {
1553
- const gqlArgs = host.getArgByIndex(1);
1554
- const gqlReq = host.getArgByIndex(3);
1555
- const reqType2 = gqlReq?.parentType?.name ?? "unknown";
1556
- const reqName2 = gqlReq?.fieldName ?? "unknown";
1557
- this.logger.error(
1558
- `GraphQL Error
1559
- Request: ${reqType2}-${reqName2}
1560
- Args: ${JSON.stringify(gqlArgs, null, 2)}
1561
- ${exception.stack}`
1562
- );
1563
- throw exception;
1564
- }
1565
- const ctx = host.switchToHttp();
1566
- const res = ctx.getResponse();
1567
- const req = ctx.getRequest();
1568
- const reqType = req.method;
1569
- const reqName = req.url;
1570
- const status = exception instanceof import_common15.HttpException ? exception.getStatus() : null;
1571
- if (status) {
1572
- res.status(status).json({
1573
- statusCode: status,
1574
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1575
- path: req.url,
1576
- message: exception instanceof import_common15.HttpException ? exception.getResponse() : exception.message
1577
- });
1578
- this.logger.error(
1579
- `Http Error: ${status}
1580
- Request: ${reqType}-${reqName}
1581
- Body: ${JSON.stringify(req.body, null, 2)}
1582
- ${exception.stack}`
1583
- );
1584
- }
1585
- }
1586
- };
1587
- AllExceptionsFilter = __decorateClass([
1588
- (0, import_common15.Catch)()
1589
- ], AllExceptionsFilter);
1590
-
1591
- // pkgs/@akanjs/nest/src/generateSecrets.ts
1592
- var import_crypto = __require("crypto");
1593
- var import_tunnel_ssh = __require("tunnel-ssh");
1594
-
1595
- // pkgs/@akanjs/nest/src/mongoose.ts
1596
- var import_mongoose2 = __toESM(__require("mongoose"));
1597
-
1598
- // pkgs/@akanjs/nest/src/searchClient.ts
1599
- var import_common17 = __require("@nestjs/common");
1600
- var SearchClient = class {
1601
- meili;
1602
- async getIndexNames() {
1603
- const { results } = await this.meili.getIndexes({ limit: 1e3 });
1604
- return results.map((index) => index.uid);
1605
- }
1606
- async getSearchResult(indexName, option) {
1607
- const { skip = 0, limit = DEFAULT_PAGE_SIZE, sort = "", searchString } = option;
1608
- if (!searchString) {
1609
- const { results, total } = await this.meili.index(indexName).getDocuments({ offset: skip, limit });
1610
- return { docs: results, skip, limit, sort, total };
1611
- }
1612
- const { hits, estimatedTotalHits } = await this.meili.index(indexName).search(searchString, { offset: skip, limit });
1613
- return { docs: hits, skip, limit, sort, total: estimatedTotalHits, query: searchString };
1614
- }
1615
- async upsertDocuments(indexName, documents) {
1616
- const task = await this.meili.index(indexName).addDocuments(documents);
1617
- return task;
1618
- }
1619
- async dropIndex(indexName) {
1620
- const task = await this.meili.index(indexName).delete();
1621
- return task;
1622
- }
1623
- };
1624
- __decorateClass([
1625
- (0, import_common17.Inject)("MEILI_CLIENT")
1626
- ], SearchClient.prototype, "meili", 2);
1627
- SearchClient = __decorateClass([
1628
- (0, import_common17.Injectable)()
1629
- ], SearchClient);
1630
-
1631
- // pkgs/@akanjs/nest/src/cacheClient.ts
1632
- var import_common18 = __require("@nestjs/common");
1633
- var CacheClient = class {
1634
- redis;
1635
- };
1636
- __decorateClass([
1637
- (0, import_common18.Inject)("REDIS_CLIENT")
1638
- ], CacheClient.prototype, "redis", 2);
1639
- CacheClient = __decorateClass([
1640
- (0, import_common18.Injectable)()
1641
- ], CacheClient);
1642
-
1643
- // pkgs/@akanjs/nest/src/databaseClient.ts
1644
- var import_common20 = __require("@nestjs/common");
1645
- var import_mongoose3 = __require("@nestjs/mongoose");
1646
- var DatabaseClient = class {
1647
- connection;
1648
- getModel(modelName) {
1649
- const model = this.connection.models[capitalize(modelName)];
1650
- return model;
1651
- }
1652
- };
1653
- __decorateClass([
1654
- (0, import_mongoose3.InjectConnection)()
1655
- ], DatabaseClient.prototype, "connection", 2);
1656
- DatabaseClient = __decorateClass([
1657
- (0, import_common20.Injectable)()
1658
- ], DatabaseClient);
1659
-
1660
- // pkgs/@akanjs/nest/src/decorators.ts
1661
- var import_reflect_metadata6 = __require("reflect-metadata");
1662
- var import_schedule = __require("@nestjs/schedule");
1663
- var Transaction = () => {
1664
- return function(target, key, descriptor) {
1665
- const originMethod = descriptor.value;
1666
- descriptor.value = function(...args) {
1667
- if (!this.connection)
1668
- throw new Error(`No Connection in function ${key}`);
1669
- return new Promise((resolve, reject) => {
1670
- this.connection.transaction(async () => {
1671
- const res = await originMethod.apply(this, args);
1672
- resolve(res);
1673
- }).catch(reject);
1674
- });
1675
- };
1676
- return descriptor;
1677
- };
1678
- };
1679
-
1680
- // pkgs/@akanjs/document/src/dataLoader.ts
1681
- var import_dataloader = __toESM(__require("dataloader"));
1682
- var import_lodash = __require("lodash");
1683
- var import_mongoose4 = __require("mongoose");
1684
- var Id = import_mongoose4.Types.ObjectId;
1685
- var ObjectId = import_mongoose4.Schema.Types.ObjectId;
1686
- var Mixed = import_mongoose4.Schema.Types.Mixed;
1687
- var createLoader = (model, fieldName = "_id", defaultQuery = {}) => {
1688
- return new import_dataloader.default(
1689
- (fields) => {
1690
- const query = { ...defaultQuery };
1691
- query[fieldName] = { $in: fields };
1692
- const data = model.find(query).then((list) => {
1693
- const listByKey = (0, import_lodash.keyBy)(list, fieldName);
1694
- return fields.map((id) => (0, import_lodash.get)(listByKey, id, null));
1695
- });
1696
- return data;
1697
- },
1698
- { name: "dataloader", cache: false }
1699
- );
1700
- };
1701
- var createArrayLoader = (model, fieldName = "_id", defaultQuery = {}) => {
1702
- return new import_dataloader.default((fields) => {
1703
- const query = { ...defaultQuery };
1704
- query[fieldName] = { $in: fields };
1705
- const data = model.find(query).then((list) => {
1706
- return fields.map((field) => list.filter((item) => field === item[fieldName]));
1707
- });
1708
- return data;
1709
- });
1710
- };
1711
- var createArrayElementLoader = (model, fieldName = "_id", defaultQuery = {}) => {
1712
- return new import_dataloader.default(
1713
- (fields) => {
1714
- const query = { ...defaultQuery };
1715
- query[fieldName] = { $in: fields };
1716
- const data = model.find(query).then((list) => {
1717
- const flat = (0, import_lodash.flatMap)(
1718
- list,
1719
- (dat) => dat[fieldName].map((datField) => ({
1720
- ...dat.toObject(),
1721
- key: datField
1722
- }))
1723
- );
1724
- const listByKey = (0, import_lodash.groupBy)(flat, (dat) => dat.key);
1725
- return fields.map((id) => (0, import_lodash.get)(listByKey, id, null));
1726
- });
1727
- return data;
1728
- },
1729
- { name: "dataloader", cache: false }
1730
- );
1731
- };
1732
- var createQueryLoader = (model, queryKeys, defaultQuery = {}) => {
1733
- return new import_dataloader.default(
1734
- (queries) => {
1735
- const query = {
1736
- $and: [{ $or: queries }, defaultQuery]
1737
- };
1738
- const getQueryKey = (query2) => queryKeys.map((key) => query2[key].toString()).join("");
1739
- const data = model.find(query).then((list) => {
1740
- const listByKey = (0, import_lodash.keyBy)(list, getQueryKey);
1741
- return queries.map((query2) => (0, import_lodash.get)(listByKey, getQueryKey(query2), null));
1742
- });
1743
- return data;
1744
- },
1745
- { name: "dataloader", cache: false }
1746
- );
1747
- };
1748
- var getLoaderMetaMapByPrototype = (prototype) => {
1749
- const loaderMetaMap = Reflect.getOwnMetadata("loaders", prototype) ?? /* @__PURE__ */ new Map();
1750
- return loaderMetaMap;
1751
- };
1752
- var getLoaderMetas = (target) => {
1753
- const metas = [...getLoaderMetaMapByPrototype(target.prototype).values()];
1754
- return metas;
1755
- };
1756
- var Loader = {
1757
- ByField: (fieldName, defaultQuery = {}) => {
1758
- return function(target, key) {
1759
- const loaderMetaMap = getLoaderMetaMapByPrototype(target);
1760
- loaderMetaMap.set(key, { key, type: "Field", fieldName, defaultQuery });
1761
- Reflect.defineMetadata("loaders", loaderMetaMap, target);
1762
- };
1763
- },
1764
- ByArrayField: (fieldName, defaultQuery = {}) => {
1765
- return function(target, key) {
1766
- const loaderMetaMap = getLoaderMetaMapByPrototype(target);
1767
- loaderMetaMap.set(key, { key, type: "ArrayField", fieldName, defaultQuery });
1768
- Reflect.defineMetadata("loaders", loaderMetaMap, target);
1769
- };
1770
- },
1771
- ByQuery: (queryKeys, defaultQuery = {}) => {
1772
- return function(target, key) {
1773
- const loaderMetaMap = getLoaderMetaMapByPrototype(target);
1774
- loaderMetaMap.set(key, { key, type: "Query", queryKeys, defaultQuery });
1775
- Reflect.defineMetadata("loaders", loaderMetaMap, target);
1776
- };
1777
- }
1778
- };
1779
-
1780
- // pkgs/@akanjs/document/src/database.ts
1781
- var CacheDatabase = class {
1782
- constructor(refName, redis) {
1783
- this.refName = refName;
1784
- this.redis = redis;
1785
- this.logger = new Logger(`${refName}Cache`);
1786
- }
1787
- logger;
1788
- async set(topic, key, value, option = {}) {
1789
- const setOption = { PXAT: option.expireAt?.toDate().getTime() };
1790
- await this.redis.set(`${this.refName}:${topic}:${key}`, value, setOption);
1791
- }
1792
- async get(topic, key) {
1793
- const value = await this.redis.get(`${this.refName}:${topic}:${key}`);
1794
- return value;
1795
- }
1796
- async delete(topic, key) {
1797
- await this.redis.del(`${this.refName}:${topic}:${key}`);
1798
- }
1799
- };
1800
- var SearchDatabase = class {
1801
- constructor(refName, meili) {
1802
- this.refName = refName;
1803
- this.meili = meili;
1804
- this.logger = new Logger(`${refName}Search`);
1805
- this.index = meili.index(lowerlize(refName));
1806
- }
1807
- logger;
1808
- index;
1809
- async searchIds(searchText, option = {}) {
1810
- const { skip = 0, limit = DEFAULT_PAGE_SIZE, sort } = option;
1811
- if (!searchText) {
1812
- const { results, total } = await this.index.getDocuments({ offset: skip ?? 0, limit: limit ?? 0 });
1813
- return { ids: results.map((result) => result.id), total };
1814
- }
1815
- const { hits, estimatedTotalHits } = await this.index.search(searchText, {
1816
- offset: skip ?? 0,
1817
- limit: limit ?? 0,
1818
- sort: sort ?? [],
1819
- filter: option.filter,
1820
- attributesToRetrieve: ["id"]
1821
- });
1822
- return { ids: hits.map((hit) => hit.id), total: estimatedTotalHits };
1823
- }
1824
- async count(searchText, option = {}) {
1825
- const { skip = 0, limit = DEFAULT_PAGE_SIZE, sort = "" } = option;
1826
- if (!searchText) {
1827
- const { results, total } = await this.index.getDocuments({ offset: skip ?? 0, limit: limit ?? 0 });
1828
- return total;
1829
- }
1830
- const { hits, estimatedTotalHits } = await this.index.search(searchText, {
1831
- offset: skip ?? 0,
1832
- limit: limit ?? 0,
1833
- filter: option.filter,
1834
- attributesToRetrieve: ["id"]
1835
- });
1836
- return estimatedTotalHits;
1837
- }
1838
- };
1839
- var DatabaseModelStorage = class {
1840
- __ModelType__ = "DatabaseModelStorage";
1841
- };
1842
- var databaseModelOf = (database, model, redis, meili) => {
1843
- const [modelName, className] = [database.refName, capitalize(database.refName)];
1844
- const insightFieldMetas = getFieldMetas(database.Insight);
1845
- const accumulator = Object.fromEntries(insightFieldMetas.map((fieldMeta) => [fieldMeta.key, fieldMeta.accumulate]));
1846
- const defaultInsight = Object.fromEntries(insightFieldMetas.map((fieldMeta) => [fieldMeta.key, fieldMeta.default]));
1847
- const makeSafeQuery = (query) => ({ removedAt: { $exists: false }, ...query ?? {} });
1848
- const makeSafeMatchStage = (query) => ({
1849
- $match: { removedAt: { $exists: false }, ...convertAggregateMatch(query) }
1850
- });
1851
- const getListQuery = (query, queryOption) => {
1852
- const find = makeSafeQuery(query);
1853
- const sort = getFilterSort(database.Filter, queryOption?.sort ?? "latest");
1854
- const skip = queryOption?.skip ?? 0;
1855
- const limit = queryOption?.limit === null ? DEFAULT_PAGE_SIZE : queryOption?.limit ?? 0;
1856
- const select = queryOption?.select;
1857
- const sample = queryOption?.sample;
1858
- return { find, sort, skip, limit, select, sample };
1859
- };
1860
- const getFindQuery = (query, queryOption) => {
1861
- const find = makeSafeQuery(query);
1862
- const sort = getFilterSort(database.Filter, queryOption?.sort ?? "latest");
1863
- const skip = queryOption?.skip ?? 0;
1864
- const select = queryOption?.select;
1865
- const sample = queryOption?.sample ?? false;
1866
- return { find, sort, skip, select, sample };
1867
- };
1868
- const getSearchSort = (sortKey) => {
1869
- const sort = getFilterSort(database.Filter, sortKey ?? "latest");
1870
- return Object.entries(sort).map(([key, value]) => `${key}:${value === 1 ? "asc" : "desc"}`);
1871
- };
1872
- const loader = createLoader(model);
1873
- const cacheDatabase = new CacheDatabase(database.refName, redis);
1874
- const searchDatabase = new SearchDatabase(database.refName, meili);
1875
- const DatabaseModel = Reflect.getMetadata(database.refName, DatabaseModelStorage.prototype) ?? class DatabaseModel {
1876
- logger = new Logger(`${modelName}Model`);
1877
- __model = model;
1878
- __cache = cacheDatabase;
1879
- __search = searchDatabase;
1880
- __loader = loader;
1881
- async __list(query, queryOption) {
1882
- const { find, sort, skip, limit, select, sample } = getListQuery(query, queryOption);
1883
- return sample ? await this.__model.sample(find, limit) : await this.__model.find(find, select).sort(sort).skip(skip).limit(limit);
1884
- }
1885
- async __listIds(query, queryOption) {
1886
- const { find, sort, skip, limit, sample } = getListQuery(query, queryOption);
1887
- return (sample ? await this.__model.sample(find, limit, [{ $project: { _id: 1 } }]) : await this.__model.find(find).sort(sort).skip(skip).limit(limit).select("_id")).map(({ _id }) => _id.toString());
1888
- }
1889
- async __find(query, queryOption) {
1890
- const { find, sort, skip, select, sample } = getFindQuery(query, queryOption);
1891
- const doc = sample ? await this.__model.sampleOne(find) : await this.__model.findOne(find, select).sort(sort).skip(skip);
1892
- if (!doc)
1893
- return null;
1894
- return doc;
1895
- }
1896
- async __findId(query, queryOption) {
1897
- const { find, sort, skip, sample } = getFindQuery(query, queryOption);
1898
- const doc = sample ? await this.__model.sampleOne(find, [{ $project: { _id: 1 } }]) : await this.__model.findOne(find).sort(sort).skip(skip).select("_id");
1899
- if (!doc)
1900
- return null;
1901
- return doc._id.toString();
1902
- }
1903
- async __pick(query, queryOption) {
1904
- const { find, sort, skip, select, sample } = getFindQuery(query, queryOption);
1905
- const doc = sample ? await this.__model.sampleOne(find) : await this.__model.findOne(find, select).sort(sort).skip(skip);
1906
- if (!doc)
1907
- throw new Error(`No Document (${database.refName}): ${JSON.stringify(query)}`);
1908
- return doc;
1909
- }
1910
- async __pickId(query, queryOption) {
1911
- const { find, sort, skip, sample } = getFindQuery(query, queryOption);
1912
- const doc = sample ? await this.__model.sampleOne(find, [{ $project: { _id: 1 } }]) : await this.__model.findOne(find).sort(sort).skip(skip).select("_id");
1913
- if (!doc)
1914
- throw new Error(`No Document (${database.refName}): ${JSON.stringify(query)}`);
1915
- return doc._id.toString();
1916
- }
1917
- async __exists(query) {
1918
- const find = makeSafeQuery(query);
1919
- const existingId = await this.__model.exists(find);
1920
- return existingId?.toString() ?? null;
1921
- }
1922
- async __count(query) {
1923
- const find = makeSafeQuery(query);
1924
- return await this.__model.countDocuments(find);
1925
- }
1926
- async __insight(query) {
1927
- if (!accumulator)
1928
- throw new Error(`No Insight (${database.refName})`);
1929
- const res = await this.__model.aggregate([
1930
- makeSafeMatchStage(query),
1931
- { $group: { _id: null, ...accumulator } }
1932
- ]);
1933
- const data = res[0];
1934
- return data ?? defaultInsight;
1935
- }
1936
- async getDefaultSummary(addQuery = {}) {
1937
- if (!database.Summary)
1938
- return {};
1939
- const fieldMetas = getFieldMetas(database.Summary);
1940
- const summary = {};
1941
- await Promise.all(
1942
- fieldMetas.filter((fieldMeta) => !!fieldMeta.query).map(async (fieldMeta) => {
1943
- const query = typeof fieldMeta.query === "function" ? fieldMeta.query() : fieldMeta.query;
1944
- summary[fieldMeta.key] = query ? await model.countDocuments({ ...query, ...addQuery }) : fieldMeta.default;
1945
- })
1946
- );
1947
- return summary;
1948
- }
1949
- async [`get${className}`](id) {
1950
- const doc = await this.__loader.load(id);
1951
- if (!doc)
1952
- throw new Error(`No Document (${database.refName}): ${id}`);
1953
- return doc;
1954
- }
1955
- async [`load${className}`](id) {
1956
- return id ? await this.__loader.load(id) : null;
1957
- }
1958
- async [`load${className}Many`](ids) {
1959
- return await this.__loader.loadMany(ids);
1960
- }
1961
- async [`create${className}`](data) {
1962
- return await new this.__model(data).save();
1963
- }
1964
- async [`update${className}`](id, data) {
1965
- const doc = await this.__model.pickById(id);
1966
- return await doc.set(data).save();
1967
- }
1968
- async [`remove${className}`](id) {
1969
- const doc = await this.__model.pickById(id);
1970
- return await doc.set({ removedAt: dayjs() }).save();
1971
- }
1972
- async [`search${className}`](searchText, queryOption = {}) {
1973
- const { skip, limit, sort } = queryOption;
1974
- const { ids, total } = await this.__search.searchIds(searchText, { skip, limit, sort: getSearchSort(sort) });
1975
- const docs = await this.__loader.loadMany(ids);
1976
- return { docs, count: total };
1977
- }
1978
- async [`searchDocs${className}`](searchText, queryOption = {}) {
1979
- const { skip, limit, sort } = queryOption;
1980
- const { ids } = await this.__search.searchIds(searchText, { skip, limit, sort: getSearchSort(sort) });
1981
- return await this.__loader.loadMany(ids);
1982
- }
1983
- async [`searchCount${className}`](searchText) {
1984
- return await this.__search.count(searchText);
1985
- }
1986
- };
1987
- DatabaseModel.prototype[className] = model;
1988
- DatabaseModel.prototype[`${modelName}Loader`] = loader;
1989
- DatabaseModel.prototype[`${modelName}Cache`] = cacheDatabase;
1990
- DatabaseModel.prototype[`${modelName}Search`] = searchDatabase;
1991
- const getQueryDataFromKey = (queryKey, args) => {
1992
- const lastArg = args.at(-1);
1993
- const hasQueryOption = lastArg && typeof lastArg === "object" && (typeof lastArg.select === "object" || typeof lastArg.skip === "number" || typeof lastArg.limit === "number" || typeof lastArg.sort === "string");
1994
- const queryFn = getFilterQuery(database.Filter, queryKey);
1995
- const query = queryFn(...hasQueryOption ? args.slice(0, -1) : args);
1996
- const queryOption = hasQueryOption ? lastArg : {};
1997
- return { query, queryOption };
1998
- };
1999
- const filterKeyMetaMap = getFilterKeyMetaMapOnPrototype(database.Filter.prototype);
2000
- const queryKeys = [...filterKeyMetaMap.keys()];
2001
- queryKeys.forEach((queryKey) => {
2002
- const queryFn = getFilterQuery(database.Filter, queryKey);
2003
- DatabaseModel.prototype[`list${capitalize(queryKey)}`] = async function(...args) {
2004
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
2005
- return this.__list(query, queryOption);
2006
- };
2007
- DatabaseModel.prototype[`listIds${capitalize(queryKey)}`] = async function(...args) {
2008
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
2009
- return this.__listIds(query, queryOption);
2010
- };
2011
- DatabaseModel.prototype[`find${capitalize(queryKey)}`] = async function(...args) {
2012
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
2013
- return this.__find(query, queryOption);
2014
- };
2015
- DatabaseModel.prototype[`findId${capitalize(queryKey)}`] = async function(...args) {
2016
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
2017
- return this.__findId(query, queryOption);
2018
- };
2019
- DatabaseModel.prototype[`pick${capitalize(queryKey)}`] = async function(...args) {
2020
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
2021
- return this.__pick(query, queryOption);
2022
- };
2023
- DatabaseModel.prototype[`pickId${capitalize(queryKey)}`] = async function(...args) {
2024
- const { query, queryOption } = getQueryDataFromKey(queryKey, args);
2025
- return this.__pickId(query, queryOption);
2026
- };
2027
- DatabaseModel.prototype[`exists${capitalize(queryKey)}`] = async function(...args) {
2028
- const query = queryFn(...args);
2029
- return this.__exists(query);
2030
- };
2031
- DatabaseModel.prototype[`count${capitalize(queryKey)}`] = async function(...args) {
2032
- const query = queryFn(...args);
2033
- return this.__count(query);
2034
- };
2035
- DatabaseModel.prototype[`insight${capitalize(queryKey)}`] = async function(...args) {
2036
- const query = queryFn(...args);
2037
- return this.__insight(query);
2038
- };
2039
- });
2040
- const loaderMetas = getLoaderMetas(database.Model);
2041
- loaderMetas.forEach((loaderMeta) => {
2042
- const loader2 = loaderMeta.type === "Field" ? createLoader(model, loaderMeta.fieldName) : loaderMeta.type === "ArrayField" ? createArrayLoader(model, loaderMeta.fieldName) : loaderMeta.type === "Query" ? createQueryLoader(model, loaderMeta.queryKeys ?? []) : null;
2043
- DatabaseModel.prototype[loaderMeta.key] = loader2;
2044
- });
2045
- Object.getOwnPropertyNames(database.Model.prototype).forEach((key) => {
2046
- DatabaseModel.prototype[key] = database.Model.prototype[key];
2047
- });
2048
- const createDescriptor = Object.getOwnPropertyDescriptor(DatabaseModel.prototype, `create${className}`);
2049
- if (createDescriptor)
2050
- Transaction()(DatabaseModel.prototype, `create${className}`, createDescriptor);
2051
- const updateDescriptor = Object.getOwnPropertyDescriptor(DatabaseModel.prototype, `update${className}`);
2052
- if (updateDescriptor)
2053
- Transaction()(DatabaseModel.prototype, `update${className}`, updateDescriptor);
2054
- const removeDescriptor = Object.getOwnPropertyDescriptor(DatabaseModel.prototype, `remove${className}`);
2055
- if (removeDescriptor)
2056
- Transaction()(DatabaseModel.prototype, `remove${className}`, removeDescriptor);
2057
- Reflect.defineMetadata(database.refName, DatabaseModel, DatabaseModelStorage.prototype);
2058
- return new DatabaseModel();
2059
- };
2060
- })();
2061
- //! Nextjs는 환경변수를 build time에 그냥 하드코딩으로 값을 넣어버림. operationMode같은것들 잘 동작안할 수 있음. 추후 수정 필요.
2062
- //! 잘되는지 확인 필요
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from))
8
+ if (!__hasOwnProp.call(to, key) && key !== except)
9
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
+ }
11
+ return to;
12
+ };
13
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
14
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
+ var index_exports = {};
16
+ module.exports = __toCommonJS(index_exports);
17
+ __reExport(index_exports, require("./src"), module.exports);
18
+ // Annotate the CommonJS export names for ESM import in node:
19
+ 0 && (module.exports = {
20
+ ...require("./src")
21
+ });