@promptbook/remote-client 0.89.0-3 → 0.89.0-31

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 (50) hide show
  1. package/README.md +9 -7
  2. package/esm/index.es.js +141 -51
  3. package/esm/index.es.js.map +1 -1
  4. package/esm/typings/servers.d.ts +40 -0
  5. package/esm/typings/src/_packages/core.index.d.ts +20 -8
  6. package/esm/typings/src/_packages/remote-client.index.d.ts +6 -8
  7. package/esm/typings/src/_packages/remote-server.index.d.ts +6 -6
  8. package/esm/typings/src/_packages/types.index.d.ts +24 -12
  9. package/esm/typings/src/cli/cli-commands/login.d.ts +0 -1
  10. package/esm/typings/src/cli/common/$addGlobalOptionsToCommand.d.ts +7 -0
  11. package/esm/typings/src/cli/common/$provideLlmToolsForCli.d.ts +28 -0
  12. package/esm/typings/src/cli/test/ptbk.d.ts +1 -1
  13. package/esm/typings/src/commands/EXPECT/expectCommandParser.d.ts +2 -0
  14. package/esm/typings/src/config.d.ts +24 -26
  15. package/esm/typings/src/errors/0-index.d.ts +9 -0
  16. package/esm/typings/src/errors/AuthenticationError.d.ts +9 -0
  17. package/esm/typings/src/errors/PipelineExecutionError.d.ts +1 -1
  18. package/esm/typings/src/errors/PromptbookFetchError.d.ts +9 -0
  19. package/esm/typings/src/errors/WrappedError.d.ts +10 -0
  20. package/esm/typings/src/errors/assertsError.d.ts +11 -0
  21. package/esm/typings/src/execution/PromptbookFetch.d.ts +1 -1
  22. package/esm/typings/src/llm-providers/_common/register/$provideEnvFilename.d.ts +12 -0
  23. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsConfigurationFromEnv.d.ts +2 -8
  24. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsForTestingAndScriptsAndPlayground.d.ts +2 -0
  25. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsForWizzardOrCli.d.ts +45 -1
  26. package/esm/typings/src/llm-providers/_common/register/$provideLlmToolsFromEnv.d.ts +1 -0
  27. package/esm/typings/src/llm-providers/anthropic-claude/AnthropicClaudeExecutionToolsOptions.d.ts +1 -1
  28. package/esm/typings/src/llm-providers/anthropic-claude/register-configuration.d.ts +1 -1
  29. package/esm/typings/src/remote-server/RemoteServer.d.ts +23 -0
  30. package/esm/typings/src/remote-server/openapi-types.d.ts +284 -0
  31. package/esm/typings/src/remote-server/openapi.d.ts +187 -0
  32. package/esm/typings/src/remote-server/socket-types/_subtypes/{PromptbookServer_Identification.d.ts → Identification.d.ts} +3 -3
  33. package/esm/typings/src/remote-server/socket-types/_subtypes/identificationToPromptbookToken.d.ts +11 -0
  34. package/esm/typings/src/remote-server/socket-types/_subtypes/promptbookTokenToIdentification.d.ts +10 -0
  35. package/esm/typings/src/remote-server/socket-types/listModels/PromptbookServer_ListModels_Request.d.ts +2 -2
  36. package/esm/typings/src/remote-server/socket-types/prepare/PromptbookServer_PreparePipeline_Request.d.ts +2 -2
  37. package/esm/typings/src/remote-server/socket-types/prompt/PromptbookServer_Prompt_Request.d.ts +2 -2
  38. package/esm/typings/src/remote-server/startRemoteServer.d.ts +3 -4
  39. package/esm/typings/src/remote-server/types/RemoteClientOptions.d.ts +4 -12
  40. package/esm/typings/src/remote-server/types/RemoteServerOptions.d.ts +84 -9
  41. package/esm/typings/src/scrapers/_common/utils/{scraperFetch.d.ts → promptbookFetch.d.ts} +2 -2
  42. package/esm/typings/src/storage/env-storage/$EnvStorage.d.ts +40 -0
  43. package/esm/typings/src/types/typeAliases.d.ts +19 -0
  44. package/esm/typings/src/utils/organization/TODO_narrow.d.ts +6 -0
  45. package/package.json +7 -3
  46. package/umd/index.umd.js +141 -51
  47. package/umd/index.umd.js.map +1 -1
  48. package/esm/typings/src/cli/test/ptbk2.d.ts +0 -5
  49. package/esm/typings/src/playground/BrjappConnector.d.ts +0 -67
  50. package/esm/typings/src/playground/brjapp-api-schema.d.ts +0 -12879
