var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
    function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
    function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
import isEqual from 'lodash/isEqual';
import { matchRoutes, useMatches } from 'react-router';
import { useRecoilCallback } from 'recoil';
import * as z from 'zod/v4';
import { HTTP_METHOD } from '@darajs/ui-utils';
import { request } from '../api';
import { handleAuthErrors } from '../auth';
import { deferred, preloadDerivedVariable, preloadServerComponent } from '../shared';
import { ActionImpl, LoaderError, UserError, isAnnotatedAction, } from '../types';
import { PreloadSkipError, cleanArgs, cleanKwargs, resolveVariableStatic, } from '../shared/interactivity/resolve-variable';
import { denormalize, normalizeRequest } from '../shared/utils/normalization';
import { SingleUseCache } from './cache';
import { useRouterContext } from './context';
const NormalizedObject = z.object({
    data: z.any(),
    lookup: z.record(z.string(), z.any()),
});
export const TemplateChunk = z.object({
    type: z.literal('template'),
    template: NormalizedObject,
});
export const ActionChunk = z.object({
    type: z.literal('actions'),
    actions: z.record(z.string(), z.array(ActionImpl)),
});
export const DerivedVariableChunk = z.object({
    type: z.literal('derived_variable'),
    uid: z.string(),
    result: z.object({ ok: z.boolean(), value: z.any() }),
});
export const PyComponentChunk = z.object({
    type: z.literal('py_component'),
    uid: z.string(),
    result: z.object({ ok: z.boolean(), value: z.any() }),
});
export const ResponseChunk = z.union([TemplateChunk, ActionChunk, DerivedVariableChunk, PyComponentChunk]);
const PRELOAD_TIMEOUT = 5000; // 5 seconds
const preloadCache = new SingleUseCache({
    defaultTimeout: PRELOAD_TIMEOUT,
});
function createCacheKey(routeId, params) {
    return `${routeId}:${JSON.stringify(params)}`;
}
/**
 * Creates an NDJSON async generator from a Response object.
 * Yields chunks of JSON data as they are received.
 *
 * @param response Response object to read from
 * @param signal AbortSignal to abort the generator
 */
function ndjson(response, signal) {
    return __asyncGenerator(this, arguments, function* ndjson_1() {
        const reader = response.body.getReader();
        const newline = /\r?\n/;
        const decoder = new TextDecoder();
        let buffer = '';
        while (true) {
            if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
                throw new DOMException('The operation was aborted', 'AbortError');
            }
            // eslint-disable-next-line no-await-in-loop
            const { done, value } = yield __await(reader.read());
            if (done) {
                if (buffer.length > 0) {
                    yield yield __await(JSON.parse(buffer));
                }
                return yield __await(void 0);
            }
            const chunk = decoder.decode(value, { stream: true });
            buffer += chunk;
            const parts = buffer.split(newline);
            buffer = parts.pop();
            for (const part of parts) {
                yield yield __await(JSON.parse(part));
            }
        }
    });
}
/**
 * Fetch route data from the server.
 *
 * Collects payloads for `on_load` actions as wel as `derived_variable`s and `py_component`s on the page and sends them in the same request.
 */
