@promptbook/fake-llm 0.86.8 → 0.86.22

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/umd/index.umd.js CHANGED
@@ -16,128 +16,19 @@
16
16
  * @generated
17
17
  * @see https://github.com/webgptorg/book
18
18
  */
19
- var BOOK_LANGUAGE_VERSION = '1.0.0';
19
+ const BOOK_LANGUAGE_VERSION = '1.0.0';
20
20
  /**
21
21
  * The version of the Promptbook engine
22
22
  *
23
23
  * @generated
24
24
  * @see https://github.com/webgptorg/promptbook
25
25
  */
26
- var PROMPTBOOK_ENGINE_VERSION = '0.86.8';
26
+ const PROMPTBOOK_ENGINE_VERSION = '0.86.22';
27
27
  /**
28
28
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
29
29
  * Note: [💞] Ignore a discrepancy between file name and entity name
30
30
  */
31
31
 
32
- /*! *****************************************************************************
33
- Copyright (c) Microsoft Corporation.
34
-
35
- Permission to use, copy, modify, and/or distribute this software for any
36
- purpose with or without fee is hereby granted.
37
-
38
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
39
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
40
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
41
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
42
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
43
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
44
- PERFORMANCE OF THIS SOFTWARE.
45
- ***************************************************************************** */
46
- /* global Reflect, Promise */
47
-
48
- var extendStatics = function(d, b) {
49
- extendStatics = Object.setPrototypeOf ||
50
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
51
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
52
- return extendStatics(d, b);
53
- };
54
-
55
- function __extends(d, b) {
56
- if (typeof b !== "function" && b !== null)
57
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
58
- extendStatics(d, b);
59
- function __() { this.constructor = d; }
60
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
61
- }
62
-
63
- var __assign = function() {
64
- __assign = Object.assign || function __assign(t) {
65
- for (var s, i = 1, n = arguments.length; i < n; i++) {
66
- s = arguments[i];
67
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
68
- }
69
- return t;
70
- };
71
- return __assign.apply(this, arguments);
72
- };
73
-
74
- function __awaiter(thisArg, _arguments, P, generator) {
75
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
76
- return new (P || (P = Promise))(function (resolve, reject) {
77
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
78
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
79
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
80
- step((generator = generator.apply(thisArg, _arguments || [])).next());
81
- });
82
- }
83
-
84
- function __generator(thisArg, body) {
85
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
86
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
87
- function verb(n) { return function (v) { return step([n, v]); }; }
88
- function step(op) {
89
- if (f) throw new TypeError("Generator is already executing.");
90
- while (_) try {
91
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
92
- if (y = 0, t) op = [op[0] & 2, t.value];
93
- switch (op[0]) {
94
- case 0: case 1: t = op; break;
95
- case 4: _.label++; return { value: op[1], done: false };
96
- case 5: _.label++; y = op[1]; op = [0]; continue;
97
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
98
- default:
99
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
100
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
101
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
102
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
103
- if (t[2]) _.ops.pop();
104
- _.trys.pop(); continue;
105
- }
106
- op = body.call(thisArg, _);
107
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
108
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
109
- }
110
- }
111
-
112
- function __values(o) {
113
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
114
- if (m) return m.call(o);
115
- if (o && typeof o.length === "number") return {
116
- next: function () {
117
- if (o && i >= o.length) o = void 0;
118
- return { value: o && o[i++], done: !o };
119
- }
120
- };
121
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
122
- }
123
-
124
- function __read(o, n) {
125
- var m = typeof Symbol === "function" && o[Symbol.iterator];
126
- if (!m) return o;
127
- var i = m.call(o), r, ar = [], e;
128
- try {
129
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
130
- }
131
- catch (error) { e = { error: error }; }
132
- finally {
133
- try {
134
- if (r && !r.done && (m = i["return"])) m.call(i);
135
- }
136
- finally { if (e) throw e.error; }
137
- }
138
- return ar;
139
- }
140
-
141
32
  /**
142
33
  * Freezes the given object and all its nested objects recursively
143
34
  *
@@ -148,26 +39,15 @@
148
39
  * @public exported from `@promptbook/utils`
149
40
  */
150
41
  function $deepFreeze(objectValue) {
151
- var e_1, _a;
152
42
  if (Array.isArray(objectValue)) {
153
- return Object.freeze(objectValue.map(function (item) { return $deepFreeze(item); }));
154
- }
155
- var propertyNames = Object.getOwnPropertyNames(objectValue);
156
- try {
157
- for (var propertyNames_1 = __values(propertyNames), propertyNames_1_1 = propertyNames_1.next(); !propertyNames_1_1.done; propertyNames_1_1 = propertyNames_1.next()) {
158
- var propertyName = propertyNames_1_1.value;
159
- var value = objectValue[propertyName];
160
- if (value && typeof value === 'object') {
161
- $deepFreeze(value);
162
- }
163
- }
43
+ return Object.freeze(objectValue.map((item) => $deepFreeze(item)));
164
44
  }
165
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
166
- finally {
167
- try {
168
- if (propertyNames_1_1 && !propertyNames_1_1.done && (_a = propertyNames_1.return)) _a.call(propertyNames_1);
45
+ const propertyNames = Object.getOwnPropertyNames(objectValue);
46
+ for (const propertyName of propertyNames) {
47
+ const value = objectValue[propertyName];
48
+ if (value && typeof value === 'object') {
49
+ $deepFreeze(value);
169
50
  }
170
- finally { if (e_1) throw e_1.error; }
171
51
  }
172
52
  Object.freeze(objectValue);
173
53
  return objectValue;
@@ -181,7 +61,7 @@
181
61
  *
182
62
  * @public exported from `@promptbook/core`
183
63
  */
184
- var ZERO_USAGE = $deepFreeze({
64
+ const ZERO_USAGE = $deepFreeze({
185
65
  price: { value: 0 },
186
66
  input: {
187
67
  tokensCount: { value: 0 },
@@ -251,38 +131,38 @@
251
131
  *
252
132
  * @public exported from `@promptbook/core`
253
133
  */
254
- var NAME = "Promptbook";
134
+ const NAME = `Promptbook`;
255
135
  /**
256
136
  * Email of the responsible person
257
137
  *
258
138
  * @public exported from `@promptbook/core`
259
139
  */
260
- var ADMIN_EMAIL = 'pavol@ptbk.io';
140
+ const ADMIN_EMAIL = 'pavol@ptbk.io';
261
141
  /**
262
142
  * Name of the responsible person for the Promptbook on GitHub
263
143
  *
264
144
  * @public exported from `@promptbook/core`
265
145
  */
266
- var ADMIN_GITHUB_NAME = 'hejny';
146
+ const ADMIN_GITHUB_NAME = 'hejny';
267
147
  // <- TODO: [🧠] Better system for generator warnings - not always "code" and "by `@promptbook/cli`"
268
148
  /**
269
149
  * The maximum number of iterations for a loops
270
150
  *
271
151
  * @private within the repository - too low-level in comparison with other `MAX_...`
272
152
  */
273
- var LOOP_LIMIT = 1000;
153
+ const LOOP_LIMIT = 1000;
274
154
  /**
275
155
  * The maximum number of iterations for a loops which adds characters one by one
276
156
  *
277
157
  * @private within the repository - too low-level in comparison with other `MAX_...`
278
158
  */
279
- var CHARACTER_LOOP_LIMIT = 100000;
159
+ const CHARACTER_LOOP_LIMIT = 100000;
280
160
  /**
281
161
  * Strings to represent various values in the context of parameter values
282
162
  *
283
163
  * @public exported from `@promptbook/utils`
284
164
  */
285
- var VALUE_STRINGS = {
165
+ const VALUE_STRINGS = {
286
166
  empty: '(nothing; empty string)',
287
167
  null: '(no value; null)',
288
168
  undefined: '(unknown value; undefined)',
@@ -296,7 +176,7 @@
296
176
  *
297
177
  * @public exported from `@promptbook/utils`
298
178
  */
299
- var SMALL_NUMBER = 0.001;
179
+ const SMALL_NUMBER = 0.001;
300
180
  // <- TODO: [🧜‍♂️]
301
181
  /**
302
182
  * @@@
@@ -321,8 +201,11 @@
321
201
  * @public exported from `@promptbook/utils`
322
202
  */
323
203
  function orderJson(options) {
324
- var value = options.value, order = options.order;
325
- var orderedValue = __assign(__assign({}, (order === undefined ? {} : Object.fromEntries(order.map(function (key) { return [key, undefined]; })))), value);
204
+ const { value, order } = options;
205
+ const orderedValue = {
206
+ ...(order === undefined ? {} : Object.fromEntries(order.map((key) => [key, undefined]))),
207
+ ...value,
208
+ };
326
209
  return orderedValue;
327
210
  }
328
211
 
@@ -332,11 +215,37 @@
332
215
  * @private private within the repository
333
216
  */
334
217
  function getErrorReportUrl(error) {
335
- var report = {
336
- title: "\uD83D\uDC1C Error report from ".concat(NAME),
337
- body: spaceTrim__default["default"](function (block) { return "\n\n\n `".concat(error.name || 'Error', "` has occurred in the [").concat(NAME, "], please look into it @").concat(ADMIN_GITHUB_NAME, ".\n\n ```\n ").concat(block(error.message || '(no error message)'), "\n ```\n\n\n ## More info:\n\n - **Promptbook engine version:** ").concat(PROMPTBOOK_ENGINE_VERSION, "\n - **Book language version:** ").concat(BOOK_LANGUAGE_VERSION, "\n - **Time:** ").concat(new Date().toISOString(), "\n\n <details>\n <summary>Stack trace:</summary>\n\n ## Stack trace:\n\n ```stacktrace\n ").concat(block(error.stack || '(empty)'), "\n ```\n </details>\n\n "); }),
218
+ const report = {
219
+ title: `🐜 Error report from ${NAME}`,
220
+ body: spaceTrim__default["default"]((block) => `
221
+
222
+
223
+ \`${error.name || 'Error'}\` has occurred in the [${NAME}], please look into it @${ADMIN_GITHUB_NAME}.
224
+
225
+ \`\`\`
226
+ ${block(error.message || '(no error message)')}
227
+ \`\`\`
228
+
229
+
230
+ ## More info:
231
+
232
+ - **Promptbook engine version:** ${PROMPTBOOK_ENGINE_VERSION}
233
+ - **Book language version:** ${BOOK_LANGUAGE_VERSION}
234
+ - **Time:** ${new Date().toISOString()}
235
+
236
+ <details>
237
+ <summary>Stack trace:</summary>
238
+
239
+ ## Stack trace:
240
+
241
+ \`\`\`stacktrace
242
+ ${block(error.stack || '(empty)')}
243
+ \`\`\`
244
+ </details>
245
+
246
+ `),
338
247
  };
339
- var reportUrl = new URL("https://github.com/webgptorg/promptbook/issues/new");
248
+ const reportUrl = new URL(`https://github.com/webgptorg/promptbook/issues/new`);
340
249
  reportUrl.searchParams.set('labels', 'bug');
341
250
  reportUrl.searchParams.set('assignees', ADMIN_GITHUB_NAME);
342
251
  reportUrl.searchParams.set('title', report.title);
@@ -349,16 +258,24 @@
349
258
  *
350
259
  * @public exported from `@promptbook/core`
351
260
  */
352
- var UnexpectedError = /** @class */ (function (_super) {
353
- __extends(UnexpectedError, _super);
354
- function UnexpectedError(message) {
355
- var _this = _super.call(this, spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(message), "\n\n Note: This error should not happen.\n It's probbably a bug in the pipeline collection\n\n Please report issue:\n ").concat(block(getErrorReportUrl(new Error(message)).href), "\n\n Or contact us on ").concat(ADMIN_EMAIL, "\n\n "); })) || this;
356
- _this.name = 'UnexpectedError';
357
- Object.setPrototypeOf(_this, UnexpectedError.prototype);
358
- return _this;
261
+ class UnexpectedError extends Error {
262
+ constructor(message) {
263
+ super(spaceTrim.spaceTrim((block) => `
264
+ ${block(message)}
265
+
266
+ Note: This error should not happen.
267
+ It's probbably a bug in the pipeline collection
268
+
269
+ Please report issue:
270
+ ${block(getErrorReportUrl(new Error(message)).href)}
271
+
272
+ Or contact us on ${ADMIN_EMAIL}
273
+
274
+ `));
275
+ this.name = 'UnexpectedError';
276
+ Object.setPrototypeOf(this, UnexpectedError.prototype);
359
277
  }
360
- return UnexpectedError;
361
- }(Error));
278
+ }
362
279
 
363
280
  /**
364
281
  * Checks if the value is [🚉] serializable as JSON
@@ -381,10 +298,9 @@
381
298
  * @public exported from `@promptbook/utils`
382
299
  */
383
300
  function checkSerializableAsJson(options) {
384
- var e_1, _a;
385
- var value = options.value, name = options.name, message = options.message;
301
+ const { value, name, message } = options;
386
302
  if (value === undefined) {
387
- throw new UnexpectedError("".concat(name, " is undefined"));
303
+ throw new UnexpectedError(`${name} is undefined`);
388
304
  }
389
305
  else if (value === null) {
390
306
  return;
@@ -399,49 +315,54 @@
399
315
  return;
400
316
  }
401
317
  else if (typeof value === 'symbol') {
402
- throw new UnexpectedError("".concat(name, " is symbol"));
318
+ throw new UnexpectedError(`${name} is symbol`);
403
319
  }
404
320
  else if (typeof value === 'function') {
405
- throw new UnexpectedError("".concat(name, " is function"));
321
+ throw new UnexpectedError(`${name} is function`);
406
322
  }
407
323
  else if (typeof value === 'object' && Array.isArray(value)) {
408
- for (var i = 0; i < value.length; i++) {
409
- checkSerializableAsJson({ name: "".concat(name, "[").concat(i, "]"), value: value[i], message: message });
324
+ for (let i = 0; i < value.length; i++) {
325
+ checkSerializableAsJson({ name: `${name}[${i}]`, value: value[i], message });
410
326
  }
411
327
  }
412
328
  else if (typeof value === 'object') {
413
329
  if (value instanceof Date) {
414
- throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n `".concat(name, "` is Date\n\n Use `string_date_iso8601` instead\n\n Additional message for `").concat(name, "`:\n ").concat(block(message || '(nothing)'), "\n "); }));
330
+ throw new UnexpectedError(spaceTrim__default["default"]((block) => `
331
+ \`${name}\` is Date
332
+
333
+ Use \`string_date_iso8601\` instead
334
+
335
+ Additional message for \`${name}\`:
336
+ ${block(message || '(nothing)')}
337
+ `));
415
338
  }
416
339
  else if (value instanceof Map) {
417
- throw new UnexpectedError("".concat(name, " is Map"));
340
+ throw new UnexpectedError(`${name} is Map`);
418
341
  }
419
342
  else if (value instanceof Set) {
420
- throw new UnexpectedError("".concat(name, " is Set"));
343
+ throw new UnexpectedError(`${name} is Set`);
421
344
  }
422
345
  else if (value instanceof RegExp) {
423
- throw new UnexpectedError("".concat(name, " is RegExp"));
346
+ throw new UnexpectedError(`${name} is RegExp`);
424
347
  }
425
348
  else if (value instanceof Error) {
426
- throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n `".concat(name, "` is unserialized Error\n\n Use function `serializeError`\n\n Additional message for `").concat(name, "`:\n ").concat(block(message || '(nothing)'), "\n\n "); }));
349
+ throw new UnexpectedError(spaceTrim__default["default"]((block) => `
350
+ \`${name}\` is unserialized Error
351
+
352
+ Use function \`serializeError\`
353
+
354
+ Additional message for \`${name}\`:
355
+ ${block(message || '(nothing)')}
356
+
357
+ `));
427
358
  }
428
359
  else {
429
- try {
430
- for (var _b = __values(Object.entries(value)), _c = _b.next(); !_c.done; _c = _b.next()) {
431
- var _d = __read(_c.value, 2), subName = _d[0], subValue = _d[1];
432
- if (subValue === undefined) {
433
- // Note: undefined in object is serializable - it is just omited
434
- continue;
435
- }
436
- checkSerializableAsJson({ name: "".concat(name, ".").concat(subName), value: subValue, message: message });
360
+ for (const [subName, subValue] of Object.entries(value)) {
361
+ if (subValue === undefined) {
362
+ // Note: undefined in object is serializable - it is just omited
363
+ continue;
437
364
  }
438
- }
439
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
440
- finally {
441
- try {
442
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
443
- }
444
- finally { if (e_1) throw e_1.error; }
365
+ checkSerializableAsJson({ name: `${name}.${subName}`, value: subValue, message });
445
366
  }
446
367
  try {
447
368
  JSON.stringify(value); // <- TODO: [0]
@@ -450,7 +371,14 @@
450
371
  if (!(error instanceof Error)) {
451
372
  throw error;
452
373
  }
453
- throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n `".concat(name, "` is not serializable\n\n ").concat(block(error.stack || error.message), "\n\n Additional message for `").concat(name, "`:\n ").concat(block(message || '(nothing)'), "\n "); }));
374
+ throw new UnexpectedError(spaceTrim__default["default"]((block) => `
375
+ \`${name}\` is not serializable
376
+
377
+ ${block(error.stack || error.message)}
378
+
379
+ Additional message for \`${name}\`:
380
+ ${block(message || '(nothing)')}
381
+ `));
454
382
  }
455
383
  /*
456
384
  TODO: [0] Is there some more elegant way to check circular references?
@@ -475,7 +403,12 @@
475
403
  }
476
404
  }
477
405
  else {
478
- throw new UnexpectedError(spaceTrim__default["default"](function (block) { return "\n `".concat(name, "` is unknown type\n\n Additional message for `").concat(name, "`:\n ").concat(block(message || '(nothing)'), "\n "); }));
406
+ throw new UnexpectedError(spaceTrim__default["default"]((block) => `
407
+ \`${name}\` is unknown type
408
+
409
+ Additional message for \`${name}\`:
410
+ ${block(message || '(nothing)')}
411
+ `));
479
412
  }
480
413
  }
481
414
  /**
@@ -521,9 +454,9 @@
521
454
  * @public exported from `@promptbook/utils`
522
455
  */
523
456
  function exportJson(options) {
524
- var name = options.name, value = options.value, order = options.order, message = options.message;
525
- checkSerializableAsJson({ name: name, value: value, message: message });
526
- var orderedValue =
457
+ const { name, value, order, message } = options;
458
+ checkSerializableAsJson({ name, value, message });
459
+ const orderedValue =
527
460
  // TODO: Fix error "Type instantiation is excessively deep and possibly infinite."
528
461
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
529
462
  // @ts-ignore
@@ -546,19 +479,19 @@
546
479
  *
547
480
  * @private within the repository
548
481
  */
549
- var REPLACING_NONCE = 'ptbkauk42kV2dzao34faw7FudQUHYPtW';
482
+ const REPLACING_NONCE = 'ptbkauk42kV2dzao34faw7FudQUHYPtW';
550
483
  /**
551
484
  * @@@
552
485
  *
553
486
  * @private within the repository
554
487
  */
555
- var RESERVED_PARAMETER_MISSING_VALUE = 'MISSING-' + REPLACING_NONCE;
488
+ const RESERVED_PARAMETER_MISSING_VALUE = 'MISSING-' + REPLACING_NONCE;
556
489
  /**
557
490
  * @@@
558
491
  *
559
492
  * @private within the repository
560
493
  */
561
- var RESERVED_PARAMETER_RESTRICTED = 'RESTRICTED-' + REPLACING_NONCE;
494
+ const RESERVED_PARAMETER_RESTRICTED = 'RESTRICTED-' + REPLACING_NONCE;
562
495
  /**
563
496
  * The names of the parameters that are reserved for special purposes
564
497
  *
@@ -566,7 +499,7 @@
566
499
  */
567
500
  exportJson({
568
501
  name: 'RESERVED_PARAMETER_NAMES',
569
- message: "The names of the parameters that are reserved for special purposes",
502
+ message: `The names of the parameters that are reserved for special purposes`,
570
503
  value: [
571
504
  'content',
572
505
  'context',
@@ -588,32 +521,26 @@
588
521
  *
589
522
  * @public exported from `@promptbook/core`
590
523
  */
591
- var LimitReachedError = /** @class */ (function (_super) {
592
- __extends(LimitReachedError, _super);
593
- function LimitReachedError(message) {
594
- var _this = _super.call(this, message) || this;
595
- _this.name = 'LimitReachedError';
596
- Object.setPrototypeOf(_this, LimitReachedError.prototype);
597
- return _this;
524
+ class LimitReachedError extends Error {
525
+ constructor(message) {
526
+ super(message);
527
+ this.name = 'LimitReachedError';
528
+ Object.setPrototypeOf(this, LimitReachedError.prototype);
598
529
  }
599
- return LimitReachedError;
600
- }(Error));
530
+ }
601
531
 
602
532
  /**
603
533
  * This error indicates errors during the execution of the pipeline
604
534
  *
605
535
  * @public exported from `@promptbook/core`
606
536
  */
607
- var PipelineExecutionError = /** @class */ (function (_super) {
608
- __extends(PipelineExecutionError, _super);
609
- function PipelineExecutionError(message) {
610
- var _this = _super.call(this, message) || this;
611
- _this.name = 'PipelineExecutionError';
612
- Object.setPrototypeOf(_this, PipelineExecutionError.prototype);
613
- return _this;
537
+ class PipelineExecutionError extends Error {
538
+ constructor(message) {
539
+ super(message);
540
+ this.name = 'PipelineExecutionError';
541
+ Object.setPrototypeOf(this, PipelineExecutionError.prototype);
614
542
  }
615
- return PipelineExecutionError;
616
- }(Error));
543
+ }
617
544
 
618
545
  /**
619
546
  * Format either small or big number
@@ -633,9 +560,9 @@
633
560
  else if (value === -Infinity) {
634
561
  return VALUE_STRINGS.negativeInfinity;
635
562
  }
636
- for (var exponent = 0; exponent < 15; exponent++) {
637
- var factor = Math.pow(10, exponent);
638
- var valueRounded = Math.round(value * factor) / factor;
563
+ for (let exponent = 0; exponent < 15; exponent++) {
564
+ const factor = 10 ** exponent;
565
+ const valueRounded = Math.round(value * factor) / factor;
639
566
  if (Math.abs(value - valueRounded) / value < SMALL_NUMBER) {
640
567
  return valueRounded.toFixed(exponent);
641
568
  }
@@ -703,47 +630,38 @@
703
630
  * @public exported from `@promptbook/utils`
704
631
  */
705
632
  function templateParameters(template, parameters) {
706
- var e_1, _a;
707
- try {
708
- for (var _b = __values(Object.entries(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) {
709
- var _d = __read(_c.value, 2), parameterName = _d[0], parameterValue = _d[1];
710
- if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
711
- throw new UnexpectedError("Parameter `{".concat(parameterName, "}` has missing value"));
712
- }
713
- else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
714
- // TODO: [🍵]
715
- throw new UnexpectedError("Parameter `{".concat(parameterName, "}` is restricted to use"));
716
- }
633
+ for (const [parameterName, parameterValue] of Object.entries(parameters)) {
634
+ if (parameterValue === RESERVED_PARAMETER_MISSING_VALUE) {
635
+ throw new UnexpectedError(`Parameter \`{${parameterName}}\` has missing value`);
717
636
  }
718
- }
719
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
720
- finally {
721
- try {
722
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
637
+ else if (parameterValue === RESERVED_PARAMETER_RESTRICTED) {
638
+ // TODO: [🍵]
639
+ throw new UnexpectedError(`Parameter \`{${parameterName}}\` is restricted to use`);
723
640
  }
724
- finally { if (e_1) throw e_1.error; }
725
641
  }
726
- var replacedTemplates = template;
727
- var match;
728
- var loopLimit = LOOP_LIMIT;
729
- var _loop_1 = function () {
642
+ let replacedTemplates = template;
643
+ let match;
644
+ let loopLimit = LOOP_LIMIT;
645
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
646
+ .exec(replacedTemplates))) {
730
647
  if (loopLimit-- < 0) {
731
648
  throw new LimitReachedError('Loop limit reached during parameters replacement in `templateParameters`');
732
649
  }
733
- var precol = match.groups.precol;
734
- var parameterName = match.groups.parameterName;
650
+ const precol = match.groups.precol;
651
+ const parameterName = match.groups.parameterName;
735
652
  if (parameterName === '') {
736
- return "continue";
653
+ // Note: Skip empty placeholders. It's used to avoid confusion with JSON-like strings
654
+ continue;
737
655
  }
738
656
  if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
739
657
  throw new PipelineExecutionError('Parameter is already opened or not closed');
740
658
  }
741
659
  if (parameters[parameterName] === undefined) {
742
- throw new PipelineExecutionError("Parameter `{".concat(parameterName, "}` is not defined"));
660
+ throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
743
661
  }
744
- var parameterValue = parameters[parameterName];
662
+ let parameterValue = parameters[parameterName];
745
663
  if (parameterValue === undefined) {
746
- throw new PipelineExecutionError("Parameter `{".concat(parameterName, "}` is not defined"));
664
+ throw new PipelineExecutionError(`Parameter \`{${parameterName}}\` is not defined`);
747
665
  }
748
666
  parameterValue = valueToString(parameterValue);
749
667
  // Escape curly braces in parameter values to prevent prompt-injection
@@ -751,17 +669,13 @@
751
669
  if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
752
670
  parameterValue = parameterValue
753
671
  .split('\n')
754
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
672
+ .map((line, index) => (index === 0 ? line : `${precol}${line}`))
755
673
  .join('\n');
756
674
  }
757
675
  replacedTemplates =
758
676
  replacedTemplates.substring(0, match.index + precol.length) +
759
677
  parameterValue +
760
678
  replacedTemplates.substring(match.index + precol.length + parameterName.length + 2);
761
- };
762
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
763
- .exec(replacedTemplates))) {
764
- _loop_1();
765
679
  }
766
680
  // [💫] Check if there are parameters that are not closed properly
767
681
  if (/{\w+$/.test(replacedTemplates)) {
@@ -779,33 +693,24 @@
779
693
  *
780
694
  * @public exported from `@promptbook/fake-llm`
781
695
  */
782
- var MockedEchoLlmExecutionTools = /** @class */ (function () {
783
- function MockedEchoLlmExecutionTools(options) {
784
- if (options === void 0) { options = {}; }
696
+ class MockedEchoLlmExecutionTools {
697
+ constructor(options = {}) {
785
698
  this.options = options;
786
699
  }
787
- Object.defineProperty(MockedEchoLlmExecutionTools.prototype, "title", {
788
- get: function () {
789
- return 'Mocked echo';
790
- },
791
- enumerable: false,
792
- configurable: true
793
- });
794
- Object.defineProperty(MockedEchoLlmExecutionTools.prototype, "description", {
795
- get: function () {
796
- return 'What you say is whay you get - just for testing';
797
- },
798
- enumerable: false,
799
- configurable: true
800
- });
700
+ get title() {
701
+ return 'Mocked echo';
702
+ }
703
+ get description() {
704
+ return 'What you say is whay you get - just for testing';
705
+ }
801
706
  /**
802
707
  * Does nothing, just to implement the interface
803
708
  */
804
- MockedEchoLlmExecutionTools.prototype.checkConfiguration = function () { };
709
+ checkConfiguration() { }
805
710
  /**
806
711
  * List all available mocked-models that can be used
807
712
  */
808
- MockedEchoLlmExecutionTools.prototype.listModels = function () {
713
+ listModels() {
809
714
  return [
810
715
  {
811
716
  modelTitle: 'Echo chat',
@@ -819,83 +724,78 @@
819
724
  },
820
725
  // <- Note: [🤖]
821
726
  ];
822
- };
727
+ }
823
728
  /**
824
729
  * Mocks chat model
825
730
  */
826
- MockedEchoLlmExecutionTools.prototype.callChatModel = function (prompt) {
827
- return __awaiter(this, void 0, void 0, function () {
828
- var modelName, rawPromptContent, usage;
829
- return __generator(this, function (_a) {
830
- if (this.options.isVerbose) {
831
- console.info('💬 Mocked callChatModel call');
832
- }
833
- modelName = 'mocked-echo';
834
- rawPromptContent = templateParameters(prompt.content, __assign(__assign({}, prompt.parameters), { modelName: modelName }));
835
- usage = ZERO_USAGE;
836
- // <- TODO: [🧠] Compute here at least words, characters,... etc
837
- return [2 /*return*/, exportJson({
838
- name: 'promptResult',
839
- message: "Result of `MockedEchoLlmExecutionTools.callChatModel`",
840
- order: [],
841
- value: {
842
- content: spaceTrim.spaceTrim(function (block) { return "\n You said:\n ".concat(block(rawPromptContent), "\n "); }),
843
- modelName: modelName,
844
- timing: {
845
- start: $getCurrentDate(),
846
- complete: $getCurrentDate(),
847
- },
848
- usage: usage,
849
- rawPromptContent: rawPromptContent,
850
- rawRequest: null,
851
- rawResponse: {
852
- note: 'This is mocked echo',
853
- },
854
- // <- [🗯]
855
- },
856
- })];
857
- });
731
+ async callChatModel(prompt) {
732
+ if (this.options.isVerbose) {
733
+ console.info('💬 Mocked callChatModel call');
734
+ }
735
+ const modelName = 'mocked-echo';
736
+ const rawPromptContent = templateParameters(prompt.content, { ...prompt.parameters, modelName });
737
+ const usage = ZERO_USAGE;
738
+ // <- TODO: [🧠] Compute here at least words, characters,... etc
739
+ return exportJson({
740
+ name: 'promptResult',
741
+ message: `Result of \`MockedEchoLlmExecutionTools.callChatModel\``,
742
+ order: [],
743
+ value: {
744
+ content: spaceTrim.spaceTrim((block) => `
745
+ You said:
746
+ ${block(rawPromptContent)}
747
+ `),
748
+ modelName,
749
+ timing: {
750
+ start: $getCurrentDate(),
751
+ complete: $getCurrentDate(),
752
+ },
753
+ usage,
754
+ rawPromptContent,
755
+ rawRequest: null,
756
+ rawResponse: {
757
+ note: 'This is mocked echo',
758
+ },
759
+ // <- [🗯]
760
+ },
858
761
  });
859
- };
762
+ }
860
763
  /**
861
764
  * Mocks completion model
862
765
  */
863
- MockedEchoLlmExecutionTools.prototype.callCompletionModel = function (prompt) {
864
- return __awaiter(this, void 0, void 0, function () {
865
- var modelName, rawPromptContent, usage;
866
- return __generator(this, function (_a) {
867
- if (this.options.isVerbose) {
868
- console.info('🖋 Mocked callCompletionModel call');
869
- }
870
- modelName = 'mocked-echo';
871
- rawPromptContent = templateParameters(prompt.content, __assign(__assign({}, prompt.parameters), { modelName: modelName }));
872
- usage = ZERO_USAGE;
873
- // <- TODO: [🧠] Compute here at least words, characters,... etc
874
- return [2 /*return*/, exportJson({
875
- name: 'promptResult',
876
- message: "Result of `MockedEchoLlmExecutionTools.callCompletionModel`",
877
- order: [],
878
- value: {
879
- content: spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(rawPromptContent), "\n And so on...\n "); }),
880
- modelName: modelName,
881
- timing: {
882
- start: $getCurrentDate(),
883
- complete: $getCurrentDate(),
884
- },
885
- usage: usage,
886
- rawPromptContent: rawPromptContent,
887
- rawRequest: null,
888
- rawResponse: {
889
- note: 'This is mocked echo',
890
- },
891
- // <- [🗯]
892
- },
893
- })];
894
- });
766
+ async callCompletionModel(prompt) {
767
+ if (this.options.isVerbose) {
768
+ console.info('🖋 Mocked callCompletionModel call');
769
+ }
770
+ const modelName = 'mocked-echo';
771
+ const rawPromptContent = templateParameters(prompt.content, { ...prompt.parameters, modelName });
772
+ const usage = ZERO_USAGE;
773
+ // <- TODO: [🧠] Compute here at least words, characters,... etc
774
+ return exportJson({
775
+ name: 'promptResult',
776
+ message: `Result of \`MockedEchoLlmExecutionTools.callCompletionModel\``,
777
+ order: [],
778
+ value: {
779
+ content: spaceTrim.spaceTrim((block) => `
780
+ ${block(rawPromptContent)}
781
+ And so on...
782
+ `),
783
+ modelName,
784
+ timing: {
785
+ start: $getCurrentDate(),
786
+ complete: $getCurrentDate(),
787
+ },
788
+ usage,
789
+ rawPromptContent,
790
+ rawRequest: null,
791
+ rawResponse: {
792
+ note: 'This is mocked echo',
793
+ },
794
+ // <- [🗯]
795
+ },
895
796
  });
896
- };
897
- return MockedEchoLlmExecutionTools;
898
- }());
797
+ }
798
+ }
899
799
  /**
900
800
  * TODO: [🧠][🈁] Maybe use `isDeterministic` from options
901
801
  * TODO: Allow in spaceTrim: nesting with > ${block(prompt.request)}, same as replace params
@@ -909,16 +809,13 @@
909
809
  * Note: Always thrown in `checkExpectations` and catched in `createPipelineExecutor` and rethrown as `PipelineExecutionError`
910
810
  * Note: This is a kindof subtype of PipelineExecutionError
911
811
  */
912
- var ExpectError = /** @class */ (function (_super) {
913
- __extends(ExpectError, _super);
914
- function ExpectError(message) {
915
- var _this = _super.call(this, message) || this;
916
- _this.name = 'ExpectError';
917
- Object.setPrototypeOf(_this, ExpectError.prototype);
918
- return _this;
812
+ class ExpectError extends Error {
813
+ constructor(message) {
814
+ super(message);
815
+ this.name = 'ExpectError';
816
+ Object.setPrototypeOf(this, ExpectError.prototype);
919
817
  }
920
- return ExpectError;
921
- }(Error));
818
+ }
922
819
 
923
820
  /**
924
821
  * Counts number of characters in the text
@@ -940,13 +837,13 @@
940
837
  *
941
838
  * @public exported from `@promptbook/utils`
942
839
  */
943
- var CHARACTERS_PER_STANDARD_LINE = 63;
840
+ const CHARACTERS_PER_STANDARD_LINE = 63;
944
841
  /**
945
842
  * Number of lines per standard A4 page with 11pt Arial font size and standard margins and spacing.
946
843
  *
947
844
  * @public exported from `@promptbook/utils`
948
845
  */
949
- var LINES_PER_STANDARD_PAGE = 44;
846
+ const LINES_PER_STANDARD_PAGE = 44;
950
847
  /**
951
848
  * TODO: [🧠] Should be this `constants.ts` or `config.ts`?
952
849
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -962,8 +859,8 @@
962
859
  function countLines(text) {
963
860
  text = text.replace('\r\n', '\n');
964
861
  text = text.replace('\r', '\n');
965
- var lines = text.split('\n');
966
- return lines.reduce(function (count, line) { return count + Math.ceil(line.length / CHARACTERS_PER_STANDARD_LINE); }, 0);
862
+ const lines = text.split('\n');
863
+ return lines.reduce((count, line) => count + Math.ceil(line.length / CHARACTERS_PER_STANDARD_LINE), 0);
967
864
  }
968
865
 
969
866
  /**
@@ -983,7 +880,7 @@
983
880
  * @public exported from `@promptbook/utils`
984
881
  */
985
882
  function countParagraphs(text) {
986
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
883
+ return text.split(/\n\s*\n/).filter((paragraph) => paragraph.trim() !== '').length;
987
884
  }
988
885
 
989
886
  /**
@@ -992,7 +889,7 @@
992
889
  * @public exported from `@promptbook/utils`
993
890
  */
994
891
  function splitIntoSentences(text) {
995
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
892
+ return text.split(/[.!?]+/).filter((sentence) => sentence.trim() !== '');
996
893
  }
997
894
  /**
998
895
  * Counts number of sentences in the text
@@ -1003,7 +900,7 @@
1003
900
  return splitIntoSentences(text).length;
1004
901
  }
1005
902
 
1006
- var defaultDiacriticsRemovalMap = [
903
+ const defaultDiacriticsRemovalMap = [
1007
904
  {
1008
905
  base: 'A',
1009
906
  letters: '\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F',
@@ -1222,12 +1119,12 @@
1222
1119
  *
1223
1120
  * @public exported from `@promptbook/utils`
1224
1121
  */
1225
- var DIACRITIC_VARIANTS_LETTERS = {};
1122
+ const DIACRITIC_VARIANTS_LETTERS = {};
1226
1123
  // tslint:disable-next-line: prefer-for-of
1227
- for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
1228
- var letters = defaultDiacriticsRemovalMap[i].letters;
1124
+ for (let i = 0; i < defaultDiacriticsRemovalMap.length; i++) {
1125
+ const letters = defaultDiacriticsRemovalMap[i].letters;
1229
1126
  // tslint:disable-next-line: prefer-for-of
1230
- for (var j = 0; j < letters.length; j++) {
1127
+ for (let j = 0; j < letters.length; j++) {
1231
1128
  DIACRITIC_VARIANTS_LETTERS[letters[j]] = defaultDiacriticsRemovalMap[i].base;
1232
1129
  }
1233
1130
  }
@@ -1256,7 +1153,7 @@
1256
1153
  */
1257
1154
  function removeDiacritics(input) {
1258
1155
  /*eslint no-control-regex: "off"*/
1259
- return input.replace(/[^\u0000-\u007E]/g, function (a) {
1156
+ return input.replace(/[^\u0000-\u007E]/g, (a) => {
1260
1157
  return DIACRITIC_VARIANTS_LETTERS[a] || a;
1261
1158
  });
1262
1159
  }
@@ -1272,7 +1169,9 @@
1272
1169
  function countWords(text) {
1273
1170
  text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
1274
1171
  text = removeDiacritics(text);
1275
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
1172
+ // Add spaces before uppercase letters preceded by lowercase letters (for camelCase)
1173
+ text = text.replace(/([a-z])([A-Z])/g, '$1 $2');
1174
+ return text.split(/[^a-zа-я0-9]+/i).filter((word) => word.length > 0).length;
1276
1175
  }
1277
1176
 
1278
1177
  /**
@@ -1280,7 +1179,7 @@
1280
1179
  *
1281
1180
  * @public exported from `@promptbook/utils`
1282
1181
  */
1283
- var CountUtils = {
1182
+ const CountUtils = {
1284
1183
  CHARACTERS: countCharacters,
1285
1184
  WORDS: countWords,
1286
1185
  SENTENCES: countSentences,
@@ -1305,25 +1204,14 @@
1305
1204
  * @private internal function of `createPipelineExecutor`
1306
1205
  */
1307
1206
  function checkExpectations(expectations, value) {
1308
- var e_1, _a;
1309
- try {
1310
- for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
1311
- var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
1312
- var amount = CountUtils[unit.toUpperCase()](value);
1313
- if (min && amount < min) {
1314
- throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
1315
- } /* not else */
1316
- if (max && amount > max) {
1317
- throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
1318
- }
1319
- }
1320
- }
1321
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1322
- finally {
1323
- try {
1324
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1207
+ for (const [unit, { max, min }] of Object.entries(expectations)) {
1208
+ const amount = CountUtils[unit.toUpperCase()](value);
1209
+ if (min && amount < min) {
1210
+ throw new ExpectError(`Expected at least ${min} ${unit} but got ${amount}`);
1211
+ } /* not else */
1212
+ if (max && amount > max) {
1213
+ throw new ExpectError(`Expected at most ${max} ${unit} but got ${amount}`);
1325
1214
  }
1326
- finally { if (e_1) throw e_1.error; }
1327
1215
  }
1328
1216
  }
1329
1217
  /**
@@ -1364,53 +1252,41 @@
1364
1252
  * @example 'iLovePromptbook'
1365
1253
  * @public exported from `@promptbook/utils`
1366
1254
  */
1367
- function normalizeTo_camelCase(text, _isFirstLetterCapital) {
1368
- var e_1, _a;
1369
- if (_isFirstLetterCapital === void 0) { _isFirstLetterCapital = false; }
1370
- var charType;
1371
- var lastCharType = null;
1372
- var normalizedName = '';
1373
- try {
1374
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
1375
- var char = text_1_1.value;
1376
- var normalizedChar = void 0;
1377
- if (/^[a-z]$/.test(char)) {
1378
- charType = 'LOWERCASE';
1379
- normalizedChar = char;
1380
- }
1381
- else if (/^[A-Z]$/.test(char)) {
1382
- charType = 'UPPERCASE';
1383
- normalizedChar = char.toLowerCase();
1384
- }
1385
- else if (/^[0-9]$/.test(char)) {
1386
- charType = 'NUMBER';
1387
- normalizedChar = char;
1388
- }
1389
- else {
1390
- charType = 'OTHER';
1391
- normalizedChar = '';
1392
- }
1393
- if (!lastCharType) {
1394
- if (_isFirstLetterCapital) {
1395
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1396
- }
1397
- }
1398
- else if (charType !== lastCharType &&
1399
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1400
- !(lastCharType === 'NUMBER') &&
1401
- !(charType === 'NUMBER')) {
1402
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
1255
+ function normalizeTo_camelCase(text, _isFirstLetterCapital = false) {
1256
+ let charType;
1257
+ let lastCharType = null;
1258
+ let normalizedName = '';
1259
+ for (const char of text) {
1260
+ let normalizedChar;
1261
+ if (/^[a-z]$/.test(char)) {
1262
+ charType = 'LOWERCASE';
1263
+ normalizedChar = char;
1264
+ }
1265
+ else if (/^[A-Z]$/.test(char)) {
1266
+ charType = 'UPPERCASE';
1267
+ normalizedChar = char.toLowerCase();
1268
+ }
1269
+ else if (/^[0-9]$/.test(char)) {
1270
+ charType = 'NUMBER';
1271
+ normalizedChar = char;
1272
+ }
1273
+ else {
1274
+ charType = 'OTHER';
1275
+ normalizedChar = '';
1276
+ }
1277
+ if (!lastCharType) {
1278
+ if (_isFirstLetterCapital) {
1279
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1403
1280
  }
1404
- normalizedName += normalizedChar;
1405
- lastCharType = charType;
1406
1281
  }
1407
- }
1408
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1409
- finally {
1410
- try {
1411
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
1282
+ else if (charType !== lastCharType &&
1283
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1284
+ !(lastCharType === 'NUMBER') &&
1285
+ !(charType === 'NUMBER')) {
1286
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
1412
1287
  }
1413
- finally { if (e_1) throw e_1.error; }
1288
+ normalizedName += normalizedChar;
1289
+ lastCharType = charType;
1414
1290
  }
1415
1291
  return normalizedName;
1416
1292
  }
@@ -1444,47 +1320,36 @@
1444
1320
  * @public exported from `@promptbook/utils`
1445
1321
  */
1446
1322
  function normalizeToKebabCase(text) {
1447
- var e_1, _a;
1448
1323
  text = removeDiacritics(text);
1449
- var charType;
1450
- var lastCharType = 'OTHER';
1451
- var normalizedName = '';
1452
- try {
1453
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
1454
- var char = text_1_1.value;
1455
- var normalizedChar = void 0;
1456
- if (/^[a-z]$/.test(char)) {
1457
- charType = 'LOWERCASE';
1458
- normalizedChar = char;
1459
- }
1460
- else if (/^[A-Z]$/.test(char)) {
1461
- charType = 'UPPERCASE';
1462
- normalizedChar = char.toLowerCase();
1463
- }
1464
- else if (/^[0-9]$/.test(char)) {
1465
- charType = 'NUMBER';
1466
- normalizedChar = char;
1467
- }
1468
- else {
1469
- charType = 'OTHER';
1470
- normalizedChar = '-';
1471
- }
1472
- if (charType !== lastCharType &&
1473
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1474
- !(lastCharType === 'NUMBER') &&
1475
- !(charType === 'NUMBER')) {
1476
- normalizedName += '-';
1477
- }
1478
- normalizedName += normalizedChar;
1479
- lastCharType = charType;
1324
+ let charType;
1325
+ let lastCharType = 'OTHER';
1326
+ let normalizedName = '';
1327
+ for (const char of text) {
1328
+ let normalizedChar;
1329
+ if (/^[a-z]$/.test(char)) {
1330
+ charType = 'LOWERCASE';
1331
+ normalizedChar = char;
1480
1332
  }
1481
- }
1482
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1483
- finally {
1484
- try {
1485
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
1333
+ else if (/^[A-Z]$/.test(char)) {
1334
+ charType = 'UPPERCASE';
1335
+ normalizedChar = char.toLowerCase();
1336
+ }
1337
+ else if (/^[0-9]$/.test(char)) {
1338
+ charType = 'NUMBER';
1339
+ normalizedChar = char;
1340
+ }
1341
+ else {
1342
+ charType = 'OTHER';
1343
+ normalizedChar = '-';
1344
+ }
1345
+ if (charType !== lastCharType &&
1346
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1347
+ !(lastCharType === 'NUMBER') &&
1348
+ !(charType === 'NUMBER')) {
1349
+ normalizedName += '-';
1486
1350
  }
1487
- finally { if (e_1) throw e_1.error; }
1351
+ normalizedName += normalizedChar;
1352
+ lastCharType = charType;
1488
1353
  }
1489
1354
  normalizedName = normalizedName.split(/-+/g).join('-');
1490
1355
  normalizedName = normalizedName.split(/-?\/-?/g).join('/');
@@ -1501,221 +1366,31 @@
1501
1366
  *
1502
1367
  * @public exported from `@promptbook/core`
1503
1368
  */
1504
- var ParseError = /** @class */ (function (_super) {
1505
- __extends(ParseError, _super);
1506
- function ParseError(message) {
1507
- var _this = _super.call(this, message) || this;
1508
- _this.name = 'ParseError';
1509
- Object.setPrototypeOf(_this, ParseError.prototype);
1510
- return _this;
1369
+ class ParseError extends Error {
1370
+ constructor(message) {
1371
+ super(message);
1372
+ this.name = 'ParseError';
1373
+ Object.setPrototypeOf(this, ParseError.prototype);
1511
1374
  }
1512
- return ParseError;
1513
- }(Error));
1375
+ }
1514
1376
  /**
1515
1377
  * TODO: Maybe split `ParseError` and `ApplyError`
1516
1378
  */
1517
1379
 
1518
- /**
1519
- * This error indicates problems parsing the format value
1520
- *
1521
- * For example, when the format value is not a valid JSON or CSV
1522
- * This is not thrown directly but in extended classes
1523
- *
1524
- * @public exported from `@promptbook/core`
1525
- */
1526
- var AbstractFormatError = /** @class */ (function (_super) {
1527
- __extends(AbstractFormatError, _super);
1528
- // Note: To allow instanceof do not put here error `name`
1529
- // public readonly name = 'AbstractFormatError';
1530
- function AbstractFormatError(message) {
1531
- var _this = _super.call(this, message) || this;
1532
- Object.setPrototypeOf(_this, AbstractFormatError.prototype);
1533
- return _this;
1534
- }
1535
- return AbstractFormatError;
1536
- }(Error));
1537
-
1538
- /**
1539
- * This error indicates problem with parsing of CSV
1540
- *
1541
- * @public exported from `@promptbook/core`
1542
- */
1543
- var CsvFormatError = /** @class */ (function (_super) {
1544
- __extends(CsvFormatError, _super);
1545
- function CsvFormatError(message) {
1546
- var _this = _super.call(this, message) || this;
1547
- _this.name = 'CsvFormatError';
1548
- Object.setPrototypeOf(_this, CsvFormatError.prototype);
1549
- return _this;
1550
- }
1551
- return CsvFormatError;
1552
- }(AbstractFormatError));
1553
-
1554
- /**
1555
- * This error indicates that the pipeline collection cannot be propperly loaded
1556
- *
1557
- * @public exported from `@promptbook/core`
1558
- */
1559
- var CollectionError = /** @class */ (function (_super) {
1560
- __extends(CollectionError, _super);
1561
- function CollectionError(message) {
1562
- var _this = _super.call(this, message) || this;
1563
- _this.name = 'CollectionError';
1564
- Object.setPrototypeOf(_this, CollectionError.prototype);
1565
- return _this;
1566
- }
1567
- return CollectionError;
1568
- }(Error));
1569
-
1570
- /**
1571
- * This error type indicates that you try to use a feature that is not available in the current environment
1572
- *
1573
- * @public exported from `@promptbook/core`
1574
- */
1575
- var EnvironmentMismatchError = /** @class */ (function (_super) {
1576
- __extends(EnvironmentMismatchError, _super);
1577
- function EnvironmentMismatchError(message) {
1578
- var _this = _super.call(this, message) || this;
1579
- _this.name = 'EnvironmentMismatchError';
1580
- Object.setPrototypeOf(_this, EnvironmentMismatchError.prototype);
1581
- return _this;
1582
- }
1583
- return EnvironmentMismatchError;
1584
- }(Error));
1585
-
1586
- /**
1587
- * This error indicates that the promptbook can not retrieve knowledge from external sources
1588
- *
1589
- * @public exported from `@promptbook/core`
1590
- */
1591
- var KnowledgeScrapeError = /** @class */ (function (_super) {
1592
- __extends(KnowledgeScrapeError, _super);
1593
- function KnowledgeScrapeError(message) {
1594
- var _this = _super.call(this, message) || this;
1595
- _this.name = 'KnowledgeScrapeError';
1596
- Object.setPrototypeOf(_this, KnowledgeScrapeError.prototype);
1597
- return _this;
1598
- }
1599
- return KnowledgeScrapeError;
1600
- }(Error));
1601
-
1602
- /**
1603
- * This error type indicates that some tools are missing for pipeline execution or preparation
1604
- *
1605
- * @public exported from `@promptbook/core`
1606
- */
1607
- var MissingToolsError = /** @class */ (function (_super) {
1608
- __extends(MissingToolsError, _super);
1609
- function MissingToolsError(message) {
1610
- var _this = _super.call(this, spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(message), "\n\n Note: You have probbably forgot to provide some tools for pipeline execution or preparation\n\n "); })) || this;
1611
- _this.name = 'MissingToolsError';
1612
- Object.setPrototypeOf(_this, MissingToolsError.prototype);
1613
- return _this;
1614
- }
1615
- return MissingToolsError;
1616
- }(Error));
1617
-
1618
- /**
1619
- * This error indicates that promptbook not found in the collection
1620
- *
1621
- * @public exported from `@promptbook/core`
1622
- */
1623
- var NotFoundError = /** @class */ (function (_super) {
1624
- __extends(NotFoundError, _super);
1625
- function NotFoundError(message) {
1626
- var _this = _super.call(this, message) || this;
1627
- _this.name = 'NotFoundError';
1628
- Object.setPrototypeOf(_this, NotFoundError.prototype);
1629
- return _this;
1630
- }
1631
- return NotFoundError;
1632
- }(Error));
1633
-
1634
- /**
1635
- * This error type indicates that some part of the code is not implemented yet
1636
- *
1637
- * @public exported from `@promptbook/core`
1638
- */
1639
- var NotYetImplementedError = /** @class */ (function (_super) {
1640
- __extends(NotYetImplementedError, _super);
1641
- function NotYetImplementedError(message) {
1642
- var _this = _super.call(this, spaceTrim.spaceTrim(function (block) { return "\n ".concat(block(message), "\n\n Note: This feature is not implemented yet but it will be soon.\n\n If you want speed up the implementation or just read more, look here:\n https://github.com/webgptorg/promptbook\n\n Or contact us on pavol@ptbk.io\n\n "); })) || this;
1643
- _this.name = 'NotYetImplementedError';
1644
- Object.setPrototypeOf(_this, NotYetImplementedError.prototype);
1645
- return _this;
1646
- }
1647
- return NotYetImplementedError;
1648
- }(Error));
1649
-
1650
- /**
1651
- * This error indicates that the promptbook object has valid syntax (=can be parsed) but contains logical errors (like circular dependencies)
1652
- *
1653
- * @public exported from `@promptbook/core`
1654
- */
1655
- var PipelineLogicError = /** @class */ (function (_super) {
1656
- __extends(PipelineLogicError, _super);
1657
- function PipelineLogicError(message) {
1658
- var _this = _super.call(this, message) || this;
1659
- _this.name = 'PipelineLogicError';
1660
- Object.setPrototypeOf(_this, PipelineLogicError.prototype);
1661
- return _this;
1662
- }
1663
- return PipelineLogicError;
1664
- }(Error));
1665
-
1666
- /**
1667
- * This error indicates errors in referencing promptbooks between each other
1668
- *
1669
- * @public exported from `@promptbook/core`
1670
- */
1671
- var PipelineUrlError = /** @class */ (function (_super) {
1672
- __extends(PipelineUrlError, _super);
1673
- function PipelineUrlError(message) {
1674
- var _this = _super.call(this, message) || this;
1675
- _this.name = 'PipelineUrlError';
1676
- Object.setPrototypeOf(_this, PipelineUrlError.prototype);
1677
- return _this;
1678
- }
1679
- return PipelineUrlError;
1680
- }(Error));
1681
-
1682
- /**
1683
- * Index of all custom errors
1684
- *
1685
- * @public exported from `@promptbook/core`
1686
- */
1687
- var PROMPTBOOK_ERRORS = {
1688
- AbstractFormatError: AbstractFormatError,
1689
- CsvFormatError: CsvFormatError,
1690
- CollectionError: CollectionError,
1691
- EnvironmentMismatchError: EnvironmentMismatchError,
1692
- ExpectError: ExpectError,
1693
- KnowledgeScrapeError: KnowledgeScrapeError,
1694
- LimitReachedError: LimitReachedError,
1695
- MissingToolsError: MissingToolsError,
1696
- NotFoundError: NotFoundError,
1697
- NotYetImplementedError: NotYetImplementedError,
1698
- ParseError: ParseError,
1699
- PipelineExecutionError: PipelineExecutionError,
1700
- PipelineLogicError: PipelineLogicError,
1701
- PipelineUrlError: PipelineUrlError,
1702
- UnexpectedError: UnexpectedError,
1703
- // TODO: [🪑]> VersionMismatchError,
1704
- };
1705
1380
  /**
1706
1381
  * Index of all javascript errors
1707
1382
  *
1708
1383
  * @private for internal usage
1709
1384
  */
1710
- var COMMON_JAVASCRIPT_ERRORS = {
1711
- Error: Error,
1712
- EvalError: EvalError,
1713
- RangeError: RangeError,
1714
- ReferenceError: ReferenceError,
1715
- SyntaxError: SyntaxError,
1716
- TypeError: TypeError,
1717
- URIError: URIError,
1718
- AggregateError: AggregateError,
1385
+ ({
1386
+ Error,
1387
+ EvalError,
1388
+ RangeError,
1389
+ ReferenceError,
1390
+ SyntaxError,
1391
+ TypeError,
1392
+ URIError,
1393
+ AggregateError,
1719
1394
  /*
1720
1395
  Note: Not widely supported
1721
1396
  > InternalError,
@@ -1724,13 +1399,7 @@
1724
1399
  > WebAssemblyCompileError,
1725
1400
  > WebAssemblyRuntimeError,
1726
1401
  */
1727
- };
1728
- /**
1729
- * Index of all errors
1730
- *
1731
- * @private for internal usage
1732
- */
1733
- __assign(__assign({}, PROMPTBOOK_ERRORS), COMMON_JAVASCRIPT_ERRORS);
1402
+ });
1734
1403
  /**
1735
1404
  * Note: [💞] Ignore a discrepancy between file name and entity name
1736
1405
  */
@@ -1742,7 +1411,13 @@
1742
1411
  *
1743
1412
  * @public exported from `@promptbook/utils`
1744
1413
  */
1745
- new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
1414
+ new Function(`
1415
+ try {
1416
+ return this === window;
1417
+ } catch (e) {
1418
+ return false;
1419
+ }
1420
+ `);
1746
1421
  /**
1747
1422
  * TODO: [🎺]
1748
1423
  */
@@ -1754,7 +1429,13 @@
1754
1429
  *
1755
1430
  * @public exported from `@promptbook/utils`
1756
1431
  */
1757
- new Function("\n try {\n return process.env.JEST_WORKER_ID !== undefined;\n } catch (e) {\n return false;\n }\n");
1432
+ new Function(`
1433
+ try {
1434
+ return process.env.JEST_WORKER_ID !== undefined;
1435
+ } catch (e) {
1436
+ return false;
1437
+ }
1438
+ `);
1758
1439
  /**
1759
1440
  * TODO: [🎺]
1760
1441
  */
@@ -1766,7 +1447,13 @@
1766
1447
  *
1767
1448
  * @public exported from `@promptbook/utils`
1768
1449
  */
1769
- new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
1450
+ new Function(`
1451
+ try {
1452
+ return this === global;
1453
+ } catch (e) {
1454
+ return false;
1455
+ }
1456
+ `);
1770
1457
  /**
1771
1458
  * TODO: [🎺]
1772
1459
  */
@@ -1778,7 +1465,17 @@
1778
1465
  *
1779
1466
  * @public exported from `@promptbook/utils`
1780
1467
  */
1781
- new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
1468
+ new Function(`
1469
+ try {
1470
+ if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
1471
+ return true;
1472
+ } else {
1473
+ return false;
1474
+ }
1475
+ } catch (e) {
1476
+ return false;
1477
+ }
1478
+ `);
1782
1479
  /**
1783
1480
  * TODO: [🎺]
1784
1481
  */
@@ -1811,46 +1508,35 @@
1811
1508
  * @public exported from `@promptbook/utils`
1812
1509
  */
1813
1510
  function normalizeTo_SCREAMING_CASE(text) {
1814
- var e_1, _a;
1815
- var charType;
1816
- var lastCharType = 'OTHER';
1817
- var normalizedName = '';
1818
- try {
1819
- for (var text_1 = __values(text), text_1_1 = text_1.next(); !text_1_1.done; text_1_1 = text_1.next()) {
1820
- var char = text_1_1.value;
1821
- var normalizedChar = void 0;
1822
- if (/^[a-z]$/.test(char)) {
1823
- charType = 'LOWERCASE';
1824
- normalizedChar = char.toUpperCase();
1825
- }
1826
- else if (/^[A-Z]$/.test(char)) {
1827
- charType = 'UPPERCASE';
1828
- normalizedChar = char;
1829
- }
1830
- else if (/^[0-9]$/.test(char)) {
1831
- charType = 'NUMBER';
1832
- normalizedChar = char;
1833
- }
1834
- else {
1835
- charType = 'OTHER';
1836
- normalizedChar = '_';
1837
- }
1838
- if (charType !== lastCharType &&
1839
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1840
- !(lastCharType === 'NUMBER') &&
1841
- !(charType === 'NUMBER')) {
1842
- normalizedName += '_';
1843
- }
1844
- normalizedName += normalizedChar;
1845
- lastCharType = charType;
1511
+ let charType;
1512
+ let lastCharType = 'OTHER';
1513
+ let normalizedName = '';
1514
+ for (const char of text) {
1515
+ let normalizedChar;
1516
+ if (/^[a-z]$/.test(char)) {
1517
+ charType = 'LOWERCASE';
1518
+ normalizedChar = char.toUpperCase();
1846
1519
  }
1847
- }
1848
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1849
- finally {
1850
- try {
1851
- if (text_1_1 && !text_1_1.done && (_a = text_1.return)) _a.call(text_1);
1520
+ else if (/^[A-Z]$/.test(char)) {
1521
+ charType = 'UPPERCASE';
1522
+ normalizedChar = char;
1523
+ }
1524
+ else if (/^[0-9]$/.test(char)) {
1525
+ charType = 'NUMBER';
1526
+ normalizedChar = char;
1527
+ }
1528
+ else {
1529
+ charType = 'OTHER';
1530
+ normalizedChar = '_';
1531
+ }
1532
+ if (charType !== lastCharType &&
1533
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1534
+ !(lastCharType === 'NUMBER') &&
1535
+ !(charType === 'NUMBER')) {
1536
+ normalizedName += '_';
1852
1537
  }
1853
- finally { if (e_1) throw e_1.error; }
1538
+ normalizedName += normalizedChar;
1539
+ lastCharType = charType;
1854
1540
  }
1855
1541
  normalizedName = normalizedName.replace(/_+/g, '_');
1856
1542
  normalizedName = normalizedName.replace(/_?\/_?/g, '/');
@@ -1875,10 +1561,10 @@
1875
1561
  * @public exported from `@promptbook/utils`
1876
1562
  */
1877
1563
  function parseKeywordsFromString(input) {
1878
- var keywords = normalizeTo_SCREAMING_CASE(removeDiacritics(input))
1564
+ const keywords = normalizeTo_SCREAMING_CASE(removeDiacritics(input))
1879
1565
  .toLowerCase()
1880
1566
  .split(/[^a-z0-9]+/gs)
1881
- .filter(function (value) { return value; });
1567
+ .filter((value) => value);
1882
1568
  return new Set(keywords);
1883
1569
  }
1884
1570
 
@@ -1891,7 +1577,7 @@
1891
1577
  * @public exported from `@promptbook/utils`
1892
1578
  */
1893
1579
  function nameToUriPart(name) {
1894
- var uriPart = name;
1580
+ let uriPart = name;
1895
1581
  uriPart = uriPart.toLowerCase();
1896
1582
  uriPart = removeDiacritics(uriPart);
1897
1583
  uriPart = uriPart.replace(/[^a-zA-Z0-9]+/g, '-');
@@ -1911,7 +1597,7 @@
1911
1597
  function nameToUriParts(name) {
1912
1598
  return nameToUriPart(name)
1913
1599
  .split('-')
1914
- .filter(function (value) { return value !== ''; });
1600
+ .filter((value) => value !== '');
1915
1601
  }
1916
1602
 
1917
1603
  /**
@@ -2019,15 +1705,15 @@
2019
1705
  * @public exported from `@promptbook/utils`
2020
1706
  */
2021
1707
  function unwrapResult(text, options) {
2022
- var _a = options || {}, _b = _a.isTrimmed, isTrimmed = _b === void 0 ? true : _b, _c = _a.isIntroduceSentenceRemoved, isIntroduceSentenceRemoved = _c === void 0 ? true : _c;
2023
- var trimmedText = text;
1708
+ const { isTrimmed = true, isIntroduceSentenceRemoved = true } = options || {};
1709
+ let trimmedText = text;
2024
1710
  // Remove leading and trailing spaces and newlines
2025
1711
  if (isTrimmed) {
2026
1712
  trimmedText = spaceTrim.spaceTrim(trimmedText);
2027
1713
  }
2028
- var processedText = trimmedText;
1714
+ let processedText = trimmedText;
2029
1715
  if (isIntroduceSentenceRemoved) {
2030
- var introduceSentenceRegex = /^[a-zěščřžýáíéúů:\s]*:\s*/i;
1716
+ const introduceSentenceRegex = /^[a-zěščřžýáíéúů:\s]*:\s*/i;
2031
1717
  if (introduceSentenceRegex.test(text)) {
2032
1718
  // Remove the introduce sentence and quotes by replacing it with an empty string
2033
1719
  processedText = processedText.replace(introduceSentenceRegex, '');
@@ -2041,7 +1727,7 @@
2041
1727
  return trimmedText;
2042
1728
  }
2043
1729
  // Remove the quotes by extracting the substring without the first and last characters
2044
- var unquotedText = processedText.slice(1, -1);
1730
+ const unquotedText = processedText.slice(1, -1);
2045
1731
  // Check if the text starts and ends with quotes
2046
1732
  if ([
2047
1733
  ['"', '"'],
@@ -2051,8 +1737,7 @@
2051
1737
  ['_', '_'],
2052
1738
  ['„', '“'],
2053
1739
  ['«', '»'] /* <- QUOTES to config */,
2054
- ].some(function (_a) {
2055
- var _b = __read(_a, 2), startQuote = _b[0], endQuote = _b[1];
1740
+ ].some(([startQuote, endQuote]) => {
2056
1741
  if (!processedText.startsWith(startQuote)) {
2057
1742
  return false;
2058
1743
  }
@@ -2092,61 +1777,50 @@
2092
1777
  * @public exported from `@promptbook/markdown-utils`
2093
1778
  */
2094
1779
  function extractAllBlocksFromMarkdown(markdown) {
2095
- var e_1, _a;
2096
- var codeBlocks = [];
2097
- var lines = markdown.split('\n');
1780
+ const codeBlocks = [];
1781
+ const lines = markdown.split('\n');
2098
1782
  // Note: [0] Ensure that the last block notated by gt > will be closed
2099
1783
  lines.push('');
2100
- var currentCodeBlock = null;
2101
- try {
2102
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2103
- var line = lines_1_1.value;
2104
- if (line.startsWith('> ') || line === '>') {
2105
- if (currentCodeBlock === null) {
2106
- currentCodeBlock = { blockNotation: '>', language: null, content: '' };
2107
- } /* not else */
2108
- if (currentCodeBlock.blockNotation === '>') {
2109
- if (currentCodeBlock.content !== '') {
2110
- currentCodeBlock.content += '\n';
2111
- }
2112
- currentCodeBlock.content += line.slice(2);
1784
+ let currentCodeBlock = null;
1785
+ for (const line of lines) {
1786
+ if (line.startsWith('> ') || line === '>') {
1787
+ if (currentCodeBlock === null) {
1788
+ currentCodeBlock = { blockNotation: '>', language: null, content: '' };
1789
+ } /* not else */
1790
+ if (currentCodeBlock.blockNotation === '>') {
1791
+ if (currentCodeBlock.content !== '') {
1792
+ currentCodeBlock.content += '\n';
2113
1793
  }
1794
+ currentCodeBlock.content += line.slice(2);
2114
1795
  }
2115
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
2116
- codeBlocks.push(currentCodeBlock);
2117
- currentCodeBlock = null;
2118
- }
2119
- /* not else */
2120
- if (line.startsWith('```')) {
2121
- var language = line.slice(3).trim() || null;
2122
- if (currentCodeBlock === null) {
2123
- currentCodeBlock = { blockNotation: '```', language: language, content: '' };
2124
- }
2125
- else {
2126
- if (language !== null) {
2127
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2128
- }
2129
- codeBlocks.push(currentCodeBlock);
2130
- currentCodeBlock = null;
2131
- }
1796
+ }
1797
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '>' /* <- Note: [0] */) {
1798
+ codeBlocks.push(currentCodeBlock);
1799
+ currentCodeBlock = null;
1800
+ }
1801
+ /* not else */
1802
+ if (line.startsWith('```')) {
1803
+ const language = line.slice(3).trim() || null;
1804
+ if (currentCodeBlock === null) {
1805
+ currentCodeBlock = { blockNotation: '```', language, content: '' };
2132
1806
  }
2133
- else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
2134
- if (currentCodeBlock.content !== '') {
2135
- currentCodeBlock.content += '\n';
1807
+ else {
1808
+ if (language !== null) {
1809
+ throw new ParseError(`${capitalize(currentCodeBlock.language || 'the')} code block was not closed and already opening new ${language} code block`);
2136
1810
  }
2137
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
1811
+ codeBlocks.push(currentCodeBlock);
1812
+ currentCodeBlock = null;
2138
1813
  }
2139
1814
  }
2140
- }
2141
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2142
- finally {
2143
- try {
2144
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
1815
+ else if (currentCodeBlock !== null && currentCodeBlock.blockNotation === '```') {
1816
+ if (currentCodeBlock.content !== '') {
1817
+ currentCodeBlock.content += '\n';
1818
+ }
1819
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2145
1820
  }
2146
- finally { if (e_1) throw e_1.error; }
2147
1821
  }
2148
1822
  if (currentCodeBlock !== null) {
2149
- throw new ParseError("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
1823
+ throw new ParseError(`${capitalize(currentCodeBlock.language || 'the')} code block was not closed at the end of the markdown`);
2150
1824
  }
2151
1825
  return codeBlocks;
2152
1826
  }
@@ -2171,9 +1845,13 @@
2171
1845
  * @throws {ParseError} if there is not exactly one code block in the markdown
2172
1846
  */
2173
1847
  function extractOneBlockFromMarkdown(markdown) {
2174
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
1848
+ const codeBlocks = extractAllBlocksFromMarkdown(markdown);
2175
1849
  if (codeBlocks.length !== 1) {
2176
- throw new ParseError(spaceTrim__default["default"](function (block) { return "\n There should be exactly 1 code block in task section, found ".concat(codeBlocks.length, " code blocks\n\n ").concat(block(codeBlocks.map(function (block, i) { return "Block ".concat(i + 1, ":\n").concat(block.content); }).join('\n\n\n')), "\n "); }));
1850
+ throw new ParseError(spaceTrim__default["default"]((block) => `
1851
+ There should be exactly 1 code block in task section, found ${codeBlocks.length} code blocks
1852
+
1853
+ ${block(codeBlocks.map((block, i) => `Block ${i + 1}:\n${block.content}`).join('\n\n\n'))}
1854
+ `));
2177
1855
  }
2178
1856
  return codeBlocks[0];
2179
1857
  }
@@ -2196,7 +1874,7 @@
2196
1874
  * @throws {ParseError} if there is not exactly one code block in the markdown
2197
1875
  */
2198
1876
  function extractBlock(markdown) {
2199
- var content = extractOneBlockFromMarkdown(markdown).content;
1877
+ const { content } = extractOneBlockFromMarkdown(markdown);
2200
1878
  return content;
2201
1879
  }
2202
1880
 
@@ -2227,7 +1905,7 @@
2227
1905
  catch (error) {
2228
1906
  // TODO: [🟥] Detect browser / node and make it colorfull
2229
1907
  console.error('There was an error with prettifying the markdown, using the original as the fallback', {
2230
- error: error,
1908
+ error,
2231
1909
  html: content,
2232
1910
  });
2233
1911
  return content;
@@ -2244,34 +1922,24 @@
2244
1922
  */
2245
1923
  function preserve(func) {
2246
1924
  // Note: NOT calling the function
2247
- var _this = this;
2248
- (function () { return __awaiter(_this, void 0, void 0, function () {
2249
- return __generator(this, function (_a) {
2250
- switch (_a.label) {
2251
- case 0:
2252
- // TODO: [💩] Change to `await forEver` or something better
2253
- return [4 /*yield*/, waitasecond.forTime(100000000)];
2254
- case 1:
2255
- // TODO: [💩] Change to `await forEver` or something better
2256
- _a.sent();
2257
- _a.label = 2;
2258
- case 2:
2259
- _a.trys.push([2, , 4, 5]);
2260
- return [4 /*yield*/, func()];
2261
- case 3:
2262
- _a.sent();
2263
- return [3 /*break*/, 5];
2264
- case 4: return [7 /*endfinally*/];
2265
- case 5: return [2 /*return*/];
2266
- }
2267
- });
2268
- }); })();
1925
+ (async () => {
1926
+ // TODO: [💩] Change to `await forEver` or something better
1927
+ await waitasecond.forTime(100000000);
1928
+ // [1]
1929
+ try {
1930
+ await func();
1931
+ }
1932
+ finally {
1933
+ // do nothing
1934
+ }
1935
+ })();
2269
1936
  }
2270
1937
  /**
2271
1938
  * TODO: Probbably remove in favour of `keepImported`
2272
1939
  * TODO: [1] This maybe does memory leak
2273
1940
  */
2274
1941
 
1942
+ // Note: [💎]
2275
1943
  /**
2276
1944
  * ScriptExecutionTools for JavaScript implemented via eval
2277
1945
  *
@@ -2280,163 +1948,191 @@
2280
1948
  *
2281
1949
  * @public exported from `@promptbook/execute-javascript`
2282
1950
  */
2283
- var JavascriptEvalExecutionTools = /** @class */ (function () {
2284
- function JavascriptEvalExecutionTools(options) {
1951
+ class JavascriptEvalExecutionTools {
1952
+ constructor(options) {
2285
1953
  this.options = options || {};
2286
1954
  }
2287
1955
  /**
2288
1956
  * Executes a JavaScript
2289
1957
  */
2290
- JavascriptEvalExecutionTools.prototype.execute = function (options) {
2291
- return __awaiter(this, void 0, void 0, function () {
2292
- var scriptLanguage, parameters, script, spaceTrim, removeQuotes$1, unwrapResult$1, trimEndOfCodeBlock$1, trimCodeBlock$1, trim, reverse, removeEmojis$1, prettifyMarkdown$1, capitalize$1, decapitalize$1, nameToUriPart$1, nameToUriParts$1, removeDiacritics$1, normalizeWhitespaces$1, normalizeToKebabCase$1, normalizeTo_camelCase$1, normalizeTo_snake_case$1, normalizeTo_PascalCase$1, parseKeywords, normalizeTo_SCREAMING_CASE$1, buildinFunctions, buildinFunctionsStatement, customFunctions, customFunctionsStatement, statementToEvaluate, result, error_1, undefinedName_1;
2293
- return __generator(this, function (_a) {
2294
- switch (_a.label) {
2295
- case 0:
2296
- scriptLanguage = options.scriptLanguage, parameters = options.parameters;
2297
- script = options.script;
2298
- if (scriptLanguage !== 'javascript') {
2299
- throw new PipelineExecutionError("Script language ".concat(scriptLanguage, " not supported to be executed by JavascriptEvalExecutionTools"));
2300
- }
2301
- spaceTrim = function (_) { return spaceTrim__default["default"](_); };
2302
- preserve(spaceTrim);
2303
- removeQuotes$1 = removeQuotes;
2304
- preserve(removeQuotes$1);
2305
- unwrapResult$1 = unwrapResult;
2306
- preserve(unwrapResult$1);
2307
- trimEndOfCodeBlock$1 = trimEndOfCodeBlock;
2308
- preserve(trimEndOfCodeBlock$1);
2309
- trimCodeBlock$1 = trimCodeBlock;
2310
- preserve(trimCodeBlock$1);
2311
- trim = function (str) { return str.trim(); };
2312
- preserve(trim);
2313
- reverse = function (str) { return str.split('').reverse().join(''); };
2314
- preserve(reverse);
2315
- removeEmojis$1 = removeEmojis;
2316
- preserve(removeEmojis$1);
2317
- prettifyMarkdown$1 = prettifyMarkdown;
2318
- preserve(prettifyMarkdown$1);
2319
- capitalize$1 = capitalize;
2320
- decapitalize$1 = decapitalize;
2321
- nameToUriPart$1 = nameToUriPart;
2322
- nameToUriParts$1 = nameToUriParts;
2323
- removeDiacritics$1 = removeDiacritics;
2324
- normalizeWhitespaces$1 = normalizeWhitespaces;
2325
- normalizeToKebabCase$1 = normalizeToKebabCase;
2326
- normalizeTo_camelCase$1 = normalizeTo_camelCase;
2327
- normalizeTo_snake_case$1 = normalizeTo_snake_case;
2328
- normalizeTo_PascalCase$1 = normalizeTo_PascalCase;
2329
- parseKeywords = function (input) {
2330
- // TODO: DRY [🍯]
2331
- return Array.from(parseKeywordsFromString(input)).join(', ');
2332
- };
2333
- normalizeTo_SCREAMING_CASE$1 = normalizeTo_SCREAMING_CASE;
2334
- preserve(capitalize$1);
2335
- preserve(decapitalize$1);
2336
- preserve(nameToUriPart$1);
2337
- preserve(nameToUriParts$1);
2338
- preserve(removeDiacritics$1);
2339
- preserve(normalizeWhitespaces$1);
2340
- preserve(normalizeToKebabCase$1);
2341
- preserve(normalizeTo_camelCase$1);
2342
- preserve(normalizeTo_snake_case$1);
2343
- preserve(normalizeTo_PascalCase$1);
2344
- preserve(parseKeywords);
2345
- preserve(normalizeTo_SCREAMING_CASE$1);
2346
- //-------[/n12]---
2347
- if (!script.includes('return')) {
2348
- script = "return ".concat(script);
2349
- }
2350
- buildinFunctions = {
2351
- // TODO: [🍯] DRY all these functions across the file
2352
- spaceTrim: spaceTrim,
2353
- removeQuotes: removeQuotes$1,
2354
- unwrapResult: unwrapResult$1,
2355
- trimEndOfCodeBlock: trimEndOfCodeBlock$1,
2356
- trimCodeBlock: trimCodeBlock$1,
2357
- trim: trim,
2358
- reverse: reverse,
2359
- removeEmojis: removeEmojis$1,
2360
- prettifyMarkdown: prettifyMarkdown$1,
2361
- capitalize: capitalize$1,
2362
- decapitalize: decapitalize$1,
2363
- nameToUriPart: nameToUriPart$1,
2364
- nameToUriParts: nameToUriParts$1,
2365
- removeDiacritics: removeDiacritics$1,
2366
- normalizeWhitespaces: normalizeWhitespaces$1,
2367
- normalizeToKebabCase: normalizeToKebabCase$1,
2368
- normalizeTo_camelCase: normalizeTo_camelCase$1,
2369
- normalizeTo_snake_case: normalizeTo_snake_case$1,
2370
- normalizeTo_PascalCase: normalizeTo_PascalCase$1,
2371
- parseKeywords: parseKeywords,
2372
- normalizeTo_SCREAMING_CASE: normalizeTo_SCREAMING_CASE$1,
2373
- extractBlock: extractBlock,
2374
- };
2375
- buildinFunctionsStatement = Object.keys(buildinFunctions)
2376
- .map(function (functionName) {
2377
- // Note: Custom functions are exposed to the current scope as variables
2378
- return "const ".concat(functionName, " = buildinFunctions.").concat(functionName, ";");
2379
- })
2380
- .join('\n');
2381
- customFunctions = this.options.functions || {};
2382
- customFunctionsStatement = Object.keys(customFunctions)
2383
- .map(function (functionName) {
2384
- // Note: Custom functions are exposed to the current scope as variables
2385
- return "const ".concat(functionName, " = customFunctions.").concat(functionName, ";");
2386
- })
2387
- .join('\n');
2388
- statementToEvaluate = spaceTrim__default["default"](function (block) { return "\n\n // Build-in functions:\n ".concat(block(buildinFunctionsStatement), "\n\n // Custom functions:\n ").concat(block(customFunctionsStatement || '// -- No custom functions --'), "\n\n // The script:\n ").concat(block(Object.entries(parameters)
2389
- .map(function (_a) {
2390
- var _b = __read(_a, 2), key = _b[0], value = _b[1];
2391
- return "const ".concat(key, " = ").concat(JSON.stringify(value), ";");
2392
- })
2393
- .join('\n')), "\n (()=>{ ").concat(script, " })()\n "); });
2394
- if (this.options.isVerbose) {
2395
- console.info(spaceTrim__default["default"](function (block) { return "\n \uD83D\uDE80 Evaluating ".concat(scriptLanguage, " script:\n\n ").concat(block(statementToEvaluate)); }));
2396
- }
2397
- _a.label = 1;
2398
- case 1:
2399
- _a.trys.push([1, 3, , 4]);
2400
- return [4 /*yield*/, eval(statementToEvaluate)];
2401
- case 2:
2402
- result = _a.sent();
2403
- if (typeof result !== 'string') {
2404
- throw new PipelineExecutionError("Script must return a string, but returned ".concat(valueToString(result)));
2405
- }
2406
- return [3 /*break*/, 4];
2407
- case 3:
2408
- error_1 = _a.sent();
2409
- if (!(error_1 instanceof Error)) {
2410
- throw error_1;
2411
- }
2412
- if (error_1 instanceof ReferenceError) {
2413
- undefinedName_1 = error_1.message.split(' ')[0];
2414
- /*
2415
- Note: Remapping error
2416
- From: [PipelineUrlError: thing is not defined],
2417
- To: [PipelineExecutionError: Parameter `{thing}` is not defined],
2418
- */
2419
- if (!statementToEvaluate.includes(undefinedName_1 + '(')) {
2420
- throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n\n Parameter `{".concat(undefinedName_1, "}` is not defined\n\n This happen during evaluation of the javascript, which has access to the following parameters as javascript variables:\n\n ").concat(block(Object.keys(parameters)
2421
- .map(function (key) { return " - ".concat(key, "\n"); })
2422
- .join('')), "\n\n The script is:\n ```javascript\n ").concat(block(script), "\n ```\n\n Original error message:\n ").concat(block(error_1.message), "\n\n\n "); }));
2423
- }
2424
- else {
2425
- throw new PipelineExecutionError(spaceTrim__default["default"](function (block) { return "\n Function ".concat(undefinedName_1, "() is not defined\n\n - Make sure that the function is one of built-in functions\n - Or you have to defined the function during construction of JavascriptEvalExecutionTools\n\n Original error message:\n ").concat(block(error_1.message), "\n\n "); }));
2426
- }
2427
- }
2428
- throw error_1;
2429
- case 4:
2430
- if (typeof result !== 'string') {
2431
- throw new PipelineExecutionError("Script must return a string, but ".concat(valueToString(result)));
2432
- }
2433
- return [2 /*return*/, result];
1958
+ async execute(options) {
1959
+ const { scriptLanguage, parameters } = options;
1960
+ let { script } = options;
1961
+ if (scriptLanguage !== 'javascript') {
1962
+ throw new PipelineExecutionError(`Script language ${scriptLanguage} not supported to be executed by JavascriptEvalExecutionTools`);
1963
+ }
1964
+ // Note: [💎]
1965
+ // Note: Using direct eval, following variables are in same scope as eval call so they are accessible from inside the evaluated script:
1966
+ const spaceTrim = (_) => spaceTrim__default["default"](_);
1967
+ preserve(spaceTrim);
1968
+ const removeQuotes$1 = removeQuotes;
1969
+ preserve(removeQuotes$1);
1970
+ const unwrapResult$1 = unwrapResult;
1971
+ preserve(unwrapResult$1);
1972
+ const trimEndOfCodeBlock$1 = trimEndOfCodeBlock;
1973
+ preserve(trimEndOfCodeBlock$1);
1974
+ const trimCodeBlock$1 = trimCodeBlock;
1975
+ preserve(trimCodeBlock$1);
1976
+ // TODO: DRY [🍯]
1977
+ const trim = (str) => str.trim();
1978
+ preserve(trim);
1979
+ // TODO: DRY [🍯]
1980
+ const reverse = (str) => str.split('').reverse().join('');
1981
+ preserve(reverse);
1982
+ const removeEmojis$1 = removeEmojis;
1983
+ preserve(removeEmojis$1);
1984
+ const prettifyMarkdown$1 = prettifyMarkdown;
1985
+ preserve(prettifyMarkdown$1);
1986
+ //-------[n12:]---
1987
+ const capitalize$1 = capitalize;
1988
+ const decapitalize$1 = decapitalize;
1989
+ const nameToUriPart$1 = nameToUriPart;
1990
+ const nameToUriParts$1 = nameToUriParts;
1991
+ const removeDiacritics$1 = removeDiacritics;
1992
+ const normalizeWhitespaces$1 = normalizeWhitespaces;
1993
+ const normalizeToKebabCase$1 = normalizeToKebabCase;
1994
+ const normalizeTo_camelCase$1 = normalizeTo_camelCase;
1995
+ const normalizeTo_snake_case$1 = normalizeTo_snake_case;
1996
+ const normalizeTo_PascalCase$1 = normalizeTo_PascalCase;
1997
+ const parseKeywords = (input) =>
1998
+ // TODO: DRY [🍯]
1999
+ Array.from(parseKeywordsFromString(input)).join(', '); /* <- TODO: [🧠] What is the best format comma list, bullet list,...? */
2000
+ const normalizeTo_SCREAMING_CASE$1 = normalizeTo_SCREAMING_CASE;
2001
+ preserve(capitalize$1);
2002
+ preserve(decapitalize$1);
2003
+ preserve(nameToUriPart$1);
2004
+ preserve(nameToUriParts$1);
2005
+ preserve(removeDiacritics$1);
2006
+ preserve(normalizeWhitespaces$1);
2007
+ preserve(normalizeToKebabCase$1);
2008
+ preserve(normalizeTo_camelCase$1);
2009
+ preserve(normalizeTo_snake_case$1);
2010
+ preserve(normalizeTo_PascalCase$1);
2011
+ preserve(parseKeywords);
2012
+ preserve(normalizeTo_SCREAMING_CASE$1);
2013
+ //-------[/n12]---
2014
+ if (!script.includes('return')) {
2015
+ script = `return ${script}`;
2016
+ }
2017
+ // TODO: DRY [🍯]
2018
+ const buildinFunctions = {
2019
+ // TODO: [🍯] DRY all these functions across the file
2020
+ spaceTrim,
2021
+ removeQuotes: removeQuotes$1,
2022
+ unwrapResult: unwrapResult$1,
2023
+ trimEndOfCodeBlock: trimEndOfCodeBlock$1,
2024
+ trimCodeBlock: trimCodeBlock$1,
2025
+ trim,
2026
+ reverse,
2027
+ removeEmojis: removeEmojis$1,
2028
+ prettifyMarkdown: prettifyMarkdown$1,
2029
+ capitalize: capitalize$1,
2030
+ decapitalize: decapitalize$1,
2031
+ nameToUriPart: nameToUriPart$1,
2032
+ nameToUriParts: nameToUriParts$1,
2033
+ removeDiacritics: removeDiacritics$1,
2034
+ normalizeWhitespaces: normalizeWhitespaces$1,
2035
+ normalizeToKebabCase: normalizeToKebabCase$1,
2036
+ normalizeTo_camelCase: normalizeTo_camelCase$1,
2037
+ normalizeTo_snake_case: normalizeTo_snake_case$1,
2038
+ normalizeTo_PascalCase: normalizeTo_PascalCase$1,
2039
+ parseKeywords,
2040
+ normalizeTo_SCREAMING_CASE: normalizeTo_SCREAMING_CASE$1,
2041
+ extractBlock, // <- [🍓] Remove balast in all other functions, use this one as example
2042
+ };
2043
+ const buildinFunctionsStatement = Object.keys(buildinFunctions)
2044
+ .map((functionName) =>
2045
+ // Note: Custom functions are exposed to the current scope as variables
2046
+ `const ${functionName} = buildinFunctions.${functionName};`)
2047
+ .join('\n');
2048
+ // TODO: DRY [🍯]
2049
+ const customFunctions = this.options.functions || {};
2050
+ const customFunctionsStatement = Object.keys(customFunctions)
2051
+ .map((functionName) =>
2052
+ // Note: Custom functions are exposed to the current scope as variables
2053
+ `const ${functionName} = customFunctions.${functionName};`)
2054
+ .join('\n');
2055
+ const statementToEvaluate = spaceTrim__default["default"]((block) => `
2056
+
2057
+ // Build-in functions:
2058
+ ${block(buildinFunctionsStatement)}
2059
+
2060
+ // Custom functions:
2061
+ ${block(customFunctionsStatement || '// -- No custom functions --')}
2062
+
2063
+ // The script:
2064
+ ${block(Object.entries(parameters)
2065
+ .map(([key, value]) => `const ${key} = ${JSON.stringify(value)};`)
2066
+ .join('\n'))}
2067
+ (()=>{ ${script} })()
2068
+ `);
2069
+ if (this.options.isVerbose) {
2070
+ console.info(spaceTrim__default["default"]((block) => `
2071
+ 🚀 Evaluating ${scriptLanguage} script:
2072
+
2073
+ ${block(statementToEvaluate)}`));
2074
+ }
2075
+ let result;
2076
+ try {
2077
+ result = await eval(statementToEvaluate);
2078
+ if (typeof result !== 'string') {
2079
+ throw new PipelineExecutionError(`Script must return a string, but returned ${valueToString(result)}`);
2080
+ }
2081
+ }
2082
+ catch (error) {
2083
+ if (!(error instanceof Error)) {
2084
+ throw error;
2085
+ }
2086
+ if (error instanceof ReferenceError) {
2087
+ const undefinedName = error.message.split(' ')[0];
2088
+ /*
2089
+ Note: Remapping error
2090
+ From: [PipelineUrlError: thing is not defined],
2091
+ To: [PipelineExecutionError: Parameter `{thing}` is not defined],
2092
+ */
2093
+ if (!statementToEvaluate.includes(undefinedName + '(')) {
2094
+ throw new PipelineExecutionError(spaceTrim__default["default"]((block) => `
2095
+
2096
+ Parameter \`{${undefinedName}}\` is not defined
2097
+
2098
+ This happen during evaluation of the javascript, which has access to the following parameters as javascript variables:
2099
+
2100
+ ${block(Object.keys(parameters)
2101
+ .map((key) => ` - ${key}\n`)
2102
+ .join(''))}
2103
+
2104
+ The script is:
2105
+ \`\`\`javascript
2106
+ ${block(script)}
2107
+ \`\`\`
2108
+
2109
+ Original error message:
2110
+ ${block(error.message)}
2111
+
2112
+
2113
+ `));
2434
2114
  }
2435
- });
2436
- });
2437
- };
2438
- return JavascriptEvalExecutionTools;
2439
- }());
2115
+ else {
2116
+ throw new PipelineExecutionError(spaceTrim__default["default"]((block) => `
2117
+ Function ${undefinedName}() is not defined
2118
+
2119
+ - Make sure that the function is one of built-in functions
2120
+ - Or you have to defined the function during construction of JavascriptEvalExecutionTools
2121
+
2122
+ Original error message:
2123
+ ${block(error.message)}
2124
+
2125
+ `));
2126
+ }
2127
+ }
2128
+ throw error;
2129
+ }
2130
+ if (typeof result !== 'string') {
2131
+ throw new PipelineExecutionError(`Script must return a string, but ${valueToString(result)}`);
2132
+ }
2133
+ return result;
2134
+ }
2135
+ }
2440
2136
  /**
2441
2137
  * TODO: Put predefined functions (like removeQuotes, spaceTrim, etc.) into annotation OR pass into constructor
2442
2138
  * TODO: [🧠][💙] Distinct between options passed into ExecutionTools and to ExecutionTools.execute
@@ -2448,7 +2144,7 @@
2448
2144
  * @alias JavascriptExecutionTools
2449
2145
  * @public exported from `@promptbook/execute-javascript`
2450
2146
  */
2451
- var JavascriptExecutionTools = JavascriptEvalExecutionTools;
2147
+ const JavascriptExecutionTools = JavascriptEvalExecutionTools;
2452
2148
 
2453
2149
  /**
2454
2150
  * Gets the expectations and creates a fake text that meets the expectations
@@ -2459,76 +2155,50 @@
2459
2155
  *
2460
2156
  * @private internal utility for MockedFackedLlmExecutionTools
2461
2157
  */
2462
- function $fakeTextToExpectations(expectations, postprocessingFunctionNames) {
2463
- return __awaiter(this, void 0, void 0, function () {
2464
- var lorem, loremText, text, loopLimit, textToCheck, scriptTools, _a, _b, postprocessingFunctionName, e_1_1;
2465
- var e_1, _c;
2466
- return __generator(this, function (_d) {
2467
- switch (_d.label) {
2468
- case 0:
2469
- lorem = new loremIpsum.LoremIpsum({
2470
- wordsPerSentence: { min: 5, max: 15 },
2471
- sentencesPerParagraph: { min: 5, max: 15 },
2472
- });
2473
- loremText = '';
2474
- text = '';
2475
- loopLimit = CHARACTER_LOOP_LIMIT;
2476
- _d.label = 1;
2477
- case 1:
2478
- if (!(loopLimit-- > 0)) return [3 /*break*/, 11];
2479
- textToCheck = text;
2480
- scriptTools = null;
2481
- _d.label = 2;
2482
- case 2:
2483
- _d.trys.push([2, 7, 8, 9]);
2484
- _a = (e_1 = void 0, __values(postprocessingFunctionNames || [])), _b = _a.next();
2485
- _d.label = 3;
2486
- case 3:
2487
- if (!!_b.done) return [3 /*break*/, 6];
2488
- postprocessingFunctionName = _b.value;
2489
- if (scriptTools === null) {
2490
- scriptTools = new JavascriptExecutionTools();
2491
- }
2492
- return [4 /*yield*/, scriptTools.execute({
2493
- scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
2494
- script: "".concat(postprocessingFunctionName, "(result)"),
2495
- parameters: {
2496
- result: textToCheck || '',
2497
- // Note: No ...parametersForTask, because working with result only
2498
- },
2499
- })];
2500
- case 4:
2501
- textToCheck = _d.sent();
2502
- _d.label = 5;
2503
- case 5:
2504
- _b = _a.next();
2505
- return [3 /*break*/, 3];
2506
- case 6: return [3 /*break*/, 9];
2507
- case 7:
2508
- e_1_1 = _d.sent();
2509
- e_1 = { error: e_1_1 };
2510
- return [3 /*break*/, 9];
2511
- case 8:
2512
- try {
2513
- if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
2514
- }
2515
- finally { if (e_1) throw e_1.error; }
2516
- return [7 /*endfinally*/];
2517
- case 9:
2518
- if (isPassingExpectations(expectations, textToCheck)) {
2519
- return [2 /*return*/, text]; // <- Note: Returning the text because the postprocessing
2520
- }
2521
- if (loremText === '') {
2522
- loremText = lorem.generateParagraphs(1) + '\n\n';
2523
- }
2524
- text += loremText.substring(0, 1);
2525
- loremText = loremText.substring(1);
2526
- _d.label = 10;
2527
- case 10: return [3 /*break*/, 1];
2528
- case 11: throw new LimitReachedError(spaceTrim.spaceTrim(function (block) { return "\n Can not generate fake text to met the expectations\n\n Loop limit reached\n The expectations:\n ".concat(block(JSON.stringify(expectations, null, 4)), "\n\n The draft text:\n ").concat(block(text), "\n\n "); }));
2529
- }
2530
- });
2158
+ async function $fakeTextToExpectations(expectations, postprocessingFunctionNames) {
2159
+ const lorem = new loremIpsum.LoremIpsum({
2160
+ wordsPerSentence: { min: 5, max: 15 },
2161
+ sentencesPerParagraph: { min: 5, max: 15 },
2531
2162
  });
2163
+ let loremText = '';
2164
+ let text = '';
2165
+ for (let loopLimit = CHARACTER_LOOP_LIMIT; loopLimit-- > 0;) {
2166
+ let textToCheck = text;
2167
+ // TODO: DRY [☯]
2168
+ let scriptTools = null;
2169
+ for (const postprocessingFunctionName of postprocessingFunctionNames || []) {
2170
+ if (scriptTools === null) {
2171
+ scriptTools = new JavascriptExecutionTools();
2172
+ }
2173
+ textToCheck = await scriptTools.execute({
2174
+ scriptLanguage: `javascript` /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
2175
+ script: `${postprocessingFunctionName}(result)`,
2176
+ parameters: {
2177
+ result: textToCheck || '',
2178
+ // Note: No ...parametersForTask, because working with result only
2179
+ },
2180
+ });
2181
+ }
2182
+ if (isPassingExpectations(expectations, textToCheck)) {
2183
+ return text; // <- Note: Returning the text because the postprocessing
2184
+ }
2185
+ if (loremText === '') {
2186
+ loremText = lorem.generateParagraphs(1) + '\n\n';
2187
+ }
2188
+ text += loremText.substring(0, 1);
2189
+ loremText = loremText.substring(1);
2190
+ }
2191
+ throw new LimitReachedError(spaceTrim.spaceTrim((block) => `
2192
+ Can not generate fake text to met the expectations
2193
+
2194
+ Loop limit reached
2195
+ The expectations:
2196
+ ${block(JSON.stringify(expectations, null, 4))}
2197
+
2198
+ The draft text:
2199
+ ${block(text)}
2200
+
2201
+ `));
2532
2202
  }
2533
2203
  /**
2534
2204
  * TODO: [💝] Unite object for expecting amount and format - use here also a format
@@ -2539,33 +2209,24 @@
2539
2209
  *
2540
2210
  * @public exported from `@promptbook/fake-llm`
2541
2211
  */
2542
- var MockedFackedLlmExecutionTools = /** @class */ (function () {
2543
- function MockedFackedLlmExecutionTools(options) {
2544
- if (options === void 0) { options = {}; }
2212
+ class MockedFackedLlmExecutionTools {
2213
+ constructor(options = {}) {
2545
2214
  this.options = options;
2546
2215
  }
2547
- Object.defineProperty(MockedFackedLlmExecutionTools.prototype, "title", {
2548
- get: function () {
2549
- return 'Mocked facked';
2550
- },
2551
- enumerable: false,
2552
- configurable: true
2553
- });
2554
- Object.defineProperty(MockedFackedLlmExecutionTools.prototype, "description", {
2555
- get: function () {
2556
- return 'Use faked lorem ipsum data - just for testing';
2557
- },
2558
- enumerable: false,
2559
- configurable: true
2560
- });
2216
+ get title() {
2217
+ return 'Mocked facked';
2218
+ }
2219
+ get description() {
2220
+ return 'Use faked lorem ipsum data - just for testing';
2221
+ }
2561
2222
  /**
2562
2223
  * Does nothing, just to implement the interface
2563
2224
  */
2564
- MockedFackedLlmExecutionTools.prototype.checkConfiguration = function () { };
2225
+ checkConfiguration() { }
2565
2226
  /**
2566
2227
  * List all available fake-models that can be used
2567
2228
  */
2568
- MockedFackedLlmExecutionTools.prototype.listModels = function () {
2229
+ listModels() {
2569
2230
  return [
2570
2231
  {
2571
2232
  modelTitle: 'Fake chat',
@@ -2579,107 +2240,90 @@
2579
2240
  },
2580
2241
  // <- Note: [🤖]
2581
2242
  ];
2582
- };
2243
+ }
2583
2244
  /**
2584
2245
  * Fakes chat model
2585
2246
  */
2586
- MockedFackedLlmExecutionTools.prototype.callChatModel = function (prompt) {
2587
- return __awaiter(this, void 0, void 0, function () {
2588
- var modelName, rawPromptContent, usage, content, result;
2589
- return __generator(this, function (_a) {
2590
- switch (_a.label) {
2591
- case 0:
2592
- if (this.options.isVerbose) {
2593
- console.info('💬 Mocked faked prompt', prompt);
2594
- }
2595
- modelName = 'mocked-facked';
2596
- rawPromptContent = templateParameters(prompt.content, __assign(__assign({}, prompt.parameters), { modelName: modelName }));
2597
- usage = ZERO_USAGE;
2598
- return [4 /*yield*/, $fakeTextToExpectations(prompt.expectations || {
2599
- sentences: { min: 1, max: 1 },
2600
- }, prompt.postprocessingFunctionNames)];
2601
- case 1:
2602
- content = _a.sent();
2603
- result = {
2604
- content: content,
2605
- modelName: modelName,
2606
- timing: {
2607
- start: $getCurrentDate(),
2608
- complete: $getCurrentDate(),
2609
- },
2610
- usage: usage,
2611
- rawPromptContent: rawPromptContent,
2612
- rawRequest: null,
2613
- rawResponse: {
2614
- note: 'This is mocked echo',
2615
- },
2616
- // <- [🗯]
2617
- };
2618
- if (this.options.isVerbose) {
2619
- console.info('💬 Mocked faked result', result);
2620
- }
2621
- return [2 /*return*/, exportJson({
2622
- name: 'promptResult',
2623
- message: "Result of `MockedFackedLlmExecutionTools.callChatModel`",
2624
- order: [],
2625
- value: result,
2626
- })];
2627
- }
2628
- });
2247
+ async callChatModel(prompt) {
2248
+ if (this.options.isVerbose) {
2249
+ console.info('💬 Mocked faked prompt', prompt);
2250
+ }
2251
+ const modelName = 'mocked-facked';
2252
+ const rawPromptContent = templateParameters(prompt.content, { ...prompt.parameters, modelName });
2253
+ const usage = ZERO_USAGE;
2254
+ // <- TODO: [🧠] Compute here at least words, characters,... etc
2255
+ const content = await $fakeTextToExpectations(prompt.expectations || {
2256
+ sentences: { min: 1, max: 1 },
2257
+ }, prompt.postprocessingFunctionNames);
2258
+ const result = {
2259
+ content,
2260
+ modelName,
2261
+ timing: {
2262
+ start: $getCurrentDate(),
2263
+ complete: $getCurrentDate(),
2264
+ },
2265
+ usage,
2266
+ rawPromptContent,
2267
+ rawRequest: null,
2268
+ rawResponse: {
2269
+ note: 'This is mocked echo',
2270
+ },
2271
+ // <- [🗯]
2272
+ };
2273
+ if (this.options.isVerbose) {
2274
+ console.info('💬 Mocked faked result', result);
2275
+ }
2276
+ return exportJson({
2277
+ name: 'promptResult',
2278
+ message: `Result of \`MockedFackedLlmExecutionTools.callChatModel\``,
2279
+ order: [],
2280
+ value: result,
2629
2281
  });
2630
- };
2282
+ }
2631
2283
  /**
2632
2284
  * Fakes completion model
2633
2285
  */
2634
- MockedFackedLlmExecutionTools.prototype.callCompletionModel = function (prompt) {
2635
- return __awaiter(this, void 0, void 0, function () {
2636
- return __generator(this, function (_a) {
2637
- return [2 /*return*/, this.callChatModel(prompt)];
2638
- });
2639
- });
2640
- };
2286
+ async callCompletionModel(prompt) {
2287
+ return this.callChatModel(prompt);
2288
+ }
2641
2289
  /**
2642
2290
  * Fakes embedding model
2643
2291
  */
2644
- MockedFackedLlmExecutionTools.prototype.callEmbeddingModel = function (prompt) {
2645
- return __awaiter(this, void 0, void 0, function () {
2646
- var modelName, rawPromptContent, content, usage, result;
2647
- return __generator(this, function (_a) {
2648
- modelName = 'mocked-facked';
2649
- rawPromptContent = templateParameters(prompt.content, __assign(__assign({}, prompt.parameters), { modelName: modelName }));
2650
- content = new Array(1024)
2651
- .fill(0)
2652
- .map(function () { return Math.random() * 2 - 1; });
2653
- usage = ZERO_USAGE;
2654
- result = {
2655
- content: content,
2656
- modelName: modelName,
2657
- timing: {
2658
- start: $getCurrentDate(),
2659
- complete: $getCurrentDate(),
2660
- },
2661
- usage: usage,
2662
- rawPromptContent: rawPromptContent,
2663
- rawRequest: null,
2664
- rawResponse: {
2665
- note: 'This is mocked embedding',
2666
- },
2667
- // <- [🗯]
2668
- };
2669
- if (this.options.isVerbose) {
2670
- console.info('💬 Mocked faked result', result);
2671
- }
2672
- return [2 /*return*/, exportJson({
2673
- name: 'promptResult',
2674
- message: "Result of `MockedFackedLlmExecutionTools.callEmbeddingModel`",
2675
- order: [],
2676
- value: result,
2677
- })];
2678
- });
2292
+ async callEmbeddingModel(prompt) {
2293
+ const modelName = 'mocked-facked';
2294
+ const rawPromptContent = templateParameters(prompt.content, { ...prompt.parameters, modelName });
2295
+ const content = new Array(1024)
2296
+ .fill(0)
2297
+ .map(() => Math.random() * 2 - 1); /* <- Note: [🤛] */
2298
+ const usage = ZERO_USAGE;
2299
+ // <- TODO: [🧠] Compute here at least words, characters,... etc
2300
+ // TODO: Make content vector exactly length of 1
2301
+ const result = {
2302
+ content,
2303
+ modelName,
2304
+ timing: {
2305
+ start: $getCurrentDate(),
2306
+ complete: $getCurrentDate(),
2307
+ },
2308
+ usage,
2309
+ rawPromptContent,
2310
+ rawRequest: null,
2311
+ rawResponse: {
2312
+ note: 'This is mocked embedding',
2313
+ },
2314
+ // <- [🗯]
2315
+ };
2316
+ if (this.options.isVerbose) {
2317
+ console.info('💬 Mocked faked result', result);
2318
+ }
2319
+ return exportJson({
2320
+ name: 'promptResult',
2321
+ message: `Result of \`MockedFackedLlmExecutionTools.callEmbeddingModel\``,
2322
+ order: [],
2323
+ value: result,
2679
2324
  });
2680
- };
2681
- return MockedFackedLlmExecutionTools;
2682
- }());
2325
+ }
2326
+ }
2683
2327
  /**
2684
2328
  * TODO: [🧠][🈁] Maybe use `isDeterministic` from options
2685
2329
  */