@hypen-space/core 0.4.2 → 0.4.3

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,150 @@
1
+ /**
2
+ * Retry Utility for Network Operations
3
+ *
4
+ * Provides configurable retry logic with exponential/linear backoff
5
+ * for handling transient failures in network operations.
6
+ */
7
+ import { type Result } from "./result.js";
8
+ /**
9
+ * Options for retry behavior
10
+ */
11
+ export interface RetryOptions {
12
+ /** Maximum number of attempts (default: 3) */
13
+ maxAttempts?: number;
14
+ /** Initial delay in milliseconds (default: 1000) */
15
+ delayMs?: number;
16
+ /** Backoff strategy (default: 'exponential') */
17
+ backoff?: "linear" | "exponential" | "none";
18
+ /** Maximum delay cap in milliseconds (default: 30000) */
19
+ maxDelayMs?: number;
20
+ /** Jitter factor 0-1 to randomize delays (default: 0.1) */
21
+ jitter?: number;
22
+ /** Callback on each retry attempt */
23
+ onRetry?: (attempt: number, error: Error, nextDelayMs: number) => void;
24
+ /** Optional predicate to determine if error is retryable */
25
+ shouldRetry?: (error: Error) => boolean;
26
+ /** AbortSignal for cancellation */
27
+ signal?: AbortSignal;
28
+ }
29
+ /**
30
+ * Retry a function with configurable backoff
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * // Basic usage
35
+ * const result = await retry(() => fetch('/api/data'));
36
+ *
37
+ * // With options
38
+ * const result = await retry(
39
+ * () => fetch('/api/data'),
40
+ * {
41
+ * maxAttempts: 5,
42
+ * delayMs: 2000,
43
+ * backoff: 'exponential',
44
+ * onRetry: (n, err) => console.log(`Attempt ${n} failed: ${err.message}`)
45
+ * }
46
+ * );
47
+ * ```
48
+ */
49
+ export declare function retry<T>(fn: () => T | Promise<T>, options?: RetryOptions): Promise<T>;
50
+ /**
51
+ * Retry a function, returning a Result instead of throwing
52
+ *
53
+ * @example
54
+ * ```typescript
55
+ * const result = await retryResult(() => fetch('/api/data'));
56
+ * if (result.ok) {
57
+ * console.log('Success:', result.value);
58
+ * } else {
59
+ * console.error('All retries failed:', result.error);
60
+ * }
61
+ * ```
62
+ */
63
+ export declare function retryResult<T>(fn: () => T | Promise<T>, options?: RetryOptions): Promise<Result<T, Error>>;
64
+ /**
65
+ * Create a retryable version of a function
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * const fetchWithRetry = withRetry(
70
+ * (url: string) => fetch(url),
71
+ * { maxAttempts: 3 }
72
+ * );
73
+ *
74
+ * const response = await fetchWithRetry('/api/data');
75
+ * ```
76
+ */
77
+ export declare function withRetry<TArgs extends unknown[], TReturn>(fn: (...args: TArgs) => TReturn | Promise<TReturn>, options?: RetryOptions): (...args: TArgs) => Promise<TReturn>;
78
+ /**
79
+ * Predefined retry conditions
80
+ */
81
+ export declare const RetryConditions: {
82
+ /**
83
+ * Retry on network errors (fetch failures, timeouts)
84
+ */
85
+ networkErrors: (error: Error) => boolean;
86
+ /**
87
+ * Retry on specific HTTP status codes (from fetch Response)
88
+ */
89
+ httpRetryable: (error: Error & {
90
+ status?: number;
91
+ }) => boolean;
92
+ /**
93
+ * Retry on transient WebSocket errors
94
+ */
95
+ websocketErrors: (error: Error) => boolean;
96
+ /**
97
+ * Combine multiple conditions (retry if any match)
98
+ */
99
+ any: (...conditions: Array<(error: Error) => boolean>) => (error: Error) => boolean;
100
+ /**
101
+ * Combine multiple conditions (retry if all match)
102
+ */
103
+ all: (...conditions: Array<(error: Error) => boolean>) => (error: Error) => boolean;
104
+ };
105
+ /**
106
+ * Preset configurations for common use cases
107
+ */
108
+ export declare const RetryPresets: {
109
+ /**
110
+ * Aggressive retry for critical operations
111
+ */
112
+ aggressive: {
113
+ maxAttempts: number;
114
+ delayMs: number;
115
+ backoff: "exponential";
116
+ maxDelayMs: number;
117
+ jitter: number;
118
+ };
119
+ /**
120
+ * Conservative retry for non-critical operations
121
+ */
122
+ conservative: {
123
+ maxAttempts: number;
124
+ delayMs: number;
125
+ backoff: "linear";
126
+ maxDelayMs: number;
127
+ jitter: number;
128
+ };
129
+ /**
130
+ * Fast retry for local operations (short delays)
131
+ */
132
+ fast: {
133
+ maxAttempts: number;
134
+ delayMs: number;
135
+ backoff: "exponential";
136
+ maxDelayMs: number;
137
+ jitter: number;
138
+ };
139
+ /**
140
+ * WebSocket reconnection preset
141
+ */
142
+ websocket: {
143
+ maxAttempts: number;
144
+ delayMs: number;
145
+ backoff: "exponential";
146
+ maxDelayMs: number;
147
+ jitter: number;
148
+ shouldRetry: (error: Error) => boolean;
149
+ };
150
+ };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Hypen Router - Declarative routing system
3
+ * Integrated with Hypen's reactive state management
4
+ */
5
+ export type RouteMatch = {
6
+ params: Record<string, string>;
7
+ query: Record<string, string>;
8
+ path: string;
9
+ };
10
+ export type RouteState = {
11
+ currentPath: string;
12
+ params: Record<string, string>;
13
+ query: Record<string, string>;
14
+ previousPath: string | null;
15
+ };
16
+ export type RouteChangeCallback = (route: RouteState) => void;
17
+ /**
18
+ * Hypen Router - Manages application routing with pattern matching
19
+ */
20
+ export declare class HypenRouter {
21
+ private state;
22
+ private subscribers;
23
+ private isInitialized;
24
+ private isUpdating;
25
+ constructor();
26
+ /**
27
+ * Initialize browser history sync
28
+ */
29
+ private initializeBrowserSync;
30
+ /**
31
+ * Get path from browser URL (supports both hash and pathname)
32
+ */
33
+ private getPathFromBrowser;
34
+ /**
35
+ * Parse query string from URL
36
+ */
37
+ private parseQuery;
38
+ /**
39
+ * Navigate to a new path
40
+ */
41
+ push(path: string): void;
42
+ /**
43
+ * Replace current path without adding to history
44
+ */
45
+ replace(path: string): void;
46
+ /**
47
+ * Go back in history
48
+ */
49
+ back(): void;
50
+ /**
51
+ * Go forward in history
52
+ */
53
+ forward(): void;
54
+ /**
55
+ * Update the current path
56
+ */
57
+ private updatePath;
58
+ /**
59
+ * Get current path
60
+ */
61
+ getCurrentPath(): string;
62
+ /**
63
+ * Get current route params
64
+ */
65
+ getParams(): Record<string, string>;
66
+ /**
67
+ * Get current query params
68
+ */
69
+ getQuery(): Record<string, string>;
70
+ /**
71
+ * Get full route state snapshot
72
+ */
73
+ getState(): RouteState;
74
+ /**
75
+ * Match a pattern against a path
76
+ */
77
+ matchPath(pattern: string, path: string): RouteMatch | null;
78
+ /**
79
+ * Subscribe to route changes
80
+ */
81
+ onNavigate(callback: RouteChangeCallback): () => void;
82
+ /**
83
+ * Notify all subscribers of route change
84
+ */
85
+ private notifySubscribers;
86
+ /**
87
+ * Check if a path matches the current route
88
+ */
89
+ isActive(pattern: string): boolean;
90
+ /**
91
+ * Get a URL with query params
92
+ */
93
+ buildUrl(path: string, query?: Record<string, string>): string;
94
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * State management with observer pattern and diffing
3
+ *
4
+ * Uses a proxy-based approach with self-detection to avoid
5
+ * creating nested proxies repeatedly.
6
+ */
7
+ export type StatePath = string;
8
+ /**
9
+ * Represents a change in state with full path information
10
+ */
11
+ export interface StateChange {
12
+ paths: StatePath[];
13
+ newValues: Record<StatePath, any>;
14
+ }
15
+ /**
16
+ * Options for state observer
17
+ */
18
+ export interface StateObserverOptions {
19
+ onChange: (change: StateChange) => void;
20
+ pathPrefix?: string;
21
+ }
22
+ /**
23
+ * Create an observable state object that tracks changes
24
+ */
25
+ export declare function createObservableState<T extends object>(initialState: T, options?: StateObserverOptions): T;
26
+ /**
27
+ * Helper to batch multiple state updates
28
+ */
29
+ export declare function batchStateUpdates<T>(state: T, fn: () => void): void;
30
+ /**
31
+ * Get a snapshot of the current state
32
+ */
33
+ export declare function getStateSnapshot<T>(state: T): T;
34
+ /**
35
+ * Check if a value is a Hypen state proxy
36
+ */
37
+ export declare function isStateProxy(value: unknown): boolean;
38
+ /**
39
+ * Get the raw (unwrapped) target from a proxy
40
+ * Returns the value as-is if not a proxy
41
+ */
42
+ export declare function unwrapProxy<T>(value: T): T;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Core types shared across the engine and runtime.
3
+ *
4
+ * These types are intentionally decoupled from the WASM engine so that
5
+ * packages can import them without pulling in any WASM code.
6
+ */
7
+ export type Patch = {
8
+ type: "create" | "setProp" | "setText" | "insert" | "move" | "remove" | "attachEvent" | "detachEvent";
9
+ id?: string;
10
+ elementType?: string;
11
+ props?: Record<string, any>;
12
+ name?: string;
13
+ value?: any;
14
+ text?: string;
15
+ parentId?: string;
16
+ beforeId?: string;
17
+ eventName?: string;
18
+ };
19
+ export type Action = {
20
+ name: string;
21
+ payload?: any;
22
+ sender?: string;
23
+ };
24
+ export type RenderCallback = (patches: Patch[]) => void;
25
+ export type ActionHandler = (action: Action) => void | Promise<void>;
26
+ export type ResolvedComponent = {
27
+ source: string;
28
+ path: string;
29
+ };
30
+ export type ComponentResolver = (componentName: string, contextPath: string | null) => ResolvedComponent | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hypen-space/core",
3
- "version": "0.4.2",
3
+ "version": "0.4.3",
4
4
  "description": "Hypen core engine - Platform-agnostic reactive UI runtime",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -152,6 +152,7 @@
152
152
  "scripts": {
153
153
  "build": "bun run build.ts",
154
154
  "build:types": "tsc --emitDeclarationOnly",
155
+ "prepublishOnly": "bun run build",
155
156
  "typecheck": "tsc --noEmit",
156
157
  "clean": "rm -rf dist"
157
158
  },
Binary file
@@ -16,5 +16,7 @@
16
16
  "hypen_engine.d.ts"
17
17
  ],
18
18
  "main": "hypen_engine.js",
19
- "types": "hypen_engine.d.ts"
20
- }
19
+ "types": "hypen_engine.d.ts",
20
+ "type": "commonjs",
21
+ "sideEffects": false
22
+ }