All files / src/tracker/promise definition.ts

0% Statements 0/0
0% Branches 0/0
0% Functions 0/0
0% Lines 0/0

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import type { Simplify } from 'type-fest';
 
import type { Logger } from '../../logger/definition.ts';
import type { OnEvent } from '../../notifier/definition.ts';
 
/**
 * A tracker for monitoring promises, providing centralized waiting, event notifications, and timing metrics.
 *
 * This tracker is designed for scenarios where you need to coordinate multiple unrelated promises - such as a server
 * waiting for various background operations to complete before shutdown, or monitoring promise performance across
 * different parts of an application.
 *
 * The tracker maintains an internal set of unsettled promises and provides real-time notifications when promises
 * resolve or reject. It supports both direct promises and promise suppliers (functions that return promises).
 *
 * @example Basic usage with direct promises
 *
 * ```ts
 * import { trackPromises } from 'emitnlog/tracker';
 *
 * const tracker = trackPromises();
 *
 * // Track some promises
 * const result1 = tracker.track(fetchUser(id), 'fetch-user');
 * const result2 = tracker.track(saveData(data), 'save-data');
 *
 * // Wait for all tracked promises to settle
 * await tracker.wait();
 * console.log('All operations complete');
 * ```
 *
 * @example Server shutdown coordination
 *
 * ```ts
 * import { trackPromises } from 'emitnlog/tracker';
 * import { withTimeout } from 'emitnlog/utils';
 *
 * const tracker = trackPromises({ logger: serverLogger });
 *
 * // Track various background operations
 * tracker.track(dbConnection.close(), 'db-close');
 * tracker.track(cache.flush(), 'cache-flush');
 * tracker.track(analytics.send(), 'analytics-send');
 *
 * // Graceful shutdown with timeout
 * await withTimeout(tracker.wait(), 5000);
 * ```
 *
 * @example Using promise suppliers
 *
 * ```ts
 * import { trackPromises } from 'emitnlog/tracker';
 *
 * const tracker = trackPromises();
 *
 * // Timing starts when the supplier is called, not when track() is called
 * const result = await tracker.track(async () => {
 *   await expensiveAsyncOperation1();
 *   await expensiveAsyncOperation2();
 * }, 'expensive-combined-op');
 * ```
 *
 * @example Monitoring promise performance
 *
 * ```ts
 * import { trackPromises } from 'emitnlog/tracker';
 *
 * const tracker = trackPromises();
 *
 * tracker.onSettled((event) => {
 *   console.log(`${event.label}: ${event.duration}ms ${event.rejected ? 'FAILED' : 'SUCCESS'}`);
 * });
 *
 * tracker.track(apiCall(), 'api-call');
 * ```
 */
