@promptbook/node 0.59.0-2 → 0.59.0-20

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 (565) hide show
  1. package/esm/index.es.js +2519 -1574
  2. package/esm/index.es.js.map +1 -1
  3. package/esm/typings/promptbook-library/promptbook-library.d.ts +25 -0
  4. package/{umd/typings → esm/typings/src}/_packages/core.index.d.ts +7 -6
  5. package/esm/typings/{_packages → src/_packages}/node.index.d.ts +1 -1
  6. package/{umd/typings → esm/typings/src}/_packages/types.index.d.ts +1 -1
  7. package/{umd/typings → esm/typings/src}/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +3 -0
  8. package/{umd/typings → esm/typings/src}/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -0
  9. package/{umd/typings → esm/typings/src}/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +3 -0
  10. package/{umd/typings → esm/typings/src}/llm-providers/remote/interfaces/RemoteServerOptions.d.ts +1 -1
  11. package/esm/typings/{types → src/types}/PromptbookJson/MaterialKnowledgePieceJson.d.ts +1 -1
  12. package/package.json +3 -3
  13. package/umd/index.umd.js +2519 -1574
  14. package/umd/index.umd.js.map +1 -1
  15. package/umd/typings/promptbook-library/promptbook-library.d.ts +25 -0
  16. package/{esm/typings → umd/typings/src}/_packages/core.index.d.ts +7 -6
  17. package/umd/typings/{_packages → src/_packages}/node.index.d.ts +1 -1
  18. package/{esm/typings → umd/typings/src}/_packages/types.index.d.ts +1 -1
  19. package/{esm/typings → umd/typings/src}/knowledge/prepare-knowledge/pdf/prepareKnowledgeFromPdf.d.ts +3 -0
  20. package/{esm/typings → umd/typings/src}/llm-providers/mocked/MockedEchoLlmExecutionTools.d.ts +1 -0
  21. package/{esm/typings → umd/typings/src}/llm-providers/mocked/MockedFackedLlmExecutionTools.d.ts +3 -0
  22. package/{esm/typings → umd/typings/src}/llm-providers/remote/interfaces/RemoteServerOptions.d.ts +1 -1
  23. package/umd/typings/{types → src/types}/PromptbookJson/MaterialKnowledgePieceJson.d.ts +1 -1
  24. /package/esm/typings/{_packages → src/_packages}/anthropic-claude.index.d.ts +0 -0
  25. /package/esm/typings/{_packages → src/_packages}/azure-openai.index.d.ts +0 -0
  26. /package/esm/typings/{_packages → src/_packages}/cli.index.d.ts +0 -0
  27. /package/esm/typings/{_packages → src/_packages}/execute-javascript.index.d.ts +0 -0
  28. /package/esm/typings/{_packages → src/_packages}/fake-llm.index.d.ts +0 -0
  29. /package/esm/typings/{_packages → src/_packages}/langtail.index.d.ts +0 -0
  30. /package/esm/typings/{_packages → src/_packages}/openai.index.d.ts +0 -0
  31. /package/esm/typings/{_packages → src/_packages}/remote-client.index.d.ts +0 -0
  32. /package/esm/typings/{_packages → src/_packages}/remote-server.index.d.ts +0 -0
  33. /package/esm/typings/{_packages → src/_packages}/utils.index.d.ts +0 -0
  34. /package/esm/typings/{config.d.ts → src/config.d.ts} +0 -0
  35. /package/esm/typings/{conversion → src/conversion}/prettify/PrettifyOptions.d.ts +0 -0
  36. /package/esm/typings/{conversion → src/conversion}/prettify/prettifyPromptbookString.d.ts +0 -0
  37. /package/esm/typings/{conversion → src/conversion}/prettify/prettifyPromptbookStringCli.d.ts +0 -0
  38. /package/esm/typings/{conversion → src/conversion}/prettify/renderPromptbookMermaid.d.ts +0 -0
  39. /package/esm/typings/{conversion → src/conversion}/promptbookJsonToString.d.ts +0 -0
  40. /package/esm/typings/{conversion → src/conversion}/promptbookStringToJson.d.ts +0 -0
  41. /package/esm/typings/{conversion → src/conversion}/promptbookStringToJson.test.d.ts +0 -0
  42. /package/esm/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.d.ts +0 -0
  43. /package/esm/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.test.d.ts +0 -0
  44. /package/esm/typings/{conversion → src/conversion}/utils/extractVariables.d.ts +0 -0
  45. /package/esm/typings/{conversion → src/conversion}/utils/extractVariables.test.d.ts +0 -0
  46. /package/esm/typings/{conversion → src/conversion}/utils/parseCommand.d.ts +0 -0
  47. /package/esm/typings/{conversion → src/conversion}/utils/parseCommand.test.d.ts +0 -0
  48. /package/esm/typings/{conversion → src/conversion}/utils/parseNumber.d.ts +0 -0
  49. /package/esm/typings/{conversion → src/conversion}/utils/parseNumber.test.d.ts +0 -0
  50. /package/esm/typings/{conversion → src/conversion}/utils/renameParameter.d.ts +0 -0
  51. /package/esm/typings/{conversion → src/conversion}/utils/renameParameter.test.d.ts +0 -0
  52. /package/esm/typings/{conversion → src/conversion}/utils/titleToName.d.ts +0 -0
  53. /package/esm/typings/{conversion → src/conversion}/utils/titleToName.test.d.ts +0 -0
  54. /package/esm/typings/{conversion → src/conversion}/validation/_importPromptbook.d.ts +0 -0
  55. /package/esm/typings/{conversion → src/conversion}/validation/promptbookStringToJson-syntaxErrors.test.d.ts +0 -0
  56. /package/esm/typings/{conversion → src/conversion}/validation/validatePromptbookJson-logicErrors.test.d.ts +0 -0
  57. /package/esm/typings/{conversion → src/conversion}/validation/validatePromptbookJson.d.ts +0 -0
  58. /package/esm/typings/{conversion → src/conversion}/validation/validatePromptbookJson.test.d.ts +0 -0
  59. /package/esm/typings/{errors → src/errors}/PromptbookExecutionError.d.ts +0 -0
  60. /package/esm/typings/{errors → src/errors}/PromptbookLibraryError.d.ts +0 -0
  61. /package/esm/typings/{errors → src/errors}/PromptbookLogicError.d.ts +0 -0
  62. /package/esm/typings/{errors → src/errors}/PromptbookNotFoundError.d.ts +0 -0
  63. /package/esm/typings/{errors → src/errors}/PromptbookReferenceError.d.ts +0 -0
  64. /package/esm/typings/{errors → src/errors}/PromptbookSyntaxError.d.ts +0 -0
  65. /package/esm/typings/{errors → src/errors}/TemplateError.d.ts +0 -0
  66. /package/esm/typings/{errors → src/errors}/UnexpectedError.d.ts +0 -0
  67. /package/esm/typings/{errors → src/errors}/_ExpectError.d.ts +0 -0
  68. /package/esm/typings/{execution → src/execution}/CommonExecutionToolsOptions.d.ts +0 -0
  69. /package/esm/typings/{execution → src/execution}/ExecutionTools.d.ts +0 -0
  70. /package/esm/typings/{execution → src/execution}/LlmExecutionTools.d.ts +0 -0
  71. /package/esm/typings/{execution → src/execution}/PromptResult.d.ts +0 -0
  72. /package/esm/typings/{execution → src/execution}/PromptbookExecutor.d.ts +0 -0
  73. /package/esm/typings/{execution → src/execution}/ScriptExecutionTools.d.ts +0 -0
  74. /package/esm/typings/{execution → src/execution}/UserInterfaceTools.d.ts +0 -0
  75. /package/esm/typings/{execution → src/execution}/addPromptResultUsage.test.d.ts +0 -0
  76. /package/esm/typings/{execution → src/execution}/assertsExecutionSuccessful.d.ts +0 -0
  77. /package/esm/typings/{execution → src/execution}/createPromptbookExecutor.d.ts +0 -0
  78. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +0 -0
  79. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +0 -0
  80. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +0 -0
  81. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +0 -0
  82. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +0 -0
  83. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +0 -0
  84. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +0 -0
  85. /package/esm/typings/{execution → src/execution}/translation/automatic-translate/translateMessages.d.ts +0 -0
  86. /package/esm/typings/{execution → src/execution}/utils/addUsage.d.ts +0 -0
  87. /package/esm/typings/{execution → src/execution}/utils/addUsage.test.d.ts +0 -0
  88. /package/esm/typings/{execution → src/execution}/utils/checkExpectations.d.ts +0 -0
  89. /package/esm/typings/{execution → src/execution}/utils/checkExpectations.test.d.ts +0 -0
  90. /package/esm/typings/{execution → src/execution}/utils/computeUsageCounts.d.ts +0 -0
  91. /package/esm/typings/{execution → src/execution}/utils/forEachAsync.d.ts +0 -0
  92. /package/esm/typings/{execution → src/execution}/utils/replaceParameters.d.ts +0 -0
  93. /package/esm/typings/{execution → src/execution}/utils/replaceParameters.test.d.ts +0 -0
  94. /package/esm/typings/{execution → src/execution}/utils/uncertainNumber.d.ts +0 -0
  95. /package/esm/typings/{execution → src/execution}/utils/usageToWorktime.d.ts +0 -0
  96. /package/esm/typings/{execution → src/execution}/utils/usageToWorktime.test.d.ts +0 -0
  97. /package/esm/typings/{expectations → src/expectations}/drafts/isDomainNameFree.d.ts +0 -0
  98. /package/esm/typings/{expectations → src/expectations}/drafts/isGithubNameFree.d.ts +0 -0
  99. /package/esm/typings/{formats → src/formats}/_common/FormatDefinition.d.ts +0 -0
  100. /package/esm/typings/{formats → src/formats}/csv/ListFormatDefinition.d.ts +0 -0
  101. /package/esm/typings/{formats → src/formats}/index.d.ts +0 -0
  102. /package/esm/typings/{formats → src/formats}/json/JsonFormatDefinition.d.ts +0 -0
  103. /package/esm/typings/{formats → src/formats}/json/utils/isValidJsonString.d.ts +0 -0
  104. /package/esm/typings/{formats → src/formats}/json/utils/isValidJsonString.test.d.ts +0 -0
  105. /package/esm/typings/{formats → src/formats}/list/ListFormatDefinition.d.ts +0 -0
  106. /package/esm/typings/{formats → src/formats}/xml/XmlFormatDefinition.d.ts +0 -0
  107. /package/esm/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceTools.d.ts +0 -0
  108. /package/esm/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +0 -0
  109. /package/esm/typings/{knowledge → src/knowledge}/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +0 -0
  110. /package/esm/typings/{knowledge → src/knowledge}/dialogs/user-interface-execution-tools.test.d.ts +0 -0
  111. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/_common/IndexPreparer.d.ts +0 -0
  112. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/playground/markdown-knowledge-playground.d.ts +0 -0
  113. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +0 -0
  114. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +0 -0
  115. /package/esm/typings/{knowledge → src/knowledge}/prepare-knowledge/pdf/prepareKnowledgeFromPdf.test.d.ts +0 -0
  116. /package/esm/typings/{promptbook-library → src/library}/PromptbookLibrary.d.ts +0 -0
  117. /package/esm/typings/{promptbook-library → src/library}/SimplePromptbookLibrary.d.ts +0 -0
  118. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromDirectory.d.ts +0 -0
  119. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromDirectory.test.d.ts +0 -0
  120. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromPromise.d.ts +0 -0
  121. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromPromise.test.d.ts +0 -0
  122. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromSources.d.ts +0 -0
  123. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromSources.test.d.ts +0 -0
  124. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromUrl.d.ts +0 -0
  125. /package/esm/typings/{promptbook-library → src/library}/constructors/createPromptbookSublibrary.d.ts +0 -0
  126. /package/esm/typings/{promptbook-library → src/library}/constructors/justTestFsImport.d.ts +0 -0
  127. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +0 -0
  128. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +0 -0
  129. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/anthropic-claude-models.d.ts +0 -0
  130. /package/esm/typings/{llm-providers → src/llm-providers}/anthropic-claude/playground/playground.d.ts +0 -0
  131. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionTools.d.ts +0 -0
  132. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +0 -0
  133. /package/esm/typings/{llm-providers → src/llm-providers}/azure-openai/playground/playground.d.ts +0 -0
  134. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionTools.d.ts +0 -0
  135. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionToolsOptions.d.ts +0 -0
  136. /package/esm/typings/{llm-providers → src/llm-providers}/langtail/playground/playground.d.ts +0 -0
  137. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.d.ts +0 -0
  138. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.test.d.ts +0 -0
  139. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/faked-completion.test.d.ts +0 -0
  140. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/joker.test.d.ts +0 -0
  141. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/mocked-chat.test.d.ts +0 -0
  142. /package/esm/typings/{llm-providers → src/llm-providers}/mocked/mocked-completion.test.d.ts +0 -0
  143. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionTools.d.ts +0 -0
  144. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionToolsOptions.d.ts +0 -0
  145. /package/esm/typings/{llm-providers → src/llm-providers}/multiple/playground/playground.d.ts +0 -0
  146. /package/esm/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionTools.d.ts +0 -0
  147. /package/esm/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionToolsOptions.d.ts +0 -0
  148. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeOpenaiUsage.d.ts +0 -0
  149. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeUsage.d.ts +0 -0
  150. /package/esm/typings/{llm-providers → src/llm-providers}/openai/computeUsage.test.d.ts +0 -0
  151. /package/esm/typings/{llm-providers → src/llm-providers}/openai/openai-models.d.ts +0 -0
  152. /package/esm/typings/{llm-providers → src/llm-providers}/openai/playground/playground.d.ts +0 -0
  153. /package/esm/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionTools.d.ts +0 -0
  154. /package/esm/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionToolsOptions.d.ts +0 -0
  155. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Error.d.ts +0 -0
  156. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Progress.d.ts +0 -0
  157. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Request.d.ts +0 -0
  158. /package/esm/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Response.d.ts +0 -0
  159. /package/esm/typings/{llm-providers → src/llm-providers}/remote/startRemoteServer.d.ts +0 -0
  160. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-async.test.ts.test.d.ts +0 -0
  161. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-missing.test.d.ts +0 -0
  162. /package/esm/typings/{scripting → src/scripting}/_test/custom-function-with-dependencies.test.d.ts +0 -0
  163. /package/esm/typings/{scripting → src/scripting}/_test/custom-function.test.d.ts +0 -0
  164. /package/esm/typings/{scripting → src/scripting}/_test/postprocessing.test.d.ts +0 -0
  165. /package/esm/typings/{scripting → src/scripting}/_test/script-execution-errors.test.d.ts +0 -0
  166. /package/esm/typings/{scripting → src/scripting}/_test/script-execution-tools.test.d.ts +0 -0
  167. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.d.ts +0 -0
  168. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.test.d.ts +0 -0
  169. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptExecutionTools.d.ts +0 -0
  170. /package/esm/typings/{scripting → src/scripting}/javascript/JavascriptExecutionToolsOptions.d.ts +0 -0
  171. /package/esm/typings/{scripting → src/scripting}/javascript/utils/preserve.d.ts +0 -0
  172. /package/esm/typings/{scripting → src/scripting}/javascript/utils/unknownToString.d.ts +0 -0
  173. /package/esm/typings/{scripting → src/scripting}/python/PythonExecutionTools.d.ts +0 -0
  174. /package/esm/typings/{scripting → src/scripting}/typescript/TypescriptExecutionTools.d.ts +0 -0
  175. /package/esm/typings/{types → src/types}/Command.d.ts +0 -0
  176. /package/esm/typings/{types → src/types}/ExecutionTypes.d.ts +0 -0
  177. /package/esm/typings/{types → src/types}/ModelRequirements.d.ts +0 -0
  178. /package/esm/typings/{types → src/types}/Parameters.d.ts +0 -0
  179. /package/esm/typings/{types → src/types}/Prompt.d.ts +0 -0
  180. /package/esm/typings/{types → src/types}/PromptbookJson/KnowledgeJson.d.ts +0 -0
  181. /package/esm/typings/{types → src/types}/PromptbookJson/PromptTemplateJson.d.ts +0 -0
  182. /package/esm/typings/{types → src/types}/PromptbookJson/PromptTemplateParameterJson.d.ts +0 -0
  183. /package/esm/typings/{types → src/types}/PromptbookJson/PromptbookJson.d.ts +0 -0
  184. /package/esm/typings/{types → src/types}/PromptbookString.d.ts +0 -0
  185. /package/esm/typings/{types → src/types}/ScriptLanguage.d.ts +0 -0
  186. /package/esm/typings/{types → src/types}/TaskProgress.d.ts +0 -0
  187. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportJson.d.ts +0 -0
  188. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportString.d.ts +0 -0
  189. /package/esm/typings/{types → src/types}/execution-report/ExecutionReportStringOptions.d.ts +0 -0
  190. /package/esm/typings/{types → src/types}/execution-report/config.d.ts +0 -0
  191. /package/esm/typings/{types → src/types}/execution-report/countWorkingDuration.d.ts +0 -0
  192. /package/esm/typings/{types → src/types}/execution-report/countWorkingDuration.test.d.ts +0 -0
  193. /package/esm/typings/{types → src/types}/execution-report/executionReportJsonToString.d.ts +0 -0
  194. /package/esm/typings/{types → src/types}/typeAliasEmoji.d.ts +0 -0
  195. /package/esm/typings/{types → src/types}/typeAliases.d.ts +0 -0
  196. /package/esm/typings/{utils → src/utils}/FromtoItems.d.ts +0 -0
  197. /package/esm/typings/{utils → src/utils}/emojis.d.ts +0 -0
  198. /package/esm/typings/{utils → src/utils}/expectation-counters/countCharacters.d.ts +0 -0
  199. /package/esm/typings/{utils → src/utils}/expectation-counters/countCharacters.test.d.ts +0 -0
  200. /package/esm/typings/{utils → src/utils}/expectation-counters/countLines.d.ts +0 -0
  201. /package/esm/typings/{utils → src/utils}/expectation-counters/countLines.test.d.ts +0 -0
  202. /package/esm/typings/{utils → src/utils}/expectation-counters/countPages.d.ts +0 -0
  203. /package/esm/typings/{utils → src/utils}/expectation-counters/countPages.test.d.ts +0 -0
  204. /package/esm/typings/{utils → src/utils}/expectation-counters/countParagraphs.d.ts +0 -0
  205. /package/esm/typings/{utils → src/utils}/expectation-counters/countParagraphs.test.d.ts +0 -0
  206. /package/esm/typings/{utils → src/utils}/expectation-counters/countSentences.d.ts +0 -0
  207. /package/esm/typings/{utils → src/utils}/expectation-counters/countSentences.test.d.ts +0 -0
  208. /package/esm/typings/{utils → src/utils}/expectation-counters/countWords.d.ts +0 -0
  209. /package/esm/typings/{utils → src/utils}/expectation-counters/countWords.test.d.ts +0 -0
  210. /package/esm/typings/{utils → src/utils}/expectation-counters/index.d.ts +0 -0
  211. /package/esm/typings/{utils → src/utils}/extractParameters.d.ts +0 -0
  212. /package/esm/typings/{utils → src/utils}/extractParameters.test.d.ts +0 -0
  213. /package/esm/typings/{utils → src/utils}/formatNumber.d.ts +0 -0
  214. /package/esm/typings/{utils → src/utils}/formatNumber.test.d.ts +0 -0
  215. /package/esm/typings/{utils → src/utils}/getCurrentIsoDate.d.ts +0 -0
  216. /package/esm/typings/{utils → src/utils}/isRunningInWhatever.d.ts +0 -0
  217. /package/esm/typings/{utils → src/utils}/just.d.ts +0 -0
  218. /package/esm/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.d.ts +0 -0
  219. /package/esm/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.test.d.ts +0 -0
  220. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownChart.d.ts +0 -0
  221. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownChart.test.d.ts +0 -0
  222. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownTable.d.ts +0 -0
  223. /package/esm/typings/{utils → src/utils}/markdown/createMarkdownTable.test.d.ts +0 -0
  224. /package/esm/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.d.ts +0 -0
  225. /package/esm/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.test.d.ts +0 -0
  226. /package/esm/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.d.ts +0 -0
  227. /package/esm/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.test.d.ts +0 -0
  228. /package/esm/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.d.ts +0 -0
  229. /package/esm/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.test.d.ts +0 -0
  230. /package/esm/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.d.ts +0 -0
  231. /package/esm/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.test.d.ts +0 -0
  232. /package/esm/typings/{utils → src/utils}/markdown/prettifyMarkdown.d.ts +0 -0
  233. /package/esm/typings/{utils → src/utils}/markdown/prettifyMarkdown.test.d.ts +0 -0
  234. /package/esm/typings/{utils → src/utils}/markdown/removeContentComments.d.ts +0 -0
  235. /package/esm/typings/{utils → src/utils}/markdown/removeContentComments.test.d.ts +0 -0
  236. /package/esm/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.d.ts +0 -0
  237. /package/esm/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.test.d.ts +0 -0
  238. /package/esm/typings/{utils → src/utils}/markdown-json/MarkdownStructure.d.ts +0 -0
  239. /package/esm/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.d.ts +0 -0
  240. /package/esm/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.test.d.ts +0 -0
  241. /package/esm/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.d.ts +0 -0
  242. /package/esm/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.test.d.ts +0 -0
  243. /package/esm/typings/{utils → src/utils}/normalization/DIACRITIC_VARIANTS_LETTERS.d.ts +0 -0
  244. /package/esm/typings/{utils → src/utils}/normalization/IKeywords.d.ts +0 -0
  245. /package/esm/typings/{utils → src/utils}/normalization/capitalize.d.ts +0 -0
  246. /package/esm/typings/{utils → src/utils}/normalization/capitalize.test.d.ts +0 -0
  247. /package/esm/typings/{utils → src/utils}/normalization/decapitalize.d.ts +0 -0
  248. /package/esm/typings/{utils → src/utils}/normalization/decapitalize.test.d.ts +0 -0
  249. /package/esm/typings/{utils → src/utils}/normalization/isValidKeyword.d.ts +0 -0
  250. /package/esm/typings/{utils → src/utils}/normalization/isValidKeyword.test.d.ts +0 -0
  251. /package/esm/typings/{utils → src/utils}/normalization/nameToUriPart.d.ts +0 -0
  252. /package/esm/typings/{utils → src/utils}/normalization/nameToUriPart.test.d.ts +0 -0
  253. /package/esm/typings/{utils → src/utils}/normalization/nameToUriParts.d.ts +0 -0
  254. /package/esm/typings/{utils → src/utils}/normalization/nameToUriParts.test.d.ts +0 -0
  255. /package/esm/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.d.ts +0 -0
  256. /package/esm/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.test.d.ts +0 -0
  257. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.d.ts +0 -0
  258. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.test.d.ts +0 -0
  259. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.d.ts +0 -0
  260. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.test.d.ts +0 -0
  261. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.d.ts +0 -0
  262. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.test.d.ts +0 -0
  263. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.d.ts +0 -0
  264. /package/esm/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.test.d.ts +0 -0
  265. /package/esm/typings/{utils → src/utils}/normalization/normalizeWhitespaces.d.ts +0 -0
  266. /package/esm/typings/{utils → src/utils}/normalization/normalizeWhitespaces.test.d.ts +0 -0
  267. /package/esm/typings/{utils → src/utils}/normalization/parseKeywords.d.ts +0 -0
  268. /package/esm/typings/{utils → src/utils}/normalization/parseKeywords.test.d.ts +0 -0
  269. /package/esm/typings/{utils → src/utils}/normalization/parseKeywordsFromString.d.ts +0 -0
  270. /package/esm/typings/{utils → src/utils}/normalization/parseKeywordsFromString.test.d.ts +0 -0
  271. /package/esm/typings/{utils → src/utils}/normalization/removeDiacritics.d.ts +0 -0
  272. /package/esm/typings/{utils → src/utils}/normalization/removeDiacritics.test.d.ts +0 -0
  273. /package/esm/typings/{utils → src/utils}/normalization/searchKeywords.d.ts +0 -0
  274. /package/esm/typings/{utils → src/utils}/normalization/searchKeywords.test.d.ts +0 -0
  275. /package/esm/typings/{utils → src/utils}/postprocessing/extractBlock.d.ts +0 -0
  276. /package/esm/typings/{utils → src/utils}/removeEmojis.d.ts +0 -0
  277. /package/esm/typings/{utils → src/utils}/removeEmojis.test.d.ts +0 -0
  278. /package/esm/typings/{utils → src/utils}/removeQuotes.d.ts +0 -0
  279. /package/esm/typings/{utils → src/utils}/removeQuotes.test.d.ts +0 -0
  280. /package/esm/typings/{utils → src/utils}/sets/difference.d.ts +0 -0
  281. /package/esm/typings/{utils → src/utils}/sets/difference.test.d.ts +0 -0
  282. /package/esm/typings/{utils → src/utils}/sets/intersection.d.ts +0 -0
  283. /package/esm/typings/{utils → src/utils}/sets/intersection.test.d.ts +0 -0
  284. /package/esm/typings/{utils → src/utils}/sets/union.d.ts +0 -0
  285. /package/esm/typings/{utils → src/utils}/sets/union.test.d.ts +0 -0
  286. /package/esm/typings/{utils → src/utils}/trimCodeBlock.d.ts +0 -0
  287. /package/esm/typings/{utils → src/utils}/trimCodeBlock.test.d.ts +0 -0
  288. /package/esm/typings/{utils → src/utils}/trimEndOfCodeBlock.d.ts +0 -0
  289. /package/esm/typings/{utils → src/utils}/trimEndOfCodeBlock.test.d.ts +0 -0
  290. /package/esm/typings/{utils → src/utils}/unwrapResult.d.ts +0 -0
  291. /package/esm/typings/{utils → src/utils}/unwrapResult.test.d.ts +0 -0
  292. /package/esm/typings/{utils → src/utils}/validators/url/isValidUrl.d.ts +0 -0
  293. /package/esm/typings/{utils → src/utils}/validators/url/isValidUrl.test.d.ts +0 -0
  294. /package/esm/typings/{version.d.ts → src/version.d.ts} +0 -0
  295. /package/umd/typings/{_packages → src/_packages}/anthropic-claude.index.d.ts +0 -0
  296. /package/umd/typings/{_packages → src/_packages}/azure-openai.index.d.ts +0 -0
  297. /package/umd/typings/{_packages → src/_packages}/cli.index.d.ts +0 -0
  298. /package/umd/typings/{_packages → src/_packages}/execute-javascript.index.d.ts +0 -0
  299. /package/umd/typings/{_packages → src/_packages}/fake-llm.index.d.ts +0 -0
  300. /package/umd/typings/{_packages → src/_packages}/langtail.index.d.ts +0 -0
  301. /package/umd/typings/{_packages → src/_packages}/openai.index.d.ts +0 -0
  302. /package/umd/typings/{_packages → src/_packages}/remote-client.index.d.ts +0 -0
  303. /package/umd/typings/{_packages → src/_packages}/remote-server.index.d.ts +0 -0
  304. /package/umd/typings/{_packages → src/_packages}/utils.index.d.ts +0 -0
  305. /package/umd/typings/{config.d.ts → src/config.d.ts} +0 -0
  306. /package/umd/typings/{conversion → src/conversion}/prettify/PrettifyOptions.d.ts +0 -0
  307. /package/umd/typings/{conversion → src/conversion}/prettify/prettifyPromptbookString.d.ts +0 -0
  308. /package/umd/typings/{conversion → src/conversion}/prettify/prettifyPromptbookStringCli.d.ts +0 -0
  309. /package/umd/typings/{conversion → src/conversion}/prettify/renderPromptbookMermaid.d.ts +0 -0
  310. /package/umd/typings/{conversion → src/conversion}/promptbookJsonToString.d.ts +0 -0
  311. /package/umd/typings/{conversion → src/conversion}/promptbookStringToJson.d.ts +0 -0
  312. /package/umd/typings/{conversion → src/conversion}/promptbookStringToJson.test.d.ts +0 -0
  313. /package/umd/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.d.ts +0 -0
  314. /package/umd/typings/{conversion → src/conversion}/utils/extractParametersFromPromptTemplate.test.d.ts +0 -0
  315. /package/umd/typings/{conversion → src/conversion}/utils/extractVariables.d.ts +0 -0
  316. /package/umd/typings/{conversion → src/conversion}/utils/extractVariables.test.d.ts +0 -0
  317. /package/umd/typings/{conversion → src/conversion}/utils/parseCommand.d.ts +0 -0
  318. /package/umd/typings/{conversion → src/conversion}/utils/parseCommand.test.d.ts +0 -0
  319. /package/umd/typings/{conversion → src/conversion}/utils/parseNumber.d.ts +0 -0
  320. /package/umd/typings/{conversion → src/conversion}/utils/parseNumber.test.d.ts +0 -0
  321. /package/umd/typings/{conversion → src/conversion}/utils/renameParameter.d.ts +0 -0
  322. /package/umd/typings/{conversion → src/conversion}/utils/renameParameter.test.d.ts +0 -0
  323. /package/umd/typings/{conversion → src/conversion}/utils/titleToName.d.ts +0 -0
  324. /package/umd/typings/{conversion → src/conversion}/utils/titleToName.test.d.ts +0 -0
  325. /package/umd/typings/{conversion → src/conversion}/validation/_importPromptbook.d.ts +0 -0
  326. /package/umd/typings/{conversion → src/conversion}/validation/promptbookStringToJson-syntaxErrors.test.d.ts +0 -0
  327. /package/umd/typings/{conversion → src/conversion}/validation/validatePromptbookJson-logicErrors.test.d.ts +0 -0
  328. /package/umd/typings/{conversion → src/conversion}/validation/validatePromptbookJson.d.ts +0 -0
  329. /package/umd/typings/{conversion → src/conversion}/validation/validatePromptbookJson.test.d.ts +0 -0
  330. /package/umd/typings/{errors → src/errors}/PromptbookExecutionError.d.ts +0 -0
  331. /package/umd/typings/{errors → src/errors}/PromptbookLibraryError.d.ts +0 -0
  332. /package/umd/typings/{errors → src/errors}/PromptbookLogicError.d.ts +0 -0
  333. /package/umd/typings/{errors → src/errors}/PromptbookNotFoundError.d.ts +0 -0
  334. /package/umd/typings/{errors → src/errors}/PromptbookReferenceError.d.ts +0 -0
  335. /package/umd/typings/{errors → src/errors}/PromptbookSyntaxError.d.ts +0 -0
  336. /package/umd/typings/{errors → src/errors}/TemplateError.d.ts +0 -0
  337. /package/umd/typings/{errors → src/errors}/UnexpectedError.d.ts +0 -0
  338. /package/umd/typings/{errors → src/errors}/_ExpectError.d.ts +0 -0
  339. /package/umd/typings/{execution → src/execution}/CommonExecutionToolsOptions.d.ts +0 -0
  340. /package/umd/typings/{execution → src/execution}/ExecutionTools.d.ts +0 -0
  341. /package/umd/typings/{execution → src/execution}/LlmExecutionTools.d.ts +0 -0
  342. /package/umd/typings/{execution → src/execution}/PromptResult.d.ts +0 -0
  343. /package/umd/typings/{execution → src/execution}/PromptbookExecutor.d.ts +0 -0
  344. /package/umd/typings/{execution → src/execution}/ScriptExecutionTools.d.ts +0 -0
  345. /package/umd/typings/{execution → src/execution}/UserInterfaceTools.d.ts +0 -0
  346. /package/umd/typings/{execution → src/execution}/addPromptResultUsage.test.d.ts +0 -0
  347. /package/umd/typings/{execution → src/execution}/assertsExecutionSuccessful.d.ts +0 -0
  348. /package/umd/typings/{execution → src/execution}/createPromptbookExecutor.d.ts +0 -0
  349. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/AutomaticTranslator.d.ts +0 -0
  350. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/DebugAutomaticTranslator.d.ts +0 -0
  351. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/FakeAutomaticTranslator.d.ts +0 -0
  352. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/LindatAutomaticTranslator.d.ts +0 -0
  353. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/TranslatorOptions.d.ts +0 -0
  354. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.d.ts +0 -0
  355. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/automatic-translators/utils/extractMultiplicatedOccurrence.test.d.ts +0 -0
  356. /package/umd/typings/{execution → src/execution}/translation/automatic-translate/translateMessages.d.ts +0 -0
  357. /package/umd/typings/{execution → src/execution}/utils/addUsage.d.ts +0 -0
  358. /package/umd/typings/{execution → src/execution}/utils/addUsage.test.d.ts +0 -0
  359. /package/umd/typings/{execution → src/execution}/utils/checkExpectations.d.ts +0 -0
  360. /package/umd/typings/{execution → src/execution}/utils/checkExpectations.test.d.ts +0 -0
  361. /package/umd/typings/{execution → src/execution}/utils/computeUsageCounts.d.ts +0 -0
  362. /package/umd/typings/{execution → src/execution}/utils/forEachAsync.d.ts +0 -0
  363. /package/umd/typings/{execution → src/execution}/utils/replaceParameters.d.ts +0 -0
  364. /package/umd/typings/{execution → src/execution}/utils/replaceParameters.test.d.ts +0 -0
  365. /package/umd/typings/{execution → src/execution}/utils/uncertainNumber.d.ts +0 -0
  366. /package/umd/typings/{execution → src/execution}/utils/usageToWorktime.d.ts +0 -0
  367. /package/umd/typings/{execution → src/execution}/utils/usageToWorktime.test.d.ts +0 -0
  368. /package/umd/typings/{expectations → src/expectations}/drafts/isDomainNameFree.d.ts +0 -0
  369. /package/umd/typings/{expectations → src/expectations}/drafts/isGithubNameFree.d.ts +0 -0
  370. /package/umd/typings/{formats → src/formats}/_common/FormatDefinition.d.ts +0 -0
  371. /package/umd/typings/{formats → src/formats}/csv/ListFormatDefinition.d.ts +0 -0
  372. /package/umd/typings/{formats → src/formats}/index.d.ts +0 -0
  373. /package/umd/typings/{formats → src/formats}/json/JsonFormatDefinition.d.ts +0 -0
  374. /package/umd/typings/{formats → src/formats}/json/utils/isValidJsonString.d.ts +0 -0
  375. /package/umd/typings/{formats → src/formats}/json/utils/isValidJsonString.test.d.ts +0 -0
  376. /package/umd/typings/{formats → src/formats}/list/ListFormatDefinition.d.ts +0 -0
  377. /package/umd/typings/{formats → src/formats}/xml/XmlFormatDefinition.d.ts +0 -0
  378. /package/umd/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceTools.d.ts +0 -0
  379. /package/umd/typings/{knowledge → src/knowledge}/dialogs/callback/CallbackInterfaceToolsOptions.d.ts +0 -0
  380. /package/umd/typings/{knowledge → src/knowledge}/dialogs/simple-prompt/SimplePromptInterfaceTools.d.ts +0 -0
  381. /package/umd/typings/{knowledge → src/knowledge}/dialogs/user-interface-execution-tools.test.d.ts +0 -0
  382. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/_common/IndexPreparer.d.ts +0 -0
  383. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/playground/markdown-knowledge-playground.d.ts +0 -0
  384. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.d.ts +0 -0
  385. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/markdown/prepareKnowledgeFromMarkdown.test.d.ts +0 -0
  386. /package/umd/typings/{knowledge → src/knowledge}/prepare-knowledge/pdf/prepareKnowledgeFromPdf.test.d.ts +0 -0
  387. /package/umd/typings/{promptbook-library → src/library}/PromptbookLibrary.d.ts +0 -0
  388. /package/umd/typings/{promptbook-library → src/library}/SimplePromptbookLibrary.d.ts +0 -0
  389. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromDirectory.d.ts +0 -0
  390. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromDirectory.test.d.ts +0 -0
  391. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromPromise.d.ts +0 -0
  392. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromPromise.test.d.ts +0 -0
  393. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromSources.d.ts +0 -0
  394. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromSources.test.d.ts +0 -0
  395. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookLibraryFromUrl.d.ts +0 -0
  396. /package/umd/typings/{promptbook-library → src/library}/constructors/createPromptbookSublibrary.d.ts +0 -0
  397. /package/umd/typings/{promptbook-library → src/library}/constructors/justTestFsImport.d.ts +0 -0
  398. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionTools.d.ts +0 -0
  399. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +0 -0
  400. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/anthropic-claude-models.d.ts +0 -0
  401. /package/umd/typings/{llm-providers → src/llm-providers}/anthropic-claude/playground/playground.d.ts +0 -0
  402. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionTools.d.ts +0 -0
  403. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/AzureOpenAiExecutionToolsOptions.d.ts +0 -0
  404. /package/umd/typings/{llm-providers → src/llm-providers}/azure-openai/playground/playground.d.ts +0 -0
  405. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionTools.d.ts +0 -0
  406. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/LangtailExecutionToolsOptions.d.ts +0 -0
  407. /package/umd/typings/{llm-providers → src/llm-providers}/langtail/playground/playground.d.ts +0 -0
  408. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.d.ts +0 -0
  409. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/fakeTextToExpectations.test.d.ts +0 -0
  410. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/faked-completion.test.d.ts +0 -0
  411. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/joker.test.d.ts +0 -0
  412. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/mocked-chat.test.d.ts +0 -0
  413. /package/umd/typings/{llm-providers → src/llm-providers}/mocked/mocked-completion.test.d.ts +0 -0
  414. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionTools.d.ts +0 -0
  415. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/MultipleLlmExecutionToolsOptions.d.ts +0 -0
  416. /package/umd/typings/{llm-providers → src/llm-providers}/multiple/playground/playground.d.ts +0 -0
  417. /package/umd/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionTools.d.ts +0 -0
  418. /package/umd/typings/{llm-providers → src/llm-providers}/openai/OpenAiExecutionToolsOptions.d.ts +0 -0
  419. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeOpenaiUsage.d.ts +0 -0
  420. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeUsage.d.ts +0 -0
  421. /package/umd/typings/{llm-providers → src/llm-providers}/openai/computeUsage.test.d.ts +0 -0
  422. /package/umd/typings/{llm-providers → src/llm-providers}/openai/openai-models.d.ts +0 -0
  423. /package/umd/typings/{llm-providers → src/llm-providers}/openai/playground/playground.d.ts +0 -0
  424. /package/umd/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionTools.d.ts +0 -0
  425. /package/umd/typings/{llm-providers → src/llm-providers}/remote/RemoteLlmExecutionToolsOptions.d.ts +0 -0
  426. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Error.d.ts +0 -0
  427. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Progress.d.ts +0 -0
  428. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Request.d.ts +0 -0
  429. /package/umd/typings/{llm-providers → src/llm-providers}/remote/interfaces/Promptbook_Server_Response.d.ts +0 -0
  430. /package/umd/typings/{llm-providers → src/llm-providers}/remote/startRemoteServer.d.ts +0 -0
  431. /package/umd/typings/{scripting → src/scripting}/_test/custom-function-async.test.ts.test.d.ts +0 -0
  432. /package/umd/typings/{scripting → src/scripting}/_test/custom-function-missing.test.d.ts +0 -0
  433. /package/umd/typings/{scripting → src/scripting}/_test/custom-function-with-dependencies.test.d.ts +0 -0
  434. /package/umd/typings/{scripting → src/scripting}/_test/custom-function.test.d.ts +0 -0
  435. /package/umd/typings/{scripting → src/scripting}/_test/postprocessing.test.d.ts +0 -0
  436. /package/umd/typings/{scripting → src/scripting}/_test/script-execution-errors.test.d.ts +0 -0
  437. /package/umd/typings/{scripting → src/scripting}/_test/script-execution-tools.test.d.ts +0 -0
  438. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.d.ts +0 -0
  439. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptEvalExecutionTools.test.d.ts +0 -0
  440. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptExecutionTools.d.ts +0 -0
  441. /package/umd/typings/{scripting → src/scripting}/javascript/JavascriptExecutionToolsOptions.d.ts +0 -0
  442. /package/umd/typings/{scripting → src/scripting}/javascript/utils/preserve.d.ts +0 -0
  443. /package/umd/typings/{scripting → src/scripting}/javascript/utils/unknownToString.d.ts +0 -0
  444. /package/umd/typings/{scripting → src/scripting}/python/PythonExecutionTools.d.ts +0 -0
  445. /package/umd/typings/{scripting → src/scripting}/typescript/TypescriptExecutionTools.d.ts +0 -0
  446. /package/umd/typings/{types → src/types}/Command.d.ts +0 -0
  447. /package/umd/typings/{types → src/types}/ExecutionTypes.d.ts +0 -0
  448. /package/umd/typings/{types → src/types}/ModelRequirements.d.ts +0 -0
  449. /package/umd/typings/{types → src/types}/Parameters.d.ts +0 -0
  450. /package/umd/typings/{types → src/types}/Prompt.d.ts +0 -0
  451. /package/umd/typings/{types → src/types}/PromptbookJson/KnowledgeJson.d.ts +0 -0
  452. /package/umd/typings/{types → src/types}/PromptbookJson/PromptTemplateJson.d.ts +0 -0
  453. /package/umd/typings/{types → src/types}/PromptbookJson/PromptTemplateParameterJson.d.ts +0 -0
  454. /package/umd/typings/{types → src/types}/PromptbookJson/PromptbookJson.d.ts +0 -0
  455. /package/umd/typings/{types → src/types}/PromptbookString.d.ts +0 -0
  456. /package/umd/typings/{types → src/types}/ScriptLanguage.d.ts +0 -0
  457. /package/umd/typings/{types → src/types}/TaskProgress.d.ts +0 -0
  458. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportJson.d.ts +0 -0
  459. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportString.d.ts +0 -0
  460. /package/umd/typings/{types → src/types}/execution-report/ExecutionReportStringOptions.d.ts +0 -0
  461. /package/umd/typings/{types → src/types}/execution-report/config.d.ts +0 -0
  462. /package/umd/typings/{types → src/types}/execution-report/countWorkingDuration.d.ts +0 -0
  463. /package/umd/typings/{types → src/types}/execution-report/countWorkingDuration.test.d.ts +0 -0
  464. /package/umd/typings/{types → src/types}/execution-report/executionReportJsonToString.d.ts +0 -0
  465. /package/umd/typings/{types → src/types}/typeAliasEmoji.d.ts +0 -0
  466. /package/umd/typings/{types → src/types}/typeAliases.d.ts +0 -0
  467. /package/umd/typings/{utils → src/utils}/FromtoItems.d.ts +0 -0
  468. /package/umd/typings/{utils → src/utils}/emojis.d.ts +0 -0
  469. /package/umd/typings/{utils → src/utils}/expectation-counters/countCharacters.d.ts +0 -0
  470. /package/umd/typings/{utils → src/utils}/expectation-counters/countCharacters.test.d.ts +0 -0
  471. /package/umd/typings/{utils → src/utils}/expectation-counters/countLines.d.ts +0 -0
  472. /package/umd/typings/{utils → src/utils}/expectation-counters/countLines.test.d.ts +0 -0
  473. /package/umd/typings/{utils → src/utils}/expectation-counters/countPages.d.ts +0 -0
  474. /package/umd/typings/{utils → src/utils}/expectation-counters/countPages.test.d.ts +0 -0
  475. /package/umd/typings/{utils → src/utils}/expectation-counters/countParagraphs.d.ts +0 -0
  476. /package/umd/typings/{utils → src/utils}/expectation-counters/countParagraphs.test.d.ts +0 -0
  477. /package/umd/typings/{utils → src/utils}/expectation-counters/countSentences.d.ts +0 -0
  478. /package/umd/typings/{utils → src/utils}/expectation-counters/countSentences.test.d.ts +0 -0
  479. /package/umd/typings/{utils → src/utils}/expectation-counters/countWords.d.ts +0 -0
  480. /package/umd/typings/{utils → src/utils}/expectation-counters/countWords.test.d.ts +0 -0
  481. /package/umd/typings/{utils → src/utils}/expectation-counters/index.d.ts +0 -0
  482. /package/umd/typings/{utils → src/utils}/extractParameters.d.ts +0 -0
  483. /package/umd/typings/{utils → src/utils}/extractParameters.test.d.ts +0 -0
  484. /package/umd/typings/{utils → src/utils}/formatNumber.d.ts +0 -0
  485. /package/umd/typings/{utils → src/utils}/formatNumber.test.d.ts +0 -0
  486. /package/umd/typings/{utils → src/utils}/getCurrentIsoDate.d.ts +0 -0
  487. /package/umd/typings/{utils → src/utils}/isRunningInWhatever.d.ts +0 -0
  488. /package/umd/typings/{utils → src/utils}/just.d.ts +0 -0
  489. /package/umd/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.d.ts +0 -0
  490. /package/umd/typings/{utils → src/utils}/markdown/addAutoGeneratedSection.test.d.ts +0 -0
  491. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownChart.d.ts +0 -0
  492. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownChart.test.d.ts +0 -0
  493. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownTable.d.ts +0 -0
  494. /package/umd/typings/{utils → src/utils}/markdown/createMarkdownTable.test.d.ts +0 -0
  495. /package/umd/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.d.ts +0 -0
  496. /package/umd/typings/{utils → src/utils}/markdown/escapeMarkdownBlock.test.d.ts +0 -0
  497. /package/umd/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.d.ts +0 -0
  498. /package/umd/typings/{utils → src/utils}/markdown/extractAllBlocksFromMarkdown.test.d.ts +0 -0
  499. /package/umd/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.d.ts +0 -0
  500. /package/umd/typings/{utils → src/utils}/markdown/extractAllListItemsFromMarkdown.test.d.ts +0 -0
  501. /package/umd/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.d.ts +0 -0
  502. /package/umd/typings/{utils → src/utils}/markdown/extractOneBlockFromMarkdown.test.d.ts +0 -0
  503. /package/umd/typings/{utils → src/utils}/markdown/prettifyMarkdown.d.ts +0 -0
  504. /package/umd/typings/{utils → src/utils}/markdown/prettifyMarkdown.test.d.ts +0 -0
  505. /package/umd/typings/{utils → src/utils}/markdown/removeContentComments.d.ts +0 -0
  506. /package/umd/typings/{utils → src/utils}/markdown/removeContentComments.test.d.ts +0 -0
  507. /package/umd/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.d.ts +0 -0
  508. /package/umd/typings/{utils → src/utils}/markdown/removeMarkdownFormatting.test.d.ts +0 -0
  509. /package/umd/typings/{utils → src/utils}/markdown-json/MarkdownStructure.d.ts +0 -0
  510. /package/umd/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.d.ts +0 -0
  511. /package/umd/typings/{utils → src/utils}/markdown-json/countMarkdownStructureDeepness.test.d.ts +0 -0
  512. /package/umd/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.d.ts +0 -0
  513. /package/umd/typings/{utils → src/utils}/markdown-json/markdownToMarkdownStructure.test.d.ts +0 -0
  514. /package/umd/typings/{utils → src/utils}/normalization/DIACRITIC_VARIANTS_LETTERS.d.ts +0 -0
  515. /package/umd/typings/{utils → src/utils}/normalization/IKeywords.d.ts +0 -0
  516. /package/umd/typings/{utils → src/utils}/normalization/capitalize.d.ts +0 -0
  517. /package/umd/typings/{utils → src/utils}/normalization/capitalize.test.d.ts +0 -0
  518. /package/umd/typings/{utils → src/utils}/normalization/decapitalize.d.ts +0 -0
  519. /package/umd/typings/{utils → src/utils}/normalization/decapitalize.test.d.ts +0 -0
  520. /package/umd/typings/{utils → src/utils}/normalization/isValidKeyword.d.ts +0 -0
  521. /package/umd/typings/{utils → src/utils}/normalization/isValidKeyword.test.d.ts +0 -0
  522. /package/umd/typings/{utils → src/utils}/normalization/nameToUriPart.d.ts +0 -0
  523. /package/umd/typings/{utils → src/utils}/normalization/nameToUriPart.test.d.ts +0 -0
  524. /package/umd/typings/{utils → src/utils}/normalization/nameToUriParts.d.ts +0 -0
  525. /package/umd/typings/{utils → src/utils}/normalization/nameToUriParts.test.d.ts +0 -0
  526. /package/umd/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.d.ts +0 -0
  527. /package/umd/typings/{utils → src/utils}/normalization/normalize-to-kebab-case.test.d.ts +0 -0
  528. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.d.ts +0 -0
  529. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_PascalCase.test.d.ts +0 -0
  530. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.d.ts +0 -0
  531. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_SCREAMING_CASE.test.d.ts +0 -0
  532. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.d.ts +0 -0
  533. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_camelCase.test.d.ts +0 -0
  534. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.d.ts +0 -0
  535. /package/umd/typings/{utils → src/utils}/normalization/normalizeTo_snake_case.test.d.ts +0 -0
  536. /package/umd/typings/{utils → src/utils}/normalization/normalizeWhitespaces.d.ts +0 -0
  537. /package/umd/typings/{utils → src/utils}/normalization/normalizeWhitespaces.test.d.ts +0 -0
  538. /package/umd/typings/{utils → src/utils}/normalization/parseKeywords.d.ts +0 -0
  539. /package/umd/typings/{utils → src/utils}/normalization/parseKeywords.test.d.ts +0 -0
  540. /package/umd/typings/{utils → src/utils}/normalization/parseKeywordsFromString.d.ts +0 -0
  541. /package/umd/typings/{utils → src/utils}/normalization/parseKeywordsFromString.test.d.ts +0 -0
  542. /package/umd/typings/{utils → src/utils}/normalization/removeDiacritics.d.ts +0 -0
  543. /package/umd/typings/{utils → src/utils}/normalization/removeDiacritics.test.d.ts +0 -0
  544. /package/umd/typings/{utils → src/utils}/normalization/searchKeywords.d.ts +0 -0
  545. /package/umd/typings/{utils → src/utils}/normalization/searchKeywords.test.d.ts +0 -0
  546. /package/umd/typings/{utils → src/utils}/postprocessing/extractBlock.d.ts +0 -0
  547. /package/umd/typings/{utils → src/utils}/removeEmojis.d.ts +0 -0
  548. /package/umd/typings/{utils → src/utils}/removeEmojis.test.d.ts +0 -0
  549. /package/umd/typings/{utils → src/utils}/removeQuotes.d.ts +0 -0
  550. /package/umd/typings/{utils → src/utils}/removeQuotes.test.d.ts +0 -0
  551. /package/umd/typings/{utils → src/utils}/sets/difference.d.ts +0 -0
  552. /package/umd/typings/{utils → src/utils}/sets/difference.test.d.ts +0 -0
  553. /package/umd/typings/{utils → src/utils}/sets/intersection.d.ts +0 -0
  554. /package/umd/typings/{utils → src/utils}/sets/intersection.test.d.ts +0 -0
  555. /package/umd/typings/{utils → src/utils}/sets/union.d.ts +0 -0
  556. /package/umd/typings/{utils → src/utils}/sets/union.test.d.ts +0 -0
  557. /package/umd/typings/{utils → src/utils}/trimCodeBlock.d.ts +0 -0
  558. /package/umd/typings/{utils → src/utils}/trimCodeBlock.test.d.ts +0 -0
  559. /package/umd/typings/{utils → src/utils}/trimEndOfCodeBlock.d.ts +0 -0
  560. /package/umd/typings/{utils → src/utils}/trimEndOfCodeBlock.test.d.ts +0 -0
  561. /package/umd/typings/{utils → src/utils}/unwrapResult.d.ts +0 -0
  562. /package/umd/typings/{utils → src/utils}/unwrapResult.test.d.ts +0 -0
  563. /package/umd/typings/{utils → src/utils}/validators/url/isValidUrl.d.ts +0 -0
  564. /package/umd/typings/{utils → src/utils}/validators/url/isValidUrl.test.d.ts +0 -0
  565. /package/umd/typings/{version.d.ts → src/version.d.ts} +0 -0
