@promptbook/core 0.52.0 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/esm/index.es.js +733 -733
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/conversion/prettify/prettifyPromptbookString.d.ts +1 -1
  4. package/esm/typings/conversion/prettify/renderPromptbookMermaid.d.ts +2 -1
  5. package/esm/typings/conversion/utils/extractParametersFromPromptTemplate.d.ts +3 -3
  6. package/esm/typings/conversion/utils/extractVariables.d.ts +2 -1
  7. package/esm/typings/conversion/validation/_importPromptbook.d.ts +2 -2
  8. package/esm/typings/execution/LlmExecutionTools.d.ts +4 -2
  9. package/esm/typings/execution/PromptResult.d.ts +5 -1
  10. package/esm/typings/execution/ScriptExecutionTools.d.ts +2 -1
  11. package/esm/typings/execution/UserInterfaceTools.d.ts +2 -1
  12. package/esm/typings/execution/createPromptbookExecutor.d.ts +3 -3
  13. package/esm/typings/execution/plugins/llm-execution-tools/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +4 -2
  14. package/esm/typings/execution/plugins/llm-execution-tools/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  15. package/esm/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionTools.d.ts +4 -2
  16. package/esm/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +2 -1
  17. package/esm/typings/execution/plugins/llm-execution-tools/mocked/MockedEchoLlmExecutionTools.d.ts +4 -2
  18. package/esm/typings/execution/plugins/llm-execution-tools/mocked/MockedFackedLlmExecutionTools.d.ts +4 -2
  19. package/esm/typings/execution/plugins/llm-execution-tools/mocked/fakeTextToExpectations.d.ts +1 -1
  20. package/esm/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionTools.d.ts +4 -2
  21. package/esm/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionToolsOptions.d.ts +2 -1
  22. package/esm/typings/execution/plugins/llm-execution-tools/openai/OpenAiExecutionTools.d.ts +4 -2
  23. package/esm/typings/execution/plugins/llm-execution-tools/openai/OpenAiExecutionToolsOptions.d.ts +1 -1
  24. package/esm/typings/execution/plugins/llm-execution-tools/openai/openai-models.d.ts +1 -1
  25. package/esm/typings/execution/plugins/llm-execution-tools/remote/RemoteLlmExecutionTools.d.ts +4 -2
  26. package/esm/typings/execution/plugins/llm-execution-tools/remote/RemoteLlmExecutionToolsOptions.d.ts +2 -1
  27. package/esm/typings/execution/plugins/llm-execution-tools/remote/interfaces/Promptbook_Server_Progress.d.ts +1 -1
  28. package/esm/typings/execution/plugins/llm-execution-tools/remote/interfaces/Promptbook_Server_Response.d.ts +1 -1
  29. package/esm/typings/execution/plugins/llm-execution-tools/remote/interfaces/RemoteServerOptions.d.ts +2 -1
  30. package/esm/typings/execution/plugins/llm-execution-tools/remote/startRemoteServer.d.ts +1 -1
  31. package/esm/typings/execution/plugins/script-execution-tools/python/PythonExecutionTools.d.ts +3 -2
  32. package/esm/typings/execution/plugins/script-execution-tools/typescript/TypescriptExecutionTools.d.ts +3 -2
  33. package/esm/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceTools.d.ts +3 -2
  34. package/esm/typings/execution/plugins/user-interface-execution-tools/simple-prompt/SimplePromptInterfaceTools.d.ts +3 -2
  35. package/esm/typings/execution/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +1 -1
  36. package/esm/typings/execution/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +1 -1
  37. package/esm/typings/execution/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +2 -2
  38. package/esm/typings/execution/translation/automatic-translate/translateMessages.d.ts +2 -2
  39. package/esm/typings/execution/utils/replaceParameters.d.ts +2 -2
  40. package/esm/typings/library/SimplePromptbookLibrary.d.ts +1 -1
  41. package/esm/typings/library/constructors/createPromptbookLibraryFromDirectory.d.ts +2 -2
  42. package/esm/typings/library/constructors/createPromptbookLibraryFromPromise.d.ts +2 -2
  43. package/esm/typings/library/constructors/createPromptbookLibraryFromSources.d.ts +2 -1
  44. package/esm/typings/library/constructors/createPromptbookLibraryFromUrl.d.ts +2 -2
  45. package/esm/typings/library/constructors/createPromptbookSublibrary.d.ts +1 -1
  46. package/esm/typings/types/Command.d.ts +5 -2
  47. package/esm/typings/types/Prompt.d.ts +4 -1
  48. package/esm/typings/types/PromptbookJson/PromptTemplateJson.d.ts +8 -1
  49. package/esm/typings/types/PromptbookJson/PromptbookJson.d.ts +2 -1
  50. package/esm/typings/types/TaskProgress.d.ts +2 -1
  51. package/esm/typings/types/execution-report/ExecutionReportJson.d.ts +2 -1
  52. package/esm/typings/types/execution-report/countWorkingDuration.d.ts +1 -1
  53. package/esm/typings/utils/emojis.d.ts +1 -1
  54. package/esm/typings/utils/expectation-counters/index.d.ts +2 -1
  55. package/esm/typings/utils/extractParameters.d.ts +2 -1
  56. package/esm/typings/utils/markdown/addAutoGeneratedSection.d.ts +2 -1
  57. package/esm/typings/utils/markdown/createMarkdownChart.d.ts +2 -2
  58. package/esm/typings/utils/markdown/createMarkdownTable.d.ts +2 -1
  59. package/esm/typings/utils/markdown/escapeMarkdownBlock.d.ts +1 -1
  60. package/esm/typings/utils/markdown/extractAllListItemsFromMarkdown.d.ts +2 -1
  61. package/esm/typings/utils/markdown/extractOneBlockFromMarkdown.d.ts +2 -2
  62. package/esm/typings/utils/markdown/removeContentComments.d.ts +2 -1
  63. package/esm/typings/utils/markdown/removeMarkdownFormatting.d.ts +1 -1
  64. package/esm/typings/utils/markdown-json/countMarkdownStructureDeepness.d.ts +1 -1
  65. package/esm/typings/utils/markdown-json/markdownToMarkdownStructure.d.ts +1 -1
  66. package/esm/typings/utils/normalization/isValidKeyword.d.ts +1 -1
  67. package/esm/typings/utils/normalization/parseKeywords.d.ts +1 -1
  68. package/esm/typings/utils/normalization/parseKeywordsFromString.d.ts +1 -1
  69. package/esm/typings/utils/normalization/searchKeywords.d.ts +1 -1
  70. package/esm/typings/utils/postprocessing/extractBlock.d.ts +1 -1
  71. package/package.json +1 -1
  72. package/umd/index.umd.js +733 -733
  73. package/umd/index.umd.js.map +1 -1
  74. package/umd/typings/conversion/prettify/prettifyPromptbookString.d.ts +1 -1
  75. package/umd/typings/conversion/prettify/renderPromptbookMermaid.d.ts +2 -1
  76. package/umd/typings/conversion/utils/extractParametersFromPromptTemplate.d.ts +3 -3
  77. package/umd/typings/conversion/utils/extractVariables.d.ts +2 -1
  78. package/umd/typings/conversion/validation/_importPromptbook.d.ts +2 -2
  79. package/umd/typings/execution/LlmExecutionTools.d.ts +4 -2
  80. package/umd/typings/execution/PromptResult.d.ts +5 -1
  81. package/umd/typings/execution/ScriptExecutionTools.d.ts +2 -1
  82. package/umd/typings/execution/UserInterfaceTools.d.ts +2 -1
  83. package/umd/typings/execution/createPromptbookExecutor.d.ts +3 -3
  84. package/umd/typings/execution/plugins/llm-execution-tools/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +4 -2
  85. package/umd/typings/execution/plugins/llm-execution-tools/anthropic-claude/anthropic-claude-models.d.ts +1 -1
  86. package/umd/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionTools.d.ts +4 -2
  87. package/umd/typings/execution/plugins/llm-execution-tools/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +2 -1
  88. package/umd/typings/execution/plugins/llm-execution-tools/mocked/MockedEchoLlmExecutionTools.d.ts +4 -2
  89. package/umd/typings/execution/plugins/llm-execution-tools/mocked/MockedFackedLlmExecutionTools.d.ts +4 -2
  90. package/umd/typings/execution/plugins/llm-execution-tools/mocked/fakeTextToExpectations.d.ts +1 -1
  91. package/umd/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionTools.d.ts +4 -2
  92. package/umd/typings/execution/plugins/llm-execution-tools/multiple/MultipleLlmExecutionToolsOptions.d.ts +2 -1
  93. package/umd/typings/execution/plugins/llm-execution-tools/openai/OpenAiExecutionTools.d.ts +4 -2
  94. package/umd/typings/execution/plugins/llm-execution-tools/openai/OpenAiExecutionToolsOptions.d.ts +1 -1
  95. package/umd/typings/execution/plugins/llm-execution-tools/openai/openai-models.d.ts +1 -1
  96. package/umd/typings/execution/plugins/llm-execution-tools/remote/RemoteLlmExecutionTools.d.ts +4 -2
  97. package/umd/typings/execution/plugins/llm-execution-tools/remote/RemoteLlmExecutionToolsOptions.d.ts +2 -1
  98. package/umd/typings/execution/plugins/llm-execution-tools/remote/interfaces/Promptbook_Server_Progress.d.ts +1 -1
  99. package/umd/typings/execution/plugins/llm-execution-tools/remote/interfaces/Promptbook_Server_Response.d.ts +1 -1
  100. package/umd/typings/execution/plugins/llm-execution-tools/remote/interfaces/RemoteServerOptions.d.ts +2 -1
  101. package/umd/typings/execution/plugins/llm-execution-tools/remote/startRemoteServer.d.ts +1 -1
  102. package/umd/typings/execution/plugins/script-execution-tools/python/PythonExecutionTools.d.ts +3 -2
  103. package/umd/typings/execution/plugins/script-execution-tools/typescript/TypescriptExecutionTools.d.ts +3 -2
  104. package/umd/typings/execution/plugins/user-interface-execution-tools/callback/CallbackInterfaceTools.d.ts +3 -2
  105. package/umd/typings/execution/plugins/user-interface-execution-tools/simple-prompt/SimplePromptInterfaceTools.d.ts +3 -2
  106. package/umd/typings/execution/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +1 -1
  107. package/umd/typings/execution/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +1 -1
  108. package/umd/typings/execution/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +2 -2
  109. package/umd/typings/execution/translation/automatic-translate/translateMessages.d.ts +2 -2
  110. package/umd/typings/execution/utils/replaceParameters.d.ts +2 -2
  111. package/umd/typings/library/SimplePromptbookLibrary.d.ts +1 -1
  112. package/umd/typings/library/constructors/createPromptbookLibraryFromDirectory.d.ts +2 -2
  113. package/umd/typings/library/constructors/createPromptbookLibraryFromPromise.d.ts +2 -2
  114. package/umd/typings/library/constructors/createPromptbookLibraryFromSources.d.ts +2 -1
  115. package/umd/typings/library/constructors/createPromptbookLibraryFromUrl.d.ts +2 -2
  116. package/umd/typings/library/constructors/createPromptbookSublibrary.d.ts +1 -1
  117. package/umd/typings/types/Command.d.ts +5 -2
  118. package/umd/typings/types/Prompt.d.ts +4 -1
  119. package/umd/typings/types/PromptbookJson/PromptTemplateJson.d.ts +8 -1
  120. package/umd/typings/types/PromptbookJson/PromptbookJson.d.ts +2 -1
  121. package/umd/typings/types/TaskProgress.d.ts +2 -1
  122. package/umd/typings/types/execution-report/ExecutionReportJson.d.ts +2 -1
  123. package/umd/typings/types/execution-report/countWorkingDuration.d.ts +1 -1
  124. package/umd/typings/utils/emojis.d.ts +1 -1
  125. package/umd/typings/utils/expectation-counters/index.d.ts +2 -1
  126. package/umd/typings/utils/extractParameters.d.ts +2 -1
  127. package/umd/typings/utils/markdown/addAutoGeneratedSection.d.ts +2 -1
  128. package/umd/typings/utils/markdown/createMarkdownChart.d.ts +2 -2
  129. package/umd/typings/utils/markdown/createMarkdownTable.d.ts +2 -1
  130. package/umd/typings/utils/markdown/escapeMarkdownBlock.d.ts +1 -1
  131. package/umd/typings/utils/markdown/extractAllListItemsFromMarkdown.d.ts +2 -1
  132. package/umd/typings/utils/markdown/extractOneBlockFromMarkdown.d.ts +2 -2
  133. package/umd/typings/utils/markdown/removeContentComments.d.ts +2 -1
  134. package/umd/typings/utils/markdown/removeMarkdownFormatting.d.ts +1 -1
  135. package/umd/typings/utils/markdown-json/countMarkdownStructureDeepness.d.ts +1 -1
  136. package/umd/typings/utils/markdown-json/markdownToMarkdownStructure.d.ts +1 -1
  137. package/umd/typings/utils/normalization/isValidKeyword.d.ts +1 -1
  138. package/umd/typings/utils/normalization/parseKeywords.d.ts +1 -1
  139. package/umd/typings/utils/normalization/parseKeywordsFromString.d.ts +1 -1
  140. package/umd/typings/utils/normalization/searchKeywords.d.ts +1 -1
  141. package/umd/typings/utils/postprocessing/extractBlock.d.ts +1 -1
