@kayjs/kay 2.0.0-alpha.4 → 2.0.0-alpha.5

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-alpha.4",
3
+ "version": "2.0.0-alpha.5",
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",
@@ -7,7 +7,7 @@ import type { BunPlugin } from 'bun'
7
7
  import type { IslandBinding, ModuleAnalysis } from '../compiler/index'
8
8
  import type { BuildPluginContext, KayPlugin } from '../plugins/index'
9
9
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
10
- import { basename, dirname, extname, join, relative, resolve } from 'node:path'
10
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
11
11
  import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
12
12
  import { analyzeModule, compileDom, compileSsr } from '../compiler/index'
13
13
  import { loadConfig } from '../plugins/index'
@@ -86,10 +86,22 @@ export function resolveKaySpecifier(specifier: string): string | undefined {
86
86
  return join(KAY_SRC_ROOT, 'ssr/index.ts')
87
87
  if (specifier === 'kay/server' || specifier === '@kayjs/kay/server')
88
88
  return join(KAY_SRC_ROOT, 'server/index.ts')
89
+ if (specifier === 'kay/compiler' || specifier === '@kayjs/kay/compiler')
90
+ return join(KAY_SRC_ROOT, 'compiler/index.ts')
91
+ if (specifier === 'kay/build' || specifier === '@kayjs/kay/build')
92
+ return join(KAY_SRC_ROOT, 'build/index.ts')
93
+ if (specifier === 'kay/dev' || specifier === '@kayjs/kay/dev')
94
+ return join(KAY_SRC_ROOT, 'dev/index.ts')
89
95
  if (specifier === 'kay/test' || specifier === '@kayjs/kay/test')
90
96
  return join(KAY_SRC_ROOT, 'test/index.ts')
91
- if (specifier === 'kay/jsx-runtime' || specifier === 'kay/jsx-dev-runtime')
97
+ if (
98
+ specifier === 'kay/jsx-runtime'
99
+ || specifier === 'kay/jsx-dev-runtime'
100
+ || specifier === '@kayjs/kay/jsx-runtime'
101
+ || specifier === '@kayjs/kay/jsx-dev-runtime'
102
+ ) {
92
103
  return join(KAY_SRC_ROOT, 'jsx-runtime.ts')
104
+ }
93
105
  return undefined
94
106
  }
95
107
 
@@ -509,13 +521,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
509
521
  const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles]
510
522
  const serverRoot = standaloneActionFiles.length > 0 ? root : routesDir
511
523
 
524
+ const relOut = relative(root, outDir)
525
+ const outDirOutsideRoot = relOut !== '' && (relOut.startsWith('..') || isAbsolute(relOut))
526
+ const EXTERNAL_KAY_SUBPATHS = new Set([
527
+ 'kay/build',
528
+ '@kayjs/kay/build',
529
+ 'kay/compiler',
530
+ '@kayjs/kay/compiler',
531
+ 'kay/dev',
532
+ '@kayjs/kay/dev',
533
+ 'kay/test',
534
+ '@kayjs/kay/test',
535
+ ])
536
+
512
537
  const runServerBuild = async (): Promise<void> => {
513
538
  const serverPlugin: BunPlugin = {
514
539
  name: 'kay-v2-server',
515
540
  setup(b) {
516
541
  b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
517
542
  const resolved = resolveKaySpecifier(args.path)
518
- return resolved !== undefined ? { path: resolved } : undefined
543
+ if (resolved === undefined)
544
+ return undefined
545
+ return EXTERNAL_KAY_SUBPATHS.has(args.path) ? { path: resolved, external: true } : { path: resolved }
519
546
  })
520
547
  b.onResolve({ filter: /^@kayjs\// }, (args) => {
521
548
  try {
@@ -525,6 +552,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
525
552
  return undefined
526
553
  }
527
554
  })
555
+ if (outDirOutsideRoot) {
556
+ b.onResolve({ filter: /^[^./]/ }, (args) => {
557
+ if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || isAbsolute(args.path))
558
+ return undefined
559
+ let resolved: string | undefined
560
+ try {
561
+ resolved = Bun.resolveSync(args.path, args.resolveDir || root)
562
+ }
563
+ catch {
564
+ try {
565
+ resolved = Bun.resolveSync(args.path, root)
566
+ }
567
+ catch {
568
+ return undefined
569
+ }
570
+ }
571
+ const isInsideNodeModules = resolved.includes('/node_modules/') || resolved.includes('\\node_modules\\')
572
+ const relToRoot = relative(root, resolved)
573
+ const isLocalSource = !isInsideNodeModules && !relToRoot.startsWith('..') && !isAbsolute(relToRoot)
574
+ return isLocalSource ? undefined : { path: resolved, external: true }
575
+ })
576
+ }
528
577
  b.onLoad({ filter: /\.tsx$/ }, (args) => {
529
578
  const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
530
579
  const analysis = analyses.get(args.path)
package/src/cli/new.ts CHANGED
@@ -15,7 +15,7 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
15
15
  const root = resolve(targetDir)
16
16
  const name = basename(root).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'kay-app'
17
17
  const template: ScaffoldTemplate = options.template ?? 'minimal'
18
- const kayVersion = options.kayVersion ?? '^2.0.0-alpha.4'
18
+ const kayVersion = options.kayVersion ?? '^2.0.0-alpha.5'
19
19
 
20
20
  if (existsSync(root) && readdirSync(root).length > 0 && !options.force)
21
21
  throw new Error(`kay new: directory "${root}" is not empty (pass --force to overwrite)`)
@@ -254,6 +254,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
254
254
  hasNestedJsx = true
255
255
  return false
256
256
  }
257
+ return undefined
257
258
  })