package/esm/index.es.js CHANGED
@@ -137,49 +137,66 @@ var PromptbookSyntaxError = /** @class */ (function (_super) {
137
137
  return PromptbookSyntaxError;
138
138
  }(Error));
139
139
 
140
- // import prepareKnowledgeFromMarkdownStringPromptbook from './prepare-knowledge-from-markdown.ptbk.md';
141
- function prepareKnowledgeFromMarkdown(options) {
142
- return __awaiter(this, void 0, void 0, function () {
143
- return __generator(this, function (_a) {
144
- return [2 /*return*/, []];
145
- });
146
- });
147
- }
140
+ var promptbookLibrary = [{title:"Prepare Knowledge from Markdown",promptbookUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.59.0-22",parameters:[{name:"content",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledge",description:"The knowledge JSON object",isInput:false,isOutput:true}],promptTemplates:[{name:"knowledge",title:"Knowledge",dependentParameterNames:["content"],executionType:"PROMPT_TEMPLATE",modelRequirements:{modelVariant:"CHAT",modelName:"claude-3-opus-20240229"},content:"You are experienced data researcher, extract the important knowledge from the document.\n\n# Rules\n\n- Make pieces of information concise, clear, and easy to understand\n- One piece of information should be approximately 1 paragraph\n- Divide the paragraphs by markdown horizontal lines ---\n- Omit irrelevant information\n- Group redundant information\n- Write just extracted information, nothing else\n\n# The document\n\nTake information from this document:\n\n> {content}",resultingParameterName:"knowledge"}],knowledge:[]}];
148
141
 
149
142
  /**
150
- * Supported script languages
143
+ * This error indicates errors during the execution of the promptbook
151
144
  */
152
- var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
145
+ var PromptbookExecutionError = /** @class */ (function (_super) {
146
+ __extends(PromptbookExecutionError, _super);
147
+ function PromptbookExecutionError(message) {
148
+ var _this = _super.call(this, message) || this;
149
+ _this.name = 'PromptbookExecutionError';
150
+ Object.setPrototypeOf(_this, PromptbookExecutionError.prototype);
151
+ return _this;
152
+ }
153
+ return PromptbookExecutionError;
154
+ }(Error));
153
155
 
154
156
  /**
155
- * Computes the deepness of the markdown structure.
157
+ * Asserts that the execution of a promptnook is successful
156
158
  *
157
- * @private within the library
159
+ * @param executionResult - The partial result of the promptnook execution
160
+ * @throws {PromptbookExecutionError} If the execution is not successful or if multiple errors occurred
158
161
  */
