dirac-lang 0.1.26 → 0.1.28

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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  integrate
3
- } from "./chunk-7OUYWIZV.js";
3
+ } from "./chunk-EVNSAF33.js";
4
4
  import {
5
5
  DiracParser
6
6
  } from "./chunk-HRHAMPOB.js";
@@ -8,7 +8,7 @@ import {
8
8
  createSession,
9
9
  getAvailableSubroutines,
10
10
  getOutput
11
- } from "./chunk-52ED23DR.js";
11
+ } from "./chunk-BSQV77YM.js";
12
12
 
13
13
  // src/utils/llm-adapter.ts
14
14
  function createLLMAdapter(session) {
@@ -67,21 +67,23 @@ function createSession(config = {}) {
67
67
  const openaiKey = config.apiKey || process.env.OPENAI_API_KEY;
68
68
  const llmProvider = config.llmProvider || process.env.LLM_PROVIDER;
69
69
  const ollamaModel = config.llmModel || process.env.LLM_MODEL || "llama2";
70
- let llmClient;
71
- switch (llmProvider) {
72
- case "ollama":
73
- llmClient = new OllamaProvider({ model: ollamaModel });
74
- break;
75
- case "anthropic":
76
- if (!anthropicKey) throw new Error("ANTHROPIC_API_KEY required for Anthropic provider");
77
- llmClient = new Anthropic({ apiKey: anthropicKey });
78
- break;
79
- case "openai":
80
- if (!openaiKey) throw new Error("OPENAI_API_KEY required for OpenAI provider");
81
- llmClient = new OpenAI({ apiKey: openaiKey });
82
- break;
83
- default:
84
- throw new Error("No valid LLM provider configured. Set llmProvider in config or LLM_PROVIDER env.");
70
+ let llmClient = null;
71
+ if (llmProvider) {
72
+ switch (llmProvider) {
73
+ case "ollama":
74
+ llmClient = new OllamaProvider({ model: ollamaModel });
75
+ break;
76
+ case "anthropic":
77
+ if (!anthropicKey) throw new Error("ANTHROPIC_API_KEY required for Anthropic provider");
78
+ llmClient = new Anthropic({ apiKey: anthropicKey });
79
+ break;
80
+ case "openai":
81
+ if (!openaiKey) throw new Error("OPENAI_API_KEY required for OpenAI provider");
82
+ llmClient = new OpenAI({ apiKey: openaiKey });
83
+ break;
84
+ default:
85
+ throw new Error(`Unknown LLM provider: ${llmProvider}. Use 'ollama', 'anthropic', or 'openai'.`);
86
+ }
85
87
  }
86
88
  return {
87
89
  variables: [],
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-HRHAMPOB.js";
4
4
  import {
5
5
  executeSubroutine
6
- } from "./chunk-E7PWEMZA.js";
6
+ } from "./chunk-LXF5PGUX.js";
7
7
  import {
8
8
  cleanToBoundary,
9
9
  emit,
@@ -23,7 +23,7 @@ import {
23
23
  substituteVariables,
24
24
  throwException,
25
25
  unsetExceptionBoundary
26
- } from "./chunk-52ED23DR.js";
26
+ } from "./chunk-BSQV77YM.js";
27
27
 
28
28
  // src/tags/parameters.ts
29
29
  async function executeParameters(session, element) {
@@ -255,7 +255,7 @@ async function executeCall(session, element) {
255
255
  }
256
256
  }
257
257
  async function registerExtendChain(session, subroutine, currentName) {
258
- const { executeSubroutine: executeSubroutine2 } = await import("./subroutine-K4YTGUGJ.js");
258
+ const { executeSubroutine: executeSubroutine2 } = await import("./subroutine-GG66UT4D.js");
259
259
  const extendsAttr = subroutine.attributes.extends;
260
260
  let parentName;
261
261
  if (extendsAttr) {
@@ -419,12 +419,12 @@ async function executeIf(session, element) {
419
419
  const condition = await evaluatePredicate(session, conditionElement);
420
420
  if (condition) {
421
421
  if (thenElement) {
422
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-MTIIHIIQ.js");
422
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-Q6UF3RRU.js");
423
423
  await integrateChildren2(session, thenElement);
424
424
  }
425
425
  } else {
426
426
  if (elseElement) {
427
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-MTIIHIIQ.js");
427
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-Q6UF3RRU.js");
428
428
  await integrateChildren2(session, elseElement);
429
429
  }
430
430
  }
@@ -437,7 +437,7 @@ async function evaluatePredicate(session, predicateElement) {
437
437
  return await evaluateCondition(session, predicateElement);
438
438
  }
439
439
  const outputLengthBefore = session.output.length;
440
- const { integrate: integrate2 } = await import("./interpreter-MTIIHIIQ.js");
440
+ const { integrate: integrate2 } = await import("./interpreter-Q6UF3RRU.js");
441
441
  await integrate2(session, predicateElement);
442
442
  const newOutputChunks = session.output.slice(outputLengthBefore);
443
443
  const result = newOutputChunks.join("").trim();
@@ -460,11 +460,11 @@ async function evaluateCondition(session, condElement) {
460
460
  }
461
461
  const outputLengthBefore = session.output.length;
462
462
  const args = [];
463
- const { integrate: integrate2 } = await import("./interpreter-MTIIHIIQ.js");
463
+ const { integrate: integrate2 } = await import("./interpreter-Q6UF3RRU.js");
464
464
  for (const child of condElement.children) {
465
465
  if (child.tag.toLowerCase() === "arg") {
466
466
  const argOutputStart = session.output.length;
467
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-MTIIHIIQ.js");
467
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-Q6UF3RRU.js");
468
468
  await integrateChildren2(session, child);
469
469
  const newChunks = session.output.slice(argOutputStart);
470
470
  const argValue = newChunks.join("");
@@ -525,7 +525,7 @@ function evaluateConditionType(evalType, args) {
525
525
  // src/tags/llm.ts
526
526
  async function executeLLM(session, element) {
527
527
  if (!session.llmClient) {
528
- throw new Error("<LLM> requires API key (set OPENAI_API_KEY, ANTHROPIC_API_KEY, or LLM_PROVIDER=ollama in .env file)");
528
+ throw new Error("<llm> tag requires LLM configuration. Set LLM_PROVIDER (ollama/anthropic/openai) and appropriate API keys in environment or config.yml");
529
529
  }
530
530
  if (session.limits.currentLLMCalls >= session.limits.maxLLMCalls) {
531
531
  throw new Error("Maximum LLM calls exceeded");
@@ -573,7 +573,7 @@ async function executeLLM(session, element) {
573
573
  console.error("[LLM] Full prompt sent to LLM (noextra):\n" + prompt + "\n");
574
574
  }
575
575
  } else {
576
- const { getAvailableSubroutines } = await import("./session-4ZNNZ6R3.js");
576
+ const { getAvailableSubroutines } = await import("./session-QXKZY7G2.js");
577
577
  const subroutines = getAvailableSubroutines(session);
578
578
  if (session.debug) {
579
579
  console.error(
@@ -700,7 +700,7 @@ ${result}
700
700
  const parser = new DiracParser();
701
701
  let dynamicAST = parser.parse(diracCode);
702
702
  if (validateTags) {
703
- const { validateDiracCode, applyCorrectedTags } = await import("./tag-validator-HBCGQV6F.js");
703
+ const { validateDiracCode, applyCorrectedTags } = await import("./tag-validator-ANTK7UTG.js");
704
704
  let validation = await validateDiracCode(session, dynamicAST, { autocorrect });
705
705
  let retryCount = 0;
706
706
  while (!validation.valid && retryCount < maxRetries) {
@@ -1230,7 +1230,7 @@ async function getBestTagMatch(candidate, allowed) {
1230
1230
  return { tag: allowed[bestIdx], score: bestScore };
1231
1231
  }
1232
1232
  async function executeTagCheck(session, element) {
1233
- const { getAvailableSubroutines } = await import("./session-4ZNNZ6R3.js");
1233
+ const { getAvailableSubroutines } = await import("./session-QXKZY7G2.js");
1234
1234
  const subroutines = getAvailableSubroutines(session);
1235
1235
  const allowed = new Set(subroutines.map((s) => s.name));
1236
1236
  console.error("[tag-check] Allowed subroutines:", Array.from(allowed));
@@ -1323,7 +1323,7 @@ async function executeTagCheck(session, element) {
1323
1323
  const executeTag = correctedTag || tagName;
1324
1324
  console.error(`[tag-check] Executing <${executeTag}/> as all checks passed and execute=true.`);
1325
1325
  const elementToExecute = correctedTag ? { ...child, tag: correctedTag } : child;
1326
- const { integrate: integrate2 } = await import("./interpreter-MTIIHIIQ.js");
1326
+ const { integrate: integrate2 } = await import("./interpreter-Q6UF3RRU.js");
1327
1327
  await integrate2(session, elementToExecute);
1328
1328
  }
1329
1329
  }
@@ -1332,7 +1332,7 @@ async function executeTagCheck(session, element) {
1332
1332
  // src/tags/throw.ts
1333
1333
  async function executeThrow(session, element) {
1334
1334
  const exceptionName = element.attributes?.name || "exception";
1335
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-MTIIHIIQ.js");
1335
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-Q6UF3RRU.js");
1336
1336
  const exceptionDom = {
1337
1337
  tag: "exception-content",
1338
1338
  attributes: { name: exceptionName },
@@ -1345,7 +1345,7 @@ async function executeThrow(session, element) {
1345
1345
  // src/tags/try.ts
1346
1346
  async function executeTry(session, element) {
1347
1347
  setExceptionBoundary(session);
1348
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-MTIIHIIQ.js");
1348
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-Q6UF3RRU.js");
1349
1349
  await integrateChildren2(session, element);
1350
1350
  unsetExceptionBoundary(session);
1351
1351
  }
@@ -1355,7 +1355,7 @@ async function executeCatch(session, element) {
1355
1355
  const exceptionName = element.attributes?.name || "exception";
1356
1356
  const caughtCount = lookupException(session, exceptionName);
1357
1357
  if (caughtCount > 0) {
1358
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-MTIIHIIQ.js");
1358
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-Q6UF3RRU.js");
1359
1359
  await integrateChildren2(session, element);
1360
1360
  }
1361
1361
  flushCurrentException(session);
@@ -1364,7 +1364,7 @@ async function executeCatch(session, element) {
1364
1364
  // src/tags/exception.ts
1365
1365
  async function executeException(session, element) {
1366
1366
  const exceptions = getCurrentExceptions(session);
1367
- const { integrateChildren: integrateChildren2 } = await import("./interpreter-MTIIHIIQ.js");
1367
+ const { integrateChildren: integrateChildren2 } = await import("./interpreter-Q6UF3RRU.js");
1368
1368
  for (const exceptionDom of exceptions) {
1369
1369
  await integrateChildren2(session, exceptionDom);
1370
1370
  }
@@ -1504,7 +1504,7 @@ async function executeForeach(session, element) {
1504
1504
  const parser2 = new DiracParser2();
1505
1505
  try {
1506
1506
  const fromElement = parser2.parse(fromAttr);
1507
- const { integrate: integrate2 } = await import("./interpreter-MTIIHIIQ.js");
1507
+ const { integrate: integrate2 } = await import("./interpreter-Q6UF3RRU.js");
1508
1508
  await integrate2(session, fromElement);
1509
1509
  } catch (e) {
1510
1510
  session.output = savedOutput;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  registerSubroutine
3
- } from "./chunk-52ED23DR.js";
3
+ } from "./chunk-BSQV77YM.js";
4
4
 
5
5
  // src/tags/subroutine.ts
6
6
  function executeSubroutine(session, element) {
package/dist/cli.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  execute
4
- } from "./chunk-OUMUIBK3.js";
5
- import "./chunk-7OUYWIZV.js";
4
+ } from "./chunk-465O4WMH.js";
5
+ import "./chunk-EVNSAF33.js";
6
6
  import "./chunk-HRHAMPOB.js";
7
- import "./chunk-E7PWEMZA.js";
8
- import "./chunk-52ED23DR.js";
7
+ import "./chunk-LXF5PGUX.js";
8
+ import "./chunk-BSQV77YM.js";
9
9
 
10
10
  // src/cli.ts
11
11
  import "dotenv/config";
@@ -13,7 +13,7 @@ import "dotenv/config";
13
13
  // package.json
14
14
  var package_default = {
15
15
  name: "dirac-lang",
16
- version: "0.1.26",
16
+ version: "0.1.28",
17
17
  description: "LLM-Augmented Declarative Execution",
18
18
  type: "module",
19
19
  main: "dist/index.js",
@@ -22,16 +22,10 @@ var package_default = {
22
22
  dirac: "dist/cli.js"
23
23
  },
24
24
  exports: {
25
- ".": "./dist/index.js",
26
- "./lib": "./lib/index.di",
27
- "./lib/math": "./lib/math.di",
28
- "./lib/advanced-math": "./lib/advanced-math.di",
29
- "./lib/fileops": "./lib/fileops.di",
30
- "./lib/mongodb": "./lib/mongodb.di"
25
+ ".": "./dist/index.js"
31
26
  },
32
27
  files: [
33
- "dist/",
34
- "lib/"
28
+ "dist/"
35
29
  ],
36
30
  scripts: {
37
31
  dev: "tsx src/cli.ts",
package/dist/index.js CHANGED
@@ -2,19 +2,19 @@ import {
2
2
  createLLMAdapter,
3
3
  execute,
4
4
  executeUserCommand
5
- } from "./chunk-OUMUIBK3.js";
5
+ } from "./chunk-465O4WMH.js";
6
6
  import {
7
7
  integrate
8
- } from "./chunk-7OUYWIZV.js";
8
+ } from "./chunk-EVNSAF33.js";
9
9
  import {
10
10
  DiracParser
11
11
  } from "./chunk-HRHAMPOB.js";
12
- import "./chunk-E7PWEMZA.js";
12
+ import "./chunk-LXF5PGUX.js";
13
13
  import {
14
14
  createSession,
15
15
  getAvailableSubroutines,
16
16
  getOutput
17
- } from "./chunk-52ED23DR.js";
17
+ } from "./chunk-BSQV77YM.js";
18
18
  export {
19
19
  DiracParser,
20
20
  createLLMAdapter,
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  integrate,
3
3
  integrateChildren
4
- } from "./chunk-7OUYWIZV.js";
4
+ } from "./chunk-EVNSAF33.js";
5
5
  import "./chunk-HRHAMPOB.js";
6
- import "./chunk-E7PWEMZA.js";
7
- import "./chunk-52ED23DR.js";
6
+ import "./chunk-LXF5PGUX.js";
7
+ import "./chunk-BSQV77YM.js";
8
8
  export {
9
9
  integrate,
10
10
  integrateChildren
@@ -26,7 +26,7 @@ import {
26
26
  substituteVariables,
27
27
  throwException,
28
28
  unsetExceptionBoundary
29
- } from "./chunk-52ED23DR.js";
29
+ } from "./chunk-BSQV77YM.js";
30
30
  export {
31
31
  cleanSubroutinesToBoundary,
32
32
  cleanToBoundary,
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  executeSubroutine
3
- } from "./chunk-E7PWEMZA.js";
4
- import "./chunk-52ED23DR.js";
3
+ } from "./chunk-LXF5PGUX.js";
4
+ import "./chunk-BSQV77YM.js";
5
5
  export {
6
6
  executeSubroutine
7
7
  };
@@ -49,7 +49,7 @@ async function getBestTagMatch(candidate, allowed) {
49
49
  }
50
50
  async function validateTag(session, element, options = {}) {
51
51
  const { autocorrect = false, similarityCutoff = SIMILARITY_CUTOFF } = options;
52
- const { getAvailableSubroutines } = await import("./session-4ZNNZ6R3.js");
52
+ const { getAvailableSubroutines } = await import("./session-QXKZY7G2.js");
53
53
  const subroutines = getAvailableSubroutines(session);
54
54
  const allowed = new Set(subroutines.map((s) => s.name));
55
55
  const tagName = element.tag;
@@ -1,14 +1,14 @@
1
1
  import {
2
2
  integrate
3
- } from "./chunk-7OUYWIZV.js";
3
+ } from "./chunk-EVNSAF33.js";
4
4
  import {
5
5
  DiracParser
6
6
  } from "./chunk-HRHAMPOB.js";
7
- import "./chunk-E7PWEMZA.js";
7
+ import "./chunk-LXF5PGUX.js";
8
8
  import {
9
9
  createSession,
10
10
  getOutput
11
- } from "./chunk-52ED23DR.js";
11
+ } from "./chunk-BSQV77YM.js";
12
12
 
13
13
  // src/test-runner.ts
14
14
  import fs from "fs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dirac-lang",
3
- "version": "0.1.26",
3
+ "version": "0.1.28",
4
4
  "description": "LLM-Augmented Declarative Execution",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -9,16 +9,10 @@
9
9
  "dirac": "dist/cli.js"
10
10
  },
11
11
  "exports": {
12
- ".": "./dist/index.js",
13
- "./lib": "./lib/index.di",
14
- "./lib/math": "./lib/math.di",
15
- "./lib/advanced-math": "./lib/advanced-math.di",
16
- "./lib/fileops": "./lib/fileops.di",
17
- "./lib/mongodb": "./lib/mongodb.di"
12
+ ".": "./dist/index.js"
18
13
  },
19
14
  "files": [
20
- "dist/",
21
- "lib/"
15
+ "dist/"
22
16
  ],
23
17
  "scripts": {
24
18
  "dev": "tsx src/cli.ts",
@@ -1,81 +0,0 @@
1
- <dirac>
2
-
3
- <subroutine name="MATH_SQRT">
4
- <eval>
5
- const caller = getParams();
6
- const n = parseFloat(caller.attributes.n || 0);
7
- if (n &lt; 0) {
8
- console.log('NaN');
9
- return;
10
- }
11
- let x = n;
12
- let prev;
13
- do {
14
- prev = x;
15
- x = (x + n / x) / 2;
16
- } while (Math.abs(x - prev) &lt; 1e-10);
17
- console.log(x);
18
- </eval>
19
- </subroutine>
20
-
21
- <subroutine name="MATH_STATS">
22
- <eval>
23
- const caller = getParams();
24
- const dataStr = caller.attributes.data || '[]';
25
- const data = JSON.parse(dataStr);
26
- if (data.length === 0) { console.log('{}'); return; }
27
- const sum = data.reduce((a, b) =&gt; a + b, 0);
28
- const mean = sum / data.length;
29
- const variance = data.reduce((acc, x) =&gt; acc + Math.pow(x - mean, 2), 0) / data.length;
30
- const stddev = Math.sqrt(variance);
31
- const sorted = [...data].sort((a, b) =&gt; a - b);
32
- const median = data.length % 2 === 0 ? (sorted[data.length/2 - 1] + sorted[data.length/2]) / 2 : sorted[Math.floor(data.length/2)];
33
- const stats = { count: data.length, sum: sum, mean: mean, median: median, stddev: stddev, min: sorted[0], max: sorted[sorted.length - 1] };
34
- console.log(JSON.stringify(stats, null, 2));
35
- </eval>
36
- </subroutine>
37
-
38
- <subroutine name="MATH_RANDOM">
39
- <eval>
40
- const caller = getParams();
41
- const min = parseFloat(caller.attributes.min || 0);
42
- const max = parseFloat(caller.attributes.max || 1);
43
- const random = Math.random() * (max - min) + min;
44
- console.log(random);
45
- </eval>
46
- </subroutine>
47
-
48
- <subroutine name="MATH_FACTORIAL">
49
- <eval>
50
- const caller = getParams();
51
- const n = parseInt(caller.attributes.n || 0);
52
- function factorial(x) { if (x &lt;= 1) return 1; return x * factorial(x - 1); }
53
- console.log(factorial(n));
54
- </eval>
55
- </subroutine>
56
-
57
- <subroutine name="MATH_GCD">
58
- <eval>
59
- const caller = getParams();
60
- const a = parseInt(caller.attributes.a || 0);
61
- const b = parseInt(caller.attributes.b || 0);
62
- function gcd(x, y) { return y === 0 ? x : gcd(y, x % y); }
63
- console.log(gcd(Math.abs(a), Math.abs(b)));
64
- </eval>
65
- </subroutine>
66
-
67
- <subroutine name="MATH_PRIME">
68
- <eval>
69
- const caller = getParams();
70
- const n = parseInt(caller.attributes.n || 0);
71
- if (n &lt;= 1) { console.log(0); return; }
72
- if (n &lt;= 3) { console.log(1); return; }
73
- if (n % 2 === 0 || n % 3 === 0) { console.log(0); return; }
74
- for (let i = 5; i * i &lt;= n; i += 6) {
75
- if (n % i === 0 || n % (i + 2) === 0) { console.log(0); return; }
76
- }
77
- console.log(1);
78
- </eval>
79
- </subroutine>
80
-
81
- </dirac>
package/lib/fileops.di DELETED
@@ -1,26 +0,0 @@
1
- <!-- File operations library -->
2
- <dirac>
3
- <!-- List files in directory -->
4
- <subroutine name="LIST_FILES">
5
- <eval name="files">
6
- return fs.readdirSync(dir || '.').join(', ');
7
- </eval>
8
- <output>Files: ${files}&#10;</output>
9
- </subroutine>
10
-
11
- <!-- Count files in directory -->
12
- <subroutine name="COUNT_FILES">
13
- <eval name="count">
14
- return fs.readdirSync(dir || '.').length;
15
- </eval>
16
- <output>Count: ${count}&#10;</output>
17
- </subroutine>
18
-
19
- <!-- Check if file exists -->
20
- <subroutine name="FILE_EXISTS">
21
- <eval name="exists">
22
- return fs.existsSync(filepath) ? 'yes' : 'no';
23
- </eval>
24
- <output>Exists: ${exists}&#10;</output>
25
- </subroutine>
26
- </dirac>
package/lib/index.di DELETED
@@ -1,9 +0,0 @@
1
- <dirac>
2
- <!-- DIRAC Standard Library -->
3
- <!-- Import all standard library modules -->
4
-
5
- <import src="./math.di"/>
6
- <import src="./advanced-math.di"/>
7
- <import src="./fileops.di"/>
8
- <import src="./mongodb.di"/>
9
- </dirac>
package/lib/math.di DELETED
@@ -1,25 +0,0 @@
1
- <!-- Math utility library -->
2
- <dirac>
3
- <!-- Square a number -->
4
- <subroutine name="SQUARE" param-x="number">
5
- <eval name="result">return Number(x) * Number(x);</eval>
6
- <output><variable name="result" /></output>
7
- </subroutine>
8
-
9
- <!-- Add two numbers -->
10
- <subroutine name="ADD" param-a="number" param-b="number">
11
- <eval name="result">return Number(a) + Number(b);</eval>
12
- <output><variable name="result" /></output>
13
- </subroutine>
14
-
15
- <!-- Calculate factorial -->
16
- <subroutine name="FACTORIAL" param-num="number">
17
- <eval name="result">
18
- const n = parseInt(num, 10);
19
- let fact = 1;
20
- for (let i = 2; i &lt;= n; i++) fact *= i;
21
- return fact;
22
- </eval>
23
- <output><variable name="result" /></output>
24
- </subroutine>
25
- </dirac>
package/lib/mongodb.di DELETED
@@ -1,72 +0,0 @@
1
- <!-- MongoDB operations library for Dirac -->
2
- <dirac>
3
- <!-- General MongoDB subroutine: supports find, aggregate, insert, count -->
4
- <subroutine name="MONGODB"
5
- description="a tag to access mongodb"
6
- param-database="string:required:the database name::betting"
7
- param-collection="string:required:the collection name::events"
8
- param-action="string:required:the action need to take:find|aggregate|insert|count:find"
9
- meta-body="string:optional:the JSON query or document body for the action, required for find/aggregate/insert: {&quot;status&quot;&#58;&quot;active&quot;}"
10
- param-limit="number:optional:limit the number of records returned::10"
11
- >
12
- <!--
13
- <parameters select="@database" />
14
- <parameters select="@collection" />
15
- <parameters select="@action" />
16
- -->
17
- <defvar name="body"><parameters select="*"/></defvar>
18
-
19
- <require_module name="mongodb" var="mongo" />
20
-
21
-
22
-
23
-
24
-
25
- <eval name="result">
26
- { let output = body;
27
- const uri = process.env.MONGODB_URI || 'mongodb://localhost:27017';
28
-
29
- const query = body ? JSON.parse(body) : {};
30
- const client = new mongo.MongoClient(uri);
31
- const limitVal = typeof limit !== 'undefined' && limit !== '' ? parseInt(limit, 10) : undefined;
32
-
33
- try {
34
- await client.connect();
35
- const db = database ? client.db(database) : undefined;
36
- const col = db && collection ? db.collection(collection) : undefined;
37
-
38
- switch (action) {
39
- case 'find':
40
- let cursor = col.find(query);
41
- if (limitVal) cursor = cursor.limit(limitVal);
42
- output = await cursor.toArray();
43
- break;
44
- case 'count':
45
- output = await col.countDocuments(query);
46
- break;
47
- case 'aggregate':
48
- let aggCursor = col.aggregate(query);
49
- if (limitVal) aggCursor = aggCursor.limit(limitVal);
50
- output = await aggCursor.toArray();
51
- break;
52
- case 'insert':
53
- output = await col.insertOne(query);
54
- break;
55
- default:
56
- throw new Error('unknown action for MONGODB: ' + action);
57
- }
58
-
59
- } finally {
60
- await client.close();
61
- }
62
-
63
- return JSON.stringify(output, null, 2);
64
- }
65
- </eval>
66
-
67
-
68
-
69
-
70
- <output>${result}</output>
71
- </subroutine>
72
- </dirac>