@@ -1,10 +1,16 @@
1
+ import type { Request, Response } from 'express';
1
2
  import type { Promisable } from 'type-fest';
2
3
  import type { PipelineCollection } from '../../collection/PipelineCollection';
4
+ import { AuthenticationError } from '../../errors/AuthenticationError';
3
5
  import type { CommonToolsOptions } from '../../execution/CommonToolsOptions';
6
+ import type { ExecutionTools } from '../../execution/ExecutionTools';
4
7
  import type { LlmExecutionTools } from '../../execution/LlmExecutionTools';
5
8
  import type { string_app_id } from '../../types/typeAliases';
6
- import type { string_uri } from '../../types/typeAliases';
9
+ import type { string_email } from '../../types/typeAliases';
10
+ import type { string_password } from '../../types/typeAliases';
7
11
  import type { string_user_id } from '../../types/typeAliases';
12
+ import type { ApplicationModeIdentification } from '../socket-types/_subtypes/Identification';
13
+ import type { Identification } from '../socket-types/_subtypes/Identification';
8
14
  /**
9
15
  * @@@
10
16
  *
@@ -16,7 +22,6 @@ import type { string_user_id } from '../../types/typeAliases';
16
22
  *
17
23
  * You can enable both modes at the same time.
18
24
  *
19
- * @public exported from `@promptbook/remote-client`
20
25
  * @public exported from `@promptbook/remote-server`
21
26
  */
22
27
  export type RemoteServerOptions<TCustomOptions> = CommonToolsOptions & {
@@ -25,15 +30,23 @@ export type RemoteServerOptions<TCustomOptions> = CommonToolsOptions & {
25
30
  */
26
31
  readonly port: number;
27
32
  /**
28
- * Root path of the server
33
+ * Creates execution tools the client
29
34
  *
30
- * Note: This is useful when you reverse proxy the server without changing the path
35
+ * This is relevant also in anonymous mode in oposition to `createLlmExecutionTools`
31
36
  *
32
- * @default '/'
33
- * @example '/api/promptbook/'
37
+ * Note: You can provide only some tools and leave the rest to the default ones also llm tools are created by `createLlmExecutionTools`
38
+ * Note: This is useful when you want to provide some custom restrictions for example:
39
+ * - Limit access to certain websites for some users
40
+ * - Bind user-interface tools to email agent
41
+ * - Allow / block script execution
42
+ * - And many more
34
43
  */
35
- readonly rootPath: string_uri;
36
- } & (AnonymousRemoteServerOptions | ApplicationRemoteServerOptions<TCustomOptions> | (AnonymousRemoteServerOptions & ApplicationRemoteServerOptions<TCustomOptions>));
44
+ createExecutionTools?(options: Identification<TCustomOptions>): Promisable<Partial<Omit<ExecutionTools, 'llm'>>>;
45
+ } & ((AnonymousRemoteServerOptions & {
46
+ readonly isApplicationModeAllowed?: false;
47
+ }) | ({
48
+ readonly isAnonymousModeAllowed?: false;
49
+ } & ApplicationRemoteServerOptions<TCustomOptions>) | (AnonymousRemoteServerOptions & ApplicationRemoteServerOptions<TCustomOptions>));
37
50
  export type AnonymousRemoteServerOptions = {
38
51
  /**
39
52
  * Enable anonymous mode
@@ -51,10 +64,22 @@ export type ApplicationRemoteServerOptions<TCustomOptions> = {
51
64
  * This is used to check validity of the prompt to prevent misuse
52
65
  */
53
66
  readonly collection: PipelineCollection;
67
+ /**
68
+ * User tries to login to the server, this function will be called verify the user and return the identification or throw an error
69
+ * This can be also doubled as a function to register the user
70
+ *
71
+ * Note: In most cases, you will return `PromptbookServer_ApplicationIdentification`
72
+ * `PromptbookServer_AnonymousIdentification` is useful only in scenarios when user stores its own api keys on the application server and
73
+ * server acts only as a api key provider
74
+ *
75
+ * Note: In most cases DO NOT THROW `AuthenticationError` but return `isSuccess: false` with message
76
+ * @throws `AuthenticationError` if the user is not allowed to login for example because of invalid credentials
77
+ */
78
+ login(loginRequest: LoginRequest): Promise<LoginResponse<TCustomOptions>>;
54
79
  /**
55
80
  * Creates llm execution tools for each client
56
81
  */
57
- createLlmExecutionTools(options: ApplicationRemoteServerClientOptions<TCustomOptions>): Promisable<LlmExecutionTools>;
82
+ createLlmExecutionTools(options: ApplicationModeIdentification<TCustomOptions>): Promisable<LlmExecutionTools>;
58
83
  };
