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

Commit 91a8389

Browse files
committed
fix: integrate render method scope correction
2 parents 25aa2b7 + 8e1b5be commit 91a8389

6 files changed

Lines changed: 171 additions & 7 deletions

File tree

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,7 +1078,10 @@ ${signals ? ` _beginScope() {
10781078
}
10791079
10801080
_callScopeMethod(name, args) {
1081-
if (!this._scopeMethods || this._updatePending) this.render(RENDER_HELPERS);
1081+
// Template calls already have this render's current prop closures. Refresh
1082+
// pending props only for an outside call, otherwise a public helper in the
1083+
// template would recursively render while the queued update is pending.
1084+
if (!this._scopeRenderDepth && (!this._scopeMethods || this._updatePending)) this.render(RENDER_HELPERS);
10821085
return this._scopeMethods[name].apply(this, args);
10831086
}
10841087
@@ -1321,8 +1324,13 @@ function componentModule(component: CompiledComponent, runtimeImport = './runtim
13211324

13221325
renderMethod = `
13231326
render(__helpers) {
1324-
const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
1325-
${indent(compiled.trim())}
1327+
this._scopeRenderDepth = (this._scopeRenderDepth || 0) + 1;
1328+
try {
1329+
const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
1330+
${indent(indent(compiled.trim()))}
1331+
} finally {
1332+
this._scopeRenderDepth--;
1333+
}
13261334
}
13271335
`
13281336
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
export const methodScopeSource = `<script>
2+
const { value } = withDefaults(defineProps<{ value?: string }>(), { value: 'initial' })
3+
const count = state(0)
4+
function label(input: string): string {
5+
if (input === 'throw') throw new Error('expected label failure')
6+
return input + ':' + count()
7+
}
8+
function read(): string { return this.label(value) }
9+
function increment(): string { count.update(current => current + 1); return this.read() }
10+
async function readLater(): Promise<string> { await Promise.resolve(); return this.read() }
11+
function recurse(depth: number): string { return depth ? this.recurse(depth - 1) : value }
12+
function overflow(): number { return 1 + this.overflow() }
13+
</script><template><p>{{ this.label(value) }}</p></template>`
14+
15+
interface Probe extends HTMLElement {
16+
value: string
17+
read(): string
18+
increment(): string
19+
readLater(): Promise<string>
20+
overflow(): number
21+
recurse(depth: number): string
22+
updateComplete: Promise<void>
23+
render(helpers: { escape(value: unknown): string }): string
24+
}
25+
26+
export async function exerciseMethodScope(tag: string): Promise<unknown[]> {
27+
const first = document.createElement(tag) as Probe
28+
const second = document.createElement(tag) as Probe
29+
const values: unknown[] = []
30+
try {
31+
// A method may be called before the element's first connection/render.
32+
values.push(first.read())
33+
second.value = 'second'
34+
document.body.append(first, second)
35+
values.push(first.textContent, second.textContent)
36+
first.value = 'pending'
37+
values.push(first.read(), first.increment())
38+
await first.updateComplete
39+
values.push(first.textContent, second.read(), second.textContent)
40+
first.value = 'manual'
41+
values.push(first.render({ escape: value => String(value) }))
42+
values.push(first.read())
43+
await first.updateComplete
44+
values.push(first.textContent)
45+
first.value = 'async'
46+
values.push(await first.readLater())
47+
await first.updateComplete
48+
values.push(first.textContent)
49+
first.value = 'throw'
50+
try { first.read() }
51+
catch (error) { values.push((error as Error).message) }
52+
first.value = 'recovered'
53+
values.push(first.read())
54+
await first.updateComplete
55+
values.push(first.textContent, first.recurse(4))
56+
// Actual user recursion still runs and throws, without a compiler guard
57+
// swallowing it or substituting a stale scope result.
58+
try { first.overflow() }
59+
catch (error) { values.push((error as Error).name) }
60+
values.push(first.read(), second.read())
61+
return values
62+
}
63+
finally { first.remove(); second.remove() }
64+
}
65+
66+
export const methodScopeExpected = ['initial:0', 'initial:0', 'second:0', 'pending:0', 'pending:1', 'pending:1', 'second:0', 'second:0', '<p>manual:1</p>', 'manual:1', 'manual:1', 'async:1', 'async:1', 'expected label failure', 'recovered:1', 'recovered:1', 'recovered', 'RangeError', 'recovered:1', 'second:0']
67+

‎packages/stx/test/web-components/component-library-emits.test.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,9 @@ for (const publicImport of [false, true]) test(`element effects and ${publicImpo
344344
const root = createTempDir('stx-module-emits-')
345345
roots.push(root)
346346
const inputDir = join(root, 'components'), outputDir = join(root, 'dist')
347-
const signals = publicImport ? '@stacksjs/stx/signals-api' : new URL('../../src/signals-api.ts', import.meta.url).pathname
347+
const signals = publicImport ? '@stacksjs/stx/signals-api' : process.env.STX_LIBRARY_DIST
348+
? new URL('../../dist/signals-api.js', import.meta.url).pathname
349+
: new URL('../../src/signals-api.ts', import.meta.url).pathname
348350
await Bun.write(join(inputDir, 'helper.ts'), `import { state } from ${JSON.stringify(signals)}; export const shared = state(0); export function bumpShared() { shared.update(value => value + 1) }`)
349351
for (const name of ['First', 'Second']) await Bun.write(join(inputDir, `${name}.stx`), `<script>
350352
import { shared, bumpShared } from './helper'
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { WebView } from 'bun'
2+
import { expect, test } from 'bun:test'
3+
import { rm } from 'node:fs/promises'
4+
import { join, relative, sep } from 'node:path'
5+
import { buildComponentLibrary as sourceBuild } from '../../src/component-library'
6+
import { createTempDir } from '../../src/temp-dir'
7+
import { createBrowserFixture } from '../../test-utils/browser-fixture'
8+
import { exerciseMethodScope, methodScopeExpected, methodScopeSource } from '../../test-utils/component-method-scope'
9+
10+
const buildComponentLibrary = process.env.STX_LIBRARY_DIST ? (await import('../../dist/component-library.js')).buildComponentLibrary : sourceBuild
11+
12+
// The maintained public contract runs in Chrome from emitted assets after the
13+
// authored source is gone, with no ambient stx or string-execution permission.
14+
for (const bundle of [false, true]) test(`public method render ownership works in ${bundle ? 'standalone' : 'ESM'} Chrome under strict CSP`, async () => {
15+
const root = createTempDir('stx-method-scope-browser-')
16+
let fixture: ReturnType<typeof createBrowserFixture> | undefined
17+
try {
18+
const inputDir = join(root, 'source'), outputDir = join(root, 'dist')
19+
await Bun.write(join(inputDir, 'Probe.stx'), methodScopeSource)
20+
const result = await buildComponentLibrary({ inputDir, outputDir, prefix: 'browser-method', bundle, progressive: false })
21+
await rm(inputDir, { recursive: true })
22+
const emitted = new Map(result.files.filter(file => file.endsWith('.js')).map(file => [`/${relative(outputDir, file).split(sep).join('/')}`, file]))
23+
fixture = createBrowserFixture({
24+
createServer: () => Bun.serve({ hostname: '127.0.0.1', port: 0, fetch(request) {
25+
const pathname = new URL(request.url).pathname
26+
if (pathname === '/') return new Response(`<!doctype html><link rel="icon" href="/favicon.ico"><script src="/probe.js"></script><script type="module" src="/${bundle ? 'bundle' : 'index'}.js"></script>`, { headers: { 'Content-Type': 'text/html', 'Content-Security-Policy': "default-src 'none'; script-src 'self'; img-src 'self'; base-uri 'none'" } })
27+
if (pathname === '/favicon.ico') return new Response(null, { status: 204 })
28+
if (pathname === '/probe.js') return new Response(`globalThis.errors=[];globalThis.violations=[];addEventListener('error',event=>errors.push(event.message));addEventListener('unhandledrejection',event=>errors.push(String(event.reason)));addEventListener('securitypolicyviolation',event=>violations.push(event.effectiveDirective));globalThis.exercise=${exerciseMethodScope.toString()}`, { headers: { 'Content-Type': 'text/javascript' } })
29+
const file = emitted.get(pathname)
30+
return file ? new Response(Bun.file(file), { headers: { 'Content-Type': 'text/javascript' } }) : new Response(null, { status: 404 })
31+
} }),
32+
createView: () => new WebView({ headless: true, backend: { type: 'chrome', url: false } }),
33+
})
34+
await fixture.view.navigate(fixture.url)
35+
expect(await fixture.waitFor(`!!customElements.get('browser-method-probe')`, value => value === true)).toBe(true)
36+
expect(JSON.parse(await fixture.view.evaluate<string>(`exercise('browser-method-probe').then(JSON.stringify)`))).toEqual(methodScopeExpected)
37+
expect(await fixture.view.evaluate('JSON.stringify(errors)')).toBe('[]')
38+
expect(await fixture.view.evaluate('JSON.stringify(violations)')).toBe('[]')
39+
expect(await fixture.view.evaluate(`typeof globalThis.stx + ':' + typeof globalThis.defineProps`)).toBe('undefined:undefined')
40+
}
41+
finally { fixture?.close(); await rm(root, { recursive: true, force: true }) }
42+
}, 30000)
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { afterEach, expect, test } from 'bun:test'
2+
import { rm } from 'node:fs/promises'
3+
import { join } from 'node:path'
4+
import { buildComponentLibrary as sourceBuild } from '../../src/component-library'
5+
import { createTempDir } from '../../src/temp-dir'
6+
import { exerciseMethodScope, methodScopeExpected, methodScopeSource } from '../../test-utils/component-method-scope'
7+
8+
const buildComponentLibrary = process.env.STX_LIBRARY_DIST ? (await import('../../dist/component-library.js')).buildComponentLibrary : sourceBuild
9+
const roots: string[] = []
10+
afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) })
11+
12+
// Compile and call actual emitted elements. This catches stale prop closures and
13+
// render reentry; the companion Chrome test adds native loading and strict CSP.
14+
for (const bundle of [false, true]) test(`public helpers use current props during ${bundle ? 'standalone' : 'ESM'} renders and pending updates`, async () => {
15+
const root = createTempDir('stx-method-scope-')
16+
roots.push(root)
17+
const inputDir = join(root, 'source'), outputDir = join(root, 'dist')
18+
await Bun.write(join(inputDir, 'Probe.stx'), methodScopeSource)
19+
await buildComponentLibrary({ inputDir, outputDir, prefix: bundle ? 'method-bundle' : 'method-esm', bundle, progressive: false })
20+
await rm(inputDir, { recursive: true })
21+
await import(join(outputDir, bundle ? 'bundle.js' : 'index.js'))
22+
if (!bundle) {
23+
await Bun.write(join(root, 'consumer.ts'), `import { Probe } from './dist/method-esm-probe.js'
24+
const element = new Probe()
25+
element.value = 'pending'
26+
const current: string = element.read()
27+
const incremented: string = element.increment()
28+
const later: Promise<string> = element.readLater()
29+
const recursed: string = element.recurse(4)
30+
// @ts-expect-error Public prop remains a string.
31+
element.value = 1
32+
// @ts-expect-error Public helper keeps its required string argument.
33+
element.label(1)
34+
void [current, incremented, later, recursed]
35+
`)
36+
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: [] }, files: ['consumer.ts'] }))
37+
const compiler = Bun.spawn(['bun', 'x', '--bun', 'tsc', '-p', join(root, 'tsconfig.json'), '--pretty', 'false'], { cwd: process.cwd(), stdout: 'pipe', stderr: 'pipe' })
38+
const output = await new Response(compiler.stdout).text() + await new Response(compiler.stderr).text()
39+
expect(await compiler.exited, output).toBe(0)
40+
}
41+
expect(await exerciseMethodScope(bundle ? 'method-bundle-probe' : 'method-esm-probe')).toEqual(methodScopeExpected)
42+
})

‎scripts/installed-package-smoke.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,16 @@ copyFileSync(join(root, 'packages/stx/test-utils/happy-dom.ts'), join(smokeRoot,
7070
// Shared emit authoring is qualified from exactly the archives being released.
7171
// Only test harnesses are copied; compiler and native signal code stay installed.
7272
copyFileSync(join(root, 'packages/stx/test-utils/browser-fixture.ts'), join(smokeRoot, 'browser-fixture.ts'))
73-
for (const fixture of ['component-library-emits.test.ts', 'component-library-emits-browser.test.ts']) {
73+
copyFileSync(join(root, 'packages/stx/test-utils/component-method-scope.ts'), join(smokeRoot, 'component-method-scope.ts'))
74+
for (const fixture of ['component-library-emits.test.ts', 'component-library-emits-browser.test.ts', 'component-library-method-scope.test.ts', 'component-library-method-scope-browser.test.ts']) {
7475
const test = readFileSync(join(root, 'packages/stx/test/web-components', fixture), 'utf8')
7576
.replaceAll("'../../src/component-library'", "'@stacksjs/stx/component-library'")
7677
.replaceAll("'../../src/process'", "'@stacksjs/stx/process'")
7778
.replace("new URL('../../src/signals-api.ts', import.meta.url).pathname", "new URL(import.meta.resolve('@stacksjs/stx/signals-api')).pathname")
79+
.replace("new URL('../../dist/signals-api.js', import.meta.url).pathname", "new URL(import.meta.resolve('@stacksjs/stx/signals-api')).pathname")
7880
.replaceAll("'../../src/temp-dir'", "'@stacksjs/stx/temp-dir'")
7981
.replaceAll("'../../test-utils/browser-fixture'", "'./browser-fixture'")
82+
.replaceAll("'../../test-utils/component-method-scope'", "'./component-method-scope'")
8083
.replace("const buildComponentLibrary = process.env.STX_LIBRARY_DIST ? (await import('../../dist/component-library.js')).buildComponentLibrary : sourceBuild", 'const buildComponentLibrary = sourceBuild')
8184
writeFileSync(join(smokeRoot, fixture), test)
8285
}
@@ -88,10 +91,10 @@ for (const flags of [[], ['--frozen-lockfile']]) {
8891
if (normalLock) assert.equal(lock, normalLock, 'Frozen install changed the qualified lockfile')
8992
else normalLock = lock
9093
await verifyPublicTypes(smokeRoot, publicTypeArchives, flags.length ? 'frozen' : 'normal', { kind: 'prepublication-original-archives', url: registry.url, requests: registry.requests })
91-
await run([process.execPath, '--no-env-file', 'test', '--preload', './happy-dom.ts', './component-library-emits.test.ts'])
94+
await run([process.execPath, '--no-env-file', 'test', '--preload', './happy-dom.ts', './component-library-emits.test.ts', './component-library-method-scope.test.ts'])
9295
// Bun's Chrome bridge discovers its executable through the real desktop HOME;
9396
// archive installation and strict/SSR consumers retain their isolated HOME.
94-
await run([process.execPath, '--no-env-file', 'test', '--preload', './happy-dom.ts', './component-library-emits-browser.test.ts'], smokeRoot,
97+
await run([process.execPath, '--no-env-file', 'test', '--preload', './happy-dom.ts', './component-library-emits-browser.test.ts', './component-library-method-scope-browser.test.ts'], smokeRoot,
9598
process.env.STX_BROWSER_HOME ? { HOME: process.env.STX_BROWSER_HOME } : {})
9699
console.log(`native emits original-archive ${flags.length ? 'frozen' : 'normal'} consumer passed`)
97100
}

0 commit comments

Comments
 (0)