export type PromiseTracker = {
  /**
   * The number of currently unsettled tracked promises.
   *
   * Returns 0 after `wait()` completes and no additional promises have been tracked.
   *
   * @example
   *
   * ```ts
   * import { trackPromises } from 'emitnlog/tracker';
   *
   * const tracker = trackPromises();
   * console.log(tracker.size); // 0
   *
   * tracker.track(slowOperation);
   * console.log(tracker.size); // 1
   *
   * await tracker.wait();
   * console.log(tracker.size); // 0
   * ```
   */
  readonly size: number;
 
  /**
   * Tracks the lifecycle of a promise or promise supplier, returning the same promise for chaining.
   *
   * Accepts either a direct promise or a function that returns a promise (supplier). Using a supplier provides more
   * accurate timing measurements since the duration is calculated from when the supplier is invoked rather than when
   * `track()` is called.
   *
   * The tracked promise is automatically removed from the tracker when it settles (resolves or rejects). Labels are
   * optional but recommended for debugging and monitoring purposes.
   *
   * @example Tracking direct promises
   *
   * ```ts
   * import { trackPromises } from 'emitnlog/tracker';
   *
   * const tracker = trackPromises();
   * const result = await tracker.track(fetch('/api/data'), 'api-fetch');
   * ```
   *
   * @example Tracking promise suppliers for accurate timing
   *
   * ```ts
   * import { trackPromises } from 'emitnlog/tracker';
   *
   * const tracker = trackPromises();
   * const result = await tracker.track(() => processLargeDataset(data), 'data-processing');
   * ```
   *
   * @param promise A promise to track, or a function that returns a promise (supplier)
   * @param label Optional label for identification in events and logs
   * @returns The same promise for chaining
   */
  track<T>(promise: Promise<T> | (() => Promise<T>)): Promise<T>;
  track<T>(label: string, promise: Promise<T> | (() => Promise<T>)): Promise<T>;
 
  /**
   * Waits for all currently tracked promises to settle (resolve or reject).
   *
   * This method takes a snapshot of currently tracked promises and waits for them to complete. Promises that are
   * tracked after `wait()` begins are not included in the current wait operation - this allows for predictable
   * coordination patterns.
   *
   * Calling `wait()` when no promises are tracked returns immediately. This can be used as a way to "clear" or verify
   * the tracker state.
   *
   * Consider using `withTimeout()` utility to prevent indefinite waiting in production scenarios.
   *
   * @example Server shutdown coordination
   *
   * ```ts
   * import { trackPromises } from 'emitnlog/tracker';
   *
   * const tracker = trackPromises();
   *
   * // Start background operations
   * tracker.track(backgroundJob1());
   * tracker.track(backgroundJob2());
   *
   * // Wait for current operations to complete
   * await tracker.wait();
   *
   * // Any new promises tracked during wait() are not included above
   * tracker.track(newOperation()); // This won't block the previous wait()
   * ```
   *
   * @example With timeout protection
   *
   * ```ts
   * import { trackPromises } from 'emitnlog/tracker';
   * import { withTimeout } from 'emitnlog/utils';
   *
   * const tracker = trackPromises();
   * tracker.track(longRunningOperation());
   *
   * // Wait maximum 30 seconds
   * await withTimeout(tracker.wait(), 30000);
   * ```
   *
   * @example Clearing/verifying tracker state
   *
   * ```ts
   * const tracker = trackPromises();
   *
   * // This returns immediately if no promises are tracked
   * await tracker.wait(); // Effectively a no-op that can verify empty state
   * ```
   *
   * @returns A promise that resolves when all tracked promises have settled
   */
  readonly wait: () => Promise<void>;
 
  /**
   * Registers event listeners for promise settlement notifications.
   *
   * Events are emitted in real-time when tracked promises resolve or reject, providing detailed information about
   * timing, results, and labels. Multiple listeners can be registered and will all receive events.
   *
   * The event data includes duration measurements, optional labels, success/failure status, and result values (for
   * successful resolutions). This enables performance monitoring, debugging, and custom logging.
   *
   * @example Performance monitoring
   *
   * ```ts
   * import { trackPromises } from 'emitnlog/tracker';
   *
   * const tracker = trackPromises();
   *
   * tracker.onSettled((event) => {
   *   const status = event.rejected ? 'FAILED' : 'SUCCESS';
   *   const label = event.label ?? 'unlabeled';
   *   console.log(`${label}: ${event.duration}ms - ${status}`);
   * });
   * ```
   *
   * @example Custom metrics collection
   *
   * ```ts
   * const metrics = { total: 0, failed: 0, avgDuration: 0 };
   *
   * tracker.onSettled((event) => {
   *   metrics.total++;
   *   if (event.rejected) metrics.failed++;
   *   metrics.avgDuration = (metrics.avgDuration + event.duration) / metrics.total;
   * });
   * ```
   *
   * @param listener Function called when any tracked promise settles
   */
  readonly onSettled: OnEvent<PromiseSettledEvent>;
};
 