59
84
  export type ApplicationRemoteServerClientOptions<TCustomOptions> = {
60
85
  /**
@@ -82,6 +107,56 @@ export type ApplicationRemoteServerClientOptions<TCustomOptions> = {
82
107
  */
83
108
  readonly customOptions?: TCustomOptions;
84
109
  };
110
+ /**
111
+ * Login request for the application mode
112
+ */
113
+ export type LoginRequest = {
114
+ /**
115
+ * Identifier of the application you are using
116
+ *
117
+ * Note: This is usefull when you use Promptbook remote server for multiple apps/frontends, if its used just for single app, use here just "app" or "your-app-name"
118
+ */
119
+ readonly appId: string_app_id | null;
120
+ /**
121
+ * Username (for example email) of the user
122
+ */
123
+ readonly username: string_email | string;
124
+ /**
125
+ * Password of the user
126
+ */
127
+ readonly password: string_password;
128
+ /**
129
+ * Request object from express if you want to access some request data for example headers, IP address, etc.
130
+ */
131
+ readonly rawRequest: Request;
132
+ /**
133
+ * Response object from express if you want to add some custom headers.
134
+ *
135
+ * Note: It is not recommended to use this object to send body of the response because it can confuse the client
136
+ */
137
+ readonly rawResponse: Response;
138
+ };
139
+ /**
140
+ * Login response for the application mode
141
+ */
142
+ export type LoginResponse<TCustomOptions> = {
143
+ /**
144
+ * Was the login successful
145
+ */
146
+ readonly isSuccess: boolean;
147
+ /**
148
+ * Message to display to the user, this message is always displayed
149
+ */
150
+ readonly message?: string;
151
+ /**
152
+ * Optional error if the login was not successful
153
+ */
154
+ readonly error?: AuthenticationError;
155
+ /**
156
+ * Identification of the user to be used in the future requests
157
+ */
158
+ readonly identification?: Identification<TCustomOptions>;
159
+ };
85
160
  /**
86
161
  * TODO: Constrain anonymous mode for specific models / providers
87
162
  */
@@ -2,9 +2,9 @@ import type { PromptbookFetch } from '../../../execution/PromptbookFetch';
2
2
  /**
3
3
  * The built-in `fetch' function with a lightweight error handling wrapper as default fetch function used in Promptbook scrapers
4
4
  *
5
- * @private as default `fetch` function used in Promptbook scrapers
5
+ * @public exported from `@promptbook/core`
6
6
  */
7
- export declare const scraperFetch: PromptbookFetch;
7
+ export declare const promptbookFetch: PromptbookFetch;
8
8
  /**
9
9
  * TODO: [🧠] Maybe rename because it is not used only for scrapers but also in `$getCompiledBook`
10
10
  */