package/umd/index.umd.js CHANGED
@@ -454,7 +454,7 @@
454
454
  /**
455
455
  * The version of the Promptbook library
456
456
  */
457
- var PROMPTBOOK_VERSION = '0.52.0-33';
457
+ var PROMPTBOOK_VERSION = '0.52.0';
458
458
 
459
459
  /**
460
460
  * Parses the template and returns the list of all parameter names
@@ -576,88 +576,108 @@
576
576
  * TODO: [🔣] If script require contentLanguage
577
577
  */
578
578
 
579
+ /* tslint:disable */
580
+ /*
581
+ TODO: Tests
582
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
583
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
584
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
585
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
586
+ */
587
+ function normalizeTo_SCREAMING_CASE(sentence) {
588
+ var e_1, _a;
589
+ var charType;
590
+ var lastCharType = 'OTHER';
591
+ var normalizedName = '';
592
+ try {
593
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
594
+ var char = sentence_1_1.value;
595
+ var normalizedChar = void 0;
596
+ if (/^[a-z]$/.test(char)) {
597
+ charType = 'LOWERCASE';
598
+ normalizedChar = char.toUpperCase();
599
+ }
600
+ else if (/^[A-Z]$/.test(char)) {
601
+ charType = 'UPPERCASE';
602
+ normalizedChar = char;
603
+ }
604
+ else if (/^[0-9]$/.test(char)) {
605
+ charType = 'NUMBER';
606
+ normalizedChar = char;
607
+ }
608
+ else if (/^\/$/.test(char)) {
609
+ charType = 'SLASH';
610
+ normalizedChar = char;
611
+ }
612
+ else {
613
+ charType = 'OTHER';
614
+ normalizedChar = '_';
615
+ }
616
+ if (charType !== lastCharType &&
617
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
618
+ !(lastCharType === 'NUMBER') &&
619
+ !(charType === 'NUMBER')) {
620
+ normalizedName += '_';
621
+ }
622
+ normalizedName += normalizedChar;
623
+ lastCharType = charType;
624
+ }
625
+ }
626
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
627
+ finally {
628
+ try {
629
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
630
+ }
631
+ finally { if (e_1) throw e_1.error; }
632
+ }
633
+ normalizedName = normalizedName.replace(/_+/g, '_');
634
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
635
+ normalizedName = normalizedName.replace(/^_/, '');
636
+ normalizedName = normalizedName.replace(/_$/, '');
637
+ return normalizedName;
638
+ }
579
639
  /**
580
- * Removes emojis from a string and fix whitespaces
640
+ * TODO: [🌺] Use some intermediate util splitWords
641
+ */
642
+
643
+ /**
644
+ * Execution type describes the way how the block is executed
581
645
  *
582
- * @param text with emojis
583
- * @returns text without emojis
646
+ * @see https://github.com/webgptorg/promptbook#execution-type
584
647
  */
585
- function removeEmojis(text) {
586
- // Replace emojis (and also ZWJ sequence) with hyphens
587
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
588
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
589
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
590
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
591
- return text;
592
- }
648
+ var ExecutionTypes = [
649
+ 'PROMPT_TEMPLATE',
650
+ 'SIMPLE_TEMPLATE',
651
+ 'SCRIPT',
652
+ 'PROMPT_DIALOG',
653
+ // <- [🥻] Insert here when making new command
654
+ ];
593
655
 
594
656
  /**
595
- * Function normalizes title to name which can be used as identifier
657
+ * Units of text measurement
658
+ */
659
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
660
+ /**
661
+ * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
662
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
663
+ * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
596
664
  */
597
- function titleToName(value) {
598
- value = removeEmojis(value);
599
- value = normalizeToKebabCase(value);
600
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
601
- return value;
602
- }
603
665
 
604
666
  /**
605
- * Creates a Mermaid graph based on the promptbook
667
+ * Removes Markdown formatting tags from a string.
606
668
  *
607
- * Note: The result is not wrapped in a Markdown code block
669
+ * @param {string} str - The string to remove Markdown tags from.
670
+ * @returns {string} The input string with all Markdown tags removed.
608
671
  */
