@pithyjs/ssr 0.0.0-stage → 0.1.2-beta.10

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.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/bin/pithy-ssg.mjs +23 -0
  4. package/dist/browser.d.ts +38 -0
  5. package/dist/browser.d.ts.map +1 -0
  6. package/dist/browser.js +40 -0
  7. package/dist/browser.js.map +1 -0
  8. package/dist/build/cli-args.d.ts +104 -0
  9. package/dist/build/cli-args.d.ts.map +1 -0
  10. package/dist/build/cli-args.js +88 -0
  11. package/dist/build/cli-args.js.map +1 -0
  12. package/dist/build/cli-exit.d.ts +95 -0
  13. package/dist/build/cli-exit.d.ts.map +1 -0
  14. package/dist/build/cli-exit.js +237 -0
  15. package/dist/build/cli-exit.js.map +1 -0
  16. package/dist/build/cli.d.ts +11 -0
  17. package/dist/build/cli.d.ts.map +1 -0
  18. package/dist/build/cli.js +93 -0
  19. package/dist/build/cli.js.map +1 -0
  20. package/dist/build/collect-css.d.ts +168 -0
  21. package/dist/build/collect-css.d.ts.map +1 -0
  22. package/dist/build/collect-css.js +479 -0
  23. package/dist/build/collect-css.js.map +1 -0
  24. package/dist/build/css-live-props.d.ts +89 -0
  25. package/dist/build/css-live-props.d.ts.map +1 -0
  26. package/dist/build/css-live-props.js +704 -0
  27. package/dist/build/css-live-props.js.map +1 -0
  28. package/dist/build/css-purge.d.ts +153 -0
  29. package/dist/build/css-purge.d.ts.map +1 -0
  30. package/dist/build/css-purge.js +463 -0
  31. package/dist/build/css-purge.js.map +1 -0
  32. package/dist/build/index.d.ts +24 -0
  33. package/dist/build/index.d.ts.map +1 -0
  34. package/dist/build/index.js +31 -0
  35. package/dist/build/index.js.map +1 -0
  36. package/dist/build/not-found.d.ts +94 -0
  37. package/dist/build/not-found.d.ts.map +1 -0
  38. package/dist/build/not-found.js +99 -0
  39. package/dist/build/not-found.js.map +1 -0
  40. package/dist/build/relative-links.d.ts +31 -0
  41. package/dist/build/relative-links.d.ts.map +1 -0
  42. package/dist/build/relative-links.js +79 -0
  43. package/dist/build/relative-links.js.map +1 -0
  44. package/dist/build/shell-head.d.ts +68 -0
  45. package/dist/build/shell-head.d.ts.map +1 -0
  46. package/dist/build/shell-head.js +236 -0
  47. package/dist/build/shell-head.js.map +1 -0
  48. package/dist/build/sprite-ssg.d.ts +61 -0
  49. package/dist/build/sprite-ssg.d.ts.map +1 -0
  50. package/dist/build/sprite-ssg.js +114 -0
  51. package/dist/build/sprite-ssg.js.map +1 -0
  52. package/dist/build/ssg.d.ts +117 -0
  53. package/dist/build/ssg.d.ts.map +1 -0
  54. package/dist/build/ssg.js +404 -0
  55. package/dist/build/ssg.js.map +1 -0
  56. package/dist/build/vite-ssg.d.ts +396 -0
  57. package/dist/build/vite-ssg.d.ts.map +1 -0
  58. package/dist/build/vite-ssg.js +1130 -0
  59. package/dist/build/vite-ssg.js.map +1 -0
  60. package/dist/client/bootstrap.d.ts +51 -0
  61. package/dist/client/bootstrap.d.ts.map +1 -0
  62. package/dist/client/bootstrap.js +121 -0
  63. package/dist/client/bootstrap.js.map +1 -0
  64. package/dist/client/hydrate.d.ts +60 -0
  65. package/dist/client/hydrate.d.ts.map +1 -0
  66. package/dist/client/hydrate.js +168 -0
  67. package/dist/client/hydrate.js.map +1 -0
  68. package/dist/client/index.d.ts +21 -0
  69. package/dist/client/index.d.ts.map +1 -0
  70. package/dist/client/index.js +16 -0
  71. package/dist/client/index.js.map +1 -0
  72. package/dist/index.d.ts +32 -0
  73. package/dist/index.d.ts.map +1 -0
  74. package/dist/index.js +31 -0
  75. package/dist/index.js.map +1 -0
  76. package/dist/server/app.d.ts +166 -0
  77. package/dist/server/app.d.ts.map +1 -0
  78. package/dist/server/app.js +200 -0
  79. package/dist/server/app.js.map +1 -0
  80. package/dist/server/context.d.ts +238 -0
  81. package/dist/server/context.d.ts.map +1 -0
  82. package/dist/server/context.js +371 -0
  83. package/dist/server/context.js.map +1 -0
  84. package/dist/server/environment.d.ts +88 -0
  85. package/dist/server/environment.d.ts.map +1 -0
  86. package/dist/server/environment.js +261 -0
  87. package/dist/server/environment.js.map +1 -0
  88. package/dist/server/html-shell.d.ts +41 -0
  89. package/dist/server/html-shell.d.ts.map +1 -0
  90. package/dist/server/html-shell.js +208 -0
  91. package/dist/server/html-shell.js.map +1 -0
  92. package/dist/server/index.d.ts +26 -0
  93. package/dist/server/index.d.ts.map +1 -0
  94. package/dist/server/index.js +37 -0
  95. package/dist/server/index.js.map +1 -0
  96. package/dist/server/layout-taint.d.ts +62 -0
  97. package/dist/server/layout-taint.d.ts.map +1 -0
  98. package/dist/server/layout-taint.js +313 -0
  99. package/dist/server/layout-taint.js.map +1 -0
  100. package/dist/server/loaders.d.ts +194 -0
  101. package/dist/server/loaders.d.ts.map +1 -0
  102. package/dist/server/loaders.js +479 -0
  103. package/dist/server/loaders.js.map +1 -0
  104. package/dist/server/render-route.d.ts +102 -0
  105. package/dist/server/render-route.d.ts.map +1 -0
  106. package/dist/server/render-route.js +182 -0
  107. package/dist/server/render-route.js.map +1 -0
  108. package/dist/server/render.d.ts +80 -0
  109. package/dist/server/render.d.ts.map +1 -0
  110. package/dist/server/render.js +256 -0
  111. package/dist/server/render.js.map +1 -0
  112. package/dist/server/router-adapter.d.ts +134 -0
  113. package/dist/server/router-adapter.d.ts.map +1 -0
  114. package/dist/server/router-adapter.js +225 -0
  115. package/dist/server/router-adapter.js.map +1 -0
  116. package/dist/server/serialization.d.ts +54 -0
  117. package/dist/server/serialization.d.ts.map +1 -0
  118. package/dist/server/serialization.js +287 -0
  119. package/dist/server/serialization.js.map +1 -0
  120. package/dist/server/ssr-worker.d.ts +18 -0
  121. package/dist/server/ssr-worker.d.ts.map +1 -0
  122. package/dist/server/ssr-worker.js +118 -0
  123. package/dist/server/ssr-worker.js.map +1 -0
  124. package/dist/server/utils.d.ts +11 -0
  125. package/dist/server/utils.d.ts.map +1 -0
  126. package/dist/server/utils.js +14 -0
  127. package/dist/server/utils.js.map +1 -0
  128. package/dist/server/worker-pool.d.ts +153 -0
  129. package/dist/server/worker-pool.d.ts.map +1 -0
  130. package/dist/server/worker-pool.js +451 -0
  131. package/dist/server/worker-pool.js.map +1 -0
  132. package/dist/server/worker-protocol.d.ts +61 -0
  133. package/dist/server/worker-protocol.d.ts.map +1 -0
  134. package/dist/server/worker-protocol.js +9 -0
  135. package/dist/server/worker-protocol.js.map +1 -0
  136. package/dist/shared/css-purge.d.ts +71 -0
  137. package/dist/shared/css-purge.d.ts.map +1 -0
  138. package/dist/shared/css-purge.js +177 -0
  139. package/dist/shared/css-purge.js.map +1 -0
  140. package/dist/shared/entry-path.d.ts +41 -0
  141. package/dist/shared/entry-path.d.ts.map +1 -0
  142. package/dist/shared/entry-path.js +87 -0
  143. package/dist/shared/entry-path.js.map +1 -0
  144. package/dist/shared/head.d.ts +87 -0
  145. package/dist/shared/head.d.ts.map +1 -0
  146. package/dist/shared/head.js +412 -0
  147. package/dist/shared/head.js.map +1 -0
  148. package/dist/shared/shell-helpers.d.ts +69 -0
  149. package/dist/shared/shell-helpers.d.ts.map +1 -0
  150. package/dist/shared/shell-helpers.js +160 -0
  151. package/dist/shared/shell-helpers.js.map +1 -0
  152. package/dist/shared/types.d.ts +332 -0
  153. package/dist/shared/types.d.ts.map +1 -0
  154. package/dist/shared/types.js +27 -0
  155. package/dist/shared/types.js.map +1 -0
  156. package/package.json +84 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-pool.js","sourceRoot":"","sources":["../../src/server/worker-pool.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EAAE,MAAM,EAAsB,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,IAAI,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACnD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AAG,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC;QACzE,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC;QACxB,IAAI,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,CAAC;QAEjC,iFAAiF;QACjF,IAAI,CAAC,kBAAkB,CAAC,KAAK,EAAE,CAAC;QAChC,IAAI,CAAC,qBAAqB,CAAC,KAAK,EAAE,CAAC;QACnC,IAAI,CAAC,kBAAkB,CAAC,KAAK,EAAE,CAAC;IAClC,CAAC;IAED,2IAA2I;IAC3I;;;;OAIG;IACH,QAAQ;QAMN,OAAO;YACL,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM;YACjC,gBAAgB,EAAE,IAAI,CAAC,gBAAgB,CAAC,MAAM;YAC9C,eAAe,EAAE,IAAI,CAAC,eAAe,CAAC,IAAI;YAC1C,cAAc,EAAE,IAAI,CAAC,YAAY,CAAC,MAAM;SACzC,CAAC;IACJ,CAAC;CACF;AAED,kLAAkL;AAClL;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CACjC,OAA8B;IAE9B,OAAO,IAAI,aAAa,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server.worker-pool\",\n \"title\": \"SSR Worker Pool for Concurrent Rendering\",\n \"category\": \"runtime\"\n}\n*/\n\n/**\n * @pithyjs/ssr - Worker Pool for Concurrent SSR\n *\n * Provides a worker pool for concurrent server-side rendering.\n * Each worker has its own isolated DOM environment (via happy-dom),\n * enabling true parallel SSR without global state conflicts.\n *\n * ## Why Worker Threads?\n *\n * The DOM environment (document, window, etc.) uses global variables that\n * cannot be isolated per-request in a single thread. AsyncLocalStorage only\n * isolates JavaScript state, not the DOM globals.\n *\n * Worker threads provide true isolation - each worker has its own global scope,\n * so each can have its own DOM environment running concurrently.\n *\n * ## Usage\n *\n * ```typescript\n * import { createSSRWorkerPool } from '@pithyjs/ssr/server';\n *\n * // Create a pool (defaults to os.availableParallelism() workers)\n * const pool = createSSRWorkerPool();\n *\n * // Render requests concurrently\n * app.get('*', async (req, res) => {\n * const result = await pool.render({\n * url: req.url,\n * componentPath: './dist/App.js',\n * context: { user: req.user },\n * });\n * res.send(result.html);\n * });\n *\n * // Shutdown when done\n * await pool.shutdown();\n * ```\n */\n\nimport { Worker, type WorkerOptions } from 'worker_threads';\nimport { availableParallelism } from 'os';\nimport { fileURLToPath, pathToFileURL } from 'url';\nimport { dirname, join, isAbsolute, resolve as resolvePath } from 'path';\nimport type { RenderRouteResult } from './render-route.js';\nimport type {\n WorkerRenderOptions,\n WorkerRequest,\n WorkerResponse,\n} from './worker-protocol.js';\n\n// Re-export for public API (consumed via @pithyjs/ssr/server)\nexport type { WorkerRenderOptions } from './worker-protocol.js';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Extended WorkerOptions that includes the 'type' field for ESM workers.\n * Note: 'type: module' requires Node.js 18.18+ / 20.8+\n * The @types/node package may not include this field yet.\n */\ninterface ESMWorkerOptions extends WorkerOptions {\n type?: 'module' | 'commonjs';\n}\n\n/**\n * Options for creating an SSR worker pool\n */\nexport interface SSRWorkerPoolOptions {\n /** Number of workers in the pool (default: os.availableParallelism()) */\n poolSize?: number;\n\n /** Maximum time to wait for a worker to complete a render (ms, default: 30000) */\n renderTimeout?: number;\n\n /** Maximum number of renders before a worker is recycled (default: 1000) */\n maxRendersPerWorker?: number;\n}\n\n/**\n * Pending render request\n */\ninterface PendingRender {\n resolve: (result: RenderRouteResult) => void;\n reject: (error: Error) => void;\n timeout: NodeJS.Timeout;\n}\n\n// =============================================================================\n// Node.js Version Check\n// =============================================================================\n\n/**\n * Check if the current Node.js version supports ESM workers.\n * ESM workers require Node.js 18.18.0+ or 20.8.0+.\n */\nfunction checkNodeVersion(): void {\n const version = process.versions.node;\n const [major, minor] = version.split('.').map(Number);\n\n const isSupported =\n (major === 18 && minor >= 18) || (major === 20 && minor >= 8) || major > 20;\n\n if (!isSupported) {\n throw new Error(\n `SSRWorkerPool requires Node.js 18.18.0+ or 20.8.0+ for ESM worker support. ` +\n `Current version: ${version}. Please upgrade Node.js.`\n );\n }\n}\n\n// =============================================================================\n// Worker Pool Implementation\n// =============================================================================\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.worker-pool\",\"name\":\"SSRWorkerPool\",\"stability\":\"experimental\",\"signature\":\"class SSRWorkerPool\"} */\n/**\n * Worker pool for concurrent SSR rendering\n *\n * Each worker runs in isolation with its own DOM environment,\n * enabling true parallel rendering without global state conflicts.\n */\nexport class SSRWorkerPool {\n private workers: Worker[] = [];\n private availableWorkers: Worker[] = [];\n private pendingRequests: Map<number, PendingRender> = new Map();\n /** Maps each worker to the set of request IDs it's currently processing */\n private workerPendingRequests: Map<Worker, Set<number>> = new Map();\n private requestQueue: Array<{\n options: WorkerRenderOptions;\n resolve: (result: RenderRouteResult) => void;\n reject: (error: Error) => void;\n }> = [];\n private requestIdCounter = 0;\n private workerRenderCounts: Map<Worker, number> = new Map();\n private isShutdown = false;\n /** Tracks workers being intentionally terminated to prevent double-replacement */\n private terminatingWorkers: Set<Worker> = new Set();\n\n private readonly poolSize: number;\n private readonly renderTimeout: number;\n private readonly maxRendersPerWorker: number;\n\n constructor(options: SSRWorkerPoolOptions = {}) {\n // Verify Node.js version supports ESM workers before initialization\n checkNodeVersion();\n\n const poolSize = options.poolSize ?? availableParallelism();\n if (!Number.isInteger(poolSize) || poolSize < 1) {\n throw new Error(\n `Invalid poolSize \"${poolSize}\". Expected an integer >= 1.`\n );\n }\n\n this.poolSize = poolSize;\n this.renderTimeout = options.renderTimeout ?? 30000;\n this.maxRendersPerWorker = options.maxRendersPerWorker ?? 1000;\n\n this.initializeWorkers();\n }\n\n /**\n * Initialize the worker pool\n */\n private initializeWorkers(): void {\n const workerPath = join(\n dirname(fileURLToPath(import.meta.url)),\n 'ssr-worker.js'\n );\n\n for (let i = 0; i < this.poolSize; i++) {\n this.createWorker(workerPath);\n }\n }\n\n /**\n * Create a new worker\n */\n private createWorker(workerPath: string): Worker {\n // Use file URL and type: 'module' for ESM compatibility\n const workerUrl = pathToFileURL(workerPath);\n const workerOptions: ESMWorkerOptions = { type: 'module' };\n const worker = new Worker(workerUrl, workerOptions);\n\n worker.on('message', (response: WorkerResponse) => {\n this.handleWorkerResponse(worker, response);\n });\n\n worker.on('error', error => {\n console.error('[SSR Worker Pool] Worker error:', error);\n this.handleWorkerError(worker, error);\n });\n\n worker.on('exit', code => {\n // Skip if worker is being intentionally terminated (recycleWorker/shutdown)\n // to prevent double-replacement that could grow pool beyond poolSize\n if (this.terminatingWorkers.has(worker)) {\n this.terminatingWorkers.delete(worker);\n return;\n }\n\n // Replace any worker that exits unexpectedly (regardless of exit code)\n // to prevent the pool from silently shrinking\n if (!this.isShutdown) {\n if (code !== 0) {\n console.warn(\n `[SSR Worker Pool] Worker exited with code ${code}, replacing...`\n );\n } else {\n console.warn(\n '[SSR Worker Pool] Worker exited unexpectedly with code 0, replacing...'\n );\n }\n // Reject any in-flight requests for this worker before replacing\n this.rejectWorkerPendingRequests(\n worker,\n new Error(`Worker exited unexpectedly with code ${code}`)\n );\n this.replaceWorker(worker, workerPath);\n }\n });\n\n this.workers.push(worker);\n this.availableWorkers.push(worker);\n this.workerRenderCounts.set(worker, 0);\n this.workerPendingRequests.set(worker, new Set());\n\n return worker;\n }\n\n /**\n * Replace a failed worker\n */\n private replaceWorker(oldWorker: Worker, workerPath: string): void {\n const index = this.workers.indexOf(oldWorker);\n if (index !== -1) {\n this.workers.splice(index, 1);\n }\n\n const availableIndex = this.availableWorkers.indexOf(oldWorker);\n if (availableIndex !== -1) {\n this.availableWorkers.splice(availableIndex, 1);\n }\n\n this.workerRenderCounts.delete(oldWorker);\n this.workerPendingRequests.delete(oldWorker);\n\n if (!this.isShutdown) {\n this.createWorker(workerPath);\n this.processQueue();\n }\n }\n\n /**\n * Handle a response from a worker\n */\n private handleWorkerResponse(worker: Worker, response: WorkerResponse): void {\n const pending = this.pendingRequests.get(response.id);\n if (!pending) return;\n\n clearTimeout(pending.timeout);\n this.pendingRequests.delete(response.id);\n\n // Remove request from worker's pending set\n this.workerPendingRequests.get(worker)?.delete(response.id);\n\n // Guard: Don't recycle or return worker to pool during shutdown\n // to prevent race conditions where workers are re-dispatched after shutdown began\n if (!this.isShutdown) {\n // Update render count and check if worker needs recycling\n const renderCount = (this.workerRenderCounts.get(worker) ?? 0) + 1;\n this.workerRenderCounts.set(worker, renderCount);\n\n if (renderCount >= this.maxRendersPerWorker) {\n this.recycleWorker(worker);\n } else {\n this.availableWorkers.push(worker);\n this.processQueue();\n }\n }\n\n // Always resolve/reject the pending request\n if (response.type === 'error') {\n pending.reject(new Error(response.error ?? 'Unknown worker error'));\n } else if (response.result) {\n pending.resolve(response.result);\n } else {\n pending.reject(new Error('Invalid worker response'));\n }\n }\n\n /**\n * Handle a worker error\n */\n private handleWorkerError(worker: Worker, error: Error): void {\n // Reject pending requests that belong to this specific worker\n this.rejectWorkerPendingRequests(worker, error);\n\n // Recycle the failed worker\n this.recycleWorker(worker);\n }\n\n /**\n * Recycle a worker that has reached its render limit or encountered an error\n */\n private recycleWorker(worker: Worker): void {\n const workerPath = join(\n dirname(fileURLToPath(import.meta.url)),\n 'ssr-worker.js'\n );\n\n // Remove from availableWorkers immediately to prevent reuse\n const availableIndex = this.availableWorkers.indexOf(worker);\n if (availableIndex !== -1) {\n this.availableWorkers.splice(availableIndex, 1);\n }\n\n // Mark as intentionally terminating to prevent exit handler from also replacing\n this.terminatingWorkers.add(worker);\n\n worker\n .terminate()\n .then(() => {\n this.cleanupWorker(worker);\n\n if (!this.isShutdown) {\n this.createWorker(workerPath);\n this.processQueue();\n }\n })\n .catch(err => {\n // Handle terminate() failure - still clean up and replace the worker\n console.error('[SSR Worker Pool] Worker termination failed:', err);\n this.cleanupWorker(worker);\n\n if (!this.isShutdown) {\n this.createWorker(workerPath);\n this.processQueue();\n }\n });\n }\n\n /**\n * Reject all pending requests for a specific worker\n */\n private rejectWorkerPendingRequests(worker: Worker, error: Error): void {\n const workerRequests = this.workerPendingRequests.get(worker);\n if (workerRequests) {\n for (const id of workerRequests) {\n const pending = this.pendingRequests.get(id);\n if (pending) {\n clearTimeout(pending.timeout);\n pending.reject(error);\n this.pendingRequests.delete(id);\n }\n }\n workerRequests.clear();\n }\n }\n\n /**\n * Clean up worker tracking data\n */\n private cleanupWorker(worker: Worker): void {\n const index = this.workers.indexOf(worker);\n if (index !== -1) {\n this.workers.splice(index, 1);\n }\n this.workerRenderCounts.delete(worker);\n this.workerPendingRequests.delete(worker);\n }\n\n /**\n * Process queued render requests\n */\n private processQueue(): void {\n while (this.requestQueue.length > 0 && this.availableWorkers.length > 0) {\n const request = this.requestQueue.shift();\n const worker = this.availableWorkers.shift();\n\n if (request && worker) {\n this.executeRender(\n worker,\n request.options,\n request.resolve,\n request.reject\n );\n }\n }\n }\n\n /**\n * Execute a render on a specific worker\n */\n private executeRender(\n worker: Worker,\n options: WorkerRenderOptions,\n resolve: (result: RenderRouteResult) => void,\n reject: (error: Error) => void\n ): void {\n const requestId = ++this.requestIdCounter;\n\n const timeout = setTimeout(() => {\n this.pendingRequests.delete(requestId);\n this.workerPendingRequests.get(worker)?.delete(requestId);\n reject(new Error(`SSR render timeout after ${this.renderTimeout}ms`));\n\n // Worker might be stuck, recycle it\n this.recycleWorker(worker);\n }, this.renderTimeout);\n\n this.pendingRequests.set(requestId, { resolve, reject, timeout });\n\n // Track which worker owns this request\n this.workerPendingRequests.get(worker)?.add(requestId);\n\n // Resolve component path to file:// URL for worker-side import\n // Both relative and absolute paths need conversion (Windows absolute paths like C:\\... are not valid ESM specifiers)\n let resolvedPath = options.componentPath;\n if (!options.componentPath.startsWith('file://')) {\n const absolutePath = isAbsolute(options.componentPath)\n ? options.componentPath\n : resolvePath(process.cwd(), options.componentPath);\n resolvedPath = pathToFileURL(absolutePath).href;\n }\n\n // Resolve route manifest path the same way\n let resolvedManifestPath = options.routeManifestPath;\n if (resolvedManifestPath && !resolvedManifestPath.startsWith('file://')) {\n const absoluteManifest = isAbsolute(resolvedManifestPath)\n ? resolvedManifestPath\n : resolvePath(process.cwd(), resolvedManifestPath);\n resolvedManifestPath = pathToFileURL(absoluteManifest).href;\n }\n\n const request: WorkerRequest = {\n id: requestId,\n type: 'render',\n options: {\n ...options,\n componentPath: resolvedPath,\n routeManifestPath: resolvedManifestPath,\n },\n };\n\n try {\n worker.postMessage(request);\n } catch (err) {\n // postMessage can throw synchronously (e.g., DataCloneError for non-serializable context)\n clearTimeout(timeout);\n this.pendingRequests.delete(requestId);\n this.workerPendingRequests.get(worker)?.delete(requestId);\n this.availableWorkers.push(worker);\n this.processQueue(); // Process any queued requests with the returned worker\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n }\n\n /** @codexApi {\"parent\":\"pithy.ssr.server.worker-pool\",\"name\":\"render\",\"stability\":\"experimental\",\"signature\":\"(options: WorkerRenderOptions) => Promise<RenderRouteResult>\"} */\n /**\n * Render a component using the worker pool\n *\n * When `routeManifestPath` is provided, the worker uses `renderRoute()` for\n * full pipeline rendering (route matching, loaders, head merging). Without it,\n * falls back to `renderToString()` for simple component rendering.\n *\n * @param options - Render options including URL and component path\n * @returns Promise resolving to the render result (with route metadata when using renderRoute)\n *\n * @example\n * ```typescript\n * // Full pipeline with route matching + loaders\n * const result = await pool.render({\n * url: '/dashboard',\n * componentPath: './dist/App.js',\n * routeManifestPath: './dist/route-manifest.js',\n * context: { user: currentUser },\n * });\n *\n * // Simple render (no route matching)\n * const result = await pool.render({\n * url: '/page',\n * componentPath: './dist/App.js',\n * });\n * ```\n */\n render(options: WorkerRenderOptions): Promise<RenderRouteResult> {\n if (this.isShutdown) {\n return Promise.reject(new Error('Worker pool is shutdown'));\n }\n\n return new Promise((resolve, reject) => {\n const worker = this.availableWorkers.shift();\n\n if (worker) {\n this.executeRender(worker, options, resolve, reject);\n } else {\n // Queue the request\n this.requestQueue.push({ options, resolve, reject });\n }\n });\n }\n\n /** @codexApi {\"parent\":\"pithy.ssr.server.worker-pool\",\"name\":\"shutdown\",\"stability\":\"experimental\",\"signature\":\"() => Promise<void>\"} */\n /**\n * Shutdown the worker pool\n *\n * Terminates all workers and rejects any pending requests.\n *\n * @example\n * ```typescript\n * await pool.shutdown();\n * ```\n */\n async shutdown(): Promise<void> {\n this.isShutdown = true;\n\n // Reject all pending requests\n for (const [, pending] of this.pendingRequests) {\n clearTimeout(pending.timeout);\n pending.reject(new Error('Worker pool shutdown'));\n }\n this.pendingRequests.clear();\n\n // Reject all queued requests\n for (const request of this.requestQueue) {\n request.reject(new Error('Worker pool shutdown'));\n }\n this.requestQueue.length = 0;\n\n // Mark all workers as terminating to prevent exit handler from replacing\n for (const worker of this.workers) {\n this.terminatingWorkers.add(worker);\n }\n\n // Terminate all workers (use allSettled to ensure cleanup runs even if some fail)\n await Promise.allSettled(this.workers.map(worker => worker.terminate()));\n this.workers.length = 0;\n this.availableWorkers.length = 0;\n\n // Clear per-worker tracking maps to avoid retaining terminated worker references\n this.workerRenderCounts.clear();\n this.workerPendingRequests.clear();\n this.terminatingWorkers.clear();\n }\n\n /** @codexApi {\"parent\":\"pithy.ssr.server.worker-pool\",\"name\":\"getStats\",\"stability\":\"experimental\",\"signature\":\"() => WorkerPoolStats\"} */\n /**\n * Get current pool statistics\n *\n * @returns Pool statistics including worker counts and queue length\n */\n getStats(): {\n totalWorkers: number;\n availableWorkers: number;\n pendingRequests: number;\n queuedRequests: number;\n } {\n return {\n totalWorkers: this.workers.length,\n availableWorkers: this.availableWorkers.length,\n pendingRequests: this.pendingRequests.size,\n queuedRequests: this.requestQueue.length,\n };\n }\n}\n\n/** @codexApi {\"parent\":\"pithy.ssr.server.worker-pool\",\"name\":\"createSSRWorkerPool\",\"stability\":\"experimental\",\"signature\":\"(options?: SSRWorkerPoolOptions) => SSRWorkerPool\"} */\n/**\n * Create an SSR worker pool\n *\n * @param options - Pool configuration options\n * @returns A new SSR worker pool instance\n *\n * @example\n * ```typescript\n * // Uses os.availableParallelism() workers by default\n * const pool = createSSRWorkerPool();\n * ```\n */\nexport function createSSRWorkerPool(\n options?: SSRWorkerPoolOptions\n): SSRWorkerPool {\n return new SSRWorkerPool(options);\n}\n"]}
