reactivity-transform.cjs.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var MagicString = require('magic-string');
  4. var estreeWalker = require('estree-walker');
  5. var compilerCore = require('@vue/compiler-core');
  6. var parser = require('@babel/parser');
  7. var shared = require('@vue/shared');
  8. const CONVERT_SYMBOL = "$";
  9. const ESCAPE_SYMBOL = "$$";
  10. const IMPORT_SOURCE = "vue/macros";
  11. const shorthands = ["ref", "computed", "shallowRef", "toRef", "customRef"];
  12. const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/;
  13. function shouldTransform(src) {
  14. return transformCheckRE.test(src);
  15. }
  16. function transform(src, {
  17. filename,
  18. sourceMap,
  19. parserPlugins,
  20. importHelpersFrom = "vue"
  21. } = {}) {
  22. const plugins = parserPlugins || [];
  23. if (filename) {
  24. if (/\.tsx?$/.test(filename)) {
  25. plugins.push("typescript");
  26. }
  27. if (filename.endsWith("x")) {
  28. plugins.push("jsx");
  29. }
  30. }
  31. const ast = parser.parse(src, {
  32. sourceType: "module",
  33. plugins
  34. });
  35. const s = new MagicString(src);
  36. const res = transformAST(ast.program, s, 0);
  37. if (res.importedHelpers.length) {
  38. s.prepend(
  39. `import { ${res.importedHelpers.map((h) => `${h} as _${h}`).join(", ")} } from '${importHelpersFrom}'
  40. `
  41. );
  42. }
  43. return {
  44. ...res,
  45. code: s.toString(),
  46. map: sourceMap ? s.generateMap({
  47. source: filename,
  48. hires: true,
  49. includeContent: true
  50. }) : null
  51. };
  52. }
  53. function transformAST(ast, s, offset = 0, knownRefs, knownProps) {
  54. warnExperimental();
  55. const userImports = /* @__PURE__ */ Object.create(null);
  56. for (const node of ast.body) {
  57. if (node.type !== "ImportDeclaration")
  58. continue;
  59. walkImportDeclaration(node);
  60. }
  61. let convertSymbol;
  62. let escapeSymbol;
  63. for (const { local, imported, source, specifier } of Object.values(
  64. userImports
  65. )) {
  66. if (source === IMPORT_SOURCE) {
  67. if (imported === ESCAPE_SYMBOL) {
  68. escapeSymbol = local;
  69. } else if (imported === CONVERT_SYMBOL) {
  70. convertSymbol = local;
  71. } else if (imported !== local) {
  72. error(
  73. `macro imports for ref-creating methods do not support aliasing.`,
  74. specifier
  75. );
  76. }
  77. }
  78. }
  79. if (!convertSymbol && !userImports[CONVERT_SYMBOL]) {
  80. convertSymbol = CONVERT_SYMBOL;
  81. }
  82. if (!escapeSymbol && !userImports[ESCAPE_SYMBOL]) {
  83. escapeSymbol = ESCAPE_SYMBOL;
  84. }
  85. const importedHelpers = /* @__PURE__ */ new Set();
  86. const rootScope = {};
  87. const scopeStack = [rootScope];
  88. let currentScope = rootScope;
  89. let escapeScope;
  90. const excludedIds = /* @__PURE__ */ new WeakSet();
  91. const parentStack = [];
  92. const propsLocalToPublicMap = /* @__PURE__ */ Object.create(null);
  93. if (knownRefs) {
  94. for (const key of knownRefs) {
  95. rootScope[key] = {};
  96. }
  97. }
  98. if (knownProps) {
  99. for (const key in knownProps) {
  100. const { local, isConst } = knownProps[key];
  101. rootScope[local] = {
  102. isProp: true,
  103. isConst: !!isConst
  104. };
  105. propsLocalToPublicMap[local] = key;
  106. }
  107. }
  108. function walkImportDeclaration(node) {
  109. const source = node.source.value;
  110. if (source === IMPORT_SOURCE) {
  111. s.remove(node.start + offset, node.end + offset);
  112. }
  113. for (const specifier of node.specifiers) {
  114. const local = specifier.local.name;
  115. const imported = specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name || "default";
  116. userImports[local] = {
  117. source,
  118. local,
  119. imported,
  120. specifier
  121. };
  122. }
  123. }
  124. function isRefCreationCall(callee) {
  125. if (!convertSymbol || currentScope[convertSymbol] !== void 0) {
  126. return false;
  127. }
  128. if (callee === convertSymbol) {
  129. return convertSymbol;
  130. }
  131. if (callee[0] === "$" && shorthands.includes(callee.slice(1))) {
  132. return callee;
  133. }
  134. return false;
  135. }
  136. function error(msg, node) {
  137. const e = new Error(msg);
  138. e.node = node;
  139. throw e;
  140. }
  141. function helper(msg) {
  142. importedHelpers.add(msg);
  143. return `_${msg}`;
  144. }
  145. function registerBinding(id, binding) {
  146. excludedIds.add(id);
  147. if (currentScope) {
  148. currentScope[id.name] = binding ? binding : false;
  149. } else {
  150. error(
  151. "registerBinding called without active scope, something is wrong.",
  152. id
  153. );
  154. }
  155. }
  156. const registerRefBinding = (id, isConst = false) => registerBinding(id, { isConst });
  157. let tempVarCount = 0;
  158. function genTempVar() {
  159. return `__$temp_${++tempVarCount}`;
  160. }
  161. function snip(node) {
  162. return s.original.slice(node.start + offset, node.end + offset);
  163. }
  164. function walkScope(node, isRoot = false) {
  165. for (const stmt of node.body) {
  166. if (stmt.type === "VariableDeclaration") {
  167. walkVariableDeclaration(stmt, isRoot);
  168. } else if (stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") {
  169. if (stmt.declare || !stmt.id)
  170. continue;
  171. registerBinding(stmt.id);
  172. } else if ((stmt.type === "ForOfStatement" || stmt.type === "ForInStatement") && stmt.left.type === "VariableDeclaration") {
  173. walkVariableDeclaration(stmt.left);
  174. } else if (stmt.type === "ExportNamedDeclaration" && stmt.declaration && stmt.declaration.type === "VariableDeclaration") {
  175. walkVariableDeclaration(stmt.declaration, isRoot);
  176. } else if (stmt.type === "LabeledStatement" && stmt.body.type === "VariableDeclaration") {
  177. walkVariableDeclaration(stmt.body, isRoot);
  178. }
  179. }
  180. }
  181. function walkVariableDeclaration(stmt, isRoot = false) {
  182. if (stmt.declare) {
  183. return;
  184. }
  185. for (const decl of stmt.declarations) {
  186. let refCall;
  187. const isCall = decl.init && decl.init.type === "CallExpression" && decl.init.callee.type === "Identifier";
  188. if (isCall && (refCall = isRefCreationCall(decl.init.callee.name))) {
  189. processRefDeclaration(
  190. refCall,
  191. decl.id,
  192. decl.init,
  193. stmt.kind === "const"
  194. );
  195. } else {
  196. const isProps = isRoot && isCall && decl.init.callee.name === "defineProps";
  197. for (const id of compilerCore.extractIdentifiers(decl.id)) {
  198. if (isProps) {
  199. excludedIds.add(id);
  200. } else {
  201. registerBinding(id);
  202. }
  203. }
  204. }
  205. }
  206. }
  207. function processRefDeclaration(method, id, call, isConst) {
  208. excludedIds.add(call.callee);
  209. if (method === convertSymbol) {
  210. s.remove(call.callee.start + offset, call.callee.end + offset);
  211. if (id.type === "Identifier") {
  212. registerRefBinding(id, isConst);
  213. } else if (id.type === "ObjectPattern") {
  214. processRefObjectPattern(id, call, isConst);
  215. } else if (id.type === "ArrayPattern") {
  216. processRefArrayPattern(id, call, isConst);
  217. }
  218. } else {
  219. if (id.type === "Identifier") {
  220. registerRefBinding(id, isConst);
  221. s.overwrite(
  222. call.start + offset,
  223. call.start + method.length + offset,
  224. helper(method.slice(1))
  225. );
  226. } else {
  227. error(`${method}() cannot be used with destructure patterns.`, call);
  228. }
  229. }
  230. }
  231. function processRefObjectPattern(pattern, call, isConst, tempVar, path = []) {
  232. if (!tempVar) {
  233. tempVar = genTempVar();
  234. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  235. }
  236. let nameId;
  237. for (const p of pattern.properties) {
  238. let key;
  239. let defaultValue;
  240. if (p.type === "ObjectProperty") {
  241. if (p.key.start === p.value.start) {
  242. nameId = p.key;
  243. if (p.value.type === "Identifier") {
  244. excludedIds.add(p.value);
  245. } else if (p.value.type === "AssignmentPattern" && p.value.left.type === "Identifier") {
  246. excludedIds.add(p.value.left);
  247. defaultValue = p.value.right;
  248. }
  249. } else {
  250. key = p.computed ? p.key : p.key.name;
  251. if (p.value.type === "Identifier") {
  252. nameId = p.value;
  253. } else if (p.value.type === "ObjectPattern") {
  254. processRefObjectPattern(p.value, call, isConst, tempVar, [
  255. ...path,
  256. key
  257. ]);
  258. } else if (p.value.type === "ArrayPattern") {
  259. processRefArrayPattern(p.value, call, isConst, tempVar, [
  260. ...path,
  261. key
  262. ]);
  263. } else if (p.value.type === "AssignmentPattern") {
  264. if (p.value.left.type === "Identifier") {
  265. nameId = p.value.left;
  266. defaultValue = p.value.right;
  267. } else if (p.value.left.type === "ObjectPattern") {
  268. processRefObjectPattern(p.value.left, call, isConst, tempVar, [
  269. ...path,
  270. [key, p.value.right]
  271. ]);
  272. } else if (p.value.left.type === "ArrayPattern") {
  273. processRefArrayPattern(p.value.left, call, isConst, tempVar, [
  274. ...path,
  275. [key, p.value.right]
  276. ]);
  277. } else ;
  278. }
  279. }
  280. } else {
  281. error(`reactivity destructure does not support rest elements.`, p);
  282. }
  283. if (nameId) {
  284. registerRefBinding(nameId, isConst);
  285. const source = pathToString(tempVar, path);
  286. const keyStr = shared.isString(key) ? `'${key}'` : key ? snip(key) : `'${nameId.name}'`;
  287. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  288. s.appendLeft(
  289. call.end + offset,
  290. `,
  291. ${nameId.name} = ${helper(
  292. "toRef"
  293. )}(${source}, ${keyStr}${defaultStr})`
  294. );
  295. }
  296. }
  297. if (nameId) {
  298. s.appendLeft(call.end + offset, ";");
  299. }
  300. }
  301. function processRefArrayPattern(pattern, call, isConst, tempVar, path = []) {
  302. if (!tempVar) {
  303. tempVar = genTempVar();
  304. s.overwrite(pattern.start + offset, pattern.end + offset, tempVar);
  305. }
  306. let nameId;
  307. for (let i = 0; i < pattern.elements.length; i++) {
  308. const e = pattern.elements[i];
  309. if (!e)
  310. continue;
  311. let defaultValue;
  312. if (e.type === "Identifier") {
  313. nameId = e;
  314. } else if (e.type === "AssignmentPattern") {
  315. nameId = e.left;
  316. defaultValue = e.right;
  317. } else if (e.type === "RestElement") {
  318. error(`reactivity destructure does not support rest elements.`, e);
  319. } else if (e.type === "ObjectPattern") {
  320. processRefObjectPattern(e, call, isConst, tempVar, [...path, i]);
  321. } else if (e.type === "ArrayPattern") {
  322. processRefArrayPattern(e, call, isConst, tempVar, [...path, i]);
  323. }
  324. if (nameId) {
  325. registerRefBinding(nameId, isConst);
  326. const source = pathToString(tempVar, path);
  327. const defaultStr = defaultValue ? `, ${snip(defaultValue)}` : ``;
  328. s.appendLeft(
  329. call.end + offset,
  330. `,
  331. ${nameId.name} = ${helper(
  332. "toRef"
  333. )}(${source}, ${i}${defaultStr})`
  334. );
  335. }
  336. }
  337. if (nameId) {
  338. s.appendLeft(call.end + offset, ";");
  339. }
  340. }
  341. function pathToString(source, path) {
  342. if (path.length) {
  343. for (const seg of path) {
  344. if (shared.isArray(seg)) {
  345. source = `(${source}${segToString(seg[0])} || ${snip(seg[1])})`;
  346. } else {
  347. source += segToString(seg);
  348. }
  349. }
  350. }
  351. return source;
  352. }
  353. function segToString(seg) {
  354. if (typeof seg === "number") {
  355. return `[${seg}]`;
  356. } else if (typeof seg === "string") {
  357. return `.${seg}`;
  358. } else {
  359. return snip(seg);
  360. }
  361. }
  362. function rewriteId(scope, id, parent, parentStack2) {
  363. if (shared.hasOwn(scope, id.name)) {
  364. const binding = scope[id.name];
  365. if (binding) {
  366. if (binding.isConst && (parent.type === "AssignmentExpression" && id === parent.left || parent.type === "UpdateExpression")) {
  367. error(`Assignment to constant variable.`, id);
  368. }
  369. const { isProp } = binding;
  370. if (compilerCore.isStaticProperty(parent) && parent.shorthand) {
  371. if (!parent.inPattern || compilerCore.isInDestructureAssignment(parent, parentStack2)) {
  372. if (isProp) {
  373. if (escapeScope) {
  374. registerEscapedPropBinding(id);
  375. s.appendLeft(
  376. id.end + offset,
  377. `: __props_${propsLocalToPublicMap[id.name]}`
  378. );
  379. } else {
  380. s.appendLeft(
  381. id.end + offset,
  382. `: ${shared.genPropsAccessExp(propsLocalToPublicMap[id.name])}`
  383. );
  384. }
  385. } else {
  386. s.appendLeft(id.end + offset, `: ${id.name}.value`);
  387. }
  388. }
  389. } else {
  390. if (isProp) {
  391. if (escapeScope) {
  392. registerEscapedPropBinding(id);
  393. s.overwrite(
  394. id.start + offset,
  395. id.end + offset,
  396. `__props_${propsLocalToPublicMap[id.name]}`
  397. );
  398. } else {
  399. s.overwrite(
  400. id.start + offset,
  401. id.end + offset,
  402. shared.genPropsAccessExp(propsLocalToPublicMap[id.name])
  403. );
  404. }
  405. } else {
  406. s.appendLeft(id.end + offset, ".value");
  407. }
  408. }
  409. }
  410. return true;
  411. }
  412. return false;
  413. }
  414. const propBindingRefs = {};
  415. function registerEscapedPropBinding(id) {
  416. if (!propBindingRefs.hasOwnProperty(id.name)) {
  417. propBindingRefs[id.name] = true;
  418. const publicKey = propsLocalToPublicMap[id.name];
  419. s.prependRight(
  420. offset,
  421. `const __props_${publicKey} = ${helper(
  422. `toRef`
  423. )}(__props, '${publicKey}');
  424. `
  425. );
  426. }
  427. }
  428. walkScope(ast, true);
  429. estreeWalker.walk(ast, {
  430. enter(node, parent) {
  431. parent && parentStack.push(parent);
  432. if (compilerCore.isFunctionType(node)) {
  433. scopeStack.push(currentScope = {});
  434. compilerCore.walkFunctionParams(node, registerBinding);
  435. if (node.body.type === "BlockStatement") {
  436. walkScope(node.body);
  437. }
  438. return;
  439. }
  440. if (node.type === "CatchClause") {
  441. scopeStack.push(currentScope = {});
  442. if (node.param && node.param.type === "Identifier") {
  443. registerBinding(node.param);
  444. }
  445. walkScope(node.body);
  446. return;
  447. }
  448. if (node.type === "BlockStatement" && !compilerCore.isFunctionType(parent)) {
  449. scopeStack.push(currentScope = {});
  450. walkScope(node);
  451. return;
  452. }
  453. if (parent && parent.type.startsWith("TS") && parent.type !== "TSAsExpression" && parent.type !== "TSNonNullExpression" && parent.type !== "TSTypeAssertion") {
  454. return this.skip();
  455. }
  456. if (node.type === "Identifier") {
  457. const binding = rootScope[node.name];
  458. if (
  459. // if inside $$(), skip unless this is a destructured prop binding
  460. !(escapeScope && (!binding || !binding.isProp)) && compilerCore.isReferencedIdentifier(node, parent, parentStack) && !excludedIds.has(node)
  461. ) {
  462. let i = scopeStack.length;
  463. while (i--) {
  464. if (rewriteId(scopeStack[i], node, parent, parentStack)) {
  465. return;
  466. }
  467. }
  468. }
  469. }
  470. if (node.type === "CallExpression" && node.callee.type === "Identifier") {
  471. const callee = node.callee.name;
  472. const refCall = isRefCreationCall(callee);
  473. if (refCall && (!parent || parent.type !== "VariableDeclarator")) {
  474. return error(
  475. `${refCall} can only be used as the initializer of a variable declaration.`,
  476. node
  477. );
  478. }
  479. if (escapeSymbol && currentScope[escapeSymbol] === void 0 && callee === escapeSymbol) {
  480. escapeScope = node;
  481. s.remove(node.callee.start + offset, node.callee.end + offset);
  482. if ((parent == null ? void 0 : parent.type) === "ExpressionStatement") {
  483. let i = (node.leadingComments ? node.leadingComments[0].start : node.start) + offset;
  484. while (i--) {
  485. const char = s.original.charAt(i);
  486. if (char === "\n") {
  487. s.prependRight(node.start + offset, ";");
  488. break;
  489. } else if (!/\s/.test(char)) {
  490. break;
  491. }
  492. }
  493. }
  494. }
  495. }
  496. },
  497. leave(node, parent) {
  498. parent && parentStack.pop();
  499. if (node.type === "BlockStatement" && !compilerCore.isFunctionType(parent) || compilerCore.isFunctionType(node)) {
  500. scopeStack.pop();
  501. currentScope = scopeStack[scopeStack.length - 1] || null;
  502. }
  503. if (node === escapeScope) {
  504. escapeScope = void 0;
  505. }
  506. }
  507. });
  508. return {
  509. rootRefs: Object.keys(rootScope).filter((key) => {
  510. const binding = rootScope[key];
  511. return binding && !binding.isProp;
  512. }),
  513. importedHelpers: [...importedHelpers]
  514. };
  515. }
  516. const hasWarned = {};
  517. function warnExperimental() {
  518. if (typeof window !== "undefined") {
  519. return;
  520. }
  521. warnOnce(
  522. `Reactivity Transform was an experimental feature and has now been deprecated. It will be removed from Vue core in 3.4. If you intend to continue using it, switch to https://vue-macros.sxzz.moe/features/reactivity-transform.html.
  523. See reason for deprecation here: https://github.com/vuejs/rfcs/discussions/369#discussioncomment-5059028`
  524. );
  525. }
  526. function warnOnce(msg) {
  527. const isNodeProd = typeof process !== "undefined" && process.env.NODE_ENV === "production";
  528. if (!isNodeProd && true && !hasWarned[msg]) {
  529. hasWarned[msg] = true;
  530. warn(msg);
  531. }
  532. }
  533. function warn(msg) {
  534. console.warn(
  535. `\x1B[1m\x1B[33m[@vue/reactivity-transform]\x1B[0m\x1B[33m ${msg}\x1B[0m
  536. `
  537. );
  538. }
  539. exports.shouldTransform = shouldTransform;
  540. exports.transform = transform;
  541. exports.transformAST = transformAST;