609
- function renderPromptbookMermaid(promptbookJson, options) {
610
- var _a = (options || {}).linkPromptTemplate, linkPromptTemplate = _a === void 0 ? function () { return null; } : _a;
611
- var parameterNameToTemplateName = function (parameterName) {
612
- var parameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
613
- if (!parameter) {
614
- throw new UnexpectedError("Could not find {".concat(parameterName, "}"));
615
- }
616
- if (parameter.isInput) {
617
- return 'input';
618
- }
619
- var template = promptbookJson.promptTemplates.find(function (template) { return template.resultingParameterName === parameterName; });
620
- if (!template) {
621
- throw new Error("Could not find template for {".concat(parameterName, "}"));
622
- }
623
- return normalizeTo_camelCase('template-' + titleToName(template.title));
624
- };
625
- var promptbookMermaid = spaceTrim.spaceTrim(function (block) { return "\n\n %% \uD83D\uDD2E Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually\n\n flowchart LR\n subgraph \"".concat(promptbookJson.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson.promptTemplates
626
- .flatMap(function (_a) {
627
- var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
628
- return __spreadArray([
629
- "".concat(parameterNameToTemplateName(resultingParameterName), "(\"").concat(title, "\")")
630
- ], __read(dependentParameterNames.map(function (dependentParameterName) {
631
- return "".concat(parameterNameToTemplateName(dependentParameterName), "--\"{").concat(dependentParameterName, "}\"-->").concat(parameterNameToTemplateName(resultingParameterName));
632
- })), false);
633
- })
634
- .join('\n')), "\n\n ").concat(block(promptbookJson.parameters
635
- .filter(function (_a) {
636
- var isOutput = _a.isOutput;
637
- return isOutput;
638
- })
639
- .map(function (_a) {
640
- var name = _a.name;
641
- return "".concat(parameterNameToTemplateName(name), "--\"{").concat(name, "}\"-->output");
642
- })
643
- .join('\n')), "\n output((Output)):::output\n\n ").concat(block(promptbookJson.promptTemplates
644
- .map(function (promptTemplate) {
645
- var link = linkPromptTemplate(promptTemplate);
646
- if (link === null) {
647
- return '';
648
- }
649
- var href = link.href, title = link.title;
650
- var templateName = parameterNameToTemplateName(promptTemplate.resultingParameterName);
651
- return "click ".concat(templateName, " href \"").concat(href, "\" \"").concat(title, "\";");
652
- })
653
- .filter(function (line) { return line !== ''; })
654
- .join('\n')), "\n\n classDef input color: grey;\n classDef output color: grey;\n\n end;\n\n "); });
655
- return promptbookMermaid;
672
+ function removeMarkdownFormatting(str) {
673
+ // Remove bold formatting
674
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
675
+ // Remove italic formatting
676
+ str = str.replace(/\*(.*?)\*/g, '$1');
677
+ // Remove code formatting
678
+ str = str.replace(/`(.*?)`/g, '$1');
679
+ return str;
656
680
  }
657
- /**
658
- * TODO: Maybe use some Mermaid library instead of string templating
659
- * TODO: [🕌] When more than 2 functionalities, split into separate functions
660
- */
661
681
 
662
682
  /**
663
683
  * Function parseNumber will parse number from string
@@ -727,146 +747,249 @@
727
747
  */
728
748
 
729
749
  /**
730
- * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
731
- */
732
- var PromptbookLogicError = /** @class */ (function (_super) {
733
- __extends(PromptbookLogicError, _super);
734
- function PromptbookLogicError(message) {
735
- var _this = _super.call(this, message) || this;
736
- _this.name = 'PromptbookLogicError';
737
- Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
738
- return _this;
739
- }
740
- return PromptbookLogicError;
741
- }(Error));
742
-
743
- /**
744
- * This error occurs during the parameter replacement in the template
745
- *
746
- * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
747
- */
748
- var TemplateError = /** @class */ (function (_super) {
749
- __extends(TemplateError, _super);
750
- function TemplateError(message) {
751
- var _this = _super.call(this, message) || this;
752
- _this.name = 'TemplateError';
753
- Object.setPrototypeOf(_this, TemplateError.prototype);
754
- return _this;
755
- }
756
- return TemplateError;
757
- }(Error));
758
-
759
- /**
760
- * Replaces parameters in template with values from parameters object
750
+ * Parses one line of ul/ol to command
761
751
  *
762
- * @param template the template with parameters in {curly} braces
763
- * @param parameters the object with parameters
764
- * @returns the template with replaced parameters
765
- * @throws {TemplateError} if parameter is not defined, not closed, or not opened
752
+ * @returns parsed command object
753
+ * @throws {PromptbookSyntaxError} if the command is invalid
766
754
  *
767
- * @private within the createPromptbookExecutor
755
+ * @private within the promptbookStringToJson
768
756
  */