@@ -0,0 +1,61 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.worker-protocol",
4
+ "title": "SSR Worker Protocol Types",
5
+ "category": "types"
6
+ }
7
+ */
8
+ /**
9
+ * Worker Protocol Types
10
+ *
11
+ * Shared type definitions for communication between the worker pool
12
+ * (main thread) and SSR workers (worker threads). Extracted to a
13
+ * single source of truth to prevent type drift.
14
+ */
15
+ import type { HeadState } from '../shared/types.js';
16
+ import type { RenderRouteResult } from './render-route.js';
17
+ /**
18
+ * Options for a render request
19
+ */
20
+ export interface WorkerRenderOptions {
21
+ /** URL to render */
22
+ url: string;
23
+ /** Path to the App component module (will be dynamically imported in worker) */
24
+ componentPath: string;
25
+ /**
26
+ * Path to the route manifest module (will be dynamically imported in worker).
27
+ * The module must export `routes` or a default export of RouteNode[].
28
+ * Cached per worker lifecycle — route changes require worker recycling.
29
+ */
30
+ routeManifestPath?: string;
31
+ /** Additional context to pass to components */
32
+ context?: Record<string, unknown>;
33
+ /** Custom app container ID */
34
+ appId?: string;
35
+ /** Loader execution timeout in ms (default: 30000) */
36
+ loaderTimeout?: number;
37
+ /** Continue rendering after loader errors (default: false) */
38
+ continueOnError?: boolean;
39
+ /** Default head state merged with per-route head (site-wide meta tags, etc.) */
40
+ defaultHead?: Partial<HeadState>;
41
+ /** Initial HTTP status code */
42
+ status?: number;
43
+ }
44
+ /**
45
+ * Message sent from the pool to a worker
46
+ */
47
+ export interface WorkerRequest {
48
+ id: number;
49
+ type: 'render';
50
+ options: WorkerRenderOptions;
51
+ }
52
+ /**
53
+ * Message sent from a worker back to the pool
54
+ */
55
+ export interface WorkerResponse {
56
+ id: number;
57
+ type: 'result' | 'error';
58
+ result?: RenderRouteResult;
59
+ error?: string;
60
+ }
61
+ //# sourceMappingURL=worker-protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-protocol.d.ts","sourceRoot":"","sources":["../../src/server/worker-protocol.ts"],"names":[],"mappings":"AAAA;;;;;;EAME;AAEF;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAE3D;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,oBAAoB;IACpB,GAAG,EAAE,MAAM,CAAC;IAEZ,gFAAgF;IAChF,aAAa,EAAE,MAAM,CAAC;IAEtB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B,+CAA+C;IAC/C,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAElC,8BAA8B;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,sDAAsD;IACtD,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB,8DAA8D;IAC9D,eAAe,CAAC,EAAE,OAAO,CAAC;IAE1B,gFAAgF;IAChF,WAAW,CAAC,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC;IAEjC,+BAA+B;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,QAAQ,CAAC;IACf,OAAO,EAAE,mBAAmB,CAAC;CAC9B;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,QAAQ,GAAG,OAAO,CAAC;IACzB,MAAM,CAAC,EAAE,iBAAiB,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
@@ -0,0 +1,9 @@
1
+ /** @codex
2
+ {
3
+ "id": "pithy.ssr.server.worker-protocol",
4
+ "title": "SSR Worker Protocol Types",
5
+ "category": "types"
6
+ }
7
+ */
8
+ export {};
9
+ //# sourceMappingURL=worker-protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-protocol.js","sourceRoot":"","sources":["../../src/server/worker-protocol.ts"],"names":[],"mappings":"AAAA;;;;;;EAME","sourcesContent":["/** @codex\n{\n \"id\": \"pithy.ssr.server.worker-protocol\",\n \"title\": \"SSR Worker Protocol Types\",\n \"category\": \"types\"\n}\n*/\n\n/**\n * Worker Protocol Types\n *\n * Shared type definitions for communication between the worker pool\n * (main thread) and SSR workers (worker threads). Extracted to a\n * single source of truth to prevent type drift.\n */\n\nimport type { HeadState } from '../shared/types.js';\nimport type { RenderRouteResult } from './render-route.js';\n\n/**\n * Options for a render request\n */\nexport interface WorkerRenderOptions {\n /** URL to render */\n url: string;\n\n /** Path to the App component module (will be dynamically imported in worker) */\n componentPath: string;\n\n /**\n * Path to the route manifest module (will be dynamically imported in worker).\n * The module must export `routes` or a default export of RouteNode[].\n * Cached per worker lifecycle — route changes require worker recycling.\n */\n routeManifestPath?: string;\n\n /** Additional context to pass to components */\n context?: Record<string, unknown>;\n\n /** Custom app container ID */\n appId?: string;\n\n /** Loader execution timeout in ms (default: 30000) */\n loaderTimeout?: number;\n\n /** Continue rendering after loader errors (default: false) */\n continueOnError?: boolean;\n\n /** Default head state merged with per-route head (site-wide meta tags, etc.) */\n defaultHead?: Partial<HeadState>;\n\n /** Initial HTTP status code */\n status?: number;\n}\n\n/**\n * Message sent from the pool to a worker\n */\nexport interface WorkerRequest {\n id: number;\n type: 'render';\n options: WorkerRenderOptions;\n}\n\n/**\n * Message sent from a worker back to the pool\n */\nexport interface WorkerResponse {\n id: number;\n type: 'result' | 'error';\n result?: RenderRouteResult;\n error?: string;\n}\n"]}
@@ -0,0 +1,71 @@
1
+ /** @codex { "id": "pithy.ssr.css-purge", "title": "Static Export CSS Purge Predicates", "category": "runtime", "risk": "high" } */
2
+ /**
3
+ * The decisions a static-export CSS purge makes, shared by `pithy-ssg` (which
4
+ * brace-matches stylesheet TEXT) and the studio export (which walks a live
5
+ * CSSOM). Only the decisions: finding the rules stays each caller's own, since
6
+ * a module graph and a live document are irreducibly different mechanisms.
7
+ *
8
+ * Every predicate fails OPEN — a rule that cannot be proven unused is kept.
9
+ *
10
+ * Node-free by construction, so the `./browser` subpath can re-export it.
11
+ */
12
+ /**
13
+ * The single DOM capability a purge needs. Narrower than `ParentNode` on
14
+ * purpose: a caller matching against several rendered pages at once has no
15
+ * single node to hand over, and every real `ParentNode` satisfies this.
16
+ */
17
+ /** @codexApi {"parent":"pithy.ssr.css-purge","name":"SelectorMatchRoot","stability":"experimental","signature":"interface { querySelector(selectors: string): unknown }"} */
18
+ export interface SelectorMatchRoot {
19
+ querySelector(selectors: string): unknown;
20
+ }
21
+ /**
22
+ * Whether any element in `root` is targeted by `selectorText` (a possibly
23
+ * comma-separated selector list). A selector the engine refuses to parse is
24
+ * treated as used.
25
+ *
26
+ * @param selectorText - A CSS selector or comma-separated selector list.
27
+ * @param root - What to match against; see {@link SelectorMatchRoot}.
28
+ * @returns `true` when the rule must be kept.
29
+ */
30
+ /** @codexApi {"parent":"pithy.ssr.css-purge","name":"isSelectorUsed","stability":"experimental","signature":"(selectorText: string, root: SelectorMatchRoot) => boolean"} */
31
+ export declare function isSelectorUsed(selectorText: string, root: SelectorMatchRoot): boolean;
32
+ /**
33
+ * The at-rule keyword of a rule or prelude, lowercased, or `null` for an
34
+ * ordinary style rule.
35
+ *
36
+ * Shared so both callers read it identically from different inputs: CSSOM
37
+ * `cssText` (no leading whitespace, serialization varies by engine) and a raw
38
+ * source slice (leading whitespace possible).
39
+ *
40
+ * @param text - A rule's full text or just its prelude.
41
+ */
42
+ /** @codexApi {"parent":"pithy.ssr.css-purge","name":"atRuleName","stability":"experimental","signature":"(text: string) => string | null"} */
43
+ export declare function atRuleName(text: string): string | null;
44
+ /**
45
+ * Whether an at-rule's body holds style rules to purge recursively. Callers
46
+ * must still check the rule has a body — `@layer a, b;` is a statement.
47
+ *
48
+ * @param name - An at-rule keyword, e.g. from {@link atRuleName}.
49
+ */
50
+ /** @codexApi {"parent":"pithy.ssr.css-purge","name":"isRecursiveAtRule","stability":"experimental","signature":"(name: string) => boolean"} */
51
+ export declare function isRecursiveAtRule(name: string): boolean;
52
+ /**
53
+ * Whether an at-rule block whose body purged to nothing must still be emitted,
54
+ * as `<prelude>{}`, to hold its place in the cascade.
55
+ *
56
+ * A NAMED `@layer` declares cascade ORDER, so dropping an emptied one moves the
57
+ * layer behind any later block that reopens the name:
58
+ * `@layer base{.unused{}} @layer components{.nav a{}} @layer base{a{}}` loses
59
+ * the first `base`, `base` then outranks `components`, and `.nav a` changes
60
+ * colour. An ANONYMOUS `@layer {}` names nothing, so nothing can reopen it and
61
+ * it holds no slot.
62
+ *
63
+ * Shared so the build and the browser sink agree, which is what
64
+ * `browser.ts` promises.
65
+ *
66
+ * @param at - An at-rule keyword, e.g. from {@link atRuleName}, or `null`.
67
+ * @param prelude - The block's prelude text, e.g. `@layer base`.
68
+ */
69
+ /** @codexApi {"parent":"pithy.ssr.css-purge","name":"holdsCascadeSlot","stability":"experimental","signature":"(at: string | null, prelude: string) => boolean"} */
70
+ export declare function holdsCascadeSlot(at: string | null, prelude: string): boolean;
71
+ //# sourceMappingURL=css-purge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"css-purge.d.ts","sourceRoot":"","sources":["../../src/shared/css-purge.ts"],"names":[],"mappings":"AAAA,mIAAmI;AAEnI;;;;;;;;;GASG;AAEH;;;;GAIG;AACH,6KAA6K;AAC7K,MAAM,WAAW,iBAAiB;IAChC,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;CAC3C;AAmED;;;;;;;;GAQG;AACH,6KAA6K;AAC7K,wBAAgB,cAAc,CAC5B,YAAY,EAAE,MAAM,EACpB,IAAI,EAAE,iBAAiB,GACtB,OAAO,CAkBT;AAED;;;;;;;;;GASG;AACH,8IAA8I;AAC9I,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAEtD;AAkBD;;;;;GAKG;AACH,+IAA+I;AAC/I,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEvD;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,oKAAoK;AACpK,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAiB5E"}
@@ -0,0 +1,177 @@
1
+ /** @codex { "id": "pithy.ssr.css-purge", "title": "Static Export CSS Purge Predicates", "category": "runtime", "risk": "high" } */
2
+ /**
3
+ * Selectors kept regardless of DOM match. A purge root is typically a detached
4
+ * page band with no `<html>`/`<body>`, so these would never "match" — yet they
5
+ * carry the custom properties and base resets the whole document depends on.
6
+ *
7
+ * The leading `(^|[\s,>+~(])` boundary is what keeps `.body-text` off the list.
8
+ */
9
+ const ALWAYS_KEEP_RE = /(^|[\s,>+~(])(html|body)\b|:root|\[data-theme|(^|,)\s*\*\s*(,|$|::?)/;
10
+ /**
11
+ * Strip pseudo-classes/elements so a selector can be tested against static
12
+ * DOM: `.ui-button:hover` → `.ui-button`, `.x:not(.y) .z` → `.x .z`.
13
+ *
14
+ * The `(?<!\\)` guard preserves ESCAPED colons, which the design system uses in
15
+ * state-variant utility class names (`.u-hover\:bg-primary:hover`). Without it
16
+ * the class name itself is mangled and the whole utility layer purges away.
17
+ */
18
+ function stripPseudos(selector) {
19
+ return selector.replace(/(?<!\\)::?[\w-]+(\([^)]*\))?/g, '').trim();
20
+ }
21
+ /**
22
+ * Split a selector list on its TOP-LEVEL commas only — the ones that separate
23
+ * selectors, not the ones inside `:is()`/`:not()`/`:where()`/`:has()` or an
24
+ * attribute value.
25
+ *
26
+ * A plain `split(',')` shreds `.a:is(.b, .c)` into `.a:is(.b` and `.c)`, which
27
+ * are not selectors at all: each fragment is then either refused by the engine
28
+ * or — worse — answered by a prefilter that reads `.b` and `.c` as REQUIRED
29
+ * when neither is. Every fragment this returns is a selector in its own right,
30
+ * so "no fragment matches" is an honest proof that the rule is unused.
31
+ *
32
+ * A `\` escapes the next character (a class name may legally contain `\,`),
33
+ * and an unbalanced `(` simply swallows the rest — which then fails open.
34
+ */
35
+ function splitSelectorList(selectorText) {
36
+ const parts = [];
37
+ let depth = 0;
38
+ let quote = '';
39
+ let start = 0;
40
+ for (let i = 0; i < selectorText.length; i++) {
41
+ const ch = selectorText[i];
42
+ if (ch === '\\') {
43
+ i++;
44
+ continue;
45
+ }
46
+ if (quote) {
47
+ if (ch === quote)
48
+ quote = '';
49
+ continue;
50
+ }
51
+ if (ch === '"' || ch === "'")
52
+ quote = ch;
53
+ else if (ch === '(' || ch === '[')
54
+ depth++;
55
+ else if (ch === ')' || ch === ']')
56
+ depth = Math.max(0, depth - 1);
57
+ else if (ch === ',' && depth === 0) {
58
+ parts.push(selectorText.slice(start, i));
59
+ start = i + 1;
60
+ }
61
+ }
62
+ parts.push(selectorText.slice(start));
63
+ return parts;
64
+ }
65
+ /**
66
+ * Whether any element in `root` is targeted by `selectorText` (a possibly
67
+ * comma-separated selector list). A selector the engine refuses to parse is
68
+ * treated as used.
69
+ *
70
+ * @param selectorText - A CSS selector or comma-separated selector list.
71
+ * @param root - What to match against; see {@link SelectorMatchRoot}.
72
+ * @returns `true` when the rule must be kept.
73
+ */
74
+ /** @codexApi {"parent":"pithy.ssr.css-purge","name":"isSelectorUsed","stability":"experimental","signature":"(selectorText: string, root: SelectorMatchRoot) => boolean"} */
75
+ export function isSelectorUsed(selectorText, root) {
76
+ for (const part of splitSelectorList(selectorText)) {
77
+ const sel = part.trim();
78
+ if (!sel)
79
+ continue;
80
+ if (ALWAYS_KEEP_RE.test(sel))
81
+ return true;
82
+ const stripped = stripPseudos(sel);
83
+ if (stripped === '' || stripped === '*')
84
+ return true;
85
+ try {
86
+ if (root.querySelector(stripped))
87
+ return true;
88
+ }
89
+ catch {
90
+ // Keep on refusal. Note this is the RARER of the two fail-open paths:
91
+ // happy-dom parses leniently and mostly does NOT throw — the `.a)` that
92
+ // `stripPseudos` leaves from `.a:not(:is(.b))` matches on `.a` instead.
93
+ // Both roads keep the rule; see the WRAPPERS note below.
94
+ return true;
95
+ }
96
+ }
97
+ return false;
98
+ }
99
+ /**
100
+ * The at-rule keyword of a rule or prelude, lowercased, or `null` for an
101
+ * ordinary style rule.
102
+ *
103
+ * Shared so both callers read it identically from different inputs: CSSOM
104
+ * `cssText` (no leading whitespace, serialization varies by engine) and a raw
105
+ * source slice (leading whitespace possible).
106
+ *
107
+ * @param text - A rule's full text or just its prelude.
108
+ */
109
+ /** @codexApi {"parent":"pithy.ssr.css-purge","name":"atRuleName","stability":"experimental","signature":"(text: string) => string | null"} */
110
+ export function atRuleName(text) {
111
+ return text.match(/^\s*@([a-z-]+)/i)?.[1].toLowerCase() ?? null;
112
+ }
113
+ /**
114
+ * Conditional grouping at-rules whose children are DOM-targeted style rules.
115
+ * Everything else — `@keyframes`, `@font-face`, `@property`, `@page` — holds
116
+ * descriptors or keyframe offsets, and testing those as selectors deletes them.
117
+ *
118
+ * `@container` earns its place: ui-kit's sections are container-queried, so
119
+ * without recursing them their (large) child sets would never purge.
120
+ */
121
+ const RECURSE_AT_RULES = new Set([
122
+ 'media',
123
+ 'supports',
124
+ 'container',
125
+ 'layer',
126
+ 'scope',
127
+ ]);
128
+ /**
129
+ * Whether an at-rule's body holds style rules to purge recursively. Callers
130
+ * must still check the rule has a body — `@layer a, b;` is a statement.
131
+ *
132
+ * @param name - An at-rule keyword, e.g. from {@link atRuleName}.
133
+ */
134
+ /** @codexApi {"parent":"pithy.ssr.css-purge","name":"isRecursiveAtRule","stability":"experimental","signature":"(name: string) => boolean"} */
135
+ export function isRecursiveAtRule(name) {
136
+ return RECURSE_AT_RULES.has(name.toLowerCase());
137
+ }
138
+ /**
139
+ * Whether an at-rule block whose body purged to nothing must still be emitted,
140
+ * as `<prelude>{}`, to hold its place in the cascade.
141
+ *
142
+ * A NAMED `@layer` declares cascade ORDER, so dropping an emptied one moves the
143
+ * layer behind any later block that reopens the name:
144
+ * `@layer base{.unused{}} @layer components{.nav a{}} @layer base{a{}}` loses
145
+ * the first `base`, `base` then outranks `components`, and `.nav a` changes
146
+ * colour. An ANONYMOUS `@layer {}` names nothing, so nothing can reopen it and
147
+ * it holds no slot.
148
+ *
149
+ * Shared so the build and the browser sink agree, which is what
150
+ * `browser.ts` promises.
151
+ *
152
+ * @param at - An at-rule keyword, e.g. from {@link atRuleName}, or `null`.
153
+ * @param prelude - The block's prelude text, e.g. `@layer base`.
154
+ */
155
+ /** @codexApi {"parent":"pithy.ssr.css-purge","name":"holdsCascadeSlot","stability":"experimental","signature":"(at: string | null, prelude: string) => boolean"} */
156
+ export function holdsCascadeSlot(at, prelude) {
157
+ // `at` already identifies the keyword, so only the NAME is in question here.
158
+ if (at !== 'layer')
159
+ return false;
160
+ // A comment is whitespace to the tokenizer, so `@layer /*c*/{}` is ANONYMOUS
161
+ // — unstripped, its `/*` reads as the layer's name. Walked with `indexOf`
162
+ // rather than `/\/\*[\s\S]*?\*\//g`, which rescans to the end of the text
163
+ // for every unclosed `/*`.
164
+ let rest = prelude
165
+ .trim()
166
+ .replace(/^@layer/i, '')
167
+ .trim();
168
+ for (;;) {
169
+ if (!rest.startsWith('/*'))
170
+ return rest.length > 0;
171
+ const close = rest.indexOf('*/', 2);
172
+ if (close === -1)
173
+ return false; // unclosed: no name can follow it
174
+ rest = rest.slice(close + 2).trim();
175
+ }
176
+ }
177
+ //# sourceMappingURL=css-purge.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"css-purge.js","sourceRoot":"","sources":["../../src/shared/css-purge.ts"],"names":[],"mappings":"AAAA,mIAAmI;AAuBnI;;;;;;GAMG;AACH,MAAM,cAAc,GAClB,sEAAsE,CAAC;AAEzE;;;;;;;GAOG;AACH,SAAS,YAAY,CAAC,QAAgB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,EAAE,CAAC,CAAC;AAClD,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,oKAAoK;AACpK,MAAM,UAAU,gBAAgB,CAAC,EAAiB,EAAE,OAAe;IACjE,6EAA6E;IAC7E,IAAI,EAAE,KAAK,OAAO;QAAE,OAAO,KAAK,CAAC;IACjC,6EAA6E;IAC7E,0EAA0E;IAC1E,0EAA0E;IAC1E,2BAA2B;IAC3B,IAAI,IAAI,GAAG,OAAO;SACf,IAAI,EAAE;SACN,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,IAAI,EAAE,CAAC;IACV,SAAS,CAAC;QACR,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;YAAE,OAAO,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QACnD,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;QACpC,IAAI,KAAK,KAAK,CAAC,CAAC;YAAE,OAAO,KAAK,CAAC,CAAC,kCAAkC;QAClE,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IACtC,CAAC;AACH,CAAC","sourcesContent":["/** @codex { \"id\": \"pithy.ssr.css-purge\", \"title\": \"Static Export CSS Purge Predicates\", \"category\": \"runtime\", \"risk\": \"high\" } */\n\n/**\n * The decisions a static-export CSS purge makes, shared by `pithy-ssg` (which\n * brace-matches stylesheet TEXT) and the studio export (which walks a live\n * CSSOM). Only the decisions: finding the rules stays each caller's own, since\n * a module graph and a live document are irreducibly different mechanisms.\n *\n * Every predicate fails OPEN — a rule that cannot be proven unused is kept.\n *\n * Node-free by construction, so the `./browser` subpath can re-export it.\n */\n\n/**\n * The single DOM capability a purge needs. Narrower than `ParentNode` on\n * purpose: a caller matching against several rendered pages at once has no\n * single node to hand over, and every real `ParentNode` satisfies this.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.css-purge\",\"name\":\"SelectorMatchRoot\",\"stability\":\"experimental\",\"signature\":\"interface { querySelector(selectors: string): unknown }\"} */\nexport interface SelectorMatchRoot {\n querySelector(selectors: string): unknown;\n}\n\n/**\n * Selectors kept regardless of DOM match. A purge root is typically a detached\n * page band with no `<html>`/`<body>`, so these would never \"match\" — yet they\n * carry the custom properties and base resets the whole document depends on.\n *\n * The leading `(^|[\\s,>+~(])` boundary is what keeps `.body-text` off the list.\n */\nconst ALWAYS_KEEP_RE =\n /(^|[\\s,>+~(])(html|body)\\b|:root|\\[data-theme|(^|,)\\s*\\*\\s*(,|$|::?)/;\n\n/**\n * Strip pseudo-classes/elements so a selector can be tested against static\n * DOM: `.ui-button:hover` → `.ui-button`, `.x:not(.y) .z` → `.x .z`.\n *\n * The `(?<!\\\\)` guard preserves ESCAPED colons, which the design system uses in\n * state-variant utility class names (`.u-hover\\:bg-primary:hover`). Without it\n * the class name itself is mangled and the whole utility layer purges away.\n */\nfunction stripPseudos(selector: string): string {\n return selector.replace(/(?<!\\\\)::?[\\w-]+(\\([^)]*\\))?/g, '').trim();\n}\n\n/**\n * Split a selector list on its TOP-LEVEL commas only — the ones that separate\n * selectors, not the ones inside `:is()`/`:not()`/`:where()`/`:has()` or an\n * attribute value.\n *\n * A plain `split(',')` shreds `.a:is(.b, .c)` into `.a:is(.b` and `.c)`, which\n * are not selectors at all: each fragment is then either refused by the engine\n * or — worse — answered by a prefilter that reads `.b` and `.c` as REQUIRED\n * when neither is. Every fragment this returns is a selector in its own right,\n * so \"no fragment matches\" is an honest proof that the rule is unused.\n *\n * A `\\` escapes the next character (a class name may legally contain `\\,`),\n * and an unbalanced `(` simply swallows the rest — which then fails open.\n */\nfunction splitSelectorList(selectorText: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let quote = '';\n let start = 0;\n\n for (let i = 0; i < selectorText.length; i++) {\n const ch = selectorText[i];\n if (ch === '\\\\') {\n i++;\n continue;\n }\n if (quote) {\n if (ch === quote) quote = '';\n continue;\n }\n if (ch === '\"' || ch === \"'\") quote = ch;\n else if (ch === '(' || ch === '[') depth++;\n else if (ch === ')' || ch === ']') depth = Math.max(0, depth - 1);\n else if (ch === ',' && depth === 0) {\n parts.push(selectorText.slice(start, i));\n start = i + 1;\n }\n }\n\n parts.push(selectorText.slice(start));\n return parts;\n}\n\n/**\n * Whether any element in `root` is targeted by `selectorText` (a possibly\n * comma-separated selector list). A selector the engine refuses to parse is\n * treated as used.\n *\n * @param selectorText - A CSS selector or comma-separated selector list.\n * @param root - What to match against; see {@link SelectorMatchRoot}.\n * @returns `true` when the rule must be kept.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.css-purge\",\"name\":\"isSelectorUsed\",\"stability\":\"experimental\",\"signature\":\"(selectorText: string, root: SelectorMatchRoot) => boolean\"} */\nexport function isSelectorUsed(\n selectorText: string,\n root: SelectorMatchRoot\n): boolean {\n for (const part of splitSelectorList(selectorText)) {\n const sel = part.trim();\n if (!sel) continue;\n if (ALWAYS_KEEP_RE.test(sel)) return true;\n const stripped = stripPseudos(sel);\n if (stripped === '' || stripped === '*') return true;\n try {\n if (root.querySelector(stripped)) return true;\n } catch {\n // Keep on refusal. Note this is the RARER of the two fail-open paths:\n // happy-dom parses leniently and mostly does NOT throw — the `.a)` that\n // `stripPseudos` leaves from `.a:not(:is(.b))` matches on `.a` instead.\n // Both roads keep the rule; see the WRAPPERS note below.\n return true;\n }\n }\n return false;\n}\n\n/**\n * The at-rule keyword of a rule or prelude, lowercased, or `null` for an\n * ordinary style rule.\n *\n * Shared so both callers read it identically from different inputs: CSSOM\n * `cssText` (no leading whitespace, serialization varies by engine) and a raw\n * source slice (leading whitespace possible).\n *\n * @param text - A rule's full text or just its prelude.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.css-purge\",\"name\":\"atRuleName\",\"stability\":\"experimental\",\"signature\":\"(text: string) => string | null\"} */\nexport function atRuleName(text: string): string | null {\n return text.match(/^\\s*@([a-z-]+)/i)?.[1].toLowerCase() ?? null;\n}\n\n/**\n * Conditional grouping at-rules whose children are DOM-targeted style rules.\n * Everything else — `@keyframes`, `@font-face`, `@property`, `@page` — holds\n * descriptors or keyframe offsets, and testing those as selectors deletes them.\n *\n * `@container` earns its place: ui-kit's sections are container-queried, so\n * without recursing them their (large) child sets would never purge.\n */\nconst RECURSE_AT_RULES = new Set([\n 'media',\n 'supports',\n 'container',\n 'layer',\n 'scope',\n]);\n\n/**\n * Whether an at-rule's body holds style rules to purge recursively. Callers\n * must still check the rule has a body — `@layer a, b;` is a statement.\n *\n * @param name - An at-rule keyword, e.g. from {@link atRuleName}.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.css-purge\",\"name\":\"isRecursiveAtRule\",\"stability\":\"experimental\",\"signature\":\"(name: string) => boolean\"} */\nexport function isRecursiveAtRule(name: string): boolean {\n return RECURSE_AT_RULES.has(name.toLowerCase());\n}\n\n/**\n * Whether an at-rule block whose body purged to nothing must still be emitted,\n * as `<prelude>{}`, to hold its place in the cascade.\n *\n * A NAMED `@layer` declares cascade ORDER, so dropping an emptied one moves the\n * layer behind any later block that reopens the name:\n * `@layer base{.unused{}} @layer components{.nav a{}} @layer base{a{}}` loses\n * the first `base`, `base` then outranks `components`, and `.nav a` changes\n * colour. An ANONYMOUS `@layer {}` names nothing, so nothing can reopen it and\n * it holds no slot.\n *\n * Shared so the build and the browser sink agree, which is what\n * `browser.ts` promises.\n *\n * @param at - An at-rule keyword, e.g. from {@link atRuleName}, or `null`.\n * @param prelude - The block's prelude text, e.g. `@layer base`.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.css-purge\",\"name\":\"holdsCascadeSlot\",\"stability\":\"experimental\",\"signature\":\"(at: string | null, prelude: string) => boolean\"} */\nexport function holdsCascadeSlot(at: string | null, prelude: string): boolean {\n // `at` already identifies the keyword, so only the NAME is in question here.\n if (at !== 'layer') return false;\n // A comment is whitespace to the tokenizer, so `@layer /*c*/{}` is ANONYMOUS\n // — unstripped, its `/*` reads as the layer's name. Walked with `indexOf`\n // rather than `/\\/\\*[\\s\\S]*?\\*\\//g`, which rescans to the end of the text\n // for every unclosed `/*`.\n let rest = prelude\n .trim()\n .replace(/^@layer/i, '')\n .trim();\n for (;;) {\n if (!rest.startsWith('/*')) return rest.length > 0;\n const close = rest.indexOf('*/', 2);\n if (close === -1) return false; // unclosed: no name can follow it\n rest = rest.slice(close + 2).trim();\n }\n}\n"]}
@@ -0,0 +1,41 @@
1
+ /** @codex { "id": "pithy.ssr.entry-path", "title": "Static Export Entry Paths", "category": "runtime", "risk": "medium" } */
2
+ /**
3
+ * Make one path segment usable verbatim as an entry name AND inside an href.
4
+ *
5
+ * Only for a sink that rewrites its links to match — see the module docblock.
6
+ *
7
+ * The text stays raw, deliberately. A URL path is percent-decoded before it is
8
+ * resolved, so `href="日本語/index.html"` requests a directory named `日本語` —
9
+ * an entry named `%E6%97%A5…` is not that, and the link would 404. A raw name
10
+ * is what the request decodes to, in the browser and on every static host.
11
+ * Only what a filesystem or a URL parser cannot take is escaped, and a trailing
12
+ * run of dots is escaped whole so a segment can never become `.`, `..`, or a
13
+ * name Windows silently truncates.
14
+ */
15
+ /** @codexApi {"parent":"pithy.ssr.entry-path","name":"escapeEntrySegment","stability":"stable","signature":"(segment: string) => string"} */
16
+ export declare function escapeEntrySegment(segment: string): string;
17
+ /**
18
+ * Key that two entry paths collide under.
19
+ *
20
+ * Folded and normalized because the check has to hold on the filesystem that
21
+ * *extracts* the output, not the one that produced it: `About/` and `about/`,
22
+ * or NFC `café/` and NFD `café/`, are two names on ext4 and one file on APFS
23
+ * and NTFS. Comparing raw strings finds neither. Both separators, because
24
+ * `path.resolve` on Win32 reads `foo\bar` as two components. Trailing dots and
25
+ * spaces, because Win32 drops them from every component — so `foo./` and `foo/`
26
+ * are one directory there, and a component left empty by that trim (`.../`)
27
+ * drops out of the path entirely.
28
+ *
29
+ * Upper-then-lower rather than `toLowerCase()`: lowercasing is not case
30
+ * folding, and leaves Greek `ς` and `σ` apart where a case-insensitive volume
31
+ * puts them together. Normalized on both sides of the fold, since folding can
32
+ * itself denormalize.
33
+ *
34
+ * This only ever reports; it never renames. A key that folds too much costs an
35
+ * export the caller can fix by renaming a page, where one that folds too little
36
+ * costs a page nobody notices is missing. `straße`/`strasse` is the visible
37
+ * price: NTFS keeps those apart, this rejects them.
38
+ */
39
+ /** @codexApi {"parent":"pithy.ssr.entry-path","name":"entryCollisionKey","stability":"stable","signature":"(entryPath: string) => string"} */
40
+ export declare function entryCollisionKey(entryPath: string): string;
41
+ //# sourceMappingURL=entry-path.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry-path.d.ts","sourceRoot":"","sources":["../../src/shared/entry-path.ts"],"names":[],"mappings":"AAAA,6HAA6H;AAsC7H;;;;;;;;;;;;GAYG;AACH,6IAA6I;AAC7I,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAG1D;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,8IAA8I;AAC9I,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAU3D"}
@@ -0,0 +1,87 @@
1
+ /** @codex { "id": "pithy.ssr.entry-path", "title": "Static Export Entry Paths", "category": "runtime", "risk": "medium" } */
2
+ /**
3
+ * Entry-name rules for static export sinks — `pithy-ssg` writing a file, the
4
+ * studio writing a zip entry.
5
+ *
6
+ * {@link entryCollisionKey} applies to both. {@link escapeEntrySegment} applies
7
+ * only to a sink that ALSO rewrites its own links: renaming a segment moves the
8
+ * file without moving the href, and `pithy-ssg` rebases links from the raw
9
+ * route (`makeLinksRelative`) or does not rebase at all, so escaping there would
10
+ * emit a page whose links resolve to nothing. The studio can escape because it
11
+ * rewrites hrefs into the same space it names entries in.
12
+ *
13
+ * Node-free by construction, so the `./browser` subpath can re-export it.
14
+ */
15
+ /**
16
+ * Punctuation a segment cannot carry verbatim when the same string is both an
17
+ * entry name and a URL path: what a Windows path rejects, the separator, and
18
+ * what a URL parser reads as structure rather than text (`#` opens a fragment,
19
+ * `%` opens an escape). `~` is the escape marker itself, so it is escaped too
20
+ * and the mapping stays one-to-one. Control characters and space are tested by
21
+ * code point alongside these.
22
+ */
23
+ const UNSAFE_SEGMENT_PUNCTUATION = '"#%*:<>?\\/|~';
24
+ function hexEscape(ch) {
25
+ return `~${ch.charCodeAt(0).toString(16).padStart(2, '0')}`;
26
+ }
27
+ // By code point rather than a character class: naming the control range in a
28
+ // regex needs a `no-control-regex` suppression to say the same thing.
29
+ function escapeChar(ch) {
30
+ const code = ch.charCodeAt(0);
31
+ if (code <= 0x20 || code === 0x7f)
32
+ return hexEscape(ch);
33
+ return UNSAFE_SEGMENT_PUNCTUATION.includes(ch) ? hexEscape(ch) : ch;
34
+ }
35
+ /**
36
+ * Make one path segment usable verbatim as an entry name AND inside an href.
37
+ *
38
+ * Only for a sink that rewrites its links to match — see the module docblock.
39
+ *
40
+ * The text stays raw, deliberately. A URL path is percent-decoded before it is
41
+ * resolved, so `href="日本語/index.html"` requests a directory named `日本語` —
42
+ * an entry named `%E6%97%A5…` is not that, and the link would 404. A raw name
43
+ * is what the request decodes to, in the browser and on every static host.
44
+ * Only what a filesystem or a URL parser cannot take is escaped, and a trailing
45
+ * run of dots is escaped whole so a segment can never become `.`, `..`, or a
46
+ * name Windows silently truncates.
47
+ */
48
+ /** @codexApi {"parent":"pithy.ssr.entry-path","name":"escapeEntrySegment","stability":"stable","signature":"(segment: string) => string"} */
49
+ export function escapeEntrySegment(segment) {
50
+ const safe = Array.from(segment, escapeChar).join('');
51
+ return safe.replace(/\.+$/, run => Array.from(run, hexEscape).join(''));
52
+ }
53
+ /**
54
+ * Key that two entry paths collide under.
55
+ *
56
+ * Folded and normalized because the check has to hold on the filesystem that
57
+ * *extracts* the output, not the one that produced it: `About/` and `about/`,
58
+ * or NFC `café/` and NFD `café/`, are two names on ext4 and one file on APFS
59
+ * and NTFS. Comparing raw strings finds neither. Both separators, because
60
+ * `path.resolve` on Win32 reads `foo\bar` as two components. Trailing dots and
61
+ * spaces, because Win32 drops them from every component — so `foo./` and `foo/`
62
+ * are one directory there, and a component left empty by that trim (`.../`)
63
+ * drops out of the path entirely.
64
+ *
65
+ * Upper-then-lower rather than `toLowerCase()`: lowercasing is not case
66
+ * folding, and leaves Greek `ς` and `σ` apart where a case-insensitive volume
67
+ * puts them together. Normalized on both sides of the fold, since folding can
68
+ * itself denormalize.
69
+ *
70
+ * This only ever reports; it never renames. A key that folds too much costs an
71
+ * export the caller can fix by renaming a page, where one that folds too little
72
+ * costs a page nobody notices is missing. `straße`/`strasse` is the visible
73
+ * price: NTFS keeps those apart, this rejects them.
74
+ */
75
+ /** @codexApi {"parent":"pithy.ssr.entry-path","name":"entryCollisionKey","stability":"stable","signature":"(entryPath: string) => string"} */
76
+ export function entryCollisionKey(entryPath) {
77
+ return entryPath
78
+ .split(/[\\/]+/)
79
+ .map(segment => segment.replace(/[. ]+$/, ''))
80
+ .filter(Boolean)
81
+ .join('/')
82
+ .normalize('NFC')
83
+ .toUpperCase()
84
+ .toLowerCase()
85
+ .normalize('NFC');
86
+ }
87
+ //# sourceMappingURL=entry-path.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry-path.js","sourceRoot":"","sources":["../../src/shared/entry-path.ts"],"names":[],"mappings":"AAAA,6HAA6H;AAE7H;;;;;;;;;;;;GAYG;AAEH;;;;;;;GAOG;AACH,MAAM,0BAA0B,GAAG,eAAe,CAAC;AAEnD,SAAS,SAAS,CAAC,EAAU;IAC3B,OAAO,IAAI,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC;AAC9D,CAAC;AAED,6EAA6E;AAC7E,sEAAsE;AACtE,SAAS,UAAU,CAAC,EAAU;IAC5B,MAAM,IAAI,GAAG,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC,EAAE,CAAC,CAAC;IACxD,OAAO,0BAA0B,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACtE,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,6IAA6I;AAC7I,MAAM,UAAU,kBAAkB,CAAC,OAAe;IAChD,MAAM,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACtD,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;AAC1E,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,8IAA8I;AAC9I,MAAM,UAAU,iBAAiB,CAAC,SAAiB;IACjD,OAAO,SAAS;SACb,KAAK,CAAC,QAAQ,CAAC;SACf,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;SAC7C,MAAM,CAAC,OAAO,CAAC;SACf,IAAI,CAAC,GAAG,CAAC;SACT,SAAS,CAAC,KAAK,CAAC;SAChB,WAAW,EAAE;SACb,WAAW,EAAE;SACb,SAAS,CAAC,KAAK,CAAC,CAAC;AACtB,CAAC","sourcesContent":["/** @codex { \"id\": \"pithy.ssr.entry-path\", \"title\": \"Static Export Entry Paths\", \"category\": \"runtime\", \"risk\": \"medium\" } */\n\n/**\n * Entry-name rules for static export sinks — `pithy-ssg` writing a file, the\n * studio writing a zip entry.\n *\n * {@link entryCollisionKey} applies to both. {@link escapeEntrySegment} applies\n * only to a sink that ALSO rewrites its own links: renaming a segment moves the\n * file without moving the href, and `pithy-ssg` rebases links from the raw\n * route (`makeLinksRelative`) or does not rebase at all, so escaping there would\n * emit a page whose links resolve to nothing. The studio can escape because it\n * rewrites hrefs into the same space it names entries in.\n *\n * Node-free by construction, so the `./browser` subpath can re-export it.\n */\n\n/**\n * Punctuation a segment cannot carry verbatim when the same string is both an\n * entry name and a URL path: what a Windows path rejects, the separator, and\n * what a URL parser reads as structure rather than text (`#` opens a fragment,\n * `%` opens an escape). `~` is the escape marker itself, so it is escaped too\n * and the mapping stays one-to-one. Control characters and space are tested by\n * code point alongside these.\n */\nconst UNSAFE_SEGMENT_PUNCTUATION = '\"#%*:<>?\\\\/|~';\n\nfunction hexEscape(ch: string): string {\n return `~${ch.charCodeAt(0).toString(16).padStart(2, '0')}`;\n}\n\n// By code point rather than a character class: naming the control range in a\n// regex needs a `no-control-regex` suppression to say the same thing.\nfunction escapeChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x20 || code === 0x7f) return hexEscape(ch);\n return UNSAFE_SEGMENT_PUNCTUATION.includes(ch) ? hexEscape(ch) : ch;\n}\n\n/**\n * Make one path segment usable verbatim as an entry name AND inside an href.\n *\n * Only for a sink that rewrites its links to match — see the module docblock.\n *\n * The text stays raw, deliberately. A URL path is percent-decoded before it is\n * resolved, so `href=\"日本語/index.html\"` requests a directory named `日本語` —\n * an entry named `%E6%97%A5…` is not that, and the link would 404. A raw name\n * is what the request decodes to, in the browser and on every static host.\n * Only what a filesystem or a URL parser cannot take is escaped, and a trailing\n * run of dots is escaped whole so a segment can never become `.`, `..`, or a\n * name Windows silently truncates.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.entry-path\",\"name\":\"escapeEntrySegment\",\"stability\":\"stable\",\"signature\":\"(segment: string) => string\"} */\nexport function escapeEntrySegment(segment: string): string {\n const safe = Array.from(segment, escapeChar).join('');\n return safe.replace(/\\.+$/, run => Array.from(run, hexEscape).join(''));\n}\n\n/**\n * Key that two entry paths collide under.\n *\n * Folded and normalized because the check has to hold on the filesystem that\n * *extracts* the output, not the one that produced it: `About/` and `about/`,\n * or NFC `café/` and NFD `café/`, are two names on ext4 and one file on APFS\n * and NTFS. Comparing raw strings finds neither. Both separators, because\n * `path.resolve` on Win32 reads `foo\\bar` as two components. Trailing dots and\n * spaces, because Win32 drops them from every component — so `foo./` and `foo/`\n * are one directory there, and a component left empty by that trim (`.../`)\n * drops out of the path entirely.\n *\n * Upper-then-lower rather than `toLowerCase()`: lowercasing is not case\n * folding, and leaves Greek `ς` and `σ` apart where a case-insensitive volume\n * puts them together. Normalized on both sides of the fold, since folding can\n * itself denormalize.\n *\n * This only ever reports; it never renames. A key that folds too much costs an\n * export the caller can fix by renaming a page, where one that folds too little\n * costs a page nobody notices is missing. `straße`/`strasse` is the visible\n * price: NTFS keeps those apart, this rejects them.\n */\n/** @codexApi {\"parent\":\"pithy.ssr.entry-path\",\"name\":\"entryCollisionKey\",\"stability\":\"stable\",\"signature\":\"(entryPath: string) => string\"} */\nexport function entryCollisionKey(entryPath: string): string {\n return entryPath\n .split(/[\\\\/]+/)\n .map(segment => segment.replace(/[. ]+$/, ''))\n .filter(Boolean)\n .join('/')\n .normalize('NFC')\n .toUpperCase()\n .toLowerCase()\n .normalize('NFC');\n}\n"]}