@@ -0,0 +1,40 @@
1
+ import type { PromptbookStorage } from '../_common/PromptbookStorage';
2
+ /**
3
+ * Stores data in .env variables
4
+ *
5
+ * Note: `$` is used to indicate that this function is not a pure function - it uses filesystem to access `.env` file and also writes to `process.env`
6
+ *
7
+ * @private within the repository - for CLI utils
8
+ */
9
+ export declare class $EnvStorage<TItem> implements PromptbookStorage<TItem> {
10
+ private envFilename;
11
+ private $provideOrCreateEnvFile;
12
+ private transformKey;
13
+ /**
14
+ * Returns the number of key/value pairs currently present in the list associated with the object.
15
+ */
16
+ get length(): number;
17
+ /**
18
+ * Empties the list associated with the object of all key/value pairs, if there are any.
19
+ */
20
+ clear(): void;
21
+ /**
22
+ * Returns the current value associated with the given key, or null if the given key does not exist in the list associated with the object.
23
+ */
24
+ getItem(key: string): Promise<TItem | null>;
25
+ /**
26
+ * Returns the name of the nth key in the list, or null if n is greater than or equal to the number of key/value pairs in the object.
27
+ */
28
+ key(index: number): string | null;
29
+ /**
30
+ * Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
31
+ */
32
+ setItem(key: string, value: TItem): Promise<void>;
33
+ /**
34
+ * Removes the key/value pair with the given key from the list associated with the object, if a key/value pair with the given key exists.
35
+ */
36
+ removeItem(key: string): void;
37
+ }
38
+ /**
39
+ * TODO: Write file more securely - ensure that there can be no accidental overwriting of existing variables and other content
40
+ */
@@ -325,6 +325,12 @@ export type string_css_selector = string;
325
325
  * For example `"https://collboard.com/9SeSQTupmQHwuSrLi"`
326
326
  */
327
327
  export type string_url = string;
328
+ /**
329
+ * Semantic helper
330
+ *
331
+ * For example `"https://s1.ptbk.io/promptbook"`
332
+ */
333
+ export type string_promptbook_server_url = string;
328
334
  /**
329
335
  * Semantic helper
330
336
  *
@@ -521,6 +527,13 @@ export type string_person_profile = string;
521
527
  * For example `"MIT"`
522
528
  */
523
529
  export type string_license = string;
530
+ /**
531
+ * Semantic helper
532
+ *
533
+ * For example `"Pavol Hejný <pavol@ptbk.io> (https://www.pavolhejny.com/)"`
534
+ * For example `"AI Web, LLC <legal@ptbk.io> (https://www.ptbk.io/)"`
535
+ */
536
+ export type string_legal_entity = string | string_person_profile | string_title;
524
537
  /**
525
538
  * Semantic helper for attributes
526
539
  *
@@ -570,6 +583,12 @@ export type string_postprocessing_function_name = string;
570
583
  export type id = string | number;
571
584
  export type task_id = string;
572
585
  export type string_token = string;
586
+ /**
587
+ * Semantic helper
588
+ *
589
+ * Made by `identificationToPromptbookToken` exported from `@promptbook/core`
590
+ */
591
+ export type string_promptbook_token = string_token;
573
592
  export type string_license_token = string_token;
574
593
  export type string_password = string;
575
594
  export type string_ssh_key = string;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Organizational helper to better mark the place where the more specific type is missing
3
+ *
4
+ * @private within the repository
5
+ */
6
+ export type TODO_narrow<T> = T;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptbook/remote-client",
3
- "version": "0.89.0-3",
3
+ "version": "0.89.0-31",
4
4
  "description": "It's time for a paradigm shift. The future of software in plain English, French or Latin",
5
5
  "private": false,
6
6
  "sideEffects": false,
@@ -43,14 +43,18 @@
43
43
  "url": "https://github.com/webgptorg/promptbook/issues"
44
44
  },
45
45
  "homepage": "https://ptbk.io/",
46
+ "engines": {
47
+ "node": ">=16.0.0",
48
+ "npm": ">=8.0.0"
49
+ },
46
50
  "main": "./umd/index.umd.js",
47
51
  "module": "./esm/index.es.js",
48
52
  "typings": "./esm/typings/src/_packages/remote-client.index.d.ts",
49
53
  "peerDependencies": {
50
- "@promptbook/core": "0.89.0-3"
54
+ "@promptbook/core": "0.89.0-31"
51
55
  },
