@promptbook/cli 0.59.0-24 → 0.59.0-25

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,16 +1,16 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('commander'), require('spacetrim'), require('colors'), require('waitasecond'), require('fs/promises'), require('glob-promise'), require('prettier'), require('prettier/parser-html')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'commander', 'spacetrim', 'colors', 'waitasecond', 'fs/promises', 'glob-promise', 'prettier', 'prettier/parser-html'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-cli"] = {}, global.commander, global.spaceTrim, global.colors, global.waitasecond, global.promises, global.glob, global.prettier, global.parserHtml));
5
- })(this, (function (exports, commander, spaceTrim, colors, waitasecond, promises, glob, prettier, parserHtml) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('commander'), require('spacetrim'), require('colors'), require('waitasecond'), require('fs/promises'), require('path'), require('prettier'), require('prettier/parser-html'), require('glob-promise')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'commander', 'spacetrim', 'colors', 'waitasecond', 'fs/promises', 'path', 'prettier', 'prettier/parser-html', 'glob-promise'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["promptbook-cli"] = {}, global.commander, global.spaceTrim, global.colors, global.waitasecond, global.promises, global.path, global.prettier, global.parserHtml, global.glob));
5
+ })(this, (function (exports, commander, spaceTrim, colors, waitasecond, promises, path, prettier, parserHtml, glob) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
9
9
  var commander__default = /*#__PURE__*/_interopDefaultLegacy(commander);
10
10
  var spaceTrim__default = /*#__PURE__*/_interopDefaultLegacy(spaceTrim);
11
11
  var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
12
- var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
13
12
  var parserHtml__default = /*#__PURE__*/_interopDefaultLegacy(parserHtml);
13
+ var glob__default = /*#__PURE__*/_interopDefaultLegacy(glob);
14
14
 
15
15
  /*! *****************************************************************************
16
16
  Copyright (c) Microsoft Corporation.
@@ -147,7 +147,7 @@
147
147
  /**
148
148
  * The version of the Promptbook library
149
149
  */
150
- var PROMPTBOOK_VERSION = '0.59.0-23';
150
+ var PROMPTBOOK_VERSION = '0.59.0-24';
151
151
 
152
152
  /**
153
153
  * Initializes testing `hello` command for Promptbook CLI utilities
@@ -180,94 +180,13 @@
180
180
  }
181
181
 
182
182
  /**
183
- * Initializes `make` command for Promptbook CLI utilities
184
- *
185
- * @private part of `promptbookCli`
183
+ * The maximum number of iterations for a loops
186
184
  */
187
- function initializeMake(program) {
188
- var _this = this;
189
- var helloCommand = program.command('make <path>');
190
- helloCommand.description(spaceTrim__default["default"]("\n Makes a new promptbook library in given folder\n "));
191
- helloCommand.argument('<path>', 'Path to promptbook folder');
192
- helloCommand.option('-f, --format <format>', "Output format of builded library \"js\", \"ts\" or \"json\"", 'js');
193
- helloCommand.option('-v, --validate', "Validate logic of promptbook", true);
194
- // TODO: !!! Auto-detect AI api keys + explicit api keys as argv
195
- helloCommand.action(function (path, _a) {
196
- var format = _a.format, validate = _a.validate;
197
- return __awaiter(_this, void 0, void 0, function () {
198
- return __generator(this, function (_b) {
199
- console.info({ path: path, format: format, validate: validate });
200
- // TODO: !!! Implement
201
- // TODO: !!! Validate logic
202
- process.exit(0);
203
- return [2 /*return*/];
204
- });
205
- });
206
- });
207
- }
208
-
185
+ var LOOP_LIMIT = 1000;
209
186
  /**
210
- * Removes HTML or Markdown comments from a string.
211
- *
212
- * @param {string} content - The string to remove comments from.
213
- * @returns {string} The input string with all comments removed.
187
+ * The name of the builded promptbook library made by CLI `promptbook make` and for lookup in `createLibraryFromDirectory`
214
188
  */
215
- function removeContentComments(content) {
216
- return spaceTrim.spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
217
- }
218
-
219
- /**
220
- * Add or modify an auto-generated section in a markdown file
221
- *
222
- * @private within the library
223
- */
224
- function addAutoGeneratedSection(content, options) {
225
- var sectionName = options.sectionName, sectionContent = options.sectionContent;
226
- var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
227
- var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
228
- var sectionMatch = content.match(sectionRegex);
229
- if (sectionMatch) {
230
- return content.replace(sectionRegex, spaceTrim.spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
231
- }
232
- var placeForSection = removeContentComments(content).match(/^##.*$/im);
233
- if (!placeForSection) {
234
- throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
235
- }
236
- var _a = __read(placeForSection, 1), heading = _a[0];
237
- return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
238
- }
239
-
240
- /**
241
- * Prettify the html code
242
- *
243
- * @param content raw html code
244
- * @returns formatted html code
245
- */
246
- function prettifyMarkdown(content) {
247
- try {
248
- return prettier.format(content, {
249
- parser: 'markdown',
250
- plugins: [parserHtml__default["default"]],
251
- // TODO: DRY - make some import or auto-copy of .prettierrc
252
- endOfLine: 'lf',
253
- tabWidth: 4,
254
- singleQuote: true,
255
- trailingComma: 'all',
256
- arrowParens: 'always',
257
- printWidth: 120,
258
- htmlWhitespaceSensitivity: 'ignore',
259
- jsxBracketSameLine: false,
260
- bracketSpacing: true,
261
- });
262
- }
263
- catch (error) {
264
- console.error('There was an error with prettifying the markdown, using the original as the fallback', {
265
- error: error,
266
- html: content,
267
- });
268
- return content;
269
- }
270
- }
189
+ var PROMPTBOOK_MAKED_BASE_FILENAME = "promptbook-library";
271
190
 
272
191
  /**
273
192
  * This error indicates that the promptbook in a markdown format cannot be parsed into a valid promptbook object
@@ -283,7 +202,7 @@
283
202
  return PromptbookSyntaxError;
284
203
  }(Error));
285
204
 
286
- var promptbookLibrary = [{title:"Prepare Knowledge from Markdown",promptbookUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.59.0-23",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:[]}];
205
+ var promptbookLibrary = [{title:"Prepare Knowledge from Markdown",promptbookUrl:"https://promptbook.studio/promptbook/prepare-knowledge-from-markdown.ptbk.md",promptbookVersion:"0.59.0-24",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:[]}];
287
206
 
288
207
  /**
289
208
  * This error indicates errors during the execution of the promptbook
@@ -324,11 +243,6 @@
324
243
  * TODO: [🧠] Can this return type be better typed than void
325
244
  */
326
245
 
327
- /**
328
- * The maximum number of iterations for a loops
329
- */
330
- var LOOP_LIMIT = 1000;
331
-
332
246
  /**
333
247
  * This error indicates that the promptbook object has valid syntax but contains logical errors (like circular dependencies)
334
248
  */
@@ -1665,6 +1579,38 @@
1665
1579
  * TODO: [🧠][3] transparent = (report intermediate parameters) / opaque execution = (report only output parameters) progress reporting mode
1666
1580
  */
1667
1581
 
1582
+ /**
1583
+ * Prettify the html code
1584
+ *
1585
+ * @param content raw html code
1586
+ * @returns formatted html code
1587
+ */
1588
+ function prettifyMarkdown(content) {
1589
+ try {
1590
+ return prettier.format(content, {
1591
+ parser: 'markdown',
1592
+ plugins: [parserHtml__default["default"]],
1593
+ // TODO: DRY - make some import or auto-copy of .prettierrc
1594
+ endOfLine: 'lf',
1595
+ tabWidth: 4,
1596
+ singleQuote: true,
1597
+ trailingComma: 'all',
1598
+ arrowParens: 'always',
1599
+ printWidth: 120,
1600
+ htmlWhitespaceSensitivity: 'ignore',
1601
+ jsxBracketSameLine: false,
1602
+ bracketSpacing: true,
1603
+ });
1604
+ }
1605
+ catch (error) {
1606
+ console.error('There was an error with prettifying the markdown, using the original as the fallback', {
1607
+ error: error,
1608
+ html: content,
1609
+ });
1610
+ return content;
1611
+ }
1612
+ }
1613
+
1668
1614
  /**
1669
1615
  * Makes first letter of a string uppercase
1670
1616
  *
@@ -2359,6 +2305,16 @@
2359
2305
  * TODO: [🍓][🌻] !!! Decide of this is internal util, external util OR validator/postprocessor
2360
2306
  */
2361
2307
 
2308
+ /**
2309
+ * Removes HTML or Markdown comments from a string.
2310
+ *
2311
+ * @param {string} content - The string to remove comments from.
2312
+ * @returns {string} The input string with all comments removed.
2313
+ */
2314
+ function removeContentComments(content) {
2315
+ return spaceTrim.spaceTrim(content.replace(/<!--(.*?)-->/gs, ''));
2316
+ }
2317
+
2362
2318
  /**
2363
2319
  * Creates a new set with all elements that are present in either set
2364
2320
  */
@@ -3230,6 +3186,443 @@
3230
3186
  * TODO: [🧠] Parameter flags - isInput, isOutput, isInternal
3231
3187
  */
3232
3188
 
3189
+ /**
3190
+ * This error indicates that the promptbook library cannot be propperly loaded
3191
+ */
3192
+ var PromptbookLibraryError = /** @class */ (function (_super) {
3193
+ __extends(PromptbookLibraryError, _super);
3194
+ function PromptbookLibraryError(message) {
3195
+ var _this = _super.call(this, message) || this;
3196
+ _this.name = 'PromptbookLibraryError';
3197
+ Object.setPrototypeOf(_this, PromptbookLibraryError.prototype);
3198
+ return _this;
3199
+ }
3200
+ return PromptbookLibraryError;
3201
+ }(Error));
3202
+
3203
+ /**
3204
+ * Constructs Promptbook from async sources
3205
+ * It can be one of the following:
3206
+ * - Promise of array of PromptbookJson or PromptbookString
3207
+ * - Factory function that returns Promise of array of PromptbookJson or PromptbookString
3208
+ *
3209
+ * Note: This is useful as internal tool for other constructor functions like
3210
+ * `createLibraryFromUrl` or `createLibraryFromDirectory`
3211
+ * Consider using those functions instead of this one
3212
+ *
3213
+ * Note: The function does NOT return promise it returns the library directly which waits for the sources to be resolved
3214
+ * when error occurs in given promise or factory function, it is thrown during `listPromptbooks` or `getPromptbookByUrl` call
3215
+ *
3216
+ * Note: Consider using `createLibraryFromDirectory` or `createLibraryFromUrl`
3217
+ *
3218
+ * @param promptbookSourcesPromiseOrFactory
3219
+ * @returns PromptbookLibrary
3220
+ * @deprecated Do not use, it will became internal tool for other constructor functions
3221
+ */
3222
+ function createLibraryFromPromise(promptbookSourcesPromiseOrFactory) {
3223
+ var library;
3224
+ function forSources() {
3225
+ return __awaiter(this, void 0, void 0, function () {
3226
+ var promptbookSources;
3227
+ return __generator(this, function (_a) {
3228
+ switch (_a.label) {
3229
+ case 0:
3230
+ if (typeof promptbookSourcesPromiseOrFactory === 'function') {
3231
+ // Note: Calling factory function only once despite multiple calls to resolveSources
3232
+ promptbookSourcesPromiseOrFactory = promptbookSourcesPromiseOrFactory();
3233
+ }
3234
+ return [4 /*yield*/, promptbookSourcesPromiseOrFactory];
3235
+ case 1:
3236
+ promptbookSources = _a.sent();
3237
+ return [4 /*yield*/, createLibraryFromJson.apply(void 0, __spreadArray([], __read(promptbookSources), false))];
3238
+ case 2:
3239
+ library = _a.sent();
3240
+ return [2 /*return*/];
3241
+ }
3242
+ });
3243
+ });
3244
+ }
3245
+ function listPromptbooks() {
3246
+ return __awaiter(this, void 0, void 0, function () {
3247
+ return __generator(this, function (_a) {
3248
+ switch (_a.label) {
3249
+ case 0: return [4 /*yield*/, forSources()];
3250
+ case 1:
3251
+ _a.sent();
3252
+ return [2 /*return*/, /* not await */ library.listPromptbooks()];
3253
+ }
3254
+ });
3255
+ });
3256
+ }
3257
+ function getPromptbookByUrl(url) {
3258
+ return __awaiter(this, void 0, void 0, function () {
3259
+ return __generator(this, function (_a) {
3260
+ switch (_a.label) {
3261
+ case 0: return [4 /*yield*/, forSources()];
3262
+ case 1:
3263
+ _a.sent();
3264
+ return [2 /*return*/, /* not await */ library.getPromptbookByUrl(url)];
3265
+ }
3266
+ });
3267
+ });
3268
+ }
3269
+ function isResponsibleForPrompt(prompt) {
3270
+ return __awaiter(this, void 0, void 0, function () {
3271
+ return __generator(this, function (_a) {
3272
+ switch (_a.label) {
3273
+ case 0: return [4 /*yield*/, forSources()];
3274
+ case 1:
3275
+ _a.sent();
3276
+ return [2 /*return*/, /* not await */ library.isResponsibleForPrompt(prompt)];
3277
+ }
3278
+ });
3279
+ });
3280
+ }
3281
+ return {
3282
+ listPromptbooks: listPromptbooks,
3283
+ getPromptbookByUrl: getPromptbookByUrl,
3284
+ isResponsibleForPrompt: isResponsibleForPrompt,
3285
+ };
3286
+ }
3287
+
3288
+ /**
3289
+ * Constructs Promptbook from given directory
3290
+ *
3291
+ * Note: Works only in Node.js environment because it reads the file system
3292
+ *
3293
+ * @param path - path to the directory with promptbooks
3294
+ * @param options - Misc options for the library
3295
+ * @returns PromptbookLibrary
3296
+ */
3297
+ function createLibraryFromDirectory(path$1, options) {
3298
+ return __awaiter(this, void 0, void 0, function () {
3299
+ var makedLibraryFilePath, makedLibraryFileExists, _a, _b, isRecursive, _c, isVerbose, _d, isLazyLoaded, _e, isCrashOnError, library;
3300
+ var _this = this;
3301
+ return __generator(this, function (_f) {
3302
+ switch (_f.label) {
3303
+ case 0:
3304
+ if (!isRunningInNode()) {
3305
+ throw new Error('Function `createLibraryFromDirectory` can only be run in Node.js environment because it reads the file system.');
3306
+ }
3307
+ makedLibraryFilePath = path.join(path$1, "".concat(PROMPTBOOK_MAKED_BASE_FILENAME, ".json"));
3308
+ return [4 /*yield*/, promises.access(makedLibraryFilePath, promises.constants.R_OK)
3309
+ .then(function () { return true; })
3310
+ .catch(function () { return false; })];
3311
+ case 1:
3312
+ makedLibraryFileExists = _f.sent();
3313
+ if (!makedLibraryFileExists) {
3314
+ console.info(colors__default["default"].yellow("Tip: Prebuild your promptbook library (file with supposed prebuild ".concat(makedLibraryFilePath, " not found) with CLI util \"promptbook make\" to speed up the library creation.")));
3315
+ }
3316
+ else {
3317
+ colors__default["default"].green("Using your prebuild promptbook library ".concat(makedLibraryFilePath));
3318
+ // TODO: !!!!! Implement;
3319
+ }
3320
+ _a = options || {}, _b = _a.isRecursive, isRecursive = _b === void 0 ? true : _b, _c = _a.isVerbose, isVerbose = _c === void 0 ? false : _c, _d = _a.isLazyLoaded, isLazyLoaded = _d === void 0 ? false : _d, _e = _a.isCrashOnError, isCrashOnError = _e === void 0 ? true : _e;
3321
+ library = createLibraryFromPromise(function () { return __awaiter(_this, void 0, void 0, function () {
3322
+ var fileNames, promptbooks, _loop_1, fileNames_1, fileNames_1_1, fileName, e_1_1;
3323
+ var e_1, _a;
3324
+ return __generator(this, function (_b) {
3325
+ switch (_b.label) {
3326
+ case 0:
3327
+ if (isVerbose) {
3328
+ console.info("Creating promptbook library from path ".concat(path$1));
3329
+ }
3330
+ return [4 /*yield*/, listAllFiles(path$1, isRecursive)];
3331
+ case 1:
3332
+ fileNames = _b.sent();
3333
+ if (isVerbose) {
3334
+ console.info('createLibraryFromDirectory', { path: path$1, isRecursive: isRecursive, fileNames: fileNames });
3335
+ }
3336
+ promptbooks = [];
3337
+ _loop_1 = function (fileName) {
3338
+ var promptbook, promptbookString, _c, _d, error_1, wrappedErrorMessage;
3339
+ return __generator(this, function (_e) {
3340
+ switch (_e.label) {
3341
+ case 0:
3342
+ _e.trys.push([0, 7, , 8]);
3343
+ promptbook = null;
3344
+ if (!fileName.endsWith('.ptbk.md')) return [3 /*break*/, 3];
3345
+ return [4 /*yield*/, promises.readFile(fileName, 'utf8')];
3346
+ case 1:
3347
+ promptbookString = (_e.sent());
3348
+ return [4 /*yield*/, promptbookStringToJson(promptbookString)];
3349
+ case 2:
3350
+ promptbook = _e.sent();
3351
+ return [3 /*break*/, 6];
3352
+ case 3:
3353
+ if (!fileName.endsWith('.ptbk.json')) return [3 /*break*/, 5];
3354
+ if (isVerbose) {
3355
+ console.info("Loading ".concat(fileName));
3356
+ }
3357
+ _d = (_c = JSON).parse;
3358
+ return [4 /*yield*/, promises.readFile(fileName, 'utf8')];
3359
+ case 4:
3360
+ // TODO: Handle non-valid JSON files
3361
+ promptbook = _d.apply(_c, [_e.sent()]);
3362
+ return [3 /*break*/, 6];
3363
+ case 5:
3364
+ if (isVerbose) {
3365
+ console.info("Skipping file ".concat(fileName));
3366
+ }
3367
+ _e.label = 6;
3368
+ case 6:
3369
+ // ---
3370
+ if (promptbook !== null) {
3371
+ if (!promptbook.promptbookUrl) {
3372
+ if (isVerbose) {
3373
+ console.info("Not loading ".concat(fileName, " - missing URL"));
3374
+ }
3375
+ }
3376
+ else {
3377
+ if (isVerbose) {
3378
+ console.info("Loading ".concat(fileName));
3379
+ }
3380
+ if (!isCrashOnError) {
3381
+ // Note: Validate promptbook to check if it is logically correct to not crash on invalid promptbooks
3382
+ // But be handled in current try-catch block
3383
+ validatePromptbookJson(promptbook);
3384
+ }
3385
+ // Note: [🦄] Promptbook with same url uniqueness will be checked automatically in SimplePromptbookLibrary
3386
+ promptbooks.push(promptbook);
3387
+ }
3388
+ }
3389
+ return [3 /*break*/, 8];
3390
+ case 7:
3391
+ error_1 = _e.sent();
3392
+ if (!(error_1 instanceof Error)) {
3393
+ throw error_1;
3394
+ }
3395
+ wrappedErrorMessage = spaceTrim__default["default"](function (block) { return "\n Error during loading promptbook from file ".concat(fileName.split('\\').join('/'), ":\n\n ").concat(block(error_1.message), "\n\n "); });
3396
+ if (isCrashOnError) {
3397
+ throw new PromptbookLibraryError(wrappedErrorMessage);
3398
+ }
3399
+ console.error(wrappedErrorMessage);
3400
+ return [3 /*break*/, 8];
3401
+ case 8: return [2 /*return*/];
3402
+ }
3403
+ });
3404
+ };
3405
+ _b.label = 2;
3406
+ case 2:
3407
+ _b.trys.push([2, 7, 8, 9]);
3408
+ fileNames_1 = __values(fileNames), fileNames_1_1 = fileNames_1.next();
3409
+ _b.label = 3;
3410
+ case 3:
3411
+ if (!!fileNames_1_1.done) return [3 /*break*/, 6];
3412
+ fileName = fileNames_1_1.value;
3413
+ return [5 /*yield**/, _loop_1(fileName)];
3414
+ case 4:
3415
+ _b.sent();
3416
+ _b.label = 5;
3417
+ case 5:
3418
+ fileNames_1_1 = fileNames_1.next();
3419
+ return [3 /*break*/, 3];
3420
+ case 6: return [3 /*break*/, 9];
3421
+ case 7:
3422
+ e_1_1 = _b.sent();
3423
+ e_1 = { error: e_1_1 };
3424
+ return [3 /*break*/, 9];
3425
+ case 8:
3426
+ try {
3427
+ if (fileNames_1_1 && !fileNames_1_1.done && (_a = fileNames_1.return)) _a.call(fileNames_1);
3428
+ }
3429
+ finally { if (e_1) throw e_1.error; }
3430
+ return [7 /*endfinally*/];
3431
+ case 9: return [2 /*return*/, promptbooks];
3432
+ }
3433
+ });
3434
+ }); });
3435
+ if (!(isLazyLoaded === false)) return [3 /*break*/, 3];
3436
+ return [4 /*yield*/, library.listPromptbooks()];
3437
+ case 2:
3438
+ _f.sent();
3439
+ _f.label = 3;
3440
+ case 3: return [2 /*return*/, library];
3441
+ }
3442
+ });
3443
+ });
3444
+ }
3445
+ /**
3446
+ * Reads all files in the directory
3447
+ *
3448
+ * @param path
3449
+ * @param isRecursive
3450
+ * @returns List of all files in the directory
3451
+ * @private internal function for `createLibraryFromDirectory`
3452
+ */
3453
+ function listAllFiles(path$1, isRecursive) {
3454
+ return __awaiter(this, void 0, void 0, function () {
3455
+ var dirents, fileNames, _a, _b, dirent, subPath, _c, _d, _e, _f, e_2_1;
3456
+ var e_2, _g;
3457
+ return __generator(this, function (_h) {
3458
+ switch (_h.label) {
3459
+ case 0: return [4 /*yield*/, promises.readdir(path$1, {
3460
+ withFileTypes: true /* Note: This is not working: recursive: isRecursive */,
3461
+ })];
3462
+ case 1:
3463
+ dirents = _h.sent();
3464
+ fileNames = dirents.filter(function (dirent) { return dirent.isFile(); }).map(function (_a) {
3465
+ var name = _a.name;
3466
+ return path.join(path$1, name);
3467
+ });
3468
+ if (!isRecursive) return [3 /*break*/, 9];
3469
+ _h.label = 2;
3470
+ case 2:
3471
+ _h.trys.push([2, 7, 8, 9]);
3472
+ _a = __values(dirents.filter(function (dirent) { return dirent.isDirectory(); })), _b = _a.next();
3473
+ _h.label = 3;
3474
+ case 3:
3475
+ if (!!_b.done) return [3 /*break*/, 6];
3476
+ dirent = _b.value;
3477
+ subPath = path.join(path$1, dirent.name);
3478
+ _d = (_c = fileNames.push).apply;
3479
+ _e = [fileNames];
3480
+ _f = [[]];
3481
+ return [4 /*yield*/, listAllFiles(subPath, isRecursive)];
3482
+ case 4:
3483
+ _d.apply(_c, _e.concat([__spreadArray.apply(void 0, _f.concat([__read.apply(void 0, [(_h.sent())]), false]))]));
3484
+ _h.label = 5;
3485
+ case 5:
3486
+ _b = _a.next();
3487
+ return [3 /*break*/, 3];
3488
+ case 6: return [3 /*break*/, 9];
3489
+ case 7:
3490
+ e_2_1 = _h.sent();
3491
+ e_2 = { error: e_2_1 };
3492
+ return [3 /*break*/, 9];
3493
+ case 8:
3494
+ try {
3495
+ if (_b && !_b.done && (_g = _a.return)) _g.call(_a);
3496
+ }
3497
+ finally { if (e_2) throw e_2.error; }
3498
+ return [7 /*endfinally*/];
3499
+ case 9: return [2 /*return*/, fileNames];
3500
+ }
3501
+ });
3502
+ });
3503
+ }
3504
+ /**
3505
+ * TODO: !!!! [🧠] Library precompilation and do not mix markdown and json promptbooks
3506
+ */
3507
+
3508
+ /**
3509
+ * Converts PromptbookLibrary to serialized JSON
3510
+ *
3511
+ * Note: Functions `libraryToJson` and `createLibraryFromJson` are complementary
3512
+ */
3513
+ function libraryToJson(library) {
3514
+ return __awaiter(this, void 0, void 0, function () {
3515
+ var promptbookUrls, promptbooks;
3516
+ return __generator(this, function (_a) {
3517
+ switch (_a.label) {
3518
+ case 0: return [4 /*yield*/, library.listPromptbooks()];
3519
+ case 1:
3520
+ promptbookUrls = _a.sent();
3521
+ return [4 /*yield*/, Promise.all(promptbookUrls.map(function (url) { return library.getPromptbookByUrl(url); }))];
3522
+ case 2:
3523
+ promptbooks = _a.sent();
3524
+ return [2 /*return*/, promptbooks];
3525
+ }
3526
+ });
3527
+ });
3528
+ }
3529
+
3530
+ /**
3531
+ * Initializes `make` command for Promptbook CLI utilities
3532
+ *
3533
+ * @private part of `promptbookCli`
3534
+ */
3535
+ function initializeMake(program) {
3536
+ var _this = this;
3537
+ var helloCommand = program.command('make');
3538
+ helloCommand.description(spaceTrim__default["default"]("\n Makes a new promptbook library in given folder\n "));
3539
+ helloCommand.argument('<path>', 'Path to promptbook directory');
3540
+ helloCommand.option('--project-name', "Name of the project for whom library is", 'Project');
3541
+ helloCommand.option('-f, --format <format>', spaceTrim__default["default"]("\n Output format of builded library \"javascript\", \"typescript\" or \"json\"\n\n Note: You can use multiple formats separated by comma\n "), 'javascript' /* <- Note: [🏳‍🌈] */);
3542
+ helloCommand.option('--no-validation', "Do not validate logic of promptbooks in library", true);
3543
+ helloCommand.option('--validation', "Types of validations separated by comma (options \"logic\",\"imports\")", 'logic,imports');
3544
+ // TODO: !!! Auto-detect AI api keys + explicit api keys as argv
3545
+ helloCommand.action(function (path$1, _a) {
3546
+ var projectName = _a.projectName, format = _a.format, validation = _a.validation;
3547
+ return __awaiter(_this, void 0, void 0, function () {
3548
+ var library, libraryJson, libraryJsonString, saveFile;
3549
+ var _this = this;
3550
+ return __generator(this, function (_b) {
3551
+ switch (_b.label) {
3552
+ case 0:
3553
+ console.info('!!!', { projectName: projectName, path: path$1, format: format, validation: validation });
3554
+ return [4 /*yield*/, createLibraryFromDirectory(path$1, {
3555
+ isVerbose: true,
3556
+ isRecursive: true,
3557
+ })];
3558
+ case 1:
3559
+ library = _b.sent();
3560
+ return [4 /*yield*/, libraryToJson(library)];
3561
+ case 2:
3562
+ libraryJson = _b.sent();
3563
+ libraryJsonString = JSON.stringify(libraryJson);
3564
+ saveFile = function (extension, content) { return __awaiter(_this, void 0, void 0, function () {
3565
+ var filePath;
3566
+ return __generator(this, function (_a) {
3567
+ switch (_a.label) {
3568
+ case 0:
3569
+ filePath = path.join(path$1, "promptbook-library.".concat(extension));
3570
+ return [4 /*yield*/, promises.writeFile(filePath, content, 'utf-8')];
3571
+ case 1:
3572
+ _a.sent();
3573
+ console.info(colors__default["default"].green("Maked ".concat(filePath)));
3574
+ return [2 /*return*/];
3575
+ }
3576
+ });
3577
+ }); };
3578
+ if (!format.includes('json')) return [3 /*break*/, 4];
3579
+ return [4 /*yield*/, saveFile('json', libraryJsonString + '\n')];
3580
+ case 3:
3581
+ _b.sent();
3582
+ _b.label = 4;
3583
+ case 4:
3584
+ if (format.includes('javascript')) {
3585
+ // TODO: !!!!;
3586
+ // TODO: !!! DRY javascript and typescript
3587
+ format.push('javascript');
3588
+ }
3589
+ if (!format.includes('typescript')) return [3 /*break*/, 6];
3590
+ // TODO: !!!!!!!! Javascript json
3591
+ return [4 /*yield*/, saveFile('ts', spaceTrim__default["default"]("\n import type { PromptbookLibrary, SimplePromptbookLibrary } from '@promptbook/types';\n import type { PromptbookLibrary } from '@promptbook/core';\n\n /**\n * Promptbook library for ".concat(projectName, "\n *\n * @private internal cache for `getPromptbookLibrary`\n */\n let promptbookLibrary: null | SimplePromptbookLibrary = null;\n\n\n /**\n * Get promptbook library for ").concat(projectName, "\n *\n * @returns {PromptbookLibrary} Library of promptbooks for ").concat(projectName, "\n * @generated by `@promptbook/cli`\n */\n export function getPromptbookLibrary(): PromptbookLibrary{\n if(promptbookLibrary===null){\n promptbookLibrary = createLibraryFromJson(...").concat(libraryJsonString, ");\n }\n\n return promptbookLibrary;\n }\n ") + '\n'))];
3592
+ case 5:
3593
+ // TODO: !!!!!!!! Javascript json
3594
+ _b.sent();
3595
+ _b.label = 6;
3596
+ case 6:
3597
+ process.exit(0);
3598
+ return [2 /*return*/];
3599
+ }
3600
+ });
3601
+ });
3602
+ });
3603
+ }
3604
+
3605
+ /**
3606
+ * Add or modify an auto-generated section in a markdown file
3607
+ *
3608
+ * @private within the library
3609
+ */
3610
+ function addAutoGeneratedSection(content, options) {
3611
+ var sectionName = options.sectionName, sectionContent = options.sectionContent;
3612
+ var warningLine = "<!-- \u26A0\uFE0F WARNING: This section was auto-generated -->";
3613
+ var sectionRegex = new RegExp("<!--".concat(sectionName, "-->([\\s\\S]*?)<!--/").concat(sectionName, "-->"), 'g');
3614
+ var sectionMatch = content.match(sectionRegex);
3615
+ if (sectionMatch) {
3616
+ return content.replace(sectionRegex, spaceTrim.spaceTrim(function (block) { return "\n <!--".concat(sectionName, "-->\n ").concat(block(warningLine), "\n ").concat(block(sectionContent), "\n <!--/").concat(sectionName, "-->\n "); }));
3617
+ }
3618
+ var placeForSection = removeContentComments(content).match(/^##.*$/im);
3619
+ if (!placeForSection) {
3620
+ throw new Error("No place where to put the section <!--".concat(sectionName, "-->"));
3621
+ }
3622
+ var _a = __read(placeForSection, 1), heading = _a[0];
3623
+ return content.replace(heading, "<!--".concat(sectionName, "-->\n").concat(warningLine, "\n").concat(sectionContent, "\n<!--/").concat(sectionName, "-->\n\n").concat(heading));
3624
+ }
3625
+
3233
3626
  /* tslint:disable */
3234
3627
  function normalizeTo_camelCase(sentence, __firstLetterCapital) {
3235
3628
  var e_1, _a;