@kayjs/kay 2.0.0-beta.1 → 2.0.0-beta.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kayjs/kay",
3
- "version": "2.0.0-beta.1",
3
+ "version": "2.0.0-beta.2",
4
4
  "description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
5
5
  "license": "MIT",
6
6
  "homepage": "https://kayjs.kaynooo.fr",
@@ -5,11 +5,12 @@ import type { IslandBinding } from '../compiler/index'
5
5
  import type { BuildPluginTarget, KayPlugin } from '../plugins/index'
6
6
  import type { BuildCache, ModuleGraph } from './graph'
7
7
  import type { ActionsByFile, IslandPlan } from './islands'
8
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
9
- import { isAbsolute, join, resolve } from 'node:path'
8
+ import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
9
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
10
10
  import { compileDom, compileSsr } from '../compiler/index'
11
11
  import { readsPrivateEnv, SERVER_ONLY_FILTER } from '../compiler/server-only'
12
- import { isOutsideRoot, isTsFile, relPosix } from './files'
12
+ import { formatBunBuildLogs, isOutsideRoot, isTsFile, relPosix } from './files'
13
+ import { stampFiles, stampsMatch } from './graph'
13
14
  import { islandKey } from './islands'
14
15
  import { resolveKaySpecifier } from './resolve'
15
16
 
@@ -21,6 +22,7 @@ export interface BundleEnv {
21
22
  assetPrefix: string
22
23
  minify: boolean
23
24
  isDev: boolean
25
+ analyze?: boolean | undefined
24
26
  graph: ModuleGraph
25
27
  cache: BuildCache | undefined
26
28
  plugins: KayPlugin[]
@@ -28,6 +30,40 @@ export interface BundleEnv {
28
30
  islands: IslandPlan
29
31
  }
30
32
 
33
+ function linkOrCopyFile(src: string, dst: string): void {
34
+ mkdirSync(dirname(dst), { recursive: true })
35
+ try {
36
+ linkSync(src, dst)
37
+ }
38
+ catch {
39
+ copyFileSync(src, dst)
40
+ }
41
+ }
42
+
43
+ function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly string[]): boolean {
44
+ if (!existsSync(srcDir))
45
+ return false
46
+ if (relFiles !== undefined) {
47
+ for (const rel of relFiles) {
48
+ const from = join(srcDir, rel)
49
+ if (!existsSync(from))
50
+ return false
51
+ linkOrCopyFile(from, join(dstDir, rel))
52
+ }
53
+ return true
54
+ }
55
+ let count = 0
56
+ for (const ent of readdirSync(srcDir, { recursive: true, withFileTypes: true })) {
57
+ if (!ent.isFile())
58
+ continue
59
+ const from = join(ent.parentPath, ent.name)
60
+ const rel = relative(srcDir, from)
61
+ linkOrCopyFile(from, join(dstDir, rel))
62
+ count++
63
+ }
64
+ return count > 0
65
+ }
66
+
31
67
  const KAY_SPECIFIER_FILTER = /^(?:@kayjs\/)?kay(?:\/.*)?$/
32
68
  const TS_FILTER = /\.(?:ts|tsx)$/
33
69
  const KAY_SCOPE_RE = /^@kayjs\//
@@ -111,10 +147,68 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
111
147
  metafile: undefined,
112
148
  }
113
149
  const pluginClientEntries = env.plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
114
- if (islands.targets.size === 0 && pluginClientEntries.length === 0 && standaloneCss.length === 0)
150
+ if (islands.targets.size === 0 && pluginClientEntries.length === 0 && standaloneCss.length === 0) {
151
+ if (cache !== undefined)
152
+ cache.lastClient = undefined
115
153
  return result
154
+ }
116
155
 
117
156
  const transforms = pluginTransforms(env.plugins)
