@_linked/server 2.23.1 β†’ 2.24.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"LinkedServer.js","sourceRoot":"","sources":["../../../src/shapes/LinkedServer.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;;;;;;;AACb,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACzC,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,OAAqC,MAAM,SAAS,CAAC;AAC5D,OAAO,WAAW,MAAM,cAAc,CAAC;AACvC,OAAO,KAAK,QAAQ,MAAM,IAAI,CAAC;AAC/B,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAElC,oEAAoE;AACpE,oEAAoE;AACpE,oEAAoE;AACpE,0BAA0B;AAC1B,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AAEjF,OAAO,EAAE,UAAU,EAAE,MAAM,wCAAwC,CAAC;AACpE,OAAO,EAAE,UAAU,EAAE,MAAM,wCAAwC,CAAC;AACpE,OAAO,EAAE,MAAM,EAAE,MAAM,oCAAoC,CAAC;AAC5D,OAAO,EAAE,eAAe,EAAE,MAAM,6CAA6C,CAAC;AAC9E,OAAO,EAAE,aAAa,EAAE,MAAM,2CAA2C,CAAC;AAC1E,OAAO,EACL,cAAc,EACd,eAAe,EACf,WAAW,EACX,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,KAAK,EAAE,MAAM,4BAA4B,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,wCAAwC,CAAC;AAC5E,OAAO,EACL,iBAAiB,EACjB,iBAAiB,GAClB,MAAM,uCAAuC,CAAC;AAE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GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,KAAK,IAAI,GAAG,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;QAC1D,OAAO,MAAM,CAAC,sBAAsB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACjD,CAAC,CAAC,CACH,CAAC;IACF,GAAG,CAAC,IAAI,CACN,oBAAoB,EACpB,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,CACzC,MAAM,CAAC,wBAAwB,CAAC,GAAG,EAAE,GAAG,CAAC,CAC1C,CACF,CAAC;IACF,GAAG,CAAC,IAAI,CACN,2BAA2B,EAC3B,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,CACzC,MAAM,CAAC,sBAAsB,CAAC,GAAG,EAAE,GAAG,CAAC,CACxC,CACF,CAAC;IACF,GAAG,CAAC,IAAI,CACN,uBAAuB,EACvB,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,CACzC,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,CACxC,CACF,CAAC;IACF,GAAG,CAAC,GAAG,CACL,uBAAuB,EACvB,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,EAAE,CACzC,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,CAAC,CACvC,CACF,CAAC;AACJ,CAAC","sourcesContent":["'use strict';\nimport { timingSafeEqual } from 'crypto';\nimport events from 'events';\nimport express, { Express as ExpressServer } from 'express';\nimport fetchCookie from 'fetch-cookie';\nimport * as fsNative from 'fs';\nimport * as fs from 'fs/promises';\nimport { Server as HttpServer } from 'http';\n// Plan-011: imports from @_linked/cli now go through ./lifecycle (a\n// dynamic-import-free file) so Vite's SSR module graph doesn't pull\n// in the legacy webpack flow and emit dozens of unanalyzable-import\n// warnings on every boot.\nimport { getLincdPackages } from '@_linked/cli/lifecycle';\nimport { getPackageJSON } from '@_linked/cli/utils';\nimport type { LinkedConfig } from '@_linked/cli/interfaces';\nimport { AppContextProvider } from '@_linked/server-utils/components/AppContext';\nimport { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';\nimport { JSONParser } from '@_linked/server-utils/utils/JSONParser';\nimport { JSONWriter } from '@_linked/server-utils/utils/JSONWriter';\nimport { Server } from '@_linked/server-utils/utils/Server';\nimport { ServerCallError } from '@_linked/server-utils/utils/ServerCallError';\nimport { ShapeProvider } from '@_linked/server-utils/utils/ShapeProvider';\nimport {\n getCallContext,\n httpCallContext,\n runAsSystem,\n runInHttpContext,\n runWithCallContext,\n} from '@_linked/server-utils/utils/CallContext';\nimport { Shape } from '@_linked/core/shapes/Shape';\nimport { LinkedErrorLogging } from '@_linked/core/utils/LinkedErrorLogging';\nimport {\n FileStorePurposes,\n LinkedFileStorage,\n} from '@_linked/core/utils/LinkedFileStorage';\nimport type { IFileStore } from '@_linked/core/interfaces/IFileStore';\nimport { getResizedImagesStore } from '../utils/resizedImagesPurpose.js';\nimport { paint } from '../utils/paint.js';\nimport { createJsonBodyParser } from '../utils/jsonBodyParser.js';\nimport { LinkedStorage } from '@_linked/core/utils/LinkedStorage';\nimport { autoLoadOntologyData } from '@_linked/core/utils/Package';\nimport {\n getShapeClass,\n getSuperShapesClasses,\n} from '@_linked/core/utils/ShapeClass';\nimport path from 'path';\nimport {pathToFileURL} from 'node:url';\nimport { isFatalError } from '../utils/fatalError.js';\nimport {\n discoverLinkedDependencies,\n isBundledBySsr,\n NODE_IMPORT_CONDITIONS,\n readInstalledPackage,\n resolveBackendEntry,\n ssrNoExternalOf,\n} from '../utils/linkedDependencies.js';\n\n/**\n * `instanceof ShapeProvider`, tolerating a second copy of server-utils.\n *\n * A registry-installed package's backend is loaded by Node (see\n * isBundledBySsr), so in a dev runner that BUNDLES server-utils β€” the\n * standalone case β€” its providers extend Node's copy of ShapeProvider, not the\n * one this module imported. Fall back to the class name along the prototype\n * chain. Production has one loader and one copy, so instanceof decides there.\n */\nfunction isShapeProvider(provider: any): boolean {\n if (provider instanceof ShapeProvider) return true;\n for (\n let proto = provider ? Object.getPrototypeOf(provider) : null;\n proto && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto)\n ) {\n if (proto.constructor?.name === 'ShapeProvider') return true;\n }\n return false;\n}\n\n/**\n * Call one provider's hook and contain its failure: a synchronous throw or a\n * rejection is logged, naming the package and the hook, and swallowed. Used\n * for hooks that run for every provider (boot lifecycle hooks and per-request\n * hooks), where one provider's bug must not take down boot or every request\n * without saying which provider it was.\n *\n * The exception is a fatal error (see utils/fatalError): with `atBoot` it is\n * logged and re-thrown, so the server refuses to start. Without it β€” the\n * server is already serving β€” it is logged as fatal and contained like any\n * other error: one provider must not take a running server down.\n */\nasync function runProviderHook(\n pkg: string,\n hook: string,\n call: () => any,\n atBoot = false\n): Promise<void> {\n try {\n await call();\n } catch (err: any) {\n if (isFatalError(err)) {\n logFatalError(pkg, hook, err, atBoot);\n if (atBoot) throw err;\n return;\n }\n console.error(\n paint('red', `[linked] ${pkg} ${hook} failed: ${err?.message ?? err}`),\n err?.stack ? `\\n${err.stack}` : ''\n );\n }\n}\n\n/** Log a fatal error once, at the point it was thrown (see runProviderHook). */\nfunction logFatalError(pkg: string, hook: string, err: any, atBoot: boolean) {\n if (loggedFatalErrors.has(err)) return;\n loggedFatalErrors.add(err);\n console.error(\n paint(\n 'red',\n atBoot\n ? `[linked] ${pkg} ${hook}: fatal error, refusing to start: ${err?.message ?? err}`\n : `[linked] ${pkg} ${hook}: fatal error after start, server keeps running: ${err?.message ?? err}`\n ),\n err?.stack ? `\\n${err.stack}` : ''\n );\n}\nconst loggedFatalErrors = new WeakSet<object>();\n\nimport process from 'process';\nimport * as React from 'react';\nimport { renderToPipeableStream, renderToStaticMarkup } from 'react-dom/server';\nimport { StaticRouter } from 'react-router-dom/server.js';\nimport { rimraf } from 'rimraf';\nimport sharp from 'sharp';\nimport {\n findStoredKey,\n resolveResizeSource,\n} from '../utils/resizeSource.js';\nimport { Transform } from 'stream';\nimport { CookieJar } from 'tough-cookie';\nimport { server } from '../ontologies/server.js';\nimport { linkedShape } from '../package.js';\nimport {\n resolveStaticAccessURL,\n staticAssetURL,\n} from '../utils/releaseManifest.js';\nimport {\n resolveBootstrapEntry,\n resolveViteMainEntry,\n resolveViteServingMode,\n} from '../utils/bootstrapEntry.js';\nimport { resolveRouteAssets } from '../utils/routeAssets.js';\nimport {\n resolveRouteComponent,\n ssrCssInlineUrls,\n ssrCssScope,\n} from '../utils/ssrCss.js';\nimport { indexShapesIntoMemory } from '../utils/Shapes.js';\nimport { materializeShapes } from '../utils/syncShapes.js';\nimport {\n installSpaFallback,\n repinSpaFallback,\n} from '../utils/spaFallback.js';\nimport { LincdAPI } from './LincdAPI.js';\nimport type { RoutesConfig, RouteConfig } from '../types/RouteConfig.js';\nimport {\n getRpcExposureMode,\n isGenericRpcDisabled,\n logSafe,\n resolveCallable,\n setRpcExposureMode,\n warnUndeclaredCall,\n} from '../utils/rpcExposure.js';\nimport { setRawQueriesMode } from '../utils/rawQueries.js';\n\n//prevent errors in node.js when (s)css files are imported in js\nconst isProduction = process.env.NODE_ENV === 'production';\nconst isDevelopment = process.env.NODE_ENV === 'development';\n\ndeclare var globalThis: any;\n// Install a global fetch that persists cookies across redirects using a CookieJar.\n// This ensures server-side requests behave more like browsers when handling Set-Cookie + redirects.\nconst __lincdCookieJar = new CookieJar();\n// Wrap native fetch with fetch-cookie so it reads/writes cookies in the jar.\nconst __lincdFetchWithCookies = fetchCookie(fetch, __lincdCookieJar);\n\n// Expose (optionally) for debugging/tests; not required by app logic.\n(globalThis as any).__lincdCookieJar = __lincdCookieJar;\n\n// Set the global fetch used throughout the server code path\n(globalThis as any).fetch = __lincdFetchWithCookies;\n\nprocess.on('uncaughtException', (err) => {\n console.warn(paint('red', 'Asynchronous error caught.'));\n console.error(err);\n\n // error logging\n LinkedErrorLogging.log(err);\n});\nprocess.on('unhandledRejection', (err) => {\n console.warn(paint('red', 'Unhandled rejection caught.'));\n console.error(err);\n\n // error logging\n LinkedErrorLogging.log(err as Error);\n});\n\nprocess.on('warning', (e) => console.warn(e.stack));\n\n//allow more listeners for when we have many concurrent users\nevents.EventEmitter.prototype.setMaxListeners(500);\n\n// const jsdom = require(\"jsdom\");\n// const { JSDOM } = jsdom;\n// const { document } = (new JSDOM(`...`)).window;\n//\n// global['document'] = document;\nglobal['reactStaticRenderer'] = renderToStaticMarkup;\n\nautoLoadOntologyData(true);\n\n/**\n * How RPC arguments treat a `{__sc}` (live Shape class) marker. No call takes a\n * Shape class from the client: logged in 'warn', refused (400) in 'enforce'.\n */\nfunction rpcShapeClassRevival(): 'warn' | 'reject' {\n return getRpcExposureMode() === 'enforce' ? 'reject' : 'warn';\n}\n\n/**\n * Serve the local upload folder at `/uploads` (where `LocalFileStore` files are\n * reachable), with the headers for untrusted files.\n */\nexport function mountUploads(\n app: { use: Function },\n folder: string = './data/uploads',\n maxAge: number = 1000 * 60 * 60 * 24 * 365\n): void {\n app.use(\n '/uploads',\n express.static(folder, {\n maxAge, // cache for a long time\n immutable: true, // Suggest that the content won't change\n // uploaded files are user content: never sniffed, never run as a page\n setHeaders: setUntrustedFileHeaders,\n })\n );\n}\n\n/**\n * Express middleware: run the rest of the chain in the request's http context.\n * `LinkedServer.start` installs it first, and again right after the JSON body\n * parser (whose stream callbacks do not carry the context).\n */\nexport function enterRequestContext(req, res, next) {\n runInHttpContext(req, res, next);\n}\n\n/**\n * Headers for files users uploaded (`/uploads`, resized copies): the browser\n * must not guess a type from the bytes, and a document served from them runs\n * sandboxed (no scripts, an opaque origin), so an uploaded HTML or SVG file\n * cannot act on the app's origin.\n */\nexport function setUntrustedFileHeaders(res) {\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('Content-Security-Policy', 'sandbox');\n}\n\n/** Whether the current HTTP call carries a session. */\nfunction hasSession(request): boolean {\n return !!request?.linkedAuth?.userAccount;\n}\n\n// Named explicitly: tsc emits `let X = class X`, and any later esbuild pass over that JS (Vite's\n// SSR `define` replacement runs one on every file mentioning a defined `process.env.*`) renames\n// the inner binding to `X2`, which would otherwise become this shape's IRI.\n@linkedShape({name: 'LinkedServer'})\nexport class LinkedServer extends Shape {\n /**\n * indicates that instances of this shape need to have this rdf.type\n */\n static targetClass = server.LincdServer;\n private config: LinkedConfig;\n private cachedPaths: Map<string, string> = new Map();\n private assets: { [key: string]: string } & {\n manifest?: Record<string, string>;\n };\n /**\n * Whether pages are served by the live Vite dev server rather than a\n * `vite build` on disk. Decided once in `start()` β€” see\n * utils/bootstrapEntry `resolveViteServingMode`.\n */\n private viteDevServer = false;\n /**\n * Base URL every asset this build produced is served from β€” resolved once in\n * `start()` and kept so per-request route chunks land on the same base as\n * the entry tags. Empty means origin-relative (development, and any app\n * serving its own bundles).\n */\n private staticAccessURL: string = '';\n /**\n * Whether `assets['main.js']` came from a Vite build. Vite always emits the\n * entry as an ES module, so it has to be bootstrapped with\n * `bootstrapModules`; a legacy webpack bundle is a classic script and must\n * keep `bootstrapScripts`.\n */\n private mainEntryIsModule = false;\n protected server: ExpressServer;\n protected httpServer: HttpServer;\n private package: any;\n private cacheWebpack: boolean;\n private cssMode = 'scss-modules';\n private analyse: boolean = false;\n private shapeProviders: Map<string, ShapeProvider[]> = new Map();\n private genericProviders: Map<string, BackendProvider> = new Map();\n // One indexing per package: boot and the lazy /call path share it, so two\n // concurrent first calls (or a call racing boot) never construct a\n // package's providers twice.\n private providerIndexing: Map<string, Promise<void>> = new Map();\n /**\n * Package name β†’ realpath of the installed copy whose backend is loaded,\n * as discovery found it. A package's backend is resolved from THIS\n * directory, never by its bare name from @_linked/server's own location:\n * Node would never look inside another package's nested node_modules, so a\n * linked package installed only there (owl/node_modules/@_linked/rdfs)\n * could not be loaded at all.\n */\n private linkedPackageDirs: Map<string, string> = new Map();\n private warnedDuplicateInstalls: Set<string> = new Set();\n //from resizedFileName to full resized path (CDN or similar)\n private resizePathsMap: Map<string, string> = new Map();\n private api: LincdAPI;\n /**\n * True while start() / initOnly() runs. A fatal provider error (see\n * utils/fatalError) thrown while booting stops the boot; after it, the same\n * error is logged and contained.\n */\n protected booting = false;\n\n /**\n * yarn linked start sends the contents of linked.config.js as an object to this constructor\n * @param n\n */\n constructor(config?: LinkedConfig | string | { id?: string }) {\n super(\n typeof config === 'string' || (config && 'id' in config)\n ? config\n : undefined\n );\n if (config && typeof config !== 'string' && !('id' in config)) {\n // The absence of `id` is the runtime discriminator for a LinkedConfig;\n // the widened `{id?: string}` member of the union keeps TS from narrowing\n // to it on that check alone.\n this.config = config as LinkedConfig;\n }\n\n this.api = new LincdAPI({ id: process.env.SITE_ROOT + '/api' });\n\n //Ensure the Server utility (for Server.call()) directly accesses\n // this server on the backend instead of going through a network call\n Server.setLocalServer(this);\n }\n\n /*async getLincdDependencies(): Promise<string[]> {\n\t\tlet lincdDependencies = [];\n\t\tlet dependencies = this.package.dependencies;\n\n\t\tawait Promise.all(\n\t\t\tObject.keys(dependencies).map((dependencyPkgName) => {\n\t\t\t\tlet modulePackageJson = getModulePackageJSON(dependencyPkgName);\n\t\t\t\tif (modulePackageJson['lincd']) {\n\t\t\t\t\tlincdDependencies.push(modulePackageJson.name);\n\t\t\t\t}\n\t\t\t\t// //TODO: also iteratively look into dependencies of this dependency\n\n\t\t\t\t// let packagePath;\n\t\t\t\t// try {\n\t\t\t\t// packagePath = require.resolve(`${dependencyPkgName}`);\n\t\t\t\t// } catch (err) {\n\t\t\t\t// console.warn('Could not find package ' + dependencyPkgName+'. Error: '+err.toString());\n\t\t\t\t// return;\n\t\t\t\t// }\n\t\t\t\t// packagePath = path.dirname(packagePath) + '/package.json'\n\t\t\t\t// return fs\n\t\t\t\t// .readFile(packagePath, 'utf-8')\n\t\t\t\t// .then((res) => {\n\t\t\t\t// let pkg = JSON.parse(res);\n\t\t\t\t// if (pkg['lincd']) {\n\t\t\t\t// lincdDependencies.push(pkg.name);\n\t\t\t\t// }\n\t\t\t\t\t// //TODO: also iteratively look into dependencies of this dependency\n\t\t\t\t\t// })\n\t\t\t\t\t// .catch((err) => {\n\t\t\t\t\t// console.log('Could not read package.json file: '+err);\n\t\t\t\t\t// });\n\t\t\t}),\n\t\t);\n\t\treturn lincdDependencies;\n\t}*/\n get app() {\n return this.server;\n }\n\n initPackage() {\n this.package = JSON.parse(\n fsNative.readFileSync(\n path.resolve(process.cwd(), 'package.json'),\n 'utf-8'\n )\n );\n }\n async initOnly() {\n return this.bootOrRefuse(() => this.initOnlyBoot());\n }\n\n private async initOnlyBoot() {\n await this.initOntologies();\n await this.initStores();\n\n this.initPackage();\n\n this.server = express();\n\n await this.initBackendProviders();\n\n await indexShapesIntoMemory();\n await this.materializeShapesIntoStore();\n return this;\n }\n\n /**\n * Materialize this server's registered shapes into the RDF store as SHACL\n * (core `syncShapes` β†’ pure `sh:NodeShape` + property shapes), so a running\n * app's app-data holds the shapes its instances validate/query against\n * (plan-010 T1e.2). Whatever shapes the app package registers (published\n * re-exports + generated) get written on boot (and re-run on shape-file HMR).\n *\n * Additive only: store shapes this process did not register are left alone\n * unless the operator sets `LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true` β€” see\n * `bootOrphanScope` in utils/syncShapes for why.\n *\n * Gated to servers whose DEFAULT dataset is a **concrete** materializable store\n * (detected via `rawQuery`) β€” i.e. an app pointing at its app-data FusekiStore.\n * CN's default is the context-routing `AppDataRouter` (no `rawQuery`), so CN is\n * skipped here β€” it materializes its own pinned native shapes in its storage\n * config.\n */\n private async materializeShapesIntoStore(): Promise<void> {\n // Opt-out via `linked.config` `syncShapesOnBoot` (default true); env\n // LINKED_SYNC_SHAPES_ON_BOOT overrides for deployment. CN sets\n // `syncShapesOnBoot: false` in its own linked.config β€” its default dataset is\n // a context-router that can't materialize context-free, and it syncs its own\n // pinned shapes separately (linked.backend.storage.js).\n const configFlag = (this.config as any)?.syncShapesOnBoot;\n const envFlag = process.env.LINKED_SYNC_SHAPES_ON_BOOT;\n if (configFlag === false || envFlag === 'false') {\n return;\n }\n const appData = LinkedStorage.getDefaultDataset();\n if (!appData) return;\n try {\n const {syncShapes} = await import('@_linked/core');\n // Explicit target: materialize EVERY registered shape into the app's own\n // data store regardless of per-shape routing/pins.\n await materializeShapes(appData, syncShapes as any);\n } catch (err) {\n console.warn('[LinkedServer] shape materialization failed (non-fatal):', err);\n }\n }\n\n // async serveData(req,res) {\n // let nodeURI = `${req.protocol}://${req.get('host')}${req.originalUrl}`;\n //\n // let store = LinkedStorage.getDatasets().find(store => {\n // return nodeURI.includes(store.namedNode.uri)\n // })\n // }\n\n /**\n * Boot the server and listen. Rejects β€” and makes the process exit non-zero β€”\n * when a provider throws a fatal error while booting (see utils/fatalError).\n */\n async start() {\n return this.bootOrRefuse(() => this.startBoot());\n }\n\n /**\n * Run a boot with `booting` set. A fatal provider error rejects it and hands\n * the error to exitAfterFatalStartupError; any other boot error rejects as it\n * always did.\n */\n private async bootOrRefuse<T>(boot: () => Promise<T>): Promise<T> {\n this.booting = true;\n try {\n return await boot();\n } catch (err) {\n if (isFatalError(err)) this.exitAfterFatalStartupError(err);\n throw err;\n } finally {\n this.booting = false;\n }\n }\n\n /**\n * Make sure a server that refused to start does not stay up as a process.\n *\n * start() rejects either way, so the caller can report the error. But a\n * rejected start() does not end the process on its own: the CLI's `linked\n * start` turns an unhandled rejection into a log line, and the Vite dev\n * server, a store connection or a provider's timer keeps the event loop\n * alive. So the exit code is set now β€” a process with nothing left running\n * exits 1 β€” and, as a backstop, the process is exited after a moment, on an\n * unref'd timer that never itself keeps the process alive.\n *\n * Override to embed the server somewhere that must not exit (tests).\n */\n protected exitAfterFatalStartupError(_err: unknown) {\n process.exitCode = 1;\n setTimeout(() => process.exit(1), 1000).unref();\n }\n\n private async startBoot() {\n this.initPackage();\n // 'warn' (default) or 'enforce'; see utils/rpcExposure.\n setRpcExposureMode((this.config?.server as any)?.rpcExposure);\n // 'session' (default) or 'off'; see utils/rawQueries.\n setRawQueriesMode((this.config?.server as any)?.rawQueries);\n // Static assets should come from the static store URL (versioned path),\n // not the upload store URL. An explicit STATIC_ACCESS_URL still wins;\n // otherwise the release manifest `linked build-app` wrote next to the\n // bundle says which published release this build is, so a deployment no\n // longer has to repeat that URL by hand. See utils/releaseManifest.\n // In development we deliberately use a relative path so bundle URLs work\n // regardless of which PORT the dev server bound to (browsers resolve\n // relative URLs against window.location.origin). Hardcoding SITE_ROOT\n // baked :4000 into every SSR'd HTML page.\n const isDevAssets = process.env.NODE_ENV === 'development';\n const staticAccessURL = resolveStaticAccessURL({\n isDevAssets,\n appRoot: process.cwd(),\n fileStoreAccessURL: LinkedFileStorage.accessURL,\n });\n this.staticAccessURL = staticAccessURL;\n const staticAsset = (assetPath: string) =>\n staticAssetURL(staticAccessURL, assetPath);\n\n // Bundle/manifest read (plan-011: Vite is the only supported build).\n // Vite manifest lives at public/bundles/.vite/manifest.json.\n this.assets = {\n 'main.js':\n staticAsset('/bundles/main.bundle.js') + '?v=' + this.package.version,\n 'main.css': staticAsset('/bundles/main.css'),\n };\n // Dev or built, decided once and reused by the render path β€” see\n // utils/bootstrapEntry. In development the build manifest is not read:\n // one left on disk by an earlier `vite build` would otherwise swap in\n // stale built CSS while Vite serves the live styles.\n const servingMode = resolveViteServingMode({\n viteConfig: (this.config.server as any)?.vite,\n nodeEnv: process.env.NODE_ENV,\n readManifest: () => {\n try {\n const viteManifestPath = path.resolve(\n process.cwd(),\n 'public/bundles/.vite/manifest.json'\n );\n if (!fsNative.existsSync(viteManifestPath)) return null;\n return JSON.parse(fsNative.readFileSync(viteManifestPath, 'utf-8'));\n } catch (err) {\n console.warn('Could not load bundle manifest:', err);\n return null;\n }\n },\n });\n this.viteDevServer = servingMode.viteDevServer;\n if (servingMode.manifest) {\n const viteManifest = servingMode.manifest as Record<string, any>;\n this.assets.manifest = viteManifest;\n // Resolve main entry per Vite manifest shape:\n // { \"src/index.tsx\": { file: \"assets/main-<hash>.js\", css: [...] } }\n const mainEntry = resolveViteMainEntry(viteManifest);\n if (mainEntry?.file) {\n this.assets['main.js'] = staticAsset(`/bundles/${mainEntry.file}`);\n this.mainEntryIsModule = true;\n }\n if (mainEntry?.css?.[0]) {\n this.assets['main.css'] = staticAsset(`/bundles/${mainEntry.css[0]}`);\n }\n }\n // Vite dev marker: the HTML renderer skips pre-built CSS/JS link tags,\n // because Vite handles asset injection itself.\n if (this.viteDevServer) {\n this.assets['__viteDev'] = '1';\n }\n\n const isProduction = process.env.NODE_ENV === 'production';\n if (!isProduction && this.config.cssMode === 'tailwind') {\n this.assets['tailwind-cdn'] = 'https://cdn.tailwindcss.com';\n }\n\n //for multicore we use PM2, and each instance needs to listen to port 0.\n // whilst the main thread will listen to env.PORT automatically\n // const PORT = this.config.multiCore ? 0 : process.env.PORT || 3000;\n // const publicPort = process.env.PORT || 3000;\n //update: back to original setup. multicore handles itself inside @semantu/multicore\n const PORT = parseInt(process.env.PORT) || 4000;\n this.server = express();\n\n const dirName = path.resolve(process.cwd(), 'frontend');\n\n await this.initOntologies();\n //TODO: when we do not keep all data in memory (and thus do not need to rely on in memory data for page requests), we can possibly remove await here, since all stores handle their own initialisation before executing commands\n await this.initStores();\n\n this.initGarbageCollection();\n // this.app.use((req, res, next) => {\n // console.log('start request');\n // next();\n // });\n // before controllers\n await this.initBackendProviders();\n\n await indexShapesIntoMemory();\n await this.materializeShapesIntoStore();\n\n //START OF EXPRESS ROUTES AND MIDDLEWARE\n\n //use cors\n // var corsOptions = {\n // origin: ['http://localhost:4001', 'https://www.mynd.site'],\n // optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204\n // };\n // Every request runs in its own http call context, from the first layer\n // on: no handler (middleware, routers, error handlers) ever runs without\n // one. The context is kept on the request, so a layer that resumes from a\n // callback that lost it (a body parser's stream events) re-enters the same\n // one below.\n this.server.use(enterRequestContext);\n //accept JSON bodies\n this.server.use(createJsonBodyParser());\n this.server.use(enterRequestContext);\n\n // this.server.use(cors(corsOptions));\n //\n // //compress server output with gzip,\n //UPDATE ive set level to 2 (low compression fast speed) because responses were taking too long (98% of server time was used by compress)\n // this.server.use(compress({level: 2}));\n\n await this.callGenericBackendProvidersMethod('setupBeforeControllers');\n\n // Vite middleware (plan 010): when the user app starts via Vite\n // (`linked start --vite`), the orchestrator passes the Vite handle\n // through config.server.viteMiddleware. We mount it and skip the\n // entire webpack-dev-middleware setup below.\n const viteMiddleware = (this.config.server as any)?.viteMiddleware;\n if (viteMiddleware) {\n this.server.use(viteMiddleware);\n }\n\n // Plan-011: legacy webpack-dev-middleware branch removed. Under Vite\n // (the only supported dev path now) `viteMiddleware` is set, which\n // previously forced `skipBuild = true` and made this whole block\n // dead. Removing it ends the static dependency on @_linked/cli/\n // config-webpack-app (full of dynamic imports Vite couldn't analyze)\n // and shrinks LinkedServer's import surface considerably.\n\n // //map URL routes to file paths\n const oneYear = 1000 * 60 * 60 * 24 * 365; // in milliseconds\n const oneMonth = 1000 * 60 * 60 * 24 * 30; // in milliseconds\n this.server.use(\n '/public',\n express.static('./public', {\n maxAge: oneYear, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n\n mountUploads(this.server, './data/uploads', oneYear);\n this.server.use('/', express.static('./public/root'));\n this.server.use(\n '/favicon.ico',\n express.static('./public/favicon.ico', {\n maxAge: oneMonth, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n this.server.use('/.well-known', express.static('./public/.well-known'));\n\n // this.server.post('/data',this.handleErrorsJson(async (req,res) => this.serveData(req, res)));\n this.server.get('/resized/*', async (req, res) => {\n this.resizeImage(req, res);\n });\n\n registerCallRoutes(this.server, this);\n // this.server.post(\n // '/api/query/:method',\n // this.handleErrorsJson(async (req, res) => this.processQuery(req, res)),\n // );\n\n // now that all the middleware is defined, we initialise the providers, before we define a catch-all route\n // before catch all\n // await this.initBackendProviders();\n await this.callGenericBackendProvidersMethod(\n 'setupBeforeCatchAllControllers'\n );\n\n // HEAD catch-all for maintenance/health check (client fetches SITE_ROOT with method: HEAD)\n this.server.head('__health', (_req, res) => {\n res.sendStatus(200);\n });\n\n // CN control channel (plan-010 T1b.3). Present only when CN spawned this\n // process with a shared secret (CN_APP_ADMIN_SECRET); a standalone app run\n // without the secret leaves the channel closed (404). Auth is the\n // x-cn-admin-secret header matching that env value.\n const adminSecret = process.env.CN_APP_ADMIN_SECRET;\n // Constant-time compare so the secret can't be recovered by timing the 401\n // response. timingSafeEqual requires equal-length buffers, so guard length.\n const secretMatches = (provided: string | undefined): boolean => {\n if (!adminSecret || !provided) return false;\n const a = Buffer.from(provided);\n const b = Buffer.from(adminSecret);\n return a.length === b.length && timingSafeEqual(a, b);\n };\n const requireAdmin = (req: express.Request, res: express.Response): boolean => {\n if (!adminSecret) {\n res.sendStatus(404); // no control channel in this mode\n return false;\n }\n if (!secretMatches(req.get('x-cn-admin-secret'))) {\n res.sendStatus(401);\n return false;\n }\n return true;\n };\n this.server.get('/admin/health', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.status(200).json({ status: 'ok' });\n });\n this.server.post('/admin/restart', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.sendStatus(202);\n // CN's provisioner respawns on exit (see ChildProcessProvisioner).\n setTimeout(() => process.exit(0), 50);\n });\n\n // after controller\n await this.callGenericBackendProvidersMethod('setupAfterControllers');\n\n // The SPA catch-all goes on LAST. `setupAfterControllers` is a documented\n // hook for providers to register their own routes, so installing the\n // catch-all before it would shadow every GET route registered there β€”\n // answering them with the client shell at status 200.\n // An API-only backend (`linked start --api-only`) has no app to render:\n // without the catch-all, page requests get express's plain 404.\n if (!(this.config.server as any)?.apiOnly) {\n this.installSpaFallback();\n }\n\n //remove http(s):// and remove port :[port]\n const HOST = process.env.SITE_ROOT.replace(/https?:\\/\\//, '').replace(\n /:\\d+$/,\n ''\n );\n\n //backlog of 1024 means maximum of 1024 connections in the queue (higher than default)\n this.httpServer = this.server.listen({ port: PORT, backlog: 1024 }, () => {\n console.log(`Up and running at http://localhost:${PORT}`);\n // open(`http://localhost:${PORT}`)\n });\n // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n this.httpServer.keepAliveTimeout = 60_000;\n // Ensure the headersTimeout is set higher than the keepAliveTimeout due to this nodejs regression bug: https://github.com/nodejs/node/issues/27363\n this.httpServer.headersTimeout = 61_000;\n\n this.httpServer.on('error', function (error) {\n if (error['syscall'] !== 'listen') {\n throw error;\n }\n const isPipe = (portOrPipe) => Number.isNaN(portOrPipe);\n const bind = isPipe(PORT) ? 'Pipe ' + PORT : 'Port ' + PORT;\n switch (error['code']) {\n case 'EACCES':\n console.error(bind + ' requires elevated privileges');\n process.exit(1);\n case 'EADDRINUSE':\n console.error(bind + ' is already in use');\n process.exit(1);\n default:\n throw error;\n }\n });\n return this;\n }\n\n async initOntologies() {}\n\n /**\n *\n * @returns\n * @todo Check if default file store is set, if not, set it\n */\n async initStores() {\n return Promise.all(\n LinkedStorage.getDatasets().map((store) => {\n return store.init ? store.init() : Promise.resolve();\n })\n );\n }\n\n /**\n * Run a lifecycle hook (setupBeforeControllers, setupBeforeCatchAllControllers,\n * setupAfterControllers) on every generic provider, in indexing order.\n *\n * Each provider is isolated: a hook that throws (or rejects) is logged with\n * the package and hook name and the next provider still runs, so one broken\n * provider does not abort boot. That provider's routes or middleware from\n * that hook may be missing, but the rest of the app starts.\n */\n async callGenericBackendProvidersMethod(method: string, ...args: any[]) {\n for (let [pkg, genericProvider] of this.genericProviders.entries()) {\n if (!genericProvider || typeof genericProvider[method] !== 'function') {\n continue;\n }\n await runProviderHook(\n pkg,\n method,\n () => genericProvider[method](...args),\n this.booting\n );\n }\n }\n\n /**\n * Removes temporary nodes from memory if they've been seen twice\n * Current interval is once per hour.\n * So after 2 hours temporary nodes are removed.\n */\n initGarbageCollection() {\n // let seenLastTime:NodeSet<NamedNode> = null;\n // setInterval(() => {\n //\n // let tempNodes = new NodeSet<NamedNode>();\n // NamedNode.getAllNamedNodes().forEach(n => {\n // if(n.isTemporaryNode) {\n // if(seenLastTime && seenLastTime.has(n))\n // {\n // n.remove();\n // } else {\n // tempNodes.add(n);\n // }\n // }\n // })\n // seenLastTime = tempNodes;\n // }, 1000 * 10); //every 10 sec\n // // }, 1000 * 60 * 60); //every hour\n }\n async initBackendProviders() {\n // Local workspace packages in this app's dependency tree. These are also\n // imported whole at boot (indexLincdPackage), not only their /backend.\n const allLocalPackages = getLincdPackages();\n const localPackageMap = new Map<\n string,\n { packageName: string; path: string }\n >(allLocalPackages.map((pkg) => [pkg.packageName, pkg]));\n const relevantPackages = this.filterPackagesByDependencyTree(\n localPackageMap,\n this.package\n );\n // Every linked package in the dependency tree, installed or local, each\n // after the linked packages it depends on. Registry installs and\n // localized checkouts are not workspace members, and used to be indexed\n // only lazily, on the first /call/<pkg>/... A provider can hook every\n // request (initRequest, supplyDataForRequest, setupBeforeControllers\n // routes), so those hooks stayed silent until some RPC to the package\n // happened β€” an installed @_linked/auth did not put the session into a\n // page's request data until then, and its setupBeforeControllers\n // middleware never registered at all.\n await this.indexLinkedDependencyProviders(relevantPackages);\n\n try {\n await fs\n .readFile(path.join(process.cwd(), 'package.json'), 'utf-8')\n .then(async (contents) => {\n let pkg = JSON.parse(contents);\n // Route through default ${pkg}/backend resolution. The app's\n // package.json `exports`./backend field handles dev vs prod:\n // \"exports\": {\n // \"./backend\": {\n // \"development\": \"./src/backend.ts\",\n // \"default\": \"./lib/esm/backend.js\"\n // }\n // }\n // Removed plan-010 D10: the source-direct\n // path.join(cwd, 'src', 'backend.ts') override that forced TS\n // runtime loading. Vite SSR's ssrLoadModule handles the\n // transform; production runs from lib/esm/.\n await this.indexPackageBackendProviders(pkg.name, false);\n });\n } catch (err) {\n // Already logged where it was thrown; it must reach start().\n if (isFatalError(err)) throw err;\n console.warn(err);\n }\n }\n\n /**\n * Index the backend providers of every linked package in the app's\n * dependency tree, dependencies first. Workspace members (`localPackages`)\n * are also imported whole, as before; for anything else only its `/backend`\n * entry is loaded β€” resolved from the directory discovery found the package\n * in, and skipped without an import when the package has none.\n */\n private async indexLinkedDependencyProviders(\n localPackages: Map<string, { packageName: string; path: string }>\n ) {\n const started = Date.now();\n const installed: string[] = [];\n const ordered = discoverLinkedDependencies(process.cwd(), this.package);\n // A workspace member the walk cannot reach through node_modules still\n // loads, after the rest, as it always did.\n const remaining = new Set(localPackages.keys());\n this.linkedPackageDirs ??= new Map();\n for (const dep of ordered) {\n this.linkedPackageDirs.set(dep.packageName, dep.path);\n this.warnIfInstalledMoreThanOnce(dep);\n }\n for (const [packageName, local] of localPackages) {\n if (!this.linkedPackageDirs.has(packageName) && local?.path) {\n let dir = local.path;\n try {\n dir = fsNative.realpathSync(dir);\n } catch {}\n this.linkedPackageDirs.set(packageName, dir);\n }\n }\n for (const { packageName } of ordered) {\n const isLocal = remaining.delete(packageName);\n await this.ensurePackageBackendProviders(packageName);\n if (isLocal) {\n await this.indexLincdPackage(packageName);\n } else if (\n this.genericProviders.get(packageName) ||\n this.shapeProviders.get(packageName)?.length\n ) {\n installed.push(packageName);\n }\n }\n for (const packageName of remaining) {\n await this.ensurePackageBackendProviders(packageName);\n await this.indexLincdPackage(packageName);\n }\n if (installed.length > 0) {\n console.log(\n paint('gray', \n `[linked] indexed backend providers of ${ordered.length} linked package(s) in ${\n Date.now() - started\n }ms; installed ones with providers: ${installed.join(', ')}`\n )\n );\n }\n }\n\n /**\n * Two installed copies of one linked package mean two copies of its module\n * state, and only one of them can own the backend. The one the app resolves\n * is loaded (see discoverLinkedDependencies); the other is never loaded.\n */\n private warnIfInstalledMoreThanOnce(dep: {\n packageName: string;\n path: string;\n copies?: { path: string; version?: string }[];\n }) {\n const copies = dep.copies ?? [];\n this.warnedDuplicateInstalls ??= new Set();\n if (copies.length < 2 || this.warnedDuplicateInstalls.has(dep.packageName)) {\n return;\n }\n this.warnedDuplicateInstalls.add(dep.packageName);\n const list = copies\n .map((c) => `${c.version ?? '?'} at ${c.path}`)\n .join(', ');\n console.warn(\n paint('yellow', \n `[linked] ${dep.packageName} is installed ${copies.length} times (${list}); loaded ${dep.path}. Run npm dedupe.`\n )\n );\n }\n\n /**\n * The directory a package's backend is resolved from: the copy discovery\n * chose, or β€” for a package outside the linked tree, reached only by a lazy\n * /call β€” the copy the app itself resolves.\n */\n private packageDirFor(pkg: string): string | null {\n const known = this.linkedPackageDirs?.get(pkg);\n if (known) return known;\n const installed = readInstalledPackage(pkg, process.cwd());\n if (!installed) return null;\n try {\n return fsNative.realpathSync(installed.root);\n } catch {\n return installed.root;\n }\n }\n\n /**\n * Index a package's backend providers once. Shared by boot and the lazy\n * path in callBackendMethod / callShapeMethod. `onSourceChange` bypasses it\n * on purpose: an HMR reload must re-index.\n */\n async ensurePackageBackendProviders(pkg: string, warnIfNotFound = false) {\n if (this.genericProviders.has(pkg) && this.shapeProviders.has(pkg)) {\n return;\n }\n let indexing = this.providerIndexing.get(pkg);\n if (!indexing) {\n // Loading a package's providers runs their constructors and setup hooks.\n // That is system work, even when the first call to the package triggers it.\n indexing = runAsSystem(\n () => this.indexPackageBackendProviders(pkg, warnIfNotFound),\n 'loading backend providers of ' + pkg\n ).then(() => undefined);\n this.providerIndexing.set(pkg, indexing);\n }\n try {\n await indexing;\n } finally {\n this.providerIndexing.delete(pkg);\n }\n }\n\n /**\n * Node's `import()`. Called with the absolute file URL of a resolved backend\n * entry (see resolveBackendEntry), never a bare name.\n */\n protected importModule(specifier: string): Promise<any> {\n return import(/* @vite-ignore */ specifier);\n }\n\n /**\n * Filters local workspace packages to only those reachable from the app's\n * dependency tree. Mirrors the logic used by `buildAll` in lincd-cli.\n */\n private filterPackagesByDependencyTree(\n allPackages: Map<string, { packageName: string; path: string }>,\n appPackageJson: any\n ): Map<string, { packageName: string; path: string }> {\n const relevantPackages = new Map<\n string,\n { packageName: string; path: string }\n >();\n const packagesToCheck = new Set<string>();\n const processedPackages = new Set<string>();\n\n // Start with direct dependencies from the app\n if (appPackageJson.dependencies) {\n for (const dep of Object.keys(appPackageJson.dependencies)) {\n if (allPackages.has(dep)) {\n packagesToCheck.add(dep);\n }\n }\n }\n\n // Recursively follow each package's dependencies\n while (packagesToCheck.size > 0) {\n const packageName = packagesToCheck.values().next().value;\n packagesToCheck.delete(packageName);\n if (processedPackages.has(packageName)) {\n continue;\n }\n processedPackages.add(packageName);\n const packageDetails = allPackages.get(packageName);\n if (packageDetails) {\n relevantPackages.set(packageName, packageDetails);\n const pkg = getPackageJSON(packageDetails.path);\n if (pkg?.dependencies) {\n for (const dep of Object.keys(pkg.dependencies)) {\n if (allPackages.has(dep) && !processedPackages.has(dep)) {\n packagesToCheck.add(dep);\n }\n }\n }\n }\n }\n\n return relevantPackages;\n }\n\n async resizeImage(req, res) {\n //check if the w or h query parameters are set\n let width = req.query.w;\n let height = req.query.h;\n //if not\n if (!width && !height) {\n //redirect to the original image\n res.redirect(req.originalUrl.replace('/resized', '/uploads'));\n return;\n }\n\n let imageFileName = req.query.src; // example: https://cdnurl.com/uploads/1710814765388-935b511c9_cropped.jpeg\n const accessURL = LinkedFileStorage.accessURL;\n\n if (imageFileName) {\n // `src` may only name an image this app already stores. Before this check\n // the value went straight to fetch(), which made the route an open proxy\n // into its own network -- cloud metadata, localhost, private ranges -- and\n // the response was then written into the PUBLIC file store and the caller\n // redirected to it, so anything reachable was persisted, not just leaked.\n //\n // resolveResizeSource compares parsed origins (a startsWith check is\n // defeated by https://cdn.example.com.evil.com) and hands back the key,\n // which must also exist in the store before anything is requested.\n const source = resolveResizeSource(imageFileName, accessURL);\n\n if (!source.allowed) {\n res.status(400).send({ error: 'Unsupported image source' });\n return;\n }\n\n // Two candidates, because the stores disagree on whether the public URL\n // includes the upload mount -- see resolveResizeSource. Fail-closed: if\n // neither shape is held, nothing is fetched.\n const storedKey = await findStoredKey(source.keys, (key) =>\n LinkedFileStorage.fileExists(key)\n );\n\n if (!storedKey) {\n res.status(404).send({ error: 'Could not fetch image from URL' });\n return;\n }\n\n // extract the base name and extension from the key the store actually\n // holds, not from the URL path.\n //\n // These differ: LocalFileStore serves `accessURL + /uploads/ + key`, so\n // deriving the destination from the URL gave it an extra `uploads/`\n // segment and resized files landed in data/uploads/uploads/resized/.\n // S3FileStore serves the key directly, so for it the two are the same --\n // which is why this went unnoticed. Deriving from the key is correct for\n // both.\n const { name, ext } = path.parse(storedKey);\n\n // Sharp READS svg but cannot WRITE it, so an SVG source is rasterized to\n // PNG below. The cache key has to say so: storing PNG bytes under a `.svg`\n // key would also mean serving them as `image/svg+xml`, since the cache-hit\n // branch types the response from this extension.\n const outputExt = ext.toLowerCase() === '.svg' ? '.png' : ext;\n\n // append the width and height parameters to the base name\n // example: 935b511c9_cropped_w190.jpeg or 935b511c9_cropped_w190h190.jpeg\n //\n // The underscore is emitted once, before either dimension, rather than as\n // part of the width segment. With it inside the width, a height-only\n // request produced `logoh30.jpeg` here while the local branch below --\n // which has always written the separator unconditionally -- produced\n // `logo_h30.jpeg` for the same request. The two halves of one route\n // disagreed on the cache key.\n const newName = `${name}_${width ? 'w' + width : ''}${\n height ? 'h' + height : ''\n }`;\n\n // the destination key, alongside the original\n // example: uploads/935b511c9_cropped.jpeg -> uploads/resized/935b511c9_cropped_w190.jpeg\n // and for a LocalFileStore key: photo.jpg -> resized/photo_w190.jpg\n const keyDir = path.dirname(storedKey);\n const newPathname = path.join(\n keyDir === '.' ? '' : keyDir,\n 'resized',\n `${newName}${outputExt}`\n );\n\n const resizedImageFileName = newPathname.startsWith('/')\n ? newPathname.slice(1)\n : newPathname;\n\n if (this.resizePathsMap.has(resizedImageFileName)) {\n res.redirect(this.resizePathsMap.get(resizedImageFileName));\n return;\n }\n\n // check if the resized image already exists in the CDN\n const imageExists: boolean = await LinkedFileStorage.fileExists(\n resizedImageFileName\n );\n\n // if exists, redirect to the resized image\n if (imageExists) {\n const resizedPathOnCdn: string = accessURL + '/' + resizedImageFileName;\n //save to cache\n this.resizePathsMap.set(resizedImageFileName, resizedPathOnCdn);\n //redirect this request to the resized image\n res.redirect(resizedPathOnCdn);\n return;\n } else {\n console.log(\n `${process.pid} - ${\n process.env.PORT\n }: Resizing image: ${imageFileName} to ${width} x ${height || ''}`\n );\n //in multicore development, we need to access the site from 127.0.0.1, and so all requests need to go there\n // // if (process.env.NODE_ENV === 'development' && process.env.NUM_WORKER_PROCESSES) {\n // // imageFileName = imageFileName.replace('localhost', '127.0.0.1');\n // // }\n\n // Read the bytes out of the store rather than fetching its public URL.\n //\n // Once `src` has to name an image the store already holds, fetching is\n // a round-trip to ask a web server for a file this process can open --\n // over the loopback interface, for a LocalFileStore. Reading directly\n // is faster, and it means the route makes no outbound request at all:\n // there is no origin to re-check after a redirect, no timeout to tune\n // and no response size to cap, because there is no response.\n const image = await LinkedFileStorage.getFile(storedKey);\n\n // if image is null or empty, return 404\n if (!image?.length) {\n res.status(404).send({ error: 'Could not fetch image from URL' });\n return;\n }\n\n // get the format of the image\n let format;\n try {\n format = await sharp(image)\n .metadata()\n .then((meta) => meta.format);\n } catch (err) {\n console.warn('Unsupported image format: ' + err);\n res.status(400).send({ error: 'Unsupported image format' });\n return;\n }\n\n // Sharp reads SVG but has no SVG encoder, so `.toFormat('svg')` throws\n // and every resize of an SVG failed. Rasterize to PNG instead β€” lossless,\n // and it matches the `.png` cache key chosen above.\n const outputFormat = format === 'svg' ? 'png' : format;\n\n // set the output options based on the format for quality and compression\n let outputOptions;\n switch (outputFormat) {\n case 'jpeg':\n outputOptions = { quality: 90 };\n break;\n case 'png':\n outputOptions = { compressionLevel: 9 };\n break;\n case 'webp':\n outputOptions = { quality: 90 };\n break;\n // add more formats here\n default:\n outputOptions = {};\n }\n\n // resize the image\n const resizedImage: Buffer = await sharp(image)\n .resize(\n width ? parseInt(width) : null,\n height ? parseInt(height) : null\n )\n .toFormat(outputFormat, outputOptions)\n .toBuffer()\n .catch((err) => {\n console.warn('Could not resize image: ' + err);\n return null;\n });\n\n // if resizedImage is null, return 500\n if (!resizedImage) {\n res.status(500).send({ error: 'Could not resize image' });\n return;\n }\n\n // upload the resized image to the CDN\n const resizedPathOnCdn = await LinkedFileStorage.saveFile(\n newPathname,\n resizedImage\n );\n\n //save to cache\n this.resizePathsMap.set(resizedImageFileName, resizedPathOnCdn);\n //redirect this request to the resized image\n res.redirect(resizedPathOnCdn);\n return;\n }\n } else {\n imageFileName = req.originalUrl.split('/resized/')[1]?.split('?')[0];\n }\n\n // Both halves of this route now read and write through LinkedFileStorage.\n //\n // This branch used to hardcode <cwd>/data/uploads for both, which meant it\n // could only ever work for a LocalFileStore: an app configured with S3 kept\n // its uploads in the bucket, so every request here looked on a local disk\n // that had nothing on it and 404'd. Going through the store also removes the\n // need to create the cache directory by hand -- LocalFileStore.saveFile\n // makes its own parent folders, which is why the mkdirSync that used to sit\n // here (commented out, so it silently did nothing) is gone rather than\n // restored.\n const [trueFileName, ...extensions] = imageFileName.split('.');\n const sourceExtension = extensions.join('.');\n\n // Same rasterization as the branch above: sharp reads SVG but cannot write\n // it. `extension` is what the cached derivative actually IS, and is what\n // `sendStoredFile` types the response with, so it has to be the OUTPUT\n // format rather than the source's.\n const extension =\n sourceExtension.toLowerCase() === 'svg' ? 'png' : sourceExtension;\n\n const resizedKey = path.join(\n path.dirname(imageFileName) === '.' ? '' : path.dirname(imageFileName),\n 'resized',\n `${path.basename(trueFileName)}_${width ? 'w' + width : ''}${\n height ? 'h' + height : ''\n }.${extension}`\n );\n\n // The resize cache is its own purpose, so an app can keep derivatives on a\n // local disk while its uploads live in S3, or share one store for both.\n // Unconfigured, it falls back to the default store, which is the previous\n // behaviour for anyone who never thinks about it.\n const cacheStore = getResizedImagesStore();\n const sendStoredFile = async (store: IFileStore, key: string) => {\n const bytes = await store.getFile(key);\n if (!bytes) {\n return false;\n }\n res.type(extension || 'bin').send(bytes);\n return true;\n };\n\n if (await cacheStore.fileExists(resizedKey)) {\n if (await sendStoredFile(cacheStore, resizedKey)) {\n return;\n }\n }\n\n const uploadsStore = LinkedFileStorage.getStore(FileStorePurposes.uploads);\n const original = await uploadsStore.getFile(imageFileName);\n\n if (!original) {\n console.warn('Could not find original image at ' + imageFileName);\n res.status(404).send({ error: 'Could not find original image' });\n return;\n }\n\n let resized: Buffer;\n try {\n const pipeline = sharp(original).resize(\n width ? parseInt(width) : null,\n height ? parseInt(height) : null\n );\n // Without this, sharp writes in the INPUT format, which for an SVG source\n // means asking for an encoder it does not have.\n resized = await (sourceExtension.toLowerCase() === 'svg'\n ? pipeline.png({ compressionLevel: 9 })\n : pipeline\n ).toBuffer();\n } catch (err) {\n console.warn('Could not resize image: ' + err);\n res.status(500).send({ error: 'Could not resize image' });\n return;\n }\n\n // preventDuplicates: false because this is a cache keyed by name. Letting\n // the store pick a fresh name on collision would write a second copy for\n // every request and never hit the cache.\n //\n // A failure here is logged, not fatal: the resize succeeded, so the caller\n // still gets its image and only the caching is lost. It used to be\n // swallowed and then followed by sendFile on a file that was never written,\n // which turned a cache miss into a 404 with nothing in the response to say\n // why -- and, on the error path, into a second send after the 500.\n try {\n await cacheStore.saveFile(resizedKey, resized, {\n preventDuplicates: false,\n });\n } catch (err) {\n console.warn('Could not cache resized image at ' + resizedKey + ': ' + err);\n }\n\n setUntrustedFileHeaders(res);\n res.type(extension || 'bin').send(resized);\n }\n\n async indexLincdPackage(pkg: string, warnIfNotFound: boolean = false) {\n if (pkg === this.package.name) {\n return;\n }\n try {\n // console.log(`πŸ” Loading package: ${pkg}`);\n // console.log(\n // `πŸ” Module resolution for ${pkg}:`,\n //@ts-ignore\n // await import.meta.resolve(pkg)\n // );\n // plan-011 Β§P6 β€” prefer Vite's SSR loader so workspace packages register\n // on the SINGLE @_linked/core instance the rest of the SSR graph uses.\n // The bare Node `import()` fallback resolves `default`β†’lib, evaluating a\n // SECOND core copy (benign post-Β§P1, but a needless second instance).\n // Node import stays as the fallback when Vite isn't active (production /\n // Node-only CLI commands). Mirrors indexPackageBackendProviders.\n const vite: any = (this.config.server as any)?.vite;\n if (vite && typeof vite.ssrLoadModule === 'function') {\n await vite.ssrLoadModule(pkg);\n } else {\n // @vite-ignore β€” dynamic specifier is intentional: this checks\n // whether `pkg` is resolvable at runtime, then catches the error.\n // eslint-disable-next-line no-unsanitized/method\n await import(/* @vite-ignore */ pkg);\n }\n // console.log(`βœ… Successfully loaded: ${pkg}`);\n } catch (e) {\n if (isFatalError(e)) {\n logFatalError(pkg, 'module load', e, this.booting);\n if (this.booting) throw e;\n return;\n }\n let providerNotFound =\n e.code === 'MODULE_NOT_FOUND' &&\n e.message.indexOf(`Cannot find package '${pkg}'`) !== -1;\n if (providerNotFound) {\n // console.warn('Error loading ' + providerPath + ': ' + e.stack);\n if (warnIfNotFound) {\n console.warn(\n paint('magenta', \n `Could not load package ${logSafe(pkg)}`,\n typeof module !== 'undefined' && typeof exports !== 'undefined'\n ? //@ts-ignore\n ' at ' + (await import.meta.resolve(pkg))\n : ''\n )\n );\n }\n } else {\n console.warn(\n paint('red', \n `Error loading '${logSafe(pkg)}' ${\n typeof module !== 'undefined' && typeof exports !== 'undefined'\n ? //@ts-ignore\n ' at ' + (await import.meta.resolve(pkg))\n : ''\n }: ${e.message}\\n`\n ),\n e.stack\n );\n }\n }\n }\n async indexPackageBackendProviders(\n pkg: string,\n warnIfNotFound: boolean = false\n ) {\n let backendProviderExports;\n let genericBackendProvider = null;\n let shapeProviders = [];\n const vite: any = (this.config.server as any)?.vite;\n // In dev, load a package's backend with the loader that owns the package\n // (see isBundledBySsr): Vite for the app itself and for what the SSR\n // runner bundles (workspaces, SSR_ENTRY_PACKAGES), Node for what it\n // leaves external (registry installs). ssrLoadModule of an EXTERNAL\n // package's /backend evaluated that package a second time, apart from the\n // copy the app's own imports reach.\n const viteOwnsPackage =\n !!vite &&\n typeof vite.ssrLoadModule === 'function' &&\n (pkg === this.package?.name ||\n isBundledBySsr(pkg, ssrNoExternalOf(vite)));\n\n // Decide whether there IS a backend before importing anything. A package\n // without one is the normal case (most linked packages have none) and is\n // quiet; once a backend file is known to exist, any failure to load it is\n // a real error. This used to be decided after the fact, by matching the\n // loader's error text β€” which Node and Vite word differently, so a nested\n // package's \"Cannot find package\" was reported as a broken backend.\n let entry: string | null = null;\n let load: (() => Promise<any>) | null = null;\n if (pkg === this.package?.name) {\n // The app's own backend cannot be imported by name: a self-reference\n // resolves only from inside the package that declares it, and this code\n // lives in node_modules/@_linked/server. Load it by path.\n const cwd = process.cwd();\n if (viteOwnsPackage) {\n const source = path.join(cwd, 'src', 'backend.ts');\n if (fsNative.existsSync(source)) {\n entry = source;\n load = () => vite.ssrLoadModule('/src/backend.ts');\n }\n } else {\n entry = [\n path.join(cwd, 'lib', 'backend.js'),\n path.join(cwd, 'src', 'backend.ts'),\n ].find((f) => fsNative.existsSync(f)) ?? null;\n if (entry) {\n const url = pathToFileURL(entry).href;\n load = () => this.importModule(url);\n }\n }\n } else {\n const dir = this.packageDirFor(pkg);\n let json: any = null;\n if (dir) {\n try {\n json = JSON.parse(\n fsNative.readFileSync(path.join(dir, 'package.json'), 'utf-8')\n );\n } catch {}\n }\n if (dir && json) {\n if (viteOwnsPackage) {\n // Vite resolves a bundled package with the `development` condition\n // (a workspace's `./backend` may point at src only there). It is\n // still loaded by its bare name, so it is the same module id the\n // rest of the SSR graph imports.\n entry = resolveBackendEntry(dir, json, [\n 'development',\n ...NODE_IMPORT_CONDITIONS,\n ]);\n if (entry) load = () => vite.ssrLoadModule(`${pkg}/backend`);\n } else {\n // Node caches ESM by resolved real file URL, and a bare import of\n // `<pkg>/backend` from the app resolves to this same real path β€” so\n // loading it by URL yields the instance the app's own imports get.\n entry = resolveBackendEntry(dir, json, NODE_IMPORT_CONDITIONS);\n if (entry) {\n const url = pathToFileURL(entry).href;\n load = () => this.importModule(url);\n }\n }\n }\n }\n\n if (!load) {\n if (warnIfNotFound) {\n console.warn(\n paint('magenta', `Could not find backend file of package ${logSafe(pkg)}. \n Check:\\n\n - Make sure backend.ts exists and is included in tsconfig.json\\n\n - Make sure the package name in src/package.ts matches the package name in package.json`)\n );\n }\n } else {\n // Loud, naming the package and the file, and contained: one package's\n // broken backend does not stop the others from loading.\n let loaded = false;\n await runProviderHook(\n pkg,\n `backend ${entry}`,\n async () => {\n backendProviderExports = await load();\n loaded = true;\n },\n this.booting\n );\n if (loaded) {\n for (const key of Object.keys(backendProviderExports)) {\n const providerClass = backendProviderExports[key];\n let provider;\n //always send an instance of the express server\n //TODO: do not create an instance, just save the class and instantiate it when needed\n await runProviderHook(\n pkg,\n `${key} constructor`,\n () => {\n provider = new providerClass(this.server, this);\n },\n this.booting\n );\n if (!provider) continue;\n if (isShapeProvider(provider)) {\n shapeProviders.push(provider);\n if (!Object.getOwnPropertyNames(provider).includes('shape')) {\n console.warn(\n paint('red', `${\n Object.getPrototypeOf(provider).constructor.name\n } in package ${logSafe(pkg)}\n is not properly linked to a shape. Use public shape = SomeShape.`)\n );\n }\n } else if (genericBackendProvider) {\n console.warn(\n `Package ${logSafe(pkg)} exports two generic backend providers. Only one will work`\n );\n } else {\n genericBackendProvider = provider;\n }\n }\n }\n }\n this.genericProviders.set(pkg, genericBackendProvider);\n this.shapeProviders.set(pkg, shapeProviders);\n return { backendProviderExports, shapeProviders };\n }\n\n /**\n * Plan-011 phase 2 β€” HMR re-index entry point.\n *\n * Called by the CLI orchestrator's Vite watcher whenever a `.ts`/`.tsx`\n * file inside a workspace package changes. Disposes the package's\n * existing providers (so routes, listeners, timers don't accumulate),\n * drops them from the registry, and re-runs indexPackageBackendProviders\n * to pick up the freshly-imported module.\n *\n * Dispose calls have a 5 s soft timeout. A hanging dispose logs a\n * warning and is abandoned so HMR doesn't stall the whole dev loop.\n */\n /**\n * Install the client-shell catch-all as the last ordinary layer on the\n * router stack. See utils/spaFallback.ts for why ordering has to be\n * re-asserted rather than assumed.\n */\n private installSpaFallback(): void {\n installSpaFallback(\n this.server,\n this.handleErrors(async (req, res) => {\n //make sure the frontend bundle has finished building\n // await this.waitForWebpack();\n this.render(req, res);\n })\n );\n }\n\n async onSourceChange(pkg: string): Promise<void> {\n const disposeWithTimeout = async (p: any, label: string) => {\n if (!p?.dispose) return;\n try {\n await Promise.race([\n Promise.resolve().then(() => p.dispose()),\n new Promise((_, reject) =>\n setTimeout(\n () => reject(new Error(`dispose timeout after 5s`)),\n 5000\n )\n ),\n ]);\n } catch (err: any) {\n console.warn(\n paint('yellow', `[linked] ${label} dispose failed: ${err.message}`)\n );\n }\n };\n\n const generic = this.genericProviders.get(pkg);\n if (generic) {\n await disposeWithTimeout(generic, `${pkg} generic provider`);\n this.genericProviders.delete(pkg);\n }\n\n const shapeProvs = this.shapeProviders.get(pkg) ?? [];\n for (const p of shapeProvs) {\n await disposeWithTimeout(\n p,\n `${pkg} ${Object.getPrototypeOf(p)?.constructor?.name ?? 'shape provider'}`\n );\n }\n this.shapeProviders.delete(pkg);\n\n await this.indexPackageBackendProviders(pkg, true);\n\n // Run the boot lifecycle on the FRESHLY-loaded provider so it\n // re-registers its Express routes/middleware after dispose. Without\n // this, dispose() tears the old routes off and the new instance is\n // constructed but never gets a chance to register the replacements.\n const fresh = this.genericProviders.get(pkg);\n if (fresh?.setupBeforeControllers) {\n try {\n await fresh.setupBeforeControllers();\n } catch (err: any) {\n console.warn(\n paint('yellow', \n `[linked] ${pkg} setupBeforeControllers after reload failed: ${err.message}`\n )\n );\n }\n }\n const freshShapes = this.shapeProviders.get(pkg) ?? [];\n for (const p of freshShapes) {\n if (p?.setupBeforeControllers) {\n try {\n await p.setupBeforeControllers();\n } catch (err: any) {\n console.warn(\n paint('yellow', \n `[linked] ${pkg} shape-provider setupBeforeControllers after reload failed: ${err.message}`\n )\n );\n }\n }\n }\n\n // Providers just re-registered their routes, which express can only APPEND\n // β€” i.e. behind the catch-all installed at boot. Put it back at the end so\n // those routes stay reachable. Safe here: every registration above has\n // completed, so no provider is mid-capture of its own layer indices.\n repinSpaFallback(this.server);\n }\n\n async processBackendMethodCall(request, response) {\n // The whole call runs in its own context: `this.request` in a provider is\n // this request, however many calls are in flight.\n return runWithCallContext(httpCallContext(request, response), async () => {\n this.noCache(response);\n await this.initRequest(request, response);\n let { pkg, method } = request.params;\n let { args } = JSONParser.parseObject<{ args }>(request.body, {\n shapeClasses: rpcShapeClassRevival(),\n });\n\n return this.callBackendMethod(pkg, method, args, request, response).then(\n (result) => {\n //some methods of backend providers may choose to work with request/response directly and will not return anything\n //so only if a result is returned\n if (typeof result !== 'undefined') {\n //do we convert it to JSON and send it to the frontend\n this.sendJson(response, result);\n } else {\n //in other cases, we still need to close the request and send an empty response\n if (!response.headersSent) {\n this.sendJson(response, null);\n }\n }\n }\n );\n });\n }\n\n noCache(response) {\n response.setHeader('Surrogate-Control', 'no-store');\n response.setHeader(\n 'Cache-Control',\n 'no-store, no-cache, must-revalidate, proxy-revalidate'\n );\n response.setHeader('Expires', '0');\n }\n async processAPICall(\n request,\n response,\n method: 'get' | 'post' | 'put' | 'delete'\n ) {\n return runWithCallContext(httpCallContext(request, response), async () => {\n this.noCache(response);\n await this.api.process(request, response, method);\n });\n }\n // async processQuery(request, response) {\n //\n // this.api.process(request, response);\n // }\n async processShapeMethodCall(request, response) {\n this.noCache(response);\n // console.log('process shape call');\n // response.on('finish', function() {\n // console.log('shape method call request finish');\n // });\n //\n // response.on('close', function() {\n // console.log('close');\n // });\n //\n // response.on('end', function() {\n // console.log('end');\n // });\n //\n // response.on('header', function() {\n // console.log('header');\n // console.log(response.statusCode);\n // });\n\n return runWithCallContext(httpCallContext(request, response), async () => {\n await this.initRequest(request, response);\n let { pkg, shape, method } = request.params;\n let { shapeURI, instanceNode, args } = JSONParser.parseObject<{\n shapeURI: string;\n instanceNode: { id: string } | null;\n args: any[];\n }>(request.body, { shapeClasses: rpcShapeClassRevival() });\n\n if (!shapeURI) {\n if (request.query?.shapeURI) {\n shapeURI = request.query?.shapeURI;\n } else {\n response.status(500).send({\n error: 'Invalid server call request: ' + request.originalUrl,\n });\n console.warn(\n paint('red', 'Invalid server call request: ' + request.originalUrl)\n );\n return;\n }\n }\n return this.callShapeMethod(\n pkg,\n method,\n shapeURI,\n instanceNode,\n args,\n request,\n response\n ).then((result) => {\n //we return json if something was returned or, if nothing was returned, we still close the request if the method has not accessed response itself already to send things over\n if (typeof result !== 'undefined' || !response.headersSent) {\n this.sendJson(response, result);\n }\n });\n });\n }\n\n async callShapeMethod(\n pkg: string,\n method: string,\n shapeURI: string,\n instanceNode: { id: string } | null,\n args: any[],\n request?,\n response?\n ) {\n // see callBackendMethod: outside any request a local call runs as system\n if (!request && !getCallContext()) {\n return runAsSystem(() =>\n this.callShapeMethod(pkg, method, shapeURI, instanceNode, args, request, response)\n );\n }\n //- index module providers if not done yet\n if (!this.shapeProviders.has(pkg)) {\n await this.ensurePackageBackendProviders(pkg, true);\n }\n\n let packageShapeProviders = this.shapeProviders.get(pkg);\n\n let findProviderForShape = (nodeShapeId: string) => {\n return packageShapeProviders.find((provider) => {\n //access the static shape (which is a linkedShape() / Shape class)\n //then access the SHACL NodeShape of that shape class, and its id\n return (\n isShapeProvider(provider) &&\n provider.shape?.shape?.id === nodeShapeId\n );\n });\n };\n\n let providerMethodFailed = false;\n try {\n //- find matching provider\n let shapeClass = getShapeClass(shapeURI);\n let shapeProvider: ShapeProvider = shapeClass?.shape\n ? findProviderForShape(shapeClass.shape.id)\n : undefined;\n if (!shapeProvider && shapeClass) {\n let superShapeClasses = getSuperShapesClasses(\n shapeClass as unknown as typeof Shape\n );\n for (let superShapeClass of superShapeClasses) {\n let superShapeProvider = findProviderForShape(\n superShapeClass.shape?.id\n );\n if (superShapeProvider) {\n shapeProvider = superShapeProvider;\n break;\n }\n }\n }\n // No provider for this shape (e.g. it isn't registered on this side).\n // Framework packages are kept single-instance by the cli vite-config's\n // `optimizeDeps.exclude`, so a mismatch here signals a real\n // misconfiguration. Answer 501 (via handleErrorsJson) rather than an empty\n // 200; direct backend callers get a rejected ServerCallError.\n if (!shapeProvider) {\n console.warn(\n `[LinkedServer] callShapeMethod: no provider for '${logSafe(shapeURI)}' ` +\n `(pkg '${logSafe(pkg)}', method '${logSafe(method)}').`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n\n if (shapeProvider) {\n const resolution = resolveCallable(shapeProvider, method);\n if (resolution.status !== 'missing') {\n this.assertDispatchAllowed(\n pkg,\n method,\n shapeProvider,\n resolution,\n request,\n 'shape'\n );\n }\n //NOTE: if this is a direct call from backend to backend, we won't know the request & response here because those don't get passed to the Server utility\n //if this is an issue, we need to see how we can get those back\n if (request && response) {\n //give the provider a chance to prepare for this request\n //wrap the call in a promise and wait for it, because providers MAY return a promise\n await Promise.resolve(shapeProvider.initRequest(request, response));\n if (resolution.status !== 'missing') {\n this.assertSessionForLevel(pkg, method, resolution, request);\n }\n }\n\n //see if the shapeProvider implements the called method\n if (resolution.status !== 'missing') {\n //prepare the first argument\n //we want to convert the instance node into an instance of the shape that this shapeProvider provides for\n //let's find the shape class\n if (shapeProvider.shape) {\n //instance nodes are not always sent. A shape can also call a shape provider from a static method without a shape instance.\n if (instanceNode) {\n let providerShapeClass = shapeProvider.shape;\n let instance = new (providerShapeClass as any)({\n id: instanceNode.id,\n });\n\n //always send instanceNode as first argument to static provider methods\n args.unshift(instance);\n }\n\n try {\n //call the method with the given arguments\n let result = await Promise.resolve(\n shapeProvider[method].apply(shapeProvider, args)\n );\n return result;\n } catch (e) {\n console.warn(\n `Error whilst calling ${\n Object.getPrototypeOf(shapeProvider).constructor.name\n }.${logSafe(method)}(): `,\n e\n );\n // Rethrow so the HTTP route answers with an error status (via\n // handleErrorsJson) instead of `200 null`, and direct backend\n // callers get a rejected promise.\n providerMethodFailed = true;\n throw e;\n }\n } else {\n console.warn(\n `${\n Object.getPrototypeOf(shapeProvider).constructor.name\n } does not define its own 'static shape' property. Please connect the provider to a shape.`\n );\n }\n } else {\n console.warn(\n `${\n Object.getPrototypeOf(shapeProvider).constructor.name\n } does not have a method called ${logSafe(method)}`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n }\n } catch (err) {\n if (!providerMethodFailed && !ServerCallError.is(err)) {\n console.warn(`Error whilst trying to access provider of ${logSafe(pkg)}: `, err);\n }\n throw err;\n }\n return null;\n }\n\n /**\n * Refuse a dispatch the exposure rules do not allow (see utils/rpcExposure).\n * Throws a 501 `ServerCallError`, the same answer as for a missing method.\n *\n * - reserved names: always, for HTTP and backend-to-backend calls alike;\n * - HTTP only: an internal method (in every mode), a generic call to a provider whose class sets\n * `static rpc = false`, and an undeclared method in 'enforce' mode\n * (in 'warn' mode it is logged once and runs).\n */\n private assertDispatchAllowed(\n pkg: string,\n method: string,\n provider,\n resolution: ReturnType<typeof resolveCallable>,\n request,\n route: 'generic' | 'shape'\n ) {\n const className = Object.getPrototypeOf(provider)?.constructor?.name;\n if (resolution.status === 'reserved') {\n console.warn(\n `[linked] refused call to reserved method ${logSafe(pkg)} ${className}.${logSafe(method)}` +\n (request ? '' : ' (backend-to-backend)')\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n if (!request) return;\n if (resolution.status === 'internal') {\n console.warn(\n `[linked] refused call to internal method ${logSafe(pkg)} ${className}.${logSafe(method)}`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n if (route === 'generic' && isGenericRpcDisabled(provider)) {\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n if (resolution.status === 'undeclared') {\n if (getRpcExposureMode() === 'enforce') {\n console.warn(\n `[linked] refused undeclared RPC ${logSafe(pkg)} ${className}.${logSafe(method)}`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n warnUndeclaredCall(pkg, resolution.owner, method, hasSession(request));\n }\n }\n\n /** A declared `'user'` method needs a session: 401 without one, in every mode. */\n private assertSessionForLevel(\n pkg: string,\n method: string,\n resolution: ReturnType<typeof resolveCallable>,\n request\n ) {\n if (\n resolution.status === 'callable' &&\n resolution.level === 'user' &&\n !hasSession(request)\n ) {\n throw new ServerCallError(401, 'Authentication required');\n }\n }\n\n handleErrors(fn) {\n return async function (req, res, next) {\n try {\n return await fn(req, res);\n } catch (x) {\n console.log(x);\n next(x);\n }\n };\n }\n\n handleErrorsJson(fn) {\n return async (req, res, next) => {\n try {\n return await fn(req, res);\n } catch (err) {\n // A ServerCallError (e.g. 501 for a call no provider handles) carries\n // its own status and a message that is safe to send to the client.\n if (ServerCallError.is(err)) {\n return this.sendError(res, err.status, err.message);\n }\n this.sendError(\n res,\n 500,\n 'internal server error' + (isDevelopment ? ': ' + err?.stack : ''),\n 'internal server error: ' + err?.stack\n );\n }\n };\n }\n\n sendError(res, statusCode = 500, message, logMessage?: string) {\n res?.status(statusCode);\n if (message) {\n res?.send({ error: message });\n console.warn(paint('red', logMessage || message));\n }\n }\n\n /**\n * The stylesheets a dev (Vite) page render needs, inlined into\n * `<style id=\"ssr-css\">` so the first paint is styled before Vite's client\n * injects the same CSS.\n *\n * Scoped to what the app module and the matched routes' pages import\n * statically (see utils/ssrCss `ssrCssScope`). The dev server preloads every\n * page into the module graph, so the whole graph is every page's CSS β€”\n * megabytes per request in a large app. When the scope cannot be\n * established (no routes config, a route rendered through a function, a\n * module not found) it falls back to the whole graph.\n *\n * Ids are kept in the combined graph's order, so the cascade order of what\n * remains is unchanged.\n */\n private async collectViteSsrCss(\n vite: any,\n App: unknown,\n matchedRoutes: RouteConfig[] | null,\n ): Promise<string> {\n if (!vite?.moduleGraph?.idToModuleMap) return '';\n // Note: Tailwind v4 `@theme` directives in app theme CSS files are\n // NOT processed at SSR collection time β€” the @tailwindcss/vite\n // plugin expands them at production build only. In dev mode, the\n // theme variables (β€”color-primary-*, etc.) are injected by Vite's\n // runtime AFTER client hydration, which causes a brief flash of\n // unthemed content (logos render black until ~hydration+200ms).\n // Production (vite build) is unaffected β€” the static main.css\n // contains expanded :root variables.\n let scope: Set<string> | null = null;\n const ssrGraph = vite.environments?.ssr?.moduleGraph;\n if (ssrGraph?.idToModuleMap && App && matchedRoutes) {\n const pages: unknown[] = [];\n let known = true;\n for (const route of matchedRoutes) {\n const component = await resolveRouteComponent(route);\n if (component === undefined) {\n known = false;\n break;\n }\n if (component !== null) pages.push(component);\n }\n if (known) {\n scope = ssrCssScope(ssrGraph.idToModuleMap.values(), {\n app: App,\n pages,\n });\n }\n }\n // Read only now: resolving a lazy route above can load its page, and the\n // combined graph's id map is a view built when it is read.\n const graphIds = [\n ...(vite.moduleGraph.idToModuleMap as Map<string, unknown>).keys(),\n ];\n const ids = scope ? graphIds.filter((id) => scope!.has(id)) : graphIds;\n // Only real stylesheets, once per file β€” see utils/ssrCss.\n const inlineUrls = ssrCssInlineUrls(ids, {\n publicDir: vite.config?.publicDir,\n });\n const cssChunks: string[] = [];\n for (const inlineUrl of inlineUrls) {\n try {\n const cssModule = await vite.ssrLoadModule(inlineUrl);\n if (typeof cssModule?.default === 'string') {\n cssChunks.push(cssModule.default);\n }\n } catch {/* skip */}\n }\n return cssChunks.join('\\n');\n }\n\n async render(req, res) {\n // Server-side rendering runs as the requesting user: a Server.call made\n // while rendering inherits this context rather than escalating to system.\n return runWithCallContext(httpCallContext(req, res), () =>\n this.renderPage(req, res)\n );\n }\n\n private async renderPage(req, res) {\n res.socket.on('error', (error) => {\n console.error('Fatal socket error', error);\n });\n\n //when render() is called, the request is always an 'initial page request', and the server which will return HTML (so this is a SSR request)\n //in that case we send data back to the frontend in a <script> tag.\n //We initiate that object here\n if (req['frontendData'] == null) {\n req['frontendData'] = {};\n }\n\n //if we are caching this page\n if (\n this.config.server?.cachePaths &&\n this.config.server.cachePaths.includes(req.url)\n ) {\n //if there is a cach for this path, send it\n if (this.cachedPaths.has(req.url)) {\n // console.log(req.url + ': Returning cached path');\n const html = this.cachedPaths.get(req.url);\n // res.setHeader('Content-Type', 'text/html; charset=utf-8');\n // res.setHeader('Content-Length', Buffer.byteLength(html, 'utf8').toString());\n // res.status(200).end(html);\n res.send(html);\n return;\n }\n }\n\n let didError = false;\n\n let App = this.config.server?.loadAppComponent\n ? await this.config.server.loadAppComponent()\n : null;\n\n // Vite dev CSS collection (plan-010 iteration 1 β€” gap A):\n // 1. Preload the matched route's module via ssrLoadModule so all\n // page-level dependencies (SigninLayout, CreateAccount, etc.)\n // enter Vite's moduleGraph BEFORE we collect CSS. Without this,\n // only App's eager imports are in the graph and lazy routes'\n // CSS would be missing β€” page renders unstyled until hydration.\n // 2. Once the route is matched, collect the CSS the app and that route's\n // page import (collectViteSsrCss), each loaded via `?inline` (Vite\n // returns the processed CSS as the default export).\n // 3. Inject as inline <style> in HTML head (Html.tsx).\n const vite: any = (this.config.server as any)?.vite;\n // Vite SSR module preload (plan-010 iter1 gap A):\n // Pages are loaded lazily via React.lazy β€” their modules only enter\n // Vite's moduleGraph after the lazy resolves. For SSR CSS collection\n // we need the page modules in the graph BEFORE the first render of\n // each route. The orchestrator passes a preloadPagesFn that lists\n // all page files (typically via `import.meta.glob`); we call\n // ssrLoadModule on each path once. After the first render of a\n // session everything is cached.\n const preloadPagesFn: any = (this.config.server as any)?.viteSsrPreload;\n if (vite?.ssrLoadModule && preloadPagesFn && !(this as any)._viteSsrPreloaded) {\n try {\n const pagePaths: string[] = await preloadPagesFn();\n for (const p of pagePaths) {\n try {\n await vite.ssrLoadModule(p);\n } catch {/* skip β€” page may not exist or have ssr errors */}\n }\n } catch {/* ignore */}\n (this as any)._viteSsrPreloaded = true;\n }\n\n await this.initRequest(req, res);\n let { requestLD, requestObject } = await this.getRequestData(req, res);\n\n //on the backend we need to inform the hook of the request-data value\n //on the frontend it will be read from the HTML\n // setRequestData(requestObject);\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n let stream;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timedout = false;\n // const timeout = setTimeout(() => {\n // stream.abort(`${req.url}: ⏱ SSR stream took too long β€” force abort`);\n // if (!res.headersSent) {\n // res.statusCode = 500;\n // res.end('SSR timed out');\n // }\n // timedout = true;\n // }, 8_000);\n\n let manifest = this.assets.manifest || {};\n let preloadScripts: string[] = [];\n let preloadStyles: string[] = [];\n let matchedRouteKey: string | null = null;\n // Null until the routes config has loaded: without it, what renders is unknown.\n let matchedRoutes: RouteConfig[] | null = null;\n // Plan-010 Vite dev mode: skip preload resolution entirely. Vite\n // handles dynamic import() at runtime β€” there are no pre-built\n // chunks to preload, and the webpack-shape fallback would pick up\n // stale bundles on disk (public/bundles/*.bundle.js from a prior\n // webpack build) and link them, breaking hydration.\n // The same decision start() made for the `__viteDev` marker. This used\n // to be re-derived from `latestManifest`, which nothing ever set, so it\n // answered \"dev\" whenever Vite was attached β€” even when start() had\n // chosen the build β€” and the page mixed built CSS with the dev preamble.\n const usingViteDev = this.viteDevServer;\n\n // Load routes config if available and extract preload chunks for the current route\n if (this.config.server?.loadRoutes) {\n try {\n const routesModule = await this.config.server.loadRoutes();\n const ROUTES: RoutesConfig =\n routesModule.ROUTES ||\n routesModule.default?.ROUTES ||\n (routesModule as RoutesConfig);\n\n // Match the current request path to a route\n let matchedRoute: RouteConfig | null = null;\n const allMatches: RouteConfig[] = [];\n for (const [key, route] of Object.entries(ROUTES)) {\n if (!route?.path) continue;\n const pathPattern = route.path\n .replace(/:\\w+\\??/g, '([^/]+)')\n .replace(/\\*/g, '.*');\n const regex = new RegExp('^' + pathPattern + '$');\n if (regex.test(req.path)) {\n // Every match, not only the first: React Router may pick a more\n // specific route than this first-match loop, and the dev CSS\n // scope must cover whichever page actually renders.\n allMatches.push(route);\n if (!matchedRoute) {\n matchedRoute = route;\n matchedRouteKey = key;\n }\n }\n }\n matchedRoutes = allMatches;\n\n // If we found a matching route with preloadChunks, resolve them to URLs (both JS and CSS).\n // Manifest format detection: Vite manifest entries are objects with .file/.css; webpack\n // manifest entries are bare strings. Try Vite shape first, fall back to webpack.\n // Skip entirely in Vite dev mode β€” no pre-built chunks exist; Vite handles dynamic\n // imports at runtime.\n if (\n !usingViteDev &&\n matchedRoute?.preloadChunks &&\n Array.isArray(matchedRoute.preloadChunks)\n ) {\n // Both lists are built on the base the entry tags use, so a release\n // served from a CDN preloads its route chunks from that release\n // rather than from this app server. See utils/routeAssets.\n const routeAssets = resolveRouteAssets(\n manifest,\n matchedRoute.preloadChunks,\n this.staticAccessURL,\n );\n preloadScripts = routeAssets.scripts;\n preloadStyles = routeAssets.styles;\n }\n } catch (err) {\n console.warn('Failed to resolve preload chunks:', err);\n }\n }\n\n // Add matched route key to request object for Html component\n req['matchedRouteKey'] = matchedRouteKey;\n\n const ssrCss = await this.collectViteSsrCss(vite, App, matchedRoutes);\n // Per request, and not enumerable: Html reads `assets.__viteSsrCss` for\n // the inline <style>, but also serialises the whole assets object into\n // `assetManifest` for the client, which never uses it. Enumerable, the\n // collected CSS β€” megabytes in a large app β€” went into every page twice.\n // A per-request copy also keeps one render's CSS out of another's.\n const assets = { ...this.assets };\n if (ssrCss) {\n Object.defineProperty(assets, '__viteSsrCss', {\n value: ssrCss,\n enumerable: false,\n });\n }\n\n stream = renderToPipeableStream(\n <React.StrictMode>\n <StaticRouter location={req.url}>\n <AppContextProvider\n assets={assets}\n requestLD={requestLD}\n requestObject={requestObject}\n preloadScripts={preloadScripts}\n preloadStyles={preloadStyles}\n expressRequest={req}\n expressResponse={res}\n >\n <App />\n </AppContextProvider>\n </StaticRouter>\n </React.StrictMode>,\n {\n // How the client entry boots β€” dev preamble, ES module, or classic\n // script. See utils/bootstrapEntry.\n ...resolveBootstrapEntry({\n viteDevServer: usingViteDev,\n mainEntryIsModule: this.mainEntryIsModule,\n mainEntry: this.assets['main.js'],\n }),\n onShellReady: function () {\n res.statusCode = didError ? 500 : 200;\n res.setHeader('Content-type', 'text/html');\n\n // Create a caching transform stream Γ  la mxstbr.com/thoughts/streaming-ssr\n if (\n this.config.server?.cachePaths &&\n this.config.server.cachePaths.includes(req.url)\n ) {\n const bufferedChunks: Buffer[] = [];\n\n const cacheStream = new Transform({\n transform(chunk, _enc, cb) {\n bufferedChunks.push(chunk); // keep a copy\n cb(null, chunk); // forward unchanged\n },\n flush: (cb) => {\n const html = Buffer.concat(bufferedChunks).toString('utf8');\n this.cachedPaths.set(req.url, html);\n if (this.config.server.cacheTimeout) {\n setTimeout(\n () => this.cachedPaths.delete(req.url),\n this.config.server.cacheTimeout\n );\n }\n clearTimeout(timeout); // rendering finished β†’ stop timer\n cb();\n },\n });\n\n // Pipe the caching stream into the real response\n cacheStream.pipe(res);\n\n // React may **only be piped once**, so pipe it to the cacheStream\n stream.pipe(cacheStream);\n } else {\n stream.pipe(res);\n }\n }.bind(this),\n onShellError(x) {\n didError = true;\n console.error(x);\n // Respond NOW. Without this the socket stays open until the 10s\n // watchdog below fires, turning every render-time crash into an\n // opaque \"SSR timed out\" with the real error buried in the log.\n clearTimeout(timeout);\n if (res.headersSent) {\n res.end();\n return;\n }\n res.statusCode = 500;\n res.setHeader('Content-type', 'text/plain');\n res.end(\n 'SSR render failed before the shell was ready:\\n\\n' +\n ((x as any)?.stack ?? (x as any)?.message ?? String(x))\n );\n },\n }\n );\n\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n timeout = setTimeout(() => {\n stream.abort('⏱ SSR stream took too long β€” force abort');\n if (!res.headersSent) {\n res.statusCode = 500;\n res.end('SSR timed out');\n }\n }, 10_000);\n\n res.on('close', () => {\n clearTimeout(timeout); // if you're using a safety timeout\n });\n }\n\n //If we ever need to use multiple webpack entry-points and different bundle names, then uncomment this\n /*getWebpackAssets()\n\t{\n\t\t// const { devMiddleware } = res.locals.webpack;\n\t\t// const outputFileSystem = devMiddleware.outputFileSystem;\n\t\t// const jsonWebpackStats = devMiddleware.stats.toJson();\n\t\t// const { assetsByChunkName, outputPath } = jsonWebpackStats;\n\t\t//\n\t\t// let normalizedAssets = normalizeAssets(assetsByChunkName.main);\n\t\t// let cssAssets = normalizedAssets\n\t\t// .filter((path) => path.endsWith(\".css\"))\n\t\t// .map((filePath) => outputFileSystem.readFileSync(path.join(outputPath, filePath)))\n\t\t// .join(\"\\n\");\n\t\t//\n\t\t// let jsAssets = normalizeAssets(assetsByChunkName.main)\n\t\t// .filter((path) => path.endsWith(\".js\"))\n\t\t// .map((path) => `<script src=\"${path}\"></script>`)\n\t\t// .join(\"\\n\")}\n\t}*/\n\n sendJson(res, obj) {\n let jsonObject = JSONWriter.toJsObject(obj);\n res.json(jsonObject);\n }\n\n async initRequest(request, response) {\n // initialise the request for all providers, one after the other (order\n // matters: later providers may read what earlier ones put on the request).\n // A provider that throws is logged by package name and skipped.\n for (const [pkg, backendProvider] of this.genericProviders.entries()) {\n if (!backendProvider || typeof backendProvider.initRequest !== 'function') {\n continue;\n }\n await runProviderHook(pkg, 'initRequest', () =>\n backendProvider.initRequest(request, response)\n );\n }\n }\n\n async getRequestData(\n request,\n response\n ): Promise<{ requestLD: string; requestObject: string }> {\n // Providers return plain JSON data via supplyDataForRequest.\n // requestLD is kept as empty string for now; SSR data seeding will\n // inject query results instead of graph data.\n // A provider that throws (synchronously or not) is logged by package\n // name; the page still renders with the other providers' data.\n let requestData: Record<string, any> = {};\n await Promise.all(\n [...this.genericProviders.entries()].map(([pkg, backendProvider]) => {\n if (\n !backendProvider ||\n typeof backendProvider.supplyDataForRequest !== 'function'\n ) {\n return;\n }\n return runProviderHook(pkg, 'supplyDataForRequest', () =>\n backendProvider.supplyDataForRequest(request, response, requestData)\n );\n })\n );\n\n let requestLD = '';\n let requestObject = JSONWriter.stringify(request['frontendData']);\n return { requestLD, requestObject };\n }\n\n async callBackendMethod(\n pkg: string,\n method: string,\n args: any[],\n request?,\n response?\n ) {\n // A backend-to-backend call outside any request runs as system. Inside a\n // request (SSR, a provider calling another) it inherits that request.\n if (!request && !getCallContext()) {\n return runAsSystem(() =>\n this.callBackendMethod(pkg, method, args, request, response)\n );\n }\n if (!this.genericProviders.has(pkg)) {\n await this.ensurePackageBackendProviders(pkg, true);\n }\n\n //retrieve the indexed provider class and create a new instance for this request\n let genericBackendProvider = this.genericProviders.get(pkg);\n\n let result;\n if (!genericBackendProvider) {\n console.warn(\n `${paint('magenta', \n pkg\n )} does not have a generic backend provider. If you can edit this package, make sure 'backend.ts' is included in 'tsconfig.json' and that it exports a provider.`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n //test if there is a matching method in the backend provider, and whether it may be called\n const resolution = resolveCallable(genericBackendProvider, method);\n if (resolution.status === 'missing') {\n console.warn(\n `Generic provider '${\n Object.getPrototypeOf(genericBackendProvider).constructor.name\n }' of ${logSafe(pkg)} does not have a method called ${logSafe(method)}`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n this.assertDispatchAllowed(\n pkg,\n method,\n genericBackendProvider,\n resolution,\n request,\n 'generic'\n );\n\n try {\n //TODO: remove init request.\n //TODO: refactor this.request and this.response to a request parameter\n //NOTE: if this is a direct call from backend to backend, we won't know the request & response here because those don't get passed to the Server utility\n //if this is an issue, we need to see how we can get those back\n if (request && response) {\n //initialise the request for this specific provider\n //wrap the call in a promise and wait for it, because providers MAY return a promise\n await Promise.resolve(\n genericBackendProvider.initRequest(request, response)\n );\n this.assertSessionForLevel(pkg, method, resolution, request);\n }\n // args.push(request);\n // args.push(response);\n\n //call the method with the given arguments and return the result as json\n result = await Promise.resolve(\n genericBackendProvider[method].apply(genericBackendProvider, args)\n );\n } catch (e) {\n if (ServerCallError.is(e) && e.status === 401) throw e;\n console.warn(\n `Error whilst calling ${logSafe(method)}() in provider ${\n Object.getPrototypeOf(genericBackendProvider).constructor.name\n } of package ${logSafe(pkg)}:\\n`,\n e\n );\n\n // error logging\n LinkedErrorLogging.log(e);\n // Rethrow so the HTTP route answers with an error status instead of `200 null`.\n throw e;\n }\n return result;\n }\n}\n\n/**\n * Register the RPC routes (`/call/...`) and the `LincdAPI` routes (`/api/...`)\n * of `linkedServer` on an express app.\n *\n * `LinkedServer.start()` calls this; tests call it on a bare express app so they\n * drive exactly the routes a running server has.\n */\nexport function registerCallRoutes(\n app: { post: Function; get: Function },\n linkedServer: LinkedServer\n): void {\n const server: any = linkedServer;\n // Scoped-package variants (@scope/pkg). Register BEFORE the unscoped\n // routes β€” Express `:pkg` won't consume slashes, so a call to\n // `/call/@_linked/auth/signinDev` would otherwise fall through to the\n // 3-segment `:pkg/:shape/:method` route and be misinterpreted as a\n // shape-method call (pkg=`@_linked`, shape=`auth`). These handlers\n // recognise the `@scope/pkg` prefix and rebuild the full package name\n // before dispatching to the same handler used for unscoped packages.\n app.post(\n '/call/@:scope/:pkg/:method',\n server.handleErrorsJson(async (req, res) => {\n req.params.pkg = `@${req.params.scope}/${req.params.pkg}`;\n return server.processBackendMethodCall(req, res);\n })\n );\n app.post(\n '/call/@:scope/:pkg/:shape/:method',\n server.handleErrorsJson(async (req, res) => {\n req.params.pkg = `@${req.params.scope}/${req.params.pkg}`;\n return server.processShapeMethodCall(req, res);\n })\n );\n app.post(\n '/call/:pkg/:method',\n server.handleErrorsJson(async (req, res) =>\n server.processBackendMethodCall(req, res)\n )\n );\n app.post(\n '/call/:pkg/:shape/:method',\n server.handleErrorsJson(async (req, res) =>\n server.processShapeMethodCall(req, res)\n )\n );\n app.post(\n '/api/:method/:action?',\n server.handleErrorsJson(async (req, res) =>\n server.processAPICall(req, res, 'post')\n )\n );\n app.get(\n '/api/:method/:action?',\n server.handleErrorsJson(async (req, res) =>\n server.processAPICall(req, res, 'get')\n )\n );\n}\n"]}
1
+ {"version":3,"file":"LinkedServer.js","sourceRoot":"","sources":["../../../src/shapes/LinkedServer.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;;;;;;;;;AACb,OAAO,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACzC,OAAO,MAAM,MAAM,QAAQ,CAAC;AAC5B,OAAO,OAAqC,MAAM,SAAS,CAAC;AAC5D,OAAO,WAAW,MAAM,cAAc,CAAC;AACvC,OAAO,KAAK,QAAQ,MAAM,IAAI,CAAC;AAC/B,OAAO,KAAK,EAAE,MAAM,aAAa,CAAC;AAElC,oEAAoE;AACpE,oEAAoE;AACpE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AE,GAAG,EAAE,GAAG,EAAE,EAAE,CACzC,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,CAAC,CACxC,CACF,CAAC;AACJ,CAAC","sourcesContent":["'use strict';\nimport { timingSafeEqual } from 'crypto';\nimport events from 'events';\nimport express, { Express as ExpressServer } from 'express';\nimport fetchCookie from 'fetch-cookie';\nimport * as fsNative from 'fs';\nimport * as fs from 'fs/promises';\nimport { Server as HttpServer } from 'http';\n// Plan-011: imports from @_linked/cli now go through ./lifecycle (a\n// dynamic-import-free file) so Vite's SSR module graph doesn't pull\n// in the legacy webpack flow and emit dozens of unanalyzable-import\n// warnings on every boot.\nimport { getLincdPackages } from '@_linked/cli/lifecycle';\nimport { getPackageJSON } from '@_linked/cli/utils';\nimport type { LinkedConfig } from '@_linked/cli/interfaces';\nimport { AppContextProvider } from '@_linked/server-utils/components/AppContext';\nimport { BackendProvider } from '@_linked/server-utils/utils/BackendProvider';\nimport { JSONParser } from '@_linked/server-utils/utils/JSONParser';\nimport { JSONWriter } from '@_linked/server-utils/utils/JSONWriter';\nimport { Server } from '@_linked/server-utils/utils/Server';\nimport { ServerCallError } from '@_linked/server-utils/utils/ServerCallError';\nimport { ShapeProvider } from '@_linked/server-utils/utils/ShapeProvider';\nimport {\n getCallContext,\n httpCallContext,\n runAsSystem,\n runInHttpContext,\n runWithCallContext,\n} from '@_linked/server-utils/utils/CallContext';\nimport { Shape } from '@_linked/core/shapes/Shape';\nimport { LinkedErrorLogging } from '@_linked/core/utils/LinkedErrorLogging';\nimport {\n FileStorePurposes,\n LinkedFileStorage,\n} from '@_linked/core/utils/LinkedFileStorage';\nimport type { IFileStore } from '@_linked/core/interfaces/IFileStore';\nimport { getResizedImagesStore } from '../utils/resizedImagesPurpose.js';\nimport { paint } from '../utils/paint.js';\nimport { createJsonBodyParser } from '../utils/jsonBodyParser.js';\nimport { LinkedStorage } from '@_linked/core/utils/LinkedStorage';\nimport { autoLoadOntologyData } from '@_linked/core/utils/Package';\nimport {\n getShapeClass,\n getSuperShapesClasses,\n} from '@_linked/core/utils/ShapeClass';\nimport path from 'path';\nimport {pathToFileURL} from 'node:url';\nimport { isFatalError } from '../utils/fatalError.js';\nimport {\n discoverLinkedDependencies,\n isBundledBySsr,\n NODE_IMPORT_CONDITIONS,\n readInstalledPackage,\n resolveBackendEntry,\n ssrNoExternalOf,\n} from '../utils/linkedDependencies.js';\n\n/**\n * `instanceof ShapeProvider`, tolerating a second copy of server-utils.\n *\n * A registry-installed package's backend is loaded by Node (see\n * isBundledBySsr), so in a dev runner that BUNDLES server-utils β€” the\n * standalone case β€” its providers extend Node's copy of ShapeProvider, not the\n * one this module imported. Fall back to the class name along the prototype\n * chain. Production has one loader and one copy, so instanceof decides there.\n */\nfunction isShapeProvider(provider: any): boolean {\n if (provider instanceof ShapeProvider) return true;\n for (\n let proto = provider ? Object.getPrototypeOf(provider) : null;\n proto && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto)\n ) {\n if (proto.constructor?.name === 'ShapeProvider') return true;\n }\n return false;\n}\n\n/**\n * Call one provider's hook and contain its failure: a synchronous throw or a\n * rejection is logged, naming the package and the hook, and swallowed. Used\n * for hooks that run for every provider (boot lifecycle hooks and per-request\n * hooks), where one provider's bug must not take down boot or every request\n * without saying which provider it was.\n *\n * The exception is a fatal error (see utils/fatalError): with `atBoot` it is\n * logged and re-thrown, so the server refuses to start. Without it β€” the\n * server is already serving β€” it is logged as fatal and contained like any\n * other error: one provider must not take a running server down.\n */\nasync function runProviderHook(\n pkg: string,\n hook: string,\n call: () => any,\n atBoot = false\n): Promise<void> {\n try {\n await call();\n } catch (err: any) {\n if (isFatalError(err)) {\n logFatalError(pkg, hook, err, atBoot);\n if (atBoot) throw err;\n return;\n }\n console.error(\n paint('red', `[linked] ${pkg} ${hook} failed: ${err?.message ?? err}`),\n err?.stack ? `\\n${err.stack}` : ''\n );\n }\n}\n\n/** Log a fatal error once, at the point it was thrown (see runProviderHook). */\nfunction logFatalError(pkg: string, hook: string, err: any, atBoot: boolean) {\n if (loggedFatalErrors.has(err)) return;\n loggedFatalErrors.add(err);\n console.error(\n paint(\n 'red',\n atBoot\n ? `[linked] ${pkg} ${hook}: fatal error, refusing to start: ${err?.message ?? err}`\n : `[linked] ${pkg} ${hook}: fatal error after start, server keeps running: ${err?.message ?? err}`\n ),\n err?.stack ? `\\n${err.stack}` : ''\n );\n}\nconst loggedFatalErrors = new WeakSet<object>();\n\nimport process from 'process';\nimport * as React from 'react';\nimport { renderToPipeableStream, renderToStaticMarkup } from 'react-dom/server';\nimport { StaticRouter } from 'react-router-dom/server.js';\nimport { rimraf } from 'rimraf';\nimport sharp from 'sharp';\nimport {\n findStoredKey,\n resolveResizeSource,\n} from '../utils/resizeSource.js';\nimport { Transform } from 'stream';\nimport { CookieJar } from 'tough-cookie';\nimport { server } from '../ontologies/server.js';\nimport { linkedShape } from '../package.js';\nimport {\n resolveStaticAccessURL,\n staticAssetURL,\n} from '../utils/releaseManifest.js';\nimport {\n resolveBootstrapEntry,\n resolveViteMainEntry,\n resolveViteServingMode,\n} from '../utils/bootstrapEntry.js';\nimport { resolveRouteAssets } from '../utils/routeAssets.js';\nimport {\n resolveRouteComponent,\n ssrCssInlineUrls,\n ssrCssScope,\n} from '../utils/ssrCss.js';\nimport { materializeShapes } from '../utils/syncShapes.js';\nimport {\n installSpaFallback,\n repinSpaFallback,\n} from '../utils/spaFallback.js';\nimport { LincdAPI } from './LincdAPI.js';\nimport type { RoutesConfig, RouteConfig } from '../types/RouteConfig.js';\nimport {\n getRpcExposureMode,\n isGenericRpcDisabled,\n logSafe,\n resolveCallable,\n setRpcExposureMode,\n warnUndeclaredCall,\n} from '../utils/rpcExposure.js';\nimport { setRawQueriesMode } from '../utils/rawQueries.js';\n\n//prevent errors in node.js when (s)css files are imported in js\nconst isProduction = process.env.NODE_ENV === 'production';\nconst isDevelopment = process.env.NODE_ENV === 'development';\n\ndeclare var globalThis: any;\n// Install a global fetch that persists cookies across redirects using a CookieJar.\n// This ensures server-side requests behave more like browsers when handling Set-Cookie + redirects.\nconst __lincdCookieJar = new CookieJar();\n// Wrap native fetch with fetch-cookie so it reads/writes cookies in the jar.\nconst __lincdFetchWithCookies = fetchCookie(fetch, __lincdCookieJar);\n\n// Expose (optionally) for debugging/tests; not required by app logic.\n(globalThis as any).__lincdCookieJar = __lincdCookieJar;\n\n// Set the global fetch used throughout the server code path\n(globalThis as any).fetch = __lincdFetchWithCookies;\n\nprocess.on('uncaughtException', (err) => {\n console.warn(paint('red', 'Asynchronous error caught.'));\n console.error(err);\n\n // error logging\n LinkedErrorLogging.log(err);\n});\nprocess.on('unhandledRejection', (err) => {\n console.warn(paint('red', 'Unhandled rejection caught.'));\n console.error(err);\n\n // error logging\n LinkedErrorLogging.log(err as Error);\n});\n\nprocess.on('warning', (e) => console.warn(e.stack));\n\n//allow more listeners for when we have many concurrent users\nevents.EventEmitter.prototype.setMaxListeners(500);\n\n// const jsdom = require(\"jsdom\");\n// const { JSDOM } = jsdom;\n// const { document } = (new JSDOM(`...`)).window;\n//\n// global['document'] = document;\nglobal['reactStaticRenderer'] = renderToStaticMarkup;\n\nautoLoadOntologyData(true);\n\n/**\n * How RPC arguments treat a `{__sc}` (live Shape class) marker. No call takes a\n * Shape class from the client: logged in 'warn', refused (400) in 'enforce'.\n */\nfunction rpcShapeClassRevival(): 'warn' | 'reject' {\n return getRpcExposureMode() === 'enforce' ? 'reject' : 'warn';\n}\n\n/**\n * Serve the local upload folder at `/uploads` (where `LocalFileStore` files are\n * reachable), with the headers for untrusted files.\n */\nexport function mountUploads(\n app: { use: Function },\n folder: string = './data/uploads',\n maxAge: number = 1000 * 60 * 60 * 24 * 365\n): void {\n app.use(\n '/uploads',\n express.static(folder, {\n maxAge, // cache for a long time\n immutable: true, // Suggest that the content won't change\n // uploaded files are user content: never sniffed, never run as a page\n setHeaders: setUntrustedFileHeaders,\n })\n );\n}\n\n/**\n * Express middleware: run the rest of the chain in the request's http context.\n * `LinkedServer.start` installs it first, and again right after the JSON body\n * parser (whose stream callbacks do not carry the context).\n */\nexport function enterRequestContext(req, res, next) {\n runInHttpContext(req, res, next);\n}\n\n/**\n * Headers for files users uploaded (`/uploads`, resized copies): the browser\n * must not guess a type from the bytes, and a document served from them runs\n * sandboxed (no scripts, an opaque origin), so an uploaded HTML or SVG file\n * cannot act on the app's origin.\n */\nexport function setUntrustedFileHeaders(res) {\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('Content-Security-Policy', 'sandbox');\n}\n\n/** Whether the current HTTP call carries a session. */\nfunction hasSession(request): boolean {\n return !!request?.linkedAuth?.userAccount;\n}\n\n// Named explicitly: tsc emits `let X = class X`, and any later esbuild pass over that JS (Vite's\n// SSR `define` replacement runs one on every file mentioning a defined `process.env.*`) renames\n// the inner binding to `X2`, which would otherwise become this shape's IRI.\n@linkedShape({name: 'LinkedServer'})\nexport class LinkedServer extends Shape {\n /**\n * indicates that instances of this shape need to have this rdf.type\n */\n static targetClass = server.LincdServer;\n private config: LinkedConfig;\n private cachedPaths: Map<string, string> = new Map();\n private assets: { [key: string]: string } & {\n manifest?: Record<string, string>;\n };\n /**\n * Whether pages are served by the live Vite dev server rather than a\n * `vite build` on disk. Decided once in `start()` β€” see\n * utils/bootstrapEntry `resolveViteServingMode`.\n */\n private viteDevServer = false;\n /**\n * Base URL every asset this build produced is served from β€” resolved once in\n * `start()` and kept so per-request route chunks land on the same base as\n * the entry tags. Empty means origin-relative (development, and any app\n * serving its own bundles).\n */\n private staticAccessURL: string = '';\n /**\n * Whether `assets['main.js']` came from a Vite build. Vite always emits the\n * entry as an ES module, so it has to be bootstrapped with\n * `bootstrapModules`; a legacy webpack bundle is a classic script and must\n * keep `bootstrapScripts`.\n */\n private mainEntryIsModule = false;\n protected server: ExpressServer;\n protected httpServer: HttpServer;\n private package: any;\n private cacheWebpack: boolean;\n private cssMode = 'scss-modules';\n private analyse: boolean = false;\n private shapeProviders: Map<string, ShapeProvider[]> = new Map();\n private genericProviders: Map<string, BackendProvider> = new Map();\n // One indexing per package: boot and the lazy /call path share it, so two\n // concurrent first calls (or a call racing boot) never construct a\n // package's providers twice.\n private providerIndexing: Map<string, Promise<void>> = new Map();\n /**\n * Package name β†’ realpath of the installed copy whose backend is loaded,\n * as discovery found it. A package's backend is resolved from THIS\n * directory, never by its bare name from @_linked/server's own location:\n * Node would never look inside another package's nested node_modules, so a\n * linked package installed only there (owl/node_modules/@_linked/rdfs)\n * could not be loaded at all.\n */\n private linkedPackageDirs: Map<string, string> = new Map();\n private warnedDuplicateInstalls: Set<string> = new Set();\n //from resizedFileName to full resized path (CDN or similar)\n private resizePathsMap: Map<string, string> = new Map();\n private api: LincdAPI;\n /**\n * True while start() / initOnly() runs. A fatal provider error (see\n * utils/fatalError) thrown while booting stops the boot; after it, the same\n * error is logged and contained.\n */\n protected booting = false;\n\n /**\n * yarn linked start sends the contents of linked.config.js as an object to this constructor\n * @param n\n */\n constructor(config?: LinkedConfig | string | { id?: string }) {\n super(\n typeof config === 'string' || (config && 'id' in config)\n ? config\n : undefined\n );\n if (config && typeof config !== 'string' && !('id' in config)) {\n // The absence of `id` is the runtime discriminator for a LinkedConfig;\n // the widened `{id?: string}` member of the union keeps TS from narrowing\n // to it on that check alone.\n this.config = config as LinkedConfig;\n }\n\n this.api = new LincdAPI({ id: process.env.SITE_ROOT + '/api' });\n\n //Ensure the Server utility (for Server.call()) directly accesses\n // this server on the backend instead of going through a network call\n Server.setLocalServer(this);\n }\n\n /*async getLincdDependencies(): Promise<string[]> {\n\t\tlet lincdDependencies = [];\n\t\tlet dependencies = this.package.dependencies;\n\n\t\tawait Promise.all(\n\t\t\tObject.keys(dependencies).map((dependencyPkgName) => {\n\t\t\t\tlet modulePackageJson = getModulePackageJSON(dependencyPkgName);\n\t\t\t\tif (modulePackageJson['lincd']) {\n\t\t\t\t\tlincdDependencies.push(modulePackageJson.name);\n\t\t\t\t}\n\t\t\t\t// //TODO: also iteratively look into dependencies of this dependency\n\n\t\t\t\t// let packagePath;\n\t\t\t\t// try {\n\t\t\t\t// packagePath = require.resolve(`${dependencyPkgName}`);\n\t\t\t\t// } catch (err) {\n\t\t\t\t// console.warn('Could not find package ' + dependencyPkgName+'. Error: '+err.toString());\n\t\t\t\t// return;\n\t\t\t\t// }\n\t\t\t\t// packagePath = path.dirname(packagePath) + '/package.json'\n\t\t\t\t// return fs\n\t\t\t\t// .readFile(packagePath, 'utf-8')\n\t\t\t\t// .then((res) => {\n\t\t\t\t// let pkg = JSON.parse(res);\n\t\t\t\t// if (pkg['lincd']) {\n\t\t\t\t// lincdDependencies.push(pkg.name);\n\t\t\t\t// }\n\t\t\t\t\t// //TODO: also iteratively look into dependencies of this dependency\n\t\t\t\t\t// })\n\t\t\t\t\t// .catch((err) => {\n\t\t\t\t\t// console.log('Could not read package.json file: '+err);\n\t\t\t\t\t// });\n\t\t\t}),\n\t\t);\n\t\treturn lincdDependencies;\n\t}*/\n get app() {\n return this.server;\n }\n\n initPackage() {\n this.package = JSON.parse(\n fsNative.readFileSync(\n path.resolve(process.cwd(), 'package.json'),\n 'utf-8'\n )\n );\n }\n async initOnly() {\n return this.bootOrRefuse(() => this.initOnlyBoot());\n }\n\n private async initOnlyBoot() {\n await this.initOntologies();\n await this.initStores();\n\n this.initPackage();\n\n this.server = express();\n\n await this.initBackendProviders();\n\n await this.materializeShapesIntoStore();\n return this;\n }\n\n /**\n * Materialize this server's registered shapes into the RDF store as SHACL\n * (core `syncShapes` β†’ pure `sh:NodeShape` + property shapes), so a running\n * app's app-data holds the shapes its instances validate/query against\n * (plan-010 T1e.2). Whatever shapes the app package registers (published\n * re-exports + generated) get written on boot (and re-run on shape-file HMR).\n *\n * Additive only: store shapes this process did not register are left alone\n * unless the operator sets `LINKED_SYNC_SHAPES_PRUNE_ORPHANS=true` β€” see\n * `bootOrphanScope` in utils/syncShapes for why.\n *\n * Gated to servers whose DEFAULT dataset is a **concrete** materializable store\n * (detected via `rawQuery`) β€” i.e. an app pointing at its app-data FusekiStore.\n * CN's default is the context-routing `AppDataRouter` (no `rawQuery`), so CN is\n * skipped here β€” it materializes its own pinned native shapes in its storage\n * config.\n */\n private async materializeShapesIntoStore(): Promise<void> {\n // Opt-out via `linked.config` `syncShapesOnBoot` (default true); env\n // LINKED_SYNC_SHAPES_ON_BOOT overrides for deployment. CN sets\n // `syncShapesOnBoot: false` in its own linked.config β€” its default dataset is\n // a context-router that can't materialize context-free, and it syncs its own\n // pinned shapes separately (linked.backend.storage.js).\n const configFlag = (this.config as any)?.syncShapesOnBoot;\n const envFlag = process.env.LINKED_SYNC_SHAPES_ON_BOOT;\n if (configFlag === false || envFlag === 'false') {\n return;\n }\n const appData = LinkedStorage.getDefaultDataset();\n if (!appData) return;\n try {\n const {syncShapes} = await import('@_linked/core');\n // Explicit target: materialize EVERY registered shape into the app's own\n // data store regardless of per-shape routing/pins.\n await materializeShapes(appData, syncShapes as any);\n } catch (err) {\n console.warn('[LinkedServer] shape materialization failed (non-fatal):', err);\n }\n }\n\n // async serveData(req,res) {\n // let nodeURI = `${req.protocol}://${req.get('host')}${req.originalUrl}`;\n //\n // let store = LinkedStorage.getDatasets().find(store => {\n // return nodeURI.includes(store.namedNode.uri)\n // })\n // }\n\n /**\n * Boot the server and listen. Rejects β€” and makes the process exit non-zero β€”\n * when a provider throws a fatal error while booting (see utils/fatalError).\n */\n async start() {\n return this.bootOrRefuse(() => this.startBoot());\n }\n\n /**\n * Run a boot with `booting` set. A fatal provider error rejects it and hands\n * the error to exitAfterFatalStartupError; any other boot error rejects as it\n * always did.\n */\n private async bootOrRefuse<T>(boot: () => Promise<T>): Promise<T> {\n this.booting = true;\n try {\n return await boot();\n } catch (err) {\n if (isFatalError(err)) this.exitAfterFatalStartupError(err);\n throw err;\n } finally {\n this.booting = false;\n }\n }\n\n /**\n * Make sure a server that refused to start does not stay up as a process.\n *\n * start() rejects either way, so the caller can report the error. But a\n * rejected start() does not end the process on its own: the CLI's `linked\n * start` turns an unhandled rejection into a log line, and the Vite dev\n * server, a store connection or a provider's timer keeps the event loop\n * alive. So the exit code is set now β€” a process with nothing left running\n * exits 1 β€” and, as a backstop, the process is exited after a moment, on an\n * unref'd timer that never itself keeps the process alive.\n *\n * Override to embed the server somewhere that must not exit (tests).\n */\n protected exitAfterFatalStartupError(_err: unknown) {\n process.exitCode = 1;\n setTimeout(() => process.exit(1), 1000).unref();\n }\n\n private async startBoot() {\n this.initPackage();\n // 'warn' (default) or 'enforce'; see utils/rpcExposure.\n setRpcExposureMode((this.config?.server as any)?.rpcExposure);\n // 'session' (default) or 'off'; see utils/rawQueries.\n setRawQueriesMode((this.config?.server as any)?.rawQueries);\n // Static assets should come from the static store URL (versioned path),\n // not the upload store URL. An explicit STATIC_ACCESS_URL still wins;\n // otherwise the release manifest `linked build-app` wrote next to the\n // bundle says which published release this build is, so a deployment no\n // longer has to repeat that URL by hand. See utils/releaseManifest.\n // In development we deliberately use a relative path so bundle URLs work\n // regardless of which PORT the dev server bound to (browsers resolve\n // relative URLs against window.location.origin). Hardcoding SITE_ROOT\n // baked :4000 into every SSR'd HTML page.\n const isDevAssets = process.env.NODE_ENV === 'development';\n const staticAccessURL = resolveStaticAccessURL({\n isDevAssets,\n appRoot: process.cwd(),\n fileStoreAccessURL: LinkedFileStorage.accessURL,\n });\n this.staticAccessURL = staticAccessURL;\n const staticAsset = (assetPath: string) =>\n staticAssetURL(staticAccessURL, assetPath);\n\n // Bundle/manifest read (plan-011: Vite is the only supported build).\n // Vite manifest lives at public/bundles/.vite/manifest.json.\n this.assets = {\n 'main.js':\n staticAsset('/bundles/main.bundle.js') + '?v=' + this.package.version,\n 'main.css': staticAsset('/bundles/main.css'),\n };\n // Dev or built, decided once and reused by the render path β€” see\n // utils/bootstrapEntry. In development the build manifest is not read:\n // one left on disk by an earlier `vite build` would otherwise swap in\n // stale built CSS while Vite serves the live styles.\n const servingMode = resolveViteServingMode({\n viteConfig: (this.config.server as any)?.vite,\n nodeEnv: process.env.NODE_ENV,\n readManifest: () => {\n try {\n const viteManifestPath = path.resolve(\n process.cwd(),\n 'public/bundles/.vite/manifest.json'\n );\n if (!fsNative.existsSync(viteManifestPath)) return null;\n return JSON.parse(fsNative.readFileSync(viteManifestPath, 'utf-8'));\n } catch (err) {\n console.warn('Could not load bundle manifest:', err);\n return null;\n }\n },\n });\n this.viteDevServer = servingMode.viteDevServer;\n if (servingMode.manifest) {\n const viteManifest = servingMode.manifest as Record<string, any>;\n this.assets.manifest = viteManifest;\n // Resolve main entry per Vite manifest shape:\n // { \"src/index.tsx\": { file: \"assets/main-<hash>.js\", css: [...] } }\n const mainEntry = resolveViteMainEntry(viteManifest);\n if (mainEntry?.file) {\n this.assets['main.js'] = staticAsset(`/bundles/${mainEntry.file}`);\n this.mainEntryIsModule = true;\n }\n if (mainEntry?.css?.[0]) {\n this.assets['main.css'] = staticAsset(`/bundles/${mainEntry.css[0]}`);\n }\n }\n // Vite dev marker: the HTML renderer skips pre-built CSS/JS link tags,\n // because Vite handles asset injection itself.\n if (this.viteDevServer) {\n this.assets['__viteDev'] = '1';\n }\n\n const isProduction = process.env.NODE_ENV === 'production';\n if (!isProduction && this.config.cssMode === 'tailwind') {\n this.assets['tailwind-cdn'] = 'https://cdn.tailwindcss.com';\n }\n\n //for multicore we use PM2, and each instance needs to listen to port 0.\n // whilst the main thread will listen to env.PORT automatically\n // const PORT = this.config.multiCore ? 0 : process.env.PORT || 3000;\n // const publicPort = process.env.PORT || 3000;\n //update: back to original setup. multicore handles itself inside @semantu/multicore\n const PORT = parseInt(process.env.PORT) || 4000;\n this.server = express();\n\n const dirName = path.resolve(process.cwd(), 'frontend');\n\n await this.initOntologies();\n //TODO: when we do not keep all data in memory (and thus do not need to rely on in memory data for page requests), we can possibly remove await here, since all stores handle their own initialisation before executing commands\n await this.initStores();\n\n this.initGarbageCollection();\n // this.app.use((req, res, next) => {\n // console.log('start request');\n // next();\n // });\n // before controllers\n await this.initBackendProviders();\n\n await this.materializeShapesIntoStore();\n\n //START OF EXPRESS ROUTES AND MIDDLEWARE\n\n //use cors\n // var corsOptions = {\n // origin: ['http://localhost:4001', 'https://www.mynd.site'],\n // optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204\n // };\n // Every request runs in its own http call context, from the first layer\n // on: no handler (middleware, routers, error handlers) ever runs without\n // one. The context is kept on the request, so a layer that resumes from a\n // callback that lost it (a body parser's stream events) re-enters the same\n // one below.\n this.server.use(enterRequestContext);\n //accept JSON bodies\n this.server.use(createJsonBodyParser());\n this.server.use(enterRequestContext);\n\n // this.server.use(cors(corsOptions));\n //\n // //compress server output with gzip,\n //UPDATE ive set level to 2 (low compression fast speed) because responses were taking too long (98% of server time was used by compress)\n // this.server.use(compress({level: 2}));\n\n await this.callGenericBackendProvidersMethod('setupBeforeControllers');\n\n // Vite middleware (plan 010): when the user app starts via Vite\n // (`linked start --vite`), the orchestrator passes the Vite handle\n // through config.server.viteMiddleware. We mount it and skip the\n // entire webpack-dev-middleware setup below.\n const viteMiddleware = (this.config.server as any)?.viteMiddleware;\n if (viteMiddleware) {\n this.server.use(viteMiddleware);\n }\n\n // Plan-011: legacy webpack-dev-middleware branch removed. Under Vite\n // (the only supported dev path now) `viteMiddleware` is set, which\n // previously forced `skipBuild = true` and made this whole block\n // dead. Removing it ends the static dependency on @_linked/cli/\n // config-webpack-app (full of dynamic imports Vite couldn't analyze)\n // and shrinks LinkedServer's import surface considerably.\n\n // //map URL routes to file paths\n const oneYear = 1000 * 60 * 60 * 24 * 365; // in milliseconds\n const oneMonth = 1000 * 60 * 60 * 24 * 30; // in milliseconds\n this.server.use(\n '/public',\n express.static('./public', {\n maxAge: oneYear, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n\n mountUploads(this.server, './data/uploads', oneYear);\n this.server.use('/', express.static('./public/root'));\n this.server.use(\n '/favicon.ico',\n express.static('./public/favicon.ico', {\n maxAge: oneMonth, // Tell browser to cache for 1 year\n immutable: true, // Suggest that the content won't change\n })\n );\n this.server.use('/.well-known', express.static('./public/.well-known'));\n\n // this.server.post('/data',this.handleErrorsJson(async (req,res) => this.serveData(req, res)));\n this.server.get('/resized/*', async (req, res) => {\n this.resizeImage(req, res);\n });\n\n registerCallRoutes(this.server, this);\n // this.server.post(\n // '/api/query/:method',\n // this.handleErrorsJson(async (req, res) => this.processQuery(req, res)),\n // );\n\n // now that all the middleware is defined, we initialise the providers, before we define a catch-all route\n // before catch all\n // await this.initBackendProviders();\n await this.callGenericBackendProvidersMethod(\n 'setupBeforeCatchAllControllers'\n );\n\n // HEAD catch-all for maintenance/health check (client fetches SITE_ROOT with method: HEAD)\n this.server.head('__health', (_req, res) => {\n res.sendStatus(200);\n });\n\n // CN control channel (plan-010 T1b.3). Present only when CN spawned this\n // process with a shared secret (CN_APP_ADMIN_SECRET); a standalone app run\n // without the secret leaves the channel closed (404). Auth is the\n // x-cn-admin-secret header matching that env value.\n const adminSecret = process.env.CN_APP_ADMIN_SECRET;\n // Constant-time compare so the secret can't be recovered by timing the 401\n // response. timingSafeEqual requires equal-length buffers, so guard length.\n const secretMatches = (provided: string | undefined): boolean => {\n if (!adminSecret || !provided) return false;\n const a = Buffer.from(provided);\n const b = Buffer.from(adminSecret);\n return a.length === b.length && timingSafeEqual(a, b);\n };\n const requireAdmin = (req: express.Request, res: express.Response): boolean => {\n if (!adminSecret) {\n res.sendStatus(404); // no control channel in this mode\n return false;\n }\n if (!secretMatches(req.get('x-cn-admin-secret'))) {\n res.sendStatus(401);\n return false;\n }\n return true;\n };\n this.server.get('/admin/health', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.status(200).json({ status: 'ok' });\n });\n this.server.post('/admin/restart', (req, res) => {\n if (!requireAdmin(req, res)) return;\n res.sendStatus(202);\n // CN's provisioner respawns on exit (see ChildProcessProvisioner).\n setTimeout(() => process.exit(0), 50);\n });\n\n // after controller\n await this.callGenericBackendProvidersMethod('setupAfterControllers');\n\n // The SPA catch-all goes on LAST. `setupAfterControllers` is a documented\n // hook for providers to register their own routes, so installing the\n // catch-all before it would shadow every GET route registered there β€”\n // answering them with the client shell at status 200.\n // An API-only backend (`linked start --api-only`) has no app to render:\n // without the catch-all, page requests get express's plain 404.\n if (!(this.config.server as any)?.apiOnly) {\n this.installSpaFallback();\n }\n\n //remove http(s):// and remove port :[port]\n const HOST = process.env.SITE_ROOT.replace(/https?:\\/\\//, '').replace(\n /:\\d+$/,\n ''\n );\n\n //backlog of 1024 means maximum of 1024 connections in the queue (higher than default)\n this.httpServer = this.server.listen({ port: PORT, backlog: 1024 }, () => {\n console.log(`Up and running at http://localhost:${PORT}`);\n // open(`http://localhost:${PORT}`)\n });\n // Ensure all inactive connections are terminated by the ALB, by setting this a few seconds higher than the ALB idle timeout\n this.httpServer.keepAliveTimeout = 60_000;\n // Ensure the headersTimeout is set higher than the keepAliveTimeout due to this nodejs regression bug: https://github.com/nodejs/node/issues/27363\n this.httpServer.headersTimeout = 61_000;\n\n this.httpServer.on('error', function (error) {\n if (error['syscall'] !== 'listen') {\n throw error;\n }\n const isPipe = (portOrPipe) => Number.isNaN(portOrPipe);\n const bind = isPipe(PORT) ? 'Pipe ' + PORT : 'Port ' + PORT;\n switch (error['code']) {\n case 'EACCES':\n console.error(bind + ' requires elevated privileges');\n process.exit(1);\n case 'EADDRINUSE':\n console.error(bind + ' is already in use');\n process.exit(1);\n default:\n throw error;\n }\n });\n return this;\n }\n\n async initOntologies() {}\n\n /**\n *\n * @returns\n * @todo Check if default file store is set, if not, set it\n */\n async initStores() {\n return Promise.all(\n LinkedStorage.getDatasets().map((store) => {\n return store.init ? store.init() : Promise.resolve();\n })\n );\n }\n\n /**\n * Run a lifecycle hook (setupBeforeControllers, setupBeforeCatchAllControllers,\n * setupAfterControllers) on every generic provider, in indexing order.\n *\n * Each provider is isolated: a hook that throws (or rejects) is logged with\n * the package and hook name and the next provider still runs, so one broken\n * provider does not abort boot. That provider's routes or middleware from\n * that hook may be missing, but the rest of the app starts.\n */\n async callGenericBackendProvidersMethod(method: string, ...args: any[]) {\n for (let [pkg, genericProvider] of this.genericProviders.entries()) {\n if (!genericProvider || typeof genericProvider[method] !== 'function') {\n continue;\n }\n await runProviderHook(\n pkg,\n method,\n () => genericProvider[method](...args),\n this.booting\n );\n }\n }\n\n /**\n * Removes temporary nodes from memory if they've been seen twice\n * Current interval is once per hour.\n * So after 2 hours temporary nodes are removed.\n */\n initGarbageCollection() {\n // let seenLastTime:NodeSet<NamedNode> = null;\n // setInterval(() => {\n //\n // let tempNodes = new NodeSet<NamedNode>();\n // NamedNode.getAllNamedNodes().forEach(n => {\n // if(n.isTemporaryNode) {\n // if(seenLastTime && seenLastTime.has(n))\n // {\n // n.remove();\n // } else {\n // tempNodes.add(n);\n // }\n // }\n // })\n // seenLastTime = tempNodes;\n // }, 1000 * 10); //every 10 sec\n // // }, 1000 * 60 * 60); //every hour\n }\n async initBackendProviders() {\n // Local workspace packages in this app's dependency tree. These are also\n // imported whole at boot (indexLincdPackage), not only their /backend.\n const allLocalPackages = getLincdPackages();\n const localPackageMap = new Map<\n string,\n { packageName: string; path: string }\n >(allLocalPackages.map((pkg) => [pkg.packageName, pkg]));\n const relevantPackages = this.filterPackagesByDependencyTree(\n localPackageMap,\n this.package\n );\n // Every linked package in the dependency tree, installed or local, each\n // after the linked packages it depends on. Registry installs and\n // localized checkouts are not workspace members, and used to be indexed\n // only lazily, on the first /call/<pkg>/... A provider can hook every\n // request (initRequest, supplyDataForRequest, setupBeforeControllers\n // routes), so those hooks stayed silent until some RPC to the package\n // happened β€” an installed @_linked/auth did not put the session into a\n // page's request data until then, and its setupBeforeControllers\n // middleware never registered at all.\n await this.indexLinkedDependencyProviders(relevantPackages);\n\n try {\n await fs\n .readFile(path.join(process.cwd(), 'package.json'), 'utf-8')\n .then(async (contents) => {\n let pkg = JSON.parse(contents);\n // Route through default ${pkg}/backend resolution. The app's\n // package.json `exports`./backend field handles dev vs prod:\n // \"exports\": {\n // \"./backend\": {\n // \"development\": \"./src/backend.ts\",\n // \"default\": \"./lib/esm/backend.js\"\n // }\n // }\n // Removed plan-010 D10: the source-direct\n // path.join(cwd, 'src', 'backend.ts') override that forced TS\n // runtime loading. Vite SSR's ssrLoadModule handles the\n // transform; production runs from lib/esm/.\n await this.indexPackageBackendProviders(pkg.name, false);\n });\n } catch (err) {\n // Already logged where it was thrown; it must reach start().\n if (isFatalError(err)) throw err;\n console.warn(err);\n }\n }\n\n /**\n * Index the backend providers of every linked package in the app's\n * dependency tree, dependencies first. Workspace members (`localPackages`)\n * are also imported whole, as before; for anything else only its `/backend`\n * entry is loaded β€” resolved from the directory discovery found the package\n * in, and skipped without an import when the package has none.\n */\n private async indexLinkedDependencyProviders(\n localPackages: Map<string, { packageName: string; path: string }>\n ) {\n const started = Date.now();\n const installed: string[] = [];\n const ordered = discoverLinkedDependencies(process.cwd(), this.package);\n // A workspace member the walk cannot reach through node_modules still\n // loads, after the rest, as it always did.\n const remaining = new Set(localPackages.keys());\n this.linkedPackageDirs ??= new Map();\n for (const dep of ordered) {\n this.linkedPackageDirs.set(dep.packageName, dep.path);\n this.warnIfInstalledMoreThanOnce(dep);\n }\n for (const [packageName, local] of localPackages) {\n if (!this.linkedPackageDirs.has(packageName) && local?.path) {\n let dir = local.path;\n try {\n dir = fsNative.realpathSync(dir);\n } catch {}\n this.linkedPackageDirs.set(packageName, dir);\n }\n }\n for (const { packageName } of ordered) {\n const isLocal = remaining.delete(packageName);\n await this.ensurePackageBackendProviders(packageName);\n if (isLocal) {\n await this.indexLincdPackage(packageName);\n } else if (\n this.genericProviders.get(packageName) ||\n this.shapeProviders.get(packageName)?.length\n ) {\n installed.push(packageName);\n }\n }\n for (const packageName of remaining) {\n await this.ensurePackageBackendProviders(packageName);\n await this.indexLincdPackage(packageName);\n }\n if (installed.length > 0) {\n console.log(\n paint('gray', \n `[linked] indexed backend providers of ${ordered.length} linked package(s) in ${\n Date.now() - started\n }ms; installed ones with providers: ${installed.join(', ')}`\n )\n );\n }\n }\n\n /**\n * Two installed copies of one linked package mean two copies of its module\n * state, and only one of them can own the backend. The one the app resolves\n * is loaded (see discoverLinkedDependencies); the other is never loaded.\n */\n private warnIfInstalledMoreThanOnce(dep: {\n packageName: string;\n path: string;\n copies?: { path: string; version?: string }[];\n }) {\n const copies = dep.copies ?? [];\n this.warnedDuplicateInstalls ??= new Set();\n if (copies.length < 2 || this.warnedDuplicateInstalls.has(dep.packageName)) {\n return;\n }\n this.warnedDuplicateInstalls.add(dep.packageName);\n const list = copies\n .map((c) => `${c.version ?? '?'} at ${c.path}`)\n .join(', ');\n console.warn(\n paint('yellow', \n `[linked] ${dep.packageName} is installed ${copies.length} times (${list}); loaded ${dep.path}. Run npm dedupe.`\n )\n );\n }\n\n /**\n * The directory a package's backend is resolved from: the copy discovery\n * chose, or β€” for a package outside the linked tree, reached only by a lazy\n * /call β€” the copy the app itself resolves.\n */\n private packageDirFor(pkg: string): string | null {\n const known = this.linkedPackageDirs?.get(pkg);\n if (known) return known;\n const installed = readInstalledPackage(pkg, process.cwd());\n if (!installed) return null;\n try {\n return fsNative.realpathSync(installed.root);\n } catch {\n return installed.root;\n }\n }\n\n /**\n * Index a package's backend providers once. Shared by boot and the lazy\n * path in callBackendMethod / callShapeMethod. `onSourceChange` bypasses it\n * on purpose: an HMR reload must re-index.\n */\n async ensurePackageBackendProviders(pkg: string, warnIfNotFound = false) {\n if (this.genericProviders.has(pkg) && this.shapeProviders.has(pkg)) {\n return;\n }\n let indexing = this.providerIndexing.get(pkg);\n if (!indexing) {\n // Loading a package's providers runs their constructors and setup hooks.\n // That is system work, even when the first call to the package triggers it.\n indexing = runAsSystem(\n () => this.indexPackageBackendProviders(pkg, warnIfNotFound),\n 'loading backend providers of ' + pkg\n ).then(() => undefined);\n this.providerIndexing.set(pkg, indexing);\n }\n try {\n await indexing;\n } finally {\n this.providerIndexing.delete(pkg);\n }\n }\n\n /**\n * Node's `import()`. Called with the absolute file URL of a resolved backend\n * entry (see resolveBackendEntry), never a bare name.\n */\n protected importModule(specifier: string): Promise<any> {\n return import(/* @vite-ignore */ specifier);\n }\n\n /**\n * Filters local workspace packages to only those reachable from the app's\n * dependency tree. Mirrors the logic used by `buildAll` in lincd-cli.\n */\n private filterPackagesByDependencyTree(\n allPackages: Map<string, { packageName: string; path: string }>,\n appPackageJson: any\n ): Map<string, { packageName: string; path: string }> {\n const relevantPackages = new Map<\n string,\n { packageName: string; path: string }\n >();\n const packagesToCheck = new Set<string>();\n const processedPackages = new Set<string>();\n\n // Start with direct dependencies from the app\n if (appPackageJson.dependencies) {\n for (const dep of Object.keys(appPackageJson.dependencies)) {\n if (allPackages.has(dep)) {\n packagesToCheck.add(dep);\n }\n }\n }\n\n // Recursively follow each package's dependencies\n while (packagesToCheck.size > 0) {\n const packageName = packagesToCheck.values().next().value;\n packagesToCheck.delete(packageName);\n if (processedPackages.has(packageName)) {\n continue;\n }\n processedPackages.add(packageName);\n const packageDetails = allPackages.get(packageName);\n if (packageDetails) {\n relevantPackages.set(packageName, packageDetails);\n const pkg = getPackageJSON(packageDetails.path);\n if (pkg?.dependencies) {\n for (const dep of Object.keys(pkg.dependencies)) {\n if (allPackages.has(dep) && !processedPackages.has(dep)) {\n packagesToCheck.add(dep);\n }\n }\n }\n }\n }\n\n return relevantPackages;\n }\n\n async resizeImage(req, res) {\n //check if the w or h query parameters are set\n let width = req.query.w;\n let height = req.query.h;\n //if not\n if (!width && !height) {\n //redirect to the original image\n res.redirect(req.originalUrl.replace('/resized', '/uploads'));\n return;\n }\n\n let imageFileName = req.query.src; // example: https://cdnurl.com/uploads/1710814765388-935b511c9_cropped.jpeg\n const accessURL = LinkedFileStorage.accessURL;\n\n if (imageFileName) {\n // `src` may only name an image this app already stores. Before this check\n // the value went straight to fetch(), which made the route an open proxy\n // into its own network -- cloud metadata, localhost, private ranges -- and\n // the response was then written into the PUBLIC file store and the caller\n // redirected to it, so anything reachable was persisted, not just leaked.\n //\n // resolveResizeSource compares parsed origins (a startsWith check is\n // defeated by https://cdn.example.com.evil.com) and hands back the key,\n // which must also exist in the store before anything is requested.\n const source = resolveResizeSource(imageFileName, accessURL);\n\n if (!source.allowed) {\n res.status(400).send({ error: 'Unsupported image source' });\n return;\n }\n\n // Two candidates, because the stores disagree on whether the public URL\n // includes the upload mount -- see resolveResizeSource. Fail-closed: if\n // neither shape is held, nothing is fetched.\n const storedKey = await findStoredKey(source.keys, (key) =>\n LinkedFileStorage.fileExists(key)\n );\n\n if (!storedKey) {\n res.status(404).send({ error: 'Could not fetch image from URL' });\n return;\n }\n\n // extract the base name and extension from the key the store actually\n // holds, not from the URL path.\n //\n // These differ: LocalFileStore serves `accessURL + /uploads/ + key`, so\n // deriving the destination from the URL gave it an extra `uploads/`\n // segment and resized files landed in data/uploads/uploads/resized/.\n // S3FileStore serves the key directly, so for it the two are the same --\n // which is why this went unnoticed. Deriving from the key is correct for\n // both.\n const { name, ext } = path.parse(storedKey);\n\n // Sharp READS svg but cannot WRITE it, so an SVG source is rasterized to\n // PNG below. The cache key has to say so: storing PNG bytes under a `.svg`\n // key would also mean serving them as `image/svg+xml`, since the cache-hit\n // branch types the response from this extension.\n const outputExt = ext.toLowerCase() === '.svg' ? '.png' : ext;\n\n // append the width and height parameters to the base name\n // example: 935b511c9_cropped_w190.jpeg or 935b511c9_cropped_w190h190.jpeg\n //\n // The underscore is emitted once, before either dimension, rather than as\n // part of the width segment. With it inside the width, a height-only\n // request produced `logoh30.jpeg` here while the local branch below --\n // which has always written the separator unconditionally -- produced\n // `logo_h30.jpeg` for the same request. The two halves of one route\n // disagreed on the cache key.\n const newName = `${name}_${width ? 'w' + width : ''}${\n height ? 'h' + height : ''\n }`;\n\n // the destination key, alongside the original\n // example: uploads/935b511c9_cropped.jpeg -> uploads/resized/935b511c9_cropped_w190.jpeg\n // and for a LocalFileStore key: photo.jpg -> resized/photo_w190.jpg\n const keyDir = path.dirname(storedKey);\n const newPathname = path.join(\n keyDir === '.' ? '' : keyDir,\n 'resized',\n `${newName}${outputExt}`\n );\n\n const resizedImageFileName = newPathname.startsWith('/')\n ? newPathname.slice(1)\n : newPathname;\n\n if (this.resizePathsMap.has(resizedImageFileName)) {\n res.redirect(this.resizePathsMap.get(resizedImageFileName));\n return;\n }\n\n // check if the resized image already exists in the CDN\n const imageExists: boolean = await LinkedFileStorage.fileExists(\n resizedImageFileName\n );\n\n // if exists, redirect to the resized image\n if (imageExists) {\n const resizedPathOnCdn: string = accessURL + '/' + resizedImageFileName;\n //save to cache\n this.resizePathsMap.set(resizedImageFileName, resizedPathOnCdn);\n //redirect this request to the resized image\n res.redirect(resizedPathOnCdn);\n return;\n } else {\n console.log(\n `${process.pid} - ${\n process.env.PORT\n }: Resizing image: ${imageFileName} to ${width} x ${height || ''}`\n );\n //in multicore development, we need to access the site from 127.0.0.1, and so all requests need to go there\n // // if (process.env.NODE_ENV === 'development' && process.env.NUM_WORKER_PROCESSES) {\n // // imageFileName = imageFileName.replace('localhost', '127.0.0.1');\n // // }\n\n // Read the bytes out of the store rather than fetching its public URL.\n //\n // Once `src` has to name an image the store already holds, fetching is\n // a round-trip to ask a web server for a file this process can open --\n // over the loopback interface, for a LocalFileStore. Reading directly\n // is faster, and it means the route makes no outbound request at all:\n // there is no origin to re-check after a redirect, no timeout to tune\n // and no response size to cap, because there is no response.\n const image = await LinkedFileStorage.getFile(storedKey);\n\n // if image is null or empty, return 404\n if (!image?.length) {\n res.status(404).send({ error: 'Could not fetch image from URL' });\n return;\n }\n\n // get the format of the image\n let format;\n try {\n format = await sharp(image)\n .metadata()\n .then((meta) => meta.format);\n } catch (err) {\n console.warn('Unsupported image format: ' + err);\n res.status(400).send({ error: 'Unsupported image format' });\n return;\n }\n\n // Sharp reads SVG but has no SVG encoder, so `.toFormat('svg')` throws\n // and every resize of an SVG failed. Rasterize to PNG instead β€” lossless,\n // and it matches the `.png` cache key chosen above.\n const outputFormat = format === 'svg' ? 'png' : format;\n\n // set the output options based on the format for quality and compression\n let outputOptions;\n switch (outputFormat) {\n case 'jpeg':\n outputOptions = { quality: 90 };\n break;\n case 'png':\n outputOptions = { compressionLevel: 9 };\n break;\n case 'webp':\n outputOptions = { quality: 90 };\n break;\n // add more formats here\n default:\n outputOptions = {};\n }\n\n // resize the image\n const resizedImage: Buffer = await sharp(image)\n .resize(\n width ? parseInt(width) : null,\n height ? parseInt(height) : null\n )\n .toFormat(outputFormat, outputOptions)\n .toBuffer()\n .catch((err) => {\n console.warn('Could not resize image: ' + err);\n return null;\n });\n\n // if resizedImage is null, return 500\n if (!resizedImage) {\n res.status(500).send({ error: 'Could not resize image' });\n return;\n }\n\n // upload the resized image to the CDN\n const resizedPathOnCdn = await LinkedFileStorage.saveFile(\n newPathname,\n resizedImage\n );\n\n //save to cache\n this.resizePathsMap.set(resizedImageFileName, resizedPathOnCdn);\n //redirect this request to the resized image\n res.redirect(resizedPathOnCdn);\n return;\n }\n } else {\n imageFileName = req.originalUrl.split('/resized/')[1]?.split('?')[0];\n }\n\n // Both halves of this route now read and write through LinkedFileStorage.\n //\n // This branch used to hardcode <cwd>/data/uploads for both, which meant it\n // could only ever work for a LocalFileStore: an app configured with S3 kept\n // its uploads in the bucket, so every request here looked on a local disk\n // that had nothing on it and 404'd. Going through the store also removes the\n // need to create the cache directory by hand -- LocalFileStore.saveFile\n // makes its own parent folders, which is why the mkdirSync that used to sit\n // here (commented out, so it silently did nothing) is gone rather than\n // restored.\n const [trueFileName, ...extensions] = imageFileName.split('.');\n const sourceExtension = extensions.join('.');\n\n // Same rasterization as the branch above: sharp reads SVG but cannot write\n // it. `extension` is what the cached derivative actually IS, and is what\n // `sendStoredFile` types the response with, so it has to be the OUTPUT\n // format rather than the source's.\n const extension =\n sourceExtension.toLowerCase() === 'svg' ? 'png' : sourceExtension;\n\n const resizedKey = path.join(\n path.dirname(imageFileName) === '.' ? '' : path.dirname(imageFileName),\n 'resized',\n `${path.basename(trueFileName)}_${width ? 'w' + width : ''}${\n height ? 'h' + height : ''\n }.${extension}`\n );\n\n // The resize cache is its own purpose, so an app can keep derivatives on a\n // local disk while its uploads live in S3, or share one store for both.\n // Unconfigured, it falls back to the default store, which is the previous\n // behaviour for anyone who never thinks about it.\n const cacheStore = getResizedImagesStore();\n const sendStoredFile = async (store: IFileStore, key: string) => {\n const bytes = await store.getFile(key);\n if (!bytes) {\n return false;\n }\n res.type(extension || 'bin').send(bytes);\n return true;\n };\n\n if (await cacheStore.fileExists(resizedKey)) {\n if (await sendStoredFile(cacheStore, resizedKey)) {\n return;\n }\n }\n\n const uploadsStore = LinkedFileStorage.getStore(FileStorePurposes.uploads);\n const original = await uploadsStore.getFile(imageFileName);\n\n if (!original) {\n console.warn('Could not find original image at ' + imageFileName);\n res.status(404).send({ error: 'Could not find original image' });\n return;\n }\n\n let resized: Buffer;\n try {\n const pipeline = sharp(original).resize(\n width ? parseInt(width) : null,\n height ? parseInt(height) : null\n );\n // Without this, sharp writes in the INPUT format, which for an SVG source\n // means asking for an encoder it does not have.\n resized = await (sourceExtension.toLowerCase() === 'svg'\n ? pipeline.png({ compressionLevel: 9 })\n : pipeline\n ).toBuffer();\n } catch (err) {\n console.warn('Could not resize image: ' + err);\n res.status(500).send({ error: 'Could not resize image' });\n return;\n }\n\n // preventDuplicates: false because this is a cache keyed by name. Letting\n // the store pick a fresh name on collision would write a second copy for\n // every request and never hit the cache.\n //\n // A failure here is logged, not fatal: the resize succeeded, so the caller\n // still gets its image and only the caching is lost. It used to be\n // swallowed and then followed by sendFile on a file that was never written,\n // which turned a cache miss into a 404 with nothing in the response to say\n // why -- and, on the error path, into a second send after the 500.\n try {\n await cacheStore.saveFile(resizedKey, resized, {\n preventDuplicates: false,\n });\n } catch (err) {\n console.warn('Could not cache resized image at ' + resizedKey + ': ' + err);\n }\n\n setUntrustedFileHeaders(res);\n res.type(extension || 'bin').send(resized);\n }\n\n async indexLincdPackage(pkg: string, warnIfNotFound: boolean = false) {\n if (pkg === this.package.name) {\n return;\n }\n try {\n // console.log(`πŸ” Loading package: ${pkg}`);\n // console.log(\n // `πŸ” Module resolution for ${pkg}:`,\n //@ts-ignore\n // await import.meta.resolve(pkg)\n // );\n // plan-011 Β§P6 β€” prefer Vite's SSR loader so workspace packages register\n // on the SINGLE @_linked/core instance the rest of the SSR graph uses.\n // The bare Node `import()` fallback resolves `default`β†’lib, evaluating a\n // SECOND core copy (benign post-Β§P1, but a needless second instance).\n // Node import stays as the fallback when Vite isn't active (production /\n // Node-only CLI commands). Mirrors indexPackageBackendProviders.\n const vite: any = (this.config.server as any)?.vite;\n if (vite && typeof vite.ssrLoadModule === 'function') {\n await vite.ssrLoadModule(pkg);\n } else {\n // @vite-ignore β€” dynamic specifier is intentional: this checks\n // whether `pkg` is resolvable at runtime, then catches the error.\n // eslint-disable-next-line no-unsanitized/method\n await import(/* @vite-ignore */ pkg);\n }\n // console.log(`βœ… Successfully loaded: ${pkg}`);\n } catch (e) {\n if (isFatalError(e)) {\n logFatalError(pkg, 'module load', e, this.booting);\n if (this.booting) throw e;\n return;\n }\n let providerNotFound =\n e.code === 'MODULE_NOT_FOUND' &&\n e.message.indexOf(`Cannot find package '${pkg}'`) !== -1;\n if (providerNotFound) {\n // console.warn('Error loading ' + providerPath + ': ' + e.stack);\n if (warnIfNotFound) {\n console.warn(\n paint('magenta', \n `Could not load package ${logSafe(pkg)}`,\n typeof module !== 'undefined' && typeof exports !== 'undefined'\n ? //@ts-ignore\n ' at ' + (await import.meta.resolve(pkg))\n : ''\n )\n );\n }\n } else {\n console.warn(\n paint('red', \n `Error loading '${logSafe(pkg)}' ${\n typeof module !== 'undefined' && typeof exports !== 'undefined'\n ? //@ts-ignore\n ' at ' + (await import.meta.resolve(pkg))\n : ''\n }: ${e.message}\\n`\n ),\n e.stack\n );\n }\n }\n }\n async indexPackageBackendProviders(\n pkg: string,\n warnIfNotFound: boolean = false\n ) {\n let backendProviderExports;\n let genericBackendProvider = null;\n let shapeProviders = [];\n const vite: any = (this.config.server as any)?.vite;\n // In dev, load a package's backend with the loader that owns the package\n // (see isBundledBySsr): Vite for the app itself and for what the SSR\n // runner bundles (workspaces, SSR_ENTRY_PACKAGES), Node for what it\n // leaves external (registry installs). ssrLoadModule of an EXTERNAL\n // package's /backend evaluated that package a second time, apart from the\n // copy the app's own imports reach.\n const viteOwnsPackage =\n !!vite &&\n typeof vite.ssrLoadModule === 'function' &&\n (pkg === this.package?.name ||\n isBundledBySsr(pkg, ssrNoExternalOf(vite)));\n\n // Decide whether there IS a backend before importing anything. A package\n // without one is the normal case (most linked packages have none) and is\n // quiet; once a backend file is known to exist, any failure to load it is\n // a real error. This used to be decided after the fact, by matching the\n // loader's error text β€” which Node and Vite word differently, so a nested\n // package's \"Cannot find package\" was reported as a broken backend.\n let entry: string | null = null;\n let load: (() => Promise<any>) | null = null;\n if (pkg === this.package?.name) {\n // The app's own backend cannot be imported by name: a self-reference\n // resolves only from inside the package that declares it, and this code\n // lives in node_modules/@_linked/server. Load it by path.\n const cwd = process.cwd();\n if (viteOwnsPackage) {\n const source = path.join(cwd, 'src', 'backend.ts');\n if (fsNative.existsSync(source)) {\n entry = source;\n load = () => vite.ssrLoadModule('/src/backend.ts');\n }\n } else {\n entry = [\n path.join(cwd, 'lib', 'backend.js'),\n path.join(cwd, 'src', 'backend.ts'),\n ].find((f) => fsNative.existsSync(f)) ?? null;\n if (entry) {\n const url = pathToFileURL(entry).href;\n load = () => this.importModule(url);\n }\n }\n } else {\n const dir = this.packageDirFor(pkg);\n let json: any = null;\n if (dir) {\n try {\n json = JSON.parse(\n fsNative.readFileSync(path.join(dir, 'package.json'), 'utf-8')\n );\n } catch {}\n }\n if (dir && json) {\n if (viteOwnsPackage) {\n // Vite resolves a bundled package with the `development` condition\n // (a workspace's `./backend` may point at src only there). It is\n // still loaded by its bare name, so it is the same module id the\n // rest of the SSR graph imports.\n entry = resolveBackendEntry(dir, json, [\n 'development',\n ...NODE_IMPORT_CONDITIONS,\n ]);\n if (entry) load = () => vite.ssrLoadModule(`${pkg}/backend`);\n } else {\n // Node caches ESM by resolved real file URL, and a bare import of\n // `<pkg>/backend` from the app resolves to this same real path β€” so\n // loading it by URL yields the instance the app's own imports get.\n entry = resolveBackendEntry(dir, json, NODE_IMPORT_CONDITIONS);\n if (entry) {\n const url = pathToFileURL(entry).href;\n load = () => this.importModule(url);\n }\n }\n }\n }\n\n if (!load) {\n if (warnIfNotFound) {\n console.warn(\n paint('magenta', `Could not find backend file of package ${logSafe(pkg)}. \n Check:\\n\n - Make sure backend.ts exists and is included in tsconfig.json\\n\n - Make sure the package name in src/package.ts matches the package name in package.json`)\n );\n }\n } else {\n // Loud, naming the package and the file, and contained: one package's\n // broken backend does not stop the others from loading.\n let loaded = false;\n await runProviderHook(\n pkg,\n `backend ${entry}`,\n async () => {\n backendProviderExports = await load();\n loaded = true;\n },\n this.booting\n );\n if (loaded) {\n for (const key of Object.keys(backendProviderExports)) {\n const providerClass = backendProviderExports[key];\n let provider;\n //always send an instance of the express server\n //TODO: do not create an instance, just save the class and instantiate it when needed\n await runProviderHook(\n pkg,\n `${key} constructor`,\n () => {\n provider = new providerClass(this.server, this);\n },\n this.booting\n );\n if (!provider) continue;\n if (isShapeProvider(provider)) {\n shapeProviders.push(provider);\n if (!Object.getOwnPropertyNames(provider).includes('shape')) {\n console.warn(\n paint('red', `${\n Object.getPrototypeOf(provider).constructor.name\n } in package ${logSafe(pkg)}\n is not properly linked to a shape. Use public shape = SomeShape.`)\n );\n }\n } else if (genericBackendProvider) {\n console.warn(\n `Package ${logSafe(pkg)} exports two generic backend providers. Only one will work`\n );\n } else {\n genericBackendProvider = provider;\n }\n }\n }\n }\n this.genericProviders.set(pkg, genericBackendProvider);\n this.shapeProviders.set(pkg, shapeProviders);\n return { backendProviderExports, shapeProviders };\n }\n\n /**\n * Plan-011 phase 2 β€” HMR re-index entry point.\n *\n * Called by the CLI orchestrator's Vite watcher whenever a `.ts`/`.tsx`\n * file inside a workspace package changes. Disposes the package's\n * existing providers (so routes, listeners, timers don't accumulate),\n * drops them from the registry, and re-runs indexPackageBackendProviders\n * to pick up the freshly-imported module.\n *\n * Dispose calls have a 5 s soft timeout. A hanging dispose logs a\n * warning and is abandoned so HMR doesn't stall the whole dev loop.\n */\n /**\n * Install the client-shell catch-all as the last ordinary layer on the\n * router stack. See utils/spaFallback.ts for why ordering has to be\n * re-asserted rather than assumed.\n */\n private installSpaFallback(): void {\n installSpaFallback(\n this.server,\n this.handleErrors(async (req, res) => {\n //make sure the frontend bundle has finished building\n // await this.waitForWebpack();\n this.render(req, res);\n })\n );\n }\n\n async onSourceChange(pkg: string): Promise<void> {\n const disposeWithTimeout = async (p: any, label: string) => {\n if (!p?.dispose) return;\n try {\n await Promise.race([\n Promise.resolve().then(() => p.dispose()),\n new Promise((_, reject) =>\n setTimeout(\n () => reject(new Error(`dispose timeout after 5s`)),\n 5000\n )\n ),\n ]);\n } catch (err: any) {\n console.warn(\n paint('yellow', `[linked] ${label} dispose failed: ${err.message}`)\n );\n }\n };\n\n const generic = this.genericProviders.get(pkg);\n if (generic) {\n await disposeWithTimeout(generic, `${pkg} generic provider`);\n this.genericProviders.delete(pkg);\n }\n\n const shapeProvs = this.shapeProviders.get(pkg) ?? [];\n for (const p of shapeProvs) {\n await disposeWithTimeout(\n p,\n `${pkg} ${Object.getPrototypeOf(p)?.constructor?.name ?? 'shape provider'}`\n );\n }\n this.shapeProviders.delete(pkg);\n\n await this.indexPackageBackendProviders(pkg, true);\n\n // Run the boot lifecycle on the FRESHLY-loaded provider so it\n // re-registers its Express routes/middleware after dispose. Without\n // this, dispose() tears the old routes off and the new instance is\n // constructed but never gets a chance to register the replacements.\n const fresh = this.genericProviders.get(pkg);\n if (fresh?.setupBeforeControllers) {\n try {\n await fresh.setupBeforeControllers();\n } catch (err: any) {\n console.warn(\n paint('yellow', \n `[linked] ${pkg} setupBeforeControllers after reload failed: ${err.message}`\n )\n );\n }\n }\n const freshShapes = this.shapeProviders.get(pkg) ?? [];\n for (const p of freshShapes) {\n if (p?.setupBeforeControllers) {\n try {\n await p.setupBeforeControllers();\n } catch (err: any) {\n console.warn(\n paint('yellow', \n `[linked] ${pkg} shape-provider setupBeforeControllers after reload failed: ${err.message}`\n )\n );\n }\n }\n }\n\n // Providers just re-registered their routes, which express can only APPEND\n // β€” i.e. behind the catch-all installed at boot. Put it back at the end so\n // those routes stay reachable. Safe here: every registration above has\n // completed, so no provider is mid-capture of its own layer indices.\n repinSpaFallback(this.server);\n }\n\n async processBackendMethodCall(request, response) {\n // The whole call runs in its own context: `this.request` in a provider is\n // this request, however many calls are in flight.\n return runWithCallContext(httpCallContext(request, response), async () => {\n this.noCache(response);\n await this.initRequest(request, response);\n let { pkg, method } = request.params;\n let { args } = JSONParser.parseObject<{ args }>(request.body, {\n shapeClasses: rpcShapeClassRevival(),\n });\n\n return this.callBackendMethod(pkg, method, args, request, response).then(\n (result) => {\n //some methods of backend providers may choose to work with request/response directly and will not return anything\n //so only if a result is returned\n if (typeof result !== 'undefined') {\n //do we convert it to JSON and send it to the frontend\n this.sendJson(response, result);\n } else {\n //in other cases, we still need to close the request and send an empty response\n if (!response.headersSent) {\n this.sendJson(response, null);\n }\n }\n }\n );\n });\n }\n\n noCache(response) {\n response.setHeader('Surrogate-Control', 'no-store');\n response.setHeader(\n 'Cache-Control',\n 'no-store, no-cache, must-revalidate, proxy-revalidate'\n );\n response.setHeader('Expires', '0');\n }\n async processAPICall(\n request,\n response,\n method: 'get' | 'post' | 'put' | 'delete'\n ) {\n return runWithCallContext(httpCallContext(request, response), async () => {\n this.noCache(response);\n await this.api.process(request, response, method);\n });\n }\n // async processQuery(request, response) {\n //\n // this.api.process(request, response);\n // }\n async processShapeMethodCall(request, response) {\n this.noCache(response);\n // console.log('process shape call');\n // response.on('finish', function() {\n // console.log('shape method call request finish');\n // });\n //\n // response.on('close', function() {\n // console.log('close');\n // });\n //\n // response.on('end', function() {\n // console.log('end');\n // });\n //\n // response.on('header', function() {\n // console.log('header');\n // console.log(response.statusCode);\n // });\n\n return runWithCallContext(httpCallContext(request, response), async () => {\n await this.initRequest(request, response);\n let { pkg, shape, method } = request.params;\n let { shapeURI, instanceNode, args } = JSONParser.parseObject<{\n shapeURI: string;\n instanceNode: { id: string } | null;\n args: any[];\n }>(request.body, { shapeClasses: rpcShapeClassRevival() });\n\n if (!shapeURI) {\n if (request.query?.shapeURI) {\n shapeURI = request.query?.shapeURI;\n } else {\n response.status(500).send({\n error: 'Invalid server call request: ' + request.originalUrl,\n });\n console.warn(\n paint('red', 'Invalid server call request: ' + request.originalUrl)\n );\n return;\n }\n }\n return this.callShapeMethod(\n pkg,\n method,\n shapeURI,\n instanceNode,\n args,\n request,\n response\n ).then((result) => {\n //we return json if something was returned or, if nothing was returned, we still close the request if the method has not accessed response itself already to send things over\n if (typeof result !== 'undefined' || !response.headersSent) {\n this.sendJson(response, result);\n }\n });\n });\n }\n\n async callShapeMethod(\n pkg: string,\n method: string,\n shapeURI: string,\n instanceNode: { id: string } | null,\n args: any[],\n request?,\n response?\n ) {\n // see callBackendMethod: outside any request a local call runs as system\n if (!request && !getCallContext()) {\n return runAsSystem(() =>\n this.callShapeMethod(pkg, method, shapeURI, instanceNode, args, request, response)\n );\n }\n //- index module providers if not done yet\n if (!this.shapeProviders.has(pkg)) {\n await this.ensurePackageBackendProviders(pkg, true);\n }\n\n let packageShapeProviders = this.shapeProviders.get(pkg);\n\n let findProviderForShape = (nodeShapeId: string) => {\n return packageShapeProviders.find((provider) => {\n //access the static shape (which is a linkedShape() / Shape class)\n //then access the SHACL NodeShape of that shape class, and its id\n return (\n isShapeProvider(provider) &&\n provider.shape?.shape?.id === nodeShapeId\n );\n });\n };\n\n let providerMethodFailed = false;\n try {\n //- find matching provider\n let shapeClass = getShapeClass(shapeURI);\n let shapeProvider: ShapeProvider = shapeClass?.shape\n ? findProviderForShape(shapeClass.shape.id)\n : undefined;\n if (!shapeProvider && shapeClass) {\n let superShapeClasses = getSuperShapesClasses(\n shapeClass as unknown as typeof Shape\n );\n for (let superShapeClass of superShapeClasses) {\n let superShapeProvider = findProviderForShape(\n superShapeClass.shape?.id\n );\n if (superShapeProvider) {\n shapeProvider = superShapeProvider;\n break;\n }\n }\n }\n // No provider for this shape (e.g. it isn't registered on this side).\n // Framework packages are kept single-instance by the cli vite-config's\n // `optimizeDeps.exclude`, so a mismatch here signals a real\n // misconfiguration. Answer 501 (via handleErrorsJson) rather than an empty\n // 200; direct backend callers get a rejected ServerCallError.\n if (!shapeProvider) {\n console.warn(\n `[LinkedServer] callShapeMethod: no provider for '${logSafe(shapeURI)}' ` +\n `(pkg '${logSafe(pkg)}', method '${logSafe(method)}').`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n\n if (shapeProvider) {\n const resolution = resolveCallable(shapeProvider, method);\n if (resolution.status !== 'missing') {\n this.assertDispatchAllowed(\n pkg,\n method,\n shapeProvider,\n resolution,\n request,\n 'shape'\n );\n }\n //NOTE: if this is a direct call from backend to backend, we won't know the request & response here because those don't get passed to the Server utility\n //if this is an issue, we need to see how we can get those back\n if (request && response) {\n //give the provider a chance to prepare for this request\n //wrap the call in a promise and wait for it, because providers MAY return a promise\n await Promise.resolve(shapeProvider.initRequest(request, response));\n if (resolution.status !== 'missing') {\n this.assertSessionForLevel(pkg, method, resolution, request);\n }\n }\n\n //see if the shapeProvider implements the called method\n if (resolution.status !== 'missing') {\n //prepare the first argument\n //we want to convert the instance node into an instance of the shape that this shapeProvider provides for\n //let's find the shape class\n if (shapeProvider.shape) {\n //instance nodes are not always sent. A shape can also call a shape provider from a static method without a shape instance.\n if (instanceNode) {\n let providerShapeClass = shapeProvider.shape;\n let instance = new (providerShapeClass as any)({\n id: instanceNode.id,\n });\n\n //always send instanceNode as first argument to static provider methods\n args.unshift(instance);\n }\n\n try {\n //call the method with the given arguments\n let result = await Promise.resolve(\n shapeProvider[method].apply(shapeProvider, args)\n );\n return result;\n } catch (e) {\n console.warn(\n `Error whilst calling ${\n Object.getPrototypeOf(shapeProvider).constructor.name\n }.${logSafe(method)}(): `,\n e\n );\n // Rethrow so the HTTP route answers with an error status (via\n // handleErrorsJson) instead of `200 null`, and direct backend\n // callers get a rejected promise.\n providerMethodFailed = true;\n throw e;\n }\n } else {\n console.warn(\n `${\n Object.getPrototypeOf(shapeProvider).constructor.name\n } does not define its own 'static shape' property. Please connect the provider to a shape.`\n );\n }\n } else {\n console.warn(\n `${\n Object.getPrototypeOf(shapeProvider).constructor.name\n } does not have a method called ${logSafe(method)}`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n }\n } catch (err) {\n if (!providerMethodFailed && !ServerCallError.is(err)) {\n console.warn(`Error whilst trying to access provider of ${logSafe(pkg)}: `, err);\n }\n throw err;\n }\n return null;\n }\n\n /**\n * Refuse a dispatch the exposure rules do not allow (see utils/rpcExposure).\n * Throws a 501 `ServerCallError`, the same answer as for a missing method.\n *\n * - reserved names: always, for HTTP and backend-to-backend calls alike;\n * - HTTP only: an internal method (in every mode), a generic call to a provider whose class sets\n * `static rpc = false`, and an undeclared method in 'enforce' mode\n * (in 'warn' mode it is logged once and runs).\n */\n private assertDispatchAllowed(\n pkg: string,\n method: string,\n provider,\n resolution: ReturnType<typeof resolveCallable>,\n request,\n route: 'generic' | 'shape'\n ) {\n const className = Object.getPrototypeOf(provider)?.constructor?.name;\n if (resolution.status === 'reserved') {\n console.warn(\n `[linked] refused call to reserved method ${logSafe(pkg)} ${className}.${logSafe(method)}` +\n (request ? '' : ' (backend-to-backend)')\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n if (!request) return;\n if (resolution.status === 'internal') {\n console.warn(\n `[linked] refused call to internal method ${logSafe(pkg)} ${className}.${logSafe(method)}`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n if (route === 'generic' && isGenericRpcDisabled(provider)) {\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n if (resolution.status === 'undeclared') {\n if (getRpcExposureMode() === 'enforce') {\n console.warn(\n `[linked] refused undeclared RPC ${logSafe(pkg)} ${className}.${logSafe(method)}`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n warnUndeclaredCall(pkg, resolution.owner, method, hasSession(request));\n }\n }\n\n /** A declared `'user'` method needs a session: 401 without one, in every mode. */\n private assertSessionForLevel(\n pkg: string,\n method: string,\n resolution: ReturnType<typeof resolveCallable>,\n request\n ) {\n if (\n resolution.status === 'callable' &&\n resolution.level === 'user' &&\n !hasSession(request)\n ) {\n throw new ServerCallError(401, 'Authentication required');\n }\n }\n\n handleErrors(fn) {\n return async function (req, res, next) {\n try {\n return await fn(req, res);\n } catch (x) {\n console.log(x);\n next(x);\n }\n };\n }\n\n handleErrorsJson(fn) {\n return async (req, res, next) => {\n try {\n return await fn(req, res);\n } catch (err) {\n // A ServerCallError (e.g. 501 for a call no provider handles) carries\n // its own status and a message that is safe to send to the client.\n if (ServerCallError.is(err)) {\n return this.sendError(res, err.status, err.message);\n }\n this.sendError(\n res,\n 500,\n 'internal server error' + (isDevelopment ? ': ' + err?.stack : ''),\n 'internal server error: ' + err?.stack\n );\n }\n };\n }\n\n sendError(res, statusCode = 500, message, logMessage?: string) {\n res?.status(statusCode);\n if (message) {\n res?.send({ error: message });\n console.warn(paint('red', logMessage || message));\n }\n }\n\n /**\n * The stylesheets a dev (Vite) page render needs, inlined into\n * `<style id=\"ssr-css\">` so the first paint is styled before Vite's client\n * injects the same CSS.\n *\n * Scoped to what the app module and the matched routes' pages import\n * statically (see utils/ssrCss `ssrCssScope`). The dev server preloads every\n * page into the module graph, so the whole graph is every page's CSS β€”\n * megabytes per request in a large app. When the scope cannot be\n * established (no routes config, a route rendered through a function, a\n * module not found) it falls back to the whole graph.\n *\n * Ids are kept in the combined graph's order, so the cascade order of what\n * remains is unchanged.\n */\n private async collectViteSsrCss(\n vite: any,\n App: unknown,\n matchedRoutes: RouteConfig[] | null,\n ): Promise<string> {\n if (!vite?.moduleGraph?.idToModuleMap) return '';\n // Note: Tailwind v4 `@theme` directives in app theme CSS files are\n // NOT processed at SSR collection time β€” the @tailwindcss/vite\n // plugin expands them at production build only. In dev mode, the\n // theme variables (β€”color-primary-*, etc.) are injected by Vite's\n // runtime AFTER client hydration, which causes a brief flash of\n // unthemed content (logos render black until ~hydration+200ms).\n // Production (vite build) is unaffected β€” the static main.css\n // contains expanded :root variables.\n let scope: Set<string> | null = null;\n const ssrGraph = vite.environments?.ssr?.moduleGraph;\n if (ssrGraph?.idToModuleMap && App && matchedRoutes) {\n const pages: unknown[] = [];\n let known = true;\n for (const route of matchedRoutes) {\n const component = await resolveRouteComponent(route);\n if (component === undefined) {\n known = false;\n break;\n }\n if (component !== null) pages.push(component);\n }\n if (known) {\n scope = ssrCssScope(ssrGraph.idToModuleMap.values(), {\n app: App,\n pages,\n });\n }\n }\n // Read only now: resolving a lazy route above can load its page, and the\n // combined graph's id map is a view built when it is read.\n const graphIds = [\n ...(vite.moduleGraph.idToModuleMap as Map<string, unknown>).keys(),\n ];\n const ids = scope ? graphIds.filter((id) => scope!.has(id)) : graphIds;\n // Only real stylesheets, once per file β€” see utils/ssrCss.\n const inlineUrls = ssrCssInlineUrls(ids, {\n publicDir: vite.config?.publicDir,\n });\n const cssChunks: string[] = [];\n for (const inlineUrl of inlineUrls) {\n try {\n const cssModule = await vite.ssrLoadModule(inlineUrl);\n if (typeof cssModule?.default === 'string') {\n cssChunks.push(cssModule.default);\n }\n } catch {/* skip */}\n }\n return cssChunks.join('\\n');\n }\n\n async render(req, res) {\n // Server-side rendering runs as the requesting user: a Server.call made\n // while rendering inherits this context rather than escalating to system.\n return runWithCallContext(httpCallContext(req, res), () =>\n this.renderPage(req, res)\n );\n }\n\n private async renderPage(req, res) {\n res.socket.on('error', (error) => {\n console.error('Fatal socket error', error);\n });\n\n //when render() is called, the request is always an 'initial page request', and the server which will return HTML (so this is a SSR request)\n //in that case we send data back to the frontend in a <script> tag.\n //We initiate that object here\n if (req['frontendData'] == null) {\n req['frontendData'] = {};\n }\n\n //if we are caching this page\n if (\n this.config.server?.cachePaths &&\n this.config.server.cachePaths.includes(req.url)\n ) {\n //if there is a cach for this path, send it\n if (this.cachedPaths.has(req.url)) {\n // console.log(req.url + ': Returning cached path');\n const html = this.cachedPaths.get(req.url);\n // res.setHeader('Content-Type', 'text/html; charset=utf-8');\n // res.setHeader('Content-Length', Buffer.byteLength(html, 'utf8').toString());\n // res.status(200).end(html);\n res.send(html);\n return;\n }\n }\n\n let didError = false;\n\n let App = this.config.server?.loadAppComponent\n ? await this.config.server.loadAppComponent()\n : null;\n\n // Vite dev CSS collection (plan-010 iteration 1 β€” gap A):\n // 1. Preload the matched route's module via ssrLoadModule so all\n // page-level dependencies (SigninLayout, CreateAccount, etc.)\n // enter Vite's moduleGraph BEFORE we collect CSS. Without this,\n // only App's eager imports are in the graph and lazy routes'\n // CSS would be missing β€” page renders unstyled until hydration.\n // 2. Once the route is matched, collect the CSS the app and that route's\n // page import (collectViteSsrCss), each loaded via `?inline` (Vite\n // returns the processed CSS as the default export).\n // 3. Inject as inline <style> in HTML head (Html.tsx).\n const vite: any = (this.config.server as any)?.vite;\n // Vite SSR module preload (plan-010 iter1 gap A):\n // Pages are loaded lazily via React.lazy β€” their modules only enter\n // Vite's moduleGraph after the lazy resolves. For SSR CSS collection\n // we need the page modules in the graph BEFORE the first render of\n // each route. The orchestrator passes a preloadPagesFn that lists\n // all page files (typically via `import.meta.glob`); we call\n // ssrLoadModule on each path once. After the first render of a\n // session everything is cached.\n const preloadPagesFn: any = (this.config.server as any)?.viteSsrPreload;\n if (vite?.ssrLoadModule && preloadPagesFn && !(this as any)._viteSsrPreloaded) {\n try {\n const pagePaths: string[] = await preloadPagesFn();\n for (const p of pagePaths) {\n try {\n await vite.ssrLoadModule(p);\n } catch {/* skip β€” page may not exist or have ssr errors */}\n }\n } catch {/* ignore */}\n (this as any)._viteSsrPreloaded = true;\n }\n\n await this.initRequest(req, res);\n let { requestLD, requestObject } = await this.getRequestData(req, res);\n\n //on the backend we need to inform the hook of the request-data value\n //on the frontend it will be read from the HTML\n // setRequestData(requestObject);\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n let stream;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n let timedout = false;\n // const timeout = setTimeout(() => {\n // stream.abort(`${req.url}: ⏱ SSR stream took too long β€” force abort`);\n // if (!res.headersSent) {\n // res.statusCode = 500;\n // res.end('SSR timed out');\n // }\n // timedout = true;\n // }, 8_000);\n\n let manifest = this.assets.manifest || {};\n let preloadScripts: string[] = [];\n let preloadStyles: string[] = [];\n let matchedRouteKey: string | null = null;\n // Null until the routes config has loaded: without it, what renders is unknown.\n let matchedRoutes: RouteConfig[] | null = null;\n // Plan-010 Vite dev mode: skip preload resolution entirely. Vite\n // handles dynamic import() at runtime β€” there are no pre-built\n // chunks to preload, and the webpack-shape fallback would pick up\n // stale bundles on disk (public/bundles/*.bundle.js from a prior\n // webpack build) and link them, breaking hydration.\n // The same decision start() made for the `__viteDev` marker. This used\n // to be re-derived from `latestManifest`, which nothing ever set, so it\n // answered \"dev\" whenever Vite was attached β€” even when start() had\n // chosen the build β€” and the page mixed built CSS with the dev preamble.\n const usingViteDev = this.viteDevServer;\n\n // Load routes config if available and extract preload chunks for the current route\n if (this.config.server?.loadRoutes) {\n try {\n const routesModule = await this.config.server.loadRoutes();\n const ROUTES: RoutesConfig =\n routesModule.ROUTES ||\n routesModule.default?.ROUTES ||\n (routesModule as RoutesConfig);\n\n // Match the current request path to a route\n let matchedRoute: RouteConfig | null = null;\n const allMatches: RouteConfig[] = [];\n for (const [key, route] of Object.entries(ROUTES)) {\n if (!route?.path) continue;\n const pathPattern = route.path\n .replace(/:\\w+\\??/g, '([^/]+)')\n .replace(/\\*/g, '.*');\n const regex = new RegExp('^' + pathPattern + '$');\n if (regex.test(req.path)) {\n // Every match, not only the first: React Router may pick a more\n // specific route than this first-match loop, and the dev CSS\n // scope must cover whichever page actually renders.\n allMatches.push(route);\n if (!matchedRoute) {\n matchedRoute = route;\n matchedRouteKey = key;\n }\n }\n }\n matchedRoutes = allMatches;\n\n // If we found a matching route with preloadChunks, resolve them to URLs (both JS and CSS).\n // Manifest format detection: Vite manifest entries are objects with .file/.css; webpack\n // manifest entries are bare strings. Try Vite shape first, fall back to webpack.\n // Skip entirely in Vite dev mode β€” no pre-built chunks exist; Vite handles dynamic\n // imports at runtime.\n if (\n !usingViteDev &&\n matchedRoute?.preloadChunks &&\n Array.isArray(matchedRoute.preloadChunks)\n ) {\n // Both lists are built on the base the entry tags use, so a release\n // served from a CDN preloads its route chunks from that release\n // rather than from this app server. See utils/routeAssets.\n const routeAssets = resolveRouteAssets(\n manifest,\n matchedRoute.preloadChunks,\n this.staticAccessURL,\n );\n preloadScripts = routeAssets.scripts;\n preloadStyles = routeAssets.styles;\n }\n } catch (err) {\n console.warn('Failed to resolve preload chunks:', err);\n }\n }\n\n // Add matched route key to request object for Html component\n req['matchedRouteKey'] = matchedRouteKey;\n\n const ssrCss = await this.collectViteSsrCss(vite, App, matchedRoutes);\n // Per request, and not enumerable: Html reads `assets.__viteSsrCss` for\n // the inline <style>, but also serialises the whole assets object into\n // `assetManifest` for the client, which never uses it. Enumerable, the\n // collected CSS β€” megabytes in a large app β€” went into every page twice.\n // A per-request copy also keeps one render's CSS out of another's.\n const assets = { ...this.assets };\n if (ssrCss) {\n Object.defineProperty(assets, '__viteSsrCss', {\n value: ssrCss,\n enumerable: false,\n });\n }\n\n stream = renderToPipeableStream(\n <React.StrictMode>\n <StaticRouter location={req.url}>\n <AppContextProvider\n assets={assets}\n requestLD={requestLD}\n requestObject={requestObject}\n preloadScripts={preloadScripts}\n preloadStyles={preloadStyles}\n expressRequest={req}\n expressResponse={res}\n >\n <App />\n </AppContextProvider>\n </StaticRouter>\n </React.StrictMode>,\n {\n // How the client entry boots β€” dev preamble, ES module, or classic\n // script. See utils/bootstrapEntry.\n ...resolveBootstrapEntry({\n viteDevServer: usingViteDev,\n mainEntryIsModule: this.mainEntryIsModule,\n mainEntry: this.assets['main.js'],\n }),\n onShellReady: function () {\n res.statusCode = didError ? 500 : 200;\n res.setHeader('Content-type', 'text/html');\n\n // Create a caching transform stream Γ  la mxstbr.com/thoughts/streaming-ssr\n if (\n this.config.server?.cachePaths &&\n this.config.server.cachePaths.includes(req.url)\n ) {\n const bufferedChunks: Buffer[] = [];\n\n const cacheStream = new Transform({\n transform(chunk, _enc, cb) {\n bufferedChunks.push(chunk); // keep a copy\n cb(null, chunk); // forward unchanged\n },\n flush: (cb) => {\n const html = Buffer.concat(bufferedChunks).toString('utf8');\n this.cachedPaths.set(req.url, html);\n if (this.config.server.cacheTimeout) {\n setTimeout(\n () => this.cachedPaths.delete(req.url),\n this.config.server.cacheTimeout\n );\n }\n clearTimeout(timeout); // rendering finished β†’ stop timer\n cb();\n },\n });\n\n // Pipe the caching stream into the real response\n cacheStream.pipe(res);\n\n // React may **only be piped once**, so pipe it to the cacheStream\n stream.pipe(cacheStream);\n } else {\n stream.pipe(res);\n }\n }.bind(this),\n onShellError(x) {\n didError = true;\n console.error(x);\n // Respond NOW. Without this the socket stays open until the 10s\n // watchdog below fires, turning every render-time crash into an\n // opaque \"SSR timed out\" with the real error buried in the log.\n clearTimeout(timeout);\n if (res.headersSent) {\n res.end();\n return;\n }\n res.statusCode = 500;\n res.setHeader('Content-type', 'text/plain');\n res.end(\n 'SSR render failed before the shell was ready:\\n\\n' +\n ((x as any)?.stack ?? (x as any)?.message ?? String(x))\n );\n },\n }\n );\n\n // Abandon and switch to client rendering if enough time passes.\n // Try lowering this to see the client recover.\n timeout = setTimeout(() => {\n stream.abort('⏱ SSR stream took too long β€” force abort');\n if (!res.headersSent) {\n res.statusCode = 500;\n res.end('SSR timed out');\n }\n }, 10_000);\n\n res.on('close', () => {\n clearTimeout(timeout); // if you're using a safety timeout\n });\n }\n\n //If we ever need to use multiple webpack entry-points and different bundle names, then uncomment this\n /*getWebpackAssets()\n\t{\n\t\t// const { devMiddleware } = res.locals.webpack;\n\t\t// const outputFileSystem = devMiddleware.outputFileSystem;\n\t\t// const jsonWebpackStats = devMiddleware.stats.toJson();\n\t\t// const { assetsByChunkName, outputPath } = jsonWebpackStats;\n\t\t//\n\t\t// let normalizedAssets = normalizeAssets(assetsByChunkName.main);\n\t\t// let cssAssets = normalizedAssets\n\t\t// .filter((path) => path.endsWith(\".css\"))\n\t\t// .map((filePath) => outputFileSystem.readFileSync(path.join(outputPath, filePath)))\n\t\t// .join(\"\\n\");\n\t\t//\n\t\t// let jsAssets = normalizeAssets(assetsByChunkName.main)\n\t\t// .filter((path) => path.endsWith(\".js\"))\n\t\t// .map((path) => `<script src=\"${path}\"></script>`)\n\t\t// .join(\"\\n\")}\n\t}*/\n\n sendJson(res, obj) {\n let jsonObject = JSONWriter.toJsObject(obj);\n res.json(jsonObject);\n }\n\n async initRequest(request, response) {\n // initialise the request for all providers, one after the other (order\n // matters: later providers may read what earlier ones put on the request).\n // A provider that throws is logged by package name and skipped.\n for (const [pkg, backendProvider] of this.genericProviders.entries()) {\n if (!backendProvider || typeof backendProvider.initRequest !== 'function') {\n continue;\n }\n await runProviderHook(pkg, 'initRequest', () =>\n backendProvider.initRequest(request, response)\n );\n }\n }\n\n async getRequestData(\n request,\n response\n ): Promise<{ requestLD: string; requestObject: string }> {\n // Providers return plain JSON data via supplyDataForRequest.\n // requestLD is kept as empty string for now; SSR data seeding will\n // inject query results instead of graph data.\n // A provider that throws (synchronously or not) is logged by package\n // name; the page still renders with the other providers' data.\n let requestData: Record<string, any> = {};\n await Promise.all(\n [...this.genericProviders.entries()].map(([pkg, backendProvider]) => {\n if (\n !backendProvider ||\n typeof backendProvider.supplyDataForRequest !== 'function'\n ) {\n return;\n }\n return runProviderHook(pkg, 'supplyDataForRequest', () =>\n backendProvider.supplyDataForRequest(request, response, requestData)\n );\n })\n );\n\n let requestLD = '';\n let requestObject = JSONWriter.stringify(request['frontendData']);\n return { requestLD, requestObject };\n }\n\n async callBackendMethod(\n pkg: string,\n method: string,\n args: any[],\n request?,\n response?\n ) {\n // A backend-to-backend call outside any request runs as system. Inside a\n // request (SSR, a provider calling another) it inherits that request.\n if (!request && !getCallContext()) {\n return runAsSystem(() =>\n this.callBackendMethod(pkg, method, args, request, response)\n );\n }\n if (!this.genericProviders.has(pkg)) {\n await this.ensurePackageBackendProviders(pkg, true);\n }\n\n //retrieve the indexed provider class and create a new instance for this request\n let genericBackendProvider = this.genericProviders.get(pkg);\n\n let result;\n if (!genericBackendProvider) {\n console.warn(\n `${paint('magenta', \n pkg\n )} does not have a generic backend provider. If you can edit this package, make sure 'backend.ts' is included in 'tsconfig.json' and that it exports a provider.`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n //test if there is a matching method in the backend provider, and whether it may be called\n const resolution = resolveCallable(genericBackendProvider, method);\n if (resolution.status === 'missing') {\n console.warn(\n `Generic provider '${\n Object.getPrototypeOf(genericBackendProvider).constructor.name\n }' of ${logSafe(pkg)} does not have a method called ${logSafe(method)}`\n );\n throw new ServerCallError(501, `No provider for ${logSafe(pkg)}/${logSafe(method)}`);\n }\n this.assertDispatchAllowed(\n pkg,\n method,\n genericBackendProvider,\n resolution,\n request,\n 'generic'\n );\n\n try {\n //TODO: remove init request.\n //TODO: refactor this.request and this.response to a request parameter\n //NOTE: if this is a direct call from backend to backend, we won't know the request & response here because those don't get passed to the Server utility\n //if this is an issue, we need to see how we can get those back\n if (request && response) {\n //initialise the request for this specific provider\n //wrap the call in a promise and wait for it, because providers MAY return a promise\n await Promise.resolve(\n genericBackendProvider.initRequest(request, response)\n );\n this.assertSessionForLevel(pkg, method, resolution, request);\n }\n // args.push(request);\n // args.push(response);\n\n //call the method with the given arguments and return the result as json\n result = await Promise.resolve(\n genericBackendProvider[method].apply(genericBackendProvider, args)\n );\n } catch (e) {\n if (ServerCallError.is(e) && e.status === 401) throw e;\n console.warn(\n `Error whilst calling ${logSafe(method)}() in provider ${\n Object.getPrototypeOf(genericBackendProvider).constructor.name\n } of package ${logSafe(pkg)}:\\n`,\n e\n );\n\n // error logging\n LinkedErrorLogging.log(e);\n // Rethrow so the HTTP route answers with an error status instead of `200 null`.\n throw e;\n }\n return result;\n }\n}\n\n/**\n * Register the RPC routes (`/call/...`) and the `LincdAPI` routes (`POST /api/...`)\n * of `linkedServer` on an express app. `LincdAPI` answers POST only: its GET\n * routes (`/api/all-shapes`, `/api/shape-details`) served the in-memory shape\n * index, which is gone, so no `GET /api/...` is mounted and those paths are left\n * to the app's own routes.\n *\n * `LinkedServer.start()` calls this; tests call it on a bare express app so they\n * drive exactly the routes a running server has.\n */\nexport function registerCallRoutes(\n app: { post: Function; get: Function },\n linkedServer: LinkedServer\n): void {\n const server: any = linkedServer;\n // Scoped-package variants (@scope/pkg). Register BEFORE the unscoped\n // routes β€” Express `:pkg` won't consume slashes, so a call to\n // `/call/@_linked/auth/signinDev` would otherwise fall through to the\n // 3-segment `:pkg/:shape/:method` route and be misinterpreted as a\n // shape-method call (pkg=`@_linked`, shape=`auth`). These handlers\n // recognise the `@scope/pkg` prefix and rebuild the full package name\n // before dispatching to the same handler used for unscoped packages.\n app.post(\n '/call/@:scope/:pkg/:method',\n server.handleErrorsJson(async (req, res) => {\n req.params.pkg = `@${req.params.scope}/${req.params.pkg}`;\n return server.processBackendMethodCall(req, res);\n })\n );\n app.post(\n '/call/@:scope/:pkg/:shape/:method',\n server.handleErrorsJson(async (req, res) => {\n req.params.pkg = `@${req.params.scope}/${req.params.pkg}`;\n return server.processShapeMethodCall(req, res);\n })\n );\n app.post(\n '/call/:pkg/:method',\n server.handleErrorsJson(async (req, res) =>\n server.processBackendMethodCall(req, res)\n )\n );\n app.post(\n '/call/:pkg/:shape/:method',\n server.handleErrorsJson(async (req, res) =>\n server.processShapeMethodCall(req, res)\n )\n );\n app.post(\n '/api/:method/:action?',\n server.handleErrorsJson(async (req, res) =>\n server.processAPICall(req, res, 'post')\n )\n );\n}\n"]}