index.mjs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. var __defProp = Object.defineProperty;
  2. var __defProps = Object.defineProperties;
  3. var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
  4. var __getOwnPropSymbols = Object.getOwnPropertySymbols;
  5. var __hasOwnProp = Object.prototype.hasOwnProperty;
  6. var __propIsEnum = Object.prototype.propertyIsEnumerable;
  7. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  8. var __spreadValues = (a, b) => {
  9. for (var prop in b || (b = {}))
  10. if (__hasOwnProp.call(b, prop))
  11. __defNormalProp(a, prop, b[prop]);
  12. if (__getOwnPropSymbols)
  13. for (var prop of __getOwnPropSymbols(b)) {
  14. if (__propIsEnum.call(b, prop))
  15. __defNormalProp(a, prop, b[prop]);
  16. }
  17. return a;
  18. };
  19. var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
  20. // src/index.ts
  21. import * as t5 from "@babel/types";
  22. import template from "@babel/template";
  23. import syntaxJsx from "@babel/plugin-syntax-jsx";
  24. import { addNamed, addNamespace, isModule } from "@babel/helper-module-imports";
  25. // src/transform-vue-jsx.ts
  26. import * as t3 from "@babel/types";
  27. import { addDefault } from "@babel/helper-module-imports";
  28. // src/utils.ts
  29. import * as t from "@babel/types";
  30. import htmlTags from "html-tags";
  31. import svgTags from "svg-tags";
  32. // src/slotFlags.ts
  33. var SlotFlags = /* @__PURE__ */ ((SlotFlags2) => {
  34. SlotFlags2[SlotFlags2["STABLE"] = 1] = "STABLE";
  35. SlotFlags2[SlotFlags2["DYNAMIC"] = 2] = "DYNAMIC";
  36. SlotFlags2[SlotFlags2["FORWARDED"] = 3] = "FORWARDED";
  37. return SlotFlags2;
  38. })(SlotFlags || {});
  39. var slotFlags_default = SlotFlags;
  40. // src/utils.ts
  41. var FRAGMENT = "Fragment";
  42. var KEEP_ALIVE = "KeepAlive";
  43. var createIdentifier = (state, name) => state.get(name)();
  44. var isDirective = (src) => src.startsWith("v-") || src.startsWith("v") && src.length >= 2 && src[1] >= "A" && src[1] <= "Z";
  45. var shouldTransformedToSlots = (tag) => !(tag.match(RegExp(`^_?${FRAGMENT}\\d*$`)) || tag === KEEP_ALIVE);
  46. var checkIsComponent = (path, state) => {
  47. var _a, _b;
  48. const namePath = path.get("name");
  49. if (namePath.isJSXMemberExpression()) {
  50. return shouldTransformedToSlots(namePath.node.property.name);
  51. }
  52. const tag = namePath.node.name;
  53. return !((_b = (_a = state.opts).isCustomElement) == null ? void 0 : _b.call(_a, tag)) && shouldTransformedToSlots(tag) && !htmlTags.includes(tag) && !svgTags.includes(tag);
  54. };
  55. var transformJSXMemberExpression = (path) => {
  56. const objectPath = path.node.object;
  57. const propertyPath = path.node.property;
  58. const transformedObject = t.isJSXMemberExpression(objectPath) ? transformJSXMemberExpression(
  59. path.get("object")
  60. ) : t.isJSXIdentifier(objectPath) ? t.identifier(objectPath.name) : t.nullLiteral();
  61. const transformedProperty = t.identifier(propertyPath.name);
  62. return t.memberExpression(transformedObject, transformedProperty);
  63. };
  64. var getTag = (path, state) => {
  65. var _a, _b;
  66. const namePath = path.get("openingElement").get("name");
  67. if (namePath.isJSXIdentifier()) {
  68. const { name } = namePath.node;
  69. if (!htmlTags.includes(name) && !svgTags.includes(name)) {
  70. return name === FRAGMENT ? createIdentifier(state, FRAGMENT) : path.scope.hasBinding(name) ? t.identifier(name) : ((_b = (_a = state.opts).isCustomElement) == null ? void 0 : _b.call(_a, name)) ? t.stringLiteral(name) : t.callExpression(createIdentifier(state, "resolveComponent"), [
  71. t.stringLiteral(name)
  72. ]);
  73. }
  74. return t.stringLiteral(name);
  75. }
  76. if (namePath.isJSXMemberExpression()) {
  77. return transformJSXMemberExpression(namePath);
  78. }
  79. throw new Error(`getTag: ${namePath.type} is not supported`);
  80. };
  81. var getJSXAttributeName = (path) => {
  82. const nameNode = path.node.name;
  83. if (t.isJSXIdentifier(nameNode)) {
  84. return nameNode.name;
  85. }
  86. return `${nameNode.namespace.name}:${nameNode.name.name}`;
  87. };
  88. var transformJSXText = (path) => {
  89. const str = transformText(path.node.value);
  90. return str !== "" ? t.stringLiteral(str) : null;
  91. };
  92. var transformText = (text) => {
  93. const lines = text.split(/\r\n|\n|\r/);
  94. let lastNonEmptyLine = 0;
  95. for (let i = 0; i < lines.length; i++) {
  96. if (lines[i].match(/[^ \t]/)) {
  97. lastNonEmptyLine = i;
  98. }
  99. }
  100. let str = "";
  101. for (let i = 0; i < lines.length; i++) {
  102. const line = lines[i];
  103. const isFirstLine = i === 0;
  104. const isLastLine = i === lines.length - 1;
  105. const isLastNonEmptyLine = i === lastNonEmptyLine;
  106. let trimmedLine = line.replace(/\t/g, " ");
  107. if (!isFirstLine) {
  108. trimmedLine = trimmedLine.replace(/^[ ]+/, "");
  109. }
  110. if (!isLastLine) {
  111. trimmedLine = trimmedLine.replace(/[ ]+$/, "");
  112. }
  113. if (trimmedLine) {
  114. if (!isLastNonEmptyLine) {
  115. trimmedLine += " ";
  116. }
  117. str += trimmedLine;
  118. }
  119. }
  120. return str;
  121. };
  122. var transformJSXExpressionContainer = (path) => path.get("expression").node;
  123. var transformJSXSpreadChild = (path) => t.spreadElement(path.get("expression").node);
  124. var walksScope = (path, name, slotFlag) => {
  125. if (path.scope.hasBinding(name) && path.parentPath) {
  126. if (t.isJSXElement(path.parentPath.node)) {
  127. path.parentPath.setData("slotFlag", slotFlag);
  128. }
  129. walksScope(path.parentPath, name, slotFlag);
  130. }
  131. };
  132. var buildIIFE = (path, children) => {
  133. const { parentPath } = path;
  134. if (parentPath.isAssignmentExpression()) {
  135. const { left } = parentPath.node;
  136. if (t.isIdentifier(left)) {
  137. return children.map((child) => {
  138. if (t.isIdentifier(child) && child.name === left.name) {
  139. const insertName = path.scope.generateUidIdentifier(child.name);
  140. parentPath.insertBefore(
  141. t.variableDeclaration("const", [
  142. t.variableDeclarator(
  143. insertName,
  144. t.callExpression(
  145. t.functionExpression(
  146. null,
  147. [],
  148. t.blockStatement([t.returnStatement(child)])
  149. ),
  150. []
  151. )
  152. )
  153. ])
  154. );
  155. return insertName;
  156. }
  157. return child;
  158. });
  159. }
  160. }
  161. return children;
  162. };
  163. var onRE = /^on[^a-z]/;
  164. var isOn = (key) => onRE.test(key);
  165. var mergeAsArray = (existing, incoming) => {
  166. if (t.isArrayExpression(existing.value)) {
  167. existing.value.elements.push(incoming.value);
  168. } else {
  169. existing.value = t.arrayExpression([
  170. existing.value,
  171. incoming.value
  172. ]);
  173. }
  174. };
  175. var dedupeProperties = (properties = [], mergeProps) => {
  176. if (!mergeProps) {
  177. return properties;
  178. }
  179. const knownProps = /* @__PURE__ */ new Map();
  180. const deduped = [];
  181. properties.forEach((prop) => {
  182. if (t.isStringLiteral(prop.key)) {
  183. const { value: name } = prop.key;
  184. const existing = knownProps.get(name);
  185. if (existing) {
  186. if (name === "style" || name === "class" || name.startsWith("on")) {
  187. mergeAsArray(existing, prop);
  188. }
  189. } else {
  190. knownProps.set(name, prop);
  191. deduped.push(prop);
  192. }
  193. } else {
  194. deduped.push(prop);
  195. }
  196. });
  197. return deduped;
  198. };
  199. var isConstant = (node) => {
  200. if (t.isIdentifier(node)) {
  201. return node.name === "undefined";
  202. }
  203. if (t.isArrayExpression(node)) {
  204. const { elements } = node;
  205. return elements.every((element) => element && isConstant(element));
  206. }
  207. if (t.isObjectExpression(node)) {
  208. return node.properties.every(
  209. (property) => isConstant(property.value)
  210. );
  211. }
  212. if (t.isLiteral(node)) {
  213. return true;
  214. }
  215. return false;
  216. };
  217. var transformJSXSpreadAttribute = (nodePath, path, mergeProps, args) => {
  218. const argument = path.get("argument");
  219. const properties = t.isObjectExpression(argument.node) ? argument.node.properties : void 0;
  220. if (!properties) {
  221. if (argument.isIdentifier()) {
  222. walksScope(
  223. nodePath,
  224. argument.node.name,
  225. slotFlags_default.DYNAMIC
  226. );
  227. }
  228. args.push(mergeProps ? argument.node : t.spreadElement(argument.node));
  229. } else if (mergeProps) {
  230. args.push(t.objectExpression(properties));
  231. } else {
  232. args.push(...properties);
  233. }
  234. };
  235. // src/parseDirectives.ts
  236. import * as t2 from "@babel/types";
  237. var getType = (path) => {
  238. const typePath = path.get("attributes").find((attribute) => {
  239. if (!attribute.isJSXAttribute()) {
  240. return false;
  241. }
  242. return attribute.get("name").isJSXIdentifier() && attribute.get("name").node.name === "type";
  243. });
  244. return typePath ? typePath.get("value").node : null;
  245. };
  246. var parseModifiers = (value) => t2.isArrayExpression(value) ? value.elements.map((el) => t2.isStringLiteral(el) ? el.value : "").filter(Boolean) : [];
  247. var parseDirectives = (params) => {
  248. var _a, _b;
  249. const { path, value, state, tag, isComponent } = params;
  250. const args = [];
  251. const vals = [];
  252. const modifiersSet = [];
  253. let directiveName;
  254. let directiveArgument;
  255. let directiveModifiers;
  256. if ("namespace" in path.node.name) {
  257. [directiveName, directiveArgument] = params.name.split(":");
  258. directiveName = path.node.name.namespace.name;
  259. directiveArgument = path.node.name.name.name;
  260. directiveModifiers = directiveArgument.split("_").slice(1);
  261. } else {
  262. const underscoreModifiers = params.name.split("_");
  263. directiveName = underscoreModifiers.shift() || "";
  264. directiveModifiers = underscoreModifiers;
  265. }
  266. directiveName = directiveName.replace(/^v/, "").replace(/^-/, "").replace(/^\S/, (s) => s.toLowerCase());
  267. if (directiveArgument) {
  268. args.push(t2.stringLiteral(directiveArgument));
  269. }
  270. const isVModels = directiveName === "models";
  271. const isVModel = directiveName === "model";
  272. if (isVModel && !path.get("value").isJSXExpressionContainer()) {
  273. throw new Error("You have to use JSX Expression inside your v-model");
  274. }
  275. if (isVModels && !isComponent) {
  276. throw new Error("v-models can only use in custom components");
  277. }
  278. const shouldResolve = !["html", "text", "model", "models"].includes(directiveName) || isVModel && !isComponent;
  279. let modifiers = directiveModifiers;
  280. if (t2.isArrayExpression(value)) {
  281. const elementsList = isVModels ? value.elements : [value];
  282. elementsList.forEach((element) => {
  283. if (isVModels && !t2.isArrayExpression(element)) {
  284. throw new Error("You should pass a Two-dimensional Arrays to v-models");
  285. }
  286. const { elements } = element;
  287. const [first, second, third] = elements;
  288. if (second && !t2.isArrayExpression(second) && !t2.isSpreadElement(second)) {
  289. args.push(second);
  290. modifiers = parseModifiers(third);
  291. } else if (t2.isArrayExpression(second)) {
  292. if (!shouldResolve) {
  293. args.push(t2.nullLiteral());
  294. }
  295. modifiers = parseModifiers(second);
  296. } else if (!shouldResolve) {
  297. args.push(t2.nullLiteral());
  298. }
  299. modifiersSet.push(new Set(modifiers));
  300. vals.push(first);
  301. });
  302. } else if (isVModel && !shouldResolve) {
  303. args.push(t2.nullLiteral());
  304. modifiersSet.push(new Set(directiveModifiers));
  305. } else {
  306. modifiersSet.push(new Set(directiveModifiers));
  307. }
  308. return {
  309. directiveName,
  310. modifiers: modifiersSet,
  311. values: vals.length ? vals : [value],
  312. args,
  313. directive: shouldResolve ? [
  314. resolveDirective(path, state, tag, directiveName),
  315. vals[0] || value,
  316. ((_a = modifiersSet[0]) == null ? void 0 : _a.size) ? args[0] || t2.unaryExpression("void", t2.numericLiteral(0), true) : args[0],
  317. !!((_b = modifiersSet[0]) == null ? void 0 : _b.size) && t2.objectExpression(
  318. [...modifiersSet[0]].map(
  319. (modifier) => t2.objectProperty(t2.identifier(modifier), t2.booleanLiteral(true))
  320. )
  321. )
  322. ].filter(Boolean) : void 0
  323. };
  324. };
  325. var resolveDirective = (path, state, tag, directiveName) => {
  326. if (directiveName === "show") {
  327. return createIdentifier(state, "vShow");
  328. }
  329. if (directiveName === "model") {
  330. let modelToUse;
  331. const type = getType(path.parentPath);
  332. switch (tag.value) {
  333. case "select":
  334. modelToUse = createIdentifier(state, "vModelSelect");
  335. break;
  336. case "textarea":
  337. modelToUse = createIdentifier(state, "vModelText");
  338. break;
  339. default:
  340. if (t2.isStringLiteral(type) || !type) {
  341. switch (type == null ? void 0 : type.value) {
  342. case "checkbox":
  343. modelToUse = createIdentifier(state, "vModelCheckbox");
  344. break;
  345. case "radio":
  346. modelToUse = createIdentifier(state, "vModelRadio");
  347. break;
  348. default:
  349. modelToUse = createIdentifier(state, "vModelText");
  350. }
  351. } else {
  352. modelToUse = createIdentifier(state, "vModelDynamic");
  353. }
  354. }
  355. return modelToUse;
  356. }
  357. return t2.callExpression(createIdentifier(state, "resolveDirective"), [
  358. t2.stringLiteral(directiveName)
  359. ]);
  360. };
  361. var parseDirectives_default = parseDirectives;
  362. // src/transform-vue-jsx.ts
  363. var xlinkRE = /^xlink([A-Z])/;
  364. var getJSXAttributeValue = (path, state) => {
  365. const valuePath = path.get("value");
  366. if (valuePath.isJSXElement()) {
  367. return transformJSXElement(valuePath, state);
  368. }
  369. if (valuePath.isStringLiteral()) {
  370. return t3.stringLiteral(transformText(valuePath.node.value));
  371. }
  372. if (valuePath.isJSXExpressionContainer()) {
  373. return transformJSXExpressionContainer(valuePath);
  374. }
  375. return null;
  376. };
  377. var buildProps = (path, state) => {
  378. const tag = getTag(path, state);
  379. const isComponent = checkIsComponent(path.get("openingElement"), state);
  380. const props = path.get("openingElement").get("attributes");
  381. const directives = [];
  382. const dynamicPropNames = /* @__PURE__ */ new Set();
  383. let slots = null;
  384. let patchFlag = 0;
  385. if (props.length === 0) {
  386. return {
  387. tag,
  388. isComponent,
  389. slots,
  390. props: t3.nullLiteral(),
  391. directives,
  392. patchFlag,
  393. dynamicPropNames
  394. };
  395. }
  396. let properties = [];
  397. let hasRef = false;
  398. let hasClassBinding = false;
  399. let hasStyleBinding = false;
  400. let hasHydrationEventBinding = false;
  401. let hasDynamicKeys = false;
  402. const mergeArgs = [];
  403. const { mergeProps = true } = state.opts;
  404. props.forEach((prop) => {
  405. if (prop.isJSXAttribute()) {
  406. let name = getJSXAttributeName(prop);
  407. const attributeValue = getJSXAttributeValue(prop, state);
  408. if (!isConstant(attributeValue) || name === "ref") {
  409. if (!isComponent && isOn(name) && // omit the flag for click handlers becaues hydration gives click
  410. // dedicated fast path.
  411. name.toLowerCase() !== "onclick" && // omit v-model handlers
  412. name !== "onUpdate:modelValue") {
  413. hasHydrationEventBinding = true;
  414. }
  415. if (name === "ref") {
  416. hasRef = true;
  417. } else if (name === "class" && !isComponent) {
  418. hasClassBinding = true;
  419. } else if (name === "style" && !isComponent) {
  420. hasStyleBinding = true;
  421. } else if (name !== "key" && !isDirective(name) && name !== "on") {
  422. dynamicPropNames.add(name);
  423. }
  424. }
  425. if (state.opts.transformOn && (name === "on" || name === "nativeOn")) {
  426. if (!state.get("transformOn")) {
  427. state.set(
  428. "transformOn",
  429. addDefault(path, "@vue/babel-helper-vue-transform-on", {
  430. nameHint: "_transformOn"
  431. })
  432. );
  433. }
  434. mergeArgs.push(
  435. t3.callExpression(state.get("transformOn"), [
  436. attributeValue || t3.booleanLiteral(true)
  437. ])
  438. );
  439. return;
  440. }
  441. if (isDirective(name)) {
  442. const { directive, modifiers, values, args, directiveName } = parseDirectives_default({
  443. tag,
  444. isComponent,
  445. name,
  446. path: prop,
  447. state,
  448. value: attributeValue
  449. });
  450. if (directiveName === "slots") {
  451. slots = attributeValue;
  452. return;
  453. }
  454. if (directive) {
  455. directives.push(t3.arrayExpression(directive));
  456. } else if (directiveName === "html") {
  457. properties.push(
  458. t3.objectProperty(t3.stringLiteral("innerHTML"), values[0])
  459. );
  460. dynamicPropNames.add("innerHTML");
  461. } else if (directiveName === "text") {
  462. properties.push(
  463. t3.objectProperty(t3.stringLiteral("textContent"), values[0])
  464. );
  465. dynamicPropNames.add("textContent");
  466. }
  467. if (["models", "model"].includes(directiveName)) {
  468. values.forEach((value, index) => {
  469. var _a;
  470. const propName = args[index];
  471. const isDynamic = propName && !t3.isStringLiteral(propName) && !t3.isNullLiteral(propName);
  472. if (!directive) {
  473. properties.push(
  474. t3.objectProperty(
  475. t3.isNullLiteral(propName) ? t3.stringLiteral("modelValue") : propName,
  476. value,
  477. isDynamic
  478. )
  479. );
  480. if (!isDynamic) {
  481. dynamicPropNames.add(
  482. (propName == null ? void 0 : propName.value) || "modelValue"
  483. );
  484. }
  485. if ((_a = modifiers[index]) == null ? void 0 : _a.size) {
  486. properties.push(
  487. t3.objectProperty(
  488. isDynamic ? t3.binaryExpression(
  489. "+",
  490. propName,
  491. t3.stringLiteral("Modifiers")
  492. ) : t3.stringLiteral(
  493. `${(propName == null ? void 0 : propName.value) || "model"}Modifiers`
  494. ),
  495. t3.objectExpression(
  496. [...modifiers[index]].map(
  497. (modifier) => t3.objectProperty(
  498. t3.stringLiteral(modifier),
  499. t3.booleanLiteral(true)
  500. )
  501. )
  502. ),
  503. isDynamic
  504. )
  505. );
  506. }
  507. }
  508. const updateName = isDynamic ? t3.binaryExpression("+", t3.stringLiteral("onUpdate"), propName) : t3.stringLiteral(
  509. `onUpdate:${(propName == null ? void 0 : propName.value) || "modelValue"}`
  510. );
  511. properties.push(
  512. t3.objectProperty(
  513. updateName,
  514. t3.arrowFunctionExpression(
  515. [t3.identifier("$event")],
  516. t3.assignmentExpression(
  517. "=",
  518. value,
  519. t3.identifier("$event")
  520. )
  521. ),
  522. isDynamic
  523. )
  524. );
  525. if (!isDynamic) {
  526. dynamicPropNames.add(updateName.value);
  527. } else {
  528. hasDynamicKeys = true;
  529. }
  530. });
  531. }
  532. } else {
  533. if (name.match(xlinkRE)) {
  534. name = name.replace(
  535. xlinkRE,
  536. (_, firstCharacter) => `xlink:${firstCharacter.toLowerCase()}`
  537. );
  538. }
  539. properties.push(
  540. t3.objectProperty(
  541. t3.stringLiteral(name),
  542. attributeValue || t3.booleanLiteral(true)
  543. )
  544. );
  545. }
  546. } else {
  547. if (properties.length && mergeProps) {
  548. mergeArgs.push(
  549. t3.objectExpression(dedupeProperties(properties, mergeProps))
  550. );
  551. properties = [];
  552. }
  553. hasDynamicKeys = true;
  554. transformJSXSpreadAttribute(
  555. path,
  556. prop,
  557. mergeProps,
  558. mergeProps ? mergeArgs : properties
  559. );
  560. }
  561. });
  562. if (hasDynamicKeys) {
  563. patchFlag |= 16 /* FULL_PROPS */;
  564. } else {
  565. if (hasClassBinding) {
  566. patchFlag |= 2 /* CLASS */;
  567. }
  568. if (hasStyleBinding) {
  569. patchFlag |= 4 /* STYLE */;
  570. }
  571. if (dynamicPropNames.size) {
  572. patchFlag |= 8 /* PROPS */;
  573. }
  574. if (hasHydrationEventBinding) {
  575. patchFlag |= 32 /* HYDRATE_EVENTS */;
  576. }
  577. }
  578. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) && (hasRef || directives.length > 0)) {
  579. patchFlag |= 512 /* NEED_PATCH */;
  580. }
  581. let propsExpression = t3.nullLiteral();
  582. if (mergeArgs.length) {
  583. if (properties.length) {
  584. mergeArgs.push(
  585. t3.objectExpression(dedupeProperties(properties, mergeProps))
  586. );
  587. }
  588. if (mergeArgs.length > 1) {
  589. propsExpression = t3.callExpression(
  590. createIdentifier(state, "mergeProps"),
  591. mergeArgs
  592. );
  593. } else {
  594. propsExpression = mergeArgs[0];
  595. }
  596. } else if (properties.length) {
  597. if (properties.length === 1 && t3.isSpreadElement(properties[0])) {
  598. propsExpression = properties[0].argument;
  599. } else {
  600. propsExpression = t3.objectExpression(
  601. dedupeProperties(properties, mergeProps)
  602. );
  603. }
  604. }
  605. return {
  606. tag,
  607. props: propsExpression,
  608. isComponent,
  609. slots,
  610. directives,
  611. patchFlag,
  612. dynamicPropNames
  613. };
  614. };
  615. var getChildren = (paths, state) => paths.map((path) => {
  616. if (path.isJSXText()) {
  617. const transformedText = transformJSXText(path);
  618. if (transformedText) {
  619. return t3.callExpression(createIdentifier(state, "createTextVNode"), [
  620. transformedText
  621. ]);
  622. }
  623. return transformedText;
  624. }
  625. if (path.isJSXExpressionContainer()) {
  626. const expression = transformJSXExpressionContainer(path);
  627. if (t3.isIdentifier(expression)) {
  628. const { name } = expression;
  629. const { referencePaths = [] } = path.scope.getBinding(name) || {};
  630. referencePaths.forEach((referencePath) => {
  631. walksScope(referencePath, name, slotFlags_default.DYNAMIC);
  632. });
  633. }
  634. return expression;
  635. }
  636. if (path.isJSXSpreadChild()) {
  637. return transformJSXSpreadChild(path);
  638. }
  639. if (path.isCallExpression()) {
  640. return path.node;
  641. }
  642. if (path.isJSXElement()) {
  643. return transformJSXElement(path, state);
  644. }
  645. throw new Error(`getChildren: ${path.type} is not supported`);
  646. }).filter(
  647. (value) => value != null && !t3.isJSXEmptyExpression(value)
  648. );
  649. var transformJSXElement = (path, state) => {
  650. const children = getChildren(path.get("children"), state);
  651. const {
  652. tag,
  653. props,
  654. isComponent,
  655. directives,
  656. patchFlag,
  657. dynamicPropNames,
  658. slots
  659. } = buildProps(path, state);
  660. const { optimize = false } = state.opts;
  661. const slotFlag = path.getData("slotFlag") || slotFlags_default.STABLE;
  662. let VNodeChild;
  663. if (children.length > 1 || slots) {
  664. VNodeChild = isComponent ? children.length ? t3.objectExpression(
  665. [
  666. !!children.length && t3.objectProperty(
  667. t3.identifier("default"),
  668. t3.arrowFunctionExpression(
  669. [],
  670. t3.arrayExpression(buildIIFE(path, children))
  671. )
  672. ),
  673. ...slots ? t3.isObjectExpression(slots) ? slots.properties : [t3.spreadElement(slots)] : [],
  674. optimize && t3.objectProperty(t3.identifier("_"), t3.numericLiteral(slotFlag))
  675. ].filter(Boolean)
  676. ) : slots : t3.arrayExpression(children);
  677. } else if (children.length === 1) {
  678. const { enableObjectSlots = true } = state.opts;
  679. const child = children[0];
  680. const objectExpression4 = t3.objectExpression(
  681. [
  682. t3.objectProperty(
  683. t3.identifier("default"),
  684. t3.arrowFunctionExpression(
  685. [],
  686. t3.arrayExpression(buildIIFE(path, [child]))
  687. )
  688. ),
  689. optimize && t3.objectProperty(
  690. t3.identifier("_"),
  691. t3.numericLiteral(slotFlag)
  692. )
  693. ].filter(Boolean)
  694. );
  695. if (t3.isIdentifier(child) && isComponent) {
  696. VNodeChild = enableObjectSlots ? t3.conditionalExpression(
  697. t3.callExpression(
  698. state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(),
  699. [child]
  700. ),
  701. child,
  702. objectExpression4
  703. ) : objectExpression4;
  704. } else if (t3.isCallExpression(child) && child.loc && isComponent) {
  705. if (enableObjectSlots) {
  706. const { scope } = path;
  707. const slotId = scope.generateUidIdentifier("slot");
  708. if (scope) {
  709. scope.push({
  710. id: slotId,
  711. kind: "let"
  712. });
  713. }
  714. const alternate = t3.objectExpression(
  715. [
  716. t3.objectProperty(
  717. t3.identifier("default"),
  718. t3.arrowFunctionExpression(
  719. [],
  720. t3.arrayExpression(buildIIFE(path, [slotId]))
  721. )
  722. ),
  723. optimize && t3.objectProperty(
  724. t3.identifier("_"),
  725. t3.numericLiteral(slotFlag)
  726. )
  727. ].filter(Boolean)
  728. );
  729. const assignment = t3.assignmentExpression("=", slotId, child);
  730. const condition = t3.callExpression(
  731. state.get("@vue/babel-plugin-jsx/runtimeIsSlot")(),
  732. [assignment]
  733. );
  734. VNodeChild = t3.conditionalExpression(condition, slotId, alternate);
  735. } else {
  736. VNodeChild = objectExpression4;
  737. }
  738. } else if (t3.isFunctionExpression(child) || t3.isArrowFunctionExpression(child)) {
  739. VNodeChild = t3.objectExpression([
  740. t3.objectProperty(t3.identifier("default"), child)
  741. ]);
  742. } else if (t3.isObjectExpression(child)) {
  743. VNodeChild = t3.objectExpression(
  744. [
  745. ...child.properties,
  746. optimize && t3.objectProperty(t3.identifier("_"), t3.numericLiteral(slotFlag))
  747. ].filter(Boolean)
  748. );
  749. } else {
  750. VNodeChild = isComponent ? t3.objectExpression([
  751. t3.objectProperty(
  752. t3.identifier("default"),
  753. t3.arrowFunctionExpression([], t3.arrayExpression([child]))
  754. )
  755. ]) : t3.arrayExpression([child]);
  756. }
  757. }
  758. const createVNode = t3.callExpression(
  759. createIdentifier(state, "createVNode"),
  760. [
  761. tag,
  762. props,
  763. VNodeChild || t3.nullLiteral(),
  764. !!patchFlag && optimize && t3.numericLiteral(patchFlag),
  765. !!dynamicPropNames.size && optimize && t3.arrayExpression(
  766. [...dynamicPropNames.keys()].map((name) => t3.stringLiteral(name))
  767. )
  768. ].filter(Boolean)
  769. );
  770. if (!directives.length) {
  771. return createVNode;
  772. }
  773. return t3.callExpression(createIdentifier(state, "withDirectives"), [
  774. createVNode,
  775. t3.arrayExpression(directives)
  776. ]);
  777. };
  778. var transform_vue_jsx_default = {
  779. JSXElement: {
  780. exit(path, state) {
  781. path.replaceWith(transformJSXElement(path, state));
  782. }
  783. }
  784. };
  785. // src/sugar-fragment.ts
  786. import * as t4 from "@babel/types";
  787. var transformFragment = (path, Fragment) => {
  788. const children = path.get("children") || [];
  789. return t4.jsxElement(
  790. t4.jsxOpeningElement(Fragment, []),
  791. t4.jsxClosingElement(Fragment),
  792. children.map(({ node }) => node),
  793. false
  794. );
  795. };
  796. var sugar_fragment_default = {
  797. JSXFragment: {
  798. enter(path, state) {
  799. const fragmentCallee = createIdentifier(state, FRAGMENT);
  800. path.replaceWith(
  801. transformFragment(
  802. path,
  803. t4.isIdentifier(fragmentCallee) ? t4.jsxIdentifier(fragmentCallee.name) : t4.jsxMemberExpression(
  804. t4.jsxIdentifier(fragmentCallee.object.name),
  805. t4.jsxIdentifier(fragmentCallee.property.name)
  806. )
  807. )
  808. );
  809. }
  810. }
  811. };
  812. // src/index.ts
  813. var hasJSX = (parentPath) => {
  814. let fileHasJSX = false;
  815. parentPath.traverse({
  816. JSXElement(path) {
  817. fileHasJSX = true;
  818. path.stop();
  819. },
  820. JSXFragment(path) {
  821. fileHasJSX = true;
  822. path.stop();
  823. }
  824. });
  825. return fileHasJSX;
  826. };
  827. var JSX_ANNOTATION_REGEX = /\*?\s*@jsx\s+([^\s]+)/;
  828. var src_default = ({ types }) => ({
  829. name: "babel-plugin-jsx",
  830. inherits: syntaxJsx,
  831. visitor: __spreadProps(__spreadValues(__spreadValues({}, transform_vue_jsx_default), sugar_fragment_default), {
  832. Program: {
  833. enter(path, state) {
  834. if (hasJSX(path)) {
  835. const importNames = [
  836. "createVNode",
  837. "Fragment",
  838. "resolveComponent",
  839. "withDirectives",
  840. "vShow",
  841. "vModelSelect",
  842. "vModelText",
  843. "vModelCheckbox",
  844. "vModelRadio",
  845. "vModelText",
  846. "vModelDynamic",
  847. "resolveDirective",
  848. "mergeProps",
  849. "createTextVNode",
  850. "isVNode"
  851. ];
  852. if (isModule(path)) {
  853. const importMap = {};
  854. importNames.forEach((name) => {
  855. state.set(name, () => {
  856. if (importMap[name]) {
  857. return types.cloneNode(importMap[name]);
  858. }
  859. const identifier5 = addNamed(path, name, "vue", {
  860. ensureLiveReference: true
  861. });
  862. importMap[name] = identifier5;
  863. return identifier5;
  864. });
  865. });
  866. const { enableObjectSlots = true } = state.opts;
  867. if (enableObjectSlots) {
  868. state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
  869. if (importMap.runtimeIsSlot) {
  870. return importMap.runtimeIsSlot;
  871. }
  872. const { name: isVNodeName } = state.get(
  873. "isVNode"
  874. )();
  875. const isSlot = path.scope.generateUidIdentifier("isSlot");
  876. const ast = template.ast`
  877. function ${isSlot.name}(s) {
  878. return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${isVNodeName}(s));
  879. }
  880. `;
  881. const lastImport = path.get("body").filter((p) => p.isImportDeclaration()).pop();
  882. if (lastImport) {
  883. lastImport.insertAfter(ast);
  884. }
  885. importMap.runtimeIsSlot = isSlot;
  886. return isSlot;
  887. });
  888. }
  889. } else {
  890. let sourceName;
  891. importNames.forEach((name) => {
  892. state.set(name, () => {
  893. if (!sourceName) {
  894. sourceName = addNamespace(path, "vue", {
  895. ensureLiveReference: true
  896. });
  897. }
  898. return t5.memberExpression(sourceName, t5.identifier(name));
  899. });
  900. });
  901. const helpers = {};
  902. const { enableObjectSlots = true } = state.opts;
  903. if (enableObjectSlots) {
  904. state.set("@vue/babel-plugin-jsx/runtimeIsSlot", () => {
  905. if (helpers.runtimeIsSlot) {
  906. return helpers.runtimeIsSlot;
  907. }
  908. const isSlot = path.scope.generateUidIdentifier("isSlot");
  909. const { object: objectName } = state.get(
  910. "isVNode"
  911. )();
  912. const ast = template.ast`
  913. function ${isSlot.name}(s) {
  914. return typeof s === 'function' || (Object.prototype.toString.call(s) === '[object Object]' && !${objectName.name}.isVNode(s));
  915. }
  916. `;
  917. const nodePaths = path.get("body");
  918. const lastImport = nodePaths.filter(
  919. (p) => p.isVariableDeclaration() && p.node.declarations.some(
  920. (d) => {
  921. var _a;
  922. return ((_a = d.id) == null ? void 0 : _a.name) === sourceName.name;
  923. }
  924. )
  925. ).pop();
  926. if (lastImport) {
  927. lastImport.insertAfter(ast);
  928. }
  929. return isSlot;
  930. });
  931. }
  932. }
  933. const {
  934. opts: { pragma = "" },
  935. file
  936. } = state;
  937. if (pragma) {
  938. state.set("createVNode", () => t5.identifier(pragma));
  939. }
  940. if (file.ast.comments) {
  941. for (const comment of file.ast.comments) {
  942. const jsxMatches = JSX_ANNOTATION_REGEX.exec(comment.value);
  943. if (jsxMatches) {
  944. state.set("createVNode", () => t5.identifier(jsxMatches[1]));
  945. }
  946. }
  947. }
  948. }
  949. },
  950. exit(path) {
  951. const body = path.get("body");
  952. const specifiersMap = /* @__PURE__ */ new Map();
  953. body.filter(
  954. (nodePath) => t5.isImportDeclaration(nodePath.node) && nodePath.node.source.value === "vue"
  955. ).forEach((nodePath) => {
  956. const { specifiers: specifiers2 } = nodePath.node;
  957. let shouldRemove = false;
  958. specifiers2.forEach((specifier) => {
  959. if (!specifier.loc && t5.isImportSpecifier(specifier) && t5.isIdentifier(specifier.imported)) {
  960. specifiersMap.set(specifier.imported.name, specifier);
  961. shouldRemove = true;
  962. }
  963. });
  964. if (shouldRemove) {
  965. nodePath.remove();
  966. }
  967. });
  968. const specifiers = [...specifiersMap.keys()].map(
  969. (imported) => specifiersMap.get(imported)
  970. );
  971. if (specifiers.length) {
  972. path.unshiftContainer(
  973. "body",
  974. t5.importDeclaration(specifiers, t5.stringLiteral("vue"))
  975. );
  976. }
  977. }
  978. }
  979. })
  980. });
  981. export {
  982. src_default as default
  983. };