lemon-core 4.2.7 → 5.0.0

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 (167) hide show
  1. package/README.md +128 -2
  2. package/dist/common/lemon-error.d.ts +34 -0
  3. package/dist/common/lemon-error.js +52 -0
  4. package/dist/common/lemon-error.js.map +1 -0
  5. package/dist/controllers/general-api-controller.d.ts +7 -0
  6. package/dist/controllers/general-api-controller.js +7 -0
  7. package/dist/controllers/general-api-controller.js.map +1 -1
  8. package/dist/cores/api/api-service.js +10 -43
  9. package/dist/cores/api/api-service.js.map +1 -1
  10. package/dist/cores/aws/aws-kms-service.d.ts +13 -5
  11. package/dist/cores/aws/aws-kms-service.js +23 -9
  12. package/dist/cores/aws/aws-kms-service.js.map +1 -1
  13. package/dist/cores/aws/aws-s3-service.d.ts +30 -4
  14. package/dist/cores/aws/aws-s3-service.js +35 -15
  15. package/dist/cores/aws/aws-s3-service.js.map +1 -1
  16. package/dist/cores/aws/aws-sns-service.js +59 -9
  17. package/dist/cores/aws/aws-sns-service.js.map +1 -1
  18. package/dist/cores/aws/aws-sqs-service.d.ts +1 -1
  19. package/dist/cores/aws/aws-sqs-service.js +54 -12
  20. package/dist/cores/aws/aws-sqs-service.js.map +1 -1
  21. package/dist/cores/cache/cache-service.d.ts +10 -9
  22. package/dist/cores/cache/cache-service.js +9 -346
  23. package/dist/cores/cache/cache-service.js.map +1 -1
  24. package/dist/cores/config/config-service.d.ts +3 -15
  25. package/dist/cores/config/config-service.js +5 -34
  26. package/dist/cores/config/config-service.js.map +1 -1
  27. package/dist/cores/dynamo/dynamo-query-service.js +42 -2
  28. package/dist/cores/dynamo/dynamo-query-service.js.map +1 -1
  29. package/dist/cores/dynamo/dynamo-scan-service.js +42 -2
  30. package/dist/cores/dynamo/dynamo-scan-service.js.map +1 -1
  31. package/dist/cores/dynamo/dynamo-service.d.ts +45 -14
  32. package/dist/cores/dynamo/dynamo-service.js +48 -21
  33. package/dist/cores/dynamo/dynamo-service.js.map +1 -1
  34. package/dist/cores/dynamo/tools/expressions.js +32 -22
  35. package/dist/cores/dynamo/tools/expressions.js.map +1 -1
  36. package/dist/cores/dynamo/tools/lang.d.ts +30 -0
  37. package/dist/cores/dynamo/tools/lang.js +75 -0
  38. package/dist/cores/dynamo/tools/lang.js.map +1 -0
  39. package/dist/cores/dynamo/tools/query.js +20 -21
  40. package/dist/cores/dynamo/tools/query.js.map +1 -1
  41. package/dist/cores/dynamo/tools/scan.js +15 -16
  42. package/dist/cores/dynamo/tools/scan.js.map +1 -1
  43. package/dist/cores/dynamo/tools/serializer.js +40 -38
  44. package/dist/cores/dynamo/tools/serializer.js.map +1 -1
  45. package/dist/cores/dynamo/tools/utils.d.ts +6 -2
  46. package/dist/cores/dynamo/tools/utils.js +11 -8
  47. package/dist/cores/dynamo/tools/utils.js.map +1 -1
  48. package/dist/cores/elastic/elastic6-query-service.d.ts +1 -104
  49. package/dist/cores/elastic/elastic6-query-service.js +15 -489
  50. package/dist/cores/elastic/elastic6-query-service.js.map +1 -1
  51. package/dist/cores/elastic/elastic6-service.d.ts +1 -482
  52. package/dist/cores/elastic/elastic6-service.js +15 -1153
  53. package/dist/cores/elastic/elastic6-service.js.map +1 -1
  54. package/dist/cores/elastic/index.d.ts +2 -2
  55. package/dist/cores/elastic/index.js +3 -2
  56. package/dist/cores/elastic/index.js.map +1 -1
  57. package/dist/cores/elastic/os2-query-service.d.ts +104 -0
  58. package/dist/cores/elastic/os2-query-service.js +495 -0
  59. package/dist/cores/elastic/os2-query-service.js.map +1 -0
  60. package/dist/cores/elastic/os2-service.d.ts +372 -0
  61. package/dist/cores/elastic/os2-service.js +943 -0
  62. package/dist/cores/elastic/os2-service.js.map +1 -0
  63. package/dist/cores/index.d.ts +6 -1
  64. package/dist/cores/index.js +9 -2
  65. package/dist/cores/index.js.map +1 -1
  66. package/dist/cores/lambda/index.js +2 -1
  67. package/dist/cores/lambda/index.js.map +1 -1
  68. package/dist/cores/lambda/lambda-cron-handler.d.ts +1 -0
  69. package/dist/cores/lambda/lambda-cron-handler.js +5 -1
  70. package/dist/cores/lambda/lambda-cron-handler.js.map +1 -1
  71. package/dist/cores/lambda/lambda-dynamo-stream-handler.d.ts +5 -4
  72. package/dist/cores/lambda/lambda-dynamo-stream-handler.js +18 -5
  73. package/dist/cores/lambda/lambda-dynamo-stream-handler.js.map +1 -1
  74. package/dist/cores/lambda/lambda-handler.d.ts +22 -2
  75. package/dist/cores/lambda/lambda-handler.js +85 -23
  76. package/dist/cores/lambda/lambda-handler.js.map +1 -1
  77. package/dist/cores/lambda/lambda-sns-handler.d.ts +1 -0
  78. package/dist/cores/lambda/lambda-sns-handler.js +5 -0
  79. package/dist/cores/lambda/lambda-sns-handler.js.map +1 -1
  80. package/dist/cores/lambda/lambda-sqs-handler.d.ts +1 -0
  81. package/dist/cores/lambda/lambda-sqs-handler.js +20 -5
  82. package/dist/cores/lambda/lambda-sqs-handler.js.map +1 -1
  83. package/dist/cores/lambda/lambda-web-handler.d.ts +10 -0
  84. package/dist/cores/lambda/lambda-web-handler.js +107 -41
  85. package/dist/cores/lambda/lambda-web-handler.js.map +1 -1
  86. package/dist/cores/protocol/aws-lambda-helper.js +58 -11
  87. package/dist/cores/protocol/aws-lambda-helper.js.map +1 -1
  88. package/dist/cores/protocol/index.js +3 -0
  89. package/dist/cores/protocol/index.js.map +1 -1
  90. package/dist/cores/protocol/protocol-service.d.ts +26 -5
  91. package/dist/cores/protocol/protocol-service.js +42 -12
  92. package/dist/cores/protocol/protocol-service.js.map +1 -1
  93. package/dist/cores/protocol/protocol-sign.d.ts +72 -0
  94. package/dist/cores/protocol/protocol-sign.js +194 -0
  95. package/dist/cores/protocol/protocol-sign.js.map +1 -0
  96. package/dist/cores/storage/index.d.ts +0 -1
  97. package/dist/cores/storage/index.js +0 -1
  98. package/dist/cores/storage/index.js.map +1 -1
  99. package/dist/cores/storage/model-fields.d.ts +7 -0
  100. package/dist/cores/storage/model-fields.js +21 -0
  101. package/dist/cores/storage/model-fields.js.map +1 -0
  102. package/dist/cores/storage/model-manager.d.ts +3 -2
  103. package/dist/cores/storage/model-manager.js +7 -3
  104. package/dist/cores/storage/model-manager.js.map +1 -1
  105. package/dist/engine/builder.js +20 -2
  106. package/dist/engine/builder.js.map +1 -1
  107. package/dist/engine/engine.d.ts +2 -2
  108. package/dist/engine/engine.js +4 -4
  109. package/dist/engine/engine.js.map +1 -1
  110. package/dist/engine/utilities.d.ts +11 -12
  111. package/dist/engine/utilities.js +30 -82
  112. package/dist/engine/utilities.js.map +1 -1
  113. package/dist/environ.d.ts +0 -6
  114. package/dist/environ.js +1 -12
  115. package/dist/environ.js.map +1 -1
  116. package/dist/esm/index.mjs +140 -0
  117. package/dist/esm/testing.mjs +12 -0
  118. package/dist/extended/abstract-service.d.ts +48 -139
  119. package/dist/extended/abstract-service.js +46 -382
  120. package/dist/extended/abstract-service.js.map +1 -1
  121. package/dist/extended/cores/abstract-controllers.d.ts +170 -0
  122. package/dist/extended/cores/abstract-controllers.js +533 -0
  123. package/dist/extended/cores/abstract-controllers.js.map +1 -0
  124. package/dist/extended/cores/abstract-rest-apis.d.ts +142 -0
  125. package/dist/extended/cores/abstract-rest-apis.js +203 -0
  126. package/dist/extended/cores/abstract-rest-apis.js.map +1 -0
  127. package/dist/extended/cores/abstract-services.d.ts +771 -0
  128. package/dist/extended/cores/abstract-services.js +2042 -0
  129. package/dist/extended/cores/abstract-services.js.map +1 -0
  130. package/dist/extended/cores/browser-cache.d.ts +2 -0
  131. package/dist/extended/cores/browser-cache.js +34 -0
  132. package/dist/extended/cores/browser-cache.js.map +1 -0
  133. package/dist/extended/cores/commons.d.ts +20 -0
  134. package/dist/extended/cores/commons.js +31 -0
  135. package/dist/extended/cores/commons.js.map +1 -0
  136. package/dist/extended/cores/index.d.ts +15 -0
  137. package/dist/extended/cores/index.js +32 -0
  138. package/dist/extended/cores/index.js.map +1 -0
  139. package/dist/extended/cores/types.d.ts +14 -0
  140. package/dist/extended/cores/types.js +31 -0
  141. package/dist/extended/cores/types.js.map +1 -0
  142. package/dist/helpers/helpers.d.ts +10 -5
  143. package/dist/helpers/helpers.js +46 -58
  144. package/dist/helpers/helpers.js.map +1 -1
  145. package/dist/helpers/types.d.ts +22 -10
  146. package/dist/index.d.ts +4 -0
  147. package/dist/index.js +12 -1
  148. package/dist/index.js.map +1 -1
  149. package/dist/lib/http-fetch.d.ts +54 -0
  150. package/dist/lib/http-fetch.js +133 -0
  151. package/dist/lib/http-fetch.js.map +1 -0
  152. package/dist/lib/lazy.d.ts +22 -0
  153. package/dist/lib/lazy.js +54 -0
  154. package/dist/lib/lazy.js.map +1 -0
  155. package/dist/lib/perf.d.ts +35 -0
  156. package/dist/lib/perf.js +52 -0
  157. package/dist/lib/perf.js.map +1 -0
  158. package/dist/tools/tools.d.ts +15 -3
  159. package/dist/tools/tools.js +21 -4
  160. package/dist/tools/tools.js.map +1 -1
  161. package/package.json +96 -39
  162. package/dist/cores/storage/redis-storage-service.d.ts +0 -183
  163. package/dist/cores/storage/redis-storage-service.js +0 -377
  164. package/dist/cores/storage/redis-storage-service.js.map +0 -1
  165. package/dist/generated/field-registry.d.ts +0 -10
  166. package/dist/generated/field-registry.js +0 -17
  167. package/dist/generated/field-registry.js.map +0 -1
