openloops 0.9.1 → 0.10.2

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 (60) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +2 -0
  3. package/dist/clients/llm/llm-client.d.ts +1 -0
  4. package/dist/clients/llm/llm-client.js +6 -3
  5. package/dist/clients/llm/llm-client.mjs +6 -3
  6. package/dist/common/base/current-user.js +2 -1
  7. package/dist/common/base/current-user.mjs +2 -1
  8. package/dist/common/index.d.ts +3 -0
  9. package/dist/common/index.js +6 -0
  10. package/dist/common/index.mjs +4 -0
  11. package/dist/common/repositories/mongo-db.client.d.ts +1 -1
  12. package/dist/common/repositories/mongo-db.client.js +7 -6
  13. package/dist/common/repositories/mongo-db.client.mjs +7 -6
  14. package/dist/common/repositories/mongo-db.repository.d.ts +3 -2
  15. package/dist/common/repositories/mongo-db.repository.js +20 -16
  16. package/dist/common/repositories/mongo-db.repository.mjs +20 -16
  17. package/dist/common/utils/config-context.d.ts +3 -0
  18. package/dist/common/utils/config-context.js +33 -0
  19. package/dist/common/utils/config-context.mjs +8 -0
  20. package/dist/common/utils/secret-manager.d.ts +7 -5
  21. package/dist/common/utils/secret-manager.js +41 -28
  22. package/dist/common/utils/secret-manager.mjs +41 -28
  23. package/dist/services/authentication/repositories/refresh-token.repository.js +1 -1
  24. package/dist/services/authentication/repositories/refresh-token.repository.mjs +1 -1
  25. package/dist/services/authentication/repositories/revoked-token.repository.js +1 -1
  26. package/dist/services/authentication/repositories/revoked-token.repository.mjs +1 -1
  27. package/dist/services/automations/entities/recurrence.d.ts +11 -0
  28. package/dist/services/automations/entities/recurrence.js +26 -6
  29. package/dist/services/automations/entities/recurrence.mjs +23 -6
  30. package/dist/services/automations/repositories/automation-run.repository.js +1 -1
  31. package/dist/services/automations/repositories/automation-run.repository.mjs +1 -1
  32. package/dist/services/automations/repositories/automation.repository.js +1 -1
  33. package/dist/services/automations/repositories/automation.repository.mjs +1 -1
  34. package/dist/services/automations/runner/automation-runner.js +1 -0
  35. package/dist/services/automations/runner/automation-runner.mjs +1 -0
  36. package/dist/services/automations/utils/next-run.js +9 -0
  37. package/dist/services/automations/utils/next-run.mjs +10 -1
  38. package/dist/services/chats/repositories/chat.repository.js +1 -1
  39. package/dist/services/chats/repositories/chat.repository.mjs +1 -1
  40. package/dist/services/llmcalls/repositories/llmcall.repository.js +1 -1
  41. package/dist/services/llmcalls/repositories/llmcall.repository.mjs +1 -1
  42. package/dist/services/mcp-servers/repositories/mcpserver.repository.js +1 -1
  43. package/dist/services/mcp-servers/repositories/mcpserver.repository.mjs +1 -1
  44. package/dist/services/tasks/repositories/agent-action.repository.js +1 -1
  45. package/dist/services/tasks/repositories/agent-action.repository.mjs +1 -1
  46. package/dist/services/tasks/repositories/agent-task.repository.js +1 -1
  47. package/dist/services/tasks/repositories/agent-task.repository.mjs +1 -1
  48. package/dist/services/traces/repositories/agent-trace.repository.js +1 -1
  49. package/dist/services/traces/repositories/agent-trace.repository.mjs +1 -1
  50. package/dist/services/users/repositories/user.repository.js +1 -1
  51. package/dist/services/users/repositories/user.repository.mjs +1 -1
  52. package/dist/services/workspaces/repositories/workspace-item.repository.js +1 -1
  53. package/dist/services/workspaces/repositories/workspace-item.repository.mjs +1 -1
  54. package/docs/README.md +1 -1
  55. package/docs/automations.md +2 -0
  56. package/docs/configuration.md +30 -1
  57. package/docs/integration-guide.md +1 -1
  58. package/docs/llms.txt +1 -1
  59. package/examples/run-agent/run-agent-multi-tenant.ts +52 -0
  60. package/package.json +13 -1
