@weapp-vite/wxml 0.0.0-stage → 0.1.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1657 @@
1
+ import { decodeXML } from "entities";
2
+ // src/lexical.ts
3
+ const lineEndPattern = /[\n\r\u2028\u2029]/g;
4
+ /** JS 行注释在任意行终止符处结束;正则只定位下一处,不逐字符分配结果。 */
5
+ function findLineEnd(source, start) {
6
+ lineEndPattern.lastIndex = start;
7
+ return lineEndPattern.exec(source)?.index ?? -1;
8
+ }
9
+ /** 词法错误携带原文偏移,由调用方选择报告或抛出。 */
10
+ var TemplateLexicalError = class extends Error {
11
+ offset;
12
+ recovery;
13
+ constructor(offset, message, recovery) {
14
+ super(message);
15
+ this.offset = offset;
16
+ this.recovery = recovery;
17
+ }
18
+ };
19
+ function isSpaceCode(code) {
20
+ if (code <= 32) return code === 32 || code >= 9 && code <= 13;
21
+ return code >= 160 && (code === 160 || code === 5760 || code >= 8192 && code <= 8202 || code === 8232 || code === 8233 || code === 8239 || code === 8287 || code === 12288 || code === 65279);
22
+ }
23
+ function isWordCode(code) {
24
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 95 || code === 36 || code >= 128;
25
+ }
26
+ function isNameCode(code) {
27
+ return isWordCode(code) || code === 58 || code === 46 || code === 45;
28
+ }
29
+ function isTagStartCode(code) {
30
+ return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code === 95;
31
+ }
32
+ function skipSpace(source, start) {
33
+ while (isSpaceCode(source.charCodeAt(start))) start++;
34
+ return start;
35
+ }
36
+ // src/attributeLayer.ts
37
+ /** 宿主属性层只移除每对反斜杠与后续字符中的第一字符,不解释 JS 转义。 */
38
+ function decodeLegacyAttributeLayer(value) {
39
+ return value.replace(/\\([\s\S])/g, "$1");
40
+ }
41
+ /** 外层引号是否结束属性只由宿主层的连续反斜杠奇偶决定。 */
42
+ function legacyAttributeEnd(source, start, quote) {
43
+ let end = source.indexOf(quote, start);
44
+ while (end >= 0) {
45
+ let previous = end - 1;
46
+ while (previous >= start && source.charCodeAt(previous) === 92) previous--;
47
+ if ((end - previous) % 2 !== 0) return end;
48
+ end = source.indexOf(quote, end + 1);
49
+ }
50
+ return -1;
51
+ }
52
+ /** 无转义不建立偏移表;有转义时只记录被移除字符的逻辑偏移。 */
53
+ function legacyAttributeSource(source, start, end) {
54
+ const content = source.slice(start, end);
55
+ if (!content.includes("\\")) return {
56
+ source: content,
57
+ start: 0,
58
+ end: content.length,
59
+ origin: start
60
+ };
61
+ const escapes = [];
62
+ const value = content.replace(/\\([\s\S])/g, (_match, character, offset) => {
63
+ escapes.push(offset - escapes.length);
64
+ return character;
65
+ });
66
+ return {
67
+ source: value,
68
+ start: 0,
69
+ end: value.length,
70
+ origin: start,
71
+ escapes
72
+ };
73
+ }
74
+ /** 逻辑字符仍映射到包含宿主层反斜杠的原始 UTF-16 位置。 */
75
+ function attributeSourcePosition(view, offset) {
76
+ const escapes = view.escapes;
77
+ let lower = 0;
78
+ let upper = escapes?.length ?? 0;
79
+ while (lower < upper) {
80
+ const middle = lower + upper >>> 1;
81
+ if (escapes[middle] < offset) lower = middle + 1;
82
+ else upper = middle;
83
+ }
84
+ return view.origin + offset + lower;
85
+ }
86
+ /** 诊断和可恢复插值范围始终引用原始源码,而非解码后的临时视图。 */
87
+ function attributeSourceError(view, error) {
88
+ if (error instanceof TemplateLexicalError) {
89
+ const recovery = error.recovery;
90
+ throw new TemplateLexicalError(attributeSourcePosition(view, error.offset), error.message, recovery && {
91
+ kind: recovery.kind,
92
+ start: attributeSourcePosition(view, recovery.start),
93
+ end: attributeSourcePosition(view, recovery.end)
94
+ });
95
+ }
96
+ throw error;
97
+ }
98
+ // src/context.ts
99
+ const expressionWord = 1;
100
+ const controlWord = 2;
101
+ const blockWord = 4;
102
+ const declarationPrefix = 8;
103
+ const lineBreakWord = 16;
104
+ const exportWord = 32;
105
+ const typeObjectWord = 64;
106
+ const functionWord = 128;
107
+ const classWord = 256;
108
+ const caseWord = 512;
109
+ const defaultWord = 1024;
110
+ const wordRoles = /* @__PURE__ */ new Map([
111
+ ["return", 17],
112
+ ["throw", expressionWord],
113
+ ["case", 513],
114
+ ["delete", expressionWord],
115
+ ["void", expressionWord],
116
+ ["typeof", expressionWord],
117
+ ["new", expressionWord],
118
+ ["in", expressionWord],
119
+ ["instanceof", expressionWord],
120
+ ["yield", 17],
121
+ ["await", expressionWord],
122
+ ["else", 5],
123
+ ["do", 5],
124
+ ["if", controlWord],
125
+ ["while", controlWord],
126
+ ["for", controlWord],
127
+ ["with", controlWord],
128
+ ["switch", controlWord],
129
+ ["catch", controlWord],
130
+ ["try", blockWord],
131
+ ["finally", blockWord],
132
+ ["async", declarationPrefix],
133
+ ["export", 40],
134
+ ["default", 1032],
135
+ ["extends", typeObjectWord],
136
+ ["keyof", typeObjectWord],
137
+ ["readonly", typeObjectWord],
138
+ ["is", typeObjectWord],
139
+ ["function", functionWord],
140
+ ["class", classWord]
141
+ ]);
142
+ const lineBreakPattern = /[\n\r\u2028\u2029]/;
143
+ const expressionAfter = 256;
144
+ const statementBody = 512;
145
+ const functionParameters = 1024;
146
+ const bracketMask = 255;
147
+ /** 保存有效 token 的词法目标,构造体正文按声明或表达式归属恢复斜杠判界。 */
148
+ var TokenContext = class {
149
+ operand = true;
150
+ previousRoles = 0;
151
+ previousCode;
152
+ brackets;
153
+ rootStatement;
154
+ statement;
155
+ label = false;
156
+ arrowBody = false;
157
+ headers;
158
+ questions;
159
+ cases;
160
+ constructor(expression = false) {
161
+ this.previousCode = expression ? -1 : 0;
162
+ this.rootStatement = this.statement = !expression;
163
+ }
164
+ get depth() {
165
+ return this.brackets?.length ?? 0;
166
+ }
167
+ get bracket() {
168
+ const frame = this.brackets?.[this.brackets.length - 1];
169
+ return frame === void 0 ? void 0 : frame & bracketMask;
170
+ }
171
+ word(source, start, end) {
172
+ if (this.previousCode === 46) {
173
+ this.value();
174
+ return;
175
+ }
176
+ const roles = wordRoles.get(source.slice(start, end)) ?? 0;
177
+ if (roles) {
178
+ this.keyword(roles);
179
+ return;
180
+ }
181
+ this.label = this.statement;
182
+ this.operand = this.statement = this.arrowBody = false;
183
+ this.previousRoles = 0;
184
+ this.previousCode = 1;
185
+ }
186
+ keyword(roles) {
187
+ const startsStatement = this.statement;
188
+ const caseLabel = startsStatement && Boolean(roles & caseWord || roles & defaultWord && !(this.previousRoles & exportWord));
189
+ if (roles & 384) (this.headers ??= []).push({
190
+ kind: roles & functionWord ? "function" : "class",
191
+ phase: "head",
192
+ depth: this.depth,
193
+ declaration: startsStatement,
194
+ angles: 0,
195
+ typed: false
196
+ });
197
+ if (caseLabel) (this.cases ??= []).push(this.depth);
198
+ this.label = startsStatement && !caseLabel && !(roles & 1447);
199
+ this.statement = Boolean(roles & blockWord || startsStatement && !caseLabel && roles & declarationPrefix);
200
+ this.previousRoles = roles;
201
+ this.previousCode = 1;
202
+ this.arrowBody = false;
203
+ this.operand = Boolean(roles & expressionWord);
204
+ }
205
+ value(code = 1) {
206
+ this.operand = false;
207
+ this.statement = this.label = this.arrowBody = false;
208
+ this.previousRoles = 0;
209
+ this.previousCode = code;
210
+ }
211
+ increment(code) {
212
+ this.statement = this.label = this.arrowBody = false;
213
+ this.previousRoles = 0;
214
+ this.previousCode = code;
215
+ }
216
+ /** 换行只恢复可开始声明的位置,不改变跨行除法的表达式目标。 */
217
+ lineBreak(source, start, end) {
218
+ if (this.operand && !(this.previousRoles & lineBreakWord)) return;
219
+ const frame = this.brackets?.[this.brackets.length - 1];
220
+ const header = this.headers?.[this.headers.length - 1];
221
+ if ((frame === void 0 ? this.rootStatement : Boolean(frame & statementBody)) && header?.depth !== this.depth && (source === void 0 || lineBreakPattern.test(source.slice(start, end)))) this.statement = true;
222
+ }
223
+ /** 普通括号仍用数字帧;只有函数或类的头部需要保存跨 token 的正文归属。 */
224
+ punctuation(code, next = 0) {
225
+ let matched = true;
226
+ if (code === 46) this.operand = this.statement = false;
227
+ else if (code === 91) {
228
+ (this.brackets ??= []).push(code);
229
+ this.operand = true;
230
+ this.statement = false;
231
+ } else matched = this.punctuationContext(code, next);
232
+ this.arrowBody = code === 62 && this.previousCode === 61;
233
+ this.label = false;
234
+ this.previousRoles = 0;
235
+ this.previousCode = code;
236
+ return matched;
237
+ }
238
+ punctuationContext(code, next) {
239
+ let matched = true;
240
+ const header = this.headers?.[this.headers.length - 1];
241
+ const currentHeader = header && header.depth === this.depth ? header : void 0;
242
+ if (code === 40) {
243
+ if (currentHeader?.kind === "function" && currentHeader.phase === "head" && !currentHeader.angles) {
244
+ currentHeader.phase = "parameters";
245
+ (this.brackets ??= []).push(code | functionParameters);
246
+ } else (this.brackets ??= []).push(code | (this.previousRoles & controlWord ? expressionAfter : 0));
247
+ this.operand = true;
248
+ this.statement = false;
249
+ } else if (code === 123) {
250
+ const typeObject = currentHeader && (currentHeader.angles > 0 || currentHeader.phase === "body" && currentHeader.typed && ([
251
+ 58,
252
+ 38,
253
+ 124,
254
+ 63,
255
+ 61,
256
+ 62
257
+ ].includes(this.previousCode) || this.previousRoles & typeObjectWord));
258
+ if (currentHeader && !typeObject && !currentHeader.angles && (currentHeader.kind === "class" || currentHeader.phase === "body")) {
259
+ this.headers.pop();
260
+ (this.brackets ??= []).push(code | statementBody | (currentHeader.declaration ? expressionAfter : 0));
261
+ this.statement = true;
262
+ } else if (this.arrowBody && !typeObject) {
263
+ (this.brackets ??= []).push(code | statementBody);
264
+ this.statement = true;
265
+ } else {
266
+ const object = typeObject || this.operand && !this.statement;
267
+ (this.brackets ??= []).push(code | (object ? 0 : 768));
268
+ this.statement = !object;
269
+ }
270
+ this.operand = true;
271
+ } else if (code === 41 || code === 93 || code === 125) {
272
+ const expected = code === 41 ? 40 : code === 93 ? 91 : 123;
273
+ const frame = this.brackets?.pop();
274
+ matched = frame !== void 0 && (frame & bracketMask) === expected;
275
+ if (frame !== void 0 && frame & functionParameters) {
276
+ const parameters = this.headers?.[this.headers.length - 1];
277
+ if (parameters?.kind === "function" && parameters.phase === "parameters" && parameters.depth === this.depth) parameters.phase = "body";
278
+ this.operand = this.statement = false;
279
+ } else {
280
+ this.operand = frame === void 0 ? code === 125 : Boolean(frame & expressionAfter);
281
+ this.statement = this.operand;
282
+ }
283
+ } else {
284
+ if (currentHeader && currentHeader.phase !== "parameters") {
285
+ if (code === 60) currentHeader.angles++;
286
+ else if (code === 62 && this.previousCode !== 61 && currentHeader.angles) currentHeader.angles--;
287
+ else if (code === 58 && currentHeader.phase === "body") currentHeader.typed = true;
288
+ else if (!currentHeader.angles && currentHeader.phase === "head" && (code === 58 || code === 61 || code === 44 || code === 59)) this.headers.pop();
289
+ }
290
+ this.operand = code !== 46;
291
+ if (code === 59) {
292
+ const frame = this.brackets?.[this.brackets.length - 1];
293
+ this.statement = frame === void 0 ? this.rootStatement : Boolean(frame & statementBody);
294
+ } else if (code === 58) {
295
+ if (this.questions?.[this.questions.length - 1] === this.depth) {
296
+ this.questions.pop();
297
+ this.statement = false;
298
+ } else if (this.cases?.[this.cases.length - 1] === this.depth) {
299
+ this.cases.pop();
300
+ this.statement = true;
301
+ } else this.statement = this.label;
302
+ } else {
303
+ this.statement = false;
304
+ if (code === 63 && next !== 46 && next !== 63 && this.previousCode !== 63) (this.questions ??= []).push(this.depth);
305
+ }
306
+ }
307
+ return matched;
308
+ }
309
+ };
310
+ // src/expression.ts
311
+ function encodedQuoteAt(source, start) {
312
+ if (source.charCodeAt(start) !== 38) return;
313
+ const end = source.indexOf(";", start + 1);
314
+ if (end < 0 || end - start > 15) return;
315
+ const name = source.slice(start + 1, end).toLowerCase();
316
+ let code = name === "quot" ? 34 : name === "apos" ? 39 : 0;
317
+ if (!code && name.charCodeAt(0) === 35) {
318
+ const hexadecimal = name.charCodeAt(1) === 120;
319
+ const begin = hexadecimal ? 2 : 1;
320
+ if (begin === name.length) return;
321
+ for (let index = begin; index < name.length; index++) {
322
+ const digit = name.charCodeAt(index);
323
+ if (!(digit >= 48 && digit <= 57 || hexadecimal && digit >= 97 && digit <= 102)) return;
324
+ }
325
+ code = Number.parseInt(name.slice(begin), hexadecimal ? 16 : 10);
326
+ }
327
+ return code === 34 || code === 39 ? {
328
+ code,
329
+ end: end + 1
330
+ } : void 0;
331
+ }
332
+ function quotedEnd$1(source, start, syntax, limit, entityQuotes) {
333
+ const opening = encodedQuoteAt(source, start);
334
+ const quote = opening?.code ?? source.charCodeAt(start);
335
+ const entityLayer = syntax === "xml" || Boolean(opening);
336
+ for (let index = opening?.end ?? start + 1; index < limit;) {
337
+ const entity = entityLayer ? encodedQuoteAt(source, index) : void 0;
338
+ const code = entity?.code ?? source.charCodeAt(index);
339
+ if (code === 92) {
340
+ const slashStart = index;
341
+ while (source.charCodeAt(index) === 92) index++;
342
+ const delimiter = entityLayer ? encodedQuoteAt(source, index) : void 0;
343
+ if ((index - slashStart) % 2 !== 0) index = delimiter?.end ?? index + 1;
344
+ continue;
345
+ }
346
+ if (quote === 96 && code === 36 && source.charCodeAt(index + 1) === 123) index = scanExpression(source, index + 1, false, syntax, limit, entityQuotes);
347
+ else if (code === quote) return entity?.end ?? index + 1;
348
+ else index = entity?.end ?? index + 1;
349
+ }
350
+ throw new TemplateLexicalError(start, "未闭合的表达式字符串");
351
+ }
352
+ function regexpEnd$1(source, start, limit) {
353
+ let characterClass = false;
354
+ for (let index = start + 1; index < limit; index++) {
355
+ const code = source.charCodeAt(index);
356
+ if (code === 92) index++;
357
+ else if (code === 91) characterClass = true;
358
+ else if (code === 93) characterClass = false;
359
+ else if (code === 47 && !characterClass) {
360
+ index++;
361
+ while (isWordCode(source.charCodeAt(index))) index++;
362
+ return index;
363
+ } else if (code === 10 || code === 13) break;
364
+ }
365
+ throw new TemplateLexicalError(start, "未闭合的表达式正则");
366
+ }
367
+ function scanExpression(source, start, mustache, syntax, limit = source.length, entityQuotes = true) {
368
+ const context = new TokenContext(true);
369
+ let mismatch;
370
+ for (let index = start + (mustache ? 2 : 1); index < limit;) {
371
+ const code = source.charCodeAt(index);
372
+ const next = source.charCodeAt(index + 1);
373
+ if (code === 125 && (!mustache ? context.depth === 0 : next === 125 && context.bracket !== 123)) {
374
+ const end = index + (mustache ? 2 : 1);
375
+ if (mismatch !== void 0 || context.depth > 0) throw new TemplateLexicalError(mismatch ?? index, "不匹配的表达式括号", {
376
+ kind: "interpolation",
377
+ start,
378
+ end
379
+ });
380
+ return end;
381
+ }
382
+ if (isSpaceCode(code)) {
383
+ if (code === 10 || code === 13 || code === 8232 || code === 8233) context.lineBreak();
384
+ index++;
385
+ continue;
386
+ }
387
+ if (entityQuotes && code === 38 && encodedQuoteAt(source, index)) {
388
+ index = quotedEnd$1(source, index, syntax, limit, entityQuotes);
389
+ context.value();
390
+ continue;
391
+ }
392
+ if (code === 34 || code === 39 || code === 96) {
393
+ index = quotedEnd$1(source, index, syntax, limit, entityQuotes);
394
+ context.value();
395
+ continue;
396
+ }
397
+ if (code === 47 && next === 42) {
398
+ const end = source.indexOf("*/", index + 2);
399
+ if (end < 0 || end >= limit) throw new TemplateLexicalError(index, "未闭合的表达式注释");
400
+ context.lineBreak(source, index + 2, end);
401
+ index = end + 2;
402
+ continue;
403
+ }
404
+ if (code === 47 && next === 47) {
405
+ const end = findLineEnd(source, index + 2);
406
+ if (end < 0 || end >= limit) throw new TemplateLexicalError(index, "未闭合的插值表达式");
407
+ context.lineBreak();
408
+ index = end + 1;
409
+ continue;
410
+ }
411
+ if (code === 47 && context.operand) {
412
+ index = regexpEnd$1(source, index, limit);
413
+ context.value();
414
+ continue;
415
+ }
416
+ if (isWordCode(code)) {
417
+ const begin = index++;
418
+ while (isWordCode(source.charCodeAt(index))) index++;
419
+ context.word(source, begin, index);
420
+ continue;
421
+ }
422
+ if ((code === 43 || code === 45) && code === next) {
423
+ context.increment(code);
424
+ index += 2;
425
+ continue;
426
+ }
427
+ if (!context.punctuation(code, next)) {
428
+ if (!mustache) throw new TemplateLexicalError(index, "不匹配的表达式括号");
429
+ mismatch ??= index;
430
+ }
431
+ index++;
432
+ }
433
+ if (mismatch !== void 0) throw new TemplateLexicalError(mismatch, "不匹配的表达式括号");
434
+ throw new TemplateLexicalError(start, "未闭合的插值表达式");
435
+ }
436
+ /** 定位插值末尾;跳过字符串、注释、正则和嵌套括号,保留原文编码。 */
437
+ function expressionEnd(source, start, mustache = true, syntax = "xml", outerQuote) {
438
+ if (syntax === "legacy" && outerQuote) {
439
+ const boundary = legacyAttributeEnd(source, start, outerQuote);
440
+ const view = legacyAttributeSource(source, start, boundary < 0 ? source.length : boundary);
441
+ try {
442
+ return attributeSourcePosition(view, scanExpression(view.source, view.start, mustache, syntax, view.end, false));
443
+ } catch (error) {
444
+ attributeSourceError(view, error);
445
+ }
446
+ }
447
+ return scanExpression(source, start, mustache, syntax);
448
+ }
449
+ function collectInterpolations(source, syntax, entityQuotes = true, begin = 0, limit = source.length) {
450
+ const result = [];
451
+ let start = source.indexOf("{{", begin);
452
+ while (start >= 0 && start < limit) {
453
+ const end = scanExpression(source, start, true, syntax, limit, entityQuotes);
454
+ result.push({
455
+ start,
456
+ end
457
+ });
458
+ start = source.indexOf("{{", end);
459
+ }
460
+ return result;
461
+ }
462
+ /** 返回完整插值的半开范围,保留属性层的编码规则。 */
463
+ function interpolations(source, syntax = "xml", outerQuote) {
464
+ if (syntax === "legacy" && outerQuote) {
465
+ const boundary = legacyAttributeEnd(source, 0, outerQuote);
466
+ const view = legacyAttributeSource(source, 0, boundary < 0 ? source.length : boundary);
467
+ try {
468
+ return collectInterpolations(view.source, syntax, false, view.start, view.end).map((range) => ({
469
+ start: attributeSourcePosition(view, range.start),
470
+ end: attributeSourcePosition(view, range.end)
471
+ }));
472
+ } catch (error) {
473
+ attributeSourceError(view, error);
474
+ }
475
+ }
476
+ return collectInterpolations(source, syntax);
477
+ }
478
+ /** 已解开宿主层的绑定不将实体样文本解释为 JavaScript 引号。 */
479
+ function legacyAttributeInterpolations(source) {
480
+ return collectInterpolations(source, "legacy", false);
481
+ }
482
+ /** 宿主先确定属性边界,绑定词法只读取解开一层后的逻辑字符。 */
483
+ function validateLegacyAttribute(source, start, end) {
484
+ const view = legacyAttributeSource(source, start, end);
485
+ let begin = view.source.indexOf("{{", view.start);
486
+ try {
487
+ while (begin >= 0 && begin < view.end) {
488
+ const boundary = scanExpression(view.source, begin, true, "legacy", view.end, false);
489
+ begin = view.source.indexOf("{{", boundary);
490
+ }
491
+ } catch (error) {
492
+ attributeSourceError(view, error);
493
+ }
494
+ }
495
+ // src/decode.ts
496
+ /** 解码不含外层引号的词法属性值;表达式内部保留 JS 字符串的转义层。 */
497
+ function decodeAttribute(value, syntax = "legacy", decodeEntities = true, quote) {
498
+ if (syntax !== "legacy") return decodeEntities ? decodeXML(value) : value;
499
+ const decoded = quote && value.includes("\\") ? decodeLegacyAttributeLayer(value) : value;
500
+ if (!decodeEntities || !decoded.includes("&")) return decoded;
501
+ if (!decoded.includes("{{")) return decodeXML(decoded);
502
+ let result = "";
503
+ let offset = 0;
504
+ for (const range of legacyAttributeInterpolations(decoded)) {
505
+ result += decodeXML(decoded.slice(offset, range.start));
506
+ result += decoded.slice(range.start, range.end);
507
+ offset = range.end;
508
+ }
509
+ return result + decodeXML(decoded.slice(offset));
510
+ }
511
+ // src/encoding.ts
512
+ /** 显式表达式只能占据一个完整绑定,不能提前结束后混入文本或模板结构。 */
513
+ function assertExpressionBoundary(source, syntax, quote) {
514
+ try {
515
+ if (expressionEnd(source, 0, true, syntax, quote) !== source.length) throw new TypeError("Invalid WXML expression: expected a single complete interpolation.");
516
+ } catch (error) {
517
+ if (!(error instanceof TemplateLexicalError)) throw error;
518
+ throw new TypeError(`Invalid WXML expression: ${error.message}`);
519
+ }
520
+ }
521
+ function encodeAttributeLayer(value, syntax) {
522
+ return syntax === "legacy" ? value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") : value.replace(/"/g, "&quot;");
523
+ }
524
+ function encodeEntities(value) {
525
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
526
+ }
527
+ /** 字面量显式拆开绑定定界符,表达式则保留独立的输入语义。 */
528
+ function encodeAttribute(value, syntax) {
529
+ if (typeof value === "string") return encodeAttributeLayer(encodeEntities(value), syntax).replace(/\{\{/g, "{{'{'}}{{'{'}}");
530
+ let expression;
531
+ if (typeof value === "number" && Number.isFinite(value)) expression = String(value);
532
+ else if (typeof value === "boolean") expression = String(value);
533
+ else if (value && typeof value === "object" && typeof value.expression === "string" && value.expression.trim()) expression = value.expression;
534
+ else throw new TypeError("Expected a string, finite number, boolean, or nonempty expression.");
535
+ return `{{${syntax === "legacy" ? encodeAttributeLayer(expression, syntax) : encodeEntities(expression).replace(/"/g, "&quot;")}}}`;
536
+ }
537
+ /** 文本字面量不能生成标签或意外触发绑定。 */
538
+ function encodeText(value) {
539
+ if (typeof value === "string") return encodeEntities(value).replace(/\{\{/g, "{{'{'}}{{'{'}}");
540
+ if (value && typeof value.expression === "string" && value.expression.trim()) return `{{${value.expression}}}`;
541
+ throw new TypeError("Expected a string or nonempty expression.");
542
+ }
543
+ /** 只转换属性外层引号,不重复编码实体或将绑定当作字符串。 */
544
+ function canonicalAttribute(attribute, syntax) {
545
+ if (attribute.value === void 0) return attribute.name;
546
+ let value = attribute.value;
547
+ if (syntax === "xml") value = value.replace(/"/g, "&quot;");
548
+ else if (attribute.quote !== "\"") value = encodeAttributeLayer(decodeAttribute(value, syntax, false, attribute.quote), syntax);
549
+ return `${attribute.name}="${value}"`;
550
+ }
551
+ // src/options.ts
552
+ /** 共享原始脚本标签列表;调用方需要查询集合时自行建立,避免共享可变 Set。 */
553
+ const defaultRawTags = Object.freeze([
554
+ "wxs",
555
+ "sjs",
556
+ "ks",
557
+ "filter",
558
+ "script",
559
+ "import-sjs"
560
+ ]);
561
+ // src/script.ts
562
+ function quotedEnd(source, start, quote) {
563
+ for (let index = start + 1; index < source.length; index++) {
564
+ const code = source.charCodeAt(index);
565
+ if (code === 92) index++;
566
+ else if (code === quote) return index + 1;
567
+ }
568
+ return source.length;
569
+ }
570
+ function regexpEnd(source, start) {
571
+ let characterClass = false;
572
+ for (let index = start + 1; index < source.length; index++) {
573
+ const code = source.charCodeAt(index);
574
+ if (code === 92) index++;
575
+ else if (code === 91) characterClass = true;
576
+ else if (code === 93) characterClass = false;
577
+ else if (code === 47 && !characterClass) {
578
+ index++;
579
+ while (isWordCode(source.charCodeAt(index))) index++;
580
+ return index;
581
+ } else if (code === 10 || code === 13) return index;
582
+ }
583
+ return source.length;
584
+ }
585
+ function closingTagAt(source, start, tagName) {
586
+ if (!tagName || source.charCodeAt(start) !== 60 || source.charCodeAt(start + 1) !== 47) return;
587
+ const begin = start + 2;
588
+ let cursor = begin;
589
+ while (isNameCode(source.charCodeAt(cursor))) cursor++;
590
+ if (source.slice(begin, cursor).toLowerCase() !== tagName) return;
591
+ while (isSpaceCode(source.charCodeAt(cursor))) cursor++;
592
+ return source.charCodeAt(cursor) === 62 ? {
593
+ start,
594
+ end: cursor + 1
595
+ } : void 0;
596
+ }
597
+ function templateEnd(source, start) {
598
+ let index = start + 1;
599
+ while (index < source.length) {
600
+ const code = source.charCodeAt(index);
601
+ if (code === 92) index += 2;
602
+ else if (code === 96) return index + 1;
603
+ else if (code === 36 && source.charCodeAt(index + 1) === 123) index = scanCode(source, index + 2, void 0, true).end;
604
+ else index++;
605
+ }
606
+ return index;
607
+ }
608
+ function scanCode(source, start, tagName, interpolation = false) {
609
+ const commentClosings = [];
610
+ const context = new TokenContext(interpolation);
611
+ let index = start;
612
+ while (index < source.length) {
613
+ const code = source.charCodeAt(index);
614
+ const next = source.charCodeAt(index + 1);
615
+ if (code === 60 && next === 47) {
616
+ const closingTag = closingTagAt(source, index, tagName);
617
+ if (closingTag) return {
618
+ closingTag,
619
+ commentClosings,
620
+ end: closingTag.end
621
+ };
622
+ }
623
+ if (isSpaceCode(code)) {
624
+ if (code === 10 || code === 13 || code === 8232 || code === 8233) context.lineBreak();
625
+ index++;
626
+ continue;
627
+ }
628
+ if (code === 34 || code === 39) {
629
+ index = quotedEnd(source, index, code);
630
+ context.value(code);
631
+ } else if (code === 96) {
632
+ index = templateEnd(source, index);
633
+ context.value(code);
634
+ } else if (code === 47 && (next === 47 || next === 42)) {
635
+ const block = next === 42;
636
+ const end = block ? source.indexOf("*/", index + 2) : findLineEnd(source, index + 2);
637
+ const limit = end < 0 ? source.length : end;
638
+ if (tagName) {
639
+ let candidate = source.indexOf("</", index + 2);
640
+ while (candidate >= 0 && candidate < limit) {
641
+ const closing = closingTagAt(source, candidate, tagName);
642
+ if (closing) commentClosings.push({
643
+ ...closing,
644
+ block
645
+ });
646
+ candidate = source.indexOf("</", candidate + 2);
647
+ }
648
+ }
649
+ if (end < 0 && block) return {
650
+ trailingComment: index,
651
+ commentClosings,
652
+ end: source.length
653
+ };
654
+ if (block) context.lineBreak(source, index + 2, limit);
655
+ else if (end >= 0) context.lineBreak();
656
+ index = limit + (end < 0 ? 0 : block ? 2 : 1);
657
+ continue;
658
+ } else if (code === 47 && context.operand) {
659
+ index = regexpEnd(source, index);
660
+ context.value(code);
661
+ } else if (isWordCode(code)) {
662
+ const begin = index++;
663
+ while (isWordCode(source.charCodeAt(index))) index++;
664
+ context.word(source, begin, index);
665
+ continue;
666
+ } else {
667
+ if (interpolation && code === 125 && context.depth === 0) return { end: index + 1 };
668
+ if ((code === 43 || code === 45) && next === code) {
669
+ context.increment(code);
670
+ index++;
671
+ } else context.punctuation(code, next);
672
+ index++;
673
+ }
674
+ }
675
+ return {
676
+ end: index,
677
+ commentClosings
678
+ };
679
+ }
680
+ /** 只收集词法候选,不加载 JS AST;歧义由调用方注入的 resolver 处理。 */
681
+ function scanScriptBoundaryCandidates(source, start, tagName) {
682
+ return scanCode(source, start, tagName.toLowerCase());
683
+ }
684
+ /** 返回明确位于脚本代码层的结束标签,不擅自采用注释内的候选。 */
685
+ function findScriptClosingTag(source, start, tagName) {
686
+ return scanScriptBoundaryCandidates(source, start, tagName).closingTag;
687
+ }
688
+ /** 查找词法确认的未闭合尾部块注释。 */
689
+ function findTrailingScriptComment(source) {
690
+ return scanCode(source, 0).trailingComment;
691
+ }
692
+ // src/tag.ts
693
+ const emptyAttributes = Object.freeze([]);
694
+ const doubleQuotedBoundary = /"|\{\{/g;
695
+ const singleQuotedBoundary = /'|\{\{/g;
696
+ /** 读取标签与属性范围;属性值始终保留未解码的原文。 */
697
+ function readTag(source, start, syntax = "xml", collectAttributes = true) {
698
+ return scanTag(source, start, syntax, collectAttributes);
699
+ }
700
+ /** 文档扫描共享单调的绑定候选,避免逐属性搜索相同后缀。 */
701
+ function scanTag(source, start, syntax, collectAttributes, bindings) {
702
+ let cursor = start + 1;
703
+ const closing = source.charCodeAt(cursor) === 47;
704
+ if (closing) cursor++;
705
+ const nameStart = cursor;
706
+ while (isNameCode(source.charCodeAt(cursor))) cursor++;
707
+ const nameEnd = cursor;
708
+ if (nameStart === nameEnd) throw new TemplateLexicalError(start, "标签缺少名称");
709
+ let attributes;
710
+ while (cursor < source.length) {
711
+ const whitespaceStart = cursor;
712
+ cursor = skipSpace(source, cursor);
713
+ const code = source.charCodeAt(cursor);
714
+ const selfClosing = code === 47 && source.charCodeAt(cursor + 1) === 62;
715
+ if (code === 62 || selfClosing) {
716
+ if (closing && selfClosing) throw new TemplateLexicalError(cursor, "结束标签不能自闭合");
717
+ return {
718
+ kind: "tag",
719
+ start,
720
+ end: cursor + (selfClosing ? 2 : 1),
721
+ name: source.slice(nameStart, nameEnd),
722
+ nameStart,
723
+ nameEnd,
724
+ closing,
725
+ selfClosing,
726
+ attributes: attributes ?? emptyAttributes,
727
+ parent: void 0,
728
+ matching: void 0
729
+ };
730
+ }
731
+ if (closing) throw new TemplateLexicalError(cursor, "结束标签不能包含属性");
732
+ if (whitespaceStart === cursor) throw new TemplateLexicalError(cursor, "属性前缺少空白分隔符");
733
+ const attributeStart = cursor;
734
+ if (source.charCodeAt(cursor) === 123 && source.charCodeAt(cursor + 1) === 123) cursor = expressionEnd(source, cursor, true, syntax);
735
+ else while (cursor < source.length) {
736
+ const attributeCode = source.charCodeAt(cursor);
737
+ if (isSpaceCode(attributeCode) || attributeCode === 61 || attributeCode === 47 || attributeCode === 62) break;
738
+ if (attributeCode === 60 || attributeCode === 34 || attributeCode === 39) throw new TemplateLexicalError(cursor, "无效的属性名称");
739
+ cursor++;
740
+ }
741
+ const attributeNameEnd = cursor;
742
+ if (cursor === attributeStart) throw new TemplateLexicalError(cursor, "属性缺少名称");
743
+ const name = collectAttributes ? source.slice(attributeStart, attributeNameEnd) : "";
744
+ cursor = skipSpace(source, cursor);
745
+ if (source.charCodeAt(cursor) !== 61) {
746
+ if (collectAttributes) (attributes ??= []).push({
747
+ name,
748
+ nameStart: attributeStart,
749
+ nameEnd: attributeNameEnd,
750
+ start: attributeStart,
751
+ end: attributeNameEnd
752
+ });
753
+ cursor = attributeNameEnd;
754
+ continue;
755
+ }
756
+ cursor = skipSpace(source, cursor + 1);
757
+ const rawStart = cursor;
758
+ const quoteCode = source.charCodeAt(cursor);
759
+ const quote = quoteCode === 34 ? "\"" : quoteCode === 39 ? "'" : void 0;
760
+ if (quote) cursor++;
761
+ const valueStart = cursor;
762
+ let closed = !quote;
763
+ if (quote && syntax === "legacy") {
764
+ const end = legacyAttributeEnd(source, valueStart, quote);
765
+ if (end >= 0) {
766
+ validateLegacyAttribute(source, valueStart, end);
767
+ cursor = end;
768
+ closed = true;
769
+ }
770
+ } else if (quote && bindings) {
771
+ let end = source.indexOf(quote, cursor);
772
+ while (true) {
773
+ if (bindings.next < cursor) {
774
+ const found = source.indexOf("{{", cursor);
775
+ bindings.next = found < 0 ? Number.POSITIVE_INFINITY : found;
776
+ }
777
+ if (end >= 0 && end < bindings.next) {
778
+ cursor = end;
779
+ closed = true;
780
+ break;
781
+ }
782
+ if (bindings.next === Number.POSITIVE_INFINITY) break;
783
+ cursor = expressionEnd(source, bindings.next, true, syntax, quote);
784
+ if (end >= 0 && end < cursor) end = source.indexOf(quote, cursor);
785
+ }
786
+ } else if (quote) {
787
+ const boundary = quoteCode === 34 ? doubleQuotedBoundary : singleQuotedBoundary;
788
+ boundary.lastIndex = cursor;
789
+ while (boundary.test(source)) {
790
+ if (source.charCodeAt(boundary.lastIndex - 1) === quoteCode) {
791
+ cursor = boundary.lastIndex - 1;
792
+ closed = true;
793
+ break;
794
+ }
795
+ cursor = expressionEnd(source, boundary.lastIndex - 2, true, syntax, quote);
796
+ boundary.lastIndex = cursor;
797
+ }
798
+ } else while (cursor < source.length) {
799
+ const valueCode = source.charCodeAt(cursor);
800
+ if (valueCode === 123 && source.charCodeAt(cursor + 1) === 123) cursor = expressionEnd(source, cursor, true, syntax, quote);
801
+ else if (quote ? valueCode === quoteCode : isSpaceCode(valueCode) || valueCode === 62 || valueCode === 47 && source.charCodeAt(cursor + 1) === 62) {
802
+ closed = true;
803
+ break;
804
+ } else cursor++;
805
+ }
806
+ if (!closed || !quote && cursor === valueStart) throw new TemplateLexicalError(attributeStart, "未闭合或为空的属性值");
807
+ const valueEnd = cursor;
808
+ if (quote) cursor++;
809
+ if (collectAttributes) {
810
+ const value = source.slice(valueStart, valueEnd);
811
+ (attributes ??= []).push({
812
+ name,
813
+ nameStart: attributeStart,
814
+ nameEnd: attributeNameEnd,
815
+ start: attributeStart,
816
+ end: cursor,
817
+ valueStart,
818
+ valueEnd,
819
+ value,
820
+ rawValue: quote ? source.slice(rawStart, cursor) : value,
821
+ quote
822
+ });
823
+ }
824
+ }
825
+ throw new TemplateLexicalError(start, "未闭合的标签");
826
+ }
827
+ // src/scanner.ts
828
+ const defaultRawTagPattern = new RegExp(`^(?:${defaultRawTags.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})$`, "i");
829
+ const platforms = /* @__PURE__ */ new Set([
830
+ "weapp",
831
+ "alipay",
832
+ "tt",
833
+ "swan",
834
+ "jd",
835
+ "xhs",
836
+ "qq",
837
+ "ks",
838
+ "ty"
839
+ ]);
840
+ function opaqueEnd(source, start) {
841
+ const delimiter = source.startsWith("<!--", start) ? "-->" : source.startsWith("<![CDATA[", start) ? "]]>" : source.startsWith("<?", start) ? "?>" : void 0;
842
+ if (delimiter) {
843
+ const end = source.indexOf(delimiter, start + 2);
844
+ if (end < 0) throw new TemplateLexicalError(start, "未闭合的注释、CDATA 或处理指令");
845
+ return end + delimiter.length;
846
+ }
847
+ let quote = 0;
848
+ let depth = 0;
849
+ for (let index = start + 2; index < source.length; index++) {
850
+ const code = source.charCodeAt(index);
851
+ if (quote) {
852
+ if (code === quote) quote = 0;
853
+ } else if (code === 34 || code === 39) quote = code;
854
+ else if (code === 91) depth++;
855
+ else if (code === 93) depth--;
856
+ else if (code === 62 && depth === 0) return index + 1;
857
+ }
858
+ throw new TemplateLexicalError(start, "未闭合的模板声明");
859
+ }
860
+ function scanDocument(source, options, buildTree, commentsOnly = false) {
861
+ if (typeof source !== "string" || !options || typeof options !== "object" || Array.isArray(options)) throw new TypeError("Expected template source and a parse options object.");
862
+ if (options.platform !== void 0 && !platforms.has(options.platform)) throw new TypeError(`Unsupported template platform: ${String(options.platform)}.`);
863
+ if (options.syntax !== void 0 && options.syntax !== "legacy" && options.syntax !== "xml") throw new TypeError(`Unsupported template syntax: ${String(options.syntax)}.`);
864
+ if (options.rawTags !== void 0 && (!Array.isArray(options.rawTags) || options.rawTags.some((name) => typeof name !== "string" || !name))) throw new TypeError("Expected rawTags to be an array of nonempty names.");
865
+ if (options.resolveScriptBoundary !== void 0 && typeof options.resolveScriptBoundary !== "function") throw new TypeError("Expected resolveScriptBoundary to be a function.");
866
+ const platform = options.platform ?? "weapp";
867
+ const syntax = options.syntax ?? (platform === "weapp" ? "legacy" : "xml");
868
+ const rawTags = options.rawTags ? new Set(options.rawTags.map((name) => name.toLowerCase())) : void 0;
869
+ const tokens = [];
870
+ const diagnostics = [];
871
+ const stack = [];
872
+ const children = buildTree ? [] : void 0;
873
+ const elements = buildTree ? [] : void 0;
874
+ const scanEnd = commentsOnly ? source.lastIndexOf("<!--") + 1 : source.length;
875
+ let cursor = 0;
876
+ let textStart = 0;
877
+ let nextTag = -1;
878
+ const bindings = { next: -1 };
879
+ function appendTag(token) {
880
+ if (commentsOnly) return;
881
+ const mutable = token;
882
+ if (token.closing) {
883
+ const openIndex = stack[stack.length - 1];
884
+ const open = openIndex === void 0 ? void 0 : tokens[openIndex];
885
+ if (!open || open.name !== token.name) diagnostics.push({
886
+ code: "template/mismatched-tag",
887
+ message: `结束标签 </${token.name}> 与开始标签不匹配`,
888
+ severity: "error",
889
+ start: token.start,
890
+ end: token.end
891
+ });
892
+ else {
893
+ stack.pop();
894
+ mutable.matching = openIndex;
895
+ mutable.parent = open.parent;
896
+ open.matching = tokens.length;
897
+ if (elements) {
898
+ const element = elements.pop();
899
+ element.closing = token;
900
+ element.end = token.end;
901
+ }
902
+ }
903
+ } else {
904
+ mutable.parent = stack[stack.length - 1];
905
+ if (elements) {
906
+ const element = {
907
+ kind: "element",
908
+ name: token.name,
909
+ attributes: token.attributes,
910
+ children: [],
911
+ opening: token,
912
+ closing: void 0,
913
+ selfClosing: token.selfClosing,
914
+ start: token.start,
915
+ end: token.end
916
+ };
917
+ (elements.length ? elements[elements.length - 1].children : children).push(element);
918
+ if (!token.selfClosing) elements.push(element);
919
+ }
920
+ if (!token.selfClosing) stack.push(tokens.length);
921
+ }
922
+ tokens.push(token);
923
+ }
924
+ function appendRaw(token) {
925
+ if (commentsOnly) {
926
+ if (token.kind === "comment") tokens.push(token);
927
+ return;
928
+ }
929
+ if (elements) (elements.length ? elements[elements.length - 1].children : children).push({
930
+ kind: token.kind,
931
+ start: token.start,
932
+ end: token.end,
933
+ tagName: token.tagName,
934
+ data: source.slice(token.start, token.end)
935
+ });
936
+ tokens.push(token);
937
+ }
938
+ try {
939
+ while (cursor < scanEnd) {
940
+ if (!commentsOnly) {
941
+ if (nextTag < cursor) {
942
+ const found = source.indexOf("<", cursor);
943
+ nextTag = found < 0 ? Number.POSITIVE_INFINITY : found;
944
+ }
945
+ if (bindings.next < cursor) {
946
+ const found = source.indexOf("{{", cursor);
947
+ bindings.next = found < 0 ? Number.POSITIVE_INFINITY : found;
948
+ }
949
+ if (bindings.next < nextTag) {
950
+ cursor = expressionEnd(source, bindings.next, true, syntax);
951
+ continue;
952
+ }
953
+ if (nextTag >= scanEnd) {
954
+ cursor = scanEnd;
955
+ break;
956
+ }
957
+ cursor = nextTag;
958
+ }
959
+ const code = source.charCodeAt(cursor);
960
+ if (code === 123 && source.charCodeAt(cursor + 1) === 123) {
961
+ cursor = expressionEnd(source, cursor, true, syntax);
962
+ continue;
963
+ }
964
+ const next = source.charCodeAt(cursor + 1);
965
+ if (code !== 60 || !isTagStartCode(next) && next !== 33 && next !== 47 && next !== 63) {
966
+ cursor++;
967
+ continue;
968
+ }
969
+ if (cursor > textStart) appendRaw({
970
+ kind: "text",
971
+ start: textStart,
972
+ end: cursor
973
+ });
974
+ if (next === 33 || next === 63) {
975
+ const end = opaqueEnd(source, cursor);
976
+ appendRaw({
977
+ kind: source.startsWith("<!--", cursor) ? "comment" : source.startsWith("<![CDATA[", cursor) ? "cdata" : "declaration",
978
+ start: cursor,
979
+ end
980
+ });
981
+ cursor = end;
982
+ } else {
983
+ const tag = scanTag(source, cursor, syntax, !commentsOnly, bindings);
984
+ appendTag(tag);
985
+ cursor = tag.end;
986
+ if (!tag.closing && !tag.selfClosing && (rawTags ? rawTags.has(tag.name.toLowerCase()) : defaultRawTagPattern.test(tag.name))) {
987
+ const candidates = scanScriptBoundaryCandidates(source, cursor, tag.name);
988
+ const close = options.resolveScriptBoundary ? options.resolveScriptBoundary(source, cursor, tag.name, candidates) : candidates.closingTag;
989
+ if (!close) {
990
+ if (candidates.commentClosings?.length) throw new TemplateLexicalError(tag.start, `脚本标签 <${tag.name}> 的结束边界存在歧义,需要 resolveScriptBoundary`);
991
+ throw new TemplateLexicalError(tag.start, `未闭合的脚本标签 <${tag.name}>`);
992
+ }
993
+ if (!Number.isInteger(close.start) || !Number.isInteger(close.end) || close.start < cursor || close.end > source.length || close.end <= close.start) throw new TemplateLexicalError(tag.start, "脚本边界 resolver 返回了无效范围");
994
+ appendRaw({
995
+ kind: "script",
996
+ tagName: tag.name,
997
+ start: cursor,
998
+ end: close.start
999
+ });
1000
+ const closing = scanTag(source, close.start, syntax, !commentsOnly, bindings);
1001
+ if (!closing.closing || closing.end !== close.end || closing.name.toLowerCase() !== tag.name.toLowerCase()) throw new TemplateLexicalError(close.start, "脚本边界 resolver 返回的范围不是对应结束标签");
1002
+ appendTag(closing);
1003
+ cursor = closing.end;
1004
+ }
1005
+ }
1006
+ textStart = cursor;
1007
+ }
1008
+ if (!commentsOnly && textStart < source.length) appendRaw({
1009
+ kind: "text",
1010
+ start: textStart,
1011
+ end: source.length
1012
+ });
1013
+ for (const index of stack) {
1014
+ const token = tokens[index];
1015
+ diagnostics.push({
1016
+ code: "template/unclosed-tag",
1017
+ message: `标签 <${token.name}> 缺少结束标签`,
1018
+ severity: "error",
1019
+ start: token.start,
1020
+ end: token.end
1021
+ });
1022
+ }
1023
+ } catch (error) {
1024
+ if (!(error instanceof TemplateLexicalError)) throw error;
1025
+ diagnostics.push({
1026
+ code: error.recovery ? "template/invalid-interpolation" : "template/invalid-syntax",
1027
+ message: error.message,
1028
+ severity: "error",
1029
+ start: error.offset,
1030
+ end: Math.min(source.length, error.offset + 1),
1031
+ ...error.recovery ? { recovery: error.recovery } : {}
1032
+ });
1033
+ }
1034
+ return buildTree ? {
1035
+ tokens,
1036
+ diagnostics,
1037
+ children,
1038
+ platform,
1039
+ syntax
1040
+ } : {
1041
+ tokens,
1042
+ diagnostics
1043
+ };
1044
+ }
1045
+ /** 扫描保留原文的 tokens 与诊断,不分配 AST 节点。 */
1046
+ function scan(source, options = {}) {
1047
+ return scanDocument(source, options, false);
1048
+ }
1049
+ /** 只收集普通模板注释,不建立属性和标签配对,最后一个候选之后停止扫描。 */
1050
+ function scanComments(source, options = {}) {
1051
+ return scanDocument(source, options, false, true);
1052
+ }
1053
+ // src/parser.ts
1054
+ /** 在一次扫描中建立保留完整原文与属性形式的模板文档。 */
1055
+ function parse(source, options = {}) {
1056
+ if (!options || typeof options !== "object" || Array.isArray(options)) throw new TypeError("Expected a parse options object.");
1057
+ const selectedPlatform = options.platform ?? "weapp";
1058
+ const rawTags = options.rawTags;
1059
+ const snapshot = Object.freeze({
1060
+ platform: selectedPlatform,
1061
+ syntax: options.syntax ?? (selectedPlatform === "weapp" ? "legacy" : "xml"),
1062
+ rawTags: Array.isArray(rawTags) ? Object.freeze(rawTags.slice()) : rawTags,
1063
+ resolveScriptBoundary: options.resolveScriptBoundary
1064
+ });
1065
+ const { tokens, diagnostics, children, platform, syntax } = scanDocument(source, snapshot, true);
1066
+ return {
1067
+ source,
1068
+ platform,
1069
+ syntax,
1070
+ tokens,
1071
+ diagnostics,
1072
+ children,
1073
+ options: snapshot
1074
+ };
1075
+ }
1076
+ // src/edit/attributes.ts
1077
+ /** 已受编码器保护的字面量和标量直接组合语义属性,不重新扫描未改动的开始标签。 */
1078
+ function editedAttributes(node, state) {
1079
+ const changes = state.attributes;
1080
+ if (!changes?.size) return node.attributes;
1081
+ const attributes = [];
1082
+ const handled = /* @__PURE__ */ new Set();
1083
+ for (const attribute of node.attributes) {
1084
+ if (!changes.has(attribute.name)) {
1085
+ attributes.push(attribute);
1086
+ continue;
1087
+ }
1088
+ if (!handled.has(attribute.name)) {
1089
+ const value = changes.get(attribute.name);
1090
+ if (value !== void 0) attributes.push(value === null ? { name: attribute.name } : {
1091
+ name: attribute.name,
1092
+ value,
1093
+ quote: "\""
1094
+ });
1095
+ handled.add(attribute.name);
1096
+ }
1097
+ }
1098
+ for (const [name, value] of changes) if (!handled.has(name) && value !== void 0) attributes.push(value === null ? { name } : {
1099
+ name,
1100
+ value,
1101
+ quote: "\""
1102
+ });
1103
+ return attributes;
1104
+ }
1105
+ // src/edit/output.ts
1106
+ function openingTag(session, node, state, expanded) {
1107
+ const { source } = session.document;
1108
+ for (const name of state?.unvalidatedAttributes ?? []) {
1109
+ const value = state?.attributes?.get(name);
1110
+ if (typeof value === "string") assertExpressionBoundary(value, session.document.syntax, "\"");
1111
+ }
1112
+ const edits = [];
1113
+ if (state?.name && state.name !== node.name) edits.push({
1114
+ start: node.opening.nameStart,
1115
+ end: node.opening.nameEnd,
1116
+ text: state.name
1117
+ });
1118
+ const handled = /* @__PURE__ */ new Set();
1119
+ const attributes = state?.attributes;
1120
+ for (const attribute of node.attributes) {
1121
+ if (!attributes?.has(attribute.name)) continue;
1122
+ const value = attributes.get(attribute.name);
1123
+ const text = handled.has(attribute.name) || value === void 0 ? "" : value === null ? attribute.name : `${attribute.name}="${value}"`;
1124
+ edits.push({
1125
+ start: attribute.start,
1126
+ end: attribute.end,
1127
+ text
1128
+ });
1129
+ handled.add(attribute.name);
1130
+ }
1131
+ let additions = "";
1132
+ for (const [name, value] of attributes ?? []) if (!handled.has(name) && value !== void 0) additions += ` ${value === null ? name : `${name}="${value}"`}`;
1133
+ const endStart = node.opening.end - (node.selfClosing ? 2 : 1);
1134
+ if (additions || expanded) edits.push({
1135
+ start: endStart,
1136
+ end: node.opening.end,
1137
+ text: `${additions}${node.selfClosing && !expanded ? "/>" : ">"}`
1138
+ });
1139
+ let cursor = node.opening.start;
1140
+ let output = "";
1141
+ for (const edit of edits.sort((a, b) => a.start - b.start)) {
1142
+ output += source.slice(cursor, edit.start) + edit.text;
1143
+ cursor = edit.end;
1144
+ }
1145
+ return output + source.slice(cursor, node.opening.end);
1146
+ }
1147
+ function childrenParts(source, children, start, end) {
1148
+ const parts = [];
1149
+ let cursor = start;
1150
+ for (const child of children) {
1151
+ if (child.start > cursor) parts.push(source.slice(cursor, child.start));
1152
+ parts.push(child);
1153
+ cursor = child.end;
1154
+ }
1155
+ if (cursor < end) parts.push(source.slice(cursor, end));
1156
+ return parts;
1157
+ }
1158
+ function containsEdit(starts, node) {
1159
+ let low = 0;
1160
+ let high = starts.length;
1161
+ while (low < high) {
1162
+ const middle = low + high >>> 1;
1163
+ if (starts[middle] < node.start) low = middle + 1;
1164
+ else high = middle;
1165
+ }
1166
+ return low < starts.length && starts[low] < node.end;
1167
+ }
1168
+ /** 源码片段按树归属组合,父级替换自然覆盖已登记的后代编辑。 */
1169
+ function renderEdits(session, ranges, snippets) {
1170
+ const { source, children } = session.document;
1171
+ const starts = Array.from(session.edits.keys(), (node) => node.start).sort((left, right) => left - right);
1172
+ const stack = childrenParts(source, children, 0, source.length).reverse();
1173
+ const output = [];
1174
+ let length = 0;
1175
+ const emit = (...parts) => {
1176
+ for (const part of parts) {
1177
+ const value = typeof part === "string" ? part : part.source;
1178
+ if (typeof part !== "string") snippets?.push({
1179
+ source: value,
1180
+ start: length,
1181
+ end: length + value.length
1182
+ });
1183
+ output.push(value);
1184
+ if (ranges || snippets) length += value.length;
1185
+ }
1186
+ };
1187
+ while (stack.length) {
1188
+ const part = stack.pop();
1189
+ if (typeof part === "string") {
1190
+ emit(part);
1191
+ continue;
1192
+ }
1193
+ if (part.kind === "range-end") {
1194
+ ranges.set(part.node, {
1195
+ start: part.start,
1196
+ end: length
1197
+ });
1198
+ continue;
1199
+ }
1200
+ if (part.kind === "snippet") {
1201
+ emit(part);
1202
+ continue;
1203
+ }
1204
+ const state = session.edits.get(part);
1205
+ if (!state && !containsEdit(starts, part)) {
1206
+ const value = source.slice(part.start, part.end);
1207
+ if (ranges?.has(part)) ranges.set(part, {
1208
+ start: length,
1209
+ end: length + value.length
1210
+ });
1211
+ emit(value);
1212
+ continue;
1213
+ }
1214
+ emit(...state?.before ?? []);
1215
+ const rangeStart = length;
1216
+ if (state?.removed || state?.replacement !== void 0) {
1217
+ if (!state.removed) {
1218
+ if (state.literalText === false && typeof state.replacement === "string") assertExpressionBoundary(state.replacement, session.document.syntax);
1219
+ emit(state.replacement);
1220
+ }
1221
+ emit(...state.after ?? []);
1222
+ continue;
1223
+ }
1224
+ if (part.kind !== "element") {
1225
+ emit(source.slice(part.start, part.end), ...state?.after ?? []);
1226
+ continue;
1227
+ }
1228
+ const expanded = Boolean(part.selfClosing && (state?.prepend?.length || state?.append?.length));
1229
+ emit(openingTag(session, part, state, expanded), ...state?.prepend ?? []);
1230
+ const inner = part.selfClosing ? [] : childrenParts(source, part.children, part.opening.end, part.closing.start);
1231
+ inner.push(...state?.append ?? []);
1232
+ if (expanded) inner.push(`</${state?.name ?? part.name}>`);
1233
+ else if (part.closing) inner.push(state?.name && state.name !== part.name ? source.slice(part.closing.start, part.closing.nameStart) + state.name + source.slice(part.closing.nameEnd, part.closing.end) : source.slice(part.closing.start, part.closing.end));
1234
+ if (ranges?.has(part)) inner.push({
1235
+ kind: "range-end",
1236
+ node: part,
1237
+ start: rangeStart
1238
+ });
1239
+ inner.push(...state?.after ?? []);
1240
+ for (let index = inner.length - 1; index >= 0; index--) stack.push(inner[index]);
1241
+ }
1242
+ return output.join("");
1243
+ }
1244
+ // src/edit/overlay.ts
1245
+ const editOverlays = /* @__PURE__ */ new WeakMap();
1246
+ // src/edit/state.ts
1247
+ function stateFor(session, node) {
1248
+ let state = session.edits.get(node);
1249
+ if (!state) {
1250
+ state = { removed: false };
1251
+ session.edits.set(node, state);
1252
+ }
1253
+ return state;
1254
+ }
1255
+ function assertName(name) {
1256
+ if (typeof name !== "string" || !/^[A-Z_][\w:.-]*$/i.test(name)) throw new TypeError(`Invalid WXML name: ${String(name)}.`);
1257
+ }
1258
+ function assertValid(document) {
1259
+ const diagnostic = document.diagnostics.find((item) => item.severity === "error");
1260
+ if (diagnostic) throw new TypeError(`Invalid WXML document: ${diagnostic.message}`);
1261
+ }
1262
+ function validateSnippet(session, source, raw = false) {
1263
+ if (typeof source !== "string") throw new TypeError("Expected a WXML source string.");
1264
+ if (!source) return source;
1265
+ if (!raw) {
1266
+ if (session.document.options.resolveScriptBoundary) return {
1267
+ kind: "snippet",
1268
+ source
1269
+ };
1270
+ assertValid(parse(source, session.document.options));
1271
+ }
1272
+ return source;
1273
+ }
1274
+ // src/edit/document.ts
1275
+ /** 只投影公开文档字段,兼容使用原型 getter 的延迟文档与普通解析结果。 */
1276
+ function copyDocument(document) {
1277
+ return {
1278
+ source: document.source,
1279
+ platform: document.platform,
1280
+ syntax: document.syntax,
1281
+ diagnostics: document.diagnostics,
1282
+ options: document.options,
1283
+ children: document.children,
1284
+ tokens: document.tokens
1285
+ };
1286
+ }
1287
+ /** 延迟状态由实例独占,getter 与物化方法共享原型,避免每次编辑分配访问器闭包。 */
1288
+ var PatchedDocument = class {
1289
+ platform;
1290
+ syntax;
1291
+ diagnostics = [];
1292
+ options;
1293
+ #snapshot;
1294
+ #sourceValue;
1295
+ #materialized;
1296
+ constructor(original, snapshot) {
1297
+ this.platform = original.platform;
1298
+ this.syntax = original.syntax;
1299
+ this.options = original.options;
1300
+ this.#snapshot = snapshot;
1301
+ }
1302
+ get source() {
1303
+ if (this.#sourceValue === void 0) {
1304
+ this.#sourceValue = renderEdits(this.#snapshot);
1305
+ this.#snapshot = void 0;
1306
+ }
1307
+ return this.#sourceValue;
1308
+ }
1309
+ get children() {
1310
+ return this.#readDocument().children;
1311
+ }
1312
+ get tokens() {
1313
+ return this.#readDocument().tokens;
1314
+ }
1315
+ toJSON() {
1316
+ return copyDocument(this);
1317
+ }
1318
+ #readDocument() {
1319
+ if (!this.#materialized) {
1320
+ const document = parse(this.source, this.options);
1321
+ assertValid(document);
1322
+ this.#materialized = document;
1323
+ editOverlays.delete(this);
1324
+ }
1325
+ return this.#materialized;
1326
+ }
1327
+ };
1328
+ /** 结构不变的受控修改只验证改动词法,公开 AST 与范围首次读取时统一重建。 */
1329
+ function createPatchedDocument(session) {
1330
+ const original = session.document;
1331
+ if (session.hasStructuralInvalidations || original.options.resolveScriptBoundary || original.diagnostics.length) return;
1332
+ const elements = /* @__PURE__ */ new Map();
1333
+ const text = /* @__PURE__ */ new Map();
1334
+ for (const [node, state] of session.edits) {
1335
+ if (state.removed || state.before?.length || state.after?.length || state.prepend?.length || state.append?.length) return;
1336
+ if (node.kind === "element") {
1337
+ if (state.replacement !== void 0 || state.name && state.name !== node.name && (original.options.rawTags ?? defaultRawTags).some((name) => name.toLowerCase() === node.name.toLowerCase() || name.toLowerCase() === state.name.toLowerCase())) return;
1338
+ if (!state.unvalidatedAttributes?.size) {
1339
+ elements.set(node, {
1340
+ name: state.name ?? node.name,
1341
+ attributes: editedAttributes(node, state)
1342
+ });
1343
+ continue;
1344
+ }
1345
+ const source = openingTag(session, node, state, false);
1346
+ try {
1347
+ const opening = readTag(source, 0, original.syntax);
1348
+ if (opening.end !== source.length || opening.selfClosing !== node.selfClosing) return;
1349
+ elements.set(node, opening);
1350
+ } catch (error) {
1351
+ if (!(error instanceof TemplateLexicalError)) throw error;
1352
+ throw new TypeError(`Invalid WXML document: ${error.message}`);
1353
+ }
1354
+ } else if (state.replacement !== void 0) {
1355
+ if (node.kind !== "text" || typeof state.replacement !== "string") return;
1356
+ if (state.literalText && state.replacement) {
1357
+ text.set(node, state.replacement);
1358
+ continue;
1359
+ }
1360
+ if (state.literalText === false) assertExpressionBoundary(state.replacement, original.syntax);
1361
+ const replacement = parse(state.replacement, original.options);
1362
+ assertValid(replacement);
1363
+ if (replacement.children.length !== 1 || replacement.children[0]?.kind !== "text") return;
1364
+ text.set(node, state.replacement);
1365
+ }
1366
+ }
1367
+ const document = new PatchedDocument(original, {
1368
+ document: original,
1369
+ active: false,
1370
+ hasStructuralInvalidations: session.hasStructuralInvalidations,
1371
+ edits: new Map(session.edits)
1372
+ });
1373
+ editOverlays.set(document, {
1374
+ original,
1375
+ elements,
1376
+ text
1377
+ });
1378
+ return document;
1379
+ }
1380
+ // src/edit/node.ts
1381
+ /** 操作仅在被读取时绑定,普通遍历节点不分配整套编辑闭包。 */
1382
+ var EditableHandle = class {
1383
+ session;
1384
+ node;
1385
+ parent;
1386
+ changes;
1387
+ constructor(session, node, parent) {
1388
+ this.session = session;
1389
+ this.node = node;
1390
+ this.parent = parent;
1391
+ }
1392
+ isInvalidated() {
1393
+ const structuralReplacement = this.changes?.replacement !== void 0 && this.changes.literalText === void 0;
1394
+ if (this.changes?.removed || structuralReplacement) return true;
1395
+ if (!this.session.hasStructuralInvalidations) return false;
1396
+ for (let current = this.parent; current; current = current.parent) {
1397
+ const parentStructuralReplacement = current.changes?.replacement !== void 0 && current.changes.literalText === void 0;
1398
+ if (current.changes?.removed || parentStructuralReplacement) return true;
1399
+ }
1400
+ return false;
1401
+ }
1402
+ assertActive() {
1403
+ if (!this.session.active || this.isInvalidated()) throw new Error("This WXML edit handle is no longer active.");
1404
+ }
1405
+ state() {
1406
+ if (!this.changes) this.changes = stateFor(this.session, this.node);
1407
+ return this.changes;
1408
+ }
1409
+ element() {
1410
+ this.assertActive();
1411
+ if (this.node.kind !== "element") throw new TypeError("This edit requires an element node.");
1412
+ return this.state();
1413
+ }
1414
+ attribute(name) {
1415
+ this.assertActive();
1416
+ assertName(name);
1417
+ return this.element();
1418
+ }
1419
+ insert(position, source) {
1420
+ this.assertActive();
1421
+ if ((position === "prepend" || position === "append") && this.node.kind !== "element") throw new TypeError("This edit requires an element node.");
1422
+ const rawOwner = this.node.kind === "script" ? this.parent : (position === "prepend" || position === "append") && this.isRawElement() ? this : void 0;
1423
+ const snippet = validateSnippet(this.session, source, Boolean(rawOwner));
1424
+ if (source) {
1425
+ rawOwner?.registerRawOwner();
1426
+ const state = this.state();
1427
+ (state[position] ??= []).push(snippet);
1428
+ }
1429
+ }
1430
+ isRawElement() {
1431
+ if (this.node.kind !== "element") return false;
1432
+ const tag = (this.changes?.name ?? this.node.name).toLowerCase();
1433
+ return (this.session.document.options.rawTags ?? defaultRawTags).some((name) => name.toLowerCase() === tag);
1434
+ }
1435
+ registerRawOwner() {
1436
+ if (this.node.kind === "element") {
1437
+ this.session.rawOwners ??= /* @__PURE__ */ new Map();
1438
+ this.session.rawOwners.set(this.node, { isInvalidated: () => this.isInvalidated() });
1439
+ }
1440
+ }
1441
+ get rename() {
1442
+ return (name) => {
1443
+ const state = this.element();
1444
+ assertName(name);
1445
+ state.name = name;
1446
+ };
1447
+ }
1448
+ get setAttribute() {
1449
+ return (name, value) => {
1450
+ const state = this.attribute(name);
1451
+ const encoded = encodeAttribute(value, this.session.document.syntax);
1452
+ (state.attributes ??= /* @__PURE__ */ new Map()).set(name, encoded);
1453
+ if (typeof value === "object") {
1454
+ state.unvalidatedAttributes ??= /* @__PURE__ */ new Set();
1455
+ state.unvalidatedAttributes.add(name);
1456
+ } else state.unvalidatedAttributes?.delete(name);
1457
+ };
1458
+ }
1459
+ get setBooleanAttribute() {
1460
+ return (name) => {
1461
+ const state = this.attribute(name);
1462
+ (state.attributes ??= /* @__PURE__ */ new Map()).set(name, null);
1463
+ state.unvalidatedAttributes?.delete(name);
1464
+ };
1465
+ }
1466
+ get removeAttribute() {
1467
+ return (name) => {
1468
+ const state = this.attribute(name);
1469
+ (state.attributes ??= /* @__PURE__ */ new Map()).set(name, void 0);
1470
+ state.unvalidatedAttributes?.delete(name);
1471
+ };
1472
+ }
1473
+ get replaceText() {
1474
+ return (value) => {
1475
+ this.assertActive();
1476
+ if (this.node.kind !== "text") throw new TypeError("replaceText requires a text node.");
1477
+ const state = this.state();
1478
+ state.replacement = encodeText(value);
1479
+ state.literalText = typeof value === "string";
1480
+ };
1481
+ }
1482
+ get remove() {
1483
+ return () => {
1484
+ this.assertActive();
1485
+ this.state().removed = true;
1486
+ if (this.node.kind === "element") this.session.hasStructuralInvalidations = true;
1487
+ };
1488
+ }
1489
+ get replaceWith() {
1490
+ return (source) => {
1491
+ this.assertActive();
1492
+ const rawOwner = this.node.kind === "script" ? this.parent : void 0;
1493
+ const state = this.state();
1494
+ state.replacement = validateSnippet(this.session, source, Boolean(rawOwner));
1495
+ state.literalText = void 0;
1496
+ rawOwner?.registerRawOwner();
1497
+ if (this.node.kind === "element") this.session.hasStructuralInvalidations = true;
1498
+ };
1499
+ }
1500
+ get insertBefore() {
1501
+ return (source) => this.insert("before", source);
1502
+ }
1503
+ get insertAfter() {
1504
+ return (source) => this.insert("after", source);
1505
+ }
1506
+ get prepend() {
1507
+ return (source) => this.insert("prepend", source);
1508
+ }
1509
+ get append() {
1510
+ return (source) => this.insert("append", source);
1511
+ }
1512
+ };
1513
+ // src/edit/snippets.ts
1514
+ /** 局部校验复用完整文档已选定的脚本边界,不向用户 resolver 传入片段上下文。 */
1515
+ function validateSnippets(document, snippets) {
1516
+ const boundaries = /* @__PURE__ */ new Map();
1517
+ for (let index = 0; index < document.tokens.length; index++) {
1518
+ const token = document.tokens[index];
1519
+ if (token.kind !== "tag" || token.closing || token.matching === void 0 || document.tokens[index + 1]?.kind !== "script") continue;
1520
+ const closing = document.tokens[token.matching];
1521
+ boundaries.set(token.end, {
1522
+ name: token.name.toLowerCase(),
1523
+ closing
1524
+ });
1525
+ }
1526
+ for (const snippet of snippets) assertValid(parse(snippet.source, {
1527
+ ...document.options,
1528
+ resolveScriptBoundary(_source, start, name) {
1529
+ const boundary = boundaries.get(snippet.start + start);
1530
+ if (!boundary || boundary.name !== name.toLowerCase() || boundary.closing.start < snippet.start || boundary.closing.end > snippet.end) return;
1531
+ return {
1532
+ start: boundary.closing.start - snippet.start,
1533
+ end: boundary.closing.end - snippet.start
1534
+ };
1535
+ }
1536
+ }));
1537
+ }
1538
+ /** 先解析最终源码,再独立验证仍存活的结构片段;被祖先覆盖的片段不会进入校验集合。 */
1539
+ function parseCompleteEdits(session, ranges) {
1540
+ const snippets = session.document.options.resolveScriptBoundary ? [] : void 0;
1541
+ const document = parse(renderEdits(session, ranges, snippets), session.document.options);
1542
+ assertValid(document);
1543
+ if (snippets?.length) validateSnippets(document, snippets);
1544
+ return document;
1545
+ }
1546
+ // src/edit/raw.ts
1547
+ /** 原始脚本片段按完整宿主上下文解析,且不能越过原有宿主边界插入结构。 */
1548
+ function parseRawEdits(session) {
1549
+ const ranges = /* @__PURE__ */ new Map();
1550
+ for (const [node, owner] of session.rawOwners ?? []) if (!owner.isInvalidated()) ranges.set(node, {
1551
+ start: 0,
1552
+ end: 0
1553
+ });
1554
+ const document = parseCompleteEdits(session, ranges);
1555
+ const expected = new Map([...ranges.values()].map((range) => [range.start, range]));
1556
+ const stack = [...document.children];
1557
+ while (stack.length && expected.size) {
1558
+ const node = stack.pop();
1559
+ const range = expected.get(node.start);
1560
+ if (range) {
1561
+ if (node.kind !== "element" || node.end !== range.end || node.children.length !== 1 || node.children[0]?.kind !== "script") throw new TypeError("Raw WXML edits must stay inside their original script owner.");
1562
+ expected.delete(node.start);
1563
+ }
1564
+ if (node.kind === "element") stack.push(...node.children);
1565
+ }
1566
+ if (expected.size) throw new TypeError("Raw WXML edits must stay inside their original script owner.");
1567
+ return document;
1568
+ }
1569
+ // src/edit/index.ts
1570
+ /** 同步编辑会话验证变更词法后发布新文档,原始文档保持不变。 */
1571
+ function edit(document, visitor) {
1572
+ assertValid(document);
1573
+ if (typeof visitor !== "function") throw new TypeError("Expected a synchronous WXML edit visitor.");
1574
+ const session = {
1575
+ document,
1576
+ active: true,
1577
+ hasStructuralInvalidations: false,
1578
+ edits: /* @__PURE__ */ new Map()
1579
+ };
1580
+ const stack = document.children.map((node) => new EditableHandle(session, node)).reverse();
1581
+ try {
1582
+ while (stack.length) {
1583
+ const handle = stack.pop();
1584
+ if (session.hasStructuralInvalidations && handle.isInvalidated()) continue;
1585
+ const { node } = handle;
1586
+ const result = visitor(handle);
1587
+ if (result !== null && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") {
1588
+ Promise.resolve(result).catch(() => {});
1589
+ throw new TypeError("WXML edit visitors must be synchronous; Promise results are not supported.");
1590
+ }
1591
+ if (result === false || node.kind !== "element" || session.hasStructuralInvalidations && handle.isInvalidated()) continue;
1592
+ for (let index = node.children.length - 1; index >= 0; index--) {
1593
+ const child = node.children[index];
1594
+ stack.push(new EditableHandle(session, child, handle));
1595
+ }
1596
+ }
1597
+ session.active = false;
1598
+ if (!session.edits.size) return copyDocument(document);
1599
+ const next = session.rawOwners?.size ? parseRawEdits(session) : createPatchedDocument(session) ?? parseCompleteEdits(session);
1600
+ assertValid(next);
1601
+ return next;
1602
+ } finally {
1603
+ session.active = false;
1604
+ session.edits.clear();
1605
+ session.rawOwners?.clear();
1606
+ }
1607
+ }
1608
+ // src/serialize.ts
1609
+ /** 保留模式输出当前文档源码;规范模式逐节点输出并保留所有文本。 */
1610
+ function serialize(document, options = {}) {
1611
+ if (document.diagnostics.length && document.diagnostics.some((diagnostic) => diagnostic.severity === "error")) throw new TypeError("Cannot serialize an invalid WXML document.");
1612
+ if (options.mode === void 0 || options.mode === "preserve") return document.source;
1613
+ if (options.mode !== "canonical") throw new TypeError(`Unknown WXML serialization mode: ${String(options.mode)}.`);
1614
+ const overlay = editOverlays.get(document);
1615
+ let output = "";
1616
+ const stack = [...(overlay?.original ?? document).children].reverse();
1617
+ while (stack.length) {
1618
+ const node = stack.pop();
1619
+ if (typeof node === "string") output += node;
1620
+ else if (node.kind !== "element") output += overlay?.text.get(node) ?? node.data;
1621
+ else {
1622
+ const element = overlay?.elements.get(node) ?? node;
1623
+ output += `<${element.name}`;
1624
+ for (const attribute of element.attributes) output += ` ${canonicalAttribute(attribute, document.syntax)}`;
1625
+ output += node.selfClosing ? " />" : ">";
1626
+ if (!node.selfClosing) {
1627
+ stack.push(`</${element.name}>`);
1628
+ for (let index = node.children.length - 1; index >= 0; index--) stack.push(node.children[index]);
1629
+ }
1630
+ }
1631
+ }
1632
+ return output;
1633
+ }
1634
+ // src/walk.ts
1635
+ /** 迭代遍历文档,enter 返回 false 时跳过子树,避免深模板递归溢出。 */
1636
+ function walk(document, visitor) {
1637
+ const roots = Array.isArray(document) ? document : document.children;
1638
+ const stack = [];
1639
+ for (let index = roots.length - 1; index >= 0; index--) stack.push({ node: roots[index] });
1640
+ while (stack.length) {
1641
+ const frame = stack.pop();
1642
+ if (frame.leave) {
1643
+ visitor.leave?.(frame.node, frame.parent);
1644
+ continue;
1645
+ }
1646
+ const descend = visitor.enter?.(frame.node, frame.parent) !== false;
1647
+ if (visitor.leave) stack.push({
1648
+ ...frame,
1649
+ leave: true
1650
+ });
1651
+ if (descend && frame.node.kind === "element") for (let index = frame.node.children.length - 1; index >= 0; index--) stack.push({
1652
+ node: frame.node.children[index],
1653
+ parent: frame.node
1654
+ });
1655
+ }
1656
+ }
1657
+ export { TemplateLexicalError, decodeAttribute, edit, expressionEnd, findScriptClosingTag, findTrailingScriptComment, interpolations, parse, readTag, scan, scanComments, scanScriptBoundaryCandidates, serialize, walk };