/**
 * A specialized implementation of the Promise Tracker that (transiently) caches async operations by ID, ensuring each
 * operation runs only once _while_ its returned promise is not settled.
 *
 * PromiseHolder is ideal when you need to prevent duplicate expensive operations, such as API calls, database queries,
 * or file system operations. Unlike PromiseTracker which focuses on coordination and monitoring, PromiseHolder
 * emphasizes operation deduplication and caching.
 *
 * The holder maintains a cache of ongoing operations by their unique IDs - in other words, the cache happens while the
 * promise is not settled. When the same ID is requested multiple times, the holder returns the same promise, ensuring
 * the underlying operation executes only once. The cache is automatically cleaned up when operations complete.
 *
 * When to use PromiseHolder vs PromiseTracker:
 *
 * - Use PromiseHolder for caching expensive operations that might be requested multiple times
 * - Use PromiseTracker for coordinating multiple different operations (like shutdown procedures), when there is no reason
 *   to identify an operation, or to track actual promises instead of operations.
 *
 * @example Basic caching of API calls
 *
 * ```ts
 * import { holdPromises } from 'emitnlog/tracker';
 *
 * const holder = holdPromises();
 *
 * // First call executes the API request
 * const user1 = holder.track('user-123', () => fetchUserFromAPI(123));
 *
 * // Second call returns the same promise, no duplicate API call
 * const user2 = holder.track('user-123', () => fetchUserFromAPI(123));
 *
 * console.log(user1 === user2); // true - same promise instance
 * ```
 *
 * @example Database query deduplication
 *
 * ```ts
 * import { holdPromises } from 'emitnlog/tracker';
 *
 * const queryHolder = holdPromises({ logger: dbLogger });
 *
 * // Multiple components request the same data simultaneously
 * const results = await Promise.all([
 *   queryHolder.track('product-456', () => db.query('SELECT * FROM products WHERE id = 456')),
 *   queryHolder.track('product-456', () => db.query('SELECT * FROM products WHERE id = 456')),
 *   queryHolder.track('product-456', () => db.query('SELECT * FROM products WHERE id = 456')),
 * ]);
 * // Only one database query was executed, but all components get the result
 * ```
 *
 * @example File system operation caching
 *
 * ```ts
 * import { holdPromises } from 'emitnlog/tracker';
 *
 * const fileHolder = holdPromises();
 *
 * // Cache expensive file operations
 * const processFile = async (filename: string) => {
 *   return fileHolder.track(`process-${filename}`, async () => {
 *     const content = await fs.readFile(filename, 'utf8');
 *     return processLargeFile(content); // Expensive operation
 *   });
 * };
 *
 * // Multiple calls to processFile with same filename will reuse the result
 * const result1 = await processFile('large-data.json');
 * const result2 = await processFile('large-data.json'); // Uses cached promise
 * ```
 *
 * @example Configuration loading with fallback
 *
 * ```ts
 * import { holdPromises } from 'emitnlog/tracker';
 *
 * const configHolder = holdPromises();
 *
 * const getConfig = (env: string) => {
 *   return configHolder.track(`config-${env}`, async () => {
 *     try {
 *       return await loadConfigFromRemote(env);
 *     } catch {
 *       return loadDefaultConfig();
 *     }
 *   });
 * };
 * ```
 */