258
259
  if (!hasNestedJsx)
259
260
  return rewriteFreeIdentifiers(code, node, scopeRewrites)
@@ -268,6 +269,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
268
269
  sub.replace(child.start - offset, child.end - offset, compileRootJsx(child, scopeRewrites))
269
270
  return false
270
271
  }
272
+ return undefined
271
273
  })
272
274
 
273
275
  // Also rewrite non-JSX free identifiers by applying identifier rewrites on non-JSX spans
@@ -374,12 +376,6 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
374
376
  }
375
377
 
376
378
  function compileElementTree(rootEl: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
377
- interface NodeRef {
378
- varName: string
379
- parentVar: string
380
- childIndex: number
381
- }
382
-
383
379
  const ops: string[] = []
384
380
  const rootVar = freshVar('_e')
385
381
  const childRefs = new Map<string, string>() // "parentVar:index" -> varName
@@ -843,6 +839,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
843
839
  fnHasJsx = true
844
840
  return false
845
841
  }
842
+ return undefined
846
843
  })
847
844
  if (!fnHasJsx)
848
845
  return
@@ -888,6 +885,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
888
885
  stmtHasJsx = true
889
886
  return false
890
887
  }
888
+ return undefined
891
889
  })
892
890
  if (!stmtHasJsx) {
893
891
  const active = new Map<string, string>()
@@ -904,6 +902,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
904
902
  editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
905
903
  return false
906
904
  }
905
+ return undefined
907
906
  })
908
907
  }
909
908
  if (stmt.type === 'VariableDeclaration') {
@@ -918,6 +917,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
918
917
  editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
919
918
  return false
920
919
  }
920
+ return undefined
921
921
  })
922
922
  }
923
923
  }
@@ -931,6 +931,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
931
931
  editor.replace(node.start, node.end, compileRootJsx(node, new Map()))
932
932
  return false
933
933
  }
934
+ return undefined
934
935
  })
935
936
 
936
937
  // Emit imports, hoisted templates, and delegated events
@@ -9,6 +9,14 @@ export function escapeStaticText(str: string): string {
9
9
  return str.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
10
10
  }
11
11
 
12
+ const RAW_TEXT_ELEMENTS = new Set(['style', 'script'])
13
+ const CLOSE_STYLE_RE = /<\/(style)/gi
14
+ const CLOSE_SCRIPT_RE = /<\/(script)/gi
15
+
16
+ function escapeRawText(str: string, tag: 'style' | 'script'): string {
17
+ return str.replace(tag === 'script' ? CLOSE_SCRIPT_RE : CLOSE_STYLE_RE, '<\\/$1')
18
+ }
19
+
12
20
  const VOID_ELEMENTS = new Set([
13
21
  'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
14
22
  'link', 'meta', 'param', 'source', 'track', 'wbr',
@@ -171,6 +179,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
171
179
  hasNestedJsx = true
172
180
  return false
173
181
  }
182
+ return undefined
174
183
  })
175
184
  if (!hasNestedJsx)