@@ -0,0 +1,943 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.$ERROR = exports.OS2CoreService = exports.OS2ClientService = exports.$hangul = void 0;
7
+ /**
8
+ * `os2-service.ts`
9
+ * - common service for OpenSearch (identifiers renamed in v5 B2-b, file renamed in v5 B3)
10
+ *
11
+ * @author Steve Jung <steve@lemoncloud.io>
12
+ * @date 2019-11-20 initial version via backbone
13
+ * @date 2022-02-21 optimized error handler, and search.
14
+ * @date 2022-02-22 optimized w/ elastic client (elasticsearch-js)
15
+ * @date 2026-10-27 v5 B2-b: `@opensearch-project/opensearch` client, no doc `type`, no version detection.
16
+ * @date 2026-10-28 v5 B3: renamed from the ES-era file name (that name is now a re-export shim).
17
+ *
18
+ * @copyright (C) 2019 LemonCloud Co Ltd. - All Rights Reserved.
19
+ */
20
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
21
+ const engine_1 = require("../../engine/");
22
+ const hangul_service_1 = __importDefault(require("./hangul-service"));
23
+ exports.$hangul = hangul_service_1.default;
24
+ const perf_1 = require("../../lib/perf");
25
+ const test_helper_1 = require("../../common/test-helper");
26
+ const NS = engine_1.$U.NS('OS2', 'green'); // NAMESPACE TO BE PRINTED.
27
+ /**
28
+ * the client package, required on the first client creation (not at import: it loads ~546 files).
29
+ * - `.Client` is read at call time, so a replaced `Client` on the cached module is honoured.
30
+ */
31
+ let $opensearch = null;
32
+ // memoized loader of `@opensearch-project/opensearch`.
33
+ const loadOpenSearch = () => {
34
+ //* first call only: `require` timed by one `PERF` line (D40).
35
+ if (!$opensearch)
36
+ $opensearch = (0, perf_1.measure)(engine_1._inf, engine_1.$U.NS('PERF', 'cyan'), 'lazy-load @opensearch-project/opensearch', () =>
37
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
38
+ require('@opensearch-project/opensearch'));
39
+ return $opensearch;
40
+ };
41
+ /**
42
+ * convert to string.
43
+ */
44
+ const _S = (v, def = '') => typeof v === 'string' ? v : v === undefined || v === null ? def : typeof v === 'object' ? engine_1.$U.json(v) : `${v}`;
45
+ /** ****************************************************************************************************************
46
+ * OS2 Client Service
47
+ ** ****************************************************************************************************************/
48
+ /**
49
+ * abstarct class: `OS2ClientService`
50
+ * - holds the options and the OpenSearch client.
51
+ * - the client is created on the first `client` access (not in the constructor).
52
+ */
53
+ class OS2ClientService {
54
+ _options;
55
+ /** the client, created on first access of `client` */
56
+ _client;
57
+ /**
58
+ * default constuctor w/ options (no client is created here).
59
+ * @param options { endpoint, indexName } is required.
60
+ */
61
+ constructor(options) {
62
+ (0, engine_1._inf)(NS, `OS2ClientService(${options.indexName}/${options.idName})...`);
63
+ if (!options.endpoint)
64
+ throw new Error('.endpoint (URL) is required');
65
+ if (!options.indexName)
66
+ throw new Error('.indexName (string) is required');
67
+ // default option values: idName='$id'
68
+ this._options = { idName: '$id', ...options };
69
+ }
70
+ /**
71
+ * build the client for `options.endpoint` (override to add `auth`).
72
+ * @see https://opensearch.org/docs/latest/clients/javascript/index/
73
+ */
74
+ createClient() {
75
+ return this.newClient();
76
+ }
77
+ /**
78
+ * build a client for `options.endpoint` with extra client options (e.g. `auth`); loads the package on first use.
79
+ */
80
+ newClient(extra) {
81
+ const { Client } = loadOpenSearch();
82
+ //* `PERF > client OS2`: constructor time (at most once per instance, D40).
83
+ return (0, perf_1.measure)(engine_1._inf, engine_1.$U.NS('PERF', 'cyan'), 'client OS2', () => new Client({
84
+ node: this.options.endpoint,
85
+ ssl: {
86
+ ca: process.env.elasticsearch_certificate,
87
+ rejectUnauthorized: false,
88
+ },
89
+ ...extra,
90
+ }));
91
+ }
92
+ /**
93
+ * get the client instance (created once, on first access).
94
+ */
95
+ get client() {
96
+ if (!this._client)
97
+ this._client = this.createClient();
98
+ return this._client;
99
+ }
100
+ /**
101
+ * get the current options.
102
+ */
103
+ get options() {
104
+ return this._options;
105
+ }
106
+ }
107
+ exports.OS2ClientService = OS2ClientService;
108
+ /** ****************************************************************************************************************
109
+ * OS2CoreService
110
+ ** ****************************************************************************************************************/
111
+ /**
112
+ * class: `OS2CoreService`
113
+ * - extends `OS2ClientService`: document CRUD, search and index management via the client.
114
+ * - the parent of `OS2Service`.
115
+ */
116
+ class OS2CoreService extends OS2ClientService {
117
+ // internal field name to store analyzed strings for autocomplete search
118
+ static DECOMPOSED_FIELD = '_decomposed';
119
+ static QWERTY_FIELD = '_qwerty';
120
+ /**
121
+ * default constuctor w/ options.
122
+ * @param options { endpoint, indexName } is required.
123
+ */
124
+ constructor(options) {
125
+ super(options);
126
+ (0, engine_1._inf)('OS2CoreService', `OS2CoreService(${options.indexName}/${options.idName})...`);
127
+ }
128
+ /**
129
+ * say hello of identity.
130
+ */
131
+ hello = () => `os2-core-service:${this.options.indexName}`;
132
+ /**
133
+ * list of index
134
+ */
135
+ async listIndices() {
136
+ (0, engine_1._log)(NS, `- listIndices()`);
137
+ //* prepare client..
138
+ const client = this.client;
139
+ const res = await client.cat.indices({ format: 'json' });
140
+ (0, engine_1._log)(NS, `> indices =`, engine_1.$U.json(res));
141
+ // eslint-disable-next-line prettier/prettier
142
+ const list0 = Array.isArray(res) ? res : res?.body && Array.isArray(res?.body) ? res?.body : null;
143
+ if (!list0)
144
+ throw new Error(`@result<${typeof res}> is invalid - ${engine_1.$U.json(res)}!`);
145
+ // {"docs.count": "84", "docs.deleted": "7", "health": "green", "index": "dev-eureka-alarms-v1", "pri": "5", "pri.store.size": "234.3kb", "rep": "1", "status": "open", "store.size": "468.6kb", "uuid": "xPp-Sx86SgmhAWxT3cGAFw"}
146
+ const list = list0.map(N => ({
147
+ pri: engine_1.$U.N(N['pri']),
148
+ rep: engine_1.$U.N(N['rep']),
149
+ docsCount: engine_1.$U.N(N['docs.count']),
150
+ docsDeleted: engine_1.$U.N(N['docs.deleted']),
151
+ health: _S(N['health']),
152
+ index: _S(N['index']),
153
+ status: _S(N['status']),
154
+ uuid: _S(N['uuid']),
155
+ priStoreSize: _S(N['pri.store.size']),
156
+ storeSize: _S(N['store.size']),
157
+ }));
158
+ return { list };
159
+ }
160
+ /**
161
+ * get mapping of an index
162
+ * @param indexName - name of the index
163
+ */
164
+ async getIndexMapping() {
165
+ const client = this.client;
166
+ const indexName = this.options.indexName;
167
+ const res = await client.indices.getMapping({ index: indexName }).catch(
168
+ // $ERROR.throwAsJson,
169
+ exports.$ERROR.handler('getMapping', e => {
170
+ const msg = (0, test_helper_1.GETERR)(e);
171
+ if (msg.startsWith('404 INDEX NOT FOUND'))
172
+ throw new Error(`404 NOT FOUND - index:${indexName}`);
173
+ throw e;
174
+ }));
175
+ const mapping = res?.body ? res.body[indexName]?.mappings : null;
176
+ if (!mapping)
177
+ throw new Error(`@indexName[${indexName}] is not found - ${engine_1.$U.json(res)}!`);
178
+ return mapping;
179
+ }
180
+ /**
181
+ * find the index by name
182
+ * @param indexName - name of the index
183
+ */
184
+ async findIndex(indexName) {
185
+ indexName = indexName || this.options.indexName;
186
+ (0, engine_1._log)(NS, `- findIndex(${indexName})`);
187
+ const { list } = await this.listIndices();
188
+ const found = list.findIndex(N => N.index == indexName);
189
+ return found >= 0 ? list[found] : null;
190
+ }
191
+ /**
192
+ * create index by name
193
+ * @param settings - creating settings
194
+ */
195
+ async createIndex(settings) {
196
+ const { indexName, idName, timeSeries } = this.options;
197
+ // default: the typeless settings (`mappings.properties`)
198
+ settings = settings || OS2CoreService.prepareSettings({ idName, timeSeries });
199
+ if (!indexName)
200
+ new Error('@index is required!');
201
+ (0, engine_1._log)(NS, `- createIndex(${indexName})`);
202
+ //* prepare payload
203
+ const payload = {
204
+ settings: {
205
+ number_of_shards: 5,
206
+ number_of_replicas: 1,
207
+ },
208
+ ...settings,
209
+ };
210
+ (0, engine_1._log)(NS, `> settings[${indexName}] = `, engine_1.$U.json(payload));
211
+ //* call create index..
212
+ const client = this.client;
213
+ const res = await client.indices.create({ index: indexName, body: payload }).catch(
214
+ // $ERROR.throwAsJson,
215
+ exports.$ERROR.handler('create', e => {
216
+ const msg = (0, test_helper_1.GETERR)(e);
217
+ if (msg.startsWith('400 RESOURCE ALREADY EXISTS'))
218
+ throw new Error(`400 IN USE - index:${indexName}`);
219
+ throw e;
220
+ }));
221
+ // if (res) throw res;
222
+ (0, engine_1._log)(NS, `> create[${indexName}] =`, engine_1.$U.json({ ...res, meta: undefined }));
223
+ //* build result.
224
+ return {
225
+ status: res.statusCode,
226
+ index: indexName,
227
+ acknowledged: res.body.shards_acknowledged,
228
+ };
229
+ }
230
+ /**
231
+ * destroy search index
232
+ */
233
+ async destroyIndex() {
234
+ const { indexName } = this.options;
235
+ if (!indexName)
236
+ new Error('@index is required!');
237
+ (0, engine_1._log)(NS, `- destroyIndex(${indexName})`);
238
+ //* call destroy index..
239
+ // const { client } = instance(endpoint);
240
+ const client = this.client;
241
+ const res = await client.indices.delete({ index: indexName }).catch(
242
+ // $ERROR.throwAsJson,
243
+ exports.$ERROR.handler('destroy', e => {
244
+ const msg = (0, test_helper_1.GETERR)(e);
245
+ if (msg.startsWith('404 INDEX NOT FOUND'))
246
+ throw new Error(`404 NOT FOUND - index:${indexName}`);
247
+ throw e;
248
+ }));
249
+ // if (res) throw res;
250
+ (0, engine_1._log)(NS, `> destroy[${indexName}] =`, engine_1.$U.json({ ...res, meta: undefined }));
251
+ return {
252
+ status: res.statusCode,
253
+ index: indexName,
254
+ acknowledged: res.body.acknowledged,
255
+ };
256
+ }
257
+ /**
258
+ * refresh search index - refresh index to make all items searchable
259
+ */
260
+ async refreshIndex() {
261
+ const { indexName } = this.options;
262
+ if (!indexName)
263
+ throw new Error('.indexName is required!');
264
+ (0, engine_1._log)(NS, `- refreshIndex(${indexName})`);
265
+ //* call refresh index..
266
+ // const { client } = instance(endpoint);
267
+ const client = this.client;
268
+ const res = await client.indices.refresh({ index: indexName }).catch(
269
+ // $ERROR.throwAsJson,
270
+ exports.$ERROR.handler('refresh', e => {
271
+ const msg = (0, test_helper_1.GETERR)(e);
272
+ if (msg.startsWith('404 INDEX NOT FOUND'))
273
+ throw new Error(`404 NOT FOUND - index:${indexName}`);
274
+ throw e;
275
+ }));
276
+ (0, engine_1._log)(NS, `> refresh[${indexName}] =`, engine_1.$U.json({ ...res, meta: undefined }));
277
+ return res.body;
278
+ }
279
+ /**
280
+ * flush search index - force store changes into search index immediately
281
+ */
282
+ async flushIndex() {
283
+ const { indexName } = this.options;
284
+ if (!indexName)
285
+ throw new Error('.indexName is required!');
286
+ (0, engine_1._log)(NS, `- flushIndex(${indexName})`);
287
+ //* call flush index..
288
+ // const { client } = instance(endpoint);
289
+ const client = this.client;
290
+ const res = await client.indices.flush({ index: indexName }).catch(
291
+ // $ERROR.throwAsJson,
292
+ exports.$ERROR.handler('flush', e => {
293
+ const msg = (0, test_helper_1.GETERR)(e);
294
+ if (msg.startsWith('404 INDEX NOT FOUND'))
295
+ throw new Error(`404 NOT FOUND - index:${indexName}`);
296
+ throw e;
297
+ }));
298
+ (0, engine_1._log)(NS, `> flush[${indexName}] =`, engine_1.$U.json({ ...res, meta: undefined }));
299
+ return res.body;
300
+ }
301
+ /**
302
+ * describe `settings` and `mappings` of index.
303
+ */
304
+ async describe() {
305
+ const { indexName } = this.options;
306
+ //* call create index..
307
+ (0, engine_1._log)(NS, `- describe(${indexName})`);
308
+ //* read settings.
309
+ // const { client } = instance(endpoint);
310
+ const client = this.client;
311
+ const res = await client.indices.getSettings({ index: indexName }).catch(
312
+ // $ERROR.throwAsJson,
313
+ exports.$ERROR.handler('describe', e => {
314
+ const msg = (0, test_helper_1.GETERR)(e);
315
+ if (msg.startsWith('404 INDEX NOT FOUND'))
316
+ throw new Error(`404 NOT FOUND - index:${indexName}`);
317
+ throw e;
318
+ }));
319
+ (0, engine_1._log)(NS, `> settings[${indexName}] =`, engine_1.$U.json({ ...res, meta: undefined }));
320
+ const settings = (res.body && res.body[indexName] && res.body[indexName].settings) || {};
321
+ (0, engine_1._log)(NS, `> number_of_shards =`, settings.index && settings.index.number_of_shards); // 5
322
+ (0, engine_1._log)(NS, `> number_of_replicas =`, settings.index && settings.index.number_of_replicas); // 1
323
+ //* read mappings.
324
+ const res2 = await client.indices.getMapping({ index: indexName });
325
+ (0, engine_1._log)(NS, `> mappings[${indexName}] =`, engine_1.$U.json(res2));
326
+ const mappings = (res2.body && res2.body[indexName] && res2.body[indexName].mappings) || {};
327
+ //* returns
328
+ return { settings, mappings };
329
+ }
330
+ /**
331
+ * save single item
332
+ *
333
+ * - typeless: no `type` param (v5).
334
+ *
335
+ * @param id - id
336
+ * @param item - item to save
337
+ */
338
+ async saveItem(id, item) {
339
+ const { indexName, idName } = this.options;
340
+ (0, engine_1._log)(NS, `- saveItem(${id})`);
341
+ // const { client } = instance(endpoint);
342
+ const client = this.client;
343
+ // prepare item body and autocomplete fields
344
+ const body = { ...item, [idName]: id };
345
+ const body2 = this.popullateAutocompleteFields(body);
346
+ const params = { index: indexName, id, body: body2 };
347
+ if (idName === '_id')
348
+ delete params.body[idName]; //WARN! `_id` is reserved in ES6.
349
+ (0, engine_1._log)(NS, `> params[${id}] =`, engine_1.$U.json(params));
350
+ //NOTE - use npm `elasticsearch#13.2.0` for avoiding error.
351
+ const res = await client.create(params).catch(
352
+ // $ERROR.throwAsJson,
353
+ exports.$ERROR.handler('save', e => {
354
+ const msg = (0, test_helper_1.GETERR)(e);
355
+ //* try to overwrite document..
356
+ if (msg.startsWith('409 VERSION CONFLICT ENGINE')) {
357
+ // delete body2[idName]; // do set id while update
358
+ // return this.updateItem(id, body2);
359
+ const param2 = { index: indexName, id, body: { ...body2 } };
360
+ return client.index(param2);
361
+ }
362
+ throw e;
363
+ }));
364
+ (0, engine_1._log)(NS, `> create[${id}].res =`, engine_1.$U.json({ ...res, meta: undefined }));
365
+ const _version = engine_1.$U.N(res.body?._version, 0);
366
+ const _id = res.body?._id;
367
+ const res2 = { ...body, _id, _version };
368
+ return res2;
369
+ }
370
+ /**
371
+ * push item for time-series data.
372
+ *
373
+ * - typeless: no `type` param (v5).
374
+ *
375
+ * @param item - item to push
376
+ */
377
+ async pushItem(item) {
378
+ const { indexName } = this.options;
379
+ const id = '';
380
+ const body = { ...item };
381
+ const body2 = this.popullateAutocompleteFields(body);
382
+ (0, engine_1._log)(NS, `- pushItem(${id})`);
383
+ const params = { index: indexName, body: body2 };
384
+ (0, engine_1._log)(NS, `> params[${id}] =`, engine_1.$U.json(params));
385
+ //NOTE - use npm `elasticsearch#13.2.0` for avoiding error.
386
+ // const { client } = instance(endpoint);
387
+ const client = this.client;
388
+ const res = await client.index(params).catch(
389
+ // $ERROR.throwAsJson,
390
+ exports.$ERROR.handler('index', e => {
391
+ (0, engine_1._err)(NS, `> index[${indexName}].err =`, e instanceof Error ? e : engine_1.$U.json(e));
392
+ throw e;
393
+ }));
394
+ // {"_index":"test-v3","_type":"_doc","_id":"rTeHiW4BPb_liACrA9qa","_version":1,"result":"created","_shards":{"total":2,"successful":2,"failed":0},"_seq_no":2,"_primary_term":1}
395
+ (0, engine_1._log)(NS, `> create[${id}].res =`, engine_1.$U.json({ ...res, meta: undefined }));
396
+ const _id = res.body?._id;
397
+ const _version = res.body?._version;
398
+ const res2 = { ...body, _id, _version };
399
+ return res2;
400
+ }
401
+ /**
402
+ * read item with projections (typeless `GET /{index}/_doc/{id}`)
403
+ *
404
+ * @param id - item-id
405
+ * @param views - projections
406
+ */
407
+ async readItem(id, views) {
408
+ const { indexName } = this.options;
409
+ (0, engine_1._log)(NS, `- readItem(${id})`);
410
+ const params = { index: indexName, id };
411
+ if (views) {
412
+ const fields = [];
413
+ const keys = Array.isArray(views) ? views : Object.keys(views);
414
+ keys.forEach((k) => {
415
+ fields.push(k);
416
+ });
417
+ params._source = fields;
418
+ }
419
+ (0, engine_1._log)(NS, `> params[${id}] =`, engine_1.$U.json(params));
420
+ // const { client } = instance(endpoint);
421
+ const client = this.client;
422
+ const res = await client.get(params).catch(
423
+ // $ERROR.throwAsJson,
424
+ exports.$ERROR.handler('read', e => {
425
+ const msg = (0, test_helper_1.GETERR)(e);
426
+ if (msg.startsWith('404 NOT FOUND'))
427
+ throw new Error(`404 NOT FOUND - id:${id}`);
428
+ if (msg.startsWith('404 INDEX NOT FOUND'))
429
+ throw new Error(`404 NOT FOUND - index:${indexName}`);
430
+ throw e;
431
+ }));
432
+ (0, engine_1._log)(NS, `> read[${id}].res =`, engine_1.$U.json({ ...res, meta: undefined }));
433
+ const _id = res.body?._id;
434
+ const _version = res.body?._version;
435
+ const data = res?._source || res.body?._source || {};
436
+ // delete internal (analyzed) field
437
+ delete data[OS2CoreService.DECOMPOSED_FIELD];
438
+ delete data[OS2CoreService.QWERTY_FIELD];
439
+ const res2 = { ...data, _id, _version };
440
+ return res2;
441
+ }
442
+ /**
443
+ * delete item with projections (typeless `DELETE /{index}/_doc/{id}`)
444
+ *
445
+ * @param id - item-id
446
+ */
447
+ async deleteItem(id) {
448
+ const { indexName } = this.options;
449
+ (0, engine_1._log)(NS, `- readItem(${id})`);
450
+ const params = { index: indexName, id };
451
+ (0, engine_1._log)(NS, `> params[${id}] =`, engine_1.$U.json(params));
452
+ // const { client } = instance(endpoint);
453
+ const client = this.client;
454
+ const res = await client.delete(params).catch(exports.$ERROR.handler('read', e => {
455
+ const msg = (0, test_helper_1.GETERR)(e);
456
+ if (msg.startsWith('404 NOT FOUND'))
457
+ throw new Error(`404 NOT FOUND - id:${id}`);
458
+ if (msg.startsWith('404 INDEX NOT FOUND'))
459
+ throw new Error(`404 NOT FOUND - index:${indexName}`);
460
+ throw e;
461
+ }));
462
+ // {"_index":"test-v3","_type":"_doc","_id":"aaa","_version":3,"result":"deleted","_shards":{"total":2,"successful":2,"failed":0},"_seq_no":4,"_primary_term":1}
463
+ (0, engine_1._log)(NS, `> delete[${id}].res =`, engine_1.$U.json({ ...res, meta: undefined }));
464
+ const _id = res.body?._id;
465
+ const _version = res.body?._version;
466
+ const data = res.body?._source || res.body?._source || {};
467
+ const res2 = { ...data, _id, _version };
468
+ return res2;
469
+ }
470
+ /**
471
+ * update item (throw if not exist)
472
+ * `update table set a=1, b=b+2 where id='a1'`
473
+ * 0. no of `a1` -> 1,2 (created)
474
+ * 1. a,b := 10,20 -> 11,22
475
+ * 2. a,b := 10,null -> 11,2 (upsert)
476
+ * 3. a,b := null,20 -> 1,22
477
+ *
478
+ * @param id - item-id
479
+ * @param item - item to update
480
+ * @param increments - item to increase
481
+ * @param options - (optional) request option of client.
482
+ */
483
+ async updateItem(id, item, increments, options) {
484
+ const { indexName, idName } = this.options;
485
+ (0, engine_1._log)(NS, `- updateItem(${id})`);
486
+ item = !item && increments ? undefined : item;
487
+ //* prepare params.
488
+ const params = { index: indexName, id, body: {} };
489
+ const scripts = [];
490
+ if (increments) {
491
+ //* it will create if not exists.
492
+ params.body.upsert = { ...increments, [idName]: id };
493
+ Object.entries(increments).forEach(([key, val]) => {
494
+ if (Array.isArray(val)) {
495
+ // If the value is an array, append it to the existing array in the source
496
+ scripts.push(`if (ctx._source['${key}'] != null && ctx._source['${key}'] instanceof List) {
497
+ ctx._source['${key}'].addAll(params.increments['${key}']);
498
+ } else {
499
+ ctx._source['${key}'] = params.increments['${key}'];
500
+ }`);
501
+ }
502
+ else {
503
+ // If the value is a number, increment the existing field
504
+ scripts.push(`if (ctx._source['${key}'] != null) {
505
+ ctx._source['${key}'] += params.increments['${key}'];
506
+ } else {
507
+ ctx._source['${key}'] = params.increments['${key}'];
508
+ }`);
509
+ }
510
+ });
511
+ }
512
+ if (item) {
513
+ // Handle item updates in the script
514
+ Object.entries(item).forEach(([key]) => {
515
+ scripts.push(`ctx._source['${key}'] = params.item['${key}'];`);
516
+ });
517
+ }
518
+ params.body.script = {
519
+ source: scripts.join(' '),
520
+ lang: 'painless',
521
+ params: { item, increments },
522
+ };
523
+ (0, engine_1._log)(NS, `> params[${id}] =`, engine_1.$U.json(params));
524
+ // const { client } = instance(endpoint);
525
+ const client = this.client;
526
+ const res = await client.update(params, options).catch(exports.$ERROR.handler('update', (e, E) => {
527
+ const msg = (0, test_helper_1.GETERR)(e);
528
+ //* id 아이템이 없을 경우 발생함.
529
+ if (msg.startsWith('404 DOCUMENT MISSING'))
530
+ throw new Error(`404 NOT FOUND - id:${id}`);
531
+ //* 해당 속성이 없을때 업데이트 하려면 생길 수 있음.
532
+ if (msg.startsWith('400 REMOTE TRANSPORT'))
533
+ throw new Error(`400 INVALID FIELD - id:${id}`);
534
+ if (msg.startsWith('404 NOT FOUND'))
535
+ throw new Error(`404 NOT FOUND - id:${id}`);
536
+ if (msg.startsWith('400 ACTION REQUEST VALIDATION'))
537
+ throw e;
538
+ if (msg.startsWith('400 INVALID FIELD'))
539
+ throw e; // at ES6.8
540
+ if (msg.startsWith('400 MAPPER PARSING'))
541
+ throw e;
542
+ if (msg.startsWith('400 ILLEGAL ARGUMENT - Cannot apply') ||
543
+ msg.startsWith('400 ILLEGAL ARGUMENT - class_cast_exception:'))
544
+ throw new Error(`400 ILLEGAL ARGUMENT - failed to update due to type mismatch in item's field`); // at ES7.1
545
+ if (msg.startsWith('400 ILLEGAL ARGUMENT'))
546
+ throw e; // at ES7.1
547
+ throw E;
548
+ }));
549
+ // {"_index":"test-v3","_type":"_doc","_id":"aaa","_version":2,"result":"updated","_shards":{"total":2,"successful":2,"failed":0},"_seq_no":8,"_primary_term":1}
550
+ // {"_index":"test-v3","_type":"_doc","_id":"aaa","_version":2,"result":"noop","_shards":{"total":0,"successful":0,"failed":0}}
551
+ (0, engine_1._log)(NS, `> update[${id}].res =`, engine_1.$U.json({ ...res, meta: undefined }));
552
+ const _id = res.body._id;
553
+ const _version = res.body._version;
554
+ const res2 = { ...item, _id, _version };
555
+ return res2;
556
+ }
557
+ /**
558
+ * run search and get the raw response (`search_type` in the query string).
559
+ * @param body - Elasticsearch Query DSL that defines the search request (e.g., size, query, filters).
560
+ * @param searchType - type of search (e.g., 'query_then_fetch', 'dfs_query_then_fetch').
561
+ */
562
+ async searchRaw(body, searchType) {
563
+ if (!body)
564
+ throw new Error('@body (SearchBody) is required');
565
+ const { indexName } = this.options;
566
+ (0, engine_1._log)(NS, `- search(${indexName}, ${searchType || ''})....`);
567
+ (0, engine_1._log)(NS, `> body =`, engine_1.$U.json(body));
568
+ // `search_type` goes to the query string as-is (the client does not rename camelCase keys)
569
+ const params = { index: indexName, body };
570
+ if (searchType)
571
+ params.search_type = searchType;
572
+ (0, engine_1._log)(NS, `> params =`, engine_1.$U.json({ ...params, body: undefined }));
573
+ // const { client } = instance(endpoint);
574
+ const client = this.client;
575
+ const $res = await client.search(params).catch(exports.$ERROR.handler('search', e => {
576
+ (0, engine_1._err)(NS, `> search[${indexName}].err =`, e);
577
+ throw e;
578
+ }));
579
+ // {"took":6,"timed_out":false,"_shards":{"total":4,"successful":4,"skipped":0,"failed":0},"hits":{"total":1,"max_score":0.2876821,"hits":[{"_index":"test-v3","_type":"_doc","_id":"aaa","_score":0.2876821,"_source":{"name":"AAA","@id":"aaa","a":-3,"b":-2}}]}}
580
+ // _log(NS, `> search[${id}].res =`, $U.json({ ...res, meta: undefined }));
581
+ // _log(NS, `> search[${tmp}].took =`, $res.took);
582
+ // _log(NS, `> search[${tmp}].hits.total =`, $res.hits?.total);
583
+ // _log(NS, `> search[${tmp}].hits.max_score =`, $res.hits?.max_score);
584
+ // _log(NS, `> search[${tmp}].hits.hits[0] =`, $res.hits && $U.json($res.hits.hits[0]));
585
+ //* return raw results.
586
+ return $res?.body;
587
+ }
588
+ /**
589
+ * run search, and get the formatmted response.
590
+ * @param body - Elasticsearch Query DSL that defines the search request (e.g., size, query, filters).
591
+ * @param searchType - type of search (e.g., 'query_then_fetch', 'dfs_query_then_fetch').
592
+ *
593
+ */
594
+ async search(body, searchType) {
595
+ const size = engine_1.$U.N(body.size, 0);
596
+ const response = await this.searchRaw(body, searchType);
597
+ // return w/ transformed id
598
+ const hits = response.hits;
599
+ if (typeof hits !== 'object')
600
+ throw new Error(`.hits (object) is required - hits:${engine_1.$U.json(hits)}`);
601
+ //NOTE - ES6.8 w/ OS1.1
602
+ return {
603
+ total: typeof hits.total?.value === 'number' ? hits.total?.value : hits.total,
604
+ list: hits.hits.map((hit) => ({
605
+ ...hit._source,
606
+ _id: hit._id,
607
+ _score: hit._score,
608
+ })),
609
+ last: hits.hits.length === size && size > 0 ? hits.hits[size - 1]?.sort : undefined,
610
+ aggregations: response.aggregations,
611
+ };
612
+ }
613
+ /**
614
+ * search all until limit (-1 means no-limit)
615
+ * @param body - Elasticsearch Query DSL that defines the search request (e.g., size, query, filters).
616
+ * @param params - parameters including search type, limit, and retry options.
617
+ */
618
+ async searchAll(body, params) {
619
+ const list = [];
620
+ for await (const chunk of this.generateSearchResult(body, params)) {
621
+ chunk.forEach((N) => list.push(N));
622
+ }
623
+ return list;
624
+ }
625
+ /**
626
+ * create async generator that yields items queried until last
627
+ *
628
+ * @param body - Elasticsearch Query DSL that defines the search request (e.g., size, query, filters).
629
+ * @param params - parameters including search type, limit, and retry options.
630
+ */
631
+ async *generateSearchResult(body, params) {
632
+ const doRetry = params?.retryOptions?.do ?? false;
633
+ const t = params?.retryOptions?.t ?? 5000;
634
+ const maxRetries = params?.retryOptions?.maxRetries ?? 3;
635
+ let limit = params?.limit ?? -1;
636
+ let retryCount = 0;
637
+ if (!body.sort)
638
+ body.sort = '_doc';
639
+ do {
640
+ try {
641
+ const { list, last } = await this.search(body, params?.searchType);
642
+ body.search_after = last;
643
+ if (list.length === 0 && !body.search_after) {
644
+ break;
645
+ }
646
+ yield list;
647
+ }
648
+ catch (e) {
649
+ const msg = (0, test_helper_1.GETERR)(e);
650
+ if (doRetry && msg.startsWith('429 UNKNOWN') && retryCount < maxRetries) {
651
+ retryCount++;
652
+ await (0, test_helper_1.waited)(t);
653
+ continue;
654
+ }
655
+ else {
656
+ throw e;
657
+ }
658
+ }
659
+ } while (body.search_after && (limit === -1 || --limit > 0));
660
+ }
661
+ /**
662
+ * prepare default setting
663
+ * - migrated from engine-v2.
664
+ * - v5: always the typeless mapping (`mappings.properties`); no doc-type or version, no `standard` filter.
665
+ *
666
+ * @param idName id-name
667
+ * @param shards number of shards (default 4)
668
+ * @param replicas number of replicas (default 1)
669
+ * @param timeSeries flag of TIMESERIES (default false)
670
+ */
671
+ static prepareSettings(params) {
672
+ const idName = params.idName === undefined ? '$id' : params.idName;
673
+ const shards = params.shards === undefined ? 4 : params.shards;
674
+ const replicas = params.replicas === undefined ? 1 : params.replicas;
675
+ const timeSeries = params.timeSeries === undefined ? false : params.timeSeries;
676
+ //* core config.
677
+ const CONF_ID_NAME = idName;
678
+ const CONF_ES_TIMESERIES = !!timeSeries;
679
+ const ES_MAPPINGS = {
680
+ // NOTE: the order of dynamic templates are important.
681
+ dynamic_templates: [
682
+ // 1. Search-as-You-Type (autocomplete search) - apply to '_decomposed.*' fields
683
+ {
684
+ autocomplete: {
685
+ path_match: `${OS2CoreService.DECOMPOSED_FIELD}.*`,
686
+ mapping: {
687
+ type: 'text',
688
+ analyzer: 'autocomplete_case_insensitive',
689
+ search_analyzer: 'standard',
690
+ },
691
+ },
692
+ },
693
+ // 2. Search-as-You-Type (Korean to Alphabet sequence in QWERTY/2벌식 keyboard) - apply to '_qwerty.*' fields
694
+ {
695
+ autocomplete_qwerty: {
696
+ path_match: `${OS2CoreService.QWERTY_FIELD}.*`,
697
+ mapping: {
698
+ type: 'text',
699
+ analyzer: 'autocomplete_case_sensitive',
700
+ search_analyzer: 'whitespace',
701
+ },
702
+ },
703
+ },
704
+ // 3. string type ID field
705
+ {
706
+ string_id: {
707
+ match_mapping_type: 'string',
708
+ match: CONF_ID_NAME,
709
+ mapping: {
710
+ type: 'keyword',
711
+ ignore_above: 256,
712
+ },
713
+ },
714
+ },
715
+ // 4. any other string fields - use Hangul analyzer and create 'keyword' sub-field
716
+ {
717
+ strings: {
718
+ match_mapping_type: 'string',
719
+ mapping: {
720
+ type: 'text',
721
+ analyzer: 'hangul',
722
+ search_analyzer: 'hangul',
723
+ fields: {
724
+ // keyword sub-field
725
+ // 문자열 타입에 대한 템플릿을 지정하지 않으면 기본으로 ES가 '.keyword' 서브필드를 생성하나
726
+ // 문자열 타입 템플릿 재정의 시 기본으로 생성되지 않으므로 명시적으로 선언함.
727
+ keyword: {
728
+ type: 'keyword',
729
+ ignore_above: 256,
730
+ },
731
+ },
732
+ },
733
+ },
734
+ },
735
+ ],
736
+ properties: {
737
+ '@version': {
738
+ type: 'keyword',
739
+ index: false,
740
+ },
741
+ created_at: {
742
+ type: 'date',
743
+ format: 'strict_date_optional_time||epoch_millis',
744
+ },
745
+ updated_at: {
746
+ type: 'date',
747
+ format: 'strict_date_optional_time||epoch_millis',
748
+ },
749
+ deleted_at: {
750
+ type: 'date',
751
+ format: 'strict_date_optional_time||epoch_millis',
752
+ },
753
+ },
754
+ };
755
+ //* default settings.
756
+ const ES_SETTINGS = {
757
+ settings: {
758
+ number_of_shards: shards,
759
+ number_of_replicas: replicas,
760
+ analysis: {
761
+ tokenizer: {
762
+ hangul: {
763
+ type: 'seunjeon_tokenizer',
764
+ decompound: true, // 복합명사 분해
765
+ deinflect: true, // 활용어의 원형 추출
766
+ index_eojeol: true, // 어절 추출
767
+ pos_tagging: false, // 품사 태깅
768
+ },
769
+ edge_30grams: {
770
+ type: 'edge_ngram',
771
+ min_gram: 1,
772
+ max_gram: 30,
773
+ token_chars: ['letter', 'digit', 'punctuation', 'symbol'],
774
+ },
775
+ },
776
+ analyzer: {
777
+ hangul: {
778
+ type: 'custom',
779
+ tokenizer: 'hangul',
780
+ filter: ['lowercase'],
781
+ },
782
+ autocomplete_case_insensitive: {
783
+ type: 'custom',
784
+ tokenizer: 'edge_30grams',
785
+ filter: ['lowercase'],
786
+ },
787
+ autocomplete_case_sensitive: {
788
+ type: 'custom',
789
+ tokenizer: 'edge_30grams',
790
+ filter: [], //* the [standard] token filter has been removed since 7.x.
791
+ },
792
+ },
793
+ },
794
+ },
795
+ //* typeless mapping (no doc-type key).
796
+ mappings: ES_MAPPINGS,
797
+ };
798
+ //* timeseries 데이터로, 기본 timestamp 값을 넣어준다. (주의! save시 current-time 값 자동 저장)
799
+ if (!!CONF_ES_TIMESERIES) {
800
+ ES_SETTINGS.settings.refresh_interval = '5s';
801
+ ES_SETTINGS.mappings.properties['@timestamp'] = { type: 'date', doc_values: true };
802
+ ES_SETTINGS.mappings.properties['ip'] = { type: 'ip' };
803
+ //* clear mappings. (fixed: v4 deleted from `ES_SETTINGS.properties`, which does not exist)
804
+ const CLEANS = '@version,created_at,updated_at,deleted_at'.split(',');
805
+ CLEANS.map(key => delete ES_SETTINGS.mappings.properties[key]);
806
+ }
807
+ //* returns settings.
808
+ return ES_SETTINGS;
809
+ }
810
+ /**
811
+ * generate autocomplete fields into the item body to be indexed
812
+ * @param body item body to be saved into ES6 index
813
+ * @private
814
+ */
815
+ popullateAutocompleteFields(body) {
816
+ const { autocompleteFields } = this.options;
817
+ const isAutoComplete = autocompleteFields && Array.isArray(autocompleteFields) && autocompleteFields.length > 0;
818
+ if (!isAutoComplete)
819
+ return body;
820
+ return autocompleteFields.reduce((N, field) => {
821
+ const value = body[field];
822
+ if (typeof value == 'string' || value) {
823
+ // 한글의 경우 자모 분해 형태와 영자판 변형 형태를 제공하고, 영문의 경우 원본 텍스트만 제공한다.
824
+ // 다만 사용자가 공백/하이픈을 생략하고 입력하는 경우에 대응하기 위해 공백/하이픈을 제거한 형태를 공통으로 제공한다.
825
+ if (hangul_service_1.default.isHangul(value, true)) {
826
+ // 자모 분해 (e.g. '레몬' -> 'ㄹㅔㅁㅗㄴ')
827
+ const decomposed = hangul_service_1.default.asJamoSequence(value);
828
+ const recomposed = decomposed.replace(/[ -]/g, '');
829
+ N[OS2CoreService.DECOMPOSED_FIELD][field] = [decomposed, recomposed];
830
+ // 영자판 (e.g. '레몬' -> 'fpahs')
831
+ N[OS2CoreService.QWERTY_FIELD][field] = hangul_service_1.default.asAlphabetKeyStokes(value);
832
+ }
833
+ else {
834
+ const recomposed = value.replace(/[ -]/g, '');
835
+ N[OS2CoreService.DECOMPOSED_FIELD][field] = [value, recomposed];
836
+ }
837
+ }
838
+ return N;
839
+ }, { ...body, [OS2CoreService.DECOMPOSED_FIELD]: {}, [OS2CoreService.QWERTY_FIELD]: {} });
840
+ }
841
+ }
842
+ exports.OS2CoreService = OS2CoreService;
843
+ /**
844
+ * error samples
845
+ */
846
+ exports.$ERROR = {
847
+ asJson: (e) => {
848
+ const _pack = (o) => JSON.parse(JSON.stringify(o, Object.getOwnPropertyNames(o)));
849
+ if (e instanceof Error) {
850
+ const err = e;
851
+ const meta = err.meta && typeof err.meta === 'object' ? err.meta : undefined;
852
+ const $err = _pack(err);
853
+ return { ...$err, meta };
854
+ }
855
+ return e;
856
+ },
857
+ throwAsJson: (e) => {
858
+ throw exports.$ERROR.asJson(e);
859
+ },
860
+ parseMeta: (meta) => {
861
+ if (typeof meta === 'string' && meta) {
862
+ try {
863
+ if (meta.startsWith('[') && meta.endsWith(']')) {
864
+ const list = JSON.parse(meta);
865
+ const $ret = { list };
866
+ return $ret;
867
+ }
868
+ else if (meta.startsWith('{') && meta.endsWith('}')) {
869
+ return JSON.parse(meta);
870
+ }
871
+ else {
872
+ const $ret = { type: 'string', value: meta };
873
+ return $ret;
874
+ }
875
+ }
876
+ catch (e) {
877
+ const $ret = { type: 'string', value: meta, error: (0, test_helper_1.GETERR)(e) };
878
+ return $ret;
879
+ }
880
+ }
881
+ else if (meta === null || meta === undefined) {
882
+ return null;
883
+ }
884
+ else if (typeof meta === 'object') {
885
+ return meta;
886
+ }
887
+ else {
888
+ const type = typeof meta;
889
+ const $ret = { type, value: meta };
890
+ return $ret;
891
+ }
892
+ },
893
+ /**
894
+ * parse a client error into `{ status, message, reason }`.
895
+ * - `type` comes from `meta.body.error.type` (same in both clients); it falls back to `message` only
896
+ * when the body has no error type (e.g. a meta-only sample of elastic 7.x).
897
+ * - output form is unchanged: `<TYPE upper, last token dropped, _ as space>` like `VERSION CONFLICT ENGINE`.
898
+ * - errors without `meta` (FGAC `http-fetch`, network) give `reason = null` and are rethrown by `handler`.
899
+ */
900
+ asError: (e) => {
901
+ const E = exports.$ERROR.asJson(e);
902
+ const status = `${E.statusCode || ''}`;
903
+ const message = `${E.message || E.msg || ''}`;
904
+ const reason = ((E) => {
905
+ //* only client response errors carry `meta`.
906
+ if (!(E.meta && typeof E.meta == 'object'))
907
+ return null;
908
+ const $res = exports.$ERROR.parseMeta(E.meta);
909
+ const source = _S($res.body?.error?.type ?? E?.message);
910
+ const type = source.toUpperCase().split('_').slice(0, -1).join(' ');
911
+ const status = engine_1.$U.N(E.meta?.statusCode, type.includes('NOT FOUND') ? 404 : 400);
912
+ //* find the reason.
913
+ const reason = $res.body?.error?.reason === 'failed to execute script'
914
+ ? $res.body?.error?.caused_by?.caused_by?.reason
915
+ : $res.body?.error?.reason;
916
+ const result = { status, type: type || (status === 404 ? 'NOT FOUND' : 'UNKNOWN') };
917
+ if (typeof reason !== 'undefined') {
918
+ result.reason = reason;
919
+ }
920
+ return result;
921
+ })(E);
922
+ //* FINAL. convert to error-object.
923
+ return {
924
+ status: engine_1.$U.N(status, reason?.status || 0),
925
+ message: message || reason?.reason,
926
+ reason,
927
+ };
928
+ },
929
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
930
+ handler: (name, cb) => (e) => {
931
+ const E = exports.$ERROR.asError(e);
932
+ //* unknown error found..
933
+ if (!E?.status) {
934
+ (0, engine_1._err)(NS, `! err[${name}]@handler =`, e instanceof Error, engine_1.$U.json(e));
935
+ throw e;
936
+ }
937
+ const $e = new Error(`${E.status} ${E.reason?.type ?? ''} - ${E.reason?.reason ?? E.message ?? ''}`);
938
+ if (cb)
939
+ return cb($e, E);
940
+ throw $e;
941
+ },
942
+ };
943
+ //# sourceMappingURL=os2-service.js.map