157
+ // A mode computed at runtime may be any of them, so it keeps both loaders.
158
+ let hasDeferredHydrate = false
159
+ let hasClientOnlyHydrate = false
160
+ for (const analysis of graph.analyses.values()) {
161
+ for (const mode of [analysis.defaultHydrate, ...analysis.hydrateModes]) {
162
+ if (mode === 'client' || mode === '*')
163
+ hasClientOnlyHydrate = true
164
+ if (mode !== undefined && mode !== 'load' && mode !== 'client')
165
+ hasDeferredHydrate = true
166
+ }
167
+ }
168
+
169
+ const envDefines = publicEnvDefines()
170
+ const clientSignature = cache !== undefined
171
+ ? JSON.stringify({
172
+ minify: env.minify,
173
+ assetPrefix,
174
+ isDev: env.isDev,
175
+ transforms: transforms.key,
176
+ hasDeferredHydrate,
177
+ hasClientOnlyHydrate,
178
+ pluginClientEntries,
179
+ standaloneCss: [...standaloneCss].sort(),
180
+ islands: [...islands.targets.entries()]
181
+ .sort(([a], [b]) => a.localeCompare(b))
182
+ .map(([k, t]) => [k, t.id, t.file, t.exportName, t.defaultHydrate ?? '']),
183
+ actions: [...actionsByFile.entries()]
184
+ .sort(([a], [b]) => a.localeCompare(b))
185
+ .map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
186
+ envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
187
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
188
+ })
189
+ : ''
190
+
191
+ if (
192
+ cache !== undefined
193
+ && !env.analyze
194
+ && cache.lastClient !== undefined
195
+ && cache.lastClient.signature === clientSignature
196
+ && stampsMatch(cache.lastClient.inputStamps)
197
+ && reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles)
198
+ ) {
199
+ cache.stats.clientSkips++
200
+ cache.lastClient.clientDir = clientDir
201
+ return {
202
+ islandChunks: new Map(cache.lastClient.islandChunks),
203
+ srcCssToUrl: new Map(cache.lastClient.srcCssToUrl),
204
+ islandCssUrl: new Map(cache.lastClient.islandCssUrl),
205
+ assetFiles: [...cache.lastClient.assetFiles],
206
+ styleUrls: [...cache.lastClient.styleUrls],
207
+ runtimeScript: cache.lastClient.runtimeScript,
208
+ metafile: undefined,
209
+ }
210
+ }
211
+
118
212
  // Bun hashes an entry's path into its chunk name, so the entries sit at one path per app: a dev rebuild or a static stage then keeps every unchanged chunk name.
119
213
  const entriesDir = join(root, 'node_modules/.cache/kay/entries')
120
214
  mkdirSync(entriesDir, { recursive: true })
@@ -129,18 +223,6 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
129
223
  const entryPoints: string[] = []
130
224
  const islandEntryToKey = new Map<string, string>()
131
225
 
132
- // A mode computed at runtime may be any of them, so it keeps both loaders.
133
- let hasDeferredHydrate = false
134
- let hasClientOnlyHydrate = false
135
- for (const analysis of graph.analyses.values()) {
136
- for (const mode of [analysis.defaultHydrate, ...analysis.hydrateModes]) {
137
- if (mode === 'client' || mode === '*')
138
- hasClientOnlyHydrate = true
139
- if (mode !== undefined && mode !== 'load' && mode !== 'client')
140
- hasDeferredHydrate = true
141
- }
142
- }
143
-
144
226
  if (islands.targets.size > 0 || pluginClientEntries.length > 0) {
145
227
  const runtimeLines: string[] = []
146
228
  if (islands.targets.size > 0) {
@@ -168,7 +250,6 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
168
250
  }
169
251
 
170
252
  const clientLeaks = new Set<string>()
171
- const envDefines = publicEnvDefines()
172
253
  const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
173
254
  const clientPlugin: BunPlugin = {
174
255
  name: 'kay-v2-client',
@@ -235,13 +316,15 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
235
316
  catch (err) {
236
317
  if (clientLeaks.size > 0)
237
318
  throw clientLeakError(clientLeaks)
319
+ if (err instanceof AggregateError && err.errors.length > 0)
320
+ throw new Error(`kay build (client) failed:\n${formatBunBuildLogs(err.errors, env.root)}`)
238
321
  throw err
239
322
  }
240
323
 
241
324
  if (clientLeaks.size > 0)
242
325
  throw clientLeakError(clientLeaks)
243
326
  if (!clientResult.success) {
244
- const msgs = clientResult.logs.map(l => l.message).join('\n')
327
+ const msgs = formatBunBuildLogs(clientResult.logs, env.root)
245
328
  throw new Error(`kay build (client) failed:\n${msgs}`)
246
329
  }
247
330
 
@@ -314,6 +397,31 @@ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Prom
314
397
  else if (output.kind === 'entry-point' && relFile.startsWith('runtime-'))
315
398
  result.runtimeScript = url
316
399
  }
400
+
401
+ if (cache !== undefined) {
402
+ cache.stats.clientBuilds++
403
+ const inputFiles = new Set<string>([...standaloneCss, ...pluginClientEntries])
404
+ for (const inKey of Object.keys(metafile?.inputs ?? {})) {
405
+ const abs = resolveMetaPath(inKey)
406
+ // Skip generated entry shims and stubbed action files (whose signature tracks exported action names/URLs, not server body).
407
+ if (abs.startsWith(entriesDir))
408
+ continue
409
+ if (actionsByFile.has(abs) && !graph.analyses.get(abs)?.isInteractive)
410
+ continue
411
+ inputFiles.add(abs)
412
+ }
413
+ cache.lastClient = {
414
+ signature: clientSignature,
415
+ clientDir,
416
+ inputStamps: stampFiles(inputFiles),
417
+ islandChunks: new Map(result.islandChunks),
418
+ srcCssToUrl: new Map(result.srcCssToUrl),
419
+ islandCssUrl: new Map(result.islandCssUrl),
420
+ assetFiles: [...result.assetFiles],
421
+ styleUrls: [...result.styleUrls],
422
+ runtimeScript: result.runtimeScript,
423
+ }
424
+ }
317
425
  return result
318
426
  }
