@stacksjs/stx 0.2.889 → 0.2.891
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/dist/{chunk-1n33yrar.js → chunk-062qfv99.js} +2 -2
- package/dist/chunk-08kcxz79.js +2 -0
- package/dist/chunk-0fyh29m1.js +2 -0
- package/dist/{chunk-2a5g80mq.js → chunk-0jdz31q1.js} +3 -3
- package/dist/{chunk-mhxg6j6s.js → chunk-0jkj8thz.js} +1 -1
- package/dist/{chunk-nbdscgvj.js → chunk-0t31rf3v.js} +6 -6
- package/dist/chunk-0w578pgv.js +3 -0
- package/dist/{chunk-f3cyghnb.js → chunk-0yxvz6qz.js} +4 -4
- package/dist/chunk-0zynd3x0.js +2 -0
- package/dist/chunk-10c7pg5h.js +2 -0
- package/dist/{chunk-cz1sdes5.js → chunk-115bb91s.js} +2 -2
- package/dist/chunk-12m3qagv.js +2 -0
- package/dist/{chunk-1gyxxfdf.js → chunk-12nmmdnp.js} +1 -1
- package/dist/chunk-1a7a8cjs.js +2 -0
- package/dist/chunk-1ph2yhfn.js +3 -0
- package/dist/{chunk-mt8edb75.js → chunk-1vp0h7d6.js} +57 -57
- package/dist/{chunk-me4yq8c2.js → chunk-29cw0fcr.js} +2 -2
- package/dist/chunk-2eq3aret.js +2 -0
- package/dist/chunk-3b3mkgpj.js +3 -0
- package/dist/{chunk-snv80b1b.js → chunk-3bsz7zj3.js} +2 -2
- package/dist/chunk-3ngbdap1.js +2 -0
- package/dist/chunk-3t30a2nx.js +2 -0
- package/dist/{chunk-eyx92t9n.js → chunk-41z7f41b.js} +2 -2
- package/dist/chunk-484x27q5.js +2 -0
- package/dist/{chunk-87g5xmmr.js → chunk-4f3456ht.js} +14 -14
- package/dist/{chunk-sjjw6y49.js → chunk-4r6hbjx7.js} +4 -4
- package/dist/chunk-4ts8qztg.js +2 -0
- package/dist/{chunk-700m927w.js → chunk-5zs5hrgz.js} +2 -2
- package/dist/{chunk-0ncafcs2.js → chunk-67j2m620.js} +3 -3
- package/dist/{chunk-bwx6w87c.js → chunk-6aq1pv9a.js} +1 -1
- package/dist/chunk-6kkatcka.js +2 -0
- package/dist/{chunk-cgfjrgfw.js → chunk-6kt9wxja.js} +11 -11
- package/dist/{chunk-kx09v9ya.js → chunk-70paeznz.js} +9 -9
- package/dist/{chunk-48rwqchc.js → chunk-7d2j41e3.js} +9 -9
- package/dist/{chunk-b15c4g3e.js → chunk-8ay5r808.js} +6 -6
- package/dist/{chunk-njpva3zq.js → chunk-8hdp4ark.js} +1 -1
- package/dist/chunk-8res5m9x.js +2 -0
- package/dist/{chunk-zf68afyh.js → chunk-8y39f6z3.js} +3 -3
- package/dist/{chunk-4akw3bym.js → chunk-90qwzwsm.js} +1 -1
- package/dist/{chunk-ch9028z3.js → chunk-9f8fda1j.js} +1 -1
- package/dist/chunk-9w6k311w.js +1322 -0
- package/dist/chunk-9zhpv03v.js +2 -0
- package/dist/{chunk-q9tc9rdv.js → chunk-a0aqs5a8.js} +2 -2
- package/dist/chunk-a5d5qveh.js +2 -0
- package/dist/{chunk-6gtecbe7.js → chunk-a7bqrjm5.js} +2 -2
- package/dist/{chunk-7hpca9c7.js → chunk-aasgawa9.js} +5 -5
- package/dist/{chunk-3dqfjpz4.js → chunk-ac3e6nhg.js} +29 -29
- package/dist/chunk-arr79m90.js +2 -0
- package/dist/{chunk-58qzyyyv.js → chunk-b0jk94wx.js} +3 -3
- package/dist/{chunk-mctzpw0w.js → chunk-b18vpz6p.js} +4 -4
- package/dist/chunk-bsbd6y64.js +2 -0
- package/dist/{chunk-ymqm898x.js → chunk-bvqgq18r.js} +2 -2
- package/dist/chunk-cf527twj.js +2 -0
- package/dist/chunk-cgrg6xzg.js +2 -0
- package/dist/{chunk-vc432a0w.js → chunk-dm069acv.js} +9 -9
- package/dist/{chunk-ranjkpc8.js → chunk-e16ef18k.js} +1 -1
- package/dist/chunk-e28czxw3.js +2 -0
- package/dist/{chunk-p8shtje2.js → chunk-e5md1cck.js} +45 -45
- package/dist/chunk-essd43ad.js +2 -0
- package/dist/chunk-fs7tv867.js +20 -0
- package/dist/chunk-fsk3rk2x.js +2 -0
- package/dist/{chunk-zwwhpxp7.js → chunk-g5nfqzfh.js} +2 -2
- package/dist/{chunk-6pz5gq6v.js → chunk-gcjqxvbb.js} +25 -21
- package/dist/{chunk-2gn2nc2j.js → chunk-gk0h2hp7.js} +1 -1
- package/dist/{chunk-9d91h636.js → chunk-gwayvyg5.js} +2 -2
- package/dist/{chunk-bqtj62ys.js → chunk-gydvy8a3.js} +7 -7
- package/dist/{chunk-eceeqy74.js → chunk-gzc16hs8.js} +2 -2
- package/dist/{chunk-xy8smv5e.js → chunk-h7yme97q.js} +2 -2
- package/dist/chunk-h87pjzn7.js +2 -0
- package/dist/chunk-hq03mwtw.js +2 -0
- package/dist/chunk-j9kejcrx.js +2 -0
- package/dist/chunk-jhbz5w30.js +2 -0
- package/dist/chunk-k0mndyb4.js +2 -0
- package/dist/{chunk-hm9d40yf.js → chunk-k89gbytd.js} +2 -2
- package/dist/{chunk-51720m79.js → chunk-kd7k31x3.js} +9 -9
- package/dist/{chunk-t0ttxayz.js → chunk-kfbw96c5.js} +2 -2
- package/dist/chunk-kh3sxa3j.js +2 -0
- package/dist/{chunk-mjp1z9kz.js → chunk-khm56bfm.js} +1 -1
- package/dist/chunk-kr4z3633.js +2 -0
- package/dist/{chunk-6pdy7ajr.js → chunk-kvz7ad7p.js} +1 -1
- package/dist/{chunk-nkyff7v6.js → chunk-kxewj557.js} +27 -27
- package/dist/chunk-mbpz45v9.js +2 -0
- package/dist/{chunk-b6bf0t02.js → chunk-mhrnjaka.js} +4 -4
- package/dist/{chunk-mw7hacm3.js → chunk-mxf6cfbg.js} +23 -23
- package/dist/{chunk-pctf14yw.js → chunk-n64zbwzr.js} +1 -1
- package/dist/{chunk-eqffvse2.js → chunk-n6q1d66k.js} +1 -1
- package/dist/chunk-nd0f11at.js +2 -0
- package/dist/{chunk-3hsv6ejp.js → chunk-neg6ckjg.js} +7 -7
- package/dist/{chunk-kbbbpae2.js → chunk-nq60tjkz.js} +2 -2
- package/dist/{chunk-6kyqejnq.js → chunk-nvre22sw.js} +22 -22
- package/dist/{chunk-967ydrq4.js → chunk-p3hbsrk9.js} +2 -2
- package/dist/chunk-p9cwapm8.js +2 -0
- package/dist/{chunk-w82nk19t.js → chunk-ph4tgp9g.js} +1 -1
- package/dist/{chunk-kj43fbzm.js → chunk-phx820py.js} +1 -1
- package/dist/{chunk-5ssv10ep.js → chunk-pjpf21y9.js} +1 -1
- package/dist/{chunk-7212fwzz.js → chunk-psykt348.js} +2 -2
- package/dist/{chunk-pz554g43.js → chunk-pvm48tse.js} +3 -3
- package/dist/{chunk-zek9t5za.js → chunk-pwpge9bj.js} +2 -2
- package/dist/{chunk-0k437z3q.js → chunk-qn45rk5n.js} +1 -1
- package/dist/{chunk-95sd8h5g.js → chunk-qrk535j6.js} +6 -6
- package/dist/{chunk-446tb2th.js → chunk-rc7djca5.js} +49 -49
- package/dist/{chunk-55tc5w32.js → chunk-sh7a0g09.js} +2 -2
- package/dist/chunk-sydgagr1.js +2 -0
- package/dist/chunk-tspqdt8e.js +2 -0
- package/dist/chunk-v6gkjg5f.js +3 -0
- package/dist/chunk-vm57848v.js +2 -0
- package/dist/{chunk-ankap9pc.js → chunk-vya7cck4.js} +1 -1
- package/dist/{chunk-hgf7bc50.js → chunk-w8djc4qb.js} +9 -9
- package/dist/chunk-wg6fmren.js +4 -0
- package/dist/chunk-wwb6c5rr.js +2 -0
- package/dist/chunk-x691tnkx.js +2 -0
- package/dist/{chunk-mgh5rst1.js → chunk-x9036mfd.js} +2 -2
- package/dist/{chunk-brzjass3.js → chunk-xc5esqcb.js} +2 -2
- package/dist/{chunk-5kqezrjt.js → chunk-xvprhdcb.js} +1 -1
- package/dist/chunk-y7qm1m0e.js +2 -0
- package/dist/{chunk-m95sygv4.js → chunk-ye6ev3qp.js} +1 -1
- package/dist/{chunk-s93yh7ed.js → chunk-ypyezjr0.js} +2 -2
- package/dist/{chunk-4kmg6g5n.js → chunk-yv797v6e.js} +9 -9
- package/dist/{chunk-cmg9x1ka.js → chunk-z012vpdz.js} +3 -3
- package/dist/{chunk-dymck524.js → chunk-z6ndrx2p.js} +5 -5
- package/dist/{chunk-2nqmw4dv.js → chunk-z8sv926e.js} +1 -1
- package/dist/{chunk-s0mf56y1.js → chunk-z92e297r.js} +4 -4
- package/dist/chunk-zd21ntcm.js +2 -0
- package/dist/{chunk-6c1vm6bs.js → chunk-zkwkhesc.js} +2 -2
- package/dist/{chunk-hpzje67q.js → chunk-zwqkbk2m.js} +2 -2
- package/dist/chunk-zxjdfgdx.js +3 -0
- package/dist/cli.js +28 -28
- package/dist/client/signals-timer-runtime.js +4 -0
- package/dist/component-contract.d.ts +1 -0
- package/dist/component-contract.js +6 -4
- package/dist/component-library.js +217 -60
- package/dist/component-renderer.js +23 -10
- package/dist/composition-api.d.ts +7 -1
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/emits-declaration.d.ts +9 -0
- package/dist/emits-declaration.js +64 -0
- package/dist/native/prop-names.js +7 -2
- package/dist/native/runtime/craft-bridge.js +29 -2
- package/dist/native/runtime/craft.d.ts +32 -0
- package/dist/native/runtime/native-host.js +27 -11
- package/dist/props-declaration.d.ts +2 -0
- package/dist/props-declaration.js +25 -0
- package/dist/pwa.js +3 -3
- package/dist/ssg.js +28 -28
- package/package.json +5 -5
- package/stx.d.ts +2 -1
- package/dist/chunk-0g9cceht.js +0 -2
- package/dist/chunk-0rpj5t80.js +0 -2
- package/dist/chunk-2ba4zfa0.js +0 -2
- package/dist/chunk-2wkpksg1.js +0 -2
- package/dist/chunk-3yjyjq0m.js +0 -2
- package/dist/chunk-444haxxa.js +0 -2
- package/dist/chunk-4rvfeee5.js +0 -2
- package/dist/chunk-5aa83bpm.js +0 -2
- package/dist/chunk-67rppc5v.js +0 -2
- package/dist/chunk-77c89d23.js +0 -2
- package/dist/chunk-79vbkez0.js +0 -2
- package/dist/chunk-8354mzpd.js +0 -2
- package/dist/chunk-8ygf6jnt.js +0 -2
- package/dist/chunk-94mpe1ny.js +0 -3
- package/dist/chunk-9n5h4sqc.js +0 -3
- package/dist/chunk-9ztn7w4y.js +0 -2
- package/dist/chunk-asnd03sr.js +0 -2
- package/dist/chunk-b0b5yr97.js +0 -2
- package/dist/chunk-b0e7dgv8.js +0 -3
- package/dist/chunk-b7jj45bz.js +0 -2
- package/dist/chunk-dzqfv801.js +0 -3
- package/dist/chunk-ery4tty7.js +0 -20
- package/dist/chunk-evwrxsxd.js +0 -3
- package/dist/chunk-fdqdz018.js +0 -2
- package/dist/chunk-g6ap4085.js +0 -2
- package/dist/chunk-gz9pknbw.js +0 -1204
- package/dist/chunk-hjb4c8g2.js +0 -2
- package/dist/chunk-jhbj9ja2.js +0 -2
- package/dist/chunk-k9abxnpa.js +0 -2
- package/dist/chunk-mvavjydq.js +0 -2
- package/dist/chunk-qqng9545.js +0 -2
- package/dist/chunk-rjm515e2.js +0 -2
- package/dist/chunk-rye4b2x3.js +0 -2
- package/dist/chunk-ryj8139z.js +0 -2
- package/dist/chunk-s9b809n2.js +0 -2
- package/dist/chunk-sb67wg5x.js +0 -2
- package/dist/chunk-sqwx2g02.js +0 -2
- package/dist/chunk-tbh7r1wh.js +0 -2
- package/dist/chunk-tpyekw0q.js +0 -2
- package/dist/chunk-v2627s75.js +0 -2
- package/dist/chunk-v98n53nk.js +0 -2
- package/dist/chunk-w34vvhm7.js +0 -2
- package/dist/chunk-wbmx0rge.js +0 -2
- package/dist/chunk-yjwa7ktk.js +0 -2
- package/dist/chunk-z47p2gx8.js +0 -2
- package/dist/chunk-z6kw6sct.js +0 -4
- package/dist/chunk-zhywjwdr.js +0 -2
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { scanHtmlScriptElements } from "./html-masking.js";
|
|
2
|
+
import { parseEmitsDeclaration } from "./emits-declaration.js";
|
|
2
3
|
import { mkdir, readFile, readdir, realpath, stat, writeFile } from "node:fs/promises";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { builtinModules } from "node:module";
|
|
@@ -6,7 +7,7 @@ import { scriptAttributes, scriptContainsCode } from "./script-attributes.js";
|
|
|
6
7
|
import { topLevelDeclarationSites } from "./client-parameter-bindings.js";
|
|
7
8
|
import { bracketDepths, stripCommentsAndLiterals } from "./strip-literals.js";
|
|
8
9
|
import { Tokenizer } from "./parser/tokenizer.js";
|
|
9
|
-
import { literalValue, parseDefaults, parsePropsDeclaration, skipBalanced, splitTopLevel } from "./props-declaration.js";
|
|
10
|
+
import { literalValue, localType, parseDefaults, parsePropsDeclaration, skipBalanced, splitTopLevel } from "./props-declaration.js";
|
|
10
11
|
export { parseDefaults } from "./props-declaration.js";
|
|
11
12
|
function reservedMethodMessage(name) {
|
|
12
13
|
if (name === "connectedCallback")
|
|
@@ -170,20 +171,21 @@ function extractClientMethods(source, file) {
|
|
|
170
171
|
const methods = {}, declarations = {}, types = [], imports = [], scripts = scanHtmlScriptElements(componentScriptSource(source)).map((script) => ({
|
|
171
172
|
code: source.slice(script.bodyStart, script.bodyEnd),
|
|
172
173
|
attributes: scriptAttributes(script.attrs)
|
|
173
|
-
})).filter(({ attributes }) => !["src", "server", "component", "stx:component"].some((name) => attributes.has(name)) && scriptContainsCode(attributes))
|
|
174
|
+
})).filter(({ attributes }) => !["src", "server", "component", "stx:component"].some((name) => attributes.has(name)) && scriptContainsCode(attributes)), combined = scripts.map((script) => script.code).join(`
|
|
175
|
+
`), publicProps = parsePropsDeclaration(combined), publicEmits = parseEmitsDeclaration(combined);
|
|
174
176
|
for (const script of scripts) {
|
|
175
|
-
const { code
|
|
177
|
+
const { code } = script;
|
|
176
178
|
try {
|
|
177
179
|
new Bun.Transpiler({ loader: "ts" }).transformSync(code);
|
|
178
180
|
} catch (error) {
|
|
179
181
|
throw Error(`${file}: failed to transpile <script client> (${error.message})`);
|
|
180
182
|
}
|
|
181
|
-
const
|
|
183
|
+
const extracted = clientMethods(code), overloads = new Set(extracted.filter((method) => !method.source).map((method) => method.name));
|
|
182
184
|
for (const method of extracted) {
|
|
183
185
|
if (RESERVED_METHODS.has(method.name))
|
|
184
186
|
throw Error(`${file}: client ${reservedMethodMessage(method.name)}`);
|
|
185
187
|
if (method.source)
|
|
186
|
-
methods[method.name] =
|
|
188
|
+
methods[method.name] = `${method.name}(...args) { return this._callScopeMethod(${JSON.stringify(method.name)}, args); }`;
|
|
187
189
|
if (!method.source || !overloads.has(method.name))
|
|
188
190
|
(declarations[method.name] ??= []).push(methodDeclaration(method));
|
|
189
191
|
}
|
|
@@ -225,10 +227,10 @@ function extractClientMethods(source, file) {
|
|
|
225
227
|
}
|
|
226
228
|
const declaration = code.slice(match.index, cursor), declarationStart = match.index, name = /(?:interface|type)\s+([A-Za-z_$][\w$]*)/.exec(match[0])?.[1], remaining = scripts.map((other) => {
|
|
227
229
|
const body = other === script ? code.slice(0, declarationStart) + code.slice(cursor) : other.code;
|
|
228
|
-
return stripCommentsAndLiterals(body.replace(parsePropsDeclaration(other.code)?.text ?? "\x00", ""));
|
|
230
|
+
return stripCommentsAndLiterals(body.replace(parsePropsDeclaration(other.code)?.text ?? "\x00", "").replace(parseEmitsDeclaration(other.code)?.text ?? "\x00", ""));
|
|
229
231
|
}).join(`
|
|
230
232
|
`);
|
|
231
|
-
if (!(
|
|
233
|
+
if (!((publicProps?.typeName === name || publicEmits?.typeName === name) && !/^export\s/.test(declaration) && name && !new RegExp(`\\b${name}\\b`).test(remaining)))
|
|
232
234
|
types.push(declaration.replace(/^export\s+/, "").trim());
|
|
233
235
|
typePattern.lastIndex = cursor + 1;
|
|
234
236
|
}
|
|
@@ -236,13 +238,21 @@ function extractClientMethods(source, file) {
|
|
|
236
238
|
const referenced = Object.values(declarations).flat().join(`
|
|
237
239
|
`) + `
|
|
238
240
|
` + types.join(`
|
|
239
|
-
`)
|
|
241
|
+
`) + `
|
|
242
|
+
` + Object.values(publicEmits?.events || {}).map((event) => event.detailType).join(`
|
|
243
|
+
`), referenceTokens = new Tokenizer(referenced, "javascript").tokenize().filter((token) => !["WHITESPACE", "COMMENT"].includes(token.type)), typeReferences = new Set(referenceTokens.filter((token, index) => {
|
|
244
|
+
if (referenceTokens[index - 1]?.value === ".")
|
|
245
|
+
return !1;
|
|
246
|
+
const next = referenceTokens[index + 1]?.value;
|
|
247
|
+
return next !== ":" && !(next === "?" && referenceTokens[index + 2]?.value === ":");
|
|
248
|
+
}).map((token) => token.value)), usedImports = imports.filter((imported) => (imported.binding.match(/[A-Za-z_$][\w$]*/g) || []).filter((name) => !["type", "as"].includes(name)).some((name) => typeReferences.has(name)));
|
|
240
249
|
for (const imported of usedImports)
|
|
241
250
|
if (imported.module.startsWith(".") || path.isAbsolute(imported.module))
|
|
242
251
|
throw Error(`${file}: public method types import ${JSON.stringify(imported.module)} outside the generated package; declare these types in the component or import them from a published dependency`);
|
|
243
252
|
const typeImports = [...new Set(usedImports.map((imported) => `import type ${imported.binding.replace(/\btype\s+/g, "")} from ${JSON.stringify(imported.module)}`))];
|
|
244
|
-
return { methods, declarations, types:
|
|
253
|
+
return { methods, declarations, types: types.join(`
|
|
245
254
|
|
|
255
|
+
`), typeImports: typeImports.join(`
|
|
246
256
|
`) };
|
|
247
257
|
}
|
|
248
258
|
function extractTemplate(source) {
|
|
@@ -311,7 +321,7 @@ export function parseNativeComponentLoop(expression) {
|
|
|
311
321
|
const pair = /^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec(expression.trim());
|
|
312
322
|
return pair ? { iterable: pair[1], key: pair[2], value: pair[3] } : void 0;
|
|
313
323
|
}
|
|
314
|
-
function compileTemplateToRender(template) {
|
|
324
|
+
function compileTemplateToRender(template, handlers) {
|
|
315
325
|
const parts = [];
|
|
316
326
|
let cursor = 0;
|
|
317
327
|
const source = template.replace(/\{\{--[\s\S]*?--\}\}/g, ""), directive = /@(if|elseif|else|endif|foreach|endforeach)\s*/g;
|
|
@@ -320,12 +330,12 @@ function compileTemplateToRender(template) {
|
|
|
320
330
|
if (raw === "")
|
|
321
331
|
return;
|
|
322
332
|
let index = 0;
|
|
323
|
-
const interpolation = /\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g;
|
|
333
|
+
const interpolation = /\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}|(data-stx-on-[\w:-]+=")(\d+)(")/g;
|
|
324
334
|
let hit;
|
|
325
335
|
while (hit = interpolation.exec(raw)) {
|
|
326
336
|
if (hit.index > index)
|
|
327
337
|
parts.push(`out += ${JSON.stringify(raw.slice(index, hit.index))};`);
|
|
328
|
-
parts.push(hit[1] !== void 0 ? `out += __raw(${hit[1]});` : `out += __escape(${hit[2]});`);
|
|
338
|
+
parts.push(hit[3] !== void 0 ? `out += ${JSON.stringify(hit[3])} + (this._handlers.push(${handlers[Number(hit[4])]}) - 1) + ${JSON.stringify(hit[5])};` : hit[1] !== void 0 ? `out += __raw(${hit[1]});` : `out += __escape(${hit[2]});`);
|
|
329
339
|
index = hit.index + hit[0].length;
|
|
330
340
|
}
|
|
331
341
|
if (index < raw.length)
|
|
@@ -410,7 +420,7 @@ function hoistScriptImports(code) {
|
|
|
410
420
|
last++;
|
|
411
421
|
const end = start + tokens[last].end;
|
|
412
422
|
spans.push({ start, end });
|
|
413
|
-
if (specifier.value.slice(1, -1)
|
|
423
|
+
if (!["stx", "@stacksjs/stx"].includes(specifier.value.slice(1, -1)))
|
|
414
424
|
imports.push(code.slice(start, end));
|
|
415
425
|
}
|
|
416
426
|
let body = code;
|
|
@@ -419,13 +429,14 @@ function hoistScriptImports(code) {
|
|
|
419
429
|
return { imports, body };
|
|
420
430
|
}
|
|
421
431
|
function compileScriptScope(source) {
|
|
422
|
-
const
|
|
432
|
+
const blocks = scanHtmlScriptElements(componentScriptSource(source)).filter((script) => {
|
|
423
433
|
const attrs = scriptAttributes(script.attrs);
|
|
424
|
-
return scriptContainsCode(attrs) && !["component", "stx:component", "
|
|
434
|
+
return scriptContainsCode(attrs) && !["component", "stx:component", "server", "src"].some((name) => attrs.has(name));
|
|
425
435
|
});
|
|
426
|
-
if (!
|
|
427
|
-
return { imports: [], body: "", propNames: [], propBindings: {}, defaults: {}, declared: {} };
|
|
428
|
-
let code = source.slice(block.bodyStart, block.bodyEnd)
|
|
436
|
+
if (!blocks.length)
|
|
437
|
+
return { imports: [], body: "", propNames: [], propBindings: {}, defaults: {}, declared: {}, apis: [] };
|
|
438
|
+
let code = blocks.map((block) => source.slice(block.bodyStart, block.bodyEnd)).join(`
|
|
439
|
+
`);
|
|
429
440
|
const imports = [], propNames = [], propBindings = Object.create(null), defaults = Object.create(null), declared = Object.create(null), hoisted = hoistScriptImports(code);
|
|
430
441
|
imports.push(...hoisted.imports);
|
|
431
442
|
code = hoisted.body;
|
|
@@ -437,31 +448,38 @@ function compileScriptScope(source) {
|
|
|
437
448
|
Object.assign(declared, props.declared);
|
|
438
449
|
code = code.replace(props.text, props.identifier ? `const ${props.identifier} = this._props();` : "");
|
|
439
450
|
}
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
propNames.push(name);
|
|
451
|
+
if (props?.typeName) {
|
|
452
|
+
const type = localType(code, props.typeName);
|
|
453
|
+
if (type)
|
|
454
|
+
for (const member of splitTopLevel(type.slice(1, -1), `;,
|
|
455
|
+
`, !0)) {
|
|
456
|
+
const parsed = /^(?:readonly\s+)?([A-Za-z_$][\w$]*)\??\s*:\s*([\s\S]+)$/.exec(member);
|
|
457
|
+
if (!parsed)
|
|
458
|
+
continue;
|
|
459
|
+
declared[parsed[1]] = parsed[2].trim();
|
|
460
|
+
if (!propNames.includes(parsed[1]))
|
|
461
|
+
propNames.push(parsed[1]);
|
|
462
|
+
}
|
|
453
463
|
}
|
|
454
|
-
|
|
455
|
-
|
|
464
|
+
const emits = parseEmitsDeclaration(code);
|
|
465
|
+
if (emits)
|
|
466
|
+
code = code.replace(emits.text, "this._emitScope.bind(this)");
|
|
467
|
+
const publicMask = stripCommentsAndLiterals(code), publicDepths = bracketDepths(publicMask).depths;
|
|
468
|
+
for (const match of [...publicMask.matchAll(/\bexport\s+(?=(?:interface|type|const|let|var|async|function)\b)/g)].reverse())
|
|
469
|
+
if (publicDepths[match.index] === 0)
|
|
470
|
+
code = code.slice(0, match.index) + " ".repeat(match[0].length) + code.slice(match.index + match[0].length);
|
|
471
|
+
const locals = new Set(topLevelDeclarationSites(code).map((site) => site.name)), masked = stripCommentsAndLiterals(code), apis = ["state", "derived", "effect", "batch", "onMount", "onDestroy"].filter((name) => !locals.has(name) && new RegExp(`\\b${name}\\s*(?:<|\\()`).test(masked));
|
|
472
|
+
return { imports, body: code.trim(), propNames, propBindings, defaults, declared, apis };
|
|
456
473
|
}
|
|
457
474
|
function compileEventDirectives(template) {
|
|
458
|
-
const eventTypes = new Set;
|
|
459
|
-
return { template: template.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([
|
|
475
|
+
const eventTypes = new Set, handlers = [];
|
|
476
|
+
return { template: template.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([\s\S]*?)\3/gi, (_match, eventName, modifiers, _quote, expression) => {
|
|
460
477
|
const event = eventName.toLowerCase();
|
|
461
478
|
eventTypes.add(event);
|
|
462
|
-
const normalizedModifiers = (modifiers || "").split(".").filter(Boolean).join(" ");
|
|
463
|
-
|
|
464
|
-
|
|
479
|
+
const normalizedModifiers = (modifiers || "").split(".").filter(Boolean).join(" "), id = handlers.length;
|
|
480
|
+
handlers.push(/^[A-Za-z_$][\w$]*$/.test(expression.trim()) ? `($event) => (typeof ${expression} === 'function' ? ${expression} : this[${JSON.stringify(expression.trim())}]).call(this, $event)` : `($event) => { ${expression} }`);
|
|
481
|
+
return ` data-stx-on-${event}="${id}"${normalizedModifiers ? ` data-stx-mod-${event}="${normalizedModifiers}"` : ""}`;
|
|
482
|
+
}), eventTypes: [...eventTypes].sort(), handlers };
|
|
465
483
|
}
|
|
466
484
|
function compileDynamicBindings(template) {
|
|
467
485
|
const bindings = [];
|
|
@@ -502,7 +520,7 @@ async function compileComponent(inputDir, entry, defaults) {
|
|
|
502
520
|
scope.imports.push(...hoistScriptImports(source.slice(script.bodyStart, script.bodyEnd)).imports);
|
|
503
521
|
}
|
|
504
522
|
scope.imports = [...new Set(scope.imports)];
|
|
505
|
-
const render = compileTemplateToRender(bindingCompilation.template);
|
|
523
|
+
const render = compileTemplateToRender(bindingCompilation.template, eventCompilation.handlers);
|
|
506
524
|
for (const propertyName of scope.propNames) {
|
|
507
525
|
if (properties[propertyName])
|
|
508
526
|
continue;
|
|
@@ -524,11 +542,18 @@ async function compileComponent(inputDir, entry, defaults) {
|
|
|
524
542
|
shadowMode: normalizeShadowMode(entry.shadowDOM ?? metadata.shadowDOM ?? defaults.shadowDOM),
|
|
525
543
|
progressive: entry.progressive ?? metadata.progressive ?? defaults.progressive ?? !0,
|
|
526
544
|
properties,
|
|
527
|
-
events:
|
|
545
|
+
events: { ...parseEmitsDeclaration(scanHtmlScriptElements(componentScriptSource(source)).filter((script) => {
|
|
546
|
+
const attrs = scriptAttributes(script.attrs);
|
|
547
|
+
return scriptContainsCode(attrs) && !["server", "component", "stx:component", "src"].some((name) => attrs.has(name));
|
|
548
|
+
}).map((script) => source.slice(script.bodyStart, script.bodyEnd)).join(`
|
|
549
|
+
`))?.events || {}, ...entry.events || metadata.events || {} },
|
|
528
550
|
methods: { ...metadataMethods, ...configuredMethods, ...extractedMethods.methods },
|
|
529
551
|
methodDeclarations: extractedMethods.declarations,
|
|
530
552
|
declarationTypes: extractedMethods.types,
|
|
553
|
+
declarationImports: extractedMethods.typeImports,
|
|
531
554
|
eventTypes: eventCompilation.eventTypes,
|
|
555
|
+
handlers: eventCompilation.handlers,
|
|
556
|
+
scopeMethods: Object.keys(extractedMethods.methods),
|
|
532
557
|
bindings: bindingCompilation.bindings,
|
|
533
558
|
slots: extractSlots(bindingCompilation.template),
|
|
534
559
|
cssProperties: extractCssProperties(extractStyles(source)),
|
|
@@ -536,9 +561,10 @@ async function compileComponent(inputDir, entry, defaults) {
|
|
|
536
561
|
render
|
|
537
562
|
};
|
|
538
563
|
}
|
|
539
|
-
function runtimeModule() {
|
|
564
|
+
function runtimeModule(signals = !1) {
|
|
540
565
|
const rawInterpolation = JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"), escapedInterpolation = JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");
|
|
541
|
-
return `
|
|
566
|
+
return `${signals ? `import { state as nativeState, derived as nativeDerived, effect as nativeEffect, batch as nativeBatch } from './signals.js';
|
|
567
|
+
` : ""}const HTMLElementBase = globalThis.HTMLElement || class {};
|
|
542
568
|
|
|
543
569
|
const escapeHTML = (value) => String(value ?? '')
|
|
544
570
|
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
@@ -600,6 +626,14 @@ export class StxElement extends HTMLElementBase {
|
|
|
600
626
|
this._initializing = false;
|
|
601
627
|
this._updatePending = false;
|
|
602
628
|
this._listeners = new Map();
|
|
629
|
+
this._scopeStates = [];
|
|
630
|
+
this._scopeDerived = [];
|
|
631
|
+
this._scopeEffects = [];
|
|
632
|
+
this._scopeSubscriptions = [];
|
|
633
|
+
this._scopeMounts = [];
|
|
634
|
+
this._scopeDestroys = [];
|
|
635
|
+
this._scopeConnectionDestroys = [];
|
|
636
|
+
this._scopeMountCleanups = [];
|
|
603
637
|
const definition = this.constructor.definition;
|
|
604
638
|
for (const [name, property] of Object.entries(definition.properties || {})) {
|
|
605
639
|
this._values[name] = defaultFor(property);
|
|
@@ -630,7 +664,10 @@ export class StxElement extends HTMLElementBase {
|
|
|
630
664
|
const hasMarkup = [...(root.childNodes || [])].some(node => node.nodeType !== 3 || node.textContent.trim());
|
|
631
665
|
const firstConnection = !this._hasConnected;
|
|
632
666
|
if (!(firstConnection && definition.progressive && hasMarkup)) this._render();
|
|
633
|
-
else
|
|
667
|
+
else {
|
|
668
|
+
if (typeof this.render === 'function') this.render(RENDER_HELPERS);
|
|
669
|
+
this._upgradeDeclarativeEvents();
|
|
670
|
+
}
|
|
634
671
|
this._bindEvents();
|
|
635
672
|
if (firstConnection) {
|
|
636
673
|
this._hasConnected = true;
|
|
@@ -640,6 +677,7 @@ export class StxElement extends HTMLElementBase {
|
|
|
640
677
|
// Called last, so a component that acquires something sees its own rendered
|
|
641
678
|
// markup and its events already bound. Reported rather than rethrown: a
|
|
642
679
|
// component that fails to set up must not take the element down with it.
|
|
680
|
+
this._runScopeMounts();
|
|
643
681
|
try { this.onConnect?.(); }
|
|
644
682
|
catch (error) { console.error('[stx] onConnect failed', error); }
|
|
645
683
|
}
|
|
@@ -652,6 +690,13 @@ export class StxElement extends HTMLElementBase {
|
|
|
652
690
|
try { this.onDisconnect?.(); }
|
|
653
691
|
catch (error) { console.error('[stx] onDisconnect failed', error); }
|
|
654
692
|
finally {
|
|
693
|
+
this._disposeScopeEffects();
|
|
694
|
+
for (const dispose of this._scopeSubscriptions.splice(0)) {
|
|
695
|
+
try { dispose?.(); } catch (error) { console.error('[stx] scope subscription cleanup failed', error); }
|
|
696
|
+
}
|
|
697
|
+
for (const cleanup of [...this._scopeDestroys.splice(0), ...this._scopeConnectionDestroys.splice(0), ...this._scopeMountCleanups.splice(0)]) {
|
|
698
|
+
try { cleanup(); } catch (error) { console.error('[stx] scope cleanup failed', error); }
|
|
699
|
+
}
|
|
655
700
|
for (const [event, listener] of this._listeners) this.renderRoot.removeEventListener(event, listener);
|
|
656
701
|
this._listeners.clear();
|
|
657
702
|
}
|
|
@@ -700,6 +745,69 @@ export class StxElement extends HTMLElementBase {
|
|
|
700
745
|
}));
|
|
701
746
|
}
|
|
702
747
|
|
|
748
|
+
_disposeScopeEffects() {
|
|
749
|
+
for (const dispose of this._scopeEffects.splice(0)) {
|
|
750
|
+
try { dispose(); } catch (error) { console.error('[stx] effect cleanup failed', error); }
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
_runScopeMounts() {
|
|
755
|
+
for (const mount of this._scopeMounts) {
|
|
756
|
+
try { const cleanup = mount(); if (typeof cleanup === 'function') this._scopeMountCleanups.push(cleanup); }
|
|
757
|
+
catch (error) { console.error('[stx] onMount failed', error); }
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
${signals ? ` _beginScope() {
|
|
762
|
+
this._disposeScopeEffects();
|
|
763
|
+
this._scopeMounts = [];
|
|
764
|
+
this._scopeDestroys = [];
|
|
765
|
+
let stateIndex = 0, derivedIndex = 0;
|
|
766
|
+
let rendering = true;
|
|
767
|
+
return {
|
|
768
|
+
finish: () => { rendering = false; },
|
|
769
|
+
state: (initial) => {
|
|
770
|
+
const index = stateIndex++;
|
|
771
|
+
const value = this._scopeStates[index] ||= nativeState(initial);
|
|
772
|
+
if (this._connected && !this._scopeSubscriptions[index]) this._scopeSubscriptions[index] = value.subscribe(() => this.requestUpdate());
|
|
773
|
+
return value;
|
|
774
|
+
},
|
|
775
|
+
derived: (compute, options) => {
|
|
776
|
+
const index = derivedIndex++;
|
|
777
|
+
let entry = this._scopeDerived[index];
|
|
778
|
+
if (!entry) {
|
|
779
|
+
entry = { compute, revision: nativeState(0) };
|
|
780
|
+
entry.value = nativeDerived(() => { entry.revision(); return entry.compute(); }, options);
|
|
781
|
+
this._scopeDerived[index] = entry;
|
|
782
|
+
} else {
|
|
783
|
+
entry.compute = compute;
|
|
784
|
+
entry.revision.update(value => value + 1);
|
|
785
|
+
}
|
|
786
|
+
return entry.value;
|
|
787
|
+
},
|
|
788
|
+
effect: (callback, options) => {
|
|
789
|
+
const dispose = nativeEffect(callback, options);
|
|
790
|
+
this._scopeEffects.push(dispose);
|
|
791
|
+
return dispose;
|
|
792
|
+
},
|
|
793
|
+
batch: nativeBatch,
|
|
794
|
+
onMount: callback => this._scopeMounts.push(callback),
|
|
795
|
+
onDestroy: callback => (rendering ? this._scopeDestroys : this._scopeConnectionDestroys).push(callback),
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
` : ""} _emitScope(name, ...args) {
|
|
800
|
+
return this.emit(name, args.length === 1 ? args[0] : args, { cancelable: true });
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
_callScopeMethod(name, args) {
|
|
804
|
+
// Template calls already have this render's current prop closures. Refresh
|
|
805
|
+
// pending props only for an outside call, otherwise a public helper in the
|
|
806
|
+
// template would recursively render while the queued update is pending.
|
|
807
|
+
if (!this._scopeRenderDepth && (!this._scopeMethods || this._updatePending)) this.render(RENDER_HELPERS);
|
|
808
|
+
return this._scopeMethods[name].apply(this, args);
|
|
809
|
+
}
|
|
810
|
+
|
|
703
811
|
_upgradeProperty(name) {
|
|
704
812
|
if (!Object.prototype.hasOwnProperty.call(this, name)) return;
|
|
705
813
|
const value = this[name];
|
|
@@ -728,10 +836,12 @@ export class StxElement extends HTMLElementBase {
|
|
|
728
836
|
const target = $event.target?.closest?.(selector);
|
|
729
837
|
if (!target || !this.renderRoot.contains(target)) return;
|
|
730
838
|
const modifiers = (target.getAttribute('data-stx-mod-' + event) || '').split(' ');
|
|
839
|
+
if (modifiers.includes('self') && target !== $event.target) return;
|
|
731
840
|
if (modifiers.includes('prevent')) $event.preventDefault();
|
|
732
841
|
if (modifiers.includes('stop')) $event.stopPropagation();
|
|
733
842
|
const method = target.getAttribute('data-stx-on-' + event);
|
|
734
|
-
if (
|
|
843
|
+
if (this._handlers?.[method]) this._handlers[method]($event);
|
|
844
|
+
else if (typeof this[method] === 'function') this[method]($event);
|
|
735
845
|
};
|
|
736
846
|
this.renderRoot.addEventListener(event, listener);
|
|
737
847
|
this._listeners.set(event, listener);
|
|
@@ -881,7 +991,12 @@ ${body}
|
|
|
881
991
|
}`;
|
|
882
992
|
}).join(`
|
|
883
993
|
|
|
884
|
-
`), scope = component.scope,
|
|
994
|
+
`), scope = component.scope, localNames = new Set(new Tokenizer([scope.body, ...scope.imports, ...Object.keys(component.properties), ...Object.values(scope.propBindings)].join(`
|
|
995
|
+
`)).tokenize().map((token) => token.value));
|
|
996
|
+
let scopeOwner = "__stxScope";
|
|
997
|
+
while (localNames.has(scopeOwner))
|
|
998
|
+
scopeOwner += "$";
|
|
999
|
+
const destructured = [...new Set([...Object.keys(component.properties), ...scope.propNames])].map((name) => {
|
|
885
1000
|
const binding = scope.propBindings[name] || name;
|
|
886
1001
|
return scope.defaults[name] === void 0 ? binding : `${binding} = ${scope.defaults[name]}`;
|
|
887
1002
|
}).join(", "), indent = (code) => code.split(`
|
|
@@ -890,10 +1005,15 @@ ${body}
|
|
|
890
1005
|
let renderMethod = "";
|
|
891
1006
|
if (component.render.trim() !== "" || scope.body !== "" || destructured !== "") {
|
|
892
1007
|
const inner = [
|
|
1008
|
+
scope.apis.length ? `const ${scopeOwner} = this._beginScope();
|
|
1009
|
+
const { ${scope.apis.join(", ")} } = ${scopeOwner};` : "",
|
|
893
1010
|
destructured ? `const { ${destructured} } = this._props();` : "",
|
|
894
1011
|
scope.body,
|
|
1012
|
+
component.scopeMethods.length ? `this._scopeMethods = { ${component.scopeMethods.join(", ")} };` : "",
|
|
1013
|
+
component.handlers.length ? "this._handlers = [];" : "",
|
|
895
1014
|
"let out = '';",
|
|
896
1015
|
component.render,
|
|
1016
|
+
scope.apis.length ? `${scopeOwner}.finish();` : "",
|
|
897
1017
|
"return out;"
|
|
898
1018
|
].filter(Boolean).join(`
|
|
899
1019
|
`);
|
|
@@ -908,8 +1028,13 @@ ${inner}
|
|
|
908
1028
|
}
|
|
909
1029
|
renderMethod = `
|
|
910
1030
|
render(__helpers) {
|
|
911
|
-
|
|
912
|
-
|
|
1031
|
+
this._scopeRenderDepth = (this._scopeRenderDepth || 0) + 1;
|
|
1032
|
+
try {
|
|
1033
|
+
const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
|
|
1034
|
+
${indent(indent(compiled.trim()))}
|
|
1035
|
+
} finally {
|
|
1036
|
+
this._scopeRenderDepth--;
|
|
1037
|
+
}
|
|
913
1038
|
}
|
|
914
1039
|
`;
|
|
915
1040
|
}
|
|
@@ -943,13 +1068,31 @@ export function typeForProperty(property) {
|
|
|
943
1068
|
}
|
|
944
1069
|
}
|
|
945
1070
|
function componentDeclaration(component) {
|
|
946
|
-
const
|
|
947
|
-
`),
|
|
1071
|
+
const authoredTypes = [component.declarationTypes, component.declarationImports, component.name, ...Object.values(component.methodDeclarations).flat(), ...Object.values(component.events).map((event) => event.detailType)].join(`
|
|
1072
|
+
`), identifiers = new Set(new Tokenizer(authoredTypes).tokenize().map((token) => token.value)), unique = (base) => {
|
|
1073
|
+
let name = base;
|
|
1074
|
+
while (identifiers.has(name))
|
|
1075
|
+
name += "$";
|
|
1076
|
+
identifiers.add(name);
|
|
1077
|
+
return name;
|
|
1078
|
+
}, support = unique("__StxSupport"), publicMethods = unique("__Methods"), eventDetails = unique("__Details"), scoped = !!component.declarationTypes, props = Object.entries(component.properties).map(([name, property]) => ` ${name}${property.required ? "" : "?"}: ${typeForProperty(property)}`).join(`
|
|
1079
|
+
`), events = Object.entries(component.events).map(([name, event]) => ` ${JSON.stringify(name)}: CustomEvent<${scoped ? `${support}.${eventDetails}[${JSON.stringify(name)}]` : event.detailType || "unknown"}>`).join(`
|
|
948
1080
|
`), methods = Object.keys(component.methods).flatMap((name) => component.methodDeclarations[name] || [`${name}($event?: Event): unknown`]).map((signature) => ` ${signature}`).join(`
|
|
949
|
-
`)
|
|
950
|
-
|
|
1081
|
+
`), supportDeclaration = scoped ? `declare namespace ${support} {
|
|
1082
|
+
${component.declarationTypes}
|
|
1083
|
+
export interface ${publicMethods} {
|
|
1084
|
+
${methods}
|
|
1085
|
+
}
|
|
1086
|
+
export interface ${eventDetails} {
|
|
1087
|
+
${Object.entries(component.events).map(([name, event]) => ` ${JSON.stringify(name)}: ${event.detailType || "unknown"}`).join(`
|
|
1088
|
+
`)}
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
` : "";
|
|
1093
|
+
return `${component.declarationImports ? component.declarationImports + `
|
|
951
1094
|
|
|
952
|
-
` : ""}export interface ${component.name}Props {
|
|
1095
|
+
` : ""}${supportDeclaration}export interface ${component.name}Props {
|
|
953
1096
|
${props}
|
|
954
1097
|
}
|
|
955
1098
|
|
|
@@ -957,10 +1100,16 @@ export interface ${component.name}EventMap {
|
|
|
957
1100
|
${events}
|
|
958
1101
|
}
|
|
959
1102
|
|
|
960
|
-
export interface ${component.name} extends Required<Pick<${component.name}Props, Exclude<keyof ${component.name}Props, keyof HTMLElement
|
|
1103
|
+
export interface ${component.name} extends Required<Pick<${component.name}Props, Exclude<keyof ${component.name}Props, keyof HTMLElement>>>${scoped ? `, ${support}.${publicMethods}` : ""} {}
|
|
961
1104
|
|
|
962
1105
|
export declare class ${component.name} extends HTMLElement {
|
|
963
|
-
${methods}
|
|
1106
|
+
${scoped ? "" : methods}
|
|
1107
|
+
addEventListener<K extends keyof ${component.name}EventMap>(type: K, listener: (this: ${component.name}, event: ${component.name}EventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void
|
|
1108
|
+
addEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, event: HTMLElementEventMap[K]) => unknown, options?: boolean | AddEventListenerOptions): void
|
|
1109
|
+
addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void
|
|
1110
|
+
removeEventListener<K extends keyof ${component.name}EventMap>(type: K, listener: (this: ${component.name}, event: ${component.name}EventMap[K]) => unknown, options?: boolean | EventListenerOptions): void
|
|
1111
|
+
removeEventListener<K extends keyof HTMLElementEventMap>(type: K, listener: (this: HTMLElement, event: HTMLElementEventMap[K]) => unknown, options?: boolean | EventListenerOptions): void
|
|
1112
|
+
removeEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions): void
|
|
964
1113
|
readonly updateComplete: Promise<void>
|
|
965
1114
|
requestUpdate(): Promise<void>
|
|
966
1115
|
emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
|
|
@@ -982,7 +1131,7 @@ function customElementsDeclaration(components) {
|
|
|
982
1131
|
${components.map((component) => {
|
|
983
1132
|
const props = Object.entries(component.properties).map(([name, property]) => ` ${JSON.stringify(name)}?: ${typeForProperty(property)}`).join(`
|
|
984
1133
|
`), events = Object.keys(component.events).map((event) => {
|
|
985
|
-
return ` ${`on${event.split(/[-:]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("")}`}?: (event:
|
|
1134
|
+
return ` ${`on${event.split(/[-:]/).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("")}`}?: (event: import('./${component.tag}.js').${component.name}EventMap[${JSON.stringify(event)}]) => void`;
|
|
986
1135
|
}).join(`
|
|
987
1136
|
`);
|
|
988
1137
|
return ` ${JSON.stringify(component.tag)}: {
|
|
@@ -1116,8 +1265,10 @@ export async function buildComponentLibrary(config) {
|
|
|
1116
1265
|
if (!files.includes(target))
|
|
1117
1266
|
files.push(target);
|
|
1118
1267
|
return target;
|
|
1119
|
-
};
|
|
1120
|
-
|
|
1268
|
+
}, signals = components.some((component) => component.scope.apis.length), extension = import.meta.url.endsWith(".ts") ? ".ts" : ".js", nativeSignals = new URL(`./signals-api${extension}`, import.meta.url).pathname;
|
|
1269
|
+
if (signals)
|
|
1270
|
+
await emit("signals.js", `export * from ${JSON.stringify(nativeSignals)};`);
|
|
1271
|
+
await emit("runtime.js", runtimeModule(signals));
|
|
1121
1272
|
for (const component of components) {
|
|
1122
1273
|
await emit(`${component.tag}.js`, componentModule(component));
|
|
1123
1274
|
if (config.declarations !== !1)
|
|
@@ -1128,11 +1279,15 @@ export async function buildComponentLibrary(config) {
|
|
|
1128
1279
|
}
|
|
1129
1280
|
}
|
|
1130
1281
|
const importScanner = new Bun.Transpiler({ loader: "ts" });
|
|
1131
|
-
if (components.some((component) => component.scope.imports.length || importScanner.scanImports(componentModule(component)).some((imported) => imported.kind === "dynamic-import"))) {
|
|
1282
|
+
if (signals || components.some((component) => component.scope.imports.length || importScanner.scanImports(componentModule(component)).some((imported) => imported.kind === "dynamic-import"))) {
|
|
1132
1283
|
const entrypoints = components.map((component) => path.join(outputDir, `${component.tag}.js`)), canonicalEntries = new Map(await Promise.all(entrypoints.map(async (file, index) => [await realpath(file), components[index]])));
|
|
1133
1284
|
for (const [index, file] of entrypoints.entries())
|
|
1134
1285
|
canonicalEntries.set(file, components[index]);
|
|
1135
|
-
const sourceEntries = new Map(components.map((component) => [path.join(path.dirname(component.sourcePath), `.stx-library-${component.tag}.ts`), component])), runtimePath = path.join(outputDir, "runtime.js")
|
|
1286
|
+
const sourceEntries = new Map(components.map((component) => [path.join(path.dirname(component.sourcePath), `.stx-library-${component.tag}.ts`), component])), runtimePath = path.join(outputDir, "runtime.js");
|
|
1287
|
+
entrypoints.push(runtimePath);
|
|
1288
|
+
if (signals)
|
|
1289
|
+
entrypoints.push(path.join(outputDir, "signals.js"));
|
|
1290
|
+
const built = await Bun.build({
|
|
1136
1291
|
entrypoints,
|
|
1137
1292
|
outdir: outputDir,
|
|
1138
1293
|
root: outputDir,
|
|
@@ -1150,7 +1305,9 @@ export async function buildComponentLibrary(config) {
|
|
|
1150
1305
|
if (!args.importer && entry)
|
|
1151
1306
|
return { path: path.join(path.dirname(entry.sourcePath), `.stx-library-${entry.tag}.ts`) };
|
|
1152
1307
|
if (args.path === runtimePath && sourceEntries.has(args.importer))
|
|
1153
|
-
return { path:
|
|
1308
|
+
return { path: runtimePath };
|
|
1309
|
+
if (/^(?:@stacksjs\/stx|stx)\/signals-api(?:\.[jt]s)?$/.test(args.path))
|
|
1310
|
+
return { path: nativeSignals };
|
|
1154
1311
|
});
|
|
1155
1312
|
builder.onLoad({ filter: /\.ts$/ }, (args) => {
|
|
1156
1313
|
const component = sourceEntries.get(args.path);
|
|
@@ -623,6 +623,15 @@ function forwardHostAttrs(html, props, declaredProps = new Set, consumedProps =
|
|
|
623
623
|
const root = findRenderedComponentHostRoot(html, nativeTarget);
|
|
624
624
|
if (!root)
|
|
625
625
|
return html;
|
|
626
|
+
const outer = nativeTarget ? findRenderedComponentRoot(html) : null;
|
|
627
|
+
if (outer) {
|
|
628
|
+
const alternates = findOwnedNativeHostRoots(html, outer).filter((other) => other.insertPos > root.insertPos);
|
|
629
|
+
for (let index = alternates.length - 1;index >= 0; index--)
|
|
630
|
+
html = forwardHostAttrsTo(html, alternates[index], props, declaredProps, consumedProps, nativeTarget);
|
|
631
|
+
}
|
|
632
|
+
return forwardHostAttrsTo(html, root, props, declaredProps, consumedProps, nativeTarget);
|
|
633
|
+
}
|
|
634
|
+
function forwardHostAttrsTo(html, root, props, declaredProps, consumedProps, nativeTarget) {
|
|
626
635
|
let openingTag = html.slice(root.insertPos, root.tagEnd);
|
|
627
636
|
const callerClass = props.serverDynamic.class ?? props.static.class;
|
|
628
637
|
if (nativeTarget && typeof callerClass === "string" && callerClass && !consumedProps.has("class")) {
|
|
@@ -703,15 +712,19 @@ function findRenderedComponentHostRoot(html, nativeTarget = !1) {
|
|
|
703
712
|
return root && nativeTarget ? findOwnedNativeHostRoot(html, root) ?? root : root;
|
|
704
713
|
}
|
|
705
714
|
function findOwnedNativeHostRoot(html, root) {
|
|
715
|
+
return findOwnedNativeHostRoots(html, root)[0] ?? null;
|
|
716
|
+
}
|
|
717
|
+
function findOwnedNativeHostRoots(html, root) {
|
|
718
|
+
const found = [];
|
|
706
719
|
if (!html.includes("data-stx-native-host-root"))
|
|
707
|
-
return
|
|
720
|
+
return found;
|
|
708
721
|
const voidTags = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
|
|
709
722
|
let cursor = html.lastIndexOf("<", root.insertPos), depth = 0, foreignDepth;
|
|
710
723
|
while (cursor >= 0 && cursor < html.length) {
|
|
711
724
|
if (html.startsWith("<!--", cursor)) {
|
|
712
725
|
const end = html.indexOf("-->", cursor + 4);
|
|
713
726
|
if (end < 0)
|
|
714
|
-
return
|
|
727
|
+
return found;
|
|
715
728
|
cursor = html.indexOf("<", end + 3);
|
|
716
729
|
continue;
|
|
717
730
|
}
|
|
@@ -726,28 +739,28 @@ function findOwnedNativeHostRoot(html, root) {
|
|
|
726
739
|
if (foreignDepth !== void 0 && depth < foreignDepth)
|
|
727
740
|
foreignDepth = void 0;
|
|
728
741
|
if (depth <= 0)
|
|
729
|
-
return
|
|
742
|
+
return found;
|
|
730
743
|
} else if (name === "script" || name === "style") {
|
|
731
744
|
const close = new RegExp(`</${name}\\s*>`, "gi");
|
|
732
745
|
close.lastIndex = tagEnd + 1;
|
|
733
746
|
if (!close.exec(html))
|
|
734
|
-
return
|
|
747
|
+
return found;
|
|
735
748
|
cursor = html.indexOf("<", close.lastIndex);
|
|
736
749
|
continue;
|
|
737
750
|
} else {
|
|
738
|
-
const attributes = parseAllAttributes(html.slice(insertPos, tagEnd)), foreign = depth > 0 && (Object.hasOwn(attributes, "data-stx-component-wrapper") || Object.hasOwn(attributes, "data-stx-native-host-owner"));
|
|
739
|
-
if (
|
|
740
|
-
|
|
751
|
+
const attributes = parseAllAttributes(html.slice(insertPos, tagEnd)), foreign = depth > 0 && (Object.hasOwn(attributes, "data-stx-component-wrapper") || Object.hasOwn(attributes, "data-stx-native-host-owner")), marked = foreignDepth === void 0 && !foreign && Object.hasOwn(attributes, "data-stx-native-host-root");
|
|
752
|
+
if (marked)
|
|
753
|
+
found.push({ insertPos, tagEnd });
|
|
741
754
|
if (!voidTags.has(name) && html[tagEnd - 1] !== "/") {
|
|
742
755
|
depth++;
|
|
743
|
-
if (foreignDepth === void 0 && foreign)
|
|
756
|
+
if (foreignDepth === void 0 && (foreign || marked))
|
|
744
757
|
foreignDepth = depth;
|
|
745
758
|
} else if (depth === 0)
|
|
746
|
-
return
|
|
759
|
+
return found;
|
|
747
760
|
}
|
|
748
761
|
cursor = html.indexOf("<", tagEnd + 1);
|
|
749
762
|
}
|
|
750
|
-
return
|
|
763
|
+
return found;
|
|
751
764
|
}
|
|
752
765
|
function findFirstRenderedElement(html, start) {
|
|
753
766
|
let cursor = start;
|
|
@@ -74,7 +74,8 @@ export declare function setGlobalProvide<T>(key: string | symbol, value: T): voi
|
|
|
74
74
|
* emit('change', 'newValue')
|
|
75
75
|
* ```
|
|
76
76
|
*/
|
|
77
|
-
export declare function defineEmits<T extends
|
|
77
|
+
export declare function defineEmits<const T extends readonly string[]>(events: T): EmitFn<T[number]>;
|
|
78
|
+
export declare function defineEmits<T extends object = Record<string, any[]>>(events?: T): ComponentEmit<T>;
|
|
78
79
|
/**
|
|
79
80
|
* Expose public properties from a component instance.
|
|
80
81
|
* These properties become accessible via template refs from the parent.
|
|
@@ -195,3 +196,8 @@ export declare interface StxComponentInstance {
|
|
|
195
196
|
/** Type-safe emit function */
|
|
196
197
|
// eslint-disable-next-line pickier/no-unused-vars
|
|
197
198
|
export type EmitFn<T extends string = string> = (event: T, ...args: any[]) => void;
|
|
199
|
+
/** Tuple maps, payload maps and callable overload contracts share one emitter. */
|
|
200
|
+
export type ComponentEmit<T> = T extends (...args: never[]) => unknown ? T : <K extends Extract<keyof T, string>>(
|
|
201
|
+
event: K,
|
|
202
|
+
...args: T[K] extends readonly unknown[] ? T[K] : [payload: T[K]]
|
|
203
|
+
) => void;
|