176
185
  return code.slice(node.start, node.end)
@@ -182,6 +191,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
182
191
  sub.replace(child.start - offset, child.end - offset, compileRootJsx(child))
183
192
  return false
184
193
  }
194
+ return undefined
185
195
  })
186
196
  return sub.toString()
187
197
  }
@@ -253,7 +263,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
253
263
  if (innerHtmlExpr !== undefined)
254
264
  parts.pushExpr(innerHtmlExpr)
255
265
  else
256
- emitChildrenIntoBuffer(node.children as AstNode[], bufVar, parts, flushParts, pushStmt)
266
+ emitChildrenIntoBuffer(node.children as AstNode[], bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
257
267
  parts.pushStatic(`</${tag}>`)
258
268
  }
259
269
 
@@ -263,6 +273,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
263
273
  parts: StringParts,
264
274
  flushParts: () => void,
265
275
  pushStmt: (stmt: string) => void,
276
+ rawTextTag?: 'style' | 'script',
266
277
  ): void {
267
278
  const meaningful = children.filter((c) => {
268
279
  if (c.type === 'JSXText')
@@ -277,7 +288,8 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
277
288
  const child = meaningful[i]!
278
289
  const isLast = i === meaningful.length - 1
279
290
  if (child.type === 'JSXText') {
280
- parts.pushStatic(cleanJsxText(child.value as string))
291
+ const text = cleanJsxText(child.value as string)
292
+ parts.pushStatic(rawTextTag !== undefined ? escapeRawText(text, rawTextTag) : text)
281
293
  }
282
294
  else if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
283
295
  emitIntoBuffer(child, bufVar, parts, flushParts, pushStmt)
@@ -285,9 +297,28 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
285
297
  else if (child.type === 'JSXExpressionContainer') {
286
298
  const expr = child.expression as AstNode
287
299
 
288
- // Fold static string literal expressions like `{' '}` directly into static text
300
+ // Fold static string literal expressions like `{' '}` or `<style>{':root { ... }'}</style>` directly into static text
289
301
  if (expr.type === 'Literal' && typeof expr.value === 'string') {
290
- parts.pushStatic(escapeStaticText(expr.value))
302
+ parts.pushStatic(rawTextTag !== undefined ? escapeRawText(expr.value, rawTextTag) : escapeStaticText(expr.value))
303
+ continue
304
+ }
305
+
306
+ // Fold static no-substitution template literals inside `<style>`/`<script>` directly into raw text
307
+ if (
308
+ rawTextTag !== undefined
309
+ && expr.type === 'TemplateLiteral'
310
+ && (expr.expressions as AstNode[]).length === 0
311
+ && (expr.quasis as AstNode[]).length === 1
312
+ ) {
313
+ const cooked = expr.quasis[0]?.value?.cooked
314
+ if (typeof cooked === 'string') {
315
+ parts.pushStatic(escapeRawText(cooked, rawTextTag))
316
+ continue
317
+ }
318
+ }
319
+
320
+ if (rawTextTag !== undefined) {
321
+ parts.pushExpr(`${use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${compileSubExpression(expr)})`)
291
322
  continue
292
323
  }
293
324
 
@@ -549,6 +580,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
549
580
  editor.replace(node.start, node.end, compileRootJsx(node))
550
581
  return false
551
582
  }
583
+ return undefined
552
584
  })
553
585
 
554
586
  if (used.size > 0) {
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { Cookies } from './cookies'
4
4
  import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
5
- import { verifyOrigin } from './security'
5
+ import { isTrustedOrigin, verifyOrigin } from './security'
6
6
  import { validateSchema } from './standard-schema'
7
7
 
8
8
  export interface ActionContext {
@@ -141,8 +141,14 @@ export async function executeAction(
141
141
  if (!wantsJson) {
142
142
  const referer = request.headers.get('referer')
143
143
  if (referer) {
144
- const refUrl = new URL(referer)
145
- if (refUrl.origin === ctx.url.origin)
144
+ let refUrl: URL | undefined
145
+ try {
146
+ refUrl = new URL(referer)
147
+ }
148
+ catch {
149
+ refUrl = undefined
150
+ }
151
+ if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins))
146
152
  return Response.redirect(refUrl.href, 303)
147
153
  }
148
154
  }
@@ -559,9 +559,12 @@ export async function createServerFromEmbedded(config: EmbeddedServerConfig): Pr
559
559
  'etag': pub.etag,
560
560
  'cache-control': pubCache,
561
561
  }
562
- routes[path] = typeof pub.body === 'string'
563
- ? () => new Response(Bun.file(pub.body as string), { status: 200, headers })
564
- : new Response(pub.body, { status: 200, headers })
562
+ routes[path] = (req: Request) => {
563
+ if (req.headers.get('if-none-match') === pub.etag)
564
+ return new Response(null, { status: 304, headers: { 'etag': pub.etag, 'cache-control': pubCache } })
565
+ const body = typeof pub.body === 'string' ? Bun.file(pub.body) : pub.body
566
+ return new Response(req.method === 'HEAD' ? null : body, { status: 200, headers })
567
+ }
565
568
  }