319
427
 
@@ -322,6 +430,34 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
322
430
  const transforms = pluginTransforms(env.plugins)
323
431
  const externalOutDir = isOutsideRoot(root, outDir)
324
432
 
433
+ const serverSignature = cache !== undefined
434
+ ? JSON.stringify({
435
+ serverRoot,
436
+ assetPrefix: env.assetPrefix,
437
+ isDev: env.isDev,
438
+ transforms: transforms.key,
439
+ entries: [...entries].sort(),
440
+ islandChunks: [...islandChunks.entries()].sort(([a], [b]) => a.localeCompare(b)),
441
+ reach: [...islands.reach].sort(),
442
+ bindings: [...islands.pageBindings.entries()]
443
+ .sort(([a], [b]) => a.localeCompare(b))
444
+ .map(([f, map]) => [f, [...map.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([l, t]) => [l, t.id, t.defaultHydrate ?? ''])]),
445
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
446
+ })
447
+ : ''
448
+
449
+ if (
450
+ cache !== undefined
451
+ && cache.lastServer !== undefined
452
+ && cache.lastServer.signature === serverSignature
453
+ && stampsMatch(cache.lastServer.inputStamps)
454
+ && reuseDirFiles(cache.lastServer.serverDir, serverDir)
455
+ ) {
456
+ cache.stats.serverSkips++
457
+ cache.lastServer.serverDir = serverDir
458
+ return
459
+ }
460
+
325
461
  // Whether a file renders components, directly or through what it imports: such packages are bundled so Kay's SSR compiler transforms them.
326
462
  const tsxReach = new Map<string, boolean>()
327
463
  const reachesTsx = (file: string, visiting = new Set<string>()): boolean => {
@@ -374,6 +510,14 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
374
510
  }
375
511
  if (resolved.endsWith('.tsx') || reachesTsx(resolved))
376
512
  return { path: resolved }
513
+ if (env.isDev && isTsFile(resolved)) {
514
+ try {
515
+ const real = realpathSync(resolved)
516
+ if (!real.includes('/node_modules/') && !real.includes('\\node_modules\\'))
517
+ return { path: resolved }
518
+ }
519
+ catch {}
520
+ }
377
521
  if (externalOutDir)
378
522
  return { path: resolved, external: true }
379
523
  return undefined
@@ -420,23 +564,52 @@ export async function buildServer(env: BundleEnv, entries: string[], serverRoot:
420
564
  },
421
565
  }
422
566
 