export type PromiseHolder = Simplify<
  Omit<PromiseTracker, 'track' | 'wait'> & {
    /**
     * Caches and tracks an async operation by its unique ID, ensuring it runs only once per ID.
     *
     * When called with an ID that's already cached, returns the existing promise without executing the supplier again.
     * When called with a new ID, executes the supplier function and caches the resulting promise.
     *
     * The cache is automatically cleaned up when the operation settles (resolves or rejects), allowing the same ID to
     * be used again for future operations.
     *
     * Operations are tracked with the same monitoring capabilities as PromiseTracker, including timing measurements and
     * event notifications.
     *
     * Clients are expected to ensure that the id is unique based on the nature of the operation: for example, in some
     * cases the id may refer to operation itself, in others it may need to be augmented with argument information.
     *
     * @example API call deduplication
     *
     * ```ts
     * import { holdPromises } from 'emitnlog/tracker';
     *
     * const holder = holdPromises();
     *
     * // These calls happen simultaneously from different parts of the app
     * const [result1, result2, result3] = await Promise.all([
     *   holder.track('user-data', () => fetchUserProfile()),
     *   holder.track('user-data', () => fetchUserProfile()),
     *   holder.track('user-data', () => fetchUserProfile()),
     * ]);
     * // Only one fetchUserProfile() call was made, all get the same result
     * ```
     *
     * @example Error handling with caching
     *
     * ```ts
     * import { holdPromises } from 'emitnlog/tracker';
     *
     * const holder = holdPromises();
     *
     * try {
     *   const result = await holder.track('risky-op', () => riskyAsyncOperation());
     *   console.log('Success:', result);
     * } catch (error) {
     *   console.log('Failed:', error);
     *   // The failed operation is removed from cache, so retry is possible
     *
     *   // Later retry with same ID works
     *   const retryResult = await holder.track('risky-op', () => riskyAsyncOperation());
     * }
     * ```
     *
     * @param id Unique identifier for the operation. Operations with the same ID will be deduplicated.
     * @param supplier Function that returns the promise to execute. Only called once per unique ID.
     * @returns The promise from the supplier (cached or fresh)
     */
    track<T>(id: string, supplier: () => Promise<T>): Promise<T>;
 
    /**
     * Checks if an operation with the given ID is currently cached (ongoing).
     *
     * Returns `true` if a promise with the specified ID is currently in progress. Once the operation completes
     * (resolves or rejects), the cache entry is automatically removed and this method will return `false`.
     *
     * This method is useful for conditional logic, debugging, or monitoring cache state without triggering any
     * operations.
     *
     * @example Conditional operation execution
     *
     * ```ts
     * import { holdPromises } from 'emitnlog/tracker';
     *
     * const holder = holdPromises();
     *
     * if (!holder.has('expensive-calc')) {
     *   console.log('Starting expensive calculation...');
     * } else {
     *   console.log('Calculation already in progress...');
     * }
     *
     * const result = await holder.track('expensive-calc', () => performCalculation());
     * ```
     *
     * @example Cache monitoring
     *
     * ```ts
     * import { holdPromises } from 'emitnlog/tracker';
     *
     * const holder = holdPromises();
     *
     * // Start some operations
     * holder.track('op1', () => longRunningTask1());
     * holder.track('op2', () => longRunningTask2());
     *
     * console.log(`Active operations: op1=${holder.has('op1')}, op2=${holder.has('op2')}`);
     * ```
     *
     * @param id The operation ID to check
     * @returns True if the operation is currently cached/ongoing, false otherwise
     */
    readonly has: (id: string) => boolean;
 
    /**
     * Waits for currently tracked promises to settle (resolve or reject). If no `id` is specified, all promises are
     * waited, otherwise only the identified promises are waited - ids that don't match tracked promises are ignored.
     *
     * This method takes a snapshot of currently tracked promises and waits for them to complete. Promises that are
     * tracked after `wait()` begins are not included in the current wait operation - this allows for predictable
     * coordination patterns.
     *
     * Calling `wait()` when no promises are tracked returns immediately. This can be used as a way to "clear" or verify
     * the tracker state.
     *
     * Consider using `withTimeout()` utility to prevent indefinite waiting in production scenarios.
     *
     * @example Server shutdown coordination
     *
     * ```ts
     * import { trackPromises } from 'emitnlog/tracker';
     *
     * const tracker = trackPromises();
     *
     * // Start background operations
     * tracker.track('op1', () => backgroundJob1());
     * tracker.track('op2', () => backgroundJob2());
     *
     * // Wait for all current operations to complete
     * await tracker.wait();
     *
     * // Any new promises tracked during wait() are not included above
     * tracker.track('op3', () => newOperation()); // This won't block the previous wait()
     * ```
     *
     * @example With timeout protection and specific ids
     *
     * ```ts
     * import { trackPromises } from 'emitnlog/tracker';
     * import { withTimeout } from 'emitnlog/utils';
     *
     * const tracker = trackPromises();
     * tracker.track('op1', () => longRunningTask1());
     * tracker.track('op2', () => longRunningTask2());
     *
     * // Wait maximum 30 seconds for 'op2'
     * await withTimeout(tracker.wait('op2'), 30000);
     * ```
     *
     * @example Clearing/verifying tracker state
     *
     * ```ts
     * const tracker = trackPromises();
     *
     * // This returns immediately if no promises are tracked
     * await tracker.wait(); // Effectively a no-op that can verify empty state
     * ```
     *
     * @returns A promise that resolves when all tracked promises have settled
     */
    readonly wait: (...ids: readonly string[]) => Promise<void>;
  }
>;
 
