import { NoyaManager } from "../NoyaManager"; import { SerializableRequest } from "../rpc/types"; import { buildLocalAssetRoutes, buildLocalResourceRoutes, createJsonResponse, } from "./localRpcHelpers"; import { ParentToEmbeddedMessage } from "./parentFrameMessages"; /** * Ensure assets are persisted locally when operating without a server. * Falls back to in-memory store if IndexedDB is not available. */ /** * Attempt to handle local asset/resource RPC routes and send a response to the child. * Returns true if the request was handled, false to allow other handlers. */ export async function bridgeRpcRequestToLocalAssets< S, M extends object, E extends object, MenuT extends string, I extends Record = Record, >( noyaManager: NoyaManager, request: SerializableRequest, send: (message: ParentToEmbeddedMessage) => void, options: { offlineStorageKey: string } ): Promise { const method = request.options?.method?.toUpperCase(); const pathname = request.url.split("?")[0]; try { // Build the local route table for assets, resources, and basic lists const routes = [ ...buildLocalAssetRoutes(noyaManager, { offlineStorageKey: options?.offlineStorageKey, }), ...buildLocalResourceRoutes(noyaManager, { offlineStorageKey: options?.offlineStorageKey, }), ]; // Attempt to match and handle the request for (const r of routes) { if (r.method === method && r.pattern.test(pathname)) { const match = pathname.match(r.pattern); const body = await r.handler(request, match); if ( r.key === "GET /api/resources" || r.key === "PATCH /api/resources" ) { send({ type: "resources", resources: noyaManager.resourceManager.resources$.get(), }); } send({ type: "end", id: request.id!, response: createJsonResponse(body), }); return true; } } return false; } catch (error) { send({ type: "error", id: request.id!, error: error instanceof Error ? error.message : String(error ?? "error"), }); return true; } } export { ensureLocalAssetStore, ensureLocalResourceStore, sendLocalInitializationMessages, } from "./localRpcHelpers";