423
- const serverResult = await Bun.build({
424
- entrypoints: entries,
425
- outdir: serverDir,
426
- root: serverRoot,
427
- target: 'bun',
428
- format: 'esm',
429
- splitting: true,
430
- packages: 'external',
431
- minify: false,
432
- define: {
433
- 'process.env.NODE_ENV': 'process.env.NODE_ENV',
434
- },
435
- plugins: [serverPlugin, ...pluginBunPlugins(env, 'server')],
436
- })
567
+ let serverResult: Awaited<ReturnType<typeof Bun.build>>
568
+ try {
569
+ serverResult = await Bun.build({
570
+ entrypoints: entries,
571
+ outdir: serverDir,
572
+ root: serverRoot,
573
+ target: 'bun',
574
+ format: 'esm',
575
+ splitting: true,
576
+ packages: 'external',
577
+ minify: false,
578
+ metafile: cache !== undefined,
579
+ define: {
580
+ 'process.env.NODE_ENV': 'process.env.NODE_ENV',
581
+ },
582
+ plugins: [serverPlugin, ...pluginBunPlugins(env, 'server')],
583
+ })
584
+ }
585
+ catch (err) {
586
+ if (err instanceof AggregateError && err.errors.length > 0)
587
+ throw new Error(`kay build (server) failed:\n${formatBunBuildLogs(err.errors, env.root)}`)
588
+ throw err
589
+ }
437
590
 
438
591
  if (!serverResult.success) {
439
- const msgs = serverResult.logs.map(l => l.message).join('\n')
592
+ const msgs = formatBunBuildLogs(serverResult.logs, env.root)
440
593
  throw new Error(`kay build (server) failed:\n${msgs}`)
441
594
  }
595
+
596
+ if (cache !== undefined) {
597
+ cache.stats.serverBuilds++
598
+ const inputFiles = new Set<string>(entries)
599
+ for (const inKey of Object.keys(serverResult.metafile?.inputs ?? {})) {
600
+ const fromCwd = resolve(process.cwd(), inKey)
601
+ const abs = existsSync(fromCwd) ? fromCwd : resolve(serverDir, inKey)
602
+ if (!existsSync(abs))
603
+ continue
604
+ // Plain `.css` stylesheets are bundled exclusively by `buildClient`; CSS edits must not trigger a server rebuild.
605
+ if (abs.endsWith('.css') && !abs.endsWith('.module.css'))
606
+ continue
607
+ inputFiles.add(abs)
608
+ }
609
+ cache.lastServer = {
610
+ signature: serverSignature,
611
+ serverDir,
612
+ inputStamps: stampFiles(inputFiles),
613
+ }
614
+ }
442
615
  }
@@ -5,6 +5,7 @@ import type { BunPlugin } from 'bun'
5
5
  import type { BuildManifest } from './index'
6
6
  import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
7
7
  import { join } from 'node:path'
8
+ import { formatBunBuildLogs } from './files'
8
9
 
9
10
  export interface CompileExecutableOptions {
10
11
  root: string
@@ -43,6 +44,7 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
43
44
  for (const l of r.layouts) addMod(l)
44
45
  for (const m of r.middlewares) addMod(m)
45
46
  }
47
+ if (manifest.rootLayoutFile) addMod(manifest.rootLayoutFile)
46
48
  if (manifest.errorFile) addMod(manifest.errorFile)
47
49
  if (manifest.notFoundFile) addMod(manifest.notFoundFile)
48
50
  for (const a of manifest.actions) {
@@ -50,7 +52,9 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
50
52
  for (const m of a.middlewares) addMod(m)
51
53
  }
52
54
 
53
- const configPath = join(root, 'kay.config.ts')
55
+ const configPath = manifest.configFile !== undefined
56
+ ? join(outDir, manifest.configFile)
57
+ : join(root, 'kay.config.ts')
54
58
  const hasConfig = existsSync(configPath)
55
59
  if (hasConfig)
56
60
  imports.push(`import _kayConfig from ${JSON.stringify(configPath)};`)
@@ -96,22 +100,23 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
96
100
  }
97
101
  }
98
102
 
99
- const cfgSpread = hasConfig ? `...pickRuntimeConfig(_kayConfig), ` : ''
103
+ const cfgExpr = hasConfig
104
+ ? `resolveServerConfig(_kayConfig, { assetPrefix: ${JSON.stringify(assetPrefix)} })`
105
+ : `{ assetPrefix: ${JSON.stringify(assetPrefix)} }`
100
106
 