/**
 * A persistent caching implementation of PromiseHolder that retains settled promises until manually cleared.
 *
 * PromiseVault provides long-term caching of expensive operations that don't change frequently, such as configuration
 * loading, initialization routines, or API calls for static data. Unlike PromiseHolder which automatically clears
 * cached promises when they settle, PromiseVault maintains the cache indefinitely until explicitly cleared.
 *
 * This is particularly useful for:
 *
 * - Application initialization that should happen only once
 * - Configuration loading that remains valid for the application lifetime
 * - Expensive computations with results that don't change
 * - API calls for static or rarely-changing data
 *
 * **Cache Management:**
 *
 * - Promises remain cached even after settlement (success or failure)
 * - Manual control via `clear()` to empty entire cache or `forget()` for specific entries
 * - Failed operations can be automatically cleared with `forgetOnRejection` option, or manually with `forget()`
 *
 * **Comparison with other promise utilities:**
 *
 * - `PromiseTracker`: Coordination and monitoring, no caching
 * - `PromiseHolder`: Transient caching during promise lifecycle only
 * - `PromiseVault`: Persistent caching with manual lifecycle control
 *
 * @example Application initialization caching
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * const initVault = vaultPromises({ logger: appLogger });
 *
 * // These expensive operations happen only once, even across multiple calls
 * const initializeDatabase = () => initVault.track('database', () => setupDatabaseConnection());
 * const loadConfiguration = () => initVault.track('config', () => fetchAppConfiguration());
 * const setupAuthentication = () => initVault.track('auth', () => initializeAuthSystem());
 *
 * // Multiple components can safely call these - only first call executes
 * await Promise.all([initializeDatabase(), loadConfiguration(), setupAuthentication()]);
 *
 * // Later in the application - these return cached results instantly
 * const config = await loadConfiguration(); // Uses cached promise
 * const dbConnection = await initializeDatabase(); // Uses cached promise
 * ```
 *
 * @example Configuration management with refresh capability
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * const configVault = vaultPromises({ logger: configLogger });
 *
 * const getConfig = (environment: string) => {
 *   return configVault.track(`config-${environment}`, async () => {
 *     console.log(`Loading config for ${environment}...`);
 *     return await fetchConfigFromRemote(environment);
 *   });
 * };
 *
 * // Initial load
 * const config1 = await getConfig('production');
 *
 * // Subsequent calls use cached result
 * const config2 = await getConfig('production'); // No network call
 *
 * // Force refresh when needed
 * configVault.forget('config-production');
 * const freshConfig = await getConfig('production'); // New network call
 * ```
 *
 * @example Static data caching with selective invalidation
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * const dataVault = vaultPromises();
 *
 * // Cache expensive computations or API calls
 * const getStaticData = (dataType: string) => {
 *   return dataVault.track(`static-${dataType}`, async () => {
 *     return await fetchStaticDataFromAPI(dataType);
 *   });
 * };
 *
 * // Load various static data - cached indefinitely
 * const countries = await getStaticData('countries');
 * const currencies = await getStaticData('currencies');
 * const timezones = await getStaticData('timezones');
 *
 * // Invalidate specific cache entries when data changes
 * dataVault.forget('static-countries'); // Only countries will be re-fetched
 *
 * // Or clear all cached data
 * dataVault.clear();
 * ```
 *
 * @example Resource loading with error handling
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * const resourceVault = vaultPromises({ logger: resourceLogger });
 *
 * const loadResource = async (resourceId: string) => {
 *   return resourceVault.track(`resource-${resourceId}`, async () => {
 *     const response = await fetch(`/api/resources/${resourceId}`);
 *     if (!response.ok) {
 *       throw new Error(`Failed to load resource: ${response.status}`);
 *     }
 *     return response.json();
 *   });
 * };
 *
 * // Handle errors and retries
 * try {
 *   const resource = await loadResource('important-data');
 * } catch (error) {
 *   console.error('Resource load failed:', error);
 *
 *   // Remove failed attempt from cache to allow retry
 *   resourceVault.forget('resource-important-data');
 *
 *   // Retry with fresh attempt
 *   const resource = await loadResource('important-data');
 * }
 * ```
 *
 * @example Automatic retry on failure with forgetOnRejection
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * // Vault that automatically clears failed operations for retry
 * const retryVault = vaultPromises({ logger: apiLogger, forgetOnRejection: true });
 *
 * const fetchWithRetry = async (url: string) => {
 *   return retryVault.track(`fetch-${url}`, async () => {
 *     const response = await fetch(url);
 *     if (!response.ok) {
 *       throw new Error(`HTTP ${response.status}: ${response.statusText}`);
 *     }
 *     return response.json();
 *   });
 * };
 *
 * // First call fails and is automatically removed from cache
 * try {
 *   await fetchWithRetry('/api/data');
 * } catch (error) {
 *   console.log('First attempt failed');
 * }
 *
 * // Second call executes fresh attempt (not cached)
 * try {
 *   const data = await fetchWithRetry('/api/data'); // New attempt
 *   console.log('Retry succeeded:', data);
 * } catch (error) {
 *   console.log('Retry also failed');
 * }
 * ```
 *
 * @example Mixed caching strategies
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * // Cache successful results but allow retries for failures
 * const smartVault = vaultPromises({ forgetOnRejection: true });
 *
 * const getConfigWithFallback = async (env: string) => {
 *   return smartVault.track(`config-${env}`, async () => {
 *     try {
 *       // Try remote config first
 *       return await fetchRemoteConfig(env);
 *     } catch (remoteError) {
 *       // Fall back to local config
 *       console.warn(`Remote config failed, using local: ${remoteError.message}`);
 *       return await loadLocalConfig(env);
 *     }
 *   });
 * };
 *
 * // If remote fails, operation throws and is cleared from cache
 * // If local succeeds, result is cached permanently
 * const config = await getConfigWithFallback('production');
 * ```
 *
 * @example Performance monitoring with persistent caching
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * const performanceVault = vaultPromises({ logger: perfLogger });
 *
 * // Monitor cache hit rates
 * const getCacheStats = () => {
 *   return {
 *     size: performanceVault.size,
 *     entries: Array.from({ length: performanceVault.size }).map((_, i) => `entry-${i}`),
 *   };
 * };
 *
 * // Track performance of cached operations
 * performanceVault.onSettled((event) => {
 *   const cacheHit = event.duration < 10; // Cached results are very fast
 *   console.log(`${event.label}: ${event.duration}ms (${cacheHit ? 'CACHE HIT' : 'CACHE MISS'})`);
 * });
 *
 * const expensiveOperation = (id: string) => {
 *   return performanceVault.track(`operation-${id}`, async () => {
 *     // Simulate expensive operation
 *     await new Promise((resolve) => setTimeout(resolve, 1000));
 *     return `Result for ${id}`;
 *   });
 * };
 *
 * // First call: cache miss, slow
 * await expensiveOperation('test'); // ~1000ms
 *
 * // Second call: cache hit, fast
 * await expensiveOperation('test'); // ~1ms
 * ```
 *
 * @example Graceful cache invalidation patterns
 *
 * ```ts
 * import { vaultPromises } from 'emitnlog/tracker';
 *
 * const cacheVault = vaultPromises();
 *
 * // Time-based invalidation
 * const cacheTimestamps = new Map<string, number>();
 * const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
 *
 * const getWithTTL = async (key: string, fetcher: () => Promise<any>) => {
 *   const now = Date.now();
 *   const timestamp = cacheTimestamps.get(key);
 *
 *   if (timestamp && now - timestamp > CACHE_TTL) {
 *     cacheVault.forget(key);
 *     cacheTimestamps.delete(key);
 *   }
 *
 *   if (!cacheVault.has(key)) {
 *     cacheTimestamps.set(key, now);
 *   }
 *
 *   return cacheVault.track(key, fetcher);
 * };
 *
 * // Usage with automatic TTL
 * const data = await getWithTTL('user-settings', () => fetchUserSettings());
 * ```
 */
