@timber-js/app 0.2.0-alpha.216 → 0.2.0-alpha.218

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 (38) hide show
  1. package/dist/_chunks/actions-CUh3cClk.js.map +1 -1
  2. package/dist/_chunks/cloudflare-Byxl8FWP.js.map +1 -1
  3. package/dist/_chunks/dev-server-B8zsT-ee.js.map +1 -1
  4. package/dist/_chunks/dist-DtrJyBbw.js.map +1 -1
  5. package/dist/_chunks/graph-cache-CYiUS2aS.js.map +1 -1
  6. package/dist/_chunks/use-query-states-I3JMng6J.js.map +1 -1
  7. package/dist/adapters/cloudflare.js +1 -2
  8. package/dist/adapters/nitro-immutable-assets.d.ts +47 -0
  9. package/dist/adapters/nitro-immutable-assets.d.ts.map +1 -0
  10. package/dist/adapters/nitro-preview.d.ts +3 -2
  11. package/dist/adapters/nitro-preview.d.ts.map +1 -1
  12. package/dist/adapters/nitro.d.ts +16 -2
  13. package/dist/adapters/nitro.d.ts.map +1 -1
  14. package/dist/adapters/nitro.js +130 -10
  15. package/dist/adapters/nitro.js.map +1 -1
  16. package/dist/analyze/graph-command.js.map +1 -1
  17. package/dist/client/error-boundary.js +1 -2
  18. package/dist/cookies/index.js.map +1 -1
  19. package/dist/index.js +29 -26
  20. package/dist/index.js.map +1 -1
  21. package/dist/plugins/build-manifest.d.ts.map +1 -1
  22. package/dist/search-params/index.js.map +1 -1
  23. package/dist/server/internal.js +11 -2
  24. package/dist/server/internal.js.map +1 -1
  25. package/dist/server/pipeline-metadata.d.ts +9 -0
  26. package/dist/server/pipeline-metadata.d.ts.map +1 -1
  27. package/dist/server/pipeline-phases.d.ts.map +1 -1
  28. package/dist/server/sitemap-handler.d.ts.map +1 -1
  29. package/docs/api/34-api-config.mdx +1 -1
  30. package/package.json +8 -8
  31. package/src/adapters/nitro-immutable-assets.ts +142 -0
  32. package/src/adapters/nitro-preview.ts +12 -3
  33. package/src/adapters/nitro.ts +31 -17
  34. package/src/client/browser-entry/index.ts +7 -1
  35. package/src/plugins/build-manifest.ts +12 -27
  36. package/src/server/pipeline-metadata.ts +11 -1
  37. package/src/server/pipeline-phases.ts +9 -2
  38. package/src/server/sitemap-handler.ts +14 -21