101
107
  const code = [
102
108
  ...imports,
103
- `import { createServerFromEmbedded, pickRuntimeConfig } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
109
+ `import { createServerFromEmbedded, resolveServerConfig } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
104
110
  `const manifest = ${JSON.stringify(manifest)};`,
105
111
  `const modules = { ${modEntries.join(', ')} };`,
106
112
  `const assets = { ${embeddedAssets.join(', ')} };`,
107
113
  `const publicAssets = { ${embeddedPublic.join(', ')} };`,
108
114
  `const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
109
- `const prerendered = {};`,
110
115
  `const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
111
116
  `const port = Number(process.env.PORT || ${hasConfig ? '_kayConfig?.port || ' : ''}3000);`,
112
117
  `const hostname = process.env.HOST || undefined;`,
113
118
  `if (Bun.argv.includes('--health')) { const probeHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${probeHost}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
114
- `const app = await createServerFromEmbedded({ ${cfgSpread}manifest, modules, assets, publicAssets, publicEtags, prerendered, prerenderedFiles, assetPrefix: ${JSON.stringify(assetPrefix)} });`,
119
+ `const app = await createServerFromEmbedded({ ...${cfgExpr}, manifest, modules, assets, publicAssets, publicEtags, prerenderedFiles });`,
115
120
  `const server = app.serve(port, hostname);`,
116
121
  `console.log(\`kay server listening on http://\${hostname ?? 'localhost'}:\${server.port}\`);`,
117
122
  ].join('\n')
@@ -127,14 +132,22 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
127
132
  })
128
133
  },
129
134
  }
130
- const res = await Bun.build({
131
- entrypoints: [entryPath],
132
- compile: { outfile },
133
- minify: true,
134
- plugins: [kayResolvePlugin, ...bunPlugins],
135
- })
135
+ let res: Awaited<ReturnType<typeof Bun.build>>
136
+ try {
137
+ res = await Bun.build({
138
+ entrypoints: [entryPath],
139
+ compile: { outfile },
140
+ minify: true,
141
+ plugins: [kayResolvePlugin, ...bunPlugins],
142
+ })
143
+ }
144
+ catch (err) {
145
+ if (err instanceof AggregateError && err.errors.length > 0)
146
+ throw new Error(`kay build --compile failed:\n${formatBunBuildLogs(err.errors, root)}`)
147
+ throw err
148
+ }
136
149
  if (!res.success) {
137
- const msgs = res.logs.map(l => l.message).join('\n')
150
+ const msgs = formatBunBuildLogs(res.logs, root)
138
151
  throw new Error(`kay build --compile failed:\n${msgs}`)
139
152
  }
140
153
  }
@@ -134,3 +134,41 @@ export function precompressFile(abs: string, minBytes: number): void {
134
134
  if (gz.byteLength < raw.byteLength)
135
135
  writeFileSync(`${abs}.gz`, gz)
136
136
  }
137
+
138
+ export interface BunBuildLogLike {
139
+ message?: string | undefined
140
+ level?: string | undefined
141
+ position?: {
142
+ file?: string | undefined
143
+ line?: number | undefined
144
+ column?: number | undefined
145
+ length?: number | undefined
146
+ lineText?: string | undefined
147
+ } | null | undefined
148
+ }
149
+
150
+ /** Formats Bun `BuildMessage` / `ResolveMessage` logs with `file:line:col: error|warning: <message>` and a source line frame. */
151
+ export function formatBunBuildLogs(logs: readonly unknown[], root?: string): string {
152
+ return logs.map((raw) => {
153
+ if (raw === null || typeof raw !== 'object')
154
+ return String(raw)
155
+ const log = raw as BunBuildLogLike
156
+ const msg = typeof log.message === 'string' && log.message.length > 0 ? log.message : String(raw)
157
+ const pos = log.position
158
+ if (pos && typeof pos.file === 'string' && pos.file.length > 0 && typeof pos.line === 'number') {
159
+ const file = root !== undefined && isAbsolute(pos.file) ? relPosix(root, pos.file) : pos.file
160
+ const col = typeof pos.column === 'number' && pos.column > 0 ? pos.column : 1
161
+ const severity = log.level === 'warning' ? 'warning' : 'error'
162
+ const header = `${file}:${pos.line}:${col}: ${severity}: ${msg}`
163
+ if (typeof pos.lineText === 'string') {
164
+ const lineStr = String(pos.line)
165
+ const pad = ' '.repeat(lineStr.length)
166
+ const maxSpan = Math.max(1, pos.lineText.length - (col - 1))
167
+ const len = typeof pos.length === 'number' && pos.length > 0 ? Math.min(pos.length, maxSpan) : 1
168
+ return `${header}\n ${lineStr} | ${pos.lineText}\n ${pad} | ${' '.repeat(Math.max(0, col - 1))}${'^'.repeat(len)}`
169
+ }
170
+ return header
171
+ }
172
+ return msg
173
+ }).join('\n')
174
+ }
@@ -1,20 +1,49 @@
1
1
  // The module graph of one build: every .ts/.tsx file reachable from the routes, analyzed once (and reused across `kay dev` rebuilds while mtime and size match).