export type PromiseVault = PromiseHolder & {
  /**
   * Caches and tracks an async operation with configurable persistence behavior.
   *
   * Extends PromiseHolder's caching functionality with optional per-operation control over cache persistence. By
   * default, promises remain cached even after settlement (standard PromiseVault behavior). When the `forget` option is
   * enabled, the operation behaves like PromiseHolder - automatically clearing the cache entry when the promise
   * settles.
   *
   * This provides fine-grained control over caching strategy, allowing you to mix persistent and transient caching
   * within the same vault instance based on the specific needs of each operation.
   *
   * @example Default persistent caching
   *
   * ```ts
   * import { vaultPromises } from 'emitnlog/tracker';
   *
   * const vault = vaultPromises();
   *
   * // Standard behavior - promise cached indefinitely
   * await vault.track('config', () => loadConfiguration());
   * await vault.track('config', () => loadConfiguration()); // Uses cached promise
   * ```
   *
   * @example Transient caching with forget option
   *
   * ```ts
   * import { vaultPromises } from 'emitnlog/tracker';
   *
   * const vault = vaultPromises();
   *
   * // First call executes and caches temporarily
   * await vault.track('temp-data', () => fetchTemporaryData(), { forget: true });
   *
   * // Second call executes again (cache was cleared after first completion)
   * await vault.track('temp-data', () => fetchTemporaryData(), { forget: true });
   * ```
   *
   * @example Mixed caching strategies
   *
   * ```ts
   * import { vaultPromises } from 'emitnlog/tracker';
   *
   * const vault = vaultPromises();
   *
   * // Persistent cache for stable configuration
   * const config = await vault.track('app-config', () => loadAppConfig());
   *
   * // Transient cache for time-sensitive data
   * const liveData = await vault.track('live-feed', () => fetchLiveFeed(), { forget: true });
   *
   * // User-specific data that should be cached persistently
   * const userData = await vault.track(`user-${userId}`, () => fetchUserData(userId));
   *
   * // Temporary computations that shouldn't persist
   * const tempResult = await vault.track(`calc-${requestId}`, () => performCalculation(), { forget: true });
   * ```
   *
   * @example Dynamic cache behavior based on conditions
   *
   * ```ts
   * import { vaultPromises } from 'emitnlog/tracker';
   *
   * const vault = vaultPromises();
   *
   * const fetchData = async (id: string, isTemporary: boolean) => {
   *   return vault.track(`data-${id}`, () => expensiveFetchOperation(id), { forget: isTemporary });
   * };
   *
   * // Persistent caching for important data
   * await fetchData('critical-config', false);
   *
   * // Transient caching for temporary requests
   * await fetchData('temp-analysis', true);
   * ```
   *
   * @example Session-based caching with cleanup
   *
   * ```ts
   * import { vaultPromises } from 'emitnlog/tracker';
   *
   * const vault = vaultPromises();
   *
   * const getSessionData = async (sessionId: string, persistent: boolean = false) => {
   *   return vault.track(`session-${sessionId}`, () => loadSessionFromDatabase(sessionId), {
   *     forget: !persistent,
   *   });
   * };
   *
   * // Short-lived session data (cleared after use)
   * await getSessionData('temp-session-123', false);
   *
   * // Long-lived session data (cached until manual cleanup)
   * await getSessionData('permanent-session-456', true);
   * ```
   *
   * @example Error handling with different cache strategies
   *
   * ```ts
   * import { vaultPromises } from 'emitnlog/tracker';
   *
   * const vault = vaultPromises();
   *
   * const robustFetch = async (url: string, cacheFailures: boolean = false) => {
   *   try {
   *     return await vault.track(
   *       `fetch-${url}`,
   *       async () => {
   *         const response = await fetch(url);
   *         if (!response.ok) throw new Error(`HTTP ${response.status}`);
   *         return response.json();
   *       },
   *       { forget: !cacheFailures },
   *     );
   *   } catch (error) {
   *     if (!cacheFailures) {
   *       // For transient operations, failed attempts are automatically cleared
   *       console.log('Failed attempt cleared, retry available');
   *     } else {
   *       // For persistent operations, manually clear to allow retry
   *       vault.forget(`fetch-${url}`);
   *       console.log('Failed attempt manually cleared');
   *     }
   *     throw error;
   *   }
   * };
   *
   * // Don't cache failures - automatic retry capability
   * await robustFetch('/api/temporary-data', false);
   *
   * // Cache everything including failures - manual retry control
   * await robustFetch('/api/critical-data', true);
   * ```
   *
   * @param id Unique identifier for the operation. Operations with the same ID will be deduplicated.
   * @param supplier Function that returns the promise to execute. Only called once per unique ID (unless cache is
   *   cleared).
   * @param options Configuration options for this specific operation
   * @param options.forget When true, automatically removes the cached promise when it settles, making this operation
   *   behave like PromiseHolder. When false or undefined (default), uses standard PromiseVault persistence behavior.
   * @returns The promise from the supplier (cached or fresh)
   */
  track<T>(id: string, supplier: () => Promise<T>, options?: { forget?: boolean }): Promise<T>;
 
  /**
   * Clears all cached promises from the vault.
   *
   * After calling this method, all subsequent `track()` calls will execute their suppliers regardless of whether they
   * were previously cached. This is useful for global cache invalidation or cleanup scenarios.
   *
   * @example Global cache reset
   *
   * ```ts
   * import { vaultPromises } from 'emitnlog/tracker';
   *
   * const vault = vaultPromises();
   *
   * // Cache some operations
   * await vault.track('config', () => loadConfig());
   * await vault.track('data', () => loadData());
   *
   * console.log(vault.size); // 2
   *
   * // Clear all cached entries
   * vault.clear();
   *
   * console.log(vault.size); // 0
   *
   * // Next calls will execute suppliers again
   * await vault.track('config', () => loadConfig()); // Executes loadConfig()
   * ```
   */
  clear(): void;
 
  /**
   * Removes a specific cached promise from the vault.
   *
   * This allows selective invalidation of cache entries. The next `track()` call with the same ID will execute the
   * supplier again instead of returning the cached promise.
   *
   * @example Selective cache invalidation
   *
   * ```ts
   * import { vaultPromises } from 'emitnlog/tracker';
   *
   * const vault = vaultPromises();
   *
   * // Cache some operations
   * await vault.track('user-123', () => fetchUser(123));
   * await vault.track('user-456', () => fetchUser(456));
   *
   * // Invalidate specific user
   * const wasRemoved = vault.forget('user-123');
   * console.log(wasRemoved); // true
   *
   * // user-123 will be fetched again, user-456 uses cached version
   * await vault.track('user-123', () => fetchUser(123)); // Executes fetchUser(123)
   * await vault.track('user-456', () => fetchUser(456)); // Uses cached promise
   * ```
   *
   * @example Error recovery
   *
   * ```ts
   * import { vaultPromises } from 'emitnlog/tracker';
   *
   * const vault = vaultPromises();
   *
   * try {
   *   await vault.track('risky-op', () => riskyOperation());
   * } catch (error) {
   *   // Remove failed operation from cache to allow retry
   *   vault.forget('risky-op');
   *
   *   // Retry will execute the operation again
   *   await vault.track('risky-op', () => riskyOperation());
   * }
   * ```
   *
   * @param id The ID of the cached promise to remove
   * @returns True if the entry was found and removed, false if it wasn't in the cache
   */
  forget(id: string): boolean;
};
 
