@promptbook/core 0.89.0-11 โ†’ 0.89.0-14

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/esm/index.es.js CHANGED
@@ -27,7 +27,7 @@ const BOOK_LANGUAGE_VERSION = '1.0.0';
27
27
  * @generated
28
28
  * @see https://github.com/webgptorg/promptbook
29
29
  */
30
- const PROMPTBOOK_ENGINE_VERSION = '0.89.0-11';
30
+ const PROMPTBOOK_ENGINE_VERSION = '0.89.0-14';
31
31
  /**
32
32
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
33
33
  * Note: [๐Ÿ’ž] Ignore a discrepancy between file name and entity name
@@ -158,239 +158,6 @@ class ParseError extends Error {
158
158
  * TODO: Maybe split `ParseError` and `ApplyError`
159
159
  */
160
160
 
161
- /**
162
- * Function isValidJsonString will tell you if the string is valid JSON or not
163
- *
164
- * @public exported from `@promptbook/utils`
165
- */
166
- function isValidJsonString(value /* <- [๐Ÿ‘จโ€โš–๏ธ] */) {
167
- try {
168
- JSON.parse(value);
169
- return true;
170
- }
171
- catch (error) {
172
- if (!(error instanceof Error)) {
173
- throw error;
174
- }
175
- if (error.message.includes('Unexpected token')) {
176
- return false;
177
- }
178
- return false;
179
- }
180
- }
181
-
182
- /**
183
- * Function `validatePipelineString` will validate the if the string is a valid pipeline string
184
- * It does not check if the string is fully logically correct, but if it is a string that can be a pipeline string or the string looks completely different.
185
- *
186
- * @param {string} pipelineString the candidate for a pipeline string
187
- * @returns {PipelineString} the same string as input, but validated as valid
188
- * @throws {ParseError} if the string is not a valid pipeline string
189
- * @public exported from `@promptbook/core`
190
- */
191
- function validatePipelineString(pipelineString) {
192
- if (isValidJsonString(pipelineString)) {
193
- throw new ParseError('Expected a book, but got a JSON string');
194
- }
195
- else if (isValidUrl(pipelineString)) {
196
- throw new ParseError(`Expected a book, but got just the URL "${pipelineString}"`);
197
- }
198
- else if (isValidFilePath(pipelineString)) {
199
- throw new ParseError(`Expected a book, but got just the file path "${pipelineString}"`);
200
- }
201
- else if (isValidEmail(pipelineString)) {
202
- throw new ParseError(`Expected a book, but got just the email "${pipelineString}"`);
203
- }
204
- // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
205
- return pipelineString;
206
- }
207
- /**
208
- * TODO: [๐Ÿง ][๐Ÿˆด] Where is the best location for this file
209
- */
210
-
211
- /**
212
- * Prettify the html code
213
- *
214
- * @param content raw html code
215
- * @returns formatted html code
216
- * @private withing the package because of HUGE size of prettier dependency
217
- */
218
- function prettifyMarkdown(content) {
219
- try {
220
- return format(content, {
221
- parser: 'markdown',
222
- plugins: [parserHtml],
223
- // TODO: DRY - make some import or auto-copy of .prettierrc
224
- endOfLine: 'lf',
225
- tabWidth: 4,
226
- singleQuote: true,
227
- trailingComma: 'all',
228
- arrowParens: 'always',
229
- printWidth: 120,
230
- htmlWhitespaceSensitivity: 'ignore',
231
- jsxBracketSameLine: false,
232
- bracketSpacing: true,
233
- });
234
- }
235
- catch (error) {
236
- // TODO: [๐ŸŸฅ] Detect browser / node and make it colorfull
237
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
238
- error,
239
- html: content,
240
- });
241
- return content;
242
- }
243
- }
244
-
245
- /**
246
- * Makes first letter of a string uppercase
247
- *
248
- * @public exported from `@promptbook/utils`
249
- */
250
- function capitalize(word) {
251
- return word.substring(0, 1).toUpperCase() + word.substring(1);
252
- }
253
-
254
- /**
255
- * Converts promptbook in JSON format to string format
256
- *
257
- * @deprecated TODO: [๐Ÿฅ][๐Ÿง ] Backup original files in `PipelineJson` same as in Promptbook.studio
258
- * @param pipelineJson Promptbook in JSON format (.bookc)
259
- * @returns Promptbook in string format (.book.md)
260
- * @public exported from `@promptbook/core`
261
- */
262
- function pipelineJsonToString(pipelineJson) {
263
- const { title, pipelineUrl, bookVersion, description, parameters, tasks } = pipelineJson;
264
- let pipelineString = `# ${title}`;
265
- if (description) {
266
- pipelineString += '\n\n';
267
- pipelineString += description;
268
- }
269
- const commands = [];
270
- if (pipelineUrl) {
271
- commands.push(`PIPELINE URL ${pipelineUrl}`);
272
- }
273
- if (bookVersion !== `undefined`) {
274
- commands.push(`BOOK VERSION ${bookVersion}`);
275
- }
276
- // TODO: [main] !!5 This increases size of the bundle and is probbably not necessary
277
- pipelineString = prettifyMarkdown(pipelineString);
278
- for (const parameter of parameters.filter(({ isInput }) => isInput)) {
279
- commands.push(`INPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
280
- }
281
- for (const parameter of parameters.filter(({ isOutput }) => isOutput)) {
282
- commands.push(`OUTPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
283
- }
284
- pipelineString += '\n\n';
285
- pipelineString += commands.map((command) => `- ${command}`).join('\n');
286
- for (const task of tasks) {
287
- const {
288
- /* Note: Not using:> name, */
289
- title, description,
290
- /* Note: dependentParameterNames, */
291
- jokerParameterNames: jokers, taskType, content, postprocessingFunctionNames: postprocessing, expectations, format, resultingParameterName, } = task;
292
- pipelineString += '\n\n';
293
- pipelineString += `## ${title}`;
294
- if (description) {
295
- pipelineString += '\n\n';
296
- pipelineString += description;
297
- }
298
- const commands = [];
299
- let contentLanguage = 'text';
300
- if (taskType === 'PROMPT_TASK') {
301
- const { modelRequirements } = task;
302
- const { modelName, modelVariant } = modelRequirements || {};
303
- // Note: Do nothing, it is default
304
- // commands.push(`PROMPT`);
305
- if (modelVariant) {
306
- commands.push(`MODEL VARIANT ${capitalize(modelVariant)}`);
307
- }
308
- if (modelName) {
309
- commands.push(`MODEL NAME \`${modelName}\``);
310
- }
311
- }
312
- else if (taskType === 'SIMPLE_TASK') {
313
- commands.push(`SIMPLE TEMPLATE`);
314
- // Note: Nothing special here
315
- }
316
- else if (taskType === 'SCRIPT_TASK') {
317
- commands.push(`SCRIPT`);
318
- if (task.contentLanguage) {
319
- contentLanguage = task.contentLanguage;
320
- }
321
- else {
322
- contentLanguage = '';
323
- }
324
- }
325
- else if (taskType === 'DIALOG_TASK') {
326
- commands.push(`DIALOG`);
327
- // Note: Nothing special here
328
- } // <- }else if([๐Ÿ…ฑ]
329
- if (jokers) {
330
- for (const joker of jokers) {
331
- commands.push(`JOKER {${joker}}`);
332
- }
333
- } /* not else */
334
- if (postprocessing) {
335
- for (const postprocessingFunctionName of postprocessing) {
336
- commands.push(`POSTPROCESSING \`${postprocessingFunctionName}\``);
337
- }
338
- } /* not else */
339
- if (expectations) {
340
- for (const [unit, { min, max }] of Object.entries(expectations)) {
341
- if (min === max) {
342
- commands.push(`EXPECT EXACTLY ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
343
- }
344
- else {
345
- if (min !== undefined) {
346
- commands.push(`EXPECT MIN ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
347
- } /* not else */
348
- if (max !== undefined) {
349
- commands.push(`EXPECT MAX ${max} ${capitalize(unit + (max > 1 ? 's' : ''))}`);
350
- }
351
- }
352
- }
353
- } /* not else */
354
- if (format) {
355
- if (format === 'JSON') {
356
- // TODO: @deprecated remove
357
- commands.push(`FORMAT JSON`);
358
- }
359
- } /* not else */
360
- pipelineString += '\n\n';
361
- pipelineString += commands.map((command) => `- ${command}`).join('\n');
362
- pipelineString += '\n\n';
363
- pipelineString += '```' + contentLanguage;
364
- pipelineString += '\n';
365
- pipelineString += spaceTrim(content);
366
- // <- TODO: [main] !!3 Escape
367
- // <- TODO: [๐Ÿง ] Some clear strategy how to spaceTrim the blocks
368
- pipelineString += '\n';
369
- pipelineString += '```';
370
- pipelineString += '\n\n';
371
- pipelineString += `\`-> {${resultingParameterName}}\``; // <- TODO: [main] !!3 If the parameter here has description, add it and use taskParameterJsonToString
372
- }
373
- return validatePipelineString(pipelineString);
374
- }
375
- /**
376
- * @private internal utility of `pipelineJsonToString`
377
- */
378
- function taskParameterJsonToString(taskParameterJson) {
379
- const { name, description } = taskParameterJson;
380
- let parameterString = `{${name}}`;
381
- if (description) {
382
- parameterString = `${parameterString} ${description}`;
383
- }
384
- return parameterString;
385
- }
386
- /**
387
- * TODO: [๐Ÿ›‹] Implement new features and commands into `pipelineJsonToString` + `taskParameterJsonToString` , use `stringifyCommand`
388
- * TODO: [๐Ÿง ] Is there a way to auto-detect missing features in pipelineJsonToString
389
- * TODO: [๐Ÿ›] Maybe make some markdown builder
390
- * TODO: [๐Ÿ›] Escape all
391
- * TODO: [๐Ÿง ] Should be in generated .book.md file GENERATOR_WARNING
392
- */
393
-
394
161
  /**
395
162
  * Returns the same value that is passed as argument.
396
163
  * No side effects.
@@ -512,6 +279,7 @@ const VALUE_STRINGS = {
512
279
  infinity: '(infinity; โˆž)',
513
280
  negativeInfinity: '(negative infinity; -โˆž)',
514
281
  unserializable: '(unserializable value)',
282
+ circular: '(circular JSON)',
515
283
  };
516
284
  /**
517
285
  * Small number limit
@@ -668,29 +436,378 @@ function SET_IS_VERBOSE(isVerbose) {
668
436
  DEFAULT_IS_VERBOSE = isVerbose;
669
437
  }
670
438
  /**
671
- * @@@
439
+ * @@@
440
+ *
441
+ * @public exported from `@promptbook/core`
442
+ */
443
+ const DEFAULT_IS_AUTO_INSTALLED = false;
444
+ /**
445
+ * Function name for generated function via `ptbk make` to get the pipeline collection
446
+ *
447
+ * @public exported from `@promptbook/core`
448
+ */
449
+ const DEFAULT_GET_PIPELINE_COLLECTION_FUNCTION_NAME = `getPipelineCollection`;
450
+ /**
451
+ * @@@
452
+ *
453
+ * @private within the repository
454
+ */
455
+ const IS_PIPELINE_LOGIC_VALIDATED = just(
456
+ /**/
457
+ // Note: In normal situations, we check the pipeline logic:
458
+ true);
459
+ /**
460
+ * Note: [๐Ÿ’ž] Ignore a discrepancy between file name and entity name
461
+ * TODO: [๐Ÿง ][๐Ÿงœโ€โ™‚๏ธ] Maybe join remoteServerUrl and path into single value
462
+ */
463
+
464
+ /**
465
+ * Make error report URL for the given error
466
+ *
467
+ * @private private within the repository
468
+ */
469
+ function getErrorReportUrl(error) {
470
+ const report = {
471
+ title: `๐Ÿœ Error report from ${NAME}`,
472
+ body: spaceTrim((block) => `
473
+
474
+
475
+ \`${error.name || 'Error'}\` has occurred in the [${NAME}], please look into it @${ADMIN_GITHUB_NAME}.
476
+
477
+ \`\`\`
478
+ ${block(error.message || '(no error message)')}
479
+ \`\`\`
480
+
481
+
482
+ ## More info:
483
+
484
+ - **Promptbook engine version:** ${PROMPTBOOK_ENGINE_VERSION}
485
+ - **Book language version:** ${BOOK_LANGUAGE_VERSION}
486
+ - **Time:** ${new Date().toISOString()}
487
+
488
+ <details>
489
+ <summary>Stack trace:</summary>
490
+
491
+ ## Stack trace:
492
+
493
+ \`\`\`stacktrace
494
+ ${block(error.stack || '(empty)')}
495
+ \`\`\`
496
+ </details>
497
+
498
+ `),
499
+ };
500
+ const reportUrl = new URL(`https://github.com/webgptorg/promptbook/issues/new`);
501
+ reportUrl.searchParams.set('labels', 'bug');
502
+ reportUrl.searchParams.set('assignees', ADMIN_GITHUB_NAME);
503
+ reportUrl.searchParams.set('title', report.title);
504
+ reportUrl.searchParams.set('body', report.body);
505
+ return reportUrl;
506
+ }
507
+
508
+ /**
509
+ * This error type indicates that the error should not happen and its last check before crashing with some other error
510
+ *
511
+ * @public exported from `@promptbook/core`
512
+ */
513
+ class UnexpectedError extends Error {
514
+ constructor(message) {
515
+ super(spaceTrim$1((block) => `
516
+ ${block(message)}
517
+
518
+ Note: This error should not happen.
519
+ It's probbably a bug in the pipeline collection
520
+
521
+ Please report issue:
522
+ ${block(getErrorReportUrl(new Error(message)).href)}
523
+
524
+ Or contact us on ${ADMIN_EMAIL}
525
+
526
+ `));
527
+ this.name = 'UnexpectedError';
528
+ Object.setPrototypeOf(this, UnexpectedError.prototype);
529
+ }
530
+ }
531
+
532
+ /**
533
+ * This error type indicates that somewhere in the code non-Error object was thrown and it was wrapped into the `WrappedError`
534
+ *
535
+ * @public exported from `@promptbook/core`
536
+ */
537
+ class WrappedError extends Error {
538
+ constructor(whatWasThrown) {
539
+ const tag = `[๐Ÿคฎ]`;
540
+ console.error(tag, whatWasThrown);
541
+ super(spaceTrim$1((block) => `
542
+ ${ /* Fixing tests !!! block(valueToString(whatWasThrown)) */block(`non-Error object was thrown`)}
543
+
544
+ Note: Look for ${tag} in the console for more details
545
+ !!! Note: \`WrappedError\` indicates that somewhere in the code non-Error object was thrown and it was wrapped
546
+
547
+ Please report issue on ${ADMIN_EMAIL}
548
+
549
+ `));
550
+ this.name = 'WrappedError';
551
+ Object.setPrototypeOf(this, WrappedError.prototype);
552
+ }
553
+ }
554
+
555
+ /**
556
+ * !!!@@@
557
+ *
558
+ * @param whatWasThrown !!!@@@
559
+ * @returns !!!@@@
560
+ *
561
+ * @private within the repository
562
+ */
563
+ function assertsError(whatWasThrown) {
564
+ // Case 1: !!!@@@
565
+ if (whatWasThrown instanceof WrappedError) {
566
+ const wrappedError = whatWasThrown;
567
+ throw wrappedError;
568
+ }
569
+ // Case 2: !!!@@@
570
+ if (whatWasThrown instanceof UnexpectedError) {
571
+ const unexpectedError = whatWasThrown;
572
+ throw unexpectedError;
573
+ }
574
+ // Case 3: !!!@@@
575
+ if (whatWasThrown instanceof Error) {
576
+ return;
577
+ }
578
+ // Case 4: !!!@@@
579
+ throw new WrappedError(whatWasThrown);
580
+ }
581
+
582
+ /**
583
+ * Function isValidJsonString will tell you if the string is valid JSON or not
584
+ *
585
+ * @public exported from `@promptbook/utils`
586
+ */
587
+ function isValidJsonString(value /* <- [๐Ÿ‘จโ€โš–๏ธ] */) {
588
+ try {
589
+ JSON.parse(value);
590
+ return true;
591
+ }
592
+ catch (error) {
593
+ assertsError(error);
594
+ if (error.message.includes('Unexpected token')) {
595
+ return false;
596
+ }
597
+ return false;
598
+ }
599
+ }
600
+
601
+ /**
602
+ * Function `validatePipelineString` will validate the if the string is a valid pipeline string
603
+ * It does not check if the string is fully logically correct, but if it is a string that can be a pipeline string or the string looks completely different.
604
+ *
605
+ * @param {string} pipelineString the candidate for a pipeline string
606
+ * @returns {PipelineString} the same string as input, but validated as valid
607
+ * @throws {ParseError} if the string is not a valid pipeline string
608
+ * @public exported from `@promptbook/core`
609
+ */
610
+ function validatePipelineString(pipelineString) {
611
+ if (isValidJsonString(pipelineString)) {
612
+ throw new ParseError('Expected a book, but got a JSON string');
613
+ }
614
+ else if (isValidUrl(pipelineString)) {
615
+ throw new ParseError(`Expected a book, but got just the URL "${pipelineString}"`);
616
+ }
617
+ else if (isValidFilePath(pipelineString)) {
618
+ throw new ParseError(`Expected a book, but got just the file path "${pipelineString}"`);
619
+ }
620
+ else if (isValidEmail(pipelineString)) {
621
+ throw new ParseError(`Expected a book, but got just the email "${pipelineString}"`);
622
+ }
623
+ // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
624
+ return pipelineString;
625
+ }
626
+ /**
627
+ * TODO: [๐Ÿง ][๐Ÿˆด] Where is the best location for this file
628
+ */
629
+
630
+ /**
631
+ * Prettify the html code
632
+ *
633
+ * @param content raw html code
634
+ * @returns formatted html code
635
+ * @private withing the package because of HUGE size of prettier dependency
636
+ */
637
+ function prettifyMarkdown(content) {
638
+ try {
639
+ return format(content, {
640
+ parser: 'markdown',
641
+ plugins: [parserHtml],
642
+ // TODO: DRY - make some import or auto-copy of .prettierrc
643
+ endOfLine: 'lf',
644
+ tabWidth: 4,
645
+ singleQuote: true,
646
+ trailingComma: 'all',
647
+ arrowParens: 'always',
648
+ printWidth: 120,
649
+ htmlWhitespaceSensitivity: 'ignore',
650
+ jsxBracketSameLine: false,
651
+ bracketSpacing: true,
652
+ });
653
+ }
654
+ catch (error) {
655
+ // TODO: [๐ŸŸฅ] Detect browser / node and make it colorfull
656
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
657
+ error,
658
+ html: content,
659
+ });
660
+ return content;
661
+ }
662
+ }
663
+
664
+ /**
665
+ * Makes first letter of a string uppercase
672
666
  *
673
- * @public exported from `@promptbook/core`
667
+ * @public exported from `@promptbook/utils`
674
668
  */