769
- function replaceParameters(template, parameters) {
770
- var replacedTemplate = template;
771
- var match;
772
- var loopLimit = LOOP_LIMIT;
773
- var _loop_1 = function () {
774
- if (loopLimit-- < 0) {
775
- throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
776
- }
777
- var precol = match.groups.precol;
778
- var parameterName = match.groups.parameterName;
779
- if (parameterName === '') {
780
- return "continue";
757
+ function parseCommand(listItem) {
758
+ var e_1, _a;
759
+ if (listItem.includes('\n') || listItem.includes('\r')) {
760
+ throw new PromptbookSyntaxError('Command can not contain new line characters:');
761
+ }
762
+ var type = listItem.trim();
763
+ type = type.split('`').join('');
764
+ type = type.split('"').join('');
765
+ type = type.split("'").join('');
766
+ type = type.split('~').join('');
767
+ type = type.split('[').join('');
768
+ type = type.split(']').join('');
769
+ type = type.split('(').join('');
770
+ type = type.split(')').join('');
771
+ type = normalizeTo_SCREAMING_CASE(type);
772
+ type = type.split('DIALOGUE').join('DIALOG');
773
+ var listItemParts = listItem
774
+ .split(' ')
775
+ .map(function (part) { return part.trim(); })
776
+ .filter(function (item) { return item !== ''; })
777
+ .filter(function (item) { return !/^PTBK$/i.test(item); })
778
+ .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
779
+ .map(removeMarkdownFormatting);
780
+ if (type.startsWith('URL') ||
781
+ type.startsWith('PTBK_URL') ||
782
+ type.startsWith('PTBKURL') ||
783
+ type.startsWith('PROMPTBOOK_URL') ||
784
+ type.startsWith('PROMPTBOOKURL') ||
785
+ type.startsWith('HTTPS')) {
786
+ if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
787
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
781
788
  }
782
- if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
783
- throw new TemplateError('Parameter is already opened or not closed');
789
+ var promptbookUrlString = listItemParts.pop();
790
+ var promptbookUrl = new URL(promptbookUrlString);
791
+ if (promptbookUrl.protocol !== 'https:') {
792
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
784
793
  }
785
- if (parameters[parameterName] === undefined) {
786
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
794
+ if (promptbookUrl.hash !== '') {
795
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
787
796
  }
788
- var parameterValue = parameters[parameterName];
789
- if (parameterValue === undefined) {
790
- throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
797
+ return {
798
+ type: 'PROMPTBOOK_URL',
799
+ promptbookUrl: promptbookUrl,
800
+ };
801
+ }
802
+ else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
803
+ if (listItemParts.length !== 2) {
804
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
791
805
  }
792
- parameterValue = parameterValue.toString();
793
- if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
794
- parameterValue = parameterValue
795
- .split('\n')
796
- .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
797
- .join('\n');
806
+ var promptbookVersion = listItemParts.pop();
807
+ // TODO: Validate version
808
+ return {
809
+ type: 'PROMPTBOOK_VERSION',
810
+ promptbookVersion: promptbookVersion,
811
+ };
812
+ }
813
+ else if (type.startsWith('EXECUTE') ||
814
+ type.startsWith('EXEC') ||
815
+ type.startsWith('PROMPT_DIALOG') ||
816
+ type.startsWith('SIMPLE_TEMPLATE')) {
817
+ var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
818
+ if (executionTypes.length !== 1) {
819
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
798
820
  }
799
- replacedTemplate =
800
- replacedTemplate.substring(0, match.index + precol.length) +
801
- parameterValue +
802
- replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
803
- };
804
- while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
805
- .exec(replacedTemplate))) {
806
- _loop_1();
821
+ return {
822
+ type: 'EXECUTE',
823
+ executionType: executionTypes[0],
824
+ };
807
825
  }
808
- // [💫] Check if there are parameters that are not closed properly
809
- if (/{\w+$/.test(replacedTemplate)) {
810
- throw new TemplateError('Parameter is not closed');
826
+ else if (type.startsWith('MODEL')) {
827
+ // TODO: Make this more elegant and dynamically
828
+ if (type.startsWith('MODEL_VARIANT')) {
829
+ if (type === 'MODEL_VARIANT_CHAT') {
830
+ return {
831
+ type: 'MODEL',
832
+ key: 'modelVariant',
833
+ value: 'CHAT',
834
+ };
835
+ }
836
+ else if (type === 'MODEL_VARIANT_COMPLETION') {
837
+ return {
838
+ type: 'MODEL',
839
+ key: 'modelVariant',
840
+ value: 'COMPLETION',
841
+ };
842
+ }
843
+ else {
844
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
845
+ }
846
+ }
847
+ if (type.startsWith('MODEL_NAME')) {
848
+ return {
849
+ type: 'MODEL',
850
+ key: 'modelName',
851
+ value: listItemParts.pop(),
852
+ };
853
+ }
854
+ else {
855
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
856
+ }
811
857
  }
812
- // [💫] Check if there are parameters that are not opened properly
813
- if (/^\w+}/.test(replacedTemplate)) {
814
- throw new TemplateError('Parameter is not opened');
858
+ else if (type.startsWith('PARAM') ||
859
+ type.startsWith('INPUT_PARAM') ||
860
+ type.startsWith('OUTPUT_PARAM') ||
861
+ listItem.startsWith('{') ||
862
+ listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
863
+ var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
864
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
865
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
866
+ }
867
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
868
+ var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
869
+ if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
870
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
871
+ }
872
+ var isInput = type.startsWith('INPUT');
873
+ var isOutput = type.startsWith('OUTPUT');
874
+ if (listItem.startsWith('> {')) {
875
+ isInput = false;
876
+ isOutput = false;
877
+ }
878
+ return {
879
+ type: 'PARAMETER',
880
+ parameterName: parameterName,
881
+ parameterDescription: parameterDescription.trim() || null,
882
+ isInput: isInput,
883
+ isOutput: isOutput,
884
+ };
815
885
  }
816
- return replacedTemplate;
817
- }
818
-
819
- /**
820
- * Counts number of characters in the text
821
- */
822
- function countCharacters(text) {
823
- // Remove null characters
824
- text = text.replace(/\0/g, '');
825
- // Replace emojis (and also ZWJ sequence) with hyphens
826
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
827
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
828
- text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
829
- return text.length;
830
- }
831
-
832
- /**
833
- * Counts number of lines in the text
834
- */
835
- function countLines(text) {
836
- if (text === '') {
837
- return 0;
886
+ else if (type.startsWith('JOKER')) {
887
+ if (listItemParts.length !== 2) {
888
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
889
+ }
890
+ var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
891
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
892
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
893
+ }
894
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
895
+ var parameterName = parametersMatch.groups.parameterName;
896
+ return {
897
+ type: 'JOKER',
898
+ parameterName: parameterName,
899
+ };
900
+ }
901
+ else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
902
+ if (listItemParts.length !== 2) {
903
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
904
+ }
905
+ var functionName = listItemParts.pop();
906
+ return {
907
+ type: 'POSTPROCESS',
908
+ functionName: functionName,
909
+ };
910
+ }
911
+ else if (type.startsWith('EXPECT_JSON')) {
912
+ return {
913
+ type: 'EXPECT_FORMAT',
914
+ format: 'JSON',
915
+ };
916
+ // [🥤]
917
+ }
918
+ else if (type.startsWith('EXPECT')) {
919
+ try {
920
+ listItemParts.shift();
921
+ var sign = void 0;
922
+ var signRaw = listItemParts.shift();
923
+ if (/^exact/i.test(signRaw)) {
924
+ sign = 'EXACTLY';
925
+ }
926
+ else if (/^min/i.test(signRaw)) {
927
+ sign = 'MINIMUM';
928
+ }
929
+ else if (/^max/i.test(signRaw)) {
930
+ sign = 'MAXIMUM';
931
+ }
932
+ else {
933
+ throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
934
+ }
935
+ var amountRaw = listItemParts.shift();
936
+ var amount = parseNumber(amountRaw);
937
+ if (amount < 0) {
938
+ throw new PromptbookSyntaxError('Amount must be positive number or zero');
939
+ }
940
+ if (amount !== Math.floor(amount)) {
941
+ throw new PromptbookSyntaxError('Amount must be whole number');
942
+ }
943
+ var unitRaw = listItemParts.shift();
944
+ var unit = undefined;
945
+ try {
946
+ for (var EXPECTATION_UNITS_1 = __values(EXPECTATION_UNITS), EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next(); !EXPECTATION_UNITS_1_1.done; EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next()) {
947
+ var existingUnit = EXPECTATION_UNITS_1_1.value;
948
+ var existingUnitText = existingUnit;
949
+ existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
950
+ if (existingUnitText === 'CHARACTER') {
951
+ existingUnitText = 'CHAR';
952
+ }
953
+ if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
954
+ new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
955
+ if (unit !== undefined) {
956
+ throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
957
+ }
958
+ unit = existingUnit;
959
+ }
960
+ }
961
+ }
962
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
963
+ finally {
964
+ try {
965
+ if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
966
+ }
967
+ finally { if (e_1) throw e_1.error; }
968
+ }
969
+ if (unit === undefined) {
970
+ throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
971
+ }
972
+ return {
973
+ type: 'EXPECT_AMOUNT',
974
+ sign: sign,
975
+ unit: unit,
976
+ amount: amount,
977
+ };
978
+ }
979
+ catch (error) {
980
+ if (!(error instanceof Error)) {
981
+ throw error;
982
+ }
983
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
984
+ }
985
+ /*
986
+ } else if (type.startsWith('__________________')) {
987
+ // <- [🥻] Insert here when making new command
988
+ */
989
+ }
990
+ else {
991
+ throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - PROMPTBOOK_URL <url>\n - PROMPTBOOK_VERSION <version>\n - EXECUTE PROMPT TEMPLATE\n - EXECUTE SIMPLE TEMPLATE\n - SIMPLE TEMPLATE\n - EXECUTE SCRIPT\n - EXECUTE PROMPT_DIALOG'\n - PROMPT_DIALOG'\n - MODEL NAME <name>\n - MODEL VARIANT <\"Chat\"|\"Completion\">\n - INPUT PARAM {<name>} <description>\n - OUTPUT PARAM {<name>} <description>\n - POSTPROCESS `{functionName}`\n - JOKER {<name>}\n - EXPECT JSON\n - EXPECT <\"Exactly\"|\"Min\"|\"Max\"> <number> <\"Chars\"|\"Words\"|\"Sentences\"|\"Paragraphs\"|\"Pages\">\n\n ")));
838
992
  }
839
- return text.split('\n').length;
840
- }
841
-
842
- /**
843
- * Counts number of pages in the text
844
- */
845
- function countPages(text) {
846
- var sentencesPerPage = 5; // Assuming each page has 5 sentences
847
- var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
848
- var pageCount = Math.ceil(sentences.length / sentencesPerPage);
849
- return pageCount;
850
- }
851
-
852
- /**
853
- * Counts number of paragraphs in the text
854
- */
855
- function countParagraphs(text) {
856
- return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
857
- }
858
-
859
- /**
860
- * Split text into sentences
861
- */
862
- function splitIntoSentences(text) {
863
- return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
864
- }
865
- /**
866
- * Counts number of sentences in the text
867
- */
868
- function countSentences(text) {
869
- return splitIntoSentences(text).length;
870
993
  }
871
994
 
872
995
  var defaultDiacriticsRemovalMap = [
@@ -1121,187 +1244,12 @@
1121
1244
  });
1122
1245
  }
1123
1246
 