/**
 * Event data emitted when a tracked promise settles (resolves or rejects).
 *
 * This event provides comprehensive information about the promise lifecycle, including timing data, optional labeling,
 * success/failure status, and result values. The duration measurement starts from when `track()` is invoked, or more
 * accurately, from when a promise supplier function is called.
 */
export type PromiseSettledEvent = {
  /**
   * Optional label provided when tracking the promise.
   *
   * Labels help identify specific promises in logs and event handlers, especially useful when tracking multiple
   * promises of the same type.
   */
  readonly label?: string;
 
  /**
   * Duration of the promise lifecycle in milliseconds.
   *
   * For direct promises, timing starts when `track()` is called. For promise suppliers (functions), timing starts when
   * the supplier function is invoked, providing more accurate measurements of the actual async operation duration.
   *
   * @example
   *
   * ```ts
   * // Less accurate - includes time between track() call and promise creation
   * tracker.track(someAsyncFunction(), 'operation');
   *
   * // More accurate - measures only the async operation itself
   * tracker.track(() => someAsyncFunction(), 'operation');
   * ```
   */
  readonly duration: number;
 
  /**
   * Indicates whether the promise was rejected.
   *
   * When `true`, the promise rejected with an error. When `false` or undefined, the promise resolved successfully.
   */
  readonly rejected?: boolean;
 
  /**
   * The result of the promise, either the resolved or rejected value.
   */
  readonly result?: unknown;
};
 
/**
 * Options for configuring a PromiseTracker.
 */
export type PromiseTrackerOptions = { readonly logger?: Logger };
 
/**
 * Options for configuring a PromiseVault.
 */
export type PromiseVaultOptions = { readonly forgetOnRejection?: boolean } & PromiseTrackerOptions;