@okf/ootils 1.2.0 → 1.3.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.
package/dist/index.mjs CHANGED
@@ -1,8 +1,437 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __commonJS = (cb, mod) => function __require2() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+
12
+ // src/models/Annotations.js
13
+ var require_Annotations = __commonJS({
14
+ "src/models/Annotations.js"(exports, module) {
15
+ "use strict";
16
+ var mongoose2 = __require("mongoose");
17
+ var Schema = mongoose2.Schema;
18
+ var AnnotationSchema = new Schema(
19
+ {
20
+ // Tags section - dynamic structure for various tag categories
21
+ tags: {
22
+ type: Map,
23
+ of: {
24
+ data: [
25
+ {
26
+ _id: { type: Schema.Types.ObjectId },
27
+ display: String,
28
+ tagId: String
29
+ }
30
+ ],
31
+ collectionId: String
32
+ }
33
+ },
34
+ // Meta information
35
+ meta: {
36
+ contentType: { type: String, required: true },
37
+ kp_contributed_by: {
38
+ type: Schema.Types.ObjectId,
39
+ ref: "user"
40
+ },
41
+ valuePath: String,
42
+ documentId: {
43
+ type: Schema.Types.ObjectId
44
+ }
45
+ },
46
+ // Main content data - using Schema.Types.Mixed for dynamic structure
47
+ main: {
48
+ type: Schema.Types.Mixed,
49
+ default: {}
50
+ },
51
+ // Annotation specific details
52
+ annotations: {
53
+ tags: {
54
+ type: Map,
55
+ of: {
56
+ collectionId: String,
57
+ data: [
58
+ {
59
+ _id: { type: Schema.Types.ObjectId },
60
+ display: String,
61
+ tagId: String
62
+ }
63
+ ]
64
+ }
65
+ },
66
+ fragment: {
67
+ isLexical: Boolean,
68
+ editorState: Object,
69
+ allText: String
70
+ },
71
+ annoKey: String,
72
+ author: {
73
+ id: { type: Schema.Types.ObjectId },
74
+ name: String
75
+ }
76
+ },
77
+ embeddings: Array,
78
+ contentEnhancedText: String,
79
+ // // Optional chunk related fields
80
+ // chunk: {
81
+ // embeddings: Schema.Types.Mixed,
82
+ // contentEnhancedText: String
83
+ // },
84
+ clusterId: String,
85
+ kp_date_published: Date,
86
+ createdAt: {
87
+ type: Date,
88
+ default: Date.now
89
+ },
90
+ updatedAt: {
91
+ type: Date,
92
+ default: Date.now
93
+ },
94
+ translations: Object
95
+ },
96
+ {
97
+ timestamps: true,
98
+ toJSON: { virtuals: true },
99
+ toObject: { virtuals: true },
100
+ strict: false
101
+ // This allows for flexible document structure beyond the defined schema
102
+ }
103
+ );
104
+ AnnotationSchema.index({ "meta.contentType": 1 });
105
+ AnnotationSchema.index({ "meta.documentId": 1 });
106
+ AnnotationSchema.index({ createdAt: -1 });
107
+ AnnotationSchema.index({ "annotations.annoKey": 1 });
108
+ AnnotationSchema.pre("save", function(next) {
109
+ this.updatedAt = /* @__PURE__ */ new Date();
110
+ next();
111
+ });
112
+ AnnotationSchema.methods.getMainField = function(fieldPath) {
113
+ if (!fieldPath) return null;
114
+ const parts = fieldPath.split(".");
115
+ let value = this.main;
116
+ for (const part of parts) {
117
+ if (!value || typeof value !== "object") return null;
118
+ value = value[part];
119
+ }
120
+ return value;
121
+ };
122
+ AnnotationSchema.virtual("displayTitle").get(function() {
123
+ return this.main.title || "Untitled Annotation";
124
+ });
125
+ module.exports = AnnotationSchema;
126
+ }
127
+ });
128
+
129
+ // src/models/PlatformConfigs.js
130
+ var require_PlatformConfigs = __commonJS({
131
+ "src/models/PlatformConfigs.js"(exports, module) {
132
+ "use strict";
133
+ var mongoose2 = __require("mongoose");
134
+ var platformConfigTypes = [
135
+ { id: "roles" },
136
+ { id: "contentTypes" },
137
+ { id: "contentCards" },
138
+ { id: "profileTypes" },
139
+ { id: "nav" },
140
+ { id: "deployment" },
141
+ { id: "userAgreement" },
142
+ { id: "localeData" },
143
+ { id: "theme" },
144
+ { id: "tagTypes" },
145
+ { id: "AI" }
146
+ ];
147
+ var PlatformConfigsSchema2 = new mongoose2.Schema(
148
+ {
149
+ type: {
150
+ type: String,
151
+ enum: platformConfigTypes.map((d) => d.id),
152
+ unique: true
153
+ },
154
+ roles: Array,
155
+ data: Object
156
+ },
157
+ { collection: "platformConfigs" }
158
+ );
159
+ module.exports = PlatformConfigsSchema2;
160
+ }
161
+ });
162
+
163
+ // src/models/Tpl.js
164
+ var require_Tpl = __commonJS({
165
+ "src/models/Tpl.js"(exports, module) {
166
+ "use strict";
167
+ var mongoose2 = __require("mongoose");
168
+ var TplSchema2 = new mongoose2.Schema({
169
+ dateFirstPublished: Date,
170
+ dateCreated: Date,
171
+ dateLastPublished: Date,
172
+ dateLastEdited: Date,
173
+ status: {
174
+ type: String,
175
+ default: "published",
176
+ // only cuz we dont want to go and add this property in all databases
177
+ enum: ["unpublished", "editPublished", "published"]
178
+ },
179
+ version: {
180
+ type: Number,
181
+ default: 0
182
+ },
183
+ versionPublishedBy: {
184
+ type: mongoose2.Schema.Types.ObjectId,
185
+ ref: "user"
186
+ // reference to the 'user' model
187
+ },
188
+ firstPublishedBy: {
189
+ type: mongoose2.Schema.Types.ObjectId,
190
+ ref: "user"
191
+ // reference to the 'user' model
192
+ },
193
+ kp_content_type: {
194
+ type: String,
195
+ required: true,
196
+ unique: true
197
+ },
198
+ category: {
199
+ //to deprecate and turn into 'layout'
200
+ type: String,
201
+ default: "knowledgeResources2"
202
+ },
203
+ kp_settings: [
204
+ {
205
+ type: Object
206
+ }
207
+ ],
208
+ kp_templates: {
209
+ type: Object
210
+ },
211
+ tplMeta: Object,
212
+ tplLocales: Object,
213
+ indexed: Object,
214
+ drafts: {
215
+ active: Object
216
+ },
217
+ rollbacks: Object,
218
+ //for 'remembering' hidden configurations
219
+ // OTHER CONFIGS
220
+ listing: Object,
221
+ //listing page configurations. this is new, currently only used in nct
222
+ general: {
223
+ content: {
224
+ title: String,
225
+ singular: String,
226
+ ctaText: String,
227
+ listingDesc: String
228
+ },
229
+ allowQuickTagCreation: { enable: Boolean },
230
+ segment: String,
231
+ settingsUIStyle: String,
232
+ hasUpdateType: Boolean,
233
+ annotation: {
234
+ enable: Boolean
235
+ },
236
+ participantModule: {
237
+ enable: Boolean
238
+ },
239
+ formFieldNumbering: {
240
+ enable: Boolean
241
+ },
242
+ postPblRedirPath: Object,
243
+ templateIndex: Object,
244
+ sharing: {
245
+ enable: Boolean,
246
+ trackShareCount: {
247
+ type: Boolean,
248
+ default: false
249
+ }
250
+ },
251
+ viewsCount: {
252
+ enable: {
253
+ type: Boolean,
254
+ default: false
255
+ }
256
+ },
257
+ comments: {
258
+ enable: Boolean
259
+ },
260
+ reactions: {
261
+ type: Map,
262
+ of: {
263
+ enable: Boolean,
264
+ icon: String
265
+ }
266
+ },
267
+ csvExport: {
268
+ enable: Boolean,
269
+ excludeFields: Array,
270
+ enableUpdateExport: Boolean,
271
+ fieldsToSortAtEnd: Array,
272
+ fetchBatches: {
273
+ enable: Boolean,
274
+ batchSize: Number
275
+ }
276
+ },
277
+ //tci helpers - these exist only to show / not show certain UIs in the tci
278
+ disableKPSettings: Boolean
279
+ }
280
+ //general contenttype configs. mostly the stuff inside platformConfigs > contentTypes
281
+ }, {
282
+ toJSON: { virtuals: true },
283
+ // So `res.json()` and other `JSON.stringify()` functions include virtuals
284
+ toObject: { virtuals: true }
285
+ // So `toObject()` output includes virtuals
286
+ });
287
+ TplSchema2.virtual("layout").get(function() {
288
+ return this.category;
289
+ });
290
+ module.exports = TplSchema2;
291
+ }
292
+ });
293
+
1
294
  // src/utils/testFn.ts
