@okf/ootils 1.1.0 → 1.2.1

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/dist/index.js CHANGED
@@ -1,8 +1,13 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function __require() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
6
11
  var __export = (target, all) => {
7
12
  for (var name in all)
8
13
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -15,12 +20,313 @@ var __copyProps = (to, from, except, desc) => {
15
20
  }
16
21
  return to;
17
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
+ ));
18
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
32
 
33
+ // src/models/Annotations.js
34
+ var require_Annotations = __commonJS({
35
+ "src/models/Annotations.js"(exports2, module2) {
36
+ "use strict";
37
+ var mongoose2 = require("mongoose");
38
+ var Schema = mongoose2.Schema;
39
+ var AnnotationSchema = new Schema(
40
+ {
41
+ // Tags section - dynamic structure for various tag categories
42
+ tags: {
43
+ type: Map,
44
+ of: {
45
+ data: [
46
+ {
47
+ _id: { type: Schema.Types.ObjectId },
48
+ display: String,
49
+ tagId: String
50
+ }
51
+ ],
52
+ collectionId: String
53
+ }
54
+ },
55
+ // Meta information
56
+ meta: {
57
+ contentType: { type: String, required: true },
58
+ kp_contributed_by: {
59
+ type: Schema.Types.ObjectId,
60
+ ref: "user"
61
+ },
62
+ valuePath: String,
63
+ documentId: {
64
+ type: Schema.Types.ObjectId
65
+ }
66
+ },
67
+ // Main content data - using Schema.Types.Mixed for dynamic structure
68
+ main: {
69
+ type: Schema.Types.Mixed,
70
+ default: {}
71
+ },
72
+ // Annotation specific details
73
+ annotations: {
74
+ tags: {
75
+ type: Map,
76
+ of: {
77
+ collectionId: String,
78
+ data: [
79
+ {
80
+ _id: { type: Schema.Types.ObjectId },
81
+ display: String,
82
+ tagId: String
83
+ }
84
+ ]
85
+ }
86
+ },
87
+ fragment: {
88
+ isLexical: Boolean,
89
+ editorState: Object,
90
+ allText: String
91
+ },
92
+ annoKey: String,
93
+ author: {
94
+ id: { type: Schema.Types.ObjectId },
95
+ name: String
96
+ }
97
+ },
98
+ embeddings: Array,
99
+ contentEnhancedText: String,
100
+ // // Optional chunk related fields
101
+ // chunk: {
102
+ // embeddings: Schema.Types.Mixed,
103
+ // contentEnhancedText: String
104
+ // },
105
+ clusterId: String,
106
+ kp_date_published: Date,
107
+ createdAt: {
108
+ type: Date,
109
+ default: Date.now
110
+ },
111
+ updatedAt: {
112
+ type: Date,
113
+ default: Date.now
114
+ },
115
+ translations: Object
116
+ },
117
+ {
118
+ timestamps: true,
119
+ toJSON: { virtuals: true },
120
+ toObject: { virtuals: true },
121
+ strict: false
122
+ // This allows for flexible document structure beyond the defined schema
123
+ }
124
+ );
125
+ AnnotationSchema.index({ "meta.contentType": 1 });
126
+ AnnotationSchema.index({ "meta.documentId": 1 });
127
+ AnnotationSchema.index({ createdAt: -1 });
128
+ AnnotationSchema.index({ "annotations.annoKey": 1 });
129
+ AnnotationSchema.pre("save", function(next) {
130
+ this.updatedAt = /* @__PURE__ */ new Date();
131
+ next();
132
+ });
133
+ AnnotationSchema.methods.getMainField = function(fieldPath) {
134
+ if (!fieldPath) return null;
135
+ const parts = fieldPath.split(".");
136
+ let value = this.main;
137
+ for (const part of parts) {
138
+ if (!value || typeof value !== "object") return null;
139
+ value = value[part];
140
+ }
141
+ return value;
142
+ };
143
+ AnnotationSchema.virtual("displayTitle").get(function() {
144
+ return this.main.title || "Untitled Annotation";
145
+ });
146
+ module2.exports = AnnotationSchema;
147
+ }
148
+ });
149
+
150
+ // src/models/PlatformConfigs.js
151
+ var require_PlatformConfigs = __commonJS({
152
+ "src/models/PlatformConfigs.js"(exports2, module2) {
153
+ "use strict";
154
+ var mongoose2 = require("mongoose");
155
+ var platformConfigTypes = [
156
+ { id: "roles" },
157
+ { id: "contentTypes" },
158
+ { id: "contentCards" },
159
+ { id: "profileTypes" },
160
+ { id: "nav" },
161
+ { id: "deployment" },
162
+ { id: "userAgreement" },
163
+ { id: "localeData" },
164
+ { id: "theme" },
165
+ { id: "tagTypes" },
166
+ { id: "AI" }
167
+ ];
168
+ var PlatformConfigsSchema2 = new mongoose2.Schema(
169
+ {
170
+ type: {
171
+ type: String,
172
+ enum: platformConfigTypes.map((d) => d.id),
173
+ unique: true
174
+ },
175
+ roles: Array,
176
+ data: Object
177
+ },
178
+ { collection: "platformConfigs" }
179
+ );
180
+ module2.exports = PlatformConfigsSchema2;
181
+ }
182
+ });
183
+
184
+ // src/models/Tpl.js
185
+ var require_Tpl = __commonJS({
186
+ "src/models/Tpl.js"(exports2, module2) {
187
+ "use strict";
188
+ var mongoose2 = require("mongoose");
189
+ var TplSchema2 = new mongoose2.Schema({
190
+ dateFirstPublished: Date,
191
+ dateCreated: Date,
192
+ dateLastPublished: Date,
193
+ dateLastEdited: Date,
194
+ status: {
195
+ type: String,
196
+ default: "published",
197
+ // only cuz we dont want to go and add this property in all databases
198
+ enum: ["unpublished", "editPublished", "published"]
199
+ },
200
+ version: {
201
+ type: Number,
202
+ default: 0
203
+ },
204
+ versionPublishedBy: {
205
+ type: mongoose2.Schema.Types.ObjectId,
206
+ ref: "user"
207
+ // reference to the 'user' model
208
+ },
209
+ firstPublishedBy: {
210
+ type: mongoose2.Schema.Types.ObjectId,
211
+ ref: "user"
212
+ // reference to the 'user' model
213
+ },
214
+ kp_content_type: {
215
+ type: String,
216
+ required: true,
217
+ unique: true
218
+ },
219
+ category: {
220
+ //to deprecate and turn into 'layout'
221
+ type: String,
222
+ default: "knowledgeResources2"
223
+ },
224
+ kp_settings: [
225
+ {
226
+ type: Object
227
+ }
228
+ ],
229
+ kp_templates: {
230
+ type: Object
231
+ },
232
+ tplMeta: Object,
233
+ tplLocales: Object,
234
+ indexed: Object,
235
+ drafts: {
236
+ active: Object
237
+ },
238
+ rollbacks: Object,
239
+ //for 'remembering' hidden configurations
240
+ // OTHER CONFIGS
241
+ listing: Object,
242
+ //listing page configurations. this is new, currently only used in nct
243
+ general: {
244
+ content: {
245
+ title: String,
246
+ singular: String,
247
+ ctaText: String,
248
+ listingDesc: String
249
+ },
250
+ allowQuickTagCreation: { enable: Boolean },
251
+ segment: String,
252
+ settingsUIStyle: String,
253
+ hasUpdateType: Boolean,
254
+ annotation: {
255
+ enable: Boolean
256
+ },
257
+ participantModule: {
258
+ enable: Boolean
259
+ },
260
+ formFieldNumbering: {
261
+ enable: Boolean
262
+ },
263
+ postPblRedirPath: Object,
264
+ templateIndex: Object,
265
+ sharing: {
266
+ enable: Boolean,
267
+ trackShareCount: {
268
+ type: Boolean,
269
+ default: false
270
+ }
271
+ },
272
+ viewsCount: {
273
+ enable: {
274
+ type: Boolean,
275
+ default: false
276
+ }
277
+ },
278
+ comments: {
279
+ enable: Boolean
280
+ },
281
+ reactions: {
282
+ type: Map,
283
+ of: {
284
+ enable: Boolean,
285
+ icon: String
286
+ }
287
+ },
288
+ csvExport: {
289
+ enable: Boolean,
290
+ excludeFields: Array,
291
+ enableUpdateExport: Boolean,
292
+ fieldsToSortAtEnd: Array,
293
+ fetchBatches: {
294
+ enable: Boolean,
295
+ batchSize: Number
296
+ }
297
+ },
298
+ //tci helpers - these exist only to show / not show certain UIs in the tci
299
+ disableKPSettings: Boolean
300
+ }
301
+ //general contenttype configs. mostly the stuff inside platformConfigs > contentTypes
302
+ }, {
303
+ toJSON: { virtuals: true },
304
+ // So `res.json()` and other `JSON.stringify()` functions include virtuals
305
+ toObject: { virtuals: true }
306
+ // So `toObject()` output includes virtuals
307
+ });
308
+ TplSchema2.virtual("layout").get(function() {
309
+ return this.category;
310
+ });
311
+ module2.exports = TplSchema2;
312
+ }
313
+ });
314
+
20
315
  // src/index.ts
