@promptbook/node 0.84.0-10 → 0.84.0-12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/umd/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('papaparse'), require('crypto-js'), require('crypto-js/enc-hex'), require('mime-types'), require('child_process'), require('dotenv'), require('crypto-js/sha256')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'papaparse', 'crypto-js', 'crypto-js/enc-hex', 'mime-types', 'child_process', 'dotenv', 'crypto-js/sha256'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.papaparse, global.cryptoJs, global.hexEncoder, global.mimeTypes, global.child_process, global.dotenv, global.sha256));
5
- })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, waitasecond, papaparse, cryptoJs, hexEncoder, mimeTypes, child_process, dotenv, sha256) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('colors'), require('fs/promises'), require('path'), require('spacetrim'), require('prettier'), require('prettier/parser-html'), require('waitasecond'), require('papaparse'), require('crypto-js/enc-hex'), require('crypto-js/sha256'), require('crypto-js'), require('mime-types'), require('child_process'), require('dotenv')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'colors', 'fs/promises', 'path', 'spacetrim', 'prettier', 'prettier/parser-html', 'waitasecond', 'papaparse', 'crypto-js/enc-hex', 'crypto-js/sha256', 'crypto-js', 'mime-types', 'child_process', 'dotenv'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-node"] = {}, global.colors, global.promises, global.path, global.spaceTrim, global.prettier, global.parserHtml, global.waitasecond, global.papaparse, global.hexEncoder, global.sha256, global.cryptoJs, global.mimeTypes, global.child_process, global.dotenv));
5
+ })(this, (function (exports, colors, promises, path, spaceTrim, prettier, parserHtml, waitasecond, papaparse, hexEncoder, sha256, cryptoJs, mimeTypes, child_process, dotenv) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
@@ -28,8 +28,8 @@
28
28
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
29
29
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
30
30
  var hexEncoder__default = /*#__PURE__*/_interopDefaultLegacy(hexEncoder);
31
- var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
32
31
  var sha256__default = /*#__PURE__*/_interopDefaultLegacy(sha256);
32
+ var dotenv__namespace = /*#__PURE__*/_interopNamespace(dotenv);
33
33
 
34
34
  // ⚠️ WARNING: This code has been generated so that any manual changes will be overwritten
35
35
  /**
@@ -45,7 +45,7 @@
45
45
  * @generated
46
46
  * @see https://github.com/webgptorg/promptbook
47
47
  */
48
- var PROMPTBOOK_ENGINE_VERSION = '0.84.0-9';
48
+ var PROMPTBOOK_ENGINE_VERSION = '0.84.0-11';
49
49
  /**
50
50
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
51
51
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -280,6 +280,15 @@
280
280
  * @public exported from `@promptbook/core`
281
281
  */
282
282
  var DEFAULT_MAX_EXECUTION_ATTEMPTS = 3; // <- TODO: [🤹‍♂️]
283
+ // <- TODO: [🕝] Make also `BOOKS_DIRNAME_ALTERNATIVES`
284
+ /**
285
+ * Where to store the temporary downloads
286
+ *
287
+ * Note: When the folder does not exist, it is created recursively
288
+ *
289
+ * @public exported from `@promptbook/core`
290
+ */
291
+ var DEFAULT_DOWNLOAD_CACHE_DIRNAME = './.promptbook/download-cache';
283
292
  /**
284
293
  * Where to store the scrape cache
285
294
  *
@@ -335,22 +344,94 @@
335
344
  var PipelineCollection = [{title:"Prepare Knowledge from Markdown",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.book.md",formfactorName:"GENERIC",parameters:[{name:"knowledgeContent",description:"Markdown document content",isInput:true,isOutput:false},{name:"knowledgePieces",description:"The knowledge JSON object",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",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> {knowledgeContent}",resultingParameterName:"knowledgePieces",dependentParameterNames:["knowledgeContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Knowledge from Markdown\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.book.md`\n- INPUT PARAMETER `{knowledgeContent}` Markdown document content\n- OUTPUT PARAMETER `{knowledgePieces}` The knowledge JSON object\n\n## Knowledge\n\n<!-- TODO: [🍆] -FORMAT JSON -->\n\n```markdown\nYou 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> {knowledgeContent}\n```\n\n`-> {knowledgePieces}`\n"}],sourceFile:"./books/prepare-knowledge-from-markdown.book.md"},{title:"Prepare Keywords",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-keywords.book.md",formfactorName:"GENERIC",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"keywords",description:"Keywords separated by comma",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}",resultingParameterName:"keywords",dependentParameterNames:["knowledgePieceContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Keywords\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-keywords.book.md`\n- INPUT PARAMETER `{knowledgePieceContent}` The content\n- OUTPUT PARAMETER `{keywords}` Keywords separated by comma\n\n## Knowledge\n\n<!-- TODO: [🍆] -FORMAT JSON -->\n\n```markdown\nYou are experienced data researcher, detect the important keywords in the document.\n\n# Rules\n\n- Write just keywords separated by comma\n\n# The document\n\nTake information from this document:\n\n> {knowledgePieceContent}\n```\n\n`-> {keywords}`\n"}],sourceFile:"./books/prepare-knowledge-keywords.book.md"},{title:"Prepare Knowledge-piece Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-knowledge-title.book.md",formfactorName:"GENERIC",parameters:[{name:"knowledgePieceContent",description:"The content",isInput:true,isOutput:false},{name:"title",description:"The title of the document",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"knowledge",title:"Knowledge",content:"You are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}",resultingParameterName:"title",expectations:{words:{min:1,max:8}},dependentParameterNames:["knowledgePieceContent"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Knowledge-piece Title\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-knowledge-title.book.md`\n- INPUT PARAMETER `{knowledgePieceContent}` The content\n- OUTPUT PARAMETER `{title}` The title of the document\n\n## Knowledge\n\n- EXPECT MIN 1 WORD\n- EXPECT MAX 8 WORDS\n\n```markdown\nYou are experienced content creator, write best title for the document.\n\n# Rules\n\n- Write just title, nothing else\n- Write maximum 5 words for the title\n\n# The document\n\n> {knowledgePieceContent}\n```\n\n`-> {title}`\n"}],sourceFile:"./books/prepare-knowledge-title.book.md"},{title:"Prepare Persona",pipelineUrl:"https://promptbook.studio/promptbook/prepare-persona.book.md",formfactorName:"GENERIC",parameters:[{name:"availableModelNames",description:"List of available model names separated by comma (,)",isInput:true,isOutput:false},{name:"personaDescription",description:"Description of the persona",isInput:true,isOutput:false},{name:"modelRequirements",description:"Specific requirements for the model",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"make-model-requirements",title:"Make modelRequirements",content:"You are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Example\n\n```json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n```\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}",resultingParameterName:"modelRequirements",format:"JSON",dependentParameterNames:["availableModelNames","personaDescription"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Persona\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-persona.book.md`\n- INPUT PARAMETER `{availableModelNames}` List of available model names separated by comma (,)\n- INPUT PARAMETER `{personaDescription}` Description of the persona\n- OUTPUT PARAMETER `{modelRequirements}` Specific requirements for the model\n\n## Make modelRequirements\n\n- FORMAT JSON\n\n```markdown\nYou are experienced AI engineer, you need to create virtual assistant.\nWrite\n\n## Example\n\n\\`\\`\\`json\n{\n\"modelName\": \"gpt-4o\",\n\"systemMessage\": \"You are experienced AI engineer and helpfull assistant.\",\n\"temperature\": 0.7\n}\n\\`\\`\\`\n\n## Instructions\n\n- Your output format is JSON object\n- Write just the JSON object, no other text should be present\n- It contains the following keys:\n - `modelName`: The name of the model to use\n - `systemMessage`: The system message to provide context to the model\n - `temperature`: The sampling temperature to use\n\n### Key `modelName`\n\nPick from the following models:\n\n- {availableModelNames}\n\n### Key `systemMessage`\n\nThe system message is used to communicate instructions or provide context to the model at the beginning of a conversation. It is displayed in a different format compared to user messages, helping the model understand its role in the conversation. The system message typically guides the model's behavior, sets the tone, or specifies desired output from the model. By utilizing the system message effectively, users can steer the model towards generating more accurate and relevant responses.\n\nFor example:\n\n> You are an experienced AI engineer and helpful assistant.\n\n> You are a friendly and knowledgeable chatbot.\n\n### Key `temperature`\n\nThe sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use log probability to automatically increase the temperature until certain thresholds are hit.\n\nYou can pick a value between 0 and 2. For example:\n\n- `0.1`: Low temperature, extremely conservative and deterministic\n- `0.5`: Medium temperature, balanced between conservative and creative\n- `1.0`: High temperature, creative and bit random\n- `1.5`: Very high temperature, extremely creative and often chaotic and unpredictable\n- `2.0`: Maximum temperature, completely random and unpredictable, for some extreme creative use cases\n\n# The assistant\n\nTake this description of the persona:\n\n> {personaDescription}\n```\n\n`-> {modelRequirements}`\n"}],sourceFile:"./books/prepare-persona.book.md"},{title:"Prepare Title",pipelineUrl:"https://promptbook.studio/promptbook/prepare-title.book.md",formfactorName:"GENERIC",parameters:[{name:"book",description:"The book to prepare the title for",isInput:true,isOutput:false},{name:"title",description:"Best title for the book",isInput:false,isOutput:true}],tasks:[{taskType:"PROMPT_TASK",name:"make-title",title:"Make title",content:"Make best title for given text which describes the workflow:\n\n## Rules\n\n- Write just title, nothing else\n- Title should be concise and clear - Write maximum ideally 2 words, maximum 5 words\n- Title starts with emoticon\n- Title should not mention the input and output of the workflow but the main purpose of the workflow\n _For example, not \"✍ Convert Knowledge-piece to title\" but \"✍ Title\"_\n\n## The workflow\n\n> {book}",resultingParameterName:"title",expectations:{words:{min:1,max:8},lines:{min:1,max:1}},dependentParameterNames:["book"]}],personas:[],preparations:[],knowledgeSources:[],knowledgePieces:[],sources:[{type:"BOOK",path:null,content:"# Prepare Title\n\n- PIPELINE URL `https://promptbook.studio/promptbook/prepare-title.book.md`\n- INPUT PARAMETER `{book}` The book to prepare the title for\n- OUTPUT PARAMETER `{title}` Best title for the book\n\n## Make title\n\n- EXPECT MIN 1 Word\n- EXPECT MAX 8 Words\n- EXPECT EXACTLY 1 Line\n\n```markdown\nMake best title for given text which describes the workflow:\n\n## Rules\n\n- Write just title, nothing else\n- Title should be concise and clear - Write maximum ideally 2 words, maximum 5 words\n- Title starts with emoticon\n- Title should not mention the input and output of the workflow but the main purpose of the workflow\n _For example, not \"✍ Convert Knowledge-piece to title\" but \"✍ Title\"_\n\n## The workflow\n\n> {book}\n```\n\n`-> {title}`\n"}],sourceFile:"./books/prepare-title.book.md"}];
336
345
 
337
346
  /**
338
- * Function isValidJsonString will tell you if the string is valid JSON or not
347
+ * Checks if value is valid email
339
348
  *
340
349
  * @public exported from `@promptbook/utils`
341
350
  */
342
- function isValidJsonString(value /* <- [👨‍⚖️] */) {
343
- try {
344
- JSON.parse(value);
351
+ function isValidEmail(email) {
352
+ if (typeof email !== 'string') {
353
+ return false;
354
+ }
355
+ if (email.split('\n').length > 1) {
356
+ return false;
357
+ }
358
+ return /^.+@.+\..+$/.test(email);
359
+ }
360
+
361
+ /**
362
+ * Tests if given string is valid URL.
363
+ *
364
+ * Note: This does not check if the file exists only if the path is valid
365
+ * @public exported from `@promptbook/utils`
366
+ */
367
+ function isValidFilePath(filename) {
368
+ if (typeof filename !== 'string') {
369
+ return false;
370
+ }
371
+ if (filename.split('\n').length > 1) {
372
+ return false;
373
+ }
374
+ if (filename.split(' ').length >
375
+ 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
376
+ return false;
377
+ }
378
+ var filenameSlashes = filename.split('\\').join('/');
379
+ // Absolute Unix path: /hello.txt
380
+ if (/^(\/)/i.test(filenameSlashes)) {
381
+ // console.log(filename, 'Absolute Unix path: /hello.txt');
345
382
  return true;
346
383
  }
347
- catch (error) {
348
- if (!(error instanceof Error)) {
349
- throw error;
384
+ // Absolute Windows path: /hello.txt
385
+ if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
386
+ // console.log(filename, 'Absolute Windows path: /hello.txt');
387
+ return true;
388
+ }
389
+ // Relative path: ./hello.txt
390
+ if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
391
+ // console.log(filename, 'Relative path: ./hello.txt');
392
+ return true;
393
+ }
394
+ // Allow paths like foo/hello
395
+ if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
396
+ // console.log(filename, 'Allow paths like foo/hello');
397
+ return true;
398
+ }
399
+ // Allow paths like hello.book
400
+ if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
401
+ // console.log(filename, 'Allow paths like hello.book');
402
+ return true;
403
+ }
404
+ return false;
405
+ }
406
+ /**
407
+ * TODO: [🍏] Implement for MacOs
408
+ */
409
+
410
+ /**
411
+ * Tests if given string is valid URL.
412
+ *
413
+ * Note: Dataurl are considered perfectly valid.
414
+ * Note: There are two simmilar functions:
415
+ * - `isValidUrl` which tests any URL
416
+ * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
417
+ *
418
+ * @public exported from `@promptbook/utils`
419
+ */
420
+ function isValidUrl(url) {
421
+ if (typeof url !== 'string') {
422
+ return false;
423
+ }
424
+ try {
425
+ if (url.startsWith('blob:')) {
426
+ url = url.replace(/^blob:/, '');
350
427
  }
351
- if (error.message.includes('Unexpected token')) {
428
+ var urlObject = new URL(url /* because fail is handled */);
429
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
352
430
  return false;
353
431
  }
432
+ return true;
433
+ }
434
+ catch (error) {
354
435
  return false;
355
436
  }
356
437
  }
@@ -374,6 +455,27 @@
374
455
  * TODO: Maybe split `ParseError` and `ApplyError`
375
456
  */
376
457
 
458
+ /**
459
+ * Function isValidJsonString will tell you if the string is valid JSON or not
460
+ *
461
+ * @public exported from `@promptbook/utils`
462
+ */
463
+ function isValidJsonString(value /* <- [👨‍⚖️] */) {
464
+ try {
465
+ JSON.parse(value);
466
+ return true;
467
+ }
468
+ catch (error) {
469
+ if (!(error instanceof Error)) {
470
+ throw error;
471
+ }
472
+ if (error.message.includes('Unexpected token')) {
473
+ return false;
474
+ }
475
+ return false;
476
+ }
477
+ }
478
+
377
479
  /**
378
480
  * Function `validatePipelineString` will validate the if the string is a valid pipeline string
379
481
  * It does not check if the string is fully logically correct, but if it is a string that can be a pipeline string or the string looks completely different.
@@ -387,6 +489,15 @@
387
489
  if (isValidJsonString(pipelineString)) {
388
490
  throw new ParseError('Expected a book, but got a JSON string');
389
491
  }
492
+ else if (isValidUrl(pipelineString)) {
493
+ throw new ParseError("Expected a book, but got just the URL \"".concat(pipelineString, "\""));
494
+ }
495
+ else if (isValidFilePath(pipelineString)) {
496
+ throw new ParseError("Expected a book, but got just the file path \"".concat(pipelineString, "\""));
497
+ }
498
+ else if (isValidEmail(pipelineString)) {
499
+ throw new ParseError("Expected a book, but got just the email \"".concat(pipelineString, "\""));
500
+ }
390
501
  // <- TODO: Implement the validation + add tests when the pipeline logic considered as invalid
391
502
  return pipelineString;
392
503
  }
@@ -1080,35 +1191,6 @@
1080
1191
  return isHostnameOnPrivateNetwork(url.hostname);
1081
1192
  }
1082
1193
 
1083
- /**
1084
- * Tests if given string is valid URL.
1085
- *
1086
- * Note: Dataurl are considered perfectly valid.
1087
- * Note: There are two simmilar functions:
1088
- * - `isValidUrl` which tests any URL
1089
- * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
1090
- *
1091
- * @public exported from `@promptbook/utils`
1092
- */
1093
- function isValidUrl(url) {
1094
- if (typeof url !== 'string') {
1095
- return false;
1096
- }
1097
- try {
1098
- if (url.startsWith('blob:')) {
1099
- url = url.replace(/^blob:/, '');
1100
- }
1101
- var urlObject = new URL(url /* because fail is handled */);
1102
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
1103
- return false;
1104
- }
1105
- return true;
1106
- }
1107
- catch (error) {
1108
- return false;
1109
- }
1110
- }
1111
-
1112
1194
  /**
1113
1195
  * Tests if given string is valid pipeline URL URL.
1114
1196
  *
@@ -1863,12 +1945,28 @@
1863
1945
  /**
1864
1946
  * Asserts that the execution of a Promptbook is successful
1865
1947
  *
1948
+ * Note: If there are only warnings, the execution is still successful but the warnings are logged in the console
1949
+ *
1866
1950
  * @param executionResult - The partial result of the Promptbook execution
1867
1951
  * @throws {PipelineExecutionError} If the execution is not successful or if multiple errors occurred
1868
1952
  * @public exported from `@promptbook/core`
1869
1953
  */
1870
1954
  function assertsExecutionSuccessful(executionResult) {
1871
- var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors;
1955
+ var e_1, _a;
1956
+ var isSuccessful = executionResult.isSuccessful, errors = executionResult.errors, warnings = executionResult.warnings;
1957
+ try {
1958
+ for (var warnings_1 = __values(warnings), warnings_1_1 = warnings_1.next(); !warnings_1_1.done; warnings_1_1 = warnings_1.next()) {
1959
+ var warning = warnings_1_1.value;
1960
+ console.warn(warning.message);
1961
+ }
1962
+ }
1963
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
1964
+ finally {
1965
+ try {
1966
+ if (warnings_1_1 && !warnings_1_1.done && (_a = warnings_1.return)) _a.call(warnings_1);
1967
+ }
1968
+ finally { if (e_1) throw e_1.error; }
1969
+ }
1872
1970
  if (isSuccessful === true) {
1873
1971
  return;
1874
1972
  }
@@ -5242,6 +5340,22 @@
5242
5340
  * TODO: [®] DRY Register logic
5243
5341
  */
5244
5342
 
5343
+ /**
5344
+ * Removes emojis from a string and fix whitespaces
5345
+ *
5346
+ * @param text with emojis
5347
+ * @returns text without emojis
5348
+ * @public exported from `@promptbook/utils`
5349
+ */
5350
+ function removeEmojis(text) {
5351
+ // Replace emojis (and also ZWJ sequence) with hyphens
5352
+ text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
5353
+ text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
5354
+ text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
5355
+ text = text.replace(/\p{Extended_Pictographic}/gu, '');
5356
+ return text;
5357
+ }
5358
+
5245
5359
  /**
5246
5360
  * @@@
5247
5361
  *
@@ -5304,6 +5418,30 @@
5304
5418
  * Note: [💞] Ignore a discrepancy between file name and entity name
5305
5419
  */
5306
5420
 
5421
+ /**
5422
+ * @@@
5423
+ *
5424
+ * @param value @@@
5425
+ * @returns @@@
5426
+ * @example @@@
5427
+ * @public exported from `@promptbook/utils`
5428
+ */
5429
+ function titleToName(value) {
5430
+ if (isValidUrl(value)) {
5431
+ value = value.replace(/^https?:\/\//, '');
5432
+ value = value.replace(/\.html$/, '');
5433
+ }
5434
+ else if (isValidFilePath(value)) {
5435
+ value = path.basename(value);
5436
+ // Note: Keeping extension in the name
5437
+ }
5438
+ value = value.split('/').join('-');
5439
+ value = removeEmojis(value);
5440
+ value = normalizeToKebabCase(value);
5441
+ // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
5442
+ return value;
5443
+ }
5444
+
5307
5445
  /**
5308
5446
  * Creates unique name for the source
5309
5447
  *
@@ -5325,6 +5463,15 @@
5325
5463
  * TODO: [🐱‍🐉][🧠] Make some smart crop NOT source-i-m-pavol-a-develop-... BUT source-i-m-pavol-a-developer-...
5326
5464
  */
5327
5465
 
5466
+ /**
5467
+ * @@@
5468
+ *
5469
+ * @private for `FileCacheStorage`
5470
+ */
5471
+ function nameToSubfolderPath(name) {
5472
+ return [name.substr(0, 1).toLowerCase(), name.substr(1, 1).toLowerCase()];
5473
+ }
5474
+
5328
5475
  /**
5329
5476
  * Convert file extension to mime type
5330
5477
  *
@@ -5380,55 +5527,6 @@
5380
5527
  * TODO: [🖇] What about symlinks?
5381
5528
  */
5382
5529
 
5383
- /**
5384
- * Tests if given string is valid URL.
5385
- *
5386
- * Note: This does not check if the file exists only if the path is valid
5387
- * @public exported from `@promptbook/utils`
5388
- */
5389
- function isValidFilePath(filename) {
5390
- if (typeof filename !== 'string') {
5391
- return false;
5392
- }
5393
- if (filename.split('\n').length > 1) {
5394
- return false;
5395
- }
5396
- if (filename.split(' ').length >
5397
- 5 /* <- TODO: [🧠][🈷] Make some better non-arbitrary way how to distinct filenames from informational texts */) {
5398
- return false;
5399
- }
5400
- var filenameSlashes = filename.split('\\').join('/');
5401
- // Absolute Unix path: /hello.txt
5402
- if (/^(\/)/i.test(filenameSlashes)) {
5403
- // console.log(filename, 'Absolute Unix path: /hello.txt');
5404
- return true;
5405
- }
5406
- // Absolute Windows path: /hello.txt
5407
- if (/^([A-Z]{1,2}:\/?)\//i.test(filenameSlashes)) {
5408
- // console.log(filename, 'Absolute Windows path: /hello.txt');
5409
- return true;
5410
- }
5411
- // Relative path: ./hello.txt
5412
- if (/^(\.\.?\/)+/i.test(filenameSlashes)) {
5413
- // console.log(filename, 'Relative path: ./hello.txt');
5414
- return true;
5415
- }
5416
- // Allow paths like foo/hello
5417
- if (/^[^/]+\/[^/]+/i.test(filenameSlashes)) {
5418
- // console.log(filename, 'Allow paths like foo/hello');
5419
- return true;
5420
- }
5421
- // Allow paths like hello.book
5422
- if (/^[^/]+\.[^/]+$/i.test(filenameSlashes)) {
5423
- // console.log(filename, 'Allow paths like hello.book');
5424
- return true;
5425
- }
5426
- return false;
5427
- }
5428
- /**
5429
- * TODO: [🍏] Implement for MacOs
5430
- */
5431
-
5432
5530
  /**
5433
5531
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
5434
5532
  *
@@ -5464,10 +5562,11 @@
5464
5562
  function makeKnowledgeSourceHandler(knowledgeSource, tools, options) {
5465
5563
  var _a;
5466
5564
  return __awaiter(this, void 0, void 0, function () {
5467
- var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response_1, mimeType, filename_1, fileExtension, mimeType;
5468
- return __generator(this, function (_f) {
5469
- switch (_f.label) {
5565
+ var _b, fetch, knowledgeSourceContent, name, _c, _d, rootDirname, url, response, mimeType, filename, hash, rootDirname_1, filepath, _f, _g, _h, _j, _k, filename_1, fileExtension, mimeType;
5566
+ return __generator(this, function (_l) {
5567
+ switch (_l.label) {
5470
5568
  case 0:
5569
+ console.log('!!! makeKnowledgeSourceHandler', knowledgeSource);
5471
5570
  _b = tools.fetch, fetch = _b === void 0 ? scraperFetch : _b;
5472
5571
  knowledgeSourceContent = knowledgeSource.knowledgeSourceContent;
5473
5572
  name = knowledgeSource.name;
@@ -5475,54 +5574,32 @@
5475
5574
  if (!name) {
5476
5575
  name = knowledgeSourceContentToName(knowledgeSourceContent);
5477
5576
  }
5478
- if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 2];
5577
+ if (!isValidUrl(knowledgeSourceContent)) return [3 /*break*/, 5];
5479
5578
  url = knowledgeSourceContent;
5480
5579
  return [4 /*yield*/, fetch(url)];
5481
5580
  case 1:
5482
- response_1 = _f.sent();
5483
- mimeType = ((_a = response_1.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
5484
- return [2 /*return*/, {
5485
- source: name,
5486
- filename: null,
5487
- url: url,
5488
- mimeType: mimeType,
5489
- /*
5490
- TODO: [🥽]
5491
- > async asBlob() {
5492
- > // TODO: [👨🏻‍🤝‍👨🏻] This can be called multiple times BUT when called second time, response in already consumed
5493
- > const content = await response.blob();
5494
- > return content;
5495
- > },
5496
- */
5497
- asJson: function () {
5498
- return __awaiter(this, void 0, void 0, function () {
5499
- var content;
5500
- return __generator(this, function (_a) {
5501
- switch (_a.label) {
5502
- case 0: return [4 /*yield*/, response_1.json()];
5503
- case 1:
5504
- content = _a.sent();
5505
- return [2 /*return*/, content];
5506
- }
5507
- });
5508
- });
5509
- },
5510
- asText: function () {
5511
- return __awaiter(this, void 0, void 0, function () {
5512
- var content;
5513
- return __generator(this, function (_a) {
5514
- switch (_a.label) {
5515
- case 0: return [4 /*yield*/, response_1.text()];
5516
- case 1:
5517
- content = _a.sent();
5518
- return [2 /*return*/, content];
5519
- }
5520
- });
5521
- });
5522
- },
5523
- }];
5581
+ response = _l.sent();
5582
+ mimeType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.split(';')[0]) || 'text/html';
5583
+ filename = url.split('/').pop() || titleToName(url);
5584
+ hash = sha256__default["default"](hexEncoder__default["default"].parse(url)).toString( /* hex */);
5585
+ rootDirname_1 = path.join(process.cwd(), DEFAULT_DOWNLOAD_CACHE_DIRNAME);
5586
+ filepath = path.join.apply(void 0, __spreadArray(__spreadArray([], __read(nameToSubfolderPath(hash /* <- TODO: [🎎] Maybe add some SHA256 prefix */)), false), ["".concat(filename.substring(0, MAX_FILENAME_LENGTH), ".pdf")], false));
5587
+ return [4 /*yield*/, tools.fs.mkdir(path.dirname(path.join(rootDirname_1, filepath)), { recursive: true })];
5524
5588
  case 2:
5525
- if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 4];
5589
+ _l.sent();
5590
+ _g = (_f = tools.fs).writeFile;
5591
+ _h = [path.join(rootDirname_1, filepath)];
5592
+ _k = (_j = Buffer).from;
5593
+ return [4 /*yield*/, response.arrayBuffer()];
5594
+ case 3: return [4 /*yield*/, _g.apply(_f, _h.concat([_k.apply(_j, [_l.sent()])]))];
5595
+ case 4:
5596
+ _l.sent();
5597
+ // TODO: !!!!!!!! Check the file security
5598
+ // TODO: !!!!!!!! Check the file size (if it is not too big)
5599
+ // TODO: !!!!!!!! Delete the file
5600
+ return [2 /*return*/, makeKnowledgeSourceHandler({ name: name, knowledgeSourceContent: filepath }, tools, __assign(__assign({}, options), { rootDirname: rootDirname_1 }))];
5601
+ case 5:
5602
+ if (!isValidFilePath(knowledgeSourceContent)) return [3 /*break*/, 7];
5526
5603
  if (tools.fs === undefined) {
5527
5604
  throw new EnvironmentMismatchError('Can not import file knowledge without filesystem tools');
5528
5605
  // <- TODO: [🧠] What is the best error type here`
@@ -5535,8 +5612,8 @@
5535
5612
  fileExtension = getFileExtension(filename_1);
5536
5613
  mimeType = extensionToMimeType(fileExtension || '');
5537
5614
  return [4 /*yield*/, isFileExisting(filename_1, tools.fs)];
5538
- case 3:
5539
- if (!(_f.sent())) {
5615
+ case 6:
5616
+ if (!(_l.sent())) {
5540
5617
  throw new NotFoundError(spaceTrim__default["default"](function (block) { return "\n Can not make source handler for file which does not exist:\n\n File:\n ".concat(block(knowledgeSourceContent), "\n\n Full file path:\n ").concat(block(filename_1), "\n "); }));
5541
5618
  }
5542
5619
  // TODO: [🧠][😿] Test security file - file is scoped to the project (BUT maybe do this in `filesystemTools`)
@@ -5582,7 +5659,7 @@
5582
5659
  });
5583
5660
  },
5584
5661
  }];