export function fetchRouteData(route, params, snapshot, signal) {
    return __awaiter(this, void 0, void 0, function* () {
        var _a, _b, _c, _d;
        // collect payloads for annotated actions - action impls can stay on the client
        let actions = [];
        if (Array.isArray(route.on_load)) {
            actions = route.on_load;
        }
        else if (route.on_load) {
            actions = [route.on_load];
        }
        const actionPayloads = actions.filter(isAnnotatedAction).map((a) => {
            try {
                const kwargs = cleanKwargs(Object.fromEntries(Object.entries(a.dynamic_kwargs).map(([k, v]) => {
                    return [k, resolveVariableStatic(v, snapshot, params)];
                })), null);
                return {
                    uid: a.uid,
                    definition_uid: a.definition_uid,
                    values: normalizeRequest(kwargs, a.dynamic_kwargs),
                };
            }
            catch (e) {
                if (e instanceof PreloadSkipError) {
                    // on_load actions cannot use variables that require runtime resolution
                    throw new UserError(`on_load action cannot use StreamVariable or StateVariable. ` +
                        `These variables are only available at runtime after the page has loaded. ` +
                        `Consider using a regular action triggered by user interaction instead.`);
                }
                throw e;
            }
        });
        // Collect payloads for DVs and py_components,
        // preloading ones that don't have a cached value.
        // Skip variables that throw PreloadSkipError (e.g., StreamVariable, StateVariable)
        const dvHandles = Object.values((_b = (_a = route.dependency_graph) === null || _a === void 0 ? void 0 : _a.derived_variables) !== null && _b !== void 0 ? _b : {}).flatMap((dv) => {
            try {
                const handle = preloadDerivedVariable(dv, snapshot, params);
                if (!handle) {
                    return [];
                }
                return Object.assign(Object.assign({}, handle), { dv, payload: {
                        values: normalizeRequest(cleanArgs(handle.result.values, null), dv.variables),
                        uid: dv.uid,
                    } });
            }
            catch (e) {
                if (e instanceof PreloadSkipError) {
                    // Skip preloading for variables that can't be resolved statically
                    // They will be resolved at runtime instead
                    return [];
                }
                throw e;
            }
        });
        const pyHandles = Object.values((_d = (_c = route.dependency_graph) === null || _c === void 0 ? void 0 : _c.py_components) !== null && _d !== void 0 ? _d : {}).flatMap((py) => {
            try {
                const handle = preloadServerComponent(py, snapshot, params);
                if (!handle) {
                    return [];
                }
                // turn the resolved values back into an object and clean them up
                const kwargValues = cleanKwargs(Object.keys(py.props.dynamic_kwargs).reduce((acc, k, idx) => {
                    acc[k] = handle.result.values[idx];
                    return acc;
                }, {}));
                return Object.assign(Object.assign({}, handle), { py, payload: {
                        uid: py.uid,
                        name: py.name,
                        values: normalizeRequest(kwargValues, py.props.dynamic_kwargs),
                    } });
            }
            catch (e) {
                if (e instanceof PreloadSkipError) {
                    // Skip preloading for variables that can't be resolved statically
                    // They will be resolved at runtime instead
                    return [];
                }
                throw e;
            }
        });
        const dvHandlesByUid = dvHandles.reduce((acc, h) => (Object.assign(Object.assign({}, acc), { [h.dv.uid]: h })), {});
        const pyHandlesByUid = pyHandles.reduce((acc, h) => (Object.assign(Object.assign({}, acc), { [h.py.uid]: h })), {});
        const wsClient = yield window.dara.ws.getValue();
        const wsChannel = yield wsClient.getChannel();
        const response = yield request(`/api/core/route/${route.id}`, {
            method: HTTP_METHOD.POST,
            body: JSON.stringify({
                action_payloads: actionPayloads,
                derived_variable_payloads: dvHandles.map((h) => h.payload),
                py_component_payloads: pyHandles.map((h) => h.payload),
                ws_channel: wsChannel,
                params,
            }),
            signal,
        });
        yield handleAuthErrors(response, { authenticationFailureRedirect: 'login' });
        if (!response.ok) {
            const error = (yield response.json());
            throw new LoaderError(error.detail);
        }
        const template = deferred();
        const onLoadActions = deferred();
        const resolvedDvs = new Set();
        const resolvedPyComponents = new Set();
        // kick off the async generator in the background
        queueMicrotask(() => __awaiter(this, void 0, void 0, function* () {
            var _a, e_1, _b, _c;
            var _d, _e;
            try {
                try {
                    for (var _f = true, _g = __asyncValues(ndjson(response, signal)), _h; _h = yield _g.next(), _a = _h.done, !_a; _f = true) {
                        _c = _h.value;
                        _f = false;
                        const data = _c;
                        const chunk = ResponseChunk.parse(data);
                        if (chunk.type === 'template') {
                            const component = denormalize(chunk.template.data, chunk.template.lookup);
                            template.resolve(component);
                        }
                        if (chunk.type === 'actions') {
                            onLoadActions.resolve(actions.flatMap((a) => (isAnnotatedAction(a) ? chunk.actions[a.uid] : a)));
                        }
                        // process the other chunks, resolving the deferreds as they come in
                        if (chunk.type === 'derived_variable') {
                            (_d = dvHandlesByUid[chunk.uid]) === null || _d === void 0 ? void 0 : _d.handle.resolve(chunk.result);
                            resolvedDvs.add(chunk.uid);
                        }
                        if (chunk.type === 'py_component') {
                            (_e = pyHandlesByUid[chunk.uid]) === null || _e === void 0 ? void 0 : _e.handle.resolve(chunk.result);
                            resolvedPyComponents.add(chunk.uid);
                        }
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (!_f && !_a && (_b = _g.return)) yield _b.call(_g);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            }
            catch (e) {
                template.reject(e);
                onLoadActions.reject(e);
                // reject remaining unresolved promises
                for (const [uid, handle] of Object.entries(dvHandlesByUid)) {
                    if (!resolvedDvs.has(uid)) {
                        handle.handle.reject(e);
                    }
                }
                for (const [uid, handle] of Object.entries(pyHandlesByUid)) {
                    if (!resolvedPyComponents.has(uid)) {
                        handle.handle.reject(e);
                    }
                }
            }
        }));
        // return as soon as we have the template and on_load actions
        const [templateValue, onLoadActionsValue] = yield Promise.all([template.getValue(), onLoadActions.getValue()]);
        return {
            template: templateValue,
            on_load: onLoadActionsValue,
            route_definition: route,
            py_components: pyHandles,
            derived_variables: dvHandles,
        };
    });
}
/**
 * Retrieve route data from the preload cache.
 *
 * @param routeId route ID
 * @param params current route params
 */
export function getFromPreloadCache(routeId, params) {
    return preloadCache.get(createCacheKey(routeId, params));
}
/**
 * Provides a function to preload data for all routes matching a given URL.
 * Checks the preload cache first, and if not found, fetches the data from the server.
 */
export function usePreloadRoute() {
    const currentMatches = useMatches();
    const { routeObjects, routeDefMap } = useRouterContext();
    return useRecoilCallback(({ snapshot }) => (url) => __awaiter(this, void 0, void 0, function* () {
        var _a;
        // Match routes for the given URL using React Router's route objects
        const matches = matchRoutes(routeObjects, url, (_a = window.dara) === null || _a === void 0 ? void 0 : _a.base_url);
        if (!matches) {
            return;
        }
        const release = snapshot.retain();
        try {
            yield Promise.all(matches
                // filter out matches for the same exact route/param combo, i.e. don't re-fetch current route as it's unlikely user will navigate into the same route again
                .filter((match) => !currentMatches.some((m) => m.id === match.route.id && isEqual(m.params, match.params)))
                .map((match) => {
                // Find the corresponding route definition using the route ID
                const routeDef = routeDefMap.get(match.route.id);
                if (!routeDef) {
                    return Promise.resolve();
                }
                return preloadCache.setIfMissing(createCacheKey(routeDef.id, match.params), () => {
                    return fetchRouteData(routeDef, match.params, snapshot);
                });
            }));
        }
        finally {
            release();
        }
    }), [routeDefMap, routeObjects, currentMatches]);
}
//# sourceMappingURL=fetching.js.map