ref-transform.cjs.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e['default'] : e; }
  9. var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
  10. const TO_VAR_SYMBOL = '$';
  11. const TO_REF_SYMBOL = '$$';
  12. const shorthands = ['ref', 'computed', 'shallowRef'];
  13. const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/;
  14. function shouldTransform(src) {
  15. return transformCheckRE.test(src);
  16. }
  17. function transform(src, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' } = {}) {
  18. const plugins = parserPlugins || [];
  19. if (filename) {
  20. if (/\.tsx?$/.test(filename)) {
  21. plugins.push('typescript');
  22. }
  23. if (filename.endsWith('x')) {
  24. plugins.push('jsx');
  25. }
  26. }
  27. const ast = parser.parse(src, {
  28. sourceType: 'module',
  29. plugins: [...new Set([...shared.babelParserDefaultPlugins, ...plugins])]
  30. });
  31. const s = new MagicString__default(src);
  32. const res = transformAST(ast.program, s);
  33. // inject helper imports
  34. if (res.importedHelpers.length) {
  35. s.prepend(`import { ${res.importedHelpers
  36. .map(h => `${h} as _${h}`)
  37. .join(', ')} } from '${importHelpersFrom}'\n`);
  38. }
  39. return Object.assign(Object.assign({}, res), { code: s.toString(), map: sourceMap
  40. ? s.generateMap({
  41. source: filename,
  42. hires: true,
  43. includeContent: true
  44. })
  45. : null });
  46. }
  47. function transformAST(ast, s, offset = 0, knownRootVars) {
  48. // TODO remove when out of experimental
  49. warnExperimental();
  50. const importedHelpers = new Set();
  51. const rootScope = {};
  52. const scopeStack = [rootScope];
  53. let currentScope = rootScope;
  54. const excludedIds = new WeakSet();
  55. const parentStack = [];
  56. if (knownRootVars) {
  57. for (const key of knownRootVars) {
  58. rootScope[key] = true;
  59. }
  60. }
  61. function error(msg, node) {
  62. const e = new Error(msg);
  63. e.node = node;
  64. throw e;
  65. }
  66. function helper(msg) {
  67. importedHelpers.add(msg);
  68. return `_${msg}`;
  69. }
  70. function registerBinding(id, isRef = false) {
  71. excludedIds.add(id);
  72. if (currentScope) {
  73. currentScope[id.name] = isRef;
  74. }
  75. else {
  76. error('registerBinding called without active scope, something is wrong.', id);
  77. }
  78. }
  79. const registerRefBinding = (id) => registerBinding(id, true);
  80. function walkScope(node) {
  81. for (const stmt of node.body) {
  82. if (stmt.type === 'VariableDeclaration') {
  83. if (stmt.declare)
  84. continue;
  85. for (const decl of stmt.declarations) {
  86. let toVarCall;
  87. if (decl.init &&
  88. decl.init.type === 'CallExpression' &&
  89. decl.init.callee.type === 'Identifier' &&
  90. (toVarCall = isToVarCall(decl.init.callee.name))) {
  91. processRefDeclaration(toVarCall, decl.init, decl.id, stmt);
  92. }
  93. else {
  94. for (const id of compilerCore.extractIdentifiers(decl.id)) {
  95. registerBinding(id);
  96. }
  97. }
  98. }
  99. }
  100. else if (stmt.type === 'FunctionDeclaration' ||
  101. stmt.type === 'ClassDeclaration') {
  102. if (stmt.declare || !stmt.id)
  103. continue;
  104. registerBinding(stmt.id);
  105. }
  106. }
  107. }
  108. function processRefDeclaration(method, call, id, statement) {
  109. excludedIds.add(call.callee);
  110. if (statement.kind !== 'let') {
  111. error(`${method}() bindings can only be declared with let`, call);
  112. }
  113. if (method === TO_VAR_SYMBOL) {
  114. // $
  115. // remove macro
  116. s.remove(call.callee.start + offset, call.callee.end + offset);
  117. if (id.type === 'Identifier') {
  118. // single variable
  119. registerRefBinding(id);
  120. }
  121. else if (id.type === 'ObjectPattern') {
  122. processRefObjectPattern(id, statement);
  123. }
  124. else if (id.type === 'ArrayPattern') {
  125. processRefArrayPattern(id, statement);
  126. }
  127. }
  128. else {
  129. // shorthands
  130. if (id.type === 'Identifier') {
  131. registerRefBinding(id);
  132. // replace call
  133. s.overwrite(call.start + offset, call.start + method.length + offset, helper(method.slice(1)));
  134. }
  135. else {
  136. error(`${method}() cannot be used with destructure patterns.`, call);
  137. }
  138. }
  139. }
  140. function processRefObjectPattern(pattern, statement) {
  141. for (const p of pattern.properties) {
  142. let nameId;
  143. if (p.type === 'ObjectProperty') {
  144. if (p.key.start === p.value.start) {
  145. // shorthand { foo } --> { foo: __foo }
  146. nameId = p.key;
  147. s.appendLeft(nameId.end + offset, `: __${nameId.name}`);
  148. if (p.value.type === 'Identifier') {
  149. // avoid shorthand value identifier from being processed
  150. excludedIds.add(p.value);
  151. }
  152. else if (p.value.type === 'AssignmentPattern' &&
  153. p.value.left.type === 'Identifier') {
  154. // { foo = 1 }
  155. excludedIds.add(p.value.left);
  156. }
  157. }
  158. else {
  159. if (p.value.type === 'Identifier') {
  160. // { foo: bar } --> { foo: __bar }
  161. nameId = p.value;
  162. s.prependRight(nameId.start + offset, `__`);
  163. }
  164. else if (p.value.type === 'ObjectPattern') {
  165. processRefObjectPattern(p.value, statement);
  166. }
  167. else if (p.value.type === 'ArrayPattern') {
  168. processRefArrayPattern(p.value, statement);
  169. }
  170. else if (p.value.type === 'AssignmentPattern') {
  171. // { foo: bar = 1 } --> { foo: __bar = 1 }
  172. nameId = p.value.left;
  173. s.prependRight(nameId.start + offset, `__`);
  174. }
  175. }
  176. }
  177. else {
  178. // rest element { ...foo } --> { ...__foo }
  179. nameId = p.argument;
  180. s.prependRight(nameId.start + offset, `__`);
  181. }
  182. if (nameId) {
  183. registerRefBinding(nameId);
  184. // append binding declarations after the parent statement
  185. s.appendLeft(statement.end + offset, `\nconst ${nameId.name} = ${helper('shallowRef')}(__${nameId.name});`);
  186. }
  187. }
  188. }
  189. function processRefArrayPattern(pattern, statement) {
  190. for (const e of pattern.elements) {
  191. if (!e)
  192. continue;
  193. let nameId;
  194. if (e.type === 'Identifier') {
  195. // [a] --> [__a]
  196. nameId = e;
  197. }
  198. else if (e.type === 'AssignmentPattern') {
  199. // [a = 1] --> [__a = 1]
  200. nameId = e.left;
  201. }
  202. else if (e.type === 'RestElement') {
  203. // [...a] --> [...__a]
  204. nameId = e.argument;
  205. }
  206. else if (e.type === 'ObjectPattern') {
  207. processRefObjectPattern(e, statement);
  208. }
  209. else if (e.type === 'ArrayPattern') {
  210. processRefArrayPattern(e, statement);
  211. }
  212. if (nameId) {
  213. registerRefBinding(nameId);
  214. // prefix original
  215. s.prependRight(nameId.start + offset, `__`);
  216. // append binding declarations after the parent statement
  217. s.appendLeft(statement.end + offset, `\nconst ${nameId.name} = ${helper('shallowRef')}(__${nameId.name});`);
  218. }
  219. }
  220. }
  221. function checkRefId(scope, id, parent, parentStack) {
  222. if (id.name in scope) {
  223. if (scope[id.name]) {
  224. if (compilerCore.isStaticProperty(parent) && parent.shorthand) {
  225. // let binding used in a property shorthand
  226. // { foo } -> { foo: foo.value }
  227. // skip for destructure patterns
  228. if (!parent.inPattern ||
  229. compilerCore.isInDestructureAssignment(parent, parentStack)) {
  230. s.appendLeft(id.end + offset, `: ${id.name}.value`);
  231. }
  232. }
  233. else {
  234. s.appendLeft(id.end + offset, '.value');
  235. }
  236. }
  237. return true;
  238. }
  239. return false;
  240. }
  241. // check root scope first
  242. walkScope(ast);
  243. estreeWalker.walk(ast, {
  244. enter(node, parent) {
  245. parent && parentStack.push(parent);
  246. // function scopes
  247. if (compilerCore.isFunctionType(node)) {
  248. scopeStack.push((currentScope = {}));
  249. compilerCore.walkFunctionParams(node, registerBinding);
  250. if (node.body.type === 'BlockStatement') {
  251. walkScope(node.body);
  252. }
  253. return;
  254. }
  255. // non-function block scopes
  256. if (node.type === 'BlockStatement' && !compilerCore.isFunctionType(parent)) {
  257. scopeStack.push((currentScope = {}));
  258. walkScope(node);
  259. return;
  260. }
  261. if (parent &&
  262. parent.type.startsWith('TS') &&
  263. parent.type !== 'TSAsExpression' &&
  264. parent.type !== 'TSNonNullExpression' &&
  265. parent.type !== 'TSTypeAssertion') {
  266. return this.skip();
  267. }
  268. if (node.type === 'Identifier' &&
  269. compilerCore.isReferencedIdentifier(node, parent, parentStack) &&
  270. !excludedIds.has(node)) {
  271. // walk up the scope chain to check if id should be appended .value
  272. let i = scopeStack.length;
  273. while (i--) {
  274. if (checkRefId(scopeStack[i], node, parent, parentStack)) {
  275. return;
  276. }
  277. }
  278. }
  279. if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
  280. const callee = node.callee.name;
  281. const toVarCall = isToVarCall(callee);
  282. if (toVarCall && (!parent || parent.type !== 'VariableDeclarator')) {
  283. return error(`${toVarCall} can only be used as the initializer of ` +
  284. `a variable declaration.`, node);
  285. }
  286. if (callee === TO_REF_SYMBOL) {
  287. s.remove(node.callee.start + offset, node.callee.end + offset);
  288. return this.skip();
  289. }
  290. // TODO remove when out of experimental
  291. if (callee === '$raw') {
  292. error(`$raw() has been replaced by $$(). ` +
  293. `See ${RFC_LINK} for latest updates.`, node);
  294. }
  295. if (callee === '$fromRef') {
  296. error(`$fromRef() has been replaced by $(). ` +
  297. `See ${RFC_LINK} for latest updates.`, node);
  298. }
  299. }
  300. },
  301. leave(node, parent) {
  302. parent && parentStack.pop();
  303. if ((node.type === 'BlockStatement' && !compilerCore.isFunctionType(parent)) ||
  304. compilerCore.isFunctionType(node)) {
  305. scopeStack.pop();
  306. currentScope = scopeStack[scopeStack.length - 1] || null;
  307. }
  308. }
  309. });
  310. return {
  311. rootVars: Object.keys(rootScope).filter(key => rootScope[key]),
  312. importedHelpers: [...importedHelpers]
  313. };
  314. }
  315. function isToVarCall(callee) {
  316. if (callee === TO_VAR_SYMBOL) {
  317. return TO_VAR_SYMBOL;
  318. }
  319. if (callee[0] === TO_VAR_SYMBOL && shorthands.includes(callee.slice(1))) {
  320. return callee;
  321. }
  322. return false;
  323. }
  324. const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369`;
  325. const hasWarned = {};
  326. function warnExperimental() {
  327. // eslint-disable-next-line
  328. if (typeof window !== 'undefined') {
  329. return;
  330. }
  331. warnOnce(`@vue/ref-transform is an experimental feature.\n` +
  332. `Experimental features may change behavior between patch versions.\n` +
  333. `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` +
  334. `You can follow the proposal's status at ${RFC_LINK}.`);
  335. }
  336. function warnOnce(msg) {
  337. const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production';
  338. if (!isNodeProd && !false && !hasWarned[msg]) {
  339. hasWarned[msg] = true;
  340. warn(msg);
  341. }
  342. }
  343. function warn(msg) {
  344. console.warn(`\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n`);
  345. }
  346. exports.shouldTransform = shouldTransform;
  347. exports.transform = transform;
  348. exports.transformAST = transformAST;