import { untrack } from 'solid-js'; import { PROXY_RESERVED_KEYS } from '../proxyKeys'; import { createAsyncValue, trackAsyncValue } from '../solidCompat'; type DynamicSource = string | { cacheKey: string }; type DynamicKey = T | (() => T); // A bare promise cannot be retried after it rejects (already settled); use a // function loader when retries matter. export type DynamicLoader = | Promise | ((source: Source) => Promise); type CacheEntry = | { status: 'pending'; promise: Promise; } | { status: 'success'; value: T; }; type CallableProxyTarget = (...argumentsList: unknown[]) => unknown; const NO_PENDING_PRIMITIVE_FALLBACK = Symbol('NO_PENDING_PRIMITIVE_FALLBACK'); /** * Property exposing the settled value behind a loadable proxy, or `undefined` * while the chunk is still in flight. See {@link unwrapLoadable}. */ const LOADABLE_SETTLED_VALUE = Symbol('LOADABLE_SETTLED_VALUE'); /** * Module-level cache to dedupe dynamic imports by key. Solid async primitives * still own suspense, SSR serialization, hydration, and refetching on source * change. */ const cache = new Map>(); export const getDynamicSourceCacheKey = (source: DynamicSource): string => typeof source === 'string' ? source : source.cacheKey; const readValueAtPath = ( value: unknown, path: readonly PropertyKey[] ): unknown => path.reduce((currentValue, property) => { if (currentValue === null || currentValue === undefined) return undefined; return Reflect.get(Object(currentValue), property); }, value); const resolveDynamicLoader = ( loader: DynamicLoader, source: Source ): Promise => (typeof loader === 'function' ? loader(source) : loader); export const loadDynamicValue = ( source: Source, loader: DynamicLoader ): T | Promise => { const key = getDynamicSourceCacheKey(source); // Cast is sound only while callers keep one value type per cache key. const cachedEntry = cache.get(key) as CacheEntry | undefined; if (cachedEntry?.status === 'success') return cachedEntry.value; if (cachedEntry?.status === 'pending') return cachedEntry.promise; const promise = resolveDynamicLoader(loader, source).then( (value) => { cache.set(key, { status: 'success', value }); return value; }, (error: unknown) => { cache.delete(key); throw error; } ); cache.set(key, { status: 'pending', promise }); return promise; }; /** * Records a value that is already available, so the next * {@link loadDynamicValue} for this key returns it synchronously. * * Used for dictionaries a build-tool plugin awaited while their entry point * evaluated: the async value resolves without ever entering a pending state, * so the loading boundary is not triggered and the first render already has the content. * * An existing entry is never replaced — an in-flight load owns its key. */ export const seedDynamicValue = (source: DynamicSource, value: T): void => { const key = getDynamicSourceCacheKey(source); if (cache.has(key)) return; cache.set(key, { status: 'success', value }); }; const bindPropertyValue = (value: unknown, propertyValue: unknown): unknown => typeof propertyValue === 'function' ? propertyValue.bind(value) : propertyValue; const createPendingPrimitiveFallback = (property: string | symbol): unknown => { if (property === Symbol.toPrimitive) return () => ''; // Keep array-shaped nodes (`array(t())`, collections) safe to read while the // chunk loads: an empty iterator and zero length make `` and spreads // render nothing instead of building an array from a proxy length. if (property === Symbol.iterator) return () => ({ next: () => ({ done: true, value: undefined }) }); if (property === 'length') return 0; if (property === PROXY_RESERVED_KEYS.toString) return () => ''; if (property === PROXY_RESERVED_KEYS.valueOf) return () => undefined; if (property === PROXY_RESERVED_KEYS.value) return ''; return NO_PENDING_PRIMITIVE_FALLBACK; }; /** * Creates a stable callable proxy that re-reads the Solid async value on each * property access. This keeps synchronous Intlayer access (`content.x.value`) * safe while the Solid loading boundary owns the actual pending state. */ export const createLoadableProxy = (read: () => T | undefined): T => { const createProxyAtPath = (path: readonly PropertyKey[]): unknown => { const target: CallableProxyTarget = () => undefined; return new Proxy(target, { get(_target, property) { if (property === PROXY_RESERVED_KEYS.promiseThen) return undefined; const currentValue = readValueAtPath(read(), path); // Answered before the fallbacks below, which would otherwise hand back // another proxy — and a proxy is truthy, so `unwrapLoadable` could // never tell a pending chunk from a settled one. if (property === LOADABLE_SETTLED_VALUE) return currentValue; if (currentValue !== null && currentValue !== undefined) { if (property === Symbol.toPrimitive) { return () => currentValue; } return bindPropertyValue( currentValue, Reflect.get(Object(currentValue), property) ); } const primitiveFallback = createPendingPrimitiveFallback(property); if (primitiveFallback !== NO_PENDING_PRIMITIVE_FALLBACK) { return primitiveFallback; } return createProxyAtPath([...path, property]); }, apply(_target, thisArgument, argumentsList) { const currentValue = readValueAtPath(read(), path); if (typeof currentValue !== 'function') { // A zero-arg call resolves the leaf: its real value once loaded, or // the empty string while pending (synchronous-safe). if (argumentsList.length === 0) return currentValue ?? ''; // A call with arguments made while the chunk is still pending must not // lose them: return a proxy that replays the exact call once the value // at this path resolves to a function. return createLoadableProxy(() => { // `read()` stays tracked so the replay re-runs once the chunk lands. const resolvedValue = readValueAtPath(read(), path); if (typeof resolvedValue !== 'function') return undefined; // The call itself is untracked: a replayed function runs inside // whichever effect happens to read this proxy, and its own reactive // reads would otherwise become that effect's dependencies and // re-trigger it forever. return untrack(() => Reflect.apply(resolvedValue, thisArgument, argumentsList) ); }); } return Reflect.apply(currentValue, thisArgument, argumentsList); }, }); }; return createProxyAtPath([]) as T; }; /** * Returns the settled value a loadable proxy stands for, or `undefined` while * its chunk is in flight — and for any value that is not a loadable proxy. * * The read stays tracked, so a caller inside a reactive scope re-runs once the * chunk lands. Interpreting the settled dictionary rather than the stand-in is * what lets `getDictionary` memoize the transform: the stand-in is created per * component and its content changes over time, while the settled dictionary is * one shared object every component resolves to. * * @param value - A loadable proxy, or any other value. */ export const unwrapLoadable = (value: T): T | undefined => { if ( value === null || (typeof value !== 'object' && typeof value !== 'function') ) return undefined; return (value as Record)[LOADABLE_SETTLED_VALUE] as | T | undefined; }; export const useLoadDynamic = ( key: DynamicKey, loader: DynamicLoader ): T => { const keyAccessor = () => (typeof key === 'function' ? key() : key); const asyncValue = createAsyncValue(keyAccessor, (resolvedSource: Source) => loadDynamicValue(resolvedSource, loader) ); // Hold the loading boundary without aborting component body execution trackAsyncValue(asyncValue); return createLoadableProxy(asyncValue); };