@gringow/gringow 0.6.0 → 0.6.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 (44) hide show
  1. package/dist/browser.d.mts +1 -1
  2. package/dist/browser.mjs +22 -22
  3. package/dist/config.d.mts +30 -3
  4. package/dist/config.mjs +12 -22
  5. package/dist/constants/default-config.mjs +2 -2
  6. package/dist/create-cache-id.d.mts +2 -2
  7. package/dist/create-cache-id.mjs +22 -21
  8. package/dist/data/cache-file-path.d.mts +13 -0
  9. package/dist/data/cache-file-path.mjs +6 -0
  10. package/dist/data/cache-queue.d.mts +35 -0
  11. package/dist/data/cache-queue.mjs +372 -0
  12. package/dist/data/check-cache.d.mts +17 -8
  13. package/dist/data/check-cache.mjs +53 -87
  14. package/dist/data/clear-cache.mjs +32 -84
  15. package/dist/data/create-cache-dir.d.mts +3 -0
  16. package/dist/data/create-cache-dir.mjs +11 -71
  17. package/dist/data/delete-cache-item.d.mts +11 -8
  18. package/dist/data/delete-cache-item.mjs +51 -103
  19. package/dist/data/get-cache.d.mts +2 -1
  20. package/dist/data/get-cache.mjs +17 -72
  21. package/dist/data/get-or-create-cache.d.mts +16 -8
  22. package/dist/data/get-or-create-cache.mjs +54 -88
  23. package/dist/data/md5.d.mts +2 -5
  24. package/dist/data/md5.mjs +10 -10
  25. package/dist/data/save-cache.d.mts +2 -9
  26. package/dist/data/save-cache.mjs +32 -84
  27. package/dist/data/write-cache-to-disk.d.mts +12 -8
  28. package/dist/data/write-cache-to-disk.mjs +49 -100
  29. package/dist/gringow.d.mts +19 -8
  30. package/dist/gringow.mjs +116 -91
  31. package/dist/index.d.mts +6 -78
  32. package/dist/index.mjs +130 -99
  33. package/dist/interpolate-template.d.mts +7 -0
  34. package/dist/interpolate-template.mjs +11 -11
  35. package/dist/io/ask-llm.d.mts +1 -8
  36. package/dist/io/ask-llm.mjs +32 -78
  37. package/dist/logger.d.mts +18 -0
  38. package/dist/logger.mjs +18 -0
  39. package/dist/schemas/config.shcema.d.mts +5 -1
  40. package/dist/schemas/config.shcema.mjs +3 -3
  41. package/dist/strip-comments.d.mts +1 -9
  42. package/dist/strip-comments.mjs +0 -1
  43. package/dist/types/index.d.mts +22 -1
  44. package/package.json +8 -9
package/dist/index.d.mts CHANGED
@@ -1,87 +1,15 @@
1
1
  export { awaitedConfig, getConfigSource, isLocalConfigFound } from './config.mjs';
2
2
  export { createCacheId } from './create-cache-id.mjs';
3
+ export { checkCache } from './data/check-cache.mjs';
3
4
  export { clearCache } from './data/clear-cache.mjs';
5
+ export { deleteCacheItem } from './data/delete-cache-item.mjs';
4
6
  export { getCache } from './data/get-cache.mjs';
7
+ export { getOrCreateCache } from './data/get-or-create-cache.mjs';
8
+ export { writeCacheToDisk } from './data/write-cache-to-disk.mjs';
9
+ export { Gringow as default, rebuild } from './gringow.mjs';
5
10
  export { interpolateTemplate } from './interpolate-template.mjs';
6
11
  export { stripComments } from './strip-comments.mjs';
7
12
  export { GringowConfig } from './constants/default-config.mjs';
13
+ export { GringowCache, GringowCacheItem, GringowError, GringowResponse, GringowTranslation } from './types/index.mjs';
8
14
  import 'zod';
