镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Commit 69a2805

Browse files
committed
fix: compile native typed emit closures
1 parent c05613d commit 69a2805

10 files changed

Lines changed: 632 additions & 51 deletions

‎docs/api/component-library.md‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,46 @@ import 'my-design-system/acme-button.js'
167167
</template>
168168
```
169169

170+
## Shared typed events in compiled libraries
171+
172+
Shared and client scripts can declare events with `defineEmits` and use ordinary
173+
functions or direct expressions in event directives:
174+
175+
```html
176+
<script>
177+
interface SaveButtonProps { id: string }
178+
const { id } = defineProps<SaveButtonProps>()
179+
const emit = defineEmits<{ save: [detail: { id: string }] }>()
180+
function save(): void { emit('save', { id }) }
181+
</script>
182+
<template>
183+
<button @click="save">Save</button>
184+
<button @click="emit('save', { id })">Save directly</button>
185+
</template>
186+
```
187+
188+
The native library compiler emits lexical handlers and dispatches through the
189+
element's existing `emit` API. Props remain data, including quoted IDs and old
190+
handler strings. No handler string is evaluated in the browser. Emitted modules
191+
resolve their imports at build time and run without an ambient stx runtime.
192+
Server scripts stay excluded from the browser package. Ordinary stx SSR projects
193+
the public props without executing shared client setup or creating emitters.
194+
195+
Tuple event maps, callable overload interfaces, and payload maps produce
196+
`CustomEvent` detail types in the element's event map, typed DOM listeners, JSX
197+
handlers, and custom-elements manifest. One emitted argument becomes `detail`;
198+
zero or multiple arguments become a tuple. Runtime arrays and object declarations
199+
supply event names with `unknown` detail types. Existing explicit event metadata
200+
can provide or override their public descriptions and detail types.
201+
202+
Functions close over the current rendered props. Top-level native `state` and
203+
`derived` values belong to each element and survive updates and reconnects.
204+
Rendering recalculates shared derived expressions, replaces handler closures,
205+
and disposes the previous render's effects. `onMount` runs on each connection;
206+
its returned cleanup and `onDestroy` callbacks run on disconnect, along with
207+
native effect and state-subscription cleanup. Browser signal primitives are
208+
bundled once into the library instead of depending on page globals.
209+
170210
## JSX-Tag Syntax
171211

172212
The tag form reads naturally for the common case and looks like every other modern templating engine.

‎packages/stx/src/component-contract.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { stripCommentsAndLiterals } from './strip-literals'
1+
import { bracketDepths, stripCommentsAndLiterals } from './strip-literals'
22

33
export interface ComponentContract {
44
declarations: string
@@ -35,10 +35,12 @@ function argumentsOf(source: string): string[] {
3535
return args
3636
}
3737

38-
function macroCall(code: string, names: string[]): { type: string, args: string[] } | null {
38+
export function macroCall(code: string, names: string[], topLevel = false): { type: string, args: string[], start: number, end: number } | null {
3939
const masked = stripCommentsAndLiterals(code)
4040
const pattern = new RegExp(`\\b(?:${names.map(name => name.replace(/[$]/g, '\\$&')).join('|')})\\s*(?=[<(])`, 'g')
41+
const depths = topLevel ? bracketDepths(masked).depths : undefined
4142
for (const match of masked.matchAll(pattern)) {
43+
if (depths && depths[match.index!] !== 0) continue
4244
let at = match.index! + match[0].length
4345
let type = ''
4446
if (masked[at] === '<') {
@@ -50,7 +52,7 @@ function macroCall(code: string, names: string[]): { type: string, args: string[
5052
}
5153
if (masked[at] !== '(') continue
5254
const close = closeAt(masked, at, '(', ')')
53-
if (close >= 0) return { type, args: argumentsOf(code.slice(at + 1, close)) }
55+
if (close >= 0) return { type, args: argumentsOf(code.slice(at + 1, close)), start: match.index!, end: close + 1 }
5456
}
5557
return null
5658
}

‎packages/stx/src/component-library.ts‎

Lines changed: 158 additions & 46 deletions
Large diffs are not rendered by default.

‎packages/stx/src/composition-api.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,12 @@ export function setGlobalProvide<T>(key: string | symbol, value: T): void {
194194
// eslint-disable-next-line pickier/no-unused-vars
195195
export type EmitFn<T extends string = string> = (event: T, ...args: any[]) => void
196196

197+
/** Tuple maps, payload maps and callable overload contracts share one emitter. */
198+
export type ComponentEmit<T> = T extends (...args: never[]) => unknown ? T : <K extends Extract<keyof T, string>>(
199+
event: K,
200+
...args: T[K] extends readonly unknown[] ? T[K] : [payload: T[K]]
201+
) => void
202+
197203
/**
198204
* Define the events a component can emit.
199205
* Returns a typed emit function.
@@ -210,7 +216,9 @@ export type EmitFn<T extends string = string> = (event: T, ...args: any[]) => vo
210216
* emit('change', 'newValue')
211217
* ```
212218
*/
213-
export function defineEmits<T extends Record<string, any[]> = Record<string, any[]>>(events?: string[] | T): EmitFn<Extract<keyof T, string>> {
219+
export function defineEmits<const T extends readonly string[]>(events: T): EmitFn<T[number]>
220+
export function defineEmits<T extends object = Record<string, any[]>>(events?: T): ComponentEmit<T>
221+
export function defineEmits(events?: readonly string[] | object): EmitFn {
214222
const instance = currentInstance
215223
const element = instance?.el as (HTMLElement & { __stx_component_emits?: Record<string, boolean> }) | undefined
216224
const declaredEvents = Array.isArray(events)
@@ -245,7 +253,7 @@ export function defineEmits<T extends Record<string, any[]> = Record<string, any
245253
instance.emit = emit
246254
}
247255

248-
return emit as EmitFn<Extract<keyof T, string>>
256+
return emit
249257
}
250258

251259
// =============================================================================
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/** Compile-time event contracts. Component setup is never executed to read them. */
2+
import { macroCall } from './component-contract'
3+
import { parseStringLiteral } from './directive-arguments'
4+
import { Tokenizer } from './parser/tokenizer'
5+
import { localType, skipBalanced, splitTopLevel } from './props-declaration'
6+
import type { ComponentLibraryEvent } from './types'
7+
8+
9+
function eventName(raw: string): string | undefined {
10+
const name = raw.trim()
11+
return /^[A-Za-z_$][\w$]*$/.test(name) ? name : parseStringLiteral(name) ?? undefined
12+
}
13+
14+
/** The native module emitter puts one argument in detail, and multiple in a tuple. */
15+
function detailFromTuple(tuple: string): string {
16+
const members = splitTopLevel(tuple.trim().slice(1, -1), ',', true)
17+
if (members.length !== 1) return tuple.trim()
18+
const member = members[0]!
19+
if (member.startsWith('...')) return tuple.trim()
20+
const labelled = /^(?:[A-Za-z_$][\w$]*)(\?)?\s*:\s*([\s\S]+)$/.exec(member)
21+
return labelled ? `${labelled[2]}${labelled[1] ? ' | undefined' : ''}` : member
22+
}
23+
24+
export interface EmitsDeclaration {
25+
text: string
26+
start: number
27+
end: number
28+
typeName?: string
29+
events: Record<string, ComponentLibraryEvent>
30+
}
31+
32+
export function parseEmitsDeclaration(code: string): EmitsDeclaration | null {
33+
const call = macroCall(code, ['defineEmits'], true)
34+
if (!call) return null
35+
const events: Record<string, ComponentLibraryEvent> = Object.create(null)
36+
const typeName = /^[A-Za-z_$][\w$]*$/.test(call.type.trim()) ? call.type.trim() : undefined
37+
const type = typeName ? localType(code, typeName) : call.type.trim()
38+
if (type?.startsWith('{')) {
39+
for (const member of splitTopLevel(type.slice(1, -1), ';,\n', true)) {
40+
// The documented overload form: (event: 'change', value: string): void.
41+
if (member.startsWith('(')) {
42+
const end = skipBalanced(member, 0, '(', ')')
43+
if (end < 0) continue
44+
const parameters = splitTopLevel(member.slice(1, end - 1), ',', true)
45+
const first = parameters.shift() || ''
46+
const colon = first.indexOf(':')
47+
if (colon < 0) continue
48+
for (const literal of splitTopLevel(first.slice(colon + 1), '|', true)) {
49+
const name = eventName(literal)
50+
if (name !== undefined) events[name] = { detailType: detailFromTuple(`[${parameters.join(', ')}]`) }
51+
}
52+
continue
53+
}
54+
const tokens = new Tokenizer(member, 'javascript').tokenize().filter(token => !['WHITESPACE', 'COMMENT', 'EOF'].includes(token.type))
55+
const key = tokens[0], colon = tokens.findIndex(token => token.value === ':')
56+
if (!key || colon < 0) continue
57+
const name = eventName(key.value)
58+
const value = member.slice(tokens[colon]!.end).trim()
59+
if (name !== undefined) events[name] = { detailType: value.startsWith('[') ? detailFromTuple(value) : value }
60+
}
61+
}
62+
else {
63+
const argument = call.args[0]?.trim() || ''
64+
if (argument.startsWith('[')) {
65+
for (const item of splitTopLevel(argument.slice(1, -1), ',', false)) {
66+
const name = eventName(item)
67+
if (name !== undefined) events[name] = { detailType: 'unknown' }
68+
}
69+
}
70+
else if (argument.startsWith('{')) {
71+
for (const member of splitTopLevel(argument.slice(1, -1), ',', false)) {
72+
const key = new Tokenizer(member, 'javascript').tokenize().find(token => !['WHITESPACE', 'COMMENT'].includes(token.type))
73+
const name = key && eventName(key.value)
74+
if (name !== undefined) events[name] = { detailType: 'unknown' }
75+
}
76+
}
77+
}
78+
return { ...call, text: code.slice(call.start, call.end), typeName, events }
79+
}

‎packages/stx/src/props-declaration.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import { topLevelDeclarationSites } from './client-parameter-bindings'
33
import { Tokenizer } from './parser/tokenizer'
44
import { parseStringLiteral } from './directive-arguments'
5+
import { bracketDepths, stripCommentsAndLiterals } from './strip-literals'
56

67
function withoutComments(source: string): string {
78
const tokens = new Tokenizer(source, 'javascript').tokenize()
@@ -483,3 +484,28 @@ export function literalValue(source: string): unknown {
483484
}
484485
catch { return undefined }
485486
}
487+
488+
/** Resolve local macro-support types with the same balanced scanner as props. */
489+
export function localType(code: string, name: string): string | undefined {
490+
const masked = stripCommentsAndLiterals(code)
491+
const depths = bracketDepths(masked).depths
492+
const pattern = /\b(interface|type)\s+([A-Za-z_$][\w$]*)\b/g
493+
for (const match of masked.matchAll(pattern)) {
494+
if (match[2] !== name || depths[match.index!] !== 0) continue
495+
const start = match.index! + match[0].length
496+
const open = masked.indexOf('{', start)
497+
if (match[1] === 'interface' && open >= 0) {
498+
const end = skipBalanced(masked, open, '{', '}')
499+
if (end >= 0) return code.slice(open, end)
500+
}
501+
if (match[1] === 'type') {
502+
const equal = masked.indexOf('=', start)
503+
if (equal < 0) continue
504+
const rest = code.slice(equal + 1).trimStart()
505+
if (rest[0] === '{') {
506+
const end = skipBalanced(rest, 0, '{', '}')
507+
if (end >= 0) return rest.slice(0, end)
508+
}
509+
}
510+
}
511+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { expect, test } from 'bun:test'
2+
import { rm } from 'node:fs/promises'
3+
import { join } from 'node:path'
4+
import { createTempDir } from '../../src/temp-dir'
5+
6+
// This checks the public module type contract, not compiler string output.
7+
test('defineEmits types match documented tuples, overloads and payload maps', async () => {
8+
const root = createTempDir('stx-emits-types-')
9+
try {
10+
const module = new URL('../../src/composition-api.ts', import.meta.url).pathname
11+
await Bun.write(join(root, 'consumer.ts'), `import { defineEmits } from ${JSON.stringify(module)}
12+
const tuple = defineEmits<{ change: [value: string]; pair: [id: number, value: string]; close: [] }>()
13+
tuple('change', 'value'); tuple('pair', 7, 'value'); tuple('close')
14+
// @ts-expect-error Tuple payload is checked.
15+
tuple('change', 1)
16+
// @ts-expect-error Required arguments are checked.
17+
tuple('pair', 7)
18+
interface Events { (event: 'change', value: string): void; (event: 'close'): void }
19+
const overload = defineEmits<Events>()
20+
overload('change', 'value'); overload('close')
21+
// @ts-expect-error Overload payload is checked.
22+
overload('change', 1)
23+
const payload = defineEmits<{ select: { id: string }; delete: string }>()
24+
payload('select', { id: 'one' }); payload('delete', 'one')
25+
// @ts-expect-error Payload maps retain object shapes.
26+
payload('select', { id: 1 })
27+
const runtime = defineEmits(['change', 'close'])
28+
runtime('change', 'value'); runtime('close')
29+
// @ts-expect-error Runtime event names are checked.
30+
runtime('absent')
31+
`)
32+
await Bun.write(join(root, 'tsconfig.json'), JSON.stringify({ compilerOptions: { noEmit: true, strict: true, skipLibCheck: false, target: 'esnext', lib: ['esnext', 'dom'], module: 'esnext', moduleResolution: 'bundler', types: [], allowImportingTsExtensions: true }, files: ['consumer.ts'] }))
33+
const compiler = Bun.spawn(['bun', 'x', '--bun', 'tsc', '-p', join(root, 'tsconfig.json'), '--pretty', 'false'], { cwd: process.cwd(), stdout: 'pipe', stderr: 'pipe' })
34+
const [code, stdout, stderr] = await Promise.all([compiler.exited, new Response(compiler.stdout).text(), new Response(compiler.stderr).text()])
35+
expect(code, stdout + stderr).toBe(0)
36+
}
37+
finally { await rm(root, { recursive: true, force: true }) }
38+
}, 30000)

0 commit comments

Comments
 (0)