21
316
  var index_exports = {};
22
317
  __export(index_exports, {
23
- add: () => add
318
+ add: () => add,
319
+ deleteVal: () => deleteVal,
320
+ getAnnotationsModelByTenant: () => getAnnotationsModelByTenant,
321
+ getDbByTenant: () => getDbByTenant,
322
+ getModelByTenant: () => getModelByTenant,
323
+ getPlatformConfigsModelByTenant: () => getPlatformConfigsModelByTenant,
324
+ getTplModelByTenant: () => getTplModelByTenant,
325
+ getVal: () => getVal,
326
+ initializeGlobalConfig: () => initializeGlobalConfig,
327
+ multiConnectToMongoDB: () => multiConnectToMongoDB,
328
+ setVal: () => setVal,
329
+ updateGlobalConfig: () => updateGlobalConfig
24
330
  });
25
331
  module.exports = __toCommonJS(index_exports);
26
332
 
@@ -28,7 +334,285 @@ module.exports = __toCommonJS(index_exports);
28
334
  function add(a, b) {
29
335
  return a + b;
30
336
  }
337
+
338
+ // src/db/mongodb.ts
339
+ var import_mongoose = __toESM(require("mongoose"));
340
+
341
+ // src/db/getGlobalConfig.ts
342
+ var globalConfig = {};
343
+ var getGlobalConfig = () => {
344
+ return {
345
+ env: globalConfig.env,
346
+ dbConfigs: globalConfig.dbConfigs ? { ...globalConfig.dbConfigs } : void 0,
347
+ mongodb: globalConfig.mongodb ? { ...globalConfig.mongodb } : void 0
348
+ };
349
+ };
350
+ var initializeGlobalConfig = (config) => {
351
+ globalConfig = {
352
+ env: config.env,
353
+ dbConfigs: config.dbConfigs ? { ...config.dbConfigs } : void 0,
354
+ mongodb: config.mongodb ? { ...config.mongodb } : void 0
355
+ };
356
+ console.log(`Global config initialized for environment: ${config.env}`);
357
+ };
358
+ var updateGlobalConfig = (updates) => {
359
+ globalConfig = {
360
+ ...globalConfig,
361
+ ...updates,
362
+ // Handle nested objects properly
363
+ dbConfigs: updates.dbConfigs ? { ...globalConfig.dbConfigs, ...updates.dbConfigs } : globalConfig.dbConfigs,
364
+ mongodb: updates.mongodb ? { ...globalConfig.mongodb, ...updates.mongodb } : globalConfig.mongodb
365
+ };
366
+ console.log("Global config updated:", Object.keys(updates));
367
+ };
368
+
369
+ // src/db/mongodb.ts
370
+ var mongoOptions = {
371
+ // Note: These legacy options are no longer needed in newer versions of mongoose
372
+ // useUnifiedTopology, useNewUrlParser, useCreateIndex, useFindAndModify are deprecated
373
+ maxPoolSize: 10
374
+ // replaces poolSize
375
+ };
376
+ var multiConnectToMongoDB = ({ env, dbConfigs } = {}) => {
377
+ const globalConfig2 = getGlobalConfig();
378
+ const actualEnv = env || globalConfig2.env;
379
+ const actualDbConfigs = dbConfigs || globalConfig2.dbConfigs;
380
+ if (!actualEnv) {
381
+ throw new Error("Environment not provided and not found in global config");
382
+ }
383
+ if (!actualDbConfigs) {
384
+ throw new Error("dbConfigs not provided and not found in global config");
385
+ }
386
+ const { connectTo } = actualDbConfigs[actualEnv];
387
+ if (!connectTo) {
388
+ throw new Error(`No connection configuration found for environment: ${actualEnv}`);
389
+ }
390
+ const dbConnections = {};
391
+ connectTo.forEach((connectToEnv) => {
392
+ const { CLUSTER_NAME, DB_URI } = actualDbConfigs[connectToEnv];
393
+ if (!CLUSTER_NAME || !DB_URI) {
394
+ throw new Error(`Missing CLUSTER_NAME or DB_URI for environment: ${connectToEnv}`);
395
+ }
396
+ dbConnections[CLUSTER_NAME] = import_mongoose.default.createConnection(DB_URI, mongoOptions);
397
+ dbConnections[CLUSTER_NAME].on("open", () => {
398
+ console.log(`Mongoose connection open to ${CLUSTER_NAME}`);
399
+ });
400
+ dbConnections[CLUSTER_NAME].on("error", (err) => {
401
+ console.log(`Mongoose connection error: ${err.message} with connection info ${CLUSTER_NAME}`);
402
+ process.exit(1);
403
+ });
404
+ });
405
+ return dbConnections;
406
+ };
407
+
408
+ // src/db/getDbByTenant.ts
409
+ var getDbByTenant = ({
410
+ tenant,
411
+ env
412
+ }) => {
413
+ if (!tenant) throw new Error("tenant id has not been provided");
414
+ const globalConfig2 = getGlobalConfig();
415
+ const actualEnv = env || globalConfig2.env;
416
+ const dbConfigs = globalConfig2.dbConfigs;
417
+ const mongodb = globalConfig2.mongodb;
418
+ if (!dbConfigs) {
419
+ throw new Error("dbConfigs not found in global config");
420
+ }
421
+ if (!actualEnv) {
422
+ throw new Error("env not provided and not found in global config");
423
+ }
424
+ const { CLUSTER_NAME } = dbConfigs[actualEnv];
425
+ const dbName = `${tenant}_${actualEnv}`;
426
+ if (mongodb) {
427
+ const db = mongodb[CLUSTER_NAME].useDb(dbName, { useCache: true });
428
+ return db;
429
+ }
430
+ throw new Error("getDbByTenant : mongodb object doesnt exist");
431
+ };
432
+
433
+ // src/db/getModelByTenant.ts
434
+ var AnnotationsSchema = require_Annotations();
435
+ var PlatformConfigsSchema = require_PlatformConfigs();
436
+ var TplSchema = require_Tpl();
437
+ var getModelByTenant = ({
438
+ tenant,
439
+ modelName,
440
+ schema,
441
+ env
442
+ }) => {
443
+ if (!tenant) {
444
+ throw new Error("tenant id has not been provided");
445
+ }
446
+ const db = getDbByTenant({
447
+ tenant,
448
+ env
449
+ });
450
+ if (!Object.keys(db.models).includes(modelName)) {
451
+ return db.model(modelName, schema);
452
+ }
453
+ return db.model(modelName);
454
+ };
455
+ var getAnnotationsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
456
+ tenant,
457
+ modelName: "annotations",
458
+ schema: AnnotationsSchema,
459
+ env
460
+ });
461
+ var getPlatformConfigsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
462
+ tenant,
463
+ modelName: "platformConfigs",
464
+ schema: PlatformConfigsSchema,
465
+ env
466
+ });
467
+ var getTplModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
468
+ tenant,
469
+ modelName: "tpl",
470
+ schema: TplSchema,
471
+ env
472
+ });
473
+
474
+ // src/utils/getterSetterDeleter/utils/set_deleteVal.ts
475
+ var set_deleteVal = (action, data, valuePath, value) => {
476
+ if (valuePath === void 0) return;
477
+ if (valuePath === null && action === "set") {
478
+ data = value;
479
+ return data;
480
+ }
481
+ let dataRef = data;
482
+ const keysArray = valuePath.split(".");
483
+ const len = keysArray.length;
484
+ let valIsUndefined = false;
485
+ for (let i = 0; i < len - 1; i++) {
486
+ const key = keysArray[i];
487
+ if (!dataRef[key]) {
488
+ if (action === "set") {
489
+ const nextKey = keysArray[i + 1];
490
+ if (nextKey && !isNaN(parseInt(nextKey))) {
491
+ dataRef[key] = [];
492
+ } else {
493
+ dataRef[key] = {};
494
+ }
495
+ } else {
496
+ valIsUndefined = true;
497
+ break;
498
+ }
499
+ }
500
+ dataRef = dataRef[key];
501
+ }
502
+ if (valIsUndefined) return void 0;
503
+ if (action === "set") {
504
+ dataRef[keysArray[len - 1]] = value;
505
+ return data;
506
+ } else if (action === "delete") {
507
+ if (Array.isArray(dataRef)) {
508
+ dataRef.splice(parseInt(keysArray[len - 1]), 1);
509
+ } else {
510
+ delete dataRef[keysArray[len - 1]];
511
+ }
512
+ return data;
513
+ }
514
+ };
515
+
516
+ // src/utils/getterSetterDeleter/deleteVal.ts
517
+ var deleteVal = (data, valuePath) => {
518
+ return set_deleteVal("delete", data, valuePath);
519
+ };
520
+
521
+ // src/utils/getterSetterDeleter/setVal.ts
522
+ var setVal = (data, valuePath, value) => {
523
+ return set_deleteVal("set", data, valuePath, value);
524
+ };
525
+
526
+ // src/utils/getterSetterDeleter/utils/flattenArrayOfArrays.ts
527
+ var flattenArrayOfArrays = ({
528
+ array,
529
+ flattenLastArray = true,
530
+ toReturn = []
531
+ }) => {
532
+ array.map((ary) => {
533
+ if (Array.isArray(ary)) {
534
+ if (flattenLastArray === true) {
535
+ if (ary.some((childAry) => !Array.isArray(childAry))) {
536
+ toReturn.push(ary);
537
+ } else {
538
+ flattenArrayOfArrays({ array: ary, flattenLastArray, toReturn });
539
+ }
540
+ } else {
541
+ flattenArrayOfArrays({ array: ary, flattenLastArray, toReturn });
542
+ }
543
+ } else {
544
+ toReturn.push(ary);
545
+ }
546
+ });
547
+ return toReturn;
548
+ };
549
+
550
+ // src/utils/getterSetterDeleter/getVal.ts
551
+ var getVal = (data, valuePath, options = {}, depthIdx = 0) => {
552
+ let value = null;
553
+ const getFinalVal = (data2, valuePath2, options2, depthIdx2) => {
554
+ return Array.isArray(data2) ? data2.map((R) => getValV2_getter(R, valuePath2, options2, depthIdx2)) : getValV2_getter(data2, valuePath2, options2, depthIdx2);
555
+ };
556
+ if (Array.isArray(valuePath)) {
557
+ for (let i = 0; i < valuePath.length; i++) {
558
+ value = getFinalVal(data, valuePath[i], options, depthIdx);
559
+ if (value) break;
560
+ }
561
+ } else {
562
+ value = getFinalVal(data, valuePath, options, depthIdx);
563
+ }
564
+ return value;
565
+ };
566
+ var getValV2_getter = (data, valuePath, options, depthIdx) => {
567
+ const { flattenIfValueIsArray = true } = options;
568
+ if (valuePath === null) return data;
569
+ let dataRef = data;
570
+ const keysArray = valuePath.split(".");
571
+ const len = keysArray.length;
572
+ let valIsUndefined = false;
573
+ let thisIterationFoundAry = false;
574
+ for (let i = 0; i < len - 1; i++) {
575
+ const key = keysArray[i];
576
+ if (!thisIterationFoundAry) {
577
+ if (!dataRef[key]) {
578
+ valIsUndefined = true;
579
+ break;
580
+ }
581
+ dataRef = dataRef[key];
582
+ } else {
583
+ const nestedAryResponse = dataRef.map((dataRefItem) => {
584
+ const remainingValuePath = keysArray.filter((dd, ii) => ii >= i).join(".");
585
+ return getVal(dataRefItem, remainingValuePath, options, depthIdx + 1);
586
+ });
587
+ return flattenArrayOfArrays({
588
+ array: nestedAryResponse,
589
+ flattenLastArray: depthIdx === 0 && flattenIfValueIsArray === false ? false : true
590
+ });
591
+ }
592
+ if (Array.isArray(dataRef) && Number.isNaN(parseInt(keysArray[i + 1]))) thisIterationFoundAry = true;
593
+ }
594
+ if (valIsUndefined) return void 0;
595
+ if (thisIterationFoundAry) {
596
+ const toReturn = dataRef.map((d) => d[keysArray[len - 1]]);
597
+ return flattenArrayOfArrays({
598
+ array: toReturn,
599
+ flattenLastArray: flattenIfValueIsArray
600
+ });
601
+ }
602
+ return dataRef[keysArray[len - 1]];
603
+ };
31
604
  // Annotate the CommonJS export names for ESM import in node:
32
605
  0 && (module.exports = {
33
- add
606
+ add,
607
+ deleteVal,
608
+ getAnnotationsModelByTenant,
609
+ getDbByTenant,
610
+ getModelByTenant,
611
+ getPlatformConfigsModelByTenant,
612
+ getTplModelByTenant,
613
+ getVal,
614
+ initializeGlobalConfig,
615
+ multiConnectToMongoDB,
616
+ setVal,
617
+ updateGlobalConfig
34
618
  });