2
2
 
3
3
  import type { ModuleAnalysis } from '../compiler/index'
4
- import { readFileSync, statSync } from 'node:fs'
4
+ import { existsSync, readFileSync, statSync } from 'node:fs'
5
5
  import { analyzeModule } from '../compiler/index'
6
6
  import { isTsFile } from './files'
7
7
  import { resolveImportPath } from './resolve'
8
8
 
9
- interface FileStamp {
9
+ export interface FileStamp {
10
10
  mtimeMs: number
11
11
  size: number
12
12
  }
13
13
 
14
+ export interface CachedClientBuild {
15
+ signature: string
16
+ clientDir: string
17
+ inputStamps: Map<string, FileStamp>
18
+ islandChunks: Map<string, string>
19
+ srcCssToUrl: Map<string, string>
20
+ islandCssUrl: Map<string, string>
21
+ assetFiles: string[]
22
+ styleUrls: string[]
23
+ runtimeScript: string | undefined
24
+ }
25
+
26
+ export interface CachedServerBuild {
27
+ signature: string
28
+ serverDir: string
29
+ inputStamps: Map<string, FileStamp>
30
+ }
31
+
32
+ export interface BuildCacheStats {
33
+ clientBuilds: number
34
+ clientSkips: number
35
+ serverBuilds: number
36
+ serverSkips: number
37
+ }
38
+
14
39
  export interface BuildCache {
15
40
  analyses: Map<string, FileStamp & { code: string, analysis: ModuleAnalysis }>
16
41
  domCompiled: Map<string, FileStamp & { key?: string | undefined, code: string }>
17
42
  ssrCompiled: Map<string, FileStamp & { key: string, code: string }>
43
+ lastClient?: CachedClientBuild | undefined
44
+ lastServer?: CachedServerBuild | undefined
45
+ watchedFiles: Set<string>
46
+ stats: BuildCacheStats
18
47
  }
19
48
 
20
49
  export function createBuildCache(): BuildCache {
@@ -22,6 +51,8 @@ export function createBuildCache(): BuildCache {
22
51
  analyses: new Map(),
23
52
  domCompiled: new Map(),
24
53
  ssrCompiled: new Map(),
54
+ watchedFiles: new Set(),
55
+ stats: { clientBuilds: 0, clientSkips: 0, serverBuilds: 0, serverSkips: 0 },
25
56
  }
26
57
  }
27
58
 
@@ -29,6 +60,40 @@ export function clearBuildCache(cache: BuildCache): void {
29
60
  cache.analyses.clear()
30
61
  cache.domCompiled.clear()
31
62
  cache.ssrCompiled.clear()
63
+ cache.lastClient = undefined
64
+ cache.lastServer = undefined
65
+ cache.watchedFiles.clear()
66
+ }
67
+
68
+ export function stampFiles(files: Iterable<string>): Map<string, FileStamp> {
69
+ const out = new Map<string, FileStamp>()
70
+ for (const file of files) {
71
+ if (out.has(file))
72
+ continue
73
+ try {
74
+ const st = statSync(file)
75
+ if (st.isFile())
76
+ out.set(file, { mtimeMs: st.mtimeMs, size: st.size })
77
+ }
78
+ catch {}
79
+ }
80
+ return out
81
+ }
82
+
83
+ export function stampsMatch(inputStamps: ReadonlyMap<string, FileStamp>): boolean {
84
+ for (const [file, prev] of inputStamps) {
85
+ if (!existsSync(file))
86
+ return false
87
+ try {
88
+ const st = statSync(file)
89
+ if (st.mtimeMs !== prev.mtimeMs || st.size !== prev.size)
90
+ return false
91
+ }
92
+ catch {
93
+ return false
94
+ }
95
+ }
96
+ return true
32
97
  }
33
98
 
34
99
  const MAX_REEXPORT_DEPTH = 8