5585
- case 4: return [2 /*return*/, {
5662
+ case 7: return [2 /*return*/, {
5586
5663
  source: name,
5587
5664
  filename: null,
5588
5665
  url: null,
@@ -6693,22 +6770,6 @@
6693
6770
  * TODO: [🌺] Use some intermediate util splitWords
6694
6771
  */
6695
6772
 
6696
- /**
6697
- * Removes emojis from a string and fix whitespaces
6698
- *
6699
- * @param text with emojis
6700
- * @returns text without emojis
6701
- * @public exported from `@promptbook/utils`
6702
- */
6703
- function removeEmojis(text) {
6704
- // Replace emojis (and also ZWJ sequence) with hyphens
6705
- text = text.replace(/(\p{Extended_Pictographic})\p{Modifier_Symbol}/gu, '$1');
6706
- text = text.replace(/(\p{Extended_Pictographic})[\u{FE00}-\u{FE0F}]/gu, '$1');
6707
- text = text.replace(/(\p{Extended_Pictographic})(\u{200D}\p{Extended_Pictographic})*/gu, '$1');
6708
- text = text.replace(/\p{Extended_Pictographic}/gu, '');
6709
- return text;
6710
- }
6711
-
6712
6773
  /**
6713
6774
  * Removes quotes from a string
6714
6775
  *
@@ -8900,30 +8961,6 @@
8900
8961
  * NOW we are working just with markdown string and its good enough
8901
8962
  */
8902
8963
 
8903
- /**
8904
- * @@@
8905
- *
8906
- * @param value @@@
8907
- * @returns @@@
8908
- * @example @@@
8909
- * @public exported from `@promptbook/utils`
8910
- */
8911
- function titleToName(value) {
8912
- if (isValidUrl(value)) {
8913
- value = value.replace(/^https?:\/\//, '');
8914
- value = value.replace(/\.html$/, '');
8915
- }
8916
- else if (isValidFilePath(value)) {
8917
- value = path.basename(value);
8918
- // Note: Keeping extension in the name
8919
- }
8920
- value = value.split('/').join('-');
8921
- value = removeEmojis(value);
8922
- value = normalizeToKebabCase(value);
8923
- // TODO: [🧠] Maybe warn or add some padding to short name which are not good identifiers
8924
- return value;
8925
- }
8926
-
8927
8964
  /**
8928
8965
  * Compile pipeline from string (markdown) format to JSON format synchronously
8929
8966
  *
@@ -9656,6 +9693,7 @@
9656
9693
  readFile: promises.readFile,
9657
9694
  writeFile: promises.writeFile,
9658
9695
  readdir: promises.readdir,
9696
+ mkdir: promises.mkdir,
9659
9697
  };
9660
9698
  }
9661
9699
  /**
@@ -11274,15 +11312,6 @@
11274
11312
  * TODO: [🍙] Make some standard order of json properties
11275
11313
  */
11276
11314
 
11277
- /**
11278
- * @@@
11279
- *
11280
- * @private for `FileCacheStorage`
11281
- */
11282
- function nameToSubfolderPath(name) {
11283
- return [name.substr(0, 1).toLowerCase(), name.substr(1, 1).toLowerCase()];
11284
- }
11285
-
11286
11315
  /**
11287
11316
  * @@@
11288
11317
  *