babel-plugin-essor 0.0.14 → 0.0.15-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,747 +1,2315 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
2
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
4
6
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
7
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
- var __spreadValues = (a, b) => {
8
+ var __spreadValues = (a2, b) => {
7
9
  for (var prop in b || (b = {}))
8
10
  if (__hasOwnProp.call(b, prop))
9
- __defNormalProp(a, prop, b[prop]);
11
+ __defNormalProp(a2, prop, b[prop]);
10
12
  if (__getOwnPropSymbols)
11
13
  for (var prop of __getOwnPropSymbols(b)) {
12
14
  if (__propIsEnum.call(b, prop))
13
- __defNormalProp(a, prop, b[prop]);
15
+ __defNormalProp(a2, prop, b[prop]);
14
16
  }
15
- return a;
17
+ return a2;
16
18
  };
19
+ var __spreadProps = (a2, b) => __defProps(a2, __getOwnPropDescs(b));
17
20
 
18
- // src/jsx/index.ts
21
+ // src/program.ts
22
+ import { types as t4 } from "@babel/core";
23
+
24
+ // src/import.ts
25
+ import { types as t } from "@babel/core";
26
+
27
+ // ../shared/dist/shared.esm.js
28
+ var w = (e) => e !== null && typeof e == "object";
29
+ var d = Array.isArray;
30
+ function m(e) {
31
+ return typeof e == "string";
32
+ }
33
+ function T(e) {
34
+ return typeof e == "number";
35
+ }
36
+ function y(e) {
37
+ return e === null;
38
+ }
39
+ function A(e) {
40
+ return typeof e == "symbol";
41
+ }
42
+ function E(e) {
43
+ return a.call(e) === "[object Map]";
44
+ }
45
+ function N(e) {
46
+ return e == null;
47
+ }
48
+ var j = (e) => ["string", "number", "boolean", "symbol", "undefined"].includes(typeof e) || y(e);
49
+ var P = (e) => a.call(e) === "[object Object]";
50
+ function _(e) {
51
+ return typeof e == "undefined";
52
+ }
53
+ function z(e) {
54
+ return typeof e == "boolean";
55
+ }
56
+ var a = Object.prototype.toString;
57
+ function G(e) {
58
+ return d(e) ? e : [e];
59
+ }
60
+ var V = Function.prototype;
61
+ function q(e, t10) {
62
+ return m(e) ? e.indexOf(t10) === 0 : false;
63
+ }
64
+ var u = (e) => {
65
+ let t10 = /* @__PURE__ */ Object.create(null);
66
+ return ((n) => t10[n] || (t10[n] = e(n)));
67
+ };
68
+ var W = Object.freeze({});
69
+ var Y = Object.freeze([]);
70
+ var J = /\B([A-Z])/g;
71
+ var Z = u((e) => e.replaceAll(J, "-$1").toLowerCase());
72
+ var Q = /[_-](\w)/g;
73
+ var ee = u((e) => (e = e.replaceAll(/^[_-]+|[_-]+$/g, ""), e = e.replaceAll(/[_-]+/g, "-"), e.replaceAll(Q, (t10, n) => n.toUpperCase())));
74
+ var te = u((e) => e.charAt(0).toUpperCase() + e.slice(1));
75
+ function ne(e, ...t10) {
76
+ console.warn(`[Essor warn]: ${e}`, ...t10);
77
+ }
78
+ function h(e, ...t10) {
79
+ console.error(`[Essor error]: ${e}`, ...t10);
80
+ }
81
+ function o(e) {
82
+ let t10 = /* @__PURE__ */ Object.create(null);
83
+ for (let n of e.split(",")) t10[n] = 1;
84
+ return (n) => n in t10;
85
+ }
86
+ var x = "itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly";
87
+ var pe = o(x);
88
+ var ue = o(`${x},async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`);
89
+ var he = o("accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap");
90
+ var be = o("xmlns,accent-height,accumulate,additive,alignment-baseline,alphabetic,amplitude,arabic-form,ascent,attributeName,attributeType,azimuth,baseFrequency,baseline-shift,baseProfile,bbox,begin,bias,by,calcMode,cap-height,class,clip,clipPathUnits,clip-path,clip-rule,color,color-interpolation,color-interpolation-filters,color-profile,color-rendering,contentScriptType,contentStyleType,crossorigin,cursor,cx,cy,d,decelerate,descent,diffuseConstant,direction,display,divisor,dominant-baseline,dur,dx,dy,edgeMode,elevation,enable-background,end,exponent,fill,fill-opacity,fill-rule,filter,filterRes,filterUnits,flood-color,flood-opacity,font-family,font-size,font-size-adjust,font-stretch,font-style,font-variant,font-weight,format,from,fr,fx,fy,g1,g2,glyph-name,glyph-orientation-horizontal,glyph-orientation-vertical,glyphRef,gradientTransform,gradientUnits,hanging,height,href,hreflang,horiz-adv-x,horiz-origin-x,id,ideographic,image-rendering,in,in2,intercept,k,k1,k2,k3,k4,kernelMatrix,kernelUnitLength,kerning,keyPoints,keySplines,keyTimes,lang,lengthAdjust,letter-spacing,lighting-color,limitingConeAngle,local,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mask,maskContentUnits,maskUnits,mathematical,max,media,method,min,mode,name,numOctaves,offset,opacity,operator,order,orient,orientation,origin,overflow,overline-position,overline-thickness,panose-1,paint-order,path,pathLength,patternContentUnits,patternTransform,patternUnits,ping,pointer-events,points,pointsAtX,pointsAtY,pointsAtZ,preserveAlpha,preserveAspectRatio,primitiveUnits,r,radius,referrerPolicy,refX,refY,rel,rendering-intent,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,result,rotate,rx,ry,scale,seed,shape-rendering,slope,spacing,specularConstant,specularExponent,speed,spreadMethod,startOffset,stdDeviation,stemh,stemv,stitchTiles,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,string,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,style,surfaceScale,systemLanguage,tabindex,tableValues,target,targetX,targetY,text-anchor,text-decoration,text-rendering,textLength,to,transform,transform-origin,type,u1,u2,underline-position,underline-thickness,unicode,unicode-bidi,unicode-range,units-per-em,v-alphabetic,v-hanging,v-ideographic,v-mathematical,values,vector-effect,version,vert-adv-y,vert-origin-x,vert-origin-y,viewBox,viewTarget,visibility,width,widths,word-spacing,writing-mode,x,x-height,x1,x2,xChannelSelector,xlink:actuate,xlink:arcrole,xlink:href,xlink:role,xlink:show,xlink:title,xlink:type,xmlns:xlink,xml:base,xml:lang,xml:space,y,y1,y2,yChannelSelector,z,zoomAndPan");
91
+ var ke = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot";
92
+ var xe = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view";
93
+ var we = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics";
94
+ var ve = "beforeinput,click,dblclick,contextmenu,focusin,focusout,input,keydown,keyup,mousedown,mousemove,mouseout,mouseover,mouseup,pointerdown,pointermove,pointerout,pointerover,pointerup,touchend,touchmove,touchstart";
95
+ var Te = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr";
96
+ var Ae = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr";
97
+ var Se = o(ke);
98
+ var Me = o(xe);
99
+ var Ce = o(we);
100
+ var Ee = o(Te);
101
+ var Ne = o(Ae);
102
+ var Oe = o(ve);
103
+
104
+ // src/constants.ts
105
+ var DEFAULT_OPTIONS = {
106
+ mode: "client",
107
+ symbol: "$",
108
+ props: true,
109
+ hmr: false,
110
+ styled: false
111
+ };
112
+ var IMPORTS_MAPS = [
113
+ // Reactive API
114
+ "signal",
115
+ "computed",
116
+ "reactive",
117
+ "memoEffect",
118
+ "omitProps",
119
+ // component
120
+ "createComponent",
121
+ "Fragment",
122
+ "For",
123
+ "Suspense",
124
+ "Portal",
125
+ // Template related
126
+ "mapNodes",
127
+ "template",
128
+ "delegateEvents",
129
+ // styled
130
+ "styled",
131
+ // binding related
132
+ "insert",
133
+ "patchStyle",
134
+ "patchClass",
135
+ "patchAttr",
136
+ "bindElement",
137
+ "setSpread",
138
+ "addEventListener",
139
+ // rendering related
140
+ "render",
141
+ "escapeHTML",
142
+ "getHydrationKey"
143
+ ];
144
+ var SSG_IMPORTS_MAPS = {
145
+ createComponent: "createSSGComponent",
146
+ patchAttr: "setSSGAttr"
147
+ };
148
+ var SSR_IMPORTS_MAPS = {
149
+ mapNodes: "mapSSRNodes",
150
+ template: "getElement"
151
+ };
152
+ var TRANSFORM_PROPERTY_NAME = "__props";
153
+
154
+ // src/import.ts
155
+ function createImportIdentifiers(path) {
156
+ const identifiers = IMPORTS_MAPS.reduce((acc, name) => {
157
+ var _a, _b;
158
+ const identifier = (_b = (_a = path.scope) == null ? void 0 : _a.generateUidIdentifier(`${name}$`)) != null ? _b : t.identifier(`${name}$`);
159
+ if (!identifier) {
160
+ throw new Error(`Failed to generate identifier for ${name}`);
161
+ }
162
+ acc[name] = identifier;
163
+ return acc;
164
+ }, {});
165
+ return identifiers;
166
+ }
167
+ var importMap = IMPORTS_MAPS.reduce(
168
+ (acc, name) => __spreadProps(__spreadValues({}, acc), { [name]: name }),
169
+ {}
170
+ );
171
+ var importedSets = /* @__PURE__ */ new Set();
172
+ function addImport(name) {
173
+ importedSets.add(name);
174
+ }
175
+ function clearImport() {
176
+ importedSets.clear();
177
+ }
178
+ function createImport(path, imports, from) {
179
+ const state = path.state;
180
+ const mode = state.opts.mode;
181
+ if (!importedSets.size) {
182
+ return;
183
+ }
184
+ try {
185
+ const importSpecifiers = Array.from(importedSets).map((name) => {
186
+ const importIdentifier = imports[name];
187
+ if (!importIdentifier) {
188
+ throw new Error(`Import identifier not found for: ${name}`);
189
+ }
190
+ const local = t.identifier(importIdentifier.name);
191
+ if (mode === "ssg" /* SSG */) {
192
+ name = SSG_IMPORTS_MAPS[name] || name;
193
+ }
194
+ if (mode === "ssr" /* SSR */) {
195
+ name = SSR_IMPORTS_MAPS[name] || name;
196
+ }
197
+ const imported = t.identifier(name);
198
+ return t.importSpecifier(local, imported);
199
+ });
200
+ const importDeclaration = t.importDeclaration(importSpecifiers, t.stringLiteral(from));
201
+ path.node.body.unshift(importDeclaration);
202
+ } catch (error_) {
203
+ h("Failed to create import declaration:", h);
204
+ throw error_;
205
+ }
206
+ }
207
+
208
+ // src/signals/symbol.ts
19
209
  import { types as t3 } from "@babel/core";
20
210
 
21
- // ../shared/dist/shared.js
22
- var isArray = Array.isArray;
23
- function isString(val) {
24
- return typeof val === "string";
25
- }
26
- var noop = Function.prototype;
27
- function startsWith(str, searchString) {
28
- if (!isString(str)) {
211
+ // src/signals/utils.ts
212
+ import { types as t2 } from "@babel/core";
213
+ function isValidPath(path) {
214
+ return !!(path && path.node);
215
+ }
216
+ function isJSXNode(node) {
217
+ return !!(node && (t2.isJSXElement(node) || t2.isJSXFragment(node)));
218
+ }
219
+ function mightReturnJSX(expr) {
220
+ if (isJSXNode(expr)) {
221
+ return true;
222
+ }
223
+ if (t2.isConditionalExpression(expr)) {
224
+ return mightReturnJSX(expr.consequent) || mightReturnJSX(expr.alternate);
225
+ }
226
+ if (t2.isLogicalExpression(expr)) {
227
+ return mightReturnJSX(expr.left) || mightReturnJSX(expr.right);
228
+ }
229
+ if (t2.isSequenceExpression(expr)) {
230
+ return expr.expressions.some(mightReturnJSX);
231
+ }
232
+ if (t2.isParenthesizedExpression(expr)) {
233
+ return mightReturnJSX(expr.expression);
234
+ }
235
+ return false;
236
+ }
237
+ function checkHasJSXReturn(path) {
238
+ if (!isValidPath(path)) return false;
239
+ try {
240
+ const body = path.get("body");
241
+ if (!isValidPath(body)) return false;
242
+ if (!t2.isBlockStatement(body.node)) {
243
+ return mightReturnJSX(body.node);
244
+ }
245
+ let hasJSX = false;
246
+ body.traverse({
247
+ "ReturnStatement": function(returnPath) {
248
+ if (!hasJSX && returnPath.node.argument && mightReturnJSX(returnPath.node.argument)) {
249
+ hasJSX = true;
250
+ returnPath.stop();
251
+ }
252
+ },
253
+ "FunctionDeclaration|FunctionExpression|ArrowFunctionExpression": (nestedPath) => {
254
+ nestedPath.skip();
255
+ }
256
+ });
257
+ return hasJSX;
258
+ } catch (e) {
29
259
  return false;
30
260
  }
31
- return str.indexOf(searchString) === 0;
32
261
  }
33
- var cacheStringFunction = (fn) => {
34
- const cache = /* @__PURE__ */ Object.create(null);
35
- return (str) => {
36
- const hit = cache[str];
37
- return hit || (cache[str] = fn(str));
38
- };
39
- };
40
- var hyphenateRE = /\B([A-Z])/g;
41
- var kebabCase = cacheStringFunction(
42
- (str) => str.replaceAll(hyphenateRE, "-$1").toLowerCase()
43
- );
44
- var camelizeRE = /-(\w)/g;
45
- var camelCase = cacheStringFunction((str) => {
46
- return str.replaceAll(camelizeRE, (_, c) => c ? c.toUpperCase() : "");
47
- });
48
- var capitalize = cacheStringFunction(
49
- (str) => {
50
- return str.charAt(0).toUpperCase() + str.slice(1);
262
+ function isMemberAccessingProperty(node, propertyName) {
263
+ if (!node.computed && t2.isIdentifier(node.property) && node.property.name === propertyName) {
264
+ return true;
51
265
  }
52
- );
266
+ if (node.computed && t2.isStringLiteral(node.property) && node.property.value === propertyName) {
267
+ return true;
268
+ }
269
+ return false;
270
+ }
271
+
272
+ // src/signals/symbol.ts
273
+ function isSignal(name) {
274
+ return !!name && name.startsWith("$");
275
+ }
276
+ function replaceSymbol(path) {
277
+ const { init, id } = path.node;
278
+ if (!t3.isIdentifier(id)) {
279
+ return;
280
+ }
281
+ const variableName = id.name;
282
+ if (!isSignal(variableName)) {
283
+ return;
284
+ }
285
+ if (isAlreadySignalCall(init)) {
286
+ return;
287
+ }
288
+ const isComputed = init && (t3.isFunctionExpression(init) || t3.isArrowFunctionExpression(init)) && path.parent.kind === "const";
289
+ const importName = isComputed ? "computed" : "signal";
290
+ const state = path.state;
291
+ const args = init ? [init] : [];
292
+ const newInit = t3.callExpression(t3.identifier(state.imports[importName].name), args);
293
+ addImport(importName);
294
+ path.node.init = newInit;
295
+ }
296
+ function isAlreadySignalCall(init) {
297
+ if (!init || !t3.isCallExpression(init) || !t3.isIdentifier(init.callee)) {
298
+ return false;
299
+ }
300
+ const calleeName = init.callee.name;
301
+ return calleeName === "signal" || calleeName === "computed" || calleeName.includes("signal") || calleeName.includes("computed");
302
+ }
303
+ function symbolIdentifier(path) {
304
+ if (!isValidPath(path)) {
305
+ return;
306
+ }
307
+ const name = path.node.name;
308
+ if (!isSignal(name)) {
309
+ return;
310
+ }
311
+ if (!shouldProcessIdentifier(path, path.parentPath)) {
312
+ return;
313
+ }
314
+ if (isAlreadyValueAccess(path)) {
315
+ return;
316
+ }
317
+ const parent = path.parent;
318
+ if (t3.isMemberExpression(parent) && parent.property === path.node) {
319
+ return;
320
+ }
321
+ path.replaceWith(t3.memberExpression(t3.identifier(name), t3.identifier("value")));
322
+ }
323
+ function shouldProcessIdentifier(path, parentPath) {
324
+ if (!parentPath) {
325
+ return false;
326
+ }
327
+ const parent = parentPath.node;
328
+ const currentNode = path.node;
329
+ if (t3.isVariableDeclarator(parent) || t3.isArrayPattern(parent) || t3.isObjectPattern(parent)) {
330
+ return false;
331
+ }
332
+ if (t3.isImportSpecifier(parent) || t3.isImportDefaultSpecifier(parent) || t3.isImportNamespaceSpecifier(parent)) {
333
+ return false;
334
+ }
335
+ if (t3.isFunctionDeclaration(parent) || t3.isFunctionExpression(parent) || t3.isArrowFunctionExpression(parent)) {
336
+ return false;
337
+ }
338
+ if (t3.isClassDeclaration(parent) && parent.id === currentNode) {
339
+ return false;
340
+ }
341
+ if (t3.isObjectMethod(parent) || t3.isClassMethod(parent)) {
342
+ return false;
343
+ }
344
+ if (t3.isObjectProperty(parent) && parent.key === currentNode) {
345
+ return false;
346
+ }
347
+ if (t3.isLabeledStatement(parent) && parent.label === currentNode) {
348
+ return false;
349
+ }
350
+ if ((t3.isBreakStatement(parent) || t3.isContinueStatement(parent)) && parent.label === currentNode) {
351
+ return false;
352
+ }
353
+ return true;
354
+ }
355
+ function isAlreadyValueAccess(path) {
356
+ const parent = path.parent;
357
+ if (t3.isMemberExpression(parent) && parent.object === path.node) {
358
+ return isMemberAccessingProperty(parent, "value");
359
+ }
360
+ if (!t3.isParenthesizedExpression(parent) && !t3.isTSAsExpression(parent) && !t3.isTSNonNullExpression(parent)) {
361
+ return false;
362
+ }
363
+ const ancestorCheck = path.findParent((p) => {
364
+ if (!p.isMemberExpression()) {
365
+ return false;
366
+ }
367
+ const memberExpr = p.node;
368
+ return memberExpr.object === path.node && isMemberAccessingProperty(memberExpr, "value");
369
+ });
370
+ return !!ancestorCheck;
371
+ }
372
+ function symbolAssignment(path) {
373
+ if (!isValidPath(path)) {
374
+ return;
375
+ }
376
+ const { left } = path.node;
377
+ if (!t3.isIdentifier(left)) {
378
+ return;
379
+ }
380
+ const name = left.name;
381
+ if (!isSignal(name)) {
382
+ return;
383
+ }
384
+ if (isAlreadyValueAssignment(left)) {
385
+ return;
386
+ }
387
+ path.node.left = t3.memberExpression(t3.identifier(name), t3.identifier("value"));
388
+ }
389
+ function isAlreadyValueAssignment(left) {
390
+ return t3.isMemberExpression(left) && isMemberAccessingProperty(left, "value");
391
+ }
392
+ function symbolUpdate(path) {
393
+ if (!isValidPath(path)) {
394
+ return;
395
+ }
396
+ const { argument } = path.node;
397
+ if (!t3.isIdentifier(argument)) {
398
+ return;
399
+ }
400
+ const name = argument.name;
401
+ if (!isSignal(name)) {
402
+ return;
403
+ }
404
+ if (isAlreadyValueUpdate(argument)) {
405
+ return;
406
+ }
407
+ path.node.argument = t3.memberExpression(t3.identifier(name), t3.identifier("value"));
408
+ }
409
+ function isAlreadyValueUpdate(argument) {
410
+ return t3.isMemberExpression(argument) && isMemberAccessingProperty(argument, "value");
411
+ }
412
+ function symbolObjectPattern(path) {
413
+ if (!isValidPath(path)) {
414
+ return;
415
+ }
416
+ const properties = path.node.properties;
417
+ if (!Array.isArray(properties) || properties.length === 0) {
418
+ return;
419
+ }
420
+ for (const property of properties) {
421
+ if (!property) continue;
422
+ if (t3.isObjectProperty(property)) {
423
+ handleObjectProperty(property, path);
424
+ } else if (t3.isRestElement(property)) {
425
+ handleRestElement(property, path);
426
+ }
427
+ }
428
+ }
429
+ function handleObjectProperty(property, parentPath) {
430
+ if (!property || !property.value) {
431
+ return;
432
+ }
433
+ const value = property.value;
434
+ if (t3.isObjectPattern(value)) {
435
+ const mockPath = {
436
+ node: value,
437
+ state: parentPath.state,
438
+ parentPath
439
+ };
440
+ symbolObjectPattern(mockPath);
441
+ } else if (t3.isArrayPattern(value)) {
442
+ const mockPath = {
443
+ node: value,
444
+ state: parentPath.state,
445
+ parentPath
446
+ };
447
+ symbolArrayPattern(mockPath);
448
+ } else if (t3.isAssignmentPattern(value)) {
449
+ handleAssignmentPattern(value, parentPath);
450
+ }
451
+ }
452
+ function handleAssignmentPattern(pattern, parentPath) {
453
+ const left = pattern.left;
454
+ if (t3.isObjectPattern(left)) {
455
+ const mockPath = {
456
+ node: left,
457
+ state: parentPath.state,
458
+ parentPath
459
+ };
460
+ symbolObjectPattern(mockPath);
461
+ } else if (t3.isArrayPattern(left)) {
462
+ const mockPath = {
463
+ node: left,
464
+ state: parentPath.state,
465
+ parentPath
466
+ };
467
+ symbolArrayPattern(mockPath);
468
+ }
469
+ }
470
+ function handleRestElement(restElement, parentPath) {
471
+ if (!restElement || !restElement.argument) {
472
+ return;
473
+ }
474
+ const argument = restElement.argument;
475
+ if (t3.isObjectPattern(argument)) {
476
+ const mockPath = {
477
+ node: argument,
478
+ state: parentPath.state,
479
+ parentPath
480
+ };
481
+ symbolObjectPattern(mockPath);
482
+ } else if (t3.isArrayPattern(argument)) {
483
+ const mockPath = {
484
+ node: argument,
485
+ state: parentPath.state,
486
+ parentPath
487
+ };
488
+ symbolArrayPattern(mockPath);
489
+ }
490
+ }
491
+ function symbolArrayPattern(path) {
492
+ if (!isValidPath(path)) {
493
+ return;
494
+ }
495
+ const elements = path.node.elements;
496
+ if (!Array.isArray(elements) || elements.length === 0) {
497
+ return;
498
+ }
499
+ for (const element of elements) {
500
+ if (!element) continue;
501
+ if (t3.isAssignmentPattern(element)) {
502
+ handleAssignmentPattern(element, path);
503
+ } else if (t3.isRestElement(element)) {
504
+ handleArrayRestElement(element, path);
505
+ } else if (t3.isObjectPattern(element)) {
506
+ const mockPath = {
507
+ node: element,
508
+ state: path.state,
509
+ parentPath: path
510
+ };
511
+ symbolObjectPattern(mockPath);
512
+ } else if (t3.isArrayPattern(element)) {
513
+ const mockPath = {
514
+ node: element,
515
+ state: path.state,
516
+ parentPath: path
517
+ };
518
+ symbolArrayPattern(mockPath);
519
+ }
520
+ }
521
+ }
522
+ function handleArrayRestElement(restElement, parentPath) {
523
+ if (!restElement || !restElement.argument) {
524
+ return;
525
+ }
526
+ const argument = restElement.argument;
527
+ if (t3.isArrayPattern(argument)) {
528
+ const mockPath = {
529
+ node: argument,
530
+ state: parentPath.state,
531
+ parentPath
532
+ };
533
+ symbolArrayPattern(mockPath);
534
+ } else if (t3.isObjectPattern(argument)) {
535
+ const mockPath = {
536
+ node: argument,
537
+ state: parentPath.state,
538
+ parentPath
539
+ };
540
+ symbolObjectPattern(mockPath);
541
+ }
542
+ }
53
543
 
54
544
  // src/program.ts
55
- import { types as t } from "@babel/core";
56
- var imports = /* @__PURE__ */ new Set();
57
- var defaultOption = {
58
- server: false,
59
- symbol: "$",
60
- props: true
61
- };
545
+ function withState(visitor, parentState) {
546
+ return (path) => {
547
+ path.state = parentState;
548
+ visitor(path);
549
+ };
550
+ }
62
551
  var transformProgram = {
63
- enter(path, state) {
64
- imports.clear();
65
- state.opts = __spreadValues(__spreadValues({}, defaultOption), state.opts);
66
- path.state = {
67
- h: path.scope.generateUidIdentifier("h$"),
68
- template: path.scope.generateUidIdentifier("template$"),
69
- ssg: path.scope.generateUidIdentifier("ssg$"),
70
- Fragment: path.scope.generateUidIdentifier("fragment$"),
71
- useSignal: path.scope.generateUidIdentifier("useSignal$"),
72
- useComputed: path.scope.generateUidIdentifier("useComputed$"),
73
- useReactive: path.scope.generateUidIdentifier("useReactive$"),
74
- tmplDeclaration: t.variableDeclaration("const", []),
75
- opts: state.opts
76
- };
552
+ enter: (path, state) => {
553
+ const opts = __spreadValues(__spreadValues({}, DEFAULT_OPTIONS), state.opts);
554
+ const imports = createImportIdentifiers(path);
555
+ clearImport();
556
+ path.state = __spreadProps(__spreadValues({}, state), {
557
+ opts,
558
+ imports,
559
+ declarations: [],
560
+ // Collect template declarations during transformation
561
+ filename: state.filename,
562
+ events: /* @__PURE__ */ new Set()
563
+ // Track delegated events for optimization
564
+ });
565
+ const parentState = path.state;
566
+ path.traverse({
567
+ VariableDeclarator: withState(replaceSymbol, parentState),
568
+ // let $x = 0 → let $x = signal(0)
569
+ Identifier: withState(symbolIdentifier, parentState),
570
+ // $x → $x.value
571
+ AssignmentExpression: withState(symbolAssignment, parentState),
572
+ // $x = 1 → $x.value = 1
573
+ UpdateExpression: withState(symbolUpdate, parentState),
574
+ // $x++ → $x.value++
575
+ ObjectPattern: withState(symbolObjectPattern, parentState),
576
+ // { $x } → handle nested patterns
577
+ ArrayPattern: withState(symbolArrayPattern, parentState)
578
+ // [$x] → handle nested patterns
579
+ });
77
580
  },
78
- exit(path) {
79
- const state = path.state;
80
- if (state.tmplDeclaration.declarations.length > 0) {
81
- const index = path.node.body.findIndex(
82
- (node) => !t.isImportDeclaration(node) && !t.isExportDeclaration(node)
83
- );
84
- path.node.body.splice(index, 0, state.tmplDeclaration);
581
+ // eslint-disable-next-line unused-imports/no-unused-vars
582
+ exit: (path, state) => {
583
+ const pluginState = path.state;
584
+ const { imports, declarations, events } = pluginState;
585
+ const insertIndex = path.node.body.findIndex(
586
+ (node) => !t4.isImportDeclaration(node) && !t4.isExportDeclaration(node)
587
+ );
588
+ if (declarations == null ? void 0 : declarations.length) {
589
+ const templateDeclaration = t4.variableDeclaration("const", declarations);
590
+ if (insertIndex !== -1) {
591
+ path.node.body.splice(insertIndex, 0, templateDeclaration);
592
+ } else {
593
+ path.node.body.push(templateDeclaration);
594
+ }
85
595
  }
86
- if (imports.size > 0) {
87
- path.node.body.unshift(createImport(state, "essor"));
596
+ if (events && events.size > 0) {
597
+ const eventsDeclaration = t4.expressionStatement(
598
+ t4.callExpression(imports.delegateEvents, [
599
+ t4.arrayExpression(Array.from(events).map((event) => t4.stringLiteral(event)))
600
+ ])
601
+ );
602
+ addImport(importMap.delegateEvents);
603
+ path.node.body.push(eventsDeclaration);
88
604
  }
605
+ createImport(path, imports, "essor");
89
606
  }
90
607
  };
91
- function createImport(state, from) {
92
- const ImportSpecifier = [];
93
- imports.forEach((name) => {
94
- const local = t.identifier(state[name].name);
95
- const imported = t.identifier(name);
96
- ImportSpecifier.push(t.importSpecifier(local, imported));
608
+
609
+ // src/signals/props.ts
610
+ import { types as t5 } from "@babel/core";
611
+ function transformProperty(path, properties, parentPath, defaultValues = {}) {
612
+ properties.forEach((property, index) => {
613
+ try {
614
+ if (!t5.isObjectProperty(property)) {
615
+ return;
616
+ }
617
+ if (!t5.isIdentifier(property.key)) {
618
+ if (true) {
619
+ ne("transformObjectProperties: Skipping computed property", { index });
620
+ }
621
+ return;
622
+ }
623
+ const keyName = property.key.name;
624
+ if (t5.isIdentifier(property.value)) {
625
+ path.scope.rename(property.value.name, `${parentPath}.${keyName}`);
626
+ } else if (t5.isAssignmentPattern(property.value)) {
627
+ if (t5.isIdentifier(property.value.left)) {
628
+ defaultValues[keyName] = property.value.right;
629
+ path.scope.rename(property.value.left.name, `${parentPath}.${keyName}`);
630
+ } else if (t5.isObjectPattern(property.value.left)) {
631
+ transformProperty(
632
+ path,
633
+ property.value.left.properties,
634
+ `${parentPath}.${keyName}`,
635
+ defaultValues
636
+ );
637
+ defaultValues[keyName] = property.value.right;
638
+ }
639
+ } else if (t5.isObjectPattern(property.value)) {
640
+ transformProperty(
641
+ path,
642
+ property.value.properties,
643
+ `${parentPath}.${keyName}`,
644
+ defaultValues
645
+ );
646
+ }
647
+ } catch (error) {
648
+ ne("transformProperty", `Failed to process property at index ${index}`, {
649
+ error: error instanceof Error ? error.message : String(error)
650
+ });
651
+ }
97
652
  });
98
- const importSource = t.stringLiteral(from);
99
- return t.importDeclaration(ImportSpecifier, importSource);
653
+ return defaultValues;
654
+ }
655
+ function buildRestVariableDeclaration(state, restName, parentPath, excludeProps) {
656
+ const validExcludeProps = excludeProps.filter(Boolean);
657
+ let init;
658
+ const pathParts = parentPath.split(".").filter((part) => part.length > 0);
659
+ let sourceObject = t5.identifier(pathParts[0] || "__props");
660
+ for (let i = 1; i < pathParts.length; i++) {
661
+ sourceObject = t5.memberExpression(sourceObject, t5.identifier(pathParts[i]));
662
+ }
663
+ if (validExcludeProps.length === 0) {
664
+ init = sourceObject;
665
+ } else {
666
+ init = t5.callExpression(state.imports.omitProps, [
667
+ sourceObject,
668
+ t5.arrayExpression(validExcludeProps.map((name) => t5.stringLiteral(name)))
669
+ ]);
670
+ }
671
+ return t5.variableDeclaration("const", [t5.variableDeclarator(t5.identifier(restName), init)]);
672
+ }
673
+ function transformRestProperties(path, restProperties, notRestNames = [], nestedRestParams = []) {
674
+ if (!t5.isIdentifier(restProperties.argument)) {
675
+ return;
676
+ }
677
+ const restName = restProperties.argument.name;
678
+ if (notRestNames.length === 0 && nestedRestParams.length === 0) {
679
+ path.node.params[0] = t5.identifier(restName);
680
+ } else {
681
+ const restDeclarations = [];
682
+ if (nestedRestParams.length > 0) {
683
+ for (const nestedRest of nestedRestParams) {
684
+ const nestedRestDeclaration = buildRestVariableDeclaration(
685
+ path.state,
686
+ nestedRest.name,
687
+ nestedRest.parentPath,
688
+ nestedRest.excludeProps
689
+ );
690
+ restDeclarations.push(nestedRestDeclaration);
691
+ if (nestedRest.excludeProps.length > 0) {
692
+ addImport(importMap.omitProps);
693
+ }
694
+ }
695
+ }
696
+ if (restProperties) {
697
+ const restDeclaration = buildRestVariableDeclaration(
698
+ path.state,
699
+ restName,
700
+ TRANSFORM_PROPERTY_NAME,
701
+ notRestNames
702
+ );
703
+ restDeclarations.push(restDeclaration);
704
+ if (notRestNames.length) {
705
+ addImport(importMap.omitProps);
706
+ }
707
+ }
708
+ for (const declaration of restDeclarations) {
709
+ const body = path.node.body;
710
+ body.body.unshift(declaration);
711
+ }
712
+ }
713
+ }
714
+ function buildDefaultValueObject(defaultValues) {
715
+ if (!P(defaultValues)) {
716
+ return t5.objectExpression([]);
717
+ }
718
+ const properties = [];
719
+ for (const [key, value] of Object.entries(defaultValues)) {
720
+ if (!key) {
721
+ continue;
722
+ }
723
+ let propertyValue;
724
+ if (P(value) && !t5.isNode(value)) {
725
+ propertyValue = buildDefaultValueObject(value);
726
+ } else if (t5.isExpression(value)) {
727
+ propertyValue = value;
728
+ } else {
729
+ continue;
730
+ }
731
+ properties.push(t5.objectProperty(t5.identifier(key), propertyValue));
732
+ }
733
+ return t5.objectExpression(properties);
734
+ }
735
+ function buildDefaultValue(path, defaultValues) {
736
+ const propsParam = Object.keys(defaultValues).length > 0 ? t5.assignmentPattern(
737
+ t5.identifier(TRANSFORM_PROPERTY_NAME),
738
+ buildDefaultValueObject(defaultValues)
739
+ ) : t5.identifier(TRANSFORM_PROPERTY_NAME);
740
+ path.node.params[0] = propsParam;
741
+ }
742
+ function transformProps(path) {
743
+ const firstParam = path.node.params[0];
744
+ if (!firstParam || !t5.isObjectPattern(firstParam) || !checkHasJSXReturn(path)) {
745
+ return;
746
+ }
747
+ const state = path.state;
748
+ const properties = firstParam.properties;
749
+ const signalPrefix = state.opts.symbol || "$";
750
+ const notRestProperties = properties.filter((prop) => !t5.isRestElement(prop));
751
+ const restProperties = properties.find((prop) => t5.isRestElement(prop));
752
+ const notRestNames = notRestProperties.map((prop) => t5.isIdentifier(prop.key) ? prop.key.name : null).filter((name) => name !== null);
753
+ if (true) {
754
+ if (notRestNames.some((name) => q(name, signalPrefix))) {
755
+ ne(
756
+ "transformProps",
757
+ "Property names cannot start with signal prefix",
758
+ notRestNames.filter((name) => q(name, signalPrefix))
759
+ );
760
+ }
761
+ }
762
+ if (notRestProperties.length) {
763
+ const defaultValues = transformProperty(path, notRestProperties, TRANSFORM_PROPERTY_NAME);
764
+ buildDefaultValue(path, defaultValues);
765
+ }
766
+ if (restProperties) {
767
+ transformRestProperties(path, restProperties, notRestNames);
768
+ }
100
769
  }
101
770
 
771
+ // src/jsx/context.ts
772
+ var contextStack = [];
773
+ function getContext() {
774
+ if (!contextStack.length) {
775
+ throw new Error("No active context found. Ensure setContext has been called.");
776
+ }
777
+ return contextStack[contextStack.length - 1];
778
+ }
779
+ function setContext(context) {
780
+ contextStack.push(context);
781
+ }
782
+ function resetContext() {
783
+ contextStack.pop();
784
+ }
785
+
786
+ // src/jsx/client.ts
787
+ import { types as t8 } from "@babel/core";
788
+
789
+ // src/jsx/constants.ts
790
+ var CLASS_NAME = "class";
791
+ var STYLE_NAME = "style";
792
+ var EVENT_ATTR_NAME = "on";
793
+ var UPDATE_PREFIX = "update";
794
+ var FRAGMENT_NAME = "Fragment";
795
+ var CHILDREN_NAME = "children";
796
+ var REF_KEY = "ref";
797
+ var SPREAD_NAME = "_$spread$";
798
+ var CREATE_COMPONENT_NAME = "createComponent";
799
+ var BIND_REG = /^bind:.+/;
800
+ var BUILT_IN_COMPONENTS = ["Fragment", "Portal", "Suspense", "For"];
801
+
102
802
  // src/jsx/shared.ts
103
- import { types as t2 } from "@babel/core";
104
- function createClientResult() {
803
+ import { types as t7 } from "@babel/core";
804
+
805
+ // src/jsx/tree.ts
806
+ import { types as t6 } from "@babel/core";
807
+ function createDefaultTree() {
105
808
  return {
809
+ root: true,
810
+ type: 0 /* NORMAL */,
811
+ tag: "",
812
+ props: {},
813
+ children: [],
106
814
  index: 1,
815
+ parentIndex: null,
107
816
  isLastChild: false,
108
- parentIndex: 0,
109
- props: {},
110
- template: ""
817
+ selfClosing: false,
818
+ _isTreeNode: true
111
819
  };
112
820
  }
113
- function createServerResult() {
114
- return {
115
- index: 1,
116
- isLastChild: false,
117
- parentIndex: 0,
118
- props: {},
119
- template: []
821
+ function isTreeNode(node) {
822
+ return !!(node && node._isTreeNode);
823
+ }
824
+ var treeIndex = 1;
825
+ function createTree(path, parentNode) {
826
+ const treeNode = createDefaultTree();
827
+ const tagName = getTagName(path.node);
828
+ treeNode.tag = tagName;
829
+ treeNode.type = determineNodeType(tagName);
830
+ treeNode.selfClosing = Ne(tagName);
831
+ if (parentNode) {
832
+ const parentIsComponent = parentNode.type === 1 /* COMPONENT */;
833
+ if (parentIsComponent) {
834
+ treeIndex = 1;
835
+ treeNode.index = treeIndex;
836
+ } else if (treeNode.type !== 1 /* COMPONENT */) {
837
+ treeNode.index = ++treeIndex;
838
+ }
839
+ treeNode.parentIndex = treeIndex;
840
+ } else {
841
+ treeNode.root = true;
842
+ treeIndex = 1;
843
+ }
844
+ if (t6.isJSXText(path.node)) {
845
+ return processJSXText(path, treeNode);
846
+ }
847
+ if (t6.isJSXElement(path.node) || t6.isJSXFragment(path.node)) {
848
+ return processJSXElement(path, treeNode);
849
+ }
850
+ return treeNode;
851
+ }
852
+ function processJSXElement(path, treeNode) {
853
+ if (!path.isJSXFragment()) {
854
+ treeNode.props = processProps(path);
855
+ }
856
+ if (!treeNode.selfClosing) {
857
+ processChildren(path, treeNode);
858
+ }
859
+ return treeNode;
860
+ }
861
+ function processProps(path) {
862
+ const props = {};
863
+ const attributes = path.get("openingElement.attributes");
864
+ if (!attributes.length) {
865
+ return props;
866
+ }
867
+ attributes.forEach((attribute) => {
868
+ if (t6.isJSXAttribute(attribute.node)) {
869
+ const name = getAttrName(attribute.node);
870
+ const value = attribute.get("value");
871
+ if (!value.node) {
872
+ props[name] = true;
873
+ } else if (value) {
874
+ if (value.isJSXExpressionContainer()) {
875
+ const expression = value.get("expression");
876
+ if (expression.isStringLiteral() || expression.isNumericLiteral()) {
877
+ props[name] = expression.node.value;
878
+ } else if (expression.isJSXElement() || expression.isJSXFragment()) {
879
+ props[name] = expression.node;
880
+ } else if (expression.isExpression()) {
881
+ processPropsExpression(expression, name, props, path);
882
+ }
883
+ } else if (value.isStringLiteral() || value.isNumericLiteral()) {
884
+ props[name] = value.node.value;
885
+ } else if (value.isJSXElement() || value.isJSXFragment()) {
886
+ props[name] = value.node;
887
+ } else if (value.isExpression()) {
888
+ processPropsExpression(value, name, props, path);
889
+ }
890
+ }
891
+ } else if (t6.isJSXSpreadAttribute(attribute.node)) {
892
+ props[SPREAD_NAME] = attribute.get("argument").node;
893
+ }
894
+ });
895
+ return props;
896
+ }
897
+ function processPropsExpression(expression, name, props, path) {
898
+ if (BIND_REG.test(name)) {
899
+ processPropsBind(name, expression, props, path);
900
+ } else {
901
+ props[name] = expression.node;
902
+ }
903
+ }
904
+ function processPropsBind(name, expression, props, path) {
905
+ const value = path.scope.generateUidIdentifier("value");
906
+ const bindName = name.slice(5).toLowerCase();
907
+ props[`${UPDATE_PREFIX}:${bindName}`] = [
908
+ expression.node,
909
+ // Getter: the bound variable
910
+ t6.arrowFunctionExpression(
911
+ [value],
912
+ // Type guard: expression.node must be LVal for bind directive
913
+ t6.isLVal(expression.node) ? t6.assignmentExpression("=", expression.node, value) : t6.assignmentExpression("=", t6.identifier("_"), value)
914
+ // Fallback for invalid LVal
915
+ )
916
+ ];
917
+ }
918
+ function processChildren(path, treeNode) {
919
+ const children = path.node.children;
920
+ if (!children || !children.length) {
921
+ return;
922
+ }
923
+ const optimizedChildren = optimizeChildNodes(path.get("children"));
924
+ optimizedChildren.forEach((child) => {
925
+ processChild(child, treeNode, optimizedChildren.length === 1);
926
+ });
927
+ }
928
+ function processChild(child, treeNode, isLastChild) {
929
+ if (t6.isJSXElement(child.node) || t6.isJSXFragment(child.node)) {
930
+ const childNode = createTree(child, treeNode);
931
+ childNode.isLastChild = isLastChild;
932
+ treeNode.children.push(childNode);
933
+ return;
934
+ }
935
+ if (t6.isJSXExpressionContainer(child.node)) {
936
+ processChildExpressionContainer(
937
+ child,
938
+ treeNode,
939
+ isLastChild
940
+ );
941
+ return;
942
+ }
943
+ if (t6.isJSXText(child.node)) {
944
+ processJSXChildText(child, treeNode, isLastChild);
945
+ return;
946
+ }
947
+ if (t6.isJSXSpreadChild(child.node)) {
948
+ processChildSpread(child, treeNode, isLastChild);
949
+ return;
950
+ }
951
+ }
952
+ function processChildExpressionContainer(child, treeNode, isLastChild) {
953
+ const expression = child.get("expression");
954
+ if (expression.isStringLiteral() || expression.isNumericLiteral()) {
955
+ treeNode.children.push({
956
+ type: 2 /* TEXT */,
957
+ children: [String(expression.node.value)],
958
+ index: ++treeIndex,
959
+ // Static text increments index
960
+ parentIndex: treeNode.index,
961
+ isLastChild,
962
+ _isTreeNode: true
963
+ });
964
+ } else if (expression.isJSXElement() || expression.isJSXFragment()) {
965
+ const childNode = createTree(child, treeNode);
966
+ childNode.isLastChild = isLastChild;
967
+ treeNode.children.push(childNode);
968
+ } else if (expression.isExpression()) {
969
+ treeNode.children.push({
970
+ type: 4 /* EXPRESSION */,
971
+ index: treeIndex,
972
+ // Expression doesn't update index because it's dynamic content
973
+ isLastChild,
974
+ // Type guard: expression.node is Expression in JSXExpressionContainer
975
+ children: t6.isExpression(expression.node) ? [expression.node] : [],
976
+ parentIndex: treeNode.index,
977
+ _isTreeNode: true
978
+ });
979
+ }
980
+ }
981
+ function shouldInsertComment(childrenLength, previousNode) {
982
+ return !!(childrenLength >= 2 && // At least two child nodes
983
+ previousNode && // Previous node exists
984
+ previousNode.type !== 6 /* COMMENT */ && // Previous node is not a comment
985
+ // Previous node is dynamic content
986
+ (previousNode.type === 4 /* EXPRESSION */ || previousNode.type === 1 /* COMPONENT */));
987
+ }
988
+ function processJSXChildText(child, treeNode, isLastChild) {
989
+ const text = textTrim(child.node);
990
+ if (!text) {
991
+ return;
992
+ }
993
+ const childrenLength = treeNode.children.length;
994
+ const previousNode = treeNode.children[childrenLength - 1];
995
+ if (shouldInsertComment(childrenLength, previousNode)) {
996
+ const commentNode = {
997
+ type: 6 /* COMMENT */,
998
+ children: [],
999
+ index: ++treeIndex,
1000
+ _isTreeNode: true
1001
+ };
1002
+ treeNode.children.push(commentNode);
1003
+ }
1004
+ const textNode = {
1005
+ type: 2 /* TEXT */,
1006
+ children: [text],
1007
+ index: ++treeIndex,
1008
+ isLastChild,
1009
+ _isTreeNode: true
1010
+ };
1011
+ treeNode.children.push(textNode);
1012
+ }
1013
+ function processChildSpread(child, treeNode, isLastChild) {
1014
+ const spreadExpression = child.get("expression");
1015
+ treeNode.children.push({
1016
+ type: 7 /* SPREAD */,
1017
+ // Type guard: spreadExpression.node is Expression in JSXSpreadChild
1018
+ children: t6.isExpression(spreadExpression.node) ? [spreadExpression.node] : [],
1019
+ index: treeIndex,
1020
+ // Note: doesn't increment here because this is dynamic content
1021
+ parentIndex: treeNode.index,
1022
+ isLastChild,
1023
+ _isTreeNode: true
1024
+ });
1025
+ }
1026
+ function determineNodeType(tagName) {
1027
+ const isComponent = isComponentName(tagName);
1028
+ if (isComponent) {
1029
+ return 1 /* COMPONENT */;
1030
+ }
1031
+ if (Me(tagName)) {
1032
+ return 5 /* SVG */;
1033
+ }
1034
+ return 0 /* NORMAL */;
1035
+ }
1036
+ function processJSXText(path, treeNode) {
1037
+ treeNode.type = 2 /* TEXT */;
1038
+ try {
1039
+ const textValue = textTrim(path.node);
1040
+ treeNode.children = textValue ? [textValue] : [];
1041
+ } catch (error) {
1042
+ ne(`Text node processing failed: ${error}`);
1043
+ treeNode.children = [];
1044
+ }
1045
+ return treeNode;
1046
+ }
1047
+
1048
+ // src/jsx/shared.ts
1049
+ function isComponentName(tagName) {
1050
+ if (!tagName) {
1051
+ return false;
1052
+ }
1053
+ const firstCharCode = tagName.charCodeAt(0);
1054
+ if (firstCharCode >= 65 && firstCharCode <= 90) {
1055
+ return true;
1056
+ }
1057
+ const dotIndex = tagName.indexOf(".");
1058
+ const colonIndex = tagName.indexOf(":");
1059
+ if (dotIndex !== -1 || colonIndex !== -1) {
1060
+ const segments = tagName.split(/[:.]/);
1061
+ const len = segments.length;
1062
+ for (let i = 0; i < len; i++) {
1063
+ const segment = segments[i];
1064
+ if (segment.length > 0) {
1065
+ const segmentCharCode = segment.charCodeAt(0);
1066
+ if (segmentCharCode >= 65 && segmentCharCode <= 90) {
1067
+ return true;
1068
+ }
1069
+ }
1070
+ }
1071
+ }
1072
+ return !(firstCharCode >= 97 && firstCharCode <= 122);
1073
+ }
1074
+ var getTagName = (node) => {
1075
+ if (t7.isJSXFragment(node)) {
1076
+ return FRAGMENT_NAME;
1077
+ }
1078
+ const tag = node.openingElement.name;
1079
+ return jsxElementNameToString(tag);
1080
+ };
1081
+ function jsxElementNameToString(node) {
1082
+ var _a, _b, _c, _d;
1083
+ if (t7.isJSXMemberExpression(node)) {
1084
+ return `${jsxElementNameToString(node.object)}.${jsxElementNameToString(node.property)}`;
1085
+ }
1086
+ if (t7.isMemberExpression(node)) {
1087
+ const objectName = jsxElementNameToString(
1088
+ node.object
1089
+ );
1090
+ const propertyName = jsxElementNameToString(
1091
+ node.property
1092
+ );
1093
+ return `${objectName}.${propertyName}`;
1094
+ }
1095
+ if (t7.isJSXIdentifier(node) || t7.isIdentifier(node)) {
1096
+ return node.name;
1097
+ }
1098
+ const namespace = (_b = (_a = node.namespace) == null ? void 0 : _a.name) != null ? _b : "";
1099
+ const name = (_d = (_c = node.name) == null ? void 0 : _c.name) != null ? _d : "";
1100
+ if (!namespace) {
1101
+ return name;
1102
+ }
1103
+ if (!name) {
1104
+ return namespace;
1105
+ }
1106
+ return `${namespace}:${name}`;
1107
+ }
1108
+ function textTrim(node) {
1109
+ if (!node || !node.value) return "";
1110
+ return node.value.trim();
1111
+ }
1112
+ function isValidChild(path) {
1113
+ const regex = /^\s*$/;
1114
+ if (t7.isStringLiteral(path.node)) {
1115
+ return !regex.test(path.node.value);
1116
+ }
1117
+ if (t7.isJSXText(path.node)) {
1118
+ return !regex.test(path.node.value);
1119
+ }
1120
+ return Object.keys(path.node).length > 0;
1121
+ }
1122
+ function getRawNodeText(path) {
1123
+ if (path.isJSXText()) {
1124
+ return path.node.value || "";
1125
+ }
1126
+ if (path.isJSXExpressionContainer()) {
1127
+ const expression = path.get("expression");
1128
+ if (expression.isStringLiteral() || expression.isNumericLiteral()) {
1129
+ return String(expression.node.value);
1130
+ }
1131
+ }
1132
+ return "";
1133
+ }
1134
+ function setNodeText(path, text) {
1135
+ if (path.isJSXText()) {
1136
+ path.node.value = text;
1137
+ }
1138
+ if (path.isJSXExpressionContainer()) {
1139
+ const expression = path.get("expression");
1140
+ if (expression.isStringLiteral() || expression.isNumericLiteral()) {
1141
+ expression.replaceWith(t7.stringLiteral(text));
1142
+ }
1143
+ }
1144
+ }
1145
+ function optimizeChildNodes(children) {
1146
+ const mergedWithExpression = /* @__PURE__ */ new WeakSet();
1147
+ return children.reduce((acc, cur) => {
1148
+ var _a, _b, _c, _d;
1149
+ if (isValidChild(cur)) {
1150
+ const lastChild = acc.at(-1);
1151
+ if (!lastChild) {
1152
+ acc.push(cur);
1153
+ return acc;
1154
+ }
1155
+ const lastIsPlainText = (_b = (_a = lastChild.isJSXText) == null ? void 0 : _a.call(lastChild)) != null ? _b : false;
1156
+ const currentIsPlainText = (_d = (_c = cur.isJSXText) == null ? void 0 : _c.call(cur)) != null ? _d : false;
1157
+ if (lastIsPlainText && t7.isJSXExpressionContainer(cur.node) && (cur.get("expression").isStringLiteral() || cur.get("expression").isNumericLiteral()) && !mergedWithExpression.has(lastChild)) {
1158
+ const mergedText = getRawNodeText(lastChild) + getRawNodeText(cur);
1159
+ setNodeText(lastChild, mergedText);
1160
+ mergedWithExpression.add(lastChild);
1161
+ return acc;
1162
+ }
1163
+ if (lastIsPlainText && currentIsPlainText && !mergedWithExpression.has(lastChild)) {
1164
+ const mergedText = getRawNodeText(lastChild) + getRawNodeText(cur);
1165
+ setNodeText(lastChild, mergedText);
1166
+ return acc;
1167
+ }
1168
+ acc.push(cur);
1169
+ }
1170
+ return acc;
1171
+ }, []);
1172
+ }
1173
+ function deepCheckObjectDynamic(node) {
1174
+ if (!t7.isObjectExpression(node)) return false;
1175
+ let dynamic = false;
1176
+ function walk(current) {
1177
+ if (dynamic) return;
1178
+ if (t7.isIdentifier(current) || t7.isCallExpression(current) || t7.isMemberExpression(current) || t7.isConditionalExpression(current) || t7.isTemplateLiteral(current) || t7.isBinaryExpression(current) || t7.isUpdateExpression(current) || t7.isUnaryExpression(current) || t7.isAwaitExpression(current) || t7.isYieldExpression(current) || t7.isTaggedTemplateExpression(current)) {
1179
+ dynamic = true;
1180
+ return;
1181
+ }
1182
+ if (t7.isObjectExpression(current)) {
1183
+ current.properties.forEach((prop) => {
1184
+ if (t7.isObjectProperty(prop)) walk(prop.value);
1185
+ if (t7.isSpreadElement(prop)) walk(prop.argument);
1186
+ });
1187
+ return;
1188
+ }
1189
+ if (t7.isArrayExpression(current)) {
1190
+ current.elements.forEach((el) => el && walk(el));
1191
+ return;
1192
+ }
1193
+ }
1194
+ walk(node);
1195
+ return dynamic;
1196
+ }
1197
+ function processObjectExpression(propName, objectExpr, propsCollection, isClassOrStyleAttr = false) {
1198
+ let classStyleString = "";
1199
+ if (deepCheckObjectDynamic(objectExpr)) {
1200
+ propsCollection[propName] = objectExpr;
1201
+ } else if (isClassOrStyleAttr) {
1202
+ classStyleString = objectExpr.properties.filter((property) => t7.isObjectProperty(property)).reduce((acc, property) => {
1203
+ const key = t7.isIdentifier(property.key) ? property.key.name : t7.isStringLiteral(property.key) ? property.key.value : String(property.key);
1204
+ if (t7.isStringLiteral(property.value)) {
1205
+ return `${acc}${key}:${property.value.value};`;
1206
+ }
1207
+ return acc;
1208
+ }, "");
1209
+ delete propsCollection[propName];
1210
+ }
1211
+ return classStyleString;
1212
+ }
1213
+ function getAttrName(attribute) {
1214
+ if (t7.isJSXIdentifier(attribute.name)) {
1215
+ return attribute.name.name;
1216
+ }
1217
+ if (t7.isJSXNamespacedName(attribute.name)) {
1218
+ return `${attribute.name.namespace.name}:${attribute.name.name.name}`;
1219
+ }
1220
+ return "";
1221
+ }
1222
+ function serializeAttributes(attributes) {
1223
+ if (!attributes || !w(attributes)) {
1224
+ return "";
1225
+ }
1226
+ let attributesString = "";
1227
+ let classNames = "";
1228
+ let styleString = "";
1229
+ for (const [attrName, attrValue] of Object.entries(attributes)) {
1230
+ if (attrName === CLASS_NAME && m(attrValue)) {
1231
+ classNames += ` ${attrValue}`;
1232
+ delete attributes[attrName];
1233
+ } else if (attrName === STYLE_NAME && m(attrValue)) {
1234
+ styleString += `${attrValue}${attrValue.at(-1) === ";" ? "" : ";"}`;
1235
+ delete attributes[attrName];
1236
+ } else if (attrValue === true) {
1237
+ attributesString += ` ${attrName}`;
1238
+ delete attributes[attrName];
1239
+ } else if (attrValue === false) {
1240
+ delete attributes[attrName];
1241
+ } else if (m(attrValue) || T(attrValue)) {
1242
+ attributesString += ` ${attrName}="${attrValue}"`;
1243
+ delete attributes[attrName];
1244
+ } else if (t7.isConditionalExpression(attrValue)) {
1245
+ attributes[attrName] = attrValue;
1246
+ } else if (t7.isObjectExpression(attrValue)) {
1247
+ const result = processObjectExpression(
1248
+ attrName,
1249
+ attrValue,
1250
+ attributes,
1251
+ attrName === CLASS_NAME || attrName === STYLE_NAME
1252
+ );
1253
+ if (result) {
1254
+ if (attrName === CLASS_NAME) {
1255
+ classNames += ` ${result}`;
1256
+ }
1257
+ if (attrName === STYLE_NAME) {
1258
+ styleString += `${result}${result.at(-1) === ";" ? "" : ";"}`;
1259
+ }
1260
+ }
1261
+ }
1262
+ }
1263
+ if (classNames.trim()) {
1264
+ attributesString += ` ${CLASS_NAME}="${classNames.trim()}"`;
1265
+ }
1266
+ if (styleString.trim()) {
1267
+ attributesString += ` ${STYLE_NAME}="${styleString.trim()}"`;
1268
+ }
1269
+ return attributesString;
1270
+ }
1271
+ function findBeforeIndex(currentNode, parentNode) {
1272
+ var _a;
1273
+ if (!((_a = parentNode == null ? void 0 : parentNode.children) == null ? void 0 : _a.length) || currentNode.isLastChild) {
1274
+ return null;
1275
+ }
1276
+ const children = parentNode.children;
1277
+ const childrenLength = children.length;
1278
+ let nodeIndex = -1;
1279
+ for (let i = 0; i < childrenLength; i++) {
1280
+ if (children[i] === currentNode) {
1281
+ nodeIndex = i;
1282
+ break;
1283
+ }
1284
+ }
1285
+ if (nodeIndex === -1 || nodeIndex === childrenLength - 1) {
1286
+ return null;
1287
+ }
1288
+ for (let searchIndex = nodeIndex + 1; searchIndex < childrenLength; searchIndex++) {
1289
+ const siblingNode = children[searchIndex];
1290
+ const siblingType = siblingNode.type;
1291
+ if (siblingType !== 4 /* EXPRESSION */ && siblingType !== 3 /* FRAGMENT */ && siblingType !== 1 /* COMPONENT */) {
1292
+ return siblingNode.index;
1293
+ }
1294
+ }
1295
+ return null;
1296
+ }
1297
+ function findIndexPosition(targetIndex, indexMap) {
1298
+ if (d(indexMap)) {
1299
+ return indexMap.indexOf(targetIndex);
1300
+ }
1301
+ if (E(indexMap)) {
1302
+ const position = indexMap.get(targetIndex);
1303
+ return T(position) ? position : -1;
1304
+ }
1305
+ return -1;
1306
+ }
1307
+ function normalizeProps(raw) {
1308
+ const normalized = {};
1309
+ const classBuffer = [];
1310
+ const styleBuffer = [];
1311
+ for (const [key, value] of Object.entries(raw)) {
1312
+ if (key === CLASS_NAME || key === "className") {
1313
+ if (m(value)) classBuffer.push(value);
1314
+ else {
1315
+ normalized[CLASS_NAME] = value;
1316
+ }
1317
+ continue;
1318
+ }
1319
+ if (key === STYLE_NAME) {
1320
+ if (m(value)) styleBuffer.push(value);
1321
+ else normalized[STYLE_NAME] = value;
1322
+ continue;
1323
+ }
1324
+ if (key === SPREAD_NAME) {
1325
+ if (!normalized[SPREAD_NAME]) normalized[SPREAD_NAME] = [];
1326
+ normalized[SPREAD_NAME].push(value);
1327
+ continue;
1328
+ }
1329
+ normalized[key] = value;
1330
+ }
1331
+ if (classBuffer.length) normalized[CLASS_NAME] = classBuffer.join(" ").trim();
1332
+ if (styleBuffer.length) {
1333
+ const s = styleBuffer.map((str) => str.endsWith(";") ? str : `${str};`).join("");
1334
+ normalized[STYLE_NAME] = s;
1335
+ }
1336
+ return normalized;
1337
+ }
1338
+ function createPropsObjectExpression(propsData, transformJSX2) {
1339
+ const objectProperties = [];
1340
+ const propsToProcess = normalizeProps(propsData);
1341
+ for (const propName in propsToProcess) {
1342
+ const propValue = propsToProcess[propName];
1343
+ if (propName === CHILDREN_NAME && (!propValue || d(propValue) && !propValue.length)) {
1344
+ continue;
1345
+ }
1346
+ const astValue = convertValueToASTNode(propValue, transformJSX2);
1347
+ if (propName === SPREAD_NAME) {
1348
+ objectProperties.push(t7.spreadElement(astValue));
1349
+ } else {
1350
+ objectProperties.push(t7.objectProperty(t7.stringLiteral(propName), astValue));
1351
+ }
1352
+ }
1353
+ return t7.objectExpression(objectProperties);
1354
+ }
1355
+ function convertValueToASTNode(value, transformJSX2) {
1356
+ if (t7.isExpression(value)) {
1357
+ return value;
1358
+ }
1359
+ if (d(value)) {
1360
+ return t7.arrayExpression(value.map((item) => convertValueToASTNode(item, transformJSX2)));
1361
+ }
1362
+ if (w(value)) {
1363
+ if (isTreeNode(value) && hasPureStringChildren(value)) {
1364
+ const stringContent = extractStringChildren(value);
1365
+ return t7.stringLiteral(stringContent);
1366
+ }
1367
+ if (value.type === 1 /* COMPONENT */ || value.type === 0 /* NORMAL */ || value.type === 2 /* TEXT */ || value.type === 5 /* SVG */) {
1368
+ const { path } = getContext();
1369
+ return transformJSX2(path, value);
1370
+ }
1371
+ if (value.type === 4 /* EXPRESSION */ && value.children && d(value.children) && value.children.length > 0) {
1372
+ return convertValueToASTNode(value.children[0], transformJSX2);
1373
+ }
1374
+ if (t7.isJSXElement(value) || t7.isJSXFragment(value)) {
1375
+ const { path } = getContext();
1376
+ const mockNodePath = {
1377
+ node: value,
1378
+ parentPath: path,
1379
+ // Keep parent path reference
1380
+ scope: path.scope
1381
+ // Keep scope reference
1382
+ };
1383
+ const tree = createTree(mockNodePath);
1384
+ return transformJSX2(path, tree);
1385
+ }
1386
+ return createPropsObjectExpression(value, transformJSX2);
1387
+ }
1388
+ if (m(value)) {
1389
+ return t7.stringLiteral(value);
1390
+ }
1391
+ if (T(value)) {
1392
+ return t7.numericLiteral(value);
1393
+ }
1394
+ if (z(value)) {
1395
+ return t7.booleanLiteral(value);
1396
+ }
1397
+ if (_(value)) {
1398
+ return t7.identifier("undefined");
1399
+ }
1400
+ if (y(value)) {
1401
+ return t7.nullLiteral();
1402
+ }
1403
+ return value;
1404
+ }
1405
+ function getSetFunctionForAttribute(attrName) {
1406
+ const { state } = getContext();
1407
+ switch (attrName) {
1408
+ case CLASS_NAME:
1409
+ return {
1410
+ name: "patchClass",
1411
+ value: state.imports.patchClass
1412
+ };
1413
+ case STYLE_NAME:
1414
+ return { name: "patchStyle", value: state.imports.patchStyle };
1415
+ default:
1416
+ return { name: "patchAttr", value: state.imports.patchAttr };
1417
+ }
1418
+ }
1419
+ function isDynamicExpression(node) {
1420
+ if (!node) return false;
1421
+ if (t7.isIdentifier(node) || t7.isMemberExpression(node) || t7.isOptionalMemberExpression(node) || t7.isCallExpression(node) || t7.isOptionalCallExpression(node) || t7.isConditionalExpression(node) || t7.isLogicalExpression(node) || t7.isTemplateLiteral(node) || t7.isTaggedTemplateExpression(node) || t7.isBinaryExpression(node) || t7.isUnaryExpression(node) || t7.isUpdateExpression(node) || t7.isAwaitExpression(node) || t7.isYieldExpression(node) || t7.isAssignmentExpression(node) || t7.isSequenceExpression(node) || t7.isArrowFunctionExpression(node) || t7.isFunctionExpression(node)) {
1422
+ return true;
1423
+ }
1424
+ if (t7.isObjectExpression(node)) {
1425
+ return deepCheckObjectDynamic(node);
1426
+ }
1427
+ if (t7.isArrayExpression(node)) {
1428
+ return node.elements.some((el) => el != null && t7.isNode(el) && isDynamicExpression(el));
1429
+ }
1430
+ if (t7.isStringLiteral(node) || t7.isNumericLiteral(node) || t7.isBooleanLiteral(node) || t7.isNullLiteral(node) || t7.isRegExpLiteral(node)) {
1431
+ return false;
1432
+ }
1433
+ return t7.isExpression(node);
1434
+ }
1435
+ function hasPureStringChildren(node) {
1436
+ if (!node.children || node.children.length === 0) {
1437
+ return false;
1438
+ }
1439
+ return node.children.every((child) => {
1440
+ if (m(child)) {
1441
+ return true;
1442
+ }
1443
+ if (isTreeNode(child) && child.type === 2 /* TEXT */) {
1444
+ return true;
1445
+ }
1446
+ return false;
1447
+ });
1448
+ }
1449
+ function extractStringChildren(node) {
1450
+ if (!node.children || node.children.length === 0) {
1451
+ return "";
1452
+ }
1453
+ return node.children.map((child) => {
1454
+ if (m(child)) {
1455
+ return child;
1456
+ }
1457
+ if (isTreeNode(child) && child.type === 2 /* TEXT */ && child.children) {
1458
+ return child.children.join("");
1459
+ }
1460
+ return "";
1461
+ }).join("");
1462
+ }
1463
+
1464
+ // src/jsx/client.ts
1465
+ function transformJSXToClient(path, node) {
1466
+ const state = path.state;
1467
+ if (node.type === 1 /* COMPONENT */) {
1468
+ const props = __spreadProps(__spreadValues({}, node.props), { children: node.children });
1469
+ return createComponentExpression(node, props);
1470
+ }
1471
+ const staticTemplate = generateStaticTemplate(node);
1472
+ const dynamicCollection = generateDynamic(node);
1473
+ const indexMap = generateIndexMap(dynamicCollection);
1474
+ const elementId = path.scope.generateUidIdentifier("_$el");
1475
+ const nodesId = path.scope.generateUidIdentifier("_$nodes");
1476
+ const statements = [];
1477
+ if (staticTemplate) {
1478
+ addImport(importMap.template);
1479
+ const tmplId = path.scope.generateUidIdentifier("_$tmpl");
1480
+ state.declarations.push(
1481
+ t8.variableDeclarator(
1482
+ tmplId,
1483
+ t8.callExpression(state.imports.template, G(staticTemplate).map(t8.stringLiteral))
1484
+ )
1485
+ );
1486
+ statements.push(
1487
+ t8.variableDeclaration("const", [
1488
+ t8.variableDeclarator(elementId, t8.callExpression(tmplId, []))
1489
+ ])
1490
+ );
1491
+ }
1492
+ if (dynamicCollection.children.length || dynamicCollection.props.length || dynamicCollection.operations.length) {
1493
+ addImport(importMap.mapNodes);
1494
+ statements.push(
1495
+ t8.variableDeclaration("const", [
1496
+ t8.variableDeclarator(
1497
+ nodesId,
1498
+ t8.callExpression(state.imports.mapNodes, [
1499
+ elementId,
1500
+ t8.arrayExpression(indexMap.map((idx) => t8.numericLiteral(idx)))
1501
+ ])
1502
+ )
1503
+ ])
1504
+ );
1505
+ if (dynamicCollection.children.length) {
1506
+ generateDynamicChildrenCode(dynamicCollection.children, statements, state, nodesId, indexMap);
1507
+ }
1508
+ if (dynamicCollection.props.length) {
1509
+ generateDynamicPropsCode(dynamicCollection.props, statements, state, nodesId, indexMap);
1510
+ }
1511
+ if (dynamicCollection.operations.length) {
1512
+ generateUnifiedMemoizedEffect(
1513
+ dynamicCollection.operations,
1514
+ statements,
1515
+ state,
1516
+ nodesId,
1517
+ indexMap
1518
+ );
1519
+ }
1520
+ }
1521
+ statements.push(t8.returnStatement(elementId));
1522
+ return t8.callExpression(t8.arrowFunctionExpression([], t8.blockStatement(statements)), []);
1523
+ }
1524
+ function generatePropKey(attrName = "attr") {
1525
+ const { operationIndex } = getContext();
1526
+ const keyMap = {
1527
+ [CLASS_NAME]: "c",
1528
+ [STYLE_NAME]: "s",
1529
+ name: "n",
1530
+ attr: "a"
120
1531
  };
1532
+ const baseKey = keyMap[attrName] || attrName.charAt(0);
1533
+ setContext(__spreadProps(__spreadValues({}, getContext()), { operationIndex: operationIndex + 1 }));
1534
+ setContext(__spreadProps(__spreadValues({}, getContext()), { operationIndex: operationIndex + 1 }));
1535
+ return `${baseKey}${operationIndex}`;
121
1536
  }
122
- function hasSiblingElement(path) {
123
- const siblings = path.getAllPrevSiblings().concat(path.getAllNextSiblings());
124
- const hasSibling = siblings.some(
125
- (siblingPath) => siblingPath.isJSXElement() || siblingPath.isJSXExpressionContainer()
126
- );
127
- return hasSibling;
1537
+ function transformJSXClientChildren(path, treeNode) {
1538
+ return transformJSXToClient(path, treeNode);
128
1539
  }
129
- function getAttrName(attribute) {
130
- if (t2.isJSXIdentifier(attribute.name)) {
131
- return attribute.name.name;
132
- }
133
- if (t2.isJSXNamespacedName(attribute.name)) {
134
- return `${attribute.name.namespace.name}:${attribute.name.name.name}`;
1540
+ function createComponentExpression(node, componentProps) {
1541
+ const { state } = getContext();
1542
+ addImport(importMap.createComponent);
1543
+ const isBuiltIn = BUILT_IN_COMPONENTS.includes(node.tag);
1544
+ if (isBuiltIn) {
1545
+ addImport(importMap[node.tag]);
135
1546
  }
136
- throw new Error("Unsupported attribute type");
137
- }
138
- function getTagName(node) {
139
- const tag = node.openingElement.name;
140
- return jsxElementNameToString(tag);
1547
+ const argTag = isBuiltIn ? state.imports[node.tag] : t8.identifier(node.tag);
1548
+ const propsObj = createPropsObjectExpression(componentProps, transformJSXClientChildren);
1549
+ const args = [argTag, propsObj];
1550
+ return t8.callExpression(state.imports[CREATE_COMPONENT_NAME], args);
141
1551
  }
142
- function jsxElementNameToString(node) {
143
- if (t2.isJSXMemberExpression(node)) {
144
- return `${jsxElementNameToString(node.object)}.${jsxElementNameToString(node.property)}`;
1552
+ function generateIndexMap({
1553
+ props,
1554
+ children,
1555
+ operations = []
1556
+ }) {
1557
+ const indexSet = /* @__PURE__ */ new Set();
1558
+ for (const item of children) {
1559
+ if (!N(item.parentIndex)) {
1560
+ indexSet.add(item.parentIndex);
1561
+ }
1562
+ if (!N(item.before)) {
1563
+ indexSet.add(item.before);
1564
+ }
145
1565
  }
146
- if (t2.isJSXIdentifier(node) || t2.isIdentifier(node)) {
147
- return node.name;
1566
+ for (const item of props) {
1567
+ if (!N(item.parentIndex)) {
1568
+ indexSet.add(item.parentIndex);
1569
+ }
148
1570
  }
149
- return `${node.namespace.name}:${node.name.name}`;
150
- }
151
- function isComponentName(tagName) {
152
- return tagName[0] && tagName[0].toLowerCase() !== tagName[0] || tagName.includes(".") || /[^a-z]/i.test(tagName[0]);
153
- }
154
- function isTextChild(path) {
155
- if (path.isJSXExpressionContainer()) {
156
- const expression = path.get("expression");
157
- if (expression.isJSXText() || expression.isStringLiteral() || expression.isNumericLiteral()) {
158
- return true;
1571
+ if (operations && operations.length > 0) {
1572
+ for (const item of operations) {
1573
+ if (!N(item.nodeIndex)) {
1574
+ indexSet.add(item.nodeIndex);
1575
+ }
159
1576
  }
160
1577
  }
161
- if (path.isJSXText() || path.isStringLiteral() || path.isNullLiteral()) {
162
- return true;
1578
+ const indexMap = Array.from(indexSet).sort((a2, b) => a2 - b);
1579
+ if (true) {
1580
+ for (const index of indexMap) {
1581
+ if (!Number.isInteger(index) || index < 1) {
1582
+ ne(`Invalid index in index map: ${index}. All indices must be positive integers.`);
1583
+ }
1584
+ }
163
1585
  }
164
- return false;
1586
+ return indexMap;
165
1587
  }
166
- function setNodeText(path, text) {
167
- if (path.isJSXText()) {
168
- path.node.value = text;
1588
+ function createRefStatement(nodesId, nodeIndex, value) {
1589
+ const elementRef = t8.memberExpression(nodesId, t8.numericLiteral(nodeIndex), true);
1590
+ const typeofCheck = t8.binaryExpression(
1591
+ "===",
1592
+ t8.unaryExpression("typeof", value),
1593
+ t8.stringLiteral("function")
1594
+ );
1595
+ const functionCall = t8.callExpression(value, [elementRef]);
1596
+ const assignmentExpr = t8.assignmentExpression(
1597
+ "=",
1598
+ t8.memberExpression(value, t8.identifier("value")),
1599
+ elementRef
1600
+ );
1601
+ const conditionalExpr = t8.conditionalExpression(typeofCheck, functionCall, assignmentExpr);
1602
+ return t8.expressionStatement(conditionalExpr);
1603
+ }
1604
+ function createAttributeStatement(functionIdentifier, nodesId, nodeIndex, value, key) {
1605
+ const args = [t8.memberExpression(nodesId, t8.numericLiteral(nodeIndex), true)];
1606
+ if (key) {
1607
+ args.push(key);
169
1608
  }
170
- if (path.isJSXExpressionContainer()) {
171
- const expression = path.get("expression");
172
- if (expression.isStringLiteral() || expression.isNumericLiteral()) {
173
- expression.replaceWith(t2.stringLiteral(text));
1609
+ if (value) {
1610
+ if (d(value)) {
1611
+ args.push(...value);
1612
+ } else {
1613
+ args.push(value);
174
1614
  }
175
1615
  }
1616
+ const functionCall = t8.callExpression(functionIdentifier, args);
1617
+ return t8.expressionStatement(functionCall);
176
1618
  }
177
- function replaceSpace(node) {
178
- return node.value.replaceAll(/\s+/g, " ").trim();
179
- }
180
- function isValidChild(path) {
181
- const regex = /^\s*$/;
182
- if (path.isStringLiteral() || path.isJSXText()) {
183
- return !regex.test(path.node.value);
1619
+ function addEventListenerStatement(attrName, attrValue, nodesId, nodeIndex, statements, state) {
1620
+ var _a;
1621
+ const eventName = attrName.slice(2).toLowerCase();
1622
+ if (Oe(eventName)) {
1623
+ const activeContext = getContext();
1624
+ if (!activeContext) {
1625
+ ne("Missing active context, unable to handle delegated events");
1626
+ return;
1627
+ }
1628
+ const elementRef = t8.memberExpression(nodesId, t8.numericLiteral(nodeIndex), true);
1629
+ const eventProperty = t8.memberExpression(elementRef, t8.stringLiteral(`_$${eventName}`), true);
1630
+ const assignmentStmt = t8.expressionStatement(
1631
+ t8.assignmentExpression("=", eventProperty, attrValue)
1632
+ );
1633
+ statements.push(assignmentStmt);
1634
+ (_a = state.events) == null ? void 0 : _a.add(eventName);
1635
+ return;
184
1636
  }
185
- return Object.keys(path.node).length > 0;
186
- }
187
- function hasObjectExpression(prop, value, props, state, isCt = false) {
188
- let ct = "";
189
- const hasConditional = value.properties.some(
190
- (property) => t2.isObjectProperty(property) && t2.isConditionalExpression(property.value)
1637
+ addImport(importMap.addEventListener);
1638
+ const eventListenerStmt = createAttributeStatement(
1639
+ state.imports.addEventListener,
1640
+ nodesId,
1641
+ nodeIndex,
1642
+ attrValue,
1643
+ t8.stringLiteral(eventName)
191
1644
  );
192
- if (hasConditional) {
193
- imports.add("useComputed");
194
- props[prop] = t2.callExpression(state.useComputed, [t2.arrowFunctionExpression([], value)]);
195
- } else if (isCt) {
196
- value.properties.forEach((property) => {
197
- if (t2.isObjectProperty(property)) {
198
- ct += `${property.key.name || property.key.value}:${property.value.value};`;
1645
+ statements.push(eventListenerStmt);
1646
+ }
1647
+ function generateSpecificAttributeCode(attributeName, attributeValue, nodesId, nodeIndex, statements, state) {
1648
+ switch (attributeName) {
1649
+ case CLASS_NAME:
1650
+ addImport(importMap.patchClass);
1651
+ statements.push(
1652
+ createAttributeStatement(state.imports.patchClass, nodesId, nodeIndex, attributeValue)
1653
+ );
1654
+ break;
1655
+ case SPREAD_NAME:
1656
+ addImport(importMap.setSpread);
1657
+ statements.push(
1658
+ createAttributeStatement(state.imports.setSpread, nodesId, nodeIndex, attributeValue)
1659
+ );
1660
+ break;
1661
+ case REF_KEY:
1662
+ statements.push(createRefStatement(nodesId, nodeIndex, attributeValue));
1663
+ break;
1664
+ case STYLE_NAME:
1665
+ addImport(importMap.patchStyle);
1666
+ statements.push(
1667
+ createAttributeStatement(state.imports.patchStyle, nodesId, nodeIndex, attributeValue)
1668
+ );
1669
+ break;
1670
+ default:
1671
+ if (q(attributeName, `${UPDATE_PREFIX}:`)) {
1672
+ addImport(importMap.bindElement);
1673
+ const attrName = attributeName.split(":")[1];
1674
+ statements.push(
1675
+ createAttributeStatement(
1676
+ state.imports.bindElement,
1677
+ nodesId,
1678
+ nodeIndex,
1679
+ attributeValue,
1680
+ t8.stringLiteral(attrName)
1681
+ )
1682
+ );
1683
+ return;
199
1684
  }
200
- });
201
- delete props[prop];
1685
+ addImport(importMap.patchAttr);
1686
+ statements.push(
1687
+ createAttributeStatement(
1688
+ state.imports.patchAttr,
1689
+ nodesId,
1690
+ nodeIndex,
1691
+ attributeValue,
1692
+ t8.stringLiteral(attributeName)
1693
+ )
1694
+ );
1695
+ break;
202
1696
  }
203
- return ct;
204
1697
  }
205
- function getNodeText(path) {
206
- if (path.isJSXText()) {
207
- return replaceSpace(path.node);
208
- }
209
- if (path.isJSXExpressionContainer()) {
210
- const expression = path.get("expression");
211
- if (expression.isStringLiteral() || expression.isNumericLiteral()) {
212
- return String(expression.node.value);
1698
+ function processIIFEExpression(node) {
1699
+ if (t8.isCallExpression(node) && (t8.isArrowFunctionExpression(node.callee) || t8.isFunctionExpression(node.callee)) && node.arguments.length === 0) {
1700
+ const callee = node.callee;
1701
+ const body = callee.body;
1702
+ if (t8.isBlockStatement(body)) {
1703
+ if (body.body.length === 1) {
1704
+ const statement = body.body[0];
1705
+ if (t8.isReturnStatement(statement) && statement.argument) {
1706
+ return statement.argument;
1707
+ }
1708
+ }
1709
+ } else if (t8.isExpression(body)) {
1710
+ return body;
213
1711
  }
214
1712
  }
215
- return "";
1713
+ return node;
216
1714
  }
217
-
218
- // src/jsx/constants.ts
219
- var selfClosingTags = [
220
- "area",
221
- "base",
222
- "br",
223
- "col",
224
- "embed",
225
- "hr",
226
- "img",
227
- "input",
228
- "link",
229
- "meta",
230
- "param",
231
- "source",
232
- "track",
233
- "wbr"
234
- ];
235
- var svgTags = [
236
- "circle",
237
- "clipPath",
238
- "defs",
239
- "ellipse",
240
- "filter",
241
- "g",
242
- "line",
243
- "linearGradient",
244
- "mask",
245
- "path",
246
- "pattern",
247
- "polygon",
248
- "polyline",
249
- "radialGradient",
250
- "rect",
251
- "stop",
252
- "symbol",
253
- "text",
254
- "use"
255
- ];
256
-
257
- // src/jsx/index.ts
258
- var currentResult;
259
- var isServer = false;
260
- function addTemplate(content, join = false) {
261
- if (isServer) {
262
- if (join && currentResult.template.length > 0) {
263
- currentResult.template[currentResult.template.length - 1] += content;
264
- } else {
265
- currentResult.template.push(content);
266
- }
267
- } else {
268
- currentResult.template += content;
1715
+ function createInsertArguments(dynamicContent, nodesIdentifier, indexMap) {
1716
+ if (N(dynamicContent.parentIndex)) {
1717
+ throw new Error("Dynamic content missing valid parent node index");
269
1718
  }
270
- }
271
- function transformJSX(path) {
272
- var _a, _b;
273
- isServer = (_b = (_a = path.state) == null ? void 0 : _a.opts) == null ? void 0 : _b.server;
274
- const preCurrentResult = currentResult;
275
- currentResult = isServer ? createServerResult() : createClientResult();
276
- transformJSXElement(path, isServer, true);
277
- path.replaceWith(isServer ? createServerNode(path) : createClientNode(path));
278
- currentResult = preCurrentResult;
279
- }
280
- function createClientNode(path) {
281
- var _a, _b;
282
- const state = path.state;
283
- const isJSXFragment = path.isJSXFragment();
284
- const isComponent = path.isJSXElement() && isComponentName(getTagName(path.node));
285
- const tmpl = isComponent ? t3.identifier(getTagName(path.node)) : path.scope.generateUidIdentifier("_tmpl$");
286
- let templateNode;
287
- if (!isComponent) {
288
- templateNode = t3.callExpression(state.template, [
289
- t3.stringLiteral(currentResult.template)
290
- ]);
291
- state.tmplDeclaration.declarations.push(t3.variableDeclarator(tmpl, templateNode));
292
- imports.add("template");
1719
+ const parentPosition = findIndexPosition(dynamicContent.parentIndex, indexMap);
1720
+ if (parentPosition === -1) {
1721
+ throw new Error(
1722
+ `Cannot find parent node index in index mapping: ${dynamicContent.parentIndex}`
1723
+ );
293
1724
  }
294
- const key = (_b = currentResult.props.key) != null ? _b : (_a = currentResult.props[0]) == null ? void 0 : _a.key;
295
- const propsArg = createProps(currentResult.props);
296
- const args = isComponent && getTagName(path.node) === "Fragment" ? [t3.stringLiteral(""), propsArg] : [tmpl, propsArg];
297
- if (key) {
298
- args.push(key);
1725
+ const argExpressions = [
1726
+ // Target parent node reference: nodes[parentPosition]
1727
+ t8.memberExpression(nodesIdentifier, t8.numericLiteral(parentPosition), true),
1728
+ // CallExpression not be use call function
1729
+ // Content lazy function: () => dynamicContent (implements on-demand calculation)
1730
+ t8.isCallExpression(dynamicContent.node) || t8.isArrowFunctionExpression(dynamicContent.node) || t8.isFunctionExpression(dynamicContent.node) ? dynamicContent.node : t8.arrowFunctionExpression([], dynamicContent.node)
1731
+ ];
1732
+ if (dynamicContent.before !== null) {
1733
+ const beforePosition = findIndexPosition(dynamicContent.before, indexMap);
1734
+ if (beforePosition === -1) {
1735
+ throw new Error(`Cannot find before node index in index mapping: ${dynamicContent.before}`);
1736
+ }
1737
+ argExpressions.push(
1738
+ t8.memberExpression(nodesIdentifier, t8.numericLiteral(beforePosition), true)
1739
+ );
299
1740
  }
300
- const fnName = isJSXFragment || isComponent && getTagName(path.node) === "Fragment" ? "Fragment" : "h";
301
- imports.add(fnName);
302
- return t3.callExpression(state[fnName], args);
1741
+ return argExpressions;
303
1742
  }
304
- function createServerNode(path) {
305
- var _a, _b;
306
- const state = path.state;
307
- const isComponent = path.isJSXElement() && isComponentName(getTagName(path.node));
308
- const tmpl = isComponent ? t3.identifier(getTagName(path.node)) : path.scope.generateUidIdentifier("_tmpl$");
309
- let templateNode;
310
- if (!isComponent) {
311
- templateNode = t3.arrayExpression(currentResult.template.map(t3.stringLiteral));
312
- state.tmplDeclaration.declarations.push(t3.variableDeclarator(tmpl, templateNode));
313
- }
314
- const key = (_b = currentResult.props.key) != null ? _b : (_a = currentResult.props[0]) == null ? void 0 : _a.key;
315
- const propsArg = createProps(currentResult.props);
316
- const args = isComponent && getTagName(path.node) === "Fragment" ? [t3.stringLiteral(""), propsArg] : [tmpl, propsArg];
317
- if (key) {
318
- args.push(key);
1743
+ function generateDynamicChildrenCode(dynamicChildren, statements, state, nodesId, indexMap) {
1744
+ addImport(importMap.insert);
1745
+ for (const dynamicContent of dynamicChildren) {
1746
+ const processedNode = processIIFEExpression(dynamicContent.node);
1747
+ const insertArgs = createInsertArguments(
1748
+ __spreadProps(__spreadValues({}, dynamicContent), { node: processedNode }),
1749
+ nodesId,
1750
+ indexMap
1751
+ );
1752
+ const insertCall = t8.callExpression(state.imports.insert, insertArgs);
1753
+ statements.push(t8.expressionStatement(insertCall));
319
1754
  }
320
- const fnName = "ssg";
321
- imports.add(fnName);
322
- return t3.callExpression(state[fnName], args);
323
1755
  }
324
- function transformJSXElement(path, isServer2 = false, isRoot = false) {
325
- const state = path.state;
326
- if (path.isJSXElement()) {
327
- const tagName = getTagName(path.node);
328
- const tagIsComponent = isComponentName(tagName);
329
- const isSelfClose = !tagIsComponent && selfClosingTags.includes(tagName);
330
- const isSvg = svgTags.includes(tagName) && currentResult.index === 1;
331
- const { props, hasExpression } = getAttrProps(path, state);
332
- if (tagIsComponent) {
333
- if (isRoot) {
334
- currentResult.props = props;
335
- const children = getChildren(path);
336
- if (children.length > 0) {
337
- const childrenGenerator = children.length === 1 ? children[0] : t3.arrayExpression(children);
338
- if (t3.isConditionalExpression(childrenGenerator)) {
339
- currentResult.props.children = t3.arrowFunctionExpression([], childrenGenerator);
340
- } else {
341
- currentResult.props.children = childrenGenerator;
1756
+ function generateDynamicPropsCode(dynamicProps, statements, state, nodesId, indexMap) {
1757
+ for (const propItem of dynamicProps) {
1758
+ const { parentIndex, props } = propItem;
1759
+ if (parentIndex === null) {
1760
+ continue;
1761
+ }
1762
+ const parentIndexPosition = indexMap.indexOf(parentIndex);
1763
+ if (parentIndexPosition === -1) {
1764
+ ne(`Cannot find parent node index: ${parentIndex}`);
1765
+ continue;
1766
+ }
1767
+ for (const [attrName, attrValue] of Object.entries(props)) {
1768
+ try {
1769
+ if (attrName.startsWith(`${UPDATE_PREFIX}:`) && Array.isArray(attrValue)) {
1770
+ if (attrValue.length === 2 && t8.isExpression(attrValue[0]) && t8.isExpression(attrValue[1])) {
1771
+ generateSpecificAttributeCode(
1772
+ attrName,
1773
+ attrValue,
1774
+ // Pass array as-is, createAttributeStatement will spread it
1775
+ nodesId,
1776
+ parentIndexPosition,
1777
+ statements,
1778
+ state
1779
+ );
342
1780
  }
1781
+ continue;
343
1782
  }
344
- } else {
345
- transformJSX(path);
346
- replaceChild(path.node);
347
- }
348
- } else {
349
- if (isSvg) {
350
- currentResult.template = isServer2 ? [`<svg _svg_ data-hk="${currentResult.index}">`] : `<svg _svg_ >`;
351
- }
352
- addTemplate(`<${tagName}${isServer2 ? ` data-hk="${currentResult.index}"` : ""}`, true);
353
- handleAttributes(props, state);
354
- addTemplate(isSelfClose ? "/>" : ">", !hasExpression);
355
- if (!isSelfClose) {
356
- transformChildren(path);
357
- if (hasSiblingElement(path) || isServer2) {
358
- addTemplate(`</${tagName}>`);
1783
+ if (!t8.isExpression(attrValue)) {
1784
+ continue;
359
1785
  }
1786
+ if (attrName.startsWith("on")) {
1787
+ addEventListenerStatement(
1788
+ attrName,
1789
+ attrValue,
1790
+ nodesId,
1791
+ parentIndexPosition,
1792
+ statements,
1793
+ state
1794
+ );
1795
+ } else {
1796
+ generateSpecificAttributeCode(
1797
+ attrName,
1798
+ attrValue,
1799
+ nodesId,
1800
+ parentIndexPosition,
1801
+ statements,
1802
+ state
1803
+ );
1804
+ }
1805
+ } catch (error) {
1806
+ ne(`Attribute processing failed (${attrName}): ${error}`);
360
1807
  }
361
1808
  }
362
- } else {
363
- currentResult.index--;
364
- transformChildren(path);
365
1809
  }
366
1810
  }
367
- function getAttrProps(path, state) {
368
- const props = {};
369
- let hasExpression = false;
370
- path.get("openingElement").get("attributes").forEach((attribute) => {
371
- if (attribute.isJSXAttribute()) {
372
- const name = getAttrName(attribute.node);
373
- const value = attribute.get("value");
374
- if (!value.node) {
375
- props[name] = true;
376
- } else if (value.isStringLiteral()) {
377
- props[name] = value.node.value;
378
- } else {
379
- if (value.isJSXExpressionContainer()) {
380
- const expression = value.get("expression");
381
- if (expression.isStringLiteral()) {
382
- props[name] = expression.node.value;
383
- } else if (expression.isNumericLiteral()) {
384
- props[name] = expression.node.value;
385
- } else if (expression.isJSXElement() || expression.isJSXFragment()) {
386
- transformJSX(expression);
387
- props[name] = expression.node;
388
- } else if (expression.isExpression()) {
389
- hasExpression = true;
390
- if (/^key|ref|on.+$/.test(name)) {
391
- props[name] = expression.node;
392
- } else if (/^bind:.+/.test(name)) {
393
- const value2 = path.scope.generateUidIdentifier("value");
394
- const bindName = name.slice(5).toLocaleLowerCase();
395
- props[bindName] = expression.node;
396
- props[`update${capitalize(bindName)}`] = t3.arrowFunctionExpression(
397
- [value2],
398
- t3.assignmentExpression("=", expression.node, value2)
399
- );
400
- } else {
401
- if (expression.isConditionalExpression()) {
402
- imports.add("useComputed");
403
- props[name] = t3.callExpression(state.useComputed, [
404
- t3.arrowFunctionExpression([], expression.node)
405
- ]);
406
- } else {
407
- props[name] = expression.node;
408
- }
409
- }
410
- }
411
- } else if (value.isJSXElement() || value.isJSXFragment()) {
412
- transformJSX(value);
413
- props[name] = value.node;
414
- }
415
- }
416
- } else if (attribute.isJSXSpreadAttribute()) {
417
- props._$spread$ = attribute.get("argument").node;
418
- hasExpression = true;
419
- } else {
420
- throw new Error("Unsupported attribute type");
421
- }
1811
+ function generateUnifiedMemoizedEffect(reactiveOperations, statements, state, nodesId, indexMap) {
1812
+ addImport(importMap.memoEffect);
1813
+ const variableDeclarations = reactiveOperations.map((op, index) => {
1814
+ const attrValue = op.attrValue;
1815
+ return t8.variableDeclarator(t8.identifier(`_v$${index}`), attrValue);
422
1816
  });
423
- return {
424
- props,
425
- hasExpression
426
- };
427
- }
428
- function getChildren(path) {
429
- return path.get("children").filter((child) => isValidChild(child)).map((child) => {
430
- if (child.isJSXElement() || child.isJSXFragment()) {
431
- transformJSX(child);
432
- } else if (child.isJSXExpressionContainer()) {
433
- child.replaceWith(child.get("expression"));
434
- } else if (child.isJSXText()) {
435
- child.replaceWith(t3.stringLiteral(replaceSpace(child.node)));
1817
+ const updateStatements = reactiveOperations.map((op, index) => {
1818
+ const parentPosition = findIndexPosition(op.nodeIndex, indexMap);
1819
+ if (parentPosition === -1) {
1820
+ throw new Error(`Cannot find parent node index in index mapping: ${op.nodeIndex}`);
1821
+ }
1822
+ const varName = t8.identifier(`_v$${index}`);
1823
+ const elementRef = t8.memberExpression(nodesId, t8.numericLiteral(parentPosition), true);
1824
+ let domOperationCall;
1825
+ if (op.setFunction.name === "patchAttr") {
1826
+ domOperationCall = t8.callExpression(op.setFunction.value, [
1827
+ elementRef,
1828
+ t8.stringLiteral(op.attrName),
1829
+ t8.memberExpression(t8.identifier("_p$"), t8.identifier(op.propKey)),
1830
+ t8.assignmentExpression(
1831
+ "=",
1832
+ t8.memberExpression(t8.identifier("_p$"), t8.identifier(op.propKey)),
1833
+ varName
1834
+ )
1835
+ ]);
436
1836
  } else {
437
- throw new Error("Unsupported child type");
1837
+ domOperationCall = t8.callExpression(op.setFunction.value, [
1838
+ elementRef,
1839
+ t8.memberExpression(t8.identifier("_p$"), t8.identifier(op.propKey)),
1840
+ t8.assignmentExpression(
1841
+ "=",
1842
+ t8.memberExpression(t8.identifier("_p$"), t8.identifier(op.propKey)),
1843
+ varName
1844
+ )
1845
+ ]);
438
1846
  }
439
- return child.node;
1847
+ return t8.expressionStatement(
1848
+ t8.logicalExpression(
1849
+ "&&",
1850
+ t8.binaryExpression(
1851
+ "!==",
1852
+ varName,
1853
+ t8.memberExpression(t8.identifier("_p$"), t8.identifier(op.propKey))
1854
+ ),
1855
+ domOperationCall
1856
+ )
1857
+ );
440
1858
  });
441
- }
442
- function replaceChild(node) {
443
- var _a, _b, _c, _d, _e;
444
- if (currentResult.isLastChild) {
445
- currentResult.index--;
446
- } else {
447
- addTemplate("<!>");
448
- }
449
- (_c = (_a = currentResult.props)[_b = currentResult.parentIndex]) != null ? _c : _a[_b] = {};
450
- (_e = (_d = currentResult.props[currentResult.parentIndex]).children) != null ? _e : _d.children = [];
451
- currentResult.props[currentResult.parentIndex].children.push(
452
- t3.arrayExpression([
453
- t3.arrowFunctionExpression([], node),
454
- currentResult.isLastChild ? t3.nullLiteral() : t3.identifier(String(currentResult.index))
455
- ])
1859
+ const effectBody = t8.blockStatement([
1860
+ // var _v$0 = expr1, _v$1 = expr2, ...;
1861
+ t8.variableDeclaration("var", variableDeclarations),
1862
+ // All update statements
1863
+ ...updateStatements,
1864
+ // return _p$;
1865
+ t8.returnStatement(t8.identifier("_p$"))
1866
+ ]);
1867
+ const effectFunction = t8.arrowFunctionExpression([t8.identifier("_p$")], effectBody);
1868
+ const initialStateProperties = reactiveOperations.map(
1869
+ (op) => t8.objectProperty(t8.identifier(op.propKey), t8.identifier("undefined"))
456
1870
  );
1871
+ const initialState = t8.objectExpression(initialStateProperties);
1872
+ const memoizedEffectCall = t8.callExpression(state.imports.memoEffect, [
1873
+ effectFunction,
1874
+ initialState
1875
+ ]);
1876
+ statements.push(t8.expressionStatement(memoizedEffectCall));
457
1877
  }
458
- function handleAttributes(props, state) {
459
- let klass = "";
460
- let style = "";
461
- for (const [prop, value] of Object.entries(props)) {
462
- if (prop === "class" && typeof value === "string") {
463
- klass += ` ${value}`;
464
- delete props[prop];
465
- } else if (prop === "style" && typeof value === "string") {
466
- style += `${value}${value.at(-1) === ";" ? "" : ";"}`;
467
- delete props[prop];
468
- } else if (value === true) {
469
- addTemplate(` ${prop}`);
470
- delete props[prop];
471
- } else if (value === false) {
472
- delete props[prop];
473
- } else if (typeof value === "string" || typeof value === "number") {
474
- addTemplate(` ${prop}="${value}"`);
475
- delete props[prop];
476
- } else if (t3.isConditionalExpression(value)) {
477
- imports.add("useComputed");
478
- props[prop] = t3.callExpression(state.useComputed, [t3.arrowFunctionExpression([], value)]);
479
- } else if (t3.isObjectExpression(value)) {
480
- const val = hasObjectExpression(
481
- prop,
482
- value,
483
- props,
484
- state,
485
- prop === "class" || prop === "style"
486
- );
487
- if (val) {
488
- if (prop === "class") {
489
- klass += ` ${val}`;
490
- }
491
- if (prop === "style") {
492
- style += `${val}${val.at(-1) === ";" ? "" : ";"}`;
493
- }
494
- }
495
- }
1878
+ function generateStaticTemplate(node) {
1879
+ if (!node || node.type === 1 /* COMPONENT */) {
1880
+ return "";
496
1881
  }
497
- if (Object.keys(props).length > 0) {
498
- currentResult.props[currentResult.index] = props;
1882
+ switch (node.type) {
1883
+ case 2 /* TEXT */:
1884
+ return Array.isArray(node.children) ? node.children.join("") : "";
1885
+ case 6 /* COMMENT */:
1886
+ return "<!>";
1887
+ case 0 /* NORMAL */:
1888
+ case 5 /* SVG */:
1889
+ return gstForNormal(node);
1890
+ default:
1891
+ return gstForChildren(node);
499
1892
  }
500
- if (klass.trim()) {
501
- addTemplate(` class="${klass.trim()}"`);
1893
+ }
1894
+ function gstForNormal(node) {
1895
+ if (!node.tag) {
1896
+ return gstForChildren(node);
502
1897
  }
503
- if (style.trim()) {
504
- addTemplate(` style="${style.trim()}"`);
1898
+ const attributes = serializeAttributes(node.props);
1899
+ const startTag = `<${node.tag}${attributes ? ` ${attributes}` : ""}`;
1900
+ if (node.selfClosing) {
1901
+ return `${startTag}/>`;
505
1902
  }
1903
+ return `${startTag}>${gstForChildren(node)}</${node.tag}>`;
506
1904
  }
507
- function transformChildren(path) {
508
- const parentIndex = currentResult.index;
509
- path.get("children").reduce((pre, cur) => {
510
- if (isValidChild(cur)) {
511
- const lastChild = pre.at(-1);
512
- if (lastChild && isTextChild(cur) && isTextChild(lastChild)) {
513
- setNodeText(lastChild, getNodeText(lastChild) + getNodeText(cur));
514
- } else {
515
- pre.push(cur);
516
- }
517
- }
518
- return pre;
519
- }, []).forEach((child, i, arr) => {
520
- currentResult.parentIndex = parentIndex;
521
- currentResult.isLastChild = i === arr.length - 1;
522
- transformChild(child);
523
- });
524
- }
525
- function transformChild(child) {
526
- currentResult.index++;
527
- if (child.isJSXElement() || child.isJSXFragment()) {
528
- transformJSXElement(child, false);
529
- } else if (child.isJSXExpressionContainer()) {
530
- const expression = child.get("expression");
531
- if (expression.isStringLiteral() || expression.isNumericLiteral()) {
532
- addTemplate(`${expression.node.value}`, true);
533
- } else if (expression.isExpression()) {
534
- replaceChild(expression.node);
535
- } else if (t3.isJSXEmptyExpression(expression.node)) {
536
- } else {
537
- throw new Error("Unsupported child type");
1905
+ function gstForChildren(node) {
1906
+ if (!node.children || !node.children.length) {
1907
+ return "";
1908
+ }
1909
+ const childTemplates = [];
1910
+ for (const child of node.children) {
1911
+ if (w(child)) {
1912
+ const childTemplate = generateStaticTemplate(child);
1913
+ childTemplates.push(childTemplate);
1914
+ } else if (m(child)) {
1915
+ childTemplates.push(child);
538
1916
  }
539
- } else if (child.isJSXText()) {
540
- addTemplate(replaceSpace(child.node), true);
541
- } else {
542
- throw new Error("Unsupported child type");
543
1917
  }
1918
+ return childTemplates.join("");
544
1919
  }
545
- function createProps(props) {
546
- const result = [];
547
- for (const prop in props) {
548
- let value = props[prop];
549
- if (prop === "key") {
550
- continue;
551
- }
552
- if (Array.isArray(value)) {
553
- value = t3.arrayExpression(value);
554
- }
555
- if (typeof value === "object" && value !== null && !t3.isNode(value)) {
556
- value = createProps(value);
557
- }
558
- if (typeof value === "string") {
559
- value = t3.stringLiteral(value);
560
- }
561
- if (typeof value === "number") {
562
- value = t3.numericLiteral(value);
563
- }
564
- if (typeof value === "boolean") {
565
- value = t3.booleanLiteral(value);
566
- }
567
- if (value === void 0) {
568
- value = t3.tsUndefinedKeyword();
1920
+ function generateDynamic(node) {
1921
+ const dynamicCollection = {
1922
+ props: [],
1923
+ children: [],
1924
+ operations: []
1925
+ };
1926
+ function walk(node2, parentNode) {
1927
+ processNodeDynamic(dynamicCollection, node2, parentNode);
1928
+ if (node2.type === 1 /* COMPONENT */ || node2.type === 3 /* FRAGMENT */) {
1929
+ return;
569
1930
  }
570
- if (value === null) {
571
- value = t3.nullLiteral();
1931
+ if (node2.children && node2.children.length) {
1932
+ node2.children.forEach((child) => {
1933
+ if (isTreeNode(child)) {
1934
+ walk(child, node2);
1935
+ }
1936
+ });
572
1937
  }
573
- if (prop === "_$spread$") {
574
- result.push(t3.spreadElement(value));
575
- } else {
576
- result.push(t3.objectProperty(t3.stringLiteral(prop), value));
1938
+ }
1939
+ walk(node);
1940
+ return dynamicCollection;
1941
+ }
1942
+ function processNodeDynamic(dynamicCollection, node, parentNode) {
1943
+ var _a, _b, _c, _d;
1944
+ const { children, props, operations } = dynamicCollection;
1945
+ switch (node.type) {
1946
+ case 1 /* COMPONENT */: {
1947
+ const componentProps = __spreadProps(__spreadValues({}, node.props), { children: node.children });
1948
+ const componentExpr = createComponentExpression(node, componentProps);
1949
+ children.push({
1950
+ index: node.index,
1951
+ node: componentExpr,
1952
+ before: findBeforeIndex(node, parentNode),
1953
+ parentIndex: (_a = parentNode == null ? void 0 : parentNode.index) != null ? _a : null
1954
+ });
1955
+ break;
577
1956
  }
1957
+ case 4 /* EXPRESSION */:
1958
+ if (node.children && node.children.length > 0) {
1959
+ const firstChild = node.children[0];
1960
+ if (w(firstChild) && t8.isNode(firstChild) && t8.isExpression(firstChild)) {
1961
+ children.push({
1962
+ index: node.index,
1963
+ node: t8.arrowFunctionExpression([], firstChild),
1964
+ before: findBeforeIndex(node, parentNode),
1965
+ parentIndex: (_b = parentNode == null ? void 0 : parentNode.index) != null ? _b : null
1966
+ });
1967
+ } else if (w(firstChild) && t8.isNode(firstChild) && t8.isJSXElement(firstChild)) {
1968
+ children.push({
1969
+ index: node.index,
1970
+ node: createComponentExpression(node, { children: [firstChild] }),
1971
+ before: findBeforeIndex(node, parentNode),
1972
+ parentIndex: (_c = parentNode == null ? void 0 : parentNode.index) != null ? _c : null
1973
+ });
1974
+ }
1975
+ }
1976
+ break;
1977
+ // Text nodes don't need dynamic processing (already handled in template stage)
1978
+ case 2 /* TEXT */:
1979
+ break;
1980
+ default:
1981
+ if (node.props && Object.keys(node.props).length > 0) {
1982
+ const currentProps = {};
1983
+ for (const [attrName, attrValue] of Object.entries(node.props)) {
1984
+ const isReactive = t8.isNode(attrValue) && isDynamicExpression(attrValue) && !q(attrName, `${UPDATE_PREFIX}:`) && !q(attrName, EVENT_ATTR_NAME) && attrName !== REF_KEY;
1985
+ if (q(attrName, `${UPDATE_PREFIX}:`)) {
1986
+ const name = attrName.split(":")[1];
1987
+ const setFunction = getSetFunctionForAttribute();
1988
+ addImport(importMap[setFunction.name]);
1989
+ operations.push({
1990
+ nodeIndex: node == null ? void 0 : node.index,
1991
+ attrName: name,
1992
+ attrValue: attrValue[0],
1993
+ setFunction,
1994
+ propKey: generatePropKey()
1995
+ });
1996
+ }
1997
+ if (isReactive && t8.isExpression(attrValue)) {
1998
+ const setFunction = getSetFunctionForAttribute(attrName);
1999
+ addImport(importMap[setFunction.name]);
2000
+ operations.push({
2001
+ nodeIndex: node == null ? void 0 : node.index,
2002
+ attrName,
2003
+ attrValue,
2004
+ setFunction,
2005
+ propKey: generatePropKey(attrName)
2006
+ });
2007
+ } else {
2008
+ currentProps[attrName] = attrValue;
2009
+ }
2010
+ }
2011
+ if (Object.keys(currentProps).length > 0) {
2012
+ props.push({
2013
+ props: currentProps,
2014
+ parentIndex: (_d = node == null ? void 0 : node.index) != null ? _d : null
2015
+ });
2016
+ }
2017
+ }
2018
+ break;
578
2019
  }
579
- return t3.objectExpression(result);
580
2020
  }
581
2021
 
582
- // src/signal/symbol.ts
583
- import { types as t5 } from "@babel/core";
584
-
585
- // src/shared.ts
586
- import { types as t4 } from "@babel/core";
587
- function isSymbolStart(path, name) {
588
- const state = path.state;
589
- const { symbol } = (state == null ? void 0 : state.opts) || "$";
590
- return startsWith(name, symbol);
2022
+ // src/jsx/ssg.ts
2023
+ import { types as t9 } from "@babel/core";
2024
+ function transformJSXToSSG(path, treeNode) {
2025
+ const { state } = getContext();
2026
+ const result = transformTemplate(treeNode);
2027
+ const { templates, dynamics } = result;
2028
+ if (treeNode.type === 1 /* COMPONENT */ || treeNode.type === 3 /* FRAGMENT */) {
2029
+ const componentProps = __spreadProps(__spreadValues({}, treeNode.props), { children: treeNode.children });
2030
+ addImport(importMap.createComponent);
2031
+ return t9.callExpression(state.imports.createComponent, [
2032
+ t9.identifier(treeNode.tag),
2033
+ createPropsObjectExpression(componentProps, transformJSXToSSG)
2034
+ ]);
2035
+ }
2036
+ const args = [];
2037
+ if (templates && templates.length > 0) {
2038
+ addImport(importMap.template);
2039
+ const tmplId = path.scope.generateUidIdentifier("_tmpl$");
2040
+ const templateNode = t9.arrayExpression(templates.map((str) => t9.stringLiteral(str)));
2041
+ state.declarations.push(t9.variableDeclarator(tmplId, templateNode));
2042
+ args.push(tmplId);
2043
+ }
2044
+ args.push(t9.callExpression(state.imports.getHydrationKey, []));
2045
+ addImport(importMap.render);
2046
+ addImport(importMap.getHydrationKey);
2047
+ const textDynamics = dynamics.filter((d2) => d2.type === "text");
2048
+ const attrDynamics = dynamics.filter((d2) => d2.type === "attr");
2049
+ attrDynamics.forEach((dynamic) => {
2050
+ args.push(dynamic.node);
2051
+ });
2052
+ textDynamics.forEach((dynamic) => {
2053
+ args.push(dynamic.node);
2054
+ });
2055
+ return t9.callExpression(state.imports.render, args);
591
2056
  }
592
-
593
- // src/signal/symbol.ts
594
- function replaceSymbol(path) {
595
- const { init, id } = path.node;
596
- const variableName = id.name;
597
- if (t5.isObjectPattern(id) || t5.isArrayPattern(id) || !isSymbolStart(path, variableName)) return;
598
- const isComputed = init && (t5.isFunctionExpression(init) || t5.isArrowFunctionExpression(init)) && path.parent.kind === "const";
599
- const hookName = isComputed ? "useComputed" : "useSignal";
600
- const newInit = t5.callExpression(t5.identifier(path.state[hookName].name), init ? [init] : []);
601
- imports.add(hookName);
602
- path.node.init = newInit;
2057
+ function transformTemplate(treeNode) {
2058
+ const result = {
2059
+ templates: [],
2060
+ dynamics: []
2061
+ };
2062
+ walkTreeNode(treeNode, result);
2063
+ return result;
603
2064
  }
604
- function symbolIdentifier(path) {
605
- const parentPath = path.parentPath;
606
- if (!shouldProcessIdentifier(parentPath)) return;
607
- const { node } = path;
608
- if (!isSymbolStart(path, node.name)) return;
609
- if (!path.findParent((p) => p.isMemberExpression() && p.node.property.name === "value")) {
610
- path.replaceWith(t5.memberExpression(t5.identifier(node.name), t5.identifier("value")));
2065
+ function walkTreeNode(treeNode, result) {
2066
+ if (!treeNode) {
2067
+ return;
2068
+ }
2069
+ switch (treeNode.type) {
2070
+ case 1 /* COMPONENT */:
2071
+ case 3 /* FRAGMENT */:
2072
+ handleComponent(treeNode, result);
2073
+ break;
2074
+ case 4 /* EXPRESSION */:
2075
+ handleExpression(treeNode, result);
2076
+ break;
2077
+ case 2 /* TEXT */:
2078
+ handleText(treeNode, result);
2079
+ break;
2080
+ case 0 /* NORMAL */:
2081
+ case 5 /* SVG */:
2082
+ handleElement(treeNode, result);
2083
+ break;
2084
+ case 6 /* COMMENT */:
2085
+ addTemplate(result, "<!>", true);
2086
+ break;
2087
+ default:
2088
+ if (treeNode.children && treeNode.children.length > 0) {
2089
+ processChildren2(treeNode.children, result);
2090
+ }
2091
+ break;
611
2092
  }
612
2093
  }
613
- function shouldProcessIdentifier(parentPath) {
614
- return parentPath && !t5.isVariableDeclarator(parentPath) && !t5.isImportSpecifier(parentPath) && !t5.isObjectProperty(parentPath) && !t5.isArrayPattern(parentPath) && !t5.isObjectPattern(parentPath);
615
- }
616
- function symbolObjectPattern(path) {
617
- path.node.properties.forEach((property) => {
618
- if (t5.isObjectProperty(property) && t5.isIdentifier(property.key) && isSymbolStart(path, property.key.name)) {
619
- property.key = t5.identifier(property.key.name);
2094
+ var addTemplate = (result, content, join = false) => {
2095
+ if (result.templates.length === 0) {
2096
+ result.templates.push(content);
2097
+ } else {
2098
+ if (join) {
2099
+ result.templates[result.templates.length - 1] += content;
2100
+ } else {
2101
+ result.templates.push(content);
620
2102
  }
2103
+ }
2104
+ };
2105
+ var handleComponent = (node, result) => {
2106
+ result.templates.push("");
2107
+ const { state } = getContext();
2108
+ const componentProps = __spreadValues({}, node.props);
2109
+ if (node.children.length) {
2110
+ componentProps.children = node.children;
2111
+ }
2112
+ addImport(importMap.createComponent);
2113
+ const componentExpr = t9.callExpression(state.imports.createComponent, [
2114
+ t9.identifier(node.tag),
2115
+ createPropsObjectExpression(componentProps, transformJSXToSSG)
2116
+ ]);
2117
+ result.dynamics.push({
2118
+ type: "text",
2119
+ node: componentExpr
621
2120
  });
622
- }
623
- function symbolArrayPattern(path) {
624
- path.node.elements.forEach((element) => {
625
- if (t5.isIdentifier(element) && element.name.startsWith("$")) {
626
- element.name = t5.identifier(element.name).name;
627
- } else if (t5.isObjectPattern(element)) {
628
- symbolObjectPattern({ node: element });
2121
+ };
2122
+ var handleExpression = (node, result) => {
2123
+ if (!node.children || node.children.length === 0) {
2124
+ return;
2125
+ }
2126
+ const firstChild = node.children[0];
2127
+ result.templates.push("");
2128
+ if (j(firstChild)) {
2129
+ const { state } = getContext();
2130
+ addImport(importMap.escapeHTML);
2131
+ result.dynamics.push({
2132
+ type: "text",
2133
+ node: t9.callExpression(state.imports.escapeHTML, [t9.valueToNode(firstChild)])
2134
+ });
2135
+ } else if (w(firstChild)) {
2136
+ const exprNode = firstChild;
2137
+ if (t9.isCallExpression(exprNode) && t9.isMemberExpression(exprNode.callee) && exprNode.arguments.length > 0) {
2138
+ const mapCallback = exprNode.arguments[0];
2139
+ if ((t9.isArrowFunctionExpression(mapCallback) || t9.isFunctionExpression(mapCallback)) && mapCallback.body) {
2140
+ let jsxElement = void 0;
2141
+ if (t9.isJSXElement(mapCallback.body)) {
2142
+ jsxElement = mapCallback.body;
2143
+ } else if (t9.isBlockStatement(mapCallback.body)) {
2144
+ const returnStmt = mapCallback.body.body.find((stmt) => t9.isReturnStatement(stmt));
2145
+ if (returnStmt && t9.isReturnStatement(returnStmt) && returnStmt.argument && t9.isJSXElement(returnStmt.argument)) {
2146
+ jsxElement = returnStmt.argument;
2147
+ }
2148
+ } else if (t9.isParenthesizedExpression(mapCallback.body) && t9.isJSXElement(mapCallback.body.expression)) {
2149
+ jsxElement = mapCallback.body.expression;
2150
+ }
2151
+ if (jsxElement) {
2152
+ const { state } = getContext();
2153
+ const tagName = jsxElement.openingElement.name.type === "JSXIdentifier" ? jsxElement.openingElement.name.name : "";
2154
+ const props = {};
2155
+ jsxElement.openingElement.attributes.forEach((attr) => {
2156
+ if (t9.isJSXAttribute(attr)) {
2157
+ const name = attr.name.name;
2158
+ if (t9.isJSXExpressionContainer(attr.value)) {
2159
+ props[name] = attr.value.expression;
2160
+ } else if (t9.isStringLiteral(attr.value)) {
2161
+ props[name] = attr.value.value;
2162
+ } else if (attr.value === null) {
2163
+ props[name] = true;
2164
+ }
2165
+ } else if (t9.isJSXSpreadAttribute(attr)) {
2166
+ props._$spread$ = attr.argument;
2167
+ }
2168
+ });
2169
+ if (tagName === FRAGMENT_NAME) {
2170
+ addImport(importMap.Fragment);
2171
+ const newCallback = t9.arrowFunctionExpression(
2172
+ mapCallback.params,
2173
+ t9.callExpression(state.imports.Fragment, [
2174
+ createPropsObjectExpression(props, transformJSXToSSG)
2175
+ ])
2176
+ );
2177
+ exprNode.arguments[0] = newCallback;
2178
+ } else if (tagName && tagName[0] === tagName[0].toUpperCase()) {
2179
+ addImport(importMap.createComponent);
2180
+ const newCallback = t9.arrowFunctionExpression(
2181
+ mapCallback.params,
2182
+ t9.callExpression(state.imports.createComponent, [
2183
+ t9.identifier(tagName),
2184
+ createPropsObjectExpression(props, transformJSXToSSG)
2185
+ ])
2186
+ );
2187
+ exprNode.arguments[0] = newCallback;
2188
+ }
2189
+ }
2190
+ }
629
2191
  }
630
- });
631
- }
632
-
633
- // src/signal/import.ts
634
- import { types as t6 } from "@babel/core";
635
- function replaceImportDeclaration(path) {
636
- path.node.specifiers.forEach((specifier) => {
637
- const variableName = specifier.local.name;
638
- if (startsWith(variableName, "$") && !isVariableUsedAsObject(path, variableName)) {
639
- path.scope.rename(variableName, `${variableName}.value`);
640
- specifier.local.name = variableName;
2192
+ result.dynamics.push({
2193
+ type: "text",
2194
+ node: exprNode
2195
+ });
2196
+ }
2197
+ };
2198
+ var handleText = (node, result) => {
2199
+ if (node.children && node.children.length > 0) {
2200
+ addTemplate(result, node.children.join(""), true);
2201
+ }
2202
+ };
2203
+ var handleElement = (node, result) => {
2204
+ let openTag = `<${node.tag} data-idx="${node.index}"`;
2205
+ const { staticAttrs, dynamicAttrs } = processAttributes(node.props || {});
2206
+ openTag += staticAttrs;
2207
+ addTemplate(result, openTag, true);
2208
+ addTemplate(result, node.selfClosing ? "/>" : ">", dynamicAttrs.length === 0);
2209
+ if (!node.selfClosing && node.children && node.children.length > 0) {
2210
+ processChildren2(node.children, result);
2211
+ }
2212
+ if (!node.selfClosing) {
2213
+ addTemplate(result, `</${node.tag}>`, true);
2214
+ }
2215
+ processDynamicAttributes(dynamicAttrs, result);
2216
+ };
2217
+ var processChildren2 = (children, result) => {
2218
+ children.forEach((child) => {
2219
+ if (isTreeNode(child)) {
2220
+ walkTreeNode(child, result);
2221
+ } else if (m(child)) {
2222
+ addTemplate(result, child, true);
641
2223
  }
642
2224
  });
643
- }
644
- function isVariableUsedAsObject(path, variableName) {
645
- var _a;
646
- const binding = path.scope.getBinding(variableName);
647
- return ((_a = binding == null ? void 0 : binding.referencePaths) == null ? void 0 : _a.some((referencePath) => {
648
- if (t6.isMemberExpression(referencePath.parent)) {
649
- const { object, property } = referencePath.parent;
650
- if (t6.isIdentifier(object, { name: variableName })) {
651
- referencePath.parentPath.replaceWith(
652
- t6.memberExpression(t6.memberExpression(object, t6.identifier("value")), property)
653
- );
654
- return true;
2225
+ };
2226
+ function processAttributes(props) {
2227
+ let staticAttrs = "";
2228
+ const dynamicAttrs = [];
2229
+ for (const [prop, value] of Object.entries(props)) {
2230
+ if (prop.startsWith(EVENT_ATTR_NAME) || prop.startsWith(UPDATE_PREFIX)) {
2231
+ continue;
2232
+ }
2233
+ if (j(value)) {
2234
+ if (value === true) {
2235
+ staticAttrs += ` ${prop}`;
2236
+ } else if (A(value)) {
2237
+ staticAttrs += ` ${prop}="${value.toString()}"`;
2238
+ } else if (value !== false) {
2239
+ staticAttrs += ` ${prop}="${value}"`;
655
2240
  }
2241
+ } else if (t9.isExpression(value)) {
2242
+ dynamicAttrs.push({ name: prop, value });
656
2243
  }
657
- return false;
658
- })) || false;
2244
+ }
2245
+ return { staticAttrs, dynamicAttrs };
659
2246
  }
660
-
661
- // src/signal/props.ts
662
- import { types as t7 } from "@babel/core";
663
- function replaceProps(path) {
664
- var _a;
665
- const state = path.state;
666
- const firstParam = path.node.params[0];
667
- if (!firstParam || !t7.isObjectPattern(firstParam)) return;
668
- const returnStatement = path.get("body").get("body").find((statement) => statement.isReturnStatement());
669
- if (!returnStatement || !t7.isJSXElement((_a = returnStatement.node) == null ? void 0 : _a.argument)) return;
670
- const replaceProperties = (properties2, parentPath) => {
671
- properties2.forEach((property) => {
672
- if (t7.isObjectProperty(property) && t7.isIdentifier(property.key)) {
673
- const keyName = property.key.name;
674
- if (t7.isIdentifier(property.value)) {
675
- path.scope.rename(property.value.name, `${parentPath}${keyName}`);
676
- } else if (t7.isObjectPattern(property.value)) {
677
- replaceProperties(property.value.properties, `${parentPath}${keyName}.`);
678
- }
679
- }
2247
+ var processDynamicAttributes = (dynamicAttrs, result) => {
2248
+ dynamicAttrs.forEach((attr) => {
2249
+ const { state } = getContext();
2250
+ addImport(importMap.patchAttr);
2251
+ addImport(importMap.escapeHTML);
2252
+ result.dynamics.push({
2253
+ type: "attr",
2254
+ node: t9.callExpression(state.imports.patchAttr, [
2255
+ t9.stringLiteral(attr.name),
2256
+ t9.callExpression(state.imports.escapeHTML, [attr.value]),
2257
+ t9.booleanLiteral(false)
2258
+ ]),
2259
+ attrName: attr.name
680
2260
  });
681
- };
682
- const properties = firstParam.properties;
683
- const notRestProperties = properties.filter(
684
- (property) => !t7.isRestElement(property)
685
- );
686
- replaceProperties(notRestProperties, "__props.");
687
- const notRestNames = notRestProperties.map((property) => property.key.name);
688
- if (notRestNames.some((name) => startsWith(name, "$"))) {
689
- console.warn("props name can not start with $");
690
- return;
2261
+ });
2262
+ };
2263
+
2264
+ // src/jsx/index.ts
2265
+ var transformStrategies = {
2266
+ ["client" /* CLIENT */]: transformJSXToClient,
2267
+ ["ssr" /* SSR */]: transformJSXToClient,
2268
+ ["ssg" /* SSG */]: transformJSXToSSG
2269
+ };
2270
+ var getRenderingStrategy = (mode) => {
2271
+ const strategy = transformStrategies[mode];
2272
+ if (!strategy) {
2273
+ throw new Error(`Unsupported render mode: ${mode}`);
691
2274
  }
692
- handleRestElement(path, state, properties, notRestNames);
693
- }
694
- function handleRestElement(path, state, properties, notRestNames) {
695
- const restElement = properties.find((property) => t7.isRestElement(property));
696
- path.node.params[0] = t7.identifier("__props");
697
- if (restElement) {
698
- const restName = restElement.argument.name;
699
- if (notRestNames.length === 0) {
700
- path.node.params[0] = t7.identifier(restName);
701
- } else {
702
- const restVariableDeclaration = createRestVariableDeclaration(state, restName, notRestNames);
703
- imports.add("useReactive");
704
- path.node.body.body.unshift(restVariableDeclaration);
705
- }
2275
+ return strategy;
2276
+ };
2277
+ function transformJSX(path) {
2278
+ var _a, _b;
2279
+ try {
2280
+ const mode = ((_b = (_a = path.state) == null ? void 0 : _a.opts) == null ? void 0 : _b.mode) || "client" /* CLIENT */;
2281
+ const strategy = getRenderingStrategy(mode);
2282
+ const tree = createTree(path);
2283
+ setContext({ state: path.state, path, operationIndex: 0 });
2284
+ const result = strategy(path, tree);
2285
+ path.replaceWith(result);
2286
+ resetContext();
2287
+ } catch (error_) {
2288
+ console.warn("JSX transformation failed in test:", { error_ });
2289
+ resetContext();
2290
+ throw error_;
706
2291
  }
707
2292
  }
708
- function createRestVariableDeclaration(state, restName, notRestNames) {
709
- return t7.variableDeclaration("const", [
710
- t7.variableDeclarator(
711
- t7.identifier(restName),
712
- t7.callExpression(state.useReactive, [
713
- t7.identifier("__props"),
714
- t7.arrayExpression(notRestNames.map((name) => t7.stringLiteral(name)))
715
- ])
716
- )
717
- ]);
718
- }
719
2293
 
720
2294
  // src/index.ts
721
- function src_default() {
2295
+ function index_default() {
722
2296
  return {
723
2297
  name: "babel-plugin-essor",
724
- manipulateOptions({ filename }, parserOpts) {
725
- if (filename.endsWith(".ts") || filename.endsWith(".tsx")) {
726
- parserOpts.plugins.push("typescript");
727
- }
2298
+ manipulateOptions(_2, parserOpts) {
728
2299
  parserOpts.plugins.push("jsx");
729
2300
  },
730
2301
  visitor: {
731
2302
  Program: transformProgram,
732
- FunctionDeclaration: replaceProps,
733
- ArrowFunctionExpression: replaceProps,
734
- VariableDeclarator: replaceSymbol,
735
- ImportDeclaration: replaceImportDeclaration,
736
- Identifier: symbolIdentifier,
737
- ObjectPattern: symbolObjectPattern,
738
- ArrayPattern: symbolArrayPattern,
2303
+ // props
2304
+ FunctionDeclaration: transformProps,
2305
+ ArrowFunctionExpression: transformProps,
2306
+ // JSX
739
2307
  JSXElement: transformJSX,
740
2308
  JSXFragment: transformJSX
741
2309
  }
742
2310
  };
743
2311
  }
744
2312
  export {
745
- src_default as default
2313
+ index_default as default
746
2314
  };
747
2315
  //# sourceMappingURL=index.js.map