9
15
  import './schemas/config.shcema.mjs';
10
-
11
- /**
12
- * Checks if a cache item exists for the given ID
13
- *
14
- * @param cacheId - The cache ID to check
15
- * @returns Promise that resolves to the cached item if found, or undefined otherwise
16
- *
17
- * @example
18
- * const item = await checkCache("gid_123abc")
19
- * if (item) {
20
- * console.log("Found in cache:", item.translation)
21
- * }
22
- */
23
- declare function checkCache(cacheId: string): Promise<GringowCacheItem | undefined>;
24
-
25
- /**
26
- * Deletes a cache item.
27
- *
28
- * @param cacheId - The cache ID.
29
- * @returns The cache ID.
30
- */
31
- declare function deleteCacheItem(cacheId: string): Promise<GringowCache>;
32
-
33
- /**
34
- * Gets the existing cache or creates a new empty one if it doesn't exist
35
- *
36
- * @returns Promise that resolves to the cache object
37
- * @throws {GringowError} If there is an error reading/writing the cache file
38
- *
39
- * @example
40
- * const cache = await getOrCreateCache()
41
- * // Returns existing cache or creates new empty cache: {}
42
- */
43
- declare function getOrCreateCache(): Promise<GringowCache>;
44
-
45
- /**
46
- * Writes the cache to disk.
47
- *
48
- * @param cacheId - The cache ID.
49
- * @param cached - The cached item.
50
- * @returns The cached item.
51
- */
52
- declare function writeCacheToDisk(cacheId: string, cached: GringowCacheItem): Promise<GringowCacheItem>;
53
-
54
- type GringowTranslation = {
55
- [key: string]: string;
56
- };
57
- type GringowCacheItem = {
58
- original: string;
59
- translation: GringowTranslation;
60
- append?: string;
61
- prepend?: string;
62
- rebuild?: boolean;
63
- };
64
- type GringowCache = {
65
- [key: string]: GringowCacheItem;
66
- };
67
- type GringowResponse = {
68
- cacheId: string;
69
- translation: GringowCacheItem;
70
- };
71
- type GringowError = Error & {
72
- code?: string;
73
- cause?: Error;
74
- };
75
-
76
- declare function rebuild(cacheId: string): Promise<GringowResponse>;
77
- /**
78
- * Gringow is a function that translates a string or a template string into a
79
- * translated string.
80
- *
81
- * @param text - The string or template string to translate.
82
- * @param values - The values to interpolate into the string.
83
- * @returns The translated string.
84
- */
85
- declare function Gringow(text: string, ...values: Array<unknown>): Promise<GringowResponse>;
86
-
87
- export { type GringowCache, type GringowCacheItem, type GringowError, type GringowResponse, type GringowTranslation, checkCache, Gringow as default, deleteCacheItem, getOrCreateCache, rebuild, writeCacheToDisk };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { cosmiconfig } from 'cosmiconfig';
2
- import merge from 'lodash.merge';
2
+ import mergeWith from 'lodash.mergewith';
3
3
  import { z } from 'zod';
4
4
  import fs from 'fs/promises';
5
5
  import { dirname, resolve, parse } from 'path';
