forgeframe 1.0.0

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.
@@ -0,0 +1,122 @@
1
+ /**
2
+ * A function that performs cleanup, optionally returning a Promise for async cleanup.
3
+ * @internal
4
+ */
5
+ type CleanupTask = () => void | Promise<void>;
6
+ /**
7
+ * Manages cleanup tasks for proper resource disposal in a LIFO (Last-In-First-Out) order.
8
+ *
9
+ * @remarks
10
+ * The CleanupManager provides a centralized way to register and execute cleanup tasks,
11
+ * ensuring resources are properly disposed of when components or processes are torn down.
12
+ * Tasks are executed in reverse registration order (LIFO), which is appropriate for
13
+ * nested resource allocation patterns.
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const cleanup = new CleanupManager();
18
+ *
19
+ * // Register cleanup tasks
20
+ * cleanup.register(() => console.log('First registered, last executed'));
21
+ * cleanup.register(() => console.log('Last registered, first executed'));
22
+ *
23
+ * // Execute all cleanup tasks
24
+ * await cleanup.cleanup();
25
+ * ```
26
+ *
27
+ * @public
28
+ */
29
+ export declare class CleanupManager {
30
+ /**
31
+ * Array of registered cleanup tasks awaiting execution.
32
+ * @internal
33
+ */
34
+ private tasks;
35
+ /**
36
+ * Flag indicating whether cleanup has already been performed.
37
+ * @internal
38
+ */
39
+ private cleaned;
40
+ /**
41
+ * Registers a cleanup task to be executed when {@link cleanup} is called.
42
+ *
43
+ * @param task - The cleanup function to register
44
+ *
45
+ * @remarks
46
+ * If cleanup has already been performed, the task is executed immediately
47
+ * rather than being registered. This ensures late-registered tasks are
48
+ * still handled appropriately.
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * cleanup.register(() => {
53
+ * eventEmitter.removeAllListeners();
54
+ * });
55
+ *
56
+ * cleanup.register(async () => {
57
+ * await database.close();
58
+ * });
59
+ * ```
60
+ *
61
+ * @public
62
+ */
63
+ register(task: CleanupTask): void;
64
+ /**
65
+ * Executes all registered cleanup tasks in LIFO order.
66
+ *
67
+ * @returns A Promise that resolves when all cleanup tasks have completed
68
+ *
69
+ * @remarks
70
+ * Tasks are executed in reverse order of registration (LIFO pattern).
71
+ * Each task is awaited individually, and errors are caught and logged
72
+ * to prevent one failing task from blocking subsequent cleanup operations.
73
+ * Calling this method multiple times has no effect after the first call.
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * // In a component's destroy lifecycle
78
+ * async destroy() {
79
+ * await this.cleanupManager.cleanup();
80
+ * }
81
+ * ```
82
+ *
83
+ * @public
84
+ */
85
+ cleanup(): Promise<void>;
86
+ /**
87
+ * Checks whether cleanup has already been performed.
88
+ *
89
+ * @returns `true` if {@link cleanup} has been called, `false` otherwise
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * if (!cleanupManager.isCleaned()) {
94
+ * // Safe to register more tasks
95
+ * cleanupManager.register(myTask);
96
+ * }
97
+ * ```
98
+ *
99
+ * @public
100
+ */
101
+ isCleaned(): boolean;
102
+ /**
103
+ * Resets the manager to its initial state, allowing it to be reused.
104
+ *
105
+ * @remarks
106
+ * This method clears all registered tasks and resets the cleaned flag.
107
+ * It is primarily intended for testing scenarios or cases where the
108
+ * manager needs to be reused after cleanup.
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * // In a test teardown
113
+ * afterEach(() => {
114
+ * cleanupManager.reset();
115
+ * });
116
+ * ```
117
+ *
118
+ * @public
119
+ */
120
+ reset(): void;
121
+ }
122
+ export {};
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * Dimension normalization utilities for consistent handling of width/height values.
4
+ */
5
+ /**
6
+ * Normalizes a dimension value to a CSS-compatible string.
7
+ *
8
+ * @remarks
9
+ * Numeric values are converted to pixel strings (e.g., `400` becomes `'400px'`).
10
+ * String values are returned as-is, allowing for units like `'100%'` or `'auto'`.
11
+ * Undefined values return the fallback (defaults to `'100%'`).
12
+ *
13
+ * @param value - The dimension value (number for pixels, string with units, or undefined)
14
+ * @param fallback - The value to use if value is undefined (default: '100%')
15
+ * @returns A CSS-compatible dimension string
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * normalizeDimensionToCSS(400); // '400px'
20
+ * normalizeDimensionToCSS('100%'); // '100%'
21
+ * normalizeDimensionToCSS(undefined); // '100%'
22
+ * normalizeDimensionToCSS(undefined, 'auto'); // 'auto'
23
+ * ```
24
+ *
25
+ * @public
26
+ */
27
+ export declare function normalizeDimensionToCSS(value: string | number | undefined, fallback?: string): string;
28
+ /**
29
+ * Normalizes a dimension value to a numeric pixel value.
30
+ *
31
+ * @remarks
32
+ * This function is useful for popup window APIs that require numeric values.
33
+ * String values are parsed as integers (e.g., `'500px'` becomes `500`).
34
+ * Undefined values or unparseable strings return the fallback.
35
+ *
36
+ * @param value - The dimension value to normalize
37
+ * @param fallback - The fallback value to use if normalization fails
38
+ * @returns A numeric pixel value
39
+ *
40
+ * @example
41
+ * ```typescript
42
+ * normalizeDimensionToNumber(400, 500); // 400
43
+ * normalizeDimensionToNumber('500px', 500); // 500
44
+ * normalizeDimensionToNumber('100%', 500); // 500 (cannot parse percentage)
45
+ * normalizeDimensionToNumber(undefined, 500); // 500
46
+ * ```
47
+ *
48
+ * @public
49
+ */
50
+ export declare function normalizeDimensionToNumber(value: string | number | undefined, fallback: number): number;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Utility functions and classes for ForgeFrame.
3
+ *
4
+ * @remarks
5
+ * This module provides common utilities used throughout the ForgeFrame framework:
6
+ * - **UID generation**: Functions for creating unique identifiers
7
+ * - **Cleanup management**: A class for managing resource disposal
8
+ * - **Promise utilities**: Helpers for working with async operations
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * import {
13
+ * generateUID,
14
+ * CleanupManager,
15
+ * createDeferred,
16
+ * delay
17
+ * } from './utils';
18
+ *
19
+ * // Generate a unique ID
20
+ * const id = generateUID();
21
+ *
22
+ * // Manage cleanup tasks
23
+ * const cleanup = new CleanupManager();
24
+ * cleanup.register(() => console.log('Cleaning up...'));
25
+ *
26
+ * // Work with deferred promises
27
+ * const deferred = createDeferred<string>();
28
+ * setTimeout(() => deferred.resolve('done'), 1000);
29
+ * await deferred.promise;
30
+ * ```
31
+ *
32
+ * @packageDocumentation
33
+ */
34
+ export { generateUID, generateShortUID, isValidUID } from './uid';
35
+ export { CleanupManager } from './cleanup';
36
+ export { createDeferred, promiseTimeout, waitFor, delay, tryCatch, type Deferred, } from './promise';
37
+ export { normalizeDimensionToCSS, normalizeDimensionToNumber } from './dimension';
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Represents a deferred promise with externally accessible resolve and reject functions.
3
+ *
4
+ * @typeParam T - The type of value the promise will resolve to
5
+ *
6
+ * @remarks
7
+ * This interface is useful when you need to create a promise that will be
8
+ * resolved or rejected from outside the promise executor function.
9
+ *
10
+ * @public
11
+ */
12
+ export interface Deferred<T> {
13
+ /** The underlying promise that can be awaited */
14
+ promise: Promise<T>;
15
+ /** Function to resolve the promise with a value */
16
+ resolve: (value: T) => void;
17
+ /** Function to reject the promise with an error */
18
+ reject: (error: Error) => void;
19
+ }
20
+ /**
21
+ * Creates a deferred promise with externally accessible resolve and reject functions.
22
+ *
23
+ * @typeParam T - The type of value the promise will resolve to
24
+ * @returns A {@link Deferred} object containing the promise and its control functions
25
+ *
26
+ * @remarks
27
+ * This utility is helpful when the resolution of a promise depends on external
28
+ * events or callbacks that occur outside the promise executor scope.
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * const deferred = createDeferred<string>();
33
+ *
34
+ * // Pass the promise to something that will await it
35
+ * someAsyncOperation(deferred.promise);
36
+ *
37
+ * // Later, resolve from elsewhere
38
+ * deferred.resolve('Success!');
39
+ * ```
40
+ *
41
+ * @public
42
+ */
43
+ export declare function createDeferred<T>(): Deferred<T>;
44
+ /**
45
+ * Wraps a promise with a timeout, rejecting if the timeout is exceeded.
46
+ *
47
+ * @typeParam T - The type of value the promise will resolve to
48
+ * @param promise - The promise to wrap with a timeout
49
+ * @param ms - The timeout duration in milliseconds
50
+ * @param message - Custom error message for timeout (defaults to 'Operation timed out')
51
+ * @returns A new promise that resolves with the original value or rejects on timeout
52
+ *
53
+ * @throws Error when the timeout is exceeded before the promise resolves
54
+ *
55
+ * @remarks
56
+ * This is useful for adding time constraints to operations that might hang
57
+ * or take unexpectedly long. The original promise continues executing even
58
+ * after timeout, but its result is ignored.
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * try {
63
+ * const result = await promiseTimeout(
64
+ * fetchData(),
65
+ * 5000,
66
+ * 'Data fetch timed out'
67
+ * );
68
+ * } catch (error) {
69
+ * console.error(error.message); // "Data fetch timed out (5000ms)"
70
+ * }
71
+ * ```
72
+ *
73
+ * @public
74
+ */
75
+ export declare function promiseTimeout<T>(promise: Promise<T>, ms: number, message?: string): Promise<T>;
76
+ /**
77
+ * Waits for a condition function to return true, polling at a specified interval.
78
+ *
79
+ * @param condition - A function that returns `true` when the wait condition is met
80
+ * @param options - Configuration options for the wait behavior
81
+ * @param options.timeout - Maximum time to wait in milliseconds (defaults to 5000)
82
+ * @param options.interval - Polling interval in milliseconds (defaults to 50)
83
+ * @returns A promise that resolves when the condition becomes true
84
+ *
85
+ * @throws Error when the timeout is exceeded before the condition becomes true
86
+ *
87
+ * @remarks
88
+ * This utility is particularly useful in testing scenarios or when waiting
89
+ * for DOM elements, state changes, or other asynchronous conditions.
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * // Wait for an element to appear
94
+ * await waitFor(
95
+ * () => document.querySelector('.modal') !== null,
96
+ * { timeout: 3000, interval: 100 }
97
+ * );
98
+ * ```
99
+ *
100
+ * @public
101
+ */
102
+ export declare function waitFor(condition: () => boolean, options?: {
103
+ timeout?: number;
104
+ interval?: number;
105
+ }): Promise<void>;
106
+ /**
107
+ * Creates a promise that resolves after a specified delay.
108
+ *
109
+ * @param ms - The delay duration in milliseconds
110
+ * @returns A promise that resolves after the specified delay
111
+ *
112
+ * @remarks
113
+ * This is a simple utility for introducing delays in async code,
114
+ * useful for throttling, debouncing, or creating artificial pauses.
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * console.log('Starting...');
119
+ * await delay(1000);
120
+ * console.log('One second later');
121
+ * ```
122
+ *
123
+ * @public
124
+ */
125
+ export declare function delay(ms: number): Promise<void>;
126
+ /**
127
+ * Executes a function and returns its result, returning a fallback value if an error occurs.
128
+ *
129
+ * @typeParam T - The type of value returned by the function and fallback
130
+ * @param fn - The function to execute (can be sync or async)
131
+ * @param fallback - The value to return if the function throws an error
132
+ * @returns A promise that resolves to either the function result or the fallback value
133
+ *
134
+ * @remarks
135
+ * This utility provides a concise way to handle errors without explicit try-catch blocks,
136
+ * particularly useful when a sensible default value exists for error cases.
137
+ *
138
+ * @example
139
+ * ```typescript
140
+ * // Safely parse JSON with a fallback
141
+ * const config = await tryCatch(
142
+ * () => JSON.parse(rawConfig),
143
+ * { defaultSetting: true }
144
+ * );
145
+ *
146
+ * // Safely fetch with a fallback
147
+ * const data = await tryCatch(
148
+ * async () => await fetchData(),
149
+ * []
150
+ * );
151
+ * ```
152
+ *
153
+ * @public
154
+ */
155
+ export declare function tryCatch<T>(fn: () => T | Promise<T>, fallback: T): Promise<T>;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Generates a unique identifier by combining a timestamp with a random string.
3
+ *
4
+ * @returns A unique identifier string in the format `{timestamp}_{random}`
5
+ *
6
+ * @remarks
7
+ * The UID is composed of two parts separated by an underscore:
8
+ * - A base-36 encoded timestamp from `Date.now()`
9
+ * - A random base-36 string of up to 9 characters
10
+ *
11
+ * This combination provides both temporal ordering and collision resistance.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const id = generateUID();
16
+ * // Returns something like: "lxyz123_abc456def"
17
+ * ```
18
+ *
19
+ * @public
20
+ */
21
+ export declare function generateUID(): string;
22
+ /**
23
+ * Generates a short unique identifier suitable for function references and internal use.
24
+ *
25
+ * @returns A short random string of up to 9 characters
26
+ *
27
+ * @remarks
28
+ * Unlike {@link generateUID}, this function does not include a timestamp component,
29
+ * making it shorter but without temporal ordering guarantees. Use this for cases
30
+ * where a compact identifier is preferred over strict uniqueness.
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * const shortId = generateShortUID();
35
+ * // Returns something like: "abc456def"
36
+ * ```
37
+ *
38
+ * @public
39
+ */
40
+ export declare function generateShortUID(): string;
41
+ /**
42
+ * Validates whether a string conforms to the ForgeFrame UID format.
43
+ *
44
+ * @param uid - The string to validate
45
+ * @returns `true` if the string matches the UID format, `false` otherwise
46
+ *
47
+ * @remarks
48
+ * A valid ForgeFrame UID consists of two lowercase alphanumeric segments
49
+ * separated by an underscore (e.g., `lxyz123_abc456def`).
50
+ *
51
+ * @example
52
+ * ```typescript
53
+ * isValidUID('abc123_def456'); // true
54
+ * isValidUID('invalid'); // false
55
+ * isValidUID('ABC_123'); // false (uppercase not allowed)
56
+ * ```
57
+ *
58
+ * @public
59
+ */
60
+ export declare function isValidUID(uid: string): boolean;