52
56
  "dependencies": {
53
- "crypto": "^1.0.1",
57
+ "crypto": "1.0.1",
54
58
  "crypto-js": "4.2.0",
55
59
  "papaparse": "5.4.1",
56
60
  "socket.io-client": "4.7.2",
package/umd/index.umd.js CHANGED
@@ -23,7 +23,7 @@
23
23
  * @generated
24
24
  * @see https://github.com/webgptorg/promptbook
25
25
  */
26
- const PROMPTBOOK_ENGINE_VERSION = '0.89.0-3';
26
+ const PROMPTBOOK_ENGINE_VERSION = '0.89.0-31';
27
27
  /**
28
28
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
29
29
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -59,6 +59,19 @@
59
59
  }
60
60
  }
61
61
 
62
+ /**
63
+ * AuthenticationError is thrown from login function which is dependency of remote server
64
+ *
65
+ * @public exported from `@promptbook/core`
66
+ */
67
+ class AuthenticationError extends Error {
68
+ constructor(message) {
69
+ super(message);
70
+ this.name = 'AuthenticationError';
71
+ Object.setPrototypeOf(this, AuthenticationError.prototype);
72
+ }
73
+ }
74
+
62
75
  /**
63
76
  * This error indicates that the pipeline collection cannot be propperly loaded
64
77
  *
@@ -228,7 +241,7 @@
228
241
  }
229
242
  }
230
243
  /**
231
- * TODO: !!!!!! Add id to all errors
244
+ * TODO: [🧠][🌂] Add id to all errors
232
245
  */
233
246
 
234
247
  /**
@@ -257,6 +270,19 @@
257
270
  }
258
271
  }
259
272
 
273
+ /**
274
+ * Error thrown when a fetch request fails
275
+ *
276
+ * @public exported from `@promptbook/core`
277
+ */
278
+ class PromptbookFetchError extends Error {
279
+ constructor(message) {
280
+ super(message);
281
+ this.name = 'PromptbookFetchError';
282
+ Object.setPrototypeOf(this, PromptbookFetchError.prototype);
283
+ }
284
+ }
285
+
260
286
  /**
261
287
  * Returns the same value that is passed as argument.
262
288
  * No side effects.
@@ -297,6 +323,7 @@
297
323
  * @public exported from `@promptbook/core`
298
324
  */
299
325
  const ADMIN_GITHUB_NAME = 'hejny';
326
+ // <- TODO: [🐊] Pick the best claim
300
327
  /**
301
328
  * When the title is not provided, the default title is used
302
329
  *
@@ -349,7 +376,7 @@
349
376
  });
350
377
  /**
351
378
  * Note: [💞] Ignore a discrepancy between file name and entity name
352
- * TODO: [🧠][🧜‍♂️] Maybe join remoteUrl and path into single value
379
+ * TODO: [🧠][🧜‍♂️] Maybe join remoteServerUrl and path into single value
353
380
  */
354
381
 
355
382
  /**
@@ -420,6 +447,26 @@
420
447
  }
421
448
  }
422
449
 
450
+ /**
451
+ * This error type indicates that somewhere in the code non-Error object was thrown and it was wrapped into the `WrappedError`
452
+ *
453
+ * @public exported from `@promptbook/core`
454
+ */
455
+ class WrappedError extends Error {
456
+ constructor(whatWasThrown) {
457
+ const tag = `[🤮]`;
458
+ console.error(tag, whatWasThrown);
459
+ super(spaceTrim.spaceTrim(`
460
+ Non-Error object was thrown
461
+
462
+ Note: Look for ${tag} in the console for more details
463
+ Please report issue on ${ADMIN_EMAIL}
464
+ `));
465
+ this.name = 'WrappedError';
466
+ Object.setPrototypeOf(this, WrappedError.prototype);
467
+ }
468
+ }
469
+
423
470
  /**
424
471
  * Index of all custom errors
425
472
  *
@@ -440,7 +487,10 @@
440
487
  PipelineExecutionError,
441
488
  PipelineLogicError,
442
489
  PipelineUrlError,
490
+ AuthenticationError,
491
+ PromptbookFetchError,
443
492
  UnexpectedError,
493
+ WrappedError,
444
494
  // TODO: [🪑]> VersionMismatchError,
445
495
  };
446
496
  /**
@@ -505,6 +555,35 @@
505
555
  return deserializedError;
506
556
  }
507
557
 
558
+ /**
559
+ * Tests if given string is valid URL.
560
+ *
561
+ * Note: Dataurl are considered perfectly valid.
562
+ * Note: There are two simmilar functions:
563
+ * - `isValidUrl` which tests any URL
564
+ * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
565
+ *
566
+ * @public exported from `@promptbook/utils`
567
+ */
568
+ function isValidUrl(url) {
569
+ if (typeof url !== 'string') {
570
+ return false;
571
+ }
572
+ try {
573
+ if (url.startsWith('blob:')) {
574
+ url = url.replace(/^blob:/, '');
575
+ }
576
+ const urlObject = new URL(url /* because fail is handled */);
577
+ if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
578
+ return false;
579
+ }
580
+ return true;
581
+ }
582
+ catch (error) {
583
+ return false;
584
+ }
585
+ }
586
+
508
587
  /**
509
588
  * Creates a connection to the remote proxy server.
510
589
  *
@@ -513,22 +592,40 @@
513
592
  * @private internal utility function
514
593
  */