@@ -24,9 +24,9 @@ var defaultConfig = {
24
24
  defaultLanguage: "pt-BR",
25
25
  languages: ["pt-BR", "fr-CA"],
26
26
  llm: {
27
- provider: "openai",
27
+ provider: "ollama",
28
28
  apiKey: void 0,
29
- model: "gpt-4o-mini",
29
+ model: "llama3.2",
30
30
  temperature: 1,
31
31
  sleep: 0
32
32
  },
@@ -48,6 +48,7 @@ var llmProviderSchema = z.enum([
48
48
  "azure",
49
49
  "meta"
50
50
  ]);
51
+ var keylessProviders = ["ollama", "lmstudio"];
51
52
  var configSchema = z.object({
52
53
  debug: z.boolean().optional(),
53
54
  log: z.object({
@@ -79,8 +80,7 @@ var configSchema = z.object({
79
80
  globby: z.string().regex(/^\.\/.*/).optional()
80
81
  }).refine(
81
82
  (data) => {
82
- const noApiKeyRequired = ["ollama", "lmstudio"];
83
- if (noApiKeyRequired.includes(data.llm.provider)) {
83
+ if (keylessProviders.includes(data.llm.provider)) {
84
84
  return true;
85
85
  }
86
86
  return !!data.llm.apiKey;
@@ -100,21 +100,14 @@ function isLocalConfigFound() {
100
100
  function getConfigSource() {
101
101
  return result?.filepath || "default";
102
102
  }
103
+ function replaceArrays(_destination, source) {
104
+ if (Array.isArray(source)) return [...source];
105
+ return void 0;
106
+ }
103
107
  async function loadUserConfig() {
104
108
  try {
105
- const mergedConfig = merge({}, defaultConfig, result?.config);
106
- const parsedConfig = await configSchema.parseAsync(mergedConfig);
107
- parsedConfig.llm.prePrompt = prePrompt(
108
- parsedConfig,
109
- parsedConfig.llm.prePromptAppend ?? "",
110
- parsedConfig.llm.prePromptReplace ?? ""
111
- );
112
- parsedConfig.llm.postPrompt = postPrompt(
113
- parsedConfig,
114
- parsedConfig.llm.postPromptPrepend ?? "",
115
- parsedConfig.llm.postPromptReplace ?? ""
116
- );
117
- return parsedConfig;
109
+ const mergedConfig = mergeWith({}, defaultConfig, result?.config, replaceArrays);
110
+ return await configSchema.parseAsync(mergedConfig);
118
111
  } catch (error) {
119
112
  console.warn(`${error?.message}, using default configuration`);
120
113
  return defaultConfig;
@@ -163,10 +156,7 @@ function defaultPostPrompt(_config) {
163
156
  return "";
164
157
  }
165
158
  function prePrompt(config, prepend, replace) {
166
- return [
167
- // ...(append ? ['[SPECIFIC_INPUTS]', String(append), '[/SPECIFIC_INPUTS]'] : []),
168
- replace ? String(replace) : defaultPrePrompt(config, prepend)
169
- ].join(" ").trim();
159
+ return [replace ? String(replace) : defaultPrePrompt(config, prepend)].join(" ").trim();
170
160
  }
171
161
  function postPrompt(config, prepend, replace) {
172
162
  return [
@@ -181,19 +171,19 @@ var MULTIPLIERS = [668265261, 374761393, 2654435769, 2496678331];
181
171
  var AVA_MULT1 = 2146121005;
182
172
  var AVA_MULT2 = 2221713035;
183
173
  function seedState(input) {
184
- const state = [...INITIAL_STATE];
174
+ let [h1, h2, h3, h4] = INITIAL_STATE;
185
175
  for (const char of input) {
186
176
  const codePoint = char.codePointAt(0) ?? 0;
187
- for (let i = 0; i < state.length; i++) {
188
- state[i] = Math.imul(state[i] ^ codePoint, MULTIPLIERS[i]);
189
- state[i] = rotateLeft(state[i], (i + 1) * 3);
190
- }
191
- state[0] ^= state[3] >>> 11;
192
- state[1] ^= state[0] << 7;
193
- state[2] ^= state[1] >>> 13;
194
- state[3] ^= state[2] << 5;
177
+ h1 = rotateLeft(Math.imul(h1 ^ codePoint, MULTIPLIERS[0]), 3);
178
+ h2 = rotateLeft(Math.imul(h2 ^ codePoint, MULTIPLIERS[1]), 6);
179
+ h3 = rotateLeft(Math.imul(h3 ^ codePoint, MULTIPLIERS[2]), 9);
180
+ h4 = rotateLeft(Math.imul(h4 ^ codePoint, MULTIPLIERS[3]), 12);
181
+ h1 ^= h4 >>> 11;
182
+ h2 ^= h1 << 7;
183
+ h3 ^= h2 >>> 13;
184
+ h4 ^= h3 << 5;
195
185
  }
196
- return state;
186
+ return [h1, h2, h3, h4];
197
187
  }
198
188
  function rotateLeft(value, shift) {
199
189
  return value << shift | value >>> 32 - shift;
@@ -222,23 +212,23 @@ function md5(input) {
222
212
  }
223
213
 
224
214
  // src/interpolate-template.ts
215
+ function formatValue(value, index) {
216
+ return value === null || value === void 0 ? `\${${index}}` : String(value);
217
+ }
225
218
  function ifArray(template, givenValues) {
226
- const strings = [...template.raw];
227
- const hasValues = givenValues !== void 0;
228
- return strings.reduce((acc, item, index) => {
229
- acc += String(item ?? "");
230
- if (index < strings.length - 1) {
231
- acc += hasValues ? String(givenValues[index] ?? "") : `\${${index}}`;
232
- }
233
- return acc;
234
- }, "");
219
+ const strings = template.raw;
220
+ let output = String(strings[0] ?? "");
221
+ for (let index = 1; index < strings.length; index++) {
222
+ output += formatValue(givenValues?.[index - 1], index - 1);
223
+ output += String(strings[index] ?? "");
224
+ }
225
+ return output;
235
226
  }
236
227
  function ifString(template, givenValues) {
237
228
  if (template?.indexOf("${") === -1) return template;
238
229
  let valueIndex = 0;
239
230
  return template.replace(/\$\{[^}]*\}/g, () => {
240
- const value = givenValues?.[valueIndex];
241
- const output = value === null || value === void 0 ? `\${${valueIndex}}` : String(value);
231
+ const output = formatValue(givenValues?.[valueIndex], valueIndex);
242
232
  valueIndex++;
243
233
  return output;
244
234
  });
@@ -256,6 +246,11 @@ function createCacheId(text) {
256
246
  const cacheId = `gid_${hexHash}`;
257
247
  return cacheId;
258
248
  }
249
+
250
+ // src/data/cache-file-path.ts
251
+ function cacheFilePath(config) {
252
+ return `${config.cache.dir}/${config.cache.file}`;
253
+ }
259
254
  var optsArg = (opts) => {
260
255
  if (!opts) {
261
256
  opts = { mode: 511 };
@@ -467,32 +462,50 @@ async function createCacheDir() {
467
462
  const config = await awaitedConfig;
468
463
  await mkdirp(config.cache.dir);
469
464
  }
470
-
471
- // src/data/get-cache.ts
472
465
  async function getCache() {
466
+ const config = await awaitedConfig;
473
467
  try {
474
- const config = await awaitedConfig;
475
- await createCacheDir();
476
- const rawCache = await fs.readFile(`${config.cache.dir}/${config.cache.file}`);
468
+ const rawCache = await fs.readFile(cacheFilePath(config));
477
469
  return rawCache.toString();
478
470
  } catch (error) {
471
+ if (error?.code === "ENOENT") await createCacheDir();
479
472
  throw error;
480
473
  }
481
474
  }
482
- var savingQueue = Promise.resolve();
483
- async function saveCache(cache) {
475
+
476
+ // src/data/cache-queue.ts
477
+ var cacheQueue = Promise.resolve();
478
+ function enqueueCacheTask(task) {
479
+ const run = cacheQueue.then(task);
480
+ cacheQueue = run.catch(() => void 0);
481
+ return run;
482
+ }
483
+ async function writeCacheFile(cache) {
484
+ const config = await awaitedConfig;
485
+ await createCacheDir();
486
+ const contents = JSON.stringify(cache, null, 2);
487
+ await fs.writeFile(cacheFilePath(config), contents);
488
+ }
489
+ async function parseCacheOrEmpty(rawCache) {
490
+ if (!rawCache) return {};
484
491
  try {
485
- savingQueue = savingQueue.then(async () => {
486
- const config = await awaitedConfig;
487
- await createCacheDir();
488
- const contents = JSON.stringify(cache, null, 2);
489
- await fs.writeFile(`${config.cache.dir}/${config.cache.file}`, contents);
490
- });
491
- await savingQueue;
492
- return cache;
492
+ return JSON.parse(rawCache);
493
493
  } catch (error) {
494
+ if (!(error instanceof SyntaxError)) throw error;
495
+ const config = await awaitedConfig;
496
+ console.warn(`Gringow cache ${cacheFilePath(config)} has invalid JSON (${error.message}), recreating it as {}`);
497
+ return {};
498
+ }
499
+ }
500
+ async function readCacheOrEmpty() {
501
+ let rawCache;
502
+ try {
503
+ rawCache = await getCache();
504
+ } catch (error) {
505
+ if (error?.code === "ENOENT") return {};
494
506
  throw error;
495
507
  }
508
+ return parseCacheOrEmpty(rawCache);
496
509
  }
497
510
 
498
511
  // src/data/get-or-create-cache.ts
@@ -502,13 +515,16 @@ async function getOrCreateCache() {
502
515
  rawCache = await getCache();
503
516
  } catch (error) {
504
517
  if (error?.code === "ENOENT") {
505
- await saveCache({});
506
- rawCache = await getCache();
518
+ return enqueueCacheTask(async () => {
519
+ const cache = await readCacheOrEmpty();
520
+ if (Object.keys(cache).length === 0) await writeCacheFile(cache);
521
+ return cache;
522
+ });
507
523
  } else {
508
524
  throw error;
509
525
  }
510
526
  }
511
- return rawCache ? JSON.parse(rawCache?.toString()) : {};
527
+ return parseCacheOrEmpty(rawCache);
512
528
  }
513
529
 
514
530
  // src/data/check-cache.ts
@@ -522,6 +538,12 @@ async function checkCache(cacheId) {
522
538
  return void 0;
523
539
  }
524
540
 
541
+ // src/data/save-cache.ts
542
+ async function saveCache(cache) {
543
+ await enqueueCacheTask(() => writeCacheFile(cache));
544
+ return cache;
545
+ }
546
+
525
547
  // src/data/clear-cache.ts
526
548
  async function clearCache() {
527
549
  await saveCache({});
@@ -529,21 +551,24 @@ async function clearCache() {
529
551
 
530
552
  // src/data/delete-cache-item.ts
531
553
  async function deleteCacheItem(cacheId) {
532
- const rawCache = await getOrCreateCache();
533
- const cache = rawCache;
534
- if (cache[cacheId]) {
535
- delete cache[cacheId];
536
- }
537
- await saveCache(cache);
538
- return cache;
554
+ return enqueueCacheTask(async () => {
555
+ const cache = await readCacheOrEmpty();
556
+ if (cache[cacheId]) {
557
+ delete cache[cacheId];
558
+ }
559
+ await writeCacheFile(cache);
560
+ return cache;
561
+ });
539
562
  }
540
563
 
541
564
  // src/data/write-cache-to-disk.ts
542
565
  async function writeCacheToDisk(cacheId, cached) {
543
- const cache = await getOrCreateCache();
544
- cache[cacheId] = cached;
545
- await saveCache(cache);
546
- return cache[cacheId];
566
+ return enqueueCacheTask(async () => {
567
+ const cache = await readCacheOrEmpty();
568
+ cache[cacheId] = cached;
569
+ await writeCacheFile(cache);
570
+ return cache[cacheId];
571
+ });
547
572
  }
548
573
  var providerEngineMap = {
549
574
  anthropic: "anthropic",
@@ -560,9 +585,23 @@ var providerEngineMap = {
560
585
  azure: "azure",
561
586
  meta: "meta"
562
587
  };
588
+ var cacheItemSchema = z.object({
589
+ original: z.string(),
590
+ translation: z.record(z.string(), z.string())
591
+ });
563
592
  function parseResponse(responseText) {
564
- const cleaned = responseText.replace(/```json/g, "").replace(/```/g, "").trim();
565
- const parsed = JSON.parse(cleaned);
593
+ const fenced = responseText.trim().match(/^```(?:json)?\s*([\s\S]*?)\s*```$/);
594
+ const cleaned = fenced ? fenced[1] : responseText.trim();
595
+ let parsed;
596
+ try {
597
+ parsed = JSON.parse(cleaned);
598
+ } catch (error) {
599
+ throw new Error(`Invalid LLM response: not valid JSON (${error.message})`, { cause: error });
600
+ }
601
+ const result2 = cacheItemSchema.safeParse(parsed);
602
+ if (!result2.success) {
603
+ throw new Error(`Invalid LLM response: ${result2.error.message}`, { cause: result2.error });
604
+ }
566
605
  return parsed;
567
606
  }
568
607
  async function askLLM(prompt, prePrompt2, postPrompt2) {
@@ -572,7 +611,7 @@ async function askLLM(prompt, prePrompt2, postPrompt2) {
572
611
  if (!engineName) {
573
612
  throw new Error(`Unknown LLM provider: ${provider}`);
574
613
  }
575
- if (!config.llm.apiKey) {
614
+ if (!config.llm.apiKey && !keylessProviders.includes(provider)) {
576
615
  throw new Error(`API key for ${provider} is not configured in llm.apiKey`);
577
616
  }
578
617
  if (config.llm.sleep && config.llm.sleep > 0) {
@@ -610,19 +649,20 @@ function getPrependAndAppend(config, cached) {
610
649
  cached?.prepend ?? config.llm.prePromptAppend ?? "",
611
650
  config.llm.prePromptReplace ?? ""
612
651
  );
613
- const append = postPrompt(config, cached?.append ?? config.llm.postPrompt ?? "", config.llm.postPromptReplace ?? "");
652
+ const append = postPrompt(
653
+ config,
654
+ cached?.append ?? config.llm.postPromptPrepend ?? "",
655
+ config.llm.postPromptReplace ?? ""
656
+ );
614
657
  return { prepend, append };
615
658
  }
616
- async function rebuild(cacheId) {
617
- const config = await awaitedConfig;
618
- const cached = await checkCache(cacheId);
619
- if (!cached) throw new Error("Cache item not found");
659
+ async function translateAndStore(config, cacheId, text, cached, label) {
620
660
  const { prepend, append } = getPrependAndAppend(config, cached);
621
661
  if (config.debug) {
622
- console.log(`rebuild::prepend ${cacheId}:`, { prepend });
623
- console.log(`rebuild::append ${cacheId}:`, { append });
662
+ console.log(`${label}::prepend ${cacheId}:`, { prepend });
663
+ console.log(`${label}::append ${cacheId}:`, { append });
624
664
  }
625
- const translation = await askLLM(cached.original, prepend, append);
665
+ const translation = await askLLM(text, prepend, append);
626
666
  const output = {
627
667
  ...translation,
628
668
  prepend: cached?.prepend ?? void 0,
@@ -633,6 +673,12 @@ async function rebuild(cacheId) {
633
673
  }
634
674
  return { cacheId, translation: output };
635
675
  }
676
+ async function rebuild(cacheId) {
677
+ const config = await awaitedConfig;
678
+ const cached = await checkCache(cacheId);
679
+ if (!cached) throw new Error("Cache item not found");
680
+ return translateAndStore(config, cacheId, cached.original, cached, "rebuild");
681
+ }
636
682
  async function Gringow(text, ...values) {
637
683
  const config = await awaitedConfig;
638
684
  const interpolated = interpolateTemplate(text.trim(), values);
@@ -641,21 +687,7 @@ async function Gringow(text, ...values) {
641
687
  if (cached !== void 0 && cached.original !== "undefined" && !cached.rebuild) {
642
688
  return { cacheId, translation: cached };
643
689
  }
644
- const { prepend, append } = getPrependAndAppend(config, cached);
645
- if (config.debug) {
646
- console.log(`asking::prepend ${cacheId}:`, { prepend });
647
- console.log(`asking::append ${cacheId}:`, { append });
648
- }
649
- const translation = await askLLM(interpolated, prepend, append);
650
- const output = {
651
- ...translation,
652
- prepend: cached?.prepend ?? void 0,
653
- append: cached?.append ?? void 0
654
- };
655
- if (config.cache.write) {
656
- await writeCacheToDisk(cacheId, output);
657
- }
658
- return { cacheId, translation: output };
690
+ return translateAndStore(config, cacheId, interpolated, cached, "asking");
659
691
  }
660
692
 
661
693
  // src/strip-comments.ts
@@ -740,7 +772,6 @@ function stripComments(code) {
740
772
  top.braceDepth--;
741
773
  out += ch;
742
774
  i++;
743
- if (top.braceDepth === 0) ;
744
775
  continue;
745
776
  }
746
777
  }
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Flattens a template string or TemplateStringsArray with its values.
3
+ *
4
+ * @param template - The template to flatten.
5
+ * @param givenValues - The values to interpolate.
6
+ * @returns The flattened string.
7
+ */
1
8
  declare function interpolateTemplate(template: TemplateStringsArray | string, givenValues?: unknown[]): string;
2
9
 
3
10
  export { interpolateTemplate };
@@ -1,21 +1,21 @@
1
1
  // src/interpolate-template.ts
2
+ function formatValue(value, index) {
3
+ return value === null || value === void 0 ? `\${${index}}` : String(value);
4
+ }
2
5
  function ifArray(template, givenValues) {
3
- const strings = [...template.raw];
4
- const hasValues = givenValues !== void 0;
5
- return strings.reduce((acc, item, index) => {
6
- acc += String(item ?? "");
7
- if (index < strings.length - 1) {
8
- acc += hasValues ? String(givenValues[index] ?? "") : `\${${index}}`;
9
- }
10
- return acc;
11
- }, "");
6
+ const strings = template.raw;
7
+ let output = String(strings[0] ?? "");
8
+ for (let index = 1; index < strings.length; index++) {
9
+ output += formatValue(givenValues?.[index - 1], index - 1);
10
+ output += String(strings[index] ?? "");
11
+ }
12
+ return output;
12
13
  }
13
14
  function ifString(template, givenValues) {
14
15
  if (template?.indexOf("${") === -1) return template;
15
16
  let valueIndex = 0;
16
17
  return template.replace(/\$\{[^}]*\}/g, () => {
17
- const value = givenValues?.[valueIndex];
18
- const output = value === null || value === void 0 ? `\${${valueIndex}}` : String(value);
18
+ const output = formatValue(givenValues?.[valueIndex], valueIndex);
19
19
  valueIndex++;
20
20
  return output;
21
21
  });
@@ -1,13 +1,6 @@
1
- import { GringowCacheItem } from '../index.mjs';
2
- import '../config.mjs';
3
- import '../constants/default-config.mjs';
1
+ import { GringowCacheItem } from '../types/index.mjs';
4
2
  import 'zod';
5
3
  import '../schemas/config.shcema.mjs';
6
- import '../create-cache-id.mjs';
7
- import '../data/clear-cache.mjs';
8
- import '../data/get-cache.mjs';
9
- import '../interpolate-template.mjs';
10
- import '../strip-comments.mjs';
11
4
 
12
5
  /**
13
6
  * Asks an LLM for a response using multi-llm-ts.