1124
- /**
1125
- * Counts number of words in the text
1126
- */
1127
- function countWords(text) {
1128
- text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
1129
- text = removeDiacritics(text);
1130
- return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
1131
- }
1132
-
1133
- /**
1134
- * Index of all counter functions
1135
- */
1136
- var CountUtils = {
1137
- CHARACTERS: countCharacters,
1138
- WORDS: countWords,
1139
- SENTENCES: countSentences,
1140
- PARAGRAPHS: countParagraphs,
1141
- LINES: countLines,
1142
- PAGES: countPages,
1143
- };
1144
-
1145
- /**
1146
- * Function isValidJsonString will tell you if the string is valid JSON or not
1147
- */
1148
- function isValidJsonString(value) {
1149
- try {
1150
- JSON.parse(value);
1151
- return true;
1152
- }
1153
- catch (error) {
1154
- if (!(error instanceof Error)) {
1155
- throw error;
1156
- }
1157
- if (error.message.includes('Unexpected token')) {
1158
- return false;
1159
- }
1160
- return false;
1161
- }
1162
- }
1163
-
1164
- /**
1165
- * Removes Markdown formatting tags from a string.
1166
- *
1167
- * @param {string} str - The string to remove Markdown tags from.
1168
- * @returns {string} The input string with all Markdown tags removed.
1169
- */
1170
- function removeMarkdownFormatting(str) {
1171
- // Remove bold formatting
1172
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
1173
- // Remove italic formatting
1174
- str = str.replace(/\*(.*?)\*/g, '$1');
1175
- // Remove code formatting
1176
- str = str.replace(/`(.*?)`/g, '$1');
1177
- return str;
1178
- }
1179
-
1180
- /* tslint:disable */
1181
- /*
1182
- TODO: Tests
1183
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
1184
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
1185
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
1186
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
1187
- */
1188
- function normalizeTo_SCREAMING_CASE(sentence) {
1189
- var e_1, _a;
1190
- var charType;
1191
- var lastCharType = 'OTHER';
1192
- var normalizedName = '';
1193
- try {
1194
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1195
- var char = sentence_1_1.value;
1196
- var normalizedChar = void 0;
1197
- if (/^[a-z]$/.test(char)) {
1198
- charType = 'LOWERCASE';
1199
- normalizedChar = char.toUpperCase();
1200
- }
1201
- else if (/^[A-Z]$/.test(char)) {
1202
- charType = 'UPPERCASE';
1203
- normalizedChar = char;
1204
- }
1205
- else if (/^[0-9]$/.test(char)) {
1206
- charType = 'NUMBER';
1207
- normalizedChar = char;
1208
- }
1209
- else if (/^\/$/.test(char)) {
1210
- charType = 'SLASH';
1211
- normalizedChar = char;
1212
- }
1213
- else {
1214
- charType = 'OTHER';
1215
- normalizedChar = '_';
1216
- }
1217
- if (charType !== lastCharType &&
1218
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1219
- !(lastCharType === 'NUMBER') &&
1220
- !(charType === 'NUMBER')) {
1221
- normalizedName += '_';
1222
- }
1223
- normalizedName += normalizedChar;
1224
- lastCharType = charType;
1225
- }
1226
- }
1227
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1228
- finally {
1229
- try {
1230
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1231
- }
1232
- finally { if (e_1) throw e_1.error; }
1233
- }
1234
- normalizedName = normalizedName.replace(/_+/g, '_');
1235
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
1236
- normalizedName = normalizedName.replace(/^_/, '');
1237
- normalizedName = normalizedName.replace(/_$/, '');
1238
- return normalizedName;
1239
- }
1240
- /**
1241
- * TODO: [🌺] Use some intermediate util splitWords
1242
- */
1243
-
1244
1247
  /* tslint:disable */
1245
1248
  function normalizeToKebabCase(sentence) {
1246
1249
  var e_1, _a;
1247
1250
  sentence = removeDiacritics(sentence);
1248
1251
  var charType;
1249
- var lastCharType = 'OTHER';
1250
- var normalizedName = '';
1251
- try {
1252
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1253
- var char = sentence_1_1.value;
1254
- var normalizedChar = void 0;
1255
- if (/^[a-z]$/.test(char)) {
1256
- charType = 'LOWERCASE';
1257
- normalizedChar = char;
1258
- }
1259
- else if (/^[A-Z]$/.test(char)) {
1260
- charType = 'UPPERCASE';
1261
- normalizedChar = char.toLowerCase();
1262
- }
1263
- else if (/^[0-9]$/.test(char)) {
1264
- charType = 'NUMBER';
1265
- normalizedChar = char;
1266
- }
1267
- else if (/^\/$/.test(char)) {
1268
- charType = 'SLASH';
1269
- normalizedChar = char;
1270
- }
1271
- else {
1272
- charType = 'OTHER';
1273
- normalizedChar = '-';
1274
- }
1275
- if (charType !== lastCharType &&
1276
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1277
- !(lastCharType === 'NUMBER') &&
1278
- !(charType === 'NUMBER')) {
1279
- normalizedName += '-';
1280
- }
1281
- normalizedName += normalizedChar;
1282
- lastCharType = charType;
1283
- }
1284
- }
1285
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1286
- finally {
1287
- try {
1288
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1289
- }
1290
- finally { if (e_1) throw e_1.error; }
1291
- }
1292
- normalizedName = normalizedName.split(/-+/g).join('-');
1293
- normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1294
- normalizedName = normalizedName.replace(/^-/, '');
1295
- normalizedName = normalizedName.replace(/-$/, '');
1296
- return normalizedName;
1297
- }
1298
-
1299
- /* tslint:disable */
1300
- function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1301
- var e_1, _a;
1302
- if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
1303
- var charType;
1304
- var lastCharType = null;
1252
+ var lastCharType = 'OTHER';
1305
1253
  var normalizedName = '';
1306
1254
  try {
1307
1255
  for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
@@ -1313,311 +1261,67 @@
1313
1261
  }
