/** * The rows the frame's layer needs for an app's own code, and the generated composition row that runs the app's plugins beside the host. * * A template with `src/frame.ts` gets the app's routes row. A template whose `src/app.ts` exports `composeInto` also gets `frame/app-plugins.mjs`, one row * that composes the app exactly as its own server does (same rows, order and config; `host: true` leaves the host's infrastructure rows out). The services * the app's own rows provide are read from their sources, never a hand list, and isolated through the Loader's own entry option, so the host's DSH rows keep * their copies of the same names. * * `init` writes these for a fresh app and `upgrade` writes them for an app made before the frame: one home for the row ids, the isolate rule and the * generated file. */ import { existsSync, readdirSync, readFileSync } from 'node:fs' import { join } from 'node:path' import { FRAME_PAGE_PREFIX } from './ide-profile' /** * Rows the host mounts itself: an app's manifest may name them, but the generated layer does not. Both spellings of each: the vendored folder's * (`acryl-router`) and the blank template's row id (`router`, `server`), whose `plugins/` folder is the host's own plugin, never the app's. */ export const HOST_PROVIDED_IDS: ReadonlySet = new Set([ 'instance', 'router', 'server', 'acryl-router', 'acryl-node-server', 'acryl-web-server', 'acryl-page', 'manifest', 'save', 'acryl-door', ]) /** * Services the app's rows provide that the host's own rows call: the door and the frame reach `pluginShare`, and no host row provides that name. Left out of * the isolate list, so they find it; every other service stays in the app's realm. */ const REACHED_FROM_HOST: ReadonlySet = new Set(['pluginShare']) /** One row of the generated layer. `isolate` is the Loader's entry option: the services this row's whole subtree provides in its own realm. */ export interface FrameRow { readonly id: string readonly name: string readonly isolate?: Readonly> } /** The generated `frame/app-plugins.mjs`, by the row that mounts it. */ export const APP_PLUGINS_FILE = 'frame/app-plugins.mjs' /** * The generated row source: the app's plugins composed beside the host, with the services they provide isolated (the Loader entry option). Every * route they mount lands under the frame's app prefix (`prefix`): a plugin's `ctx.router.route('/board')` answers `/app/board` in the canvas and * `/board` on the app's own server, so a plugin never writes the prefix. `@param prefix` is the canvas prefix, {@link FRAME_PAGE_PREFIX}. */ export function appPluginsRow(prefix: string): string { return [ "// Generated by acrylblends: the app's own plugins, composed as the app's server composes them (src/app.ts composeInto). The layer row isolates the", "// services this app provides (the Loader entry option), so the host's driver rows keep their own. Every route these rows mount lands under the", `// frame's app prefix (${prefix}): a plugin's ctx.router.route('/board') answers /${prefix.replace(/^\/+/u, '')}/board in the canvas and /board on the app's own server.`, "import { composeInto } from '../src/app.ts'", '', "export const name = 'app-plugins'", "export const inject = ['appInstance', 'router']", '', '/** The path a route lands at under the prefix: "/" is the prefix itself, a path already under it stays as it is. */', 'function prefixedAppRoute(prefix, path) {', " const base = prefix.replace(/\\/+$/, '')", " if (base === '') return path", " if (path === '' || path === '/') return base", " return path === base || path.startsWith(base + '/') ? path : base + (path.startsWith('/') ? '' : '/') + path", '}', '', "/** The router as the app's rows see it: mounts land under the prefix, and a plugin's own request (its install check) finds them there; every other member is the host router's. */", 'function appRouter(router, prefix) {', ' const route = (path, app) => router.route(prefixedAppRoute(prefix, path), app)', " const request = (input, ...rest) => router.request(typeof input === 'string' && input.startsWith('/') ? prefixedAppRoute(prefix, input) : input, ...rest)", ' return new Proxy(router, {', ' get(target, property) {', " if (property === 'route') return route", " if (property === 'request') return request", ' const value = Reflect.get(target, property, target)', " return typeof value === 'function' ? value.bind(target) : value", ' },', ' })', '}', '', 'export async function apply(ctx, config) {', ` const prefix = typeof config?.appPrefix === 'string' ? config.appPrefix : ${JSON.stringify(prefix)}`, " // The rows read ctx.router as the app's own router: the same paths as on their own server, under the frame's prefix. A getter, read by each plugin", ' // from its own context: it gets the host router traced for that context, so a route it mounts is its own and goes when the plugin is removed', " // (a router taken once here would make every route this row's, served until the whole app reloads).", " const appScope = ctx.extend({ get router() { return appRouter(this.get('router'), prefix) } })", ' const fibers = await composeInto(appScope, ctx.appInstance, { host: true })', " ctx.effect(() => () => { for (const fiber of [...fibers].reverse()) void fiber.dispose() }, 'app-plugins: dispose')", '}', '', ].join('\n') } /** Whether an app's composition root is the one `composeInto` makes: the row can call it only then. */ export function carriesComposeInto(appTs: string): boolean { return appTs.includes('export async function composeInto') } /** The ids of the app's own rows (blend.yaml), without the ones the host provides. */ function ownRowIds(appDir: string): string[] { const blend = join(appDir, 'blend.yaml') if (!existsSync(blend)) return [] const ids: string[] = [] for (const match of readFileSync(blend, 'utf8').matchAll(/^\s*- id:\s*(\S+)\s*$/gmu)) if (!HOST_PROVIDED_IDS.has(match[1] as string)) ids.push(match[1] as string) return ids } /** The service names the app's own plugins provide, read from their sources. */ function providedServices(appDir: string): Record { const provided = new Set() const walk = (folder: string): void => { if (!existsSync(folder)) return for (const entry of readdirSync(folder, { withFileTypes: true })) { const path = join(folder, entry.name) if (entry.isDirectory()) { walk(path) continue } if (!/\.(ts|tsx|mjs)$/u.test(entry.name)) continue const text = readFileSync(path, 'utf8') for (const match of text.matchAll(/super\(\s*ctx\s*,\s*['"]([\w.-]+)['"]/gu)) provided.add(match[1] as string) for (const match of text.matchAll(/reflect\.provide\(\s*['"]([\w.-]+)['"]/gu)) provided.add(match[1] as string) for (const match of text.matchAll(/ctx\.provide\(\s*['"]([\w.-]+)['"]/gu)) provided.add(match[1] as string) } } for (const row of ownRowIds(appDir)) walk(join(appDir, 'plugins', row)) return Object.fromEntries( [...provided] .filter((name) => !REACHED_FROM_HOST.has(name)) .sort() .map((name) => [name, true as const]), ) } export interface AppFrameRows { /** The layer rows, in order: the app's plugins first, then its routes. Empty for an app with no `src/frame.ts`. */ readonly rows: readonly FrameRow[] /** The generated row file's text, when the app's composition exports `composeInto`; the caller writes it. */ readonly appPlugins: string | undefined } /** * The frame rows for an app: its routes row when it carries `src/frame.ts`, and the composition row when its `src/app.ts` exports `composeInto`. * `appTs` and `hasFrame` let a caller plan against the files it is about to write (an upgrade replacing the scaffold) rather than the ones on disk. */ export function appFrameRows( appDir: string, options: { appTs?: string; hasFrame?: boolean } = {}, ): AppFrameRows { if (options.hasFrame !== true && !existsSync(join(appDir, 'src', 'frame.ts'))) return { rows: [], appPlugins: undefined } const appTs = options.appTs ?? readAppTs(appDir) const composes = appTs !== undefined && carriesComposeInto(appTs) const rows: FrameRow[] = [] if (composes) { const isolate = providedServices(appDir) rows.push({ id: 'app-plugins', name: `./${APP_PLUGINS_FILE}`, ...(Object.keys(isolate).length === 0 ? {} : { isolate }), }) } rows.push({ id: 'app-routes', name: './src/frame.ts' }) return { rows, appPlugins: composes ? appPluginsRow(FRAME_PAGE_PREFIX) : undefined } } function readAppTs(appDir: string): string | undefined { const file = join(appDir, 'src', 'app.ts') return existsSync(file) ? readFileSync(file, 'utf8') : undefined }