@dcloudio/uni-cli-shared 3.0.0-alpha-4070720250804001 → 3.0.0-alpha-4070620250731002

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.
Files changed (163) hide show
  1. package/dist/easycom.d.ts +0 -1
  2. package/dist/easycom.js +13 -17
  3. package/dist/hbx/alias.js +10 -43
  4. package/dist/hbx/index.js +0 -10
  5. package/dist/hbx/log.js +1 -23
  6. package/dist/index.d.ts +1 -2
  7. package/dist/index.js +1 -3
  8. package/dist/json/index.d.ts +1 -1
  9. package/dist/json/index.js +1 -2
  10. package/dist/json/manifest.d.ts +0 -1
  11. package/dist/json/manifest.js +1 -11
  12. package/dist/json/mp/jsonFile.js +2 -4
  13. package/dist/json/mp/pages.js +0 -1
  14. package/dist/json/mp/types.d.ts +1 -4
  15. package/dist/json/uni-x/manifest.d.ts +0 -1
  16. package/dist/json/uni-x/manifest.js +1 -5
  17. package/dist/messages/zh_CN.js +0 -1
  18. package/dist/uni_modules.cloud.d.ts +4 -10
  19. package/dist/uni_modules.cloud.js +19 -58
  20. package/dist/uni_modules.d.ts +0 -2
  21. package/dist/uni_modules.js +2 -81
  22. package/dist/uts.js +0 -16
  23. package/dist/vite/autoImport.js +0 -2
  24. package/dist/vite/cloud.js +5 -51
  25. package/dist/vite/plugins/index.d.ts +0 -1
  26. package/dist/vite/plugins/index.js +1 -3
  27. package/dist/vite/plugins/inject.js +1 -3
  28. package/dist/vite/plugins/uts/uni_modules.d.ts +0 -1
  29. package/dist/vite/plugins/uts/uni_modules.js +14 -63
  30. package/dist/vite/plugins/uts/uvue.js +3 -17
  31. package/dist/vite/plugins/vitejs/plugins/css.js +5 -40
  32. package/dist/vue/transforms/transformUTSComponent.js +3 -8
  33. package/package.json +38 -38
  34. package/dist/vite/plugins/stats.d.ts +0 -2
  35. package/dist/vite/plugins/stats.js +0 -42
  36. package/dist/workers.d.ts +0 -14
  37. package/dist/workers.js +0 -187
  38. package/lib/vapor/@vitejs/plugin-vue/LICENSE +0 -21
  39. package/lib/vapor/@vitejs/plugin-vue/README.md +0 -278
  40. package/lib/vapor/@vitejs/plugin-vue/dist/index.cjs +0 -3105
  41. package/lib/vapor/@vitejs/plugin-vue/dist/index.d.cts +0 -113
  42. package/lib/vapor/@vitejs/plugin-vue/dist/index.d.mts +0 -111
  43. package/lib/vapor/@vitejs/plugin-vue/dist/index.d.ts +0 -113
  44. package/lib/vapor/@vitejs/plugin-vue/dist/index.mjs +0 -3090
  45. package/lib/vapor/@vitejs/plugin-vue/package.json +0 -50
  46. package/lib/vapor/@vue/compiler-core/LICENSE +0 -21
  47. package/lib/vapor/@vue/compiler-core/README.md +0 -1
  48. package/lib/vapor/@vue/compiler-core/dist/compiler-core.cjs.js +0 -6902
  49. package/lib/vapor/@vue/compiler-core/dist/compiler-core.cjs.prod.js +0 -6779
  50. package/lib/vapor/@vue/compiler-core/dist/compiler-core.esm-bundler.js +0 -5870
  51. package/lib/vapor/@vue/compiler-core/index.js +0 -7
  52. package/lib/vapor/@vue/compiler-core/package.json +0 -58
  53. package/lib/vapor/@vue/compiler-dom/LICENSE +0 -21
  54. package/lib/vapor/@vue/compiler-dom/README.md +0 -1
  55. package/lib/vapor/@vue/compiler-dom/dist/compiler-dom.cjs.js +0 -936
  56. package/lib/vapor/@vue/compiler-dom/dist/compiler-dom.cjs.prod.js +0 -856
  57. package/lib/vapor/@vue/compiler-dom/dist/compiler-dom.esm-browser.js +0 -6682
  58. package/lib/vapor/@vue/compiler-dom/dist/compiler-dom.esm-browser.prod.js +0 -14
  59. package/lib/vapor/@vue/compiler-dom/dist/compiler-dom.esm-bundler.js +0 -693
  60. package/lib/vapor/@vue/compiler-dom/dist/compiler-dom.global.js +0 -6855
  61. package/lib/vapor/@vue/compiler-dom/dist/compiler-dom.global.prod.js +0 -14
  62. package/lib/vapor/@vue/compiler-dom/index.js +0 -7
  63. package/lib/vapor/@vue/compiler-dom/package.json +0 -57
  64. package/lib/vapor/@vue/compiler-sfc/LICENSE +0 -21
  65. package/lib/vapor/@vue/compiler-sfc/README.md +0 -80
  66. package/lib/vapor/@vue/compiler-sfc/dist/compiler-sfc.cjs.js +0 -21682
  67. package/lib/vapor/@vue/compiler-sfc/dist/compiler-sfc.esm-browser.js +0 -66272
  68. package/lib/vapor/@vue/compiler-sfc/package.json +0 -68
  69. package/lib/vapor/@vue/compiler-ssr/LICENSE +0 -21
  70. package/lib/vapor/@vue/compiler-ssr/README.md +0 -1
  71. package/lib/vapor/@vue/compiler-ssr/dist/compiler-ssr.cjs.js +0 -1402
  72. package/lib/vapor/@vue/compiler-ssr/package.json +0 -34
  73. package/lib/vapor/@vue/compiler-vapor/LICENSE +0 -21
  74. package/lib/vapor/@vue/compiler-vapor/README.md +0 -1
  75. package/lib/vapor/@vue/compiler-vapor/dist/compiler-vapor.cjs.js +0 -4540
  76. package/lib/vapor/@vue/compiler-vapor/dist/compiler-vapor.esm-browser.js +0 -37020
  77. package/lib/vapor/@vue/compiler-vapor/package.json +0 -49
  78. package/lib/vapor/@vue/reactivity/LICENSE +0 -21
  79. package/lib/vapor/@vue/reactivity/README.md +0 -19
  80. package/lib/vapor/@vue/reactivity/dist/reactivity.cjs.js +0 -2033
  81. package/lib/vapor/@vue/reactivity/dist/reactivity.cjs.prod.js +0 -1841
  82. package/lib/vapor/@vue/reactivity/dist/reactivity.esm-browser.js +0 -2023
  83. package/lib/vapor/@vue/reactivity/dist/reactivity.esm-browser.prod.js +0 -5
  84. package/lib/vapor/@vue/reactivity/dist/reactivity.esm-bundler.js +0 -1992
  85. package/lib/vapor/@vue/reactivity/dist/reactivity.global.js +0 -2082
  86. package/lib/vapor/@vue/reactivity/dist/reactivity.global.prod.js +0 -5
  87. package/lib/vapor/@vue/reactivity/index.js +0 -7
  88. package/lib/vapor/@vue/reactivity/package.json +0 -55
  89. package/lib/vapor/@vue/runtime-core/LICENSE +0 -21
  90. package/lib/vapor/@vue/runtime-core/README.md +0 -28
  91. package/lib/vapor/@vue/runtime-core/dist/runtime-core.cjs.js +0 -8972
  92. package/lib/vapor/@vue/runtime-core/dist/runtime-core.cjs.prod.js +0 -7088
  93. package/lib/vapor/@vue/runtime-core/dist/runtime-core.esm-bundler.js +0 -8913
  94. package/lib/vapor/@vue/runtime-core/index.js +0 -7
  95. package/lib/vapor/@vue/runtime-core/package.json +0 -54
  96. package/lib/vapor/@vue/runtime-dom/LICENSE +0 -21
  97. package/lib/vapor/@vue/runtime-dom/README.md +0 -13
  98. package/lib/vapor/@vue/runtime-dom/dist/runtime-dom.cjs.js +0 -1797
  99. package/lib/vapor/@vue/runtime-dom/dist/runtime-dom.cjs.prod.js +0 -1646
  100. package/lib/vapor/@vue/runtime-dom/dist/runtime-dom.esm-browser.js +0 -12929
  101. package/lib/vapor/@vue/runtime-dom/dist/runtime-dom.esm-browser.prod.js +0 -6
  102. package/lib/vapor/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js +0 -1838
  103. package/lib/vapor/@vue/runtime-dom/dist/runtime-dom.global.js +0 -13086
  104. package/lib/vapor/@vue/runtime-dom/dist/runtime-dom.global.prod.js +0 -6
  105. package/lib/vapor/@vue/runtime-dom/index.js +0 -7
  106. package/lib/vapor/@vue/runtime-dom/package.json +0 -60
  107. package/lib/vapor/@vue/runtime-vapor/LICENSE +0 -21
  108. package/lib/vapor/@vue/runtime-vapor/README.md +0 -8
  109. package/lib/vapor/@vue/runtime-vapor/dist/runtime-vapor.esm-bundler.js +0 -3242
  110. package/lib/vapor/@vue/runtime-vapor/package.json +0 -47
  111. package/lib/vapor/@vue/server-renderer/LICENSE +0 -21
  112. package/lib/vapor/@vue/server-renderer/README.md +0 -178
  113. package/lib/vapor/@vue/server-renderer/dist/server-renderer.cjs.js +0 -1144
  114. package/lib/vapor/@vue/server-renderer/dist/server-renderer.cjs.prod.js +0 -871
  115. package/lib/vapor/@vue/server-renderer/dist/server-renderer.esm-browser.js +0 -8756
  116. package/lib/vapor/@vue/server-renderer/dist/server-renderer.esm-browser.prod.js +0 -5
  117. package/lib/vapor/@vue/server-renderer/dist/server-renderer.esm-bundler.js +0 -1366
  118. package/lib/vapor/@vue/server-renderer/index.js +0 -7
  119. package/lib/vapor/@vue/server-renderer/package.json +0 -55
  120. package/lib/vapor/@vue/shared/LICENSE +0 -21
  121. package/lib/vapor/@vue/shared/README.md +0 -3
  122. package/lib/vapor/@vue/shared/dist/shared.cjs.js +0 -698
  123. package/lib/vapor/@vue/shared/dist/shared.cjs.prod.js +0 -690
  124. package/lib/vapor/@vue/shared/dist/shared.esm-bundler.js +0 -616
  125. package/lib/vapor/@vue/shared/index.js +0 -7
  126. package/lib/vapor/@vue/shared/package.json +0 -47
  127. package/lib/vapor/@vue/vue/LICENSE +0 -21
  128. package/lib/vapor/@vue/vue/README.md +0 -62
  129. package/lib/vapor/@vue/vue/compiler-sfc/index.browser.js +0 -1
  130. package/lib/vapor/@vue/vue/compiler-sfc/index.browser.mjs +0 -1
  131. package/lib/vapor/@vue/vue/compiler-sfc/index.d.mts +0 -1
  132. package/lib/vapor/@vue/vue/compiler-sfc/index.d.ts +0 -1
  133. package/lib/vapor/@vue/vue/compiler-sfc/index.js +0 -3
  134. package/lib/vapor/@vue/vue/compiler-sfc/index.mjs +0 -3
  135. package/lib/vapor/@vue/vue/compiler-sfc/package.json +0 -4
  136. package/lib/vapor/@vue/vue/compiler-sfc/register-ts.js +0 -3
  137. package/lib/vapor/@vue/vue/dist/vue.cjs.js +0 -80
  138. package/lib/vapor/@vue/vue/dist/vue.cjs.prod.js +0 -66
  139. package/lib/vapor/@vue/vue/dist/vue.esm-browser.js +0 -18840
  140. package/lib/vapor/@vue/vue/dist/vue.esm-browser.prod.js +0 -12
  141. package/lib/vapor/@vue/vue/dist/vue.esm-bundler.js +0 -72
  142. package/lib/vapor/@vue/vue/dist/vue.global.js +0 -18820
  143. package/lib/vapor/@vue/vue/dist/vue.global.prod.js +0 -12
  144. package/lib/vapor/@vue/vue/dist/vue.runtime-with-vapor.esm-browser.js +0 -15648
  145. package/lib/vapor/@vue/vue/dist/vue.runtime-with-vapor.esm-browser.prod.js +0 -9
  146. package/lib/vapor/@vue/vue/dist/vue.runtime.esm-browser.js +0 -12953
  147. package/lib/vapor/@vue/vue/dist/vue.runtime.esm-browser.prod.js +0 -6
  148. package/lib/vapor/@vue/vue/dist/vue.runtime.esm-bundler.js +0 -29
  149. package/lib/vapor/@vue/vue/dist/vue.runtime.global.js +0 -13111
  150. package/lib/vapor/@vue/vue/dist/vue.runtime.global.prod.js +0 -6
  151. package/lib/vapor/@vue/vue/index.js +0 -7
  152. package/lib/vapor/@vue/vue/index.mjs +0 -1
  153. package/lib/vapor/@vue/vue/jsx-runtime/index.d.ts +0 -25
  154. package/lib/vapor/@vue/vue/jsx-runtime/index.js +0 -15
  155. package/lib/vapor/@vue/vue/jsx-runtime/index.mjs +0 -12
  156. package/lib/vapor/@vue/vue/jsx-runtime/package.json +0 -5
  157. package/lib/vapor/@vue/vue/jsx.d.ts +0 -22
  158. package/lib/vapor/@vue/vue/package.json +0 -114
  159. package/lib/vapor/@vue/vue/server-renderer/index.d.mts +0 -1
  160. package/lib/vapor/@vue/vue/server-renderer/index.d.ts +0 -1
  161. package/lib/vapor/@vue/vue/server-renderer/index.js +0 -1
  162. package/lib/vapor/@vue/vue/server-renderer/index.mjs +0 -1
  163. package/lib/vapor/@vue/vue/server-renderer/package.json +0 -4