package/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  All notable changes to `openloops` are written here, newest first. The format follows [Keep a Changelog](https://keepachangelog.com) and the versions follow [semantic versioning](https://semver.org), where a minor version can still break the API while the package is in beta. Changes before 0.4.0 are not recorded here, see the commits and the tags.
4
4
 
5
+ ## 0.10.1
6
+
7
+ ### Added
8
+
9
+ - `openloops/tasks`, `openloops/traces` and `openloops/workspaces` are exported, so a backend can read the tasks, actions, traces and workspace items of a chat (`listAgentTasksByChat`, `getAgentTaskById`, `listAgentActionsByTask`, `listAgentTracesByChat`, `listWorkspaceItems`, `getWorkspaceItem`, `searchWorkspaceItems`, `saveWorkspaceItem`, `deleteWorkspaceItem`). Their functions already existed and only the subpaths were missing.
10
+
11
+ - Recurrence of type `interval` for automations: every X minutes or hours counted from a `start` date and time (`{ type: 'interval', every, unit, start }`, `IntervalUnit` enum). It is an exact interval from `start`, not tied to the clock, and the shortest is 5 minutes. No migration needed.
12
+
13
+ ### Changed
14
+
15
+ - The chat of an automation run takes the name of the automation as its title. Before, it took the first 80 characters of the instructions, or had none.
16
+
17
+ ## 0.10.0
18
+
19
+ ### Added
20
+
21
+ - `runWithConfigs(configs, fn)` (`openloops/common`) runs `fn` with its own configuration, so one process can serve several agents. `secretManager.get` reads the configs of the current context first (values can be `ENC:` or `ENC:v<N>:`) and the environment when there is no context.
22
+ - Versioned encrypted values, `ENC:v<N>:`, with the master key in `SECRET_MANAGER_KEY_V<N>`. `SecretManager.encrypt(value, version?)` writes them. `ENC:` values keep using `SECRET_MANAGER_KEY`.
23
+
24
+ ### Changed
25
+
26
+ - The repositories resolve the database name and the Mongo client on every call, not when the module loads. Mongo clients are cached by connection string. `getMongoDBClient` returns `undefined` when the connection string is not configured.
27
+ - The LLM client sends the API key of the provider on each request (`apiKey`) and no longer writes `OPENAI_API_KEY` and `ANTHROPIC_API_KEY` into `process.env`. When the key is not configured, the provider falls back to its own environment variable as before.
28
+
5
29
  ## 0.9.1
6
30
 
7
31
  ### Changed
package/README.md CHANGED
@@ -187,6 +187,8 @@ OPENLOOPS_DB_URI="mongodb://localhost:27017/"
187
187
  OPENLOOPS_DB_NAME='openloops'
188
188
 
189
189
  SECRET_MANAGER_KEY=secret
190
+ # Only for ENC:v<N>: values, see docs/configuration.md
191
+ # SECRET_MANAGER_KEY_V1=
190
192
 
191
193
  # Default model provider (anthropic, claude-haiku-5-5)
192
194
  ANTHROPIC_API_KEY=
@@ -9,6 +9,7 @@ export declare class LLMClient {
9
9
  private readonly callTimeoutMs;
10
10
  constructor();
11
11
  chat(params: LLMChatParams): Promise<LLMResponse>;
12
+ private apiKeyOf;
12
13
  private chooseModel;
13
14
  private withDeadline;
14
15
  private flushLangfuse;
@@ -66,8 +66,6 @@ class LLMClient {
66
66
  langfuseEnabled;
67
67
  callTimeoutMs;
68
68
  constructor() {
69
- process.env.OPENAI_API_KEY = import_secret_manager.secretManager.get("OPENAI_API_KEY");
70
- process.env.ANTHROPIC_API_KEY = import_secret_manager.secretManager.get("ANTHROPIC_API_KEY");
71
69
  this.callTimeoutMs = (0, import_number_setting.numberSetting)("LLM_CALL_TIMEOUT_MS", DEFAULT_CALL_TIMEOUT_MS);
72
70
  const publicKey = import_secret_manager.secretManager.get("LANGFUSE_PUBLIC_KEY");
73
71
  const secretKey = import_secret_manager.secretManager.get("LANGFUSE_SECRET_KEY");
@@ -103,7 +101,8 @@ class LLMClient {
103
101
  const reasoning = thinking && thinking !== "off" ? thinking : void 0;
104
102
  const ruleOmitsTemperature = (0, import_sampling_rules.omitsTemperature)(provider, modelName, Boolean(reasoning));
105
103
  const send = (omitTemperature) => this.withDeadline(thinking === "high" ? this.callTimeoutMs * HIGH_THINKING_TIMEOUT_FACTOR : this.callTimeoutMs, (signal) => {
106
- const options = { ...omitTemperature || ruleOmitsTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, signal, ...sessionId ? { sessionId } : {} };
104
+ const apiKey = this.apiKeyOf(provider);
105
+ const options = { ...apiKey ? { apiKey } : {}, ...omitTemperature || ruleOmitsTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, signal, ...sessionId ? { sessionId } : {} };
107
106
  return resolvedChoice || thinking ? models.completeSimple(model, context, { ...options, ...resolvedChoice ? { toolChoice: resolvedChoice } : {}, ...reasoning ? { reasoning } : {} }) : models.complete(model, context, options);
108
107
  });
109
108
  const raw = await this.traced(
@@ -116,6 +115,10 @@ class LLMClient {
116
115
  }
117
116
  return (0, import_pi_ai_adapter.fromPiMessage)(raw);
118
117
  }
118
+ apiKeyOf(provider) {
119
+ const name = provider === "google" ? "GEMINI_API_KEY" : `${provider.toUpperCase().replace(/-/g, "_")}_API_KEY`;
120
+ return import_secret_manager.secretManager.get(name) || void 0;
121
+ }
119
122
  chooseModel(params) {
120
123
  const { provider, modelName, currentUser } = params ?? {};
121
124
  if (Boolean(provider) !== Boolean(modelName)) throw new Error("[LLM Client] provider and modelName must be given together");
@@ -33,8 +33,6 @@ class LLMClient {
33
33
  langfuseEnabled;
34
34
  callTimeoutMs;
35
35
  constructor() {
36
- process.env.OPENAI_API_KEY = secretManager.get("OPENAI_API_KEY");
37
- process.env.ANTHROPIC_API_KEY = secretManager.get("ANTHROPIC_API_KEY");
38
36
  this.callTimeoutMs = numberSetting("LLM_CALL_TIMEOUT_MS", DEFAULT_CALL_TIMEOUT_MS);
39
37
  const publicKey = secretManager.get("LANGFUSE_PUBLIC_KEY");
40
38
  const secretKey = secretManager.get("LANGFUSE_SECRET_KEY");
@@ -70,7 +68,8 @@ class LLMClient {
70
68
  const reasoning = thinking && thinking !== "off" ? thinking : void 0;
71
69
  const ruleOmitsTemperature = omitsTemperature(provider, modelName, Boolean(reasoning));
72
70
  const send = (omitTemperature) => this.withDeadline(thinking === "high" ? this.callTimeoutMs * HIGH_THINKING_TIMEOUT_FACTOR : this.callTimeoutMs, (signal) => {
73
- const options = { ...omitTemperature || ruleOmitsTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, signal, ...sessionId ? { sessionId } : {} };
71
+ const apiKey = this.apiKeyOf(provider);
72
+ const options = { ...apiKey ? { apiKey } : {}, ...omitTemperature || ruleOmitsTemperature ? {} : { temperature }, maxRetries: MAX_RETRIES, signal, ...sessionId ? { sessionId } : {} };
74
73
  return resolvedChoice || thinking ? models.completeSimple(model, context, { ...options, ...resolvedChoice ? { toolChoice: resolvedChoice } : {}, ...reasoning ? { reasoning } : {} }) : models.complete(model, context, options);
75
74
  });
76
75
  const raw = await this.traced(
@@ -83,6 +82,10 @@ class LLMClient {
83
82
  }
84
83
  return fromPiMessage(raw);
85
84
  }
85
+ apiKeyOf(provider) {
86
+ const name = provider === "google" ? "GEMINI_API_KEY" : `${provider.toUpperCase().replace(/-/g, "_")}_API_KEY`;
87
+ return secretManager.get(name) || void 0;
88
+ }
86
89
  chooseModel(params) {
87
90
  const { provider, modelName, currentUser } = params ?? {};
88
91
  if (Boolean(provider) !== Boolean(modelName)) throw new Error("[LLM Client] provider and modelName must be given together");
@@ -32,11 +32,12 @@ class CurrentUser extends import_user.User {
32
32
  static async asyncFromDB(userId) {
33
33
  if (!userId) return void 0;
34
34
  const mongoDBClient = (0, import_mongo_db.getMongoDBClient)();
35
+ if (!mongoDBClient) throw new Error("[Current User] Database client not found");
35
36
  const db = await mongoDBClient.db((0, import_database_name.getDatabaseName)());
36
37
  let user;
37
38
  try {
38
39
  user = await db.collection("users").findOne(
39
- { _id: new import_mongodb.ObjectId(userId) },
40
+ { _id: new import_mongodb.ObjectId(userId), deletedAt: null, archivedAt: null },
40
41
  { projection: { password: 0 } }
41
42
  );
42
43
  } catch (error) {
@@ -9,11 +9,12 @@ class CurrentUser extends User {
9
9
  static async asyncFromDB(userId) {
10
10
  if (!userId) return void 0;
11
11
  const mongoDBClient = getMongoDBClient();
12
+ if (!mongoDBClient) throw new Error("[Current User] Database client not found");
12
13
  const db = await mongoDBClient.db(getDatabaseName());
13
14
  let user;
14
15
  try {
15
16
  user = await db.collection("users").findOne(
16
- { _id: new ObjectId(userId) },
17
+ { _id: new ObjectId(userId), deletedAt: null, archivedAt: null },
17
18
  { projection: { password: 0 } }
18
19
  );
19
20
  } catch (error) {
@@ -1,3 +1,6 @@
1
1
  export * from './logger';
2
2
  export { setErrorReporter } from './error/error-reporter';
3
3
  export type { ErrorReporter, ErrorReportDetails } from './error/error-reporter';
4
+ export { runWithConfigs } from './utils/config-context';
5
+ export type { Configs } from './utils/config-context';
6
+ export { SecretManager } from './utils/secret-manager';
@@ -19,13 +19,19 @@ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "defau
19
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
20
  var common_exports = {};
21
21
  __export(common_exports, {
22
+ SecretManager: () => import_secret_manager.SecretManager,
23
+ runWithConfigs: () => import_config_context.runWithConfigs,
22
24
  setErrorReporter: () => import_error_reporter.setErrorReporter
23
25
  });
24
26
  module.exports = __toCommonJS(common_exports);
25
27
  __reExport(common_exports, require("./logger"), module.exports);
26
28
  var import_error_reporter = require("./error/error-reporter");
29
+ var import_config_context = require("./utils/config-context");
30
+ var import_secret_manager = require("./utils/secret-manager");
27
31
  // Annotate the CommonJS export names for ESM import in node:
28
32
  0 && (module.exports = {
33
+ SecretManager,
34
+ runWithConfigs,
29
35
  setErrorReporter,
30
36
  ...require("./logger")
31
37
  });
@@ -1,5 +1,9 @@
1
1
  export * from "./logger";
2
2
  import { setErrorReporter } from "./error/error-reporter";
3
+ import { runWithConfigs } from "./utils/config-context";
4
+ import { SecretManager } from "./utils/secret-manager";
3
5
  export {
6
+ SecretManager,
7
+ runWithConfigs,
4
8
  setErrorReporter
5
9
  };
@@ -8,4 +8,4 @@ export declare class MongoClient {
8
8
  close(force?: boolean): Promise<void>;
9
9
  db(dbName?: string, options?: DbOptions): Promise<Db>;
10
10
  }
11
- export declare function getMongoDBClient(envVarName?: string): MongoClient;
11
+ export declare function getMongoDBClient(envVarName?: string): MongoClient | undefined;
@@ -67,13 +67,14 @@ class MongoClient {
67
67
  }
68
68
  const mongoDBClients = /* @__PURE__ */ new Map();
69
69
  function getMongoDBClient(envVarName = "OPENLOOPS_DB_URI") {
70
- if (!mongoDBClients.has(envVarName)) {
71
- const connString = import_secret_manager.secretManager.get(envVarName);
72
- if (connString) {
73
- mongoDBClients.set(envVarName, new MongoClient(connString, {}));
74
- }
70
+ const connString = import_secret_manager.secretManager.get(envVarName);
71
+ if (!connString) return void 0;
72
+ let client = mongoDBClients.get(connString);
73
+ if (!client) {
74
+ client = new MongoClient(connString, {});
75
+ mongoDBClients.set(connString, client);
75
76
  }
76
- return mongoDBClients.get(envVarName);
77
+ return client;
77
78
  }
78
79
  // Annotate the CommonJS export names for ESM import in node:
79
80
  0 && (module.exports = {
@@ -45,13 +45,14 @@ class MongoClient {
45
45
  }
46
46
  const mongoDBClients = /* @__PURE__ */ new Map();
47
47
  function getMongoDBClient(envVarName = "OPENLOOPS_DB_URI") {
48
- if (!mongoDBClients.has(envVarName)) {
49
- const connString = secretManager.get(envVarName);
50
- if (connString) {
51
- mongoDBClients.set(envVarName, new MongoClient(connString, {}));
52
- }
48
+ const connString = secretManager.get(envVarName);
49
+ if (!connString) return void 0;
50
+ let client = mongoDBClients.get(connString);
51
+ if (!client) {
52
+ client = new MongoClient(connString, {});
53
+ mongoDBClients.set(connString, client);
53
54
  }
54
- return mongoDBClients.get(envVarName);
55
+ return client;
55
56
  }
56
57
  export {
57
58
  MongoClient,
@@ -9,20 +9,21 @@ export declare class VersionConflictError extends Error {
9
9
  export declare class MongoRepository<T> {
10
10
  private readonly database;
11
11
  private readonly collection;
12
- private readonly dbClient;
12
+ private readonly envvar?;
13
13
  private readonly _where;
14
14
  private readonly scoped;
15
15
  private readonly ownerField;
16
16
  private readonly protectedFields;
17
17
  private readonly report;
18
18
  constructor(props: {
19
- database: string;
19
+ database: string | (() => string);
20
20
  collection: string;
21
21
  envvar?: string;
22
22
  scoped?: boolean;
23
23
  ownerField?: string;
24
24
  protectedFields?: string[];
25
25
  });
26
+ private db;
26
27
  private assertScope;
27
28
  private actorId;
28
29
  private withScope;
@@ -39,7 +39,7 @@ class VersionConflictError extends Error {
39
39
  class MongoRepository {
40
40
  database;
41
41
  collection;
42
- dbClient;
42
+ envvar;
43
43
  _where = { deletedAt: null, archivedAt: null };
44
44
  scoped;
45
45
  ownerField;
@@ -49,14 +49,18 @@ class MongoRepository {
49
49
  const { database, collection, envvar, scoped = false, ownerField = "ownerId", protectedFields = [] } = props || {};
50
50
  if (!database) throw new Error("[Mongo Repository] Database name is required");
51
51
  if (!collection) throw new Error("[Mongo Repository] Collection name is required");
52
- this.dbClient = (0, import_mongo_db.getMongoDBClient)(envvar);
53
- if (!this.dbClient) throw new Error("[Mongo Repository] Database client not found");
52
+ this.envvar = envvar;
54
53
  this.database = database;
55
54
  this.collection = collection;
56
55
  this.scoped = scoped;
57
56
  this.ownerField = ownerField;
58
57
  this.protectedFields = [...PROTECTED_FIELDS, ...protectedFields];
59
58
  }
59
+ async db() {
60
+ const client = (0, import_mongo_db.getMongoDBClient)(this.envvar);
61
+ if (!client) throw new Error("[Mongo Repository] Database client not found");
62
+ return client.db(typeof this.database === "function" ? this.database() : this.database);
63
+ }
60
64
  assertScope(scope) {
61
65
  if (!scope && this.scoped) throw new Error(`[Mongo Repository] Scope is required in ${this.collection}`);
62
66
  }
@@ -114,7 +118,7 @@ class MongoRepository {
114
118
  async findOne({ where, select, options, scope }) {
115
119
  const filter = this.withScope({ ...where, ...this._where }, scope);
116
120
  try {
117
- const db = await this.dbClient.db(this.database);
121
+ const db = await this.db();
118
122
  const collection = db.collection(this.collection);
119
123
  const result = await collection.findOne(
120
124
  filter,
@@ -141,7 +145,7 @@ class MongoRepository {
141
145
  async query({ where, select, options, scope }, pageSize, fetchSize) {
142
146
  const filter = this.withScope({ ...where, ...this._where }, scope);
143
147
  try {
144
- const db = await this.dbClient.db(this.database);
148
+ const db = await this.db();
145
149
  const collection = db.collection(this.collection);
146
150
  const { page = 1 } = options || {};
147
151
  const _skip = +page > 0 ? (+page - 1) * pageSize : 0;
@@ -155,7 +159,7 @@ class MongoRepository {
155
159
  async findAll({ where, select, options, scope }) {
156
160
  const filter = this.withScope({ ...where, ...this._where }, scope);
157
161
  try {
158
- const db = await this.dbClient.db(this.database);
162
+ const db = await this.db();
159
163
  const collection = db.collection(this.collection);
160
164
  const cursor = collection.find(filter, { projection: select });
161
165
  const result = await (options?.sortBy ? cursor.sort(options.sortBy) : cursor).toArray();
@@ -169,7 +173,7 @@ class MongoRepository {
169
173
  if (!payload || Object.keys(payload).length === 0) throw new Error("[Mongo Repository] Payload is required for createOne operation");
170
174
  const document = this.stampCreate(payload, scope);
171
175
  try {
172
- const db = await this.dbClient.db(this.database);
176
+ const db = await this.db();
173
177
  const collection = db.collection(this.collection);
174
178
  const { insertedId } = await collection.insertOne({ ...document, __v: 1 }, { ignoreUndefined: true });
175
179
  return { ...document, _id: insertedId, __v: 1 };
@@ -181,7 +185,7 @@ class MongoRepository {
181
185
  async createMany({ payload, scope }) {
182
186
  const documents = payload.map((item) => this.stampCreate(item, scope));
183
187
  try {
184
- const db = await this.dbClient.db(this.database);
188
+ const db = await this.db();
185
189
  const collection = db.collection(this.collection);
186
190
  const { insertedIds } = await collection.insertMany(documents.map((document) => ({ ...document, __v: 1 })), { ignoreUndefined: true });
187
191
  return insertedIds;
@@ -214,7 +218,7 @@ class MongoRepository {
214
218
  async claimOne({ where, set, scope }) {
215
219
  const filter = this.withScope({ ...where, ...this._where }, scope);
216
220
  try {
217
- const db = await this.dbClient.db(this.database);
221
+ const db = await this.db();
218
222
  const collection = db.collection(this.collection);
219
223
  const result = await collection.findOneAndUpdate(
220
224
  filter,
@@ -246,7 +250,7 @@ class MongoRepository {
246
250
  const checkVersion = typeof expectedVersion === "number";
247
251
  const filter = this.withScope({ ...where, ...checkVersion ? { __v: expectedVersion } : {}, ...this._where }, scope);
248
252
  try {
249
- const db = await this.dbClient.db(this.database);
253
+ const db = await this.db();
250
254
  const collection = db.collection(this.collection);
251
255
  const result = await collection.findOneAndUpdate(
252
256
  filter,
@@ -271,7 +275,7 @@ class MongoRepository {
271
275
  ...scope ? { updatedAt: /* @__PURE__ */ new Date(), ...actor ? { updatedBy: actor } : {} } : {}
272
276
  };
273
277
  try {
274
- const db = await this.dbClient.db(this.database);
278
+ const db = await this.db();
275
279
  const collection = db.collection(this.collection);
276
280
  const result = await collection.updateMany(
277
281
  filter,
@@ -287,7 +291,7 @@ class MongoRepository {
287
291
  async deleteOne({ where, scope }) {
288
292
  const filter = this.withScope({ ...where }, scope);
289
293
  try {
290
- const db = await this.dbClient.db(this.database);
294
+ const db = await this.db();
291
295
  const collection = db.collection(this.collection);
292
296
  const { deletedCount } = await collection.deleteOne(filter);
293
297
  return deletedCount;
@@ -299,7 +303,7 @@ class MongoRepository {
299
303
  async deleteMany({ where, scope }) {
300
304
  const filter = this.withScope({ ...where }, scope);
301
305
  try {
302
- const db = await this.dbClient.db(this.database);
306
+ const db = await this.db();
303
307
  const collection = db.collection(this.collection);
304
308
  const { deletedCount } = await collection.deleteMany(filter);
305
309
  return deletedCount;
@@ -311,7 +315,7 @@ class MongoRepository {
311
315
  async count({ where, options, scope }) {
312
316
  const filter = this.withScope({ ...where, ...options?.includeDeleted ? {} : this._where }, scope);
313
317
  try {
314
- const db = await this.dbClient.db(this.database);
318
+ const db = await this.db();
315
319
  const collection = db.collection(this.collection);
316
320
  const result = await collection.countDocuments(filter);
317
321
  return result;
@@ -324,7 +328,7 @@ class MongoRepository {
324
328
  const scopeFilter = this.withScope({}, scope);
325
329
  const scopedPipeline = Object.keys(scopeFilter).length ? [{ $match: scopeFilter }, ...pipeline] : pipeline;
326
330
  try {
327
- const db = await this.dbClient.db(this.database);
331
+ const db = await this.db();
328
332
  const collection = db.collection(this.collection);
329
333
  const result = await collection.aggregate(scopedPipeline).toArray();
330
334
  return result;
@@ -336,7 +340,7 @@ class MongoRepository {
336
340
  async distinct(field, where, scope) {
337
341
  const filter = this.withScope({ ...where, ...this._where }, scope);
338
342
  try {
339
- const db = await this.dbClient.db(this.database);
343
+ const db = await this.db();
340
344
  const collection = db.collection(this.collection);
341
345
  const result = await collection.distinct(field, filter);
342
346
  return result;
@@ -15,7 +15,7 @@ class VersionConflictError extends Error {
15
15
  class MongoRepository {
16
16
  database;
17
17
  collection;
18
- dbClient;
18
+ envvar;
19
19
  _where = { deletedAt: null, archivedAt: null };
20
20
  scoped;
21
21
  ownerField;
@@ -25,14 +25,18 @@ class MongoRepository {
25
25
  const { database, collection, envvar, scoped = false, ownerField = "ownerId", protectedFields = [] } = props || {};
26
26
  if (!database) throw new Error("[Mongo Repository] Database name is required");
27
27
  if (!collection) throw new Error("[Mongo Repository] Collection name is required");
28
- this.dbClient = getMongoDBClient(envvar);
29
- if (!this.dbClient) throw new Error("[Mongo Repository] Database client not found");
28
+ this.envvar = envvar;
30
29
  this.database = database;
31
30
  this.collection = collection;
32
31
  this.scoped = scoped;
33
32
  this.ownerField = ownerField;
34
33
  this.protectedFields = [...PROTECTED_FIELDS, ...protectedFields];
35
34
  }
35
+ async db() {
36
+ const client = getMongoDBClient(this.envvar);
37
+ if (!client) throw new Error("[Mongo Repository] Database client not found");
38
+ return client.db(typeof this.database === "function" ? this.database() : this.database);
39
+ }
36
40
  assertScope(scope) {
37
41
  if (!scope && this.scoped) throw new Error(`[Mongo Repository] Scope is required in ${this.collection}`);
38
42
  }
@@ -90,7 +94,7 @@ class MongoRepository {
90
94
  async findOne({ where, select, options, scope }) {
91
95
  const filter = this.withScope({ ...where, ...this._where }, scope);
92
96
  try {
93
- const db = await this.dbClient.db(this.database);
97
+ const db = await this.db();
94
98
  const collection = db.collection(this.collection);
95
99
  const result = await collection.findOne(
96
100
  filter,
@@ -117,7 +121,7 @@ class MongoRepository {
117
121
  async query({ where, select, options, scope }, pageSize, fetchSize) {
118
122
  const filter = this.withScope({ ...where, ...this._where }, scope);
119
123
  try {
120
- const db = await this.dbClient.db(this.database);
124
+ const db = await this.db();
121
125
  const collection = db.collection(this.collection);
122
126
  const { page = 1 } = options || {};
123
127
  const _skip = +page > 0 ? (+page - 1) * pageSize : 0;
@@ -131,7 +135,7 @@ class MongoRepository {
131
135
  async findAll({ where, select, options, scope }) {
132
136
  const filter = this.withScope({ ...where, ...this._where }, scope);
133
137
  try {
134
- const db = await this.dbClient.db(this.database);
138
+ const db = await this.db();
135
139
  const collection = db.collection(this.collection);
136
140
  const cursor = collection.find(filter, { projection: select });
137
141
  const result = await (options?.sortBy ? cursor.sort(options.sortBy) : cursor).toArray();
@@ -145,7 +149,7 @@ class MongoRepository {
145
149
  if (!payload || Object.keys(payload).length === 0) throw new Error("[Mongo Repository] Payload is required for createOne operation");
146
150
  const document = this.stampCreate(payload, scope);
147
151
  try {
148
- const db = await this.dbClient.db(this.database);
152
+ const db = await this.db();
149
153
  const collection = db.collection(this.collection);
150
154
  const { insertedId } = await collection.insertOne({ ...document, __v: 1 }, { ignoreUndefined: true });
151
155
  return { ...document, _id: insertedId, __v: 1 };
@@ -157,7 +161,7 @@ class MongoRepository {
157
161
  async createMany({ payload, scope }) {
158
162
  const documents = payload.map((item) => this.stampCreate(item, scope));
159
163
  try {
160
- const db = await this.dbClient.db(this.database);
164
+ const db = await this.db();
161
165
  const collection = db.collection(this.collection);
162
166
  const { insertedIds } = await collection.insertMany(documents.map((document) => ({ ...document, __v: 1 })), { ignoreUndefined: true });
163
167
  return insertedIds;
@@ -190,7 +194,7 @@ class MongoRepository {
190
194
  async claimOne({ where, set, scope }) {
191
195
  const filter = this.withScope({ ...where, ...this._where }, scope);
192
196
  try {
193
- const db = await this.dbClient.db(this.database);
197
+ const db = await this.db();
194
198
  const collection = db.collection(this.collection);
195
199
  const result = await collection.findOneAndUpdate(
196
200
  filter,
@@ -222,7 +226,7 @@ class MongoRepository {
222
226
  const checkVersion = typeof expectedVersion === "number";
223
227
  const filter = this.withScope({ ...where, ...checkVersion ? { __v: expectedVersion } : {}, ...this._where }, scope);
224
228
  try {
225
- const db = await this.dbClient.db(this.database);
229
+ const db = await this.db();
226
230
  const collection = db.collection(this.collection);
227
231
  const result = await collection.findOneAndUpdate(
228
232
  filter,
@@ -247,7 +251,7 @@ class MongoRepository {
247
251
  ...scope ? { updatedAt: /* @__PURE__ */ new Date(), ...actor ? { updatedBy: actor } : {} } : {}
248
252
  };
249
253
  try {
250
- const db = await this.dbClient.db(this.database);
254
+ const db = await this.db();
251
255
  const collection = db.collection(this.collection);
252
256
  const result = await collection.updateMany(
253
257
  filter,
@@ -263,7 +267,7 @@ class MongoRepository {
263
267
  async deleteOne({ where, scope }) {
264
268
  const filter = this.withScope({ ...where }, scope);
265
269
  try {
266
- const db = await this.dbClient.db(this.database);
270
+ const db = await this.db();
267
271
  const collection = db.collection(this.collection);
268
272
  const { deletedCount } = await collection.deleteOne(filter);
269
273
  return deletedCount;
@@ -275,7 +279,7 @@ class MongoRepository {
275
279
  async deleteMany({ where, scope }) {
276
280
  const filter = this.withScope({ ...where }, scope);
277
281
  try {
278
- const db = await this.dbClient.db(this.database);
282
+ const db = await this.db();
279
283
  const collection = db.collection(this.collection);
280
284
  const { deletedCount } = await collection.deleteMany(filter);
281
285
  return deletedCount;
@@ -287,7 +291,7 @@ class MongoRepository {
287
291
  async count({ where, options, scope }) {
288
292
  const filter = this.withScope({ ...where, ...options?.includeDeleted ? {} : this._where }, scope);
289
293
  try {
290
- const db = await this.dbClient.db(this.database);
294
+ const db = await this.db();
291
295
  const collection = db.collection(this.collection);
292
296
  const result = await collection.countDocuments(filter);
293
297
  return result;
@@ -300,7 +304,7 @@ class MongoRepository {
300
304
  const scopeFilter = this.withScope({}, scope);
301
305
  const scopedPipeline = Object.keys(scopeFilter).length ? [{ $match: scopeFilter }, ...pipeline] : pipeline;
302
306
  try {
303
- const db = await this.dbClient.db(this.database);
307
+ const db = await this.db();
304
308
  const collection = db.collection(this.collection);
305
309
  const result = await collection.aggregate(scopedPipeline).toArray();
306
310
  return result;
@@ -312,7 +316,7 @@ class MongoRepository {
312
316
  async distinct(field, where, scope) {
313
317
  const filter = this.withScope({ ...where, ...this._where }, scope);
314
318
  try {
315
- const db = await this.dbClient.db(this.database);
319
+ const db = await this.db();
316
320
  const collection = db.collection(this.collection);
317
321
  const result = await collection.distinct(field, filter);
318
322
  return result;
@@ -0,0 +1,3 @@
1
+ export type Configs = Readonly<Record<string, string>>;
2
+ export declare const runWithConfigs: <T>(configs: Configs, fn: () => T) => T;
3
+ export declare const getContextConfigs: () => Configs | undefined;
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
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 config_context_exports = {};
20
+ __export(config_context_exports, {
21
+ getContextConfigs: () => getContextConfigs,
22
+ runWithConfigs: () => runWithConfigs
23
+ });
24
+ module.exports = __toCommonJS(config_context_exports);
25
+ var import_node_async_hooks = require("node:async_hooks");
26
+ const storage = new import_node_async_hooks.AsyncLocalStorage();
27
+ const runWithConfigs = (configs, fn) => storage.run(configs, fn);
28
+ const getContextConfigs = () => storage.getStore();
29
+ // Annotate the CommonJS export names for ESM import in node:
30
+ 0 && (module.exports = {
31
+ getContextConfigs,
32
+ runWithConfigs
33
+ });
@@ -0,0 +1,8 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const storage = new AsyncLocalStorage();
3
+ const runWithConfigs = (configs, fn) => storage.run(configs, fn);
4
+ const getContextConfigs = () => storage.getStore();
5
+ export {
6
+ getContextConfigs,
7
+ runWithConfigs
8
+ };
@@ -1,15 +1,17 @@
1
1
  import 'dotenv/config';
2
2
  export declare class SecretManager {
3
3
  private static instance;
4
- private cache;
5
- private cryptr;
4
+ private envCache;
5
+ private contextCache;
6
+ private cryptrs;
6
7
  static getInstance(): SecretManager;
7
- static encrypt(value: string): string;
8
+ static encrypt(value: string, version?: number): string;
8
9
  private constructor();
10
+ private cryptr;
9
11
  get(key: string): string;
12
+ private cacheOf;
10
13
  private getEnvVar;
11
- private decryptEnvVar;
12
- private isStringEncrypted;
14
+ private decrypt;
13
15
  private logElapsed;
14
16
  }
15
17
  export declare const secretManager: SecretManager;