@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +20 -11
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +231 -1296
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +298 -79
  18. package/src/cli/new.ts +67 -35
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +822 -629
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +390 -324
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +291 -76
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +157 -84
  30. package/src/dom/index.ts +154 -33
  31. package/src/dom/island.ts +117 -39
  32. package/src/dom/loop.ts +34 -21
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +120 -17
  37. package/src/reactivity/index.ts +250 -157
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +37 -12
  40. package/src/server/action.ts +217 -74
  41. package/src/server/compress.ts +155 -56
  42. package/src/server/cookies.ts +59 -22
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +201 -33
  45. package/src/server/index.ts +964 -737
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +27 -8
  48. package/src/server/security.ts +87 -39
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +96 -10
  52. package/src/ssr/index.ts +225 -56
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -0
  55. package/src/unrenderable.ts +35 -0
@@ -0,0 +1,136 @@
1
+ // File-system helpers of the build: directory walks, the outDir safety check, and precompressed sidecars.
2
+
3
+ import type { Dirent } from 'node:fs'
4
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
7
+ import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
8
+
9
+ const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
10
+ const BACKSLASH_RE = /\\/g
11
+ const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm'])
12
+
13
+ /** `relative(from, to)` with forward slashes, the form manifests and messages use. */
14
+ export function relPosix(from: string, to: string): string {
15
+ return relative(from, to).replace(BACKSLASH_RE, '/')
16
+ }
17
+
18
+ export function isTsFile(file: string): boolean {
19
+ return file.endsWith('.tsx') || file.endsWith('.ts')
20
+ }
21
+
22
+ /** The size of a file in bytes, or undefined when it does not exist. */
23
+ export function fileSize(file: string): number | undefined {
24
+ try {
25
+ return statSync(file).size
26
+ }
27
+ catch {
28
+ return undefined
29
+ }
30
+ }
31
+
32
+ interface WalkOptions {
33
+ skipDir?: (name: string) => boolean
34
+ keep?: (entry: Dirent) => boolean
35
+ }
36
+
37
+ /** Every kept file under `dir`, depth first; a missing `dir` is empty. */
38
+ export function walkFiles(dir: string, options: WalkOptions = {}, out: string[] = []): string[] {
39
+ if (!existsSync(dir))
40
+ return out
41
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
42
+ const full = join(dir, entry.name)
43
+ if (entry.isDirectory()) {
44
+ if (options.skipDir?.(entry.name) !== true)
45
+ walkFiles(full, options, out)
46
+ }
47
+ else if (options.keep === undefined || options.keep(entry)) {
48
+ out.push(full)
49
+ }
50
+ }
51
+ return out
52
+ }
53
+
54
+ /** Route sources: `.ts`/`.tsx` outside `_`-prefixed folders, without declarations and tests. */
55
+ export function walkRoutes(dir: string): string[] {
56
+ return walkFiles(dir, {
57
+ skipDir: name => name.startsWith('_'),
58
+ keep: entry => isTsFile(entry.name) && !entry.name.endsWith('.d.ts') && !TEST_FILE_RE.test(entry.name),
59
+ })
60
+ }
61
+
62
+ export function walkAllFiles(dir: string): string[] {
63
+ return walkFiles(dir, { keep: entry => entry.isFile() })
64
+ }
65
+
66
+ function isOutside(base: string, target: string): boolean {
67
+ const rel = relative(base, target)
68
+ return rel === '..' || rel.startsWith('../') || rel.startsWith('..\\') || isAbsolute(rel)
69
+ }
70
+
71
+ function isStrictDescendant(base: string, target: string): boolean {
72
+ return relative(base, target) !== '' && !isOutside(base, target)
73
+ }
74
+
75
+ export function isOutsideRoot(root: string, outDir: string): boolean {
76
+ const rel = relative(root, outDir)
77
+ return rel !== '' && (rel.startsWith('..') || isAbsolute(rel))
78
+ }
79
+
80
+ export function assertSafeOutDir(root: string, outDir: string, routesDir: string, publicDir: string): void {
81
+ // Refuse filesystem root, home dir, tmpdir root, or root/ancestors of root
82
+ if (dirname(outDir) === outDir || outDir === tmpdir() || outDir === resolve(process.env.HOME ?? '\0')) {
83
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — cannot wipe a root or shared system directory.`)
84
+ }
85
+ if (!isOutside(outDir, root)) {
86
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — outDir cannot be or contain project root "${root}".`)
87
+ }
88
+ if (existsSync(outDir)) {
89
+ try {
90
+ const realRoot = realpathSync(root)
91
+ const realOut = realpathSync(outDir)
92
+ if (dirname(realOut) === realOut || !isOutside(realOut, realRoot)) {
93
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is or contains project root "${realRoot}".`)
94
+ }
95
+ }
96
+ catch (err) {
97
+ if (err instanceof Error && err.message.startsWith('kay build: refusing unsafe outDir'))
98
+ throw err
99
+ }
100
+ }
101
+ const protectedTargets: [string, string][] = [
102
+ ['src', resolve(root, 'src')],
103
+ ['routesDir', routesDir],
104
+ ['publicDir', publicDir],
105
+ ['kay.config.ts', resolve(root, 'kay.config.ts')],
106
+ ['package.json', resolve(root, 'package.json')],
107
+ ]
108
+ for (const [label, target] of protectedTargets) {
109
+ if (!isOutside(outDir, target)) {
110
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — it equals or contains protected path ${label} ("${target}").`)
111
+ }
112
+ }
113
+ // If outDir is outside root (e.g. an external temp build dir), refuse it if it looks like another project directory.
114
+ if (!isStrictDescendant(root, outDir) && existsSync(outDir)) {
115
+ for (const marker of ['package.json', 'kay.config.ts', 'src']) {
116
+ if (existsSync(join(outDir, marker))) {
117
+ throw new Error(`kay build: refusing unsafe external outDir "${outDir}" — it contains "${marker}".`)
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ /** Writes `.br` and `.gz` sidecars next to a compressible file of at least `minBytes`, when they come out smaller. */
124
+ export function precompressFile(abs: string, minBytes: number): void {
125
+ if (!COMPRESSIBLE_EXTS.has(extname(abs).toLowerCase()))
126
+ return
127
+ const raw = readFileSync(abs)
128
+ if (raw.byteLength < minBytes)
129
+ return
130
+ const br = brotliCompressSync(raw, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 6 } })
131
+ if (br.byteLength < raw.byteLength)
132
+ writeFileSync(`${abs}.br`, br)
133
+ const gz = Bun.gzipSync(raw, { level: 9 })
134
+ if (gz.byteLength < raw.byteLength)
135
+ writeFileSync(`${abs}.gz`, gz)
136
+ }
@@ -0,0 +1,158 @@
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
+
3
+ import type { ModuleAnalysis } from '../compiler/index'
4
+ import { readFileSync, statSync } from 'node:fs'
5
+ import { analyzeModule } from '../compiler/index'
6
+ import { isTsFile } from './files'
7
+ import { resolveImportPath } from './resolve'
8
+
9
+ interface FileStamp {
10
+ mtimeMs: number
11
+ size: number
12
+ }
13
+
14
+ export interface BuildCache {
15
+ analyses: Map<string, FileStamp & { code: string, analysis: ModuleAnalysis }>
16
+ domCompiled: Map<string, FileStamp & { key?: string | undefined, code: string }>
17
+ ssrCompiled: Map<string, FileStamp & { key: string, code: string }>
18
+ }
19
+
20
+ export function createBuildCache(): BuildCache {
21
+ return {
22
+ analyses: new Map(),
23
+ domCompiled: new Map(),
24
+ ssrCompiled: new Map(),
25
+ }
26
+ }
27
+
28
+ export function clearBuildCache(cache: BuildCache): void {
29
+ cache.analyses.clear()
30
+ cache.domCompiled.clear()
31
+ cache.ssrCompiled.clear()
32
+ }
33
+
34
+ const MAX_REEXPORT_DEPTH = 8
35
+
36
+ export class ModuleGraph {
37
+ readonly analyses = new Map<string, ModuleAnalysis>()
38
+ private readonly sources = new Map<string, string>()
39
+ private readonly stamps = new Map<string, FileStamp>()
40
+ private readonly resolved = new Map<string, string | undefined>()
41
+ private readonly deps = new Map<string, string[]>()
42
+
43
+ constructor(private readonly cache?: BuildCache) {}
44
+
45
+ /** The file's mtime and size; only tracked when a cache is in use. */
46
+ stamp(file: string): FileStamp | undefined {
47
+ const known = this.stamps.get(file)
48
+ if (known !== undefined || this.cache === undefined)
49
+ return known
50
+ try {
51
+ const st = statSync(file)
52
+ const stamp = { mtimeMs: st.mtimeMs, size: st.size }
53
+ this.stamps.set(file, stamp)
54
+ return stamp
55
+ }
56
+ catch {
57
+ return undefined
58
+ }
59
+ }
60
+
61
+ /** The text of a file, read once per build. */
62
+ source(file: string): string {
63
+ let code = this.sources.get(file)
64
+ if (code === undefined) {
65
+ code = readFileSync(file, 'utf8')
66
+ this.sources.set(file, code)
67
+ }
68
+ return code
69
+ }
70
+
71
+ /** `resolveImportPath`, remembered for the build. */
72
+ resolve(from: string, specifier: string): string | undefined {
73
+ const key = `${from}\0${specifier}`
74
+ if (this.resolved.has(key))
75
+ return this.resolved.get(key)
76
+ const target = resolveImportPath(from, specifier)
77
+ this.resolved.set(key, target)
78
+ return target
79
+ }
80
+
81
+ /** The .ts/.tsx modules a loaded file imports or re-exports from. */
82
+ localDeps(file: string): string[] {
83
+ let list = this.deps.get(file)
84
+ if (list === undefined) {
85
+ list = []
86
+ const analysis = this.analyses.get(file)
87
+ for (const { source } of [...(analysis?.imports ?? []), ...(analysis?.reexports ?? [])]) {
88
+ const target = this.resolve(file, source)
89
+ if (target !== undefined && isTsFile(target))
90
+ list.push(target)
91
+ }
92
+ if (analysis !== undefined)
93
+ this.deps.set(file, list)
94
+ }
95
+ return list
96
+ }
97
+
98
+ /** Analyzes `file` and everything it imports. */
99
+ load(file: string): ModuleAnalysis {
100
+ const existing = this.analyses.get(file)
101
+ if (existing !== undefined)
102
+ return existing
103
+ const stamp = this.stamp(file)
104
+ const cached = stamp === undefined ? undefined : this.cache?.analyses.get(file)
105
+ let analysis: ModuleAnalysis
106
+ if (cached !== undefined && cached.mtimeMs === stamp!.mtimeMs && cached.size === stamp!.size) {
107
+ analysis = cached.analysis
108
+ this.sources.set(file, cached.code)
109
+ }
110
+ else {
111
+ const code = this.source(file)
112
+ analysis = analyzeModule(file, code)
113
+ if (this.cache !== undefined && stamp !== undefined)
114
+ this.cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis })
115
+ }
116
+ this.analyses.set(file, analysis)
117
+ for (const dep of this.localDeps(file))
118
+ this.load(dep)
119
+ return analysis
120
+ }
121
+
122
+ /** Follows `export { x } from './y'` and `export * from './y'` chains to the module that declares the export. */
123
+ exportTarget(file: string, exportName: string, depth = 0, seen = new Set<string>()): { file: string, exportName: string } {
124
+ if (depth > MAX_REEXPORT_DEPTH)
125
+ return { file, exportName }
126
+ const key = `${file}\0${exportName}`
127
+ if (seen.has(key))
128
+ return { file, exportName }
129
+ seen.add(key)
130
+
131
+ const analysis = this.load(file)
132
+ const direct = analysis.reexports.find(r => r.exported === exportName)
133
+ if (direct !== undefined) {
134
+ const next = this.resolve(file, direct.source)
135
+ if (next !== undefined && isTsFile(next))
136
+ return this.exportTarget(next, direct.local, depth + 1, seen)
137
+ }
138
+
139
+ if (analysis.exportedNames.includes(exportName))
140
+ return { file, exportName }
141
+
142
+ // Follow `export * from './y'` barrel re-exports (named exports only, per ESM spec `export *` never re-exports `default`).
143
+ if (exportName !== 'default') {
144
+ for (const re of analysis.reexports) {
145
+ if (re.exported !== '*')
146
+ continue
147
+ const next = this.resolve(file, re.source)
148
+ if (next === undefined || !isTsFile(next))
149
+ continue
150
+ const candidate = this.exportTarget(next, exportName, depth + 1, seen)
151
+ if (this.load(candidate.file).exportedNames.includes(candidate.exportName))
152
+ return candidate
153
+ }
154
+ }
155
+
156
+ return { file, exportName }
157
+ }
158
+ }