@@ -1,4540 +0,0 @@
1
- /**
2
- * @vue/compiler-vapor v3.6.0-alpha.2
3
- * (c) 2018-present Yuxi (Evan) You and Vue contributors
4
- * @license MIT
5
- **/
6
- 'use strict';
7
-
8
- Object.defineProperty(exports, '__esModule', { value: true });
9
-
10
- var compilerDom = require('@vue/compiler-dom');
11
- var shared = require('@vue/shared');
12
- var sourceMapJs = require('source-map-js');
13
- var parser = require('@babel/parser');
14
- var types = require('@babel/types');
15
- var estreeWalker = require('estree-walker');
16
-
17
- const newDynamic = () => ({
18
- flags: 1,
19
- children: []
20
- });
21
- const newBlock = (node) => ({
22
- type: 1,
23
- node,
24
- dynamic: newDynamic(),
25
- effect: [],
26
- operation: [],
27
- returns: [],
28
- tempId: 0
29
- });
30
- function wrapTemplate(node, dirs) {
31
- if (node.tagType === 3) {
32
- return node;
33
- }
34
- const reserved = [];
35
- const pass = [];
36
- node.props.forEach((prop) => {
37
- if (prop.type === 7 && dirs.includes(prop.name)) {
38
- reserved.push(prop);
39
- } else {
40
- pass.push(prop);
41
- }
42
- });
43
- return shared.extend({}, node, {
44
- type: 1,
45
- tag: "template",
46
- props: reserved,
47
- tagType: 3,
48
- children: [shared.extend({}, node, { props: pass })]
49
- });
50
- }
51
- const EMPTY_EXPRESSION = compilerDom.createSimpleExpression(
52
- "",
53
- true
54
- );
55
-
56
- const findProp = compilerDom.findProp;
57
- const findDir = compilerDom.findDir;
58
- function propToExpression(prop) {
59
- return prop.type === 6 ? prop.value ? compilerDom.createSimpleExpression(prop.value.content, true, prop.value.loc) : EMPTY_EXPRESSION : prop.exp;
60
- }
61
- function isConstantExpression(exp) {
62
- return compilerDom.isLiteralWhitelisted(exp.content) || shared.isGloballyAllowed(exp.content) || getLiteralExpressionValue(exp) !== null;
63
- }
64
- function isStaticExpression(node, bindings) {
65
- if (node.ast) {
66
- return compilerDom.isConstantNode(node.ast, bindings);
67
- } else if (node.ast === null) {
68
- const type = bindings[node.content];
69
- return type === "literal-const";
70
- }
71
- return false;
72
- }
73
- function resolveExpression(exp) {
74
- if (!exp.isStatic) {
75
- const value = getLiteralExpressionValue(exp);
76
- if (value !== null) {
77
- return compilerDom.createSimpleExpression("" + value, true, exp.loc);
78
- }
79
- }
80
- return exp;
81
- }
82
- function getLiteralExpressionValue(exp) {
83
- if (exp.ast) {
84
- if (exp.ast.type === "StringLiteral") {
85
- return exp.ast.value;
86
- } else if (exp.ast.type === "TemplateLiteral" && exp.ast.expressions.length === 0) {
87
- return exp.ast.quasis[0].value.cooked;
88
- }
89
- }
90
- return exp.isStatic ? exp.content : null;
91
- }
92
-
93
- class TransformContext {
94
- constructor(ir, node, options = {}) {
95
- this.ir = ir;
96
- this.node = node;
97
- this.selfName = null;
98
- this.parent = null;
99
- this.index = 0;
100
- this.block = this.ir.block;
101
- this.template = "";
102
- this.childrenTemplate = [];
103
- this.dynamic = this.ir.block.dynamic;
104
- this.inVOnce = false;
105
- this.inVFor = 0;
106
- this.comment = [];
107
- this.component = this.ir.component;
108
- this.directive = this.ir.directive;
109
- this.slots = [];
110
- this.globalId = 0;
111
- this.increaseId = () => this.globalId++;
112
- this.options = shared.extend({}, defaultOptions, options);
113
- this.root = this;
114
- if (options.filename) this.selfName = compilerDom.getSelfName(options.filename);
115
- }
116
- enterBlock(ir, isVFor = false) {
117
- const { block, template, dynamic, childrenTemplate, slots } = this;
118
- this.block = ir;
119
- this.dynamic = ir.dynamic;
120
- this.template = "";
121
- this.childrenTemplate = [];
122
- this.slots = [];
123
- isVFor && this.inVFor++;
124
- return () => {
125
- this.registerTemplate();
126
- this.block = block;
127
- this.template = template;
128
- this.dynamic = dynamic;
129
- this.childrenTemplate = childrenTemplate;
130
- this.slots = slots;
131
- isVFor && this.inVFor--;
132
- };
133
- }
134
- reference() {
135
- if (this.dynamic.id !== void 0) return this.dynamic.id;
136
- this.dynamic.flags |= 1;
137
- return this.dynamic.id = this.increaseId();
138
- }
139
- pushTemplate(content) {
140
- const existing = this.ir.template.findIndex(
141
- (template) => template === content
142
- );
143
- if (existing !== -1) return existing;
144
- this.ir.template.push(content);
145
- return this.ir.template.length - 1;
146
- }
147
- registerTemplate() {
148
- if (!this.template) return -1;
149
- const id = this.pushTemplate(this.template);
150
- return this.dynamic.template = id;
151
- }
152
- registerEffect(expressions, operation, getIndex = () => this.block.effect.length) {
153
- const operations = [operation].flat();
154
- expressions = expressions.filter((exp) => !isConstantExpression(exp));
155
- if (this.inVOnce || expressions.length === 0 || expressions.every(
156
- (e) => isStaticExpression(e, this.root.options.bindingMetadata)
157
- )) {
158
- return this.registerOperation(...operations);
159
- }
160
- this.block.effect.splice(getIndex(), 0, {
161
- expressions,
162
- operations
163
- });
164
- }
165
- registerOperation(...node) {
166
- this.block.operation.push(...node);
167
- }
168
- create(node, index) {
169
- return Object.assign(Object.create(TransformContext.prototype), this, {
170
- node,
171
- parent: this,
172
- index,
173
- template: "",
174
- childrenTemplate: [],
175
- dynamic: newDynamic()
176
- });
177
- }
178
- }
179
- const defaultOptions = {
180
- filename: "",
181
- prefixIdentifiers: true,
182
- hoistStatic: false,
183
- hmr: false,
184
- cacheHandlers: false,
185
- nodeTransforms: [],
186
- directiveTransforms: {},
187
- transformHoist: null,
188
- isBuiltInComponent: shared.NOOP,
189
- isCustomElement: shared.NOOP,
190
- expressionPlugins: [],
191
- scopeId: null,
192
- slotted: true,
193
- ssr: false,
194
- inSSR: false,
195
- ssrCssVars: ``,
196
- templateMode: "string",
197
- bindingMetadata: shared.EMPTY_OBJ,
198
- inline: false,
199
- isTS: false,
200
- // fixed by uts
201
- disableEventDelegation: false,
202
- disableClassBinding: false,
203
- onError: compilerDom.defaultOnError,
204
- onWarn: compilerDom.defaultOnWarn
205
- };
206
- function transform(node, options = {}) {
207
- const ir = {
208
- type: 0,
209
- node,
210
- source: node.source,
211
- template: [],
212
- component: /* @__PURE__ */ new Set(),
213
- directive: /* @__PURE__ */ new Set(),
214
- block: newBlock(node),
215
- hasTemplateRef: false
216
- };
217
- const context = new TransformContext(ir, node, options);
218
- transformNode(context);
219
- return ir;
220
- }
221
- function transformNode(context) {
222
- let { node } = context;
223
- const { nodeTransforms } = context.options;
224
- const exitFns = [];
225
- for (const nodeTransform of nodeTransforms) {
226
- const onExit = nodeTransform(node, context);
227
- if (onExit) {
228
- if (shared.isArray(onExit)) {
229
- exitFns.push(...onExit);
230
- } else {
231
- exitFns.push(onExit);
232
- }
233
- }
234
- if (!context.node) {
235
- return;
236
- } else {
237
- node = context.node;
238
- }
239
- }
240
- context.node = node;
241
- let i = exitFns.length;
242
- while (i--) {
243
- exitFns[i]();
244
- }
245
- if (context.node.type === 0) {
246
- context.registerTemplate();
247
- }
248
- }
249
- function createStructuralDirectiveTransform(name, fn) {
250
- const matches = (n) => shared.isString(name) ? n === name : name.includes(n);
251
- return (node, context) => {
252
- if (node.type === 1) {
253
- const { props } = node;
254
- if (node.tagType === 3 && props.some(compilerDom.isVSlot)) {
255
- return;
256
- }
257
- const exitFns = [];
258
- for (const prop of props) {
259
- if (prop.type === 7 && matches(prop.name)) {
260
- const onExit = fn(
261
- node,
262
- prop,
263
- context
264
- );
265
- if (onExit) exitFns.push(onExit);
266
- }
267
- }
268
- return exitFns;
269
- }
270
- };
271
- }
272
-
273
- const NEWLINE = Symbol(`newline` );
274
- const LF = Symbol(`line feed` );
275
- const INDENT_START = Symbol(`indent start` );
276
- const INDENT_END = Symbol(`indent end` );
277
- function buildCodeFragment(...frag) {
278
- const push = frag.push.bind(frag);
279
- const unshift = frag.unshift.bind(frag);
280
- return [frag, push, unshift];
281
- }
282
- function genMulti([left, right, seg, placeholder], ...frags) {
283
- if (placeholder) {
284
- while (frags.length > 0 && !frags[frags.length - 1]) {
285
- frags.pop();
286
- }
287
- frags = frags.map((frag2) => frag2 || placeholder);
288
- } else {
289
- frags = frags.filter(Boolean);
290
- }
291
- const frag = [];
292
- push(left);
293
- for (let [i, fn] of frags.entries()) {
294
- push(fn);
295
- if (i < frags.length - 1) push(seg);
296
- }
297
- push(right);
298
- return frag;
299
- function push(fn) {
300
- if (!shared.isArray(fn)) fn = [fn];
301
- frag.push(...fn);
302
- }
303
- }
304
- const DELIMITERS_ARRAY = ["[", "]", ", "];
305
- const DELIMITERS_ARRAY_NEWLINE = [
306
- ["[", INDENT_START, NEWLINE],
307
- [INDENT_END, NEWLINE, "]"],
308
- [", ", NEWLINE]
309
- ];
310
- const DELIMITERS_OBJECT = ["{ ", " }", ", "];
311
- const DELIMITERS_OBJECT_NEWLINE = [
312
- ["{", INDENT_START, NEWLINE],
313
- [INDENT_END, NEWLINE, "}"],
314
- [", ", NEWLINE]
315
- ];
316
- function genCall(name, ...frags) {
317
- const hasPlaceholder = shared.isArray(name);
318
- const fnName = hasPlaceholder ? name[0] : name;
319
- const placeholder = hasPlaceholder ? name[1] : "null";
320
- return [fnName, ...genMulti(["(", ")", ", ", placeholder], ...frags)];
321
- }
322
- function codeFragmentToString(code, context) {
323
- const {
324
- options: { filename, sourceMap }
325
- } = context;
326
- let map;
327
- if (sourceMap) {
328
- map = new sourceMapJs.SourceMapGenerator();
329
- map.setSourceContent(filename, context.ir.source);
330
- map._sources.add(filename);
331
- }
332
- let codegen = "";
333
- const pos = { line: 1, column: 1, offset: 0 };
334
- let indentLevel = 0;
335
- for (let frag of code) {
336
- if (!frag) continue;
337
- if (frag === NEWLINE) {
338
- frag = [`
339
- ${` `.repeat(indentLevel)}`, 0];
340
- } else if (frag === INDENT_START) {
341
- indentLevel++;
342
- continue;
343
- } else if (frag === INDENT_END) {
344
- indentLevel--;
345
- continue;
346
- } else if (frag === LF) {
347
- pos.line++;
348
- pos.column = 0;
349
- pos.offset++;
350
- continue;
351
- }
352
- if (shared.isString(frag)) frag = [frag];
353
- let [code2, newlineIndex = -2, loc, name] = frag;
354
- codegen += code2;
355
- if (map) {
356
- if (loc) addMapping(loc.start, name);
357
- if (newlineIndex === -3) {
358
- compilerDom.advancePositionWithMutation(pos, code2);
359
- } else {
360
- pos.offset += code2.length;
361
- if (newlineIndex === -2) {
362
- pos.column += code2.length;
363
- } else {
364
- if (newlineIndex === -1) {
365
- newlineIndex = code2.length - 1;
366
- }
367
- pos.line++;
368
- pos.column = code2.length - newlineIndex;
369
- }
370
- }
371
- if (loc && loc !== compilerDom.locStub) {
372
- addMapping(loc.end);
373
- }
374
- }
375
- }
376
- return [codegen, map];
377
- function addMapping(loc, name = null) {
378
- const { _names, _mappings } = map;
379
- if (name !== null && !_names.has(name)) _names.add(name);
380
- _mappings.add({
381
- originalLine: loc.line,
382
- originalColumn: loc.column - 1,
383
- // source-map column is 0 based
384
- generatedLine: pos.line,
385
- generatedColumn: pos.column - 1,
386
- source: filename,
387
- name
388
- });
389
- }
390
- }
391
-
392
- const IRDynamicPropsKind = {
393
- "EXPRESSION": 0,
394
- "0": "EXPRESSION",
395
- "ATTRIBUTE": 1,
396
- "1": "ATTRIBUTE"
397
- };
398
- const IRSlotType = {
399
- "STATIC": 0,
400
- "0": "STATIC",
401
- "DYNAMIC": 1,
402
- "1": "DYNAMIC",
403
- "LOOP": 2,
404
- "2": "LOOP",
405
- "CONDITIONAL": 3,
406
- "3": "CONDITIONAL",
407
- "EXPRESSION": 4,
408
- "4": "EXPRESSION"
409
- };
410
-
411
- const IRNodeTypes = {
412
- "ROOT": 0,
413
- "0": "ROOT",
414
- "BLOCK": 1,
415
- "1": "BLOCK",
416
- "SET_PROP": 2,
417
- "2": "SET_PROP",
418
- "SET_DYNAMIC_PROPS": 3,
419
- "3": "SET_DYNAMIC_PROPS",
420
- "SET_TEXT": 4,
421
- "4": "SET_TEXT",
422
- "SET_EVENT": 5,
423
- "5": "SET_EVENT",
424
- "SET_DYNAMIC_EVENTS": 6,
425
- "6": "SET_DYNAMIC_EVENTS",
426
- "SET_HTML": 7,
427
- "7": "SET_HTML",
428
- "SET_TEMPLATE_REF": 8,
429
- "8": "SET_TEMPLATE_REF",
430
- "INSERT_NODE": 9,
431
- "9": "INSERT_NODE",
432
- "PREPEND_NODE": 10,
433
- "10": "PREPEND_NODE",
434
- "CREATE_COMPONENT_NODE": 11,
435
- "11": "CREATE_COMPONENT_NODE",
436
- "SLOT_OUTLET_NODE": 12,
437
- "12": "SLOT_OUTLET_NODE",
438
- "DIRECTIVE": 13,
439
- "13": "DIRECTIVE",
440
- "DECLARE_OLD_REF": 14,
441
- "14": "DECLARE_OLD_REF",
442
- "IF": 15,
443
- "15": "IF",
444
- "FOR": 16,
445
- "16": "FOR",
446
- "GET_TEXT_CHILD": 17,
447
- "17": "GET_TEXT_CHILD"
448
- };
449
- const DynamicFlag = {
450
- "NONE": 0,
451
- "0": "NONE",
452
- "REFERENCED": 1,
453
- "1": "REFERENCED",
454
- "NON_TEMPLATE": 2,
455
- "2": "NON_TEMPLATE",
456
- "INSERT": 4,
457
- "4": "INSERT"
458
- };
459
- function isBlockOperation(op) {
460
- const type = op.type;
461
- return type === 11 || type === 12 || type === 15 || type === 16;
462
- }
463
-
464
- function genInsertNode({ parent, elements, anchor }, { helper }) {
465
- let element = elements.map((el) => `n${el}`).join(", ");
466
- if (elements.length > 1) element = `[${element}]`;
467
- return [
468
- NEWLINE,
469
- ...genCall(
470
- helper("insert"),
471
- element,
472
- `n${parent}`,
473
- anchor === void 0 ? void 0 : `n${anchor}`
474
- )
475
- ];
476
- }
477
- function genPrependNode(oper, { helper }) {
478
- return [
479
- NEWLINE,
480
- ...genCall(
481
- helper("prepend"),
482
- `n${oper.parent}`,
483
- ...oper.elements.map((el) => `n${el}`)
484
- )
485
- ];
486
- }
487
-
488
- function genExpression(node, context, assignment) {
489
- const { content, ast, isStatic, loc } = node;
490
- if (isStatic) {
491
- return [[JSON.stringify(content), -2, loc]];
492
- }
493
- if (!node.content.trim() || // there was a parsing error
494
- ast === false || isConstantExpression(node)) {
495
- return [[content, -2, loc], assignment && ` = ${assignment}`];
496
- }
497
- if (ast === null) {
498
- return genIdentifier(content, context, loc, assignment);
499
- }
500
- const ids = [];
501
- const parentStackMap = /* @__PURE__ */ new Map();
502
- const parentStack = [];
503
- compilerDom.walkIdentifiers(
504
- ast,
505
- (id) => {
506
- ids.push(id);
507
- parentStackMap.set(id, parentStack.slice());
508
- },
509
- false,
510
- parentStack
511
- );
512
- let hasMemberExpression = false;
513
- if (ids.length) {
514
- const [frag, push] = buildCodeFragment();
515
- const isTSNode = ast && compilerDom.TS_NODE_TYPES.includes(ast.type);
516
- ids.sort((a, b) => a.start - b.start).forEach((id, i) => {
517
- const start = id.start - 1;
518
- const end = id.end - 1;
519
- const last = ids[i - 1];
520
- if (!(isTSNode && i === 0)) {
521
- const leadingText = content.slice(last ? last.end - 1 : 0, start);
522
- if (leadingText.length) push([leadingText, -3]);
523
- }
524
- const source = content.slice(start, end);
525
- const parentStack2 = parentStackMap.get(id);
526
- const parent = parentStack2[parentStack2.length - 1];
527
- hasMemberExpression || (hasMemberExpression = parent && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression"));
528
- push(
529
- ...genIdentifier(
530
- source,
531
- context,
532
- {
533
- start: compilerDom.advancePositionWithClone(node.loc.start, source, start),
534
- end: compilerDom.advancePositionWithClone(node.loc.start, source, end),
535
- source
536
- },
537
- hasMemberExpression ? void 0 : assignment,
538
- id,
539
- parent,
540
- parentStack2
541
- )
542
- );
543
- if (i === ids.length - 1 && end < content.length && !isTSNode) {
544
- push([content.slice(end), -3]);
545
- }
546
- });
547
- if (assignment && hasMemberExpression) {
548
- push(` = ${assignment}`);
549
- }
550
- return frag;
551
- } else {
552
- return [[content, -3, loc]];
553
- }
554
- }
555
- function genIdentifier(raw, context, loc, assignment, id, parent, parentStack) {
556
- const { options, helper, identifiers } = context;
557
- const { inline, bindingMetadata } = options;
558
- let name = raw;
559
- const idMap = identifiers[raw];
560
- if (idMap && idMap.length) {
561
- const replacement = idMap[0];
562
- if (shared.isString(replacement)) {
563
- if (parent && parent.type === "ObjectProperty" && parent.shorthand) {
564
- return [[`${name}: ${replacement}`, -2, loc]];
565
- } else {
566
- return [[replacement, -2, loc]];
567
- }
568
- } else {
569
- return genExpression(replacement, context, assignment);
570
- }
571
- }
572
- let prefix;
573
- if (compilerDom.isStaticProperty(parent) && parent.shorthand) {
574
- prefix = `${raw}: `;
575
- }
576
- const type = bindingMetadata && bindingMetadata[raw];
577
- if (inline) {
578
- switch (type) {
579
- case "setup-let":
580
- name = raw = assignment ? `_isRef(${raw}) ? (${raw}.value = ${assignment}) : (${raw} = ${assignment})` : unref();
581
- break;
582
- case "setup-ref":
583
- name = raw = withAssignment(`${raw}.value`);
584
- break;
585
- case "setup-maybe-ref":
586
- const isDestructureAssignment = parent && compilerDom.isInDestructureAssignment(parent, parentStack || []);
587
- const isAssignmentLVal = parent && parent.type === "AssignmentExpression" && parent.left === id;
588
- const isUpdateArg = parent && parent.type === "UpdateExpression" && parent.argument === id;
589
- raw = isAssignmentLVal || isUpdateArg || isDestructureAssignment ? name = `${raw}.value` : assignment ? `${helper("isRef")}(${raw}) ? (${raw}.value = ${assignment}) : null` : unref();
590
- break;
591
- case "props":
592
- raw = shared.genPropsAccessExp(raw);
593
- break;
594
- case "props-aliased":
595
- raw = shared.genPropsAccessExp(bindingMetadata.__propsAliases[raw]);
596
- break;
597
- default:
598
- raw = withAssignment(raw);
599
- }
600
- } else {
601
- if (canPrefix(raw)) {
602
- if (type === "props-aliased") {
603
- raw = `$props['${bindingMetadata.__propsAliases[raw]}']`;
604
- } else {
605
- raw = `${type === "props" ? "$props" : "_ctx"}.${raw}`;
606
- }
607
- }
608
- raw = withAssignment(raw);
609
- }
610
- return [prefix, [raw, -2, loc, name]];
611
- function withAssignment(s) {
612
- return assignment ? `${s} = ${assignment}` : s;
613
- }
614
- function unref() {
615
- return `${helper("unref")}(${raw})`;
616
- }
617
- }
618
- function canPrefix(name) {
619
- if (shared.isGloballyAllowed(name)) {
620
- return false;
621
- }
622
- if (
623
- // special case for webpack compilation
624
- name === "require" || name === "$props" || name === "$emit" || name === "$attrs" || name === "$slots"
625
- )
626
- return false;
627
- return true;
628
- }
629
- function processExpressions(context, expressions, shouldDeclare) {
630
- const {
631
- seenVariable,
632
- variableToExpMap,
633
- expToVariableMap,
634
- seenIdentifier,
635
- updatedVariable
636
- } = analyzeExpressions(expressions);
637
- const varDeclarations = processRepeatedVariables(
638
- context,
639
- seenVariable,
640
- variableToExpMap,
641
- expToVariableMap,
642
- seenIdentifier,
643
- updatedVariable
644
- );
645
- const expDeclarations = processRepeatedExpressions(
646
- context,
647
- expressions,
648
- varDeclarations,
649
- updatedVariable,
650
- expToVariableMap
651
- );
652
- return genDeclarations(
653
- [...varDeclarations, ...expDeclarations],
654
- context,
655
- shouldDeclare
656
- );
657
- }
658
- function analyzeExpressions(expressions) {
659
- const seenVariable = /* @__PURE__ */ Object.create(null);
660
- const variableToExpMap = /* @__PURE__ */ new Map();
661
- const expToVariableMap = /* @__PURE__ */ new Map();
662
- const seenIdentifier = /* @__PURE__ */ new Set();
663
- const updatedVariable = /* @__PURE__ */ new Set();
664
- const registerVariable = (name, exp, isIdentifier, loc, parentStack = []) => {
665
- if (isIdentifier) seenIdentifier.add(name);
666
- seenVariable[name] = (seenVariable[name] || 0) + 1;
667
- variableToExpMap.set(
668
- name,
669
- (variableToExpMap.get(name) || /* @__PURE__ */ new Set()).add(exp)
670
- );
671
- const variables = expToVariableMap.get(exp) || [];
672
- variables.push({ name, loc });
673
- expToVariableMap.set(exp, variables);
674
- if (parentStack.some(
675
- (p) => p.type === "UpdateExpression" || p.type === "AssignmentExpression"
676
- )) {
677
- updatedVariable.add(name);
678
- }
679
- };
680
- for (const exp of expressions) {
681
- if (!exp.ast) {
682
- exp.ast === null && registerVariable(exp.content, exp, true);
683
- continue;
684
- }
685
- compilerDom.walkIdentifiers(exp.ast, (currentNode, parent, parentStack) => {
686
- if (parent && isMemberExpression(parent)) {
687
- const memberExp = extractMemberExpression(parent, (id) => {
688
- registerVariable(id.name, exp, true, {
689
- start: id.start,
690
- end: id.end
691
- });
692
- });
693
- registerVariable(
694
- memberExp,
695
- exp,
696
- false,
697
- { start: parent.start, end: parent.end },
698
- parentStack
699
- );
700
- } else if (!parentStack.some(isMemberExpression)) {
701
- registerVariable(
702
- currentNode.name,
703
- exp,
704
- true,
705
- { start: currentNode.start, end: currentNode.end },
706
- parentStack
707
- );
708
- }
709
- });
710
- }
711
- return {
712
- seenVariable,
713
- seenIdentifier,
714
- variableToExpMap,
715
- expToVariableMap,
716
- updatedVariable
717
- };
718
- }
719
- function processRepeatedVariables(context, seenVariable, variableToExpMap, expToVariableMap, seenIdentifier, updatedVariable) {
720
- const declarations = [];
721
- const expToReplacementMap = /* @__PURE__ */ new Map();
722
- for (const [name, exps] of variableToExpMap) {
723
- if (updatedVariable.has(name)) continue;
724
- if (seenVariable[name] > 1 && exps.size > 0) {
725
- const isIdentifier = seenIdentifier.has(name);
726
- const varName = isIdentifier ? name : genVarName(name);
727
- exps.forEach((node) => {
728
- if (node.ast && varName !== name) {
729
- const replacements = expToReplacementMap.get(node) || [];
730
- replacements.push({
731
- name: varName,
732
- locs: expToVariableMap.get(node).reduce(
733
- (locs, v) => {
734
- if (v.name === name && v.loc) locs.push(v.loc);
735
- return locs;
736
- },
737
- []
738
- )
739
- });
740
- expToReplacementMap.set(node, replacements);
741
- }
742
- });
743
- if (!declarations.some((d) => d.name === varName) && (!isIdentifier || shouldDeclareVariable(name, expToVariableMap, exps))) {
744
- declarations.push({
745
- name: varName,
746
- isIdentifier,
747
- value: shared.extend(
748
- { ast: isIdentifier ? null : parseExp(context, name) },
749
- compilerDom.createSimpleExpression(name)
750
- ),
751
- rawName: name,
752
- exps,
753
- seenCount: seenVariable[name]
754
- });
755
- }
756
- }
757
- }
758
- for (const [exp, replacements] of expToReplacementMap) {
759
- replacements.flatMap(
760
- ({ name, locs }) => locs.map(({ start, end }) => ({ start, end, name }))
761
- ).sort((a, b) => b.end - a.end).forEach(({ start, end, name }) => {
762
- exp.content = exp.content.slice(0, start - 1) + name + exp.content.slice(end - 1);
763
- });
764
- exp.ast = parseExp(context, exp.content);
765
- }
766
- return declarations;
767
- }
768
- function shouldDeclareVariable(name, expToVariableMap, exps) {
769
- const vars = Array.from(
770
- exps,
771
- (exp) => expToVariableMap.get(exp).map((v) => v.name)
772
- );
773
- if (vars.every((v) => v.length === 1)) {
774
- return true;
775
- }
776
- if (vars.some((v) => v.filter((e) => e === name).length > 1)) {
777
- return true;
778
- }
779
- const first = vars[0];
780
- if (vars.some((v) => v.length !== first.length)) {
781
- if (vars.some(
782
- (v) => v.length > first.length && v.every((e) => first.includes(e))
783
- ) || vars.some((v) => first.length > v.length && first.every((e) => v.includes(e)))) {
784
- return false;
785
- }
786
- return true;
787
- }
788
- if (vars.some((v) => v.some((e) => first.includes(e)))) {
789
- return false;
790
- }
791
- return true;
792
- }
793
- function processRepeatedExpressions(context, expressions, varDeclarations, updatedVariable, expToVariableMap) {
794
- const declarations = [];
795
- const seenExp = expressions.reduce(
796
- (acc, exp) => {
797
- const variables = expToVariableMap.get(exp).map((v) => v.name);
798
- if (exp.ast && exp.ast.type !== "Identifier" && !(variables && variables.some((v) => updatedVariable.has(v)))) {
799
- acc[exp.content] = (acc[exp.content] || 0) + 1;
800
- }
801
- return acc;
802
- },
803
- /* @__PURE__ */ Object.create(null)
804
- );
805
- Object.entries(seenExp).forEach(([content, count]) => {
806
- if (count > 1) {
807
- const varName = genVarName(content);
808
- if (!declarations.some((d) => d.name === varName)) {
809
- const delVars = {};
810
- for (let i = varDeclarations.length - 1; i >= 0; i--) {
811
- const item = varDeclarations[i];
812
- if (!item.exps || !item.seenCount) continue;
813
- const shouldRemove = [...item.exps].every(
814
- (node) => node.content === content && item.seenCount === count
815
- );
816
- if (shouldRemove) {
817
- delVars[item.name] = item.rawName;
818
- varDeclarations.splice(i, 1);
819
- }
820
- }
821
- const value = shared.extend(
822
- {},
823
- expressions.find((exp) => exp.content === content)
824
- );
825
- Object.keys(delVars).forEach((name) => {
826
- value.content = value.content.replace(name, delVars[name]);
827
- if (value.ast) value.ast = parseExp(context, value.content);
828
- });
829
- declarations.push({
830
- name: varName,
831
- value
832
- });
833
- }
834
- expressions.forEach((exp) => {
835
- if (exp.content === content) {
836
- exp.content = varName;
837
- exp.ast = null;
838
- } else if (exp.content.includes(content)) {
839
- exp.content = exp.content.replace(
840
- new RegExp(escapeRegExp(content), "g"),
841
- varName
842
- );
843
- exp.ast = parseExp(context, exp.content);
844
- }
845
- });
846
- }
847
- });
848
- return declarations;
849
- }
850
- function genDeclarations(declarations, context, shouldDeclare) {
851
- const [frag, push] = buildCodeFragment();
852
- const ids = /* @__PURE__ */ Object.create(null);
853
- const varNames = /* @__PURE__ */ new Set();
854
- declarations.forEach(({ name, isIdentifier, value }) => {
855
- if (isIdentifier) {
856
- const varName = ids[name] = `_${name}`;
857
- varNames.add(varName);
858
- if (shouldDeclare) {
859
- push(`const `);
860
- }
861
- push(`${varName} = `, ...genExpression(value, context), NEWLINE);
862
- }
863
- });
864
- declarations.forEach(({ name, isIdentifier, value }) => {
865
- if (!isIdentifier) {
866
- const varName = ids[name] = `_${name}`;
867
- varNames.add(varName);
868
- if (shouldDeclare) {
869
- push(`const `);
870
- }
871
- push(
872
- `${varName} = `,
873
- ...context.withId(() => genExpression(value, context), ids),
874
- NEWLINE
875
- );
876
- }
877
- });
878
- return { ids, frag, varNames: [...varNames] };
879
- }
880
- function escapeRegExp(string) {
881
- return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
882
- }
883
- function parseExp(context, content) {
884
- const plugins = context.options.expressionPlugins;
885
- const options = {
886
- plugins: plugins ? [...plugins, "typescript"] : ["typescript"]
887
- };
888
- return parser.parseExpression(`(${content})`, options);
889
- }
890
- function genVarName(exp) {
891
- return `${exp.replace(/[^a-zA-Z0-9]/g, "_").replace(/_+/g, "_").replace(/_+$/, "")}`;
892
- }
893
- function extractMemberExpression(exp, onIdentifier) {
894
- if (!exp) return "";
895
- switch (exp.type) {
896
- case "Identifier":
897
- onIdentifier(exp);
898
- return exp.name;
899
- case "StringLiteral":
900
- return exp.extra ? exp.extra.raw : exp.value;
901
- case "NumericLiteral":
902
- return exp.value.toString();
903
- case "BinaryExpression":
904
- return `${extractMemberExpression(exp.left, onIdentifier)} ${exp.operator} ${extractMemberExpression(exp.right, onIdentifier)}`;
905
- case "CallExpression":
906
- return `${extractMemberExpression(exp.callee, onIdentifier)}(${exp.arguments.map((arg) => extractMemberExpression(arg, onIdentifier)).join(", ")})`;
907
- case "MemberExpression":
908
- // foo[bar.baz]
909
- case "OptionalMemberExpression":
910
- const object = extractMemberExpression(exp.object, onIdentifier);
911
- const prop = exp.computed ? `[${extractMemberExpression(exp.property, onIdentifier)}]` : `.${extractMemberExpression(exp.property, shared.NOOP)}`;
912
- return `${object}${prop}`;
913
- default:
914
- return "";
915
- }
916
- }
917
- const isMemberExpression = (node) => {
918
- return node.type === "MemberExpression" || node.type === "OptionalMemberExpression";
919
- };
920
-
921
- function genSetEvent(oper, context) {
922
- const { helper } = context;
923
- const { element, key, keyOverride, value, modifiers, delegate, effect } = oper;
924
- const name = genName();
925
- const handler = genEventHandler(context, value, modifiers);
926
- const eventOptions = genEventOptions();
927
- if (delegate) {
928
- context.delegates.add(key.content);
929
- if (!context.block.operation.some(isSameDelegateEvent)) {
930
- return [NEWLINE, `n${element}.$evt${key.content} = `, ...handler];
931
- }
932
- }
933
- return [
934
- NEWLINE,
935
- ...genCall(
936
- helper(delegate ? "delegate" : "on"),
937
- `n${element}`,
938
- name,
939
- handler,
940
- eventOptions
941
- )
942
- ];
943
- function genName() {
944
- const expr = genExpression(key, context);
945
- if (keyOverride) {
946
- const find = JSON.stringify(keyOverride[0]);
947
- const replacement = JSON.stringify(keyOverride[1]);
948
- const wrapped = ["(", ...expr, ")"];
949
- return [...wrapped, ` === ${find} ? ${replacement} : `, ...wrapped];
950
- } else {
951
- return genExpression(key, context);
952
- }
953
- }
954
- function genEventOptions() {
955
- let { options } = modifiers;
956
- if (!options.length && !effect) return;
957
- return genMulti(
958
- DELIMITERS_OBJECT_NEWLINE,
959
- effect && ["effect: true"],
960
- ...options.map((option) => [`${option}: true`])
961
- );
962
- }
963
- function isSameDelegateEvent(op) {
964
- if (op.type === 5 && op !== oper && op.delegate && op.element === oper.element && op.key.content === key.content) {
965
- return true;
966
- }
967
- }
968
- }
969
- function genSetDynamicEvents(oper, context) {
970
- const { helper } = context;
971
- return [
972
- NEWLINE,
973
- ...genCall(
974
- helper("setDynamicEvents"),
975
- `n${oper.element}`,
976
- genExpression(oper.event, context)
977
- )
978
- ];
979
- }
980
- function genEventHandler(context, value, modifiers = { nonKeys: [], keys: [] }, extraWrap = false) {
981
- let handlerExp = [`() => {}`];
982
- if (value && value.content.trim()) {
983
- if (compilerDom.isMemberExpression(value, context.options)) {
984
- handlerExp = genExpression(value, context);
985
- if (!isConstantBinding(value, context) && !extraWrap) {
986
- handlerExp = [`e => `, ...handlerExp, `(e)`];
987
- }
988
- } else if (compilerDom.isFnExpression(value, context.options)) {
989
- handlerExp = genExpression(value, context);
990
- } else {
991
- const referencesEvent = value.content.includes("$event");
992
- const hasMultipleStatements = value.content.includes(`;`);
993
- const expr = referencesEvent ? context.withId(() => genExpression(value, context), {
994
- $event: null
995
- }) : genExpression(value, context);
996
- handlerExp = [
997
- referencesEvent ? "$event => " : "() => ",
998
- hasMultipleStatements ? "{" : "(",
999
- ...expr,
1000
- hasMultipleStatements ? "}" : ")"
1001
- ];
1002
- }
1003
- }
1004
- const { keys, nonKeys } = modifiers;
1005
- if (nonKeys.length)
1006
- handlerExp = genWithModifiers(context, handlerExp, nonKeys);
1007
- if (keys.length) handlerExp = genWithKeys(context, handlerExp, keys);
1008
- if (extraWrap) handlerExp.unshift(`() => `);
1009
- return handlerExp;
1010
- }
1011
- function genWithModifiers(context, handler, nonKeys) {
1012
- return genCall(
1013
- context.helper("withModifiers"),
1014
- handler,
1015
- JSON.stringify(nonKeys)
1016
- );
1017
- }
1018
- function genWithKeys(context, handler, keys) {
1019
- return genCall(context.helper("withKeys"), handler, JSON.stringify(keys));
1020
- }
1021
- function isConstantBinding(value, context) {
1022
- if (value.ast === null) {
1023
- const bindingType = context.options.bindingMetadata[value.content];
1024
- if (bindingType === "setup-const") {
1025
- return true;
1026
- }
1027
- }
1028
- }
1029
-
1030
- function genFor(oper, context) {
1031
- const { helper } = context;
1032
- const {
1033
- source,
1034
- value,
1035
- key,
1036
- index,
1037
- render,
1038
- keyProp,
1039
- once,
1040
- id,
1041
- component,
1042
- onlyChild
1043
- } = oper;
1044
- let rawValue = null;
1045
- const rawKey = key && key.content;
1046
- const rawIndex = index && index.content;
1047
- const sourceExpr = ["() => (", ...genExpression(source, context), ")"];
1048
- const idToPathMap = parseValueDestructure();
1049
- const [depth, exitScope] = context.enterScope();
1050
- const idMap = {};
1051
- const itemVar = `_for_item${depth}`;
1052
- idMap[itemVar] = null;
1053
- idToPathMap.forEach((pathInfo, id2) => {
1054
- let path = `${itemVar}.value${pathInfo ? pathInfo.path : ""}`;
1055
- if (pathInfo) {
1056
- if (pathInfo.helper) {
1057
- idMap[pathInfo.helper] = null;
1058
- path = `${pathInfo.helper}(${path}, ${pathInfo.helperArgs})`;
1059
- }
1060
- if (pathInfo.dynamic) {
1061
- const node = idMap[id2] = compilerDom.createSimpleExpression(path);
1062
- const plugins = context.options.expressionPlugins;
1063
- node.ast = parser.parseExpression(`(${path})`, {
1064
- plugins: plugins ? [...plugins, "typescript"] : ["typescript"]
1065
- });
1066
- } else {
1067
- idMap[id2] = path;
1068
- }
1069
- } else {
1070
- idMap[id2] = path;
1071
- }
1072
- });
1073
- const args = [itemVar];
1074
- if (rawKey) {
1075
- const keyVar = `_for_key${depth}`;
1076
- args.push(`, ${keyVar}`);
1077
- idMap[rawKey] = `${keyVar}.value`;
1078
- idMap[keyVar] = null;
1079
- }
1080
- if (rawIndex) {
1081
- const indexVar = `_for_index${depth}`;
1082
- args.push(`, ${indexVar}`);
1083
- idMap[rawIndex] = `${indexVar}.value`;
1084
- idMap[indexVar] = null;
1085
- }
1086
- const { selectorPatterns, keyOnlyBindingPatterns } = matchPatterns(
1087
- render,
1088
- keyProp,
1089
- idMap
1090
- );
1091
- const selectorDeclarations = [];
1092
- const selectorSetup = [];
1093
- for (let i = 0; i < selectorPatterns.length; i++) {
1094
- const { selector } = selectorPatterns[i];
1095
- const selectorName = `_selector${id}_${i}`;
1096
- selectorDeclarations.push(`let ${selectorName}`, NEWLINE);
1097
- if (i === 0) {
1098
- selectorSetup.push(`({ createSelector }) => {`, INDENT_START);
1099
- }
1100
- selectorSetup.push(
1101
- NEWLINE,
1102
- `${selectorName} = `,
1103
- ...genCall(`createSelector`, [
1104
- `() => `,
1105
- ...genExpression(selector, context)
1106
- ])
1107
- );
1108
- if (i === selectorPatterns.length - 1) {
1109
- selectorSetup.push(INDENT_END, NEWLINE, "}");
1110
- }
1111
- }
1112
- const blockFn = context.withId(() => {
1113
- const frag = [];
1114
- frag.push("(", ...args, ") => {", INDENT_START);
1115
- if (selectorPatterns.length || keyOnlyBindingPatterns.length) {
1116
- frag.push(
1117
- ...genBlockContent(render, context, false, () => {
1118
- const patternFrag = [];
1119
- for (let i = 0; i < selectorPatterns.length; i++) {
1120
- const { effect } = selectorPatterns[i];
1121
- patternFrag.push(
1122
- NEWLINE,
1123
- `_selector${id}_${i}(() => {`,
1124
- INDENT_START
1125
- );
1126
- for (const oper2 of effect.operations) {
1127
- patternFrag.push(...genOperation(oper2, context));
1128
- }
1129
- patternFrag.push(INDENT_END, NEWLINE, `})`);
1130
- }
1131
- for (const { effect } of keyOnlyBindingPatterns) {
1132
- for (const oper2 of effect.operations) {
1133
- patternFrag.push(...genOperation(oper2, context));
1134
- }
1135
- }
1136
- return patternFrag;
1137
- })
1138
- );
1139
- } else {
1140
- frag.push(...genBlockContent(render, context));
1141
- }
1142
- frag.push(INDENT_END, NEWLINE, "}");
1143
- return frag;
1144
- }, idMap);
1145
- exitScope();
1146
- let flags = 0;
1147
- if (onlyChild) {
1148
- flags |= 1;
1149
- }
1150
- if (component) {
1151
- flags |= 2;
1152
- }
1153
- if (once) {
1154
- flags |= 4;
1155
- }
1156
- const forArgs = [
1157
- sourceExpr,
1158
- blockFn,
1159
- genCallback(keyProp),
1160
- flags ? String(flags) : void 0,
1161
- selectorSetup.length ? selectorSetup : void 0
1162
- // todo: hydrationNode
1163
- ];
1164
- if (context.options.templateMode === "factory") {
1165
- forArgs.unshift(`$doc`);
1166
- }
1167
- return [
1168
- NEWLINE,
1169
- ...selectorDeclarations,
1170
- `const n${id} = `,
1171
- // fixed by uts
1172
- ...genCall([helper("createFor"), "null"], ...forArgs)
1173
- ];
1174
- function parseValueDestructure() {
1175
- const map = /* @__PURE__ */ new Map();
1176
- if (value) {
1177
- rawValue = value && value.content;
1178
- if (value.ast) {
1179
- compilerDom.walkIdentifiers(
1180
- value.ast,
1181
- (id2, _, parentStack, ___, isLocal) => {
1182
- if (isLocal) {
1183
- let path = "";
1184
- let isDynamic = false;
1185
- let helper2;
1186
- let helperArgs;
1187
- for (let i = 0; i < parentStack.length; i++) {
1188
- const parent = parentStack[i];
1189
- const child = parentStack[i + 1] || id2;
1190
- if (parent.type === "ObjectProperty" && parent.value === child) {
1191
- if (parent.key.type === "StringLiteral") {
1192
- path += `[${JSON.stringify(parent.key.value)}]`;
1193
- } else if (parent.computed) {
1194
- isDynamic = true;
1195
- path += `[${value.content.slice(
1196
- parent.key.start - 1,
1197
- parent.key.end - 1
1198
- )}]`;
1199
- } else {
1200
- path += `.${parent.key.name}`;
1201
- }
1202
- } else if (parent.type === "ArrayPattern") {
1203
- const index2 = parent.elements.indexOf(child);
1204
- if (child.type === "RestElement") {
1205
- path += `.slice(${index2})`;
1206
- } else {
1207
- path += `[${index2}]`;
1208
- }
1209
- } else if (parent.type === "ObjectPattern" && child.type === "RestElement") {
1210
- helper2 = context.helper("getRestElement");
1211
- helperArgs = "[" + parent.properties.filter((p) => p.type === "ObjectProperty").map((p) => {
1212
- if (p.key.type === "StringLiteral") {
1213
- return JSON.stringify(p.key.value);
1214
- } else if (p.computed) {
1215
- isDynamic = true;
1216
- return value.content.slice(
1217
- p.key.start - 1,
1218
- p.key.end - 1
1219
- );
1220
- } else {
1221
- return JSON.stringify(p.key.name);
1222
- }
1223
- }).join(", ") + "]";
1224
- }
1225
- if (child.type === "AssignmentPattern" && (parent.type === "ObjectProperty" || parent.type === "ArrayPattern")) {
1226
- isDynamic = true;
1227
- helper2 = context.helper("getDefaultValue");
1228
- helperArgs = value.content.slice(
1229
- child.right.start - 1,
1230
- child.right.end - 1
1231
- );
1232
- }
1233
- }
1234
- map.set(id2.name, { path, dynamic: isDynamic, helper: helper2, helperArgs });
1235
- }
1236
- },
1237
- true
1238
- );
1239
- } else {
1240
- map.set(rawValue, null);
1241
- }
1242
- }
1243
- return map;
1244
- }
1245
- function genCallback(expr) {
1246
- if (!expr) return false;
1247
- const res = context.withId(
1248
- () => genExpression(expr, context),
1249
- genSimpleIdMap()
1250
- );
1251
- return [
1252
- ...genMulti(
1253
- ["(", ")", ", "],
1254
- rawValue ? rawValue : rawKey || rawIndex ? "_" : void 0,
1255
- rawKey ? rawKey : rawIndex ? "__" : void 0,
1256
- rawIndex
1257
- ),
1258
- " => (",
1259
- ...res,
1260
- ")"
1261
- ];
1262
- }
1263
- function genSimpleIdMap() {
1264
- const idMap2 = {};
1265
- if (rawKey) idMap2[rawKey] = null;
1266
- if (rawIndex) idMap2[rawIndex] = null;
1267
- idToPathMap.forEach((_, id2) => idMap2[id2] = null);
1268
- return idMap2;
1269
- }
1270
- }
1271
- function matchPatterns(render, keyProp, idMap) {
1272
- const selectorPatterns = [];
1273
- const keyOnlyBindingPatterns = [];
1274
- render.effect = render.effect.filter((effect) => {
1275
- if (keyProp !== void 0) {
1276
- const selector = matchSelectorPattern(effect, keyProp.ast, idMap);
1277
- if (selector) {
1278
- selectorPatterns.push(selector);
1279
- return false;
1280
- }
1281
- const keyOnly = matchKeyOnlyBindingPattern(effect, keyProp.ast);
1282
- if (keyOnly) {
1283
- keyOnlyBindingPatterns.push(keyOnly);
1284
- return false;
1285
- }
1286
- }
1287
- return true;
1288
- });
1289
- return {
1290
- keyOnlyBindingPatterns,
1291
- selectorPatterns
1292
- };
1293
- }
1294
- function matchKeyOnlyBindingPattern(effect, keyAst) {
1295
- if (effect.expressions.length === 1) {
1296
- const ast = effect.expressions[0].ast;
1297
- if (typeof ast === "object" && ast !== null) {
1298
- if (isKeyOnlyBinding(ast, keyAst)) {
1299
- return { effect };
1300
- }
1301
- }
1302
- }
1303
- }
1304
- function matchSelectorPattern(effect, keyAst, idMap) {
1305
- if (effect.expressions.length === 1) {
1306
- const ast = effect.expressions[0].ast;
1307
- if (typeof ast === "object" && ast) {
1308
- const matcheds = [];
1309
- estreeWalker.walk(ast, {
1310
- enter(node) {
1311
- if (typeof node === "object" && node && node.type === "BinaryExpression" && node.operator === "===" && node.left.type !== "PrivateName") {
1312
- const { left, right } = node;
1313
- for (const [a, b] of [
1314
- [left, right],
1315
- [right, left]
1316
- ]) {
1317
- const aIsKey = isKeyOnlyBinding(a, keyAst);
1318
- const bIsKey = isKeyOnlyBinding(b, keyAst);
1319
- const bVars = analyzeVariableScopes(b, idMap);
1320
- if (aIsKey && !bIsKey && !bVars.locals.length) {
1321
- matcheds.push([a, b]);
1322
- }
1323
- }
1324
- }
1325
- }
1326
- });
1327
- if (matcheds.length === 1) {
1328
- const [key, selector] = matcheds[0];
1329
- const content2 = effect.expressions[0].content;
1330
- let hasExtraId = false;
1331
- const parentStackMap = /* @__PURE__ */ new Map();
1332
- const parentStack = [];
1333
- compilerDom.walkIdentifiers(
1334
- ast,
1335
- (id) => {
1336
- if (id.start !== key.start && id.start !== selector.start) {
1337
- hasExtraId = true;
1338
- }
1339
- parentStackMap.set(id, parentStack.slice());
1340
- },
1341
- false,
1342
- parentStack
1343
- );
1344
- if (!hasExtraId) {
1345
- const name = content2.slice(selector.start - 1, selector.end - 1);
1346
- return {
1347
- effect,
1348
- // @ts-expect-error
1349
- selector: {
1350
- content: name,
1351
- ast: shared.extend({}, selector, {
1352
- start: 1,
1353
- end: name.length + 1
1354
- }),
1355
- loc: selector.loc,
1356
- isStatic: false
1357
- }
1358
- };
1359
- }
1360
- }
1361
- }
1362
- const content = effect.expressions[0].content;
1363
- if (typeof ast === "object" && ast && ast.type === "ConditionalExpression" && ast.test.type === "BinaryExpression" && ast.test.operator === "===" && ast.test.left.type !== "PrivateName" && compilerDom.isStaticNode(ast.consequent) && compilerDom.isStaticNode(ast.alternate)) {
1364
- const left = ast.test.left;
1365
- const right = ast.test.right;
1366
- for (const [a, b] of [
1367
- [left, right],
1368
- [right, left]
1369
- ]) {
1370
- const aIsKey = isKeyOnlyBinding(a, keyAst);
1371
- const bIsKey = isKeyOnlyBinding(b, keyAst);
1372
- const bVars = analyzeVariableScopes(b, idMap);
1373
- if (aIsKey && !bIsKey && !bVars.locals.length) {
1374
- return {
1375
- effect,
1376
- // @ts-expect-error
1377
- selector: {
1378
- content: content.slice(b.start - 1, b.end - 1),
1379
- ast: b,
1380
- loc: b.loc,
1381
- isStatic: false
1382
- }
1383
- };
1384
- }
1385
- }
1386
- }
1387
- }
1388
- }
1389
- function analyzeVariableScopes(ast, idMap) {
1390
- let globals = [];
1391
- let locals = [];
1392
- const ids = [];
1393
- const parentStackMap = /* @__PURE__ */ new Map();
1394
- const parentStack = [];
1395
- compilerDom.walkIdentifiers(
1396
- ast,
1397
- (id) => {
1398
- ids.push(id);
1399
- parentStackMap.set(id, parentStack.slice());
1400
- },
1401
- false,
1402
- parentStack
1403
- );
1404
- for (const id of ids) {
1405
- if (shared.isGloballyAllowed(id.name)) {
1406
- continue;
1407
- }
1408
- if (idMap[id.name]) {
1409
- locals.push(id.name);
1410
- } else {
1411
- globals.push(id.name);
1412
- }
1413
- }
1414
- return { globals, locals };
1415
- }
1416
- function isKeyOnlyBinding(expr, keyAst) {
1417
- let only = true;
1418
- estreeWalker.walk(expr, {
1419
- enter(node) {
1420
- if (types.isNodesEquivalent(node, keyAst)) {
1421
- this.skip();
1422
- return;
1423
- }
1424
- if (node.type === "Identifier") {
1425
- only = false;
1426
- }
1427
- }
1428
- });
1429
- return only;
1430
- }
1431
-
1432
- function genSetHtml(oper, context) {
1433
- const { helper } = context;
1434
- const { value, element } = oper;
1435
- return [
1436
- NEWLINE,
1437
- ...genCall(helper("setHtml"), `n${element}`, genExpression(value, context))
1438
- ];
1439
- }
1440
-
1441
- function genIf(oper, context, isNested = false) {
1442
- const { helper } = context;
1443
- const { condition, positive, negative, once } = oper;
1444
- const [frag, push] = buildCodeFragment();
1445
- const conditionExpr = [
1446
- "() => (",
1447
- ...genExpression(condition, context),
1448
- ")"
1449
- ];
1450
- let positiveArg = genBlock(positive, context);
1451
- let negativeArg = false;
1452
- if (negative) {
1453
- if (negative.type === 1) {
1454
- negativeArg = genBlock(negative, context);
1455
- } else {
1456
- negativeArg = ["() => ", ...genIf(negative, context, true)];
1457
- }
1458
- }
1459
- if (!isNested) push(NEWLINE, `const n${oper.id} = `);
1460
- const ifArgs = [
1461
- conditionExpr,
1462
- positiveArg,
1463
- negativeArg,
1464
- once && "true"
1465
- ];
1466
- if (context.options.templateMode === "factory") {
1467
- ifArgs.unshift(`$doc`);
1468
- }
1469
- push(...genCall(helper("createIf"), ...ifArgs));
1470
- return frag;
1471
- }
1472
-
1473
- const helpers = {
1474
- setText: { name: "setText" },
1475
- setHtml: { name: "setHtml" },
1476
- setClass: { name: "setClass" },
1477
- setStyle: { name: "setStyle" },
1478
- setValue: { name: "setValue" },
1479
- setAttr: { name: "setAttr", needKey: true },
1480
- setProp: { name: "setProp", needKey: true },
1481
- setDOMProp: { name: "setDOMProp", needKey: true }};
1482
- function genSetProp(oper, context) {
1483
- const { helper } = context;
1484
- const {
1485
- prop: { key, values, modifier },
1486
- tag
1487
- } = oper;
1488
- const resolvedHelper = getRuntimeHelper(tag, key.content, modifier);
1489
- const propValue = genPropValue(values, context);
1490
- return [
1491
- NEWLINE,
1492
- ...genCall(
1493
- [helper(resolvedHelper.name), null],
1494
- `n${oper.element}`,
1495
- resolvedHelper.needKey ? genExpression(key, context) : false,
1496
- propValue
1497
- )
1498
- ];
1499
- }
1500
- function genDynamicProps$1(oper, context) {
1501
- const { helper } = context;
1502
- const values = oper.props.map(
1503
- (props) => Array.isArray(props) ? genLiteralObjectProps(props, context) : props.kind === 1 ? genLiteralObjectProps([props], context) : genExpression(props.value, context)
1504
- );
1505
- return [
1506
- NEWLINE,
1507
- ...genCall(
1508
- helper("setDynamicProps"),
1509
- `n${oper.element}`,
1510
- genMulti(DELIMITERS_ARRAY, ...values),
1511
- oper.root && "true"
1512
- )
1513
- ];
1514
- }
1515
- function genLiteralObjectProps(props, context) {
1516
- return genMulti(
1517
- DELIMITERS_OBJECT,
1518
- ...props.map((prop) => [
1519
- ...genPropKey(prop, context),
1520
- `: `,
1521
- ...genPropValue(prop.values, context)
1522
- ])
1523
- );
1524
- }
1525
- function genPropKey({ key: node, modifier, runtimeCamelize, handler, handlerModifiers }, context) {
1526
- const { helper } = context;
1527
- const handlerModifierPostfix = handlerModifiers ? handlerModifiers.map(shared.capitalize).join("") : "";
1528
- if (node.isStatic) {
1529
- const keyName = (handler ? shared.toHandlerKey(node.content) : node.content) + handlerModifierPostfix;
1530
- return [
1531
- [
1532
- compilerDom.isSimpleIdentifier(keyName) ? keyName : JSON.stringify(keyName),
1533
- -2,
1534
- node.loc
1535
- ]
1536
- ];
1537
- }
1538
- let key = genExpression(node, context);
1539
- if (runtimeCamelize) {
1540
- key = genCall(helper("camelize"), key);
1541
- }
1542
- if (handler) {
1543
- key = genCall(helper("toHandlerKey"), key);
1544
- }
1545
- return [
1546
- "[",
1547
- modifier && `${JSON.stringify(modifier)} + `,
1548
- ...key,
1549
- handlerModifierPostfix ? ` + ${JSON.stringify(handlerModifierPostfix)}` : void 0,
1550
- "]"
1551
- ];
1552
- }
1553
- function genPropValue(values, context) {
1554
- if (values.length === 1) {
1555
- return genExpression(values[0], context);
1556
- }
1557
- return genMulti(
1558
- DELIMITERS_ARRAY,
1559
- ...values.map((expr) => genExpression(expr, context))
1560
- );
1561
- }
1562
- function getRuntimeHelper(tag, key, modifier) {
1563
- const tagName = tag.toUpperCase();
1564
- if (modifier) {
1565
- if (modifier === ".") {
1566
- return getSpecialHelper(key, tagName) || helpers.setDOMProp;
1567
- } else {
1568
- return helpers.setAttr;
1569
- }
1570
- }
1571
- const helper = getSpecialHelper(key, tagName);
1572
- if (helper) {
1573
- return helper;
1574
- }
1575
- if (/aria[A-Z]/.test(key)) {
1576
- return helpers.setDOMProp;
1577
- }
1578
- if (shared.isSVGTag(tag)) {
1579
- return helpers.setAttr;
1580
- }
1581
- if (shared.shouldSetAsAttr(tagName, key) || key.includes("-")) {
1582
- return helpers.setAttr;
1583
- }
1584
- return helpers.setProp;
1585
- }
1586
- function getSpecialHelper(keyName, tagName) {
1587
- if (keyName === "value" && shared.canSetValueDirectly(tagName)) {
1588
- return helpers.setValue;
1589
- } else if (keyName === "class") {
1590
- return helpers.setClass;
1591
- } else if (keyName === "style") {
1592
- return helpers.setStyle;
1593
- } else if (keyName === "innerHTML") {
1594
- return helpers.setHtml;
1595
- } else if (keyName === "textContent") {
1596
- return helpers.setText;
1597
- }
1598
- }
1599
-
1600
- const setTemplateRefIdent = `_setTemplateRef`;
1601
- function genSetTemplateRef(oper, context) {
1602
- return [
1603
- NEWLINE,
1604
- oper.effect && `r${oper.element} = `,
1605
- ...genCall(
1606
- setTemplateRefIdent,
1607
- // will be generated in root scope
1608
- `n${oper.element}`,
1609
- genRefValue(oper.value, context),
1610
- oper.effect ? `r${oper.element}` : oper.refFor ? "void 0" : void 0,
1611
- oper.refFor && "true"
1612
- )
1613
- ];
1614
- }
1615
- function genDeclareOldRef(oper) {
1616
- return [NEWLINE, `let r${oper.id}`];
1617
- }
1618
- function genRefValue(value, context) {
1619
- if (value && context.options.inline) {
1620
- const binding = context.options.bindingMetadata[value.content];
1621
- if (binding === "setup-let" || binding === "setup-ref" || binding === "setup-maybe-ref") {
1622
- return [value.content];
1623
- }
1624
- }
1625
- return genExpression(value, context);
1626
- }
1627
-
1628
- const COMMENT_START = "<!--";
1629
- const COMMENT_END = "-->";
1630
- const DOCTYPE_START = "<!";
1631
- const WHITESPACE_REGEX = /\s/;
1632
- const ATTRIBUTE_NAME_REGEX = /[\s=]/;
1633
- const SELF_CLOSING_REGEX = /\s*\/$/;
1634
- class HtmlParser {
1635
- constructor(html) {
1636
- this.html = html;
1637
- this.length = html.length;
1638
- this.index = 0;
1639
- }
1640
- /**
1641
- * Parse HTML string into an array of HTML nodes
1642
- */
1643
- parse() {
1644
- const nodes = [];
1645
- this.index = 0;
1646
- while (this.index < this.length) {
1647
- if (this.html[this.index] === "<") {
1648
- const result = this.parseTag();
1649
- if (result) {
1650
- nodes.push(result.node);
1651
- this.index = result.endIndex;
1652
- } else {
1653
- this.index++;
1654
- }
1655
- } else {
1656
- const textNode = this.parseText();
1657
- if (textNode) {
1658
- nodes.push(textNode);
1659
- }
1660
- }
1661
- }
1662
- return nodes;
1663
- }
1664
- // =============================================================================
1665
- // Private Methods - Main Parsing Logic
1666
- // =============================================================================
1667
- /**
1668
- * Parse text content until next tag
1669
- */
1670
- parseText() {
1671
- const start = this.index;
1672
- const nextTag = this.html.indexOf("<", start);
1673
- const end = nextTag === -1 ? this.length : nextTag;
1674
- if (start === end) return null;
1675
- const content = this.html.substring(start, end);
1676
- this.index = end;
1677
- return { type: "text", content };
1678
- }
1679
- /**
1680
- * Parse a tag (element, comment, or doctype)
1681
- */
1682
- parseTag() {
1683
- if (this.html.startsWith(COMMENT_START, this.index)) {
1684
- return this.parseComment();
1685
- }
1686
- if (this.html.startsWith(DOCTYPE_START, this.index)) {
1687
- return this.parseDoctype();
1688
- }
1689
- return this.parseElement();
1690
- }
1691
- /**
1692
- * Parse HTML comment
1693
- */
1694
- parseComment() {
1695
- const start = this.index + COMMENT_START.length;
1696
- const end = this.html.indexOf(COMMENT_END, start);
1697
- if (end === -1) return null;
1698
- const content = this.html.substring(start, end);
1699
- return {
1700
- node: { type: "comment", content },
1701
- endIndex: end + COMMENT_END.length
1702
- };
1703
- }
1704
- /**
1705
- * Parse DOCTYPE and other declarations
1706
- */
1707
- parseDoctype() {
1708
- const end = this.html.indexOf(">", this.index + DOCTYPE_START.length);
1709
- if (end === -1) return null;
1710
- return {
1711
- node: { type: "comment", content: "" },
1712
- endIndex: end + 1
1713
- };
1714
- }
1715
- /**
1716
- * Parse HTML element
1717
- */
1718
- parseElement() {
1719
- const tagEnd = this.html.indexOf(">", this.index);
1720
- if (tagEnd === -1) return null;
1721
- const tagContent = this.html.substring(this.index + 1, tagEnd);
1722
- const { tag, attrs, selfClosing } = this.parseTagContent(tagContent);
1723
- if (selfClosing) {
1724
- return {
1725
- node: { type: "element", tag, attrs, children: [] },
1726
- endIndex: tagEnd + 1
1727
- };
1728
- }
1729
- const endTagIndex = this.findMatchingEndTag(tag, tagEnd + 1);
1730
- if (endTagIndex === -1) {
1731
- return {
1732
- node: { type: "element", tag, attrs, children: [] },
1733
- endIndex: tagEnd + 1
1734
- };
1735
- }
1736
- const innerHtml = this.html.substring(tagEnd + 1, endTagIndex);
1737
- const children = innerHtml ? new HtmlParser(innerHtml).parse() : [];
1738
- return {
1739
- node: { type: "element", tag, attrs, children },
1740
- endIndex: endTagIndex + `</${tag}>`.length
1741
- };
1742
- }
1743
- // =============================================================================
1744
- // Private Methods - Tag Content Parsing
1745
- // =============================================================================
1746
- /**
1747
- * Parse tag content to extract tag name, attributes, and self-closing flag
1748
- */
1749
- parseTagContent(content) {
1750
- const selfClosing = SELF_CLOSING_REGEX.test(content);
1751
- const cleanContent = content.replace(SELF_CLOSING_REGEX, "").trim();
1752
- if (!cleanContent) {
1753
- return { tag: "", attrs: {}, selfClosing };
1754
- }
1755
- const spaceIndex = cleanContent.search(WHITESPACE_REGEX);
1756
- const tag = spaceIndex === -1 ? cleanContent : cleanContent.substring(0, spaceIndex);
1757
- if (spaceIndex === -1) {
1758
- return { tag, attrs: {}, selfClosing };
1759
- }
1760
- const attrContent = cleanContent.substring(spaceIndex + 1);
1761
- const attrs = this.parseAttributes(attrContent);
1762
- return { tag, attrs, selfClosing };
1763
- }
1764
- /**
1765
- * Parse attributes from attribute content string
1766
- */
1767
- parseAttributes(content) {
1768
- const attrs = {};
1769
- let i = 0;
1770
- const length = content.length;
1771
- while (i < length) {
1772
- i = this.skipWhitespace(content, i);
1773
- if (i >= length) break;
1774
- const nameStart = i;
1775
- while (i < length && !ATTRIBUTE_NAME_REGEX.test(content[i])) {
1776
- i++;
1777
- }
1778
- if (i === nameStart) break;
1779
- const name = content.substring(nameStart, i);
1780
- i = this.skipWhitespace(content, i);
1781
- if (i >= length || content[i] !== "=") {
1782
- if (!this.isSpecialAttribute(name)) {
1783
- attrs[name] = name;
1784
- }
1785
- continue;
1786
- }
1787
- i++;
1788
- i = this.skipWhitespace(content, i);
1789
- if (i >= length) {
1790
- if (!this.isSpecialAttribute(name)) {
1791
- attrs[name] = "";
1792
- }
1793
- continue;
1794
- }
1795
- const value = this.parseAttributeValue(content, i);
1796
- if (!this.isSpecialAttribute(name) || value.value.trim() !== "") {
1797
- attrs[name] = value.value;
1798
- }
1799
- i = value.endIndex;
1800
- }
1801
- return attrs;
1802
- }
1803
- /**
1804
- * Parse attribute value (quoted or unquoted)
1805
- */
1806
- parseAttributeValue(content, startIndex) {
1807
- const quote = content[startIndex];
1808
- if (quote === '"' || quote === "'") {
1809
- const valueStart = startIndex + 1;
1810
- let i = valueStart;
1811
- while (i < content.length && content[i] !== quote) {
1812
- i++;
1813
- }
1814
- const value = content.substring(valueStart, i);
1815
- return {
1816
- value,
1817
- endIndex: i < content.length ? i + 1 : i
1818
- // Skip closing quote if found
1819
- };
1820
- } else {
1821
- const valueStart = startIndex;
1822
- let i = valueStart;
1823
- while (i < content.length && !WHITESPACE_REGEX.test(content[i])) {
1824
- i++;
1825
- }
1826
- const value = content.substring(valueStart, i);
1827
- return { value, endIndex: i };
1828
- }
1829
- }
1830
- // =============================================================================
1831
- // Private Methods - Utilities
1832
- // =============================================================================
1833
- /**
1834
- * Check if attribute is a special attribute (id, class, style)
1835
- */
1836
- isSpecialAttribute(name) {
1837
- return name === "id" || name === "class" || name === "style";
1838
- }
1839
- /**
1840
- * Skip whitespace characters starting from index
1841
- */
1842
- skipWhitespace(content, index) {
1843
- while (index < content.length && WHITESPACE_REGEX.test(content[index])) {
1844
- index++;
1845
- }
1846
- return index;
1847
- }
1848
- /**
1849
- * Find matching end tag for given tag name
1850
- */
1851
- findMatchingEndTag(tag, startIndex) {
1852
- const startTag = `<${tag}`;
1853
- const endTag = `</${tag}>`;
1854
- let depth = 1;
1855
- let searchIndex = startIndex;
1856
- while (depth > 0 && searchIndex < this.length) {
1857
- const nextStart = this.html.indexOf(startTag, searchIndex);
1858
- const nextEnd = this.html.indexOf(endTag, searchIndex);
1859
- if (nextEnd === -1) break;
1860
- if (nextStart !== -1 && nextStart < nextEnd) {
1861
- const nextTagEnd = this.html.indexOf(">", nextStart);
1862
- if (nextTagEnd !== -1 && nextTagEnd < nextEnd) {
1863
- const nextTagContent = this.html.substring(nextStart + 1, nextTagEnd);
1864
- if (!SELF_CLOSING_REGEX.test(nextTagContent)) {
1865
- depth++;
1866
- }
1867
- }
1868
- searchIndex = nextTagEnd + 1;
1869
- } else {
1870
- depth--;
1871
- if (depth === 0) {
1872
- return nextEnd;
1873
- }
1874
- searchIndex = nextEnd + endTag.length;
1875
- }
1876
- }
1877
- return -1;
1878
- }
1879
- }
1880
-
1881
- const NODE_TYPE_TEXT = "text";
1882
- const NODE_TYPE_COMMENT = "comment";
1883
- const NODE_TYPE_ELEMENT = "element";
1884
- const VALUE_ATTR = "value";
1885
- const EMPTY_STRING = "";
1886
- const UNKNOWN_COMMENT = "unknown";
1887
- class DomCodeGenerator {
1888
- constructor(options) {
1889
- this.variableCounter = 0;
1890
- this.styleCounter = 0;
1891
- this.disableClassBinding = false;
1892
- this.parseStaticStyle = options.parseStaticStyle;
1893
- this.disableClassBinding = options.disableClassBinding;
1894
- }
1895
- genNodeStatements(node) {
1896
- this.variableCounter = 0;
1897
- this.styleCounter = 0;
1898
- return this.genNodeCode(node);
1899
- }
1900
- genNodeCode(node) {
1901
- switch (node.type) {
1902
- case NODE_TYPE_TEXT:
1903
- return this.createTextNode(node.content || EMPTY_STRING);
1904
- case NODE_TYPE_COMMENT:
1905
- return this.createCommentNode(node.content || EMPTY_STRING);
1906
- case NODE_TYPE_ELEMENT:
1907
- return this.genElementCode(node);
1908
- default:
1909
- return this.createCommentNode(UNKNOWN_COMMENT);
1910
- }
1911
- }
1912
- createTextNode(content) {
1913
- const varName = this.getNextVariableName();
1914
- const statements = [
1915
- // 处理换行符\n
1916
- `const ${varName} = doc.createTextNode(${JSON.stringify(
1917
- content.replace(/[\\]+n/g, function(match) {
1918
- return JSON.parse(`"${match}"`);
1919
- })
1920
- )})`
1921
- ];
1922
- return { variableName: varName, statements };
1923
- }
1924
- createCommentNode(content) {
1925
- const varName = this.getNextVariableName();
1926
- const statements = [
1927
- `const ${varName} = doc.createComment(${JSON.stringify(content)})`
1928
- ];
1929
- return { variableName: varName, statements };
1930
- }
1931
- genElementCode(node) {
1932
- const { tag, attrs, children } = node;
1933
- if (tag === NODE_TYPE_TEXT) {
1934
- return this.genTextElementCode({ tag, attrs, children });
1935
- }
1936
- return this.genRegularElementCode({ tag, attrs, children });
1937
- }
1938
- genTextElementCode(params) {
1939
- const { tag, attrs, children } = params;
1940
- const hasComplexChildren = children && children.some((child) => child.type === NODE_TYPE_ELEMENT);
1941
- if (hasComplexChildren) {
1942
- return this.buildElementStatements(tag, attrs, children);
1943
- } else {
1944
- const textContent = this.extractTextContent(children);
1945
- const finalAttrs = this.mergeTextAttributes(attrs, textContent);
1946
- return this.buildElementStatements(tag, finalAttrs, void 0);
1947
- }
1948
- }
1949
- genRegularElementCode(params) {
1950
- const { tag, attrs, children } = params;
1951
- return this.buildElementStatements(tag, attrs, children);
1952
- }
1953
- buildElementStatements(tag, attrs, children) {
1954
- const varName = this.getNextVariableName();
1955
- const statements = [];
1956
- statements.push(`const ${varName} = doc.createElement('${tag}')`);
1957
- if (attrs && !isEmptyAttrs(attrs, this.disableClassBinding)) {
1958
- let shouldCacheStyle = false;
1959
- if (this.disableClassBinding && "ext:style" in attrs) {
1960
- shouldCacheStyle = true;
1961
- delete attrs["ext:style"];
1962
- }
1963
- for (const [name, value] of Object.entries(attrs)) {
1964
- if (name === "style") {
1965
- const mapStyleStr = this.parseStaticStyle(value);
1966
- if (mapStyleStr) {
1967
- if (shouldCacheStyle) {
1968
- const styleVar = this.getNextStyleVariableName();
1969
- statements.push(`const ${styleVar} = ${mapStyleStr}`);
1970
- statements.push(`${varName}.ext.set('style', ${styleVar})`);
1971
- statements.push(`${varName}.updateStyle(${styleVar})`);
1972
- } else {
1973
- statements.push(`${varName}.updateStyle(${mapStyleStr})`);
1974
- }
1975
- }
1976
- } else {
1977
- let newValue = value;
1978
- if (tag === "text" && name === "value") {
1979
- newValue = value.replace(/[\\]+n/g, function(match) {
1980
- return JSON.parse(`"${match}"`);
1981
- });
1982
- }
1983
- statements.push(
1984
- `${varName}.setAttribute('${name}', ${JSON.stringify(newValue)})`
1985
- );
1986
- }
1987
- }
1988
- }
1989
- if (children && children.length > 0) {
1990
- for (const child of children) {
1991
- const inlineCode = this.tryInlineChild(child);
1992
- if (inlineCode) {
1993
- statements.push(`${varName}.appendChild(${inlineCode})`);
1994
- } else {
1995
- const childInfo = this.genNodeCode(child);
1996
- statements.push(...childInfo.statements);
1997
- statements.push(`${varName}.appendChild(${childInfo.variableName})`);
1998
- }
1999
- }
2000
- }
2001
- return { variableName: varName, statements };
2002
- }
2003
- extractTextContent(children) {
2004
- if (!children || children.length !== 1 || children[0].type !== NODE_TYPE_TEXT) {
2005
- return EMPTY_STRING;
2006
- }
2007
- if (children[0].content === " ") {
2008
- return EMPTY_STRING;
2009
- }
2010
- return children[0].content || EMPTY_STRING;
2011
- }
2012
- mergeTextAttributes(attrs, textContent) {
2013
- const result = shared.extend({}, attrs);
2014
- if (textContent) {
2015
- result[VALUE_ATTR] = textContent;
2016
- }
2017
- return result;
2018
- }
2019
- getNextStyleVariableName() {
2020
- return `s${this.styleCounter++}`;
2021
- }
2022
- getNextVariableName() {
2023
- return `e${this.variableCounter++}`;
2024
- }
2025
- tryInlineChild(child) {
2026
- switch (child.type) {
2027
- case NODE_TYPE_TEXT:
2028
- return `doc.createTextNode(${JSON.stringify(child.content || EMPTY_STRING)})`;
2029
- case NODE_TYPE_COMMENT:
2030
- return `doc.createComment(${JSON.stringify(child.content || EMPTY_STRING)})`;
2031
- case NODE_TYPE_ELEMENT:
2032
- const elementChild = child;
2033
- if (this.canInlineElement(elementChild)) {
2034
- return `doc.createElement('${elementChild.tag}')`;
2035
- }
2036
- return null;
2037
- default:
2038
- return `doc.createComment(${JSON.stringify(UNKNOWN_COMMENT)})`;
2039
- }
2040
- }
2041
- canInlineElement(node) {
2042
- if (node.tag === NODE_TYPE_TEXT) {
2043
- return false;
2044
- }
2045
- if (!isEmptyAttrs(node.attrs, this.disableClassBinding)) {
2046
- return false;
2047
- }
2048
- if (node.children && node.children.length > 0) {
2049
- return false;
2050
- }
2051
- return true;
2052
- }
2053
- }
2054
- function isEmptyAttrs(attrs, disableClassBinding) {
2055
- return !attrs || Object.keys(attrs).length === 0 || disableClassBinding && Object.keys(attrs).length === 1 && // 上一步会添加ext:style来标记当前节点有class属性,后续根据该属性设置 ext.set('style',...)
2056
- "ext:style" in attrs;
2057
- }
2058
- class TemplateFactoryGenerator {
2059
- constructor(options) {
2060
- this.codeGenerator = new DomCodeGenerator(options);
2061
- this.isTs = options.isTs || false;
2062
- this.disableClassBinding = options.disableClassBinding;
2063
- }
2064
- genFactoryFunction(template, index) {
2065
- try {
2066
- const parser = new HtmlParser(template);
2067
- const nodes = parser.parse();
2068
- if (nodes.length === 0) {
2069
- return this.genEmptyFunction(index);
2070
- }
2071
- if (nodes.length === 1) {
2072
- return this.genSingleNodeFunction(nodes[0], index);
2073
- }
2074
- return this.genEmptyFunction(index);
2075
- } catch (error) {
2076
- return this.genEmptyFunction(index);
2077
- }
2078
- }
2079
- genEmptyFunction(index) {
2080
- const { paramType, returnType } = this.getFunctionSignature();
2081
- return `function f${index}(${paramType})${returnType} {
2082
- return doc.createTextNode(${JSON.stringify(EMPTY_STRING)})
2083
- }`;
2084
- }
2085
- genSingleNodeFunction(node, index) {
2086
- const { paramType, returnType } = this.getFunctionSignature();
2087
- const simpleReturn = this.tryGenSimpleReturn(node);
2088
- if (simpleReturn) {
2089
- return `function f${index}(${paramType})${returnType} {
2090
- return ${simpleReturn}
2091
- }`;
2092
- }
2093
- const nodeInfo = this.codeGenerator.genNodeStatements(node);
2094
- const statements = nodeInfo.statements.map((stmt) => ` ${stmt}`).join("\n");
2095
- const returnStatement = ` return ${nodeInfo.variableName}`;
2096
- return `function f${index}(${paramType})${returnType} {
2097
- ${statements}
2098
- ${returnStatement}
2099
- }`;
2100
- }
2101
- tryGenSimpleReturn(node) {
2102
- switch (node.type) {
2103
- case NODE_TYPE_TEXT:
2104
- return `doc.createTextNode(${JSON.stringify(node.content || EMPTY_STRING)})`;
2105
- case NODE_TYPE_COMMENT:
2106
- return `doc.createComment(${JSON.stringify(node.content || EMPTY_STRING)})`;
2107
- case NODE_TYPE_ELEMENT:
2108
- const elementNode = node;
2109
- if (this.isSimpleElement(elementNode)) {
2110
- return `doc.createElement('${elementNode.tag}')`;
2111
- }
2112
- return null;
2113
- default:
2114
- return `doc.createComment(${JSON.stringify(UNKNOWN_COMMENT)})`;
2115
- }
2116
- }
2117
- isSimpleElement(node) {
2118
- const emptyAttrs = isEmptyAttrs(node.attrs, this.disableClassBinding);
2119
- if (!emptyAttrs) return false;
2120
- if (node.tag === NODE_TYPE_TEXT) {
2121
- const textContent = this.extractTextContent(node.children);
2122
- return !textContent;
2123
- }
2124
- return !node.children || node.children.length === 0;
2125
- }
2126
- extractTextContent(children) {
2127
- if (!children || children.length !== 1 || children[0].type !== NODE_TYPE_TEXT) {
2128
- return EMPTY_STRING;
2129
- }
2130
- if (children[0].content === " ") {
2131
- return EMPTY_STRING;
2132
- }
2133
- return children[0].content || EMPTY_STRING;
2134
- }
2135
- getFunctionSignature() {
2136
- const paramType = this.isTs ? "doc: IDocument" : "doc";
2137
- const returnType = this.isTs ? ": UniElement" : "";
2138
- return { paramType, returnType };
2139
- }
2140
- }
2141
- function genFactoryFunctions(templates, context) {
2142
- const generator = new TemplateFactoryGenerator({
2143
- parseStaticStyle: context.options.parseStaticStyle,
2144
- isTs: context.options.isTS,
2145
- disableClassBinding: context.options.disableClassBinding
2146
- });
2147
- const functions = templates.map(
2148
- (template, index) => generator.genFactoryFunction(template, index)
2149
- );
2150
- return functions.join("\n");
2151
- }
2152
- function genFactoryCallsInRender(templates, rootIndex, context) {
2153
- const { helper } = context;
2154
- const calls = templates.map((_, index) => {
2155
- const rootParam = index === rootIndex ? ", true" : "";
2156
- return `const t${index} = ${helper("factory")}($doc, f${index}${rootParam})`;
2157
- });
2158
- return calls.join("\n ");
2159
- }
2160
- function genNextSiblingCall(from, context) {
2161
- if (context.options.templateMode === "factory") {
2162
- return [`${from}.nextSibling${context.options.isTS ? "!" : ""}`];
2163
- }
2164
- return genCall(context.helper("next"), from);
2165
- }
2166
- function genNthChildCall(from, index, context) {
2167
- if (context.options.templateMode === "factory") {
2168
- return [`${from}.childNodes[${index}]`];
2169
- } else {
2170
- return genCall(context.helper("nthChild"), from, String(index));
2171
- }
2172
- }
2173
- function genFirstChildCall(from, context) {
2174
- if (context.options.templateMode === "factory") {
2175
- return [`${from}.firstChild${context.options.isTS ? "!" : ""}`];
2176
- }
2177
- return genCall(context.helper("child"), from);
2178
- }
2179
- function genTextFirstChildCall(oper, context) {
2180
- if (context.options.templateMode === "factory") {
2181
- return [
2182
- NEWLINE,
2183
- `const x${oper.parent} = n${oper.parent}.firstChild${context.options.isTS ? "!" : ""}`
2184
- ];
2185
- } else {
2186
- return [
2187
- NEWLINE,
2188
- `const x${oper.parent} = ${context.helper("child")}(n${oper.parent})`
2189
- ];
2190
- }
2191
- }
2192
- function genComplexChildAccess(from, elementIndex, context) {
2193
- if (context.options.templateMode === "factory") {
2194
- if (elementIndex === 1) {
2195
- return [
2196
- `${from}.firstChild${context.options.isTS ? "!" : ""}.nextSibling${context.options.isTS ? "!" : ""}`
2197
- ];
2198
- } else {
2199
- return [`${from}.childNodes[${elementIndex}]`];
2200
- }
2201
- } else {
2202
- let init = genCall(context.helper("child"), from);
2203
- if (elementIndex === 1) {
2204
- init = genCall(context.helper("next"), init);
2205
- } else if (elementIndex > 1) {
2206
- init = genCall(context.helper("nthChild"), from, String(elementIndex));
2207
- }
2208
- return init;
2209
- }
2210
- }
2211
-
2212
- function genSetText(oper, context) {
2213
- const { helper, options } = context;
2214
- const { element, values, generated, jsx } = oper;
2215
- const texts = combineValues(values, context, jsx);
2216
- if (options.templateMode === "factory") {
2217
- return [
2218
- NEWLINE,
2219
- `${generated ? "x" : "n"}${element}.setAttribute('value', `,
2220
- // 处理换行符\n
2221
- ...texts.map((text) => {
2222
- if (shared.isString(text)) {
2223
- return text.replace(/[\\]+n/g, function(match) {
2224
- return JSON.parse(`"${match}"`);
2225
- });
2226
- }
2227
- return text;
2228
- }),
2229
- ")"
2230
- ];
2231
- }
2232
- return [
2233
- NEWLINE,
2234
- ...genCall(helper("setText"), `${generated ? "x" : "n"}${element}`, texts)
2235
- ];
2236
- }
2237
- function combineValues(values, context, jsx) {
2238
- return values.flatMap((value, i) => {
2239
- let exp = genExpression(value, context);
2240
- if (!jsx && getLiteralExpressionValue(value) == null) {
2241
- exp = genCall(context.helper("toDisplayString"), exp);
2242
- }
2243
- if (i > 0) {
2244
- exp.unshift(jsx ? ", " : " + ");
2245
- }
2246
- return exp;
2247
- });
2248
- }
2249
- function genGetTextChild(oper, context) {
2250
- return genTextFirstChildCall(oper, context);
2251
- }
2252
-
2253
- function genVShow(oper, context) {
2254
- return [
2255
- NEWLINE,
2256
- ...genCall(context.helper("applyVShow"), `n${oper.element}`, [
2257
- `() => (`,
2258
- ...genExpression(oper.dir.exp, context),
2259
- `)`
2260
- ])
2261
- ];
2262
- }
2263
-
2264
- const helperMap = {
2265
- text: "applyTextModel",
2266
- radio: "applyRadioModel",
2267
- checkbox: "applyCheckboxModel",
2268
- select: "applySelectModel",
2269
- dynamic: "applyDynamicModel"
2270
- };
2271
- function genVModel(oper, context) {
2272
- const {
2273
- modelType,
2274
- element,
2275
- dir: { exp, modifiers }
2276
- } = oper;
2277
- return [
2278
- NEWLINE,
2279
- ...genCall(
2280
- context.helper(helperMap[modelType]),
2281
- `n${element}`,
2282
- // getter
2283
- [`() => (`, ...genExpression(exp, context), `)`],
2284
- // setter
2285
- genModelHandler(exp, context),
2286
- // modifiers
2287
- modifiers.length ? `{ ${modifiers.map((e) => e.content + ": true").join(",")} }` : void 0
2288
- )
2289
- ];
2290
- }
2291
- function genModelHandler(exp, context) {
2292
- return [
2293
- `${context.options.isTS ? `(_value: any)` : `_value`} => (`,
2294
- ...genExpression(exp, context, "_value"),
2295
- ")"
2296
- ];
2297
- }
2298
-
2299
- function genBuiltinDirective(oper, context) {
2300
- switch (oper.name) {
2301
- case "show":
2302
- return genVShow(oper, context);
2303
- case "model":
2304
- return genVModel(oper, context);
2305
- default:
2306
- return [];
2307
- }
2308
- }
2309
- function genDirectivesForElement(id, context) {
2310
- const dirs = filterCustomDirectives(id, context.block.operation);
2311
- return dirs.length ? genCustomDirectives(dirs, context) : [];
2312
- }
2313
- function genCustomDirectives(opers, context) {
2314
- const { helper } = context;
2315
- const element = `n${opers[0].element}`;
2316
- const directiveItems = opers.map(genDirectiveItem);
2317
- const directives = genMulti(DELIMITERS_ARRAY, ...directiveItems);
2318
- return [
2319
- NEWLINE,
2320
- ...genCall(helper("withVaporDirectives"), element, directives)
2321
- ];
2322
- function genDirectiveItem({
2323
- dir,
2324
- name,
2325
- asset
2326
- }) {
2327
- const directiveVar = asset ? compilerDom.toValidAssetId(name, "directive") : genExpression(
2328
- shared.extend(compilerDom.createSimpleExpression(name, false), { ast: null }),
2329
- context
2330
- );
2331
- const value = dir.exp && ["() => ", ...genExpression(dir.exp, context)];
2332
- const argument = dir.arg && genExpression(dir.arg, context);
2333
- const modifiers = !!dir.modifiers.length && [
2334
- "{ ",
2335
- genDirectiveModifiers(dir.modifiers.map((m) => m.content)),
2336
- " }"
2337
- ];
2338
- return genMulti(
2339
- DELIMITERS_ARRAY.concat("void 0"),
2340
- directiveVar,
2341
- value,
2342
- argument,
2343
- modifiers
2344
- );
2345
- }
2346
- }
2347
- function genDirectiveModifiers(modifiers) {
2348
- return modifiers.map(
2349
- (value) => `${compilerDom.isSimpleIdentifier(value) ? value : JSON.stringify(value)}: true`
2350
- ).join(", ");
2351
- }
2352
- function filterCustomDirectives(id, operations) {
2353
- return operations.filter(
2354
- (oper) => oper.type === 13 && oper.element === id && !oper.builtin
2355
- );
2356
- }
2357
-
2358
- function genCreateComponent(operation, context) {
2359
- const { helper } = context;
2360
- const tag = genTag();
2361
- const { root, props, slots, once } = operation;
2362
- const rawSlots = genRawSlots(slots, context);
2363
- const [ids, handlers] = processInlineHandlers(props, context);
2364
- const rawProps = context.withId(() => genRawProps(props, context), ids);
2365
- const inlineHandlers = handlers.reduce(
2366
- (acc, { name, value }) => {
2367
- const handler = genEventHandler(context, value, void 0, false);
2368
- return [...acc, `const ${name} = `, ...handler, NEWLINE];
2369
- },
2370
- []
2371
- );
2372
- const args = [
2373
- tag,
2374
- rawProps,
2375
- rawSlots,
2376
- root ? "true" : false,
2377
- once && "true"
2378
- ];
2379
- if (context.options.templateMode === "factory") {
2380
- if (operation.asset || operation.dynamic && !operation.dynamic.isStatic) {
2381
- args.unshift(`$doc`);
2382
- }
2383
- }
2384
- return [
2385
- NEWLINE,
2386
- ...inlineHandlers,
2387
- `const n${operation.id} = `,
2388
- ...genCall(
2389
- operation.dynamic && !operation.dynamic.isStatic ? helper("createDynamicComponent") : operation.asset ? helper("createComponentWithFallback") : helper("createComponent"),
2390
- ...args
2391
- ),
2392
- ...genDirectivesForElement(operation.id, context)
2393
- ];
2394
- function genTag() {
2395
- if (operation.dynamic) {
2396
- if (operation.dynamic.isStatic) {
2397
- return genCall(
2398
- helper("resolveDynamicComponent"),
2399
- genExpression(operation.dynamic, context)
2400
- );
2401
- } else {
2402
- return ["() => (", ...genExpression(operation.dynamic, context), ")"];
2403
- }
2404
- } else if (operation.asset) {
2405
- return compilerDom.toValidAssetId(operation.tag, "component");
2406
- } else {
2407
- return genExpression(
2408
- shared.extend(compilerDom.createSimpleExpression(operation.tag, false), { ast: null }),
2409
- context
2410
- );
2411
- }
2412
- }
2413
- }
2414
- function getUniqueHandlerName(context, name) {
2415
- const { seenInlineHandlerNames } = context;
2416
- name = genVarName(name);
2417
- const count = seenInlineHandlerNames[name] || 0;
2418
- seenInlineHandlerNames[name] = count + 1;
2419
- return count === 0 ? name : `${name}${count}`;
2420
- }
2421
- function processInlineHandlers(props, context) {
2422
- const ids = /* @__PURE__ */ Object.create(null);
2423
- const handlers = [];
2424
- const staticProps = props[0];
2425
- if (shared.isArray(staticProps)) {
2426
- for (let i = 0; i < staticProps.length; i++) {
2427
- const prop = staticProps[i];
2428
- if (!prop.handler) continue;
2429
- prop.values.forEach((value, i2) => {
2430
- const isMemberExp = compilerDom.isMemberExpression(value, context.options);
2431
- if (!isMemberExp) {
2432
- const name = getUniqueHandlerName(context, `_on_${prop.key.content}`);
2433
- handlers.push({ name, value });
2434
- ids[name] = null;
2435
- prop.values[i2] = shared.extend({ ast: null }, compilerDom.createSimpleExpression(name));
2436
- }
2437
- });
2438
- }
2439
- }
2440
- return [ids, handlers];
2441
- }
2442
- function genRawProps(props, context) {
2443
- const staticProps = props[0];
2444
- if (shared.isArray(staticProps)) {
2445
- if (!staticProps.length && props.length === 1) {
2446
- return;
2447
- }
2448
- return genStaticProps(
2449
- staticProps,
2450
- context,
2451
- genDynamicProps(props.slice(1), context)
2452
- );
2453
- } else if (props.length) {
2454
- return genStaticProps([], context, genDynamicProps(props, context));
2455
- }
2456
- }
2457
- function genStaticProps(props, context, dynamicProps) {
2458
- const args = props.map((prop) => genProp(prop, context, true));
2459
- if (dynamicProps) {
2460
- args.push([`$: `, ...dynamicProps]);
2461
- }
2462
- return genMulti(
2463
- args.length > 1 ? DELIMITERS_OBJECT_NEWLINE : DELIMITERS_OBJECT,
2464
- ...args
2465
- );
2466
- }
2467
- function genDynamicProps(props, context) {
2468
- const { helper } = context;
2469
- const frags = [];
2470
- for (const p of props) {
2471
- let expr;
2472
- if (shared.isArray(p)) {
2473
- if (p.length) {
2474
- frags.push(genStaticProps(p, context));
2475
- }
2476
- continue;
2477
- } else {
2478
- if (p.kind === 1)
2479
- expr = genMulti(DELIMITERS_OBJECT, genProp(p, context));
2480
- else {
2481
- expr = genExpression(p.value, context);
2482
- if (p.handler) expr = genCall(helper("toHandlers"), expr);
2483
- }
2484
- }
2485
- frags.push(["() => (", ...expr, ")"]);
2486
- }
2487
- if (frags.length) {
2488
- return genMulti(DELIMITERS_ARRAY_NEWLINE, ...frags);
2489
- }
2490
- }
2491
- function genProp(prop, context, isStatic) {
2492
- const values = genPropValue(prop.values, context);
2493
- return [
2494
- ...genPropKey(prop, context),
2495
- ": ",
2496
- ...prop.handler ? genEventHandler(
2497
- context,
2498
- prop.values[0],
2499
- void 0,
2500
- true
2501
- ) : isStatic ? ["() => (", ...values, ")"] : values,
2502
- ...prop.model ? [...genModelEvent(prop, context), ...genModelModifiers(prop, context)] : []
2503
- ];
2504
- }
2505
- function genModelEvent(prop, context) {
2506
- const name = prop.key.isStatic ? [JSON.stringify(`onUpdate:${shared.camelize(prop.key.content)}`)] : ['["onUpdate:" + ', ...genExpression(prop.key, context), "]"];
2507
- const handler = genModelHandler(prop.values[0], context);
2508
- return [",", NEWLINE, ...name, ": () => ", ...handler];
2509
- }
2510
- function genModelModifiers(prop, context) {
2511
- const { key, modelModifiers } = prop;
2512
- if (!modelModifiers || !modelModifiers.length) return [];
2513
- const modifiersKey = key.isStatic ? key.content === "modelValue" ? [`modelModifiers`] : [`${key.content}Modifiers`] : ["[", ...genExpression(key, context), ' + "Modifiers"]'];
2514
- const modifiersVal = genDirectiveModifiers(modelModifiers);
2515
- return [",", NEWLINE, ...modifiersKey, `: () => ({ ${modifiersVal} })`];
2516
- }
2517
- function genRawSlots(slots, context) {
2518
- if (!slots.length) return;
2519
- const staticSlots = slots[0];
2520
- if (staticSlots.slotType === 0) {
2521
- return genStaticSlots(
2522
- staticSlots,
2523
- context,
2524
- slots.length > 1 ? slots.slice(1) : void 0
2525
- );
2526
- } else {
2527
- return genStaticSlots(
2528
- { slots: {} },
2529
- context,
2530
- slots
2531
- );
2532
- }
2533
- }
2534
- function genStaticSlots({ slots }, context, dynamicSlots) {
2535
- const args = Object.keys(slots).map((name) => [
2536
- `${JSON.stringify(name)}: `,
2537
- ...genSlotBlockWithProps(slots[name], context)
2538
- ]);
2539
- if (dynamicSlots) {
2540
- args.push([`$: `, ...genDynamicSlots(dynamicSlots, context)]);
2541
- }
2542
- return genMulti(DELIMITERS_OBJECT_NEWLINE, ...args);
2543
- }
2544
- function genDynamicSlots(slots, context) {
2545
- return genMulti(
2546
- DELIMITERS_ARRAY_NEWLINE,
2547
- ...slots.map(
2548
- (slot) => slot.slotType === 0 ? genStaticSlots(slot, context) : slot.slotType === 4 ? slot.slots.content : genDynamicSlot(slot, context, true)
2549
- )
2550
- );
2551
- }
2552
- function genDynamicSlot(slot, context, withFunction = false) {
2553
- let frag;
2554
- switch (slot.slotType) {
2555
- case 1:
2556
- frag = genBasicDynamicSlot(slot, context);
2557
- break;
2558
- case 2:
2559
- frag = genLoopSlot(slot, context);
2560
- break;
2561
- case 3:
2562
- frag = genConditionalSlot(slot, context);
2563
- break;
2564
- }
2565
- return withFunction ? ["() => (", ...frag, ")"] : frag;
2566
- }
2567
- function genBasicDynamicSlot(slot, context) {
2568
- const { name, fn } = slot;
2569
- return genMulti(
2570
- DELIMITERS_OBJECT_NEWLINE,
2571
- ["name: ", ...genExpression(name, context)],
2572
- ["fn: ", ...genSlotBlockWithProps(fn, context)]
2573
- );
2574
- }
2575
- function genLoopSlot(slot, context) {
2576
- const { name, fn, loop } = slot;
2577
- const { value, key, index, source } = loop;
2578
- const rawValue = value && value.content;
2579
- const rawKey = key && key.content;
2580
- const rawIndex = index && index.content;
2581
- const idMap = {};
2582
- if (rawValue) idMap[rawValue] = rawValue;
2583
- if (rawKey) idMap[rawKey] = rawKey;
2584
- if (rawIndex) idMap[rawIndex] = rawIndex;
2585
- const slotExpr = genMulti(
2586
- DELIMITERS_OBJECT_NEWLINE,
2587
- ["name: ", ...context.withId(() => genExpression(name, context), idMap)],
2588
- [
2589
- "fn: ",
2590
- ...context.withId(() => genSlotBlockWithProps(fn, context), idMap)
2591
- ]
2592
- );
2593
- return [
2594
- ...genCall(
2595
- context.helper("createForSlots"),
2596
- genExpression(source, context),
2597
- [
2598
- ...genMulti(
2599
- ["(", ")", ", "],
2600
- rawValue ? rawValue : rawKey || rawIndex ? "_" : void 0,
2601
- rawKey ? rawKey : rawIndex ? "__" : void 0,
2602
- rawIndex
2603
- ),
2604
- " => (",
2605
- ...slotExpr,
2606
- ")"
2607
- ]
2608
- )
2609
- ];
2610
- }
2611
- function genConditionalSlot(slot, context) {
2612
- const { condition, positive, negative } = slot;
2613
- return [
2614
- ...genExpression(condition, context),
2615
- INDENT_START,
2616
- NEWLINE,
2617
- "? ",
2618
- ...genDynamicSlot(positive, context),
2619
- NEWLINE,
2620
- ": ",
2621
- ...negative ? [...genDynamicSlot(negative, context)] : ["void 0"],
2622
- INDENT_END
2623
- ];
2624
- }
2625
- function genSlotBlockWithProps(oper, context) {
2626
- let isDestructureAssignment = false;
2627
- let rawProps;
2628
- let propsName;
2629
- let exitScope;
2630
- let depth;
2631
- const { props } = oper;
2632
- const idsOfProps = /* @__PURE__ */ new Set();
2633
- if (props) {
2634
- rawProps = props.content;
2635
- if (isDestructureAssignment = !!props.ast) {
2636
- [depth, exitScope] = context.enterScope();
2637
- propsName = `_slotProps${depth}`;
2638
- compilerDom.walkIdentifiers(
2639
- props.ast,
2640
- (id, _, __, ___, isLocal) => {
2641
- if (isLocal) idsOfProps.add(id.name);
2642
- },
2643
- true
2644
- );
2645
- } else {
2646
- idsOfProps.add(propsName = rawProps);
2647
- }
2648
- }
2649
- const idMap = {};
2650
- idsOfProps.forEach(
2651
- (id) => idMap[id] = isDestructureAssignment ? `${propsName}[${JSON.stringify(id)}]` : null
2652
- );
2653
- const blockFn = context.withId(
2654
- () => genBlock(oper, context, [propsName]),
2655
- idMap
2656
- );
2657
- exitScope && exitScope();
2658
- return blockFn;
2659
- }
2660
-
2661
- function genSlotOutlet(oper, context) {
2662
- const { helper } = context;
2663
- const { id, name, fallback } = oper;
2664
- const [frag, push] = buildCodeFragment();
2665
- const nameExpr = name.isStatic ? genExpression(name, context) : ["() => (", ...genExpression(name, context), ")"];
2666
- let fallbackArg;
2667
- if (fallback) {
2668
- fallbackArg = genBlock(fallback, context);
2669
- }
2670
- const slotArgs = [
2671
- nameExpr,
2672
- genRawProps(oper.props, context) || "null",
2673
- fallbackArg
2674
- ];
2675
- if (context.options.templateMode === "factory") {
2676
- slotArgs.unshift(`$doc`);
2677
- }
2678
- push(
2679
- NEWLINE,
2680
- `const n${id} = `,
2681
- ...genCall(helper("createSlot"), ...slotArgs)
2682
- );
2683
- return frag;
2684
- }
2685
-
2686
- function genOperations(opers, context) {
2687
- const [frag, push] = buildCodeFragment();
2688
- for (const operation of opers) {
2689
- push(...genOperationWithInsertionState(operation, context));
2690
- }
2691
- return frag;
2692
- }
2693
- function genOperationWithInsertionState(oper, context) {
2694
- const [frag, push] = buildCodeFragment();
2695
- if (isBlockOperation(oper) && oper.parent) {
2696
- push(...genInsertionState(oper, context));
2697
- }
2698
- push(...genOperation(oper, context));
2699
- return frag;
2700
- }
2701
- function genOperation(oper, context) {
2702
- switch (oper.type) {
2703
- case 2:
2704
- return genSetProp(oper, context);
2705
- case 3:
2706
- return genDynamicProps$1(oper, context);
2707
- case 4:
2708
- return genSetText(oper, context);
2709
- case 5:
2710
- return genSetEvent(oper, context);
2711
- case 6:
2712
- return genSetDynamicEvents(oper, context);
2713
- case 7:
2714
- return genSetHtml(oper, context);
2715
- case 8:
2716
- return genSetTemplateRef(oper, context);
2717
- case 9:
2718
- return genInsertNode(oper, context);
2719
- case 10:
2720
- return genPrependNode(oper, context);
2721
- case 15:
2722
- return genIf(oper, context);
2723
- case 16:
2724
- return genFor(oper, context);
2725
- case 11:
2726
- return genCreateComponent(oper, context);
2727
- case 14:
2728
- return genDeclareOldRef(oper);
2729
- case 12:
2730
- return genSlotOutlet(oper, context);
2731
- case 13:
2732
- return genBuiltinDirective(oper, context);
2733
- case 17:
2734
- return genGetTextChild(oper, context);
2735
- default:
2736
- const exhaustiveCheck = oper;
2737
- throw new Error(
2738
- `Unhandled operation type in genOperation: ${exhaustiveCheck}`
2739
- );
2740
- }
2741
- }
2742
- function genEffects(effects, context, genExtraFrag) {
2743
- const { helper } = context;
2744
- const expressions = effects.flatMap((effect) => effect.expressions);
2745
- const [frag, push, unshift] = buildCodeFragment();
2746
- const shouldDeclare = genExtraFrag === void 0;
2747
- let operationsCount = 0;
2748
- const {
2749
- ids,
2750
- frag: declarationFrags,
2751
- varNames
2752
- } = processExpressions(context, expressions, shouldDeclare);
2753
- push(...declarationFrags);
2754
- for (let i = 0; i < effects.length; i++) {
2755
- const effect = effects[i];
2756
- operationsCount += effect.operations.length;
2757
- const frags = context.withId(() => genEffect(effect, context), ids);
2758
- i > 0 && push(NEWLINE);
2759
- if (frag[frag.length - 1] === ")" && frags[0] === "(") {
2760
- push(";");
2761
- }
2762
- push(...frags);
2763
- }
2764
- const newLineCount = frag.filter((frag2) => frag2 === NEWLINE).length;
2765
- if (newLineCount > 1 || operationsCount > 1 || declarationFrags.length > 0) {
2766
- unshift(`{`, INDENT_START, NEWLINE);
2767
- push(INDENT_END, NEWLINE, "}");
2768
- if (!effects.length) {
2769
- unshift(NEWLINE);
2770
- }
2771
- }
2772
- if (effects.length) {
2773
- unshift(NEWLINE, `${helper("renderEffect")}(() => `);
2774
- push(`)`);
2775
- }
2776
- if (!shouldDeclare && varNames.length) {
2777
- unshift(NEWLINE, `let `, varNames.join(", "));
2778
- }
2779
- if (genExtraFrag) {
2780
- push(...context.withId(genExtraFrag, ids));
2781
- }
2782
- return frag;
2783
- }
2784
- function genEffect({ operations }, context) {
2785
- const [frag, push] = buildCodeFragment();
2786
- const operationsExps = genOperations(operations, context);
2787
- const newlineCount = operationsExps.filter((frag2) => frag2 === NEWLINE).length;
2788
- if (newlineCount > 1) {
2789
- push(...operationsExps);
2790
- } else {
2791
- push(...operationsExps.filter((frag2) => frag2 !== NEWLINE));
2792
- }
2793
- return frag;
2794
- }
2795
- function genInsertionState(operation, context) {
2796
- return [
2797
- NEWLINE,
2798
- ...genCall(
2799
- context.helper("setInsertionState"),
2800
- `n${operation.parent}`,
2801
- operation.anchor == null ? void 0 : operation.anchor === -1 ? `0` : `n${operation.anchor}`
2802
- )
2803
- ];
2804
- }
2805
-
2806
- function genTemplates(templates, rootIndex, context) {
2807
- const { helper, options } = context;
2808
- if (options.templateMode === "factory") {
2809
- const factoryFunctions = genFactoryFunctions(templates, context);
2810
- return factoryFunctions ? factoryFunctions + "\n" : "";
2811
- } else {
2812
- return templates.map(
2813
- (template, i) => `const t${i} = ${helper("template")}(${JSON.stringify(
2814
- template
2815
- )}${i === rootIndex ? ", true" : ""})
2816
- `
2817
- ).join("");
2818
- }
2819
- }
2820
- function genSelf(dynamic, context) {
2821
- const [frag, push] = buildCodeFragment();
2822
- const { id, template, operation } = dynamic;
2823
- if (id !== void 0 && template !== void 0) {
2824
- push(NEWLINE, `const n${id} = t${template}()`);
2825
- push(...genDirectivesForElement(id, context));
2826
- }
2827
- if (operation) {
2828
- push(...genOperationWithInsertionState(operation, context));
2829
- }
2830
- return frag;
2831
- }
2832
- function genChildren(dynamic, context, pushBlock, from = `n${dynamic.id}`) {
2833
- const [frag, push] = buildCodeFragment();
2834
- const { children } = dynamic;
2835
- let offset = 0;
2836
- let prev;
2837
- const childrenToGen = [];
2838
- for (const [index, child] of children.entries()) {
2839
- if (child.flags & 2) {
2840
- offset--;
2841
- }
2842
- const id = child.flags & 1 ? child.flags & 4 ? child.anchor : child.id : void 0;
2843
- if (id === void 0 && !child.hasDynamicChild) {
2844
- push(...genSelf(child, context));
2845
- continue;
2846
- }
2847
- const elementIndex = Number(index) + offset;
2848
- const variable = id === void 0 ? `p${context.block.tempId++}` : `n${id}`;
2849
- pushBlock(NEWLINE, `const ${variable} = `);
2850
- if (prev) {
2851
- if (elementIndex - prev[1] === 1) {
2852
- pushBlock(...genNextSiblingCall(prev[0], context));
2853
- } else {
2854
- pushBlock(...genNthChildCall(from, elementIndex, context));
2855
- }
2856
- } else {
2857
- if (elementIndex === 0) {
2858
- pushBlock(...genFirstChildCall(from, context));
2859
- } else {
2860
- pushBlock(...genComplexChildAccess(from, elementIndex, context));
2861
- }
2862
- }
2863
- if (id === child.anchor) {
2864
- push(...genSelf(child, context));
2865
- }
2866
- if (id !== void 0) {
2867
- push(...genDirectivesForElement(id, context));
2868
- }
2869
- prev = [variable, elementIndex];
2870
- childrenToGen.push([child, variable]);
2871
- }
2872
- if (childrenToGen.length) {
2873
- for (const [child, from2] of childrenToGen) {
2874
- push(...genChildren(child, context, pushBlock, from2));
2875
- }
2876
- }
2877
- return frag;
2878
- }
2879
-
2880
- function genBlock(oper, context, args = [], root) {
2881
- return [
2882
- "(",
2883
- ...args,
2884
- ") => {",
2885
- INDENT_START,
2886
- ...genBlockContent(oper, context, root),
2887
- INDENT_END,
2888
- NEWLINE,
2889
- "}"
2890
- ];
2891
- }
2892
- function genBlockContent(block, context, root, genEffectsExtraFrag) {
2893
- const [frag, push] = buildCodeFragment();
2894
- const { dynamic, effect, operation, returns } = block;
2895
- const resetBlock = context.enterBlock(block);
2896
- if (root) {
2897
- for (let name of context.ir.component) {
2898
- const id = compilerDom.toValidAssetId(name, "component");
2899
- const maybeSelfReference = name.endsWith("__self");
2900
- if (maybeSelfReference) name = name.slice(0, -6);
2901
- push(
2902
- NEWLINE,
2903
- `const ${id} = `,
2904
- ...genCall(
2905
- context.helper("resolveComponent"),
2906
- JSON.stringify(name),
2907
- // pass additional `maybeSelfReference` flag
2908
- maybeSelfReference ? "true" : void 0
2909
- )
2910
- );
2911
- }
2912
- genResolveAssets("directive", "resolveDirective");
2913
- }
2914
- for (const child of dynamic.children) {
2915
- push(...genSelf(child, context));
2916
- }
2917
- for (const child of dynamic.children) {
2918
- push(...genChildren(child, context, push, `n${child.id}`));
2919
- }
2920
- push(...genOperations(operation, context));
2921
- push(...genEffects(effect, context, genEffectsExtraFrag));
2922
- push(NEWLINE, `return `);
2923
- const returnNodes = returns.map((n) => `n${n}`);
2924
- const returnsCode = returnNodes.length > 1 ? genMulti(DELIMITERS_ARRAY, ...returnNodes) : [returnNodes[0] || "null"];
2925
- push(...returnsCode);
2926
- resetBlock();
2927
- return frag;
2928
- function genResolveAssets(kind, helper) {
2929
- for (const name of context.ir[kind]) {
2930
- push(
2931
- NEWLINE,
2932
- `const ${compilerDom.toValidAssetId(name, kind)} = `,
2933
- ...genCall(context.helper(helper), JSON.stringify(name))
2934
- );
2935
- }
2936
- }
2937
- }
2938
-
2939
- class CodegenContext {
2940
- constructor(ir, options) {
2941
- this.ir = ir;
2942
- this.helpers = /* @__PURE__ */ new Set([]);
2943
- this.helper = (name) => {
2944
- this.helpers.add(name);
2945
- return `_${name}`;
2946
- };
2947
- this.delegates = /* @__PURE__ */ new Set();
2948
- this.identifiers = /* @__PURE__ */ Object.create(null);
2949
- this.seenInlineHandlerNames = /* @__PURE__ */ Object.create(null);
2950
- this.scopeLevel = 0;
2951
- const defaultOptions = {
2952
- mode: "module",
2953
- prefixIdentifiers: true,
2954
- sourceMap: false,
2955
- filename: `template.vue.html`,
2956
- scopeId: null,
2957
- runtimeGlobalName: `Vue`,
2958
- runtimeModuleName: `vue`,
2959
- ssrRuntimeModuleName: "vue/server-renderer",
2960
- ssr: false,
2961
- isTS: false,
2962
- inSSR: false,
2963
- inline: false,
2964
- bindingMetadata: {},
2965
- expressionPlugins: [],
2966
- // fixed by uts
2967
- templateMode: "string",
2968
- disableEventDelegation: false,
2969
- parseStaticStyle: (style) => JSON.stringify(style),
2970
- disableClassBinding: false
2971
- };
2972
- this.options = shared.extend(defaultOptions, options);
2973
- this.block = ir.block;
2974
- }
2975
- withId(fn, map) {
2976
- const { identifiers } = this;
2977
- const ids = Object.keys(map);
2978
- for (const id of ids) {
2979
- identifiers[id] || (identifiers[id] = []);
2980
- identifiers[id].unshift(map[id] || id);
2981
- }
2982
- const ret = fn();
2983
- ids.forEach((id) => shared.remove(identifiers[id], map[id] || id));
2984
- return ret;
2985
- }
2986
- enterBlock(block) {
2987
- const parent = this.block;
2988
- this.block = block;
2989
- return () => this.block = parent;
2990
- }
2991
- enterScope() {
2992
- return [this.scopeLevel++, () => this.scopeLevel--];
2993
- }
2994
- }
2995
- function generate(ir, options = {}) {
2996
- const [frag, push] = buildCodeFragment();
2997
- const context = new CodegenContext(ir, options);
2998
- const { helpers } = context;
2999
- const { inline, bindingMetadata } = options;
3000
- const functionName = "render";
3001
- const args = ["_ctx"];
3002
- if (bindingMetadata && !inline) {
3003
- args.push("$props", "$emit", "$attrs", "$slots");
3004
- }
3005
- const signature = (options.isTS ? args.map((arg) => `${arg}: any`) : args).join(
3006
- ", "
3007
- );
3008
- const shouldWrap = inline && options.templateMode === "factory";
3009
- if (!inline) {
3010
- push(NEWLINE, `export function ${functionName}(${signature}) {`);
3011
- } else if (shouldWrap) {
3012
- push(NEWLINE, `return (() => {`);
3013
- push(NEWLINE, ` 'raw js'`);
3014
- }
3015
- push(INDENT_START);
3016
- if (ir.hasTemplateRef) {
3017
- push(
3018
- NEWLINE,
3019
- `const ${setTemplateRefIdent} = ${context.helper("createTemplateRefSetter")}()`
3020
- );
3021
- }
3022
- const codeFragments = genBlockContent(ir.block, context, true);
3023
- if (options.templateMode === "factory") {
3024
- if (ir.template.length > 0 || context.delegates.size > 0 || context.helpers.has("createDynamicComponent") || context.helpers.has("createComponentWithFallback") || context.helpers.has("createIf") || context.helpers.has("createFor") || context.helpers.has("createSlot")) {
3025
- push(
3026
- NEWLINE,
3027
- `const $ins = ${context.helper("getCurrentGenericInstance")}()`
3028
- );
3029
- push(NEWLINE, `const $proxy = $ins.proxy${options.isTS ? "!" : ""}`);
3030
- push(NEWLINE, `const $doc = $proxy.$nativePage.document`);
3031
- }
3032
- if (context.delegates.size) {
3033
- const delegatesCall = genCall(
3034
- context.helper("delegateEvents"),
3035
- ...[`$doc`, ...Array.from(context.delegates).map((v) => `"${v}"`)]
3036
- ).join("");
3037
- push(NEWLINE, delegatesCall);
3038
- }
3039
- if (ir.template.length > 0) {
3040
- const templateCalls = genFactoryCallsInRender(
3041
- ir.template,
3042
- ir.rootTemplateIndex,
3043
- context
3044
- );
3045
- push(NEWLINE, templateCalls);
3046
- }
3047
- }
3048
- push(...codeFragments);
3049
- push(INDENT_END, NEWLINE);
3050
- if (!inline) {
3051
- push("}");
3052
- } else if (shouldWrap) {
3053
- push(`})()`);
3054
- }
3055
- const delegates = genDelegates(context);
3056
- const templates = genTemplates(ir.template, ir.rootTemplateIndex, context);
3057
- const imports = genHelperImports(context);
3058
- const preamble = imports + templates + delegates;
3059
- const newlineCount = [...preamble].filter((c) => c === "\n").length;
3060
- if (newlineCount && !inline) {
3061
- frag.unshift(...new Array(newlineCount).fill(LF));
3062
- }
3063
- let [code, map] = codeFragmentToString(frag, context);
3064
- if (!inline) {
3065
- code = preamble + code;
3066
- }
3067
- return {
3068
- code,
3069
- ast: ir,
3070
- preamble,
3071
- map: map && map.toJSON(),
3072
- helpers
3073
- };
3074
- }
3075
- function genDelegates({ delegates, helper, options }) {
3076
- if (options.templateMode === "factory") {
3077
- return "";
3078
- }
3079
- return delegates.size ? genCall(
3080
- helper("delegateEvents"),
3081
- ...Array.from(delegates).map((v) => `"${v}"`)
3082
- ).join("") + "\n" : "";
3083
- }
3084
- function genHelperImports({ helpers, helper, options }) {
3085
- let imports = "";
3086
- if (helpers.size) {
3087
- imports += `import { ${[...helpers].map((h) => `${h} as _${h}`).join(", ")} } from '${options.runtimeModuleName}';
3088
- `;
3089
- }
3090
- return imports;
3091
- }
3092
-
3093
- const transformChildren = (node, context) => {
3094
- const isFragment = node.type === 0 || node.type === 1 && (node.tagType === 3 || node.tagType === 1);
3095
- if (!isFragment && node.type !== 1) return;
3096
- for (const [i, child] of node.children.entries()) {
3097
- const childContext = context.create(child, i);
3098
- transformNode(childContext);
3099
- const childDynamic = childContext.dynamic;
3100
- if (isFragment) {
3101
- childContext.reference();
3102
- childContext.registerTemplate();
3103
- if (!(childDynamic.flags & 2) || childDynamic.flags & 4) {
3104
- context.block.returns.push(childContext.dynamic.id);
3105
- }
3106
- } else {
3107
- context.childrenTemplate.push(childContext.template);
3108
- }
3109
- if (childDynamic.hasDynamicChild || childDynamic.id !== void 0 || childDynamic.flags & 2 || childDynamic.flags & 4) {
3110
- context.dynamic.hasDynamicChild = true;
3111
- }
3112
- context.dynamic.children[i] = childDynamic;
3113
- }
3114
- if (!isFragment) {
3115
- processDynamicChildren(context);
3116
- }
3117
- };
3118
- function processDynamicChildren(context) {
3119
- let prevDynamics = [];
3120
- let hasStaticTemplate = false;
3121
- const children = context.dynamic.children;
3122
- for (const [index, child] of children.entries()) {
3123
- if (child.flags & 4) {
3124
- prevDynamics.push(child);
3125
- }
3126
- if (!(child.flags & 2)) {
3127
- if (prevDynamics.length) {
3128
- if (hasStaticTemplate) {
3129
- context.childrenTemplate[index - prevDynamics.length] = `<!>`;
3130
- prevDynamics[0].flags -= 2;
3131
- const anchor = prevDynamics[0].anchor = context.increaseId();
3132
- registerInsertion(prevDynamics, context, anchor);
3133
- } else {
3134
- registerInsertion(
3135
- prevDynamics,
3136
- context,
3137
- -1
3138
- /* prepend */
3139
- );
3140
- }
3141
- prevDynamics = [];
3142
- }
3143
- hasStaticTemplate = true;
3144
- }
3145
- }
3146
- if (prevDynamics.length) {
3147
- registerInsertion(prevDynamics, context);
3148
- }
3149
- }
3150
- function registerInsertion(dynamics, context, anchor) {
3151
- for (const child of dynamics) {
3152
- if (child.template != null) {
3153
- context.registerOperation({
3154
- type: 9,
3155
- elements: dynamics.map((child2) => child2.id),
3156
- parent: context.reference(),
3157
- anchor
3158
- });
3159
- } else if (child.operation && isBlockOperation(child.operation)) {
3160
- child.operation.parent = context.reference();
3161
- child.operation.anchor = anchor;
3162
- }
3163
- }
3164
- }
3165
-
3166
- const transformVOnce = (node, context) => {
3167
- if (
3168
- // !context.inSSR &&
3169
- node.type === 1 && compilerDom.findDir(node, "once", true)
3170
- ) {
3171
- context.inVOnce = true;
3172
- }
3173
- };
3174
-
3175
- const isReservedProp = /* @__PURE__ */ shared.makeMap(
3176
- // the leading comma is intentional so empty string "" is also included
3177
- ",key,ref,ref_for,ref_key,"
3178
- );
3179
- const transformElement = (node, context) => {
3180
- let effectIndex = context.block.effect.length;
3181
- const getEffectIndex = () => effectIndex++;
3182
- return function postTransformElement() {
3183
- ({ node } = context);
3184
- if (!(node.type === 1 && (node.tagType === 0 || node.tagType === 1)))
3185
- return;
3186
- const isComponent = node.tagType === 1;
3187
- const isDynamicComponent = isComponentTag(node.tag);
3188
- const propsResult = buildProps(
3189
- node,
3190
- context,
3191
- isComponent,
3192
- isDynamicComponent,
3193
- getEffectIndex
3194
- );
3195
- let { parent } = context;
3196
- while (parent && parent.parent && parent.node.type === 1 && parent.node.tagType === 3) {
3197
- parent = parent.parent;
3198
- }
3199
- const singleRoot = context.root === parent && parent.node.children.filter((child) => child.type !== 3).length === 1;
3200
- if (isComponent) {
3201
- transformComponentElement(
3202
- node,
3203
- propsResult,
3204
- singleRoot,
3205
- context,
3206
- isDynamicComponent
3207
- );
3208
- } else {
3209
- transformNativeElement(
3210
- node,
3211
- propsResult,
3212
- singleRoot,
3213
- context,
3214
- getEffectIndex
3215
- );
3216
- }
3217
- };
3218
- };
3219
- function transformComponentElement(node, propsResult, singleRoot, context, isDynamicComponent) {
3220
- const dynamicComponent = isDynamicComponent ? resolveDynamicComponent(node) : void 0;
3221
- let { tag } = node;
3222
- let asset = true;
3223
- if (!dynamicComponent) {
3224
- const fromSetup = resolveSetupReference(tag, context);
3225
- if (fromSetup) {
3226
- tag = fromSetup;
3227
- asset = false;
3228
- }
3229
- const dotIndex = tag.indexOf(".");
3230
- if (dotIndex > 0) {
3231
- const ns = resolveSetupReference(tag.slice(0, dotIndex), context);
3232
- if (ns) {
3233
- tag = ns + tag.slice(dotIndex);
3234
- asset = false;
3235
- }
3236
- }
3237
- if (asset) {
3238
- if (context.selfName && shared.capitalize(shared.camelize(tag)) === context.selfName) {
3239
- tag += `__self`;
3240
- }
3241
- context.component.add(tag);
3242
- }
3243
- }
3244
- context.dynamic.flags |= 2 | 4;
3245
- context.dynamic.operation = {
3246
- type: 11,
3247
- id: context.reference(),
3248
- tag,
3249
- props: propsResult[0] ? propsResult[1] : [propsResult[1]],
3250
- asset,
3251
- root: singleRoot && !context.inVFor,
3252
- slots: [...context.slots],
3253
- once: context.inVOnce,
3254
- dynamic: dynamicComponent
3255
- };
3256
- context.slots = [];
3257
- }
3258
- function resolveDynamicComponent(node) {
3259
- const isProp = findProp(
3260
- node,
3261
- "is",
3262
- false,
3263
- true
3264
- /* allow empty */
3265
- );
3266
- if (!isProp) return;
3267
- if (isProp.type === 6) {
3268
- return isProp.value && compilerDom.createSimpleExpression(isProp.value.content, true);
3269
- } else {
3270
- return isProp.exp || // #10469 handle :is shorthand
3271
- shared.extend(compilerDom.createSimpleExpression(`is`, false, isProp.arg.loc), {
3272
- ast: null
3273
- });
3274
- }
3275
- }
3276
- function resolveSetupReference(name, context) {
3277
- const bindings = context.options.bindingMetadata;
3278
- if (!bindings || bindings.__isScriptSetup === false) {
3279
- return;
3280
- }
3281
- const camelName = shared.camelize(name);
3282
- const PascalName = shared.capitalize(camelName);
3283
- return bindings[name] ? name : bindings[camelName] ? camelName : bindings[PascalName] ? PascalName : void 0;
3284
- }
3285
- function transformNativeElement(node, propsResult, singleRoot, context, getEffectIndex) {
3286
- const { tag } = node;
3287
- const { scopeId } = context.options;
3288
- let template = "";
3289
- template += `<${tag}`;
3290
- if (scopeId) template += ` ${scopeId}`;
3291
- const dynamicProps = [];
3292
- if (propsResult[0]) {
3293
- const [, dynamicArgs, expressions] = propsResult;
3294
- context.registerEffect(
3295
- expressions,
3296
- {
3297
- type: 3,
3298
- element: context.reference(),
3299
- props: dynamicArgs,
3300
- root: singleRoot
3301
- },
3302
- getEffectIndex
3303
- );
3304
- } else {
3305
- let hasStaticStyle = false;
3306
- let hasClass = false;
3307
- for (const prop of propsResult[1]) {
3308
- const { key, values } = prop;
3309
- if (key.isStatic && values.length === 1 && values[0].isStatic) {
3310
- if (key.content === "style") {
3311
- hasStaticStyle = true;
3312
- }
3313
- if (key.content === "class") {
3314
- hasClass = true;
3315
- }
3316
- if (context.options.disableClassBinding && key.content === "class") {
3317
- dynamicProps.push(key.content);
3318
- context.registerEffect(
3319
- values,
3320
- {
3321
- type: 2,
3322
- element: context.reference(),
3323
- prop,
3324
- root: singleRoot,
3325
- tag
3326
- },
3327
- getEffectIndex
3328
- );
3329
- continue;
3330
- }
3331
- template += ` ${key.content}`;
3332
- if (values[0].content) template += `="${values[0].content}"`;
3333
- } else {
3334
- if (key.content === "class") {
3335
- hasClass = true;
3336
- }
3337
- dynamicProps.push(key.content);
3338
- context.registerEffect(
3339
- values,
3340
- {
3341
- type: 2,
3342
- element: context.reference(),
3343
- prop,
3344
- root: singleRoot,
3345
- tag
3346
- },
3347
- getEffectIndex
3348
- );
3349
- }
3350
- }
3351
- if (context.options.templateMode === "factory" && context.options.disableClassBinding) {
3352
- if (hasStaticStyle && hasClass) {
3353
- template += ` ext:style`;
3354
- }
3355
- }
3356
- }
3357
- template += `>` + context.childrenTemplate.join("");
3358
- if (!shared.isVoidTag(tag)) {
3359
- template += `</${tag}>`;
3360
- }
3361
- if (singleRoot) {
3362
- context.ir.rootTemplateIndex = context.ir.template.length;
3363
- }
3364
- if (context.parent && context.parent.node.type === 1 && !compilerDom.isValidHTMLNesting(context.parent.node.tag, tag)) {
3365
- context.reference();
3366
- context.dynamic.template = context.pushTemplate(template);
3367
- context.dynamic.flags |= 4 | 2;
3368
- } else {
3369
- context.template += template;
3370
- }
3371
- }
3372
- function buildProps(node, context, isComponent, isDynamicComponent, getEffectIndex) {
3373
- const props = node.props;
3374
- if (props.length === 0) return [false, []];
3375
- const dynamicArgs = [];
3376
- const dynamicExpr = [];
3377
- let results = [];
3378
- function pushMergeArg() {
3379
- if (results.length) {
3380
- dynamicArgs.push(dedupeProperties(results));
3381
- results = [];
3382
- }
3383
- }
3384
- for (const prop of props) {
3385
- if (prop.type === 7 && !prop.arg) {
3386
- if (prop.name === "bind") {
3387
- if (prop.exp) {
3388
- dynamicExpr.push(prop.exp);
3389
- pushMergeArg();
3390
- dynamicArgs.push({
3391
- kind: 0,
3392
- value: prop.exp
3393
- });
3394
- } else {
3395
- context.options.onError(
3396
- compilerDom.createCompilerError(34, prop.loc)
3397
- );
3398
- }
3399
- continue;
3400
- } else if (prop.name === "on") {
3401
- if (prop.exp) {
3402
- if (isComponent) {
3403
- dynamicExpr.push(prop.exp);
3404
- pushMergeArg();
3405
- dynamicArgs.push({
3406
- kind: 0,
3407
- value: prop.exp,
3408
- handler: true
3409
- });
3410
- } else {
3411
- context.registerEffect(
3412
- [prop.exp],
3413
- {
3414
- type: 6,
3415
- element: context.reference(),
3416
- event: prop.exp
3417
- },
3418
- getEffectIndex
3419
- );
3420
- }
3421
- } else {
3422
- context.options.onError(
3423
- compilerDom.createCompilerError(35, prop.loc)
3424
- );
3425
- }
3426
- continue;
3427
- }
3428
- }
3429
- if (isDynamicComponent && prop.type === 6 && prop.name === "is" || prop.type === 7 && prop.name === "bind" && compilerDom.isStaticArgOf(prop.arg, "is")) {
3430
- continue;
3431
- }
3432
- const result = transformProp(prop, node, context);
3433
- if (result) {
3434
- dynamicExpr.push(result.key, result.value);
3435
- if (isComponent && !result.key.isStatic) {
3436
- pushMergeArg();
3437
- dynamicArgs.push(
3438
- shared.extend(resolveDirectiveResult(result), {
3439
- kind: 1
3440
- })
3441
- );
3442
- } else {
3443
- results.push(result);
3444
- }
3445
- }
3446
- }
3447
- if (dynamicArgs.length || results.some(({ key }) => !key.isStatic)) {
3448
- pushMergeArg();
3449
- return [true, dynamicArgs, dynamicExpr];
3450
- }
3451
- const irProps = dedupeProperties(results);
3452
- return [false, irProps];
3453
- }
3454
- function transformProp(prop, node, context) {
3455
- let { name } = prop;
3456
- if (prop.type === 6) {
3457
- if (isReservedProp(name)) return;
3458
- return {
3459
- key: compilerDom.createSimpleExpression(prop.name, true, prop.nameLoc),
3460
- value: prop.value ? compilerDom.createSimpleExpression(prop.value.content, true, prop.value.loc) : EMPTY_EXPRESSION
3461
- };
3462
- }
3463
- const directiveTransform = context.options.directiveTransforms[name];
3464
- if (directiveTransform) {
3465
- return directiveTransform(prop, node, context);
3466
- }
3467
- if (!shared.isBuiltInDirective(name)) {
3468
- const fromSetup = resolveSetupReference(`v-${name}`, context);
3469
- if (fromSetup) {
3470
- name = fromSetup;
3471
- } else {
3472
- context.directive.add(name);
3473
- }
3474
- context.registerOperation({
3475
- type: 13,
3476
- element: context.reference(),
3477
- dir: prop,
3478
- name,
3479
- asset: !fromSetup
3480
- });
3481
- }
3482
- }
3483
- function dedupeProperties(results) {
3484
- const knownProps = /* @__PURE__ */ new Map();
3485
- const deduped = [];
3486
- for (const result of results) {
3487
- const prop = resolveDirectiveResult(result);
3488
- if (!prop.key.isStatic) {
3489
- deduped.push(prop);
3490
- continue;
3491
- }
3492
- const name = prop.key.content;
3493
- const existing = knownProps.get(name);
3494
- if (existing) {
3495
- if (name === "style" || name === "class") {
3496
- mergePropValues(existing, prop);
3497
- }
3498
- } else {
3499
- knownProps.set(name, prop);
3500
- deduped.push(prop);
3501
- }
3502
- }
3503
- return deduped;
3504
- }
3505
- function resolveDirectiveResult(prop) {
3506
- return shared.extend({}, prop, {
3507
- value: void 0,
3508
- values: [prop.value]
3509
- });
3510
- }
3511
- function mergePropValues(existing, incoming) {
3512
- const newValues = incoming.values;
3513
- existing.values.push(...newValues);
3514
- }
3515
- function isComponentTag(tag) {
3516
- return tag === "component" || tag === "Component";
3517
- }
3518
-
3519
- const transformVHtml = (dir, node, context) => {
3520
- let { exp, loc } = dir;
3521
- if (!exp) {
3522
- context.options.onError(
3523
- compilerDom.createDOMCompilerError(53, loc)
3524
- );
3525
- exp = EMPTY_EXPRESSION;
3526
- }
3527
- if (node.children.length) {
3528
- context.options.onError(
3529
- compilerDom.createDOMCompilerError(54, loc)
3530
- );
3531
- context.childrenTemplate.length = 0;
3532
- }
3533
- context.registerEffect([exp], {
3534
- type: 7,
3535
- element: context.reference(),
3536
- value: exp
3537
- });
3538
- };
3539
-
3540
- /*! #__NO_SIDE_EFFECTS__ */
3541
- // @__NO_SIDE_EFFECTS__
3542
- function makeMap(str) {
3543
- const map = /* @__PURE__ */ Object.create(null);
3544
- for (const key of str.split(",")) map[key] = 1;
3545
- return (val) => val in map;
3546
- }
3547
-
3548
- const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr";
3549
- const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS);
3550
-
3551
- const transformVText = (dir, node, context) => {
3552
- let { exp, loc } = dir;
3553
- if (!exp) {
3554
- context.options.onError(
3555
- compilerDom.createDOMCompilerError(55, loc)
3556
- );
3557
- exp = EMPTY_EXPRESSION;
3558
- }
3559
- if (node.children.length) {
3560
- context.options.onError(
3561
- compilerDom.createDOMCompilerError(56, loc)
3562
- );
3563
- context.childrenTemplate.length = 0;
3564
- }
3565
- if (isVoidTag(context.node.tag)) {
3566
- return;
3567
- }
3568
- const literal = getLiteralExpressionValue(exp);
3569
- if (literal != null) {
3570
- context.childrenTemplate = [String(literal)];
3571
- } else {
3572
- context.childrenTemplate = [" "];
3573
- context.registerOperation({
3574
- type: 17,
3575
- parent: context.reference()
3576
- });
3577
- context.registerEffect([exp], {
3578
- type: 4,
3579
- element: context.reference(),
3580
- values: [exp],
3581
- generated: true
3582
- });
3583
- }
3584
- };
3585
-
3586
- function normalizeBindShorthand(arg, context) {
3587
- if (arg.type !== 4 || !arg.isStatic) {
3588
- context.options.onError(
3589
- compilerDom.createCompilerError(
3590
- 52,
3591
- arg.loc
3592
- )
3593
- );
3594
- return compilerDom.createSimpleExpression("", true, arg.loc);
3595
- }
3596
- const propName = shared.camelize(arg.content);
3597
- const exp = compilerDom.createSimpleExpression(propName, false, arg.loc);
3598
- exp.ast = null;
3599
- return exp;
3600
- }
3601
- const transformVBind = (dir, node, context) => {
3602
- const { loc, modifiers } = dir;
3603
- let { exp } = dir;
3604
- let arg = dir.arg;
3605
- const modifiersString = modifiers.map((s) => s.content);
3606
- if (!exp) exp = normalizeBindShorthand(arg, context);
3607
- if (!exp.content.trim()) {
3608
- context.options.onError(
3609
- compilerDom.createCompilerError(34, loc)
3610
- );
3611
- exp = compilerDom.createSimpleExpression("", true, loc);
3612
- }
3613
- exp = resolveExpression(exp);
3614
- arg = resolveExpression(arg);
3615
- if (arg.isStatic && isReservedProp(arg.content)) return;
3616
- let camel = false;
3617
- if (modifiersString.includes("camel")) {
3618
- if (arg.isStatic) {
3619
- arg = shared.extend({}, arg, { content: shared.camelize(arg.content) });
3620
- } else {
3621
- camel = true;
3622
- }
3623
- }
3624
- return {
3625
- key: arg,
3626
- value: exp,
3627
- loc,
3628
- runtimeCamelize: camel,
3629
- modifier: modifiersString.includes("prop") ? "." : modifiersString.includes("attr") ? "^" : void 0
3630
- };
3631
- };
3632
-
3633
- const delegatedEvents = /* @__PURE__ */ shared.makeMap(
3634
- "beforeinput,click,dblclick,contextmenu,focusin,focusout,input,keydown,keyup,mousedown,mousemove,mouseout,mouseover,mouseup,pointerdown,pointermove,pointerout,pointerover,pointerup,touchend,touchmove,touchstart"
3635
- );
3636
- const transformVOn = (dir, node, context) => {
3637
- let { arg, exp, loc, modifiers } = dir;
3638
- const isComponent = node.tagType === 1;
3639
- const isSlotOutlet = node.tag === "slot";
3640
- if (!exp && !modifiers.length) {
3641
- context.options.onError(
3642
- compilerDom.createCompilerError(35, loc)
3643
- );
3644
- }
3645
- arg = resolveExpression(arg);
3646
- const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = compilerDom.resolveModifiers(
3647
- arg.isStatic ? `on${arg.content}` : arg,
3648
- modifiers,
3649
- null,
3650
- loc
3651
- );
3652
- let keyOverride;
3653
- const isStaticClick = arg.isStatic && arg.content.toLowerCase() === "click";
3654
- if (nonKeyModifiers.includes("middle")) {
3655
- if (isStaticClick) {
3656
- arg = shared.extend({}, arg, { content: "mouseup" });
3657
- } else if (!arg.isStatic) {
3658
- keyOverride = ["click", "mouseup"];
3659
- }
3660
- }
3661
- if (nonKeyModifiers.includes("right")) {
3662
- if (isStaticClick) {
3663
- arg = shared.extend({}, arg, { content: "contextmenu" });
3664
- } else if (!arg.isStatic) {
3665
- keyOverride = ["click", "contextmenu"];
3666
- }
3667
- }
3668
- if (isComponent || isSlotOutlet) {
3669
- const handler = exp || EMPTY_EXPRESSION;
3670
- return {
3671
- key: arg,
3672
- value: handler,
3673
- handler: true,
3674
- handlerModifiers: eventOptionModifiers
3675
- };
3676
- }
3677
- const delegate = !context.options.disableEventDelegation && arg.isStatic && !eventOptionModifiers.length && delegatedEvents(arg.content);
3678
- const operation = {
3679
- type: 5,
3680
- element: context.reference(),
3681
- key: arg,
3682
- value: exp,
3683
- modifiers: {
3684
- keys: keyModifiers,
3685
- nonKeys: nonKeyModifiers,
3686
- options: eventOptionModifiers
3687
- },
3688
- keyOverride,
3689
- delegate,
3690
- effect: !arg.isStatic
3691
- };
3692
- context.registerEffect([arg], operation);
3693
- };
3694
-
3695
- const transformVShow = (dir, node, context) => {
3696
- const { exp, loc } = dir;
3697
- if (!exp) {
3698
- context.options.onError(
3699
- compilerDom.createDOMCompilerError(61, loc)
3700
- );
3701
- return;
3702
- }
3703
- if (node.tagType === 2) {
3704
- context.options.onError(
3705
- compilerDom.createCompilerError(
3706
- 36,
3707
- loc
3708
- )
3709
- );
3710
- return;
3711
- }
3712
- context.registerOperation({
3713
- type: 13,
3714
- element: context.reference(),
3715
- dir,
3716
- name: "show",
3717
- builtin: true
3718
- });
3719
- };
3720
-
3721
- const transformTemplateRef = (node, context) => {
3722
- if (node.type !== 1) return;
3723
- const dir = findProp(node, "ref", false, true);
3724
- if (!dir) return;
3725
- context.ir.hasTemplateRef = true;
3726
- let value;
3727
- if (dir.type === 7) {
3728
- value = dir.exp || normalizeBindShorthand(dir.arg, context);
3729
- } else {
3730
- value = dir.value ? compilerDom.createSimpleExpression(dir.value.content, true, dir.value.loc) : EMPTY_EXPRESSION;
3731
- }
3732
- return () => {
3733
- const id = context.reference();
3734
- const effect = !isConstantExpression(value);
3735
- effect && context.registerOperation({
3736
- type: 14,
3737
- id
3738
- });
3739
- context.registerEffect([value], {
3740
- type: 8,
3741
- element: id,
3742
- value,
3743
- refFor: !!context.inVFor,
3744
- effect
3745
- });
3746
- };
3747
- };
3748
-
3749
- const seen = /* @__PURE__ */ new WeakMap();
3750
- function markNonTemplate(node, context) {
3751
- seen.get(context.root).add(node);
3752
- }
3753
- const transformText = (node, context) => {
3754
- if (!seen.has(context.root)) seen.set(context.root, /* @__PURE__ */ new WeakSet());
3755
- if (seen.get(context.root).has(node)) {
3756
- context.dynamic.flags |= 2;
3757
- return;
3758
- }
3759
- const isFragment = node.type === 0 || node.type === 1 && (node.tagType === 3 || node.tagType === 1);
3760
- if ((isFragment || node.type === 1 && node.tagType === 0) && node.children.length) {
3761
- let hasInterp = false;
3762
- let isAllTextLike = true;
3763
- for (const c of node.children) {
3764
- if (c.type === 5) {
3765
- hasInterp = true;
3766
- } else if (c.type !== 2) {
3767
- isAllTextLike = false;
3768
- }
3769
- }
3770
- if (!isFragment && isAllTextLike && hasInterp) {
3771
- processTextContainer(
3772
- node.children,
3773
- context
3774
- );
3775
- } else if (hasInterp) {
3776
- for (let i = 0; i < node.children.length; i++) {
3777
- const c = node.children[i];
3778
- const prev = node.children[i - 1];
3779
- if (c.type === 5 && prev && prev.type === 2) {
3780
- markNonTemplate(prev, context);
3781
- }
3782
- }
3783
- }
3784
- } else if (node.type === 5) {
3785
- processInterpolation(context);
3786
- } else if (node.type === 2) {
3787
- context.template += node.content;
3788
- }
3789
- };
3790
- function processInterpolation(context) {
3791
- const parentNode = context.parent.node;
3792
- const children = parentNode.children;
3793
- const nexts = children.slice(context.index);
3794
- const idx = nexts.findIndex((n) => !isTextLike(n));
3795
- const nodes = idx > -1 ? nexts.slice(0, idx) : nexts;
3796
- const prev = children[context.index - 1];
3797
- if (prev && prev.type === 2) {
3798
- nodes.unshift(prev);
3799
- }
3800
- const values = processTextLikeChildren(nodes, context);
3801
- if (values.length === 0 && parentNode.type !== 0) {
3802
- return;
3803
- }
3804
- context.template += " ";
3805
- const isParentText = context.options.templateMode === "factory" && context.parent && context.parent.node.type === 1 && context.parent.node.tag === "text";
3806
- const id = isParentText ? context.parent.reference() : context.reference();
3807
- if (values.length === 0) {
3808
- return;
3809
- }
3810
- const nonConstantExps = values.filter((v) => !isConstantExpression(v));
3811
- const isStatic = !nonConstantExps.length || nonConstantExps.every(
3812
- (e) => isStaticExpression(e, context.options.bindingMetadata)
3813
- ) || context.inVOnce;
3814
- if (isStatic) {
3815
- context.registerOperation({
3816
- type: 4,
3817
- element: id,
3818
- values
3819
- });
3820
- } else {
3821
- context.registerEffect(values, {
3822
- type: 4,
3823
- element: id,
3824
- values
3825
- });
3826
- }
3827
- }
3828
- function processTextContainer(children, context) {
3829
- if (context.options.templateMode === "factory") {
3830
- if (context.node.tag === "text") {
3831
- return;
3832
- }
3833
- }
3834
- const values = processTextLikeChildren(children, context);
3835
- const literals = values.map(getLiteralExpressionValue);
3836
- if (literals.every((l) => l != null)) {
3837
- context.childrenTemplate = literals.map((l) => String(l));
3838
- } else {
3839
- context.childrenTemplate = [" "];
3840
- context.registerOperation({
3841
- type: 17,
3842
- parent: context.reference()
3843
- });
3844
- context.registerEffect(values, {
3845
- type: 4,
3846
- element: context.reference(),
3847
- values,
3848
- // indicates this node is generated, so prefix should be "x" instead of "n"
3849
- generated: true
3850
- });
3851
- }
3852
- }
3853
- function processTextLikeChildren(nodes, context) {
3854
- const exps = [];
3855
- for (const node of nodes) {
3856
- let exp;
3857
- markNonTemplate(node, context);
3858
- if (node.type === 2) {
3859
- exp = compilerDom.createSimpleExpression(node.content, true, node.loc);
3860
- } else {
3861
- exp = node.content;
3862
- }
3863
- if (exp.content) exps.push(exp);
3864
- }
3865
- return exps;
3866
- }
3867
- function isTextLike(node) {
3868
- return node.type === 5 || node.type === 2;
3869
- }
3870
-
3871
- const transformVModel = (dir, node, context) => {
3872
- const { exp, arg } = dir;
3873
- if (!exp) {
3874
- context.options.onError(
3875
- compilerDom.createCompilerError(41, dir.loc)
3876
- );
3877
- return;
3878
- }
3879
- const rawExp = exp.loc.source;
3880
- const bindingType = context.options.bindingMetadata[rawExp];
3881
- if (bindingType === "props" || bindingType === "props-aliased") {
3882
- context.options.onError(
3883
- compilerDom.createCompilerError(44, exp.loc)
3884
- );
3885
- return;
3886
- }
3887
- const expString = exp.content;
3888
- const maybeRef = context.options.inline && (bindingType === "setup-let" || bindingType === "setup-ref" || bindingType === "setup-maybe-ref");
3889
- if (!expString.trim() || !compilerDom.isMemberExpression(exp, context.options) && !maybeRef) {
3890
- context.options.onError(
3891
- compilerDom.createCompilerError(42, exp.loc)
3892
- );
3893
- return;
3894
- }
3895
- const isComponent = node.tagType === 1;
3896
- if (isComponent) {
3897
- return {
3898
- key: arg ? arg : compilerDom.createSimpleExpression("modelValue", true),
3899
- value: exp,
3900
- model: true,
3901
- modelModifiers: dir.modifiers.map((m) => m.content)
3902
- };
3903
- }
3904
- if (dir.arg)
3905
- context.options.onError(
3906
- compilerDom.createDOMCompilerError(
3907
- 58,
3908
- dir.arg.loc
3909
- )
3910
- );
3911
- const { tag } = node;
3912
- const isCustomElement = context.options.isCustomElement(tag);
3913
- let modelType = "text";
3914
- if (tag === "input" || tag === "textarea" || tag === "select" || isCustomElement) {
3915
- if (tag === "input" || isCustomElement) {
3916
- const type = compilerDom.findProp(node, "type");
3917
- if (type) {
3918
- if (type.type === 7) {
3919
- modelType = "dynamic";
3920
- } else if (type.value) {
3921
- switch (type.value.content) {
3922
- case "radio":
3923
- modelType = "radio";
3924
- break;
3925
- case "checkbox":
3926
- modelType = "checkbox";
3927
- break;
3928
- case "file":
3929
- modelType = void 0;
3930
- context.options.onError(
3931
- compilerDom.createDOMCompilerError(
3932
- 59,
3933
- dir.loc
3934
- )
3935
- );
3936
- break;
3937
- default:
3938
- checkDuplicatedValue();
3939
- break;
3940
- }
3941
- }
3942
- } else if (compilerDom.hasDynamicKeyVBind(node)) {
3943
- modelType = "dynamic";
3944
- } else {
3945
- checkDuplicatedValue();
3946
- }
3947
- } else if (tag === "select") {
3948
- modelType = "select";
3949
- } else {
3950
- checkDuplicatedValue();
3951
- }
3952
- } else {
3953
- context.options.onError(
3954
- compilerDom.createDOMCompilerError(
3955
- 57,
3956
- dir.loc
3957
- )
3958
- );
3959
- }
3960
- if (modelType)
3961
- context.registerOperation({
3962
- type: 13,
3963
- element: context.reference(),
3964
- dir,
3965
- name: "model",
3966
- modelType,
3967
- builtin: true
3968
- });
3969
- function checkDuplicatedValue() {
3970
- const value = compilerDom.findDir(node, "bind");
3971
- if (value && compilerDom.isStaticArgOf(value.arg, "value")) {
3972
- context.options.onError(
3973
- compilerDom.createDOMCompilerError(
3974
- 60,
3975
- value.loc
3976
- )
3977
- );
3978
- }
3979
- }
3980
- };
3981
-
3982
- const transformComment = (node, context) => {
3983
- if (node.type !== 3) return;
3984
- if (getSiblingIf(context)) {
3985
- context.comment.push(node);
3986
- context.dynamic.flags |= 2;
3987
- } else {
3988
- context.template += `<!--${node.content}-->`;
3989
- }
3990
- };
3991
- function getSiblingIf(context, reverse) {
3992
- const parent = context.parent;
3993
- if (!parent) return;
3994
- const siblings = parent.node.children;
3995
- let sibling;
3996
- let i = siblings.indexOf(context.node);
3997
- while (reverse ? --i >= 0 : ++i < siblings.length) {
3998
- sibling = siblings[i];
3999
- if (!isCommentLike(sibling)) {
4000
- break;
4001
- }
4002
- }
4003
- if (sibling && sibling.type === 1 && sibling.props.some(
4004
- ({ type, name }) => type === 7 && ["else-if", reverse ? "if" : "else"].includes(name)
4005
- )) {
4006
- return sibling;
4007
- }
4008
- }
4009
- function isCommentLike(node) {
4010
- return node.type === 3 || node.type === 2 && !node.content.trim().length;
4011
- }
4012
-
4013
- const transformVIf = createStructuralDirectiveTransform(
4014
- ["if", "else", "else-if"],
4015
- processIf
4016
- );
4017
- function processIf(node, dir, context) {
4018
- if (dir.name !== "else" && (!dir.exp || !dir.exp.content.trim())) {
4019
- const loc = dir.exp ? dir.exp.loc : node.loc;
4020
- context.options.onError(
4021
- compilerDom.createCompilerError(28, dir.loc)
4022
- );
4023
- dir.exp = compilerDom.createSimpleExpression(`true`, false, loc);
4024
- }
4025
- context.dynamic.flags |= 2;
4026
- if (dir.name === "if") {
4027
- const id = context.reference();
4028
- context.dynamic.flags |= 4;
4029
- const [branch, onExit] = createIfBranch(node, context);
4030
- return () => {
4031
- onExit();
4032
- context.dynamic.operation = {
4033
- type: 15,
4034
- id,
4035
- condition: dir.exp,
4036
- positive: branch,
4037
- once: context.inVOnce || isStaticExpression(dir.exp, context.options.bindingMetadata)
4038
- };
4039
- };
4040
- } else {
4041
- const siblingIf = getSiblingIf(context, true);
4042
- const siblings = context.parent && context.parent.dynamic.children;
4043
- let lastIfNode;
4044
- if (siblings) {
4045
- let i = siblings.length;
4046
- while (i--) {
4047
- if (siblings[i].operation && siblings[i].operation.type === 15) {
4048
- lastIfNode = siblings[i].operation;
4049
- break;
4050
- }
4051
- }
4052
- }
4053
- if (
4054
- // check if v-if is the sibling node
4055
- !siblingIf || // check if IfNode is the last operation and get the root IfNode
4056
- !lastIfNode || lastIfNode.type !== 15
4057
- ) {
4058
- context.options.onError(
4059
- compilerDom.createCompilerError(30, node.loc)
4060
- );
4061
- return;
4062
- }
4063
- while (lastIfNode.negative && lastIfNode.negative.type === 15) {
4064
- lastIfNode = lastIfNode.negative;
4065
- }
4066
- if (dir.name === "else-if" && lastIfNode.negative) {
4067
- context.options.onError(
4068
- compilerDom.createCompilerError(30, node.loc)
4069
- );
4070
- }
4071
- if (context.root.comment.length) {
4072
- node = wrapTemplate(node, ["else-if", "else"]);
4073
- context.node = node = shared.extend({}, node, {
4074
- children: [...context.comment, ...node.children]
4075
- });
4076
- }
4077
- context.root.comment = [];
4078
- const [branch, onExit] = createIfBranch(node, context);
4079
- if (dir.name === "else") {
4080
- lastIfNode.negative = branch;
4081
- } else {
4082
- lastIfNode.negative = {
4083
- type: 15,
4084
- id: -1,
4085
- condition: dir.exp,
4086
- positive: branch,
4087
- once: context.inVOnce
4088
- };
4089
- }
4090
- return () => onExit();
4091
- }
4092
- }
4093
- function createIfBranch(node, context) {
4094
- context.node = node = wrapTemplate(node, ["if", "else-if", "else"]);
4095
- const branch = newBlock(node);
4096
- const exitBlock = context.enterBlock(branch);
4097
- context.reference();
4098
- return [branch, exitBlock];
4099
- }
4100
-
4101
- const transformVFor = createStructuralDirectiveTransform(
4102
- "for",
4103
- processFor
4104
- );
4105
- function processFor(node, dir, context) {
4106
- if (!dir.exp) {
4107
- context.options.onError(
4108
- compilerDom.createCompilerError(31, dir.loc)
4109
- );
4110
- return;
4111
- }
4112
- const parseResult = dir.forParseResult;
4113
- if (!parseResult) {
4114
- context.options.onError(
4115
- compilerDom.createCompilerError(32, dir.loc)
4116
- );
4117
- return;
4118
- }
4119
- const { source, value, key, index } = parseResult;
4120
- const keyProp = findProp(node, "key");
4121
- const keyProperty = keyProp && propToExpression(keyProp);
4122
- const isComponent = node.tagType === 1;
4123
- context.node = node = wrapTemplate(node, ["for"]);
4124
- context.dynamic.flags |= 2 | 4;
4125
- const id = context.reference();
4126
- const render = newBlock(node);
4127
- const exitBlock = context.enterBlock(render, true);
4128
- context.reference();
4129
- return () => {
4130
- exitBlock();
4131
- const { parent } = context;
4132
- const isOnlyChild = parent && parent.block.node !== parent.node && parent.node.children.length === 1;
4133
- context.dynamic.operation = {
4134
- type: 16,
4135
- id,
4136
- source,
4137
- value,
4138
- key,
4139
- index,
4140
- keyProp: keyProperty,
4141
- render,
4142
- once: context.inVOnce || isStaticExpression(
4143
- source,
4144
- context.options.bindingMetadata
4145
- ),
4146
- component: isComponent,
4147
- onlyChild: !!isOnlyChild
4148
- };
4149
- };
4150
- }
4151
-
4152
- const transformSlotOutlet = (node, context) => {
4153
- if (node.type !== 1 || node.tag !== "slot") {
4154
- return;
4155
- }
4156
- const id = context.reference();
4157
- context.dynamic.flags |= 4 | 2;
4158
- const [fallback, exitBlock] = createFallback(
4159
- node,
4160
- context
4161
- );
4162
- let slotName;
4163
- const slotProps = [];
4164
- for (const prop of node.props) {
4165
- if (prop.type === 6) {
4166
- if (prop.value) {
4167
- if (prop.name === "name") {
4168
- slotName = compilerDom.createSimpleExpression(prop.value.content, true, prop.loc);
4169
- } else {
4170
- slotProps.push(shared.extend({}, prop, { name: shared.camelize(prop.name) }));
4171
- }
4172
- }
4173
- } else if (prop.name === "bind" && compilerDom.isStaticArgOf(prop.arg, "name")) {
4174
- if (prop.exp) {
4175
- slotName = prop.exp;
4176
- } else {
4177
- slotName = compilerDom.createSimpleExpression(
4178
- shared.camelize(prop.arg.content),
4179
- false,
4180
- prop.arg.loc
4181
- );
4182
- slotName.ast = null;
4183
- }
4184
- } else {
4185
- let slotProp = prop;
4186
- if (slotProp.name === "bind" && slotProp.arg && compilerDom.isStaticExp(slotProp.arg)) {
4187
- slotProp = shared.extend({}, prop, {
4188
- arg: shared.extend({}, slotProp.arg, {
4189
- content: shared.camelize(slotProp.arg.content)
4190
- })
4191
- });
4192
- }
4193
- slotProps.push(slotProp);
4194
- }
4195
- }
4196
- slotName || (slotName = compilerDom.createSimpleExpression("default", true));
4197
- let irProps = [];
4198
- if (slotProps.length) {
4199
- const [isDynamic, props] = buildProps(
4200
- shared.extend({}, node, { props: slotProps }),
4201
- context,
4202
- true
4203
- );
4204
- irProps = isDynamic ? props : [props];
4205
- const runtimeDirective = context.block.operation.find(
4206
- (oper) => oper.type === 13 && oper.element === id
4207
- );
4208
- if (runtimeDirective) {
4209
- context.options.onError(
4210
- compilerDom.createCompilerError(
4211
- 36,
4212
- runtimeDirective.dir.loc
4213
- )
4214
- );
4215
- }
4216
- }
4217
- return () => {
4218
- exitBlock && exitBlock();
4219
- context.dynamic.operation = {
4220
- type: 12,
4221
- id,
4222
- name: slotName,
4223
- props: irProps,
4224
- fallback
4225
- };
4226
- };
4227
- };
4228
- function createFallback(node, context) {
4229
- if (!node.children.length) {
4230
- return [];
4231
- }
4232
- context.node = node = shared.extend({}, node, {
4233
- type: 1,
4234
- tag: "template",
4235
- props: [],
4236
- tagType: 3,
4237
- children: node.children
4238
- });
4239
- const fallback = newBlock(node);
4240
- const exitBlock = context.enterBlock(fallback);
4241
- context.reference();
4242
- return [fallback, exitBlock];
4243
- }
4244
-
4245
- const transformVSlot = (node, context) => {
4246
- if (node.type !== 1) return;
4247
- const dir = findDir(node, "slot", true);
4248
- const { tagType, children } = node;
4249
- const { parent } = context;
4250
- const isComponent = tagType === 1;
4251
- const isSlotTemplate = compilerDom.isTemplateNode(node) && parent && parent.node.type === 1 && parent.node.tagType === 1;
4252
- if (isComponent && children.length) {
4253
- return transformComponentSlot(
4254
- node,
4255
- dir,
4256
- context
4257
- );
4258
- } else if (isSlotTemplate && dir) {
4259
- return transformTemplateSlot(
4260
- node,
4261
- dir,
4262
- context
4263
- );
4264
- } else if (!isComponent && dir) {
4265
- context.options.onError(
4266
- compilerDom.createCompilerError(40, dir.loc)
4267
- );
4268
- }
4269
- };
4270
- function transformComponentSlot(node, dir, context) {
4271
- const { children } = node;
4272
- const arg = dir && dir.arg;
4273
- const emptyTextNodes = [];
4274
- const nonSlotTemplateChildren = children.filter((n) => {
4275
- if (isNonWhitespaceContent(n)) {
4276
- return !(n.type === 1 && n.props.some(compilerDom.isVSlot));
4277
- } else {
4278
- emptyTextNodes.push(n);
4279
- }
4280
- });
4281
- if (!nonSlotTemplateChildren.length) {
4282
- emptyTextNodes.forEach((n) => {
4283
- markNonTemplate(n, context);
4284
- });
4285
- }
4286
- const [block, onExit] = createSlotBlock(node, dir, context);
4287
- const { slots } = context;
4288
- return () => {
4289
- onExit();
4290
- const hasOtherSlots = !!slots.length;
4291
- if (dir && hasOtherSlots) {
4292
- context.options.onError(
4293
- compilerDom.createCompilerError(37, dir.loc)
4294
- );
4295
- return;
4296
- }
4297
- if (nonSlotTemplateChildren.length) {
4298
- if (hasStaticSlot(slots, "default")) {
4299
- context.options.onError(
4300
- compilerDom.createCompilerError(
4301
- 39,
4302
- nonSlotTemplateChildren[0].loc
4303
- )
4304
- );
4305
- } else {
4306
- registerSlot(slots, arg, block);
4307
- context.slots = slots;
4308
- }
4309
- } else if (hasOtherSlots) {
4310
- context.slots = slots;
4311
- }
4312
- };
4313
- }
4314
- function transformTemplateSlot(node, dir, context) {
4315
- context.dynamic.flags |= 2;
4316
- const arg = dir.arg && resolveExpression(dir.arg);
4317
- const vFor = findDir(node, "for");
4318
- const vIf = findDir(node, "if");
4319
- const vElse = findDir(
4320
- node,
4321
- /^else(-if)?$/,
4322
- true
4323
- /* allowEmpty */
4324
- );
4325
- const { slots } = context;
4326
- const [block, onExit] = createSlotBlock(node, dir, context);
4327
- if (!vFor && !vIf && !vElse) {
4328
- const slotName = arg ? arg.isStatic && arg.content : "default";
4329
- if (slotName && hasStaticSlot(slots, slotName)) {
4330
- context.options.onError(
4331
- compilerDom.createCompilerError(38, dir.loc)
4332
- );
4333
- } else {
4334
- registerSlot(slots, arg, block);
4335
- }
4336
- } else if (vIf) {
4337
- registerDynamicSlot(slots, {
4338
- slotType: 3,
4339
- condition: vIf.exp,
4340
- positive: {
4341
- slotType: 1,
4342
- name: arg,
4343
- fn: block
4344
- }
4345
- });
4346
- } else if (vElse) {
4347
- const vIfSlot = slots[slots.length - 1];
4348
- if (vIfSlot.slotType === 3) {
4349
- let ifNode = vIfSlot;
4350
- while (ifNode.negative && ifNode.negative.slotType === 3)
4351
- ifNode = ifNode.negative;
4352
- const negative = vElse.exp ? {
4353
- slotType: 3,
4354
- condition: vElse.exp,
4355
- positive: {
4356
- slotType: 1,
4357
- name: arg,
4358
- fn: block
4359
- }
4360
- } : {
4361
- slotType: 1,
4362
- name: arg,
4363
- fn: block
4364
- };
4365
- ifNode.negative = negative;
4366
- } else {
4367
- context.options.onError(
4368
- compilerDom.createCompilerError(30, vElse.loc)
4369
- );
4370
- }
4371
- } else if (vFor) {
4372
- if (vFor.forParseResult) {
4373
- registerDynamicSlot(slots, {
4374
- slotType: 2,
4375
- name: arg,
4376
- fn: block,
4377
- loop: vFor.forParseResult
4378
- });
4379
- } else {
4380
- context.options.onError(
4381
- compilerDom.createCompilerError(32, vFor.loc)
4382
- );
4383
- }
4384
- }
4385
- return onExit;
4386
- }
4387
- function ensureStaticSlots(slots) {
4388
- let lastSlots = slots[slots.length - 1];
4389
- if (!slots.length || lastSlots.slotType !== 0) {
4390
- slots.push(
4391
- lastSlots = {
4392
- slotType: 0,
4393
- slots: {}
4394
- }
4395
- );
4396
- }
4397
- return lastSlots.slots;
4398
- }
4399
- function registerSlot(slots, name, block) {
4400
- const isStatic = !name || name.isStatic;
4401
- if (isStatic) {
4402
- const staticSlots = ensureStaticSlots(slots);
4403
- staticSlots[name ? name.content : "default"] = block;
4404
- } else {
4405
- slots.push({
4406
- slotType: 1,
4407
- name,
4408
- fn: block
4409
- });
4410
- }
4411
- }
4412
- function registerDynamicSlot(allSlots, dynamic) {
4413
- allSlots.push(dynamic);
4414
- }
4415
- function hasStaticSlot(slots, name) {
4416
- return slots.some((slot) => {
4417
- if (slot.slotType === 0) return !!slot.slots[name];
4418
- });
4419
- }
4420
- function createSlotBlock(slotNode, dir, context) {
4421
- const block = newBlock(slotNode);
4422
- block.props = dir && dir.exp;
4423
- const exitBlock = context.enterBlock(block);
4424
- return [block, exitBlock];
4425
- }
4426
- function isNonWhitespaceContent(node) {
4427
- if (node.type !== 2) return true;
4428
- return !!node.content.trim();
4429
- }
4430
-
4431
- function compile(source, options = {}) {
4432
- const resolvedOptions = shared.extend({}, options);
4433
- const ast = shared.isString(source) ? compilerDom.parse(source, resolvedOptions) : source;
4434
- const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
4435
- if (options.isTS) {
4436
- const { expressionPlugins } = options;
4437
- if (!expressionPlugins || !expressionPlugins.includes("typescript")) {
4438
- resolvedOptions.expressionPlugins = [
4439
- ...expressionPlugins || [],
4440
- "typescript"
4441
- ];
4442
- }
4443
- }
4444
- const ir = transform(
4445
- ast,
4446
- shared.extend({}, resolvedOptions, {
4447
- nodeTransforms: [
4448
- ...nodeTransforms,
4449
- ...options.nodeTransforms || []
4450
- // user transforms
4451
- ],
4452
- directiveTransforms: shared.extend(
4453
- {},
4454
- directiveTransforms,
4455
- options.directiveTransforms || {}
4456
- // user transforms
4457
- )
4458
- })
4459
- );
4460
- return generate(ir, resolvedOptions);
4461
- }
4462
- function getBaseTransformPreset() {
4463
- return [
4464
- [
4465
- transformVOnce,
4466
- transformVIf,
4467
- transformVFor,
4468
- transformSlotOutlet,
4469
- transformTemplateRef,
4470
- transformElement,
4471
- transformText,
4472
- transformVSlot,
4473
- transformComment,
4474
- transformChildren
4475
- ],
4476
- {
4477
- bind: transformVBind,
4478
- on: transformVOn,
4479
- html: transformVHtml,
4480
- text: transformVText,
4481
- show: transformVShow,
4482
- model: transformVModel
4483
- }
4484
- ];
4485
- }
4486
-
4487
- function createVaporCompilerError(code, loc) {
4488
- return compilerDom.createCompilerError(
4489
- code,
4490
- loc,
4491
- VaporErrorMessages
4492
- );
4493
- }
4494
- const VaporErrorCodes = {
4495
- "X_V_PLACEHOLDER": 100,
4496
- "100": "X_V_PLACEHOLDER",
4497
- "__EXTEND_POINT__": 101,
4498
- "101": "__EXTEND_POINT__"
4499
- };
4500
- const VaporErrorMessages = {
4501
- [100]: `[placeholder]`,
4502
- // just to fulfill types
4503
- [101]: ``
4504
- };
4505
-
4506
- exports.parse = compilerDom.parse;
4507
- exports.CodegenContext = CodegenContext;
4508
- exports.DynamicFlag = DynamicFlag;
4509
- exports.IRDynamicPropsKind = IRDynamicPropsKind;
4510
- exports.IRNodeTypes = IRNodeTypes;
4511
- exports.IRSlotType = IRSlotType;
4512
- exports.VaporErrorCodes = VaporErrorCodes;
4513
- exports.VaporErrorMessages = VaporErrorMessages;
4514
- exports.buildCodeFragment = buildCodeFragment;
4515
- exports.codeFragmentToString = codeFragmentToString;
4516
- exports.compile = compile;
4517
- exports.createStructuralDirectiveTransform = createStructuralDirectiveTransform;
4518
- exports.createVaporCompilerError = createVaporCompilerError;
4519
- exports.genCall = genCall;
4520
- exports.genMulti = genMulti;
4521
- exports.generate = generate;
4522
- exports.isBlockOperation = isBlockOperation;
4523
- exports.transform = transform;
4524
- exports.transformChildren = transformChildren;
4525
- exports.transformComment = transformComment;
4526
- exports.transformElement = transformElement;
4527
- exports.transformSlotOutlet = transformSlotOutlet;
4528
- exports.transformTemplateRef = transformTemplateRef;
4529
- exports.transformText = transformText;
4530
- exports.transformVBind = transformVBind;
4531
- exports.transformVFor = transformVFor;
4532
- exports.transformVHtml = transformVHtml;
4533
- exports.transformVIf = transformVIf;
4534
- exports.transformVModel = transformVModel;
4535
- exports.transformVOn = transformVOn;
4536
- exports.transformVOnce = transformVOnce;
4537
- exports.transformVShow = transformVShow;
4538
- exports.transformVSlot = transformVSlot;
4539
- exports.transformVText = transformVText;
4540
- exports.wrapTemplate = wrapTemplate;