2
295
  function add(a, b) {
3
296
  return a + b;
4
297
  }
5
298
 
299
+ // src/db/mongodb.ts
300
+ import mongoose from "mongoose";
301
+
302
+ // src/db/getGlobalConfig.ts
303
+ var globalConfig = {};
304
+ var getGlobalConfig = () => {
305
+ return {
306
+ env: globalConfig.env,
307
+ dbConfigs: globalConfig.dbConfigs ? { ...globalConfig.dbConfigs } : void 0,
308
+ mongodb: globalConfig.mongodb ? { ...globalConfig.mongodb } : void 0
309
+ };
310
+ };
311
+ var initializeGlobalConfig = (config) => {
312
+ globalConfig = {
313
+ env: config.env,
314
+ dbConfigs: config.dbConfigs ? { ...config.dbConfigs } : void 0,
315
+ mongodb: config.mongodb ? { ...config.mongodb } : void 0
316
+ };
317
+ console.log(`Global config initialized for environment: ${config.env}`);
318
+ };
319
+ var updateGlobalConfig = (updates) => {
320
+ globalConfig = {
321
+ ...globalConfig,
322
+ ...updates,
323
+ // Handle nested objects properly
324
+ dbConfigs: updates.dbConfigs ? { ...globalConfig.dbConfigs, ...updates.dbConfigs } : globalConfig.dbConfigs,
325
+ mongodb: updates.mongodb ? { ...globalConfig.mongodb, ...updates.mongodb } : globalConfig.mongodb
326
+ };
327
+ console.log("Global config updated:", Object.keys(updates));
328
+ };
329
+
330
+ // src/db/mongodb.ts
331
+ var mongoOptions = {
332
+ // Note: These legacy options are no longer needed in newer versions of mongoose
333
+ // useUnifiedTopology, useNewUrlParser, useCreateIndex, useFindAndModify are deprecated
334
+ maxPoolSize: 10
335
+ // replaces poolSize
336
+ };
337
+ var multiConnectToMongoDB = ({ env, dbConfigs } = {}) => {
338
+ const globalConfig2 = getGlobalConfig();
339
+ const actualEnv = env || globalConfig2.env;
340
+ const actualDbConfigs = dbConfigs || globalConfig2.dbConfigs;
341
+ if (!actualEnv) {
342
+ throw new Error("Environment not provided and not found in global config");
343
+ }
344
+ if (!actualDbConfigs) {
345
+ throw new Error("dbConfigs not provided and not found in global config");
346
+ }
347
+ const { connectTo } = actualDbConfigs[actualEnv];
348
+ if (!connectTo) {
349
+ throw new Error(`No connection configuration found for environment: ${actualEnv}`);
350
+ }
351
+ const dbConnections = {};
352
+ connectTo.forEach((connectToEnv) => {
353
+ const { CLUSTER_NAME, DB_URI } = actualDbConfigs[connectToEnv];
354
+ if (!CLUSTER_NAME || !DB_URI) {
355
+ throw new Error(`Missing CLUSTER_NAME or DB_URI for environment: ${connectToEnv}`);
356
+ }
357
+ dbConnections[CLUSTER_NAME] = mongoose.createConnection(DB_URI, mongoOptions);
358
+ dbConnections[CLUSTER_NAME].on("open", () => {
359
+ console.log(`Mongoose connection open to ${CLUSTER_NAME}`);
360
+ });
361
+ dbConnections[CLUSTER_NAME].on("error", (err) => {
362
+ console.log(`Mongoose connection error: ${err.message} with connection info ${CLUSTER_NAME}`);
363
+ process.exit(1);
364
+ });
365
+ });
366
+ return dbConnections;
367
+ };
368
+
369
+ // src/db/getDbByTenant.ts
370
+ var getDbByTenant = ({
371
+ tenant,
372
+ env
373
+ }) => {
374
+ if (!tenant) throw new Error("tenant id has not been provided");
375
+ const globalConfig2 = getGlobalConfig();
376
+ const actualEnv = env || globalConfig2.env;
377
+ const dbConfigs = globalConfig2.dbConfigs;
378
+ const mongodb = globalConfig2.mongodb;
379
+ if (!dbConfigs) {
380
+ throw new Error("dbConfigs not found in global config");
381
+ }
382
+ if (!actualEnv) {
383
+ throw new Error("env not provided and not found in global config");
384
+ }
385
+ const { CLUSTER_NAME } = dbConfigs[actualEnv];
386
+ const dbName = `${tenant}_${actualEnv}`;
387
+ if (mongodb) {
388
+ const db = mongodb[CLUSTER_NAME].useDb(dbName, { useCache: true });
389
+ return db;
390
+ }
391
+ throw new Error("getDbByTenant : mongodb object doesnt exist");
392
+ };
393
+
394
+ // src/db/getModelByTenant.ts
395
+ var AnnotationsSchema = require_Annotations();
396
+ var PlatformConfigsSchema = require_PlatformConfigs();
397
+ var TplSchema = require_Tpl();
398
+ var getModelByTenant = ({
399
+ tenant,
400
+ modelName,
401
+ schema,
402
+ env
403
+ }) => {
404
+ if (!tenant) {
405
+ throw new Error("tenant id has not been provided");
406
+ }
407
+ const db = getDbByTenant({
408
+ tenant,
409
+ env
410
+ });
411
+ if (!Object.keys(db.models).includes(modelName)) {
412
+ return db.model(modelName, schema);
413
+ }
414
+ return db.model(modelName);
415
+ };
416
+ var getAnnotationsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
417
+ tenant,
418
+ modelName: "annotations",
419
+ schema: AnnotationsSchema,
420
+ env
421
+ });
422
+ var getPlatformConfigsModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
423
+ tenant,
424
+ modelName: "platformConfigs",
425
+ schema: PlatformConfigsSchema,
426
+ env
427
+ });
428
+ var getTplModelByTenant = ({ tenant, env, mongodb, dbConfigs }) => getModelByTenant({
429
+ tenant,
430
+ modelName: "tpl",
431
+ schema: TplSchema,
432
+ env
433
+ });
434
+
6
435
  // src/utils/getterSetterDeleter/utils/set_deleteVal.ts