566
569
  }
567
570
 
@@ -9,16 +9,40 @@ export interface SecurityHeadersOptions {
9
9
 
10
10
  const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
11
11
 
12
+ function requestOrigins(request: Request): { expectedOrigin: string, forwardedOrigin: string | undefined } {
13
+ const expectedOrigin = new URL(request.url).origin
14
+ const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim()
15
+ const fwdHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() || request.headers.get('host')?.trim()
16
+ let forwardedOrigin: string | undefined
17
+ if (fwdProto && fwdHost) {
18
+ try {
19
+ forwardedOrigin = new URL(`${fwdProto}://${fwdHost}`).origin
20
+ }
21
+ catch {
22
+ forwardedOrigin = `${fwdProto}://${fwdHost}`
23
+ }
24
+ }
25
+ return { expectedOrigin, forwardedOrigin }
26
+ }
27
+
28
+ /** Returns true when `origin` matches the request's direct/forwarded origin or `trustedOrigins`. */
29
+ export function isTrustedOrigin(
30
+ origin: string,
31
+ request: Request,
32
+ trustedOrigins?: ReadonlySet<string>,
33
+ ): boolean {
34
+ const { expectedOrigin, forwardedOrigin } = requestOrigins(request)
35
+ return origin === expectedOrigin
36
+ || (forwardedOrigin !== undefined && origin === forwardedOrigin)
37
+ || trustedOrigins?.has(origin) === true
38
+ }
39
+
12
40
  /** Rejects cross-site state-changing requests based on Origin / Sec-Fetch-Site headers. */
13
41
  export function verifyOrigin(request: Request, trustedOrigins?: ReadonlySet<string>): { ok: true } | { ok: false, reason: string } {
14
42
  if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
15
43
  return { ok: true }
16
44
 
17
- const url = new URL(request.url)
18
- const expectedOrigin = url.origin
19
- const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim()
20
- const fwdHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() || request.headers.get('host')?.trim()
21
- const forwardedOrigin = fwdProto && fwdHost ? `${fwdProto}://${fwdHost}` : undefined
45
+ const { expectedOrigin, forwardedOrigin } = requestOrigins(request)
22
46
  const origin = request.headers.get('origin')
23
47
 
24
48
  if (origin !== null) {
package/src/ssr/index.ts CHANGED
@@ -42,6 +42,27 @@ export function ssrRaw(value: unknown): string {
42
42
  return String(value)
43
43
  }
44
44
 
45
+ const CLOSE_STYLE_RE = /<\/(style)/gi
46
+ const CLOSE_SCRIPT_RE = /<\/(script)/gi
47
+
48
+ /** Emits raw text inside `<style>` or `<script>` without HTML entity escaping, neutralizing only its closing tag. */
49
+ export function ssrRawText(tag: 'style' | 'script', value: unknown): string {
50
+ if (value == null || typeof value === 'boolean')
51
+ return ''
52
+ if (Array.isArray(value)) {
53
+ let out = ''
54
+ for (let i = 0; i < value.length; i++)
55
+ out += ssrRawText(tag, value[i])
56
+ return out
57
+ }
58
+ const str = typeof value === 'string'
59
+ ? value
60
+ : typeof value === 'object' && '__html' in value
61
+ ? String((value as Html).__html)
62
+ : String(value)
63
+ return str.replace(tag === 'script' ? CLOSE_SCRIPT_RE : CLOSE_STYLE_RE, '<\\/$1')
64
+ }
65
+
45
66
  export function escAttr(value: unknown): string {
46
67
  const str = String(value)
47
68
  if (bunEscape !== undefined)