版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

810 lines
25 KiB

  1. // src/core/impl.ts
  2. import MagicString from "magic-string";
  3. // ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
  4. var WalkerBase = class {
  5. constructor() {
  6. this.should_skip = false;
  7. this.should_remove = false;
  8. this.replacement = null;
  9. this.context = {
  10. skip: () => this.should_skip = true,
  11. remove: () => this.should_remove = true,
  12. replace: (node) => this.replacement = node
  13. };
  14. }
  15. /**
  16. * @template {Node} Parent
  17. * @param {Parent | null | undefined} parent
  18. * @param {keyof Parent | null | undefined} prop
  19. * @param {number | null | undefined} index
  20. * @param {Node} node
  21. */
  22. replace(parent, prop, index, node) {
  23. if (parent && prop) {
  24. if (index != null) {
  25. parent[prop][index] = node;
  26. } else {
  27. parent[prop] = node;
  28. }
  29. }
  30. }
  31. /**
  32. * @template {Node} Parent
  33. * @param {Parent | null | undefined} parent
  34. * @param {keyof Parent | null | undefined} prop
  35. * @param {number | null | undefined} index
  36. */
  37. remove(parent, prop, index) {
  38. if (parent && prop) {
  39. if (index !== null && index !== void 0) {
  40. parent[prop].splice(index, 1);
  41. } else {
  42. delete parent[prop];
  43. }
  44. }
  45. }
  46. };
  47. // ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
  48. var SyncWalker = class extends WalkerBase {
  49. /**
  50. *
  51. * @param {SyncHandler} [enter]
  52. * @param {SyncHandler} [leave]
  53. */
  54. constructor(enter, leave) {
  55. super();
  56. this.should_skip = false;
  57. this.should_remove = false;
  58. this.replacement = null;
  59. this.context = {
  60. skip: () => this.should_skip = true,
  61. remove: () => this.should_remove = true,
  62. replace: (node) => this.replacement = node
  63. };
  64. this.enter = enter;
  65. this.leave = leave;
  66. }
  67. /**
  68. * @template {Node} Parent
  69. * @param {Node} node
  70. * @param {Parent | null} parent
  71. * @param {keyof Parent} [prop]
  72. * @param {number | null} [index]
  73. * @returns {Node | null}
  74. */
  75. visit(node, parent, prop, index) {
  76. if (node) {
  77. if (this.enter) {
  78. const _should_skip = this.should_skip;
  79. const _should_remove = this.should_remove;
  80. const _replacement = this.replacement;
  81. this.should_skip = false;
  82. this.should_remove = false;
  83. this.replacement = null;
  84. this.enter.call(this.context, node, parent, prop, index);
  85. if (this.replacement) {
  86. node = this.replacement;
  87. this.replace(parent, prop, index, node);
  88. }
  89. if (this.should_remove) {
  90. this.remove(parent, prop, index);
  91. }
  92. const skipped = this.should_skip;
  93. const removed = this.should_remove;
  94. this.should_skip = _should_skip;
  95. this.should_remove = _should_remove;
  96. this.replacement = _replacement;
  97. if (skipped)
  98. return node;
  99. if (removed)
  100. return null;
  101. }
  102. let key;
  103. for (key in node) {
  104. const value = node[key];
  105. if (value && typeof value === "object") {
  106. if (Array.isArray(value)) {
  107. const nodes = (
  108. /** @type {Array<unknown>} */
  109. value
  110. );
  111. for (let i = 0; i < nodes.length; i += 1) {
  112. const item = nodes[i];
  113. if (isNode(item)) {
  114. if (!this.visit(item, node, key, i)) {
  115. i--;
  116. }
  117. }
  118. }
  119. } else if (isNode(value)) {
  120. this.visit(value, node, key, null);
  121. }
  122. }
  123. }
  124. if (this.leave) {
  125. const _replacement = this.replacement;
  126. const _should_remove = this.should_remove;
  127. this.replacement = null;
  128. this.should_remove = false;
  129. this.leave.call(this.context, node, parent, prop, index);
  130. if (this.replacement) {
  131. node = this.replacement;
  132. this.replace(parent, prop, index, node);
  133. }
  134. if (this.should_remove) {
  135. this.remove(parent, prop, index);
  136. }
  137. const removed = this.should_remove;
  138. this.replacement = _replacement;
  139. this.should_remove = _should_remove;
  140. if (removed)
  141. return null;
  142. }
  143. }
  144. return node;
  145. }
  146. };
  147. function isNode(value) {
  148. return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
  149. }
  150. // ../../node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
  151. function walk(ast, { enter, leave }) {
  152. const instance = new SyncWalker(enter, leave);
  153. return instance.visit(ast, null);
  154. }
  155. // src/core/impl.ts
  156. import {
  157. extractIdentifiers,
  158. isFunctionType,
  159. isInDestructureAssignment,
  160. isReferencedIdentifier,
  161. isStaticProperty,
  162. walkFunctionParams
  163. } from "@vue/compiler-core";
  164. import { parse } from "@babel/parser";
  165. import { genPropsAccessExp, hasOwn, isArray, isString } from "@vue/shared";
  166. import { TS_NODE_TYPES, unwrapTSNode } from "@vue-macros/common";
  167. var CONVERT_SYMBOL = "$";
  168. var ESCAPE_SYMBOL = "$$";
  169. var IMPORT_SOURCE = "vue/macros";
  170. var shorthands = ["ref", "computed", "shallowRef", "toRef", "customRef"];
  171. var transformCheckRE = /\W\$(?:\$|ref|computed|shallowRef|toRef|customRef)?\s*([(<])/;
  172. function shouldTransform(src) {
  173. return transformCheckRE.test(src);
  174. }
  175. function transform(src, {
  176. filename,
  177. sourceMap,
  178. parserPlugins,
  179. importHelpersFrom = "vue"
  180. } = {}) {
  181. const plugins = parserPlugins || [];
  182. if (filename) {
  183. if (/\.tsx?$/.test(filename)) {
  184. plugins.push("typescript");
  185. }
  186. if (filename.endsWith("x")) {
  187. plugins.push("jsx");
  188. }
  189. }
  190. const ast = parse(src, {
  191. sourceType: "module",
  192. plugins
  193. });
  194. const s = new MagicString(src);
  195. const res = transformAST(ast.program, s, 0);
  196. if (res.importedHelpers.length > 0) {
  197. s.prepend(
  198. `import { ${res.importedHelpers.map((h) => `${h} as _${h}`).join(", ")} } from '${importHelpersFrom}'
  199. `
  200. );
  201. }
  202. return {
  203. ...res,
  204. code: s.toString(),
  205. map: sourceMap ? s.generateMap({
  206. source: filename,
  207. hires: true,
  208. includeContent: true
  209. }) : null
  210. };
  211. }
  212. function transformAST(ast, s, offset = 0, knownRefs, knownProps) {
  213. const userImports = /* @__PURE__ */ Object.create(null);
  214. for (const node of ast.body) {
  215. if (node.type !== "ImportDeclaration")
  216. continue;
  217. walkImportDeclaration(node);
  218. }
  219. let convertSymbol;
  220. let escapeSymbol;
  221. for (const { local, imported, source, specifier } of Object.values(
  222. userImports
  223. )) {
  224. if (source === IMPORT_SOURCE) {
  225. if (imported === ESCAPE_SYMBOL) {
  226. escapeSymbol = local;
  227. } else if (imported === CONVERT_SYMBOL) {
  228. convertSymbol = local;
  229. } else if (imported !== local) {
  230. error(
  231. `macro imports for ref-creating methods do not support aliasing.`,
  232. specifier
  233. );
  234. }
  235. }
  236. }
  237. if (!convertSymbol && !userImports[CONVERT_SYMBOL]) {
  238. convertSymbol = CONVERT_SYMBOL;
  239. }
  240. if (!escapeSymbol && !userImports[ESCAPE_SYMBOL]) {
  241. escapeSymbol = ESCAPE_SYMBOL;
  242. }
  243. const importedHelpers = /* @__PURE__ */ new Set();
  244. const rootScope = {};
  245. const scopeStack = [rootScope];
  246. let currentScope = rootScope;
  247. let escapeScope;
  248. const excludedIds = /* @__PURE__ */ new WeakSet();
  249. const parentStack = [];
  250. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  251. if (knownRefs) {
  252. for (const key of knownRefs) {
  253. rootScope[key] = {};
  254. }
  255. }
  256. if (knownProps) {
  257. for (const key in knownProps) {
  258. const { local, isConst } = knownProps[key];
  259. rootScope[local] = {
  260. isProp: true,
  261. isConst: !!isConst
  262. };
  263. propsLocalToPublicMap[local] = key;
  264. }
  265. }
  266. function walkImportDeclaration(node) {
  267. const source = node.source.value;
  268. if (source === IMPORT_SOURCE) {
  269. s.remove(node.start + offset, node.end + offset);
  270. }
  271. for (const specifier of node.specifiers) {
  272. const local = specifier.local.name;
  273. const imported = specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name || "default";
  274. userImports[local] = {
  275. source,
  276. local,
  277. imported,
  278. specifier
  279. };
  280. }
  281. }
  282. function isRefCreationCall(callee) {
  283. if (!convertSymbol || getCurrentScope()[convertSymbol] !== void 0) {
  284. return false;
  285. }
  286. if (callee === convertSymbol) {
  287. return convertSymbol;
  288. }
  289. if (callee[0] === "$" && shorthands.includes(callee.slice(1))) {
  290. return callee;
  291. }
  292. return false;
  293. }
  294. function error(msg, node) {
  295. const e = new Error(msg);
  296. e.node = node;
  297. throw e;
  298. }
  299. function helper(msg) {
  300. importedHelpers.add(msg);
  301. return `_${msg}`;
  302. }
  303. function getCurrentScope() {
  304. return scopeStack.reduce((prev, curr) => ({ ...prev, ...curr }), {});
  305. }
  306. function registerBinding(id, binding) {
  307. excludedIds.add(id);
  308. if (currentScope) {
  309. currentScope[id.name] = binding ? binding : false;
  310. } else {
  311. error(
  312. "registerBinding called without active scope, something is wrong.",
  313. id
  314. );
  315. }
  316. }
  317. const registerRefBinding = (id, isConst = false) => registerBinding(id, { isConst });
  318. let tempVarCount = 0;
  319. function genTempVar() {
  320. return `__$temp_${++tempVarCount}`;
  321. }
  322. function snip(node) {
  323. return s.original.slice(node.start + offset, node.end + offset);
  324. }
  325. function findUpParent() {
  326. return parentStack.slice().reverse().find(({ type }) => !TS_NODE_TYPES.includes(type));
  327. }
  328. function walkScope(node, isRoot = false) {
  329. for (const stmt of node.body) {
  330. if (stmt.type === "VariableDeclaration") {
  331. walkVariableDeclaration(stmt, isRoot);
  332. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  333. if (stmt.declare || !stmt.id)
  334. continue;
  335. registerBinding(stmt.id);
  336. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  337. walkVariableDeclaration(stmt.left);
  338. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  339. walkVariableDeclaration(stmt.declaration, isRoot);
  340. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  341. walkVariableDeclaration(stmt.body, isRoot);
  342. }
  343. }
  344. }
  345. function walkVariableDeclaration(stmt, isRoot = false) {
  346. if (stmt.declare) {
  347. return;
  348. }
  349. for (const decl of stmt.declarations) {
  350. let refCall;
  351. const init = decl.init ? unwrapTSNode(decl.init) : null;
  352. const isCall = init && init.type === "CallExpression" && init.callee.type === "Identifier";
  353. if (isCall && (refCall = isRefCreationCall(init.callee.name))) {
  354. processRefDeclaration(
  355. refCall,
  356. decl.id,
  357. decl.init,
  358. init,
  359. stmt.kind === "const"
  360. );
  361. } else {
  362. const isProps = isRoot && isCall && init.callee.name === "defineProps";
  363. for (const id of extractIdentifiers(decl.id)) {
  364. if (isProps) {
  365. excludedIds.add(id);
  366. } else {
  367. registerBinding(id);
  368. }
  369. }
  370. }
  371. }
  372. }
  373. function processRefDeclaration(method, id, init, call, isConst) {
  374. excludedIds.add(call.callee);
  375. if (method === convertSymbol) {
  376. s.remove(call.callee.start + offset, call.callee.end + offset);
  377. if (id.type === "Identifier") {
  378. registerRefBinding(id, isConst);
  379. } else if (id.type === "ObjectPattern") {
  380. processRefObjectPattern(id, init, isConst);
  381. } else if (id.type === "ArrayPattern") {
  382. processRefArrayPattern(id, init, isConst);
  383. }
  384. } else if (id.type === "Identifier") {
  385. registerRefBinding(id, isConst);
  386. s.overwrite(
  387. call.start + offset,
  388. call.start + method.length + offset,
  389. helper(method.slice(1))
  390. );
  391. } else {
  392. error(`${method}() cannot be used with destructure patterns.`, call);
  393. }
  394. }
  395. function processRefObjectPattern(pattern, value, isConst, tempVar, path = []) {
  396. if (!tempVar) {
  397. tempVar = genTempVar();
  398. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  399. }
  400. let nameId;
  401. for (const p of pattern.properties) {
  402. let key;
  403. let defaultValue;
  404. if (p.type === "ObjectProperty") {
  405. if (p.key.start === p.value.start) {
  406. nameId = p.key;
  407. if (p.value.type === "Identifier") {
  408. excludedIds.add(p.value);
  409. } else if (p.value.type === "AssignmentPattern" && p.value.left.type === "Identifier") {
  410. excludedIds.add(p.value.left);
  411. defaultValue = p.value.right;
  412. }
  413. } else {
  414. key = p.computed ? p.key : p.key.name;
  415. if (p.value.type === "Identifier") {
  416. nameId = p.value;
  417. } else if (p.value.type === "ObjectPattern") {
  418. processRefObjectPattern(p.value, value, isConst, tempVar, [
  419. ...path,
  420. key
  421. ]);
  422. } else if (p.value.type === "ArrayPattern") {
  423. processRefArrayPattern(p.value, value, isConst, tempVar, [
  424. ...path,
  425. key
  426. ]);
  427. } else if (p.value.type === "AssignmentPattern") {
  428. if (p.value.left.type === "Identifier") {
  429. nameId = p.value.left;
  430. defaultValue = p.value.right;
  431. } else if (p.value.left.type === "ObjectPattern") {
  432. processRefObjectPattern(p.value.left, value, isConst, tempVar, [
  433. ...path,
  434. [key, p.value.right]
  435. ]);
  436. } else if (p.value.left.type === "ArrayPattern") {
  437. processRefArrayPattern(p.value.left, value, isConst, tempVar, [
  438. ...path,
  439. [key, p.value.right]
  440. ]);
  441. } else {
  442. }
  443. }
  444. }
  445. } else {
  446. error(`reactivity destructure does not support rest elements.`, p);
  447. }
  448. if (nameId) {
  449. registerRefBinding(nameId, isConst);
  450. const source = pathToString(tempVar, path);
  451. const keyStr = isString(key) ? `'${key}'` : key ? snip(key) : `'${nameId.name}'`;
  452. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  453. s.appendLeft(
  454. value.end + offset,
  455. `,
  456. ${nameId.name} = ${helper(
  457. "toRef"
  458. )}(${source}, ${keyStr}${defaultStr})`
  459. );
  460. }
  461. }
  462. if (nameId) {
  463. s.appendLeft(value.end + offset, ";");
  464. }
  465. }
  466. function processRefArrayPattern(pattern, value, isConst, tempVar, path = []) {
  467. if (!tempVar) {
  468. tempVar = genTempVar();
  469. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  470. }
  471. let nameId;
  472. for (let i = 0; i < pattern.elements.length; i++) {
  473. const e = pattern.elements[i];
  474. if (!e)
  475. continue;
  476. let defaultValue;
  477. if (e.type === "Identifier") {
  478. nameId = e;
  479. } else if (e.type === "AssignmentPattern") {
  480. nameId = e.left;
  481. defaultValue = e.right;
  482. } else if (e.type === "RestElement") {
  483. error(`reactivity destructure does not support rest elements.`, e);
  484. } else if (e.type === "ObjectPattern") {
  485. processRefObjectPattern(e, value, isConst, tempVar, [...path, i]);
  486. } else if (e.type === "ArrayPattern") {
  487. processRefArrayPattern(e, value, isConst, tempVar, [...path, i]);
  488. }
  489. if (nameId) {
  490. registerRefBinding(nameId, isConst);
  491. const source = pathToString(tempVar, path);
  492. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  493. s.appendLeft(
  494. value.end + offset,
  495. `,
  496. ${nameId.name} = ${helper(
  497. "toRef"
  498. )}(${source}, ${i}${defaultStr})`
  499. );
  500. }
  501. }
  502. if (nameId) {
  503. s.appendLeft(value.end + offset, ";");
  504. }
  505. }
  506. function pathToString(source, path) {
  507. if (path.length > 0) {
  508. for (const seg of path) {
  509. if (isArray(seg)) {
  510. source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`;
  511. } else {
  512. source += segToString(seg);
  513. }
  514. }
  515. }
  516. return source;
  517. }
  518. function segToString(seg) {
  519. if (typeof seg === "number") {
  520. return `[${seg}]`;
  521. } else if (typeof seg === "string") {
  522. return `.${seg}`;
  523. } else {
  524. return snip(seg);
  525. }
  526. }
  527. function rewriteId(scope, id, parent, parentStack2) {
  528. if (hasOwn(scope, id.name)) {
  529. const binding = scope[id.name];
  530. if (binding) {
  531. if (binding.isConst && (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression")) {
  532. error(`Assignment to constant variable.`, id);
  533. }
  534. const { isProp } = binding;
  535. if (isStaticProperty(parent) && parent.shorthand) {
  536. if (!parent.inPattern || isInDestructureAssignment(parent, parentStack2)) {
  537. if (isProp) {
  538. if (escapeScope) {
  539. registerEscapedPropBinding(id);
  540. s.appendLeft(
  541. id.end + offset,
  542. `: __props_${propsLocalToPublicMap[id.name]}`
  543. );
  544. } else {
  545. s.appendLeft(
  546. id.end + offset,
  547. `: ${genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  548. );
  549. }
  550. } else {
  551. s.appendLeft(id.end + offset, `: ${id.name}.value`);
  552. }
  553. }
  554. } else if (isProp) {
  555. if (escapeScope) {
  556. registerEscapedPropBinding(id);
  557. s.overwrite(
  558. id.start + offset,
  559. id.end + offset,
  560. `__props_${propsLocalToPublicMap[id.name]}`
  561. );
  562. } else {
  563. s.overwrite(
  564. id.start + offset,
  565. id.end + offset,
  566. genPropsAccessExp(propsLocalToPublicMap[id.name])
  567. );
  568. }
  569. } else {
  570. s.appendLeft(id.end + offset, ".value");
  571. }
  572. }
  573. return true;
  574. }
  575. return false;
  576. }
  577. const propBindingRefs = {};
  578. function registerEscapedPropBinding(id) {
  579. if (!propBindingRefs.hasOwnProperty(id.name)) {
  580. propBindingRefs[id.name] = true;
  581. const publicKey = propsLocalToPublicMap[id.name];
  582. s.prependRight(
  583. offset,
  584. `const __props_${publicKey} = ${helper(
  585. `toRef`
  586. )}(__props, '${publicKey}');
  587. `
  588. );
  589. }
  590. }
  591. walkScope(ast, true);
  592. walk(ast, {
  593. enter(node, parent) {
  594. parent && parentStack.push(parent);
  595. if (isFunctionType(node)) {
  596. scopeStack.push(currentScope = {});
  597. walkFunctionParams(node, registerBinding);
  598. if (node.body.type === "BlockStatement") {
  599. walkScope(node.body);
  600. }
  601. return;
  602. }
  603. if (node.type === "CatchClause") {
  604. scopeStack.push(currentScope = {});
  605. if (node.param && node.param.type === "Identifier") {
  606. registerBinding(node.param);
  607. }
  608. walkScope(node.body);
  609. return;
  610. }
  611. if (node.type === "BlockStatement" && !isFunctionType(parent)) {
  612. scopeStack.push(currentScope = {});
  613. walkScope(node);
  614. return;
  615. }
  616. if (parent && parent.type.startsWith("TS") && !TS_NODE_TYPES.includes(parent.type)) {
  617. return this.skip();
  618. }
  619. if (node.type === "Identifier") {
  620. const binding = rootScope[node.name];
  621. if (
  622. // if inside $$(), skip unless this is a destructured prop binding
  623. !(escapeScope && (!binding || !binding.isProp)) && isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)
  624. ) {
  625. let i = scopeStack.length;
  626. while (i--) {
  627. if (rewriteId(scopeStack[i], node, parent, parentStack)) {
  628. return;
  629. }
  630. }
  631. }
  632. }
  633. if (node.type === "CallExpression" && node.callee.type === "Identifier") {
  634. const callee = node.callee.name;
  635. const refCall = isRefCreationCall(callee);
  636. const parent2 = findUpParent();
  637. if (refCall && (!parent2 || parent2.type !== "VariableDeclarator")) {
  638. return error(
  639. `${refCall} can only be used as the initializer of a variable declaration.`,
  640. node
  641. );
  642. }
  643. if (escapeSymbol && getCurrentScope()[escapeSymbol] === void 0 && callee === escapeSymbol) {
  644. escapeScope = node;
  645. s.remove(node.callee.start + offset, node.callee.end + offset);
  646. if ((parent2 == null ? void 0 : parent2.type) === "ExpressionStatement") {
  647. let i = (node.leadingComments ? node.leadingComments[0].start : node.start) + offset;
  648. while (i--) {
  649. const char = s.original.charAt(i);
  650. if (char === "\n") {
  651. s.prependRight(node.start + offset, ";");
  652. break;
  653. } else if (!/\s/.test(char)) {
  654. break;
  655. }
  656. }
  657. }
  658. }
  659. }
  660. },
  661. leave(node, parent) {
  662. parent && parentStack.pop();
  663. if (node.type === "BlockStatement" && !isFunctionType(parent) || isFunctionType(node)) {
  664. scopeStack.pop();
  665. currentScope = scopeStack[scopeStack.length - 1] || null;
  666. }
  667. if (node === escapeScope) {
  668. escapeScope = void 0;
  669. }
  670. }
  671. });
  672. return {
  673. rootRefs: Object.keys(rootScope).filter((key) => {
  674. const binding = rootScope[key];
  675. return binding && !binding.isProp;
  676. }),
  677. importedHelpers: [...importedHelpers]
  678. };
  679. }
  680. // src/core/helper/code.ts?raw
  681. var code_default = "export function createPropsRestProxy(props,excludedKeys){const ret={};for(const key in props){if(!excludedKeys.includes(key)){Object.defineProperty(ret,key,{enumerable:true,get:()=>props[key]})}}return ret}\n";
  682. // src/core/helper/index.ts
  683. var helperId = "/vue-macros/reactivity-transform/helper";
  684. // src/core/index.ts
  685. import {
  686. DEFINE_PROPS,
  687. MagicString as MagicString2,
  688. getTransformResult,
  689. isCallOf,
  690. parseSFC,
  691. resolveObjectKey
  692. } from "@vue-macros/common";
  693. function transformVueSFC(code, id) {
  694. const s = new MagicString2(code);
  695. const { script, scriptSetup, getScriptAst, getSetupAst } = parseSFC(code, id);
  696. let refBindings;
  697. let propsDestructuredBindings;
  698. if (script && shouldTransform(script.content)) {
  699. const offset = script.loc.start.offset;
  700. const { importedHelpers, rootRefs } = transformAST(
  701. getScriptAst(),
  702. s,
  703. offset
  704. );
  705. refBindings = rootRefs;
  706. importHelpers(s, script.loc.start.offset, importedHelpers);
  707. }
  708. if (scriptSetup) {
  709. const ast = getSetupAst();
  710. for (const node of ast.body) {
  711. processDefineProps(node);
  712. }
  713. if (propsDestructuredBindings || refBindings || shouldTransform(scriptSetup.content)) {
  714. const { importedHelpers } = transformAST(
  715. ast,
  716. s,
  717. scriptSetup.loc.start.offset,
  718. refBindings,
  719. propsDestructuredBindings
  720. );
  721. importHelpers(s, scriptSetup.loc.start.offset, importedHelpers);
  722. }
  723. }
  724. return getTransformResult(s, id);
  725. function processDefineProps(node) {
  726. if (node.type !== "VariableDeclaration")
  727. return;
  728. const decl = node.declarations.find(
  729. (decl2) => isCallOf(decl2.init, DEFINE_PROPS)
  730. );
  731. if (!decl || decl.id.type !== "ObjectPattern")
  732. return;
  733. if (node.declarations.length > 1)
  734. throw new SyntaxError(
  735. `${DEFINE_PROPS}() don't support multiple declarations.`
  736. );
  737. const offset = scriptSetup.loc.start.offset;
  738. let defaultStr = "";
  739. propsDestructuredBindings = {};
  740. for (const prop of decl.id.properties) {
  741. if (prop.type === "ObjectProperty") {
  742. const propKey = resolveObjectKey(prop.key, prop.computed, false);
  743. if (!propKey) {
  744. throw new SyntaxError(
  745. `${DEFINE_PROPS}() destructure cannot use computed key.`
  746. );
  747. }
  748. if (prop.value.type === "AssignmentPattern") {
  749. const { left, right } = prop.value;
  750. if (left.type !== "Identifier") {
  751. throw new SyntaxError(
  752. `${DEFINE_PROPS}() destructure does not support nested patterns.`
  753. );
  754. }
  755. propsDestructuredBindings[propKey] = {
  756. local: left.name
  757. };
  758. defaultStr += `${propKey}: ${s.sliceNode(right, { offset })},`;
  759. } else if (prop.value.type === "Identifier") {
  760. propsDestructuredBindings[propKey] = {
  761. local: prop.value.name
  762. };
  763. } else {
  764. throw new SyntaxError(
  765. `${DEFINE_PROPS}() destructure does not support nested patterns.`
  766. );
  767. }
  768. } else {
  769. s.prependLeft(
  770. offset,
  771. `import { createPropsRestProxy } from '${helperId}';
  772. const ${prop.argument.name} = createPropsRestProxy(__props, ${JSON.stringify(
  773. Object.keys(propsDestructuredBindings)
  774. )});
  775. `
  776. );
  777. }
  778. }
  779. const declStr = `withDefaults(${s.sliceNode(decl.init, {
  780. offset
  781. })}, { ${defaultStr} })`;
  782. s.overwriteNode(node, declStr, { offset });
  783. }
  784. }
  785. function importHelpers(s, offset, helpers) {
  786. if (helpers.length === 0)
  787. return;
  788. s.prependLeft(
  789. offset,
  790. `import { ${helpers.map((h) => `${h} as _${h}`).join(", ")} } from 'vue';
  791. `
  792. );
  793. }
  794. export {
  795. shouldTransform,
  796. transform,
  797. transformAST,
  798. code_default,
  799. helperId,
  800. transformVueSFC
  801. };