7
436
  var set_deleteVal = (action, data, valuePath, value) => {
8
437
  if (valuePath === void 0) return;
@@ -133,9 +562,127 @@ var getValV2_getter = (data, valuePath, options, depthIdx) => {
133
562
  }
134
563
  return dataRef[keysArray[len - 1]];
135
564
  };
565
+
566
+ // src/redis/index.ts
567
+ import IORedis from "ioredis";
568
+ var redisClient = null;
569
+ var REDIS_CONFIG = {
570
+ port: Number(process.env.REDIS_PORT),
571
+ host: process.env.REDIS_HOST || "",
572
+ username: process.env.REDIS_USERNAME || "",
573
+ password: process.env.REDIS_PASSWORD || ""
574
+ };
575
+ var connectToRedis = async () => {
576
+ try {
577
+ redisClient = new IORedis(REDIS_CONFIG);
578
+ await redisClient.ping();
579
+ console.log("Redis connected successfully");
580
+ } catch (error) {
581
+ console.error(
582
+ "Redis connection failed:",
583
+ error instanceof Error && error.message
584
+ );
585
+ if (redisClient) {
586
+ redisClient.disconnect();
587
+ }
588
+ throw error;
589
+ }
590
+ };
591
+ var getRedisClient = () => {
592
+ if (!redisClient) {
593
+ throw new Error("Redis client not initialized. Call connectToRedis first.");
594
+ }
595
+ return redisClient;
596
+ };
597
+
598
+ // src/redis/functions.ts
599
+ var findInCache = async ({
600
+ tenant,
601
+ modelName,
602
+ type,
603
+ query = {}
604
+ }) => {
605
+ const key = `${process.env.ENV}:${tenant}:${modelName}:${type}`;
606
+ try {
607
+ const redisClient2 = getRedisClient();
608
+ const value = await redisClient2.get(key);
609
+ if (value) {
610
+ return JSON.parse(value);
611
+ }
612
+ } catch (error) {
613
+ console.warn(
614
+ `redis read failed for key ${key}`,
615
+ error instanceof Error && error.message
616
+ );
617
+ }
618
+ try {
619
+ const collection = getDbByTenant({
620
+ tenant,
621
+ env: process.env.ENV
622
+ }).collection(modelName);
623
+ const value = await collection.findOne(query);
624
+ if (!value) {
625
+ throw new Error(`${type} value not found in ${modelName} for ${tenant}`);
626
+ }
627
+ try {
628
+ const redisClient2 = getRedisClient();
629
+ await redisClient2.set(key, JSON.stringify(value));
630
+ } catch (error) {
631
+ console.warn(
632
+ `redis write failed for key ${key}:`,
633
+ error instanceof Error && error.message
634
+ );
635
+ }
636
+ return value;
637
+ } catch (error) {
638
+ throw new Error(
639
+ `db read failed: ${error instanceof Error && error.message}`
640
+ );
641
+ }
642
+ };
643
+ var getTpl = async ({ name, tenant }) => {
644
+ if (!name || !tenant) {
645
+ throw new Error("Missing required parameters: name or tenant");
646
+ }
647
+ return await findInCache({
648
+ modelName: "tpls",
649
+ type: name,
650
+ tenant,
651
+ query: {
652
+ kp_content_type: name,
653
+ status: { $in: ["published", "editPublished"] }
654
+ }
655
+ });
656
+ };
657
+ var getAIConfigs = async ({
658
+ tenant
659
+ }) => {
660
+ if (!tenant) {
661
+ throw new Error("Missing required parameter: tenant");
662
+ }
663
+ return await findInCache({
664
+ modelName: "platformConfigs",
665
+ type: "ai",
666
+ tenant,
667
+ query: {
668
+ type: "ai"
669
+ }
670
+ });
671
+ };
136
672
  export {
137
673
  add,
674
+ connectToRedis,
138
675
  deleteVal,
676
+ getAIConfigs,
677
+ getAnnotationsModelByTenant,
678
+ getDbByTenant,
679
+ getModelByTenant,
680
+ getPlatformConfigsModelByTenant,
681
+ getTpl,
682
+ getTplModelByTenant,
139
683
  getVal,
140
- setVal
684
+ initializeGlobalConfig,
685
+ multiConnectToMongoDB,
686
+ setVal,
687
+ updateGlobalConfig
141
688
  };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.2.0",
6
+ "version": "1.3.0",
7
7
  "description": "Utility functions for both browser and Node.js",
8
8
  "main": "dist/index.js",
9
9
  "module": "dist/index.mjs",
@@ -34,11 +34,16 @@
34
34
  "@semantic-release/github": "^11.0.1",
35
35
  "@semantic-release/npm": "^12.0.1",
36
36
  "@semantic-release/release-notes-generator": "^14.0.3",
37
+ "@types/ioredis": "^4.28.10",
37
38
  "@types/node": "^22.13.10",
38
39
  "commitizen": "^4.3.1",
39
40
  "cz-conventional-changelog": "^3.3.0",
40
41
  "semantic-release": "^24.2.3",
41
42
  "tsup": "^8.4.0",
42
43
  "typescript": "^5.8.2"
44
+ },
45
+ "dependencies": {
46
+ "ioredis": "^5.6.1",
47
+ "mongoose": "^8.15.1"
43
48
  }
44
49
  }