@akanjs/document 0.0.44 → 0.0.45

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