@akanjs/signal 0.0.40 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/gql.js DELETED
@@ -1,958 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var gql_exports = {};
20
- __export(gql_exports, {
21
- CrystalizeStorage: () => CrystalizeStorage,
22
- DefaultStorage: () => DefaultStorage,
23
- FragmentStorage: () => FragmentStorage,
24
- GqlStorage: () => GqlStorage,
25
- PurifyStorage: () => PurifyStorage,
26
- deserializeArg: () => deserializeArg,
27
- fetchOf: () => fetchOf,
28
- getGqlOnStorage: () => getGqlOnStorage,
29
- getGqlStr: () => getGqlStr,
30
- gqlOf: () => gqlOf,
31
- makeCrystalize: () => makeCrystalize,
32
- makeDefault: () => makeDefault,
33
- makeFetch: () => makeFetch,
34
- makeFragment: () => makeFragment,
35
- makePurify: () => makePurify,
36
- scalarUtilOf: () => scalarUtilOf,
37
- serializeArg: () => serializeArg
38
- });
39
- module.exports = __toCommonJS(gql_exports);
40
- var import_base = require("@akanjs/base");
41
- var import_common = require("@akanjs/common");
42
- var import_constant = require("@akanjs/constant");
43
- var import__ = require(".");
44
- var import_signalDecorators = require("./signalDecorators");
45
- function graphql(literals, ...args) {
46
- if (typeof literals === "string") literals = [
47
- literals
48
- ];
49
- let result = literals[0];
50
- args.forEach((arg, i) => {
51
- if (arg && arg.kind === "Document") result += arg.loc.source.body;
52
- else result += arg;
53
- result += literals[i + 1];
54
- });
55
- return result;
56
- }
57
- __name(graphql, "graphql");
58
- class GqlStorage {
59
- static {
60
- __name(this, "GqlStorage");
61
- }
62
- }
63
- class FragmentStorage {
64
- static {
65
- __name(this, "FragmentStorage");
66
- }
67
- }
68
- class PurifyStorage {
69
- static {
70
- __name(this, "PurifyStorage");
71
- }
72
- }
73
- class DefaultStorage {
74
- static {
75
- __name(this, "DefaultStorage");
76
- }
77
- }
78
- class CrystalizeStorage {
79
- static {
80
- __name(this, "CrystalizeStorage");
81
- }
82
- }
83
- const scalarUtilOf = /* @__PURE__ */ __name((name, target) => {
84
- const refName = (0, import_constant.getClassMeta)(target).refName;
85
- const [fieldName, className] = [
86
- (0, import_common.lowerlize)(refName),
87
- (0, import_common.capitalize)(refName)
88
- ];
89
- const graphQL = {
90
- refName,
91
- [className]: target,
92
- [`default${className}`]: (0, import__.immerify)(target, Object.assign(new target(), makeDefault(target))),
93
- [`purify${className}`]: makePurify(target),
94
- [`crystalize${className}`]: makeCrystalize(target),
95
- [`${fieldName}Fragment`]: makeFragment(target)
96
- };
97
- return graphQL;
98
- }, "scalarUtilOf");
99
- const getGqlOnStorage = /* @__PURE__ */ __name((refName) => {
100
- const modelGql = Reflect.getMetadata(refName, GqlStorage.prototype);
101
- if (!modelGql) throw new Error("Gql is not defined");
102
- return modelGql;
103
- }, "getGqlOnStorage");
104
- const setGqlOnStorage = /* @__PURE__ */ __name((refName, modelGql) => {
105
- Reflect.defineMetadata(refName, modelGql, GqlStorage.prototype);
106
- }, "setGqlOnStorage");
107
- const gqlOf = /* @__PURE__ */ __name((constant, sigRef, option = {}) => {
108
- const refName = constant.refName;
109
- const [fieldName, className] = [
110
- (0, import_common.lowerlize)(refName),
111
- (0, import_common.capitalize)(refName)
112
- ];
113
- const sigMeta = (0, import_signalDecorators.getSigMeta)(sigRef);
114
- const names = {
115
- refName,
116
- model: fieldName,
117
- Model: className,
118
- _model: `_${fieldName}`,
119
- lightModel: `light${className}`,
120
- _lightModel: `_light${className}`,
121
- purifyModel: `purify${className}`,
122
- crystalizeModel: `crystalize${className}`,
123
- lightCrystalizeModel: `lightCrystalize${className}`,
124
- crystalizeModelInsight: `crystalize${className}Insight`,
125
- defaultModel: `default${className}`,
126
- defaultModelInsight: `default${className}Insight`,
127
- mergeModel: `merge${className}`,
128
- viewModel: `view${className}`,
129
- getModelView: `get${className}View`,
130
- modelView: `${fieldName}View`,
131
- modelViewAt: `${fieldName}ViewAt`,
132
- editModel: `edit${className}`,
133
- getModelEdit: `get${className}Edit`,
134
- modelEdit: `${fieldName}Edit`,
135
- listModel: `list${className}`,
136
- modelList: `${fieldName}List`,
137
- modelObjList: `${fieldName}ObjList`,
138
- modelInsight: `${fieldName}Insight`,
139
- modelObjInsight: `${fieldName}ObjInsight`,
140
- updateModel: `update${className}`,
141
- modelObj: `${fieldName}Obj`,
142
- _modelList: `_${fieldName}List`,
143
- modelInit: `${fieldName}Init`,
144
- pageOfModel: `pageOf${className}`,
145
- lastPageOfModel: `lastPageOf${className}`,
146
- limitOfModel: `limitOf${className}`,
147
- queryArgsOfModel: `queryArgsOf${className}`,
148
- sortOfModel: `sortOf${className}`,
149
- modelInitAt: `${fieldName}InitAt`,
150
- initModel: `init${className}`,
151
- getModelInit: `get${className}Init`,
152
- addModelFiles: `add${className}Files`
153
- };
154
- const base = {
155
- refName,
156
- [names.purifyModel]: makePurify(constant.Input, option),
157
- [names.crystalizeModel]: makeCrystalize(constant.Full, option),
158
- [names.lightCrystalizeModel]: makeCrystalize(constant.Light, option),
159
- [names.crystalizeModelInsight]: makeCrystalize(constant.Insight, option),
160
- [names.defaultModel]: (0, import__.immerify)(constant.Full, Object.assign(new constant.Full(), makeDefault(constant.Full, option))),
161
- [names.defaultModelInsight]: Object.assign(new constant.Insight(), makeDefault(constant.Insight, option))
162
- };
163
- const gql = Object.assign(option.overwrite ?? {
164
- client: import__.client
165
- }, fetchOf(sigRef));
166
- const util = {
167
- [names.addModelFiles]: async (files, id, option2) => {
168
- const fileGql = getGqlOnStorage("file");
169
- const metas = Array.from(files).map((file) => ({
170
- lastModifiedAt: new Date(file.lastModified),
171
- size: file.size
172
- }));
173
- return await fileGql.addFiles(files, metas, names.model, id, option2);
174
- },
175
- [names.mergeModel]: async (modelOrId, data, option2) => {
176
- const model = typeof modelOrId === "string" ? await gql[names._model](modelOrId) : modelOrId;
177
- const input = base[names.purifyModel]({
178
- ...model,
179
- ...data
180
- });
181
- if (!input) throw new Error("Error");
182
- return await gql[names.updateModel](model.id, input, option2);
183
- },
184
- [names.viewModel]: async (id, option2) => {
185
- const modelObj = await gql[names._model](id, option2);
186
- return {
187
- [names.model]: base[names.crystalizeModel](modelObj),
188
- [names.modelView]: {
189
- refName: names.model,
190
- [names.modelObj]: modelObj,
191
- [names.modelViewAt]: /* @__PURE__ */ new Date()
192
- }
193
- };
194
- },
195
- [names.getModelView]: async (id, option2) => {
196
- const modelView = await gql[names._model](id, option2);
197
- return {
198
- refName: names.model,
199
- [names.modelObj]: modelView,
200
- [names.modelViewAt]: /* @__PURE__ */ new Date()
201
- };
202
- },
203
- [names.editModel]: async (id, option2) => {
204
- const modelObj = await gql[names._model](id, option2);
205
- return {
206
- [names.model]: base[names.crystalizeModel](modelObj),
207
- [names.modelEdit]: {
208
- refName: names.model,
209
- [names.modelObj]: modelObj,
210
- [names.modelViewAt]: /* @__PURE__ */ new Date()
211
- }
212
- };
213
- },
214
- [names.getModelEdit]: async (id, option2) => {
215
- const modelEdit = await gql[names.editModel](id, option2);
216
- return modelEdit[names.modelEdit];
217
- }
218
- };
219
- const sliceUtil = Object.fromEntries(sigMeta.slices.reduce((acc, { sliceName, argLength, defaultArgs }) => {
220
- const namesOfSlice = {
221
- modelList: sliceName.replace(names.model, names.modelList),
222
- modelInsight: sliceName.replace(names.model, names.modelInsight),
223
- modelInit: sliceName.replace(names.model, names.modelInit),
224
- initModel: sliceName.replace(names.model, names.initModel),
225
- getModelInit: sliceName.replace(names.model, names.getModelInit)
226
- };
227
- const getInitFn = /* @__PURE__ */ __name(async (...args) => {
228
- const queryArgLength = Math.min(args.length, argLength);
229
- const queryArgs = [
230
- ...new Array(queryArgLength).fill(null).map((_, i) => args[i]),
231
- ...queryArgLength < argLength ? new Array(argLength - queryArgLength).fill(null).map((_, i) => defaultArgs[i + queryArgLength] ?? null) : []
232
- ];
233
- const fetchInitOption = args[argLength] ?? {};
234
- const { page = 1, limit = 20, sort = "latest", insight } = fetchInitOption;
235
- const skip = (page - 1) * limit;
236
- const [modelObjList, modelObjInsight] = await Promise.all([
237
- gql[`_${namesOfSlice.modelList}`](...queryArgs, skip, limit, sort, fetchInitOption),
238
- gql[`_${namesOfSlice.modelInsight}`](...queryArgs, fetchInitOption)
239
- ]);
240
- const count = modelObjInsight.count;
241
- return {
242
- // Client Component용
243
- refName: names.model,
244
- sliceName,
245
- argLength,
246
- [names.modelObjList]: modelObjList,
247
- [names.modelObjInsight]: modelObjInsight,
248
- [names.pageOfModel]: page,
249
- [names.lastPageOfModel]: Math.max(Math.floor((count - 1) / limit) + 1, 1),
250
- [names.limitOfModel]: limit,
251
- [names.queryArgsOfModel]: JSON.parse(JSON.stringify(queryArgs)),
252
- [names.sortOfModel]: sort,
253
- [names.modelInitAt]: /* @__PURE__ */ new Date()
254
- };
255
- }, "getInitFn");
256
- const initFn = /* @__PURE__ */ __name(async (...args) => {
257
- const modelInit = await getInitFn(...args);
258
- const modelObjList = modelInit[names.modelObjList];
259
- const modelObjInsight = modelInit[names.modelObjInsight];
260
- const modelList = new import_base.DataList(modelObjList.map((modelObj) => base[names.lightCrystalizeModel](modelObj)));
261
- const modelInsight = base[names.crystalizeModelInsight](modelObjInsight);
262
- return {
263
- [namesOfSlice.modelList]: modelList,
264
- [namesOfSlice.modelInsight]: modelInsight,
265
- [namesOfSlice.modelInit]: modelInit
266
- };
267
- }, "initFn");
268
- return [
269
- ...acc,
270
- [
271
- namesOfSlice.getModelInit,
272
- getInitFn
273
- ],
274
- [
275
- namesOfSlice.initModel,
276
- initFn
277
- ]
278
- ];
279
- }, []));
280
- const overwriteSlices = option.overwrite ? option.overwrite.slices.filter((slice) => !sigMeta.slices.some((s) => s.sliceName === slice.sliceName)) : [];
281
- const modelGql = Object.assign(option.overwrite ?? {}, {
282
- ...gql,
283
- ...base,
284
- ...util,
285
- ...sliceUtil,
286
- slices: [
287
- ...overwriteSlices,
288
- ...sigMeta.slices
289
- ]
290
- });
291
- setGqlOnStorage(refName, modelGql);
292
- return modelGql;
293
- }, "gqlOf");
294
- const getPredefinedDefault = /* @__PURE__ */ __name((refName) => {
295
- const defaultData = Reflect.getMetadata(refName, DefaultStorage.prototype);
296
- return defaultData;
297
- }, "getPredefinedDefault");
298
- const setPredefinedDefault = /* @__PURE__ */ __name((refName, defaultData) => {
299
- Reflect.defineMetadata(refName, defaultData, DefaultStorage.prototype);
300
- }, "setPredefinedDefault");
301
- const makeDefault = /* @__PURE__ */ __name((target, option = {}) => {
302
- const classMeta = (0, import_constant.getClassMeta)(target);
303
- const predefinedDefault = getPredefinedDefault(classMeta.refName);
304
- if (predefinedDefault && !option.overwrite) return predefinedDefault;
305
- if (option.isChild && classMeta.type !== "scalar") return null;
306
- const metadatas = (0, import_constant.getFieldMetas)(target);
307
- const result = {};
308
- for (const metadata of metadatas) {
309
- if (metadata.fieldType === "hidden") result[metadata.key] = null;
310
- else if (metadata.default) {
311
- if (typeof metadata.default === "function") result[metadata.key] = metadata.default();
312
- else if (metadata.default instanceof import_base.Enum) result[metadata.key] = [
313
- ...metadata.default.values
314
- ];
315
- else result[metadata.key] = metadata.default;
316
- } else if (metadata.isArray) result[metadata.key] = [];
317
- else if (metadata.nullable) result[metadata.key] = null;
318
- else if (metadata.isClass) result[metadata.key] = metadata.isScalar ? makeDefault(metadata.modelRef) : null;
319
- else result[metadata.key] = import_base.scalarDefaultMap.get(metadata.modelRef);
320
- }
321
- setPredefinedDefault(classMeta.refName, result);
322
- return result;
323
- }, "makeDefault");
324
- const query = /* @__PURE__ */ __name(async (fetchClient, query2, variables = {}, option = {}) => {
325
- const jwt = option.url ? null : await fetchClient.getJwt();
326
- const { data, error } = await fetchClient.gql.query(query2, variables, {
327
- fetch,
328
- url: option.url ?? fetchClient.uri,
329
- requestPolicy: typeof option.cache === "string" ? option.cache : option.cache === true ? "cache-first" : "network-only",
330
- fetchOptions: {
331
- ...typeof option.cache === "number" ? {
332
- next: {
333
- revalidate: option.cache
334
- }
335
- } : option.cache === true ? {
336
- cache: "force-cache"
337
- } : {
338
- cache: "no-store"
339
- },
340
- headers: {
341
- "apollo-require-preflight": "true",
342
- ...jwt ? {
343
- authorization: `Bearer ${jwt}`
344
- } : {},
345
- ...option.token ? {
346
- authorization: `Bearer ${option.token}`
347
- } : {}
348
- }
349
- }
350
- }).toPromise();
351
- if (!data) {
352
- const content = error?.graphQLErrors[0]?.message ?? "Unknown Error";
353
- if (option.onError) {
354
- option.onError(content);
355
- return;
356
- } else throw new Error(content);
357
- }
358
- return data;
359
- }, "query");
360
- const mutate = /* @__PURE__ */ __name(async (fetchClient, mutation, variables = {}, option = {}) => {
361
- const jwt = option.url ? null : await fetchClient.getJwt();
362
- const { data, error } = await fetchClient.gql.mutation(mutation, variables, {
363
- fetch,
364
- url: option.url ?? fetchClient.uri,
365
- requestPolicy: "network-only",
366
- fetchOptions: {
367
- cache: "no-store",
368
- headers: {
369
- "apollo-require-preflight": "true",
370
- ...jwt ? {
371
- authorization: `Bearer ${jwt}`
372
- } : {},
373
- ...option.token ? {
374
- authorization: `Bearer ${option.token}`
375
- } : {}
376
- }
377
- }
378
- }).toPromise();
379
- if (!data) {
380
- const content = error?.graphQLErrors[0]?.message ?? "Unknown Error";
381
- if (option.onError) {
382
- option.onError(content);
383
- return;
384
- } else throw new Error(content);
385
- }
386
- return data;
387
- }, "mutate");
388
- const scalarPurifyMap = /* @__PURE__ */ new Map([
389
- [
390
- Date,
391
- (value) => (0, import_base.dayjs)(value).toDate()
392
- ],
393
- [
394
- String,
395
- (value) => value
396
- ],
397
- [
398
- import_base.ID,
399
- (value) => value
400
- ],
401
- [
402
- Boolean,
403
- (value) => value
404
- ],
405
- [
406
- import_base.Int,
407
- (value) => value
408
- ],
409
- [
410
- import_base.Float,
411
- (value) => value
412
- ],
413
- [
414
- import_base.JSON,
415
- (value) => value
416
- ]
417
- ]);
418
- const getPurifyFn = /* @__PURE__ */ __name((modelRef) => {
419
- const [valueRef] = (0, import_base.getNonArrayModel)(modelRef);
420
- return scalarPurifyMap.get(valueRef) ?? ((value) => value);
421
- }, "getPurifyFn");
422
- const purify = /* @__PURE__ */ __name((metadata, value, self) => {
423
- if (metadata.nullable && (value === null || value === void 0 || typeof value === "number" && isNaN(value) || typeof value === "string" && !value.length)) return null;
424
- if (metadata.isArray) {
425
- if (!Array.isArray(value)) throw new Error(`Invalid Array Value in ${metadata.key} for value ${value}`);
426
- if (metadata.minlength && value.length < metadata.minlength) throw new Error(`Invalid Array Length (Min) in ${metadata.key} for value ${value}`);
427
- else if (metadata.maxlength && value.length > metadata.maxlength) throw new Error(`Invalid Array Length (Max) in ${metadata.key} for value ${value}`);
428
- else if (metadata.optArrDepth === 0 && metadata.validate && !metadata.validate(value, self)) throw new Error(`Invalid Array Value (Failed to pass validation) in ${metadata.key} for value ${value}`);
429
- return value.map((v) => purify({
430
- ...metadata,
431
- isArray: false
432
- }, v, v));
433
- }
434
- if (metadata.isMap && metadata.of) {
435
- const purifyFn2 = getPurifyFn(metadata.of);
436
- return Object.fromEntries([
437
- ...value.entries()
438
- ].map(([key, val]) => [
439
- key,
440
- (0, import_base.applyFnToArrayObjects)(val, purifyFn2)
441
- ]));
442
- }
443
- if (metadata.isClass) return makePurify(metadata.modelRef)(value, true);
444
- if (metadata.name === "Date" && (0, import_base.dayjs)(value).isBefore((0, import_base.dayjs)(/* @__PURE__ */ new Date("0000")))) throw new Error(`Invalid Date Value (Default) in ${metadata.key} for value ${value}`);
445
- if ([
446
- "String",
447
- "ID"
448
- ].includes(metadata.name) && (value === "" || !value)) throw new Error(`Invalid String Value (Default) in ${metadata.key} for value ${value}`);
449
- if (metadata.validate && !metadata.validate(value, self)) throw new Error(`Invalid Value (Failed to pass validation) / ${value} in ${metadata.key}`);
450
- if (!metadata.nullable && !value && value !== 0 && value !== false) throw new Error(`Invalid Value (Nullable) in ${metadata.key} for value ${value}`);
451
- const purifyFn = getPurifyFn(metadata.modelRef);
452
- return purifyFn(value);
453
- }, "purify");
454
- const getPredefinedPurifyFn = /* @__PURE__ */ __name((refName) => {
455
- const purify2 = Reflect.getMetadata(refName, PurifyStorage.prototype);
456
- return purify2;
457
- }, "getPredefinedPurifyFn");
458
- const setPredefinedPurifyFn = /* @__PURE__ */ __name((refName, purify2) => {
459
- Reflect.defineMetadata(refName, purify2, PurifyStorage.prototype);
460
- }, "setPredefinedPurifyFn");
461
- const makePurify = /* @__PURE__ */ __name((target, option = {}) => {
462
- const classMeta = (0, import_constant.getClassMeta)(target);
463
- const purifyFn = getPredefinedPurifyFn(classMeta.refName);
464
- if (purifyFn && !option.overwrite) return purifyFn;
465
- const metadatas = (0, import_constant.getFieldMetas)(target);
466
- const fn = /* @__PURE__ */ __name((self, isChild) => {
467
- try {
468
- if (isChild && classMeta.type !== "scalar") {
469
- const id = self.id;
470
- if (!id) throw new Error(`Invalid Value (No ID) for id ${classMeta.refName}`);
471
- return id;
472
- }
473
- const result = {};
474
- for (const metadata of metadatas) {
475
- const value = self[metadata.key];
476
- result[metadata.key] = purify(metadata, value, self);
477
- }
478
- return result;
479
- } catch (err) {
480
- if (isChild) throw new Error(err);
481
- import_common.Logger.debug(err);
482
- return null;
483
- }
484
- }, "fn");
485
- setPredefinedPurifyFn(classMeta.refName, fn);
486
- return fn;
487
- }, "makePurify");
488
- const scalarCrystalizeMap = /* @__PURE__ */ new Map([
489
- [
490
- Date,
491
- (value) => (0, import_base.dayjs)(value)
492
- ],
493
- [
494
- String,
495
- (value) => value
496
- ],
497
- [
498
- import_base.ID,
499
- (value) => value
500
- ],
501
- [
502
- Boolean,
503
- (value) => value
504
- ],
505
- [
506
- import_base.Int,
507
- (value) => value
508
- ],
509
- [
510
- import_base.Float,
511
- (value) => value
512
- ],
513
- [
514
- import_base.JSON,
515
- (value) => value
516
- ]
517
- ]);
518
- const crystalize = /* @__PURE__ */ __name((metadata, value) => {
519
- if (value === void 0 || value === null) return value;
520
- if (metadata.isArray && Array.isArray(value)) return value.map((v) => crystalize({
521
- ...metadata,
522
- isArray: false
523
- }, v));
524
- if (metadata.isMap) {
525
- const [valueRef] = (0, import_base.getNonArrayModel)(metadata.of);
526
- const crystalizeValue = scalarCrystalizeMap.get(valueRef) ?? ((value2) => value2);
527
- return new Map(Object.entries(value).map(([key, val]) => [
528
- key,
529
- (0, import_base.applyFnToArrayObjects)(val, crystalizeValue)
530
- ]));
531
- }
532
- if (metadata.isClass) return makeCrystalize(metadata.modelRef)(value, true);
533
- if (metadata.name === "Date") return (0, import_base.dayjs)(value);
534
- return (scalarCrystalizeMap.get(metadata.modelRef) ?? ((value2) => value2))(value);
535
- }, "crystalize");
536
- const getPredefinedCrystalizeFn = /* @__PURE__ */ __name((refName) => {
537
- const crystalize2 = Reflect.getMetadata(refName, CrystalizeStorage.prototype);
538
- return crystalize2;
539
- }, "getPredefinedCrystalizeFn");
540
- const setPredefinedCrystalizeFn = /* @__PURE__ */ __name((refName, crystalize2) => {
541
- Reflect.defineMetadata(refName, crystalize2, CrystalizeStorage.prototype);
542
- }, "setPredefinedCrystalizeFn");
543
- const makeCrystalize = /* @__PURE__ */ __name((target, option = {}) => {
544
- const classMeta = (0, import_constant.getClassMeta)(target);
545
- const crystalizeFn = getPredefinedCrystalizeFn(classMeta.refName);
546
- if (crystalizeFn && !option.overwrite && !option.partial?.length) return crystalizeFn;
547
- const fieldMetaMap = (0, import_constant.getFieldMetaMap)(target);
548
- const fieldKeys = option.partial?.length ? classMeta.type === "scalar" ? option.partial : [
549
- "id",
550
- ...option.partial,
551
- "updatedAt"
552
- ] : [
553
- ...fieldMetaMap.keys()
554
- ];
555
- const metadatas = fieldKeys.map((key) => fieldMetaMap.get(key));
556
- const fn = /* @__PURE__ */ __name((self, isChild) => {
557
- try {
558
- const result = Object.assign(new target(), self);
559
- for (const metadata of metadatas.filter((m) => !!self[m.key])) {
560
- if (metadata.fieldType === "hidden") continue;
561
- result[metadata.key] = crystalize(metadata, self[metadata.key]);
562
- }
563
- return result;
564
- } catch (err) {
565
- if (isChild) throw new Error(err);
566
- return null;
567
- }
568
- }, "fn");
569
- if (!option.partial?.length) setPredefinedCrystalizeFn(classMeta.refName, fn);
570
- return fn;
571
- }, "makeCrystalize");
572
- const fragmentize = /* @__PURE__ */ __name((target, fragMap = /* @__PURE__ */ new Map(), partial) => {
573
- const classMeta = (0, import_constant.getClassMeta)(target);
574
- const metadatas = (0, import_constant.getFieldMetas)(target);
575
- const selectKeys = partial ? [
576
- "id",
577
- ...partial,
578
- "updatedAt"
579
- ] : metadatas.map((metadata) => metadata.key);
580
- const selectKeySet = new Set(selectKeys);
581
- const fragment = `fragment ${(0, import_common.lowerlize)(classMeta.refName)}Fragment on ${(0, import_common.capitalize)(classMeta.type === "light" ? classMeta.refName.slice(5) : classMeta.refName)} {
582
- ` + metadatas.filter((metadata) => metadata.fieldType !== "hidden" && selectKeySet.has(metadata.key)).map((metadata) => {
583
- return metadata.isClass ? ` ${metadata.key} {
584
- ...${(0, import_common.lowerlize)(metadata.name)}Fragment
585
- }` : ` ${metadata.key}`;
586
- }).join(`
587
- `) + `
588
- }`;
589
- fragMap.set(classMeta.refName, fragment);
590
- metadatas.filter((metadata) => metadata.fieldType !== "hidden" && selectKeySet.has(metadata.key) && metadata.isClass).forEach((metadata) => fragmentize(metadata.modelRef, fragMap));
591
- return fragMap;
592
- }, "fragmentize");
593
- const getPredefinedFragment = /* @__PURE__ */ __name((refName) => {
594
- const fragment = Reflect.getMetadata(refName, FragmentStorage.prototype);
595
- return fragment;
596
- }, "getPredefinedFragment");
597
- const setPredefinedFragment = /* @__PURE__ */ __name((refName, fragment) => {
598
- Reflect.defineMetadata(refName, fragment, FragmentStorage.prototype);
599
- }, "setPredefinedFragment");
600
- const makeFragment = /* @__PURE__ */ __name((target, option = {}) => {
601
- const classMeta = (0, import_constant.getClassMeta)(target);
602
- const fragment = getPredefinedFragment(classMeta.refName);
603
- if (fragment && !option.overwrite && !option.excludeSelf && !option.partial?.length) return fragment;
604
- const fragMap = new Map(fragmentize(target, /* @__PURE__ */ new Map(), option.partial));
605
- if (option.excludeSelf) fragMap.delete(classMeta.refName);
606
- const gqlStr = [
607
- ...fragMap.values()
608
- ].join("\n");
609
- if (!option.excludeSelf) setPredefinedFragment(classMeta.refName, gqlStr);
610
- return gqlStr;
611
- }, "makeFragment");
612
- const getGqlStr = /* @__PURE__ */ __name((modelRef, gqlMeta, argMetas, returnRef, partial) => {
613
- const isScalar = (0, import_base.isGqlScalar)(modelRef);
614
- const argStr = makeArgStr(argMetas);
615
- const argAssignStr = makeArgAssignStr(argMetas);
616
- const returnStr = makeReturnStr(returnRef, partial);
617
- const gqlStr = `${isScalar ? "" : makeFragment(returnRef, {
618
- excludeSelf: !!partial?.length,
619
- partial
620
- })}
621
- ${(0, import_common.lowerlize)(gqlMeta.type) + " " + gqlMeta.key + argStr}{
622
- ${gqlMeta.key}${argAssignStr}${returnStr}
623
- }
624
- `;
625
- return gqlStr;
626
- }, "getGqlStr");
627
- const scalarSerializeMap = /* @__PURE__ */ new Map([
628
- [
629
- Date,
630
- (value) => (0, import_base.dayjs)(value).toDate()
631
- ],
632
- [
633
- String,
634
- (value) => value
635
- ],
636
- [
637
- import_base.ID,
638
- (value) => value
639
- ],
640
- [
641
- Boolean,
642
- (value) => value
643
- ],
644
- [
645
- import_base.Int,
646
- (value) => value
647
- ],
648
- [
649
- import_base.Float,
650
- (value) => value
651
- ],
652
- [
653
- import_base.JSON,
654
- (value) => value
655
- ]
656
- ]);
657
- const getSerializeFn = /* @__PURE__ */ __name((inputRef) => {
658
- const serializeFn = scalarSerializeMap.get(inputRef);
659
- if (!serializeFn) return (value) => value;
660
- else return serializeFn;
661
- }, "getSerializeFn");
662
- const serializeInput = /* @__PURE__ */ __name((value, inputRef, arrDepth) => {
663
- if (arrDepth && Array.isArray(value)) return value.map((v) => serializeInput(v, inputRef, arrDepth - 1));
664
- else if (inputRef.prototype === Map.prototype) {
665
- const [valueRef] = (0, import_base.getNonArrayModel)(inputRef);
666
- const serializeFn = getSerializeFn(valueRef);
667
- return Object.fromEntries([
668
- ...value.entries()
669
- ].map(([key, val]) => [
670
- key,
671
- (0, import_base.applyFnToArrayObjects)(val, serializeFn)
672
- ]));
673
- } else if ((0, import_base.isGqlScalar)(inputRef)) {
674
- const serializeFn = getSerializeFn(inputRef);
675
- return serializeFn(value);
676
- }
677
- const classMeta = (0, import_constant.getClassMeta)(inputRef);
678
- if (classMeta.type !== "scalar") return value;
679
- else return Object.fromEntries((0, import_constant.getFieldMetas)(inputRef).map((fieldMeta) => [
680
- fieldMeta.key,
681
- serializeInput(value[fieldMeta.key], fieldMeta.modelRef, fieldMeta.arrDepth)
682
- ]));
683
- }, "serializeInput");
684
- const serializeArg = /* @__PURE__ */ __name((argMeta, value) => {
685
- const [returnRef, arrDepth] = (0, import_base.getNonArrayModel)(argMeta.returns());
686
- if (argMeta.argsOption.nullable && (value === null || value === void 0)) return null;
687
- else if (!argMeta.argsOption.nullable && (value === null || value === void 0)) throw new Error(`Invalid Value (Nullable) in ${argMeta.name} for value ${value}`);
688
- return serializeInput(value, returnRef, arrDepth);
689
- }, "serializeArg");
690
- const scalarDeserializeMap = /* @__PURE__ */ new Map([
691
- [
692
- Date,
693
- (value) => (0, import_base.dayjs)(value)
694
- ],
695
- [
696
- String,
697
- (value) => value
698
- ],
699
- [
700
- import_base.ID,
701
- (value) => value
702
- ],
703
- [
704
- Boolean,
705
- (value) => value
706
- ],
707
- [
708
- import_base.Int,
709
- (value) => value
710
- ],
711
- [
712
- import_base.Float,
713
- (value) => value
714
- ],
715
- [
716
- import_base.JSON,
717
- (value) => value
718
- ]
719
- ]);
720
- const getDeserializeFn = /* @__PURE__ */ __name((inputRef) => {
721
- const deserializeFn = scalarDeserializeMap.get(inputRef);
722
- if (!deserializeFn) return (value) => value;
723
- return deserializeFn;
724
- }, "getDeserializeFn");
725
- const deserializeInput = /* @__PURE__ */ __name((value, inputRef, arrDepth) => {
726
- if (arrDepth && Array.isArray(value)) return value.map((v) => deserializeInput(v, inputRef, arrDepth - 1));
727
- else if (inputRef.prototype === Map.prototype) {
728
- const [valueRef] = (0, import_base.getNonArrayModel)(inputRef);
729
- const deserializeFn = getDeserializeFn(valueRef);
730
- return Object.fromEntries([
731
- ...value.entries()
732
- ].map(([key, val]) => [
733
- key,
734
- (0, import_base.applyFnToArrayObjects)(val, deserializeFn)
735
- ]));
736
- } else if ((0, import_base.isGqlScalar)(inputRef)) {
737
- const deserializeFn = getDeserializeFn(inputRef);
738
- return deserializeFn(value);
739
- }
740
- const classMeta = (0, import_constant.getClassMeta)(inputRef);
741
- if (classMeta.type !== "scalar") return value;
742
- else return Object.fromEntries((0, import_constant.getFieldMetas)(inputRef).map((fieldMeta) => [
743
- fieldMeta.key,
744
- deserializeInput(value[fieldMeta.key], fieldMeta.modelRef, fieldMeta.arrDepth)
745
- ]));
746
- }, "deserializeInput");
747
- const deserializeArg = /* @__PURE__ */ __name((argMeta, value) => {
748
- const [returnRef, arrDepth] = (0, import_base.getNonArrayModel)(argMeta.returns());
749
- if (argMeta.argsOption.nullable && (value === null || value === void 0)) return null;
750
- else if (!argMeta.argsOption.nullable && (value === null || value === void 0)) throw new Error(`Invalid Value (Nullable) in ${argMeta.name} for value ${value}`);
751
- return deserializeInput(value, returnRef, arrDepth);
752
- }, "deserializeArg");
753
- const fetchOf = /* @__PURE__ */ __name((sigRef) => {
754
- const gqls = {};
755
- const gqlMetas = (0, import_signalDecorators.getGqlMetas)(sigRef);
756
- gqlMetas.filter((gqlMeta) => !gqlMeta.signalOption.default).forEach((gqlMeta) => {
757
- if (gqlMeta.type === "Message") {
758
- const [returnRef, arrDepth] = (0, import_base.getNonArrayModel)(gqlMeta.returns());
759
- const [argMetas] = (0, import_signalDecorators.getArgMetas)(sigRef, gqlMeta.signalOption.name ?? gqlMeta.key);
760
- const isScalar = (0, import_base.isGqlScalar)(returnRef);
761
- const emitEvent = /* @__PURE__ */ __name(function(...args) {
762
- const fetchPolicy = args[argMetas.length] ?? {
763
- crystalize: true
764
- };
765
- if (!this.client.io && !fetchPolicy.url) {
766
- import_common.Logger.warn(`${gqlMeta.key} emit suppressed - socket is not connected`);
767
- return;
768
- }
769
- const message = Object.fromEntries(argMetas.map((argMeta) => [
770
- argMeta.name,
771
- serializeArg(argMeta, args[argMeta.idx]) ?? null
772
- ]));
773
- if (fetchPolicy.transport === "udp") {
774
- if (!this.client.udp) throw new Error("UDP is not set");
775
- const uri = fetchPolicy.url ?? "udpout:localhost:4000";
776
- const [host, port] = uri.split(":").slice(1);
777
- this.client.udp.send(JSON.stringify(message), parseInt(port), host);
778
- import_common.Logger.debug(`udp emit: ${gqlMeta.key}: ${(0, import_base.dayjs)().format("YYYY-MM-DD HH:mm:ss.SSS")}`);
779
- return;
780
- } else {
781
- const io = this.client.getIo(fetchPolicy.url);
782
- void this.client.waitUntilWebSocketConnected(fetchPolicy.url).then(() => {
783
- io.emit(gqlMeta.key, message);
784
- import_common.Logger.debug(`socket emit: ${gqlMeta.key}: ${(0, import_base.dayjs)().format("YYYY-MM-DD HH:mm:ss.SSS")}`);
785
- });
786
- }
787
- }, "emitEvent");
788
- const listenEvent = /* @__PURE__ */ __name(function(handleEvent, fetchPolicy = {}) {
789
- const crystalize2 = /* @__PURE__ */ __name((data) => {
790
- if (isScalar) {
791
- if (returnRef.prototype === Date.prototype) return (0, import_base.dayjs)(data);
792
- else return data;
793
- } else if (Array.isArray(data)) return data.map((d) => crystalize2(d));
794
- else return makeCrystalize(returnRef)(data);
795
- }, "crystalize");
796
- const handle = /* @__PURE__ */ __name((data) => {
797
- import_common.Logger.debug(`socket listened: ${gqlMeta.key}: ${(0, import_base.dayjs)().format("YYYY-MM-DD HH:mm:ss.SSS")}`);
798
- handleEvent(crystalize2(data));
799
- }, "handle");
800
- const io = this.client.getIo(fetchPolicy.url);
801
- this.client.waitUntilWebSocketConnected(fetchPolicy.url).then(() => {
802
- io.removeListener(gqlMeta.key, handle);
803
- io.on(gqlMeta.key, handle);
804
- import_common.Logger.debug(`socket listen start: ${gqlMeta.key}: ${(0, import_base.dayjs)().format("YYYY-MM-DD HH:mm:ss.SSS")}`);
805
- });
806
- return async () => {
807
- await this.client.waitUntilWebSocketConnected(fetchPolicy.url);
808
- import_common.Logger.debug(`socket listen end: ${gqlMeta.key}: ${(0, import_base.dayjs)().format("YYYY-MM-DD HH:mm:ss.SSS")}`);
809
- io.removeListener(gqlMeta.key, handle);
810
- };
811
- }, "listenEvent");
812
- gqls[gqlMeta.key] = emitEvent;
813
- gqls[`listen${(0, import_common.capitalize)(gqlMeta.key)}`] = listenEvent;
814
- } else if (gqlMeta.type === "Pubsub") {
815
- const [returnRef] = (0, import_base.getNonArrayModel)(gqlMeta.returns());
816
- const [argMetas] = (0, import_signalDecorators.getArgMetas)(sigRef, gqlMeta.signalOption.name ?? gqlMeta.key);
817
- const isScalar = (0, import_base.isGqlScalar)(returnRef);
818
- const makeRoomId = /* @__PURE__ */ __name((gqlKey, argValues) => `${gqlKey}-${argValues.join("-")}`, "makeRoomId");
819
- const crystalize2 = /* @__PURE__ */ __name((data) => {
820
- if (isScalar) {
821
- if (returnRef.prototype === Date.prototype) return (0, import_base.dayjs)(data);
822
- else return data;
823
- } else if (Array.isArray(data)) return data.map((d) => crystalize2(d));
824
- else return makeCrystalize(returnRef)(data);
825
- }, "crystalize");
826
- const subscribeEvent = /* @__PURE__ */ __name(function(...args) {
827
- const onData = args[argMetas.length];
828
- const fetchPolicy = args[argMetas.length + 1] ?? {
829
- crystalize: true
830
- };
831
- const message = Object.fromEntries(argMetas.map((argMeta) => [
832
- argMeta.name,
833
- serializeArg(argMeta, args[argMeta.idx]) ?? null
834
- ]));
835
- const handleEvent = /* @__PURE__ */ __name((data) => {
836
- if (data.__subscribe__) return;
837
- onData(crystalize2(data));
838
- }, "handleEvent");
839
- const roomId = makeRoomId(gqlMeta.key, argMetas.map((argMeta) => message[argMeta.name]));
840
- const io = this.client.getIo(fetchPolicy.url);
841
- void this.client.waitUntilWebSocketConnected(fetchPolicy.url).then(() => {
842
- import_common.Logger.debug(`socket subscribe start: ${gqlMeta.key}: ${(0, import_base.dayjs)().format("YYYY-MM-DD HH:mm:ss.SSS")}`);
843
- io.subscribe({
844
- key: gqlMeta.key,
845
- roomId,
846
- message,
847
- handleEvent
848
- });
849
- });
850
- return async () => {
851
- //! 앱에서 다른 앱 넘어갈 때 언마운트 되버리면서 subscribe가 끊기는 일이 있음.
852
- await this.client.waitUntilWebSocketConnected(fetchPolicy.url);
853
- import_common.Logger.debug(`socket unsubscribe: ${gqlMeta.key}: ${(0, import_base.dayjs)().format("YYYY-MM-DD HH:mm:ss.SSS")}`);
854
- io.unsubscribe(roomId, handleEvent);
855
- };
856
- }, "subscribeEvent");
857
- gqls[`subscribe${(0, import_common.capitalize)(gqlMeta.key)}`] = subscribeEvent;
858
- } else if (gqlMeta.type === "Query" || gqlMeta.type === "Mutation") {
859
- const name = gqlMeta.signalOption.name ?? gqlMeta.key;
860
- const makeReq = /* @__PURE__ */ __name(({ resolve }) => async function(...args) {
861
- import_common.Logger.debug(`fetch: ${gqlMeta.key} start: ${(0, import_base.dayjs)().format("YYYY-MM-DD HH:mm:ss.SSS")}`);
862
- const now = Date.now();
863
- const [argMetas] = (0, import_signalDecorators.getArgMetas)(sigRef, gqlMeta.signalOption.name ?? gqlMeta.key);
864
- const [modelRef, arrDepth] = (0, import_base.getNonArrayModel)(gqlMeta.returns());
865
- const isScalar = (0, import_base.isGqlScalar)(modelRef);
866
- const returnRef = isScalar || !arrDepth ? modelRef : (0, import_constant.getLightModelRef)(modelRef);
867
- const fetchPolicy = args[argMetas.length] ?? {
868
- crystalize: true
869
- };
870
- const partial = fetchPolicy.partial ?? gqlMeta.signalOption.partial;
871
- const crystalize2 = /* @__PURE__ */ __name((data) => {
872
- if (fetchPolicy.crystalize === false) return data;
873
- if (isScalar) {
874
- if (returnRef.prototype === Date.prototype) return (0, import_base.dayjs)(data);
875
- else return data;
876
- } else if (Array.isArray(data)) return data.map((d) => crystalize2(d));
877
- else return makeCrystalize(returnRef, {
878
- partial
879
- })(data);
880
- }, "crystalize");
881
- try {
882
- const res = (await (gqlMeta.type === "Query" ? query : mutate)(this.client, graphql(getGqlStr(modelRef, gqlMeta, argMetas, returnRef, partial)), Object.fromEntries(argMetas.map((argMeta) => [
883
- argMeta.name,
884
- serializeArg(argMeta, args[argMeta.idx]) ?? null
885
- ])), fetchPolicy))[name];
886
- const data = resolve ? crystalize2(res) : res;
887
- import_common.Logger.debug(`fetch: ${gqlMeta.key} end: ${(0, import_base.dayjs)().format("YYYY-MM-DD HH:mm:ss.SSS")} ${Date.now() - now}ms`);
888
- return data;
889
- } catch (e) {
890
- import_common.Logger.error(`fetch: ${gqlMeta.key} error: ${e}`);
891
- throw e;
892
- }
893
- }, "makeReq");
894
- gqls[name] = makeReq({
895
- resolve: true
896
- });
897
- gqls[`_${name}`] = makeReq({
898
- resolve: false
899
- });
900
- }
901
- });
902
- return gqls;
903
- }, "fetchOf");
904
- const makeFetch = /* @__PURE__ */ __name((fetch1, fetch2, fetch3, fetch4, fetch5, fetch6, fetch7, fetch8, fetch9, fetch10) => {
905
- return Object.assign(fetch1, fetch2, fetch3, fetch4, fetch5, fetch6, fetch7, fetch8, fetch9, fetch10);
906
- }, "makeFetch");
907
- const makeArgStr = /* @__PURE__ */ __name((argMetas) => {
908
- return argMetas.length ? `(${argMetas.map((argMeta) => {
909
- const [argRef, arrDepth] = (0, import_base.getNonArrayModel)(argMeta.returns());
910
- const argRefType = (0, import_base.isGqlScalar)(argRef) ? "gqlScalar" : (0, import_constant.getClassMeta)(argRef).type === "scalar" ? "scalar" : "model";
911
- const gqlTypeStr = "[".repeat(arrDepth) + ((0, import_constant.getGqlTypeStr)(argRef) + (argRefType === "scalar" ? "Input" : "")) + "!]".repeat(arrDepth);
912
- return `$${argMeta.name}: ` + gqlTypeStr + (argMeta.argsOption.nullable ? "" : "!");
913
- }).join(", ")})` : "";
914
- }, "makeArgStr");
915
- const makeArgAssignStr = /* @__PURE__ */ __name((argMetas) => {
916
- return argMetas.length ? `(${argMetas.map((argMeta) => `${argMeta.name}: $${argMeta.name}`).join(", ")})` : "";
917
- }, "makeArgAssignStr");
918
- const makeReturnStr = /* @__PURE__ */ __name((returnRef, partial) => {
919
- const isScalar = (0, import_base.isGqlScalar)(returnRef);
920
- if (isScalar) return "";
921
- const classMeta = (0, import_constant.getClassMeta)(returnRef);
922
- if (!partial?.length) return ` {
923
- ...${(0, import_common.lowerlize)(classMeta.refName)}Fragment
924
- }`;
925
- const targetKeys = classMeta.type === "scalar" ? partial : [
926
- .../* @__PURE__ */ new Set([
927
- "id",
928
- ...partial,
929
- "updatedAt"
930
- ])
931
- ];
932
- const fieldMetaMap = (0, import_constant.getFieldMetaMap)(returnRef);
933
- return ` {
934
- ${targetKeys.map((key) => fieldMetaMap.get(key)).filter((metadata) => metadata && metadata.fieldType !== "hidden").map((fieldMeta) => fieldMeta.isClass ? ` ${fieldMeta.key} {
935
- ...${(0, import_common.lowerlize)(fieldMeta.name)}Fragment
936
- }` : ` ${fieldMeta.key}`).join("\n")}
937
- }`;
938
- }, "makeReturnStr");
939
- // Annotate the CommonJS export names for ESM import in node:
940
- 0 && (module.exports = {
941
- CrystalizeStorage,
942
- DefaultStorage,
943
- FragmentStorage,
944
- GqlStorage,
945
- PurifyStorage,
946
- deserializeArg,
947
- fetchOf,
948
- getGqlOnStorage,
949
- getGqlStr,
950
- gqlOf,
951
- makeCrystalize,
952
- makeDefault,
953
- makeFetch,
954
- makeFragment,
955
- makePurify,
956
- scalarUtilOf,
957
- serializeArg
958
- });