@@ -1 +1 @@
1
- {"version":3,"file":"graph-command.js","names":[],"sources":["../../src/analyze/graph-command.ts"],"sourcesContent":["/**\n * graph-command — `timber graph <file> [--json] [--all --json]`.\n *\n * Answers \"what environment(s) does this file run in?\" by delegating\n * to a running dev server when one is discovered (milliseconds), and\n * falling back to the cold crawl + mtime-keyed cache otherwise\n * (design/47 §5b). Dev-server responses are NOT cached in the mtime\n * cache: live answers may include real browser-graph data.\n *\n * Config anchoring deliberately diverges from `check`/`build`: those\n * discover the Vite config from the cwd (\"the app here\"), which is\n * wrong for a file-addressed command invoked from a monorepo root —\n * cwd anchoring would select the wrong app. `graph` walks UP from the\n * target file's directory to the nearest Vite config and resolves from\n * there, so the file's own app answers. `--config` overrides, same as\n * everywhere else.\n *\n * Cold-path policy: a cold single-file query runs the full-project\n * crawl (`--all` internally) and caches the entire report — one crawl\n * per project state, every subsequent question a cache hit. The\n * cache-hit path never imports Vite.\n */\n\nimport { execFile } from 'node:child_process';\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { mkdir, readFile, realpath, rm } from 'node:fs/promises';\nimport { request as httpRequest } from 'node:http';\nimport { request as httpsRequest } from 'node:https';\nimport { createRequire } from 'node:module';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { promisify } from 'node:util';\nimport { DEV_DISCOVERY_DIR, isPidAlive, type DevRecord } from '../plugins/dev-discovery.ts';\nimport {\n collectBaseFingerprintEntries,\n computeProjectFingerprint,\n fingerprintEntriesForFiles,\n hashFingerprintEntries,\n readGraphCache,\n writeGraphCache,\n GRAPH_CACHE_VERSION,\n GRAPH_JSON_VERSION,\n} from './graph-cache.ts';\nimport type { CrawlReport, GraphModuleReport } from './crawl.ts';\nimport type { ImportChain } from './chains.ts';\nimport { normalizeSlashes } from './scan.ts';\n\nconst execFileAsync = promisify(execFile);\n\nexport type GraphSource = 'dev-server' | 'static-scan';\n\n/** Crawl deadline passed to the child, plus slack for its boot/exit. */\nconst CRAWL_TIMEOUT_MS = 120_000;\nconst SPAWN_SLACK_MS = 30_000;\n\n/**\n * Short timeout for the dev-server probe: the fast path must not hold\n * the fallback hostage if the server is wedged or the connection hangs.\n */\nconst DEV_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Vite's own default config file names, in Vite's precedence order.\n * Matching the list (rather than globbing) keeps the walk-up aligned\n * with what `createServer` would discover in each directory.\n */\nconst VITE_CONFIG_FILES = [\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.ts',\n 'vite.config.cjs',\n 'vite.config.mts',\n 'vite.config.cts',\n];\n\nexport interface GraphOptions {\n /** Target file; required unless `all`. */\n file?: string;\n /** Explicit Vite config path (overrides the walk-up discovery). */\n config?: string;\n json: boolean;\n all: boolean;\n}\n\n/**\n * Walk up from `startDir` to the nearest directory containing a Vite\n * config file. Returns the config's absolute path, or null at the\n * filesystem root.\n */\nexport function findViteConfigUpward(startDir: string): string | null {\n let dir = startDir;\n for (;;) {\n for (const name of VITE_CONFIG_FILES) {\n const candidate = join(dir, name);\n if (existsSync(candidate)) return candidate;\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/** Max response body size (16 MB — matches the crawl child). */\nconst PROBE_MAX_BODY_BYTES = 16 * 1024 * 1024;\n\n/**\n * HTTP(S) GET with a wall-clock deadline and response-size limit,\n * returning the parsed JSON body or null on any failure. Uses\n * node:http/https directly — `fetch` silently strips the Host header,\n * which the endpoint's DNS-rebinding defense needs to see as `localhost`.\n *\n * The wall-clock timer covers both connection and body streaming —\n * node's `timeout` option is an INACTIVITY timeout that resets on every\n * chunk, so a slow-drip response would never fire it.\n */\nfunction probeEndpoint(record: DevRecord, path: string, timeoutMs: number): Promise<unknown> {\n return new Promise((resolve) => {\n let settled = false;\n const done = (value: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(wallClock);\n resolve(value);\n };\n\n const probeHost =\n record.host === '0.0.0.0' || record.host === '::' || record.host === ''\n ? '127.0.0.1'\n : record.host;\n const doRequest = record.protocol === 'https' ? httpsRequest : httpRequest;\n const req = doRequest(\n {\n hostname: probeHost,\n port: record.port,\n path,\n method: 'GET',\n // Self-signed certs are normal for dev servers.\n rejectUnauthorized: false,\n },\n (res) => {\n if (res.statusCode !== 200) {\n req.destroy();\n done(null);\n return;\n }\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n res.on('data', (chunk: Buffer) => {\n totalBytes += chunk.length;\n if (totalBytes > PROBE_MAX_BODY_BYTES) {\n req.destroy();\n done(null);\n return;\n }\n chunks.push(chunk);\n });\n res.on('end', () => {\n try {\n const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<\n string,\n unknown\n >;\n done(\n parsed?.version === GRAPH_JSON_VERSION && parsed?.source === 'dev-server'\n ? parsed\n : null\n );\n } catch {\n done(null);\n }\n });\n res.on('error', () => done(null));\n }\n );\n req.on('error', () => done(null));\n\n const wallClock = setTimeout(() => {\n req.destroy();\n done(null);\n }, timeoutMs);\n req.end();\n });\n}\n\n/**\n * Try to delegate a graph query to a running dev server discovered via\n * `.timber/dev/` records. Returns the parsed JSON response on success,\n * null on any failure (missing dir, no live records, probe failure).\n * Every failure mode is silent — the caller falls back to the cold crawl.\n */\nasync function tryDevServer(\n configDir: string,\n configFile: string,\n queryString: string\n): Promise<unknown> {\n const dir = join(configDir, DEV_DISCOVERY_DIR);\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return null;\n }\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n let record: DevRecord;\n try {\n record = JSON.parse(readFileSync(join(dir, entry), 'utf8')) as DevRecord;\n } catch {\n continue;\n }\n if (\n typeof record.port !== 'number' ||\n !Number.isInteger(record.port) ||\n record.port < 1 ||\n record.port > 65535 ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid < 1 ||\n typeof record.host !== 'string' ||\n (record.protocol !== 'http' && record.protocol !== 'https')\n ) {\n continue;\n }\n // Skip records from a different Vite config (TIM-1393). Records\n // without configFile (old servers) are accepted — rejecting them\n // would break the fast path until every server restarts.\n if (record.configFile && normalizeSlashes(record.configFile) !== normalizeSlashes(configFile))\n continue;\n if (!isPidAlive(record.pid)) continue;\n let result: unknown;\n try {\n result = await probeEndpoint(record, `/__timber/graph${queryString}`, DEV_PROBE_TIMEOUT_MS);\n } catch {\n // http.request can throw synchronously on malformed hostnames\n // (ERR_INVALID_CHAR) or other invalid options — treat as absent.\n continue;\n }\n if (result) return result;\n }\n return null;\n}\n\n/**\n * Resolve the app root from the config file's own directory, reading\n * it off the timber root-sync plugin api (the single supported way —\n * cf. cli-check.ts). Only runs on the cold path.\n *\n * Resolution uses SERVE/development semantics, not build's: the crawl\n * child evaluates this same config through `createServer` (dev), and\n * the dev-server fast path answers from dev graphs — the dev graphs\n * are the tool's ground truth (design/47 §Motivation). Resolving the\n * root under build mode while crawling under serve would let a\n * command/mode-branching config select one app and crawl another.\n */\nasync function resolveAppRoot(\n configFile: string\n): Promise<{ root: string; configFileDependencies: string[]; pageExtensions?: string[] }> {\n const { resolveConfig } = await import('vite');\n // Lazy for the same reason as Vite itself: plugin-context.ts has a\n // module-level `parseAst` import from vite, so a static import here\n // would make even warm cache hits pay Vite's startup cost — the\n // cache-hit path must stay vite-free (design/47 §Cold-path policy).\n const { isTimberPluginApi } = await import('../plugin-context.ts');\n // Anchor Vite's cwd-relative defaults at the config's directory, not\n // the caller's cwd — the whole point of the walk-up. The config's own\n // explicit `root` option still wins over this cwd, as it should.\n const previousCwd = process.cwd();\n process.chdir(dirname(configFile));\n // Route config-evaluation stdout to stderr for the duration: the\n // app's config and plugin hooks run in THIS process, and any\n // console.log from them would land in front of the --json contract,\n // breaking JSON.parse(stdout) consumers. (The crawl child has the\n // same problem solved by --out; this parent-side evaluation needs\n // the equivalent.) Bind write() so its overloads keep their exact\n // callback semantics.\n const stdoutWrite = process.stdout.write;\n process.stdout.write = process.stderr.write.bind(process.stderr) as typeof process.stdout.write;\n try {\n // TIMBER_ANALYZE and middlewareMode mirror the crawl child's boot:\n // serve-mode config hooks otherwise start dev-only side effects in\n // THIS process — the startup holding server binds the app's port\n // and keeps the CLI alive forever (index.ts gates it on\n // !middlewareMode), and platform dev plugins may open remote\n // connections classification never needs.\n process.env.TIMBER_ANALYZE = '1';\n const {\n plugins,\n configFileDependencies,\n resolve: resolveOptions,\n } = await resolveConfig(\n { configFile, logLevel: 'error', server: { middlewareMode: true } },\n 'serve',\n 'development',\n 'development'\n );\n const rootSync = plugins.find((plugin) => plugin.name === 'timber-root-sync');\n if (!rootSync || !isTimberPluginApi(rootSync.api)) {\n throw new Error(\n `[timber] ${configFile} does not produce the timber plugin.\\n` +\n ` \\`timber graph\\` resolves the app through Vite so it classifies the same\\n` +\n ` modules the build builds. Check that the config lists timber():\\n\\n` +\n ` import { timber } from '@timber-js/app';\\n` +\n ` export default { plugins: [timber()] };\\n`\n );\n }\n // Same path space as the crawl's report.root — the hit path\n // fingerprints cache.report.root, so a divergent space here\n // (backslashes, or symlink-vs-physical) would make miss- and\n // hit-path entry strings differ and the cache never match. Vite\n // does NOT realpath its resolved root; the crawl realpaths unless\n // resolve.preserveSymlinks keeps graphs on symlink paths — mirror\n // that decision from the same resolved config.\n const { normalizePath } = await import('vite');\n const pluginCtx = rootSync.api.getContext();\n const rawRoot = pluginCtx.root;\n return {\n root: normalizePath(resolveOptions.preserveSymlinks ? rawRoot : await realpath(rawRoot)),\n // A config helper imported from OUTSIDE the app root (a shared\n // vite.shared.ts beside a monorepo config) can reshape aliases,\n // plugins, or timber options without touching anything the disk\n // scan sees — the fingerprint must track these too. Vite's list\n // covers the vite.config bundle; timber.config.ts is require()d\n // by root-sync during resolveConfig, so its transitive imports\n // live in require.cache and are collected from there.\n configFileDependencies: [...configFileDependencies, ...collectTimberConfigDeps()],\n pageExtensions: pluginCtx.config.pageExtensions,\n };\n } finally {\n process.stdout.write = stdoutWrite;\n process.chdir(previousCwd);\n }\n}\n\n/**\n * Transitive dependencies of the loaded timber.config, from\n * require.cache: `loadTimberConfigFile` loads the config with native\n * require() (design/11 §Config Loading Semantics), so after\n * resolveConfig has run the config module and everything it imported —\n * including helpers OUTSIDE the app root that Vite's\n * configFileDependencies cannot see — sit in the cache with their\n * children recorded. node_modules entries are skipped (the lockfile\n * fingerprint covers them).\n */\nfunction collectTimberConfigDeps(): string[] {\n const require = createRequire(import.meta.url);\n const cache = require.cache ?? {};\n const roots = Object.values(cache).filter(\n (mod): mod is NonNullable<typeof mod> =>\n mod != null && /timber\\.config\\.(?:ts|js|mjs)$/.test(mod.filename)\n );\n const deps: string[] = [];\n const seen = new Set<string>();\n const queue = [...roots];\n while (queue.length > 0) {\n const mod = queue.shift()!;\n if (seen.has(mod.filename)) continue;\n seen.add(mod.filename);\n if (mod.filename.includes(`${sep}node_modules${sep}`)) continue;\n deps.push(mod.filename);\n queue.push(...mod.children);\n }\n return deps;\n}\n\n/**\n * Locate the crawl child entry beside this module: the built `.js` in\n * a published install, the `.ts` source under tsx (tests, this repo).\n */\nfunction resolveCrawlEntry(): { entry: string; nodeArgs: string[] } {\n const jsEntry = fileURLToPath(new URL('./crawl-entry.js', import.meta.url));\n if (existsSync(jsEntry)) return { entry: jsEntry, nodeArgs: [] };\n const tsEntry = fileURLToPath(new URL('./crawl-entry.ts', import.meta.url));\n return { entry: tsEntry, nodeArgs: ['--import', 'tsx/esm'] };\n}\n\n/** Spawn the crawl child and read its report from the --out file. */\nasync function runColdCrawl(root: string, configFile: string): Promise<CrawlReport> {\n const { entry, nodeArgs } = resolveCrawlEntry();\n const outFile = join(root, '.timber', `graph-crawl-${process.pid}.json`);\n await mkdir(dirname(outFile), { recursive: true });\n try {\n await execFileAsync(\n process.execPath,\n [\n ...nodeArgs,\n entry,\n '--root',\n root,\n '--config',\n configFile,\n '--out',\n outFile,\n '--timeout',\n String(CRAWL_TIMEOUT_MS),\n ],\n {\n // Same cwd anchor as resolveAppRoot: a config that derives\n // options from process.cwd() must evaluate identically in the\n // resolution that selected the app and in the crawl that\n // classifies it, or the two describe different apps. The app\n // root still reaches the child explicitly via --root.\n cwd: dirname(configFile),\n // The child's BFS deadline handles hung transforms; this spawn\n // timeout is the outer guard for a hang in createServer itself,\n // which the deadline cannot cover (see crawl-entry.ts).\n timeout: CRAWL_TIMEOUT_MS + SPAWN_SLACK_MS,\n maxBuffer: 16 * 1024 * 1024,\n }\n );\n return JSON.parse(await readFile(outFile, 'utf8')) as CrawlReport;\n } finally {\n await rm(outFile, { force: true }).catch(() => {});\n }\n}\n\ninterface GraphAnswer {\n report: CrawlReport;\n configFile: string;\n cached: boolean;\n}\n\n/**\n * Produce the full-project report: cache hit when the fingerprint\n * matches, cold crawl otherwise.\n *\n * The scan-derived base entries are computed BEFORE the crawl — files\n * changing mid-crawl make the next query miss, never the reverse. The\n * `trackedExtras` (config dependencies + every file the report\n * classifies) are only knowable after resolution and crawl, so their\n * entries are stat'd afterwards; for those alone, a mid-crawl edit is\n * stale-until-the-next-edit rather than an immediate miss.\n */\nasync function loadReport(configFile: string): Promise<GraphAnswer> {\n // The cache is anchored at the config file's directory, NOT the\n // resolved Vite root: knowing the root requires resolveConfig (which\n // imports Vite), and the entire point of the hit path is answering\n // without it. Reading and writing must use the same anchor — a split\n // (read here, write under the resolved root) would never hit for a\n // config whose `root` points elsewhere, silently re-crawling forever.\n const cacheDir = dirname(configFile);\n const cache = await readGraphCache(cacheDir);\n if (cache && cache.configFile === configFile) {\n const fingerprint = await computeProjectFingerprint(\n cache.report.root,\n configFile,\n cache.trackedExtras,\n cache.pageExtensions\n );\n if (fingerprint === cache.fingerprint) {\n return { report: cache.report, configFile, cached: true };\n }\n }\n\n const { root, configFileDependencies, pageExtensions } = await resolveAppRoot(configFile);\n const baseEntries = await collectBaseFingerprintEntries(root, configFile, pageExtensions);\n process.stderr.write('[timber] graph cache miss — cold project crawl (~2.5–10 s)\\n');\n // Config-dependency entries are snapshotted BEFORE the crawl, like\n // the base entries: a config helper edited during the multi-second\n // crawl must make the next query miss, not be stamped post-crawl\n // with its new mtime beside a report built from its old contents.\n const configDepEntries = await fingerprintEntriesForFiles(configFileDependencies);\n const report = await runColdCrawl(root, configFile);\n if (report.incomplete) {\n // Deadline-truncated report: transient (slow machine, cold dep\n // optimizer). Serve it — a truncated answer now beats none — but\n // never cache it: with unchanged files it would be served forever,\n // with no retry after the transient cause cleared.\n process.stderr.write('[timber] crawl hit its deadline — serving truncated, uncached report\\n');\n return { report, configFile, cached: false };\n }\n const trackedExtras = [\n ...new Set([...configFileDependencies, ...report.modules.map((m) => m.file)]),\n ].sort();\n // Report-file entries can only be stat'd post-crawl (the set is\n // unknowable before); for those alone a mid-crawl edit is stale-\n // until-next-edit. Files already covered pre-crawl (scan overlap,\n // config deps) keep their pre-crawl entries — hashFingerprintEntries\n // dedupes identical strings, and a mid-crawl edit produces a\n // DIFFERENT post-crawl entry for the same path, which changes the\n // hash and correctly misses on the next query.\n const reportFileEntries = await fingerprintEntriesForFiles(report.modules.map((m) => m.file));\n const fingerprint = hashFingerprintEntries([\n ...baseEntries,\n ...configDepEntries,\n ...reportFileEntries,\n ]);\n await writeGraphCache(cacheDir, {\n version: GRAPH_CACHE_VERSION,\n fingerprint,\n configFile,\n pageExtensions,\n trackedExtras,\n report,\n });\n return { report, configFile, cached: false };\n}\n\n/** Project-relative display path (JSON always stays absolute). */\nfunction displayPath(file: string, root: string): string {\n const rel = relative(root, file);\n return rel.startsWith('..') ? file : rel;\n}\n\n/**\n * Crawl errors that bear on one file's answer: failures on the file\n * itself (recorded by path or by root-relative URL) plus scan-level\n * failures, which undermine completeness for every file. Without this,\n * a target whose own transform failed would print a confident `server`\n * classification while only `--all` exposed the error (codex review,\n * PR #1056).\n */\nfunction errorsForTarget(report: CrawlReport, target: string): CrawlReport['errors'] {\n const asUrl = '/' + relative(report.root, target).split('\\\\').join('/');\n return report.errors.filter(\n (error) => error.environment === 'scan' || error.id === target || error.id === asUrl\n );\n}\n\nasync function printSingleFile(\n input: string,\n target: string,\n module: GraphModuleReport,\n answer: GraphAnswer,\n json: boolean\n): Promise<void> {\n const errors = errorsForTarget(answer.report, target);\n if (json) {\n console.log(\n JSON.stringify({\n version: GRAPH_JSON_VERSION,\n source: 'static-scan' satisfies GraphSource,\n cached: answer.cached,\n target: { input, resolved: target },\n kind: module.kind,\n pending: module.pending,\n subtreeUnknown: module.subtreeUnknown,\n envs: module.envs,\n boundary: module.boundary,\n chains: module.chains,\n poisonings: module.poisonings,\n errors,\n })\n );\n return;\n }\n\n const root = answer.report.root;\n const envs = Object.entries(module.envs)\n .filter(([, present]) => present)\n .map(([env]) => env);\n console.log(\n `${displayPath(target, root)} — ${module.kind}` +\n `${module.pending ? ' (pending: no graph has confirmed this file yet)' : ''}`\n );\n console.log(` source: static-scan${answer.cached ? ' (cached)' : ''}`);\n console.log(` environments: ${envs.length > 0 ? envs.join(', ') : 'none'}`);\n if (module.subtreeUnknown) {\n console.log(' note: reachable, but its subtree is unknown (never transformed)');\n }\n if (module.chains.length > 0) {\n // Lazy import: the text formatter pulls Vite (normalizePath); the\n // JSON path above must stay import-free for fast cache hits.\n const { formatChains } = await import('./chains.ts');\n console.log(' import chains:');\n console.log(formatChains(module.chains, root));\n }\n for (const poisoning of module.poisonings) {\n console.log(\n ` poisoning: ${poisoning.description} (${poisoning.specifier}) — ` +\n `implies ${poisoning.implies}`\n );\n }\n for (const error of errors) {\n console.log(` error [${error.environment}]: ${error.message} (${error.id})`);\n }\n}\n\n/**\n * The single-file JSON contract shape for dev-server responses. Shared\n * between the HTTP endpoint (graph-endpoint.ts) and this consumer so\n * the boundary crossing is typed, not cast. The endpoint produces this\n * shape; `probeEndpoint` parses it; `printDevServerText` formats it.\n */\ninterface DevServerFileResponse {\n version: number;\n source: string;\n cached: boolean;\n target: { input: string; resolved: string };\n kind: string;\n pending: boolean;\n subtreeUnknown: boolean;\n envs: Record<string, boolean>;\n boundary: boolean;\n chains: ImportChain[];\n poisonings: Array<{ description: string; specifier: string; implies: string }>;\n errors: Array<{ environment: string; message: string; id: string }>;\n}\n\n/**\n * Text-mode output for a dev-server response. The response carries the\n * same fields as the static-scan JSON, so the formatting mirrors\n * `printSingleFile` with `source: \"dev-server\"`.\n */\nasync function printDevServerText(data: DevServerFileResponse, configDir: string): Promise<void> {\n console.log(\n `${displayPath(data.target.resolved, configDir)} — ${data.kind}` +\n `${data.pending ? ' (pending: no graph has confirmed this file yet)' : ''}`\n );\n console.log(' source: dev-server');\n const envList = Object.entries(data.envs)\n .filter(([, present]) => present)\n .map(([env]) => env);\n console.log(` environments: ${envList.length > 0 ? envList.join(', ') : 'none'}`);\n if (data.subtreeUnknown) {\n console.log(' note: reachable, but its subtree is unknown (never transformed)');\n }\n if (data.chains.length > 0) {\n const { formatChains } = await import('./chains.ts');\n console.log(' import chains:');\n console.log(formatChains(data.chains, configDir));\n }\n for (const poisoning of data.poisonings) {\n console.log(\n ` poisoning: ${poisoning.description} (${poisoning.specifier}) — ` +\n `implies ${poisoning.implies}`\n );\n }\n for (const error of data.errors) {\n console.log(` error [${error.environment}]: ${error.message} (${error.id})`);\n }\n}\n\n/**\n * Run `timber graph`. Throws with actionable messages; the CLI's main()\n * prints and exits nonzero.\n */\nexport async function runGraph(options: GraphOptions): Promise<void> {\n if (options.all && !options.json) {\n throw new Error(\n 'timber graph --all requires --json (no text format is defined for the full project).'\n );\n }\n let target: { input: string; candidates: string[] } | null = null;\n if (options.file) {\n const resolved = resolve(process.cwd(), options.file);\n if (!existsSync(resolved)) {\n throw new Error(`[timber] file not found: ${resolved}`);\n }\n // Report paths are slash-normalized (normalizeSlashes) and usually\n // realpaths — but under resolve.preserveSymlinks the graphs keep\n // symlink paths. Look up BOTH forms rather than guessing the\n // config's setting (the hit path is vite-free and cannot ask):\n // as-typed first, realpath second.\n const asTyped = normalizeSlashes(resolved);\n const physical = normalizeSlashes(await realpath(resolved));\n target = {\n input: options.file,\n candidates: asTyped === physical ? [asTyped] : [asTyped, physical],\n };\n }\n if (!options.all && !target) {\n throw new Error('Usage: timber graph <file> [--json], or timber graph --all --json');\n }\n\n // Anchor config discovery at the AS-TYPED path (candidates[0]): under\n // preserveSymlinks a symlinked target's realpath may live in a\n // sibling workspace package, and walking up from there would select\n // that package's config — or none — instead of the app the user\n // addressed. The realpath candidate exists only for module lookup.\n const anchor = target ? dirname(target.candidates[0]) : process.cwd();\n const configFile = options.config\n ? resolve(process.cwd(), options.config)\n : findViteConfigUpward(anchor);\n if (!configFile || !existsSync(configFile)) {\n throw new Error(\n `[timber] no Vite config found walking up from ${anchor}.\\n` +\n ` \\`timber graph\\` anchors config discovery at the target file (not the cwd)\\n` +\n ` so the file's own app answers in a monorepo. Pass --config <path> to override.`\n );\n }\n\n // Fast path: delegate to a running dev server if one is discovered.\n // The query string mirrors the endpoint's contract — `?file=` for\n // single-file, `?all=1` for the full project. The endpoint returns\n // the same JSON contract the CLI prints, so on success the response\n // is printed verbatim (JSON mode) or decoded and formatted (text).\n // TIMBER_ANALYZE=1 suppresses delegation: the crawl child sets it\n // to skip dev-server side effects, and it also prevents the child\n // from discovering and probing the parent dev server's own endpoint.\n const configDir = dirname(configFile);\n const delegate = process.env.TIMBER_ANALYZE !== '1';\n if (delegate && options.all) {\n const live = await tryDevServer(configDir, configFile, '?all=1');\n if (live) {\n // --json is already guaranteed by the guard at the top.\n console.log(JSON.stringify(live));\n return;\n }\n } else if (delegate && target) {\n // The endpoint accepts absolute paths — pass the as-typed candidate\n // (matching the CLI's own config anchoring, not the realpath).\n const live = await tryDevServer(\n configDir,\n configFile,\n `?file=${encodeURIComponent(target.candidates[0])}`\n );\n if (live) {\n if (options.json) {\n // Preserve the user's original input (e.g. \"app/page.tsx\") —\n // the endpoint echoes the absolute path we sent as target.input,\n // which would differ from the cold path's relative input.\n const liveObj = live as Record<string, unknown>;\n if (typeof liveObj.target === 'object' && liveObj.target !== null) {\n (liveObj.target as Record<string, unknown>).input = target.input;\n }\n console.log(JSON.stringify(liveObj));\n return;\n }\n // The endpoint produces DevServerFileResponse by construction —\n // both frontends use the same classification pipeline. This is\n // the HTTP JSON boundary: probeEndpoint returns `unknown` from\n // JSON.parse; we narrow here because the endpoint's shape is our\n // own contract, not third-party data.\n await printDevServerText(live as DevServerFileResponse, configDir);\n return;\n }\n }\n\n // Cold path: mtime-keyed cache, then crawl.\n const answer = await loadReport(configFile);\n\n if (options.all) {\n console.log(\n JSON.stringify({\n version: GRAPH_JSON_VERSION,\n source: 'static-scan' satisfies GraphSource,\n cached: answer.cached,\n root: answer.report.root,\n configFile: answer.configFile,\n modules: answer.report.modules,\n errors: answer.report.errors,\n stats: answer.report.stats,\n })\n );\n return;\n }\n\n if (!target) {\n // Unreachable — validated at the top; kept for type narrowing.\n throw new Error('Usage: timber graph <file> [--json]');\n }\n const candidates = target.candidates;\n const module = answer.report.modules.find((m) => candidates.includes(m.file));\n if (!module) {\n throw new Error(\n `[timber] ${candidates[0]} is not part of the app at ${answer.report.root}\\n` +\n ` (resolved from ${configFile}). Only project source files inside the app\\n` +\n ` root are classified — node_modules and non-source files are not.`\n );\n }\n await printSingleFile(target.input, module.file, module, answer, options.json);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,gBAAgB,UAAU,QAAQ;;AAKxC,IAAM,mBAAmB;;;;;AAOzB,IAAM,uBAAuB;;;;;;AAO7B,IAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAgBA,SAAgB,qBAAqB,UAAiC;CACpE,IAAI,MAAM;CACV,SAAS;EACP,KAAK,MAAM,QAAQ,mBAAmB;GACpC,MAAM,YAAY,KAAK,KAAK,IAAI;GAChC,IAAI,WAAW,SAAS,GAAG,OAAO;EACpC;EACA,MAAM,SAAS,QAAQ,GAAG;EAC1B,IAAI,WAAW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","names":["httpsRequest","httpRequest"],"sources":["../../src/analyze/graph-command.ts"],"sourcesContent":["/**\n * graph-command — `timber graph <file> [--json] [--all --json]`.\n *\n * Answers \"what environment(s) does this file run in?\" by delegating\n * to a running dev server when one is discovered (milliseconds), and\n * falling back to the cold crawl + mtime-keyed cache otherwise\n * (design/47 §5b). Dev-server responses are NOT cached in the mtime\n * cache: live answers may include real browser-graph data.\n *\n * Config anchoring deliberately diverges from `check`/`build`: those\n * discover the Vite config from the cwd (\"the app here\"), which is\n * wrong for a file-addressed command invoked from a monorepo root —\n * cwd anchoring would select the wrong app. `graph` walks UP from the\n * target file's directory to the nearest Vite config and resolves from\n * there, so the file's own app answers. `--config` overrides, same as\n * everywhere else.\n *\n * Cold-path policy: a cold single-file query runs the full-project\n * crawl (`--all` internally) and caches the entire report — one crawl\n * per project state, every subsequent question a cache hit. The\n * cache-hit path never imports Vite.\n */\n\nimport { execFile } from 'node:child_process';\nimport { existsSync, readdirSync, readFileSync } from 'node:fs';\nimport { mkdir, readFile, realpath, rm } from 'node:fs/promises';\nimport { request as httpRequest } from 'node:http';\nimport { request as httpsRequest } from 'node:https';\nimport { createRequire } from 'node:module';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { promisify } from 'node:util';\nimport { DEV_DISCOVERY_DIR, isPidAlive, type DevRecord } from '../plugins/dev-discovery.ts';\nimport {\n collectBaseFingerprintEntries,\n computeProjectFingerprint,\n fingerprintEntriesForFiles,\n hashFingerprintEntries,\n readGraphCache,\n writeGraphCache,\n GRAPH_CACHE_VERSION,\n GRAPH_JSON_VERSION,\n} from './graph-cache.ts';\nimport type { CrawlReport, GraphModuleReport } from './crawl.ts';\nimport type { ImportChain } from './chains.ts';\nimport { normalizeSlashes } from './scan.ts';\n\nconst execFileAsync = promisify(execFile);\n\nexport type GraphSource = 'dev-server' | 'static-scan';\n\n/** Crawl deadline passed to the child, plus slack for its boot/exit. */\nconst CRAWL_TIMEOUT_MS = 120_000;\nconst SPAWN_SLACK_MS = 30_000;\n\n/**\n * Short timeout for the dev-server probe: the fast path must not hold\n * the fallback hostage if the server is wedged or the connection hangs.\n */\nconst DEV_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Vite's own default config file names, in Vite's precedence order.\n * Matching the list (rather than globbing) keeps the walk-up aligned\n * with what `createServer` would discover in each directory.\n */\nconst VITE_CONFIG_FILES = [\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.ts',\n 'vite.config.cjs',\n 'vite.config.mts',\n 'vite.config.cts',\n];\n\nexport interface GraphOptions {\n /** Target file; required unless `all`. */\n file?: string;\n /** Explicit Vite config path (overrides the walk-up discovery). */\n config?: string;\n json: boolean;\n all: boolean;\n}\n\n/**\n * Walk up from `startDir` to the nearest directory containing a Vite\n * config file. Returns the config's absolute path, or null at the\n * filesystem root.\n */\nexport function findViteConfigUpward(startDir: string): string | null {\n let dir = startDir;\n for (;;) {\n for (const name of VITE_CONFIG_FILES) {\n const candidate = join(dir, name);\n if (existsSync(candidate)) return candidate;\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/** Max response body size (16 MB — matches the crawl child). */\nconst PROBE_MAX_BODY_BYTES = 16 * 1024 * 1024;\n\n/**\n * HTTP(S) GET with a wall-clock deadline and response-size limit,\n * returning the parsed JSON body or null on any failure. Uses\n * node:http/https directly — `fetch` silently strips the Host header,\n * which the endpoint's DNS-rebinding defense needs to see as `localhost`.\n *\n * The wall-clock timer covers both connection and body streaming —\n * node's `timeout` option is an INACTIVITY timeout that resets on every\n * chunk, so a slow-drip response would never fire it.\n */\nfunction probeEndpoint(record: DevRecord, path: string, timeoutMs: number): Promise<unknown> {\n return new Promise((resolve) => {\n let settled = false;\n const done = (value: unknown) => {\n if (settled) return;\n settled = true;\n clearTimeout(wallClock);\n resolve(value);\n };\n\n const probeHost =\n record.host === '0.0.0.0' || record.host === '::' || record.host === ''\n ? '127.0.0.1'\n : record.host;\n const doRequest = record.protocol === 'https' ? httpsRequest : httpRequest;\n const req = doRequest(\n {\n hostname: probeHost,\n port: record.port,\n path,\n method: 'GET',\n // Self-signed certs are normal for dev servers.\n rejectUnauthorized: false,\n },\n (res) => {\n if (res.statusCode !== 200) {\n req.destroy();\n done(null);\n return;\n }\n const chunks: Buffer[] = [];\n let totalBytes = 0;\n res.on('data', (chunk: Buffer) => {\n totalBytes += chunk.length;\n if (totalBytes > PROBE_MAX_BODY_BYTES) {\n req.destroy();\n done(null);\n return;\n }\n chunks.push(chunk);\n });\n res.on('end', () => {\n try {\n const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<\n string,\n unknown\n >;\n done(\n parsed?.version === GRAPH_JSON_VERSION && parsed?.source === 'dev-server'\n ? parsed\n : null\n );\n } catch {\n done(null);\n }\n });\n res.on('error', () => done(null));\n }\n );\n req.on('error', () => done(null));\n\n const wallClock = setTimeout(() => {\n req.destroy();\n done(null);\n }, timeoutMs);\n req.end();\n });\n}\n\n/**\n * Try to delegate a graph query to a running dev server discovered via\n * `.timber/dev/` records. Returns the parsed JSON response on success,\n * null on any failure (missing dir, no live records, probe failure).\n * Every failure mode is silent — the caller falls back to the cold crawl.\n */\nasync function tryDevServer(\n configDir: string,\n configFile: string,\n queryString: string\n): Promise<unknown> {\n const dir = join(configDir, DEV_DISCOVERY_DIR);\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return null;\n }\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n let record: DevRecord;\n try {\n record = JSON.parse(readFileSync(join(dir, entry), 'utf8')) as DevRecord;\n } catch {\n continue;\n }\n if (\n typeof record.port !== 'number' ||\n !Number.isInteger(record.port) ||\n record.port < 1 ||\n record.port > 65535 ||\n typeof record.pid !== 'number' ||\n !Number.isInteger(record.pid) ||\n record.pid < 1 ||\n typeof record.host !== 'string' ||\n (record.protocol !== 'http' && record.protocol !== 'https')\n ) {\n continue;\n }\n // Skip records from a different Vite config (TIM-1393). Records\n // without configFile (old servers) are accepted — rejecting them\n // would break the fast path until every server restarts.\n if (record.configFile && normalizeSlashes(record.configFile) !== normalizeSlashes(configFile))\n continue;\n if (!isPidAlive(record.pid)) continue;\n let result: unknown;\n try {\n result = await probeEndpoint(record, `/__timber/graph${queryString}`, DEV_PROBE_TIMEOUT_MS);\n } catch {\n // http.request can throw synchronously on malformed hostnames\n // (ERR_INVALID_CHAR) or other invalid options — treat as absent.\n continue;\n }\n if (result) return result;\n }\n return null;\n}\n\n/**\n * Resolve the app root from the config file's own directory, reading\n * it off the timber root-sync plugin api (the single supported way —\n * cf. cli-check.ts). Only runs on the cold path.\n *\n * Resolution uses SERVE/development semantics, not build's: the crawl\n * child evaluates this same config through `createServer` (dev), and\n * the dev-server fast path answers from dev graphs — the dev graphs\n * are the tool's ground truth (design/47 §Motivation). Resolving the\n * root under build mode while crawling under serve would let a\n * command/mode-branching config select one app and crawl another.\n */\nasync function resolveAppRoot(\n configFile: string\n): Promise<{ root: string; configFileDependencies: string[]; pageExtensions?: string[] }> {\n const { resolveConfig } = await import('vite');\n // Lazy for the same reason as Vite itself: plugin-context.ts has a\n // module-level `parseAst` import from vite, so a static import here\n // would make even warm cache hits pay Vite's startup cost — the\n // cache-hit path must stay vite-free (design/47 §Cold-path policy).\n const { isTimberPluginApi } = await import('../plugin-context.ts');\n // Anchor Vite's cwd-relative defaults at the config's directory, not\n // the caller's cwd — the whole point of the walk-up. The config's own\n // explicit `root` option still wins over this cwd, as it should.\n const previousCwd = process.cwd();\n process.chdir(dirname(configFile));\n // Route config-evaluation stdout to stderr for the duration: the\n // app's config and plugin hooks run in THIS process, and any\n // console.log from them would land in front of the --json contract,\n // breaking JSON.parse(stdout) consumers. (The crawl child has the\n // same problem solved by --out; this parent-side evaluation needs\n // the equivalent.) Bind write() so its overloads keep their exact\n // callback semantics.\n const stdoutWrite = process.stdout.write;\n process.stdout.write = process.stderr.write.bind(process.stderr) as typeof process.stdout.write;\n try {\n // TIMBER_ANALYZE and middlewareMode mirror the crawl child's boot:\n // serve-mode config hooks otherwise start dev-only side effects in\n // THIS process — the startup holding server binds the app's port\n // and keeps the CLI alive forever (index.ts gates it on\n // !middlewareMode), and platform dev plugins may open remote\n // connections classification never needs.\n process.env.TIMBER_ANALYZE = '1';\n const {\n plugins,\n configFileDependencies,\n resolve: resolveOptions,\n } = await resolveConfig(\n { configFile, logLevel: 'error', server: { middlewareMode: true } },\n 'serve',\n 'development',\n 'development'\n );\n const rootSync = plugins.find((plugin) => plugin.name === 'timber-root-sync');\n if (!rootSync || !isTimberPluginApi(rootSync.api)) {\n throw new Error(\n `[timber] ${configFile} does not produce the timber plugin.\\n` +\n ` \\`timber graph\\` resolves the app through Vite so it classifies the same\\n` +\n ` modules the build builds. Check that the config lists timber():\\n\\n` +\n ` import { timber } from '@timber-js/app';\\n` +\n ` export default { plugins: [timber()] };\\n`\n );\n }\n // Same path space as the crawl's report.root — the hit path\n // fingerprints cache.report.root, so a divergent space here\n // (backslashes, or symlink-vs-physical) would make miss- and\n // hit-path entry strings differ and the cache never match. Vite\n // does NOT realpath its resolved root; the crawl realpaths unless\n // resolve.preserveSymlinks keeps graphs on symlink paths — mirror\n // that decision from the same resolved config.\n const { normalizePath } = await import('vite');\n const pluginCtx = rootSync.api.getContext();\n const rawRoot = pluginCtx.root;\n return {\n root: normalizePath(resolveOptions.preserveSymlinks ? rawRoot : await realpath(rawRoot)),\n // A config helper imported from OUTSIDE the app root (a shared\n // vite.shared.ts beside a monorepo config) can reshape aliases,\n // plugins, or timber options without touching anything the disk\n // scan sees — the fingerprint must track these too. Vite's list\n // covers the vite.config bundle; timber.config.ts is require()d\n // by root-sync during resolveConfig, so its transitive imports\n // live in require.cache and are collected from there.\n configFileDependencies: [...configFileDependencies, ...collectTimberConfigDeps()],\n pageExtensions: pluginCtx.config.pageExtensions,\n };\n } finally {\n process.stdout.write = stdoutWrite;\n process.chdir(previousCwd);\n }\n}\n\n/**\n * Transitive dependencies of the loaded timber.config, from\n * require.cache: `loadTimberConfigFile` loads the config with native\n * require() (design/11 §Config Loading Semantics), so after\n * resolveConfig has run the config module and everything it imported —\n * including helpers OUTSIDE the app root that Vite's\n * configFileDependencies cannot see — sit in the cache with their\n * children recorded. node_modules entries are skipped (the lockfile\n * fingerprint covers them).\n */\nfunction collectTimberConfigDeps(): string[] {\n const require = createRequire(import.meta.url);\n const cache = require.cache ?? {};\n const roots = Object.values(cache).filter(\n (mod): mod is NonNullable<typeof mod> =>\n mod != null && /timber\\.config\\.(?:ts|js|mjs)$/.test(mod.filename)\n );\n const deps: string[] = [];\n const seen = new Set<string>();\n const queue = [...roots];\n while (queue.length > 0) {\n const mod = queue.shift()!;\n if (seen.has(mod.filename)) continue;\n seen.add(mod.filename);\n if (mod.filename.includes(`${sep}node_modules${sep}`)) continue;\n deps.push(mod.filename);\n queue.push(...mod.children);\n }\n return deps;\n}\n\n/**\n * Locate the crawl child entry beside this module: the built `.js` in\n * a published install, the `.ts` source under tsx (tests, this repo).\n */\nfunction resolveCrawlEntry(): { entry: string; nodeArgs: string[] } {\n const jsEntry = fileURLToPath(new URL('./crawl-entry.js', import.meta.url));\n if (existsSync(jsEntry)) return { entry: jsEntry, nodeArgs: [] };\n const tsEntry = fileURLToPath(new URL('./crawl-entry.ts', import.meta.url));\n return { entry: tsEntry, nodeArgs: ['--import', 'tsx/esm'] };\n}\n\n/** Spawn the crawl child and read its report from the --out file. */\nasync function runColdCrawl(root: string, configFile: string): Promise<CrawlReport> {\n const { entry, nodeArgs } = resolveCrawlEntry();\n const outFile = join(root, '.timber', `graph-crawl-${process.pid}.json`);\n await mkdir(dirname(outFile), { recursive: true });\n try {\n await execFileAsync(\n process.execPath,\n [\n ...nodeArgs,\n entry,\n '--root',\n root,\n '--config',\n configFile,\n '--out',\n outFile,\n '--timeout',\n String(CRAWL_TIMEOUT_MS),\n ],\n {\n // Same cwd anchor as resolveAppRoot: a config that derives\n // options from process.cwd() must evaluate identically in the\n // resolution that selected the app and in the crawl that\n // classifies it, or the two describe different apps. The app\n // root still reaches the child explicitly via --root.\n cwd: dirname(configFile),\n // The child's BFS deadline handles hung transforms; this spawn\n // timeout is the outer guard for a hang in createServer itself,\n // which the deadline cannot cover (see crawl-entry.ts).\n timeout: CRAWL_TIMEOUT_MS + SPAWN_SLACK_MS,\n maxBuffer: 16 * 1024 * 1024,\n }\n );\n return JSON.parse(await readFile(outFile, 'utf8')) as CrawlReport;\n } finally {\n await rm(outFile, { force: true }).catch(() => {});\n }\n}\n\ninterface GraphAnswer {\n report: CrawlReport;\n configFile: string;\n cached: boolean;\n}\n\n/**\n * Produce the full-project report: cache hit when the fingerprint\n * matches, cold crawl otherwise.\n *\n * The scan-derived base entries are computed BEFORE the crawl — files\n * changing mid-crawl make the next query miss, never the reverse. The\n * `trackedExtras` (config dependencies + every file the report\n * classifies) are only knowable after resolution and crawl, so their\n * entries are stat'd afterwards; for those alone, a mid-crawl edit is\n * stale-until-the-next-edit rather than an immediate miss.\n */\nasync function loadReport(configFile: string): Promise<GraphAnswer> {\n // The cache is anchored at the config file's directory, NOT the\n // resolved Vite root: knowing the root requires resolveConfig (which\n // imports Vite), and the entire point of the hit path is answering\n // without it. Reading and writing must use the same anchor — a split\n // (read here, write under the resolved root) would never hit for a\n // config whose `root` points elsewhere, silently re-crawling forever.\n const cacheDir = dirname(configFile);\n const cache = await readGraphCache(cacheDir);\n if (cache && cache.configFile === configFile) {\n const fingerprint = await computeProjectFingerprint(\n cache.report.root,\n configFile,\n cache.trackedExtras,\n cache.pageExtensions\n );\n if (fingerprint === cache.fingerprint) {\n return { report: cache.report, configFile, cached: true };\n }\n }\n\n const { root, configFileDependencies, pageExtensions } = await resolveAppRoot(configFile);\n const baseEntries = await collectBaseFingerprintEntries(root, configFile, pageExtensions);\n process.stderr.write('[timber] graph cache miss — cold project crawl (~2.5–10 s)\\n');\n // Config-dependency entries are snapshotted BEFORE the crawl, like\n // the base entries: a config helper edited during the multi-second\n // crawl must make the next query miss, not be stamped post-crawl\n // with its new mtime beside a report built from its old contents.\n const configDepEntries = await fingerprintEntriesForFiles(configFileDependencies);\n const report = await runColdCrawl(root, configFile);\n if (report.incomplete) {\n // Deadline-truncated report: transient (slow machine, cold dep\n // optimizer). Serve it — a truncated answer now beats none — but\n // never cache it: with unchanged files it would be served forever,\n // with no retry after the transient cause cleared.\n process.stderr.write('[timber] crawl hit its deadline — serving truncated, uncached report\\n');\n return { report, configFile, cached: false };\n }\n const trackedExtras = [\n ...new Set([...configFileDependencies, ...report.modules.map((m) => m.file)]),\n ].sort();\n // Report-file entries can only be stat'd post-crawl (the set is\n // unknowable before); for those alone a mid-crawl edit is stale-\n // until-next-edit. Files already covered pre-crawl (scan overlap,\n // config deps) keep their pre-crawl entries — hashFingerprintEntries\n // dedupes identical strings, and a mid-crawl edit produces a\n // DIFFERENT post-crawl entry for the same path, which changes the\n // hash and correctly misses on the next query.\n const reportFileEntries = await fingerprintEntriesForFiles(report.modules.map((m) => m.file));\n const fingerprint = hashFingerprintEntries([\n ...baseEntries,\n ...configDepEntries,\n ...reportFileEntries,\n ]);\n await writeGraphCache(cacheDir, {\n version: GRAPH_CACHE_VERSION,\n fingerprint,\n configFile,\n pageExtensions,\n trackedExtras,\n report,\n });\n return { report, configFile, cached: false };\n}\n\n/** Project-relative display path (JSON always stays absolute). */\nfunction displayPath(file: string, root: string): string {\n const rel = relative(root, file);\n return rel.startsWith('..') ? file : rel;\n}\n\n/**\n * Crawl errors that bear on one file's answer: failures on the file\n * itself (recorded by path or by root-relative URL) plus scan-level\n * failures, which undermine completeness for every file. Without this,\n * a target whose own transform failed would print a confident `server`\n * classification while only `--all` exposed the error (codex review,\n * PR #1056).\n */\nfunction errorsForTarget(report: CrawlReport, target: string): CrawlReport['errors'] {\n const asUrl = '/' + relative(report.root, target).split('\\\\').join('/');\n return report.errors.filter(\n (error) => error.environment === 'scan' || error.id === target || error.id === asUrl\n );\n}\n\nasync function printSingleFile(\n input: string,\n target: string,\n module: GraphModuleReport,\n answer: GraphAnswer,\n json: boolean\n): Promise<void> {\n const errors = errorsForTarget(answer.report, target);\n if (json) {\n console.log(\n JSON.stringify({\n version: GRAPH_JSON_VERSION,\n source: 'static-scan' satisfies GraphSource,\n cached: answer.cached,\n target: { input, resolved: target },\n kind: module.kind,\n pending: module.pending,\n subtreeUnknown: module.subtreeUnknown,\n envs: module.envs,\n boundary: module.boundary,\n chains: module.chains,\n poisonings: module.poisonings,\n errors,\n })\n );\n return;\n }\n\n const root = answer.report.root;\n const envs = Object.entries(module.envs)\n .filter(([, present]) => present)\n .map(([env]) => env);\n console.log(\n `${displayPath(target, root)} — ${module.kind}` +\n `${module.pending ? ' (pending: no graph has confirmed this file yet)' : ''}`\n );\n console.log(` source: static-scan${answer.cached ? ' (cached)' : ''}`);\n console.log(` environments: ${envs.length > 0 ? envs.join(', ') : 'none'}`);\n if (module.subtreeUnknown) {\n console.log(' note: reachable, but its subtree is unknown (never transformed)');\n }\n if (module.chains.length > 0) {\n // Lazy import: the text formatter pulls Vite (normalizePath); the\n // JSON path above must stay import-free for fast cache hits.\n const { formatChains } = await import('./chains.ts');\n console.log(' import chains:');\n console.log(formatChains(module.chains, root));\n }\n for (const poisoning of module.poisonings) {\n console.log(\n ` poisoning: ${poisoning.description} (${poisoning.specifier}) — ` +\n `implies ${poisoning.implies}`\n );\n }\n for (const error of errors) {\n console.log(` error [${error.environment}]: ${error.message} (${error.id})`);\n }\n}\n\n/**\n * The single-file JSON contract shape for dev-server responses. Shared\n * between the HTTP endpoint (graph-endpoint.ts) and this consumer so\n * the boundary crossing is typed, not cast. The endpoint produces this\n * shape; `probeEndpoint` parses it; `printDevServerText` formats it.\n */\ninterface DevServerFileResponse {\n version: number;\n source: string;\n cached: boolean;\n target: { input: string; resolved: string };\n kind: string;\n pending: boolean;\n subtreeUnknown: boolean;\n envs: Record<string, boolean>;\n boundary: boolean;\n chains: ImportChain[];\n poisonings: Array<{ description: string; specifier: string; implies: string }>;\n errors: Array<{ environment: string; message: string; id: string }>;\n}\n\n/**\n * Text-mode output for a dev-server response. The response carries the\n * same fields as the static-scan JSON, so the formatting mirrors\n * `printSingleFile` with `source: \"dev-server\"`.\n */\nasync function printDevServerText(data: DevServerFileResponse, configDir: string): Promise<void> {\n console.log(\n `${displayPath(data.target.resolved, configDir)} — ${data.kind}` +\n `${data.pending ? ' (pending: no graph has confirmed this file yet)' : ''}`\n );\n console.log(' source: dev-server');\n const envList = Object.entries(data.envs)\n .filter(([, present]) => present)\n .map(([env]) => env);\n console.log(` environments: ${envList.length > 0 ? envList.join(', ') : 'none'}`);\n if (data.subtreeUnknown) {\n console.log(' note: reachable, but its subtree is unknown (never transformed)');\n }\n if (data.chains.length > 0) {\n const { formatChains } = await import('./chains.ts');\n console.log(' import chains:');\n console.log(formatChains(data.chains, configDir));\n }\n for (const poisoning of data.poisonings) {\n console.log(\n ` poisoning: ${poisoning.description} (${poisoning.specifier}) — ` +\n `implies ${poisoning.implies}`\n );\n }\n for (const error of data.errors) {\n console.log(` error [${error.environment}]: ${error.message} (${error.id})`);\n }\n}\n\n/**\n * Run `timber graph`. Throws with actionable messages; the CLI's main()\n * prints and exits nonzero.\n */\nexport async function runGraph(options: GraphOptions): Promise<void> {\n if (options.all && !options.json) {\n throw new Error(\n 'timber graph --all requires --json (no text format is defined for the full project).'\n );\n }\n let target: { input: string; candidates: string[] } | null = null;\n if (options.file) {\n const resolved = resolve(process.cwd(), options.file);\n if (!existsSync(resolved)) {\n throw new Error(`[timber] file not found: ${resolved}`);\n }\n // Report paths are slash-normalized (normalizeSlashes) and usually\n // realpaths — but under resolve.preserveSymlinks the graphs keep\n // symlink paths. Look up BOTH forms rather than guessing the\n // config's setting (the hit path is vite-free and cannot ask):\n // as-typed first, realpath second.\n const asTyped = normalizeSlashes(resolved);\n const physical = normalizeSlashes(await realpath(resolved));\n target = {\n input: options.file,\n candidates: asTyped === physical ? [asTyped] : [asTyped, physical],\n };\n }\n if (!options.all && !target) {\n throw new Error('Usage: timber graph <file> [--json], or timber graph --all --json');\n }\n\n // Anchor config discovery at the AS-TYPED path (candidates[0]): under\n // preserveSymlinks a symlinked target's realpath may live in a\n // sibling workspace package, and walking up from there would select\n // that package's config — or none — instead of the app the user\n // addressed. The realpath candidate exists only for module lookup.\n const anchor = target ? dirname(target.candidates[0]) : process.cwd();\n const configFile = options.config\n ? resolve(process.cwd(), options.config)\n : findViteConfigUpward(anchor);\n if (!configFile || !existsSync(configFile)) {\n throw new Error(\n `[timber] no Vite config found walking up from ${anchor}.\\n` +\n ` \\`timber graph\\` anchors config discovery at the target file (not the cwd)\\n` +\n ` so the file's own app answers in a monorepo. Pass --config <path> to override.`\n );\n }\n\n // Fast path: delegate to a running dev server if one is discovered.\n // The query string mirrors the endpoint's contract — `?file=` for\n // single-file, `?all=1` for the full project. The endpoint returns\n // the same JSON contract the CLI prints, so on success the response\n // is printed verbatim (JSON mode) or decoded and formatted (text).\n // TIMBER_ANALYZE=1 suppresses delegation: the crawl child sets it\n // to skip dev-server side effects, and it also prevents the child\n // from discovering and probing the parent dev server's own endpoint.\n const configDir = dirname(configFile);\n const delegate = process.env.TIMBER_ANALYZE !== '1';\n if (delegate && options.all) {\n const live = await tryDevServer(configDir, configFile, '?all=1');\n if (live) {\n // --json is already guaranteed by the guard at the top.\n console.log(JSON.stringify(live));\n return;\n }\n } else if (delegate && target) {\n // The endpoint accepts absolute paths — pass the as-typed candidate\n // (matching the CLI's own config anchoring, not the realpath).\n const live = await tryDevServer(\n configDir,\n configFile,\n `?file=${encodeURIComponent(target.candidates[0])}`\n );\n if (live) {\n if (options.json) {\n // Preserve the user's original input (e.g. \"app/page.tsx\") —\n // the endpoint echoes the absolute path we sent as target.input,\n // which would differ from the cold path's relative input.\n const liveObj = live as Record<string, unknown>;\n if (typeof liveObj.target === 'object' && liveObj.target !== null) {\n (liveObj.target as Record<string, unknown>).input = target.input;\n }\n console.log(JSON.stringify(liveObj));\n return;\n }\n // The endpoint produces DevServerFileResponse by construction —\n // both frontends use the same classification pipeline. This is\n // the HTTP JSON boundary: probeEndpoint returns `unknown` from\n // JSON.parse; we narrow here because the endpoint's shape is our\n // own contract, not third-party data.\n await printDevServerText(live as DevServerFileResponse, configDir);\n return;\n }\n }\n\n // Cold path: mtime-keyed cache, then crawl.\n const answer = await loadReport(configFile);\n\n if (options.all) {\n console.log(\n JSON.stringify({\n version: GRAPH_JSON_VERSION,\n source: 'static-scan' satisfies GraphSource,\n cached: answer.cached,\n root: answer.report.root,\n configFile: answer.configFile,\n modules: answer.report.modules,\n errors: answer.report.errors,\n stats: answer.report.stats,\n })\n );\n return;\n }\n\n if (!target) {\n // Unreachable — validated at the top; kept for type narrowing.\n throw new Error('Usage: timber graph <file> [--json]');\n }\n const candidates = target.candidates;\n const module = answer.report.modules.find((m) => candidates.includes(m.file));\n if (!module) {\n throw new Error(\n `[timber] ${candidates[0]} is not part of the app at ${answer.report.root}\\n` +\n ` (resolved from ${configFile}). Only project source files inside the app\\n` +\n ` root are classified — node_modules and non-source files are not.`\n );\n }\n await printSingleFile(target.input, module.file, module, answer, options.json);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,IAAM,gBAAgB,UAAU,QAAQ;;AAKxC,IAAM,mBAAmB;;;;;AAOzB,IAAM,uBAAuB;;;;;;AAO7B,IAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAgBA,SAAgB,qBAAqB,UAAiC;CACpE,IAAI,MAAM;CACV,SAAS;EACP,KAAK,MAAM,QAAQ,mBAAmB;GACpC,MAAM,YAAY,KAAK,KAAK,IAAI;GAChC,IAAI,WAAW,SAAS,GAAG,OAAO;EACpC;EACA,MAAM,SAAS,QAAQ,GAAG;EAC1B,IAAI,WAAW,KAAK,OAAO;EAC3B,MAAM;CACR;AACF;;AAGA,IAAM,uBAAuB;;;;;;;;;;;AAY7B,SAAS,cAAc,QAAmB,MAAc,WAAqC;CAC3F,OAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,UAAU;EACd,MAAM,Q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AI,MAAM;GAER,QAAQ,IAAI,KAAK,UAAU,IAAI,CAAC;GAChC;EACF;CACF,OAAO,IAAI,YAAY,QAAQ;EAG7B,MAAM,OAAO,MAAM,aACjB,WACA,YACA,SAAS,mBAAmB,OAAO,WAAW,EAAE,GAClD;EACA,IAAI,MAAM;GACR,IAAI,QAAQ,MAAM;IAIhB,MAAM,UAAU;IAChB,IAAI,OAAO,QAAQ,WAAW,YAAY,QAAQ,WAAW,MAC3D,QAAS,OAAmC,QAAQ,OAAO;IAE7D,QAAQ,IAAI,KAAK,UAAU,OAAO,CAAC;IACnC;GACF;GAMA,MAAM,mBAAmB,MAA+B,SAAS;GACjE;EACF;CACF;CAGA,MAAM,SAAS,MAAM,WAAW,UAAU;CAE1C,IAAI,QAAQ,KAAK;EACf,QAAQ,IACN,KAAK,UAAU;GACb,SAAA;GACA,QAAQ;GACR,QAAQ,OAAO;GACf,MAAM,OAAO,OAAO;GACpB,YAAY,OAAO;GACnB,SAAS,OAAO,OAAO;GACvB,QAAQ,OAAO,OAAO;GACtB,OAAO,OAAO,OAAO;EACvB,CAAC,CACH;EACA;CACF;CAEA,IAAI,CAAC,QAEH,MAAM,IAAI,MAAM,qCAAqC;CAEvD,MAAM,aAAa,OAAO;CAC1B,MAAM,SAAS,OAAO,OAAO,QAAQ,MAAM,MAAM,WAAW,SAAS,EAAE,IAAI,CAAC;CAC5E,IAAI,CAAC,QACH,MAAM,IAAI,MACR,YAAY,WAAW,GAAG,6BAA6B,OAAO,OAAO,KAAK,qBACpD,WAAW,gHAEnC;CAEF,MAAM,gBAAgB,OAAO,OAAO,OAAO,MAAM,QAAQ,QAAQ,QAAQ,IAAI;AAC/E"}
@@ -1,4 +1,3 @@
1
1
  "use client";
2
2
  "use client";
3
- import { n as TimberErrorBoundary, t as DenyAncestryContext } from "../_chunks/error-boundary-xxxLtXt6.js";
4
- export { DenyAncestryContext, TimberErrorBoundary };
3
+ export { t as DenyAncestryContext, n as TimberErrorBoundary } from "../_chunks/error-boundary-xxxLtXt6.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/client/use-cookie.ts","../../src/cookies/define-cookie.ts","../../src/cookies/json-cookie.ts"],"sourcesContent":["/**\n * useCookie — reactive client-side cookie hook.\n *\n * Uses useSyncExternalStore for SSR-safe, reactive cookie access.\n * All components reading the same cookie name re-render on change.\n * No cross-tab sync (intentional — see design/29-cookies.md).\n *\n * See design/29-cookies.md §\"useCookie(name) Hook\"\n */\n\n// Namespace access, not `import { useSyncExternalStore }`. This module is\n// reachable from `@timber-js/app/cookies` — `defineCookie()` exposes both a\n// server `.get()` and a client `.useCookie()`, so the entry is isomorphic and\n// loads in the RSC environment. React's `react-server` export withholds\n// `useSyncExternalStore` exactly as it withholds `createContext`, and a *named*\n// ESM import of a missing export fails at module instantiation, before any\n// code runs. Same rule as `client/params-context.ts` (TIM-1297, TIM-1298).\nimport * as React from 'react';\nimport { parseCookie, stringifySetCookie } from 'cookie';\nimport { getSsrData } from './ssr-data.ts';\nimport { assertValidCookieName } from '../cookies/validation.ts';\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\nexport interface ClientCookieOptions {\n /** URL path scope. Default: '/'. */\n path?: string;\n /** Domain scope. Default: omitted (current domain). */\n domain?: string;\n /** Max age in seconds. */\n maxAge?: number;\n /** Expiration date. */\n expires?: Date;\n /** Cross-site policy. Default: 'lax'. */\n sameSite?: 'strict' | 'lax' | 'none';\n /** Only send over HTTPS. Default: true in production. */\n secure?: boolean;\n}\n\nexport type CookieSetter = (value: string, options?: ClientCookieOptions) => void;\n\n// ─── Module-Level Cookie Store ────────────────────────────────────────────\n\ntype Listener = () => void;\n\n/** Per-name subscriber sets. */\nconst listeners = new Map<string, Set<Listener>>();\n\n/** Parse a cookie name from document.cookie. */\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n const cookies = parseCookie(document.cookie);\n return cookies[name];\n}\n\n/** Serialize options into a cookie string suffix. */\nexport function serializeOptions(options?: ClientCookieOptions): string {\n if (!options) return '; Path=/; SameSite=Lax';\n const sameSite = options.sameSite ?? 'lax';\n // Build a Set-Cookie string via the cookie package, then strip the\n // `__placeholder__=` name=value prefix to get just the attributes.\n const full = stringifySetCookie({\n name: '__placeholder__',\n value: '',\n path: options.path ?? '/',\n domain: options.domain,\n maxAge: options.maxAge,\n expires: options.expires,\n sameSite,\n secure: options.secure,\n });\n // Strip everything up to and including the first \"; \"\n const idx = full.indexOf('; ');\n return idx >= 0 ? full.slice(idx) : '';\n}\n\n/** Notify all subscribers for a given cookie name. */\nfunction notify(name: string): void {\n const subs = listeners.get(name);\n if (subs) {\n for (const fn of subs) fn();\n }\n}\n\n/**\n * Notify useCookie subscribers that a cookie value changed.\n * Called by defineCookie's imperative client .set()/.delete() methods\n * so mounted useCookie() consumers re-render.\n *\n * @internal — framework use only\n */\nexport function notifyCookieChange(name: string): void {\n notify(name);\n}\n\n// ─── Hook ─────────────────────────────────────────────────────────────────\n\n/**\n * Reactive hook for reading/writing a client-side cookie.\n *\n * Returns `[value, setCookie, deleteCookie]`:\n * - `value`: current cookie value (string | undefined)\n * - `setCookie`: sets the cookie and triggers re-renders\n * - `deleteCookie`: deletes the cookie and triggers re-renders\n *\n * @param name - Cookie name.\n * @param defaultOptions - Default options for setCookie calls.\n */\nexport function useCookie(\n name: string,\n defaultOptions?: ClientCookieOptions\n): [value: string | undefined, setCookie: CookieSetter, deleteCookie: () => void] {\n const subscribe = (callback: Listener): (() => void) => {\n let subs = listeners.get(name);\n if (!subs) {\n subs = new Set();\n listeners.set(name, subs);\n }\n subs.add(callback);\n return () => {\n subs!.delete(callback);\n if (subs!.size === 0) listeners.delete(name);\n };\n };\n\n const getSnapshot = (): string | undefined => getCookieValue(name);\n const getServerSnapshot = (): string | undefined => {\n // During SSR, read the ALS-backed request cookies.\n const ssrData = getSsrData();\n if (ssrData) return ssrData.cookies.get(name);\n // During client hydration there is no SSR data (it lives in the server's\n // module graph), but React still calls getServerSnapshot. document.cookie\n // holds the same cookies the server rendered with, so reading it here\n // keeps the hydration render consistent with the server HTML.\n // See design/29-cookies.md §\"SSR Hydration\".\n return getCookieValue(name);\n };\n\n const value = React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n\n // Validate the name once per hook instance — names are typically\n // stable string literals, so this catches the bug at first render\n // rather than on every write. Throws via `assertValidCookieName` with\n // a precise error if the name violates RFC 7230 token rules.\n assertValidCookieName(name);\n\n const setCookie: CookieSetter = (newValue: string, options?: ClientCookieOptions) => {\n if (typeof newValue !== 'string') {\n throw new Error(\n `[timber] useCookie(${JSON.stringify(name)}): value must be a string, got ${typeof newValue}.\\n` +\n ` To store a JSON-serializable value, use defineCookie + jsonCookieCodec from\\n` +\n ` '@timber-js/app/cookies' and call its useCookie() hook instead.`\n );\n }\n const merged = { ...defaultOptions, ...options };\n // Auto-encode mirrors the server's `cookies().set()` contract:\n // values are URL-encoded on write, URL-decoded on read, so the\n // logical bytes round-trip losslessly. See design/29-cookies.md\n // §\"Encoding Contract\".\n document.cookie = `${name}=${encodeURIComponent(newValue)}${serializeOptions(merged)}`;\n notify(name);\n };\n\n const deleteCookie = (): void => {\n const path = defaultOptions?.path ?? '/';\n const domain = defaultOptions?.domain;\n let cookieStr = `${name}=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=${path}`;\n if (domain) cookieStr += `; Domain=${domain}`;\n document.cookie = cookieStr;\n notify(name);\n };\n\n return [value, setCookie, deleteCookie];\n}\n","/**\n * defineCookie — typed cookie definitions.\n *\n * Bundles name + codec + options into a reusable CookieDefinition<T>\n * with sync .get(), .set(), .delete() isomorphic methods (server + client)\n * and a .useCookie() client hook.\n *\n * Environment detection is call-time: on the server, getCookieJar() is\n * used directly (ALS-backed). On the client, document.cookie helpers\n * and the useCookie hook are used. No registration pattern — imports\n * resolve via the shims plugin (client bundle gets a stub for\n * @timber-js/app/server).\n *\n * Standard Schema objects (Zod, Valibot, ArkType) are auto-detected in\n * the codec option — no explicit fromSchema() wrapper needed.\n *\n * See design/29-cookies.md §\"Typed Cookies with Schema Validation\"\n */\n\nimport type { CookieOptions } from '../server/cookie-context.ts';\nimport type { ClientCookieOptions } from '../client/use-cookie.ts';\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\nimport type { Codec } from '../codec.ts';\nimport type { StandardSchemaV1 } from '../schema-bridge.ts';\nimport { resolveCodecOrSchema } from '../schema-bridge.ts';\n\n/**\n * A codec that converts between string cookie values and typed values.\n * Type alias for the shared Codec<T> protocol.\n */\nexport type CookieCodec<T> = Codec<T>;\n\n/** Options for defineCookie: codec + CookieOptions merged. */\nexport interface DefineCookieOptions<T, HttpOnly extends boolean = boolean> extends CookieOptions {\n /**\n * Codec for parsing/serializing the cookie value.\n * Accepts a Codec<T> or a Standard Schema object (Zod, Valibot, ArkType)\n * which is auto-wrapped via fromSchema.\n */\n codec: CookieCodec<T> | StandardSchemaV1<T>;\n /**\n * Prevent client-side JS access. Default: true.\n * When true (or omitted), client methods (useCookie, get/set/delete on\n * client) are omitted from the return type and throw at runtime.\n */\n httpOnly?: HttpOnly;\n}\n\n/**\n * Server-only cookie definition. Returned when httpOnly is true or omitted.\n * Client methods are absent from the type — accessing them is a TS error.\n */\nexport interface ServerOnlyCookieDefinition<T> {\n readonly name: string;\n readonly options: CookieOptions;\n readonly codec: CookieCodec<T>;\n\n /** Read the typed value. Sync, isomorphic (server + client). */\n get(): T;\n /** Set the typed value. Sync, isomorphic (server + client). */\n set(value: T): void;\n /** Delete the cookie. Sync, isomorphic (server + client). */\n delete(): void;\n}\n\n/**\n * Full cookie definition with client methods. Returned when httpOnly: false.\n */\nexport interface CookieDefinition<T> extends ServerOnlyCookieDefinition<T> {\n /** Client: React hook for reading/writing this cookie. Returns [value, setter, deleter]. */\n useCookie(): [T, (value: T) => void, () => void];\n}\n\n// ─── Direct Imports (no registration) ─────────────────────────────────────\n//\n// Server: getCookieJar is imported from @timber-js/app/server. In the client\n// bundle, the shims plugin replaces @timber-js/app/server with a stub module\n// where getCookieJar throws on call. We detect the environment at call time\n// by trying getCookieJar() — if it throws the stub error, we fall through\n// to the client path.\n//\n// Client: useCookie, getCookieValue, notifyCookieChange\n// are imported from use-cookie.ts. These are safe in all environments (no\n// node:async_hooks dependency).\n//\n// Schema: fromSchema is a pure function — safe in all environments.\n\nimport { getCookieJar } from '@timber-js/app/server';\nimport {\n useCookie as useRawCookie,\n notifyCookieChange,\n getCookieValue,\n} from '../client/use-cookie.ts';\n\n// ─── Environment Detection ────────────────────────────────────────────────\n\n/**\n * Try to get the server cookie jar. Returns null if we're in the client\n * environment (stub throws) or if there's no request context.\n *\n * On the server, getCookieJar() throws \"outside of a request context\" if\n * called without an ALS store — this is a real error and is re-thrown.\n * The client stub throws a different message — that's caught and returns null.\n */\nfunction tryGetServerCookieJar(): ReturnType<typeof getCookieJar> | null {\n try {\n return getCookieJar();\n } catch (e) {\n // Server-side \"no request context\" error — re-throw as a real bug.\n if (e instanceof Error && e.message.includes('outside of a request context')) {\n throw e;\n }\n // Client stub error or other — fall through to client path.\n return null;\n }\n}\n\n// ─── Client Cookie Helpers ────────────────────────────────────────────────\n\n/** Write a cookie via document.cookie and notify useCookie subscribers. */\nfunction setClientCookie(name: string, value: string, options?: ClientCookieOptions): void {\n const parts: string[] = [`${name}=${encodeURIComponent(value)}`];\n const path = options?.path ?? '/';\n parts.push(`Path=${path}`);\n if (options?.domain) parts.push(`Domain=${options.domain}`);\n if (options?.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);\n if (options?.expires) parts.push(`Expires=${options.expires.toUTCString()}`);\n const sameSite = options?.sameSite ?? 'lax';\n parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`);\n if (options?.secure) parts.push('Secure');\n document.cookie = parts.join('; ');\n notifyCookieChange(name);\n}\n\n/** Delete a cookie via document.cookie and notify useCookie subscribers. */\nfunction deleteClientCookie(name: string, options?: ClientCookieOptions): void {\n const path = options?.path ?? '/';\n const domain = options?.domain;\n let cookieStr = `${name}=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=${path}`;\n if (domain) cookieStr += `; Domain=${domain}`;\n document.cookie = cookieStr;\n notifyCookieChange(name);\n}\n\n// ─── Standard Schema Auto-Detection ───────────────────────────────────────\n\nfunction resolveCodec<T>(codecOrSchema: CookieCodec<T> | StandardSchemaV1<T>): CookieCodec<T> {\n // 'cookie', not 'search': a cookie carries one string per name, so the\n // repeated-key array shape the search bridge tolerates does not exist\n // here — and `serialize` returning `null` means DELETE for a cookie\n // where it means \"omit the key\" for a search param. See\n // schema-bridge.ts §fromCookieSchema.\n return resolveCodecOrSchema('codec', codecOrSchema, 'cookie') as CookieCodec<T>;\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────\n\n/**\n * Define a typed cookie.\n *\n * ```ts\n * import { defineCookie } from '@timber-js/app/cookies';\n * import { z } from 'zod/v4';\n *\n * // httpOnly: false — client methods available\n * export const themeCookie = defineCookie('theme', {\n * codec: z.enum(['light', 'dark', 'system']).default('system'),\n * httpOnly: false,\n * maxAge: 60 * 60 * 24 * 365,\n * });\n *\n * // Server or client\n * const theme = themeCookie.get();\n * themeCookie.set('dark');\n *\n * // Client hook\n * const [theme, setTheme] = themeCookie.useCookie();\n *\n * // httpOnly: true (default) — server-only, no client methods\n * export const sessionCookie = defineCookie('session', {\n * codec: z.string(),\n * });\n * sessionCookie.get(); // works on server\n * sessionCookie.useCookie(); // TS error — httpOnly cookie\n * ```\n */\nexport function defineCookie<T, HttpOnly extends boolean = true>(\n name: string,\n options: DefineCookieOptions<T, HttpOnly>\n): HttpOnly extends false ? CookieDefinition<T> : ServerOnlyCookieDefinition<T> {\n const { codec: codecOrSchema, ...cookieOpts } = options;\n const codec = resolveCodec(codecOrSchema);\n const resolvedOptions: CookieOptions = { ...cookieOpts };\n const isHttpOnly = options.httpOnly !== false; // default true\n\n function getClientOpts(): ClientCookieOptions {\n return {\n path: resolvedOptions.path,\n domain: resolvedOptions.domain,\n maxAge: resolvedOptions.maxAge,\n expires: resolvedOptions.expires,\n sameSite: resolvedOptions.sameSite,\n secure: resolvedOptions.secure,\n };\n }\n\n const base: ServerOnlyCookieDefinition<T> = {\n name,\n options: resolvedOptions,\n codec,\n\n get(): T {\n const serverJar = tryGetServerCookieJar();\n if (serverJar) {\n return codec.parse(serverJar.get(name));\n }\n // Client path\n if (isHttpOnly) {\n throw new Error(\n `[timber] defineCookie('${name}').get() cannot be used with httpOnly cookies — ` +\n `the browser cannot access them. Set httpOnly: false to enable client access.`\n );\n }\n const raw = getCookieValue(name);\n return codec.parse(raw);\n },\n\n set(value: T): void {\n const serverJar = tryGetServerCookieJar();\n if (serverJar) {\n const serialized = codec.serialize(value);\n if (serialized === null) {\n serverJar.delete(name, {\n path: resolvedOptions.path,\n domain: resolvedOptions.domain,\n });\n } else {\n serverJar.set(name, serialized, resolvedOptions);\n }\n return;\n }\n // Client path\n if (isHttpOnly) {\n throw new Error(\n `[timber] defineCookie('${name}').set() cannot be used with httpOnly cookies — ` +\n `the browser cannot access them. Set httpOnly: false to enable client access.`\n );\n }\n const serialized = codec.serialize(value);\n if (serialized === null) {\n deleteClientCookie(name, getClientOpts());\n } else {\n setClientCookie(name, serialized, getClientOpts());\n }\n },\n\n delete(): void {\n const serverJar = tryGetServerCookieJar();\n if (serverJar) {\n serverJar.delete(name, {\n path: resolvedOptions.path,\n domain: resolvedOptions.domain,\n });\n return;\n }\n // Client path\n if (isHttpOnly) {\n throw new Error(\n `[timber] defineCookie('${name}').delete() cannot be used with httpOnly cookies — ` +\n `the browser cannot access them. Set httpOnly: false to enable client access.`\n );\n }\n deleteClientCookie(name, getClientOpts());\n },\n };\n\n if (isHttpOnly) {\n return base as HttpOnly extends false ? CookieDefinition<T> : ServerOnlyCookieDefinition<T>;\n }\n\n // httpOnly: false — add useCookie client hook\n const full: CookieDefinition<T> = {\n ...base,\n\n useCookie(): [T, (value: T) => void, () => void] {\n const clientOpts = getClientOpts();\n const [raw, setRaw, deleteRaw] = useRawCookie(name, clientOpts);\n const parsed = codec.parse(raw);\n\n const setTyped = (value: T): void => {\n const serialized = codec.serialize(value);\n if (serialized === null) {\n deleteRaw();\n } else {\n setRaw(serialized);\n }\n };\n\n return [parsed, setTyped, deleteRaw];\n },\n };\n\n return full as HttpOnly extends false ? CookieDefinition<T> : ServerOnlyCookieDefinition<T>;\n}\n","/**\n * jsonCookieCodec — Codec helper for storing JSON-serializable values in\n * cookies.\n *\n * The codec is intentionally minimal: `JSON.stringify` on serialize,\n * `JSON.parse` on parse. The framework handles the URL encoding /\n * decoding around it (see design/29-cookies.md §\"Encoding Contract\"):\n *\n * defineCookie.setCookie(value)\n * → codec.serialize: JSON.stringify → '{\"a\":1}'\n * → cookies().set: encodeURIComponent → '%7B%22a%22%3A1%7D'\n * → wire: Set-Cookie: prefs=%7B%22a%22%3A1%7D\n *\n * defineCookie.getCookie()\n * → wire: Cookie: prefs=%7B%22a%22%3A1%7D\n * → parseCookieHeader: decodeURIComponent → '{\"a\":1}'\n * → codec.parse: JSON.parse → { a: 1 }\n *\n * The same chain works on the client: `useCookie` auto-encodes on writes\n * and auto-decodes on reads, so `jsonCookieCodec` composes with both the\n * server `defineCookie` methods and the client `useCookie` hook with no\n * environment-specific branches.\n *\n * Parsing is total: any non-JSON value (or `undefined`) returns the\n * supplied default. This matches the \"never crash on user-controlled\n * cookie input\" semantics that `fromSchema` uses for typed search params.\n *\n * ```ts\n * import { defineCookie, jsonCookieCodec } from '@timber-js/app/cookies';\n *\n * interface Prefs { lang: string; fontSize: number }\n *\n * export const prefsCookie = defineCookie('prefs', {\n * codec: jsonCookieCodec<Prefs>({ lang: 'en', fontSize: 16 }),\n * httpOnly: false,\n * maxAge: 60 * 60 * 24 * 365,\n * });\n *\n * await prefsCookie.setCookie({ lang: 'fr', fontSize: 18 });\n * ```\n */\n\nimport type { Codec } from '../codec.ts';\n\n/**\n * Build a CookieCodec that JSON-encodes the value. The framework's\n * cookie write path then URL-encodes the JSON string into a valid\n * `cookie-octet` form, and the read path reverses both transforms.\n *\n * @param defaultValue - Returned by `parse` when the cookie is missing\n * or the stored value cannot be JSON-parsed. Optional — if omitted,\n * `parse` returns `undefined` on missing/malformed input.\n *\n * The default is **deep-cloned** on every fallback return via\n * `structuredClone`, so mutating the parsed result in one request\n * cannot leak into later requests that fall back to the same\n * default. This matters for long-lived server processes where a\n * codec is defined once at module load and shared across all\n * requests — without the clone, a user doing\n * `const prefs = prefsCookie.get(); prefs.lang = 'fr'` on a missing\n * cookie would mutate the module-level default and poison every\n * later fallback. See the \"shared mutable default\" regression test\n * in `tests/define-cookie.test.ts`.\n */\nexport function jsonCookieCodec<T>(defaultValue?: T): Codec<T> {\n // Resolve the fallback at call time, not capture time, so every\n // fallback return produces a fresh deep copy. structuredClone handles\n // nested objects, arrays, dates, maps, sets — everything\n // JSON-serializable plus more. For primitives and undefined,\n // structuredClone is effectively a no-op.\n const cloneDefault = (): T => {\n if (defaultValue === undefined || defaultValue === null) {\n return defaultValue as T;\n }\n // structuredClone is a Node built-in since Node 17, available in\n // all supported runtimes.\n return structuredClone(defaultValue);\n };\n\n return {\n parse(value: string | string[] | undefined): T {\n if (value === undefined || value === '') {\n return cloneDefault();\n }\n // Cookies are single-valued by name; defensively pick the last\n // entry if a Codec consumer somehow passes an array.\n const raw = Array.isArray(value) ? value[value.length - 1] : value;\n if (raw === undefined || raw === '') {\n return cloneDefault();\n }\n try {\n return JSON.parse(raw) as T;\n } catch {\n return cloneDefault();\n }\n },\n\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return JSON.stringify(value);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8CA,IAAM,4BAAY,IAAI,IAA2B;;AAGjD,SAAgB,eAAe,MAAkC;CAC/D,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAE5C,OADgB,YAAY,SAAS,MAC9B,CAAA,CAAQ;AACjB;;AAGA,SAAgB,iBAAiB,SAAuC;CACtE,IAAI,CAA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b,MAAM,YAAY,sBAAsB;GACxC,IAAI,WAAW;IACb,UAAU,OAAO,MAAM;KACrB,MAAM,gBAAgB;KACtB,QAAQ,gBAAgB;IAC1B,CAAC;IACD;GACF;GAEA,IAAI,YACF,MAAM,IAAI,MACR,0BAA0B,KAAK,gIAEjC;GAEF,mBAAmB,MAAM,cAAc,CAAC;EAC1C;CACF;CAEA,IAAI,YACF,OAAO;CAyBT,OAAO;EApBL,GAAG;EAEH,YAAiD;GAE/C,MAAM,CAAC,KAAK,QAAQ,aAAa,UAAa,MAD3B,cACiC,CAAU;GAC9D,MAAM,SAAS,MAAM,MAAM,GAAG;GAE9B,MAAM,YAAY,UAAmB;IACnC,MAAM,aAAa,MAAM,UAAU,KAAK;IACxC,IAAI,eAAe,MACjB,UAAU;SAEV,OAAO,UAAU;GAErB;GAEA,OAAO;IAAC;IAAQ;IAAU;GAAS;EACrC;CAGK;AACT;;;;;;;;;;;;;;;;;;;;;;;ACjPA,SAAgB,gBAAmB,cAA4B;CAM7D,MAAM,qBAAwB;EAC5B,IAAI,iBAAiB,KAAA,KAAa,iBAAiB,MACjD,OAAO;EAIT,OAAO,gBAAgB,YAAY;CACrC;CAEA,OAAO;EACL,MAAM,OAAyC;GAC7C,IAAI,UAAU,KAAA,KAAa,UAAU,IACnC,OAAO,aAAa;GAItB,MAAM,MAAM,MAAM,QAAQ,KAAK,IAAI,MAAM,MAAM,SAAS,KAAK;GAC7D,IAAI,QAAQ,KAAA,KAAa,QAAQ,IAC/B,OAAO,aAAa;GAEtB,IAAI;IACF,OAAO,KAAK,MAAM,GAAG;GACvB,QAAQ;IACN,OAAO,aAAa;GACtB;EACF;EAEA,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAET,OAAO,KAAK,UAAU,KAAK;EAC7B;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["React","useRawCookie"],"sources":["../../src/client/use-cookie.ts","../../src/cookies/define-cookie.ts","../../src/cookies/json-cookie.ts"],"sourcesContent":["/**\n * useCookie — reactive client-side cookie hook.\n *\n * Uses useSyncExternalStore for SSR-safe, reactive cookie access.\n * All components reading the same cookie name re-render on change.\n * No cross-tab sync (intentional — see design/29-cookies.md).\n *\n * See design/29-cookies.md §\"useCookie(name) Hook\"\n */\n\n// Namespace access, not `import { useSyncExternalStore }`. This module is\n// reachable from `@timber-js/app/cookies` — `defineCookie()` exposes both a\n// server `.get()` and a client `.useCookie()`, so the entry is isomorphic and\n// loads in the RSC environment. React's `react-server` export withholds\n// `useSyncExternalStore` exactly as it withholds `createContext`, and a *named*\n// ESM import of a missing export fails at module instantiation, before any\n// code runs. Same rule as `client/params-context.ts` (TIM-1297, TIM-1298).\nimport * as React from 'react';\nimport { parseCookie, stringifySetCookie } from 'cookie';\nimport { getSsrData } from './ssr-data.ts';\nimport { assertValidCookieName } from '../cookies/validation.ts';\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\nexport interface ClientCookieOptions {\n /** URL path scope. Default: '/'. */\n path?: string;\n /** Domain scope. Default: omitted (current domain). */\n domain?: string;\n /** Max age in seconds. */\n maxAge?: number;\n /** Expiration date. */\n expires?: Date;\n /** Cross-site policy. Default: 'lax'. */\n sameSite?: 'strict' | 'lax' | 'none';\n /** Only send over HTTPS. Default: true in production. */\n secure?: boolean;\n}\n\nexport type CookieSetter = (value: string, options?: ClientCookieOptions) => void;\n\n// ─── Module-Level Cookie Store ────────────────────────────────────────────\n\ntype Listener = () => void;\n\n/** Per-name subscriber sets. */\nconst listeners = new Map<string, Set<Listener>>();\n\n/** Parse a cookie name from document.cookie. */\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n const cookies = parseCookie(document.cookie);\n return cookies[name];\n}\n\n/** Serialize options into a cookie string suffix. */\nexport function serializeOptions(options?: ClientCookieOptions): string {\n if (!options) return '; Path=/; SameSite=Lax';\n const sameSite = options.sameSite ?? 'lax';\n // Build a Set-Cookie string via the cookie package, then strip the\n // `__placeholder__=` name=value prefix to get just the attributes.\n const full = stringifySetCookie({\n name: '__placeholder__',\n value: '',\n path: options.path ?? '/',\n domain: options.domain,\n maxAge: options.maxAge,\n expires: options.expires,\n sameSite,\n secure: options.secure,\n });\n // Strip everything up to and including the first \"; \"\n const idx = full.indexOf('; ');\n return idx >= 0 ? full.slice(idx) : '';\n}\n\n/** Notify all subscribers for a given cookie name. */\nfunction notify(name: string): void {\n const subs = listeners.get(name);\n if (subs) {\n for (const fn of subs) fn();\n }\n}\n\n/**\n * Notify useCookie subscribers that a cookie value changed.\n * Called by defineCookie's imperative client .set()/.delete() methods\n * so mounted useCookie() consumers re-render.\n *\n * @internal — framework use only\n */\nexport function notifyCookieChange(name: string): void {\n notify(name);\n}\n\n// ─── Hook ─────────────────────────────────────────────────────────────────\n\n/**\n * Reactive hook for reading/writing a client-side cookie.\n *\n * Returns `[value, setCookie, deleteCookie]`:\n * - `value`: current cookie value (string | undefined)\n * - `setCookie`: sets the cookie and triggers re-renders\n * - `deleteCookie`: deletes the cookie and triggers re-renders\n *\n * @param name - Cookie name.\n * @param defaultOptions - Default options for setCookie calls.\n */\nexport function useCookie(\n name: string,\n defaultOptions?: ClientCookieOptions\n): [value: string | undefined, setCookie: CookieSetter, deleteCookie: () => void] {\n const subscribe = (callback: Listener): (() => void) => {\n let subs = listeners.get(name);\n if (!subs) {\n subs = new Set();\n listeners.set(name, subs);\n }\n subs.add(callback);\n return () => {\n subs!.delete(callback);\n if (subs!.size === 0) listeners.delete(name);\n };\n };\n\n const getSnapshot = (): string | undefined => getCookieValue(name);\n const getServerSnapshot = (): string | undefined => {\n // During SSR, read the ALS-backed request cookies.\n const ssrData = getSsrData();\n if (ssrData) return ssrData.cookies.get(name);\n // During client hydration there is no SSR data (it lives in the server's\n // module graph), but React still calls getServerSnapshot. document.cookie\n // holds the same cookies the server rendered with, so reading it here\n // keeps the hydration render consistent with the server HTML.\n // See design/29-cookies.md §\"SSR Hydration\".\n return getCookieValue(name);\n };\n\n const value = React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n\n // Validate the name once per hook instance — names are typically\n // stable string literals, so this catches the bug at first render\n // rather than on every write. Throws via `assertValidCookieName` with\n // a precise error if the name violates RFC 7230 token rules.\n assertValidCookieName(name);\n\n const setCookie: CookieSetter = (newValue: string, options?: ClientCookieOptions) => {\n if (typeof newValue !== 'string') {\n throw new Error(\n `[timber] useCookie(${JSON.stringify(name)}): value must be a string, got ${typeof newValue}.\\n` +\n ` To store a JSON-serializable value, use defineCookie + jsonCookieCodec from\\n` +\n ` '@timber-js/app/cookies' and call its useCookie() hook instead.`\n );\n }\n const merged = { ...defaultOptions, ...options };\n // Auto-encode mirrors the server's `cookies().set()` contract:\n // values are URL-encoded on write, URL-decoded on read, so the\n // logical bytes round-trip losslessly. See design/29-cookies.md\n // §\"Encoding Contract\".\n document.cookie = `${name}=${encodeURIComponent(newValue)}${serializeOptions(merged)}`;\n notify(name);\n };\n\n const deleteCookie = (): void => {\n const path = defaultOptions?.path ?? '/';\n const domain = defaultOptions?.domain;\n let cookieStr = `${name}=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=${path}`;\n if (domain) cookieStr += `; Domain=${domain}`;\n document.cookie = cookieStr;\n notify(name);\n };\n\n return [value, setCookie, deleteCookie];\n}\n","/**\n * defineCookie — typed cookie definitions.\n *\n * Bundles name + codec + options into a reusable CookieDefinition<T>\n * with sync .get(), .set(), .delete() isomorphic methods (server + client)\n * and a .useCookie() client hook.\n *\n * Environment detection is call-time: on the server, getCookieJar() is\n * used directly (ALS-backed). On the client, document.cookie helpers\n * and the useCookie hook are used. No registration pattern — imports\n * resolve via the shims plugin (client bundle gets a stub for\n * @timber-js/app/server).\n *\n * Standard Schema objects (Zod, Valibot, ArkType) are auto-detected in\n * the codec option — no explicit fromSchema() wrapper needed.\n *\n * See design/29-cookies.md §\"Typed Cookies with Schema Validation\"\n */\n\nimport type { CookieOptions } from '../server/cookie-context.ts';\nimport type { ClientCookieOptions } from '../client/use-cookie.ts';\n\n// ─── Types ────────────────────────────────────────────────────────────────\n\nimport type { Codec } from '../codec.ts';\nimport type { StandardSchemaV1 } from '../schema-bridge.ts';\nimport { resolveCodecOrSchema } from '../schema-bridge.ts';\n\n/**\n * A codec that converts between string cookie values and typed values.\n * Type alias for the shared Codec<T> protocol.\n */\nexport type CookieCodec<T> = Codec<T>;\n\n/** Options for defineCookie: codec + CookieOptions merged. */\nexport interface DefineCookieOptions<T, HttpOnly extends boolean = boolean> extends CookieOptions {\n /**\n * Codec for parsing/serializing the cookie value.\n * Accepts a Codec<T> or a Standard Schema object (Zod, Valibot, ArkType)\n * which is auto-wrapped via fromSchema.\n */\n codec: CookieCodec<T> | StandardSchemaV1<T>;\n /**\n * Prevent client-side JS access. Default: true.\n * When true (or omitted), client methods (useCookie, get/set/delete on\n * client) are omitted from the return type and throw at runtime.\n */\n httpOnly?: HttpOnly;\n}\n\n/**\n * Server-only cookie definition. Returned when httpOnly is true or omitted.\n * Client methods are absent from the type — accessing them is a TS error.\n */\nexport interface ServerOnlyCookieDefinition<T> {\n readonly name: string;\n readonly options: CookieOptions;\n readonly codec: CookieCodec<T>;\n\n /** Read the typed value. Sync, isomorphic (server + client). */\n get(): T;\n /** Set the typed value. Sync, isomorphic (server + client). */\n set(value: T): void;\n /** Delete the cookie. Sync, isomorphic (server + client). */\n delete(): void;\n}\n\n/**\n * Full cookie definition with client methods. Returned when httpOnly: false.\n */\nexport interface CookieDefinition<T> extends ServerOnlyCookieDefinition<T> {\n /** Client: React hook for reading/writing this cookie. Returns [value, setter, deleter]. */\n useCookie(): [T, (value: T) => void, () => void];\n}\n\n// ─── Direct Imports (no registration) ─────────────────────────────────────\n//\n// Server: getCookieJar is imported from @timber-js/app/server. In the client\n// bundle, the shims plugin replaces @timber-js/app/server with a stub module\n// where getCookieJar throws on call. We detect the environment at call time\n// by trying getCookieJar() — if it throws the stub error, we fall through\n// to the client path.\n//\n// Client: useCookie, getCookieValue, notifyCookieChange\n// are imported from use-cookie.ts. These are safe in all environments (no\n// node:async_hooks dependency).\n//\n// Schema: fromSchema is a pure function — safe in all environments.\n\nimport { getCookieJar } from '@timber-js/app/server';\nimport {\n useCookie as useRawCookie,\n notifyCookieChange,\n getCookieValue,\n} from '../client/use-cookie.ts';\n\n// ─── Environment Detection ────────────────────────────────────────────────\n\n/**\n * Try to get the server cookie jar. Returns null if we're in the client\n * environment (stub throws) or if there's no request context.\n *\n * On the server, getCookieJar() throws \"outside of a request context\" if\n * called without an ALS store — this is a real error and is re-thrown.\n * The client stub throws a different message — that's caught and returns null.\n */\nfunction tryGetServerCookieJar(): ReturnType<typeof getCookieJar> | null {\n try {\n return getCookieJar();\n } catch (e) {\n // Server-side \"no request context\" error — re-throw as a real bug.\n if (e instanceof Error && e.message.includes('outside of a request context')) {\n throw e;\n }\n // Client stub error or other — fall through to client path.\n return null;\n }\n}\n\n// ─── Client Cookie Helpers ────────────────────────────────────────────────\n\n/** Write a cookie via document.cookie and notify useCookie subscribers. */\nfunction setClientCookie(name: string, value: string, options?: ClientCookieOptions): void {\n const parts: string[] = [`${name}=${encodeURIComponent(value)}`];\n const path = options?.path ?? '/';\n parts.push(`Path=${path}`);\n if (options?.domain) parts.push(`Domain=${options.domain}`);\n if (options?.maxAge !== undefined) parts.push(`Max-Age=${options.maxAge}`);\n if (options?.expires) parts.push(`Expires=${options.expires.toUTCString()}`);\n const sameSite = options?.sameSite ?? 'lax';\n parts.push(`SameSite=${sameSite.charAt(0).toUpperCase()}${sameSite.slice(1)}`);\n if (options?.secure) parts.push('Secure');\n document.cookie = parts.join('; ');\n notifyCookieChange(name);\n}\n\n/** Delete a cookie via document.cookie and notify useCookie subscribers. */\nfunction deleteClientCookie(name: string, options?: ClientCookieOptions): void {\n const path = options?.path ?? '/';\n const domain = options?.domain;\n let cookieStr = `${name}=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=${path}`;\n if (domain) cookieStr += `; Domain=${domain}`;\n document.cookie = cookieStr;\n notifyCookieChange(name);\n}\n\n// ─── Standard Schema Auto-Detection ───────────────────────────────────────\n\nfunction resolveCodec<T>(codecOrSchema: CookieCodec<T> | StandardSchemaV1<T>): CookieCodec<T> {\n // 'cookie', not 'search': a cookie carries one string per name, so the\n // repeated-key array shape the search bridge tolerates does not exist\n // here — and `serialize` returning `null` means DELETE for a cookie\n // where it means \"omit the key\" for a search param. See\n // schema-bridge.ts §fromCookieSchema.\n return resolveCodecOrSchema('codec', codecOrSchema, 'cookie') as CookieCodec<T>;\n}\n\n// ─── Factory ──────────────────────────────────────────────────────────────\n\n/**\n * Define a typed cookie.\n *\n * ```ts\n * import { defineCookie } from '@timber-js/app/cookies';\n * import { z } from 'zod/v4';\n *\n * // httpOnly: false — client methods available\n * export const themeCookie = defineCookie('theme', {\n * codec: z.enum(['light', 'dark', 'system']).default('system'),\n * httpOnly: false,\n * maxAge: 60 * 60 * 24 * 365,\n * });\n *\n * // Server or client\n * const theme = themeCookie.get();\n * themeCookie.set('dark');\n *\n * // Client hook\n * const [theme, setTheme] = themeCookie.useCookie();\n *\n * // httpOnly: true (default) — server-only, no client methods\n * export const sessionCookie = defineCookie('session', {\n * codec: z.string(),\n * });\n * sessionCookie.get(); // works on server\n * sessionCookie.useCookie(); // TS error — httpOnly cookie\n * ```\n */\nexport function defineCookie<T, HttpOnly extends boolean = true>(\n name: string,\n options: DefineCookieOptions<T, HttpOnly>\n): HttpOnly extends false ? CookieDefinition<T> : ServerOnlyCookieDefinition<T> {\n const { codec: codecOrSchema, ...cookieOpts } = options;\n const codec = resolveCodec(codecOrSchema);\n const resolvedOptions: CookieOptions = { ...cookieOpts };\n const isHttpOnly = options.httpOnly !== false; // default true\n\n function getClientOpts(): ClientCookieOptions {\n return {\n path: resolvedOptions.path,\n domain: resolvedOptions.domain,\n maxAge: resolvedOptions.maxAge,\n expires: resolvedOptions.expires,\n sameSite: resolvedOptions.sameSite,\n secure: resolvedOptions.secure,\n };\n }\n\n const base: ServerOnlyCookieDefinition<T> = {\n name,\n options: resolvedOptions,\n codec,\n\n get(): T {\n const serverJar = tryGetServerCookieJar();\n if (serverJar) {\n return codec.parse(serverJar.get(name));\n }\n // Client path\n if (isHttpOnly) {\n throw new Error(\n `[timber] defineCookie('${name}').get() cannot be used with httpOnly cookies — ` +\n `the browser cannot access them. Set httpOnly: false to enable client access.`\n );\n }\n const raw = getCookieValue(name);\n return codec.parse(raw);\n },\n\n set(value: T): void {\n const serverJar = tryGetServerCookieJar();\n if (serverJar) {\n const serialized = codec.serialize(value);\n if (serialized === null) {\n serverJar.delete(name, {\n path: resolvedOptions.path,\n domain: resolvedOptions.domain,\n });\n } else {\n serverJar.set(name, serialized, resolvedOptions);\n }\n return;\n }\n // Client path\n if (isHttpOnly) {\n throw new Error(\n `[timber] defineCookie('${name}').set() cannot be used with httpOnly cookies — ` +\n `the browser cannot access them. Set httpOnly: false to enable client access.`\n );\n }\n const serialized = codec.serialize(value);\n if (serialized === null) {\n deleteClientCookie(name, getClientOpts());\n } else {\n setClientCookie(name, serialized, getClientOpts());\n }\n },\n\n delete(): void {\n const serverJar = tryGetServerCookieJar();\n if (serverJar) {\n serverJar.delete(name, {\n path: resolvedOptions.path,\n domain: resolvedOptions.domain,\n });\n return;\n }\n // Client path\n if (isHttpOnly) {\n throw new Error(\n `[timber] defineCookie('${name}').delete() cannot be used with httpOnly cookies — ` +\n `the browser cannot access them. Set httpOnly: false to enable client access.`\n );\n }\n deleteClientCookie(name, getClientOpts());\n },\n };\n\n if (isHttpOnly) {\n return base as HttpOnly extends false ? CookieDefinition<T> : ServerOnlyCookieDefinition<T>;\n }\n\n // httpOnly: false — add useCookie client hook\n const full: CookieDefinition<T> = {\n ...base,\n\n useCookie(): [T, (value: T) => void, () => void] {\n const clientOpts = getClientOpts();\n const [raw, setRaw, deleteRaw] = useRawCookie(name, clientOpts);\n const parsed = codec.parse(raw);\n\n const setTyped = (value: T): void => {\n const serialized = codec.serialize(value);\n if (serialized === null) {\n deleteRaw();\n } else {\n setRaw(serialized);\n }\n };\n\n return [parsed, setTyped, deleteRaw];\n },\n };\n\n return full as HttpOnly extends false ? CookieDefinition<T> : ServerOnlyCookieDefinition<T>;\n}\n","/**\n * jsonCookieCodec — Codec helper for storing JSON-serializable values in\n * cookies.\n *\n * The codec is intentionally minimal: `JSON.stringify` on serialize,\n * `JSON.parse` on parse. The framework handles the URL encoding /\n * decoding around it (see design/29-cookies.md §\"Encoding Contract\"):\n *\n * defineCookie.setCookie(value)\n * → codec.serialize: JSON.stringify → '{\"a\":1}'\n * → cookies().set: encodeURIComponent → '%7B%22a%22%3A1%7D'\n * → wire: Set-Cookie: prefs=%7B%22a%22%3A1%7D\n *\n * defineCookie.getCookie()\n * → wire: Cookie: prefs=%7B%22a%22%3A1%7D\n * → parseCookieHeader: decodeURIComponent → '{\"a\":1}'\n * → codec.parse: JSON.parse → { a: 1 }\n *\n * The same chain works on the client: `useCookie` auto-encodes on writes\n * and auto-decodes on reads, so `jsonCookieCodec` composes with both the\n * server `defineCookie` methods and the client `useCookie` hook with no\n * environment-specific branches.\n *\n * Parsing is total: any non-JSON value (or `undefined`) returns the\n * supplied default. This matches the \"never crash on user-controlled\n * cookie input\" semantics that `fromSchema` uses for typed search params.\n *\n * ```ts\n * import { defineCookie, jsonCookieCodec } from '@timber-js/app/cookies';\n *\n * interface Prefs { lang: string; fontSize: number }\n *\n * export const prefsCookie = defineCookie('prefs', {\n * codec: jsonCookieCodec<Prefs>({ lang: 'en', fontSize: 16 }),\n * httpOnly: false,\n * maxAge: 60 * 60 * 24 * 365,\n * });\n *\n * await prefsCookie.setCookie({ lang: 'fr', fontSize: 18 });\n * ```\n */\n\nimport type { Codec } from '../codec.ts';\n\n/**\n * Build a CookieCodec that JSON-encodes the value. The framework's\n * cookie write path then URL-encodes the JSON string into a valid\n * `cookie-octet` form, and the read path reverses both transforms.\n *\n * @param defaultValue - Returned by `parse` when the cookie is missing\n * or the stored value cannot be JSON-parsed. Optional — if omitted,\n * `parse` returns `undefined` on missing/malformed input.\n *\n * The default is **deep-cloned** on every fallback return via\n * `structuredClone`, so mutating the parsed result in one request\n * cannot leak into later requests that fall back to the same\n * default. This matters for long-lived server processes where a\n * codec is defined once at module load and shared across all\n * requests — without the clone, a user doing\n * `const prefs = prefsCookie.get(); prefs.lang = 'fr'` on a missing\n * cookie would mutate the module-level default and poison every\n * later fallback. See the \"shared mutable default\" regression test\n * in `tests/define-cookie.test.ts`.\n */\nexport function jsonCookieCodec<T>(defaultValue?: T): Codec<T> {\n // Resolve the fallback at call time, not capture time, so every\n // fallback return produces a fresh deep copy. structuredClone handles\n // nested objects, arrays, dates, maps, sets — everything\n // JSON-serializable plus more. For primitives and undefined,\n // structuredClone is effectively a no-op.\n const cloneDefault = (): T => {\n if (defaultValue === undefined || defaultValue === null) {\n return defaultValue as T;\n }\n // structuredClone is a Node built-in since Node 17, available in\n // all supported runtimes.\n return structuredClone(defaultValue);\n };\n\n return {\n parse(value: string | string[] | undefined): T {\n if (value === undefined || value === '') {\n return cloneDefault();\n }\n // Cookies are single-valued by name; defensively pick the last\n // entry if a Codec consumer somehow passes an array.\n const raw = Array.isArray(value) ? value[value.length - 1] : value;\n if (raw === undefined || raw === '') {\n return cloneDefault();\n }\n try {\n return JSON.parse(raw) as T;\n } catch {\n return cloneDefault();\n }\n },\n\n serialize(value: T): string | null {\n if (value === null || value === undefined) {\n return null;\n }\n return JSON.stringify(value);\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8CA,IAAM,4BAAY,IAAI,IAA2B;;AAGjD,SAAgB,eAAe,MAAkC;CAC/D,IAAI,OAAO,aAAa,aAAa,OAAO,KAAA;CAE5C,OADgB,YAAY,SAAS,MAC9B,CAAA,CAAQ;AACjB;;AAGA,SAAgB,iBAAiB,SAAuC;CACtE,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,WAAW,QAAQ,YAAY;CAGrC,MAAM,OAAO,mBAAmB;EAC9B,MAAM;EACN,OAAO;EACP,MAAM,QAAQ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CAAC;IACD;GACF;GAEA,IAAI,YACF,MAAM,IAAI,MACR,0BAA0B,KAAK,gIAEjC;GAEF,mBAAmB,MAAM,cAAc,CAAC;EAC1C;CACF;CAEA,IAAI,YACF,OAAO;CAyBT,OAAO;EApBL,GAAG;EAEH,YAAiD;GAE/C,MAAM,CAAC,KAAK,QAAQ,aAAaC,UAAa,MAD3B,cACiC,CAAU;GAC9D,MAAM,SAAS,MAAM,MAAM,GAAG;GAE9B,MAAM,YAAY,UAAmB;IACnC,MAAM,aAAa,MAAM,UAAU,KAAK;IACxC,IAAI,eAAe,MACjB,UAAU;SAEV,OAAO,UAAU;GAErB;GAEA,OAAO;IAAC;IAAQ;IAAU;GAAS;EACrC;CAGK;AACT;;;;;;;;;;;;;;;;;;;;;;;ACjPA,SAAgB,gBAAmB,cAA4B;CAM7D,MAAM,qBAAwB;EAC5B,IAAI,iBAAiB,KAAA,KAAa,iBAAiB,MACjD,OAAO;EAIT,OAAO,gBAAgB,YAAY;CACrC;CAEA,OAAO;EACL,MAAM,OAAyC;GAC7C,IAAI,UAAU,KAAA,KAAa,UAAU,IACnC,OAAO,aAAa;GAItB,MAAM,MAAM,MAAM,QAAQ,KAAK,IAAI,MAAM,MAAM,SAAS,KAAK;GAC7D,IAAI,QAAQ,KAAA,KAAa,QAAQ,IAC/B,OAAO,aAAa;GAEtB,IAAI;IACF,OAAO,KAAK,MAAM,GAAG;GACvB,QAAQ;IACN,OAAO,aAAa;GACtB;EACF;EAEA,UAAU,OAAyB;GACjC,IAAI,UAAU,QAAQ,UAAU,KAAA,GAC9B,OAAO;GAET,OAAO,KAAK,UAAU,KAAK;EAC7B;CACF;AACF"}
package/dist/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { a as reportConfigErrors, i as formatMissingPeers, n as timberDevServer, o as validateConfig, r as checkPeerDependencies } from "./_chunks/dev-server-B8zsT-ee.js";
2
2
  import { i as resolveRenderTimeoutMs } from "./_chunks/render-timeout-DOf_BBcO.js";
3
3
  import { t as writeFileAtomic } from "./_chunks/write-file-atomic-D1qWqHb4.js";
4
- import { a as isDynamicMetadataExtension } from "./_chunks/metadata-routes-B3XJNyIH.js";
5
4
  import { d as collectInterceptionRewrites, l as getPrerenderExport, n as scanRoutes } from "./_chunks/scanner-Cb3fSjAC.js";
6
5
  import { v as swallow } from "./_chunks/logger-CbLdcy-W.js";
7
6
  import { c as buildDirToRouteMap, n as formatConventionWarnings, o as flushCodegenWrites, r as lintConventions, s as writeRouteCodegen, t as checkAppDirExists } from "./_chunks/convention-lint-ByKJ6aqD.js";
@@ -2832,7 +2831,7 @@ function encode(decoded) {
2832
2831
  return writer.flush();
2833
2832
  }
2834
2833
  //#endregion
2835
- //#region ../../node_modules/.pnpm/magic-string@1.4.1/node_modules/magic-string/dist/index.mjs
2834
+ //#region ../../node_modules/.pnpm/magic-string@1.4.3/node_modules/magic-string/dist/index.mjs
2836
2835
  var BitSet = class BitSet {
2837
2836
  constructor(arg) {
2838
2837
  this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
@@ -2926,7 +2925,7 @@ var Chunk = class Chunk {
2926
2925
  this.outro = "";
2927
2926
  this.end = index;
2928
2927
  if (this.edited) {
2929
- newChunk.edit("", false);
2928
+ newChunk.edit("", false, true);
2930
2929
  this.content = "";
2931
2930
  } else this.content = originalBefore;
2932
2931
  newChunk.next = this.next;
@@ -3841,7 +3840,7 @@ var MagicString = class MagicString {
3841
3840
  while (chunk !== last) {
3842
3841
  if (chunk.next !== this.byStart.get(chunk.end)) throw new MagicStringError("cannot overwrite across a split point");
3843
3842
  chunk = chunk.next;
3844
- chunk.edit("", false);
3843
+ chunk.edit("", false, !overwrite);
3845
3844
  }
3846
3845
  first.edit(content, storeName, !overwrite);
3847
3846
  } else {
@@ -3888,7 +3887,7 @@ var MagicString = class MagicString {
3888
3887
  * Content appended or prepended at positions strictly inside the range is removed with it, while
3889
3888
  * content attached at `start` or `end` is preserved — use `s.overwrite(start, end, '')` to remove
3890
3889
  * the range including its edge inserts.
3891
- * Removing the same content twice, or making removals that partially overlap, will cause an error.
3890
+ * Repeated removals and removals with partially overlapping ranges are allowed.
3892
3891
  */
3893
3892
  remove(start, end) {
3894
3893
  start = start + this.offset;
@@ -4170,10 +4169,16 @@ var MagicString = class MagicString {
4170
4169
  * @internal
4171
4170
  */
4172
4171
  _hasRemovedContent(start, end) {
4173
- let chunk = this.firstChunk;
4174
- while (chunk) {
4175
- if (chunk.content === "" && chunk.start < end && chunk.end > start) return true;
4176
- chunk = chunk.next;
4172
+ let chunk = this.byStart.get(start);
4173
+ if (!chunk) {
4174
+ chunk = this.lastSearchedChunk;
4175
+ const searchForward = start >= chunk.end;
4176
+ while (chunk && !chunk.contains(start)) chunk = searchForward ? this.byStart.get(chunk.end) : this.byEnd.get(chunk.start);
4177
+ if (chunk) this.lastSearchedChunk = chunk;
4178
+ }
4179
+ while (chunk && chunk.start < end) {
4180
+ if (chunk.content === "") return true;
4181
+ chunk = this.byStart.get(chunk.end);
4177
4182
  }
4178
4183
  return false;
4179
4184
  }
@@ -4189,8 +4194,8 @@ var MagicString = class MagicString {
4189
4194
  if (this._hasRemovedContent(match.index, match.index + match[0].length)) return false;
4190
4195
  const replacement = getReplacement(match, this.original);
4191
4196
  if (replacement === match[0]) return true;
4192
- if (match[0].length === 0) this.appendRight(match.index, replacement);
4193
- else this.overwrite(match.index, match.index + match[0].length, replacement);
4197
+ if (match[0].length === 0) this.appendRight(match.index - this.offset, replacement);
4198
+ else this.overwrite(match.index - this.offset, match.index + match[0].length - this.offset, replacement);
4194
4199
  return true;
4195
4200
  };
4196
4201
  if (searchValue.global) {
@@ -4217,8 +4222,8 @@ var MagicString = class MagicString {
4217
4222
  if (typeof replacement === "function") replacement = replacement(string, index, original);
4218
4223
  else replacement = expandReplacement(replacement, string, index, original, [], void 0);
4219
4224
  if (string !== replacement) {
4220
- if (string.length === 0) this.appendRight(index, replacement);
4221
- else this.overwrite(index, index + string.length, replacement);
4225
+ if (string.length === 0) this.appendRight(index - this.offset, replacement);
4226
+ else this.overwrite(index - this.offset, index + string.length - this.offset, replacement);
4222
4227
  }
4223
4228
  break;
4224
4229
  }
@@ -4237,8 +4242,9 @@ var MagicString = class MagicString {
4237
4242
  const stringLength = string.length;
4238
4243
  if (stringLength === 0) {
4239
4244
  for (let index = 0; index <= original.length; index += 1) {
4245
+ if (this._hasRemovedContent(index, index)) continue;
4240
4246
  const _replacement = typeof replacement === "function" ? replacement("", index, original) : expandReplacement(replacement, "", index, original, [], void 0);
4241
- if (_replacement !== "") this.appendRight(index, _replacement);
4247
+ if (_replacement !== "") this.appendRight(index - this.offset, _replacement);
4242
4248
  }
4243
4249
  return this;
4244
4250
  }
@@ -4246,7 +4252,7 @@ var MagicString = class MagicString {
4246
4252
  if (this._hasRemovedContent(index, index + stringLength)) continue;
4247
4253
  const previous = original.slice(index, index + stringLength);
4248
4254
  const _replacement = typeof replacement === "function" ? replacement(previous, index, original) : expandReplacement(replacement, previous, index, original, [], void 0);
4249
- if (previous !== _replacement) this.overwrite(index, index + stringLength, _replacement);
4255
+ if (previous !== _replacement) this.overwrite(index - this.offset, index + stringLength - this.offset, _replacement);
4250
4256
  }
4251
4257
  return this;
4252
4258
  }
@@ -5358,21 +5364,18 @@ function collectTransitiveBundleDeps(chunk, chunksByFileName, base) {
5358
5364
  return result;
5359
5365
  }
5360
5366
  /**
5361
- * Walk the route tree and compute short content hashes for metadata route files
5362
- * (opengraph-image, icon, apple-icon) used for cache-busting
5363
- * the auto-linked URLs in <head>.
5367
+ * Walk the route tree and compute short content hashes for metadata route
5368
+ * files, used to cache-bust the auto-linked opengraph-image URL in <head>.
5369
+ * A dynamic handler (.ts/.tsx) is hashed by its source: its output can depend
5370
+ * on runtime data too, but the source is the best build-time signal there is.
5371
+ * An unreadable file gets no hash, and the link falls back to the per-startup
5372
+ * nonce.
5364
5373
  */
5365
5374
  function computeMetadataRouteHashes(node) {
5366
5375
  const hashes = {};
5367
- if (node.metadataRoutes) for (const [baseName, file] of Object.entries(node.metadataRoutes)) if (!isDynamicMetadataExtension(baseName, file.extension)) try {
5368
- const content = readFileSync(file.filePath);
5369
- const hash = createHash("sha256").update(content).digest("hex").slice(0, 8);
5370
- hashes[file.filePath] = hash;
5371
- } catch {}
5372
- else try {
5376
+ for (const file of Object.values(node.metadataRoutes ?? {})) try {
5373
5377
  const content = readFileSync(file.filePath);
5374
- const hash = createHash("sha256").update(content).digest("hex").slice(0, 8);
5375
- hashes[file.filePath] = hash;
5378
+ hashes[file.filePath] = createHash("sha256").update(content).digest("hex").slice(0, 8);
5376
5379
  } catch {}
5377
5380
  for (const child of node.children) Object.assign(hashes, computeMetadataRouteHashes(child));
5378
5381
  for (const slot of Object.values(node.slots)) Object.assign(hashes, computeMetadataRouteHashes(slot));