159
- function countMarkdownStructureDeepness(markdownStructure) {
160
- var e_1, _a;
161
- var maxDeepness = 0;
162
- try {
163
- for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
164
- var section = _c.value;
165
- maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
166
- }
162
+ function assertsExecutionSuccessful(executionResult) {
163
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
164
+ if (isSuccessful === true) {
165
+ return;
167
166
  }
168
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
169
- finally {
170
- try {
171
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
172
- }
173
- finally { if (e_1) throw e_1.error; }
167
+ if (errors.length === 0) {
168
+ throw new PromptbookExecutionError("Promptnook Execution failed because of unknown reason");
169
+ }
170
+ else if (errors.length === 1) {
171
+ throw errors[0];
172
+ }
173
+ else {
174
+ throw new PromptbookExecutionError(spaceTrim(function (block) { return "\n Multiple errors occurred during promptnook execution\n\n ".concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n')), "\n "); }));
174
175
  }
175
- return maxDeepness + 1;
176
176
  }
177
+ /**
178
+ * TODO: [🧠] Can this return type be better typed than void
179
+ */
177
180
 
178
181
  /**
179
182
  * The maximum number of iterations for a loops
180
183
  */
181
184
  var LOOP_LIMIT = 1000;
182
185
 
186
+ /**
187
+ * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
188
+ */
189
+ var PromptbookLogicError = /** @class */ (function (_super) {
190
+ __extends(PromptbookLogicError, _super);
191
+ function PromptbookLogicError(message) {
192
+ var _this = _super.call(this, message) || this;
193
+ _this.name = 'PromptbookLogicError';
194
+ Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
195
+ return _this;
196
+ }
197
+ return PromptbookLogicError;
198
+ }(Error));
199
+
183
200
  /**
184
201
  * This error type indicates that the error should not happen and its last check before crashing with some other error
185
202
  */
@@ -195,804 +212,400 @@ var UnexpectedError = /** @class */ (function (_super) {
195
212
  }(Error));
196
213
 
197
214
  /**
198
- * Parse a markdown string into a MarkdownStructure object.
199
- *
200
- * Note: This function does work with code blocks
201
- * Note: This function does not work with markdown comments
202
- *
203
- * @param markdown The markdown string to parse.
204
- * @returns The MarkdownStructure object.
215
+ * Tests if given string is valid URL.
205
216
  *
206
- * @private within the library
217
+ * Note: Dataurl are considered perfectly valid.
207
218
  */
208
- function markdownToMarkdownStructure(markdown) {
209
- var e_1, _a;
210
- var lines = markdown.split('\n');
211
- var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
212
- var current = root;
213
- var isInsideCodeBlock = false;
219
+ function isValidUrl(url) {
220
+ if (typeof url !== 'string') {
221
+ return false;
222
+ }
214
223
  try {
215
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
216
- var line = lines_1_1.value;
217
- var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
218
- if (isInsideCodeBlock || !headingMatch) {
219
- if (line.startsWith('```')) {
220
- isInsideCodeBlock = !isInsideCodeBlock;
221
- }
222
- current.contentLines.push(line);
223
- }
224
- else {
225
- var level = headingMatch.groups.mark.length;
226
- var title = headingMatch.groups.title.trim();
227
- var parent_1 = void 0;
228
- if (level > current.level) {
229
- // Note: Going deeper (next section is child of current)
230
- parent_1 = current;
231
- }
232
- else {
233
- // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
234
- parent_1 = current;
235
- var loopLimit = LOOP_LIMIT;
236
- while (parent_1.level !== level - 1) {
237
- if (loopLimit-- < 0) {
238
- throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
239
- }
240
- if (parent_1.parent === null /* <- Note: We are in root */) {
241
- // [🌻]
242
- throw new Error(spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
243
- }
244
- parent_1 = parent_1.parent;
245
- }
246
- }
247
- var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
248
- parent_1.sections.push(section);
249
- current = section;
250
- }
224
+ if (url.startsWith('blob:')) {
225
+ url = url.replace(/^blob:/, '');
251
226
  }
252
- }
253
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
254
- finally {
255
- try {
256
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
227
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
228
+ var urlObject = new URL(url);
229
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
230
+ return false;
257
231
  }
258
- finally { if (e_1) throw e_1.error; }
232
+ return true;
259
233
  }
260
- if (root.sections.length === 1) {
261
- var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
262
- return markdownStructure;
234
+ catch (error) {
235
+ return false;
263
236
  }
264
- // [🌻]
265
- throw new Error('The markdown file must have exactly one top-level section.');
266
- // return root;
267
- }
268
- /**
269
- * @private
270
- */
271
- function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
272
- var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
273
- return {
274
- level: level,
275
- title: title,
276
- content: spaceTrim(contentLines.join('\n')),
277
- sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
278
- };
279
237
  }
280
238
 
281
239
  /**
282
- * Utility function to extract all list items from markdown
240
+ * Validates PromptbookJson if it is logically valid
283
241
  *
284
- * Note: It works with both ul and ol
285
- * Note: It omits list items in code blocks
286
- * Note: It flattens nested lists
287
- * Note: It can not work with html syntax and comments
242
+ * It checks:
243
+ * - if it has correct parameters dependency
288
244
  *
289
- * @param markdown any valid markdown
290
- * @returns
245
+ * It does NOT check:
246
+ * - if it is valid json
247
+ * - if it is meaningful
248
+ *
249
+ * @param promptbook valid or invalid PromptbookJson
250
+ * @returns the same promptbook if it is logically valid
251
+ * @throws {PromptbookLogicError} on logical error in the promptbook
291
252
  */
292
- function extractAllListItemsFromMarkdown(markdown) {
293
- var e_1, _a;
294
- var lines = markdown.split('\n');
295
- var listItems = [];
296
- var isInCodeBlock = false;
253
+ function validatePromptbookJson(promptbook) {
254
+ // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
255
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
256
+ if (promptbook.promptbookUrl !== undefined) {
257
+ if (!isValidUrl(promptbook.promptbookUrl)) {
258
+ // TODO: This should be maybe the syntax error detected during parsing
259
+ throw new PromptbookLogicError("Invalid promptbook URL \"".concat(promptbook.promptbookUrl, "\""));
260
+ }
261
+ }
262
+ // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
263
+ if (!Array.isArray(promptbook.parameters)) {
264
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
265
+ throw new PromptbookSyntaxError(spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.parameters expected to be an array, but got ".concat(typeof promptbook.parameters, "\n ")));
266
+ }
267
+ // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
268
+ if (!Array.isArray(promptbook.promptTemplates)) {
269
+ // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
270
+ throw new PromptbookSyntaxError(spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.promptTemplates expected to be an array, but got ".concat(typeof promptbook.promptTemplates, "\n ")));
271
+ }
272
+ var _loop_1 = function (parameter) {
273
+ if (parameter.isInput && parameter.isOutput) {
274
+ throw new PromptbookLogicError("Parameter {".concat(parameter.name, "} can not be both input and output"));
275
+ }
276
+ // Note: Testing that parameter is either intermediate or output BUT not created and unused
277
+ if (!parameter.isInput &&
278
+ !parameter.isOutput &&
279
+ !promptbook.promptTemplates.some(function (template) { return template.dependentParameterNames.includes(parameter.name); })) {
280
+ throw new PromptbookLogicError(spaceTrim("\n Parameter {".concat(parameter.name, "} is created but not used\n\n You can declare {").concat(parameter.name, "} as output parameter by adding in the header:\n - OUTPUT PARAMETER `{").concat(parameter.name, "}` ").concat(parameter.description || '', "\n\n ")));
281
+ }
282
+ // Note: Testing that parameter is either input or result of some template
283
+ if (!parameter.isInput &&
284
+ !promptbook.promptTemplates.some(function (template) { return template.resultingParameterName === parameter.name; })) {
285
+ throw new PromptbookLogicError(spaceTrim("\n Parameter {".concat(parameter.name, "} is declared but not defined\n\n You can do one of these:\n - Remove declaration of {").concat(parameter.name, "}\n - Add prompt template that results in -> {").concat(parameter.name, "}\n\n ")));
286
+ }
287
+ };
297
288
  try {
298
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
299
- var line = lines_1_1.value;
300
- var trimmedLine = line.trim();
301
- if (trimmedLine.startsWith('```')) {
302
- isInCodeBlock = !isInCodeBlock;
303
- }
304
- if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
305
- var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
306
- listItems.push(listItem);
307
- }
289
+ // Note: Check each parameter individually
290
+ for (var _e = __values(promptbook.parameters), _f = _e.next(); !_f.done; _f = _e.next()) {
291
+ var parameter = _f.value;
292
+ _loop_1(parameter);
308
293
  }
309
294
  }
310
295
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
311
296
  finally {
312
297
  try {
313
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
298
+ if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
314
299
  }
315
300
  finally { if (e_1) throw e_1.error; }
316
301
  }
317
- return listItems;
318
- }
319
-
320
- /**
321
- * Makes first letter of a string uppercase
322
- *
323
- */
324
- function capitalize(word) {
325
- return word.substring(0, 1).toUpperCase() + word.substring(1);
326
- }
327
-
328
- /**
329
- * Extracts all code blocks from markdown.
330
- *
331
- * Note: There are 3 simmilar function:
332
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
333
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
334
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
335
- *
336
- * @param markdown any valid markdown
337
- * @returns code blocks with language and content
338
- *
339
- */
340
- function extractAllBlocksFromMarkdown(markdown) {
341
- var e_1, _a;
342
- var codeBlocks = [];
343
- var lines = markdown.split('\n');
344
- var currentCodeBlock = null;
302
+ // Note: Check each template individually
303
+ var definedParameters = new Set(promptbook.parameters.filter(function (_a) {
304
+ var isInput = _a.isInput;
305
+ return isInput;
306
+ }).map(function (_a) {
307
+ var name = _a.name;
308
+ return name;
309
+ }));
345
310
  try {
346
- for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
347
- var line = lines_1_1.value;
348
- if (line.startsWith('```')) {
349
- var language = line.slice(3).trim() || null;
350
- if (currentCodeBlock === null) {
351
- currentCodeBlock = { language: language, content: '' };
352
- }
353
- else {
354
- if (language !== null) {
355
- // [🌻]
356
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
311
+ for (var _g = __values(promptbook.promptTemplates), _h = _g.next(); !_h.done; _h = _g.next()) {
312
+ var template = _h.value;
313
+ if (definedParameters.has(template.resultingParameterName)) {
314
+ throw new PromptbookLogicError("Parameter {".concat(template.resultingParameterName, "} is defined multiple times"));
315
+ }
316
+ definedParameters.add(template.resultingParameterName);
317
+ if (template.executionType === 'PROMPT_TEMPLATE' &&
318
+ (template.modelRequirements.modelVariant === undefined)) {
319
+ throw new PromptbookLogicError(spaceTrim("\n\n You must specify MODEL VARIANT in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
320
+ }
321
+ if (template.jokers && template.jokers.length > 0) {
322
+ if (!template.expectFormat &&
323
+ !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
324
+ throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
325
+ }
326
+ try {
327
+ for (var _j = (e_3 = void 0, __values(template.jokers)), _k = _j.next(); !_k.done; _k = _j.next()) {
328
+ var joker = _k.value;
329
+ if (!template.dependentParameterNames.includes(joker)) {
330
+ throw new PromptbookLogicError("Parameter {".concat(joker, "} is used for {").concat(template.resultingParameterName, "} as joker but not in dependentParameterNames"));
331
+ }
357
332
  }
358
- codeBlocks.push(currentCodeBlock);
359
- currentCodeBlock = null;
333
+ }
334
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
335
+ finally {
336
+ try {
337
+ if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
338
+ }
339
+ finally { if (e_3) throw e_3.error; }
360
340
  }
361
341
  }
362
- else if (currentCodeBlock !== null) {
363
- if (currentCodeBlock.content !== '') {
364
- currentCodeBlock.content += '\n';
342
+ if (template.expectations) {
343
+ try {
344
+ for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
345
+ var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
346
+ if (min !== undefined && max !== undefined && min > max) {
347
+ throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
348
+ }
349
+ if (min !== undefined && min < 0) {
350
+ throw new PromptbookLogicError("Min expectation of ".concat(unit, " must be zero or positive"));
351
+ }
352
+ if (max !== undefined && max <= 0) {
353
+ throw new PromptbookLogicError("Max expectation of ".concat(unit, " must be positive"));
354
+ }
355
+ }
356
+ }
357
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
358
+ finally {
359
+ try {
360
+ if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
361
+ }
362
+ finally { if (e_4) throw e_4.error; }
365
363
  }
366
- currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
367
364
  }
368
365
  }
369
366
  }
370
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
367
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
371
368
  finally {
372
369
  try {
373
- if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
370
+ if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
374
371
  }
375
- finally { if (e_1) throw e_1.error; }
372
+ finally { if (e_2) throw e_2.error; }
376
373
  }
377
- if (currentCodeBlock !== null) {
378
- // [🌻]
379
- throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
374
+ // Note: Detect circular dependencies
375
+ var resovedParameters = promptbook.parameters
376
+ .filter(function (_a) {
377
+ var isInput = _a.isInput;
378
+ return isInput;
379
+ })
380
+ .map(function (_a) {
381
+ var name = _a.name;
382
+ return name;
383
+ });
384
+ var unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
385
+ var loopLimit = LOOP_LIMIT;
386
+ var _loop_2 = function () {
387
+ if (loopLimit-- < 0) {
388
+ throw new UnexpectedError('Loop limit reached during detection of circular dependencies in `validatePromptbookJson`');
389
+ }
390
+ var currentlyResovedTemplates = unresovedTemplates.filter(function (template) {
391
+ return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
392
+ });
393
+ if (currentlyResovedTemplates.length === 0) {
394
+ throw new PromptbookLogicError(spaceTrim(function (block) { return "\n\n Can not resolve some parameters\n It may be circular dependencies\n\n Can not resolve:\n ".concat(block(unresovedTemplates
395
+ .map(function (_a) {
396
+ var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
397
+ return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
398
+ .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
399
+ .join(', '));
400
+ })
401
+ .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
402
+ }
403
+ resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), __read(currentlyResovedTemplates.map(function (_a) {
404
+ var resultingParameterName = _a.resultingParameterName;
405
+ return resultingParameterName;
406
+ })), false);
407
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return !currentlyResovedTemplates.includes(template); });
408
+ };
409
+ while (unresovedTemplates.length > 0) {
410
+ _loop_2();
380
411
  }
381
- return codeBlocks;
412
+ return promptbook;
382
413
  }
414
+ /**
415
+ * TODO: [🧠] Work with promptbookVersion
416
+ * TODO: Use here some json-schema, Zod or something similar and change it to:
417
+ * > /**
418
+ * > * Validates PromptbookJson if it is logically valid.
419
+ * > *
420
+ * > * It checks:
421
+ * > * - it has a valid structure
422
+ * > * - ...
423
+ * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
424
+ */
383
425
 
384
426
  /**
385
- * Extracts exactly ONE code block from markdown.
386
- *
387
- * Note: If there are multiple or no code blocks the function throws an error
388
- *
389
- * Note: There are 3 simmilar function:
390
- * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
391
- * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
392
- * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
427
+ * This error occurs when some expectation is not met in the execution of the pipeline
393
428
  *
394
- * @param markdown any valid markdown
395
- * @returns code block with language and content
429
+ * @private Always catched and rethrown as `PromptbookExecutionError`
430
+ * Note: This is a kindof subtype of PromptbookExecutionError
396
431
  */
397
- function extractOneBlockFromMarkdown(markdown) {
398
- var codeBlocks = extractAllBlocksFromMarkdown(markdown);
399
- if (codeBlocks.length !== 1) {
400
- // TODO: Report more specific place where the error happened
401
- throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
432
+ var ExpectError = /** @class */ (function (_super) {
433
+ __extends(ExpectError, _super);
434
+ function ExpectError(message) {
435
+ var _this = _super.call(this, message) || this;
436
+ _this.name = 'ExpectError';
437
+ Object.setPrototypeOf(_this, ExpectError.prototype);
438
+ return _this;
402
439
  }
403
- return codeBlocks[0];
404
- }
405
- /***
406
- * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
407
- */
440
+ return ExpectError;
441
+ }(Error));
408
442
 
409
443
  /**
410
- * Removes HTML or Markdown comments from a string.
411
- *
412
- * @param {string} content - The string to remove comments from.
413
- * @returns {string} The input string with all comments removed.
444
+ * Function isValidJsonString will tell you if the string is valid JSON or not
414
445
  */
415
- function removeContentComments(content) {
416
- return spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
446
+ function isValidJsonString(value /* <-[👨‍⚖️] */) {
447
+ try {
448
+ JSON.parse(value);
449
+ return true;
450
+ }
451
+ catch (error) {
452
+ if (!(error instanceof Error)) {
453
+ throw error;
454
+ }
455
+ if (error.message.includes('Unexpected token')) {
456
+ return false;
457
+ }
458
+ return false;
459
+ }
417
460
  }
418
461
 
419
462
  /**
420
- * Creates a new set with all elements that are present in either set
463
+ * The version of the Promptbook library
421
464
  */
422
- function union() {
423
- var e_1, _a, e_2, _b;
424
- var sets = [];
465
+ var PROMPTBOOK_VERSION = '0.59.0-22';
466
+
467
+ /**
468
+ * Function `addUsage` will add multiple usages into one
469
+ *
470
+ * Note: If you provide 0 values, it returns void usage
471
+ */
472
+ function addUsage() {
473
+ var usageItems = [];
425
474
  for (var _i = 0; _i < arguments.length; _i++) {
426
- sets[_i] = arguments[_i];
427
- }
428
- var union = new Set();
429
- try {
430
- for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
431
- var set = sets_1_1.value;
432
- try {
433
- for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
434
- var item = _d.value;
435
- union.add(item);
475
+ usageItems[_i] = arguments[_i];
476
+ }
477
+ var initialStructure = {
478
+ price: { value: 0 },
479
+ input: {
480
+ tokensCount: { value: 0 },
481
+ charactersCount: { value: 0 },
482
+ wordsCount: { value: 0 },
483
+ sentencesCount: { value: 0 },
484
+ linesCount: { value: 0 },
485
+ paragraphsCount: { value: 0 },
486
+ pagesCount: { value: 0 },
487
+ },
488
+ output: {
489
+ tokensCount: { value: 0 },
490
+ charactersCount: { value: 0 },
491
+ wordsCount: { value: 0 },
492
+ sentencesCount: { value: 0 },
493
+ linesCount: { value: 0 },
494
+ paragraphsCount: { value: 0 },
495
+ pagesCount: { value: 0 },
496
+ },
497
+ };
498
+ return usageItems.reduce(function (acc, item) {
499
+ var e_1, _a, e_2, _b;
500
+ var _c;
501
+ acc.price.value += ((_c = item.price) === null || _c === void 0 ? void 0 : _c.value) || 0;
502
+ try {
503
+ for (var _d = __values(Object.keys(acc.input)), _e = _d.next(); !_e.done; _e = _d.next()) {
504
+ var key = _e.value;
505
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
506
+ //@ts-ignore
507
+ if (item.input[key]) {
508
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
509
+ //@ts-ignore
510
+ acc.input[key].value += item.input[key].value || 0;
511
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
512
+ //@ts-ignore
513
+ if (item.input[key].isUncertain) {
514
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
515
+ //@ts-ignore
516
+ acc.input[key].isUncertain = true;
517
+ }
436
518
  }
437
519
  }
438
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
439
- finally {
440
- try {
441
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
442
- }
443
- finally { if (e_2) throw e_2.error; }
520
+ }
521
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
522
+ finally {
523
+ try {
524
+ if (_e && !_e.done && (_a = _d.return)) _a.call(_d);
444
525
  }
526
+ finally { if (e_1) throw e_1.error; }
445
527
  }
446
- }
447
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
448
- finally {
449
528
  try {
450
- if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
529
+ for (var _f = __values(Object.keys(acc.output)), _g = _f.next(); !_g.done; _g = _f.next()) {
530
+ var key = _g.value;
531
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
532
+ //@ts-ignore
533
+ if (item.output[key]) {
534
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
535
+ //@ts-ignore
536
+ acc.output[key].value += item.output[key].value || 0;
537
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
538
+ //@ts-ignore
539
+ if (item.output[key].isUncertain) {
540
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
541
+ //@ts-ignore
542
+ acc.output[key].isUncertain = true;
543
+ }
544
+ }
545
+ }
451
546
  }
452
- finally { if (e_1) throw e_1.error; }
453
- }
454
- return union;
547
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
548
+ finally {
549
+ try {
550
+ if (_g && !_g.done && (_b = _f.return)) _b.call(_f);
551
+ }
552
+ finally { if (e_2) throw e_2.error; }
553
+ }
554
+ return acc;
555
+ }, initialStructure);
455
556
  }
456
557
 
457
558
  /**
458
- * The version of the Promptbook library
559
+ * Counts number of characters in the text
459
560
  */
460
- var PROMPTBOOK_VERSION = '0.59.0-1';
561
+ function countCharacters(text) {
562
+ // Remove null characters
563
+ text = text.replace(/\0/g, '');
564
+ // Replace emojis (and also ZWJ sequence) with hyphens
565
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
566
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
567
+ text = text.replace(/\p{Extended_Pictographic}(\u{200D}\p{Extended_Pictographic})*/gu, '-');
568
+ return text.length;
569
+ }
461
570
 
462
571
  /**
463
- * Parses the template and returns the list of all parameter names
464
- *
465
- * @param template the template with parameters in {curly} braces
466
- * @returns the list of parameter names
572
+ * Counts number of lines in the text
467
573
  */
468
- function extractParameters(template) {
469
- var e_1, _a;
470
- var matches = template.matchAll(/{\w+}/g);
471
- var parameterNames = new Set();
472
- try {
473
- for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
474
- var match = matches_1_1.value;
475
- var parameterName = match[0].slice(1, -1);
476
- parameterNames.add(parameterName);
477
- }
478
- }
479
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
480
- finally {
481
- try {
482
- if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
483
- }
484
- finally { if (e_1) throw e_1.error; }
574
+ function countLines(text) {
575
+ if (text === '') {
576
+ return 0;
485
577
  }
486
- return parameterNames;
578
+ return text.split('\n').length;
487
579
  }
488
580
 
489
581
  /**
490
- * Parses the given script and returns the list of all used variables that are not defined in the script
491
- *
492
- * @param script from which to extract the variables
493
- * @returns the list of variable names
494
- * @throws {PromptbookSyntaxError} if the script is invalid
582
+ * Counts number of pages in the text
495
583
  */
496
- function extractVariables(script) {
497
- var variables = new Set();
498
- script = "(()=>{".concat(script, "})()");
499
- try {
500
- for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
501
- try {
502
- eval(script);
503
- }
504
- catch (error) {
505
- if (!(error instanceof ReferenceError)) {
506
- throw error;
507
- }
508
- var undefinedName = error.message.split(' ')[0];
509
- /*
510
- Note: Remapping error
511
- From: [ReferenceError: thing is not defined],
512
- To: [Error: Parameter {thing} is not defined],
513
- */
514
- if (!undefinedName) {
515
- throw error;
516
- }
517
- if (script.includes(undefinedName + '(')) {
518
- script = "const ".concat(undefinedName, " = ()=>'';") + script;
519
- }
520
- else {
521
- variables.add(undefinedName);
522
- script = "const ".concat(undefinedName, " = '';") + script;
523
- }
524
- }
525
- }
526
- catch (error) {
527
- if (!(error instanceof Error)) {
528
- throw error;
529
- }
530
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
531
- }
532
- return variables;
584
+ function countPages(text) {
585
+ var sentencesPerPage = 5; // Assuming each page has 5 sentences
586
+ var sentences = text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
587
+ var pageCount = Math.ceil(sentences.length / sentencesPerPage);
588
+ return pageCount;
533
589
  }
534
- /**
535
- * TODO: [🔣] Support for multiple languages - python, java,...
536
- */
537
590
 
538
591
  /**
539
- * Parses the prompt template and returns the set of all used parameters
540
- *
541
- * @param promptTemplate the template with used parameters
542
- * @returns the set of parameter names
543
- * @throws {PromptbookSyntaxError} if the script is invalid
544
- */
545
- function extractParametersFromPromptTemplate(promptTemplate) {
546
- var e_1, _a, e_2, _b;
547
- var parameterNames = new Set();
548
- try {
549
- for (var _c = __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(promptTemplate.title)), false), __read(extractParameters(promptTemplate.description || '')), false), __read(extractParameters(promptTemplate.content)), false)), _d = _c.next(); !_d.done; _d = _c.next()) {
550
- var parameterName = _d.value;
551
- parameterNames.add(parameterName);
552
- }
553
- }
554
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
555
- finally {
556
- try {
557
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
558
- }
559
- finally { if (e_1) throw e_1.error; }
560
- }
561
- if (promptTemplate.executionType === 'SCRIPT') {
562
- try {
563
- for (var _e = __values(extractVariables(promptTemplate.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
564
- var parameterName = _f.value;
565
- parameterNames.add(parameterName);
566
- }
567
- }
568
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
569
- finally {
570
- try {
571
- if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
572
- }
573
- finally { if (e_2) throw e_2.error; }
574
- }
575
- }
576
- return parameterNames;
577
- }
578
- /**
579
- * TODO: [🔣] If script require contentLanguage
592
+ * Counts number of paragraphs in the text
580
593
  */
581
-
582
- /* tslint:disable */
583
- /*
584
- TODO: Tests
585
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
586
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
587
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
588
- expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
589
- */
590
- function normalizeTo_SCREAMING_CASE(sentence) {
591
- var e_1, _a;
592
- var charType;
593
- var lastCharType = 'OTHER';
594
- var normalizedName = '';
595
- try {
596
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
597
- var char = sentence_1_1.value;
598
- var normalizedChar = void 0;
599
- if (/^[a-z]$/.test(char)) {
600
- charType = 'LOWERCASE';
601
- normalizedChar = char.toUpperCase();
602
- }
603
- else if (/^[A-Z]$/.test(char)) {
604
- charType = 'UPPERCASE';
605
- normalizedChar = char;
606
- }
607
- else if (/^[0-9]$/.test(char)) {
608
- charType = 'NUMBER';
609
- normalizedChar = char;
610
- }
611
- else if (/^\/$/.test(char)) {
612
- charType = 'SLASH';
613
- normalizedChar = char;
614
- }
615
- else {
616
- charType = 'OTHER';
617
- normalizedChar = '_';
618
- }
619
- if (charType !== lastCharType &&
620
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
621
- !(lastCharType === 'NUMBER') &&
622
- !(charType === 'NUMBER')) {
623
- normalizedName += '_';
624
- }
625
- normalizedName += normalizedChar;
626
- lastCharType = charType;
627
- }
628
- }
629
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
630
- finally {
631
- try {
632
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
633
- }
634
- finally { if (e_1) throw e_1.error; }
635
- }
636
- normalizedName = normalizedName.replace(/_+/g, '_');
637
- normalizedName = normalizedName.replace(/_?\/_?/g, '/');
638
- normalizedName = normalizedName.replace(/^_/, '');
639
- normalizedName = normalizedName.replace(/_$/, '');
640
- return normalizedName;
594
+ function countParagraphs(text) {
595
+ return text.split(/\n\s*\n/).filter(function (paragraph) { return paragraph.trim() !== ''; }).length;
641
596
  }
642
- /**
643
- * TODO: [🌺] Use some intermediate util splitWords
644
- */
645
-
646
- /**
647
- * Execution type describes the way how the block is executed
648
- *
649
- * @see https://github.com/webgptorg/promptbook#execution-type
650
- */
651
- var ExecutionTypes = [
652
- 'PROMPT_TEMPLATE',
653
- 'SIMPLE_TEMPLATE',
654
- 'SCRIPT',
655
- 'PROMPT_DIALOG',
656
- // <- [🥻] Insert here when making new command
657
- ];
658
-
659
- /**
660
- * Units of text measurement
661
- */
662
- var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
663
- /**
664
- * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
665
- * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
666
- * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
667
- */
668
597
 
669
598
  /**
670
- * Removes Markdown formatting tags from a string.
671
- *
672
- * @param {string} str - The string to remove Markdown tags from.
673
- * @returns {string} The input string with all Markdown tags removed.
599
+ * Split text into sentences
674
600
  */
675
- function removeMarkdownFormatting(str) {
676
- // Remove bold formatting
677
- str = str.replace(/\*\*(.*?)\*\*/g, '$1');
678
- // Remove italic formatting
679
- str = str.replace(/\*(.*?)\*/g, '$1');
680
- // Remove code formatting
681
- str = str.replace(/`(.*?)`/g, '$1');
682
- return str;
601
+ function splitIntoSentences(text) {
602
+ return text.split(/[.!?]+/).filter(function (sentence) { return sentence.trim() !== ''; });
683
603
  }
684
-
685
604
  /**
686
- * Function parseNumber will parse number from string
687
- *
688
- * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
689
- * Note: it also works only with decimal numbers
690
- *
691
- * @returns parsed number
692
- * @throws {PromptbookSyntaxError} if the value is not a number
693
- *
694
- * @private within the parseCommand
605
+ * Counts number of sentences in the text
695
606
  */
696
- function parseNumber(value) {
697
- var originalValue = value;
698
- if (typeof value === 'number') {
699
- value = value.toString(); // <- TODO: Maybe more efficient way to do this
700
- }
701
- if (typeof value !== 'string') {
702
- return 0;
703
- }
704
- value = value.trim();
705
- if (value.startsWith('+')) {
706
- return parseNumber(value.substring(1));
707
- }
708
- if (value.startsWith('-')) {
709
- var number = parseNumber(value.substring(1));
710
- if (number === 0) {
711
- return 0; // <- Note: To prevent -0
712
- }
713
- return -number;
714
- }
715
- value = value.replace(/,/g, '.');
716
- value = value.toUpperCase();
717
- if (value === '') {
718
- return 0;
719
- }
720
- if (value === '♾' || value.startsWith('INF')) {
721
- return Infinity;
722
- }
723
- if (value.includes('/')) {
724
- var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
725
- var numerator = parseNumber(numerator_);
726
- var denominator = parseNumber(denominator_);
727
- if (denominator === 0) {
728
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
729
- }
730
- return numerator / denominator;
731
- }
732
- if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
733
- return 0;
734
- }
735
- if (value.includes('E')) {
736
- var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
737
- return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
738
- }
739
- if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
740
- throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
741
- }
742
- var num = parseFloat(value);
743
- if (isNaN(num)) {
744
- throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
745
- }
746
- return num;
747
- }
748
- /**
749
- * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
750
- */
751
-
752
- /**
753
- * Parses one line of ul/ol to command
754
- *
755
- * @returns parsed command object
756
- * @throws {PromptbookSyntaxError} if the command is invalid
757
- *
758
- * @private within the promptbookStringToJson
759
- */
760
- function parseCommand(listItem) {
761
- var e_1, _a;
762
- if (listItem.includes('\n') || listItem.includes('\r')) {
763
- throw new PromptbookSyntaxError('Command can not contain new line characters:');
764
- }
765
- var type = listItem.trim();
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 = type.split(']').join('');
772
- type = type.split('(').join('');
773
- type = type.split(')').join('');
774
- type = normalizeTo_SCREAMING_CASE(type);
775
- type = type.split('DIALOGUE').join('DIALOG');
776
- var listItemParts = listItem
777
- .split(' ')
778
- .map(function (part) { return part.trim(); })
779
- .filter(function (item) { return item !== ''; })
780
- .filter(function (item) { return !/^PTBK$/i.test(item); })
781
- .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
782
- .map(removeMarkdownFormatting);
783
- if (type.startsWith('URL') ||
784
- type.startsWith('PTBK_URL') ||
785
- type.startsWith('PTBKURL') ||
786
- type.startsWith('PROMPTBOOK_URL') ||
787
- type.startsWith('PROMPTBOOKURL') ||
788
- type.startsWith('HTTPS')) {
789
- if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
790
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
791
- }
792
- var promptbookUrlString = listItemParts.pop();
793
- var promptbookUrl = new URL(promptbookUrlString);
794
- if (promptbookUrl.protocol !== 'https:') {
795
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
796
- }
797
- if (promptbookUrl.hash !== '') {
798
- throw new PromptbookSyntaxError(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 ")));
799
- }
800
- return {
801
- type: 'PROMPTBOOK_URL',
802
- promptbookUrl: promptbookUrl,
803
- };
804
- }
805
- else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
806
- if (listItemParts.length !== 2) {
807
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
808
- }
809
- var promptbookVersion = listItemParts.pop();
810
- // TODO: Validate version
811
- return {
812
- type: 'PROMPTBOOK_VERSION',
813
- promptbookVersion: promptbookVersion,
814
- };
815
- }
816
- else if (type.startsWith('EXECUTE') ||
817
- type.startsWith('EXEC') ||
818
- type.startsWith('PROMPT_DIALOG') ||
819
- type.startsWith('SIMPLE_TEMPLATE')) {
820
- var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
821
- if (executionTypes.length !== 1) {
822
- throw new PromptbookSyntaxError(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 "); }));
823
- }
824
- return {
825
- type: 'EXECUTE',
826
- executionType: executionTypes[0],
827
- };
828
- }
829
- else if (type.startsWith('MODEL')) {
830
- // TODO: Make this more elegant and dynamically
831
- if (type.startsWith('MODEL_VARIANT')) {
832
- if (type === 'MODEL_VARIANT_CHAT') {
833
- return {
834
- type: 'MODEL',
835
- key: 'modelVariant',
836
- value: 'CHAT',
837
- };
838
- }
839
- else if (type === 'MODEL_VARIANT_COMPLETION') {
840
- return {
841
- type: 'MODEL',
842
- key: 'modelVariant',
843
- value: 'COMPLETION',
844
- };
845
- }
846
- else {
847
- throw new PromptbookSyntaxError(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 "); }));
848
- }
849
- }
850
- if (type.startsWith('MODEL_NAME')) {
851
- return {
852
- type: 'MODEL',
853
- key: 'modelName',
854
- value: listItemParts.pop(),
855
- };
856
- }
857
- else {
858
- throw new PromptbookSyntaxError(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 "); }));
859
- }
860
- }
861
- else if (type.startsWith('PARAM') ||
862
- type.startsWith('INPUT_PARAM') ||
863
- type.startsWith('OUTPUT_PARAM') ||
864
- listItem.startsWith('{') ||
865
- listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
866
- var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
867
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
868
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
869
- }
870
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
871
- var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
872
- if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
873
- throw new PromptbookSyntaxError(spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
874
- }
875
- var isInput = type.startsWith('INPUT');
876
- var isOutput = type.startsWith('OUTPUT');
877
- if (listItem.startsWith('> {')) {
878
- isInput = false;
879
- isOutput = false;
880
- }
881
- return {
882
- type: 'PARAMETER',
883
- parameterName: parameterName,
884
- parameterDescription: parameterDescription.trim() || null,
885
- isInput: isInput,
886
- isOutput: isOutput,
887
- };
888
- }
889
- else if (type.startsWith('JOKER')) {
890
- if (listItemParts.length !== 2) {
891
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
892
- }
893
- var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
894
- if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
895
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
896
- }
897
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
898
- var parameterName = parametersMatch.groups.parameterName;
899
- return {
900
- type: 'JOKER',
901
- parameterName: parameterName,
902
- };
903
- }
904
- else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
905
- if (listItemParts.length !== 2) {
906
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
907
- }
908
- var functionName = listItemParts.pop();
909
- return {
910
- type: 'POSTPROCESS',
911
- functionName: functionName,
912
- };
913
- }
914
- else if (type.startsWith('EXPECT_JSON')) {
915
- return {
916
- type: 'EXPECT_FORMAT',
917
- format: 'JSON',
918
- };
919
- // [🥤]
920
- }
921
- else if (type.startsWith('EXPECT')) {
922
- try {
923
- listItemParts.shift();
924
- var sign = void 0;
925
- var signRaw = listItemParts.shift();
926
- if (/^exact/i.test(signRaw)) {
927
- sign = 'EXACTLY';
928
- }
929
- else if (/^min/i.test(signRaw)) {
930
- sign = 'MINIMUM';
931
- }
932
- else if (/^max/i.test(signRaw)) {
933
- sign = 'MAXIMUM';
934
- }
935
- else {
936
- throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
937
- }
938
- var amountRaw = listItemParts.shift();
939
- var amount = parseNumber(amountRaw);
940
- if (amount < 0) {
941
- throw new PromptbookSyntaxError('Amount must be positive number or zero');
942
- }
943
- if (amount !== Math.floor(amount)) {
944
- throw new PromptbookSyntaxError('Amount must be whole number');
945
- }
946
- var unitRaw = listItemParts.shift();
947
- var unit = undefined;
948
- try {
949
- 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()) {
950
- var existingUnit = EXPECTATION_UNITS_1_1.value;
951
- var existingUnitText = existingUnit;
952
- existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
953
- if (existingUnitText === 'CHARACTER') {
954
- existingUnitText = 'CHAR';
955
- }
956
- if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
957
- new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
958
- if (unit !== undefined) {
959
- throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
960
- }
961
- unit = existingUnit;
962
- }
963
- }
964
- }
965
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
966
- finally {
967
- try {
968
- if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
969
- }
970
- finally { if (e_1) throw e_1.error; }
971
- }
972
- if (unit === undefined) {
973
- throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
974
- }
975
- return {
976
- type: 'EXPECT_AMOUNT',
977
- sign: sign,
978
- unit: unit,
979
- amount: amount,
980
- };
981
- }
982
- catch (error) {
983
- if (!(error instanceof Error)) {
984
- throw error;
985
- }
986
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
987
- }
988
- /*
989
- } else if (type.startsWith('__________________')) {
990
- // <- [🥻] Insert here when making new command
991
- */
992
- }
993
- else {
994
- throw new PromptbookSyntaxError(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 ")));
995
- }
607
+ function countSentences(text) {
608
+ return splitIntoSentences(text).length;
996
609
  }
997
610
 
998
611
  var defaultDiacriticsRemovalMap = [
@@ -1247,674 +860,744 @@ function removeDiacritics(input) {
1247
860
  });
1248
861
  }
1249
862
 
1250
- /* tslint:disable */
1251
- function normalizeToKebabCase(sentence) {
863
+ /**
864
+ * Counts number of words in the text
865
+ */
866
+ function countWords(text) {
867
+ text = text.replace(/[\p{Extended_Pictographic}]/gu, 'a');
868
+ text = removeDiacritics(text);
869
+ return text.split(/[^a-zа-я0-9]+/i).filter(function (word) { return word.length > 0; }).length;
870
+ }
871
+
872
+ /**
873
+ * Index of all counter functions
874
+ */
875
+ var CountUtils = {
876
+ CHARACTERS: countCharacters,
877
+ WORDS: countWords,
878
+ SENTENCES: countSentences,
879
+ PARAGRAPHS: countParagraphs,
880
+ LINES: countLines,
881
+ PAGES: countPages,
882
+ };
883
+
884
+ /**
885
+ * Function checkExpectations will check if the expectations on given value are met
886
+ *
887
+ * Note: There are two simmilar functions:
888
+ * - `checkExpectations` which throws an error if the expectations are not met
889
+ * - `isPassingExpectations` which returns a boolean
890
+ *
891
+ * @throws {ExpectError} if the expectations are not met
892
+ * @returns {void} Nothing
893
+ */
894
+ function checkExpectations(expectations, value) {
1252
895
  var e_1, _a;
1253
- sentence = removeDiacritics(sentence);
1254
- var charType;
1255
- var lastCharType = 'OTHER';
1256
- var normalizedName = '';
1257
896
  try {
1258
- for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1259
- var char = sentence_1_1.value;
1260
- var normalizedChar = void 0;
1261
- if (/^[a-z]$/.test(char)) {
1262
- charType = 'LOWERCASE';
1263
- normalizedChar = char;
1264
- }
1265
- else if (/^[A-Z]$/.test(char)) {
1266
- charType = 'UPPERCASE';
1267
- normalizedChar = char.toLowerCase();
1268
- }
1269
- else if (/^[0-9]$/.test(char)) {
1270
- charType = 'NUMBER';
1271
- normalizedChar = char;
1272
- }
1273
- else if (/^\/$/.test(char)) {
1274
- charType = 'SLASH';
1275
- normalizedChar = char;
1276
- }
1277
- else {
1278
- charType = 'OTHER';
1279
- normalizedChar = '-';
897
+ for (var _b = __values(Object.entries(expectations)), _c = _b.next(); !_c.done; _c = _b.next()) {
898
+ var _d = __read(_c.value, 2), unit = _d[0], _e = _d[1], max = _e.max, min = _e.min;
899
+ var amount = CountUtils[unit.toUpperCase()](value);
900
+ if (min && amount < min) {
901
+ throw new ExpectError("Expected at least ".concat(min, " ").concat(unit, " but got ").concat(amount));
902
+ } /* not else */
903
+ if (max && amount > max) {
904
+ throw new ExpectError("Expected at most ".concat(max, " ").concat(unit, " but got ").concat(amount));
1280
905
  }
1281
- if (charType !== lastCharType &&
1282
- !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1283
- !(lastCharType === 'NUMBER') &&
1284
- !(charType === 'NUMBER')) {
1285
- normalizedName += '-';
1286
- }
1287
- normalizedName += normalizedChar;
1288
- lastCharType = charType;
1289
906
  }
1290
907
  }
1291
908
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1292
909
  finally {
1293
910
  try {
1294
- if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
911
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1295
912
  }
1296
913
  finally { if (e_1) throw e_1.error; }
1297
914
  }
1298
- normalizedName = normalizedName.split(/-+/g).join('-');
1299
- normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1300
- normalizedName = normalizedName.replace(/^-/, '');
1301
- normalizedName = normalizedName.replace(/-$/, '');
1302
- return normalizedName;
1303
915
  }
916
+ /**
917
+ * TODO: [💝] Unite object for expecting amount and format
918
+ */
1304
919
 
1305
920
  /**
1306
- * Removes emojis from a string and fix whitespaces
921
+ * This error occurs during the parameter replacement in the template
1307
922
  *
1308
- * @param text with emojis
1309
- * @returns text without emojis
923
+ * Note: This is a kindof subtype of PromptbookExecutionError because it occurs during the execution of the pipeline
1310
924
  */
1311
- function removeEmojis(text) {
1312
- // Replace emojis (and also ZWJ sequence) with hyphens
1313
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
1314
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
1315
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
1316
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
1317
- return text;
1318
- }
925
+ var TemplateError = /** @class */ (function (_super) {
926
+ __extends(TemplateError, _super);
927
+ function TemplateError(message) {
928
+ var _this = _super.call(this, message) || this;
929
+ _this.name = 'TemplateError';
930
+ Object.setPrototypeOf(_this, TemplateError.prototype);
931
+ return _this;
932
+ }
933
+ return TemplateError;
934
+ }(Error));
1319
935
 
1320
936
  /**
1321
- * Function normalizes title to name which can be used as identifier
937
+ * Replaces parameters in template with values from parameters object
938
+ *
939
+ * @param template the template with parameters in {curly} braces
940
+ * @param parameters the object with parameters
941
+ * @returns the template with replaced parameters
942
+ * @throws {TemplateError} if parameter is not defined, not closed, or not opened
943
+ *
944
+ * @private within the createPromptbookExecutor
1322
945
  */
1323
- function titleToName(value) {
1324
- value = removeEmojis(value);
1325
- value = normalizeToKebabCase(value);
1326
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
1327
- return value;
946
+ function replaceParameters(template, parameters) {
947
+ var replacedTemplate = template;
948
+ var match;
949
+ var loopLimit = LOOP_LIMIT;
950
+ var _loop_1 = function () {
951
+ if (loopLimit-- < 0) {
952
+ throw new UnexpectedError('Loop limit reached during parameters replacement in `replaceParameters`');
953
+ }
954
+ var precol = match.groups.precol;
955
+ var parameterName = match.groups.parameterName;
956
+ if (parameterName === '') {
957
+ return "continue";
958
+ }
959
+ if (parameterName.indexOf('{') !== -1 || parameterName.indexOf('}') !== -1) {
960
+ throw new TemplateError('Parameter is already opened or not closed');
961
+ }
962
+ if (parameters[parameterName] === undefined) {
963
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
964
+ }
965
+ var parameterValue = parameters[parameterName];
966
+ if (parameterValue === undefined) {
967
+ throw new TemplateError("Parameter {".concat(parameterName, "} is not defined"));
968
+ }
969
+ parameterValue = parameterValue.toString();
970
+ if (parameterValue.includes('\n') && /^\s*\W{0,3}\s*$/.test(precol)) {
971
+ parameterValue = parameterValue
972
+ .split('\n')
973
+ .map(function (line, index) { return (index === 0 ? line : "".concat(precol).concat(line)); })
974
+ .join('\n');
975
+ }
976
+ replacedTemplate =
977
+ replacedTemplate.substring(0, match.index + precol.length) +
978
+ parameterValue +
979
+ replacedTemplate.substring(match.index + precol.length + parameterName.length + 2);
980
+ };
981
+ while ((match = /^(?<precol>.*){(?<parameterName>\w+)}(.*)/m /* <- Not global */
982
+ .exec(replacedTemplate))) {
983
+ _loop_1();
984
+ }
985
+ // [💫] Check if there are parameters that are not closed properly
986
+ if (/{\w+$/.test(replacedTemplate)) {
987
+ throw new TemplateError('Parameter is not closed');
988
+ }
989
+ // [💫] Check if there are parameters that are not opened properly
990
+ if (/^\w+}/.test(replacedTemplate)) {
991
+ throw new TemplateError('Parameter is not opened');
992
+ }
993
+ return replacedTemplate;
1328
994
  }
1329
995
 
1330
996
  /**
1331
- * Compile promptbook from string (markdown) format to JSON format
1332
- *
1333
- * @param promptbookString {Promptbook} in string markdown format (.ptbk.md)
1334
- * @param options - Options and tools for the compilation
1335
- * @returns {Promptbook} compiled in JSON format (.ptbk.json)
1336
- * @throws {PromptbookSyntaxError} if the promptbook string is not valid
997
+ * Creates executor function from promptbook and execution tools.
1337
998
  *
1338
- * Note: This function does not validate logic of the pipeline only the syntax
1339
- * Note: This function acts as compilation process
999
+ * @returns The executor function
1000
+ * @throws {PromptbookLogicError} on logical error in the promptbook
1340
1001
  */
1341
- function promptbookStringToJson(promptbookString, options) {
1342
- if (options === void 0) { options = {}; }
1343
- return __awaiter(this, void 0, void 0, function () {
1344
- var llmTools, promptbookJson, knowledge, addParam, markdownStructure, markdownStructureDeepness, description, defaultModelRequirements, listItems, listItems_1, listItems_1_1, listItem, command, _loop_1, _a, _b, section;
1345
- var e_1, _c, e_2, _d;
1346
- return __generator(this, function (_e) {
1347
- switch (_e.label) {
1348
- case 0:
1349
- llmTools = options.llmTools;
1350
- promptbookJson = {
1002
+ function createPromptbookExecutor(options) {
1003
+ var _this = this;
1004
+ var promptbook = options.promptbook, tools = options.tools, _a = options.settings, settings = _a === void 0 ? {} : _a;
1005
+ var _b = settings.maxExecutionAttempts, maxExecutionAttempts = _b === void 0 ? 3 : _b;
1006
+ validatePromptbookJson(promptbook);
1007
+ var promptbookExecutor = function (inputParameters, onProgress) { return __awaiter(_this, void 0, void 0, function () {
1008
+ function executeSingleTemplate(currentTemplate) {
1009
+ return __awaiter(this, void 0, void 0, function () {
1010
+ var name, title, priority, prompt, chatThread, completionResult, result, resultString, expectError, scriptExecutionErrors, maxAttempts, jokers, attempt, isJokerAttempt, joker, _a, _b, _c, _d, scriptTools, error_2, e_2_1, _e, _f, functionName, postprocessingError, _g, _h, scriptTools, error_3, e_3_1, e_4_1, error_4;
1011
+ var e_2, _j, e_4, _k, e_3, _l, _m;
1012
+ var _this = this;
1013
+ return __generator(this, function (_o) {
1014
+ switch (_o.label) {
1015
+ case 0:
1016
+ name = "promptbook-executor-frame-".concat(currentTemplate.name);
1017
+ title = currentTemplate.title;
1018
+ priority = promptbook.promptTemplates.length - promptbook.promptTemplates.indexOf(currentTemplate);
1019
+ if (!onProgress /* <- [3] */) return [3 /*break*/, 2]; /* <- [3] */
1020
+ return [4 /*yield*/, onProgress({
1021
+ name: name,
1022
+ title: title,
1023
+ isStarted: false,
1024
+ isDone: false,
1025
+ executionType: currentTemplate.executionType,
1026
+ parameterName: currentTemplate.resultingParameterName,
1027
+ parameterValue: null,
1028
+ // <- [3]
1029
+ })];
1030
+ case 1:
1031
+ _o.sent();
1032
+ _o.label = 2;
1033
+ case 2:
1034
+ result = null;
1035
+ resultString = null;
1036
+ expectError = null;
1037
+ maxAttempts = currentTemplate.executionType === 'PROMPT_DIALOG' ? Infinity : maxExecutionAttempts;
1038
+ jokers = currentTemplate.jokers || [];
1039
+ attempt = -jokers.length;
1040
+ _o.label = 3;
1041
+ case 3:
1042
+ if (!(attempt < maxAttempts)) return [3 /*break*/, 49];
1043
+ isJokerAttempt = attempt < 0;
1044
+ joker = jokers[jokers.length + attempt];
1045
+ if (isJokerAttempt && !joker) {
1046
+ throw new UnexpectedError("Joker not found in attempt ".concat(attempt));
1047
+ }
1048
+ result = null;
1049
+ resultString = null;
1050
+ expectError = null;
1051
+ if (isJokerAttempt) {
1052
+ if (typeof parametersToPass[joker] === 'undefined') {
1053
+ throw new PromptbookExecutionError("Joker parameter {".concat(joker, "} not defined"));
1054
+ }
1055
+ resultString = parametersToPass[joker];
1056
+ }
1057
+ _o.label = 4;
1058
+ case 4:
1059
+ _o.trys.push([4, 45, 46, 47]);
1060
+ if (!!isJokerAttempt) return [3 /*break*/, 27];
1061
+ _a = currentTemplate.executionType;
1062
+ switch (_a) {
1063
+ case 'SIMPLE_TEMPLATE': return [3 /*break*/, 5];
1064
+ case 'PROMPT_TEMPLATE': return [3 /*break*/, 6];
1065
+ case 'SCRIPT': return [3 /*break*/, 13];
1066
+ case 'PROMPT_DIALOG': return [3 /*break*/, 24];
1067
+ }
1068
+ return [3 /*break*/, 26];
1069
+ case 5:
1070
+ resultString = replaceParameters(currentTemplate.content, parametersToPass);
1071
+ return [3 /*break*/, 27];
1072
+ case 6:
1073
+ prompt = {
1074
+ title: currentTemplate.title,
1075
+ promptbookUrl: "".concat(promptbook.promptbookUrl
1076
+ ? promptbook.promptbookUrl
1077
+ : 'anonymous' /* <- TODO: [🧠] How to deal with anonymous PROMPTBOOKs, do here some auto-url like SHA-256 based ad-hoc identifier? */, "#").concat(currentTemplate.name),
1078
+ parameters: parametersToPass,
1079
+ content: replaceParameters(currentTemplate.content, parametersToPass) /* <- [2] */,
1080
+ modelRequirements: currentTemplate.modelRequirements,
1081
+ expectations: currentTemplate.expectations,
1082
+ expectFormat: currentTemplate.expectFormat,
1083
+ postprocessing: (currentTemplate.postprocessing || []).map(function (functionName) { return function (result) { return __awaiter(_this, void 0, void 0, function () {
1084
+ var errors, _a, _b, scriptTools, error_5, e_5_1;
1085
+ var e_5, _c;
1086
+ return __generator(this, function (_d) {
1087
+ switch (_d.label) {
1088
+ case 0:
1089
+ errors = [];
1090
+ _d.label = 1;
1091
+ case 1:
1092
+ _d.trys.push([1, 8, 9, 10]);
1093
+ _a = __values(tools.script), _b = _a.next();
1094
+ _d.label = 2;
1095
+ case 2:
1096
+ if (!!_b.done) return [3 /*break*/, 7];
1097
+ scriptTools = _b.value;
1098
+ _d.label = 3;
1099
+ case 3:
1100
+ _d.trys.push([3, 5, , 6]);
1101
+ return [4 /*yield*/, scriptTools.execute({
1102
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1103
+ script: "".concat(functionName, "(result)"),
1104
+ parameters: {
1105
+ result: result || '',
1106
+ // Note: No ...parametersToPass, because working with result only
1107
+ },
1108
+ })];
1109
+ case 4: return [2 /*return*/, _d.sent()];
1110
+ case 5:
1111
+ error_5 = _d.sent();
1112
+ if (!(error_5 instanceof Error)) {
1113
+ throw error_5;
1114
+ }
1115
+ errors.push(error_5);
1116
+ return [3 /*break*/, 6];
1117
+ case 6:
1118
+ _b = _a.next();
1119
+ return [3 /*break*/, 2];
1120
+ case 7: return [3 /*break*/, 10];
1121
+ case 8:
1122
+ e_5_1 = _d.sent();
1123
+ e_5 = { error: e_5_1 };
1124
+ return [3 /*break*/, 10];
1125
+ case 9:
1126
+ try {
1127
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1128
+ }
1129
+ finally { if (e_5) throw e_5.error; }
1130
+ return [7 /*endfinally*/];
1131
+ case 10:
1132
+ if (errors.length === 0) {
1133
+ throw new PromptbookExecutionError('Postprocessing in LlmExecutionTools failed because no ScriptExecutionTools were provided');
1134
+ }
1135
+ else if (errors.length === 1) {
1136
+ throw errors[0];
1137
+ }
1138
+ else {
1139
+ throw new PromptbookExecutionError(spaceTrim(function (block) { return "\n Postprocessing in LlmExecutionTools failed ".concat(errors.length, "x\n\n ").concat(block(errors.map(function (error) { return '- ' + error.message; }).join('\n\n')), "\n "); }));
1140
+ }
1141
+ }
1142
+ });
1143
+ }); }; }),
1144
+ };
1145
+ _b = currentTemplate.modelRequirements.modelVariant;
1146
+ switch (_b) {
1147
+ case 'CHAT': return [3 /*break*/, 7];
1148
+ case 'COMPLETION': return [3 /*break*/, 9];
1149
+ }
1150
+ return [3 /*break*/, 11];
1151
+ case 7: return [4 /*yield*/, tools.llm.gptChat(prompt)];
1152
+ case 8:
1153
+ chatThread = _o.sent();
1154
+ // TODO: [🍬] Destroy chatThread
1155
+ result = chatThread;
1156
+ resultString = chatThread.content;
1157
+ return [3 /*break*/, 12];
1158
+ case 9: return [4 /*yield*/, tools.llm.gptComplete(prompt)];
1159
+ case 10:
1160
+ completionResult = _o.sent();
1161
+ result = completionResult;
1162
+ resultString = completionResult.content;
1163
+ return [3 /*break*/, 12];
1164
+ case 11: throw new PromptbookExecutionError("Unknown model variant \"".concat(currentTemplate.modelRequirements.modelVariant, "\""));
1165
+ case 12: return [3 /*break*/, 27];
1166
+ case 13:
1167
+ if (tools.script.length === 0) {
1168
+ throw new PromptbookExecutionError('No script execution tools are available');
1169
+ }
1170
+ if (!currentTemplate.contentLanguage) {
1171
+ throw new PromptbookExecutionError("Script language is not defined for prompt template \"".concat(currentTemplate.name, "\""));
1172
+ }
1173
+ // TODO: DRY [1]
1174
+ scriptExecutionErrors = [];
1175
+ _o.label = 14;
1176
+ case 14:
1177
+ _o.trys.push([14, 21, 22, 23]);
1178
+ _c = (e_2 = void 0, __values(tools.script)), _d = _c.next();
1179
+ _o.label = 15;
1180
+ case 15:
1181
+ if (!!_d.done) return [3 /*break*/, 20];
1182
+ scriptTools = _d.value;
1183
+ _o.label = 16;
1184
+ case 16:
1185
+ _o.trys.push([16, 18, , 19]);
1186
+ return [4 /*yield*/, scriptTools.execute({
1187
+ scriptLanguage: currentTemplate.contentLanguage,
1188
+ script: currentTemplate.content,
1189
+ parameters: parametersToPass,
1190
+ })];
1191
+ case 17:
1192
+ resultString = _o.sent();
1193
+ return [3 /*break*/, 20];
1194
+ case 18:
1195
+ error_2 = _o.sent();
1196
+ if (!(error_2 instanceof Error)) {
1197
+ throw error_2;
1198
+ }
1199
+ scriptExecutionErrors.push(error_2);
1200
+ return [3 /*break*/, 19];
1201
+ case 19:
1202
+ _d = _c.next();
1203
+ return [3 /*break*/, 15];
1204
+ case 20: return [3 /*break*/, 23];
1205
+ case 21:
1206
+ e_2_1 = _o.sent();
1207
+ e_2 = { error: e_2_1 };
1208
+ return [3 /*break*/, 23];
1209
+ case 22:
1210
+ try {
1211
+ if (_d && !_d.done && (_j = _c.return)) _j.call(_c);
1212
+ }
1213
+ finally { if (e_2) throw e_2.error; }
1214
+ return [7 /*endfinally*/];
1215
+ case 23:
1216
+ if (resultString !== null) {
1217
+ return [3 /*break*/, 27];
1218
+ }
1219
+ if (scriptExecutionErrors.length === 1) {
1220
+ throw scriptExecutionErrors[0];
1221
+ }
1222
+ else {
1223
+ throw new PromptbookExecutionError(spaceTrim(function (block) { return "\n Script execution failed ".concat(scriptExecutionErrors.length, " times\n\n ").concat(block(scriptExecutionErrors
1224
+ .map(function (error) { return '- ' + error.message; })
1225
+ .join('\n\n')), "\n "); }));
1226
+ }
1227
+ case 24:
1228
+ if (tools.userInterface === undefined) {
1229
+ throw new PromptbookExecutionError('User interface tools are not available');
1230
+ }
1231
+ return [4 /*yield*/, tools.userInterface.promptDialog({
1232
+ promptTitle: currentTemplate.title,
1233
+ promptMessage: replaceParameters(currentTemplate.description || '', parametersToPass),
1234
+ defaultValue: replaceParameters(currentTemplate.content, parametersToPass),
1235
+ // TODO: [🧠] !! Figure out how to define placeholder in .ptbk.md file
1236
+ placeholder: undefined,
1237
+ priority: priority,
1238
+ })];
1239
+ case 25:
1240
+ // TODO: [🌹] When making next attempt for `PROMPT DIALOG`, preserve the previous user input
1241
+ resultString = _o.sent();
1242
+ return [3 /*break*/, 27];
1243
+ case 26: throw new PromptbookExecutionError(
1351
1244
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1352
- title: undefined /* <- Note: Putting here placeholder to keep `title` on top at final JSON */,
1353
- promptbookUrl: undefined /* <- Note: Putting here placeholder to keep `promptbookUrl` on top at final JSON */,
1354
- promptbookVersion: PROMPTBOOK_VERSION,
1355
- description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
1356
- parameters: [],
1357
- promptTemplates: [],
1358
- knowledge: [],
1245
+ "Unknown execution type \"".concat(currentTemplate.executionType, "\""));
1246
+ case 27:
1247
+ if (!(!isJokerAttempt && currentTemplate.postprocessing)) return [3 /*break*/, 44];
1248
+ _o.label = 28;
1249
+ case 28:
1250
+ _o.trys.push([28, 42, 43, 44]);
1251
+ _e = (e_4 = void 0, __values(currentTemplate.postprocessing)), _f = _e.next();
1252
+ _o.label = 29;
1253
+ case 29:
1254
+ if (!!_f.done) return [3 /*break*/, 41];
1255
+ functionName = _f.value;
1256
+ // TODO: DRY [1]
1257
+ scriptExecutionErrors = [];
1258
+ postprocessingError = null;
1259
+ _o.label = 30;
1260
+ case 30:
1261
+ _o.trys.push([30, 37, 38, 39]);
1262
+ _g = (e_3 = void 0, __values(tools.script)), _h = _g.next();
1263
+ _o.label = 31;
1264
+ case 31:
1265
+ if (!!_h.done) return [3 /*break*/, 36];
1266
+ scriptTools = _h.value;
1267
+ _o.label = 32;
1268
+ case 32:
1269
+ _o.trys.push([32, 34, , 35]);
1270
+ return [4 /*yield*/, scriptTools.execute({
1271
+ scriptLanguage: "javascript" /* <- TODO: Try it in each languages; In future allow postprocessing with arbitrary combination of languages to combine */,
1272
+ script: "".concat(functionName, "(resultString)"),
1273
+ parameters: {
1274
+ resultString: resultString || '',
1275
+ // Note: No ...parametersToPass, because working with result only
1276
+ },
1277
+ })];
1278
+ case 33:
1279
+ resultString = _o.sent();
1280
+ postprocessingError = null;
1281
+ return [3 /*break*/, 36];
1282
+ case 34:
1283
+ error_3 = _o.sent();
1284
+ if (!(error_3 instanceof Error)) {
1285
+ throw error_3;
1286
+ }
1287
+ postprocessingError = error_3;
1288
+ scriptExecutionErrors.push(error_3);
1289
+ return [3 /*break*/, 35];
1290
+ case 35:
1291
+ _h = _g.next();
1292
+ return [3 /*break*/, 31];
1293
+ case 36: return [3 /*break*/, 39];
1294
+ case 37:
1295
+ e_3_1 = _o.sent();
1296
+ e_3 = { error: e_3_1 };
1297
+ return [3 /*break*/, 39];
1298
+ case 38:
1299
+ try {
1300
+ if (_h && !_h.done && (_l = _g.return)) _l.call(_g);
1301
+ }
1302
+ finally { if (e_3) throw e_3.error; }
1303
+ return [7 /*endfinally*/];
1304
+ case 39:
1305
+ if (postprocessingError) {
1306
+ throw postprocessingError;
1307
+ }
1308
+ _o.label = 40;
1309
+ case 40:
1310
+ _f = _e.next();
1311
+ return [3 /*break*/, 29];
1312
+ case 41: return [3 /*break*/, 44];
1313
+ case 42:
1314
+ e_4_1 = _o.sent();
1315
+ e_4 = { error: e_4_1 };
1316
+ return [3 /*break*/, 44];
1317
+ case 43:
1318
+ try {
1319
+ if (_f && !_f.done && (_k = _e.return)) _k.call(_e);
1320
+ }
1321
+ finally { if (e_4) throw e_4.error; }
1322
+ return [7 /*endfinally*/];
1323
+ case 44:
1324
+ // TODO: [💝] Unite object for expecting amount and format
1325
+ if (currentTemplate.expectFormat) {
1326
+ if (currentTemplate.expectFormat === 'JSON') {
1327
+ if (!isValidJsonString(resultString || '')) {
1328
+ throw new ExpectError('Expected valid JSON string');
1329
+ }
1330
+ }
1331
+ }
1332
+ // TODO: [💝] Unite object for expecting amount and format
1333
+ if (currentTemplate.expectations) {
1334
+ checkExpectations(currentTemplate.expectations, resultString || '');
1335
+ }
1336
+ return [3 /*break*/, 49];
1337
+ case 45:
1338
+ error_4 = _o.sent();
1339
+ if (!(error_4 instanceof ExpectError)) {
1340
+ throw error_4;
1341
+ }
1342
+ expectError = error_4;
1343
+ return [3 /*break*/, 47];
1344
+ case 46:
1345
+ if (!isJokerAttempt &&
1346
+ currentTemplate.executionType === 'PROMPT_TEMPLATE' &&
1347
+ prompt
1348
+ // <- Note: [2] When some expected parameter is not defined, error will occur in replaceParameters
1349
+ // In that case we don’t want to make a report about it because it’s not a llm execution error
1350
+ ) {
1351
+ // TODO: [🧠] Maybe put other executionTypes into report
1352
+ executionReport.promptExecutions.push({
1353
+ prompt: {
1354
+ title: currentTemplate.title /* <- Note: If title in promptbook contains emojis, pass it innto report */,
1355
+ content: prompt.content,
1356
+ modelRequirements: prompt.modelRequirements,
1357
+ expectations: prompt.expectations,
1358
+ expectFormat: prompt.expectFormat,
1359
+ // <- Note: Do want to pass ONLY wanted information to the report
1360
+ },
1361
+ result: result || undefined,
1362
+ error: expectError || undefined,
1363
+ });
1364
+ }
1365
+ return [7 /*endfinally*/];
1366
+ case 47:
1367
+ if (expectError !== null && attempt === maxAttempts - 1) {
1368
+ throw new PromptbookExecutionError(spaceTrim(function (block) { return "\n LLM execution failed ".concat(maxExecutionAttempts, "x\n\n ---\n Last error ").concat((expectError === null || expectError === void 0 ? void 0 : expectError.name) || '', ":\n ").concat(block((expectError === null || expectError === void 0 ? void 0 : expectError.message) || ''), "\n\n Last result:\n ").concat(resultString, "\n ---\n "); }));
1369
+ }
1370
+ _o.label = 48;
1371
+ case 48:
1372
+ attempt++;
1373
+ return [3 /*break*/, 3];
1374
+ case 49:
1375
+ if (resultString === null) {
1376
+ throw new UnexpectedError('Something went wrong and prompt result is null');
1377
+ }
1378
+ if (onProgress /* <- [3] */) {
1379
+ onProgress({
1380
+ name: name,
1381
+ title: title,
1382
+ isStarted: true,
1383
+ isDone: true,
1384
+ executionType: currentTemplate.executionType,
1385
+ parameterName: currentTemplate.resultingParameterName,
1386
+ parameterValue: resultString,
1387
+ // <- [3]
1388
+ });
1389
+ }
1390
+ parametersToPass = __assign(__assign({}, parametersToPass), (_m = {}, _m[currentTemplate.resultingParameterName] = resultString /* <- Note: Not need to detect parameter collision here because Promptbook checks logic consistency during construction */, _m));
1391
+ return [2 /*return*/];
1392
+ }
1393
+ });
1394
+ });
1395
+ }
1396
+ var parametersToPass, executionReport, resovedParameters_1, unresovedTemplates, resolving_1, loopLimit, _loop_1, error_1, usage_1, _a, _b, parameter, usage;
1397
+ var e_1, _c;
1398
+ return __generator(this, function (_d) {
1399
+ switch (_d.label) {
1400
+ case 0:
1401
+ parametersToPass = inputParameters;
1402
+ executionReport = {
1403
+ promptbookUrl: promptbook.promptbookUrl,
1404
+ title: promptbook.title,
1405
+ promptbookUsedVersion: PROMPTBOOK_VERSION,
1406
+ promptbookRequestedVersion: promptbook.promptbookVersion,
1407
+ description: promptbook.description,
1408
+ promptExecutions: [],
1359
1409
  };
1360
- if (!llmTools) return [3 /*break*/, 2];
1361
- return [4 /*yield*/, prepareKnowledgeFromMarkdown()];
1410
+ _d.label = 1;
1362
1411
  case 1:
1363
- knowledge = _e.sent();
1364
- console.info('!!!! knowledge', knowledge);
1365
- _e.label = 2;
1366
- case 2:
1367
- // =============================================================
1368
- // Note: 1️⃣ Normalization of the PROMPTBOOK string
1369
- promptbookString = removeContentComments(promptbookString);
1370
- promptbookString = promptbookString.replaceAll(/`\{(?<parameterName>[a-z0-9_]+)\}`/gi, '{$<parameterName>}');
1371
- promptbookString = promptbookString.replaceAll(/`->\s+\{(?<parameterName>[a-z0-9_]+)\}`/gi, '-> {$<parameterName>}');
1372
- addParam = function (parameterCommand) {
1373
- var parameterName = parameterCommand.parameterName, parameterDescription = parameterCommand.parameterDescription, isInput = parameterCommand.isInput, isOutput = parameterCommand.isOutput;
1374
- var existingParameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
1375
- if (existingParameter &&
1376
- existingParameter.description &&
1377
- existingParameter.description !== parameterDescription &&
1378
- parameterDescription) {
1379
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
1380
- }
1381
- if (existingParameter) {
1382
- if (parameterDescription) {
1383
- existingParameter.description = parameterDescription;
1412
+ _d.trys.push([1, 6, , 7]);
1413
+ resovedParameters_1 = promptbook.parameters
1414
+ .filter(function (_a) {
1415
+ var isInput = _a.isInput;
1416
+ return isInput;
1417
+ })
1418
+ .map(function (_a) {
1419
+ var name = _a.name;
1420
+ return name;
1421
+ });
1422
+ unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
1423
+ resolving_1 = [];
1424
+ loopLimit = LOOP_LIMIT;
1425
+ _loop_1 = function () {
1426
+ var currentTemplate, work_1;
1427
+ return __generator(this, function (_e) {
1428
+ switch (_e.label) {
1429
+ case 0:
1430
+ if (loopLimit-- < 0) {
1431
+ throw new UnexpectedError('Loop limit reached during resolving parameters promptbook execution');
1432
+ }
1433
+ currentTemplate = unresovedTemplates.find(function (template) {
1434
+ return template.dependentParameterNames.every(function (name) { return resovedParameters_1.includes(name); });
1435
+ });
1436
+ if (!(!currentTemplate && resolving_1.length === 0)) return [3 /*break*/, 1];
1437
+ throw new UnexpectedError(spaceTrim("\n Can not resolve some parameters\n\n Note: This should be catched during validatePromptbookJson\n "));
1438
+ case 1:
1439
+ if (!!currentTemplate) return [3 /*break*/, 3];
1440
+ /* [5] */ return [4 /*yield*/, Promise.race(resolving_1)];
1441
+ case 2:
1442
+ /* [5] */ _e.sent();
1443
+ return [3 /*break*/, 4];
1444
+ case 3:
1445
+ unresovedTemplates = unresovedTemplates.filter(function (template) { return template !== currentTemplate; });
1446
+ work_1 = executeSingleTemplate(currentTemplate)
1447
+ .then(function () {
1448
+ resovedParameters_1 = __spreadArray(__spreadArray([], __read(resovedParameters_1), false), [currentTemplate.resultingParameterName], false);
1449
+ })
1450
+ .then(function () {
1451
+ resolving_1 = resolving_1.filter(function (w) { return w !== work_1; });
1452
+ });
1453
+ resolving_1.push(work_1);
1454
+ _e.label = 4;
1455
+ case 4: return [2 /*return*/];
1384
1456
  }
1385
- }
1386
- else {
1387
- promptbookJson.parameters.push({
1388
- name: parameterName,
1389
- description: parameterDescription || undefined,
1390
- isInput: isInput,
1391
- isOutput: isOutput,
1392
- });
1393
- }
1457
+ });
1394
1458
  };
1395
- markdownStructure = markdownToMarkdownStructure(promptbookString);
1396
- markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
1397
- if (markdownStructureDeepness !== 2) {
1398
- throw new PromptbookSyntaxError(spaceTrim("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
1399
- }
1400
- promptbookJson.title = markdownStructure.title;
1401
- description = markdownStructure.content;
1402
- // Note: Remove codeblocks
1403
- description = description.split(/^```.*^```/gms).join('');
1404
- //Note: Remove lists and return statement
1405
- description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1406
- description = spaceTrim(description);
1407
- if (description === '') {
1408
- description = undefined;
1459
+ _d.label = 2;
1460
+ case 2:
1461
+ if (!(unresovedTemplates.length > 0)) return [3 /*break*/, 4];
1462
+ return [5 /*yield**/, _loop_1()];
1463
+ case 3:
1464
+ _d.sent();
1465
+ return [3 /*break*/, 2];
1466
+ case 4: return [4 /*yield*/, Promise.all(resolving_1)];
1467
+ case 5:
1468
+ _d.sent();
1469
+ return [3 /*break*/, 7];
1470
+ case 6:
1471
+ error_1 = _d.sent();
1472
+ if (!(error_1 instanceof Error)) {
1473
+ throw error_1;
1409
1474
  }
1410
- promptbookJson.description = description;
1411
- defaultModelRequirements = {};
1412
- listItems = extractAllListItemsFromMarkdown(markdownStructure.content);
1475
+ usage_1 = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
1476
+ var result = _a.result;
1477
+ return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
1478
+ })), false));
1479
+ return [2 /*return*/, {
1480
+ isSuccessful: false,
1481
+ errors: [error_1],
1482
+ usage: usage_1,
1483
+ executionReport: executionReport,
1484
+ outputParameters: parametersToPass,
1485
+ }];
1486
+ case 7:
1413
1487
  try {
1414
- for (listItems_1 = __values(listItems), listItems_1_1 = listItems_1.next(); !listItems_1_1.done; listItems_1_1 = listItems_1.next()) {
1415
- listItem = listItems_1_1.value;
1416
- command = parseCommand(listItem);
1417
- switch (command.type) {
1418
- case 'PROMPTBOOK_URL':
1419
- promptbookJson.promptbookUrl = command.promptbookUrl.href;
1420
- break;
1421
- case 'PROMPTBOOK_VERSION':
1422
- promptbookJson.promptbookVersion = command.promptbookVersion;
1423
- break;
1424
- case 'MODEL':
1425
- defaultModelRequirements[command.key] = command.value;
1426
- break;
1427
- case 'PARAMETER':
1428
- addParam(command);
1429
- break;
1430
- default:
1431
- throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the head of the promptbook ONLY at the prompt template block"));
1488
+ // Note: Filter ONLY output parameters
1489
+ for (_a = __values(promptbook.parameters), _b = _a.next(); !_b.done; _b = _a.next()) {
1490
+ parameter = _b.value;
1491
+ if (parameter.isOutput) {
1492
+ continue;
1432
1493
  }
1494
+ delete parametersToPass[parameter.name];
1433
1495
  }
1434
1496
  }
1435
1497
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1436
1498
  finally {
1437
1499
  try {
1438
- if (listItems_1_1 && !listItems_1_1.done && (_c = listItems_1.return)) _c.call(listItems_1);
1500
+ if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
1439
1501
  }
1440
1502
  finally { if (e_1) throw e_1.error; }
1441
1503
  }
1442
- _loop_1 = function (section) {
1443
- var e_3, _f;
1444
- // TODO: Parse prompt template description (the content out of the codeblock and lists)
1445
- var templateModelRequirements = __assign({}, defaultModelRequirements);
1446
- var listItems_3 = extractAllListItemsFromMarkdown(section.content);
1447
- var dependentParameterNames = new Set();
1448
- var executionType = 'PROMPT_TEMPLATE';
1449
- var jokers = [];
1450
- var postprocessing = [];
1451
- var expectAmount = {};
1452
- var expectFormat = undefined;
1453
- var isExecutionTypeChanged = false;
1454
- try {
1455
- for (var listItems_2 = (e_3 = void 0, __values(listItems_3)), listItems_2_1 = listItems_2.next(); !listItems_2_1.done; listItems_2_1 = listItems_2.next()) {
1456
- var listItem = listItems_2_1.value;
1457
- var command = parseCommand(listItem);
1458
- switch (command.type) {
1459
- case 'JOKER':
1460
- jokers.push(command.parameterName);
1461
- dependentParameterNames.add(command.parameterName);
1462
- break;
1463
- case 'EXECUTE':
1464
- if (isExecutionTypeChanged) {
1465
- throw new PromptbookSyntaxError('Execution type is already defined in the prompt template. It can be defined only once.');
1466
- }
1467
- executionType = command.executionType;
1468
- isExecutionTypeChanged = true;
1469
- break;
1470
- case 'MODEL':
1471
- templateModelRequirements[command.key] = command.value;
1472
- break;
1473
- case 'PARAMETER':
1474
- // Note: This is just for detecting resulitng parameter name
1475
- addParam(command);
1476
- break;
1477
- case 'POSTPROCESS':
1478
- postprocessing.push(command.functionName);
1479
- break;
1480
- case 'EXPECT_AMOUNT':
1481
- // eslint-disable-next-line no-case-declarations
1482
- var unit = command.unit.toLowerCase();
1483
- expectAmount[unit] = expectAmount[unit] || {};
1484
- if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
1485
- if (expectAmount[unit].min !== undefined) {
1486
- throw new PromptbookSyntaxError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
1487
- }
1488
- expectAmount[unit].min = command.amount;
1489
- } /* not else */
1490
- if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
1491
- if (expectAmount[unit].max !== undefined) {
1492
- throw new PromptbookSyntaxError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
1493
- }
1494
- expectAmount[unit].max = command.amount;
1495
- }
1496
- break;
1497
- case 'EXPECT_FORMAT':
1498
- if (expectFormat !== undefined && command.format !== expectFormat) {
1499
- throw new PromptbookSyntaxError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
1500
- }
1501
- expectFormat = command.format;
1502
- break;
1503
- default:
1504
- throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the block of the prompt template ONLY at the head of the promptbook"));
1505
- }
1506
- }
1507
- }
1508
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
1509
- finally {
1510
- try {
1511
- if (listItems_2_1 && !listItems_2_1.done && (_f = listItems_2.return)) _f.call(listItems_2);
1512
- }
1513
- finally { if (e_3) throw e_3.error; }
1514
- }
1515
- var _g = extractOneBlockFromMarkdown(section.content), language = _g.language, content = _g.content;
1516
- if (executionType === 'SCRIPT') {
1517
- if (!language) {
1518
- throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
1519
- }
1520
- else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
1521
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
1522
- }
1523
- }
1524
- var lastLine = section.content.split('\n').pop();
1525
- var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
1526
- if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
1527
- throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
1528
- // TODO: Show code of invalid sections each time + DRY
1529
- section.content
1530
- .split('\n')
1531
- .map(function (line) { return "> ".concat(line); })
1532
- .join('\n')), "\n "); }));
1533
- }
1534
- var resultingParameterName = match.groups.resultingParamName;
1535
- // TODO: [1] DRY description
1536
- var description_1 = section.content;
1537
- // Note: Remove codeblocks
1538
- description_1 = description_1.split(/^```.*^```/gms).join('');
1539
- //Note: Remove lists and return statement
1540
- description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
1541
- description_1 = spaceTrim(description_1);
1542
- if (description_1 === '') {
1543
- description_1 = undefined;
1544
- }
1545
- if (Object.keys(jokers).length === 0) {
1546
- jokers = undefined;
1547
- }
1548
- if (Object.keys(expectAmount).length === 0) {
1549
- expectAmount = undefined;
1550
- }
1551
- if (Object.keys(postprocessing).length === 0) {
1552
- postprocessing = undefined;
1553
- }
1554
- dependentParameterNames = union(dependentParameterNames, extractParametersFromPromptTemplate(__assign(__assign({}, section), { description: description_1, executionType: executionType, content: content })));
1555
- if (templateModelRequirements.modelVariant === undefined) {
1556
- templateModelRequirements.modelVariant = 'CHAT';
1557
- }
1558
- promptbookJson.promptTemplates.push({
1559
- name: titleToName(section.title),
1560
- title: section.title,
1561
- description: description_1,
1562
- dependentParameterNames: Array.from(dependentParameterNames),
1563
- executionType: executionType,
1564
- jokers: jokers,
1565
- postprocessing: postprocessing,
1566
- expectations: expectAmount,
1567
- expectFormat: expectFormat,
1568
- modelRequirements: templateModelRequirements,
1569
- contentLanguage: executionType === 'SCRIPT' ? language : undefined,
1570
- content: content,
1571
- resultingParameterName: resultingParameterName,
1572
- });
1573
- };
1574
- try {
1575
- for (_a = __values(markdownStructure.sections), _b = _a.next(); !_b.done; _b = _a.next()) {
1576
- section = _b.value;
1577
- _loop_1(section);
1578
- }
1579
- }
1580
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1581
- finally {
1582
- try {
1583
- if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
1584
- }
1585
- finally { if (e_2) throw e_2.error; }
1586
- }
1587
- // =============================================================
1588
- return [2 /*return*/, promptbookJson];
1504
+ usage = addUsage.apply(void 0, __spreadArray([], __read(executionReport.promptExecutions.map(function (_a) {
1505
+ var result = _a.result;
1506
+ return (result === null || result === void 0 ? void 0 : result.usage) || addUsage();
1507
+ })), false));
1508
+ return [2 /*return*/, {
1509
+ isSuccessful: true,
1510
+ errors: [],
1511
+ usage: usage,
1512
+ executionReport: executionReport,
1513
+ outputParameters: parametersToPass,
1514
+ }];
1589
1515
  }
1590
1516
  });
1591
- });
1517
+ }); };
1518
+ return promptbookExecutor;
1592
1519
  }
1593
1520
  /**
1594
- * TODO: Report here line/column of error
1595
- * TODO: Use spaceTrim more effectively
1596
- * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
1597
- */
1598
-
1599
- /**
1600
- * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
1521
+ * TODO: [🧠] When not meet expectations in PROMPT_DIALOG, make some way to tell the user
1522
+ * TODO: [👧] Strongly type the executors to avoid need of remove nullables whtn noUncheckedIndexedAccess in tsconfig.json
1523
+ * Note: CreatePromptbookExecutorOptions are just connected to PromptbookExecutor so do not extract to types folder
1524
+ * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
1601
1525
  */
1602
- var PromptbookLogicError = /** @class */ (function (_super) {
1603
- __extends(PromptbookLogicError, _super);
1604
- function PromptbookLogicError(message) {
1605
- var _this = _super.call(this, message) || this;
1606
- _this.name = 'PromptbookLogicError';
1607
- Object.setPrototypeOf(_this, PromptbookLogicError.prototype);
1608
- return _this;
1609
- }
1610
- return PromptbookLogicError;
1611
- }(Error));
1612
1526
 
1613
1527
  /**
1614
- * Tests if given string is valid URL.
1528
+ * Prettify the html code
1615
1529
  *
1616
- * Note: Dataurl are considered perfectly valid.
1530
+ * @param content raw html code
1531
+ * @returns formatted html code
1617
1532
  */
1618
- function isValidUrl(url) {
1619
- if (typeof url !== 'string') {
1620
- return false;
1621
- }
1533
+ function prettifyMarkdown(content) {
1622
1534
  try {
1623
- if (url.startsWith('blob:')) {
1624
- url = url.replace(/^blob:/, '');
1625
- }
1626
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1627
- var urlObject = new URL(url);
1628
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1629
- return false;
1630
- }
1631
- return true;
1535
+ return format(content, {
1536
+ parser: 'markdown',
1537
+ plugins: [parserHtml],
1538
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1539
+ endOfLine: 'lf',
1540
+ tabWidth: 4,
1541
+ singleQuote: true,
1542
+ trailingComma: 'all',
1543
+ arrowParens: 'always',
1544
+ printWidth: 120,
1545
+ htmlWhitespaceSensitivity: 'ignore',
1546
+ jsxBracketSameLine: false,
1547
+ bracketSpacing: true,
1548
+ });
1632
1549
  }
1633
1550
  catch (error) {
1634
- return false;
1551
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1552
+ error: error,
1553
+ html: content,
1554
+ });
1555
+ return content;
1635
1556
  }
1636
1557
  }
1637
1558
 
1638
1559
  /**
1639
- * Validates PromptbookJson if it is logically valid
1640
- *
1641
- * It checks:
1642
- * - if it has correct parameters dependency
1560
+ * Makes first letter of a string uppercase
1643
1561
  *
1644
- * It does NOT check:
1645
- * - if it is valid json
1646
- * - if it is meaningful
1562
+ */
1563
+ function capitalize(word) {
1564
+ return word.substring(0, 1).toUpperCase() + word.substring(1);
1565
+ }
1566
+
1567
+ /**
1568
+ * Converts promptbook in JSON format to string format
1647
1569
  *
1648
- * @param promptbook valid or invalid PromptbookJson
1649
- * @returns the same promptbook if it is logically valid
1650
- * @throws {PromptbookLogicError} on logical error in the promptbook
1570
+ * @param promptbookJson Promptbook in JSON format (.ptbk.json)
1571
+ * @returns Promptbook in string format (.ptbk.md)
1651
1572
  */
1652
- function validatePromptbookJson(promptbook) {
1653
- // TODO: [🧠] Maybe test if promptbook is a promise and make specific error case for that
1654
- var e_1, _a, e_2, _b, e_3, _c, e_4, _d;
1655
- if (promptbook.promptbookUrl !== undefined) {
1656
- if (!isValidUrl(promptbook.promptbookUrl)) {
1657
- // TODO: This should be maybe the syntax error detected during parsing
1658
- throw new PromptbookLogicError("Invalid promptbook URL \"".concat(promptbook.promptbookUrl, "\""));
1659
- }
1660
- }
1661
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1662
- if (!Array.isArray(promptbook.parameters)) {
1663
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1664
- throw new PromptbookSyntaxError(spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.parameters expected to be an array, but got ".concat(typeof promptbook.parameters, "\n ")));
1573
+ function promptbookJsonToString(promptbookJson) {
1574
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f;
1575
+ var title = promptbookJson.title, promptbookUrl = promptbookJson.promptbookUrl, promptbookVersion = promptbookJson.promptbookVersion, description = promptbookJson.description, parameters = promptbookJson.parameters, promptTemplates = promptbookJson.promptTemplates;
1576
+ var promptbookString = "# ".concat(title);
1577
+ if (description) {
1578
+ promptbookString += '\n\n';
1579
+ promptbookString += description;
1665
1580
  }
1666
- // TODO: [🧠] Maybe do here some propper JSON-schema / ZOD checking
1667
- if (!Array.isArray(promptbook.promptTemplates)) {
1668
- // TODO: [🧠] what is the correct error tp throw - maybe PromptbookSchemaError
1669
- throw new PromptbookSyntaxError(spaceTrim("\n Promptbook is valid JSON but with wrong structure\n\n promptbook.promptTemplates expected to be an array, but got ".concat(typeof promptbook.promptTemplates, "\n ")));
1581
+ // TODO:> const commands: Array<Command>
1582
+ var commands = [];
1583
+ if (promptbookUrl) {
1584
+ commands.push("PROMPTBOOK URL ".concat(promptbookUrl));
1670
1585
  }
1671
- var _loop_1 = function (parameter) {
1672
- if (parameter.isInput && parameter.isOutput) {
1673
- throw new PromptbookLogicError("Parameter {".concat(parameter.name, "} can not be both input and output"));
1674
- }
1675
- // Note: Testing that parameter is either intermediate or output BUT not created and unused
1676
- if (!parameter.isInput &&
1677
- !parameter.isOutput &&
1678
- !promptbook.promptTemplates.some(function (template) { return template.dependentParameterNames.includes(parameter.name); })) {
1679
- throw new PromptbookLogicError(spaceTrim("\n Parameter {".concat(parameter.name, "} is created but not used\n\n You can declare {").concat(parameter.name, "} as output parameter by adding in the header:\n - OUTPUT PARAMETER `{").concat(parameter.name, "}` ").concat(parameter.description || '', "\n\n ")));
1680
- }
1681
- // Note: Testing that parameter is either input or result of some template
1682
- if (!parameter.isInput &&
1683
- !promptbook.promptTemplates.some(function (template) { return template.resultingParameterName === parameter.name; })) {
1684
- throw new PromptbookLogicError(spaceTrim("\n Parameter {".concat(parameter.name, "} is declared but not defined\n\n You can do one of these:\n - Remove declaration of {").concat(parameter.name, "}\n - Add prompt template that results in -> {").concat(parameter.name, "}\n\n ")));
1685
- }
1686
- };
1586
+ commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
1587
+ promptbookString = prettifyMarkdown(promptbookString);
1687
1588
  try {
1688
- // Note: Check each parameter individually
1689
- for (var _e = __values(promptbook.parameters), _f = _e.next(); !_f.done; _f = _e.next()) {
1690
- var parameter = _f.value;
1691
- _loop_1(parameter);
1589
+ for (var _g = __values(parameters.filter(function (_a) {
1590
+ var isInput = _a.isInput;
1591
+ return isInput;
1592
+ })), _h = _g.next(); !_h.done; _h = _g.next()) {
1593
+ var parameter = _h.value;
1594
+ commands.push("INPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1692
1595
  }
1693
1596
  }
1694
1597
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
1695
1598
  finally {
1696
1599
  try {
1697
- if (_f && !_f.done && (_a = _e.return)) _a.call(_e);
1698
- }
1699
- finally { if (e_1) throw e_1.error; }
1700
- }
1701
- // Note: Check each template individually
1702
- var definedParameters = new Set(promptbook.parameters.filter(function (_a) {
1703
- var isInput = _a.isInput;
1704
- return isInput;
1705
- }).map(function (_a) {
1706
- var name = _a.name;
1707
- return name;
1708
- }));
1709
- try {
1710
- for (var _g = __values(promptbook.promptTemplates), _h = _g.next(); !_h.done; _h = _g.next()) {
1711
- var template = _h.value;
1712
- if (definedParameters.has(template.resultingParameterName)) {
1713
- throw new PromptbookLogicError("Parameter {".concat(template.resultingParameterName, "} is defined multiple times"));
1714
- }
1715
- definedParameters.add(template.resultingParameterName);
1716
- if (template.executionType === 'PROMPT_TEMPLATE' &&
1717
- (template.modelRequirements.modelVariant === undefined)) {
1718
- throw new PromptbookLogicError(spaceTrim("\n\n You must specify MODEL VARIANT in the prompt template \"".concat(template.title, "\"\n\n For example:\n - MODEL VARIANT Chat\n - MODEL NAME `gpt-4-1106-preview`\n\n ")));
1719
- }
1720
- if (template.jokers && template.jokers.length > 0) {
1721
- if (!template.expectFormat &&
1722
- !template.expectations /* <- TODO: Require at least 1 -> min <- expectation to use jokers */) {
1723
- throw new PromptbookLogicError("Joker parameters are used for {".concat(template.resultingParameterName, "} but no expectations are defined"));
1724
- }
1725
- try {
1726
- for (var _j = (e_3 = void 0, __values(template.jokers)), _k = _j.next(); !_k.done; _k = _j.next()) {
1727
- var joker = _k.value;
1728
- if (!template.dependentParameterNames.includes(joker)) {
1729
- throw new PromptbookLogicError("Parameter {".concat(joker, "} is used for {").concat(template.resultingParameterName, "} as joker but not in dependentParameterNames"));
1730
- }
1731
- }
1732
- }
1733
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
1734
- finally {
1735
- try {
1736
- if (_k && !_k.done && (_c = _j.return)) _c.call(_j);
1737
- }
1738
- finally { if (e_3) throw e_3.error; }
1739
- }
1740
- }
1741
- if (template.expectations) {
1742
- try {
1743
- for (var _l = (e_4 = void 0, __values(Object.entries(template.expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
1744
- var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1745
- if (min !== undefined && max !== undefined && min > max) {
1746
- throw new PromptbookLogicError("Min expectation (=".concat(min, ") of ").concat(unit, " is higher than max expectation (=").concat(max, ")"));
1747
- }
1748
- if (min !== undefined && min < 0) {
1749
- throw new PromptbookLogicError("Min expectation of ".concat(unit, " must be zero or positive"));
1750
- }
1751
- if (max !== undefined && max <= 0) {
1752
- throw new PromptbookLogicError("Max expectation of ".concat(unit, " must be positive"));
1753
- }
1754
- }
1755
- }
1756
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
1757
- finally {
1758
- try {
1759
- if (_m && !_m.done && (_d = _l.return)) _d.call(_l);
1760
- }
1761
- finally { if (e_4) throw e_4.error; }
1762
- }
1763
- }
1764
- }
1765
- }
1766
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
1767
- finally {
1768
- try {
1769
- if (_h && !_h.done && (_b = _g.return)) _b.call(_g);
1770
- }
1771
- finally { if (e_2) throw e_2.error; }
1772
- }
1773
- // Note: Detect circular dependencies
1774
- var resovedParameters = promptbook.parameters
1775
- .filter(function (_a) {
1776
- var isInput = _a.isInput;
1777
- return isInput;
1778
- })
1779
- .map(function (_a) {
1780
- var name = _a.name;
1781
- return name;
1782
- });
1783
- var unresovedTemplates = __spreadArray([], __read(promptbook.promptTemplates), false);
1784
- var loopLimit = LOOP_LIMIT;
1785
- var _loop_2 = function () {
1786
- if (loopLimit-- < 0) {
1787
- throw new UnexpectedError('Loop limit reached during detection of circular dependencies in `validatePromptbookJson`');
1788
- }
1789
- var currentlyResovedTemplates = unresovedTemplates.filter(function (template) {
1790
- return template.dependentParameterNames.every(function (name) { return resovedParameters.includes(name); });
1791
- });
1792
- if (currentlyResovedTemplates.length === 0) {
1793
- throw new PromptbookLogicError(spaceTrim(function (block) { return "\n\n Can not resolve some parameters\n It may be circular dependencies\n\n Can not resolve:\n ".concat(block(unresovedTemplates
1794
- .map(function (_a) {
1795
- var resultingParameterName = _a.resultingParameterName, dependentParameterNames = _a.dependentParameterNames;
1796
- return "- {".concat(resultingParameterName, "} depends on ").concat(dependentParameterNames
1797
- .map(function (dependentParameterName) { return "{".concat(dependentParameterName, "}"); })
1798
- .join(', '));
1799
- })
1800
- .join('\n')), "\n\n Resolved:\n ").concat(block(resovedParameters.map(function (name) { return "- {".concat(name, "}"); }).join('\n')), "\n "); }));
1801
- }
1802
- resovedParameters = __spreadArray(__spreadArray([], __read(resovedParameters), false), __read(currentlyResovedTemplates.map(function (_a) {
1803
- var resultingParameterName = _a.resultingParameterName;
1804
- return resultingParameterName;
1805
- })), false);
1806
- unresovedTemplates = unresovedTemplates.filter(function (template) { return !currentlyResovedTemplates.includes(template); });
1807
- };
1808
- while (unresovedTemplates.length > 0) {
1809
- _loop_2();
1810
- }
1811
- return promptbook;
1812
- }
1813
- /**
1814
- * TODO: [🧠] Work with promptbookVersion
1815
- * TODO: Use here some json-schema, Zod or something similar and change it to:
1816
- * > /**
1817
- * > * Validates PromptbookJson if it is logically valid.
1818
- * > *
1819
- * > * It checks:
1820
- * > * - it has a valid structure
1821
- * > * - ...
1822
- * > ex port function validatePromptbookJson(promptbook: unknown): asserts promptbook is PromptbookJson {
1823
- */
1824
-
1825
- /**
1826
- * This error indicates that the promptbook library cannot be propperly loaded
1827
- */
1828
- var PromptbookLibraryError = /** @class */ (function (_super) {
1829
- __extends(PromptbookLibraryError, _super);
1830
- function PromptbookLibraryError(message) {
1831
- var _this = _super.call(this, message) || this;
1832
- _this.name = 'PromptbookLibraryError';
1833
- Object.setPrototypeOf(_this, PromptbookLibraryError.prototype);
1834
- return _this;
1835
- }
1836
- return PromptbookLibraryError;
1837
- }(Error));
1838
-
1839
- /**
1840
- * Detects if the code is running in a browser environment in main thread (Not in a web worker)
1841
- */
1842
- new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
1843
- /**
1844
- * Detects if the code is running in a Node.js environment
1845
- */
1846
- var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
1847
- /**
1848
- * Detects if the code is running in a web worker
1849
- */
1850
- new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
1851
-
1852
- /**
1853
- * Prettify the html code
1854
- *
1855
- * @param content raw html code
1856
- * @returns formatted html code
1857
- */
1858
- function prettifyMarkdown(content) {
1859
- try {
1860
- return format(content, {
1861
- parser: 'markdown',
1862
- plugins: [parserHtml],
1863
- // TODO: DRY - make some import or auto-copy of .prettierrc
1864
- endOfLine: 'lf',
1865
- tabWidth: 4,
1866
- singleQuote: true,
1867
- trailingComma: 'all',
1868
- arrowParens: 'always',
1869
- printWidth: 120,
1870
- htmlWhitespaceSensitivity: 'ignore',
1871
- jsxBracketSameLine: false,
1872
- bracketSpacing: true,
1873
- });
1874
- }
1875
- catch (error) {
1876
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1877
- error: error,
1878
- html: content,
1879
- });
1880
- return content;
1881
- }
1882
- }
1883
-
1884
- /**
1885
- * Converts promptbook in JSON format to string format
1886
- *
1887
- * @param promptbookJson Promptbook in JSON format (.ptbk.json)
1888
- * @returns Promptbook in string format (.ptbk.md)
1889
- */
1890
- function promptbookJsonToString(promptbookJson) {
1891
- var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f;
1892
- var title = promptbookJson.title, promptbookUrl = promptbookJson.promptbookUrl, promptbookVersion = promptbookJson.promptbookVersion, description = promptbookJson.description, parameters = promptbookJson.parameters, promptTemplates = promptbookJson.promptTemplates;
1893
- var promptbookString = "# ".concat(title);
1894
- if (description) {
1895
- promptbookString += '\n\n';
1896
- promptbookString += description;
1897
- }
1898
- // TODO:> const commands: Array<Command>
1899
- var commands = [];
1900
- if (promptbookUrl) {
1901
- commands.push("PROMPTBOOK URL ".concat(promptbookUrl));
1902
- }
1903
- commands.push("PROMPTBOOK VERSION ".concat(promptbookVersion));
1904
- promptbookString = prettifyMarkdown(promptbookString);
1905
- try {
1906
- for (var _g = __values(parameters.filter(function (_a) {
1907
- var isInput = _a.isInput;
1908
- return isInput;
1909
- })), _h = _g.next(); !_h.done; _h = _g.next()) {
1910
- var parameter = _h.value;
1911
- commands.push("INPUT PARAMETER ".concat(promptTemplateParameterJsonToString(parameter)));
1912
- }
1913
- }
1914
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1915
- finally {
1916
- try {
1917
- if (_h && !_h.done && (_a = _g.return)) _a.call(_g);
1600
+ if (_h && !_h.done && (_a = _g.return)) _a.call(_g);
1918
1601
  }
1919
1602
  finally { if (e_1) throw e_1.error; }
1920
1603
  }
@@ -2006,252 +1689,1514 @@ function promptbookJsonToString(promptbookJson) {
2006
1689
  catch (e_5_1) { e_5 = { error: e_5_1 }; }
2007
1690
  finally {
2008
1691
  try {
2009
- if (postprocessing_1_1 && !postprocessing_1_1.done && (_e = postprocessing_1.return)) _e.call(postprocessing_1);
2010
- }
2011
- finally { if (e_5) throw e_5.error; }
2012
- }
2013
- } /* not else */
2014
- if (expectations) {
2015
- try {
2016
- for (var _l = (e_6 = void 0, __values(Object.entries(expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
2017
- var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
2018
- if (min === max) {
2019
- commands_1.push("EXPECT EXACTLY ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
2020
- }
2021
- else {
2022
- if (min !== undefined) {
2023
- commands_1.push("EXPECT MIN ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
2024
- } /* not else */
2025
- if (max !== undefined) {
2026
- commands_1.push("EXPECT MAX ".concat(max, " ").concat(capitalize(unit + (max > 1 ? 's' : ''))));
2027
- }
1692
+ if (postprocessing_1_1 && !postprocessing_1_1.done && (_e = postprocessing_1.return)) _e.call(postprocessing_1);
1693
+ }
1694
+ finally { if (e_5) throw e_5.error; }
1695
+ }
1696
+ } /* not else */
1697
+ if (expectations) {
1698
+ try {
1699
+ for (var _l = (e_6 = void 0, __values(Object.entries(expectations))), _m = _l.next(); !_m.done; _m = _l.next()) {
1700
+ var _o = __read(_m.value, 2), unit = _o[0], _p = _o[1], min = _p.min, max = _p.max;
1701
+ if (min === max) {
1702
+ commands_1.push("EXPECT EXACTLY ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
1703
+ }
1704
+ else {
1705
+ if (min !== undefined) {
1706
+ commands_1.push("EXPECT MIN ".concat(min, " ").concat(capitalize(unit + (min > 1 ? 's' : ''))));
1707
+ } /* not else */
1708
+ if (max !== undefined) {
1709
+ commands_1.push("EXPECT MAX ".concat(max, " ").concat(capitalize(unit + (max > 1 ? 's' : ''))));
1710
+ }
1711
+ }
1712
+ }
1713
+ }
1714
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
1715
+ finally {
1716
+ try {
1717
+ if (_m && !_m.done && (_f = _l.return)) _f.call(_l);
1718
+ }
1719
+ finally { if (e_6) throw e_6.error; }
1720
+ }
1721
+ } /* not else */
1722
+ if (expectFormat) {
1723
+ if (expectFormat === 'JSON') {
1724
+ // TODO: @deprecated remove
1725
+ commands_1.push("EXPECT JSON");
1726
+ }
1727
+ } /* not else */
1728
+ promptbookString += '\n\n';
1729
+ promptbookString += commands_1.map(function (command) { return "- ".concat(command); }).join('\n');
1730
+ promptbookString += '\n\n';
1731
+ promptbookString += '```' + contentLanguage;
1732
+ promptbookString += '\n';
1733
+ promptbookString += spaceTrim$1(content);
1734
+ // <- TODO: !!! Escape
1735
+ // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
1736
+ promptbookString += '\n';
1737
+ promptbookString += '```';
1738
+ promptbookString += '\n\n';
1739
+ promptbookString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use promptTemplateParameterJsonToString
1740
+ }
1741
+ }
1742
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
1743
+ finally {
1744
+ try {
1745
+ if (promptTemplates_1_1 && !promptTemplates_1_1.done && (_c = promptTemplates_1.return)) _c.call(promptTemplates_1);
1746
+ }
1747
+ finally { if (e_3) throw e_3.error; }
1748
+ }
1749
+ return promptbookString;
1750
+ }
1751
+ /**
1752
+ * @private internal util of promptbookJsonToString
1753
+ */
1754
+ function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
1755
+ var name = promptTemplateParameterJson.name, description = promptTemplateParameterJson.description;
1756
+ var parameterString = "{".concat(name, "}");
1757
+ if (description) {
1758
+ parameterString = "".concat(parameterString, " ").concat(description);
1759
+ }
1760
+ return parameterString;
1761
+ }
1762
+ /**
1763
+ * TODO: Escape all
1764
+ */
1765
+
1766
+ /**
1767
+ * This error indicates that promptbook not found in the library
1768
+ */
1769
+ var PromptbookNotFoundError = /** @class */ (function (_super) {
1770
+ __extends(PromptbookNotFoundError, _super);
1771
+ function PromptbookNotFoundError(message) {
1772
+ var _this = _super.call(this, message) || this;
1773
+ _this.name = 'PromptbookNotFoundError';
1774
+ Object.setPrototypeOf(_this, PromptbookNotFoundError.prototype);
1775
+ return _this;
1776
+ }
1777
+ return PromptbookNotFoundError;
1778
+ }(Error));
1779
+
1780
+ /**
1781
+ * This error indicates errors in referencing promptbooks between each other
1782
+ */
1783
+ var PromptbookReferenceError = /** @class */ (function (_super) {
1784
+ __extends(PromptbookReferenceError, _super);
1785
+ function PromptbookReferenceError(message) {
1786
+ var _this = _super.call(this, message) || this;
1787
+ _this.name = 'PromptbookReferenceError';
1788
+ Object.setPrototypeOf(_this, PromptbookReferenceError.prototype);
1789
+ return _this;
1790
+ }
1791
+ return PromptbookReferenceError;
1792
+ }(Error));
1793
+
1794
+ /**
1795
+ * Library of promptbooks that groups together promptbooks for an application.
1796
+ * This implementation is a very thin wrapper around the Array / Map of promptbooks.
1797
+ *
1798
+ * @see https://github.com/webgptorg/promptbook#promptbook-library
1799
+ */
1800
+ var SimplePromptbookLibrary = /** @class */ (function () {
1801
+ /**
1802
+ * Constructs a promptbook library from promptbooks
1803
+ *
1804
+ * @param promptbooks !!!
1805
+ *
1806
+ * Note: During the construction logic of all promptbooks are validated
1807
+ * Note: It is not recommended to use this constructor directly, use `createPromptbookLibraryFromSources` *(or other variant)* instead
1808
+ */
1809
+ function SimplePromptbookLibrary() {
1810
+ var e_1, _a;
1811
+ var promptbooks = [];
1812
+ for (var _i = 0; _i < arguments.length; _i++) {
1813
+ promptbooks[_i] = arguments[_i];
1814
+ }
1815
+ this.library = new Map();
1816
+ try {
1817
+ for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
1818
+ var promptbook = promptbooks_1_1.value;
1819
+ if (promptbook.promptbookUrl === undefined) {
1820
+ throw new PromptbookReferenceError(spaceTrim("\n Promptbook with name \"".concat(promptbook.title, "\" does not have defined URL\n\n Note: Promptbooks without URLs are called anonymous promptbooks\n They can be used as standalone promptbooks, but they cannot be referenced by other promptbooks\n And also they cannot be used in the promptbook library\n\n ")));
1821
+ }
1822
+ validatePromptbookJson(promptbook);
1823
+ // Note: [🦄]
1824
+ if (this.library.has(promptbook.promptbookUrl) &&
1825
+ promptbookJsonToString(promptbook) !==
1826
+ promptbookJsonToString(this.library.get(promptbook.promptbookUrl))) {
1827
+ throw new PromptbookReferenceError(spaceTrim("\n Promptbook with URL \"".concat(promptbook.promptbookUrl, "\" is already in the library\n\n Note: Promptbooks with the same URL are not allowed\n Note: Automatically check whether the promptbooks are the same BUT they are DIFFERENT\n\n ")));
1828
+ }
1829
+ this.library.set(promptbook.promptbookUrl, promptbook);
1830
+ }
1831
+ }
1832
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1833
+ finally {
1834
+ try {
1835
+ if (promptbooks_1_1 && !promptbooks_1_1.done && (_a = promptbooks_1.return)) _a.call(promptbooks_1);
1836
+ }
1837
+ finally { if (e_1) throw e_1.error; }
1838
+ }
1839
+ }
1840
+ /**
1841
+ * Gets all promptbooks in the library
1842
+ */
1843
+ SimplePromptbookLibrary.prototype.listPromptbooks = function () {
1844
+ return Array.from(this.library.keys());
1845
+ };
1846
+ /**
1847
+ * Gets promptbook by its URL
1848
+ *
1849
+ * Note: This is not a direct fetching from the URL, but a lookup in the library
1850
+ */
1851
+ SimplePromptbookLibrary.prototype.getPromptbookByUrl = function (url) {
1852
+ var _this = this;
1853
+ var promptbook = this.library.get(url);
1854
+ if (!promptbook) {
1855
+ if (this.listPromptbooks().length === 0) {
1856
+ throw new PromptbookNotFoundError(spaceTrim("\n Promptbook with url \"".concat(url, "\" not found\n\n No promptbooks available\n ")));
1857
+ }
1858
+ throw new PromptbookNotFoundError(spaceTrim(function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
1859
+ .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
1860
+ .join('\n')), "\n\n "); }));
1861
+ }
1862
+ return promptbook;
1863
+ };
1864
+ /**
1865
+ * Checks whether given prompt was defined in any promptbook in the library
1866
+ */
1867
+ SimplePromptbookLibrary.prototype.isResponsibleForPrompt = function (prompt) {
1868
+ return true;
1869
+ };
1870
+ return SimplePromptbookLibrary;
1871
+ }());
1872
+
1873
+ /**
1874
+ * Creates PromptbookLibrary from array of PromptbookJson or PromptbookString
1875
+ *
1876
+ * Note: You can combine `PromptbookString` (`.ptbk.md`) with `PromptbookJson` BUT it is not recommended
1877
+ * Note: During the construction syntax and logic of all sources are validated
1878
+ *
1879
+ * @param promptbookSources
1880
+ * @returns PromptbookLibrary
1881
+ */
1882
+ function createPromptbookLibraryFromSources() {
1883
+ var promptbookSources = [];
1884
+ for (var _i = 0; _i < arguments.length; _i++) {
1885
+ promptbookSources[_i] = arguments[_i];
1886
+ }
1887
+ return __awaiter(this, void 0, void 0, function () {
1888
+ var promptbooks, promptbookSources_1, promptbookSources_1_1, source, promptbook, e_1_1;
1889
+ var e_1, _a;
1890
+ return __generator(this, function (_b) {
1891
+ switch (_b.label) {
1892
+ case 0:
1893
+ promptbooks = new Array();
1894
+ _b.label = 1;
1895
+ case 1:
1896
+ _b.trys.push([1, 8, 9, 10]);
1897
+ promptbookSources_1 = __values(promptbookSources), promptbookSources_1_1 = promptbookSources_1.next();
1898
+ _b.label = 2;
1899
+ case 2:
1900
+ if (!!promptbookSources_1_1.done) return [3 /*break*/, 7];
1901
+ source = promptbookSources_1_1.value;
1902
+ promptbook = void 0;
1903
+ if (!(typeof source === 'string')) return [3 /*break*/, 4];
1904
+ return [4 /*yield*/, promptbookStringToJson(source)];
1905
+ case 3:
1906
+ // Note: When directly creating from string, no need to validate the source
1907
+ // The validation is performed always before execution
1908
+ promptbook = _b.sent();
1909
+ return [3 /*break*/, 5];
1910
+ case 4:
1911
+ promptbook = source;
1912
+ _b.label = 5;
1913
+ case 5:
1914
+ promptbooks.push(promptbook);
1915
+ _b.label = 6;
1916
+ case 6:
1917
+ promptbookSources_1_1 = promptbookSources_1.next();
1918
+ return [3 /*break*/, 2];
1919
+ case 7: return [3 /*break*/, 10];
1920
+ case 8:
1921
+ e_1_1 = _b.sent();
1922
+ e_1 = { error: e_1_1 };
1923
+ return [3 /*break*/, 10];
1924
+ case 9:
1925
+ try {
1926
+ if (promptbookSources_1_1 && !promptbookSources_1_1.done && (_a = promptbookSources_1.return)) _a.call(promptbookSources_1);
1927
+ }
1928
+ finally { if (e_1) throw e_1.error; }
1929
+ return [7 /*endfinally*/];
1930
+ case 10: return [2 /*return*/, new (SimplePromptbookLibrary.bind.apply(SimplePromptbookLibrary, __spreadArray([void 0], __read(promptbooks), false)))()];
1931
+ }
1932
+ });
1933
+ });
1934
+ }
1935
+ /**
1936
+ * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
1937
+ */
1938
+
1939
+ /* tslint:disable */
1940
+ function normalizeToKebabCase(sentence) {
1941
+ var e_1, _a;
1942
+ sentence = removeDiacritics(sentence);
1943
+ var charType;
1944
+ var lastCharType = 'OTHER';
1945
+ var normalizedName = '';
1946
+ try {
1947
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
1948
+ var char = sentence_1_1.value;
1949
+ var normalizedChar = void 0;
1950
+ if (/^[a-z]$/.test(char)) {
1951
+ charType = 'LOWERCASE';
1952
+ normalizedChar = char;
1953
+ }
1954
+ else if (/^[A-Z]$/.test(char)) {
1955
+ charType = 'UPPERCASE';
1956
+ normalizedChar = char.toLowerCase();
1957
+ }
1958
+ else if (/^[0-9]$/.test(char)) {
1959
+ charType = 'NUMBER';
1960
+ normalizedChar = char;
1961
+ }
1962
+ else if (/^\/$/.test(char)) {
1963
+ charType = 'SLASH';
1964
+ normalizedChar = char;
1965
+ }
1966
+ else {
1967
+ charType = 'OTHER';
1968
+ normalizedChar = '-';
1969
+ }
1970
+ if (charType !== lastCharType &&
1971
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
1972
+ !(lastCharType === 'NUMBER') &&
1973
+ !(charType === 'NUMBER')) {
1974
+ normalizedName += '-';
1975
+ }
1976
+ normalizedName += normalizedChar;
1977
+ lastCharType = charType;
1978
+ }
1979
+ }
1980
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1981
+ finally {
1982
+ try {
1983
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
1984
+ }
1985
+ finally { if (e_1) throw e_1.error; }
1986
+ }
1987
+ normalizedName = normalizedName.split(/-+/g).join('-');
1988
+ normalizedName = normalizedName.split(/-?\/-?/g).join('/');
1989
+ normalizedName = normalizedName.replace(/^-/, '');
1990
+ normalizedName = normalizedName.replace(/-$/, '');
1991
+ return normalizedName;
1992
+ }
1993
+
1994
+ function prepareKnowledgeFromMarkdown(options) {
1995
+ return __awaiter(this, void 0, void 0, function () {
1996
+ var content, llmTools, library, promptbook, executor, result, outputParameters, knowledgeRaw, knowledgeTextPieces, knowledge;
1997
+ var _this = this;
1998
+ return __generator(this, function (_a) {
1999
+ switch (_a.label) {
2000
+ case 0:
2001
+ content = options.content, llmTools = options.llmTools;
2002
+ return [4 /*yield*/, createPromptbookLibraryFromSources.apply(void 0, __spreadArray([], __read(promptbookLibrary), false))];
2003
+ case 1:
2004
+ library = _a.sent();
2005
+ promptbook = library.getPromptbookByUrl('https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md');
2006
+ executor = createPromptbookExecutor({
2007
+ promptbook: promptbook,
2008
+ tools: {
2009
+ llm: llmTools,
2010
+ script: [
2011
+ /* <- TODO: Allow to just keep script undefined */
2012
+ ],
2013
+ },
2014
+ });
2015
+ return [4 /*yield*/, executor({ content: content })];
2016
+ case 2:
2017
+ result = _a.sent();
2018
+ assertsExecutionSuccessful(result);
2019
+ outputParameters = result.outputParameters;
2020
+ knowledgeRaw = outputParameters.knowledge;
2021
+ knowledgeTextPieces = (knowledgeRaw || '').split('\n---\n');
2022
+ return [4 /*yield*/, Promise.all(knowledgeTextPieces.map(function (knowledgeTextPiece, i) { return __awaiter(_this, void 0, void 0, function () {
2023
+ var name, title, content, keywords, index, sources;
2024
+ return __generator(this, function (_a) {
2025
+ name = "piece-".concat(i);
2026
+ title = spaceTrim$1(knowledgeTextPiece.substring(0, 100));
2027
+ content = spaceTrim$1(knowledgeTextPiece);
2028
+ keywords = [];
2029
+ index = [];
2030
+ sources = [];
2031
+ try {
2032
+ // TODO: !!!! Summarize name and title from the content
2033
+ title = spaceTrim$1(knowledgeTextPiece.substring(0, 30));
2034
+ name = normalizeToKebabCase(title);
2035
+ // TODO: !!!! Extract keywords via prompt
2036
+ // TODO: !!!! Index through LLM model
2037
+ // TODO: [🖖] !!!! Make system for sources and identification of sources
2038
+ }
2039
+ catch (error) {
2040
+ console.error(error);
2041
+ }
2042
+ return [2 /*return*/, {
2043
+ name: name,
2044
+ title: title,
2045
+ content: content,
2046
+ keywords: keywords,
2047
+ index: index,
2048
+ sources: sources,
2049
+ }];
2050
+ });
2051
+ }); }))];
2052
+ case 3:
2053
+ knowledge = _a.sent();
2054
+ return [2 /*return*/, knowledge];
2055
+ }
2056
+ });
2057
+ });
2058
+ }
2059
+
2060
+ /**
2061
+ * Supported script languages
2062
+ */
2063
+ var SUPPORTED_SCRIPT_LANGUAGES = ['javascript', 'typescript', 'python'];
2064
+
2065
+ /**
2066
+ * Computes the deepness of the markdown structure.
2067
+ *
2068
+ * @private within the library
2069
+ */
2070
+ function countMarkdownStructureDeepness(markdownStructure) {
2071
+ var e_1, _a;
2072
+ var maxDeepness = 0;
2073
+ try {
2074
+ for (var _b = __values(markdownStructure.sections), _c = _b.next(); !_c.done; _c = _b.next()) {
2075
+ var section = _c.value;
2076
+ maxDeepness = Math.max(maxDeepness, countMarkdownStructureDeepness(section));
2077
+ }
2078
+ }
2079
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2080
+ finally {
2081
+ try {
2082
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
2083
+ }
2084
+ finally { if (e_1) throw e_1.error; }
2085
+ }
2086
+ return maxDeepness + 1;
2087
+ }
2088
+
2089
+ /**
2090
+ * Parse a markdown string into a MarkdownStructure object.
2091
+ *
2092
+ * Note: This function does work with code blocks
2093
+ * Note: This function does not work with markdown comments
2094
+ *
2095
+ * @param markdown The markdown string to parse.
2096
+ * @returns The MarkdownStructure object.
2097
+ *
2098
+ * @private within the library
2099
+ */
2100
+ function markdownToMarkdownStructure(markdown) {
2101
+ var e_1, _a;
2102
+ var lines = markdown.split('\n');
2103
+ var root = { level: 0, title: '', contentLines: [], sections: [], parent: null };
2104
+ var current = root;
2105
+ var isInsideCodeBlock = false;
2106
+ try {
2107
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2108
+ var line = lines_1_1.value;
2109
+ var headingMatch = line.match(/^(?<mark>#{1,6})\s(?<title>.*)/);
2110
+ if (isInsideCodeBlock || !headingMatch) {
2111
+ if (line.startsWith('```')) {
2112
+ isInsideCodeBlock = !isInsideCodeBlock;
2113
+ }
2114
+ current.contentLines.push(line);
2115
+ }
2116
+ else {
2117
+ var level = headingMatch.groups.mark.length;
2118
+ var title = headingMatch.groups.title.trim();
2119
+ var parent_1 = void 0;
2120
+ if (level > current.level) {
2121
+ // Note: Going deeper (next section is child of current)
2122
+ parent_1 = current;
2123
+ }
2124
+ else {
2125
+ // Note: Going up or staying at the same level (next section is sibling or parent or grandparent,... of current)
2126
+ parent_1 = current;
2127
+ var loopLimit = LOOP_LIMIT;
2128
+ while (parent_1.level !== level - 1) {
2129
+ if (loopLimit-- < 0) {
2130
+ throw new UnexpectedError('Loop limit reached during parsing of markdown structure in `markdownToMarkdownStructure`');
2131
+ }
2132
+ if (parent_1.parent === null /* <- Note: We are in root */) {
2133
+ // [🌻]
2134
+ throw new Error(spaceTrim("\n The file has an invalid structure.\n The markdown file must have exactly one top-level section.\n "));
2135
+ }
2136
+ parent_1 = parent_1.parent;
2137
+ }
2138
+ }
2139
+ var section = { level: level, title: title, contentLines: [], sections: [], parent: parent_1 };
2140
+ parent_1.sections.push(section);
2141
+ current = section;
2142
+ }
2143
+ }
2144
+ }
2145
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2146
+ finally {
2147
+ try {
2148
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2149
+ }
2150
+ finally { if (e_1) throw e_1.error; }
2151
+ }
2152
+ if (root.sections.length === 1) {
2153
+ var markdownStructure = parsingMarkdownStructureToMarkdownStructure(root.sections[0]);
2154
+ return markdownStructure;
2155
+ }
2156
+ // [🌻]
2157
+ throw new Error('The markdown file must have exactly one top-level section.');
2158
+ // return root;
2159
+ }
2160
+ /**
2161
+ * @private
2162
+ */
2163
+ function parsingMarkdownStructureToMarkdownStructure(parsingMarkdownStructure) {
2164
+ var level = parsingMarkdownStructure.level, title = parsingMarkdownStructure.title, contentLines = parsingMarkdownStructure.contentLines, sections = parsingMarkdownStructure.sections;
2165
+ return {
2166
+ level: level,
2167
+ title: title,
2168
+ content: spaceTrim(contentLines.join('\n')),
2169
+ sections: sections.map(parsingMarkdownStructureToMarkdownStructure),
2170
+ };
2171
+ }
2172
+
2173
+ /**
2174
+ * Utility function to extract all list items from markdown
2175
+ *
2176
+ * Note: It works with both ul and ol
2177
+ * Note: It omits list items in code blocks
2178
+ * Note: It flattens nested lists
2179
+ * Note: It can not work with html syntax and comments
2180
+ *
2181
+ * @param markdown any valid markdown
2182
+ * @returns
2183
+ */
2184
+ function extractAllListItemsFromMarkdown(markdown) {
2185
+ var e_1, _a;
2186
+ var lines = markdown.split('\n');
2187
+ var listItems = [];
2188
+ var isInCodeBlock = false;
2189
+ try {
2190
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2191
+ var line = lines_1_1.value;
2192
+ var trimmedLine = line.trim();
2193
+ if (trimmedLine.startsWith('```')) {
2194
+ isInCodeBlock = !isInCodeBlock;
2195
+ }
2196
+ if (!isInCodeBlock && (trimmedLine.startsWith('-') || trimmedLine.match(/^\d+\./))) {
2197
+ var listItem = trimmedLine.replace(/^-|\d+\./, '').trim();
2198
+ listItems.push(listItem);
2199
+ }
2200
+ }
2201
+ }
2202
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2203
+ finally {
2204
+ try {
2205
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2206
+ }
2207
+ finally { if (e_1) throw e_1.error; }
2208
+ }
2209
+ return listItems;
2210
+ }
2211
+
2212
+ /**
2213
+ * Extracts all code blocks from markdown.
2214
+ *
2215
+ * Note: There are 3 simmilar function:
2216
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2217
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2218
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2219
+ *
2220
+ * @param markdown any valid markdown
2221
+ * @returns code blocks with language and content
2222
+ *
2223
+ */
2224
+ function extractAllBlocksFromMarkdown(markdown) {
2225
+ var e_1, _a;
2226
+ var codeBlocks = [];
2227
+ var lines = markdown.split('\n');
2228
+ var currentCodeBlock = null;
2229
+ try {
2230
+ for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
2231
+ var line = lines_1_1.value;
2232
+ if (line.startsWith('```')) {
2233
+ var language = line.slice(3).trim() || null;
2234
+ if (currentCodeBlock === null) {
2235
+ currentCodeBlock = { language: language, content: '' };
2236
+ }
2237
+ else {
2238
+ if (language !== null) {
2239
+ // [🌻]
2240
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed and already opening new ").concat(language, " code block"));
2241
+ }
2242
+ codeBlocks.push(currentCodeBlock);
2243
+ currentCodeBlock = null;
2244
+ }
2245
+ }
2246
+ else if (currentCodeBlock !== null) {
2247
+ if (currentCodeBlock.content !== '') {
2248
+ currentCodeBlock.content += '\n';
2249
+ }
2250
+ currentCodeBlock.content += line.split('\\`\\`\\`').join('```') /* <- TODO: Maybe make propper unescape */;
2251
+ }
2252
+ }
2253
+ }
2254
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2255
+ finally {
2256
+ try {
2257
+ if (lines_1_1 && !lines_1_1.done && (_a = lines_1.return)) _a.call(lines_1);
2258
+ }
2259
+ finally { if (e_1) throw e_1.error; }
2260
+ }
2261
+ if (currentCodeBlock !== null) {
2262
+ // [🌻]
2263
+ throw new Error("".concat(capitalize(currentCodeBlock.language || 'the'), " code block was not closed at the end of the markdown"));
2264
+ }
2265
+ return codeBlocks;
2266
+ }
2267
+
2268
+ /**
2269
+ * Extracts exactly ONE code block from markdown.
2270
+ *
2271
+ * Note: If there are multiple or no code blocks the function throws an error
2272
+ *
2273
+ * Note: There are 3 simmilar function:
2274
+ * - `extractBlock` just extracts the content of the code block which is also used as build-in function for postprocessing
2275
+ * - `extractOneBlockFromMarkdown` extracts exactly one code block with language of the code block
2276
+ * - `extractAllBlocksFromMarkdown` extracts all code blocks with language of the code block
2277
+ *
2278
+ * @param markdown any valid markdown
2279
+ * @returns code block with language and content
2280
+ */
2281
+ function extractOneBlockFromMarkdown(markdown) {
2282
+ var codeBlocks = extractAllBlocksFromMarkdown(markdown);
2283
+ if (codeBlocks.length !== 1) {
2284
+ // TODO: Report more specific place where the error happened
2285
+ throw new Error(/* <- [🌻] */ 'There should be exactly one code block in the markdown');
2286
+ }
2287
+ return codeBlocks[0];
2288
+ }
2289
+ /***
2290
+ * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
2291
+ */
2292
+
2293
+ /**
2294
+ * Removes HTML or Markdown comments from a string.
2295
+ *
2296
+ * @param {string} content - The string to remove comments from.
2297
+ * @returns {string} The input string with all comments removed.
2298
+ */
2299
+ function removeContentComments(content) {
2300
+ return spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
2301
+ }
2302
+
2303
+ /**
2304
+ * Creates a new set with all elements that are present in either set
2305
+ */
2306
+ function union() {
2307
+ var e_1, _a, e_2, _b;
2308
+ var sets = [];
2309
+ for (var _i = 0; _i < arguments.length; _i++) {
2310
+ sets[_i] = arguments[_i];
2311
+ }
2312
+ var union = new Set();
2313
+ try {
2314
+ for (var sets_1 = __values(sets), sets_1_1 = sets_1.next(); !sets_1_1.done; sets_1_1 = sets_1.next()) {
2315
+ var set = sets_1_1.value;
2316
+ try {
2317
+ for (var _c = (e_2 = void 0, __values(Array.from(set))), _d = _c.next(); !_d.done; _d = _c.next()) {
2318
+ var item = _d.value;
2319
+ union.add(item);
2320
+ }
2321
+ }
2322
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2323
+ finally {
2324
+ try {
2325
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
2326
+ }
2327
+ finally { if (e_2) throw e_2.error; }
2328
+ }
2329
+ }
2330
+ }
2331
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2332
+ finally {
2333
+ try {
2334
+ if (sets_1_1 && !sets_1_1.done && (_a = sets_1.return)) _a.call(sets_1);
2335
+ }
2336
+ finally { if (e_1) throw e_1.error; }
2337
+ }
2338
+ return union;
2339
+ }
2340
+
2341
+ /**
2342
+ * Parses the template and returns the list of all parameter names
2343
+ *
2344
+ * @param template the template with parameters in {curly} braces
2345
+ * @returns the list of parameter names
2346
+ */
2347
+ function extractParameters(template) {
2348
+ var e_1, _a;
2349
+ var matches = template.matchAll(/{\w+}/g);
2350
+ var parameterNames = new Set();
2351
+ try {
2352
+ for (var matches_1 = __values(matches), matches_1_1 = matches_1.next(); !matches_1_1.done; matches_1_1 = matches_1.next()) {
2353
+ var match = matches_1_1.value;
2354
+ var parameterName = match[0].slice(1, -1);
2355
+ parameterNames.add(parameterName);
2356
+ }
2357
+ }
2358
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2359
+ finally {
2360
+ try {
2361
+ if (matches_1_1 && !matches_1_1.done && (_a = matches_1.return)) _a.call(matches_1);
2362
+ }
2363
+ finally { if (e_1) throw e_1.error; }
2364
+ }
2365
+ return parameterNames;
2366
+ }
2367
+
2368
+ /**
2369
+ * Parses the given script and returns the list of all used variables that are not defined in the script
2370
+ *
2371
+ * @param script from which to extract the variables
2372
+ * @returns the list of variable names
2373
+ * @throws {PromptbookSyntaxError} if the script is invalid
2374
+ */
2375
+ function extractVariables(script) {
2376
+ var variables = new Set();
2377
+ script = "(()=>{".concat(script, "})()");
2378
+ try {
2379
+ for (var i = 0; i < 100 /* <- TODO: This limit to configuration */; i++)
2380
+ try {
2381
+ eval(script);
2382
+ }
2383
+ catch (error) {
2384
+ if (!(error instanceof ReferenceError)) {
2385
+ throw error;
2386
+ }
2387
+ var undefinedName = error.message.split(' ')[0];
2388
+ /*
2389
+ Note: Remapping error
2390
+ From: [ReferenceError: thing is not defined],
2391
+ To: [Error: Parameter {thing} is not defined],
2392
+ */
2393
+ if (!undefinedName) {
2394
+ throw error;
2395
+ }
2396
+ if (script.includes(undefinedName + '(')) {
2397
+ script = "const ".concat(undefinedName, " = ()=>'';") + script;
2398
+ }
2399
+ else {
2400
+ variables.add(undefinedName);
2401
+ script = "const ".concat(undefinedName, " = '';") + script;
2402
+ }
2403
+ }
2404
+ }
2405
+ catch (error) {
2406
+ if (!(error instanceof Error)) {
2407
+ throw error;
2408
+ }
2409
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Can not extract variables from the script\n\n ".concat(block(error.name), ": ").concat(block(error.message), "\n "); }));
2410
+ }
2411
+ return variables;
2412
+ }
2413
+ /**
2414
+ * TODO: [🔣] Support for multiple languages - python, java,...
2415
+ */
2416
+
2417
+ /**
2418
+ * Parses the prompt template and returns the set of all used parameters
2419
+ *
2420
+ * @param promptTemplate the template with used parameters
2421
+ * @returns the set of parameter names
2422
+ * @throws {PromptbookSyntaxError} if the script is invalid
2423
+ */
2424
+ function extractParametersFromPromptTemplate(promptTemplate) {
2425
+ var e_1, _a, e_2, _b;
2426
+ var parameterNames = new Set();
2427
+ try {
2428
+ for (var _c = __values(__spreadArray(__spreadArray(__spreadArray([], __read(extractParameters(promptTemplate.title)), false), __read(extractParameters(promptTemplate.description || '')), false), __read(extractParameters(promptTemplate.content)), false)), _d = _c.next(); !_d.done; _d = _c.next()) {
2429
+ var parameterName = _d.value;
2430
+ parameterNames.add(parameterName);
2431
+ }
2432
+ }
2433
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2434
+ finally {
2435
+ try {
2436
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
2437
+ }
2438
+ finally { if (e_1) throw e_1.error; }
2439
+ }
2440
+ if (promptTemplate.executionType === 'SCRIPT') {
2441
+ try {
2442
+ for (var _e = __values(extractVariables(promptTemplate.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
2443
+ var parameterName = _f.value;
2444
+ parameterNames.add(parameterName);
2445
+ }
2446
+ }
2447
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
2448
+ finally {
2449
+ try {
2450
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
2451
+ }
2452
+ finally { if (e_2) throw e_2.error; }
2453
+ }
2454
+ }
2455
+ return parameterNames;
2456
+ }
2457
+ /**
2458
+ * TODO: [🔣] If script require contentLanguage
2459
+ */
2460
+
2461
+ /* tslint:disable */
2462
+ /*
2463
+ TODO: Tests
2464
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'Moje tabule' })).toEqual('/VtG7sR9rRJqwNEdM2/Moje tabule');
2465
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: 'ěščřžžýáíúů' })).toEqual('/VtG7sR9rRJqwNEdM2/escrzyaieuu');
2466
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj');
2467
+ expect(encodeRoutePath({ uriId: 'VtG7sR9rRJqwNEdM2', name: ' ahoj_ahojAhoj ahoj ' })).toEqual('/VtG7sR9rRJqwNEdM2/ahoj-ahoj-ahoj-ahoj');
2468
+ */
2469
+ function normalizeTo_SCREAMING_CASE(sentence) {
2470
+ var e_1, _a;
2471
+ var charType;
2472
+ var lastCharType = 'OTHER';
2473
+ var normalizedName = '';
2474
+ try {
2475
+ for (var sentence_1 = __values(sentence), sentence_1_1 = sentence_1.next(); !sentence_1_1.done; sentence_1_1 = sentence_1.next()) {
2476
+ var char = sentence_1_1.value;
2477
+ var normalizedChar = void 0;
2478
+ if (/^[a-z]$/.test(char)) {
2479
+ charType = 'LOWERCASE';
2480
+ normalizedChar = char.toUpperCase();
2481
+ }
2482
+ else if (/^[A-Z]$/.test(char)) {
2483
+ charType = 'UPPERCASE';
2484
+ normalizedChar = char;
2485
+ }
2486
+ else if (/^[0-9]$/.test(char)) {
2487
+ charType = 'NUMBER';
2488
+ normalizedChar = char;
2489
+ }
2490
+ else if (/^\/$/.test(char)) {
2491
+ charType = 'SLASH';
2492
+ normalizedChar = char;
2493
+ }
2494
+ else {
2495
+ charType = 'OTHER';
2496
+ normalizedChar = '_';
2497
+ }
2498
+ if (charType !== lastCharType &&
2499
+ !(lastCharType === 'UPPERCASE' && charType === 'LOWERCASE') &&
2500
+ !(lastCharType === 'NUMBER') &&
2501
+ !(charType === 'NUMBER')) {
2502
+ normalizedName += '_';
2503
+ }
2504
+ normalizedName += normalizedChar;
2505
+ lastCharType = charType;
2506
+ }
2507
+ }
2508
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2509
+ finally {
2510
+ try {
2511
+ if (sentence_1_1 && !sentence_1_1.done && (_a = sentence_1.return)) _a.call(sentence_1);
2512
+ }
2513
+ finally { if (e_1) throw e_1.error; }
2514
+ }
2515
+ normalizedName = normalizedName.replace(/_+/g, '_');
2516
+ normalizedName = normalizedName.replace(/_?\/_?/g, '/');
2517
+ normalizedName = normalizedName.replace(/^_/, '');
2518
+ normalizedName = normalizedName.replace(/_$/, '');
2519
+ return normalizedName;
2520
+ }
2521
+ /**
2522
+ * TODO: [🌺] Use some intermediate util splitWords
2523
+ */
2524
+
2525
+ /**
2526
+ * Execution type describes the way how the block is executed
2527
+ *
2528
+ * @see https://github.com/webgptorg/promptbook#execution-type
2529
+ */
2530
+ var ExecutionTypes = [
2531
+ 'PROMPT_TEMPLATE',
2532
+ 'SIMPLE_TEMPLATE',
2533
+ 'SCRIPT',
2534
+ 'PROMPT_DIALOG',
2535
+ // <- [🥻] Insert here when making new command
2536
+ ];
2537
+
2538
+ /**
2539
+ * Units of text measurement
2540
+ */
2541
+ var EXPECTATION_UNITS = ['CHARACTERS', 'WORDS', 'SENTENCES', 'LINES', 'PARAGRAPHS', 'PAGES'];
2542
+ /**
2543
+ * TODO: [💝] Unite object for expecting amount and format - remove expectFormat
2544
+ * TODO: use one helper type> (string_prompt | string_javascript | string_markdown) & string_template
2545
+ * TODO: [👙][🧠] Just selecting gpt3 or gpt4 level of model
2546
+ */
2547
+
2548
+ /**
2549
+ * Removes Markdown formatting tags from a string.
2550
+ *
2551
+ * @param {string} str - The string to remove Markdown tags from.
2552
+ * @returns {string} The input string with all Markdown tags removed.
2553
+ */
2554
+ function removeMarkdownFormatting(str) {
2555
+ // Remove bold formatting
2556
+ str = str.replace(/\*\*(.*?)\*\*/g, '$1');
2557
+ // Remove italic formatting
2558
+ str = str.replace(/\*(.*?)\*/g, '$1');
2559
+ // Remove code formatting
2560
+ str = str.replace(/`(.*?)`/g, '$1');
2561
+ return str;
2562
+ }
2563
+
2564
+ /**
2565
+ * Function parseNumber will parse number from string
2566
+ *
2567
+ * Unlike Number.parseInt, Number.parseFloat it will never ever result in NaN
2568
+ * Note: it also works only with decimal numbers
2569
+ *
2570
+ * @returns parsed number
2571
+ * @throws {PromptbookSyntaxError} if the value is not a number
2572
+ *
2573
+ * @private within the parseCommand
2574
+ */
2575
+ function parseNumber(value) {
2576
+ var originalValue = value;
2577
+ if (typeof value === 'number') {
2578
+ value = value.toString(); // <- TODO: Maybe more efficient way to do this
2579
+ }
2580
+ if (typeof value !== 'string') {
2581
+ return 0;
2582
+ }
2583
+ value = value.trim();
2584
+ if (value.startsWith('+')) {
2585
+ return parseNumber(value.substring(1));
2586
+ }
2587
+ if (value.startsWith('-')) {
2588
+ var number = parseNumber(value.substring(1));
2589
+ if (number === 0) {
2590
+ return 0; // <- Note: To prevent -0
2591
+ }
2592
+ return -number;
2593
+ }
2594
+ value = value.replace(/,/g, '.');
2595
+ value = value.toUpperCase();
2596
+ if (value === '') {
2597
+ return 0;
2598
+ }
2599
+ if (value === '♾' || value.startsWith('INF')) {
2600
+ return Infinity;
2601
+ }
2602
+ if (value.includes('/')) {
2603
+ var _a = __read(value.split('/'), 2), numerator_ = _a[0], denominator_ = _a[1];
2604
+ var numerator = parseNumber(numerator_);
2605
+ var denominator = parseNumber(denominator_);
2606
+ if (denominator === 0) {
2607
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\" because denominator is zero"));
2608
+ }
2609
+ return numerator / denominator;
2610
+ }
2611
+ if (/^(NAN|NULL|NONE|UNDEFINED|ZERO|NO.*)$/.test(value)) {
2612
+ return 0;
2613
+ }
2614
+ if (value.includes('E')) {
2615
+ var _b = __read(value.split('E'), 2), significand = _b[0], exponent = _b[1];
2616
+ return parseNumber(significand) * Math.pow(10, parseNumber(exponent));
2617
+ }
2618
+ if (!/^[0-9.]+$/.test(value) || value.split('.').length > 2) {
2619
+ throw new PromptbookSyntaxError("Unable to parse number from \"".concat(originalValue, "\""));
2620
+ }
2621
+ var num = parseFloat(value);
2622
+ if (isNaN(num)) {
2623
+ throw new PromptbookSyntaxError("Unexpected NaN when parsing number from \"".concat(originalValue, "\""));
2624
+ }
2625
+ return num;
2626
+ }
2627
+ /**
2628
+ * TODO: Maybe use sth. like safe-eval in fraction/calculation case @see https://www.npmjs.com/package/safe-eval
2629
+ */
2630
+
2631
+ /**
2632
+ * Parses one line of ul/ol to command
2633
+ *
2634
+ * @returns parsed command object
2635
+ * @throws {PromptbookSyntaxError} if the command is invalid
2636
+ *
2637
+ * @private within the promptbookStringToJson
2638
+ */
2639
+ function parseCommand(listItem) {
2640
+ var e_1, _a;
2641
+ if (listItem.includes('\n') || listItem.includes('\r')) {
2642
+ throw new PromptbookSyntaxError('Command can not contain new line characters:');
2643
+ }
2644
+ var type = listItem.trim();
2645
+ type = type.split('`').join('');
2646
+ type = type.split('"').join('');
2647
+ type = type.split("'").join('');
2648
+ type = type.split('~').join('');
2649
+ type = type.split('[').join('');
2650
+ type = type.split(']').join('');
2651
+ type = type.split('(').join('');
2652
+ type = type.split(')').join('');
2653
+ type = normalizeTo_SCREAMING_CASE(type);
2654
+ type = type.split('DIALOGUE').join('DIALOG');
2655
+ var listItemParts = listItem
2656
+ .split(' ')
2657
+ .map(function (part) { return part.trim(); })
2658
+ .filter(function (item) { return item !== ''; })
2659
+ .filter(function (item) { return !/^PTBK$/i.test(item); })
2660
+ .filter(function (item) { return !/^PROMPTBOOK$/i.test(item); })
2661
+ .map(removeMarkdownFormatting);
2662
+ if (type.startsWith('URL') ||
2663
+ type.startsWith('PTBK_URL') ||
2664
+ type.startsWith('PTBKURL') ||
2665
+ type.startsWith('PROMPTBOOK_URL') ||
2666
+ type.startsWith('PROMPTBOOKURL') ||
2667
+ type.startsWith('HTTPS')) {
2668
+ if (!(listItemParts.length === 2 || (listItemParts.length === 1 && type.startsWith('HTTPS')))) {
2669
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n ")));
2670
+ }
2671
+ var promptbookUrlString = listItemParts.pop();
2672
+ var promptbookUrl = new URL(promptbookUrlString);
2673
+ if (promptbookUrl.protocol !== 'https:') {
2674
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_URL command:\n\n - ".concat(listItem, "\n\n Protocol must be HTTPS\n ")));
2675
+ }
2676
+ if (promptbookUrl.hash !== '') {
2677
+ throw new PromptbookSyntaxError(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 ")));
2678
+ }
2679
+ return {
2680
+ type: 'PROMPTBOOK_URL',
2681
+ promptbookUrl: promptbookUrl,
2682
+ };
2683
+ }
2684
+ else if (type.startsWith('PROMPTBOOK_VERSION') || type.startsWith('PTBK_VERSION')) {
2685
+ if (listItemParts.length !== 2) {
2686
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid PROMPTBOOK_VERSION command:\n\n - ".concat(listItem, "\n ")));
2687
+ }
2688
+ var promptbookVersion = listItemParts.pop();
2689
+ // TODO: Validate version
2690
+ return {
2691
+ type: 'PROMPTBOOK_VERSION',
2692
+ promptbookVersion: promptbookVersion,
2693
+ };
2694
+ }
2695
+ else if (type.startsWith('EXECUTE') ||
2696
+ type.startsWith('EXEC') ||
2697
+ type.startsWith('PROMPT_DIALOG') ||
2698
+ type.startsWith('SIMPLE_TEMPLATE')) {
2699
+ var executionTypes = ExecutionTypes.filter(function (executionType) { return type.includes(executionType); });
2700
+ if (executionTypes.length !== 1) {
2701
+ throw new PromptbookSyntaxError(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 "); }));
2702
+ }
2703
+ return {
2704
+ type: 'EXECUTE',
2705
+ executionType: executionTypes[0],
2706
+ };
2707
+ }
2708
+ else if (type.startsWith('MODEL')) {
2709
+ // TODO: Make this more elegant and dynamically
2710
+ if (type.startsWith('MODEL_VARIANT')) {
2711
+ if (type === 'MODEL_VARIANT_CHAT') {
2712
+ return {
2713
+ type: 'MODEL',
2714
+ key: 'modelVariant',
2715
+ value: 'CHAT',
2716
+ };
2717
+ }
2718
+ else if (type === 'MODEL_VARIANT_COMPLETION') {
2719
+ return {
2720
+ type: 'MODEL',
2721
+ key: 'modelVariant',
2722
+ value: 'COMPLETION',
2723
+ };
2724
+ }
2725
+ else {
2726
+ throw new PromptbookSyntaxError(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 "); }));
2727
+ }
2728
+ }
2729
+ if (type.startsWith('MODEL_NAME')) {
2730
+ return {
2731
+ type: 'MODEL',
2732
+ key: 'modelName',
2733
+ value: listItemParts.pop(),
2734
+ };
2735
+ }
2736
+ else {
2737
+ throw new PromptbookSyntaxError(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 "); }));
2738
+ }
2739
+ }
2740
+ else if (type.startsWith('PARAM') ||
2741
+ type.startsWith('INPUT_PARAM') ||
2742
+ type.startsWith('OUTPUT_PARAM') ||
2743
+ listItem.startsWith('{') ||
2744
+ listItem.startsWith('> {') /* <- Note: This is a bit hack to parse return parameters defined at the end of each section */) {
2745
+ var parametersMatch = listItem.match(/\{(?<parameterName>[a-z0-9_]+)\}[^\S\r\n]*(?<parameterDescription>.*)$/im);
2746
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
2747
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
2748
+ }
2749
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2750
+ var _b = parametersMatch.groups, parameterName = _b.parameterName, parameterDescription = _b.parameterDescription;
2751
+ if (parameterDescription && parameterDescription.match(/\{(?<parameterName>[a-z0-9_]+)\}/im)) {
2752
+ throw new PromptbookSyntaxError(spaceTrim("\n Parameter {".concat(parameterName, "} can not contain another parameter in description:\n\n - ").concat(listItem, "\n ")));
2753
+ }
2754
+ var isInput = type.startsWith('INPUT');
2755
+ var isOutput = type.startsWith('OUTPUT');
2756
+ if (listItem.startsWith('> {')) {
2757
+ isInput = false;
2758
+ isOutput = false;
2759
+ }
2760
+ return {
2761
+ type: 'PARAMETER',
2762
+ parameterName: parameterName,
2763
+ parameterDescription: parameterDescription.trim() || null,
2764
+ isInput: isInput,
2765
+ isOutput: isOutput,
2766
+ };
2767
+ }
2768
+ else if (type.startsWith('JOKER')) {
2769
+ if (listItemParts.length !== 2) {
2770
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid JOKER command:\n\n - ".concat(listItem, "\n ")));
2771
+ }
2772
+ var parametersMatch = (listItemParts.pop() || '').match(/^\{(?<parameterName>[a-z0-9_]+)\}$/im);
2773
+ if (!parametersMatch || !parametersMatch.groups || !parametersMatch.groups.parameterName) {
2774
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid parameter in command:\n\n - ".concat(listItem, "\n ")));
2775
+ }
2776
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2777
+ var parameterName = parametersMatch.groups.parameterName;
2778
+ return {
2779
+ type: 'JOKER',
2780
+ parameterName: parameterName,
2781
+ };
2782
+ }
2783
+ else if (type.startsWith('POSTPROCESS') || type.startsWith('POST_PROCESS')) {
2784
+ if (listItemParts.length !== 2) {
2785
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid POSTPROCESSING command:\n\n - ".concat(listItem, "\n ")));
2786
+ }
2787
+ var functionName = listItemParts.pop();
2788
+ return {
2789
+ type: 'POSTPROCESS',
2790
+ functionName: functionName,
2791
+ };
2792
+ }
2793
+ else if (type.startsWith('EXPECT_JSON')) {
2794
+ return {
2795
+ type: 'EXPECT_FORMAT',
2796
+ format: 'JSON',
2797
+ };
2798
+ // [🥤]
2799
+ }
2800
+ else if (type.startsWith('EXPECT')) {
2801
+ try {
2802
+ listItemParts.shift();
2803
+ var sign = void 0;
2804
+ var signRaw = listItemParts.shift();
2805
+ if (/^exact/i.test(signRaw)) {
2806
+ sign = 'EXACTLY';
2807
+ }
2808
+ else if (/^min/i.test(signRaw)) {
2809
+ sign = 'MINIMUM';
2810
+ }
2811
+ else if (/^max/i.test(signRaw)) {
2812
+ sign = 'MAXIMUM';
2813
+ }
2814
+ else {
2815
+ throw new PromptbookSyntaxError("Invalid sign \"".concat(signRaw, "\", expected EXACTLY, MIN or MAX"));
2816
+ }
2817
+ var amountRaw = listItemParts.shift();
2818
+ var amount = parseNumber(amountRaw);
2819
+ if (amount < 0) {
2820
+ throw new PromptbookSyntaxError('Amount must be positive number or zero');
2821
+ }
2822
+ if (amount !== Math.floor(amount)) {
2823
+ throw new PromptbookSyntaxError('Amount must be whole number');
2824
+ }
2825
+ var unitRaw = listItemParts.shift();
2826
+ var unit = undefined;
2827
+ try {
2828
+ 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()) {
2829
+ var existingUnit = EXPECTATION_UNITS_1_1.value;
2830
+ var existingUnitText = existingUnit;
2831
+ existingUnitText = existingUnitText.substring(0, existingUnitText.length - 1);
2832
+ if (existingUnitText === 'CHARACTER') {
2833
+ existingUnitText = 'CHAR';
2834
+ }
2835
+ if (new RegExp("^".concat(existingUnitText.toLowerCase())).test(unitRaw.toLowerCase()) ||
2836
+ new RegExp("^".concat(unitRaw.toLowerCase())).test(existingUnitText.toLowerCase())) {
2837
+ if (unit !== undefined) {
2838
+ throw new PromptbookSyntaxError("Ambiguous unit \"".concat(unitRaw, "\""));
2839
+ }
2840
+ unit = existingUnit;
2841
+ }
2842
+ }
2843
+ }
2844
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
2845
+ finally {
2846
+ try {
2847
+ if (EXPECTATION_UNITS_1_1 && !EXPECTATION_UNITS_1_1.done && (_a = EXPECTATION_UNITS_1.return)) _a.call(EXPECTATION_UNITS_1);
2848
+ }
2849
+ finally { if (e_1) throw e_1.error; }
2850
+ }
2851
+ if (unit === undefined) {
2852
+ throw new PromptbookSyntaxError("Invalid unit \"".concat(unitRaw, "\""));
2853
+ }
2854
+ return {
2855
+ type: 'EXPECT_AMOUNT',
2856
+ sign: sign,
2857
+ unit: unit,
2858
+ amount: amount,
2859
+ };
2860
+ }
2861
+ catch (error) {
2862
+ if (!(error instanceof Error)) {
2863
+ throw error;
2864
+ }
2865
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid EXPECT command; ".concat(error.message, ":\n\n - ").concat(listItem, "\n ")));
2866
+ }
2867
+ /*
2868
+ } else if (type.startsWith('__________________')) {
2869
+ // <- [🥻] Insert here when making new command
2870
+ */
2871
+ }
2872
+ else {
2873
+ throw new PromptbookSyntaxError(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 ")));
2874
+ }
2875
+ }
2876
+
2877
+ /**
2878
+ * Removes emojis from a string and fix whitespaces
2879
+ *
2880
+ * @param text with emojis
2881
+ * @returns text without emojis
2882
+ */
2883
+ function removeEmojis(text) {
2884
+ // Replace emojis (and also ZWJ sequence) with hyphens
2885
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
2886
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
2887
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
2888
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
2889
+ return text;
2890
+ }
2891
+
2892
+ /**
2893
+ * Function normalizes title to name which can be used as identifier
2894
+ */
2895
+ function titleToName(value) {
2896
+ value = removeEmojis(value);
2897
+ value = normalizeToKebabCase(value);
2898
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
2899
+ return value;
2900
+ }
2901
+
2902
+ /**
2903
+ * Compile promptbook from string (markdown) format to JSON format
2904
+ *
2905
+ * @param promptbookString {Promptbook} in string markdown format (.ptbk.md)
2906
+ * @param options - Options and tools for the compilation
2907
+ * @returns {Promptbook} compiled in JSON format (.ptbk.json)
2908
+ * @throws {PromptbookSyntaxError} if the promptbook string is not valid
2909
+ *
2910
+ * Note: This function does not validate logic of the pipeline only the syntax
2911
+ * Note: This function acts as compilation process
2912
+ */
2913
+ function promptbookStringToJson(promptbookString, options) {
2914
+ if (options === void 0) { options = {}; }
2915
+ return __awaiter(this, void 0, void 0, function () {
2916
+ var llmTools, promptbookJson, knowledge, addParam, markdownStructure, markdownStructureDeepness, description, defaultModelRequirements, listItems, listItems_1, listItems_1_1, listItem, command, _loop_1, _a, _b, section;
2917
+ var e_1, _c, e_2, _d;
2918
+ return __generator(this, function (_e) {
2919
+ switch (_e.label) {
2920
+ case 0:
2921
+ llmTools = options.llmTools;
2922
+ promptbookJson = {
2923
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2924
+ title: undefined /* <- Note: Putting here placeholder to keep `title` on top at final JSON */,
2925
+ promptbookUrl: undefined /* <- Note: Putting here placeholder to keep `promptbookUrl` on top at final JSON */,
2926
+ promptbookVersion: PROMPTBOOK_VERSION,
2927
+ description: undefined /* <- Note: Putting here placeholder to keep `description` on top at final JSON */,
2928
+ parameters: [],
2929
+ promptTemplates: [],
2930
+ knowledge: [],
2931
+ };
2932
+ if (!llmTools) return [3 /*break*/, 2];
2933
+ return [4 /*yield*/, prepareKnowledgeFromMarkdown({
2934
+ content: 'Roses are red, violets are blue, programmers use Promptbook, users too',
2935
+ llmTools: llmTools,
2936
+ })];
2937
+ case 1:
2938
+ knowledge = _e.sent();
2939
+ console.info('!!!! knowledge', knowledge);
2940
+ _e.label = 2;
2941
+ case 2:
2942
+ // =============================================================
2943
+ // Note: 1️⃣ Normalization of the PROMPTBOOK string
2944
+ promptbookString = removeContentComments(promptbookString);
2945
+ promptbookString = promptbookString.replaceAll(/`\{(?<parameterName>[a-z0-9_]+)\}`/gi, '{$<parameterName>}');
2946
+ promptbookString = promptbookString.replaceAll(/`->\s+\{(?<parameterName>[a-z0-9_]+)\}`/gi, '-> {$<parameterName>}');
2947
+ addParam = function (parameterCommand) {
2948
+ var parameterName = parameterCommand.parameterName, parameterDescription = parameterCommand.parameterDescription, isInput = parameterCommand.isInput, isOutput = parameterCommand.isOutput;
2949
+ var existingParameter = promptbookJson.parameters.find(function (parameter) { return parameter.name === parameterName; });
2950
+ if (existingParameter &&
2951
+ existingParameter.description &&
2952
+ existingParameter.description !== parameterDescription &&
2953
+ parameterDescription) {
2954
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Parameter {".concat(parameterName, "} is defined multiple times with different description.\n\n First definition:\n ").concat(block(existingParameter.description || '[undefined]'), "\n\n Second definition:\n ").concat(block(parameterDescription || '[undefined]'), "\n "); }));
2955
+ }
2956
+ if (existingParameter) {
2957
+ if (parameterDescription) {
2958
+ existingParameter.description = parameterDescription;
2959
+ }
2960
+ }
2961
+ else {
2962
+ promptbookJson.parameters.push({
2963
+ name: parameterName,
2964
+ description: parameterDescription || undefined,
2965
+ isInput: isInput,
2966
+ isOutput: isOutput,
2967
+ });
2968
+ }
2969
+ };
2970
+ markdownStructure = markdownToMarkdownStructure(promptbookString);
2971
+ markdownStructureDeepness = countMarkdownStructureDeepness(markdownStructure);
2972
+ if (markdownStructureDeepness !== 2) {
2973
+ throw new PromptbookSyntaxError(spaceTrim("\n Invalid markdown structure.\n The markdown must have exactly 2 levels of headings (one top-level section and one section for each template).\n Now it has ".concat(markdownStructureDeepness, " levels of headings.\n ")));
2974
+ }
2975
+ promptbookJson.title = markdownStructure.title;
2976
+ description = markdownStructure.content;
2977
+ // Note: Remove codeblocks
2978
+ description = description.split(/^```.*^```/gms).join('');
2979
+ //Note: Remove lists and return statement
2980
+ description = description.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
2981
+ description = spaceTrim(description);
2982
+ if (description === '') {
2983
+ description = undefined;
2984
+ }
2985
+ promptbookJson.description = description;
2986
+ defaultModelRequirements = {};
2987
+ listItems = extractAllListItemsFromMarkdown(markdownStructure.content);
2988
+ try {
2989
+ for (listItems_1 = __values(listItems), listItems_1_1 = listItems_1.next(); !listItems_1_1.done; listItems_1_1 = listItems_1.next()) {
2990
+ listItem = listItems_1_1.value;
2991
+ command = parseCommand(listItem);
2992
+ switch (command.type) {
2993
+ case 'PROMPTBOOK_URL':
2994
+ promptbookJson.promptbookUrl = command.promptbookUrl.href;
2995
+ break;
2996
+ case 'PROMPTBOOK_VERSION':
2997
+ promptbookJson.promptbookVersion = command.promptbookVersion;
2998
+ break;
2999
+ case 'MODEL':
3000
+ defaultModelRequirements[command.key] = command.value;
3001
+ break;
3002
+ case 'PARAMETER':
3003
+ addParam(command);
3004
+ break;
3005
+ default:
3006
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the head of the promptbook ONLY at the prompt template block"));
3007
+ }
3008
+ }
3009
+ }
3010
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
3011
+ finally {
3012
+ try {
3013
+ if (listItems_1_1 && !listItems_1_1.done && (_c = listItems_1.return)) _c.call(listItems_1);
3014
+ }
3015
+ finally { if (e_1) throw e_1.error; }
3016
+ }
3017
+ _loop_1 = function (section) {
3018
+ var e_3, _f;
3019
+ // TODO: Parse prompt template description (the content out of the codeblock and lists)
3020
+ var templateModelRequirements = __assign({}, defaultModelRequirements);
3021
+ var listItems_3 = extractAllListItemsFromMarkdown(section.content);
3022
+ var dependentParameterNames = new Set();
3023
+ var executionType = 'PROMPT_TEMPLATE';
3024
+ var jokers = [];
3025
+ var postprocessing = [];
3026
+ var expectAmount = {};
3027
+ var expectFormat = undefined;
3028
+ var isExecutionTypeChanged = false;
3029
+ try {
3030
+ for (var listItems_2 = (e_3 = void 0, __values(listItems_3)), listItems_2_1 = listItems_2.next(); !listItems_2_1.done; listItems_2_1 = listItems_2.next()) {
3031
+ var listItem = listItems_2_1.value;
3032
+ var command = parseCommand(listItem);
3033
+ switch (command.type) {
3034
+ case 'JOKER':
3035
+ jokers.push(command.parameterName);
3036
+ dependentParameterNames.add(command.parameterName);
3037
+ break;
3038
+ case 'EXECUTE':
3039
+ if (isExecutionTypeChanged) {
3040
+ throw new PromptbookSyntaxError('Execution type is already defined in the prompt template. It can be defined only once.');
3041
+ }
3042
+ executionType = command.executionType;
3043
+ isExecutionTypeChanged = true;
3044
+ break;
3045
+ case 'MODEL':
3046
+ templateModelRequirements[command.key] = command.value;
3047
+ break;
3048
+ case 'PARAMETER':
3049
+ // Note: This is just for detecting resulitng parameter name
3050
+ addParam(command);
3051
+ break;
3052
+ case 'POSTPROCESS':
3053
+ postprocessing.push(command.functionName);
3054
+ break;
3055
+ case 'EXPECT_AMOUNT':
3056
+ // eslint-disable-next-line no-case-declarations
3057
+ var unit = command.unit.toLowerCase();
3058
+ expectAmount[unit] = expectAmount[unit] || {};
3059
+ if (command.sign === 'MINIMUM' || command.sign === 'EXACTLY') {
3060
+ if (expectAmount[unit].min !== undefined) {
3061
+ throw new PromptbookSyntaxError("Already defined minumum ".concat(expectAmount[unit].min, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
3062
+ }
3063
+ expectAmount[unit].min = command.amount;
3064
+ } /* not else */
3065
+ if (command.sign === 'MAXIMUM' || command.sign === 'EXACTLY') {
3066
+ if (expectAmount[unit].max !== undefined) {
3067
+ throw new PromptbookSyntaxError("Already defined maximum ".concat(expectAmount[unit].max, " ").concat(command.unit.toLowerCase(), ", now trying to redefine it to ").concat(command.amount));
3068
+ }
3069
+ expectAmount[unit].max = command.amount;
3070
+ }
3071
+ break;
3072
+ case 'EXPECT_FORMAT':
3073
+ if (expectFormat !== undefined && command.format !== expectFormat) {
3074
+ throw new PromptbookSyntaxError("Expect format is already defined to \"".concat(expectFormat, "\". Now you try to redefine it by \"").concat(command.format, "\"."));
3075
+ }
3076
+ expectFormat = command.format;
3077
+ break;
3078
+ default:
3079
+ throw new PromptbookSyntaxError("Command ".concat(command.type, " is not allowed in the block of the prompt template ONLY at the head of the promptbook"));
3080
+ }
3081
+ }
3082
+ }
3083
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
3084
+ finally {
3085
+ try {
3086
+ if (listItems_2_1 && !listItems_2_1.done && (_f = listItems_2.return)) _f.call(listItems_2);
3087
+ }
3088
+ finally { if (e_3) throw e_3.error; }
3089
+ }
3090
+ var _g = extractOneBlockFromMarkdown(section.content), language = _g.language, content = _g.content;
3091
+ if (executionType === 'SCRIPT') {
3092
+ if (!language) {
3093
+ throw new PromptbookSyntaxError('You must specify the language of the script in the prompt template');
3094
+ }
3095
+ else if (!SUPPORTED_SCRIPT_LANGUAGES.includes(language)) {
3096
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Script language ".concat(language, " is not supported.\n\n Supported languages are:\n ").concat(block(SUPPORTED_SCRIPT_LANGUAGES.join(', ')), "\n\n "); }));
3097
+ }
3098
+ }
3099
+ var lastLine = section.content.split('\n').pop();
3100
+ var match = /^->\s*\{(?<resultingParamName>[a-z0-9_]+)\}/im.exec(lastLine);
3101
+ if (!match || match.groups === undefined || match.groups.resultingParamName === undefined) {
3102
+ throw new PromptbookSyntaxError(spaceTrim(function (block) { return "\n Invalid template - each section must end with \"-> {...}\"\n\n Invalid section:\n ".concat(block(
3103
+ // TODO: Show code of invalid sections each time + DRY
3104
+ section.content
3105
+ .split('\n')
3106
+ .map(function (line) { return "> ".concat(line); })
3107
+ .join('\n')), "\n "); }));
3108
+ }
3109
+ var resultingParameterName = match.groups.resultingParamName;
3110
+ // TODO: [1] DRY description
3111
+ var description_1 = section.content;
3112
+ // Note: Remove codeblocks
3113
+ description_1 = description_1.split(/^```.*^```/gms).join('');
3114
+ //Note: Remove lists and return statement
3115
+ description_1 = description_1.split(/^(?:(?:-)|(?:\d\))|(?:`?->))\s+.*$/gm).join('');
3116
+ description_1 = spaceTrim(description_1);
3117
+ if (description_1 === '') {
3118
+ description_1 = undefined;
3119
+ }
3120
+ if (Object.keys(jokers).length === 0) {
3121
+ jokers = undefined;
3122
+ }
3123
+ if (Object.keys(expectAmount).length === 0) {
3124
+ expectAmount = undefined;
3125
+ }
3126
+ if (Object.keys(postprocessing).length === 0) {
3127
+ postprocessing = undefined;
3128
+ }
3129
+ dependentParameterNames = union(dependentParameterNames, extractParametersFromPromptTemplate(__assign(__assign({}, section), { description: description_1, executionType: executionType, content: content })));
3130
+ if (templateModelRequirements.modelVariant === undefined) {
3131
+ templateModelRequirements.modelVariant = 'CHAT';
3132
+ }
3133
+ promptbookJson.promptTemplates.push({
3134
+ name: titleToName(section.title),
3135
+ title: section.title,
3136
+ description: description_1,
3137
+ dependentParameterNames: Array.from(dependentParameterNames),
3138
+ executionType: executionType,
3139
+ jokers: jokers,
3140
+ postprocessing: postprocessing,
3141
+ expectations: expectAmount,
3142
+ expectFormat: expectFormat,
3143
+ modelRequirements: templateModelRequirements,
3144
+ contentLanguage: executionType === 'SCRIPT' ? language : undefined,
3145
+ content: content,
3146
+ resultingParameterName: resultingParameterName,
3147
+ });
3148
+ };
3149
+ try {
3150
+ for (_a = __values(markdownStructure.sections), _b = _a.next(); !_b.done; _b = _a.next()) {
3151
+ section = _b.value;
3152
+ _loop_1(section);
2028
3153
  }
2029
3154
  }
2030
- }
2031
- catch (e_6_1) { e_6 = { error: e_6_1 }; }
2032
- finally {
2033
- try {
2034
- if (_m && !_m.done && (_f = _l.return)) _f.call(_l);
3155
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
3156
+ finally {
3157
+ try {
3158
+ if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
3159
+ }
3160
+ finally { if (e_2) throw e_2.error; }
2035
3161
  }
2036
- finally { if (e_6) throw e_6.error; }
2037
- }
2038
- } /* not else */
2039
- if (expectFormat) {
2040
- if (expectFormat === 'JSON') {
2041
- // TODO: @deprecated remove
2042
- commands_1.push("EXPECT JSON");
2043
- }
2044
- } /* not else */
2045
- promptbookString += '\n\n';
2046
- promptbookString += commands_1.map(function (command) { return "- ".concat(command); }).join('\n');
2047
- promptbookString += '\n\n';
2048
- promptbookString += '```' + contentLanguage;
2049
- promptbookString += '\n';
2050
- promptbookString += spaceTrim$1(content);
2051
- // <- TODO: !!! Escape
2052
- // <- TODO: [🧠] Some clear strategy how to spaceTrim the blocks
2053
- promptbookString += '\n';
2054
- promptbookString += '```';
2055
- promptbookString += '\n\n';
2056
- promptbookString += "`-> {".concat(resultingParameterName, "}`"); // <- TODO: !!! If the parameter here has description, add it and use promptTemplateParameterJsonToString
2057
- }
2058
- }
2059
- catch (e_3_1) { e_3 = { error: e_3_1 }; }
2060
- finally {
2061
- try {
2062
- if (promptTemplates_1_1 && !promptTemplates_1_1.done && (_c = promptTemplates_1.return)) _c.call(promptTemplates_1);
2063
- }
2064
- finally { if (e_3) throw e_3.error; }
2065
- }
2066
- return promptbookString;
2067
- }
2068
- /**
2069
- * @private internal util of promptbookJsonToString
2070
- */
2071
- function promptTemplateParameterJsonToString(promptTemplateParameterJson) {
2072
- var name = promptTemplateParameterJson.name, description = promptTemplateParameterJson.description;
2073
- var parameterString = "{".concat(name, "}");
2074
- if (description) {
2075
- parameterString = "".concat(parameterString, " ").concat(description);
2076
- }
2077
- return parameterString;
3162
+ // =============================================================
3163
+ return [2 /*return*/, promptbookJson];
3164
+ }
3165
+ });
3166
+ });
2078
3167
  }
2079
3168
  /**
2080
- * TODO: Escape all
2081
- */
2082
-
2083
- /**
2084
- * This error indicates that promptbook not found in the library
3169
+ * TODO: Report here line/column of error
3170
+ * TODO: Use spaceTrim more effectively
3171
+ * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
2085
3172
  */
2086
- var PromptbookNotFoundError = /** @class */ (function (_super) {
2087
- __extends(PromptbookNotFoundError, _super);
2088
- function PromptbookNotFoundError(message) {
2089
- var _this = _super.call(this, message) || this;
2090
- _this.name = 'PromptbookNotFoundError';
2091
- Object.setPrototypeOf(_this, PromptbookNotFoundError.prototype);
2092
- return _this;
2093
- }
2094
- return PromptbookNotFoundError;
2095
- }(Error));
2096
3173
 
2097
3174
  /**
2098
- * This error indicates errors in referencing promptbooks between each other
3175
+ * This error indicates that the promptbook library cannot be propperly loaded
2099
3176
  */
2100
- var PromptbookReferenceError = /** @class */ (function (_super) {
2101
- __extends(PromptbookReferenceError, _super);
2102
- function PromptbookReferenceError(message) {
3177
+ var PromptbookLibraryError = /** @class */ (function (_super) {
3178
+ __extends(PromptbookLibraryError, _super);
3179
+ function PromptbookLibraryError(message) {
2103
3180
  var _this = _super.call(this, message) || this;
2104
- _this.name = 'PromptbookReferenceError';
2105
- Object.setPrototypeOf(_this, PromptbookReferenceError.prototype);
3181
+ _this.name = 'PromptbookLibraryError';
3182
+ Object.setPrototypeOf(_this, PromptbookLibraryError.prototype);
2106
3183
  return _this;
2107
3184
  }
2108
- return PromptbookReferenceError;
3185
+ return PromptbookLibraryError;
2109
3186
  }(Error));
2110
3187
 
2111
3188
  /**
2112
- * Library of promptbooks that groups together promptbooks for an application.
2113
- * This implementation is a very thin wrapper around the Array / Map of promptbooks.
2114
- *
2115
- * @see https://github.com/webgptorg/promptbook#promptbook-library
3189
+ * Detects if the code is running in a browser environment in main thread (Not in a web worker)
2116
3190
  */
2117
- var SimplePromptbookLibrary = /** @class */ (function () {
2118
- /**
2119
- * Constructs a promptbook library from promptbooks
2120
- *
2121
- * @param promptbooks !!!
2122
- *
2123
- * Note: During the construction logic of all promptbooks are validated
2124
- * Note: It is not recommended to use this constructor directly, use `createPromptbookLibraryFromSources` *(or other variant)* instead
2125
- */
2126
- function SimplePromptbookLibrary() {
2127
- var e_1, _a;
2128
- var promptbooks = [];
2129
- for (var _i = 0; _i < arguments.length; _i++) {
2130
- promptbooks[_i] = arguments[_i];
2131
- }
2132
- this.library = new Map();
2133
- try {
2134
- for (var promptbooks_1 = __values(promptbooks), promptbooks_1_1 = promptbooks_1.next(); !promptbooks_1_1.done; promptbooks_1_1 = promptbooks_1.next()) {
2135
- var promptbook = promptbooks_1_1.value;
2136
- if (promptbook.promptbookUrl === undefined) {
2137
- throw new PromptbookReferenceError(spaceTrim("\n Promptbook with name \"".concat(promptbook.title, "\" does not have defined URL\n\n Note: Promptbooks without URLs are called anonymous promptbooks\n They can be used as standalone promptbooks, but they cannot be referenced by other promptbooks\n And also they cannot be used in the promptbook library\n\n ")));
2138
- }
2139
- validatePromptbookJson(promptbook);
2140
- // Note: [🦄]
2141
- if (this.library.has(promptbook.promptbookUrl) &&
2142
- promptbookJsonToString(promptbook) !==
2143
- promptbookJsonToString(this.library.get(promptbook.promptbookUrl))) {
2144
- throw new PromptbookReferenceError(spaceTrim("\n Promptbook with URL \"".concat(promptbook.promptbookUrl, "\" is already in the library\n\n Note: Promptbooks with the same URL are not allowed\n Note: Automatically check whether the promptbooks are the same BUT they are DIFFERENT\n\n ")));
2145
- }
2146
- this.library.set(promptbook.promptbookUrl, promptbook);
2147
- }
2148
- }
2149
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
2150
- finally {
2151
- try {
2152
- if (promptbooks_1_1 && !promptbooks_1_1.done && (_a = promptbooks_1.return)) _a.call(promptbooks_1);
2153
- }
2154
- finally { if (e_1) throw e_1.error; }
2155
- }
2156
- }
2157
- /**
2158
- * Gets all promptbooks in the library
2159
- */
2160
- SimplePromptbookLibrary.prototype.listPromptbooks = function () {
2161
- return Array.from(this.library.keys());
2162
- };
2163
- /**
2164
- * Gets promptbook by its URL
2165
- *
2166
- * Note: This is not a direct fetching from the URL, but a lookup in the library
2167
- */
2168
- SimplePromptbookLibrary.prototype.getPromptbookByUrl = function (url) {
2169
- var _this = this;
2170
- var promptbook = this.library.get(url);
2171
- if (!promptbook) {
2172
- if (this.listPromptbooks().length === 0) {
2173
- throw new PromptbookNotFoundError(spaceTrim("\n Promptbook with url \"".concat(url, "\" not found\n\n No promptbooks available\n ")));
2174
- }
2175
- throw new PromptbookNotFoundError(spaceTrim(function (block) { return "\n Promptbook with url \"".concat(url, "\" not found\n\n Available promptbooks:\n ").concat(block(_this.listPromptbooks()
2176
- .map(function (promptbookUrl) { return "- ".concat(promptbookUrl); })
2177
- .join('\n')), "\n\n "); }));
2178
- }
2179
- return promptbook;
2180
- };
2181
- /**
2182
- * Checks whether given prompt was defined in any promptbook in the library
2183
- */
2184
- SimplePromptbookLibrary.prototype.isResponsibleForPrompt = function (prompt) {
2185
- return true;
2186
- };
2187
- return SimplePromptbookLibrary;
2188
- }());
2189
-
3191
+ new Function("\n try {\n return this === window;\n } catch (e) {\n return false;\n }\n");
2190
3192
  /**
2191
- * Creates PromptbookLibrary from array of PromptbookJson or PromptbookString
2192
- *
2193
- * Note: You can combine `PromptbookString` (`.ptbk.md`) with `PromptbookJson` BUT it is not recommended
2194
- * Note: During the construction syntax and logic of all sources are validated
2195
- *
2196
- * @param promptbookSources
2197
- * @returns PromptbookLibrary
3193
+ * Detects if the code is running in a Node.js environment
2198
3194
  */
2199
- function createPromptbookLibraryFromSources() {
2200
- var promptbookSources = [];
2201
- for (var _i = 0; _i < arguments.length; _i++) {
2202
- promptbookSources[_i] = arguments[_i];
2203
- }
2204
- return __awaiter(this, void 0, void 0, function () {
2205
- var promptbooks, promptbookSources_1, promptbookSources_1_1, source, promptbook, e_1_1;
2206
- var e_1, _a;
2207
- return __generator(this, function (_b) {
2208
- switch (_b.label) {
2209
- case 0:
2210
- promptbooks = new Array();
2211
- _b.label = 1;
2212
- case 1:
2213
- _b.trys.push([1, 8, 9, 10]);
2214
- promptbookSources_1 = __values(promptbookSources), promptbookSources_1_1 = promptbookSources_1.next();
2215
- _b.label = 2;
2216
- case 2:
2217
- if (!!promptbookSources_1_1.done) return [3 /*break*/, 7];
2218
- source = promptbookSources_1_1.value;
2219
- promptbook = void 0;
2220
- if (!(typeof source === 'string')) return [3 /*break*/, 4];
2221
- return [4 /*yield*/, promptbookStringToJson(source)];
2222
- case 3:
2223
- // Note: When directly creating from string, no need to validate the source
2224
- // The validation is performed always before execution
2225
- promptbook = _b.sent();
2226
- return [3 /*break*/, 5];
2227
- case 4:
2228
- promptbook = source;
2229
- _b.label = 5;
2230
- case 5:
2231
- promptbooks.push(promptbook);
2232
- _b.label = 6;
2233
- case 6:
2234
- promptbookSources_1_1 = promptbookSources_1.next();
2235
- return [3 /*break*/, 2];
2236
- case 7: return [3 /*break*/, 10];
2237
- case 8:
2238
- e_1_1 = _b.sent();
2239
- e_1 = { error: e_1_1 };
2240
- return [3 /*break*/, 10];
2241
- case 9:
2242
- try {
2243
- if (promptbookSources_1_1 && !promptbookSources_1_1.done && (_a = promptbookSources_1.return)) _a.call(promptbookSources_1);
2244
- }
2245
- finally { if (e_1) throw e_1.error; }
2246
- return [7 /*endfinally*/];
2247
- case 10: return [2 /*return*/, new (SimplePromptbookLibrary.bind.apply(SimplePromptbookLibrary, __spreadArray([void 0], __read(promptbooks), false)))()];
2248
- }
2249
- });
2250
- });
2251
- }
3195
+ var isRunningInNode = new Function("\n try {\n return this === global;\n } catch (e) {\n return false;\n }\n");
2252
3196
  /**
2253
- * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
3197
+ * Detects if the code is running in a web worker
2254
3198
  */
3199
+ new Function("\n try {\n if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {\n return true;\n } else {\n return false;\n }\n } catch (e) {\n return false;\n }\n");
2255
3200
 
2256
3201
  /**
2257
3202
  * Constructs Promptbook from async sources