@shadow-js/core 0.1.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,609 @@
1
+ export { F as Fragment, j as jsx, b as jsxDEV, a as jsxs } from './jsx-Bugil6CJ.cjs';
2
+
3
+ /**
4
+ * Return type of `useData`.
5
+ * A reactive accessor function with extra properties.
6
+ */
7
+ type UseDataReturn<T> = {
8
+ (): T | undefined;
9
+ loading: () => boolean;
10
+ error: () => unknown;
11
+ mutate: (value: T | ((prev: T | undefined) => T)) => void;
12
+ refetch: () => Promise<void>;
13
+ };
14
+ /**
15
+ * A fetcher function that takes a source and returns a Promise of data.
16
+ */
17
+ type Fetcher<S, T> = (source: S) => Promise<T>;
18
+ /**
19
+ * Reactive data-fetching hook.
20
+ *
21
+ * @param source A static value or reactive getter providing the fetch key.
22
+ * @param fetcher Async function to fetch data for the given source.
23
+ * @param deps Optional reactive dependencies controlling refetching.
24
+ * @returns A reactive accessor with `.loading`, `.error`, `.mutate`, `.refetch`.
25
+ */
26
+ declare function useData<S, T>(source: (() => S) | S, fetcher?: Fetcher<S, T>, deps?: (() => unknown)[]): UseDataReturn<T>;
27
+
28
+ /**
29
+ * Create a reactive effect that re-runs whenever its dependencies change.
30
+ *
31
+ * Modes:
32
+ * - Auto-tracked (no deps array): reads from stores inside fn() subscribe
33
+ * this effect automatically. Any store update re-runs the effect.
34
+ * - Dep-tracked (deps array): fn() re-runs only when deps() values change.
35
+ * Stores read inside fn() are NOT tracked automatically in this mode.
36
+ *
37
+ * Cleanup:
38
+ * - If fn() returns a function, it runs before next run and on unmount.
39
+ *
40
+ * Correctness details:
41
+ * - We unsubscribe from the previously tracked stores BEFORE each re-run
42
+ * (both modes). This prevents "ghost" updates caused by stale subscriptions.
43
+ */
44
+ declare function useEffect(fn: () => void | (() => void), deps?: (() => unknown)[]): () => void;
45
+
46
+ /**
47
+ * Return a stable, globally unique id string for use in attributes
48
+ * like `id` and `for`. Client-only counter-based implementation.
49
+ *
50
+ * @example
51
+ * const id = useId();
52
+ * <label for={id}>Name</label>
53
+ * <input id={id} />
54
+ *
55
+ * @returns A unique id string, e.g., "sfid-1"
56
+ */
57
+ declare function useId(): string;
58
+
59
+ type Store<T> = {
60
+ /**
61
+ * Reactive getter for the store's current value.
62
+ * Reading this within an effect subscribes that effect to changes.
63
+ */
64
+ (): T;
65
+ /**
66
+ * Direct, non-reactive access to the current value.
67
+ */
68
+ value: T;
69
+ /**
70
+ * Internal marker so we can detect Shadow stores at runtime.
71
+ */
72
+ __isStore: boolean;
73
+ };
74
+ /**
75
+ * Create a reactive store.
76
+ *
77
+ * - Calling the returned function reads the current value and subscribes
78
+ * the current effect (if any).
79
+ * - Calling the setter updates the value and notifies subscribers.
80
+ *
81
+ * HMR (dev-only, Vite):
82
+ * - Pass a stable `hmrKey` to preserve the store value across module updates.
83
+ * The value is saved in `import.meta.hot.data` on dispose and restored
84
+ * when the module re-evaluates after a hot update.
85
+ *
86
+ * Example:
87
+ * const [count, setCount] = useStore(0, {
88
+ * hmrKey: import.meta.url + "#App.count"
89
+ * });
90
+ *
91
+ * @param initialValue Initial value of the store.
92
+ * @param opts Optional settings.
93
+ * - hmrKey: string key to persist the value across Vite HMR updates.
94
+ * @returns A tuple [store, set] where:
95
+ * - store is a callable getter (Store<T>)
96
+ * - set is a setter (newValue: T | ((prev: T) => T)) => void
97
+ */
98
+ declare function useStore<T>(initialValue: T, opts?: {
99
+ hmrKey?: string;
100
+ }): [Store<T>, (newValue: T | ((prev: T) => T)) => void];
101
+
102
+ /**
103
+ * Memoize a computed value reactively.
104
+ *
105
+ * `useMemo` creates a reactive store that automatically updates whenever the
106
+ * computation function's dependencies change. Unlike `useEffect`, `useMemo`
107
+ * returns a reactive value that can be used in JSX expressions.
108
+ *
109
+ * The memoized value is computed immediately and updates reactively based on
110
+ * any reactive dependencies accessed during the computation.
111
+ *
112
+ * @param fn - Function that computes the memoized value. This function should
113
+ * be pure and return the value to be memoized.
114
+ * @returns A reactive store containing the memoized value. The returned store
115
+ * can be called as a getter and will automatically update when dependencies change.
116
+ *
117
+ * @example
118
+ * ```tsx
119
+ * function ExpensiveComponent({ items }) {
120
+ * // Memoize expensive computation
121
+ * const sortedItems = useMemo(() => {
122
+ * console.log("Sorting items...");
123
+ * return [...items()].sort((a, b) => a.name.localeCompare(b.name));
124
+ * });
125
+ *
126
+ * return (
127
+ * <ul>
128
+ * <For each={sortedItems()}>
129
+ * {(item) => <li>{item.name}</li>}
130
+ * </For>
131
+ * </ul>
132
+ * );
133
+ * }
134
+ * ```
135
+ *
136
+ * @example
137
+ * ```tsx
138
+ * // Memoizing complex calculations
139
+ * function StatsComponent({ data }) {
140
+ * const average = useMemo(() => {
141
+ * const values = data().map(item => item.value);
142
+ * return values.reduce((sum, val) => sum + val, 0) / values.length;
143
+ * });
144
+ *
145
+ * const max = useMemo(() => {
146
+ * return Math.max(...data().map(item => item.value));
147
+ * });
148
+ *
149
+ * return (
150
+ * <div>
151
+ * <p>Average: {average()}</p>
152
+ * <p>Maximum: {max()}</p>
153
+ * </div>
154
+ * );
155
+ * }
156
+ * ```
157
+ */
158
+ declare function useMemo<T>(fn: () => T): Store<T>;
159
+
160
+ type Reducer<State, Action> = (state: State, action: Action) => State;
161
+ /**
162
+ * Create an optimistic state derived from a base state (store or plain value).
163
+ *
164
+ * Overloads:
165
+ * - useOptimistic(baseStoreOrValue)
166
+ * - useOptimistic(baseStoreOrValue, reducer)
167
+ *
168
+ * @param base Base state as a Store<T> or a plain value.
169
+ * @param reducer Optional reducer to compute next optimistic state from action.
170
+ * @returns [optimisticStore, dispatchOrSet]
171
+ */
172
+ declare function useOptimistic<T>(base: Store<T>): [Store<T>, (nextState: T) => void];
173
+ declare function useOptimistic<T, A>(base: Store<T>, reducer: Reducer<T, A>): [Store<T>, (action: A) => void];
174
+ declare function useOptimistic<T>(base: T): [Store<T>, (nextState: T) => void];
175
+ declare function useOptimistic<T, A>(base: T, reducer: Reducer<T, A>): [Store<T>, (action: A) => void];
176
+
177
+ /**
178
+ * Run a function once when the component is first invoked.
179
+ *
180
+ * Note: This is synchronous and runs during component execution.
181
+ *
182
+ * @param fn The function to run once on mount.
183
+ */
184
+ declare function onMount(fn: () => void): void;
185
+
186
+ /**
187
+ * Register a cleanup to run when the current component unmounts.
188
+ *
189
+ * @param fn Cleanup callback.
190
+ */
191
+ declare function onCleanup(fn: () => void): void;
192
+
193
+ /**
194
+ * For component (each-only).
195
+ *
196
+ * Usage:
197
+ * <For each={items()}>
198
+ * {(item, i) => <li>{item.name}</li>}
199
+ * </For>
200
+ *
201
+ * For automatically handles efficient updates by default, so no key property is needed.
202
+ * Parameter names are flexible - you can use any names you want:
203
+ * <For each={count()}>
204
+ * {(num: string, idx: number) => <p>Item {idx}: {num}</p>}
205
+ * </For>
206
+ *
207
+ * Or even simpler:
208
+ * <For each={users()}>
209
+ * {(u: User, i: number) => <div>{u.name}</div>}
210
+ * </For>
211
+ */
212
+ type ForProps<T> = {
213
+ each: T[] | readonly T[];
214
+ children: (item: T, index: number, ...rest: unknown[]) => unknown;
215
+ };
216
+ declare function For<T>(props: ForProps<T>): DocumentFragment;
217
+
218
+ type ShowProps = {
219
+ when: boolean | (() => boolean);
220
+ fallback?: unknown;
221
+ children: unknown;
222
+ /**
223
+ * If true, unmount subtree when condition changes.
224
+ * If false (default), detach and cache nodes for faster re-show.
225
+ */
226
+ unmount?: boolean;
227
+ };
228
+ /**
229
+ * Conditional rendering:
230
+ * - when is true: render children
231
+ * - when is false: render fallback (if provided)
232
+ * - if unmount=false, caches DOM nodes to avoid re-creating them
233
+ */
234
+ declare function Show(props: ShowProps): DocumentFragment;
235
+
236
+ /**
237
+ * Match component - represents a conditional case within a Switch.
238
+ * This component doesn't render anything itself, but serves as a marker
239
+ * for the Switch component to evaluate conditions and render content.
240
+ *
241
+ * @example
242
+ * ```tsx
243
+ * <Switch>
244
+ * <Match when={count() === 0}>
245
+ * <div>No items</div>
246
+ * </Match>
247
+ * <Match when={count() === 1}>
248
+ * <div>One item</div>
249
+ * </Match>
250
+ * <Match when={count() > 1}>
251
+ * <div>{count()} items</div>
252
+ * </Match>
253
+ * </Switch>
254
+ * ```
255
+ */
256
+ declare function Match(): null;
257
+ /**
258
+ * Props for the Switch component.
259
+ * Switch renders the first matching Match child or the fallback.
260
+ */
261
+ type SwitchProps = {
262
+ /** Content to render if no Match conditions are true. */
263
+ fallback?: unknown;
264
+ /** Child components, typically Match components. */
265
+ children: unknown;
266
+ };
267
+ /**
268
+ * Switch component - renders the first matching Match child or fallback.
269
+ *
270
+ * This component evaluates Match children in order and renders the content
271
+ * of the first Match whose condition evaluates to true. If no Match conditions
272
+ * are true, it renders the fallback content if provided.
273
+ *
274
+ * Unlike traditional switch statements, Switch components are reactive and
275
+ * will re-evaluate conditions when their dependencies change.
276
+ *
277
+ * @param props Switch component props
278
+ * @returns DocumentFragment containing the rendered content
279
+ *
280
+ * @example
281
+ * ```tsx
282
+ * const [status, setStatus] = useStore<"idle" | "loading" | "success" | "error">("idle");
283
+ *
284
+ * return (
285
+ * <Switch fallback={<div>Unknown status</div>}>
286
+ * <Match when={status() === "idle"}>
287
+ * <div>Ready to start</div>
288
+ * </Match>
289
+ * <Match when={status() === "loading"}>
290
+ * <div>Loading...</div>
291
+ * </Match>
292
+ * <Match when={status() === "success"}>
293
+ * <div>Operation completed successfully!</div>
294
+ * </Match>
295
+ * <Match when={status() === "error"}>
296
+ * <div>Something went wrong</div>
297
+ * </Match>
298
+ * </Switch>
299
+ * );
300
+ * ```
301
+ */
302
+ declare function Switch(props: SwitchProps): DocumentFragment;
303
+
304
+ type TitleProps = {
305
+ children?: unknown;
306
+ };
307
+ /**
308
+ * <Title> updates document.title reactively based on its children.
309
+ *
310
+ * Examples:
311
+ * <Title>My App</Title>
312
+ * <Title>Count: {count()}</Title>
313
+ *
314
+ * Notes:
315
+ * - Avoid passing component children; Title expects text-like content.
316
+ * - On unmount, restores the previous title only if it was the last setter.
317
+ */
318
+ declare function Title(props: TitleProps): DocumentFragment;
319
+
320
+ /**
321
+ * ShadowJS Lazy Loading System
322
+ *
323
+ * The lazy component enables code splitting and dynamic imports in ShadowJS applications.
324
+ * It provides:
325
+ * - **Code Splitting**: Load components on-demand
326
+ * - **Caching**: Avoid re-importing already loaded modules
327
+ * - **Error Handling**: Retry logic with configurable attempts
328
+ * - **Suspense Integration**: Works seamlessly with Suspense boundaries
329
+ * - **Type Safety**: Full TypeScript support with proper inference
330
+ *
331
+ * The lazy system works by:
332
+ * 1. Creating placeholder fragments during loading
333
+ * 2. Loading the module asynchronously
334
+ * 3. Replacing the placeholder with the actual component
335
+ * 4. Notifying Suspense boundaries when complete
336
+ */
337
+ /**
338
+ * Creates a lazy-loaded component that loads on first use.
339
+ *
340
+ * The lazy function enables code splitting by creating a placeholder component
341
+ * that loads the actual component asynchronously. Once loaded, the component
342
+ * is cached for future use.
343
+ *
344
+ * Features:
345
+ * - **Automatic caching**: Loaded components are cached to prevent re-importing
346
+ * - **Retry logic**: Configurable retry attempts with delays
347
+ * - **Suspense support**: Integrates with Suspense boundaries for loading states
348
+ * - **Type safety**: Full TypeScript support with proper type inference
349
+ * - **Error handling**: Graceful error handling with informative messages
350
+ *
351
+ * @param importFn - Function that returns a Promise resolving to the component module
352
+ * @param options - Configuration options for loading behavior
353
+ * @param options.retries - Number of retry attempts (default: 3)
354
+ * @param options.retryDelay - Delay between retries in milliseconds (default: 1000)
355
+ * @returns A lazy wrapper component that loads the actual component on first render
356
+ *
357
+ * @example
358
+ * ```tsx
359
+ * // Basic usage with dynamic import
360
+ * const LazyComponent = lazy(() => import("./MyComponent"));
361
+ *
362
+ * function App() {
363
+ * return (
364
+ * <div>
365
+ * <LazyComponent />
366
+ * </div>
367
+ * );
368
+ * }
369
+ * ```
370
+ *
371
+ * @example
372
+ * ```tsx
373
+ * // With Suspense for loading states
374
+ * const LazyComponent = lazy(() => import("./MyComponent"));
375
+ *
376
+ * function App() {
377
+ * return (
378
+ * <Suspense fallback={<div>Loading...</div>}>
379
+ * <LazyComponent />
380
+ * </Suspense>
381
+ * );
382
+ * }
383
+ * ```
384
+ *
385
+ * @example
386
+ * ```tsx
387
+ * // With custom retry configuration
388
+ * const LazyComponent = lazy(
389
+ * () => import("./MyComponent"),
390
+ * { retries: 5, retryDelay: 2000 }
391
+ * );
392
+ * ```
393
+ *
394
+ * @example
395
+ * ```tsx
396
+ * // With TypeScript types
397
+ * const LazyComponent = lazy<{ name: string }, JSX.Element>(
398
+ * () => import("./MyComponent")
399
+ * );
400
+ *
401
+ * function App() {
402
+ * return <LazyComponent name="World" />;
403
+ * }
404
+ * ```
405
+ */
406
+ /**
407
+ * Overload (permissive first): accepts any Promise loader shape.
408
+ * This helps TypeScript inference for manual `new Promise(...)` cases.
409
+ */
410
+ declare function lazy(importFn: () => Promise<unknown>, options?: {
411
+ retries?: number;
412
+ retryDelay?: number;
413
+ }): (props?: Record<string, unknown>) => unknown;
414
+ /**
415
+ * Overload (typed): strongly typed default export that is a component fn.
416
+ */
417
+ declare function lazy<TProps = Record<string, unknown>, TResult = unknown>(importFn: () => Promise<{
418
+ default: (props: TProps) => TResult;
419
+ }>, options?: {
420
+ retries?: number;
421
+ retryDelay?: number;
422
+ }): (props: TProps) => TResult;
423
+
424
+ /**
425
+ * Portal renders its children into a different DOM container (mount).
426
+ *
427
+ * @param props.mount Target element to render into (required).
428
+ * @param props.children Content to render (supports reactive functions).
429
+ * @param props.ref Optional ref to the mount element.
430
+ */
431
+ declare function Portal(props: {
432
+ mount?: Element | null;
433
+ children?: unknown;
434
+ ref?: (element: Element) => void | {
435
+ current: Element | null;
436
+ };
437
+ }): DocumentFragment;
438
+
439
+ /**
440
+ * Suspense component - coordinates asynchronous operations with fallback UI.
441
+ *
442
+ * Suspense provides a way to show fallback content while waiting for async
443
+ * operations to complete. It works with:
444
+ * - Promises (thenables) thrown or returned by components
445
+ * - Lazy-loaded components (via lazy() function)
446
+ * - Nested Suspense components
447
+ *
448
+ * Behavior:
449
+ * 1. Shows fallback content if any top-level child is pending
450
+ * 2. Waits for all top-level async operations to resolve
451
+ * 3. Reveals actual content once all top-level operations complete
452
+ * 4. Keeps nested Suspense boundaries functional for fine-grained loading states
453
+ * 5. Updates reactively when children change
454
+ *
455
+ * @param props.fallback - Content to show while waiting for async operations
456
+ * @param props.children - Child components that may be async
457
+ * @returns DocumentFragment containing the Suspense boundary
458
+ *
459
+ * @example
460
+ * ```tsx
461
+ * const [data, setData] = useStore(null);
462
+ * const [loading, setLoading] = useStore(false);
463
+ *
464
+ * const fetchData = async () => {
465
+ * setLoading(true);
466
+ * const result = await fetch("/api/data").then(r => r.json());
467
+ * setData(result);
468
+ * setLoading(false);
469
+ * };
470
+ *
471
+ * function DataComponent() {
472
+ * if (loading()) {
473
+ * // This promise will be caught by Suspense
474
+ * throw new Promise(resolve => {
475
+ * if (!loading()) resolve();
476
+ * });
477
+ * }
478
+ * return <div>{JSON.stringify(data())}</div>;
479
+ * }
480
+ *
481
+ * return (
482
+ * <Suspense fallback={<div>Loading...</div>}>
483
+ * <DataComponent />
484
+ * </Suspense>
485
+ * );
486
+ * ```
487
+ *
488
+ * @example Lazy loading
489
+ * ```tsx
490
+ * const LazyComponent = lazy(() => import("./MyComponent"));
491
+ *
492
+ * return (
493
+ * <Suspense fallback={<div>Loading component...</div>}>
494
+ * <LazyComponent />
495
+ * </Suspense>
496
+ * );
497
+ * ```
498
+ */
499
+ declare function Suspense(props: {
500
+ fallback?: unknown;
501
+ children?: unknown;
502
+ }): DocumentFragment;
503
+
504
+ type ErrorBoundaryProps = {
505
+ fallback?: unknown | ((error: unknown) => unknown);
506
+ children?: unknown;
507
+ onError?: (error: unknown) => void;
508
+ };
509
+ /**
510
+ * ErrorBoundary catches synchronous rendering errors from its children
511
+ * and renders a fallback. It also calls the optional `onError` handler.
512
+ *
513
+ * Note: It catches errors thrown during render of function children.
514
+ * For async errors within Suspense/lazy, use Suspense and fallback.
515
+ */
516
+ declare function ErrorBoundary(props: ErrorBoundaryProps): DocumentFragment;
517
+
518
+ /**
519
+ * ShadowJS Render Function
520
+ *
521
+ * The render function is the entry point for mounting ShadowJS applications to the DOM.
522
+ * It handles the initial mounting of components and manages the component lifecycle.
523
+ *
524
+ * Features:
525
+ * - **Component Mounting**: Renders function components or DOM nodes
526
+ * - **Lifecycle Management**: Properly initializes component scopes and effects
527
+ * - **Cleanup**: Automatically disposes previous content before mounting new content
528
+ * - **Error Handling**: Validates inputs and provides clear error messages
529
+ * - **Component Thunk Support**: Handles lazy-loaded and async components
530
+ */
531
+ /**
532
+ * Renders a ShadowJS component or DOM node into a container element.
533
+ *
534
+ * This function is the primary entry point for mounting ShadowJS applications.
535
+ * It handles both function components (which get executed via JSX runtime) and
536
+ * direct DOM nodes, providing a unified mounting interface.
537
+ *
538
+ * The render process:
539
+ * 1. **Validation**: Ensures container is provided and valid
540
+ * 2. **Cleanup**: Disposes any existing mounted content
541
+ * 3. **Component Processing**: Handles function components vs DOM nodes
542
+ * 4. **Mounting**: Appends the rendered content to the container
543
+ * 5. **Lifecycle**: Initializes component scopes and effects
544
+ *
545
+ * @param component - Component to render. Can be:
546
+ * - A function component that returns JSX
547
+ * - A DOM Node or DocumentFragment
548
+ * - A component thunk (from lazy loading)
549
+ * @param container - Target DOM element to mount the component into.
550
+ * Must be a valid Element (not a DocumentFragment).
551
+ * @returns The mounted DOM node or the result of the component rendering.
552
+ *
553
+ * @throws Error if container is invalid or component returns invalid content
554
+ *
555
+ * @example
556
+ * ```tsx
557
+ * // Basic component rendering
558
+ * function App() {
559
+ * return <h1>Hello ShadowJS!</h1>;
560
+ * }
561
+ *
562
+ * const root = document.getElementById("app");
563
+ * render(App, root!);
564
+ * ```
565
+ *
566
+ * @example
567
+ * ```tsx
568
+ * // Rendering with props
569
+ * function Greeting({ name }) {
570
+ * return <h1>Hello, {name}!</h1>;
571
+ * }
572
+ *
573
+ * const root = document.getElementById("app");
574
+ * render(() => <Greeting name="World" />, root!);
575
+ * ```
576
+ *
577
+ * @example
578
+ * ```tsx
579
+ * // Rendering existing DOM nodes
580
+ * const existingElement = document.createElement("div");
581
+ * existingElement.textContent = "Pre-rendered content";
582
+ *
583
+ * const root = document.getElementById("app");
584
+ * render(existingElement, root!);
585
+ * ```
586
+ *
587
+ * @example
588
+ * ```tsx
589
+ * // With lazy loading
590
+ * const LazyApp = lazy(() => import("./App"));
591
+ *
592
+ * const root = document.getElementById("app");
593
+ * render(LazyApp, root!);
594
+ * ```
595
+ */
596
+ declare function render(component: unknown, container: Element): object & Record<"nodeType", unknown>;
597
+
598
+ /**
599
+ * Shadow's `createElement` function used by the JSX transform when
600
+ * `jsxImportSource: "@shadow-js/core"` is set. Delegates to `jsx`.
601
+ *
602
+ * @param tag The tag name (e.g., "div") or a component function.
603
+ * @param props Props object passed from JSX.
604
+ * @param children Children passed by JSX variadic arguments.
605
+ * @returns A DOM element or a MatchMarker (for <Match> in <Switch>).
606
+ */
607
+ declare function createElement(tag: unknown, props?: Record<string, unknown>, ...children: unknown[]): unknown;
608
+
609
+ export { ErrorBoundary, For, Match, Portal, Show, type Store, Suspense, Switch, Title, createElement, lazy, onCleanup, onMount, render, useData, useEffect, useId, useMemo, useOptimistic, useStore };