1314
1262
  else if (/^[A-Z]$/.test(char)) {
1315
1263
  charType = 'UPPERCASE';
1316
- normalizedChar = char.toLowerCase();
1317
- }
1318
- else if (/^[0-9]$/.test(char)) {
1319
- charType = 'NUMBER';
1320
- normalizedChar = char;
1321
- }
1322
- else {
1323
- charType = 'OTHER';
1324
- normalizedChar = '';
1325
- }
1326
- if (!lastCharType) {
1327
- if (__firstLetterCapital) {
1328
- normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1329
- }
1330
- }
1331
- else if (charType !== lastCharType &&
1332
- !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1333
- !(lastCharType === 'NUMBER') &&
1334
- !(charType === 'NUMBER')) {
1335
- normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
1336
- }
1337
- normalizedName += normalizedChar;
1338
- lastCharType = charType;
1339
- }
1340
- }
1341
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1342
- finally {
1343
- try {
1344
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1345
- }
1346
- finally { if (e_1) throw e_1.error; }
1347
- }
1348
- return normalizedName;
1349
- }
1350
- /**
1351
- * TODO: [🌺] Use some intermediate util splitWords
1352
- */
1353
-
1354
- /**
1355
- * Execution type describes the way how the block is executed
1356
- *
1357
- * @see https://github.com/webgptorg/promptbook#execution-type
1358
- */
1359
- var ExecutionTypes = [
1360
- 'PROMPT_TEMPLATE',
1361
- 'SIMPLE_TEMPLATE',
1362
- 'SCRIPT',
1363
- 'PROMPT_DIALOG',
1364
- // <- [🥻] Insert here when making new command
1365
- ];
1366
-
1367
- /**
1368
- * Units of text measurement
1369
- */
1370
- var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
1371
- /**
1372
- * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
1373
- * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
1374
- * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
1375
- */
1376
-
1377
- /**
1378
- * Parses one line of ul/ol to command
1379
- *
1380
- * @returns parsed command object
1381
- * @throws {PromptbookSyntaxError} if the command is invalid
1382
- *
1383
- * @private within the promptbookStringToJson
1384
- */
1385
- function parseCommand(listItem) {
1386
- var e_1, _a;
1387
- if (listItem.includes('\n') || listItem.includes('\r')) {
1388
- throw new PromptbookSyntaxError('Command can not contain new line characters:');
1389
- }
1390
- var type = listItem.trim();
1391
- type = type.split('`').join('');
1392
- type = type.split('"').join('');
1393
- type = type.split("'").join('');
1394
- type = type.split('~').join('');
1395
- type = type.split('[').join('');
1396
- type = type.split(']').join('');
1397
- type = type.split('(').join('');
1398
- type = type.split(')').join('');
1399
- type = normalizeTo_SCREAMING_CASE(type);
1400
- type = type.split('DIALOGUE').join('DIALOG');
1401
- var listItemParts = listItem
1402
- .split(' ')
1403
- .map(function (part) { return part.trim(); })
1404
- .filter(function (item) { return item !== ''; })
1405
- .filter(function (item) { return !/^PTBK$/i.test(item); })
1406
- .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
1407
- .map(removeMarkdownFormatting);
1408
- if (type.startsWith('URL') ||
1409
- type.startsWith('PTBK_URL') ||
1410
- type.startsWith('PTBKURL') ||
1411
- type.startsWith('PROMPTBOOK_URL') ||
1412
- type.startsWith('PROMPTBOOKURL') ||
1413
- type.startsWith('HTTPS')) {
1414
- if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
1415
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
1416
- }
1417
- var promptbookUrlString = listItemParts.pop();
1418
- var promptbookUrl = new URL(promptbookUrlString);
1419
- if (promptbookUrl.protocol !== 'https:') {
1420
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
1421
- }
1422
- if (promptbookUrl.hash !== '') {
1423
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n URL must not contain hash\n Hash is used for identification of the prompt template in the pipeline\n ")));
1424
- }
1425
- return {
1426
- type: 'PROMPTBOOK_URL',
1427
- promptbookUrl: promptbookUrl,
1428
- };
1429
- }
1430
- else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
1431
- if (listItemParts.length !== 2) {
1432
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
1433
- }
1434
- var promptbookVersion = listItemParts.pop();
1435
- // TODO: Validate version
1436
- return {
1437
- type: 'PROMPTBOOK_VERSION',
1438
- promptbookVersion: promptbookVersion,
1439
- };
1440
- }
1441
- else if (type.startsWith('EXECUTE') ||
1442
- type.startsWith('EXEC') ||
1443
- type.startsWith('PROMPT_DIALOG') ||
1444
- type.startsWith('SIMPLE_TEMPLATE')) {
1445
- var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
1446
- if (executionTypes.length !== 1) {
1447
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown execution type in command:\n\n - ".concat(listItem, "\n\n Supported execution types are:\n ").concat(block(ExecutionTypes.join(', ')), "\n "); }));
1448
- }
1449
- return {
1450
- type: 'EXECUTE',
1451
- executionType: executionTypes[0],
1452
- };
1453
- }
1454
- else if (type.startsWith('MODEL')) {
1455
- // TODO: Make this more elegant and dynamically
1456
- if (type.startsWith('MODEL_VARIANT')) {
1457
- if (type === 'MODEL_VARIANT_CHAT') {
1458
- return {
1459
- type: 'MODEL',
1460
- key: 'modelVariant',
1461
- value: 'CHAT',
1462
- };
1463
- }
1464
- else if (type === 'MODEL_VARIANT_COMPLETION') {
1465
- return {
1466
- type: 'MODEL',
1467
- key: 'modelVariant',
1468
- value: 'COMPLETION',
1469
- };
1470
- }
1471
- else {
1472
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model variant in command:\n\n - ".concat(listItem, "\n\n Supported variants are:\n ").concat(block(['CHAT', 'COMPLETION'].join(', ')), "\n "); }));
1473
- }
1474
- }
1475
- if (type.startsWith('MODEL_NAME')) {
1476
- return {
1477
- type: 'MODEL',
1478
- key: 'modelName',
1479
- value: listItemParts.pop(),
1480
- };
1481
- }
1482
- else {
1483
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim(function (block) { return "\n Unknown model key in command:\n\n - ".concat(listItem, "\n\n Supported model keys are:\n ").concat(block(['variant', 'name'].join(', ')), "\n\n Example:\n\n - MODEL VARIANT Chat\n - MODEL NAME gpt-4\n "); }));
1484
- }
1485
- }
1486
- else if (type.startsWith('PARAM') ||
1487
- type.startsWith('INPUT_PARAM') ||
1488
- type.startsWith('OUTPUT_PARAM') ||
1489
- listItem.startsWith('{') ||
1490
- listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
1491
- var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
1492
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
1493
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1494
- }
1495
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1496
- var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
1497
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
1498
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
1499
- }
1500
- var isInput = type.startsWith('INPUT');
1501
- var isOutput = type.startsWith('OUTPUT');
1502
- if (listItem.startsWith('> {')) {
1503
- isInput = false;
1504
- isOutput = false;
1505
- }
1506
- return {
1507
- type: 'PARAMETER',
1508
- parameterName: parameterName,
1509
- parameterDescription: parameterDescription.trim() || null,
1510
- isInput: isInput,
1511
- isOutput: isOutput,
1512
- };
1513
- }
1514
- else if (type.startsWith('JOKER')) {
1515
- if (listItemParts.length !== 2) {
1516
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
1517
- }
1518
- var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
1519
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
1520
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
1521
- }
1522
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1523
- var parameterName = parametersMatch.groups.parameterName;
1524
- return {
1525
- type: 'JOKER',
1526
- parameterName: parameterName,
1527
- };
1528
- }
1529
- else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
1530
- if (listItemParts.length !== 2) {
1531
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
1532
- }
1533
- var functionName = listItemParts.pop();
1534
- return {
1535
- type: 'POSTPROCESS',
1536
- functionName: functionName,
1537
- };
1538
- }
1539
- else if (type.startsWith('EXPECT_JSON')) {
1540
- return {
1541
- type: 'EXPECT_FORMAT',
1542
- format: 'JSON',
1543
- };
1544
- // [🥤]
1545
- }
1546
- else if (type.startsWith('EXPECT')) {
1547
- try {
1548
- listItemParts.shift();
1549
- var sign = void 0;
1550
- var signRaw = listItemParts.shift();
1551
- if (/^exact/i.test(signRaw)) {
1552
- sign = 'EXACTLY';
1553
- }
1554
- else if (/^min/i.test(signRaw)) {
1555
- sign = 'MINIMUM';
1556
- }
1557
- else if (/^max/i.test(signRaw)) {
1558
- sign = 'MAXIMUM';
1559
- }
1560
- else {
1561
- throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
1562
- }
1563
- var amountRaw = listItemParts.shift();
1564
- var amount = parseNumber(amountRaw);
1565
- if (amount < 0) {
1566
- throw new PromptbookSyntaxError('Amount must be positive number or zero');
1567
- }
1568
- if (amount !== Math.floor(amount)) {
1569
- throw new PromptbookSyntaxError('Amount must be whole number');
1264
+ normalizedChar = char.toLowerCase();
1570
1265
  }
1571
- var unitRaw = listItemParts.shift();
1572
- var unit = undefined;
1573
- try {
1574
- for (var EXPECTATION_UNITS_1 = __values(EXPECTATION_UNITS), EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next(); !EXPECTATION_UNITS_1_1.done; EXPECTATION_UNITS_1_1 = EXPECTATION_UNITS_1.next()) {
1575
- var existingUnit = EXPECTATION_UNITS_1_1.value;
1576
- var existingUnitText = existingUnit;
1577
- existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
1578
- if (existingUnitText === 'CHARACTER') {
1579
- existingUnitText = 'CHAR';
1580
- }
1581
- if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
1582
- new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
1583
- if (unit !== undefined) {
1584
- throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
1585
- }
1586
- unit = existingUnit;
1587
- }
1588
- }
1266
+ else if (/^[0-9]$/.test(char)) {
1267
+ charType = 'NUMBER';
1268
+ normalizedChar = char;
1589
1269
  }
1590
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1591
- finally {
1592
- try {
1593
- if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
1594
- }
1595
- finally { if (e_1) throw e_1.error; }
1270
+ else if (/^\/$/.test(char)) {
1271
+ charType = 'SLASH';
1272
+ normalizedChar = char;
1596
1273
  }
1597
- if (unit === undefined) {
1598
- throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
1274
+ else {
1275
+ charType = 'OTHER';
1276
+ normalizedChar = '-';
1599
1277
  }
1600
- return {
1601
- type: 'EXPECT_AMOUNT',
1602
- sign: sign,
1603
- unit: unit,
1604
- amount: amount,
1605
- };
1606
- }
1607
- catch (error) {
1608
- if (!(error instanceof Error)) {
1609
- throw error;
1278
+ if (charType !== lastCharType &&
1279
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1280
+ !(lastCharType === 'NUMBER') &&
1281
+ !(charType === 'NUMBER')) {
1282
+ normalizedName += '-';
1610
1283
  }
1611
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
1284
+ normalizedName += normalizedChar;
1285
+ lastCharType = charType;
1612
1286
  }
1613
- /*
1614
- } else if (type.startsWith('__________________')) {
1615
- // <- [🥻] Insert here when making new command
1616
- */
1617
1287
  }
1618
- else {
1619
- throw new PromptbookSyntaxError(spaceTrim.spaceTrim("\n Unknown command:\n\n - ".concat(listItem, "\n\n Supported commands are:\n - PROMPTBOOK_URL <url>\n - PROMPTBOOK_VERSION <version>\n - EXECUTE PROMPT TEMPLATE\n - EXECUTE SIMPLE TEMPLATE\n - SIMPLE TEMPLATE\n - EXECUTE SCRIPT\n - EXECUTE PROMPT_DIALOG'\n - PROMPT_DIALOG'\n - MODEL NAME <name>\n - MODEL VARIANT <\"Chat\"|\"Completion\">\n - INPUT PARAM {<name>} <description>\n - OUTPUT PARAM {<name>} <description>\n - POSTPROCESS `{functionName}`\n - JOKER {<name>}\n - EXPECT JSON\n - EXPECT <\"Exactly\"|\"Min\"|\"Max\"> <number> <\"Chars\"|\"Words\"|\"Sentences\"|\"Paragraphs\"|\"Pages\">\n\n ")));
1288
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1289
+ finally {
1290
+ try {
1291
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1292
+ }
1293
+ finally { if (e_1) throw e_1.error; }
1620
1294
  }
1295
+ normalizedName = normalizedName.split(/-+/g).join('-');
1296
+ normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1297
+ normalizedName = normalizedName.replace(/^-/, '');
1298
+ normalizedName = normalizedName.replace(/-$/, '');
1299
+ return normalizedName;
1300
+ }
1301
+
1302
+ /**
1303
+ * Removes emojis from a string and fix whitespaces
1304
+ *
1305
+ * @param text with emojis
1306
+ * @returns text without emojis
1307
+ */
1308
+ function removeEmojis(text) {
1309
+ // Replace emojis (and also ZWJ sequence) with hyphens
1310
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
1311
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
1312
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
1313
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
1314
+ return text;
1315
+ }
1316
+
1317
+ /**
1318
+ * Function normalizes title to name which can be used as identifier
1319
+ */
1320
+ function titleToName(value) {
1321
+ value = removeEmojis(value);
1322
+ value = normalizeToKebabCase(value);
1323
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
1324
+ return value;
1621
1325
  }
1622
1326
 
1623
1327
  /**
@@ -1861,69 +1565,182 @@
1861
1565
  try {
1862
1566
  if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
1863
1567
  }
1864
- finally { if (e_2) throw e_2.error; }
1865
- }
1866
- // =============================================================
1867
- return promptbookJson;
1868
- }
1869
- /**
1870
- * TODO: Report here line/column of error
1871
- * TODO: Use spaceTrim more effectively
1872
- * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1873
- */
1874
-
1875
- /**
1876
- * Add or modify an auto-generated section in a markdown file
1877
- *
1878
- * @private within the library
1879
- */
1880
- function addAutoGeneratedSection(content, options) {
1881
- var sectionName = options.sectionName, sectionContent = options.sectionContent;
1882
- var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
1883
- var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
1884
- var sectionMatch = content.match(sectionRegex);
1885
- if (sectionMatch) {
1886
- return content.replace(sectionRegex, spaceTrim.spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
1887
- }
1888
- var placeForSection = removeContentComments(content).match(/^##.*$/im);
1889
- if (!placeForSection) {
1890
- throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
1891
- }
1892
- var _a = __read(placeForSection, 1), heading = _a[0];
1893
- return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
1568
+ finally { if (e_2) throw e_2.error; }
1569
+ }
1570
+ // =============================================================
1571
+ return promptbookJson;
1572
+ }
1573
+ /**
1574
+ * TODO: Report here line/column of error
1575
+ * TODO: Use spaceTrim more effectively
1576
+ * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1577
+ */
1578
+
1579
+ /**
1580
+ * Add or modify an auto-generated section in a markdown file
1581
+ *
1582
+ * @private within the library
1583
+ */
1584
+ function addAutoGeneratedSection(content, options) {
1585
+ var sectionName = options.sectionName, sectionContent = options.sectionContent;
1586
+ var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
1587
+ var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
1588
+ var sectionMatch = content.match(sectionRegex);
1589
+ if (sectionMatch) {
1590
+ return content.replace(sectionRegex, spaceTrim.spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
1591
+ }
1592
+ var placeForSection = removeContentComments(content).match(/^##.*$/im);
1593
+ if (!placeForSection) {
1594
+ throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
1595
+ }
1596
+ var _a = __read(placeForSection, 1), heading = _a[0];
1597
+ return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
1598
+ }
1599
+
1600
+ /**
1601
+ * Prettify the html code
1602
+ *
1603
+ * @param content raw html code
1604
+ * @returns formatted html code
1605
+ */
1606
+ function prettifyMarkdown(content) {
1607
+ try {
1608
+ return prettier.format(content, {
1609
+ parser: 'markdown',
1610
+ plugins: [parserHtml__default["default"]],
1611
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1612
+ endOfLine: 'lf',
1613
+ tabWidth: 4,
1614
+ singleQuote: true,
1615
+ trailingComma: 'all',
1616
+ arrowParens: 'always',
1617
+ printWidth: 120,
1618
+ htmlWhitespaceSensitivity: 'ignore',
1619
+ jsxBracketSameLine: false,
1620
+ bracketSpacing: true,
1621
+ });
1622
+ }
1623
+ catch (error) {
1624
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1625
+ error: error,
1626
+ html: content,
1627
+ });
1628
+ return content;
1629
+ }
1630
+ }
1631
+
1632
+ /* tslint:disable */
1633
+ function normalizeTo_camelCase(sentence, __firstLetterCapital) {
1634
+ var e_1, _a;
1635
+ if (__firstLetterCapital === void 0) { __firstLetterCapital = false; }
1636
+ var charType;
1637
+ var lastCharType = null;
1638
+ var normalizedName = '';
1639
+ try {
1640
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1641
+ var char = sentence_1_1.value;
1642
+ var normalizedChar = void 0;
1643
+ if (/^[a-z]$/.test(char)) {
1644
+ charType = 'LOWERCASE';
1645
+ normalizedChar = char;
1646
+ }
1647
+ else if (/^[A-Z]$/.test(char)) {
1648
+ charType = 'UPPERCASE';
1649
+ normalizedChar = char.toLowerCase();
1650
+ }
1651
+ else if (/^[0-9]$/.test(char)) {
1652
+ charType = 'NUMBER';
1653
+ normalizedChar = char;
1654
+ }
1655
+ else {
1656
+ charType = 'OTHER';
1657
+ normalizedChar = '';
1658
+ }
1659
+ if (!lastCharType) {
1660
+ if (__firstLetterCapital) {
1661
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: DRY
1662
+ }
1663
+ }
1664
+ else if (charType !== lastCharType &&
1665
+ !(charType === 'LOWERCASE' && lastCharType === 'UPPERCASE') &&
1666
+ !(lastCharType === 'NUMBER') &&
1667
+ !(charType === 'NUMBER')) {
1668
+ normalizedChar = normalizedChar.toUpperCase(); //TODO: [🌺] DRY
1669
+ }
1670
+ normalizedName += normalizedChar;
1671
+ lastCharType = charType;
1672
+ }
1673
+ }
1674
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1675
+ finally {
1676
+ try {
1677
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1678
+ }
1679
+ finally { if (e_1) throw e_1.error; }
1680
+ }
1681
+ return normalizedName;
1682
+ }
1683
+ /**
1684
+ * TODO: [🌺] Use some intermediate util splitWords
1685
+ */
1686
+
1687
+ /**
1688
+ * Creates a Mermaid graph based on the promptbook
1689
+ *
1690
+ * Note: The result is not wrapped in a Markdown code block
1691
+ */
1692
+ function renderPromptbookMermaid(promptbookJson, options) {
1693
+ var _a = (options || {}).linkPromptTemplate, linkPromptTemplate = _a === void 0 ? function () { return null; } : _a;
1694
+ var parameterNameToTemplateName = function (parameterName) {
1695
+ var parameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
1696
+ if (!parameter) {
1697
+ throw new UnexpectedError("Could not find {".concat(parameterName, "}"));
1698
+ }
1699
+ if (parameter.isInput) {
1700
+ return 'input';
1701
+ }
1702
+ var template = promptbookJson.promptTemplates.find(function (template) { return template.resultingParameterName === parameterName; });
1703
+ if (!template) {
1704
+ throw new Error("Could not find template for {".concat(parameterName, "}"));
1705
+ }
1706
+ return normalizeTo_camelCase('template-' + titleToName(template.title));
1707
+ };
1708
+ var promptbookMermaid = spaceTrim.spaceTrim(function (block) { return "\n\n %% \uD83D\uDD2E Tip: Open this on GitHub or in the VSCode website to see the Mermaid graph visually\n\n flowchart LR\n subgraph \"".concat(promptbookJson.title, "\"\n\n direction TB\n\n input((Input)):::input\n ").concat(block(promptbookJson.promptTemplates
1709
+ .flatMap(function (_a) {
1710
+ var title = _a.title, dependentParameterNames = _a.dependentParameterNames, resultingParameterName = _a.resultingParameterName;
1711
+ return __spreadArray([
1712
+ "".concat(parameterNameToTemplateName(resultingParameterName), "(\"").concat(title, "\")")
1713
+ ], __read(dependentParameterNames.map(function (dependentParameterName) {
1714
+ return "".concat(parameterNameToTemplateName(dependentParameterName), "--\"{").concat(dependentParameterName, "}\"-->").concat(parameterNameToTemplateName(resultingParameterName));
1715
+ })), false);
1716
+ })
1717
+ .join('\n')), "\n\n ").concat(block(promptbookJson.parameters
1718
+ .filter(function (_a) {
1719
+ var isOutput = _a.isOutput;
1720
+ return isOutput;
1721
+ })
1722
+ .map(function (_a) {
1723
+ var name = _a.name;
1724
+ return "".concat(parameterNameToTemplateName(name), "--\"{").concat(name, "}\"-->output");
1725
+ })
1726
+ .join('\n')), "\n output((Output)):::output\n\n ").concat(block(promptbookJson.promptTemplates
1727
+ .map(function (promptTemplate) {
1728
+ var link = linkPromptTemplate(promptTemplate);
1729
+ if (link === null) {
1730
+ return '';
1731
+ }
1732
+ var href = link.href, title = link.title;
1733
+ var templateName = parameterNameToTemplateName(promptTemplate.resultingParameterName);
1734
+ return "click ".concat(templateName, " href \"").concat(href, "\" \"").concat(title, "\";");
1735
+ })
1736
+ .filter(function (line) { return line !== ''; })
1737
+ .join('\n')), "\n\n classDef input color: grey;\n classDef output color: grey;\n\n end;\n\n "); });
1738
+ return promptbookMermaid;
1894
1739
  }
1895
-
1896
1740
  /**
1897
- * Prettify the html code
1898
- *
1899
- * @param content raw html code
1900
- * @returns formatted html code
1741
+ * TODO: Maybe use some Mermaid library instead of string templating
1742
+ * TODO: [🕌] When more than 2 functionalities, split into separate functions
1901
1743
  */
1902
- function prettifyMarkdown(content) {
1903
- try {
1904
- return prettier.format(content, {
1905
- parser: 'markdown',
1906
- plugins: [parserHtml__default["default"]],
1907
- // TODO: DRY - make some import or auto-copy of .prettierrc
1908
- endOfLine: 'lf',
1909
- tabWidth: 4,
1910
- singleQuote: true,
1911
- trailingComma: 'all',
1912
- arrowParens: 'always',
1913
- printWidth: 120,
1914
- htmlWhitespaceSensitivity: 'ignore',
1915
- jsxBracketSameLine: false,
1916
- bracketSpacing: true,
1917
- });
1918
- }
1919
- catch (error) {
1920
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1921
- error: error,
1922
- html: content,
1923
- });
1924
- return content;
1925
- }
1926
- }
1927
1744
 
1928
1745
  /**
1929
1746
  * Prettyfies Promptbook string and adds Mermaid graph
@@ -2139,6 +1956,20 @@
2139
1956
  * TODO: Escape all
2140
1957
  */
2141
1958
 
1959
+ /**
1960
+ * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
1961
+ */
1962
+ var PromptbookLogicError = /** @class */ (function (_super) {
1963
+ __extends(PromptbookLogicError, _super);
1964
+ function PromptbookLogicError(message) {
1965
+ var _this = _super.call(this, message) || this;
1966
+ _this.name = 'PromptbookLogicError';
1967
+ Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
1968
+ return _this;
1969
+ }
1970
+ return PromptbookLogicError;
1971
+ }(Error));
1972
+
2142
1973
  /**
2143
1974
  * Tests if given string is valid URL.
2144
1975
  *
@@ -2407,6 +2238,99 @@
2407
2238
  return ExpectError;
2408
2239
  }(Error));
2409
2240
 
2241
+ /**
2242
+ * Function isValidJsonString will tell you if the string is valid JSON or not
2243
+ */
2244
+ function isValidJsonString(value) {
2245
+ try {
2246
+ JSON.parse(value);
2247
+ return true;
2248
+ }
2249
+ catch (error) {
2250
+ if (!(error instanceof Error)) {
2251
+ throw error;
2252
+ }
2253
+ if (error.message.includes('Unexpected token')) {
2254
+ return false;
2255
+ }
2256
+ return false;
2257
+ }
2258
+ }
2259
+
2260
+ /**
2261
+ * Counts number of characters in the text
2262
+ */
2263
+ function countCharacters(text) {
2264
+ // Remove null characters
2265
+ text = text.replace(/\0/g, '');
2266
+ // Replace emojis (and also ZWJ sequence) with hyphens
2267
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
2268
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2269
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
2270
+ return text.length;
2271
+ }
2272
+
2273
+ /**
2274
+ * Counts number of lines in the text
2275
+ */
2276
+ function countLines(text) {
2277
+ if (text === '') {
2278
+ return 0;
2279
+ }
2280
+ return text.split('\n').length;
2281
+ }
2282
+
2283
+ /**
2284
+ * Counts number of pages in the text
2285
+ */
2286
+ function countPages(text) {
2287
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
2288
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
2289
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
2290
+ return pageCount;
2291
+ }
2292
+
2293
+ /**
2294
+ * Counts number of paragraphs in the text
2295
+ */
2296
+ function countParagraphs(text) {
2297
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
2298
+ }
2299
+
2300
+ /**
2301
+ * Split text into sentences
2302
+ */
2303
+ function splitIntoSentences(text) {
2304
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
2305
+ }
2306
+ /**
2307
+ * Counts number of sentences in the text
2308
+ */
2309
+ function countSentences(text) {
2310
+ return splitIntoSentences(text).length;
2311
+ }
2312
+
2313
+ /**
2314
+ * Counts number of words in the text
2315
+ */
2316
+ function countWords(text) {
2317
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
2318
+ text = removeDiacritics(text);
2319
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
2320
+ }
2321
+
2322
+ /**
2323
+ * Index of all counter functions
2324
+ */
2325
+ var CountUtils = {
2326
+ CHARACTERS: countCharacters,
2327
+ WORDS: countWords,
2328
+ SENTENCES: countSentences,
2329
+ PARAGRAPHS: countParagraphs,
2330
+ LINES: countLines,
2331
+ PAGES: countPages,
2332
+ };
2333
+
2410
2334
  /**
2411
2335
  * Function checkExpectations will check if the expectations on given value are met
2412
2336
  *
@@ -2464,6 +2388,82 @@
2464
2388
  * TODO: [💝] Unite object for expecting amount and format
2465
2389
  */
2466
2390
 
2391
+ /**
2392
+ * This error occurs during the parameter replacement in the template
2393
+ *
2394
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
2395
+ */
2396
+ var TemplateError = /** @class */ (function (_super) {
2397
+ __extends(TemplateError, _super);
2398
+ function TemplateError(message) {
2399
+ var _this = _super.call(this, message) || this;
2400
+ _this.name = 'TemplateError';
2401
+ Object.setPrototypeOf(_this, TemplateError.prototype);
2402
+ return _this;
2403
+ }
2404
+ return TemplateError;
2405
+ }(Error));
2406
+
2407
+ /**
2408
+ * Replaces parameters in template with values from parameters object
2409
+ *
2410
+ * @param template the template with parameters in {curly} braces
2411
+ * @param parameters the object with parameters
2412
+ * @returns the template with replaced parameters
2413
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
2414
+ *
2415
+ * @private within the createPromptbookExecutor
2416
+ */
2417
+ function replaceParameters(template, parameters) {
2418
+ var replacedTemplate = template;
2419
+ var match;
2420
+ var loopLimit = LOOP_LIMIT;
2421
+ var _loop_1 = function () {
2422
+ if (loopLimit-- < 0) {
2423
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
2424
+ }
2425
+ var precol = match.groups.precol;
2426
+ var parameterName = match.groups.parameterName;
2427
+ if (parameterName === '') {
2428
+ return "continue";
2429
+ }
2430
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
2431
+ throw new TemplateError('Parameter is already opened or not closed');
2432
+ }
2433
+ if (parameters[parameterName] === undefined) {
2434
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
2435
+ }
2436
+ var parameterValue = parameters[parameterName];
2437
+ if (parameterValue === undefined) {
2438
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
2439
+ }
2440
+ parameterValue = parameterValue.toString();
2441
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
2442
+ parameterValue = parameterValue
2443
+ .split('\n')
2444
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
2445
+ .join('\n');
2446
+ }
2447
+ replacedTemplate =
2448
+ replacedTemplate.substring(0, match.index + precol.length) +
2449
+ parameterValue +
2450
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
2451
+ };
2452
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
2453
+ .exec(replacedTemplate))) {
2454
+ _loop_1();
2455
+ }
2456
+ // [💫] Check if there are parameters that are not closed properly
2457
+ if (/{\w+$/.test(replacedTemplate)) {
2458
+ throw new TemplateError('Parameter is not closed');
2459
+ }
2460
+ // [💫] Check if there are parameters that are not opened properly
2461
+ if (/^\w+}/.test(replacedTemplate)) {
2462
+ throw new TemplateError('Parameter is not opened');
2463
+ }
2464
+ return replacedTemplate;
2465
+ }
2466
+
2467
2467
  /**
2468
2468
  * Creates executor function from promptbook and execution tools.
2469
2469
  *