675
- const DEFAULT_IS_AUTO_INSTALLED = false;
669
+ function capitalize(word) {
670
+ return word.substring(0, 1).toUpperCase() + word.substring(1);
671
+ }
672
+
676
673
  /**
677
- * Function name for generated function via `ptbk make` to get the pipeline collection
674
+ * Converts promptbook in JSON format to string format
678
675
  *
676
+ * @deprecated TODO: [๐Ÿฅ][๐Ÿง ] Backup original files in `PipelineJson` same as in Promptbook.studio
677
+ * @param pipelineJson Promptbook in JSON format (.bookc)
678
+ * @returns Promptbook in string format (.book.md)
679
679
  * @public exported from `@promptbook/core`
680
680
  */
681
- const DEFAULT_GET_PIPELINE_COLLECTION_FUNCTION_NAME = `getPipelineCollection`;
681
+ function pipelineJsonToString(pipelineJson) {
682
+ const { title, pipelineUrl, bookVersion, description, parameters, tasks } = pipelineJson;
683
+ let pipelineString = `# ${title}`;
684
+ if (description) {
685
+ pipelineString += '\n\n';
686
+ pipelineString += description;
687
+ }
688
+ const commands = [];
689
+ if (pipelineUrl) {
690
+ commands.push(`PIPELINE URL ${pipelineUrl}`);
691
+ }
692
+ if (bookVersion !== `undefined`) {
693
+ commands.push(`BOOK VERSION ${bookVersion}`);
694
+ }
695
+ // TODO: [main] !!5 This increases size of the bundle and is probbably not necessary
696
+ pipelineString = prettifyMarkdown(pipelineString);
697
+ for (const parameter of parameters.filter(({ isInput }) => isInput)) {
698
+ commands.push(`INPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
699
+ }
700
+ for (const parameter of parameters.filter(({ isOutput }) => isOutput)) {
701
+ commands.push(`OUTPUT PARAMETER ${taskParameterJsonToString(parameter)}`);
702
+ }
703
+ pipelineString += '\n\n';
704
+ pipelineString += commands.map((command) => `- ${command}`).join('\n');
705
+ for (const task of tasks) {
706
+ const {
707
+ /* Note: Not using:> name, */
708
+ title, description,
709
+ /* Note: dependentParameterNames, */
710
+ jokerParameterNames: jokers, taskType, content, postprocessingFunctionNames: postprocessing, expectations, format, resultingParameterName, } = task;
711
+ pipelineString += '\n\n';
712
+ pipelineString += `## ${title}`;
713
+ if (description) {
714
+ pipelineString += '\n\n';
715
+ pipelineString += description;
716
+ }
717
+ const commands = [];
718
+ let contentLanguage = 'text';
719
+ if (taskType === 'PROMPT_TASK') {
720
+ const { modelRequirements } = task;
721
+ const { modelName, modelVariant } = modelRequirements || {};
722
+ // Note: Do nothing, it is default
723
+ // commands.push(`PROMPT`);
724
+ if (modelVariant) {
725
+ commands.push(`MODEL VARIANT ${capitalize(modelVariant)}`);
726
+ }
727
+ if (modelName) {
728
+ commands.push(`MODEL NAME \`${modelName}\``);
729
+ }
730
+ }
731
+ else if (taskType === 'SIMPLE_TASK') {
732
+ commands.push(`SIMPLE TEMPLATE`);
733
+ // Note: Nothing special here
734
+ }
735
+ else if (taskType === 'SCRIPT_TASK') {
736
+ commands.push(`SCRIPT`);
737
+ if (task.contentLanguage) {
738
+ contentLanguage = task.contentLanguage;
739
+ }
740
+ else {
741
+ contentLanguage = '';
742
+ }
743
+ }
744
+ else if (taskType === 'DIALOG_TASK') {
745
+ commands.push(`DIALOG`);
746
+ // Note: Nothing special here
747
+ } // <- }else if([๐Ÿ…ฑ]
748
+ if (jokers) {
749
+ for (const joker of jokers) {
750
+ commands.push(`JOKER {${joker}}`);
751
+ }
752
+ } /* not else */
753
+ if (postprocessing) {
754
+ for (const postprocessingFunctionName of postprocessing) {
755
+ commands.push(`POSTPROCESSING \`${postprocessingFunctionName}\``);
756
+ }
757
+ } /* not else */
758
+ if (expectations) {
759
+ for (const [unit, { min, max }] of Object.entries(expectations)) {
760
+ if (min === max) {
761
+ commands.push(`EXPECT EXACTLY ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
762
+ }
763
+ else {
764
+ if (min !== undefined) {
765
+ commands.push(`EXPECT MIN ${min} ${capitalize(unit + (min > 1 ? 's' : ''))}`);
766
+ } /* not else */
767
+ if (max !== undefined) {
768
+ commands.push(`EXPECT MAX ${max} ${capitalize(unit + (max > 1 ? 's' : ''))}`);
769
+ }
770
+ }
771
+ }
772
+ } /* not else */
773
+ if (format) {
774
+ if (format === 'JSON') {
775
+ // TODO: @deprecated remove
776
+ commands.push(`FORMAT JSON`);
777
+ }
778
+ } /* not else */
779
+ pipelineString += '\n\n';
780
+ pipelineString += commands.map((command) => `- ${command}`).join('\n');
781
+ pipelineString += '\n\n';
782
+ pipelineString += '```' + contentLanguage;
783
+ pipelineString += '\n';
784
+ pipelineString += spaceTrim(content);
785
+ // <- TODO: [main] !!3 Escape
786
+ // <- TODO: [๐Ÿง ] Some clear strategy how to spaceTrim the blocks
787
+ pipelineString += '\n';
788
+ pipelineString += '```';
789
+ pipelineString += '\n\n';
790
+ pipelineString += `\`-> {${resultingParameterName}}\``; // <- TODO: [main] !!3 If the parameter here has description, add it and use taskParameterJsonToString
791
+ }
792
+ return validatePipelineString(pipelineString);
793
+ }
682
794
  /**
683
- * @@@
684
- *
685
- * @private within the repository
795
+ * @private internal utility of `pipelineJsonToString`
686
796
  */
687
- const IS_PIPELINE_LOGIC_VALIDATED = just(
688
- /**/
689
- // Note: In normal situations, we check the pipeline logic:
690
- true);
797
+ function taskParameterJsonToString(taskParameterJson) {
798
+ const { name, description } = taskParameterJson;
799
+ let parameterString = `{${name}}`;
800
+ if (description) {
801
+ parameterString = `${parameterString} ${description}`;
802
+ }
803
+ return parameterString;
804
+ }
691
805
  /**
692
- * Note: [๐Ÿ’ž] Ignore a discrepancy between file name and entity name
693
- * TODO: [๐Ÿง ][๐Ÿงœโ€โ™‚๏ธ] Maybe join remoteServerUrl and path into single value
806
+ * TODO: [๐Ÿ›‹] Implement new features and commands into `pipelineJsonToString` + `taskParameterJsonToString` , use `stringifyCommand`
807
+ * TODO: [๐Ÿง ] Is there a way to auto-detect missing features in pipelineJsonToString
808
+ * TODO: [๐Ÿ›] Maybe make some markdown builder
809
+ * TODO: [๐Ÿ›] Escape all
810
+ * TODO: [๐Ÿง ] Should be in generated .book.md file GENERATOR_WARNING
694
811
  */
695
812
 
696
813
  /**
@@ -735,74 +852,6 @@ function $deepFreeze(objectValue) {
735
852
  * TODO: [๐Ÿง ] Is there a way how to meaningfully test this utility
736
853
  */
737
854
 
738
- /**
739
- * Make error report URL for the given error
740
- *
741
- * @private private within the repository
742
- */
743
- function getErrorReportUrl(error) {
744
- const report = {
745
- title: `๐Ÿœ Error report from ${NAME}`,
746
- body: spaceTrim((block) => `
747
-
748
-
749
- \`${error.name || 'Error'}\` has occurred in the [${NAME}], please look into it @${ADMIN_GITHUB_NAME}.
750
-
751
- \`\`\`
752
- ${block(error.message || '(no error message)')}
753
- \`\`\`
754
-
755
-
756
- ## More info:
757
-
758
- - **Promptbook engine version:** ${PROMPTBOOK_ENGINE_VERSION}
759
- - **Book language version:** ${BOOK_LANGUAGE_VERSION}
760
- - **Time:** ${new Date().toISOString()}
761
-
762
- <details>
763
- <summary>Stack trace:</summary>
764
-
765
- ## Stack trace:
766
-
767
- \`\`\`stacktrace
768
- ${block(error.stack || '(empty)')}
769
- \`\`\`
770
- </details>
771
-
772
- `),
773
- };
774
- const reportUrl = new URL(`https://github.com/webgptorg/promptbook/issues/new`);
775
- reportUrl.searchParams.set('labels', 'bug');
776
- reportUrl.searchParams.set('assignees', ADMIN_GITHUB_NAME);
777
- reportUrl.searchParams.set('title', report.title);
778
- reportUrl.searchParams.set('body', report.body);
779
- return reportUrl;
780
- }
781
-
782
- /**
783
- * This error type indicates that the error should not happen and its last check before crashing with some other error
784
- *
785
- * @public exported from `@promptbook/core`
786
- */
787
- class UnexpectedError extends Error {
788
- constructor(message) {
789
- super(spaceTrim$1((block) => `
790
- ${block(message)}
791
-
792
- Note: This error should not happen.
793
- It's probbably a bug in the pipeline collection
794
-
795
- Please report issue:
796
- ${block(getErrorReportUrl(new Error(message)).href)}
797
-
798
- Or contact us on ${ADMIN_EMAIL}
799
-
800
- `));
801
- this.name = 'UnexpectedError';
802
- Object.setPrototypeOf(this, UnexpectedError.prototype);
803
- }
804
- }
805
-
806
855
  /**
807
856
  * Checks if the value is [๐Ÿš‰] serializable as JSON
808
857
  * If not, throws an UnexpectedError with a rich error message and tracking
@@ -894,9 +943,7 @@ function checkSerializableAsJson(options) {
894
943
  JSON.stringify(value); // <- TODO: [0]
895
944
  }
896
945
  catch (error) {
897
- if (!(error instanceof Error)) {
898
- throw error;
899
- }
946
+ assertsError(error);
900
947
  throw new UnexpectedError(spaceTrim((block) => `
901
948
  \`${name}\` is not serializable
902
949
 
@@ -2046,7 +2093,10 @@ const PROMPTBOOK_ERRORS = {
2046
2093
  PipelineExecutionError,
2047
2094
  PipelineLogicError,
2048
2095
  PipelineUrlError,
2096
+ AuthenticationError,
2097
+ PromptbookFetchError,
2049
2098
  UnexpectedError,
2099
+ WrappedError,
2050
2100
  // TODO: [๐Ÿช‘]> VersionMismatchError,
2051
2101
  };
2052
2102
  /**
@@ -2063,8 +2113,6 @@ const COMMON_JAVASCRIPT_ERRORS = {
2063
2113
  TypeError,
2064
2114
  URIError,
2065
2115
  AggregateError,
2066
- AuthenticationError,
2067
- PromptbookFetchError,
2068
2116
  /*
2069
2117
  Note: Not widely supported
2070
2118
  > InternalError,
@@ -2198,6 +2246,7 @@ function createTask(options) {
2198
2246
  partialResultSubject.next(executionResult);
2199
2247
  }
2200
2248
  catch (error) {
2249
+ assertsError(error);
2201
2250
  status = 'ERROR';
2202
2251
  errors.push(error);
2203
2252
  partialResultSubject.error(error);
@@ -2343,13 +2392,19 @@ function valueToString(value) {
2343
2392
  return value.toISOString();
2344
2393
  }
2345
2394
  else {
2346
- return JSON.stringify(value);
2395
+ try {
2396
+ return JSON.stringify(value);
2397
+ }
2398
+ catch (error) {
2399
+ if (error instanceof TypeError && error.message.includes('circular structure')) {
2400
+ return VALUE_STRINGS.circular;
2401
+ }
2402
+ throw error;
2403
+ }
2347
2404
  }
2348
2405
  }
2349
2406
  catch (error) {
2350
- if (!(error instanceof Error)) {
2351
- throw error;
2352
- }
2407
+ assertsError(error);
2353
2408
  console.error(error);
2354
2409
  return VALUE_STRINGS.unserializable;
2355
2410
  }
@@ -2521,9 +2576,7 @@ function extractVariablesFromJavascript(script) {
2521
2576
  }
2522
2577
  }
2523
2578
  catch (error) {
2524
- if (!(error instanceof Error)) {
2525
- throw error;
2526
- }
2579
+ assertsError(error);
2527
2580
  throw new ParseError(spaceTrim$1((block) => `
2528
2581
  Can not extract variables from the script
2529
2582
  ${block(error.stack || error.message)}
@@ -3012,14 +3065,15 @@ class MultipleLlmExecutionTools {
3012
3065
  }
3013
3066
  }
3014
3067
  catch (error) {
3015
- if (!(error instanceof Error) || error instanceof UnexpectedError) {
3068
+ assertsError(error);
3069
+ if (error instanceof UnexpectedError) {
3016
3070
  throw error;
3017
3071
  }
3018
3072
  errors.push({ llmExecutionTools, error });
3019
3073
  }
3020
3074
  }
3021
3075
  if (errors.length === 1) {
3022
- throw errors[0];
3076
+ throw errors[0].error;
3023
3077
  }
3024
3078
  else if (errors.length > 1) {
3025
3079
  throw new PipelineExecutionError(
@@ -3898,9 +3952,7 @@ async function executeAttempts(options) {
3898
3952
  break scripts;
3899
3953
  }
3900
3954
  catch (error) {
3901
- if (!(error instanceof Error)) {
3902
- throw error;
3903
- }
3955
+ assertsError(error);
3904
3956
  if (error instanceof UnexpectedError) {
3905
3957
  throw error;
3906
3958
  }
@@ -3970,9 +4022,7 @@ async function executeAttempts(options) {
3970
4022
  break scripts;
3971
4023
  }
3972
4024
  catch (error) {
3973
- if (!(error instanceof Error)) {
3974
- throw error;
3975
- }
4025
+ assertsError(error);
3976
4026
  if (error instanceof UnexpectedError) {
3977
4027
  throw error;
3978
4028
  }
@@ -4593,9 +4643,7 @@ async function executePipeline(options) {
4593
4643
  await Promise.all(resolving);
4594
4644
  }
4595
4645
  catch (error /* <- Note: [3] */) {
4596
- if (!(error instanceof Error)) {
4597
- throw error;
4598
- }
4646
+ assertsError(error);
4599
4647
  // Note: No need to rethrow UnexpectedError
4600
4648
  // if (error instanceof UnexpectedError) {
4601
4649
  // Note: Count usage, [๐Ÿง ] Maybe put to separate function executionReportJsonToUsage + DRY [๐Ÿคนโ€โ™‚๏ธ]
@@ -5311,9 +5359,7 @@ const promptbookFetch = async (urlOrRequest, init) => {
5311
5359
  return await fetch(urlOrRequest, init);
5312
5360
  }
5313
5361
  catch (error) {
5314
- if (!(error instanceof Error)) {
5315
- throw error;
5316
- }
5362
+ assertsError(error);
5317
5363
  let url;
5318
5364
  if (typeof urlOrRequest === 'string') {
5319
5365
  url = urlOrRequest;
@@ -5544,9 +5590,7 @@ async function prepareKnowledgePieces(knowledgeSources, tools, options) {
5544
5590
  knowledgePreparedUnflatten[index] = pieces;
5545
5591
  }
5546
5592
  catch (error) {
5547
- if (!(error instanceof Error)) {
5548
- throw error;
5549
- }
5593
+ assertsError(error);
5550
5594
  console.warn(error);
5551
5595
  // <- TODO: [๐Ÿฎ] Some standard way how to transform errors into warnings and how to handle non-critical fails during the tasks
5552
5596
  }
@@ -6344,6 +6388,8 @@ function parseNumber(value) {
6344
6388
  */
6345
6389
 
6346
6390
  /**
6391
+ import { WrappedError } from '../../errors/WrappedError';
6392
+ import { assertsError } from '../../errors/assertsError';
6347
6393
  * Parses the expect command
6348
6394
  *
6349
6395
  * @see `documentationUrl` for more details
@@ -6435,9 +6481,7 @@ const expectCommandParser = {
6435
6481
  };
6436
6482
  }
6437
6483
  catch (error) {
6438
- if (!(error instanceof Error)) {
6439
- throw error;
6440
- }
6484
+ assertsError(error);
6441
6485
  throw new ParseError(spaceTrim((block) => `
6442
6486
  Invalid FORMAT command
6443
6487
  ${block(error.message)}:
@@ -10531,9 +10575,7 @@ function isValidPipelineString(pipelineString) {
10531
10575
  return true;
10532
10576
  }
10533
10577
  catch (error) {
10534
- if (!(error instanceof Error)) {
10535
- throw error;
10536
- }
10578
+ assertsError(error);
10537
10579
  return false;
10538
10580
  }
10539
10581
  }
@@ -10917,5 +10959,5 @@ class PrefixStorage {
10917
10959
  }
10918
10960
  }
10919
10961
 
10920
- export { $llmToolsMetadataRegister, $llmToolsRegister, $scrapersMetadataRegister, $scrapersRegister, ADMIN_EMAIL, ADMIN_GITHUB_NAME, AbstractFormatError, AuthenticationError, BOOK_LANGUAGE_VERSION, BlackholeStorage, BoilerplateError, BoilerplateFormfactorDefinition, CLAIM, CLI_APP_ID, CallbackInterfaceTools, ChatbotFormfactorDefinition, CollectionError, CsvFormatDefinition, CsvFormatError, DEFAULT_BOOKS_DIRNAME, DEFAULT_BOOK_OUTPUT_PARAMETER_NAME, DEFAULT_BOOK_TITLE, DEFAULT_CSV_SETTINGS, DEFAULT_DOWNLOAD_CACHE_DIRNAME, DEFAULT_EXECUTION_CACHE_DIRNAME, DEFAULT_GET_PIPELINE_COLLECTION_FUNCTION_NAME, DEFAULT_INTERMEDIATE_FILES_STRATEGY, DEFAULT_IS_AUTO_INSTALLED, DEFAULT_IS_VERBOSE, DEFAULT_MAX_EXECUTION_ATTEMPTS, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, DEFAULT_MAX_PARALLEL_COUNT, DEFAULT_PIPELINE_COLLECTION_BASE_FILENAME, DEFAULT_PROMPT_TASK_TITLE, DEFAULT_REMOTE_SERVER_URL, DEFAULT_SCRAPE_CACHE_DIRNAME, DEFAULT_TASK_TITLE, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, FORMFACTOR_DEFINITIONS, GENERIC_PIPELINE_INTERFACE, GeneratorFormfactorDefinition, GenericFormfactorDefinition, ImageGeneratorFormfactorDefinition, KnowledgeScrapeError, LOGO_DARK_SRC, LOGO_LIGHT_SRC, LimitReachedError, MANDATORY_CSV_SETTINGS, MAX_FILENAME_LENGTH, MODEL_VARIANTS, MatcherFormfactorDefinition, MemoryStorage, MissingToolsError, MultipleLlmExecutionTools, NAME, NonTaskSectionTypes, NotFoundError, NotYetImplementedError, ORDER_OF_PIPELINE_JSON, PLAYGROUND_APP_ID, PROMPTBOOK_ENGINE_VERSION, PROMPTBOOK_ERRORS, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, PromptbookFetchError, RESERVED_PARAMETER_NAMES, SET_IS_VERBOSE, SectionTypes, SheetsFormfactorDefinition, TaskTypes, TextFormatDefinition, TranslatorFormfactorDefinition, UNCERTAIN_USAGE, UNCERTAIN_ZERO_VALUE, UnexpectedError, ZERO_USAGE, ZERO_VALUE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _BoilerplateScraperMetadataRegistration, _DeepseekMetadataRegistration, _DocumentScraperMetadataRegistration, _GoogleMetadataRegistration, _LegacyDocumentScraperMetadataRegistration, _MarkdownScraperMetadataRegistration, _MarkitdownScraperMetadataRegistration, _OpenAiAssistantMetadataRegistration, _OpenAiMetadataRegistration, _PdfScraperMetadataRegistration, _WebsiteScraperMetadataRegistration, addUsage, book, cacheLlmTools, collectionToJson, compilePipeline, countUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, extractParameterNamesFromTask, getPipelineInterface, isPassingExpectations, isPipelineImplementingInterface, isPipelineInterfacesEqual, isPipelinePrepared, isValidPipelineString, joinLlmExecutionTools, limitTotalUsage, makeKnowledgeSourceHandler, parsePipeline, pipelineJsonToString, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTasks, prettifyPipelineString, promptbookFetch, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline, validatePipelineString };
10962
+ export { $llmToolsMetadataRegister, $llmToolsRegister, $scrapersMetadataRegister, $scrapersRegister, ADMIN_EMAIL, ADMIN_GITHUB_NAME, AbstractFormatError, AuthenticationError, BOOK_LANGUAGE_VERSION, BlackholeStorage, BoilerplateError, BoilerplateFormfactorDefinition, CLAIM, CLI_APP_ID, CallbackInterfaceTools, ChatbotFormfactorDefinition, CollectionError, CsvFormatDefinition, CsvFormatError, DEFAULT_BOOKS_DIRNAME, DEFAULT_BOOK_OUTPUT_PARAMETER_NAME, DEFAULT_BOOK_TITLE, DEFAULT_CSV_SETTINGS, DEFAULT_DOWNLOAD_CACHE_DIRNAME, DEFAULT_EXECUTION_CACHE_DIRNAME, DEFAULT_GET_PIPELINE_COLLECTION_FUNCTION_NAME, DEFAULT_INTERMEDIATE_FILES_STRATEGY, DEFAULT_IS_AUTO_INSTALLED, DEFAULT_IS_VERBOSE, DEFAULT_MAX_EXECUTION_ATTEMPTS, DEFAULT_MAX_FILE_SIZE, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_DEPTH, DEFAULT_MAX_KNOWLEDGE_SOURCES_SCRAPING_TOTAL, DEFAULT_MAX_PARALLEL_COUNT, DEFAULT_PIPELINE_COLLECTION_BASE_FILENAME, DEFAULT_PROMPT_TASK_TITLE, DEFAULT_REMOTE_SERVER_URL, DEFAULT_SCRAPE_CACHE_DIRNAME, DEFAULT_TASK_TITLE, EXPECTATION_UNITS, EnvironmentMismatchError, ExecutionReportStringOptionsDefaults, ExpectError, FORMFACTOR_DEFINITIONS, GENERIC_PIPELINE_INTERFACE, GeneratorFormfactorDefinition, GenericFormfactorDefinition, ImageGeneratorFormfactorDefinition, KnowledgeScrapeError, LOGO_DARK_SRC, LOGO_LIGHT_SRC, LimitReachedError, MANDATORY_CSV_SETTINGS, MAX_FILENAME_LENGTH, MODEL_VARIANTS, MatcherFormfactorDefinition, MemoryStorage, MissingToolsError, MultipleLlmExecutionTools, NAME, NonTaskSectionTypes, NotFoundError, NotYetImplementedError, ORDER_OF_PIPELINE_JSON, PLAYGROUND_APP_ID, PROMPTBOOK_ENGINE_VERSION, PROMPTBOOK_ERRORS, ParseError, PipelineExecutionError, PipelineLogicError, PipelineUrlError, PrefixStorage, PromptbookFetchError, RESERVED_PARAMETER_NAMES, SET_IS_VERBOSE, SectionTypes, SheetsFormfactorDefinition, TaskTypes, TextFormatDefinition, TranslatorFormfactorDefinition, UNCERTAIN_USAGE, UNCERTAIN_ZERO_VALUE, UnexpectedError, WrappedError, ZERO_USAGE, ZERO_VALUE, _AnthropicClaudeMetadataRegistration, _AzureOpenAiMetadataRegistration, _BoilerplateScraperMetadataRegistration, _DeepseekMetadataRegistration, _DocumentScraperMetadataRegistration, _GoogleMetadataRegistration, _LegacyDocumentScraperMetadataRegistration, _MarkdownScraperMetadataRegistration, _MarkitdownScraperMetadataRegistration, _OpenAiAssistantMetadataRegistration, _OpenAiMetadataRegistration, _PdfScraperMetadataRegistration, _WebsiteScraperMetadataRegistration, addUsage, book, cacheLlmTools, collectionToJson, compilePipeline, countUsage, createCollectionFromJson, createCollectionFromPromise, createCollectionFromUrl, createLlmToolsFromConfiguration, createPipelineExecutor, createSubcollection, embeddingVectorToString, executionReportJsonToString, extractParameterNamesFromTask, getPipelineInterface, isPassingExpectations, isPipelineImplementingInterface, isPipelineInterfacesEqual, isPipelinePrepared, isValidPipelineString, joinLlmExecutionTools, limitTotalUsage, makeKnowledgeSourceHandler, parsePipeline, pipelineJsonToString, prepareKnowledgePieces, preparePersona, preparePipeline, prepareTasks, prettifyPipelineString, promptbookFetch, unpreparePipeline, usageToHuman, usageToWorktime, validatePipeline, validatePipelineString };
10921
10963
  //# sourceMappingURL=index.es.js.map