515
594
  async function createRemoteClient(options) {
516
- const { remoteUrl, path } = options;
595
+ const { remoteServerUrl } = options;
596
+ if (!isValidUrl(remoteServerUrl)) {
597
+ throw new Error(`Invalid \`remoteServerUrl\`: "${remoteServerUrl}"`);
598
+ }
599
+ const remoteServerUrlParsed = new URL(remoteServerUrl);
600
+ if (remoteServerUrlParsed.pathname !== '/' && remoteServerUrlParsed.pathname !== '') {
601
+ remoteServerUrlParsed.pathname = '/';
602
+ throw new Error(spaceTrim__default["default"]((block) => `
603
+ Remote server requires root url \`/\`
604
+
605
+ You have provided \`remoteServerUrl\`:
606
+ ${block(remoteServerUrl)}
607
+
608
+ But something like this is expected:
609
+ ${block(remoteServerUrlParsed.href)}
610
+
611
+ Note: If you need to run multiple services on the same server, use 3rd or 4th degree subdomain
612
+
613
+ `));
614
+ }
517
615
  return new Promise((resolve, reject) => {
518
- const socket = socket_ioClient.io(remoteUrl, {
616
+ const socket = socket_ioClient.io(remoteServerUrl, {
519
617
  retries: CONNECTION_RETRIES_LIMIT,
520
618
  timeout: CONNECTION_TIMEOUT_MS,
521
- path,
522
- // path: `${this.remoteUrl.pathname}/socket.io`,
523
- transports: [/*'websocket', <- TODO: [🌬] Make websocket transport work */ 'polling'],
619
+ path: '/socket.io',
620
+ transports: ['polling', 'websocket' /*, <- TODO: [🌬] Allow to pass `transports`, add 'webtransport' */],
524
621
  });
525
- // console.log('Connecting to', this.options.remoteUrl.href, { socket });
622
+ // console.log('Connecting to', this.options.remoteServerUrl.href, { socket });
526
623
  socket.on('connect', () => {
527
624
  resolve(socket);
528
625
  });
529
626
  // TODO: [💩] Better timeout handling
530
627
  setTimeout(() => {
531
- reject(new Error(`Timeout while connecting to ${remoteUrl}`));
628
+ reject(new Error(`Timeout while connecting to ${remoteServerUrl}`));
532
629
  }, CONNECTION_TIMEOUT_MS);
533
630
  });
534
631
  }
@@ -654,35 +751,6 @@
654
751
  * TODO: [🍏] Implement for MacOs
655
752
  */
656
753
 
657
- /**
658
- * Tests if given string is valid URL.
659
- *
660
- * Note: Dataurl are considered perfectly valid.
661
- * Note: There are two simmilar functions:
662
- * - `isValidUrl` which tests any URL
663
- * - `isValidPipelineUrl` *(this one)* which tests just promptbook URL
664
- *
665
- * @public exported from `@promptbook/utils`
666
- */
667
- function isValidUrl(url) {
668
- if (typeof url !== 'string') {
669
- return false;
670
- }
671
- try {
672
- if (url.startsWith('blob:')) {
673
- url = url.replace(/^blob:/, '');
674
- }
675
- const urlObject = new URL(url /* because fail is handled */);
676
- if (!['http:', 'https:', 'data:'].includes(urlObject.protocol)) {
677
- return false;
678
- }
679
- return true;
680
- }
681
- catch (error) {
682
- return false;
683
- }
684
- }
685
-
686
754
  const defaultDiacriticsRemovalMap = [
687
755
  {
688
756
  base: 'A',
@@ -1510,6 +1578,34 @@
1510
1578
  },
1511
1579
  };
1512
1580
 
1581
+ /**
1582
+ * Helper used in catch blocks to assert that the error is an instance of `Error`
1583
+ *
1584
+ * @param whatWasThrown Any object that was thrown
1585
+ * @returns Nothing if the error is an instance of `Error`
1586
+ * @throws `WrappedError` or `UnexpectedError` if the error is not standard
1587
+ *
1588
+ * @private within the repository
1589
+ */
1590
+ function assertsError(whatWasThrown) {
1591
+ // Case 1: Handle error which was rethrown as `WrappedError`
1592
+ if (whatWasThrown instanceof WrappedError) {
1593
+ const wrappedError = whatWasThrown;
1594
+ throw wrappedError;
1595
+ }
1596
+ // Case 2: Handle unexpected errors
1597
+ if (whatWasThrown instanceof UnexpectedError) {
1598
+ const unexpectedError = whatWasThrown;
1599
+ throw unexpectedError;
1600
+ }
1601
+ // Case 3: Handle standard errors - keep them up to consumer
1602
+ if (whatWasThrown instanceof Error) {
1603
+ return;
1604
+ }
1605
+ // Case 4: Handle non-standard errors - wrap them into `WrappedError` and throw
1606
+ throw new WrappedError(whatWasThrown);
1607
+ }
1608
+
1513
1609
  /**
1514
1610
  * Units of text measurement
1515
1611
  *
@@ -1590,6 +1686,8 @@
1590
1686
  */
1591
1687
 
1592
1688
  /**
1689
+ import { WrappedError } from '../../errors/WrappedError';
1690
+ import { assertsError } from '../../errors/assertsError';
1593
1691
  * Parses the expect command
1594
1692
  *
1595
1693
  * @see `documentationUrl` for more details
@@ -1681,9 +1779,7 @@
1681
1779
  };
1682
1780
  }
1683
1781
  catch (error) {
1684
- if (!(error instanceof Error)) {
1685
- throw error;
1686
- }
1782
+ assertsError(error);
1687
1783
  throw new ParseError(spaceTrim__default["default"]((block) => `
1688
1784
  Invalid FORMAT command
1689
1785
  ${block(error.message)}:
@@ -1840,9 +1936,7 @@
1840
1936
  return true;
1841
1937
  }
1842
1938
  catch (error) {
1843
- if (!(error instanceof Error)) {
1844
- throw error;
1845
- }
1939
+ assertsError(error);
1846
1940
  if (error.message.includes('Unexpected token')) {
1847
1941
  return false;
1848
1942
  }
@@ -2160,9 +2254,7 @@
2160
2254
  JSON.stringify(value); // <- TODO: [0]
2161
2255
  }
2162
2256
  catch (error) {
2163
- if (!(error instanceof Error)) {
2164
- throw error;
2165
- }
2257
+ assertsError(error);
2166
2258
  throw new UnexpectedError(spaceTrim__default["default"]((block) => `
2167
2259
  \`${name}\` is not serializable
2168
2260
 
@@ -4817,9 +4909,7 @@
4817
4909
  }
4818
4910
  }
4819
4911
  catch (error) {
4820
- if (!(error instanceof Error)) {
4821
- throw error;
4822
- }
4912
+ assertsError(error);
4823
4913
  throw new ParseError(spaceTrim.spaceTrim((block) => `
4824
4914
  Can not extract variables from the script
4825
4915
  ${block(error.stack || error.message)}