My SMM panel
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.
 
 
 
 
 
 

13409 lines
507 KiB

  1. var Vue = (function (exports) {
  2. 'use strict';
  3. /**
  4. * Make a map and return a function for checking if a key
  5. * is in that map.
  6. * IMPORTANT: all calls of this function must be prefixed with
  7. * \/\*#\_\_PURE\_\_\*\/
  8. * So that rollup can tree-shake them if necessary.
  9. */
  10. function makeMap(str, expectsLowerCase) {
  11. const map = Object.create(null);
  12. const list = str.split(',');
  13. for (let i = 0; i < list.length; i++) {
  14. map[list[i]] = true;
  15. }
  16. return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
  17. }
  18. // Patch flags are optimization hints generated by the compiler.
  19. // when a block with dynamicChildren is encountered during diff, the algorithm
  20. // enters "optimized mode". In this mode, we know that the vdom is produced by
  21. // a render function generated by the compiler, so the algorithm only needs to
  22. // handle updates explicitly marked by these patch flags.
  23. // dev only flag -> name mapping
  24. const PatchFlagNames = {
  25. [1 /* TEXT */]: `TEXT`,
  26. [2 /* CLASS */]: `CLASS`,
  27. [4 /* STYLE */]: `STYLE`,
  28. [8 /* PROPS */]: `PROPS`,
  29. [16 /* FULL_PROPS */]: `FULL_PROPS`,
  30. [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
  31. [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
  32. [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
  33. [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
  34. [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
  35. [512 /* NEED_PATCH */]: `NEED_PATCH`,
  36. [-1 /* HOISTED */]: `HOISTED`,
  37. [-2 /* BAIL */]: `BAIL`
  38. };
  39. const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
  40. 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
  41. 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl';
  42. const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
  43. const range = 2;
  44. function generateCodeFrame(source, start = 0, end = source.length) {
  45. const lines = source.split(/\r?\n/);
  46. let count = 0;
  47. const res = [];
  48. for (let i = 0; i < lines.length; i++) {
  49. count += lines[i].length + 1;
  50. if (count >= start) {
  51. for (let j = i - range; j <= i + range || end > count; j++) {
  52. if (j < 0 || j >= lines.length)
  53. continue;
  54. const line = j + 1;
  55. res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
  56. const lineLength = lines[j].length;
  57. if (j === i) {
  58. // push underline
  59. const pad = start - (count - lineLength) + 1;
  60. const length = Math.max(1, end > count ? lineLength - pad : end - start);
  61. res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
  62. }
  63. else if (j > i) {
  64. if (end > count) {
  65. const length = Math.max(Math.min(end - count, lineLength), 1);
  66. res.push(` | ` + '^'.repeat(length));
  67. }
  68. count += lineLength + 1;
  69. }
  70. }
  71. break;
  72. }
  73. }
  74. return res.join('\n');
  75. }
  76. /**
  77. * On the client we only need to offer special cases for boolean attributes that
  78. * have different names from their corresponding dom properties:
  79. * - itemscope -> N/A
  80. * - allowfullscreen -> allowFullscreen
  81. * - formnovalidate -> formNoValidate
  82. * - ismap -> isMap
  83. * - nomodule -> noModule
  84. * - novalidate -> noValidate
  85. * - readonly -> readOnly
  86. */
  87. const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
  88. const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
  89. function normalizeStyle(value) {
  90. if (isArray(value)) {
  91. const res = {};
  92. for (let i = 0; i < value.length; i++) {
  93. const item = value[i];
  94. const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
  95. if (normalized) {
  96. for (const key in normalized) {
  97. res[key] = normalized[key];
  98. }
  99. }
  100. }
  101. return res;
  102. }
  103. else if (isObject(value)) {
  104. return value;
  105. }
  106. }
  107. const listDelimiterRE = /;(?![^(]*\))/g;
  108. const propertyDelimiterRE = /:(.+)/;
  109. function parseStringStyle(cssText) {
  110. const ret = {};
  111. cssText.split(listDelimiterRE).forEach(item => {
  112. if (item) {
  113. const tmp = item.split(propertyDelimiterRE);
  114. tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
  115. }
  116. });
  117. return ret;
  118. }
  119. function normalizeClass(value) {
  120. let res = '';
  121. if (isString(value)) {
  122. res = value;
  123. }
  124. else if (isArray(value)) {
  125. for (let i = 0; i < value.length; i++) {
  126. res += normalizeClass(value[i]) + ' ';
  127. }
  128. }
  129. else if (isObject(value)) {
  130. for (const name in value) {
  131. if (value[name]) {
  132. res += name + ' ';
  133. }
  134. }
  135. }
  136. return res.trim();
  137. }
  138. // These tag configs are shared between compiler-dom and runtime-dom, so they
  139. // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  140. const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
  141. 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
  142. 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
  143. 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
  144. 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
  145. 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
  146. 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
  147. 'option,output,progress,select,textarea,details,dialog,menu,' +
  148. 'summary,template,blockquote,iframe,tfoot';
  149. // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
  150. const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
  151. 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
  152. 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
  153. 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
  154. 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
  155. 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
  156. 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
  157. 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
  158. 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
  159. 'text,textPath,title,tspan,unknown,use,view';
  160. const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
  161. const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
  162. const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
  163. const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
  164. function looseCompareArrays(a, b) {
  165. if (a.length !== b.length)
  166. return false;
  167. let equal = true;
  168. for (let i = 0; equal && i < a.length; i++) {
  169. equal = looseEqual(a[i], b[i]);
  170. }
  171. return equal;
  172. }
  173. function looseEqual(a, b) {
  174. if (a === b)
  175. return true;
  176. let aValidType = isDate(a);
  177. let bValidType = isDate(b);
  178. if (aValidType || bValidType) {
  179. return aValidType && bValidType ? a.getTime() === b.getTime() : false;
  180. }
  181. aValidType = isArray(a);
  182. bValidType = isArray(b);
  183. if (aValidType || bValidType) {
  184. return aValidType && bValidType ? looseCompareArrays(a, b) : false;
  185. }
  186. aValidType = isObject(a);
  187. bValidType = isObject(b);
  188. if (aValidType || bValidType) {
  189. /* istanbul ignore if: this if will probably never be called */
  190. if (!aValidType || !bValidType) {
  191. return false;
  192. }
  193. const aKeysCount = Object.keys(a).length;
  194. const bKeysCount = Object.keys(b).length;
  195. if (aKeysCount !== bKeysCount) {
  196. return false;
  197. }
  198. for (const key in a) {
  199. const aHasKey = a.hasOwnProperty(key);
  200. const bHasKey = b.hasOwnProperty(key);
  201. if ((aHasKey && !bHasKey) ||
  202. (!aHasKey && bHasKey) ||
  203. !looseEqual(a[key], b[key])) {
  204. return false;
  205. }
  206. }
  207. }
  208. return String(a) === String(b);
  209. }
  210. function looseIndexOf(arr, val) {
  211. return arr.findIndex(item => looseEqual(item, val));
  212. }
  213. /**
  214. * For converting {{ interpolation }} values to displayed strings.
  215. * @private
  216. */
  217. const toDisplayString = (val) => {
  218. return val == null
  219. ? ''
  220. : isObject(val)
  221. ? JSON.stringify(val, replacer, 2)
  222. : String(val);
  223. };
  224. const replacer = (_key, val) => {
  225. if (isMap(val)) {
  226. return {
  227. [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
  228. entries[`${key} =>`] = val;
  229. return entries;
  230. }, {})
  231. };
  232. }
  233. else if (isSet(val)) {
  234. return {
  235. [`Set(${val.size})`]: [...val.values()]
  236. };
  237. }
  238. else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
  239. return String(val);
  240. }
  241. return val;
  242. };
  243. const EMPTY_OBJ = Object.freeze({})
  244. ;
  245. const EMPTY_ARR = Object.freeze([]) ;
  246. const NOOP = () => { };
  247. /**
  248. * Always return false.
  249. */
  250. const NO = () => false;
  251. const onRE = /^on[^a-z]/;
  252. const isOn = (key) => onRE.test(key);
  253. const isModelListener = (key) => key.startsWith('onUpdate:');
  254. const extend = Object.assign;
  255. const remove = (arr, el) => {
  256. const i = arr.indexOf(el);
  257. if (i > -1) {
  258. arr.splice(i, 1);
  259. }
  260. };
  261. const hasOwnProperty = Object.prototype.hasOwnProperty;
  262. const hasOwn = (val, key) => hasOwnProperty.call(val, key);
  263. const isArray = Array.isArray;
  264. const isMap = (val) => toTypeString(val) === '[object Map]';
  265. const isSet = (val) => toTypeString(val) === '[object Set]';
  266. const isDate = (val) => val instanceof Date;
  267. const isFunction = (val) => typeof val === 'function';
  268. const isString = (val) => typeof val === 'string';
  269. const isSymbol = (val) => typeof val === 'symbol';
  270. const isObject = (val) => val !== null && typeof val === 'object';
  271. const isPromise = (val) => {
  272. return isObject(val) && isFunction(val.then) && isFunction(val.catch);
  273. };
  274. const objectToString = Object.prototype.toString;
  275. const toTypeString = (value) => objectToString.call(value);
  276. const toRawType = (value) => {
  277. // extract "RawType" from strings like "[object RawType]"
  278. return toTypeString(value).slice(8, -1);
  279. };
  280. const isPlainObject = (val) => toTypeString(val) === '[object Object]';
  281. const isIntegerKey = (key) => isString(key) &&
  282. key !== 'NaN' &&
  283. key[0] !== '-' &&
  284. '' + parseInt(key, 10) === key;
  285. const isReservedProp = /*#__PURE__*/ makeMap(
  286. // the leading comma is intentional so empty string "" is also included
  287. ',key,ref,' +
  288. 'onVnodeBeforeMount,onVnodeMounted,' +
  289. 'onVnodeBeforeUpdate,onVnodeUpdated,' +
  290. 'onVnodeBeforeUnmount,onVnodeUnmounted');
  291. const cacheStringFunction = (fn) => {
  292. const cache = Object.create(null);
  293. return ((str) => {
  294. const hit = cache[str];
  295. return hit || (cache[str] = fn(str));
  296. });
  297. };
  298. const camelizeRE = /-(\w)/g;
  299. /**
  300. * @private
  301. */
  302. const camelize = cacheStringFunction((str) => {
  303. return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
  304. });
  305. const hyphenateRE = /\B([A-Z])/g;
  306. /**
  307. * @private
  308. */
  309. const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
  310. /**
  311. * @private
  312. */
  313. const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
  314. /**
  315. * @private
  316. */
  317. const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
  318. // compare whether a value has changed, accounting for NaN.
  319. const hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
  320. const invokeArrayFns = (fns, arg) => {
  321. for (let i = 0; i < fns.length; i++) {
  322. fns[i](arg);
  323. }
  324. };
  325. const def = (obj, key, value) => {
  326. Object.defineProperty(obj, key, {
  327. configurable: true,
  328. enumerable: false,
  329. value
  330. });
  331. };
  332. const toNumber = (val) => {
  333. const n = parseFloat(val);
  334. return isNaN(n) ? val : n;
  335. };
  336. let _globalThis;
  337. const getGlobalThis = () => {
  338. return (_globalThis ||
  339. (_globalThis =
  340. typeof globalThis !== 'undefined'
  341. ? globalThis
  342. : typeof self !== 'undefined'
  343. ? self
  344. : typeof window !== 'undefined'
  345. ? window
  346. : typeof global !== 'undefined'
  347. ? global
  348. : {}));
  349. };
  350. const targetMap = new WeakMap();
  351. const effectStack = [];
  352. let activeEffect;
  353. const ITERATE_KEY = Symbol( 'iterate' );
  354. const MAP_KEY_ITERATE_KEY = Symbol( 'Map key iterate' );
  355. function isEffect(fn) {
  356. return fn && fn._isEffect === true;
  357. }
  358. function effect(fn, options = EMPTY_OBJ) {
  359. if (isEffect(fn)) {
  360. fn = fn.raw;
  361. }
  362. const effect = createReactiveEffect(fn, options);
  363. if (!options.lazy) {
  364. effect();
  365. }
  366. return effect;
  367. }
  368. function stop(effect) {
  369. if (effect.active) {
  370. cleanup(effect);
  371. if (effect.options.onStop) {
  372. effect.options.onStop();
  373. }
  374. effect.active = false;
  375. }
  376. }
  377. let uid = 0;
  378. function createReactiveEffect(fn, options) {
  379. const effect = function reactiveEffect() {
  380. if (!effect.active) {
  381. return options.scheduler ? undefined : fn();
  382. }
  383. if (!effectStack.includes(effect)) {
  384. cleanup(effect);
  385. try {
  386. enableTracking();
  387. effectStack.push(effect);
  388. activeEffect = effect;
  389. return fn();
  390. }
  391. finally {
  392. effectStack.pop();
  393. resetTracking();
  394. activeEffect = effectStack[effectStack.length - 1];
  395. }
  396. }
  397. };
  398. effect.id = uid++;
  399. effect.allowRecurse = !!options.allowRecurse;
  400. effect._isEffect = true;
  401. effect.active = true;
  402. effect.raw = fn;
  403. effect.deps = [];
  404. effect.options = options;
  405. return effect;
  406. }
  407. function cleanup(effect) {
  408. const { deps } = effect;
  409. if (deps.length) {
  410. for (let i = 0; i < deps.length; i++) {
  411. deps[i].delete(effect);
  412. }
  413. deps.length = 0;
  414. }
  415. }
  416. let shouldTrack = true;
  417. const trackStack = [];
  418. function pauseTracking() {
  419. trackStack.push(shouldTrack);
  420. shouldTrack = false;
  421. }
  422. function enableTracking() {
  423. trackStack.push(shouldTrack);
  424. shouldTrack = true;
  425. }
  426. function resetTracking() {
  427. const last = trackStack.pop();
  428. shouldTrack = last === undefined ? true : last;
  429. }
  430. function track(target, type, key) {
  431. if (!shouldTrack || activeEffect === undefined) {
  432. return;
  433. }
  434. let depsMap = targetMap.get(target);
  435. if (!depsMap) {
  436. targetMap.set(target, (depsMap = new Map()));
  437. }
  438. let dep = depsMap.get(key);
  439. if (!dep) {
  440. depsMap.set(key, (dep = new Set()));
  441. }
  442. if (!dep.has(activeEffect)) {
  443. dep.add(activeEffect);
  444. activeEffect.deps.push(dep);
  445. if ( activeEffect.options.onTrack) {
  446. activeEffect.options.onTrack({
  447. effect: activeEffect,
  448. target,
  449. type,
  450. key
  451. });
  452. }
  453. }
  454. }
  455. function trigger(target, type, key, newValue, oldValue, oldTarget) {
  456. const depsMap = targetMap.get(target);
  457. if (!depsMap) {
  458. // never been tracked
  459. return;
  460. }
  461. const effects = new Set();
  462. const add = (effectsToAdd) => {
  463. if (effectsToAdd) {
  464. effectsToAdd.forEach(effect => {
  465. if (effect !== activeEffect || effect.allowRecurse) {
  466. effects.add(effect);
  467. }
  468. });
  469. }
  470. };
  471. if (type === "clear" /* CLEAR */) {
  472. // collection being cleared
  473. // trigger all effects for target
  474. depsMap.forEach(add);
  475. }
  476. else if (key === 'length' && isArray(target)) {
  477. depsMap.forEach((dep, key) => {
  478. if (key === 'length' || key >= newValue) {
  479. add(dep);
  480. }
  481. });
  482. }
  483. else {
  484. // schedule runs for SET | ADD | DELETE
  485. if (key !== void 0) {
  486. add(depsMap.get(key));
  487. }
  488. // also run for iteration key on ADD | DELETE | Map.SET
  489. switch (type) {
  490. case "add" /* ADD */:
  491. if (!isArray(target)) {
  492. add(depsMap.get(ITERATE_KEY));
  493. if (isMap(target)) {
  494. add(depsMap.get(MAP_KEY_ITERATE_KEY));
  495. }
  496. }
  497. else if (isIntegerKey(key)) {
  498. // new index added to array -> length changes
  499. add(depsMap.get('length'));
  500. }
  501. break;
  502. case "delete" /* DELETE */:
  503. if (!isArray(target)) {
  504. add(depsMap.get(ITERATE_KEY));
  505. if (isMap(target)) {
  506. add(depsMap.get(MAP_KEY_ITERATE_KEY));
  507. }
  508. }
  509. break;
  510. case "set" /* SET */:
  511. if (isMap(target)) {
  512. add(depsMap.get(ITERATE_KEY));
  513. }
  514. break;
  515. }
  516. }
  517. const run = (effect) => {
  518. if ( effect.options.onTrigger) {
  519. effect.options.onTrigger({
  520. effect,
  521. target,
  522. key,
  523. type,
  524. newValue,
  525. oldValue,
  526. oldTarget
  527. });
  528. }
  529. if (effect.options.scheduler) {
  530. effect.options.scheduler(effect);
  531. }
  532. else {
  533. effect();
  534. }
  535. };
  536. effects.forEach(run);
  537. }
  538. const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
  539. .map(key => Symbol[key])
  540. .filter(isSymbol));
  541. const get = /*#__PURE__*/ createGetter();
  542. const shallowGet = /*#__PURE__*/ createGetter(false, true);
  543. const readonlyGet = /*#__PURE__*/ createGetter(true);
  544. const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
  545. const arrayInstrumentations = {};
  546. ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
  547. const method = Array.prototype[key];
  548. arrayInstrumentations[key] = function (...args) {
  549. const arr = toRaw(this);
  550. for (let i = 0, l = this.length; i < l; i++) {
  551. track(arr, "get" /* GET */, i + '');
  552. }
  553. // we run the method using the original args first (which may be reactive)
  554. const res = method.apply(arr, args);
  555. if (res === -1 || res === false) {
  556. // if that didn't work, run it again using raw values.
  557. return method.apply(arr, args.map(toRaw));
  558. }
  559. else {
  560. return res;
  561. }
  562. };
  563. });
  564. ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
  565. const method = Array.prototype[key];
  566. arrayInstrumentations[key] = function (...args) {
  567. pauseTracking();
  568. const res = method.apply(this, args);
  569. resetTracking();
  570. return res;
  571. };
  572. });
  573. function createGetter(isReadonly = false, shallow = false) {
  574. return function get(target, key, receiver) {
  575. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  576. return !isReadonly;
  577. }
  578. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  579. return isReadonly;
  580. }
  581. else if (key === "__v_raw" /* RAW */ &&
  582. receiver === (isReadonly ? readonlyMap : reactiveMap).get(target)) {
  583. return target;
  584. }
  585. const targetIsArray = isArray(target);
  586. if (targetIsArray && hasOwn(arrayInstrumentations, key)) {
  587. return Reflect.get(arrayInstrumentations, key, receiver);
  588. }
  589. const res = Reflect.get(target, key, receiver);
  590. if (isSymbol(key)
  591. ? builtInSymbols.has(key)
  592. : key === `__proto__` || key === `__v_isRef`) {
  593. return res;
  594. }
  595. if (!isReadonly) {
  596. track(target, "get" /* GET */, key);
  597. }
  598. if (shallow) {
  599. return res;
  600. }
  601. if (isRef(res)) {
  602. // ref unwrapping - does not apply for Array + integer key.
  603. const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
  604. return shouldUnwrap ? res.value : res;
  605. }
  606. if (isObject(res)) {
  607. // Convert returned value into a proxy as well. we do the isObject check
  608. // here to avoid invalid value warning. Also need to lazy access readonly
  609. // and reactive here to avoid circular dependency.
  610. return isReadonly ? readonly(res) : reactive(res);
  611. }
  612. return res;
  613. };
  614. }
  615. const set = /*#__PURE__*/ createSetter();
  616. const shallowSet = /*#__PURE__*/ createSetter(true);
  617. function createSetter(shallow = false) {
  618. return function set(target, key, value, receiver) {
  619. const oldValue = target[key];
  620. if (!shallow) {
  621. value = toRaw(value);
  622. if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
  623. oldValue.value = value;
  624. return true;
  625. }
  626. }
  627. const hadKey = isArray(target) && isIntegerKey(key)
  628. ? Number(key) < target.length
  629. : hasOwn(target, key);
  630. const result = Reflect.set(target, key, value, receiver);
  631. // don't trigger if target is something up in the prototype chain of original
  632. if (target === toRaw(receiver)) {
  633. if (!hadKey) {
  634. trigger(target, "add" /* ADD */, key, value);
  635. }
  636. else if (hasChanged(value, oldValue)) {
  637. trigger(target, "set" /* SET */, key, value, oldValue);
  638. }
  639. }
  640. return result;
  641. };
  642. }
  643. function deleteProperty(target, key) {
  644. const hadKey = hasOwn(target, key);
  645. const oldValue = target[key];
  646. const result = Reflect.deleteProperty(target, key);
  647. if (result && hadKey) {
  648. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  649. }
  650. return result;
  651. }
  652. function has(target, key) {
  653. const result = Reflect.has(target, key);
  654. if (!isSymbol(key) || !builtInSymbols.has(key)) {
  655. track(target, "has" /* HAS */, key);
  656. }
  657. return result;
  658. }
  659. function ownKeys(target) {
  660. track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
  661. return Reflect.ownKeys(target);
  662. }
  663. const mutableHandlers = {
  664. get,
  665. set,
  666. deleteProperty,
  667. has,
  668. ownKeys
  669. };
  670. const readonlyHandlers = {
  671. get: readonlyGet,
  672. set(target, key) {
  673. {
  674. console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
  675. }
  676. return true;
  677. },
  678. deleteProperty(target, key) {
  679. {
  680. console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
  681. }
  682. return true;
  683. }
  684. };
  685. const shallowReactiveHandlers = extend({}, mutableHandlers, {
  686. get: shallowGet,
  687. set: shallowSet
  688. });
  689. // Props handlers are special in the sense that it should not unwrap top-level
  690. // refs (in order to allow refs to be explicitly passed down), but should
  691. // retain the reactivity of the normal readonly object.
  692. const shallowReadonlyHandlers = extend({}, readonlyHandlers, {
  693. get: shallowReadonlyGet
  694. });
  695. const toReactive = (value) => isObject(value) ? reactive(value) : value;
  696. const toReadonly = (value) => isObject(value) ? readonly(value) : value;
  697. const toShallow = (value) => value;
  698. const getProto = (v) => Reflect.getPrototypeOf(v);
  699. function get$1(target, key, isReadonly = false, isShallow = false) {
  700. // #1772: readonly(reactive(Map)) should return readonly + reactive version
  701. // of the value
  702. target = target["__v_raw" /* RAW */];
  703. const rawTarget = toRaw(target);
  704. const rawKey = toRaw(key);
  705. if (key !== rawKey) {
  706. !isReadonly && track(rawTarget, "get" /* GET */, key);
  707. }
  708. !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
  709. const { has } = getProto(rawTarget);
  710. const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
  711. if (has.call(rawTarget, key)) {
  712. return wrap(target.get(key));
  713. }
  714. else if (has.call(rawTarget, rawKey)) {
  715. return wrap(target.get(rawKey));
  716. }
  717. }
  718. function has$1(key, isReadonly = false) {
  719. const target = this["__v_raw" /* RAW */];
  720. const rawTarget = toRaw(target);
  721. const rawKey = toRaw(key);
  722. if (key !== rawKey) {
  723. !isReadonly && track(rawTarget, "has" /* HAS */, key);
  724. }
  725. !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
  726. return key === rawKey
  727. ? target.has(key)
  728. : target.has(key) || target.has(rawKey);
  729. }
  730. function size(target, isReadonly = false) {
  731. target = target["__v_raw" /* RAW */];
  732. !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
  733. return Reflect.get(target, 'size', target);
  734. }
  735. function add(value) {
  736. value = toRaw(value);
  737. const target = toRaw(this);
  738. const proto = getProto(target);
  739. const hadKey = proto.has.call(target, value);
  740. const result = target.add(value);
  741. if (!hadKey) {
  742. trigger(target, "add" /* ADD */, value, value);
  743. }
  744. return result;
  745. }
  746. function set$1(key, value) {
  747. value = toRaw(value);
  748. const target = toRaw(this);
  749. const { has, get } = getProto(target);
  750. let hadKey = has.call(target, key);
  751. if (!hadKey) {
  752. key = toRaw(key);
  753. hadKey = has.call(target, key);
  754. }
  755. else {
  756. checkIdentityKeys(target, has, key);
  757. }
  758. const oldValue = get.call(target, key);
  759. const result = target.set(key, value);
  760. if (!hadKey) {
  761. trigger(target, "add" /* ADD */, key, value);
  762. }
  763. else if (hasChanged(value, oldValue)) {
  764. trigger(target, "set" /* SET */, key, value, oldValue);
  765. }
  766. return result;
  767. }
  768. function deleteEntry(key) {
  769. const target = toRaw(this);
  770. const { has, get } = getProto(target);
  771. let hadKey = has.call(target, key);
  772. if (!hadKey) {
  773. key = toRaw(key);
  774. hadKey = has.call(target, key);
  775. }
  776. else {
  777. checkIdentityKeys(target, has, key);
  778. }
  779. const oldValue = get ? get.call(target, key) : undefined;
  780. // forward the operation before queueing reactions
  781. const result = target.delete(key);
  782. if (hadKey) {
  783. trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
  784. }
  785. return result;
  786. }
  787. function clear() {
  788. const target = toRaw(this);
  789. const hadItems = target.size !== 0;
  790. const oldTarget = isMap(target)
  791. ? new Map(target)
  792. : new Set(target)
  793. ;
  794. // forward the operation before queueing reactions
  795. const result = target.clear();
  796. if (hadItems) {
  797. trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
  798. }
  799. return result;
  800. }
  801. function createForEach(isReadonly, isShallow) {
  802. return function forEach(callback, thisArg) {
  803. const observed = this;
  804. const target = observed["__v_raw" /* RAW */];
  805. const rawTarget = toRaw(target);
  806. const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
  807. !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
  808. return target.forEach((value, key) => {
  809. // important: make sure the callback is
  810. // 1. invoked with the reactive map as `this` and 3rd arg
  811. // 2. the value received should be a corresponding reactive/readonly.
  812. return callback.call(thisArg, wrap(value), wrap(key), observed);
  813. });
  814. };
  815. }
  816. function createIterableMethod(method, isReadonly, isShallow) {
  817. return function (...args) {
  818. const target = this["__v_raw" /* RAW */];
  819. const rawTarget = toRaw(target);
  820. const targetIsMap = isMap(rawTarget);
  821. const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
  822. const isKeyOnly = method === 'keys' && targetIsMap;
  823. const innerIterator = target[method](...args);
  824. const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
  825. !isReadonly &&
  826. track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
  827. // return a wrapped iterator which returns observed versions of the
  828. // values emitted from the real iterator
  829. return {
  830. // iterator protocol
  831. next() {
  832. const { value, done } = innerIterator.next();
  833. return done
  834. ? { value, done }
  835. : {
  836. value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
  837. done
  838. };
  839. },
  840. // iterable protocol
  841. [Symbol.iterator]() {
  842. return this;
  843. }
  844. };
  845. };
  846. }
  847. function createReadonlyMethod(type) {
  848. return function (...args) {
  849. {
  850. const key = args[0] ? `on key "${args[0]}" ` : ``;
  851. console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
  852. }
  853. return type === "delete" /* DELETE */ ? false : this;
  854. };
  855. }
  856. const mutableInstrumentations = {
  857. get(key) {
  858. return get$1(this, key);
  859. },
  860. get size() {
  861. return size(this);
  862. },
  863. has: has$1,
  864. add,
  865. set: set$1,
  866. delete: deleteEntry,
  867. clear,
  868. forEach: createForEach(false, false)
  869. };
  870. const shallowInstrumentations = {
  871. get(key) {
  872. return get$1(this, key, false, true);
  873. },
  874. get size() {
  875. return size(this);
  876. },
  877. has: has$1,
  878. add,
  879. set: set$1,
  880. delete: deleteEntry,
  881. clear,
  882. forEach: createForEach(false, true)
  883. };
  884. const readonlyInstrumentations = {
  885. get(key) {
  886. return get$1(this, key, true);
  887. },
  888. get size() {
  889. return size(this, true);
  890. },
  891. has(key) {
  892. return has$1.call(this, key, true);
  893. },
  894. add: createReadonlyMethod("add" /* ADD */),
  895. set: createReadonlyMethod("set" /* SET */),
  896. delete: createReadonlyMethod("delete" /* DELETE */),
  897. clear: createReadonlyMethod("clear" /* CLEAR */),
  898. forEach: createForEach(true, false)
  899. };
  900. const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
  901. iteratorMethods.forEach(method => {
  902. mutableInstrumentations[method] = createIterableMethod(method, false, false);
  903. readonlyInstrumentations[method] = createIterableMethod(method, true, false);
  904. shallowInstrumentations[method] = createIterableMethod(method, false, true);
  905. });
  906. function createInstrumentationGetter(isReadonly, shallow) {
  907. const instrumentations = shallow
  908. ? shallowInstrumentations
  909. : isReadonly
  910. ? readonlyInstrumentations
  911. : mutableInstrumentations;
  912. return (target, key, receiver) => {
  913. if (key === "__v_isReactive" /* IS_REACTIVE */) {
  914. return !isReadonly;
  915. }
  916. else if (key === "__v_isReadonly" /* IS_READONLY */) {
  917. return isReadonly;
  918. }
  919. else if (key === "__v_raw" /* RAW */) {
  920. return target;
  921. }
  922. return Reflect.get(hasOwn(instrumentations, key) && key in target
  923. ? instrumentations
  924. : target, key, receiver);
  925. };
  926. }
  927. const mutableCollectionHandlers = {
  928. get: createInstrumentationGetter(false, false)
  929. };
  930. const shallowCollectionHandlers = {
  931. get: createInstrumentationGetter(false, true)
  932. };
  933. const readonlyCollectionHandlers = {
  934. get: createInstrumentationGetter(true, false)
  935. };
  936. function checkIdentityKeys(target, has, key) {
  937. const rawKey = toRaw(key);
  938. if (rawKey !== key && has.call(target, rawKey)) {
  939. const type = toRawType(target);
  940. console.warn(`Reactive ${type} contains both the raw and reactive ` +
  941. `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
  942. `which can lead to inconsistencies. ` +
  943. `Avoid differentiating between the raw and reactive versions ` +
  944. `of an object and only use the reactive version if possible.`);
  945. }
  946. }
  947. const reactiveMap = new WeakMap();
  948. const readonlyMap = new WeakMap();
  949. function targetTypeMap(rawType) {
  950. switch (rawType) {
  951. case 'Object':
  952. case 'Array':
  953. return 1 /* COMMON */;
  954. case 'Map':
  955. case 'Set':
  956. case 'WeakMap':
  957. case 'WeakSet':
  958. return 2 /* COLLECTION */;
  959. default:
  960. return 0 /* INVALID */;
  961. }
  962. }
  963. function getTargetType(value) {
  964. return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
  965. ? 0 /* INVALID */
  966. : targetTypeMap(toRawType(value));
  967. }
  968. function reactive(target) {
  969. // if trying to observe a readonly proxy, return the readonly version.
  970. if (target && target["__v_isReadonly" /* IS_READONLY */]) {
  971. return target;
  972. }
  973. return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers);
  974. }
  975. // Return a reactive-copy of the original object, where only the root level
  976. // properties are reactive, and does NOT unwrap refs nor recursively convert
  977. // returned properties.
  978. function shallowReactive(target) {
  979. return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers);
  980. }
  981. function readonly(target) {
  982. return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers);
  983. }
  984. // Return a reactive-copy of the original object, where only the root level
  985. // properties are readonly, and does NOT unwrap refs nor recursively convert
  986. // returned properties.
  987. // This is used for creating the props proxy object for stateful components.
  988. function shallowReadonly(target) {
  989. return createReactiveObject(target, true, shallowReadonlyHandlers, readonlyCollectionHandlers);
  990. }
  991. function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers) {
  992. if (!isObject(target)) {
  993. {
  994. console.warn(`value cannot be made reactive: ${String(target)}`);
  995. }
  996. return target;
  997. }
  998. // target is already a Proxy, return it.
  999. // exception: calling readonly() on a reactive object
  1000. if (target["__v_raw" /* RAW */] &&
  1001. !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
  1002. return target;
  1003. }
  1004. // target already has corresponding Proxy
  1005. const proxyMap = isReadonly ? readonlyMap : reactiveMap;
  1006. const existingProxy = proxyMap.get(target);
  1007. if (existingProxy) {
  1008. return existingProxy;
  1009. }
  1010. // only a whitelist of value types can be observed.
  1011. const targetType = getTargetType(target);
  1012. if (targetType === 0 /* INVALID */) {
  1013. return target;
  1014. }
  1015. const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
  1016. proxyMap.set(target, proxy);
  1017. return proxy;
  1018. }
  1019. function isReactive(value) {
  1020. if (isReadonly(value)) {
  1021. return isReactive(value["__v_raw" /* RAW */]);
  1022. }
  1023. return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
  1024. }
  1025. function isReadonly(value) {
  1026. return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
  1027. }
  1028. function isProxy(value) {
  1029. return isReactive(value) || isReadonly(value);
  1030. }
  1031. function toRaw(observed) {
  1032. return ((observed && toRaw(observed["__v_raw" /* RAW */])) || observed);
  1033. }
  1034. function markRaw(value) {
  1035. def(value, "__v_skip" /* SKIP */, true);
  1036. return value;
  1037. }
  1038. const convert = (val) => isObject(val) ? reactive(val) : val;
  1039. function isRef(r) {
  1040. return Boolean(r && r.__v_isRef === true);
  1041. }
  1042. function ref(value) {
  1043. return createRef(value);
  1044. }
  1045. function shallowRef(value) {
  1046. return createRef(value, true);
  1047. }
  1048. class RefImpl {
  1049. constructor(_rawValue, _shallow = false) {
  1050. this._rawValue = _rawValue;
  1051. this._shallow = _shallow;
  1052. this.__v_isRef = true;
  1053. this._value = _shallow ? _rawValue : convert(_rawValue);
  1054. }
  1055. get value() {
  1056. track(toRaw(this), "get" /* GET */, 'value');
  1057. return this._value;
  1058. }
  1059. set value(newVal) {
  1060. if (hasChanged(toRaw(newVal), this._rawValue)) {
  1061. this._rawValue = newVal;
  1062. this._value = this._shallow ? newVal : convert(newVal);
  1063. trigger(toRaw(this), "set" /* SET */, 'value', newVal);
  1064. }
  1065. }
  1066. }
  1067. function createRef(rawValue, shallow = false) {
  1068. if (isRef(rawValue)) {
  1069. return rawValue;
  1070. }
  1071. return new RefImpl(rawValue, shallow);
  1072. }
  1073. function triggerRef(ref) {
  1074. trigger(toRaw(ref), "set" /* SET */, 'value', ref.value );
  1075. }
  1076. function unref(ref) {
  1077. return isRef(ref) ? ref.value : ref;
  1078. }
  1079. const shallowUnwrapHandlers = {
  1080. get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
  1081. set: (target, key, value, receiver) => {
  1082. const oldValue = target[key];
  1083. if (isRef(oldValue) && !isRef(value)) {
  1084. oldValue.value = value;
  1085. return true;
  1086. }
  1087. else {
  1088. return Reflect.set(target, key, value, receiver);
  1089. }
  1090. }
  1091. };
  1092. function proxyRefs(objectWithRefs) {
  1093. return isReactive(objectWithRefs)
  1094. ? objectWithRefs
  1095. : new Proxy(objectWithRefs, shallowUnwrapHandlers);
  1096. }
  1097. class CustomRefImpl {
  1098. constructor(factory) {
  1099. this.__v_isRef = true;
  1100. const { get, set } = factory(() => track(this, "get" /* GET */, 'value'), () => trigger(this, "set" /* SET */, 'value'));
  1101. this._get = get;
  1102. this._set = set;
  1103. }
  1104. get value() {
  1105. return this._get();
  1106. }
  1107. set value(newVal) {
  1108. this._set(newVal);
  1109. }
  1110. }
  1111. function customRef(factory) {
  1112. return new CustomRefImpl(factory);
  1113. }
  1114. function toRefs(object) {
  1115. if ( !isProxy(object)) {
  1116. console.warn(`toRefs() expects a reactive object but received a plain one.`);
  1117. }
  1118. const ret = isArray(object) ? new Array(object.length) : {};
  1119. for (const key in object) {
  1120. ret[key] = toRef(object, key);
  1121. }
  1122. return ret;
  1123. }
  1124. class ObjectRefImpl {
  1125. constructor(_object, _key) {
  1126. this._object = _object;
  1127. this._key = _key;
  1128. this.__v_isRef = true;
  1129. }
  1130. get value() {
  1131. return this._object[this._key];
  1132. }
  1133. set value(newVal) {
  1134. this._object[this._key] = newVal;
  1135. }
  1136. }
  1137. function toRef(object, key) {
  1138. return isRef(object[key])
  1139. ? object[key]
  1140. : new ObjectRefImpl(object, key);
  1141. }
  1142. class ComputedRefImpl {
  1143. constructor(getter, _setter, isReadonly) {
  1144. this._setter = _setter;
  1145. this._dirty = true;
  1146. this.__v_isRef = true;
  1147. this.effect = effect(getter, {
  1148. lazy: true,
  1149. scheduler: () => {
  1150. if (!this._dirty) {
  1151. this._dirty = true;
  1152. trigger(toRaw(this), "set" /* SET */, 'value');
  1153. }
  1154. }
  1155. });
  1156. this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
  1157. }
  1158. get value() {
  1159. if (this._dirty) {
  1160. this._value = this.effect();
  1161. this._dirty = false;
  1162. }
  1163. track(toRaw(this), "get" /* GET */, 'value');
  1164. return this._value;
  1165. }
  1166. set value(newValue) {
  1167. this._setter(newValue);
  1168. }
  1169. }
  1170. function computed(getterOrOptions) {
  1171. let getter;
  1172. let setter;
  1173. if (isFunction(getterOrOptions)) {
  1174. getter = getterOrOptions;
  1175. setter = () => {
  1176. console.warn('Write operation failed: computed value is readonly');
  1177. }
  1178. ;
  1179. }
  1180. else {
  1181. getter = getterOrOptions.get;
  1182. setter = getterOrOptions.set;
  1183. }
  1184. return new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set);
  1185. }
  1186. const stack = [];
  1187. function pushWarningContext(vnode) {
  1188. stack.push(vnode);
  1189. }
  1190. function popWarningContext() {
  1191. stack.pop();
  1192. }
  1193. function warn(msg, ...args) {
  1194. // avoid props formatting or warn handler tracking deps that might be mutated
  1195. // during patch, leading to infinite recursion.
  1196. pauseTracking();
  1197. const instance = stack.length ? stack[stack.length - 1].component : null;
  1198. const appWarnHandler = instance && instance.appContext.config.warnHandler;
  1199. const trace = getComponentTrace();
  1200. if (appWarnHandler) {
  1201. callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
  1202. msg + args.join(''),
  1203. instance && instance.proxy,
  1204. trace
  1205. .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
  1206. .join('\n'),
  1207. trace
  1208. ]);
  1209. }
  1210. else {
  1211. const warnArgs = [`[Vue warn]: ${msg}`, ...args];
  1212. /* istanbul ignore if */
  1213. if (trace.length &&
  1214. // avoid spamming console during tests
  1215. !false) {
  1216. warnArgs.push(`\n`, ...formatTrace(trace));
  1217. }
  1218. console.warn(...warnArgs);
  1219. }
  1220. resetTracking();
  1221. }
  1222. function getComponentTrace() {
  1223. let currentVNode = stack[stack.length - 1];
  1224. if (!currentVNode) {
  1225. return [];
  1226. }
  1227. // we can't just use the stack because it will be incomplete during updates
  1228. // that did not start from the root. Re-construct the parent chain using
  1229. // instance parent pointers.
  1230. const normalizedStack = [];
  1231. while (currentVNode) {
  1232. const last = normalizedStack[0];
  1233. if (last && last.vnode === currentVNode) {
  1234. last.recurseCount++;
  1235. }
  1236. else {
  1237. normalizedStack.push({
  1238. vnode: currentVNode,
  1239. recurseCount: 0
  1240. });
  1241. }
  1242. const parentInstance = currentVNode.component && currentVNode.component.parent;
  1243. currentVNode = parentInstance && parentInstance.vnode;
  1244. }
  1245. return normalizedStack;
  1246. }
  1247. /* istanbul ignore next */
  1248. function formatTrace(trace) {
  1249. const logs = [];
  1250. trace.forEach((entry, i) => {
  1251. logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
  1252. });
  1253. return logs;
  1254. }
  1255. function formatTraceEntry({ vnode, recurseCount }) {
  1256. const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
  1257. const isRoot = vnode.component ? vnode.component.parent == null : false;
  1258. const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
  1259. const close = `>` + postfix;
  1260. return vnode.props
  1261. ? [open, ...formatProps(vnode.props), close]
  1262. : [open + close];
  1263. }
  1264. /* istanbul ignore next */
  1265. function formatProps(props) {
  1266. const res = [];
  1267. const keys = Object.keys(props);
  1268. keys.slice(0, 3).forEach(key => {
  1269. res.push(...formatProp(key, props[key]));
  1270. });
  1271. if (keys.length > 3) {
  1272. res.push(` ...`);
  1273. }
  1274. return res;
  1275. }
  1276. /* istanbul ignore next */
  1277. function formatProp(key, value, raw) {
  1278. if (isString(value)) {
  1279. value = JSON.stringify(value);
  1280. return raw ? value : [`${key}=${value}`];
  1281. }
  1282. else if (typeof value === 'number' ||
  1283. typeof value === 'boolean' ||
  1284. value == null) {
  1285. return raw ? value : [`${key}=${value}`];
  1286. }
  1287. else if (isRef(value)) {
  1288. value = formatProp(key, toRaw(value.value), true);
  1289. return raw ? value : [`${key}=Ref<`, value, `>`];
  1290. }
  1291. else if (isFunction(value)) {
  1292. return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
  1293. }
  1294. else {
  1295. value = toRaw(value);
  1296. return raw ? value : [`${key}=`, value];
  1297. }
  1298. }
  1299. const ErrorTypeStrings = {
  1300. ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
  1301. ["c" /* CREATED */]: 'created hook',
  1302. ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
  1303. ["m" /* MOUNTED */]: 'mounted hook',
  1304. ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
  1305. ["u" /* UPDATED */]: 'updated',
  1306. ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
  1307. ["um" /* UNMOUNTED */]: 'unmounted hook',
  1308. ["a" /* ACTIVATED */]: 'activated hook',
  1309. ["da" /* DEACTIVATED */]: 'deactivated hook',
  1310. ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
  1311. ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
  1312. ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
  1313. [0 /* SETUP_FUNCTION */]: 'setup function',
  1314. [1 /* RENDER_FUNCTION */]: 'render function',
  1315. [2 /* WATCH_GETTER */]: 'watcher getter',
  1316. [3 /* WATCH_CALLBACK */]: 'watcher callback',
  1317. [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
  1318. [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
  1319. [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
  1320. [7 /* VNODE_HOOK */]: 'vnode hook',
  1321. [8 /* DIRECTIVE_HOOK */]: 'directive hook',
  1322. [9 /* TRANSITION_HOOK */]: 'transition hook',
  1323. [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
  1324. [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
  1325. [12 /* FUNCTION_REF */]: 'ref function',
  1326. [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
  1327. [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
  1328. 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
  1329. };
  1330. function callWithErrorHandling(fn, instance, type, args) {
  1331. let res;
  1332. try {
  1333. res = args ? fn(...args) : fn();
  1334. }
  1335. catch (err) {
  1336. handleError(err, instance, type);
  1337. }
  1338. return res;
  1339. }
  1340. function callWithAsyncErrorHandling(fn, instance, type, args) {
  1341. if (isFunction(fn)) {
  1342. const res = callWithErrorHandling(fn, instance, type, args);
  1343. if (res && isPromise(res)) {
  1344. res.catch(err => {
  1345. handleError(err, instance, type);
  1346. });
  1347. }
  1348. return res;
  1349. }
  1350. const values = [];
  1351. for (let i = 0; i < fn.length; i++) {
  1352. values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
  1353. }
  1354. return values;
  1355. }
  1356. function handleError(err, instance, type, throwInDev = true) {
  1357. const contextVNode = instance ? instance.vnode : null;
  1358. if (instance) {
  1359. let cur = instance.parent;
  1360. // the exposed instance is the render proxy to keep it consistent with 2.x
  1361. const exposedInstance = instance.proxy;
  1362. // in production the hook receives only the error code
  1363. const errorInfo = ErrorTypeStrings[type] ;
  1364. while (cur) {
  1365. const errorCapturedHooks = cur.ec;
  1366. if (errorCapturedHooks) {
  1367. for (let i = 0; i < errorCapturedHooks.length; i++) {
  1368. if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
  1369. return;
  1370. }
  1371. }
  1372. }
  1373. cur = cur.parent;
  1374. }
  1375. // app-level handling
  1376. const appErrorHandler = instance.appContext.config.errorHandler;
  1377. if (appErrorHandler) {
  1378. callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
  1379. return;
  1380. }
  1381. }
  1382. logError(err, type, contextVNode, throwInDev);
  1383. }
  1384. function logError(err, type, contextVNode, throwInDev = true) {
  1385. {
  1386. const info = ErrorTypeStrings[type];
  1387. if (contextVNode) {
  1388. pushWarningContext(contextVNode);
  1389. }
  1390. warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
  1391. if (contextVNode) {
  1392. popWarningContext();
  1393. }
  1394. // crash in dev by default so it's more noticeable
  1395. if (throwInDev) {
  1396. throw err;
  1397. }
  1398. else {
  1399. console.error(err);
  1400. }
  1401. }
  1402. }
  1403. let isFlushing = false;
  1404. let isFlushPending = false;
  1405. const queue = [];
  1406. let flushIndex = 0;
  1407. const pendingPreFlushCbs = [];
  1408. let activePreFlushCbs = null;
  1409. let preFlushIndex = 0;
  1410. const pendingPostFlushCbs = [];
  1411. let activePostFlushCbs = null;
  1412. let postFlushIndex = 0;
  1413. const resolvedPromise = Promise.resolve();
  1414. let currentFlushPromise = null;
  1415. let currentPreFlushParentJob = null;
  1416. const RECURSION_LIMIT = 100;
  1417. function nextTick(fn) {
  1418. const p = currentFlushPromise || resolvedPromise;
  1419. return fn ? p.then(this ? fn.bind(this) : fn) : p;
  1420. }
  1421. function queueJob(job) {
  1422. // the dedupe search uses the startIndex argument of Array.includes()
  1423. // by default the search index includes the current job that is being run
  1424. // so it cannot recursively trigger itself again.
  1425. // if the job is a watch() callback, the search will start with a +1 index to
  1426. // allow it recursively trigger itself - it is the user's responsibility to
  1427. // ensure it doesn't end up in an infinite loop.
  1428. if ((!queue.length ||
  1429. !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
  1430. job !== currentPreFlushParentJob) {
  1431. queue.push(job);
  1432. queueFlush();
  1433. }
  1434. }
  1435. function queueFlush() {
  1436. if (!isFlushing && !isFlushPending) {
  1437. isFlushPending = true;
  1438. currentFlushPromise = resolvedPromise.then(flushJobs);
  1439. }
  1440. }
  1441. function invalidateJob(job) {
  1442. const i = queue.indexOf(job);
  1443. if (i > -1) {
  1444. queue[i] = null;
  1445. }
  1446. }
  1447. function queueCb(cb, activeQueue, pendingQueue, index) {
  1448. if (!isArray(cb)) {
  1449. if (!activeQueue ||
  1450. !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
  1451. pendingQueue.push(cb);
  1452. }
  1453. }
  1454. else {
  1455. // if cb is an array, it is a component lifecycle hook which can only be
  1456. // triggered by a job, which is already deduped in the main queue, so
  1457. // we can skip duplicate check here to improve perf
  1458. pendingQueue.push(...cb);
  1459. }
  1460. queueFlush();
  1461. }
  1462. function queuePreFlushCb(cb) {
  1463. queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
  1464. }
  1465. function queuePostFlushCb(cb) {
  1466. queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
  1467. }
  1468. function flushPreFlushCbs(seen, parentJob = null) {
  1469. if (pendingPreFlushCbs.length) {
  1470. currentPreFlushParentJob = parentJob;
  1471. activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
  1472. pendingPreFlushCbs.length = 0;
  1473. {
  1474. seen = seen || new Map();
  1475. }
  1476. for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
  1477. {
  1478. checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex]);
  1479. }
  1480. activePreFlushCbs[preFlushIndex]();
  1481. }
  1482. activePreFlushCbs = null;
  1483. preFlushIndex = 0;
  1484. currentPreFlushParentJob = null;
  1485. // recursively flush until it drains
  1486. flushPreFlushCbs(seen, parentJob);
  1487. }
  1488. }
  1489. function flushPostFlushCbs(seen) {
  1490. if (pendingPostFlushCbs.length) {
  1491. const deduped = [...new Set(pendingPostFlushCbs)];
  1492. pendingPostFlushCbs.length = 0;
  1493. // #1947 already has active queue, nested flushPostFlushCbs call
  1494. if (activePostFlushCbs) {
  1495. activePostFlushCbs.push(...deduped);
  1496. return;
  1497. }
  1498. activePostFlushCbs = deduped;
  1499. {
  1500. seen = seen || new Map();
  1501. }
  1502. activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
  1503. for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
  1504. {
  1505. checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex]);
  1506. }
  1507. activePostFlushCbs[postFlushIndex]();
  1508. }
  1509. activePostFlushCbs = null;
  1510. postFlushIndex = 0;
  1511. }
  1512. }
  1513. const getId = (job) => job.id == null ? Infinity : job.id;
  1514. function flushJobs(seen) {
  1515. isFlushPending = false;
  1516. isFlushing = true;
  1517. {
  1518. seen = seen || new Map();
  1519. }
  1520. flushPreFlushCbs(seen);
  1521. // Sort queue before flush.
  1522. // This ensures that:
  1523. // 1. Components are updated from parent to child. (because parent is always
  1524. // created before the child so its render effect will have smaller
  1525. // priority number)
  1526. // 2. If a component is unmounted during a parent component's update,
  1527. // its update can be skipped.
  1528. // Jobs can never be null before flush starts, since they are only invalidated
  1529. // during execution of another flushed job.
  1530. queue.sort((a, b) => getId(a) - getId(b));
  1531. try {
  1532. for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
  1533. const job = queue[flushIndex];
  1534. if (job) {
  1535. if (true) {
  1536. checkRecursiveUpdates(seen, job);
  1537. }
  1538. callWithErrorHandling(job, null, 14 /* SCHEDULER */);
  1539. }
  1540. }
  1541. }
  1542. finally {
  1543. flushIndex = 0;
  1544. queue.length = 0;
  1545. flushPostFlushCbs(seen);
  1546. isFlushing = false;
  1547. currentFlushPromise = null;
  1548. // some postFlushCb queued jobs!
  1549. // keep flushing until it drains.
  1550. if (queue.length || pendingPostFlushCbs.length) {
  1551. flushJobs(seen);
  1552. }
  1553. }
  1554. }
  1555. function checkRecursiveUpdates(seen, fn) {
  1556. if (!seen.has(fn)) {
  1557. seen.set(fn, 1);
  1558. }
  1559. else {
  1560. const count = seen.get(fn);
  1561. if (count > RECURSION_LIMIT) {
  1562. throw new Error(`Maximum recursive updates exceeded. ` +
  1563. `This means you have a reactive effect that is mutating its own ` +
  1564. `dependencies and thus recursively triggering itself. Possible sources ` +
  1565. `include component template, render function, updated hook or ` +
  1566. `watcher source function.`);
  1567. }
  1568. else {
  1569. seen.set(fn, count + 1);
  1570. }
  1571. }
  1572. }
  1573. /* eslint-disable no-restricted-globals */
  1574. let isHmrUpdating = false;
  1575. const hmrDirtyComponents = new Set();
  1576. // Expose the HMR runtime on the global object
  1577. // This makes it entirely tree-shakable without polluting the exports and makes
  1578. // it easier to be used in toolings like vue-loader
  1579. // Note: for a component to be eligible for HMR it also needs the __hmrId option
  1580. // to be set so that its instances can be registered / removed.
  1581. {
  1582. const globalObject = typeof global !== 'undefined'
  1583. ? global
  1584. : typeof self !== 'undefined'
  1585. ? self
  1586. : typeof window !== 'undefined'
  1587. ? window
  1588. : {};
  1589. globalObject.__VUE_HMR_RUNTIME__ = {
  1590. createRecord: tryWrap(createRecord),
  1591. rerender: tryWrap(rerender),
  1592. reload: tryWrap(reload)
  1593. };
  1594. }
  1595. const map = new Map();
  1596. function registerHMR(instance) {
  1597. const id = instance.type.__hmrId;
  1598. let record = map.get(id);
  1599. if (!record) {
  1600. createRecord(id);
  1601. record = map.get(id);
  1602. }
  1603. record.add(instance);
  1604. }
  1605. function unregisterHMR(instance) {
  1606. map.get(instance.type.__hmrId).delete(instance);
  1607. }
  1608. function createRecord(id) {
  1609. if (map.has(id)) {
  1610. return false;
  1611. }
  1612. map.set(id, new Set());
  1613. return true;
  1614. }
  1615. function rerender(id, newRender) {
  1616. const record = map.get(id);
  1617. if (!record)
  1618. return;
  1619. // Array.from creates a snapshot which avoids the set being mutated during
  1620. // updates
  1621. Array.from(record).forEach(instance => {
  1622. if (newRender) {
  1623. instance.render = newRender;
  1624. }
  1625. instance.renderCache = [];
  1626. // this flag forces child components with slot content to update
  1627. isHmrUpdating = true;
  1628. instance.update();
  1629. isHmrUpdating = false;
  1630. });
  1631. }
  1632. function reload(id, newComp) {
  1633. const record = map.get(id);
  1634. if (!record)
  1635. return;
  1636. // Array.from creates a snapshot which avoids the set being mutated during
  1637. // updates
  1638. Array.from(record).forEach(instance => {
  1639. const comp = instance.type;
  1640. if (!hmrDirtyComponents.has(comp)) {
  1641. // 1. Update existing comp definition to match new one
  1642. newComp = isClassComponent(newComp) ? newComp.__vccOpts : newComp;
  1643. extend(comp, newComp);
  1644. for (const key in comp) {
  1645. if (!(key in newComp)) {
  1646. delete comp[key];
  1647. }
  1648. }
  1649. // 2. Mark component dirty. This forces the renderer to replace the component
  1650. // on patch.
  1651. hmrDirtyComponents.add(comp);
  1652. // 3. Make sure to unmark the component after the reload.
  1653. queuePostFlushCb(() => {
  1654. hmrDirtyComponents.delete(comp);
  1655. });
  1656. }
  1657. if (instance.parent) {
  1658. // 4. Force the parent instance to re-render. This will cause all updated
  1659. // components to be unmounted and re-mounted. Queue the update so that we
  1660. // don't end up forcing the same parent to re-render multiple times.
  1661. queueJob(instance.parent.update);
  1662. }
  1663. else if (instance.appContext.reload) {
  1664. // root instance mounted via createApp() has a reload method
  1665. instance.appContext.reload();
  1666. }
  1667. else if (typeof window !== 'undefined') {
  1668. // root instance inside tree created via raw render(). Force reload.
  1669. window.location.reload();
  1670. }
  1671. else {
  1672. console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
  1673. }
  1674. });
  1675. }
  1676. function tryWrap(fn) {
  1677. return (id, arg) => {
  1678. try {
  1679. return fn(id, arg);
  1680. }
  1681. catch (e) {
  1682. console.error(e);
  1683. console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
  1684. `Full reload required.`);
  1685. }
  1686. };
  1687. }
  1688. function setDevtoolsHook(hook) {
  1689. exports.devtools = hook;
  1690. }
  1691. function devtoolsInitApp(app, version) {
  1692. // TODO queue if devtools is undefined
  1693. if (!exports.devtools)
  1694. return;
  1695. exports.devtools.emit("app:init" /* APP_INIT */, app, version, {
  1696. Fragment,
  1697. Text,
  1698. Comment,
  1699. Static
  1700. });
  1701. }
  1702. function devtoolsUnmountApp(app) {
  1703. if (!exports.devtools)
  1704. return;
  1705. exports.devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
  1706. }
  1707. const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
  1708. const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
  1709. const devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
  1710. function createDevtoolsComponentHook(hook) {
  1711. return (component) => {
  1712. if (!exports.devtools)
  1713. return;
  1714. exports.devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined);
  1715. };
  1716. }
  1717. function devtoolsComponentEmit(component, event, params) {
  1718. if (!exports.devtools)
  1719. return;
  1720. exports.devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
  1721. }
  1722. function emit(instance, event, ...rawArgs) {
  1723. const props = instance.vnode.props || EMPTY_OBJ;
  1724. {
  1725. const { emitsOptions, propsOptions: [propsOptions] } = instance;
  1726. if (emitsOptions) {
  1727. if (!(event in emitsOptions)) {
  1728. if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
  1729. warn(`Component emitted event "${event}" but it is neither declared in ` +
  1730. `the emits option nor as an "${toHandlerKey(event)}" prop.`);
  1731. }
  1732. }
  1733. else {
  1734. const validator = emitsOptions[event];
  1735. if (isFunction(validator)) {
  1736. const isValid = validator(...rawArgs);
  1737. if (!isValid) {
  1738. warn(`Invalid event arguments: event validation failed for event "${event}".`);
  1739. }
  1740. }
  1741. }
  1742. }
  1743. }
  1744. let args = rawArgs;
  1745. const isModelListener = event.startsWith('update:');
  1746. // for v-model update:xxx events, apply modifiers on args
  1747. const modelArg = isModelListener && event.slice(7);
  1748. if (modelArg && modelArg in props) {
  1749. const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
  1750. const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
  1751. if (trim) {
  1752. args = rawArgs.map(a => a.trim());
  1753. }
  1754. else if (number) {
  1755. args = rawArgs.map(toNumber);
  1756. }
  1757. }
  1758. {
  1759. devtoolsComponentEmit(instance, event, args);
  1760. }
  1761. {
  1762. const lowerCaseEvent = event.toLowerCase();
  1763. if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
  1764. warn(`Event "${lowerCaseEvent}" is emitted in component ` +
  1765. `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
  1766. `Note that HTML attributes are case-insensitive and you cannot use ` +
  1767. `v-on to listen to camelCase events when using in-DOM templates. ` +
  1768. `You should probably use "${hyphenate(event)}" instead of "${event}".`);
  1769. }
  1770. }
  1771. // convert handler name to camelCase. See issue #2249
  1772. let handlerName = toHandlerKey(camelize(event));
  1773. let handler = props[handlerName];
  1774. // for v-model update:xxx events, also trigger kebab-case equivalent
  1775. // for props passed via kebab-case
  1776. if (!handler && isModelListener) {
  1777. handlerName = toHandlerKey(hyphenate(event));
  1778. handler = props[handlerName];
  1779. }
  1780. if (handler) {
  1781. callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  1782. }
  1783. const onceHandler = props[handlerName + `Once`];
  1784. if (onceHandler) {
  1785. if (!instance.emitted) {
  1786. (instance.emitted = {})[handlerName] = true;
  1787. }
  1788. else if (instance.emitted[handlerName]) {
  1789. return;
  1790. }
  1791. callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
  1792. }
  1793. }
  1794. function normalizeEmitsOptions(comp, appContext, asMixin = false) {
  1795. if (!appContext.deopt && comp.__emits !== undefined) {
  1796. return comp.__emits;
  1797. }
  1798. const raw = comp.emits;
  1799. let normalized = {};
  1800. // apply mixin/extends props
  1801. let hasExtends = false;
  1802. if ( !isFunction(comp)) {
  1803. const extendEmits = (raw) => {
  1804. hasExtends = true;
  1805. extend(normalized, normalizeEmitsOptions(raw, appContext, true));
  1806. };
  1807. if (!asMixin && appContext.mixins.length) {
  1808. appContext.mixins.forEach(extendEmits);
  1809. }
  1810. if (comp.extends) {
  1811. extendEmits(comp.extends);
  1812. }
  1813. if (comp.mixins) {
  1814. comp.mixins.forEach(extendEmits);
  1815. }
  1816. }
  1817. if (!raw && !hasExtends) {
  1818. return (comp.__emits = null);
  1819. }
  1820. if (isArray(raw)) {
  1821. raw.forEach(key => (normalized[key] = null));
  1822. }
  1823. else {
  1824. extend(normalized, raw);
  1825. }
  1826. return (comp.__emits = normalized);
  1827. }
  1828. // Check if an incoming prop key is a declared emit event listener.
  1829. // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
  1830. // both considered matched listeners.
  1831. function isEmitListener(options, key) {
  1832. if (!options || !isOn(key)) {
  1833. return false;
  1834. }
  1835. key = key.replace(/Once$/, '');
  1836. return (hasOwn(options, key[2].toLowerCase() + key.slice(3)) ||
  1837. hasOwn(options, key.slice(2)));
  1838. }
  1839. // mark the current rendering instance for asset resolution (e.g.
  1840. // resolveComponent, resolveDirective) during render
  1841. let currentRenderingInstance = null;
  1842. function setCurrentRenderingInstance(instance) {
  1843. currentRenderingInstance = instance;
  1844. }
  1845. // dev only flag to track whether $attrs was used during render.
  1846. // If $attrs was used during render then the warning for failed attrs
  1847. // fallthrough can be suppressed.
  1848. let accessedAttrs = false;
  1849. function markAttrsAccessed() {
  1850. accessedAttrs = true;
  1851. }
  1852. function renderComponentRoot(instance) {
  1853. const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx } = instance;
  1854. let result;
  1855. currentRenderingInstance = instance;
  1856. {
  1857. accessedAttrs = false;
  1858. }
  1859. try {
  1860. let fallthroughAttrs;
  1861. if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
  1862. // withProxy is a proxy with a different `has` trap only for
  1863. // runtime-compiled render functions using `with` block.
  1864. const proxyToUse = withProxy || proxy;
  1865. result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
  1866. fallthroughAttrs = attrs;
  1867. }
  1868. else {
  1869. // functional
  1870. const render = Component;
  1871. // in dev, mark attrs accessed if optional props (attrs === props)
  1872. if (true && attrs === props) {
  1873. markAttrsAccessed();
  1874. }
  1875. result = normalizeVNode(render.length > 1
  1876. ? render(props, true
  1877. ? {
  1878. get attrs() {
  1879. markAttrsAccessed();
  1880. return attrs;
  1881. },
  1882. slots,
  1883. emit
  1884. }
  1885. : { attrs, slots, emit })
  1886. : render(props, null /* we know it doesn't need it */));
  1887. fallthroughAttrs = Component.props
  1888. ? attrs
  1889. : getFunctionalFallthrough(attrs);
  1890. }
  1891. // attr merging
  1892. // in dev mode, comments are preserved, and it's possible for a template
  1893. // to have comments along side the root element which makes it a fragment
  1894. let root = result;
  1895. let setRoot = undefined;
  1896. if (true) {
  1897. ;
  1898. [root, setRoot] = getChildRoot(result);
  1899. }
  1900. if (Component.inheritAttrs !== false && fallthroughAttrs) {
  1901. const keys = Object.keys(fallthroughAttrs);
  1902. const { shapeFlag } = root;
  1903. if (keys.length) {
  1904. if (shapeFlag & 1 /* ELEMENT */ ||
  1905. shapeFlag & 6 /* COMPONENT */) {
  1906. if (propsOptions && keys.some(isModelListener)) {
  1907. // If a v-model listener (onUpdate:xxx) has a corresponding declared
  1908. // prop, it indicates this component expects to handle v-model and
  1909. // it should not fallthrough.
  1910. // related: #1543, #1643, #1989
  1911. fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
  1912. }
  1913. root = cloneVNode(root, fallthroughAttrs);
  1914. }
  1915. else if (true && !accessedAttrs && root.type !== Comment) {
  1916. const allAttrs = Object.keys(attrs);
  1917. const eventAttrs = [];
  1918. const extraAttrs = [];
  1919. for (let i = 0, l = allAttrs.length; i < l; i++) {
  1920. const key = allAttrs[i];
  1921. if (isOn(key)) {
  1922. // ignore v-model handlers when they fail to fallthrough
  1923. if (!isModelListener(key)) {
  1924. // remove `on`, lowercase first letter to reflect event casing
  1925. // accurately
  1926. eventAttrs.push(key[2].toLowerCase() + key.slice(3));
  1927. }
  1928. }
  1929. else {
  1930. extraAttrs.push(key);
  1931. }
  1932. }
  1933. if (extraAttrs.length) {
  1934. warn(`Extraneous non-props attributes (` +
  1935. `${extraAttrs.join(', ')}) ` +
  1936. `were passed to component but could not be automatically inherited ` +
  1937. `because component renders fragment or text root nodes.`);
  1938. }
  1939. if (eventAttrs.length) {
  1940. warn(`Extraneous non-emits event listeners (` +
  1941. `${eventAttrs.join(', ')}) ` +
  1942. `were passed to component but could not be automatically inherited ` +
  1943. `because component renders fragment or text root nodes. ` +
  1944. `If the listener is intended to be a component custom event listener only, ` +
  1945. `declare it using the "emits" option.`);
  1946. }
  1947. }
  1948. }
  1949. }
  1950. // inherit directives
  1951. if (vnode.dirs) {
  1952. if (true && !isElementRoot(root)) {
  1953. warn(`Runtime directive used on component with non-element root node. ` +
  1954. `The directives will not function as intended.`);
  1955. }
  1956. root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
  1957. }
  1958. // inherit transition data
  1959. if (vnode.transition) {
  1960. if (true && !isElementRoot(root)) {
  1961. warn(`Component inside <Transition> renders non-element root node ` +
  1962. `that cannot be animated.`);
  1963. }
  1964. root.transition = vnode.transition;
  1965. }
  1966. if (true && setRoot) {
  1967. setRoot(root);
  1968. }
  1969. else {
  1970. result = root;
  1971. }
  1972. }
  1973. catch (err) {
  1974. handleError(err, instance, 1 /* RENDER_FUNCTION */);
  1975. result = createVNode(Comment);
  1976. }
  1977. currentRenderingInstance = null;
  1978. return result;
  1979. }
  1980. /**
  1981. * dev only
  1982. * In dev mode, template root level comments are rendered, which turns the
  1983. * template into a fragment root, but we need to locate the single element
  1984. * root for attrs and scope id processing.
  1985. */
  1986. const getChildRoot = (vnode) => {
  1987. if (vnode.type !== Fragment) {
  1988. return [vnode, undefined];
  1989. }
  1990. const rawChildren = vnode.children;
  1991. const dynamicChildren = vnode.dynamicChildren;
  1992. const childRoot = filterSingleRoot(rawChildren);
  1993. if (!childRoot) {
  1994. return [vnode, undefined];
  1995. }
  1996. const index = rawChildren.indexOf(childRoot);
  1997. const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
  1998. const setRoot = (updatedRoot) => {
  1999. rawChildren[index] = updatedRoot;
  2000. if (dynamicChildren) {
  2001. if (dynamicIndex > -1) {
  2002. dynamicChildren[dynamicIndex] = updatedRoot;
  2003. }
  2004. else if (updatedRoot.patchFlag > 0) {
  2005. vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
  2006. }
  2007. }
  2008. };
  2009. return [normalizeVNode(childRoot), setRoot];
  2010. };
  2011. /**
  2012. * dev only
  2013. */
  2014. function filterSingleRoot(children) {
  2015. const filtered = children.filter(child => {
  2016. return !(isVNode(child) &&
  2017. child.type === Comment &&
  2018. child.children !== 'v-if');
  2019. });
  2020. return filtered.length === 1 && isVNode(filtered[0]) ? filtered[0] : null;
  2021. }
  2022. const getFunctionalFallthrough = (attrs) => {
  2023. let res;
  2024. for (const key in attrs) {
  2025. if (key === 'class' || key === 'style' || isOn(key)) {
  2026. (res || (res = {}))[key] = attrs[key];
  2027. }
  2028. }
  2029. return res;
  2030. };
  2031. const filterModelListeners = (attrs, props) => {
  2032. const res = {};
  2033. for (const key in attrs) {
  2034. if (!isModelListener(key) || !(key.slice(9) in props)) {
  2035. res[key] = attrs[key];
  2036. }
  2037. }
  2038. return res;
  2039. };
  2040. const isElementRoot = (vnode) => {
  2041. return (vnode.shapeFlag & 6 /* COMPONENT */ ||
  2042. vnode.shapeFlag & 1 /* ELEMENT */ ||
  2043. vnode.type === Comment // potential v-if branch switch
  2044. );
  2045. };
  2046. function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
  2047. const { props: prevProps, children: prevChildren, component } = prevVNode;
  2048. const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
  2049. const emits = component.emitsOptions;
  2050. // Parent component's render function was hot-updated. Since this may have
  2051. // caused the child component's slots content to have changed, we need to
  2052. // force the child to update as well.
  2053. if ( (prevChildren || nextChildren) && isHmrUpdating) {
  2054. return true;
  2055. }
  2056. // force child update for runtime directive or transition on component vnode.
  2057. if (nextVNode.dirs || nextVNode.transition) {
  2058. return true;
  2059. }
  2060. if (optimized && patchFlag > 0) {
  2061. if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
  2062. // slot content that references values that might have changed,
  2063. // e.g. in a v-for
  2064. return true;
  2065. }
  2066. if (patchFlag & 16 /* FULL_PROPS */) {
  2067. if (!prevProps) {
  2068. return !!nextProps;
  2069. }
  2070. // presence of this flag indicates props are always non-null
  2071. return hasPropsChanged(prevProps, nextProps, emits);
  2072. }
  2073. else if (patchFlag & 8 /* PROPS */) {
  2074. const dynamicProps = nextVNode.dynamicProps;
  2075. for (let i = 0; i < dynamicProps.length; i++) {
  2076. const key = dynamicProps[i];
  2077. if (nextProps[key] !== prevProps[key] &&
  2078. !isEmitListener(emits, key)) {
  2079. return true;
  2080. }
  2081. }
  2082. }
  2083. }
  2084. else {
  2085. // this path is only taken by manually written render functions
  2086. // so presence of any children leads to a forced update
  2087. if (prevChildren || nextChildren) {
  2088. if (!nextChildren || !nextChildren.$stable) {
  2089. return true;
  2090. }
  2091. }
  2092. if (prevProps === nextProps) {
  2093. return false;
  2094. }
  2095. if (!prevProps) {
  2096. return !!nextProps;
  2097. }
  2098. if (!nextProps) {
  2099. return true;
  2100. }
  2101. return hasPropsChanged(prevProps, nextProps, emits);
  2102. }
  2103. return false;
  2104. }
  2105. function hasPropsChanged(prevProps, nextProps, emitsOptions) {
  2106. const nextKeys = Object.keys(nextProps);
  2107. if (nextKeys.length !== Object.keys(prevProps).length) {
  2108. return true;
  2109. }
  2110. for (let i = 0; i < nextKeys.length; i++) {
  2111. const key = nextKeys[i];
  2112. if (nextProps[key] !== prevProps[key] &&
  2113. !isEmitListener(emitsOptions, key)) {
  2114. return true;
  2115. }
  2116. }
  2117. return false;
  2118. }
  2119. function updateHOCHostEl({ vnode, parent }, el // HostNode
  2120. ) {
  2121. while (parent && parent.subTree === vnode) {
  2122. (vnode = parent.vnode).el = el;
  2123. parent = parent.parent;
  2124. }
  2125. }
  2126. const isSuspense = (type) => type.__isSuspense;
  2127. // Suspense exposes a component-like API, and is treated like a component
  2128. // in the compiler, but internally it's a special built-in type that hooks
  2129. // directly into the renderer.
  2130. const SuspenseImpl = {
  2131. // In order to make Suspense tree-shakable, we need to avoid importing it
  2132. // directly in the renderer. The renderer checks for the __isSuspense flag
  2133. // on a vnode's type and calls the `process` method, passing in renderer
  2134. // internals.
  2135. __isSuspense: true,
  2136. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized,
  2137. // platform-specific impl passed from renderer
  2138. rendererInternals) {
  2139. if (n1 == null) {
  2140. mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals);
  2141. }
  2142. else {
  2143. patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, rendererInternals);
  2144. }
  2145. },
  2146. hydrate: hydrateSuspense,
  2147. create: createSuspenseBoundary
  2148. };
  2149. // Force-casted public typing for h and TSX props inference
  2150. const Suspense = ( SuspenseImpl
  2151. );
  2152. function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals) {
  2153. const { p: patch, o: { createElement } } = rendererInternals;
  2154. const hiddenContainer = createElement('div');
  2155. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals));
  2156. // start mounting the content subtree in an off-dom container
  2157. patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG);
  2158. // now check if we have encountered any async deps
  2159. if (suspense.deps > 0) {
  2160. // has async
  2161. // mount the fallback tree
  2162. patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2163. isSVG);
  2164. setActiveBranch(suspense, vnode.ssFallback);
  2165. }
  2166. else {
  2167. // Suspense has no async deps. Just resolve.
  2168. suspense.resolve();
  2169. }
  2170. }
  2171. function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, { p: patch, um: unmount, o: { createElement } }) {
  2172. const suspense = (n2.suspense = n1.suspense);
  2173. suspense.vnode = n2;
  2174. n2.el = n1.el;
  2175. const newBranch = n2.ssContent;
  2176. const newFallback = n2.ssFallback;
  2177. const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
  2178. if (pendingBranch) {
  2179. suspense.pendingBranch = newBranch;
  2180. if (isSameVNodeType(newBranch, pendingBranch)) {
  2181. // same root type but content may have changed.
  2182. patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2183. if (suspense.deps <= 0) {
  2184. suspense.resolve();
  2185. }
  2186. else if (isInFallback) {
  2187. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2188. isSVG);
  2189. setActiveBranch(suspense, newFallback);
  2190. }
  2191. }
  2192. else {
  2193. // toggled before pending tree is resolved
  2194. suspense.pendingId++;
  2195. if (isHydrating) {
  2196. // if toggled before hydration is finished, the current DOM tree is
  2197. // no longer valid. set it as the active branch so it will be unmounted
  2198. // when resolved
  2199. suspense.isHydrating = false;
  2200. suspense.activeBranch = pendingBranch;
  2201. }
  2202. else {
  2203. unmount(pendingBranch, parentComponent, suspense);
  2204. }
  2205. // increment pending ID. this is used to invalidate async callbacks
  2206. // reset suspense state
  2207. suspense.deps = 0;
  2208. // discard effects from pending branch
  2209. suspense.effects.length = 0;
  2210. // discard previous container
  2211. suspense.hiddenContainer = createElement('div');
  2212. if (isInFallback) {
  2213. // already in fallback state
  2214. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2215. if (suspense.deps <= 0) {
  2216. suspense.resolve();
  2217. }
  2218. else {
  2219. patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2220. isSVG);
  2221. setActiveBranch(suspense, newFallback);
  2222. }
  2223. }
  2224. else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2225. // toggled "back" to current active branch
  2226. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG);
  2227. // force resolve
  2228. suspense.resolve(true);
  2229. }
  2230. else {
  2231. // switched to a 3rd branch
  2232. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2233. if (suspense.deps <= 0) {
  2234. suspense.resolve();
  2235. }
  2236. }
  2237. }
  2238. }
  2239. else {
  2240. if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
  2241. // root did not change, just normal patch
  2242. patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG);
  2243. setActiveBranch(suspense, newBranch);
  2244. }
  2245. else {
  2246. // root node toggled
  2247. // invoke @pending event
  2248. const onPending = n2.props && n2.props.onPending;
  2249. if (isFunction(onPending)) {
  2250. onPending();
  2251. }
  2252. // mount pending branch in off-dom container
  2253. suspense.pendingBranch = newBranch;
  2254. suspense.pendingId++;
  2255. patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
  2256. if (suspense.deps <= 0) {
  2257. // incoming branch has no async deps, resolve now.
  2258. suspense.resolve();
  2259. }
  2260. else {
  2261. const { timeout, pendingId } = suspense;
  2262. if (timeout > 0) {
  2263. setTimeout(() => {
  2264. if (suspense.pendingId === pendingId) {
  2265. suspense.fallback(newFallback);
  2266. }
  2267. }, timeout);
  2268. }
  2269. else if (timeout === 0) {
  2270. suspense.fallback(newFallback);
  2271. }
  2272. }
  2273. }
  2274. }
  2275. }
  2276. let hasWarned = false;
  2277. function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals, isHydrating = false) {
  2278. /* istanbul ignore if */
  2279. if ( !hasWarned) {
  2280. hasWarned = true;
  2281. // @ts-ignore `console.info` cannot be null error
  2282. console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
  2283. }
  2284. const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
  2285. const timeout = toNumber(vnode.props && vnode.props.timeout);
  2286. const suspense = {
  2287. vnode,
  2288. parent,
  2289. parentComponent,
  2290. isSVG,
  2291. container,
  2292. hiddenContainer,
  2293. anchor,
  2294. deps: 0,
  2295. pendingId: 0,
  2296. timeout: typeof timeout === 'number' ? timeout : -1,
  2297. activeBranch: null,
  2298. pendingBranch: null,
  2299. isInFallback: true,
  2300. isHydrating,
  2301. isUnmounted: false,
  2302. effects: [],
  2303. resolve(resume = false) {
  2304. {
  2305. if (!resume && !suspense.pendingBranch) {
  2306. throw new Error(`suspense.resolve() is called without a pending branch.`);
  2307. }
  2308. if (suspense.isUnmounted) {
  2309. throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
  2310. }
  2311. }
  2312. const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
  2313. if (suspense.isHydrating) {
  2314. suspense.isHydrating = false;
  2315. }
  2316. else if (!resume) {
  2317. const delayEnter = activeBranch &&
  2318. pendingBranch.transition &&
  2319. pendingBranch.transition.mode === 'out-in';
  2320. if (delayEnter) {
  2321. activeBranch.transition.afterLeave = () => {
  2322. if (pendingId === suspense.pendingId) {
  2323. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2324. }
  2325. };
  2326. }
  2327. // this is initial anchor on mount
  2328. let { anchor } = suspense;
  2329. // unmount current active tree
  2330. if (activeBranch) {
  2331. // if the fallback tree was mounted, it may have been moved
  2332. // as part of a parent suspense. get the latest anchor for insertion
  2333. anchor = next(activeBranch);
  2334. unmount(activeBranch, parentComponent, suspense, true);
  2335. }
  2336. if (!delayEnter) {
  2337. // move content from off-dom container to actual container
  2338. move(pendingBranch, container, anchor, 0 /* ENTER */);
  2339. }
  2340. }
  2341. setActiveBranch(suspense, pendingBranch);
  2342. suspense.pendingBranch = null;
  2343. suspense.isInFallback = false;
  2344. // flush buffered effects
  2345. // check if there is a pending parent suspense
  2346. let parent = suspense.parent;
  2347. let hasUnresolvedAncestor = false;
  2348. while (parent) {
  2349. if (parent.pendingBranch) {
  2350. // found a pending parent suspense, merge buffered post jobs
  2351. // into that parent
  2352. parent.effects.push(...effects);
  2353. hasUnresolvedAncestor = true;
  2354. break;
  2355. }
  2356. parent = parent.parent;
  2357. }
  2358. // no pending parent suspense, flush all jobs
  2359. if (!hasUnresolvedAncestor) {
  2360. queuePostFlushCb(effects);
  2361. }
  2362. suspense.effects = [];
  2363. // invoke @resolve event
  2364. const onResolve = vnode.props && vnode.props.onResolve;
  2365. if (isFunction(onResolve)) {
  2366. onResolve();
  2367. }
  2368. },
  2369. fallback(fallbackVNode) {
  2370. if (!suspense.pendingBranch) {
  2371. return;
  2372. }
  2373. const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
  2374. // invoke @fallback event
  2375. const onFallback = vnode.props && vnode.props.onFallback;
  2376. if (isFunction(onFallback)) {
  2377. onFallback();
  2378. }
  2379. const anchor = next(activeBranch);
  2380. const mountFallback = () => {
  2381. if (!suspense.isInFallback) {
  2382. return;
  2383. }
  2384. // mount the fallback tree
  2385. patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
  2386. isSVG);
  2387. setActiveBranch(suspense, fallbackVNode);
  2388. };
  2389. const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
  2390. if (delayEnter) {
  2391. activeBranch.transition.afterLeave = mountFallback;
  2392. }
  2393. // unmount current active branch
  2394. unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
  2395. true // shouldRemove
  2396. );
  2397. suspense.isInFallback = true;
  2398. if (!delayEnter) {
  2399. mountFallback();
  2400. }
  2401. },
  2402. move(container, anchor, type) {
  2403. suspense.activeBranch &&
  2404. move(suspense.activeBranch, container, anchor, type);
  2405. suspense.container = container;
  2406. },
  2407. next() {
  2408. return suspense.activeBranch && next(suspense.activeBranch);
  2409. },
  2410. registerDep(instance, setupRenderEffect) {
  2411. if (!suspense.pendingBranch) {
  2412. return;
  2413. }
  2414. const hydratedEl = instance.vnode.el;
  2415. suspense.deps++;
  2416. instance
  2417. .asyncDep.catch(err => {
  2418. handleError(err, instance, 0 /* SETUP_FUNCTION */);
  2419. })
  2420. .then(asyncSetupResult => {
  2421. // retry when the setup() promise resolves.
  2422. // component may have been unmounted before resolve.
  2423. if (instance.isUnmounted ||
  2424. suspense.isUnmounted ||
  2425. suspense.pendingId !== instance.suspenseId) {
  2426. return;
  2427. }
  2428. suspense.deps--;
  2429. // retry from this component
  2430. instance.asyncResolved = true;
  2431. const { vnode } = instance;
  2432. {
  2433. pushWarningContext(vnode);
  2434. }
  2435. handleSetupResult(instance, asyncSetupResult);
  2436. if (hydratedEl) {
  2437. // vnode may have been replaced if an update happened before the
  2438. // async dep is resolved.
  2439. vnode.el = hydratedEl;
  2440. }
  2441. const placeholder = !hydratedEl && instance.subTree.el;
  2442. setupRenderEffect(instance, vnode,
  2443. // component may have been moved before resolve.
  2444. // if this is not a hydration, instance.subTree will be the comment
  2445. // placeholder.
  2446. parentNode(hydratedEl || instance.subTree.el),
  2447. // anchor will not be used if this is hydration, so only need to
  2448. // consider the comment placeholder case.
  2449. hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
  2450. if (placeholder) {
  2451. remove(placeholder);
  2452. }
  2453. updateHOCHostEl(instance, vnode.el);
  2454. {
  2455. popWarningContext();
  2456. }
  2457. if (suspense.deps === 0) {
  2458. suspense.resolve();
  2459. }
  2460. });
  2461. },
  2462. unmount(parentSuspense, doRemove) {
  2463. suspense.isUnmounted = true;
  2464. if (suspense.activeBranch) {
  2465. unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
  2466. }
  2467. if (suspense.pendingBranch) {
  2468. unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
  2469. }
  2470. }
  2471. };
  2472. return suspense;
  2473. }
  2474. function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, optimized, rendererInternals, hydrateNode) {
  2475. /* eslint-disable no-restricted-globals */
  2476. const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, optimized, rendererInternals, true /* hydrating */));
  2477. // there are two possible scenarios for server-rendered suspense:
  2478. // - success: ssr content should be fully resolved
  2479. // - failure: ssr content should be the fallback branch.
  2480. // however, on the client we don't really know if it has failed or not
  2481. // attempt to hydrate the DOM assuming it has succeeded, but we still
  2482. // need to construct a suspense boundary first
  2483. const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, optimized);
  2484. if (suspense.deps === 0) {
  2485. suspense.resolve();
  2486. }
  2487. return result;
  2488. /* eslint-enable no-restricted-globals */
  2489. }
  2490. function normalizeSuspenseChildren(vnode) {
  2491. const { shapeFlag, children } = vnode;
  2492. let content;
  2493. let fallback;
  2494. if (shapeFlag & 32 /* SLOTS_CHILDREN */) {
  2495. content = normalizeSuspenseSlot(children.default);
  2496. fallback = normalizeSuspenseSlot(children.fallback);
  2497. }
  2498. else {
  2499. content = normalizeSuspenseSlot(children);
  2500. fallback = normalizeVNode(null);
  2501. }
  2502. return {
  2503. content,
  2504. fallback
  2505. };
  2506. }
  2507. function normalizeSuspenseSlot(s) {
  2508. if (isFunction(s)) {
  2509. s = s();
  2510. }
  2511. if (isArray(s)) {
  2512. const singleChild = filterSingleRoot(s);
  2513. if ( !singleChild) {
  2514. warn(`<Suspense> slots expect a single root node.`);
  2515. }
  2516. s = singleChild;
  2517. }
  2518. return normalizeVNode(s);
  2519. }
  2520. function queueEffectWithSuspense(fn, suspense) {
  2521. if (suspense && suspense.pendingBranch) {
  2522. if (isArray(fn)) {
  2523. suspense.effects.push(...fn);
  2524. }
  2525. else {
  2526. suspense.effects.push(fn);
  2527. }
  2528. }
  2529. else {
  2530. queuePostFlushCb(fn);
  2531. }
  2532. }
  2533. function setActiveBranch(suspense, branch) {
  2534. suspense.activeBranch = branch;
  2535. const { vnode, parentComponent } = suspense;
  2536. const el = (vnode.el = branch.el);
  2537. // in case suspense is the root node of a component,
  2538. // recursively update the HOC el
  2539. if (parentComponent && parentComponent.subTree === vnode) {
  2540. parentComponent.vnode.el = el;
  2541. updateHOCHostEl(parentComponent, el);
  2542. }
  2543. }
  2544. let isRenderingCompiledSlot = 0;
  2545. const setCompiledSlotRendering = (n) => (isRenderingCompiledSlot += n);
  2546. /**
  2547. * Compiler runtime helper for rendering `<slot/>`
  2548. * @private
  2549. */
  2550. function renderSlot(slots, name, props = {},
  2551. // this is not a user-facing function, so the fallback is always generated by
  2552. // the compiler and guaranteed to be a function returning an array
  2553. fallback) {
  2554. let slot = slots[name];
  2555. if ( slot && slot.length > 1) {
  2556. warn(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
  2557. `function. You need to mark this component with $dynamic-slots in the ` +
  2558. `parent template.`);
  2559. slot = () => [];
  2560. }
  2561. // a compiled slot disables block tracking by default to avoid manual
  2562. // invocation interfering with template-based block tracking, but in
  2563. // `renderSlot` we can be sure that it's template-based so we can force
  2564. // enable it.
  2565. isRenderingCompiledSlot++;
  2566. const rendered = (openBlock(),
  2567. createBlock(Fragment, { key: props.key }, slot ? slot(props) : fallback ? fallback() : [], slots._ === 1 /* STABLE */
  2568. ? 64 /* STABLE_FRAGMENT */
  2569. : -2 /* BAIL */));
  2570. isRenderingCompiledSlot--;
  2571. return rendered;
  2572. }
  2573. /**
  2574. * Wrap a slot function to memoize current rendering instance
  2575. * @private
  2576. */
  2577. function withCtx(fn, ctx = currentRenderingInstance) {
  2578. if (!ctx)
  2579. return fn;
  2580. const renderFnWithContext = (...args) => {
  2581. // If a user calls a compiled slot inside a template expression (#1745), it
  2582. // can mess up block tracking, so by default we need to push a null block to
  2583. // avoid that. This isn't necessary if rendering a compiled `<slot>`.
  2584. if (!isRenderingCompiledSlot) {
  2585. openBlock(true /* null block that disables tracking */);
  2586. }
  2587. const owner = currentRenderingInstance;
  2588. setCurrentRenderingInstance(ctx);
  2589. const res = fn(...args);
  2590. setCurrentRenderingInstance(owner);
  2591. if (!isRenderingCompiledSlot) {
  2592. closeBlock();
  2593. }
  2594. return res;
  2595. };
  2596. renderFnWithContext._c = true;
  2597. return renderFnWithContext;
  2598. }
  2599. // SFC scoped style ID management.
  2600. let currentScopeId = null;
  2601. const scopeIdStack = [];
  2602. /**
  2603. * @private
  2604. */
  2605. function pushScopeId(id) {
  2606. scopeIdStack.push((currentScopeId = id));
  2607. }
  2608. /**
  2609. * @private
  2610. */
  2611. function popScopeId() {
  2612. scopeIdStack.pop();
  2613. currentScopeId = scopeIdStack[scopeIdStack.length - 1] || null;
  2614. }
  2615. /**
  2616. * @private
  2617. */
  2618. function withScopeId(id) {
  2619. return ((fn) => withCtx(function () {
  2620. pushScopeId(id);
  2621. const res = fn.apply(this, arguments);
  2622. popScopeId();
  2623. return res;
  2624. }));
  2625. }
  2626. function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
  2627. isSSR = false) {
  2628. const props = {};
  2629. const attrs = {};
  2630. def(attrs, InternalObjectKey, 1);
  2631. setFullProps(instance, rawProps, props, attrs);
  2632. // validation
  2633. {
  2634. validateProps(props, instance);
  2635. }
  2636. if (isStateful) {
  2637. // stateful
  2638. instance.props = isSSR ? props : shallowReactive(props);
  2639. }
  2640. else {
  2641. if (!instance.type.props) {
  2642. // functional w/ optional props, props === attrs
  2643. instance.props = attrs;
  2644. }
  2645. else {
  2646. // functional w/ declared props
  2647. instance.props = props;
  2648. }
  2649. }
  2650. instance.attrs = attrs;
  2651. }
  2652. function updateProps(instance, rawProps, rawPrevProps, optimized) {
  2653. const { props, attrs, vnode: { patchFlag } } = instance;
  2654. const rawCurrentProps = toRaw(props);
  2655. const [options] = instance.propsOptions;
  2656. if (
  2657. // always force full diff in dev
  2658. // - #1942 if hmr is enabled with sfc component
  2659. // - vite#872 non-sfc component used by sfc component
  2660. !(
  2661. (instance.type.__hmrId ||
  2662. (instance.parent && instance.parent.type.__hmrId))) &&
  2663. (optimized || patchFlag > 0) &&
  2664. !(patchFlag & 16 /* FULL_PROPS */)) {
  2665. if (patchFlag & 8 /* PROPS */) {
  2666. // Compiler-generated props & no keys change, just set the updated
  2667. // the props.
  2668. const propsToUpdate = instance.vnode.dynamicProps;
  2669. for (let i = 0; i < propsToUpdate.length; i++) {
  2670. const key = propsToUpdate[i];
  2671. // PROPS flag guarantees rawProps to be non-null
  2672. const value = rawProps[key];
  2673. if (options) {
  2674. // attr / props separation was done on init and will be consistent
  2675. // in this code path, so just check if attrs have it.
  2676. if (hasOwn(attrs, key)) {
  2677. attrs[key] = value;
  2678. }
  2679. else {
  2680. const camelizedKey = camelize(key);
  2681. props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance);
  2682. }
  2683. }
  2684. else {
  2685. attrs[key] = value;
  2686. }
  2687. }
  2688. }
  2689. }
  2690. else {
  2691. // full props update.
  2692. setFullProps(instance, rawProps, props, attrs);
  2693. // in case of dynamic props, check if we need to delete keys from
  2694. // the props object
  2695. let kebabKey;
  2696. for (const key in rawCurrentProps) {
  2697. if (!rawProps ||
  2698. // for camelCase
  2699. (!hasOwn(rawProps, key) &&
  2700. // it's possible the original props was passed in as kebab-case
  2701. // and converted to camelCase (#955)
  2702. ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
  2703. if (options) {
  2704. if (rawPrevProps &&
  2705. // for camelCase
  2706. (rawPrevProps[key] !== undefined ||
  2707. // for kebab-case
  2708. rawPrevProps[kebabKey] !== undefined)) {
  2709. props[key] = resolvePropValue(options, rawProps || EMPTY_OBJ, key, undefined, instance);
  2710. }
  2711. }
  2712. else {
  2713. delete props[key];
  2714. }
  2715. }
  2716. }
  2717. // in the case of functional component w/o props declaration, props and
  2718. // attrs point to the same object so it should already have been updated.
  2719. if (attrs !== rawCurrentProps) {
  2720. for (const key in attrs) {
  2721. if (!rawProps || !hasOwn(rawProps, key)) {
  2722. delete attrs[key];
  2723. }
  2724. }
  2725. }
  2726. }
  2727. // trigger updates for $attrs in case it's used in component slots
  2728. trigger(instance, "set" /* SET */, '$attrs');
  2729. if ( rawProps) {
  2730. validateProps(props, instance);
  2731. }
  2732. }
  2733. function setFullProps(instance, rawProps, props, attrs) {
  2734. const [options, needCastKeys] = instance.propsOptions;
  2735. if (rawProps) {
  2736. for (const key in rawProps) {
  2737. const value = rawProps[key];
  2738. // key, ref are reserved and never passed down
  2739. if (isReservedProp(key)) {
  2740. continue;
  2741. }
  2742. // prop option names are camelized during normalization, so to support
  2743. // kebab -> camel conversion here we need to camelize the key.
  2744. let camelKey;
  2745. if (options && hasOwn(options, (camelKey = camelize(key)))) {
  2746. props[camelKey] = value;
  2747. }
  2748. else if (!isEmitListener(instance.emitsOptions, key)) {
  2749. // Any non-declared (either as a prop or an emitted event) props are put
  2750. // into a separate `attrs` object for spreading. Make sure to preserve
  2751. // original key casing
  2752. attrs[key] = value;
  2753. }
  2754. }
  2755. }
  2756. if (needCastKeys) {
  2757. const rawCurrentProps = toRaw(props);
  2758. for (let i = 0; i < needCastKeys.length; i++) {
  2759. const key = needCastKeys[i];
  2760. props[key] = resolvePropValue(options, rawCurrentProps, key, rawCurrentProps[key], instance);
  2761. }
  2762. }
  2763. }
  2764. function resolvePropValue(options, props, key, value, instance) {
  2765. const opt = options[key];
  2766. if (opt != null) {
  2767. const hasDefault = hasOwn(opt, 'default');
  2768. // default values
  2769. if (hasDefault && value === undefined) {
  2770. const defaultValue = opt.default;
  2771. if (opt.type !== Function && isFunction(defaultValue)) {
  2772. setCurrentInstance(instance);
  2773. value = defaultValue(props);
  2774. setCurrentInstance(null);
  2775. }
  2776. else {
  2777. value = defaultValue;
  2778. }
  2779. }
  2780. // boolean casting
  2781. if (opt[0 /* shouldCast */]) {
  2782. if (!hasOwn(props, key) && !hasDefault) {
  2783. value = false;
  2784. }
  2785. else if (opt[1 /* shouldCastTrue */] &&
  2786. (value === '' || value === hyphenate(key))) {
  2787. value = true;
  2788. }
  2789. }
  2790. }
  2791. return value;
  2792. }
  2793. function normalizePropsOptions(comp, appContext, asMixin = false) {
  2794. if (!appContext.deopt && comp.__props) {
  2795. return comp.__props;
  2796. }
  2797. const raw = comp.props;
  2798. const normalized = {};
  2799. const needCastKeys = [];
  2800. // apply mixin/extends props
  2801. let hasExtends = false;
  2802. if ( !isFunction(comp)) {
  2803. const extendProps = (raw) => {
  2804. hasExtends = true;
  2805. const [props, keys] = normalizePropsOptions(raw, appContext, true);
  2806. extend(normalized, props);
  2807. if (keys)
  2808. needCastKeys.push(...keys);
  2809. };
  2810. if (!asMixin && appContext.mixins.length) {
  2811. appContext.mixins.forEach(extendProps);
  2812. }
  2813. if (comp.extends) {
  2814. extendProps(comp.extends);
  2815. }
  2816. if (comp.mixins) {
  2817. comp.mixins.forEach(extendProps);
  2818. }
  2819. }
  2820. if (!raw && !hasExtends) {
  2821. return (comp.__props = EMPTY_ARR);
  2822. }
  2823. if (isArray(raw)) {
  2824. for (let i = 0; i < raw.length; i++) {
  2825. if ( !isString(raw[i])) {
  2826. warn(`props must be strings when using array syntax.`, raw[i]);
  2827. }
  2828. const normalizedKey = camelize(raw[i]);
  2829. if (validatePropName(normalizedKey)) {
  2830. normalized[normalizedKey] = EMPTY_OBJ;
  2831. }
  2832. }
  2833. }
  2834. else if (raw) {
  2835. if ( !isObject(raw)) {
  2836. warn(`invalid props options`, raw);
  2837. }
  2838. for (const key in raw) {
  2839. const normalizedKey = camelize(key);
  2840. if (validatePropName(normalizedKey)) {
  2841. const opt = raw[key];
  2842. const prop = (normalized[normalizedKey] =
  2843. isArray(opt) || isFunction(opt) ? { type: opt } : opt);
  2844. if (prop) {
  2845. const booleanIndex = getTypeIndex(Boolean, prop.type);
  2846. const stringIndex = getTypeIndex(String, prop.type);
  2847. prop[0 /* shouldCast */] = booleanIndex > -1;
  2848. prop[1 /* shouldCastTrue */] =
  2849. stringIndex < 0 || booleanIndex < stringIndex;
  2850. // if the prop needs boolean casting or default value
  2851. if (booleanIndex > -1 || hasOwn(prop, 'default')) {
  2852. needCastKeys.push(normalizedKey);
  2853. }
  2854. }
  2855. }
  2856. }
  2857. }
  2858. return (comp.__props = [normalized, needCastKeys]);
  2859. }
  2860. function validatePropName(key) {
  2861. if (key[0] !== '$') {
  2862. return true;
  2863. }
  2864. else {
  2865. warn(`Invalid prop name: "${key}" is a reserved property.`);
  2866. }
  2867. return false;
  2868. }
  2869. // use function string name to check type constructors
  2870. // so that it works across vms / iframes.
  2871. function getType(ctor) {
  2872. const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  2873. return match ? match[1] : '';
  2874. }
  2875. function isSameType(a, b) {
  2876. return getType(a) === getType(b);
  2877. }
  2878. function getTypeIndex(type, expectedTypes) {
  2879. if (isArray(expectedTypes)) {
  2880. for (let i = 0, len = expectedTypes.length; i < len; i++) {
  2881. if (isSameType(expectedTypes[i], type)) {
  2882. return i;
  2883. }
  2884. }
  2885. }
  2886. else if (isFunction(expectedTypes)) {
  2887. return isSameType(expectedTypes, type) ? 0 : -1;
  2888. }
  2889. return -1;
  2890. }
  2891. /**
  2892. * dev only
  2893. */
  2894. function validateProps(props, instance) {
  2895. const rawValues = toRaw(props);
  2896. const options = instance.propsOptions[0];
  2897. for (const key in options) {
  2898. let opt = options[key];
  2899. if (opt == null)
  2900. continue;
  2901. validateProp(key, rawValues[key], opt, !hasOwn(rawValues, key));
  2902. }
  2903. }
  2904. /**
  2905. * dev only
  2906. */
  2907. function validateProp(name, value, prop, isAbsent) {
  2908. const { type, required, validator } = prop;
  2909. // required!
  2910. if (required && isAbsent) {
  2911. warn('Missing required prop: "' + name + '"');
  2912. return;
  2913. }
  2914. // missing but optional
  2915. if (value == null && !prop.required) {
  2916. return;
  2917. }
  2918. // type check
  2919. if (type != null && type !== true) {
  2920. let isValid = false;
  2921. const types = isArray(type) ? type : [type];
  2922. const expectedTypes = [];
  2923. // value is valid as long as one of the specified types match
  2924. for (let i = 0; i < types.length && !isValid; i++) {
  2925. const { valid, expectedType } = assertType(value, types[i]);
  2926. expectedTypes.push(expectedType || '');
  2927. isValid = valid;
  2928. }
  2929. if (!isValid) {
  2930. warn(getInvalidTypeMessage(name, value, expectedTypes));
  2931. return;
  2932. }
  2933. }
  2934. // custom validator
  2935. if (validator && !validator(value)) {
  2936. warn('Invalid prop: custom validator check failed for prop "' + name + '".');
  2937. }
  2938. }
  2939. const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');
  2940. /**
  2941. * dev only
  2942. */
  2943. function assertType(value, type) {
  2944. let valid;
  2945. const expectedType = getType(type);
  2946. if (isSimpleType(expectedType)) {
  2947. const t = typeof value;
  2948. valid = t === expectedType.toLowerCase();
  2949. // for primitive wrapper objects
  2950. if (!valid && t === 'object') {
  2951. valid = value instanceof type;
  2952. }
  2953. }
  2954. else if (expectedType === 'Object') {
  2955. valid = isObject(value);
  2956. }
  2957. else if (expectedType === 'Array') {
  2958. valid = isArray(value);
  2959. }
  2960. else {
  2961. valid = value instanceof type;
  2962. }
  2963. return {
  2964. valid,
  2965. expectedType
  2966. };
  2967. }
  2968. /**
  2969. * dev only
  2970. */
  2971. function getInvalidTypeMessage(name, value, expectedTypes) {
  2972. let message = `Invalid prop: type check failed for prop "${name}".` +
  2973. ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
  2974. const expectedType = expectedTypes[0];
  2975. const receivedType = toRawType(value);
  2976. const expectedValue = styleValue(value, expectedType);
  2977. const receivedValue = styleValue(value, receivedType);
  2978. // check if we need to specify expected value
  2979. if (expectedTypes.length === 1 &&
  2980. isExplicable(expectedType) &&
  2981. !isBoolean(expectedType, receivedType)) {
  2982. message += ` with value ${expectedValue}`;
  2983. }
  2984. message += `, got ${receivedType} `;
  2985. // check if we need to specify received value
  2986. if (isExplicable(receivedType)) {
  2987. message += `with value ${receivedValue}.`;
  2988. }
  2989. return message;
  2990. }
  2991. /**
  2992. * dev only
  2993. */
  2994. function styleValue(value, type) {
  2995. if (type === 'String') {
  2996. return `"${value}"`;
  2997. }
  2998. else if (type === 'Number') {
  2999. return `${Number(value)}`;
  3000. }
  3001. else {
  3002. return `${value}`;
  3003. }
  3004. }
  3005. /**
  3006. * dev only
  3007. */
  3008. function isExplicable(type) {
  3009. const explicitTypes = ['string', 'number', 'boolean'];
  3010. return explicitTypes.some(elem => type.toLowerCase() === elem);
  3011. }
  3012. /**
  3013. * dev only
  3014. */
  3015. function isBoolean(...args) {
  3016. return args.some(elem => elem.toLowerCase() === 'boolean');
  3017. }
  3018. function injectHook(type, hook, target = currentInstance, prepend = false) {
  3019. if (target) {
  3020. const hooks = target[type] || (target[type] = []);
  3021. // cache the error handling wrapper for injected hooks so the same hook
  3022. // can be properly deduped by the scheduler. "__weh" stands for "with error
  3023. // handling".
  3024. const wrappedHook = hook.__weh ||
  3025. (hook.__weh = (...args) => {
  3026. if (target.isUnmounted) {
  3027. return;
  3028. }
  3029. // disable tracking inside all lifecycle hooks
  3030. // since they can potentially be called inside effects.
  3031. pauseTracking();
  3032. // Set currentInstance during hook invocation.
  3033. // This assumes the hook does not synchronously trigger other hooks, which
  3034. // can only be false when the user does something really funky.
  3035. setCurrentInstance(target);
  3036. const res = callWithAsyncErrorHandling(hook, target, type, args);
  3037. setCurrentInstance(null);
  3038. resetTracking();
  3039. return res;
  3040. });
  3041. if (prepend) {
  3042. hooks.unshift(wrappedHook);
  3043. }
  3044. else {
  3045. hooks.push(wrappedHook);
  3046. }
  3047. return wrappedHook;
  3048. }
  3049. else {
  3050. const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
  3051. warn(`${apiName} is called when there is no active component instance to be ` +
  3052. `associated with. ` +
  3053. `Lifecycle injection APIs can only be used during execution of setup().` +
  3054. ( ` If you are using async setup(), make sure to register lifecycle ` +
  3055. `hooks before the first await statement.`
  3056. ));
  3057. }
  3058. }
  3059. const createHook = (lifecycle) => (hook, target = currentInstance) =>
  3060. // post-create lifecycle registrations are noops during SSR
  3061. !isInSSRComponentSetup && injectHook(lifecycle, hook, target);
  3062. const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
  3063. const onMounted = createHook("m" /* MOUNTED */);
  3064. const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
  3065. const onUpdated = createHook("u" /* UPDATED */);
  3066. const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
  3067. const onUnmounted = createHook("um" /* UNMOUNTED */);
  3068. const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
  3069. const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
  3070. const onErrorCaptured = (hook, target = currentInstance) => {
  3071. injectHook("ec" /* ERROR_CAPTURED */, hook, target);
  3072. };
  3073. // Simple effect.
  3074. function watchEffect(effect, options) {
  3075. return doWatch(effect, null, options);
  3076. }
  3077. // initial value for watchers to trigger on undefined initial values
  3078. const INITIAL_WATCHER_VALUE = {};
  3079. // implementation
  3080. function watch(source, cb, options) {
  3081. if ( !isFunction(cb)) {
  3082. warn(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
  3083. `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
  3084. `supports \`watch(source, cb, options?) signature.`);
  3085. }
  3086. return doWatch(source, cb, options);
  3087. }
  3088. function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ, instance = currentInstance) {
  3089. if ( !cb) {
  3090. if (immediate !== undefined) {
  3091. warn(`watch() "immediate" option is only respected when using the ` +
  3092. `watch(source, callback, options?) signature.`);
  3093. }
  3094. if (deep !== undefined) {
  3095. warn(`watch() "deep" option is only respected when using the ` +
  3096. `watch(source, callback, options?) signature.`);
  3097. }
  3098. }
  3099. const warnInvalidSource = (s) => {
  3100. warn(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
  3101. `a reactive object, or an array of these types.`);
  3102. };
  3103. let getter;
  3104. let forceTrigger = false;
  3105. if (isRef(source)) {
  3106. getter = () => source.value;
  3107. forceTrigger = !!source._shallow;
  3108. }
  3109. else if (isReactive(source)) {
  3110. getter = () => source;
  3111. deep = true;
  3112. }
  3113. else if (isArray(source)) {
  3114. getter = () => source.map(s => {
  3115. if (isRef(s)) {
  3116. return s.value;
  3117. }
  3118. else if (isReactive(s)) {
  3119. return traverse(s);
  3120. }
  3121. else if (isFunction(s)) {
  3122. return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
  3123. }
  3124. else {
  3125. warnInvalidSource(s);
  3126. }
  3127. });
  3128. }
  3129. else if (isFunction(source)) {
  3130. if (cb) {
  3131. // getter with cb
  3132. getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
  3133. }
  3134. else {
  3135. // no cb -> simple effect
  3136. getter = () => {
  3137. if (instance && instance.isUnmounted) {
  3138. return;
  3139. }
  3140. if (cleanup) {
  3141. cleanup();
  3142. }
  3143. return callWithErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
  3144. };
  3145. }
  3146. }
  3147. else {
  3148. getter = NOOP;
  3149. warnInvalidSource(source);
  3150. }
  3151. if (cb && deep) {
  3152. const baseGetter = getter;
  3153. getter = () => traverse(baseGetter());
  3154. }
  3155. let cleanup;
  3156. const onInvalidate = (fn) => {
  3157. cleanup = runner.options.onStop = () => {
  3158. callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
  3159. };
  3160. };
  3161. let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE;
  3162. const job = () => {
  3163. if (!runner.active) {
  3164. return;
  3165. }
  3166. if (cb) {
  3167. // watch(source, cb)
  3168. const newValue = runner();
  3169. if (deep || forceTrigger || hasChanged(newValue, oldValue)) {
  3170. // cleanup before running cb again
  3171. if (cleanup) {
  3172. cleanup();
  3173. }
  3174. callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
  3175. newValue,
  3176. // pass undefined as the old value when it's changed for the first time
  3177. oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
  3178. onInvalidate
  3179. ]);
  3180. oldValue = newValue;
  3181. }
  3182. }
  3183. else {
  3184. // watchEffect
  3185. runner();
  3186. }
  3187. };
  3188. // important: mark the job as a watcher callback so that scheduler knows
  3189. // it is allowed to self-trigger (#1727)
  3190. job.allowRecurse = !!cb;
  3191. let scheduler;
  3192. if (flush === 'sync') {
  3193. scheduler = job;
  3194. }
  3195. else if (flush === 'post') {
  3196. scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
  3197. }
  3198. else {
  3199. // default: 'pre'
  3200. scheduler = () => {
  3201. if (!instance || instance.isMounted) {
  3202. queuePreFlushCb(job);
  3203. }
  3204. else {
  3205. // with 'pre' option, the first call must happen before
  3206. // the component is mounted so it is called synchronously.
  3207. job();
  3208. }
  3209. };
  3210. }
  3211. const runner = effect(getter, {
  3212. lazy: true,
  3213. onTrack,
  3214. onTrigger,
  3215. scheduler
  3216. });
  3217. recordInstanceBoundEffect(runner);
  3218. // initial run
  3219. if (cb) {
  3220. if (immediate) {
  3221. job();
  3222. }
  3223. else {
  3224. oldValue = runner();
  3225. }
  3226. }
  3227. else if (flush === 'post') {
  3228. queuePostRenderEffect(runner, instance && instance.suspense);
  3229. }
  3230. else {
  3231. runner();
  3232. }
  3233. return () => {
  3234. stop(runner);
  3235. if (instance) {
  3236. remove(instance.effects, runner);
  3237. }
  3238. };
  3239. }
  3240. // this.$watch
  3241. function instanceWatch(source, cb, options) {
  3242. const publicThis = this.proxy;
  3243. const getter = isString(source)
  3244. ? () => publicThis[source]
  3245. : source.bind(publicThis);
  3246. return doWatch(getter, cb.bind(publicThis), options, this);
  3247. }
  3248. function traverse(value, seen = new Set()) {
  3249. if (!isObject(value) || seen.has(value)) {
  3250. return value;
  3251. }
  3252. seen.add(value);
  3253. if (isRef(value)) {
  3254. traverse(value.value, seen);
  3255. }
  3256. else if (isArray(value)) {
  3257. for (let i = 0; i < value.length; i++) {
  3258. traverse(value[i], seen);
  3259. }
  3260. }
  3261. else if (isSet(value) || isMap(value)) {
  3262. value.forEach((v) => {
  3263. traverse(v, seen);
  3264. });
  3265. }
  3266. else {
  3267. for (const key in value) {
  3268. traverse(value[key], seen);
  3269. }
  3270. }
  3271. return value;
  3272. }
  3273. function useTransitionState() {
  3274. const state = {
  3275. isMounted: false,
  3276. isLeaving: false,
  3277. isUnmounting: false,
  3278. leavingVNodes: new Map()
  3279. };
  3280. onMounted(() => {
  3281. state.isMounted = true;
  3282. });
  3283. onBeforeUnmount(() => {
  3284. state.isUnmounting = true;
  3285. });
  3286. return state;
  3287. }
  3288. const TransitionHookValidator = [Function, Array];
  3289. const BaseTransitionImpl = {
  3290. name: `BaseTransition`,
  3291. props: {
  3292. mode: String,
  3293. appear: Boolean,
  3294. persisted: Boolean,
  3295. // enter
  3296. onBeforeEnter: TransitionHookValidator,
  3297. onEnter: TransitionHookValidator,
  3298. onAfterEnter: TransitionHookValidator,
  3299. onEnterCancelled: TransitionHookValidator,
  3300. // leave
  3301. onBeforeLeave: TransitionHookValidator,
  3302. onLeave: TransitionHookValidator,
  3303. onAfterLeave: TransitionHookValidator,
  3304. onLeaveCancelled: TransitionHookValidator,
  3305. // appear
  3306. onBeforeAppear: TransitionHookValidator,
  3307. onAppear: TransitionHookValidator,
  3308. onAfterAppear: TransitionHookValidator,
  3309. onAppearCancelled: TransitionHookValidator
  3310. },
  3311. setup(props, { slots }) {
  3312. const instance = getCurrentInstance();
  3313. const state = useTransitionState();
  3314. let prevTransitionKey;
  3315. return () => {
  3316. const children = slots.default && getTransitionRawChildren(slots.default(), true);
  3317. if (!children || !children.length) {
  3318. return;
  3319. }
  3320. // warn multiple elements
  3321. if ( children.length > 1) {
  3322. warn('<transition> can only be used on a single element or component. Use ' +
  3323. '<transition-group> for lists.');
  3324. }
  3325. // there's no need to track reactivity for these props so use the raw
  3326. // props for a bit better perf
  3327. const rawProps = toRaw(props);
  3328. const { mode } = rawProps;
  3329. // check mode
  3330. if ( mode && !['in-out', 'out-in', 'default'].includes(mode)) {
  3331. warn(`invalid <transition> mode: ${mode}`);
  3332. }
  3333. // at this point children has a guaranteed length of 1.
  3334. const child = children[0];
  3335. if (state.isLeaving) {
  3336. return emptyPlaceholder(child);
  3337. }
  3338. // in the case of <transition><keep-alive/></transition>, we need to
  3339. // compare the type of the kept-alive children.
  3340. const innerChild = getKeepAliveChild(child);
  3341. if (!innerChild) {
  3342. return emptyPlaceholder(child);
  3343. }
  3344. const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
  3345. setTransitionHooks(innerChild, enterHooks);
  3346. const oldChild = instance.subTree;
  3347. const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
  3348. let transitionKeyChanged = false;
  3349. const { getTransitionKey } = innerChild.type;
  3350. if (getTransitionKey) {
  3351. const key = getTransitionKey();
  3352. if (prevTransitionKey === undefined) {
  3353. prevTransitionKey = key;
  3354. }
  3355. else if (key !== prevTransitionKey) {
  3356. prevTransitionKey = key;
  3357. transitionKeyChanged = true;
  3358. }
  3359. }
  3360. // handle mode
  3361. if (oldInnerChild &&
  3362. oldInnerChild.type !== Comment &&
  3363. (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
  3364. const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
  3365. // update old tree's hooks in case of dynamic transition
  3366. setTransitionHooks(oldInnerChild, leavingHooks);
  3367. // switching between different views
  3368. if (mode === 'out-in') {
  3369. state.isLeaving = true;
  3370. // return placeholder node and queue update when leave finishes
  3371. leavingHooks.afterLeave = () => {
  3372. state.isLeaving = false;
  3373. instance.update();
  3374. };
  3375. return emptyPlaceholder(child);
  3376. }
  3377. else if (mode === 'in-out') {
  3378. leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
  3379. const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
  3380. leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
  3381. // early removal callback
  3382. el._leaveCb = () => {
  3383. earlyRemove();
  3384. el._leaveCb = undefined;
  3385. delete enterHooks.delayedLeave;
  3386. };
  3387. enterHooks.delayedLeave = delayedLeave;
  3388. };
  3389. }
  3390. }
  3391. return child;
  3392. };
  3393. }
  3394. };
  3395. // export the public type for h/tsx inference
  3396. // also to avoid inline import() in generated d.ts files
  3397. const BaseTransition = BaseTransitionImpl;
  3398. function getLeavingNodesForType(state, vnode) {
  3399. const { leavingVNodes } = state;
  3400. let leavingVNodesCache = leavingVNodes.get(vnode.type);
  3401. if (!leavingVNodesCache) {
  3402. leavingVNodesCache = Object.create(null);
  3403. leavingVNodes.set(vnode.type, leavingVNodesCache);
  3404. }
  3405. return leavingVNodesCache;
  3406. }
  3407. // The transition hooks are attached to the vnode as vnode.transition
  3408. // and will be called at appropriate timing in the renderer.
  3409. function resolveTransitionHooks(vnode, props, state, instance) {
  3410. const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
  3411. const key = String(vnode.key);
  3412. const leavingVNodesCache = getLeavingNodesForType(state, vnode);
  3413. const callHook = (hook, args) => {
  3414. hook &&
  3415. callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
  3416. };
  3417. const hooks = {
  3418. mode,
  3419. persisted,
  3420. beforeEnter(el) {
  3421. let hook = onBeforeEnter;
  3422. if (!state.isMounted) {
  3423. if (appear) {
  3424. hook = onBeforeAppear || onBeforeEnter;
  3425. }
  3426. else {
  3427. return;
  3428. }
  3429. }
  3430. // for same element (v-show)
  3431. if (el._leaveCb) {
  3432. el._leaveCb(true /* cancelled */);
  3433. }
  3434. // for toggled element with same key (v-if)
  3435. const leavingVNode = leavingVNodesCache[key];
  3436. if (leavingVNode &&
  3437. isSameVNodeType(vnode, leavingVNode) &&
  3438. leavingVNode.el._leaveCb) {
  3439. // force early removal (not cancelled)
  3440. leavingVNode.el._leaveCb();
  3441. }
  3442. callHook(hook, [el]);
  3443. },
  3444. enter(el) {
  3445. let hook = onEnter;
  3446. let afterHook = onAfterEnter;
  3447. let cancelHook = onEnterCancelled;
  3448. if (!state.isMounted) {
  3449. if (appear) {
  3450. hook = onAppear || onEnter;
  3451. afterHook = onAfterAppear || onAfterEnter;
  3452. cancelHook = onAppearCancelled || onEnterCancelled;
  3453. }
  3454. else {
  3455. return;
  3456. }
  3457. }
  3458. let called = false;
  3459. const done = (el._enterCb = (cancelled) => {
  3460. if (called)
  3461. return;
  3462. called = true;
  3463. if (cancelled) {
  3464. callHook(cancelHook, [el]);
  3465. }
  3466. else {
  3467. callHook(afterHook, [el]);
  3468. }
  3469. if (hooks.delayedLeave) {
  3470. hooks.delayedLeave();
  3471. }
  3472. el._enterCb = undefined;
  3473. });
  3474. if (hook) {
  3475. hook(el, done);
  3476. if (hook.length <= 1) {
  3477. done();
  3478. }
  3479. }
  3480. else {
  3481. done();
  3482. }
  3483. },
  3484. leave(el, remove) {
  3485. const key = String(vnode.key);
  3486. if (el._enterCb) {
  3487. el._enterCb(true /* cancelled */);
  3488. }
  3489. if (state.isUnmounting) {
  3490. return remove();
  3491. }
  3492. callHook(onBeforeLeave, [el]);
  3493. let called = false;
  3494. const done = (el._leaveCb = (cancelled) => {
  3495. if (called)
  3496. return;
  3497. called = true;
  3498. remove();
  3499. if (cancelled) {
  3500. callHook(onLeaveCancelled, [el]);
  3501. }
  3502. else {
  3503. callHook(onAfterLeave, [el]);
  3504. }
  3505. el._leaveCb = undefined;
  3506. if (leavingVNodesCache[key] === vnode) {
  3507. delete leavingVNodesCache[key];
  3508. }
  3509. });
  3510. leavingVNodesCache[key] = vnode;
  3511. if (onLeave) {
  3512. onLeave(el, done);
  3513. if (onLeave.length <= 1) {
  3514. done();
  3515. }
  3516. }
  3517. else {
  3518. done();
  3519. }
  3520. },
  3521. clone(vnode) {
  3522. return resolveTransitionHooks(vnode, props, state, instance);
  3523. }
  3524. };
  3525. return hooks;
  3526. }
  3527. // the placeholder really only handles one special case: KeepAlive
  3528. // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
  3529. // placeholder with empty content to avoid the KeepAlive instance from being
  3530. // unmounted.
  3531. function emptyPlaceholder(vnode) {
  3532. if (isKeepAlive(vnode)) {
  3533. vnode = cloneVNode(vnode);
  3534. vnode.children = null;
  3535. return vnode;
  3536. }
  3537. }
  3538. function getKeepAliveChild(vnode) {
  3539. return isKeepAlive(vnode)
  3540. ? vnode.children
  3541. ? vnode.children[0]
  3542. : undefined
  3543. : vnode;
  3544. }
  3545. function setTransitionHooks(vnode, hooks) {
  3546. if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
  3547. setTransitionHooks(vnode.component.subTree, hooks);
  3548. }
  3549. else if ( vnode.shapeFlag & 128 /* SUSPENSE */) {
  3550. vnode.ssContent.transition = hooks.clone(vnode.ssContent);
  3551. vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
  3552. }
  3553. else {
  3554. vnode.transition = hooks;
  3555. }
  3556. }
  3557. function getTransitionRawChildren(children, keepComment = false) {
  3558. let ret = [];
  3559. let keyedFragmentCount = 0;
  3560. for (let i = 0; i < children.length; i++) {
  3561. const child = children[i];
  3562. // handle fragment children case, e.g. v-for
  3563. if (child.type === Fragment) {
  3564. if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
  3565. keyedFragmentCount++;
  3566. ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
  3567. }
  3568. // comment placeholders should be skipped, e.g. v-if
  3569. else if (keepComment || child.type !== Comment) {
  3570. ret.push(child);
  3571. }
  3572. }
  3573. // #1126 if a transition children list contains multiple sub fragments, these
  3574. // fragments will be merged into a flat children array. Since each v-for
  3575. // fragment may contain different static bindings inside, we need to de-top
  3576. // these children to force full diffs to ensure correct behavior.
  3577. if (keyedFragmentCount > 1) {
  3578. for (let i = 0; i < ret.length; i++) {
  3579. ret[i].patchFlag = -2 /* BAIL */;
  3580. }
  3581. }
  3582. return ret;
  3583. }
  3584. const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
  3585. const KeepAliveImpl = {
  3586. name: `KeepAlive`,
  3587. // Marker for special handling inside the renderer. We are not using a ===
  3588. // check directly on KeepAlive in the renderer, because importing it directly
  3589. // would prevent it from being tree-shaken.
  3590. __isKeepAlive: true,
  3591. inheritRef: true,
  3592. props: {
  3593. include: [String, RegExp, Array],
  3594. exclude: [String, RegExp, Array],
  3595. max: [String, Number]
  3596. },
  3597. setup(props, { slots }) {
  3598. const cache = new Map();
  3599. const keys = new Set();
  3600. let current = null;
  3601. const instance = getCurrentInstance();
  3602. const parentSuspense = instance.suspense;
  3603. // KeepAlive communicates with the instantiated renderer via the
  3604. // ctx where the renderer passes in its internals,
  3605. // and the KeepAlive instance exposes activate/deactivate implementations.
  3606. // The whole point of this is to avoid importing KeepAlive directly in the
  3607. // renderer to facilitate tree-shaking.
  3608. const sharedContext = instance.ctx;
  3609. const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
  3610. const storageContainer = createElement('div');
  3611. sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
  3612. const instance = vnode.component;
  3613. move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
  3614. // in case props have changed
  3615. patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, optimized);
  3616. queuePostRenderEffect(() => {
  3617. instance.isDeactivated = false;
  3618. if (instance.a) {
  3619. invokeArrayFns(instance.a);
  3620. }
  3621. const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
  3622. if (vnodeHook) {
  3623. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3624. }
  3625. }, parentSuspense);
  3626. };
  3627. sharedContext.deactivate = (vnode) => {
  3628. const instance = vnode.component;
  3629. move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
  3630. queuePostRenderEffect(() => {
  3631. if (instance.da) {
  3632. invokeArrayFns(instance.da);
  3633. }
  3634. const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
  3635. if (vnodeHook) {
  3636. invokeVNodeHook(vnodeHook, instance.parent, vnode);
  3637. }
  3638. instance.isDeactivated = true;
  3639. }, parentSuspense);
  3640. };
  3641. function unmount(vnode) {
  3642. // reset the shapeFlag so it can be properly unmounted
  3643. resetShapeFlag(vnode);
  3644. _unmount(vnode, instance, parentSuspense);
  3645. }
  3646. function pruneCache(filter) {
  3647. cache.forEach((vnode, key) => {
  3648. const name = getName(vnode.type);
  3649. if (name && (!filter || !filter(name))) {
  3650. pruneCacheEntry(key);
  3651. }
  3652. });
  3653. }
  3654. function pruneCacheEntry(key) {
  3655. const cached = cache.get(key);
  3656. if (!current || cached.type !== current.type) {
  3657. unmount(cached);
  3658. }
  3659. else if (current) {
  3660. // current active instance should no longer be kept-alive.
  3661. // we can't unmount it now but it might be later, so reset its flag now.
  3662. resetShapeFlag(current);
  3663. }
  3664. cache.delete(key);
  3665. keys.delete(key);
  3666. }
  3667. // prune cache on include/exclude prop change
  3668. watch(() => [props.include, props.exclude], ([include, exclude]) => {
  3669. include && pruneCache(name => matches(include, name));
  3670. exclude && pruneCache(name => !matches(exclude, name));
  3671. },
  3672. // prune post-render after `current` has been updated
  3673. { flush: 'post' });
  3674. // cache sub tree after render
  3675. let pendingCacheKey = null;
  3676. const cacheSubtree = () => {
  3677. // fix #1621, the pendingCacheKey could be 0
  3678. if (pendingCacheKey != null) {
  3679. cache.set(pendingCacheKey, getInnerChild(instance.subTree));
  3680. }
  3681. };
  3682. onMounted(cacheSubtree);
  3683. onUpdated(cacheSubtree);
  3684. onBeforeUnmount(() => {
  3685. cache.forEach(cached => {
  3686. const { subTree, suspense } = instance;
  3687. const vnode = getInnerChild(subTree);
  3688. if (cached.type === vnode.type) {
  3689. // current instance will be unmounted as part of keep-alive's unmount
  3690. resetShapeFlag(vnode);
  3691. // but invoke its deactivated hook here
  3692. const da = vnode.component.da;
  3693. da && queuePostRenderEffect(da, suspense);
  3694. return;
  3695. }
  3696. unmount(cached);
  3697. });
  3698. });
  3699. return () => {
  3700. pendingCacheKey = null;
  3701. if (!slots.default) {
  3702. return null;
  3703. }
  3704. const children = slots.default();
  3705. const rawVNode = children[0];
  3706. if (children.length > 1) {
  3707. {
  3708. warn(`KeepAlive should contain exactly one component child.`);
  3709. }
  3710. current = null;
  3711. return children;
  3712. }
  3713. else if (!isVNode(rawVNode) ||
  3714. (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
  3715. !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
  3716. current = null;
  3717. return rawVNode;
  3718. }
  3719. let vnode = getInnerChild(rawVNode);
  3720. const comp = vnode.type;
  3721. const name = getName(comp);
  3722. const { include, exclude, max } = props;
  3723. if ((include && (!name || !matches(include, name))) ||
  3724. (exclude && name && matches(exclude, name))) {
  3725. current = vnode;
  3726. return rawVNode;
  3727. }
  3728. const key = vnode.key == null ? comp : vnode.key;
  3729. const cachedVNode = cache.get(key);
  3730. // clone vnode if it's reused because we are going to mutate it
  3731. if (vnode.el) {
  3732. vnode = cloneVNode(vnode);
  3733. if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
  3734. rawVNode.ssContent = vnode;
  3735. }
  3736. }
  3737. // #1513 it's possible for the returned vnode to be cloned due to attr
  3738. // fallthrough or scopeId, so the vnode here may not be the final vnode
  3739. // that is mounted. Instead of caching it directly, we store the pending
  3740. // key and cache `instance.subTree` (the normalized vnode) in
  3741. // beforeMount/beforeUpdate hooks.
  3742. pendingCacheKey = key;
  3743. if (cachedVNode) {
  3744. // copy over mounted state
  3745. vnode.el = cachedVNode.el;
  3746. vnode.component = cachedVNode.component;
  3747. if (vnode.transition) {
  3748. // recursively update transition hooks on subTree
  3749. setTransitionHooks(vnode, vnode.transition);
  3750. }
  3751. // avoid vnode being mounted as fresh
  3752. vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
  3753. // make this key the freshest
  3754. keys.delete(key);
  3755. keys.add(key);
  3756. }
  3757. else {
  3758. keys.add(key);
  3759. // prune oldest entry
  3760. if (max && keys.size > parseInt(max, 10)) {
  3761. pruneCacheEntry(keys.values().next().value);
  3762. }
  3763. }
  3764. // avoid vnode being unmounted
  3765. vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  3766. current = vnode;
  3767. return rawVNode;
  3768. };
  3769. }
  3770. };
  3771. // export the public type for h/tsx inference
  3772. // also to avoid inline import() in generated d.ts files
  3773. const KeepAlive = KeepAliveImpl;
  3774. function getName(comp) {
  3775. return comp.displayName || comp.name;
  3776. }
  3777. function matches(pattern, name) {
  3778. if (isArray(pattern)) {
  3779. return pattern.some((p) => matches(p, name));
  3780. }
  3781. else if (isString(pattern)) {
  3782. return pattern.split(',').indexOf(name) > -1;
  3783. }
  3784. else if (pattern.test) {
  3785. return pattern.test(name);
  3786. }
  3787. /* istanbul ignore next */
  3788. return false;
  3789. }
  3790. function onActivated(hook, target) {
  3791. registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
  3792. }
  3793. function onDeactivated(hook, target) {
  3794. registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
  3795. }
  3796. function registerKeepAliveHook(hook, type, target = currentInstance) {
  3797. // cache the deactivate branch check wrapper for injected hooks so the same
  3798. // hook can be properly deduped by the scheduler. "__wdc" stands for "with
  3799. // deactivation check".
  3800. const wrappedHook = hook.__wdc ||
  3801. (hook.__wdc = () => {
  3802. // only fire the hook if the target instance is NOT in a deactivated branch.
  3803. let current = target;
  3804. while (current) {
  3805. if (current.isDeactivated) {
  3806. return;
  3807. }
  3808. current = current.parent;
  3809. }
  3810. hook();
  3811. });
  3812. injectHook(type, wrappedHook, target);
  3813. // In addition to registering it on the target instance, we walk up the parent
  3814. // chain and register it on all ancestor instances that are keep-alive roots.
  3815. // This avoids the need to walk the entire component tree when invoking these
  3816. // hooks, and more importantly, avoids the need to track child components in
  3817. // arrays.
  3818. if (target) {
  3819. let current = target.parent;
  3820. while (current && current.parent) {
  3821. if (isKeepAlive(current.parent.vnode)) {
  3822. injectToKeepAliveRoot(wrappedHook, type, target, current);
  3823. }
  3824. current = current.parent;
  3825. }
  3826. }
  3827. }
  3828. function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
  3829. // injectHook wraps the original for error handling, so make sure to remove
  3830. // the wrapped version.
  3831. const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
  3832. onUnmounted(() => {
  3833. remove(keepAliveRoot[type], injected);
  3834. }, target);
  3835. }
  3836. function resetShapeFlag(vnode) {
  3837. let shapeFlag = vnode.shapeFlag;
  3838. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  3839. shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
  3840. }
  3841. if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  3842. shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
  3843. }
  3844. vnode.shapeFlag = shapeFlag;
  3845. }
  3846. function getInnerChild(vnode) {
  3847. return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
  3848. }
  3849. const isInternalKey = (key) => key[0] === '_' || key === '$stable';
  3850. const normalizeSlotValue = (value) => isArray(value)
  3851. ? value.map(normalizeVNode)
  3852. : [normalizeVNode(value)];
  3853. const normalizeSlot = (key, rawSlot, ctx) => withCtx((props) => {
  3854. if ( currentInstance) {
  3855. warn(`Slot "${key}" invoked outside of the render function: ` +
  3856. `this will not track dependencies used in the slot. ` +
  3857. `Invoke the slot function inside the render function instead.`);
  3858. }
  3859. return normalizeSlotValue(rawSlot(props));
  3860. }, ctx);
  3861. const normalizeObjectSlots = (rawSlots, slots) => {
  3862. const ctx = rawSlots._ctx;
  3863. for (const key in rawSlots) {
  3864. if (isInternalKey(key))
  3865. continue;
  3866. const value = rawSlots[key];
  3867. if (isFunction(value)) {
  3868. slots[key] = normalizeSlot(key, value, ctx);
  3869. }
  3870. else if (value != null) {
  3871. {
  3872. warn(`Non-function value encountered for slot "${key}". ` +
  3873. `Prefer function slots for better performance.`);
  3874. }
  3875. const normalized = normalizeSlotValue(value);
  3876. slots[key] = () => normalized;
  3877. }
  3878. }
  3879. };
  3880. const normalizeVNodeSlots = (instance, children) => {
  3881. if ( !isKeepAlive(instance.vnode)) {
  3882. warn(`Non-function value encountered for default slot. ` +
  3883. `Prefer function slots for better performance.`);
  3884. }
  3885. const normalized = normalizeSlotValue(children);
  3886. instance.slots.default = () => normalized;
  3887. };
  3888. const initSlots = (instance, children) => {
  3889. if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  3890. const type = children._;
  3891. if (type) {
  3892. instance.slots = children;
  3893. // make compiler marker non-enumerable
  3894. def(children, '_', type);
  3895. }
  3896. else {
  3897. normalizeObjectSlots(children, (instance.slots = {}));
  3898. }
  3899. }
  3900. else {
  3901. instance.slots = {};
  3902. if (children) {
  3903. normalizeVNodeSlots(instance, children);
  3904. }
  3905. }
  3906. def(instance.slots, InternalObjectKey, 1);
  3907. };
  3908. const updateSlots = (instance, children) => {
  3909. const { vnode, slots } = instance;
  3910. let needDeletionCheck = true;
  3911. let deletionComparisonTarget = EMPTY_OBJ;
  3912. if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
  3913. const type = children._;
  3914. if (type) {
  3915. // compiled slots.
  3916. if ( isHmrUpdating) {
  3917. // Parent was HMR updated so slot content may have changed.
  3918. // force update slots and mark instance for hmr as well
  3919. extend(slots, children);
  3920. }
  3921. else if (type === 1 /* STABLE */) {
  3922. // compiled AND stable.
  3923. // no need to update, and skip stale slots removal.
  3924. needDeletionCheck = false;
  3925. }
  3926. else {
  3927. // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
  3928. // normalization.
  3929. extend(slots, children);
  3930. }
  3931. }
  3932. else {
  3933. needDeletionCheck = !children.$stable;
  3934. normalizeObjectSlots(children, slots);
  3935. }
  3936. deletionComparisonTarget = children;
  3937. }
  3938. else if (children) {
  3939. // non slot object children (direct value) passed to a component
  3940. normalizeVNodeSlots(instance, children);
  3941. deletionComparisonTarget = { default: 1 };
  3942. }
  3943. // delete stale slots
  3944. if (needDeletionCheck) {
  3945. for (const key in slots) {
  3946. if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
  3947. delete slots[key];
  3948. }
  3949. }
  3950. }
  3951. };
  3952. /**
  3953. Runtime helper for applying directives to a vnode. Example usage:
  3954. const comp = resolveComponent('comp')
  3955. const foo = resolveDirective('foo')
  3956. const bar = resolveDirective('bar')
  3957. return withDirectives(h(comp), [
  3958. [foo, this.x],
  3959. [bar, this.y]
  3960. ])
  3961. */
  3962. const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
  3963. function validateDirectiveName(name) {
  3964. if (isBuiltInDirective(name)) {
  3965. warn('Do not use built-in directive ids as custom directive id: ' + name);
  3966. }
  3967. }
  3968. /**
  3969. * Adds directives to a VNode.
  3970. */
  3971. function withDirectives(vnode, directives) {
  3972. const internalInstance = currentRenderingInstance;
  3973. if (internalInstance === null) {
  3974. warn(`withDirectives can only be used inside render functions.`);
  3975. return vnode;
  3976. }
  3977. const instance = internalInstance.proxy;
  3978. const bindings = vnode.dirs || (vnode.dirs = []);
  3979. for (let i = 0; i < directives.length; i++) {
  3980. let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
  3981. if (isFunction(dir)) {
  3982. dir = {
  3983. mounted: dir,
  3984. updated: dir
  3985. };
  3986. }
  3987. bindings.push({
  3988. dir,
  3989. instance,
  3990. value,
  3991. oldValue: void 0,
  3992. arg,
  3993. modifiers
  3994. });
  3995. }
  3996. return vnode;
  3997. }
  3998. function invokeDirectiveHook(vnode, prevVNode, instance, name) {
  3999. const bindings = vnode.dirs;
  4000. const oldBindings = prevVNode && prevVNode.dirs;
  4001. for (let i = 0; i < bindings.length; i++) {
  4002. const binding = bindings[i];
  4003. if (oldBindings) {
  4004. binding.oldValue = oldBindings[i].value;
  4005. }
  4006. const hook = binding.dir[name];
  4007. if (hook) {
  4008. callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
  4009. vnode.el,
  4010. binding,
  4011. vnode,
  4012. prevVNode
  4013. ]);
  4014. }
  4015. }
  4016. }
  4017. function createAppContext() {
  4018. return {
  4019. app: null,
  4020. config: {
  4021. isNativeTag: NO,
  4022. performance: false,
  4023. globalProperties: {},
  4024. optionMergeStrategies: {},
  4025. isCustomElement: NO,
  4026. errorHandler: undefined,
  4027. warnHandler: undefined
  4028. },
  4029. mixins: [],
  4030. components: {},
  4031. directives: {},
  4032. provides: Object.create(null)
  4033. };
  4034. }
  4035. let uid$1 = 0;
  4036. function createAppAPI(render, hydrate) {
  4037. return function createApp(rootComponent, rootProps = null) {
  4038. if (rootProps != null && !isObject(rootProps)) {
  4039. warn(`root props passed to app.mount() must be an object.`);
  4040. rootProps = null;
  4041. }
  4042. const context = createAppContext();
  4043. const installedPlugins = new Set();
  4044. let isMounted = false;
  4045. const app = (context.app = {
  4046. _uid: uid$1++,
  4047. _component: rootComponent,
  4048. _props: rootProps,
  4049. _container: null,
  4050. _context: context,
  4051. version,
  4052. get config() {
  4053. return context.config;
  4054. },
  4055. set config(v) {
  4056. {
  4057. warn(`app.config cannot be replaced. Modify individual options instead.`);
  4058. }
  4059. },
  4060. use(plugin, ...options) {
  4061. if (installedPlugins.has(plugin)) {
  4062. warn(`Plugin has already been applied to target app.`);
  4063. }
  4064. else if (plugin && isFunction(plugin.install)) {
  4065. installedPlugins.add(plugin);
  4066. plugin.install(app, ...options);
  4067. }
  4068. else if (isFunction(plugin)) {
  4069. installedPlugins.add(plugin);
  4070. plugin(app, ...options);
  4071. }
  4072. else {
  4073. warn(`A plugin must either be a function or an object with an "install" ` +
  4074. `function.`);
  4075. }
  4076. return app;
  4077. },
  4078. mixin(mixin) {
  4079. {
  4080. if (!context.mixins.includes(mixin)) {
  4081. context.mixins.push(mixin);
  4082. // global mixin with props/emits de-optimizes props/emits
  4083. // normalization caching.
  4084. if (mixin.props || mixin.emits) {
  4085. context.deopt = true;
  4086. }
  4087. }
  4088. else {
  4089. warn('Mixin has already been applied to target app' +
  4090. (mixin.name ? `: ${mixin.name}` : ''));
  4091. }
  4092. }
  4093. return app;
  4094. },
  4095. component(name, component) {
  4096. {
  4097. validateComponentName(name, context.config);
  4098. }
  4099. if (!component) {
  4100. return context.components[name];
  4101. }
  4102. if ( context.components[name]) {
  4103. warn(`Component "${name}" has already been registered in target app.`);
  4104. }
  4105. context.components[name] = component;
  4106. return app;
  4107. },
  4108. directive(name, directive) {
  4109. {
  4110. validateDirectiveName(name);
  4111. }
  4112. if (!directive) {
  4113. return context.directives[name];
  4114. }
  4115. if ( context.directives[name]) {
  4116. warn(`Directive "${name}" has already been registered in target app.`);
  4117. }
  4118. context.directives[name] = directive;
  4119. return app;
  4120. },
  4121. mount(rootContainer, isHydrate) {
  4122. if (!isMounted) {
  4123. const vnode = createVNode(rootComponent, rootProps);
  4124. // store app context on the root VNode.
  4125. // this will be set on the root instance on initial mount.
  4126. vnode.appContext = context;
  4127. // HMR root reload
  4128. {
  4129. context.reload = () => {
  4130. render(cloneVNode(vnode), rootContainer);
  4131. };
  4132. }
  4133. if (isHydrate && hydrate) {
  4134. hydrate(vnode, rootContainer);
  4135. }
  4136. else {
  4137. render(vnode, rootContainer);
  4138. }
  4139. isMounted = true;
  4140. app._container = rootContainer;
  4141. rootContainer.__vue_app__ = app;
  4142. {
  4143. devtoolsInitApp(app, version);
  4144. }
  4145. return vnode.component.proxy;
  4146. }
  4147. else {
  4148. warn(`App has already been mounted.\n` +
  4149. `If you want to remount the same app, move your app creation logic ` +
  4150. `into a factory function and create fresh app instances for each ` +
  4151. `mount - e.g. \`const createMyApp = () => createApp(App)\``);
  4152. }
  4153. },
  4154. unmount() {
  4155. if (isMounted) {
  4156. render(null, app._container);
  4157. {
  4158. devtoolsUnmountApp(app);
  4159. }
  4160. }
  4161. else {
  4162. warn(`Cannot unmount an app that is not mounted.`);
  4163. }
  4164. },
  4165. provide(key, value) {
  4166. if ( key in context.provides) {
  4167. warn(`App already provides property with key "${String(key)}". ` +
  4168. `It will be overwritten with the new value.`);
  4169. }
  4170. // TypeScript doesn't allow symbols as index type
  4171. // https://github.com/Microsoft/TypeScript/issues/24587
  4172. context.provides[key] = value;
  4173. return app;
  4174. }
  4175. });
  4176. return app;
  4177. };
  4178. }
  4179. let hasMismatch = false;
  4180. const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
  4181. const isComment = (node) => node.nodeType === 8 /* COMMENT */;
  4182. // Note: hydration is DOM-specific
  4183. // But we have to place it in core due to tight coupling with core - splitting
  4184. // it out creates a ton of unnecessary complexity.
  4185. // Hydration also depends on some renderer internal logic which needs to be
  4186. // passed in via arguments.
  4187. function createHydrationFunctions(rendererInternals) {
  4188. const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
  4189. const hydrate = (vnode, container) => {
  4190. if ( !container.hasChildNodes()) {
  4191. warn(`Attempting to hydrate existing markup but container is empty. ` +
  4192. `Performing full mount instead.`);
  4193. patch(null, vnode, container);
  4194. return;
  4195. }
  4196. hasMismatch = false;
  4197. hydrateNode(container.firstChild, vnode, null, null);
  4198. flushPostFlushCbs();
  4199. if (hasMismatch && !false) {
  4200. // this error should show up in production
  4201. console.error(`Hydration completed but contains mismatches.`);
  4202. }
  4203. };
  4204. const hydrateNode = (node, vnode, parentComponent, parentSuspense, optimized = false) => {
  4205. const isFragmentStart = isComment(node) && node.data === '[';
  4206. const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, isFragmentStart);
  4207. const { type, ref, shapeFlag } = vnode;
  4208. const domType = node.nodeType;
  4209. vnode.el = node;
  4210. let nextNode = null;
  4211. switch (type) {
  4212. case Text:
  4213. if (domType !== 3 /* TEXT */) {
  4214. nextNode = onMismatch();
  4215. }
  4216. else {
  4217. if (node.data !== vnode.children) {
  4218. hasMismatch = true;
  4219. warn(`Hydration text mismatch:` +
  4220. `\n- Client: ${JSON.stringify(node.data)}` +
  4221. `\n- Server: ${JSON.stringify(vnode.children)}`);
  4222. node.data = vnode.children;
  4223. }
  4224. nextNode = nextSibling(node);
  4225. }
  4226. break;
  4227. case Comment:
  4228. if (domType !== 8 /* COMMENT */ || isFragmentStart) {
  4229. nextNode = onMismatch();
  4230. }
  4231. else {
  4232. nextNode = nextSibling(node);
  4233. }
  4234. break;
  4235. case Static:
  4236. if (domType !== 1 /* ELEMENT */) {
  4237. nextNode = onMismatch();
  4238. }
  4239. else {
  4240. // determine anchor, adopt content
  4241. nextNode = node;
  4242. // if the static vnode has its content stripped during build,
  4243. // adopt it from the server-rendered HTML.
  4244. const needToAdoptContent = !vnode.children.length;
  4245. for (let i = 0; i < vnode.staticCount; i++) {
  4246. if (needToAdoptContent)
  4247. vnode.children += nextNode.outerHTML;
  4248. if (i === vnode.staticCount - 1) {
  4249. vnode.anchor = nextNode;
  4250. }
  4251. nextNode = nextSibling(nextNode);
  4252. }
  4253. return nextNode;
  4254. }
  4255. break;
  4256. case Fragment:
  4257. if (!isFragmentStart) {
  4258. nextNode = onMismatch();
  4259. }
  4260. else {
  4261. nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, optimized);
  4262. }
  4263. break;
  4264. default:
  4265. if (shapeFlag & 1 /* ELEMENT */) {
  4266. if (domType !== 1 /* ELEMENT */ ||
  4267. vnode.type !== node.tagName.toLowerCase()) {
  4268. nextNode = onMismatch();
  4269. }
  4270. else {
  4271. nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, optimized);
  4272. }
  4273. }
  4274. else if (shapeFlag & 6 /* COMPONENT */) {
  4275. // when setting up the render effect, if the initial vnode already
  4276. // has .el set, the component will perform hydration instead of mount
  4277. // on its sub-tree.
  4278. const container = parentNode(node);
  4279. const hydrateComponent = () => {
  4280. mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
  4281. };
  4282. // async component
  4283. const loadAsync = vnode.type.__asyncLoader;
  4284. if (loadAsync) {
  4285. loadAsync().then(hydrateComponent);
  4286. }
  4287. else {
  4288. hydrateComponent();
  4289. }
  4290. // component may be async, so in the case of fragments we cannot rely
  4291. // on component's rendered output to determine the end of the fragment
  4292. // instead, we do a lookahead to find the end anchor node.
  4293. nextNode = isFragmentStart
  4294. ? locateClosingAsyncAnchor(node)
  4295. : nextSibling(node);
  4296. }
  4297. else if (shapeFlag & 64 /* TELEPORT */) {
  4298. if (domType !== 8 /* COMMENT */) {
  4299. nextNode = onMismatch();
  4300. }
  4301. else {
  4302. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, optimized, rendererInternals, hydrateChildren);
  4303. }
  4304. }
  4305. else if ( shapeFlag & 128 /* SUSPENSE */) {
  4306. nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), optimized, rendererInternals, hydrateNode);
  4307. }
  4308. else {
  4309. warn('Invalid HostVNode type:', type, `(${typeof type})`);
  4310. }
  4311. }
  4312. if (ref != null && parentComponent) {
  4313. setRef(ref, null, parentComponent, parentSuspense, vnode);
  4314. }
  4315. return nextNode;
  4316. };
  4317. const hydrateElement = (el, vnode, parentComponent, parentSuspense, optimized) => {
  4318. optimized = optimized || !!vnode.dynamicChildren;
  4319. const { props, patchFlag, shapeFlag, dirs } = vnode;
  4320. // skip props & children if this is hoisted static nodes
  4321. if (patchFlag !== -1 /* HOISTED */) {
  4322. if (dirs) {
  4323. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  4324. }
  4325. // props
  4326. if (props) {
  4327. if (!optimized ||
  4328. (patchFlag & 16 /* FULL_PROPS */ ||
  4329. patchFlag & 32 /* HYDRATE_EVENTS */)) {
  4330. for (const key in props) {
  4331. if (!isReservedProp(key) && isOn(key)) {
  4332. patchProp(el, key, null, props[key]);
  4333. }
  4334. }
  4335. }
  4336. else if (props.onClick) {
  4337. // Fast path for click listeners (which is most often) to avoid
  4338. // iterating through props.
  4339. patchProp(el, 'onClick', null, props.onClick);
  4340. }
  4341. }
  4342. // vnode / directive hooks
  4343. let vnodeHooks;
  4344. if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
  4345. invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  4346. }
  4347. if (dirs) {
  4348. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  4349. }
  4350. if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
  4351. queueEffectWithSuspense(() => {
  4352. vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
  4353. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  4354. }, parentSuspense);
  4355. }
  4356. // children
  4357. if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
  4358. // skip if element has innerHTML / textContent
  4359. !(props && (props.innerHTML || props.textContent))) {
  4360. let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, optimized);
  4361. let hasWarned = false;
  4362. while (next) {
  4363. hasMismatch = true;
  4364. if ( !hasWarned) {
  4365. warn(`Hydration children mismatch in <${vnode.type}>: ` +
  4366. `server rendered element contains more child nodes than client vdom.`);
  4367. hasWarned = true;
  4368. }
  4369. // The SSRed DOM contains more nodes than it should. Remove them.
  4370. const cur = next;
  4371. next = next.nextSibling;
  4372. remove(cur);
  4373. }
  4374. }
  4375. else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  4376. if (el.textContent !== vnode.children) {
  4377. hasMismatch = true;
  4378. warn(`Hydration text content mismatch in <${vnode.type}>:\n` +
  4379. `- Client: ${el.textContent}\n` +
  4380. `- Server: ${vnode.children}`);
  4381. el.textContent = vnode.children;
  4382. }
  4383. }
  4384. }
  4385. return el.nextSibling;
  4386. };
  4387. const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, optimized) => {
  4388. optimized = optimized || !!parentVNode.dynamicChildren;
  4389. const children = parentVNode.children;
  4390. const l = children.length;
  4391. let hasWarned = false;
  4392. for (let i = 0; i < l; i++) {
  4393. const vnode = optimized
  4394. ? children[i]
  4395. : (children[i] = normalizeVNode(children[i]));
  4396. if (node) {
  4397. node = hydrateNode(node, vnode, parentComponent, parentSuspense, optimized);
  4398. }
  4399. else {
  4400. hasMismatch = true;
  4401. if ( !hasWarned) {
  4402. warn(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
  4403. `server rendered element contains fewer child nodes than client vdom.`);
  4404. hasWarned = true;
  4405. }
  4406. // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
  4407. patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container));
  4408. }
  4409. }
  4410. return node;
  4411. };
  4412. const hydrateFragment = (node, vnode, parentComponent, parentSuspense, optimized) => {
  4413. const container = parentNode(node);
  4414. const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, optimized);
  4415. if (next && isComment(next) && next.data === ']') {
  4416. return nextSibling((vnode.anchor = next));
  4417. }
  4418. else {
  4419. // fragment didn't hydrate successfully, since we didn't get a end anchor
  4420. // back. This should have led to node/children mismatch warnings.
  4421. hasMismatch = true;
  4422. // since the anchor is missing, we need to create one and insert it
  4423. insert((vnode.anchor = createComment(`]`)), container, next);
  4424. return next;
  4425. }
  4426. };
  4427. const handleMismatch = (node, vnode, parentComponent, parentSuspense, isFragment) => {
  4428. hasMismatch = true;
  4429. warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
  4430. ? `(text)`
  4431. : isComment(node) && node.data === '['
  4432. ? `(start of fragment)`
  4433. : ``);
  4434. vnode.el = null;
  4435. if (isFragment) {
  4436. // remove excessive fragment nodes
  4437. const end = locateClosingAsyncAnchor(node);
  4438. while (true) {
  4439. const next = nextSibling(node);
  4440. if (next && next !== end) {
  4441. remove(next);
  4442. }
  4443. else {
  4444. break;
  4445. }
  4446. }
  4447. }
  4448. const next = nextSibling(node);
  4449. const container = parentNode(node);
  4450. remove(node);
  4451. patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container));
  4452. return next;
  4453. };
  4454. const locateClosingAsyncAnchor = (node) => {
  4455. let match = 0;
  4456. while (node) {
  4457. node = nextSibling(node);
  4458. if (node && isComment(node)) {
  4459. if (node.data === '[')
  4460. match++;
  4461. if (node.data === ']') {
  4462. if (match === 0) {
  4463. return nextSibling(node);
  4464. }
  4465. else {
  4466. match--;
  4467. }
  4468. }
  4469. }
  4470. }
  4471. return node;
  4472. };
  4473. return [hydrate, hydrateNode];
  4474. }
  4475. let supported;
  4476. let perf;
  4477. function startMeasure(instance, type) {
  4478. if (instance.appContext.config.performance && isSupported()) {
  4479. perf.mark(`vue-${type}-${instance.uid}`);
  4480. }
  4481. }
  4482. function endMeasure(instance, type) {
  4483. if (instance.appContext.config.performance && isSupported()) {
  4484. const startTag = `vue-${type}-${instance.uid}`;
  4485. const endTag = startTag + `:end`;
  4486. perf.mark(endTag);
  4487. perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
  4488. perf.clearMarks(startTag);
  4489. perf.clearMarks(endTag);
  4490. }
  4491. }
  4492. function isSupported() {
  4493. if (supported !== undefined) {
  4494. return supported;
  4495. }
  4496. /* eslint-disable no-restricted-globals */
  4497. if (typeof window !== 'undefined' && window.performance) {
  4498. supported = true;
  4499. perf = window.performance;
  4500. }
  4501. else {
  4502. supported = false;
  4503. }
  4504. /* eslint-enable no-restricted-globals */
  4505. return supported;
  4506. }
  4507. function createDevEffectOptions(instance) {
  4508. return {
  4509. scheduler: queueJob,
  4510. allowRecurse: true,
  4511. onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0,
  4512. onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0
  4513. };
  4514. }
  4515. const queuePostRenderEffect = queueEffectWithSuspense
  4516. ;
  4517. const setRef = (rawRef, oldRawRef, parentComponent, parentSuspense, vnode) => {
  4518. if (isArray(rawRef)) {
  4519. rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentComponent, parentSuspense, vnode));
  4520. return;
  4521. }
  4522. let value;
  4523. if (!vnode) {
  4524. value = null;
  4525. }
  4526. else {
  4527. if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
  4528. value = vnode.component.proxy;
  4529. }
  4530. else {
  4531. value = vnode.el;
  4532. }
  4533. }
  4534. const { i: owner, r: ref } = rawRef;
  4535. if ( !owner) {
  4536. warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
  4537. `A vnode with ref must be created inside the render function.`);
  4538. return;
  4539. }
  4540. const oldRef = oldRawRef && oldRawRef.r;
  4541. const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
  4542. const setupState = owner.setupState;
  4543. // unset old ref
  4544. if (oldRef != null && oldRef !== ref) {
  4545. if (isString(oldRef)) {
  4546. refs[oldRef] = null;
  4547. if (hasOwn(setupState, oldRef)) {
  4548. setupState[oldRef] = null;
  4549. }
  4550. }
  4551. else if (isRef(oldRef)) {
  4552. oldRef.value = null;
  4553. }
  4554. }
  4555. if (isString(ref)) {
  4556. const doSet = () => {
  4557. refs[ref] = value;
  4558. if (hasOwn(setupState, ref)) {
  4559. setupState[ref] = value;
  4560. }
  4561. };
  4562. // #1789: for non-null values, set them after render
  4563. // null values means this is unmount and it should not overwrite another
  4564. // ref with the same key
  4565. if (value) {
  4566. doSet.id = -1;
  4567. queuePostRenderEffect(doSet, parentSuspense);
  4568. }
  4569. else {
  4570. doSet();
  4571. }
  4572. }
  4573. else if (isRef(ref)) {
  4574. const doSet = () => {
  4575. ref.value = value;
  4576. };
  4577. if (value) {
  4578. doSet.id = -1;
  4579. queuePostRenderEffect(doSet, parentSuspense);
  4580. }
  4581. else {
  4582. doSet();
  4583. }
  4584. }
  4585. else if (isFunction(ref)) {
  4586. callWithErrorHandling(ref, parentComponent, 12 /* FUNCTION_REF */, [
  4587. value,
  4588. refs
  4589. ]);
  4590. }
  4591. else {
  4592. warn('Invalid template ref type:', value, `(${typeof value})`);
  4593. }
  4594. };
  4595. /**
  4596. * The createRenderer function accepts two generic arguments:
  4597. * HostNode and HostElement, corresponding to Node and Element types in the
  4598. * host environment. For example, for runtime-dom, HostNode would be the DOM
  4599. * `Node` interface and HostElement would be the DOM `Element` interface.
  4600. *
  4601. * Custom renderers can pass in the platform specific types like this:
  4602. *
  4603. * ``` js
  4604. * const { render, createApp } = createRenderer<Node, Element>({
  4605. * patchProp,
  4606. * ...nodeOps
  4607. * })
  4608. * ```
  4609. */
  4610. function createRenderer(options) {
  4611. return baseCreateRenderer(options);
  4612. }
  4613. // Separate API for creating hydration-enabled renderer.
  4614. // Hydration logic is only used when calling this function, making it
  4615. // tree-shakable.
  4616. function createHydrationRenderer(options) {
  4617. return baseCreateRenderer(options, createHydrationFunctions);
  4618. }
  4619. // implementation
  4620. function baseCreateRenderer(options, createHydrationFns) {
  4621. const { insert: hostInsert, remove: hostRemove, patchProp: hostPatchProp, forcePatchProp: hostForcePatchProp, createElement: hostCreateElement, createText: hostCreateText, createComment: hostCreateComment, setText: hostSetText, setElementText: hostSetElementText, parentNode: hostParentNode, nextSibling: hostNextSibling, setScopeId: hostSetScopeId = NOOP, cloneNode: hostCloneNode, insertStaticContent: hostInsertStaticContent } = options;
  4622. // Note: functions inside this closure should use `const xxx = () => {}`
  4623. // style in order to prevent being inlined by minifiers.
  4624. const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, optimized = false) => {
  4625. // patching & not same type, unmount old tree
  4626. if (n1 && !isSameVNodeType(n1, n2)) {
  4627. anchor = getNextHostNode(n1);
  4628. unmount(n1, parentComponent, parentSuspense, true);
  4629. n1 = null;
  4630. }
  4631. if (n2.patchFlag === -2 /* BAIL */) {
  4632. optimized = false;
  4633. n2.dynamicChildren = null;
  4634. }
  4635. const { type, ref, shapeFlag } = n2;
  4636. switch (type) {
  4637. case Text:
  4638. processText(n1, n2, container, anchor);
  4639. break;
  4640. case Comment:
  4641. processCommentNode(n1, n2, container, anchor);
  4642. break;
  4643. case Static:
  4644. if (n1 == null) {
  4645. mountStaticNode(n2, container, anchor, isSVG);
  4646. }
  4647. else {
  4648. patchStaticNode(n1, n2, container, isSVG);
  4649. }
  4650. break;
  4651. case Fragment:
  4652. processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4653. break;
  4654. default:
  4655. if (shapeFlag & 1 /* ELEMENT */) {
  4656. processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4657. }
  4658. else if (shapeFlag & 6 /* COMPONENT */) {
  4659. processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4660. }
  4661. else if (shapeFlag & 64 /* TELEPORT */) {
  4662. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals);
  4663. }
  4664. else if ( shapeFlag & 128 /* SUSPENSE */) {
  4665. type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals);
  4666. }
  4667. else {
  4668. warn('Invalid VNode type:', type, `(${typeof type})`);
  4669. }
  4670. }
  4671. // set ref
  4672. if (ref != null && parentComponent) {
  4673. setRef(ref, n1 && n1.ref, parentComponent, parentSuspense, n2);
  4674. }
  4675. };
  4676. const processText = (n1, n2, container, anchor) => {
  4677. if (n1 == null) {
  4678. hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
  4679. }
  4680. else {
  4681. const el = (n2.el = n1.el);
  4682. if (n2.children !== n1.children) {
  4683. hostSetText(el, n2.children);
  4684. }
  4685. }
  4686. };
  4687. const processCommentNode = (n1, n2, container, anchor) => {
  4688. if (n1 == null) {
  4689. hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
  4690. }
  4691. else {
  4692. // there's no support for dynamic comments
  4693. n2.el = n1.el;
  4694. }
  4695. };
  4696. const mountStaticNode = (n2, container, anchor, isSVG) => {
  4697. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  4698. };
  4699. /**
  4700. * Dev / HMR only
  4701. */
  4702. const patchStaticNode = (n1, n2, container, isSVG) => {
  4703. // static nodes are only patched during dev for HMR
  4704. if (n2.children !== n1.children) {
  4705. const anchor = hostNextSibling(n1.anchor);
  4706. // remove existing
  4707. removeStaticNode(n1);
  4708. [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
  4709. }
  4710. else {
  4711. n2.el = n1.el;
  4712. n2.anchor = n1.anchor;
  4713. }
  4714. };
  4715. /**
  4716. * Dev / HMR only
  4717. */
  4718. const moveStaticNode = (vnode, container, anchor) => {
  4719. let cur = vnode.el;
  4720. const end = vnode.anchor;
  4721. while (cur && cur !== end) {
  4722. const next = hostNextSibling(cur);
  4723. hostInsert(cur, container, anchor);
  4724. cur = next;
  4725. }
  4726. hostInsert(end, container, anchor);
  4727. };
  4728. /**
  4729. * Dev / HMR only
  4730. */
  4731. const removeStaticNode = (vnode) => {
  4732. let cur = vnode.el;
  4733. while (cur && cur !== vnode.anchor) {
  4734. const next = hostNextSibling(cur);
  4735. hostRemove(cur);
  4736. cur = next;
  4737. }
  4738. hostRemove(vnode.anchor);
  4739. };
  4740. const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  4741. isSVG = isSVG || n2.type === 'svg';
  4742. if (n1 == null) {
  4743. mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4744. }
  4745. else {
  4746. patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized);
  4747. }
  4748. };
  4749. const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  4750. let el;
  4751. let vnodeHook;
  4752. const { type, props, shapeFlag, transition, scopeId, patchFlag, dirs } = vnode;
  4753. {
  4754. el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is);
  4755. // mount children first, since some props may rely on child content
  4756. // being already rendered, e.g. `<select value>`
  4757. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  4758. hostSetElementText(el, vnode.children);
  4759. }
  4760. else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  4761. mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', optimized || !!vnode.dynamicChildren);
  4762. }
  4763. if (dirs) {
  4764. invokeDirectiveHook(vnode, null, parentComponent, 'created');
  4765. }
  4766. // props
  4767. if (props) {
  4768. for (const key in props) {
  4769. if (!isReservedProp(key)) {
  4770. hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  4771. }
  4772. }
  4773. if ((vnodeHook = props.onVnodeBeforeMount)) {
  4774. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  4775. }
  4776. }
  4777. // scopeId
  4778. setScopeId(el, scopeId, vnode, parentComponent);
  4779. }
  4780. {
  4781. Object.defineProperty(el, '__vnode', {
  4782. value: vnode,
  4783. enumerable: false
  4784. });
  4785. Object.defineProperty(el, '__vueParentComponent', {
  4786. value: parentComponent,
  4787. enumerable: false
  4788. });
  4789. }
  4790. if (dirs) {
  4791. invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
  4792. }
  4793. // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
  4794. // #1689 For inside suspense + suspense resolved case, just call it
  4795. const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
  4796. transition &&
  4797. !transition.persisted;
  4798. if (needCallTransitionHooks) {
  4799. transition.beforeEnter(el);
  4800. }
  4801. hostInsert(el, container, anchor);
  4802. if ((vnodeHook = props && props.onVnodeMounted) ||
  4803. needCallTransitionHooks ||
  4804. dirs) {
  4805. queuePostRenderEffect(() => {
  4806. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  4807. needCallTransitionHooks && transition.enter(el);
  4808. dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
  4809. }, parentSuspense);
  4810. }
  4811. };
  4812. const setScopeId = (el, scopeId, vnode, parentComponent) => {
  4813. if (scopeId) {
  4814. hostSetScopeId(el, scopeId);
  4815. }
  4816. if (parentComponent) {
  4817. const treeOwnerId = parentComponent.type.__scopeId;
  4818. // vnode's own scopeId and the current patched component's scopeId is
  4819. // different - this is a slot content node.
  4820. if (treeOwnerId && treeOwnerId !== scopeId) {
  4821. hostSetScopeId(el, treeOwnerId + '-s');
  4822. }
  4823. let subTree = parentComponent.subTree;
  4824. if ( subTree.type === Fragment) {
  4825. subTree =
  4826. filterSingleRoot(subTree.children) || subTree;
  4827. }
  4828. if (vnode === subTree) {
  4829. setScopeId(el, parentComponent.vnode.scopeId, parentComponent.vnode, parentComponent.parent);
  4830. }
  4831. }
  4832. };
  4833. const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, optimized, start = 0) => {
  4834. for (let i = start; i < children.length; i++) {
  4835. const child = (children[i] = optimized
  4836. ? cloneIfMounted(children[i])
  4837. : normalizeVNode(children[i]));
  4838. patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  4839. }
  4840. };
  4841. const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, optimized) => {
  4842. const el = (n2.el = n1.el);
  4843. let { patchFlag, dynamicChildren, dirs } = n2;
  4844. // #1426 take the old vnode's patch flag into account since user may clone a
  4845. // compiler-generated vnode, which de-opts to FULL_PROPS
  4846. patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
  4847. const oldProps = n1.props || EMPTY_OBJ;
  4848. const newProps = n2.props || EMPTY_OBJ;
  4849. let vnodeHook;
  4850. if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
  4851. invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  4852. }
  4853. if (dirs) {
  4854. invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
  4855. }
  4856. if ( isHmrUpdating) {
  4857. // HMR updated, force full diff
  4858. patchFlag = 0;
  4859. optimized = false;
  4860. dynamicChildren = null;
  4861. }
  4862. if (patchFlag > 0) {
  4863. // the presence of a patchFlag means this element's render code was
  4864. // generated by the compiler and can take the fast path.
  4865. // in this path old node and new node are guaranteed to have the same shape
  4866. // (i.e. at the exact same position in the source template)
  4867. if (patchFlag & 16 /* FULL_PROPS */) {
  4868. // element props contain dynamic keys, full diff needed
  4869. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  4870. }
  4871. else {
  4872. // class
  4873. // this flag is matched when the element has dynamic class bindings.
  4874. if (patchFlag & 2 /* CLASS */) {
  4875. if (oldProps.class !== newProps.class) {
  4876. hostPatchProp(el, 'class', null, newProps.class, isSVG);
  4877. }
  4878. }
  4879. // style
  4880. // this flag is matched when the element has dynamic style bindings
  4881. if (patchFlag & 4 /* STYLE */) {
  4882. hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
  4883. }
  4884. // props
  4885. // This flag is matched when the element has dynamic prop/attr bindings
  4886. // other than class and style. The keys of dynamic prop/attrs are saved for
  4887. // faster iteration.
  4888. // Note dynamic keys like :[foo]="bar" will cause this optimization to
  4889. // bail out and go through a full diff because we need to unset the old key
  4890. if (patchFlag & 8 /* PROPS */) {
  4891. // if the flag is present then dynamicProps must be non-null
  4892. const propsToUpdate = n2.dynamicProps;
  4893. for (let i = 0; i < propsToUpdate.length; i++) {
  4894. const key = propsToUpdate[i];
  4895. const prev = oldProps[key];
  4896. const next = newProps[key];
  4897. if (next !== prev ||
  4898. (hostForcePatchProp && hostForcePatchProp(el, key))) {
  4899. hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
  4900. }
  4901. }
  4902. }
  4903. }
  4904. // text
  4905. // This flag is matched when the element has only dynamic text children.
  4906. if (patchFlag & 1 /* TEXT */) {
  4907. if (n1.children !== n2.children) {
  4908. hostSetElementText(el, n2.children);
  4909. }
  4910. }
  4911. }
  4912. else if (!optimized && dynamicChildren == null) {
  4913. // unoptimized, full diff
  4914. patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
  4915. }
  4916. const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
  4917. if (dynamicChildren) {
  4918. patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG);
  4919. if (
  4920. parentComponent &&
  4921. parentComponent.type.__hmrId) {
  4922. traverseStaticChildren(n1, n2);
  4923. }
  4924. }
  4925. else if (!optimized) {
  4926. // full diff
  4927. patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG);
  4928. }
  4929. if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
  4930. queuePostRenderEffect(() => {
  4931. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
  4932. dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
  4933. }, parentSuspense);
  4934. }
  4935. };
  4936. // The fast path for blocks.
  4937. const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG) => {
  4938. for (let i = 0; i < newChildren.length; i++) {
  4939. const oldVNode = oldChildren[i];
  4940. const newVNode = newChildren[i];
  4941. // Determine the container (parent element) for the patch.
  4942. const container =
  4943. // - In the case of a Fragment, we need to provide the actual parent
  4944. // of the Fragment itself so it can move its children.
  4945. oldVNode.type === Fragment ||
  4946. // - In the case of different nodes, there is going to be a replacement
  4947. // which also requires the correct parent container
  4948. !isSameVNodeType(oldVNode, newVNode) ||
  4949. // - In the case of a component, it could contain anything.
  4950. oldVNode.shapeFlag & 6 /* COMPONENT */ ||
  4951. oldVNode.shapeFlag & 64 /* TELEPORT */
  4952. ? hostParentNode(oldVNode.el)
  4953. : // In other cases, the parent container is not actually used so we
  4954. // just pass the block element here to avoid a DOM parentNode call.
  4955. fallbackContainer;
  4956. patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, true);
  4957. }
  4958. };
  4959. const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
  4960. if (oldProps !== newProps) {
  4961. for (const key in newProps) {
  4962. // empty string is not valid prop
  4963. if (isReservedProp(key))
  4964. continue;
  4965. const next = newProps[key];
  4966. const prev = oldProps[key];
  4967. if (next !== prev ||
  4968. (hostForcePatchProp && hostForcePatchProp(el, key))) {
  4969. hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  4970. }
  4971. }
  4972. if (oldProps !== EMPTY_OBJ) {
  4973. for (const key in oldProps) {
  4974. if (!isReservedProp(key) && !(key in newProps)) {
  4975. hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
  4976. }
  4977. }
  4978. }
  4979. }
  4980. };
  4981. const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  4982. const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
  4983. const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
  4984. let { patchFlag, dynamicChildren } = n2;
  4985. if (patchFlag > 0) {
  4986. optimized = true;
  4987. }
  4988. if ( isHmrUpdating) {
  4989. // HMR updated, force full diff
  4990. patchFlag = 0;
  4991. optimized = false;
  4992. dynamicChildren = null;
  4993. }
  4994. if (n1 == null) {
  4995. hostInsert(fragmentStartAnchor, container, anchor);
  4996. hostInsert(fragmentEndAnchor, container, anchor);
  4997. // a fragment can only have array children
  4998. // since they are either generated by the compiler, or implicitly created
  4999. // from arrays.
  5000. mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);
  5001. }
  5002. else {
  5003. if (patchFlag > 0 &&
  5004. patchFlag & 64 /* STABLE_FRAGMENT */ &&
  5005. dynamicChildren) {
  5006. // a stable fragment (template root or <template v-for>) doesn't need to
  5007. // patch children order, but it may contain dynamicChildren.
  5008. patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG);
  5009. if ( parentComponent && parentComponent.type.__hmrId) {
  5010. traverseStaticChildren(n1, n2);
  5011. }
  5012. else if (
  5013. // #2080 if the stable fragment has a key, it's a <template v-for> that may
  5014. // get moved around. Make sure all root level vnodes inherit el.
  5015. // #2134 or if it's a component root, it may also get moved around
  5016. // as the component is being moved.
  5017. n2.key != null ||
  5018. (parentComponent && n2 === parentComponent.subTree)) {
  5019. traverseStaticChildren(n1, n2, true /* shallow */);
  5020. }
  5021. }
  5022. else {
  5023. // keyed / unkeyed, or manual fragments.
  5024. // for keyed & unkeyed, since they are compiler generated from v-for,
  5025. // each child is guaranteed to be a block so the fragment will never
  5026. // have dynamicChildren.
  5027. patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);
  5028. }
  5029. }
  5030. };
  5031. const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5032. if (n1 == null) {
  5033. if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
  5034. parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
  5035. }
  5036. else {
  5037. mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5038. }
  5039. }
  5040. else {
  5041. updateComponent(n1, n2, optimized);
  5042. }
  5043. };
  5044. const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5045. const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
  5046. if ( instance.type.__hmrId) {
  5047. registerHMR(instance);
  5048. }
  5049. {
  5050. pushWarningContext(initialVNode);
  5051. startMeasure(instance, `mount`);
  5052. }
  5053. // inject renderer internals for keepAlive
  5054. if (isKeepAlive(initialVNode)) {
  5055. instance.ctx.renderer = internals;
  5056. }
  5057. // resolve props and slots for setup context
  5058. {
  5059. startMeasure(instance, `init`);
  5060. }
  5061. setupComponent(instance);
  5062. {
  5063. endMeasure(instance, `init`);
  5064. }
  5065. // setup() is async. This component relies on async logic to be resolved
  5066. // before proceeding
  5067. if ( instance.asyncDep) {
  5068. parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
  5069. // Give it a placeholder if this is not hydration
  5070. // TODO handle self-defined fallback
  5071. if (!initialVNode.el) {
  5072. const placeholder = (instance.subTree = createVNode(Comment));
  5073. processCommentNode(null, placeholder, container, anchor);
  5074. }
  5075. return;
  5076. }
  5077. setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
  5078. {
  5079. popWarningContext();
  5080. endMeasure(instance, `mount`);
  5081. }
  5082. };
  5083. const updateComponent = (n1, n2, optimized) => {
  5084. const instance = (n2.component = n1.component);
  5085. if (shouldUpdateComponent(n1, n2, optimized)) {
  5086. if (
  5087. instance.asyncDep &&
  5088. !instance.asyncResolved) {
  5089. // async & still pending - just update props and slots
  5090. // since the component's reactive effect for render isn't set-up yet
  5091. {
  5092. pushWarningContext(n2);
  5093. }
  5094. updateComponentPreRender(instance, n2, optimized);
  5095. {
  5096. popWarningContext();
  5097. }
  5098. return;
  5099. }
  5100. else {
  5101. // normal update
  5102. instance.next = n2;
  5103. // in case the child component is also queued, remove it to avoid
  5104. // double updating the same child component in the same flush.
  5105. invalidateJob(instance.update);
  5106. // instance.update is the reactive effect runner.
  5107. instance.update();
  5108. }
  5109. }
  5110. else {
  5111. // no update needed. just copy over properties
  5112. n2.component = n1.component;
  5113. n2.el = n1.el;
  5114. instance.vnode = n2;
  5115. }
  5116. };
  5117. const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
  5118. // create reactive effect for rendering
  5119. instance.update = effect(function componentEffect() {
  5120. if (!instance.isMounted) {
  5121. let vnodeHook;
  5122. const { el, props } = initialVNode;
  5123. const { bm, m, parent } = instance;
  5124. // beforeMount hook
  5125. if (bm) {
  5126. invokeArrayFns(bm);
  5127. }
  5128. // onVnodeBeforeMount
  5129. if ((vnodeHook = props && props.onVnodeBeforeMount)) {
  5130. invokeVNodeHook(vnodeHook, parent, initialVNode);
  5131. }
  5132. // render
  5133. {
  5134. startMeasure(instance, `render`);
  5135. }
  5136. const subTree = (instance.subTree = renderComponentRoot(instance));
  5137. {
  5138. endMeasure(instance, `render`);
  5139. }
  5140. if (el && hydrateNode) {
  5141. {
  5142. startMeasure(instance, `hydrate`);
  5143. }
  5144. // vnode has adopted host node - perform hydration instead of mount.
  5145. hydrateNode(initialVNode.el, subTree, instance, parentSuspense);
  5146. {
  5147. endMeasure(instance, `hydrate`);
  5148. }
  5149. }
  5150. else {
  5151. {
  5152. startMeasure(instance, `patch`);
  5153. }
  5154. patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
  5155. {
  5156. endMeasure(instance, `patch`);
  5157. }
  5158. initialVNode.el = subTree.el;
  5159. }
  5160. // mounted hook
  5161. if (m) {
  5162. queuePostRenderEffect(m, parentSuspense);
  5163. }
  5164. // onVnodeMounted
  5165. if ((vnodeHook = props && props.onVnodeMounted)) {
  5166. queuePostRenderEffect(() => {
  5167. invokeVNodeHook(vnodeHook, parent, initialVNode);
  5168. }, parentSuspense);
  5169. }
  5170. // activated hook for keep-alive roots.
  5171. // #1742 activated hook must be accessed after first render
  5172. // since the hook may be injected by a child keep-alive
  5173. const { a } = instance;
  5174. if (a &&
  5175. initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  5176. queuePostRenderEffect(a, parentSuspense);
  5177. }
  5178. instance.isMounted = true;
  5179. }
  5180. else {
  5181. // updateComponent
  5182. // This is triggered by mutation of component's own state (next: null)
  5183. // OR parent calling processComponent (next: VNode)
  5184. let { next, bu, u, parent, vnode } = instance;
  5185. let originNext = next;
  5186. let vnodeHook;
  5187. {
  5188. pushWarningContext(next || instance.vnode);
  5189. }
  5190. if (next) {
  5191. next.el = vnode.el;
  5192. updateComponentPreRender(instance, next, optimized);
  5193. }
  5194. else {
  5195. next = vnode;
  5196. }
  5197. // beforeUpdate hook
  5198. if (bu) {
  5199. invokeArrayFns(bu);
  5200. }
  5201. // onVnodeBeforeUpdate
  5202. if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
  5203. invokeVNodeHook(vnodeHook, parent, next, vnode);
  5204. }
  5205. // render
  5206. {
  5207. startMeasure(instance, `render`);
  5208. }
  5209. const nextTree = renderComponentRoot(instance);
  5210. {
  5211. endMeasure(instance, `render`);
  5212. }
  5213. const prevTree = instance.subTree;
  5214. instance.subTree = nextTree;
  5215. {
  5216. startMeasure(instance, `patch`);
  5217. }
  5218. patch(prevTree, nextTree,
  5219. // parent may have changed if it's in a teleport
  5220. hostParentNode(prevTree.el),
  5221. // anchor may have changed if it's in a fragment
  5222. getNextHostNode(prevTree), instance, parentSuspense, isSVG);
  5223. {
  5224. endMeasure(instance, `patch`);
  5225. }
  5226. next.el = nextTree.el;
  5227. if (originNext === null) {
  5228. // self-triggered update. In case of HOC, update parent component
  5229. // vnode el. HOC is indicated by parent instance's subTree pointing
  5230. // to child component's vnode
  5231. updateHOCHostEl(instance, nextTree.el);
  5232. }
  5233. // updated hook
  5234. if (u) {
  5235. queuePostRenderEffect(u, parentSuspense);
  5236. }
  5237. // onVnodeUpdated
  5238. if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
  5239. queuePostRenderEffect(() => {
  5240. invokeVNodeHook(vnodeHook, parent, next, vnode);
  5241. }, parentSuspense);
  5242. }
  5243. {
  5244. devtoolsComponentUpdated(instance);
  5245. }
  5246. {
  5247. popWarningContext();
  5248. }
  5249. }
  5250. }, createDevEffectOptions(instance) );
  5251. };
  5252. const updateComponentPreRender = (instance, nextVNode, optimized) => {
  5253. nextVNode.component = instance;
  5254. const prevProps = instance.vnode.props;
  5255. instance.vnode = nextVNode;
  5256. instance.next = null;
  5257. updateProps(instance, nextVNode.props, prevProps, optimized);
  5258. updateSlots(instance, nextVNode.children);
  5259. // props update may have triggered pre-flush watchers.
  5260. // flush them before the render update.
  5261. flushPreFlushCbs(undefined, instance.update);
  5262. };
  5263. const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized = false) => {
  5264. const c1 = n1 && n1.children;
  5265. const prevShapeFlag = n1 ? n1.shapeFlag : 0;
  5266. const c2 = n2.children;
  5267. const { patchFlag, shapeFlag } = n2;
  5268. // fast path
  5269. if (patchFlag > 0) {
  5270. if (patchFlag & 128 /* KEYED_FRAGMENT */) {
  5271. // this could be either fully-keyed or mixed (some keyed some not)
  5272. // presence of patchFlag means children are guaranteed to be arrays
  5273. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5274. return;
  5275. }
  5276. else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
  5277. // unkeyed
  5278. patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5279. return;
  5280. }
  5281. }
  5282. // children has 3 possibilities: text, array or no children.
  5283. if (shapeFlag & 8 /* TEXT_CHILDREN */) {
  5284. // text children fast path
  5285. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  5286. unmountChildren(c1, parentComponent, parentSuspense);
  5287. }
  5288. if (c2 !== c1) {
  5289. hostSetElementText(container, c2);
  5290. }
  5291. }
  5292. else {
  5293. if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
  5294. // prev children was array
  5295. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5296. // two arrays, cannot assume anything, do full diff
  5297. patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5298. }
  5299. else {
  5300. // no new children, just unmount old
  5301. unmountChildren(c1, parentComponent, parentSuspense, true);
  5302. }
  5303. }
  5304. else {
  5305. // prev children was text OR null
  5306. // new children is array OR null
  5307. if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
  5308. hostSetElementText(container, '');
  5309. }
  5310. // mount new if array
  5311. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5312. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5313. }
  5314. }
  5315. }
  5316. };
  5317. const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5318. c1 = c1 || EMPTY_ARR;
  5319. c2 = c2 || EMPTY_ARR;
  5320. const oldLength = c1.length;
  5321. const newLength = c2.length;
  5322. const commonLength = Math.min(oldLength, newLength);
  5323. let i;
  5324. for (i = 0; i < commonLength; i++) {
  5325. const nextChild = (c2[i] = optimized
  5326. ? cloneIfMounted(c2[i])
  5327. : normalizeVNode(c2[i]));
  5328. patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, optimized);
  5329. }
  5330. if (oldLength > newLength) {
  5331. // remove old
  5332. unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
  5333. }
  5334. else {
  5335. // mount new
  5336. mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, commonLength);
  5337. }
  5338. };
  5339. // can be all-keyed or mixed
  5340. const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, optimized) => {
  5341. let i = 0;
  5342. const l2 = c2.length;
  5343. let e1 = c1.length - 1; // prev ending index
  5344. let e2 = l2 - 1; // next ending index
  5345. // 1. sync from start
  5346. // (a b) c
  5347. // (a b) d e
  5348. while (i <= e1 && i <= e2) {
  5349. const n1 = c1[i];
  5350. const n2 = (c2[i] = optimized
  5351. ? cloneIfMounted(c2[i])
  5352. : normalizeVNode(c2[i]));
  5353. if (isSameVNodeType(n1, n2)) {
  5354. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, optimized);
  5355. }
  5356. else {
  5357. break;
  5358. }
  5359. i++;
  5360. }
  5361. // 2. sync from end
  5362. // a (b c)
  5363. // d e (b c)
  5364. while (i <= e1 && i <= e2) {
  5365. const n1 = c1[e1];
  5366. const n2 = (c2[e2] = optimized
  5367. ? cloneIfMounted(c2[e2])
  5368. : normalizeVNode(c2[e2]));
  5369. if (isSameVNodeType(n1, n2)) {
  5370. patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, optimized);
  5371. }
  5372. else {
  5373. break;
  5374. }
  5375. e1--;
  5376. e2--;
  5377. }
  5378. // 3. common sequence + mount
  5379. // (a b)
  5380. // (a b) c
  5381. // i = 2, e1 = 1, e2 = 2
  5382. // (a b)
  5383. // c (a b)
  5384. // i = 0, e1 = -1, e2 = 0
  5385. if (i > e1) {
  5386. if (i <= e2) {
  5387. const nextPos = e2 + 1;
  5388. const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
  5389. while (i <= e2) {
  5390. patch(null, (c2[i] = optimized
  5391. ? cloneIfMounted(c2[i])
  5392. : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG);
  5393. i++;
  5394. }
  5395. }
  5396. }
  5397. // 4. common sequence + unmount
  5398. // (a b) c
  5399. // (a b)
  5400. // i = 2, e1 = 2, e2 = 1
  5401. // a (b c)
  5402. // (b c)
  5403. // i = 0, e1 = 0, e2 = -1
  5404. else if (i > e2) {
  5405. while (i <= e1) {
  5406. unmount(c1[i], parentComponent, parentSuspense, true);
  5407. i++;
  5408. }
  5409. }
  5410. // 5. unknown sequence
  5411. // [i ... e1 + 1]: a b [c d e] f g
  5412. // [i ... e2 + 1]: a b [e d c h] f g
  5413. // i = 2, e1 = 4, e2 = 5
  5414. else {
  5415. const s1 = i; // prev starting index
  5416. const s2 = i; // next starting index
  5417. // 5.1 build key:index map for newChildren
  5418. const keyToNewIndexMap = new Map();
  5419. for (i = s2; i <= e2; i++) {
  5420. const nextChild = (c2[i] = optimized
  5421. ? cloneIfMounted(c2[i])
  5422. : normalizeVNode(c2[i]));
  5423. if (nextChild.key != null) {
  5424. if ( keyToNewIndexMap.has(nextChild.key)) {
  5425. warn(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
  5426. }
  5427. keyToNewIndexMap.set(nextChild.key, i);
  5428. }
  5429. }
  5430. // 5.2 loop through old children left to be patched and try to patch
  5431. // matching nodes & remove nodes that are no longer present
  5432. let j;
  5433. let patched = 0;
  5434. const toBePatched = e2 - s2 + 1;
  5435. let moved = false;
  5436. // used to track whether any node has moved
  5437. let maxNewIndexSoFar = 0;
  5438. // works as Map<newIndex, oldIndex>
  5439. // Note that oldIndex is offset by +1
  5440. // and oldIndex = 0 is a special value indicating the new node has
  5441. // no corresponding old node.
  5442. // used for determining longest stable subsequence
  5443. const newIndexToOldIndexMap = new Array(toBePatched);
  5444. for (i = 0; i < toBePatched; i++)
  5445. newIndexToOldIndexMap[i] = 0;
  5446. for (i = s1; i <= e1; i++) {
  5447. const prevChild = c1[i];
  5448. if (patched >= toBePatched) {
  5449. // all new children have been patched so this can only be a removal
  5450. unmount(prevChild, parentComponent, parentSuspense, true);
  5451. continue;
  5452. }
  5453. let newIndex;
  5454. if (prevChild.key != null) {
  5455. newIndex = keyToNewIndexMap.get(prevChild.key);
  5456. }
  5457. else {
  5458. // key-less node, try to locate a key-less node of the same type
  5459. for (j = s2; j <= e2; j++) {
  5460. if (newIndexToOldIndexMap[j - s2] === 0 &&
  5461. isSameVNodeType(prevChild, c2[j])) {
  5462. newIndex = j;
  5463. break;
  5464. }
  5465. }
  5466. }
  5467. if (newIndex === undefined) {
  5468. unmount(prevChild, parentComponent, parentSuspense, true);
  5469. }
  5470. else {
  5471. newIndexToOldIndexMap[newIndex - s2] = i + 1;
  5472. if (newIndex >= maxNewIndexSoFar) {
  5473. maxNewIndexSoFar = newIndex;
  5474. }
  5475. else {
  5476. moved = true;
  5477. }
  5478. patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, optimized);
  5479. patched++;
  5480. }
  5481. }
  5482. // 5.3 move and mount
  5483. // generate longest stable subsequence only when nodes have moved
  5484. const increasingNewIndexSequence = moved
  5485. ? getSequence(newIndexToOldIndexMap)
  5486. : EMPTY_ARR;
  5487. j = increasingNewIndexSequence.length - 1;
  5488. // looping backwards so that we can use last patched node as anchor
  5489. for (i = toBePatched - 1; i >= 0; i--) {
  5490. const nextIndex = s2 + i;
  5491. const nextChild = c2[nextIndex];
  5492. const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
  5493. if (newIndexToOldIndexMap[i] === 0) {
  5494. // mount new
  5495. patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG);
  5496. }
  5497. else if (moved) {
  5498. // move if:
  5499. // There is no stable subsequence (e.g. a reverse)
  5500. // OR current node is not among the stable sequence
  5501. if (j < 0 || i !== increasingNewIndexSequence[j]) {
  5502. move(nextChild, container, anchor, 2 /* REORDER */);
  5503. }
  5504. else {
  5505. j--;
  5506. }
  5507. }
  5508. }
  5509. }
  5510. };
  5511. const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
  5512. const { el, type, transition, children, shapeFlag } = vnode;
  5513. if (shapeFlag & 6 /* COMPONENT */) {
  5514. move(vnode.component.subTree, container, anchor, moveType);
  5515. return;
  5516. }
  5517. if ( shapeFlag & 128 /* SUSPENSE */) {
  5518. vnode.suspense.move(container, anchor, moveType);
  5519. return;
  5520. }
  5521. if (shapeFlag & 64 /* TELEPORT */) {
  5522. type.move(vnode, container, anchor, internals);
  5523. return;
  5524. }
  5525. if (type === Fragment) {
  5526. hostInsert(el, container, anchor);
  5527. for (let i = 0; i < children.length; i++) {
  5528. move(children[i], container, anchor, moveType);
  5529. }
  5530. hostInsert(vnode.anchor, container, anchor);
  5531. return;
  5532. }
  5533. // static node move can only happen when force updating HMR
  5534. if ( type === Static) {
  5535. moveStaticNode(vnode, container, anchor);
  5536. return;
  5537. }
  5538. // single nodes
  5539. const needTransition = moveType !== 2 /* REORDER */ &&
  5540. shapeFlag & 1 /* ELEMENT */ &&
  5541. transition;
  5542. if (needTransition) {
  5543. if (moveType === 0 /* ENTER */) {
  5544. transition.beforeEnter(el);
  5545. hostInsert(el, container, anchor);
  5546. queuePostRenderEffect(() => transition.enter(el), parentSuspense);
  5547. }
  5548. else {
  5549. const { leave, delayLeave, afterLeave } = transition;
  5550. const remove = () => hostInsert(el, container, anchor);
  5551. const performLeave = () => {
  5552. leave(el, () => {
  5553. remove();
  5554. afterLeave && afterLeave();
  5555. });
  5556. };
  5557. if (delayLeave) {
  5558. delayLeave(el, remove, performLeave);
  5559. }
  5560. else {
  5561. performLeave();
  5562. }
  5563. }
  5564. }
  5565. else {
  5566. hostInsert(el, container, anchor);
  5567. }
  5568. };
  5569. const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
  5570. const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
  5571. // unset ref
  5572. if (ref != null && parentComponent) {
  5573. setRef(ref, null, parentComponent, parentSuspense, null);
  5574. }
  5575. if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
  5576. parentComponent.ctx.deactivate(vnode);
  5577. return;
  5578. }
  5579. const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
  5580. let vnodeHook;
  5581. if ((vnodeHook = props && props.onVnodeBeforeUnmount)) {
  5582. invokeVNodeHook(vnodeHook, parentComponent, vnode);
  5583. }
  5584. if (shapeFlag & 6 /* COMPONENT */) {
  5585. unmountComponent(vnode.component, parentSuspense, doRemove);
  5586. }
  5587. else {
  5588. if ( shapeFlag & 128 /* SUSPENSE */) {
  5589. vnode.suspense.unmount(parentSuspense, doRemove);
  5590. return;
  5591. }
  5592. if (shouldInvokeDirs) {
  5593. invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
  5594. }
  5595. if (dynamicChildren &&
  5596. // #1153: fast path should not be taken for non-stable (v-for) fragments
  5597. (type !== Fragment ||
  5598. (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
  5599. // fast path for block nodes: only need to unmount dynamic children.
  5600. unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
  5601. }
  5602. else if ((type === Fragment &&
  5603. (patchFlag & 128 /* KEYED_FRAGMENT */ ||
  5604. patchFlag & 256 /* UNKEYED_FRAGMENT */)) ||
  5605. (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
  5606. unmountChildren(children, parentComponent, parentSuspense);
  5607. }
  5608. // an unmounted teleport should always remove its children if not disabled
  5609. if (shapeFlag & 64 /* TELEPORT */ &&
  5610. (doRemove || !isTeleportDisabled(vnode.props))) {
  5611. vnode.type.remove(vnode, internals);
  5612. }
  5613. if (doRemove) {
  5614. remove(vnode);
  5615. }
  5616. }
  5617. if ((vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {
  5618. queuePostRenderEffect(() => {
  5619. vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
  5620. shouldInvokeDirs &&
  5621. invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
  5622. }, parentSuspense);
  5623. }
  5624. };
  5625. const remove = vnode => {
  5626. const { type, el, anchor, transition } = vnode;
  5627. if (type === Fragment) {
  5628. removeFragment(el, anchor);
  5629. return;
  5630. }
  5631. if ( type === Static) {
  5632. removeStaticNode(vnode);
  5633. return;
  5634. }
  5635. const performRemove = () => {
  5636. hostRemove(el);
  5637. if (transition && !transition.persisted && transition.afterLeave) {
  5638. transition.afterLeave();
  5639. }
  5640. };
  5641. if (vnode.shapeFlag & 1 /* ELEMENT */ &&
  5642. transition &&
  5643. !transition.persisted) {
  5644. const { leave, delayLeave } = transition;
  5645. const performLeave = () => leave(el, performRemove);
  5646. if (delayLeave) {
  5647. delayLeave(vnode.el, performRemove, performLeave);
  5648. }
  5649. else {
  5650. performLeave();
  5651. }
  5652. }
  5653. else {
  5654. performRemove();
  5655. }
  5656. };
  5657. const removeFragment = (cur, end) => {
  5658. // For fragments, directly remove all contained DOM nodes.
  5659. // (fragment child nodes cannot have transition)
  5660. let next;
  5661. while (cur !== end) {
  5662. next = hostNextSibling(cur);
  5663. hostRemove(cur);
  5664. cur = next;
  5665. }
  5666. hostRemove(end);
  5667. };
  5668. const unmountComponent = (instance, parentSuspense, doRemove) => {
  5669. if ( instance.type.__hmrId) {
  5670. unregisterHMR(instance);
  5671. }
  5672. const { bum, effects, update, subTree, um } = instance;
  5673. // beforeUnmount hook
  5674. if (bum) {
  5675. invokeArrayFns(bum);
  5676. }
  5677. if (effects) {
  5678. for (let i = 0; i < effects.length; i++) {
  5679. stop(effects[i]);
  5680. }
  5681. }
  5682. // update may be null if a component is unmounted before its async
  5683. // setup has resolved.
  5684. if (update) {
  5685. stop(update);
  5686. unmount(subTree, instance, parentSuspense, doRemove);
  5687. }
  5688. // unmounted hook
  5689. if (um) {
  5690. queuePostRenderEffect(um, parentSuspense);
  5691. }
  5692. queuePostRenderEffect(() => {
  5693. instance.isUnmounted = true;
  5694. }, parentSuspense);
  5695. // A component with async dep inside a pending suspense is unmounted before
  5696. // its async dep resolves. This should remove the dep from the suspense, and
  5697. // cause the suspense to resolve immediately if that was the last dep.
  5698. if (
  5699. parentSuspense &&
  5700. parentSuspense.pendingBranch &&
  5701. !parentSuspense.isUnmounted &&
  5702. instance.asyncDep &&
  5703. !instance.asyncResolved &&
  5704. instance.suspenseId === parentSuspense.pendingId) {
  5705. parentSuspense.deps--;
  5706. if (parentSuspense.deps === 0) {
  5707. parentSuspense.resolve();
  5708. }
  5709. }
  5710. {
  5711. devtoolsComponentRemoved(instance);
  5712. }
  5713. };
  5714. const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
  5715. for (let i = start; i < children.length; i++) {
  5716. unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
  5717. }
  5718. };
  5719. const getNextHostNode = vnode => {
  5720. if (vnode.shapeFlag & 6 /* COMPONENT */) {
  5721. return getNextHostNode(vnode.component.subTree);
  5722. }
  5723. if ( vnode.shapeFlag & 128 /* SUSPENSE */) {
  5724. return vnode.suspense.next();
  5725. }
  5726. return hostNextSibling((vnode.anchor || vnode.el));
  5727. };
  5728. const render = (vnode, container) => {
  5729. if (vnode == null) {
  5730. if (container._vnode) {
  5731. unmount(container._vnode, null, null, true);
  5732. }
  5733. }
  5734. else {
  5735. patch(container._vnode || null, vnode, container);
  5736. }
  5737. flushPostFlushCbs();
  5738. container._vnode = vnode;
  5739. };
  5740. const internals = {
  5741. p: patch,
  5742. um: unmount,
  5743. m: move,
  5744. r: remove,
  5745. mt: mountComponent,
  5746. mc: mountChildren,
  5747. pc: patchChildren,
  5748. pbc: patchBlockChildren,
  5749. n: getNextHostNode,
  5750. o: options
  5751. };
  5752. let hydrate;
  5753. let hydrateNode;
  5754. if (createHydrationFns) {
  5755. [hydrate, hydrateNode] = createHydrationFns(internals);
  5756. }
  5757. return {
  5758. render,
  5759. hydrate,
  5760. createApp: createAppAPI(render, hydrate)
  5761. };
  5762. }
  5763. function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
  5764. callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
  5765. vnode,
  5766. prevVNode
  5767. ]);
  5768. }
  5769. /**
  5770. * #1156
  5771. * When a component is HMR-enabled, we need to make sure that all static nodes
  5772. * inside a block also inherit the DOM element from the previous tree so that
  5773. * HMR updates (which are full updates) can retrieve the element for patching.
  5774. *
  5775. * #2080
  5776. * Inside keyed `template` fragment static children, if a fragment is moved,
  5777. * the children will always moved so that need inherit el form previous nodes
  5778. * to ensure correct moved position.
  5779. */
  5780. function traverseStaticChildren(n1, n2, shallow = false) {
  5781. const ch1 = n1.children;
  5782. const ch2 = n2.children;
  5783. if (isArray(ch1) && isArray(ch2)) {
  5784. for (let i = 0; i < ch1.length; i++) {
  5785. // this is only called in the optimized path so array children are
  5786. // guaranteed to be vnodes
  5787. const c1 = ch1[i];
  5788. let c2 = ch2[i];
  5789. if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
  5790. if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
  5791. c2 = ch2[i] = cloneIfMounted(ch2[i]);
  5792. c2.el = c1.el;
  5793. }
  5794. if (!shallow)
  5795. traverseStaticChildren(c1, c2);
  5796. }
  5797. // also inherit for comment nodes, but not placeholders (e.g. v-if which
  5798. // would have received .el during block patch)
  5799. if ( c2.type === Comment && !c2.el) {
  5800. c2.el = c1.el;
  5801. }
  5802. }
  5803. }
  5804. }
  5805. // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
  5806. function getSequence(arr) {
  5807. const p = arr.slice();
  5808. const result = [0];
  5809. let i, j, u, v, c;
  5810. const len = arr.length;
  5811. for (i = 0; i < len; i++) {
  5812. const arrI = arr[i];
  5813. if (arrI !== 0) {
  5814. j = result[result.length - 1];
  5815. if (arr[j] < arrI) {
  5816. p[i] = j;
  5817. result.push(i);
  5818. continue;
  5819. }
  5820. u = 0;
  5821. v = result.length - 1;
  5822. while (u < v) {
  5823. c = ((u + v) / 2) | 0;
  5824. if (arr[result[c]] < arrI) {
  5825. u = c + 1;
  5826. }
  5827. else {
  5828. v = c;
  5829. }
  5830. }
  5831. if (arrI < arr[result[u]]) {
  5832. if (u > 0) {
  5833. p[i] = result[u - 1];
  5834. }
  5835. result[u] = i;
  5836. }
  5837. }
  5838. }
  5839. u = result.length;
  5840. v = result[u - 1];
  5841. while (u-- > 0) {
  5842. result[u] = v;
  5843. v = p[v];
  5844. }
  5845. return result;
  5846. }
  5847. const isTeleport = (type) => type.__isTeleport;
  5848. const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
  5849. const resolveTarget = (props, select) => {
  5850. const targetSelector = props && props.to;
  5851. if (isString(targetSelector)) {
  5852. if (!select) {
  5853. warn(`Current renderer does not support string target for Teleports. ` +
  5854. `(missing querySelector renderer option)`);
  5855. return null;
  5856. }
  5857. else {
  5858. const target = select(targetSelector);
  5859. if (!target) {
  5860. warn(`Failed to locate Teleport target with selector "${targetSelector}". ` +
  5861. `Note the target element must exist before the component is mounted - ` +
  5862. `i.e. the target cannot be rendered by the component itself, and ` +
  5863. `ideally should be outside of the entire Vue component tree.`);
  5864. }
  5865. return target;
  5866. }
  5867. }
  5868. else {
  5869. if ( !targetSelector && !isTeleportDisabled(props)) {
  5870. warn(`Invalid Teleport target: ${targetSelector}`);
  5871. }
  5872. return targetSelector;
  5873. }
  5874. };
  5875. const TeleportImpl = {
  5876. __isTeleport: true,
  5877. process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals) {
  5878. const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
  5879. const disabled = isTeleportDisabled(n2.props);
  5880. const { shapeFlag, children } = n2;
  5881. if (n1 == null) {
  5882. // insert anchors in the main view
  5883. const placeholder = (n2.el = createComment('teleport start')
  5884. );
  5885. const mainAnchor = (n2.anchor = createComment('teleport end')
  5886. );
  5887. insert(placeholder, container, anchor);
  5888. insert(mainAnchor, container, anchor);
  5889. const target = (n2.target = resolveTarget(n2.props, querySelector));
  5890. const targetAnchor = (n2.targetAnchor = createText(''));
  5891. if (target) {
  5892. insert(targetAnchor, target);
  5893. }
  5894. else if ( !disabled) {
  5895. warn('Invalid Teleport target on mount:', target, `(${typeof target})`);
  5896. }
  5897. const mount = (container, anchor) => {
  5898. // Teleport *always* has Array children. This is enforced in both the
  5899. // compiler and vnode children normalization.
  5900. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5901. mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
  5902. }
  5903. };
  5904. if (disabled) {
  5905. mount(container, mainAnchor);
  5906. }
  5907. else if (target) {
  5908. mount(target, targetAnchor);
  5909. }
  5910. }
  5911. else {
  5912. // update content
  5913. n2.el = n1.el;
  5914. const mainAnchor = (n2.anchor = n1.anchor);
  5915. const target = (n2.target = n1.target);
  5916. const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
  5917. const wasDisabled = isTeleportDisabled(n1.props);
  5918. const currentContainer = wasDisabled ? container : target;
  5919. const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
  5920. if (n2.dynamicChildren) {
  5921. // fast path when the teleport happens to be a block root
  5922. patchBlockChildren(n1.dynamicChildren, n2.dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG);
  5923. // even in block tree mode we need to make sure all root-level nodes
  5924. // in the teleport inherit previous DOM references so that they can
  5925. // be moved in future patches.
  5926. traverseStaticChildren(n1, n2, true);
  5927. }
  5928. else if (!optimized) {
  5929. patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG);
  5930. }
  5931. if (disabled) {
  5932. if (!wasDisabled) {
  5933. // enabled -> disabled
  5934. // move into main container
  5935. moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
  5936. }
  5937. }
  5938. else {
  5939. // target changed
  5940. if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
  5941. const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
  5942. if (nextTarget) {
  5943. moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
  5944. }
  5945. else {
  5946. warn('Invalid Teleport target on update:', target, `(${typeof target})`);
  5947. }
  5948. }
  5949. else if (wasDisabled) {
  5950. // disabled -> enabled
  5951. // move into teleport target
  5952. moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
  5953. }
  5954. }
  5955. }
  5956. },
  5957. remove(vnode, { r: remove, o: { remove: hostRemove } }) {
  5958. const { shapeFlag, children, anchor } = vnode;
  5959. hostRemove(anchor);
  5960. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5961. for (let i = 0; i < children.length; i++) {
  5962. remove(children[i]);
  5963. }
  5964. }
  5965. },
  5966. move: moveTeleport,
  5967. hydrate: hydrateTeleport
  5968. };
  5969. function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
  5970. // move target anchor if this is a target change.
  5971. if (moveType === 0 /* TARGET_CHANGE */) {
  5972. insert(vnode.targetAnchor, container, parentAnchor);
  5973. }
  5974. const { el, anchor, shapeFlag, children, props } = vnode;
  5975. const isReorder = moveType === 2 /* REORDER */;
  5976. // move main view anchor if this is a re-order.
  5977. if (isReorder) {
  5978. insert(el, container, parentAnchor);
  5979. }
  5980. // if this is a re-order and teleport is enabled (content is in target)
  5981. // do not move children. So the opposite is: only move children if this
  5982. // is not a reorder, or the teleport is disabled
  5983. if (!isReorder || isTeleportDisabled(props)) {
  5984. // Teleport has either Array children or no children.
  5985. if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
  5986. for (let i = 0; i < children.length; i++) {
  5987. move(children[i], container, parentAnchor, 2 /* REORDER */);
  5988. }
  5989. }
  5990. }
  5991. // move main view anchor if this is a re-order.
  5992. if (isReorder) {
  5993. insert(anchor, container, parentAnchor);
  5994. }
  5995. }
  5996. function hydrateTeleport(node, vnode, parentComponent, parentSuspense, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
  5997. const target = (vnode.target = resolveTarget(vnode.props, querySelector));
  5998. if (target) {
  5999. // if multiple teleports rendered to the same target element, we need to
  6000. // pick up from where the last teleport finished instead of the first node
  6001. const targetNode = target._lpa || target.firstChild;
  6002. if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
  6003. if (isTeleportDisabled(vnode.props)) {
  6004. vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, optimized);
  6005. vnode.targetAnchor = targetNode;
  6006. }
  6007. else {
  6008. vnode.anchor = nextSibling(node);
  6009. vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, optimized);
  6010. }
  6011. target._lpa =
  6012. vnode.targetAnchor && nextSibling(vnode.targetAnchor);
  6013. }
  6014. }
  6015. return vnode.anchor && nextSibling(vnode.anchor);
  6016. }
  6017. // Force-casted public typing for h and TSX props inference
  6018. const Teleport = TeleportImpl;
  6019. const COMPONENTS = 'components';
  6020. const DIRECTIVES = 'directives';
  6021. /**
  6022. * @private
  6023. */
  6024. function resolveComponent(name) {
  6025. return resolveAsset(COMPONENTS, name) || name;
  6026. }
  6027. const NULL_DYNAMIC_COMPONENT = Symbol();
  6028. /**
  6029. * @private
  6030. */
  6031. function resolveDynamicComponent(component) {
  6032. if (isString(component)) {
  6033. return resolveAsset(COMPONENTS, component, false) || component;
  6034. }
  6035. else {
  6036. // invalid types will fallthrough to createVNode and raise warning
  6037. return (component || NULL_DYNAMIC_COMPONENT);
  6038. }
  6039. }
  6040. /**
  6041. * @private
  6042. */
  6043. function resolveDirective(name) {
  6044. return resolveAsset(DIRECTIVES, name);
  6045. }
  6046. // implementation
  6047. function resolveAsset(type, name, warnMissing = true) {
  6048. const instance = currentRenderingInstance || currentInstance;
  6049. if (instance) {
  6050. const Component = instance.type;
  6051. // self name has highest priority
  6052. if (type === COMPONENTS) {
  6053. const selfName = Component.displayName || Component.name;
  6054. if (selfName &&
  6055. (selfName === name ||
  6056. selfName === camelize(name) ||
  6057. selfName === capitalize(camelize(name)))) {
  6058. return Component;
  6059. }
  6060. }
  6061. const res =
  6062. // local registration
  6063. // check instance[type] first for components with mixin or extends.
  6064. resolve(instance[type] || Component[type], name) ||
  6065. // global registration
  6066. resolve(instance.appContext[type], name);
  6067. if ( warnMissing && !res) {
  6068. warn(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
  6069. }
  6070. return res;
  6071. }
  6072. else {
  6073. warn(`resolve${capitalize(type.slice(0, -1))} ` +
  6074. `can only be used in render() or setup().`);
  6075. }
  6076. }
  6077. function resolve(registry, name) {
  6078. return (registry &&
  6079. (registry[name] ||
  6080. registry[camelize(name)] ||
  6081. registry[capitalize(camelize(name))]));
  6082. }
  6083. const Fragment = Symbol( 'Fragment' );
  6084. const Text = Symbol( 'Text' );
  6085. const Comment = Symbol( 'Comment' );
  6086. const Static = Symbol( 'Static' );
  6087. // Since v-if and v-for are the two possible ways node structure can dynamically
  6088. // change, once we consider v-if branches and each v-for fragment a block, we
  6089. // can divide a template into nested blocks, and within each block the node
  6090. // structure would be stable. This allows us to skip most children diffing
  6091. // and only worry about the dynamic nodes (indicated by patch flags).
  6092. const blockStack = [];
  6093. let currentBlock = null;
  6094. /**
  6095. * Open a block.
  6096. * This must be called before `createBlock`. It cannot be part of `createBlock`
  6097. * because the children of the block are evaluated before `createBlock` itself
  6098. * is called. The generated code typically looks like this:
  6099. *
  6100. * ```js
  6101. * function render() {
  6102. * return (openBlock(),createBlock('div', null, [...]))
  6103. * }
  6104. * ```
  6105. * disableTracking is true when creating a v-for fragment block, since a v-for
  6106. * fragment always diffs its children.
  6107. *
  6108. * @private
  6109. */
  6110. function openBlock(disableTracking = false) {
  6111. blockStack.push((currentBlock = disableTracking ? null : []));
  6112. }
  6113. function closeBlock() {
  6114. blockStack.pop();
  6115. currentBlock = blockStack[blockStack.length - 1] || null;
  6116. }
  6117. // Whether we should be tracking dynamic child nodes inside a block.
  6118. // Only tracks when this value is > 0
  6119. // We are not using a simple boolean because this value may need to be
  6120. // incremented/decremented by nested usage of v-once (see below)
  6121. let shouldTrack$1 = 1;
  6122. /**
  6123. * Block tracking sometimes needs to be disabled, for example during the
  6124. * creation of a tree that needs to be cached by v-once. The compiler generates
  6125. * code like this:
  6126. *
  6127. * ``` js
  6128. * _cache[1] || (
  6129. * setBlockTracking(-1),
  6130. * _cache[1] = createVNode(...),
  6131. * setBlockTracking(1),
  6132. * _cache[1]
  6133. * )
  6134. * ```
  6135. *
  6136. * @private
  6137. */
  6138. function setBlockTracking(value) {
  6139. shouldTrack$1 += value;
  6140. }
  6141. /**
  6142. * Create a block root vnode. Takes the same exact arguments as `createVNode`.
  6143. * A block root keeps track of dynamic nodes within the block in the
  6144. * `dynamicChildren` array.
  6145. *
  6146. * @private
  6147. */
  6148. function createBlock(type, props, children, patchFlag, dynamicProps) {
  6149. const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */);
  6150. // save current block children on the block vnode
  6151. vnode.dynamicChildren = currentBlock || EMPTY_ARR;
  6152. // close block
  6153. closeBlock();
  6154. // a block is always going to be patched, so track it as a child of its
  6155. // parent block
  6156. if (shouldTrack$1 > 0 && currentBlock) {
  6157. currentBlock.push(vnode);
  6158. }
  6159. return vnode;
  6160. }
  6161. function isVNode(value) {
  6162. return value ? value.__v_isVNode === true : false;
  6163. }
  6164. function isSameVNodeType(n1, n2) {
  6165. if (
  6166. n2.shapeFlag & 6 /* COMPONENT */ &&
  6167. hmrDirtyComponents.has(n2.type)) {
  6168. // HMR only: if the component has been hot-updated, force a reload.
  6169. return false;
  6170. }
  6171. return n1.type === n2.type && n1.key === n2.key;
  6172. }
  6173. let vnodeArgsTransformer;
  6174. /**
  6175. * Internal API for registering an arguments transform for createVNode
  6176. * used for creating stubs in the test-utils
  6177. * It is *internal* but needs to be exposed for test-utils to pick up proper
  6178. * typings
  6179. */
  6180. function transformVNodeArgs(transformer) {
  6181. vnodeArgsTransformer = transformer;
  6182. }
  6183. const createVNodeWithArgsTransform = (...args) => {
  6184. return _createVNode(...(vnodeArgsTransformer
  6185. ? vnodeArgsTransformer(args, currentRenderingInstance)
  6186. : args));
  6187. };
  6188. const InternalObjectKey = `__vInternal`;
  6189. const normalizeKey = ({ key }) => key != null ? key : null;
  6190. const normalizeRef = ({ ref }) => {
  6191. return (ref != null
  6192. ? isArray(ref)
  6193. ? ref
  6194. : { i: currentRenderingInstance, r: ref }
  6195. : null);
  6196. };
  6197. const createVNode = ( createVNodeWithArgsTransform
  6198. );
  6199. function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
  6200. if (!type || type === NULL_DYNAMIC_COMPONENT) {
  6201. if ( !type) {
  6202. warn(`Invalid vnode type when creating vnode: ${type}.`);
  6203. }
  6204. type = Comment;
  6205. }
  6206. if (isVNode(type)) {
  6207. // createVNode receiving an existing vnode. This happens in cases like
  6208. // <component :is="vnode"/>
  6209. // #2078 make sure to merge refs during the clone instead of overwriting it
  6210. const cloned = cloneVNode(type, props, true /* mergeRef: true */);
  6211. if (children) {
  6212. normalizeChildren(cloned, children);
  6213. }
  6214. return cloned;
  6215. }
  6216. // class component normalization.
  6217. if (isClassComponent(type)) {
  6218. type = type.__vccOpts;
  6219. }
  6220. // class & style normalization.
  6221. if (props) {
  6222. // for reactive or proxy objects, we need to clone it to enable mutation.
  6223. if (isProxy(props) || InternalObjectKey in props) {
  6224. props = extend({}, props);
  6225. }
  6226. let { class: klass, style } = props;
  6227. if (klass && !isString(klass)) {
  6228. props.class = normalizeClass(klass);
  6229. }
  6230. if (isObject(style)) {
  6231. // reactive state objects need to be cloned since they are likely to be
  6232. // mutated
  6233. if (isProxy(style) && !isArray(style)) {
  6234. style = extend({}, style);
  6235. }
  6236. props.style = normalizeStyle(style);
  6237. }
  6238. }
  6239. // encode the vnode type information into a bitmap
  6240. const shapeFlag = isString(type)
  6241. ? 1 /* ELEMENT */
  6242. : isSuspense(type)
  6243. ? 128 /* SUSPENSE */
  6244. : isTeleport(type)
  6245. ? 64 /* TELEPORT */
  6246. : isObject(type)
  6247. ? 4 /* STATEFUL_COMPONENT */
  6248. : isFunction(type)
  6249. ? 2 /* FUNCTIONAL_COMPONENT */
  6250. : 0;
  6251. if ( shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
  6252. type = toRaw(type);
  6253. warn(`Vue received a Component which was made a reactive object. This can ` +
  6254. `lead to unnecessary performance overhead, and should be avoided by ` +
  6255. `marking the component with \`markRaw\` or using \`shallowRef\` ` +
  6256. `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
  6257. }
  6258. const vnode = {
  6259. __v_isVNode: true,
  6260. ["__v_skip" /* SKIP */]: true,
  6261. type,
  6262. props,
  6263. key: props && normalizeKey(props),
  6264. ref: props && normalizeRef(props),
  6265. scopeId: currentScopeId,
  6266. children: null,
  6267. component: null,
  6268. suspense: null,
  6269. ssContent: null,
  6270. ssFallback: null,
  6271. dirs: null,
  6272. transition: null,
  6273. el: null,
  6274. anchor: null,
  6275. target: null,
  6276. targetAnchor: null,
  6277. staticCount: 0,
  6278. shapeFlag,
  6279. patchFlag,
  6280. dynamicProps,
  6281. dynamicChildren: null,
  6282. appContext: null
  6283. };
  6284. // validate key
  6285. if ( vnode.key !== vnode.key) {
  6286. warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
  6287. }
  6288. normalizeChildren(vnode, children);
  6289. // normalize suspense children
  6290. if ( shapeFlag & 128 /* SUSPENSE */) {
  6291. const { content, fallback } = normalizeSuspenseChildren(vnode);
  6292. vnode.ssContent = content;
  6293. vnode.ssFallback = fallback;
  6294. }
  6295. if (shouldTrack$1 > 0 &&
  6296. // avoid a block node from tracking itself
  6297. !isBlockNode &&
  6298. // has current parent block
  6299. currentBlock &&
  6300. // presence of a patch flag indicates this node needs patching on updates.
  6301. // component nodes also should always be patched, because even if the
  6302. // component doesn't need to update, it needs to persist the instance on to
  6303. // the next vnode so that it can be properly unmounted later.
  6304. (patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
  6305. // the EVENTS flag is only for hydration and if it is the only flag, the
  6306. // vnode should not be considered dynamic due to handler caching.
  6307. patchFlag !== 32 /* HYDRATE_EVENTS */) {
  6308. currentBlock.push(vnode);
  6309. }
  6310. return vnode;
  6311. }
  6312. function cloneVNode(vnode, extraProps, mergeRef = false) {
  6313. // This is intentionally NOT using spread or extend to avoid the runtime
  6314. // key enumeration cost.
  6315. const { props, ref, patchFlag } = vnode;
  6316. const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
  6317. return {
  6318. __v_isVNode: true,
  6319. ["__v_skip" /* SKIP */]: true,
  6320. type: vnode.type,
  6321. props: mergedProps,
  6322. key: mergedProps && normalizeKey(mergedProps),
  6323. ref: extraProps && extraProps.ref
  6324. ? // #2078 in the case of <component :is="vnode" ref="extra"/>
  6325. // if the vnode itself already has a ref, cloneVNode will need to merge
  6326. // the refs so the single vnode can be set on multiple refs
  6327. mergeRef && ref
  6328. ? isArray(ref)
  6329. ? ref.concat(normalizeRef(extraProps))
  6330. : [ref, normalizeRef(extraProps)]
  6331. : normalizeRef(extraProps)
  6332. : ref,
  6333. scopeId: vnode.scopeId,
  6334. children: vnode.children,
  6335. target: vnode.target,
  6336. targetAnchor: vnode.targetAnchor,
  6337. staticCount: vnode.staticCount,
  6338. shapeFlag: vnode.shapeFlag,
  6339. // if the vnode is cloned with extra props, we can no longer assume its
  6340. // existing patch flag to be reliable and need to add the FULL_PROPS flag.
  6341. // note: perserve flag for fragments since they use the flag for children
  6342. // fast paths only.
  6343. patchFlag: extraProps && vnode.type !== Fragment
  6344. ? patchFlag === -1 // hoisted node
  6345. ? 16 /* FULL_PROPS */
  6346. : patchFlag | 16 /* FULL_PROPS */
  6347. : patchFlag,
  6348. dynamicProps: vnode.dynamicProps,
  6349. dynamicChildren: vnode.dynamicChildren,
  6350. appContext: vnode.appContext,
  6351. dirs: vnode.dirs,
  6352. transition: vnode.transition,
  6353. // These should technically only be non-null on mounted VNodes. However,
  6354. // they *should* be copied for kept-alive vnodes. So we just always copy
  6355. // them since them being non-null during a mount doesn't affect the logic as
  6356. // they will simply be overwritten.
  6357. component: vnode.component,
  6358. suspense: vnode.suspense,
  6359. ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
  6360. ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
  6361. el: vnode.el,
  6362. anchor: vnode.anchor
  6363. };
  6364. }
  6365. /**
  6366. * @private
  6367. */
  6368. function createTextVNode(text = ' ', flag = 0) {
  6369. return createVNode(Text, null, text, flag);
  6370. }
  6371. /**
  6372. * @private
  6373. */
  6374. function createStaticVNode(content, numberOfNodes) {
  6375. // A static vnode can contain multiple stringified elements, and the number
  6376. // of elements is necessary for hydration.
  6377. const vnode = createVNode(Static, null, content);
  6378. vnode.staticCount = numberOfNodes;
  6379. return vnode;
  6380. }
  6381. /**
  6382. * @private
  6383. */
  6384. function createCommentVNode(text = '',
  6385. // when used as the v-else branch, the comment node must be created as a
  6386. // block to ensure correct updates.
  6387. asBlock = false) {
  6388. return asBlock
  6389. ? (openBlock(), createBlock(Comment, null, text))
  6390. : createVNode(Comment, null, text);
  6391. }
  6392. function normalizeVNode(child) {
  6393. if (child == null || typeof child === 'boolean') {
  6394. // empty placeholder
  6395. return createVNode(Comment);
  6396. }
  6397. else if (isArray(child)) {
  6398. // fragment
  6399. return createVNode(Fragment, null, child);
  6400. }
  6401. else if (typeof child === 'object') {
  6402. // already vnode, this should be the most common since compiled templates
  6403. // always produce all-vnode children arrays
  6404. return child.el === null ? child : cloneVNode(child);
  6405. }
  6406. else {
  6407. // strings and numbers
  6408. return createVNode(Text, null, String(child));
  6409. }
  6410. }
  6411. // optimized normalization for template-compiled render fns
  6412. function cloneIfMounted(child) {
  6413. return child.el === null ? child : cloneVNode(child);
  6414. }
  6415. function normalizeChildren(vnode, children) {
  6416. let type = 0;
  6417. const { shapeFlag } = vnode;
  6418. if (children == null) {
  6419. children = null;
  6420. }
  6421. else if (isArray(children)) {
  6422. type = 16 /* ARRAY_CHILDREN */;
  6423. }
  6424. else if (typeof children === 'object') {
  6425. if (shapeFlag & 1 /* ELEMENT */ || shapeFlag & 64 /* TELEPORT */) {
  6426. // Normalize slot to plain children for plain element and Teleport
  6427. const slot = children.default;
  6428. if (slot) {
  6429. // _c marker is added by withCtx() indicating this is a compiled slot
  6430. slot._c && setCompiledSlotRendering(1);
  6431. normalizeChildren(vnode, slot());
  6432. slot._c && setCompiledSlotRendering(-1);
  6433. }
  6434. return;
  6435. }
  6436. else {
  6437. type = 32 /* SLOTS_CHILDREN */;
  6438. const slotFlag = children._;
  6439. if (!slotFlag && !(InternalObjectKey in children)) {
  6440. children._ctx = currentRenderingInstance;
  6441. }
  6442. else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
  6443. // a child component receives forwarded slots from the parent.
  6444. // its slot type is determined by its parent's slot type.
  6445. if (currentRenderingInstance.vnode.patchFlag & 1024 /* DYNAMIC_SLOTS */) {
  6446. children._ = 2 /* DYNAMIC */;
  6447. vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  6448. }
  6449. else {
  6450. children._ = 1 /* STABLE */;
  6451. }
  6452. }
  6453. }
  6454. }
  6455. else if (isFunction(children)) {
  6456. children = { default: children, _ctx: currentRenderingInstance };
  6457. type = 32 /* SLOTS_CHILDREN */;
  6458. }
  6459. else {
  6460. children = String(children);
  6461. // force teleport children to array so it can be moved around
  6462. if (shapeFlag & 64 /* TELEPORT */) {
  6463. type = 16 /* ARRAY_CHILDREN */;
  6464. children = [createTextVNode(children)];
  6465. }
  6466. else {
  6467. type = 8 /* TEXT_CHILDREN */;
  6468. }
  6469. }
  6470. vnode.children = children;
  6471. vnode.shapeFlag |= type;
  6472. }
  6473. function mergeProps(...args) {
  6474. const ret = extend({}, args[0]);
  6475. for (let i = 1; i < args.length; i++) {
  6476. const toMerge = args[i];
  6477. for (const key in toMerge) {
  6478. if (key === 'class') {
  6479. if (ret.class !== toMerge.class) {
  6480. ret.class = normalizeClass([ret.class, toMerge.class]);
  6481. }
  6482. }
  6483. else if (key === 'style') {
  6484. ret.style = normalizeStyle([ret.style, toMerge.style]);
  6485. }
  6486. else if (isOn(key)) {
  6487. const existing = ret[key];
  6488. const incoming = toMerge[key];
  6489. if (existing !== incoming) {
  6490. ret[key] = existing
  6491. ? [].concat(existing, toMerge[key])
  6492. : incoming;
  6493. }
  6494. }
  6495. else if (key !== '') {
  6496. ret[key] = toMerge[key];
  6497. }
  6498. }
  6499. }
  6500. return ret;
  6501. }
  6502. function provide(key, value) {
  6503. if (!currentInstance) {
  6504. {
  6505. warn(`provide() can only be used inside setup().`);
  6506. }
  6507. }
  6508. else {
  6509. let provides = currentInstance.provides;
  6510. // by default an instance inherits its parent's provides object
  6511. // but when it needs to provide values of its own, it creates its
  6512. // own provides object using parent provides object as prototype.
  6513. // this way in `inject` we can simply look up injections from direct
  6514. // parent and let the prototype chain do the work.
  6515. const parentProvides = currentInstance.parent && currentInstance.parent.provides;
  6516. if (parentProvides === provides) {
  6517. provides = currentInstance.provides = Object.create(parentProvides);
  6518. }
  6519. // TS doesn't allow symbol as index type
  6520. provides[key] = value;
  6521. }
  6522. }
  6523. function inject(key, defaultValue, treatDefaultAsFactory = false) {
  6524. // fallback to `currentRenderingInstance` so that this can be called in
  6525. // a functional component
  6526. const instance = currentInstance || currentRenderingInstance;
  6527. if (instance) {
  6528. // #2400
  6529. // to support `app.use` plugins,
  6530. // fallback to appContext's `provides` if the intance is at root
  6531. const provides = instance.parent == null
  6532. ? instance.vnode.appContext && instance.vnode.appContext.provides
  6533. : instance.parent.provides;
  6534. if (provides && key in provides) {
  6535. // TS doesn't allow symbol as index type
  6536. return provides[key];
  6537. }
  6538. else if (arguments.length > 1) {
  6539. return treatDefaultAsFactory && isFunction(defaultValue)
  6540. ? defaultValue()
  6541. : defaultValue;
  6542. }
  6543. else {
  6544. warn(`injection "${String(key)}" not found.`);
  6545. }
  6546. }
  6547. else {
  6548. warn(`inject() can only be used inside setup() or functional components.`);
  6549. }
  6550. }
  6551. function createDuplicateChecker() {
  6552. const cache = Object.create(null);
  6553. return (type, key) => {
  6554. if (cache[key]) {
  6555. warn(`${type} property "${key}" is already defined in ${cache[key]}.`);
  6556. }
  6557. else {
  6558. cache[key] = type;
  6559. }
  6560. };
  6561. }
  6562. let isInBeforeCreate = false;
  6563. function applyOptions(instance, options, deferredData = [], deferredWatch = [], deferredProvide = [], asMixin = false) {
  6564. const {
  6565. // composition
  6566. mixins, extends: extendsOptions,
  6567. // state
  6568. data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
  6569. // assets
  6570. components, directives,
  6571. // lifecycle
  6572. beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured } = options;
  6573. const publicThis = instance.proxy;
  6574. const ctx = instance.ctx;
  6575. const globalMixins = instance.appContext.mixins;
  6576. if (asMixin && render && instance.render === NOOP) {
  6577. instance.render = render;
  6578. }
  6579. // applyOptions is called non-as-mixin once per instance
  6580. if (!asMixin) {
  6581. isInBeforeCreate = true;
  6582. callSyncHook('beforeCreate', "bc" /* BEFORE_CREATE */, options, instance, globalMixins);
  6583. isInBeforeCreate = false;
  6584. // global mixins are applied first
  6585. applyMixins(instance, globalMixins, deferredData, deferredWatch, deferredProvide);
  6586. }
  6587. // extending a base component...
  6588. if (extendsOptions) {
  6589. applyOptions(instance, extendsOptions, deferredData, deferredWatch, deferredProvide, true);
  6590. }
  6591. // local mixins
  6592. if (mixins) {
  6593. applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide);
  6594. }
  6595. const checkDuplicateProperties = createDuplicateChecker() ;
  6596. {
  6597. const [propsOptions] = instance.propsOptions;
  6598. if (propsOptions) {
  6599. for (const key in propsOptions) {
  6600. checkDuplicateProperties("Props" /* PROPS */, key);
  6601. }
  6602. }
  6603. }
  6604. // options initialization order (to be consistent with Vue 2):
  6605. // - props (already done outside of this function)
  6606. // - inject
  6607. // - methods
  6608. // - data (deferred since it relies on `this` access)
  6609. // - computed
  6610. // - watch (deferred since it relies on `this` access)
  6611. if (injectOptions) {
  6612. if (isArray(injectOptions)) {
  6613. for (let i = 0; i < injectOptions.length; i++) {
  6614. const key = injectOptions[i];
  6615. ctx[key] = inject(key);
  6616. {
  6617. checkDuplicateProperties("Inject" /* INJECT */, key);
  6618. }
  6619. }
  6620. }
  6621. else {
  6622. for (const key in injectOptions) {
  6623. const opt = injectOptions[key];
  6624. if (isObject(opt)) {
  6625. ctx[key] = inject(opt.from || key, opt.default, true /* treat default function as factory */);
  6626. }
  6627. else {
  6628. ctx[key] = inject(opt);
  6629. }
  6630. {
  6631. checkDuplicateProperties("Inject" /* INJECT */, key);
  6632. }
  6633. }
  6634. }
  6635. }
  6636. if (methods) {
  6637. for (const key in methods) {
  6638. const methodHandler = methods[key];
  6639. if (isFunction(methodHandler)) {
  6640. ctx[key] = methodHandler.bind(publicThis);
  6641. {
  6642. checkDuplicateProperties("Methods" /* METHODS */, key);
  6643. }
  6644. }
  6645. else {
  6646. warn(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
  6647. `Did you reference the function correctly?`);
  6648. }
  6649. }
  6650. }
  6651. if (!asMixin) {
  6652. if (deferredData.length) {
  6653. deferredData.forEach(dataFn => resolveData(instance, dataFn, publicThis));
  6654. }
  6655. if (dataOptions) {
  6656. resolveData(instance, dataOptions, publicThis);
  6657. }
  6658. {
  6659. const rawData = toRaw(instance.data);
  6660. for (const key in rawData) {
  6661. checkDuplicateProperties("Data" /* DATA */, key);
  6662. // expose data on ctx during dev
  6663. if (key[0] !== '$' && key[0] !== '_') {
  6664. Object.defineProperty(ctx, key, {
  6665. configurable: true,
  6666. enumerable: true,
  6667. get: () => rawData[key],
  6668. set: NOOP
  6669. });
  6670. }
  6671. }
  6672. }
  6673. }
  6674. else if (dataOptions) {
  6675. deferredData.push(dataOptions);
  6676. }
  6677. if (computedOptions) {
  6678. for (const key in computedOptions) {
  6679. const opt = computedOptions[key];
  6680. const get = isFunction(opt)
  6681. ? opt.bind(publicThis, publicThis)
  6682. : isFunction(opt.get)
  6683. ? opt.get.bind(publicThis, publicThis)
  6684. : NOOP;
  6685. if ( get === NOOP) {
  6686. warn(`Computed property "${key}" has no getter.`);
  6687. }
  6688. const set = !isFunction(opt) && isFunction(opt.set)
  6689. ? opt.set.bind(publicThis)
  6690. : () => {
  6691. warn(`Write operation failed: computed property "${key}" is readonly.`);
  6692. }
  6693. ;
  6694. const c = computed$1({
  6695. get,
  6696. set
  6697. });
  6698. Object.defineProperty(ctx, key, {
  6699. enumerable: true,
  6700. configurable: true,
  6701. get: () => c.value,
  6702. set: v => (c.value = v)
  6703. });
  6704. {
  6705. checkDuplicateProperties("Computed" /* COMPUTED */, key);
  6706. }
  6707. }
  6708. }
  6709. if (watchOptions) {
  6710. deferredWatch.push(watchOptions);
  6711. }
  6712. if (!asMixin && deferredWatch.length) {
  6713. deferredWatch.forEach(watchOptions => {
  6714. for (const key in watchOptions) {
  6715. createWatcher(watchOptions[key], ctx, publicThis, key);
  6716. }
  6717. });
  6718. }
  6719. if (provideOptions) {
  6720. deferredProvide.push(provideOptions);
  6721. }
  6722. if (!asMixin && deferredProvide.length) {
  6723. deferredProvide.forEach(provideOptions => {
  6724. const provides = isFunction(provideOptions)
  6725. ? provideOptions.call(publicThis)
  6726. : provideOptions;
  6727. for (const key in provides) {
  6728. provide(key, provides[key]);
  6729. }
  6730. });
  6731. }
  6732. // asset options.
  6733. // To reduce memory usage, only components with mixins or extends will have
  6734. // resolved asset registry attached to instance.
  6735. if (asMixin) {
  6736. if (components) {
  6737. extend(instance.components ||
  6738. (instance.components = extend({}, instance.type.components)), components);
  6739. }
  6740. if (directives) {
  6741. extend(instance.directives ||
  6742. (instance.directives = extend({}, instance.type.directives)), directives);
  6743. }
  6744. }
  6745. // lifecycle options
  6746. if (!asMixin) {
  6747. callSyncHook('created', "c" /* CREATED */, options, instance, globalMixins);
  6748. }
  6749. if (beforeMount) {
  6750. onBeforeMount(beforeMount.bind(publicThis));
  6751. }
  6752. if (mounted) {
  6753. onMounted(mounted.bind(publicThis));
  6754. }
  6755. if (beforeUpdate) {
  6756. onBeforeUpdate(beforeUpdate.bind(publicThis));
  6757. }
  6758. if (updated) {
  6759. onUpdated(updated.bind(publicThis));
  6760. }
  6761. if (activated) {
  6762. onActivated(activated.bind(publicThis));
  6763. }
  6764. if (deactivated) {
  6765. onDeactivated(deactivated.bind(publicThis));
  6766. }
  6767. if (errorCaptured) {
  6768. onErrorCaptured(errorCaptured.bind(publicThis));
  6769. }
  6770. if (renderTracked) {
  6771. onRenderTracked(renderTracked.bind(publicThis));
  6772. }
  6773. if (renderTriggered) {
  6774. onRenderTriggered(renderTriggered.bind(publicThis));
  6775. }
  6776. if ( beforeDestroy) {
  6777. warn(`\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`);
  6778. }
  6779. if (beforeUnmount) {
  6780. onBeforeUnmount(beforeUnmount.bind(publicThis));
  6781. }
  6782. if ( destroyed) {
  6783. warn(`\`destroyed\` has been renamed to \`unmounted\`.`);
  6784. }
  6785. if (unmounted) {
  6786. onUnmounted(unmounted.bind(publicThis));
  6787. }
  6788. }
  6789. function callSyncHook(name, type, options, instance, globalMixins) {
  6790. callHookFromMixins(name, type, globalMixins, instance);
  6791. const { extends: base, mixins } = options;
  6792. if (base) {
  6793. callHookFromExtends(name, type, base, instance);
  6794. }
  6795. if (mixins) {
  6796. callHookFromMixins(name, type, mixins, instance);
  6797. }
  6798. const selfHook = options[name];
  6799. if (selfHook) {
  6800. callWithAsyncErrorHandling(selfHook.bind(instance.proxy), instance, type);
  6801. }
  6802. }
  6803. function callHookFromExtends(name, type, base, instance) {
  6804. if (base.extends) {
  6805. callHookFromExtends(name, type, base.extends, instance);
  6806. }
  6807. const baseHook = base[name];
  6808. if (baseHook) {
  6809. callWithAsyncErrorHandling(baseHook.bind(instance.proxy), instance, type);
  6810. }
  6811. }
  6812. function callHookFromMixins(name, type, mixins, instance) {
  6813. for (let i = 0; i < mixins.length; i++) {
  6814. const chainedMixins = mixins[i].mixins;
  6815. if (chainedMixins) {
  6816. callHookFromMixins(name, type, chainedMixins, instance);
  6817. }
  6818. const fn = mixins[i][name];
  6819. if (fn) {
  6820. callWithAsyncErrorHandling(fn.bind(instance.proxy), instance, type);
  6821. }
  6822. }
  6823. }
  6824. function applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide) {
  6825. for (let i = 0; i < mixins.length; i++) {
  6826. applyOptions(instance, mixins[i], deferredData, deferredWatch, deferredProvide, true);
  6827. }
  6828. }
  6829. function resolveData(instance, dataFn, publicThis) {
  6830. if ( !isFunction(dataFn)) {
  6831. warn(`The data option must be a function. ` +
  6832. `Plain object usage is no longer supported.`);
  6833. }
  6834. const data = dataFn.call(publicThis, publicThis);
  6835. if ( isPromise(data)) {
  6836. warn(`data() returned a Promise - note data() cannot be async; If you ` +
  6837. `intend to perform data fetching before component renders, use ` +
  6838. `async setup() + <Suspense>.`);
  6839. }
  6840. if (!isObject(data)) {
  6841. warn(`data() should return an object.`);
  6842. }
  6843. else if (instance.data === EMPTY_OBJ) {
  6844. instance.data = reactive(data);
  6845. }
  6846. else {
  6847. // existing data: this is a mixin or extends.
  6848. extend(instance.data, data);
  6849. }
  6850. }
  6851. function createWatcher(raw, ctx, publicThis, key) {
  6852. const getter = key.includes('.')
  6853. ? createPathGetter(publicThis, key)
  6854. : () => publicThis[key];
  6855. if (isString(raw)) {
  6856. const handler = ctx[raw];
  6857. if (isFunction(handler)) {
  6858. watch(getter, handler);
  6859. }
  6860. else {
  6861. warn(`Invalid watch handler specified by key "${raw}"`, handler);
  6862. }
  6863. }
  6864. else if (isFunction(raw)) {
  6865. watch(getter, raw.bind(publicThis));
  6866. }
  6867. else if (isObject(raw)) {
  6868. if (isArray(raw)) {
  6869. raw.forEach(r => createWatcher(r, ctx, publicThis, key));
  6870. }
  6871. else {
  6872. const handler = isFunction(raw.handler)
  6873. ? raw.handler.bind(publicThis)
  6874. : ctx[raw.handler];
  6875. if (isFunction(handler)) {
  6876. watch(getter, handler, raw);
  6877. }
  6878. else {
  6879. warn(`Invalid watch handler specified by key "${raw.handler}"`, handler);
  6880. }
  6881. }
  6882. }
  6883. else {
  6884. warn(`Invalid watch option: "${key}"`, raw);
  6885. }
  6886. }
  6887. function createPathGetter(ctx, path) {
  6888. const segments = path.split('.');
  6889. return () => {
  6890. let cur = ctx;
  6891. for (let i = 0; i < segments.length && cur; i++) {
  6892. cur = cur[segments[i]];
  6893. }
  6894. return cur;
  6895. };
  6896. }
  6897. function resolveMergedOptions(instance) {
  6898. const raw = instance.type;
  6899. const { __merged, mixins, extends: extendsOptions } = raw;
  6900. if (__merged)
  6901. return __merged;
  6902. const globalMixins = instance.appContext.mixins;
  6903. if (!globalMixins.length && !mixins && !extendsOptions)
  6904. return raw;
  6905. const options = {};
  6906. globalMixins.forEach(m => mergeOptions(options, m, instance));
  6907. mergeOptions(options, raw, instance);
  6908. return (raw.__merged = options);
  6909. }
  6910. function mergeOptions(to, from, instance) {
  6911. const strats = instance.appContext.config.optionMergeStrategies;
  6912. const { mixins, extends: extendsOptions } = from;
  6913. extendsOptions && mergeOptions(to, extendsOptions, instance);
  6914. mixins &&
  6915. mixins.forEach((m) => mergeOptions(to, m, instance));
  6916. for (const key in from) {
  6917. if (strats && hasOwn(strats, key)) {
  6918. to[key] = strats[key](to[key], from[key], instance.proxy, key);
  6919. }
  6920. else {
  6921. to[key] = from[key];
  6922. }
  6923. }
  6924. }
  6925. const publicPropertiesMap = extend(Object.create(null), {
  6926. $: i => i,
  6927. $el: i => i.vnode.el,
  6928. $data: i => i.data,
  6929. $props: i => ( shallowReadonly(i.props) ),
  6930. $attrs: i => ( shallowReadonly(i.attrs) ),
  6931. $slots: i => ( shallowReadonly(i.slots) ),
  6932. $refs: i => ( shallowReadonly(i.refs) ),
  6933. $parent: i => i.parent && i.parent.proxy,
  6934. $root: i => i.root && i.root.proxy,
  6935. $emit: i => i.emit,
  6936. $options: i => ( resolveMergedOptions(i) ),
  6937. $forceUpdate: i => () => queueJob(i.update),
  6938. $nextTick: i => nextTick.bind(i.proxy),
  6939. $watch: i => ( instanceWatch.bind(i) )
  6940. });
  6941. const PublicInstanceProxyHandlers = {
  6942. get({ _: instance }, key) {
  6943. const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
  6944. // let @vue/reactivity know it should never observe Vue public instances.
  6945. if (key === "__v_skip" /* SKIP */) {
  6946. return true;
  6947. }
  6948. // for internal formatters to know that this is a Vue instance
  6949. if ( key === '__isVue') {
  6950. return true;
  6951. }
  6952. // data / props / ctx
  6953. // This getter gets called for every property access on the render context
  6954. // during render and is a major hotspot. The most expensive part of this
  6955. // is the multiple hasOwn() calls. It's much faster to do a simple property
  6956. // access on a plain object, so we use an accessCache object (with null
  6957. // prototype) to memoize what access type a key corresponds to.
  6958. let normalizedProps;
  6959. if (key[0] !== '$') {
  6960. const n = accessCache[key];
  6961. if (n !== undefined) {
  6962. switch (n) {
  6963. case 0 /* SETUP */:
  6964. return setupState[key];
  6965. case 1 /* DATA */:
  6966. return data[key];
  6967. case 3 /* CONTEXT */:
  6968. return ctx[key];
  6969. case 2 /* PROPS */:
  6970. return props[key];
  6971. // default: just fallthrough
  6972. }
  6973. }
  6974. else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  6975. accessCache[key] = 0 /* SETUP */;
  6976. return setupState[key];
  6977. }
  6978. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  6979. accessCache[key] = 1 /* DATA */;
  6980. return data[key];
  6981. }
  6982. else if (
  6983. // only cache other properties when instance has declared (thus stable)
  6984. // props
  6985. (normalizedProps = instance.propsOptions[0]) &&
  6986. hasOwn(normalizedProps, key)) {
  6987. accessCache[key] = 2 /* PROPS */;
  6988. return props[key];
  6989. }
  6990. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  6991. accessCache[key] = 3 /* CONTEXT */;
  6992. return ctx[key];
  6993. }
  6994. else if ( !isInBeforeCreate) {
  6995. accessCache[key] = 4 /* OTHER */;
  6996. }
  6997. }
  6998. const publicGetter = publicPropertiesMap[key];
  6999. let cssModule, globalProperties;
  7000. // public $xxx properties
  7001. if (publicGetter) {
  7002. if (key === '$attrs') {
  7003. track(instance, "get" /* GET */, key);
  7004. markAttrsAccessed();
  7005. }
  7006. return publicGetter(instance);
  7007. }
  7008. else if (
  7009. // css module (injected by vue-loader)
  7010. (cssModule = type.__cssModules) &&
  7011. (cssModule = cssModule[key])) {
  7012. return cssModule;
  7013. }
  7014. else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
  7015. // user may set custom properties to `this` that start with `$`
  7016. accessCache[key] = 3 /* CONTEXT */;
  7017. return ctx[key];
  7018. }
  7019. else if (
  7020. // global properties
  7021. ((globalProperties = appContext.config.globalProperties),
  7022. hasOwn(globalProperties, key))) {
  7023. return globalProperties[key];
  7024. }
  7025. else if (
  7026. currentRenderingInstance &&
  7027. (!isString(key) ||
  7028. // #1091 avoid internal isRef/isVNode checks on component instance leading
  7029. // to infinite warning loop
  7030. key.indexOf('__v') !== 0)) {
  7031. if (data !== EMPTY_OBJ &&
  7032. (key[0] === '$' || key[0] === '_') &&
  7033. hasOwn(data, key)) {
  7034. warn(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
  7035. `character ("$" or "_") and is not proxied on the render context.`);
  7036. }
  7037. else {
  7038. warn(`Property ${JSON.stringify(key)} was accessed during render ` +
  7039. `but is not defined on instance.`);
  7040. }
  7041. }
  7042. },
  7043. set({ _: instance }, key, value) {
  7044. const { data, setupState, ctx } = instance;
  7045. if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
  7046. setupState[key] = value;
  7047. }
  7048. else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
  7049. data[key] = value;
  7050. }
  7051. else if (key in instance.props) {
  7052. warn(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
  7053. return false;
  7054. }
  7055. if (key[0] === '$' && key.slice(1) in instance) {
  7056. warn(`Attempting to mutate public property "${key}". ` +
  7057. `Properties starting with $ are reserved and readonly.`, instance);
  7058. return false;
  7059. }
  7060. else {
  7061. if ( key in instance.appContext.config.globalProperties) {
  7062. Object.defineProperty(ctx, key, {
  7063. enumerable: true,
  7064. configurable: true,
  7065. value
  7066. });
  7067. }
  7068. else {
  7069. ctx[key] = value;
  7070. }
  7071. }
  7072. return true;
  7073. },
  7074. has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
  7075. let normalizedProps;
  7076. return (accessCache[key] !== undefined ||
  7077. (data !== EMPTY_OBJ && hasOwn(data, key)) ||
  7078. (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
  7079. ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
  7080. hasOwn(ctx, key) ||
  7081. hasOwn(publicPropertiesMap, key) ||
  7082. hasOwn(appContext.config.globalProperties, key));
  7083. }
  7084. };
  7085. {
  7086. PublicInstanceProxyHandlers.ownKeys = (target) => {
  7087. warn(`Avoid app logic that relies on enumerating keys on a component instance. ` +
  7088. `The keys will be empty in production mode to avoid performance overhead.`);
  7089. return Reflect.ownKeys(target);
  7090. };
  7091. }
  7092. const RuntimeCompiledPublicInstanceProxyHandlers = extend({}, PublicInstanceProxyHandlers, {
  7093. get(target, key) {
  7094. // fast path for unscopables when using `with` block
  7095. if (key === Symbol.unscopables) {
  7096. return;
  7097. }
  7098. return PublicInstanceProxyHandlers.get(target, key, target);
  7099. },
  7100. has(_, key) {
  7101. const has = key[0] !== '_' && !isGloballyWhitelisted(key);
  7102. if ( !has && PublicInstanceProxyHandlers.has(_, key)) {
  7103. warn(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
  7104. }
  7105. return has;
  7106. }
  7107. });
  7108. // In dev mode, the proxy target exposes the same properties as seen on `this`
  7109. // for easier console inspection. In prod mode it will be an empty object so
  7110. // these properties definitions can be skipped.
  7111. function createRenderContext(instance) {
  7112. const target = {};
  7113. // expose internal instance for proxy handlers
  7114. Object.defineProperty(target, `_`, {
  7115. configurable: true,
  7116. enumerable: false,
  7117. get: () => instance
  7118. });
  7119. // expose public properties
  7120. Object.keys(publicPropertiesMap).forEach(key => {
  7121. Object.defineProperty(target, key, {
  7122. configurable: true,
  7123. enumerable: false,
  7124. get: () => publicPropertiesMap[key](instance),
  7125. // intercepted by the proxy so no need for implementation,
  7126. // but needed to prevent set errors
  7127. set: NOOP
  7128. });
  7129. });
  7130. // expose global properties
  7131. const { globalProperties } = instance.appContext.config;
  7132. Object.keys(globalProperties).forEach(key => {
  7133. Object.defineProperty(target, key, {
  7134. configurable: true,
  7135. enumerable: false,
  7136. get: () => globalProperties[key],
  7137. set: NOOP
  7138. });
  7139. });
  7140. return target;
  7141. }
  7142. // dev only
  7143. function exposePropsOnRenderContext(instance) {
  7144. const { ctx, propsOptions: [propsOptions] } = instance;
  7145. if (propsOptions) {
  7146. Object.keys(propsOptions).forEach(key => {
  7147. Object.defineProperty(ctx, key, {
  7148. enumerable: true,
  7149. configurable: true,
  7150. get: () => instance.props[key],
  7151. set: NOOP
  7152. });
  7153. });
  7154. }
  7155. }
  7156. // dev only
  7157. function exposeSetupStateOnRenderContext(instance) {
  7158. const { ctx, setupState } = instance;
  7159. Object.keys(toRaw(setupState)).forEach(key => {
  7160. if (key[0] === '$' || key[0] === '_') {
  7161. warn(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
  7162. `which are reserved prefixes for Vue internals.`);
  7163. return;
  7164. }
  7165. Object.defineProperty(ctx, key, {
  7166. enumerable: true,
  7167. configurable: true,
  7168. get: () => setupState[key],
  7169. set: NOOP
  7170. });
  7171. });
  7172. }
  7173. const emptyAppContext = createAppContext();
  7174. let uid$2 = 0;
  7175. function createComponentInstance(vnode, parent, suspense) {
  7176. const type = vnode.type;
  7177. // inherit parent app context - or - if root, adopt from root vnode
  7178. const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
  7179. const instance = {
  7180. uid: uid$2++,
  7181. vnode,
  7182. type,
  7183. parent,
  7184. appContext,
  7185. root: null,
  7186. next: null,
  7187. subTree: null,
  7188. update: null,
  7189. render: null,
  7190. proxy: null,
  7191. withProxy: null,
  7192. effects: null,
  7193. provides: parent ? parent.provides : Object.create(appContext.provides),
  7194. accessCache: null,
  7195. renderCache: [],
  7196. // local resovled assets
  7197. components: null,
  7198. directives: null,
  7199. // resolved props and emits options
  7200. propsOptions: normalizePropsOptions(type, appContext),
  7201. emitsOptions: normalizeEmitsOptions(type, appContext),
  7202. // emit
  7203. emit: null,
  7204. emitted: null,
  7205. // state
  7206. ctx: EMPTY_OBJ,
  7207. data: EMPTY_OBJ,
  7208. props: EMPTY_OBJ,
  7209. attrs: EMPTY_OBJ,
  7210. slots: EMPTY_OBJ,
  7211. refs: EMPTY_OBJ,
  7212. setupState: EMPTY_OBJ,
  7213. setupContext: null,
  7214. // suspense related
  7215. suspense,
  7216. suspenseId: suspense ? suspense.pendingId : 0,
  7217. asyncDep: null,
  7218. asyncResolved: false,
  7219. // lifecycle hooks
  7220. // not using enums here because it results in computed properties
  7221. isMounted: false,
  7222. isUnmounted: false,
  7223. isDeactivated: false,
  7224. bc: null,
  7225. c: null,
  7226. bm: null,
  7227. m: null,
  7228. bu: null,
  7229. u: null,
  7230. um: null,
  7231. bum: null,
  7232. da: null,
  7233. a: null,
  7234. rtg: null,
  7235. rtc: null,
  7236. ec: null
  7237. };
  7238. {
  7239. instance.ctx = createRenderContext(instance);
  7240. }
  7241. instance.root = parent ? parent.root : instance;
  7242. instance.emit = emit.bind(null, instance);
  7243. {
  7244. devtoolsComponentAdded(instance);
  7245. }
  7246. return instance;
  7247. }
  7248. let currentInstance = null;
  7249. const getCurrentInstance = () => currentInstance || currentRenderingInstance;
  7250. const setCurrentInstance = (instance) => {
  7251. currentInstance = instance;
  7252. };
  7253. const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
  7254. function validateComponentName(name, config) {
  7255. const appIsNativeTag = config.isNativeTag || NO;
  7256. if (isBuiltInTag(name) || appIsNativeTag(name)) {
  7257. warn('Do not use built-in or reserved HTML elements as component id: ' + name);
  7258. }
  7259. }
  7260. let isInSSRComponentSetup = false;
  7261. function setupComponent(instance, isSSR = false) {
  7262. isInSSRComponentSetup = isSSR;
  7263. const { props, children, shapeFlag } = instance.vnode;
  7264. const isStateful = shapeFlag & 4 /* STATEFUL_COMPONENT */;
  7265. initProps(instance, props, isStateful, isSSR);
  7266. initSlots(instance, children);
  7267. const setupResult = isStateful
  7268. ? setupStatefulComponent(instance, isSSR)
  7269. : undefined;
  7270. isInSSRComponentSetup = false;
  7271. return setupResult;
  7272. }
  7273. function setupStatefulComponent(instance, isSSR) {
  7274. const Component = instance.type;
  7275. {
  7276. if (Component.name) {
  7277. validateComponentName(Component.name, instance.appContext.config);
  7278. }
  7279. if (Component.components) {
  7280. const names = Object.keys(Component.components);
  7281. for (let i = 0; i < names.length; i++) {
  7282. validateComponentName(names[i], instance.appContext.config);
  7283. }
  7284. }
  7285. if (Component.directives) {
  7286. const names = Object.keys(Component.directives);
  7287. for (let i = 0; i < names.length; i++) {
  7288. validateDirectiveName(names[i]);
  7289. }
  7290. }
  7291. }
  7292. // 0. create render proxy property access cache
  7293. instance.accessCache = Object.create(null);
  7294. // 1. create public instance / render proxy
  7295. // also mark it raw so it's never observed
  7296. instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
  7297. {
  7298. exposePropsOnRenderContext(instance);
  7299. }
  7300. // 2. call setup()
  7301. const { setup } = Component;
  7302. if (setup) {
  7303. const setupContext = (instance.setupContext =
  7304. setup.length > 1 ? createSetupContext(instance) : null);
  7305. currentInstance = instance;
  7306. pauseTracking();
  7307. const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [ shallowReadonly(instance.props) , setupContext]);
  7308. resetTracking();
  7309. currentInstance = null;
  7310. if (isPromise(setupResult)) {
  7311. if (isSSR) {
  7312. // return the promise so server-renderer can wait on it
  7313. return setupResult.then((resolvedResult) => {
  7314. handleSetupResult(instance, resolvedResult);
  7315. });
  7316. }
  7317. else {
  7318. // async setup returned Promise.
  7319. // bail here and wait for re-entry.
  7320. instance.asyncDep = setupResult;
  7321. }
  7322. }
  7323. else {
  7324. handleSetupResult(instance, setupResult);
  7325. }
  7326. }
  7327. else {
  7328. finishComponentSetup(instance);
  7329. }
  7330. }
  7331. function handleSetupResult(instance, setupResult, isSSR) {
  7332. if (isFunction(setupResult)) {
  7333. // setup returned an inline render function
  7334. instance.render = setupResult;
  7335. }
  7336. else if (isObject(setupResult)) {
  7337. if ( isVNode(setupResult)) {
  7338. warn(`setup() should not return VNodes directly - ` +
  7339. `return a render function instead.`);
  7340. }
  7341. // setup returned bindings.
  7342. // assuming a render function compiled from template is present.
  7343. {
  7344. instance.devtoolsRawSetupState = setupResult;
  7345. }
  7346. instance.setupState = proxyRefs(setupResult);
  7347. {
  7348. exposeSetupStateOnRenderContext(instance);
  7349. }
  7350. }
  7351. else if ( setupResult !== undefined) {
  7352. warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
  7353. }
  7354. finishComponentSetup(instance);
  7355. }
  7356. let compile;
  7357. /**
  7358. * For runtime-dom to register the compiler.
  7359. * Note the exported method uses any to avoid d.ts relying on the compiler types.
  7360. */
  7361. function registerRuntimeCompiler(_compile) {
  7362. compile = _compile;
  7363. }
  7364. function finishComponentSetup(instance, isSSR) {
  7365. const Component = instance.type;
  7366. // template / render function normalization
  7367. if (!instance.render) {
  7368. // could be set from setup()
  7369. if (compile && Component.template && !Component.render) {
  7370. {
  7371. startMeasure(instance, `compile`);
  7372. }
  7373. Component.render = compile(Component.template, {
  7374. isCustomElement: instance.appContext.config.isCustomElement,
  7375. delimiters: Component.delimiters
  7376. });
  7377. {
  7378. endMeasure(instance, `compile`);
  7379. }
  7380. }
  7381. instance.render = (Component.render || NOOP);
  7382. // for runtime-compiled render functions using `with` blocks, the render
  7383. // proxy used needs a different `has` handler which is more performant and
  7384. // also only allows a whitelist of globals to fallthrough.
  7385. if (instance.render._rc) {
  7386. instance.withProxy = new Proxy(instance.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
  7387. }
  7388. }
  7389. // support for 2.x options
  7390. {
  7391. currentInstance = instance;
  7392. applyOptions(instance, Component);
  7393. currentInstance = null;
  7394. }
  7395. // warn missing template/render
  7396. if ( !Component.render && instance.render === NOOP) {
  7397. /* istanbul ignore if */
  7398. if (!compile && Component.template) {
  7399. warn(`Component provided template option but ` +
  7400. `runtime compilation is not supported in this build of Vue.` +
  7401. ( ` Use "vue.global.js" instead.`
  7402. ) /* should not happen */);
  7403. }
  7404. else {
  7405. warn(`Component is missing template or render function.`);
  7406. }
  7407. }
  7408. }
  7409. const attrHandlers = {
  7410. get: (target, key) => {
  7411. {
  7412. markAttrsAccessed();
  7413. }
  7414. return target[key];
  7415. },
  7416. set: () => {
  7417. warn(`setupContext.attrs is readonly.`);
  7418. return false;
  7419. },
  7420. deleteProperty: () => {
  7421. warn(`setupContext.attrs is readonly.`);
  7422. return false;
  7423. }
  7424. };
  7425. function createSetupContext(instance) {
  7426. {
  7427. // We use getters in dev in case libs like test-utils overwrite instance
  7428. // properties (overwrites should not be done in prod)
  7429. return Object.freeze({
  7430. get attrs() {
  7431. return new Proxy(instance.attrs, attrHandlers);
  7432. },
  7433. get slots() {
  7434. return shallowReadonly(instance.slots);
  7435. },
  7436. get emit() {
  7437. return (event, ...args) => instance.emit(event, ...args);
  7438. }
  7439. });
  7440. }
  7441. }
  7442. // record effects created during a component's setup() so that they can be
  7443. // stopped when the component unmounts
  7444. function recordInstanceBoundEffect(effect) {
  7445. if (currentInstance) {
  7446. (currentInstance.effects || (currentInstance.effects = [])).push(effect);
  7447. }
  7448. }
  7449. const classifyRE = /(?:^|[-_])(\w)/g;
  7450. const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
  7451. /* istanbul ignore next */
  7452. function formatComponentName(instance, Component, isRoot = false) {
  7453. let name = isFunction(Component)
  7454. ? Component.displayName || Component.name
  7455. : Component.name;
  7456. if (!name && Component.__file) {
  7457. const match = Component.__file.match(/([^/\\]+)\.vue$/);
  7458. if (match) {
  7459. name = match[1];
  7460. }
  7461. }
  7462. if (!name && instance && instance.parent) {
  7463. // try to infer the name based on reverse resolution
  7464. const inferFromRegistry = (registry) => {
  7465. for (const key in registry) {
  7466. if (registry[key] === Component) {
  7467. return key;
  7468. }
  7469. }
  7470. };
  7471. name =
  7472. inferFromRegistry(instance.components ||
  7473. instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
  7474. }
  7475. return name ? classify(name) : isRoot ? `App` : `Anonymous`;
  7476. }
  7477. function isClassComponent(value) {
  7478. return isFunction(value) && '__vccOpts' in value;
  7479. }
  7480. function computed$1(getterOrOptions) {
  7481. const c = computed(getterOrOptions);
  7482. recordInstanceBoundEffect(c.effect);
  7483. return c;
  7484. }
  7485. // implementation, close to no-op
  7486. function defineComponent(options) {
  7487. return isFunction(options) ? { setup: options, name: options.name } : options;
  7488. }
  7489. function defineAsyncComponent(source) {
  7490. if (isFunction(source)) {
  7491. source = { loader: source };
  7492. }
  7493. const { loader, loadingComponent: loadingComponent, errorComponent: errorComponent, delay = 200, timeout, // undefined = never times out
  7494. suspensible = true, onError: userOnError } = source;
  7495. let pendingRequest = null;
  7496. let resolvedComp;
  7497. let retries = 0;
  7498. const retry = () => {
  7499. retries++;
  7500. pendingRequest = null;
  7501. return load();
  7502. };
  7503. const load = () => {
  7504. let thisRequest;
  7505. return (pendingRequest ||
  7506. (thisRequest = pendingRequest = loader()
  7507. .catch(err => {
  7508. err = err instanceof Error ? err : new Error(String(err));
  7509. if (userOnError) {
  7510. return new Promise((resolve, reject) => {
  7511. const userRetry = () => resolve(retry());
  7512. const userFail = () => reject(err);
  7513. userOnError(err, userRetry, userFail, retries + 1);
  7514. });
  7515. }
  7516. else {
  7517. throw err;
  7518. }
  7519. })
  7520. .then((comp) => {
  7521. if (thisRequest !== pendingRequest && pendingRequest) {
  7522. return pendingRequest;
  7523. }
  7524. if ( !comp) {
  7525. warn(`Async component loader resolved to undefined. ` +
  7526. `If you are using retry(), make sure to return its return value.`);
  7527. }
  7528. // interop module default
  7529. if (comp &&
  7530. (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
  7531. comp = comp.default;
  7532. }
  7533. if ( comp && !isObject(comp) && !isFunction(comp)) {
  7534. throw new Error(`Invalid async component load result: ${comp}`);
  7535. }
  7536. resolvedComp = comp;
  7537. return comp;
  7538. })));
  7539. };
  7540. return defineComponent({
  7541. __asyncLoader: load,
  7542. name: 'AsyncComponentWrapper',
  7543. setup() {
  7544. const instance = currentInstance;
  7545. // already resolved
  7546. if (resolvedComp) {
  7547. return () => createInnerComp(resolvedComp, instance);
  7548. }
  7549. const onError = (err) => {
  7550. pendingRequest = null;
  7551. handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
  7552. };
  7553. // suspense-controlled or SSR.
  7554. if (( suspensible && instance.suspense) ||
  7555. (false )) {
  7556. return load()
  7557. .then(comp => {
  7558. return () => createInnerComp(comp, instance);
  7559. })
  7560. .catch(err => {
  7561. onError(err);
  7562. return () => errorComponent
  7563. ? createVNode(errorComponent, {
  7564. error: err
  7565. })
  7566. : null;
  7567. });
  7568. }
  7569. const loaded = ref(false);
  7570. const error = ref();
  7571. const delayed = ref(!!delay);
  7572. if (delay) {
  7573. setTimeout(() => {
  7574. delayed.value = false;
  7575. }, delay);
  7576. }
  7577. if (timeout != null) {
  7578. setTimeout(() => {
  7579. if (!loaded.value && !error.value) {
  7580. const err = new Error(`Async component timed out after ${timeout}ms.`);
  7581. onError(err);
  7582. error.value = err;
  7583. }
  7584. }, timeout);
  7585. }
  7586. load()
  7587. .then(() => {
  7588. loaded.value = true;
  7589. })
  7590. .catch(err => {
  7591. onError(err);
  7592. error.value = err;
  7593. });
  7594. return () => {
  7595. if (loaded.value && resolvedComp) {
  7596. return createInnerComp(resolvedComp, instance);
  7597. }
  7598. else if (error.value && errorComponent) {
  7599. return createVNode(errorComponent, {
  7600. error: error.value
  7601. });
  7602. }
  7603. else if (loadingComponent && !delayed.value) {
  7604. return createVNode(loadingComponent);
  7605. }
  7606. };
  7607. }
  7608. });
  7609. }
  7610. function createInnerComp(comp, { vnode: { props, children } }) {
  7611. return createVNode(comp, props, children);
  7612. }
  7613. // Actual implementation
  7614. function h(type, propsOrChildren, children) {
  7615. const l = arguments.length;
  7616. if (l === 2) {
  7617. if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
  7618. // single vnode without props
  7619. if (isVNode(propsOrChildren)) {
  7620. return createVNode(type, null, [propsOrChildren]);
  7621. }
  7622. // props without children
  7623. return createVNode(type, propsOrChildren);
  7624. }
  7625. else {
  7626. // omit props
  7627. return createVNode(type, null, propsOrChildren);
  7628. }
  7629. }
  7630. else {
  7631. if (l > 3) {
  7632. children = Array.prototype.slice.call(arguments, 2);
  7633. }
  7634. else if (l === 3 && isVNode(children)) {
  7635. children = [children];
  7636. }
  7637. return createVNode(type, propsOrChildren, children);
  7638. }
  7639. }
  7640. const ssrContextKey = Symbol( `ssrContext` );
  7641. const useSSRContext = () => {
  7642. {
  7643. warn(`useSsrContext() is not supported in the global build.`);
  7644. }
  7645. };
  7646. function initCustomFormatter() {
  7647. const vueStyle = { style: 'color:#3ba776' };
  7648. const numberStyle = { style: 'color:#0b1bc9' };
  7649. const stringStyle = { style: 'color:#b62e24' };
  7650. const keywordStyle = { style: 'color:#9d288c' };
  7651. // custom formatter for Chrome
  7652. // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
  7653. const formatter = {
  7654. header(obj) {
  7655. // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
  7656. if (!isObject(obj)) {
  7657. return null;
  7658. }
  7659. if (obj.__isVue) {
  7660. return ['div', vueStyle, `VueInstance`];
  7661. }
  7662. else if (isRef(obj)) {
  7663. return [
  7664. 'div',
  7665. {},
  7666. ['span', vueStyle, genRefFlag(obj)],
  7667. '<',
  7668. formatValue(obj.value),
  7669. `>`
  7670. ];
  7671. }
  7672. else if (isReactive(obj)) {
  7673. return [
  7674. 'div',
  7675. {},
  7676. ['span', vueStyle, 'Reactive'],
  7677. '<',
  7678. formatValue(obj),
  7679. `>${isReadonly(obj) ? ` (readonly)` : ``}`
  7680. ];
  7681. }
  7682. else if (isReadonly(obj)) {
  7683. return [
  7684. 'div',
  7685. {},
  7686. ['span', vueStyle, 'Readonly'],
  7687. '<',
  7688. formatValue(obj),
  7689. '>'
  7690. ];
  7691. }
  7692. return null;
  7693. },
  7694. hasBody(obj) {
  7695. return obj && obj.__isVue;
  7696. },
  7697. body(obj) {
  7698. if (obj && obj.__isVue) {
  7699. return [
  7700. 'div',
  7701. {},
  7702. ...formatInstance(obj.$)
  7703. ];
  7704. }
  7705. }
  7706. };
  7707. function formatInstance(instance) {
  7708. const blocks = [];
  7709. if (instance.type.props && instance.props) {
  7710. blocks.push(createInstanceBlock('props', toRaw(instance.props)));
  7711. }
  7712. if (instance.setupState !== EMPTY_OBJ) {
  7713. blocks.push(createInstanceBlock('setup', instance.setupState));
  7714. }
  7715. if (instance.data !== EMPTY_OBJ) {
  7716. blocks.push(createInstanceBlock('data', toRaw(instance.data)));
  7717. }
  7718. const computed = extractKeys(instance, 'computed');
  7719. if (computed) {
  7720. blocks.push(createInstanceBlock('computed', computed));
  7721. }
  7722. const injected = extractKeys(instance, 'inject');
  7723. if (injected) {
  7724. blocks.push(createInstanceBlock('injected', injected));
  7725. }
  7726. blocks.push([
  7727. 'div',
  7728. {},
  7729. [
  7730. 'span',
  7731. {
  7732. style: keywordStyle.style + ';opacity:0.66'
  7733. },
  7734. '$ (internal): '
  7735. ],
  7736. ['object', { object: instance }]
  7737. ]);
  7738. return blocks;
  7739. }
  7740. function createInstanceBlock(type, target) {
  7741. target = extend({}, target);
  7742. if (!Object.keys(target).length) {
  7743. return ['span', {}];
  7744. }
  7745. return [
  7746. 'div',
  7747. { style: 'line-height:1.25em;margin-bottom:0.6em' },
  7748. [
  7749. 'div',
  7750. {
  7751. style: 'color:#476582'
  7752. },
  7753. type
  7754. ],
  7755. [
  7756. 'div',
  7757. {
  7758. style: 'padding-left:1.25em'
  7759. },
  7760. ...Object.keys(target).map(key => {
  7761. return [
  7762. 'div',
  7763. {},
  7764. ['span', keywordStyle, key + ': '],
  7765. formatValue(target[key], false)
  7766. ];
  7767. })
  7768. ]
  7769. ];
  7770. }
  7771. function formatValue(v, asRaw = true) {
  7772. if (typeof v === 'number') {
  7773. return ['span', numberStyle, v];
  7774. }
  7775. else if (typeof v === 'string') {
  7776. return ['span', stringStyle, JSON.stringify(v)];
  7777. }
  7778. else if (typeof v === 'boolean') {
  7779. return ['span', keywordStyle, v];
  7780. }
  7781. else if (isObject(v)) {
  7782. return ['object', { object: asRaw ? toRaw(v) : v }];
  7783. }
  7784. else {
  7785. return ['span', stringStyle, String(v)];
  7786. }
  7787. }
  7788. function extractKeys(instance, type) {
  7789. const Comp = instance.type;
  7790. if (isFunction(Comp)) {
  7791. return;
  7792. }
  7793. const extracted = {};
  7794. for (const key in instance.ctx) {
  7795. if (isKeyOfType(Comp, key, type)) {
  7796. extracted[key] = instance.ctx[key];
  7797. }
  7798. }
  7799. return extracted;
  7800. }
  7801. function isKeyOfType(Comp, key, type) {
  7802. const opts = Comp[type];
  7803. if ((isArray(opts) && opts.includes(key)) ||
  7804. (isObject(opts) && key in opts)) {
  7805. return true;
  7806. }
  7807. if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
  7808. return true;
  7809. }
  7810. if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
  7811. return true;
  7812. }
  7813. }
  7814. function genRefFlag(v) {
  7815. if (v._shallow) {
  7816. return `ShallowRef`;
  7817. }
  7818. if (v.effect) {
  7819. return `ComputedRef`;
  7820. }
  7821. return `Ref`;
  7822. }
  7823. /* eslint-disable no-restricted-globals */
  7824. if (window.devtoolsFormatters) {
  7825. window.devtoolsFormatters.push(formatter);
  7826. }
  7827. else {
  7828. window.devtoolsFormatters = [formatter];
  7829. }
  7830. }
  7831. /**
  7832. * Actual implementation
  7833. */
  7834. function renderList(source, renderItem) {
  7835. let ret;
  7836. if (isArray(source) || isString(source)) {
  7837. ret = new Array(source.length);
  7838. for (let i = 0, l = source.length; i < l; i++) {
  7839. ret[i] = renderItem(source[i], i);
  7840. }
  7841. }
  7842. else if (typeof source === 'number') {
  7843. if ( !Number.isInteger(source)) {
  7844. warn(`The v-for range expect an integer value but got ${source}.`);
  7845. return [];
  7846. }
  7847. ret = new Array(source);
  7848. for (let i = 0; i < source; i++) {
  7849. ret[i] = renderItem(i + 1, i);
  7850. }
  7851. }
  7852. else if (isObject(source)) {
  7853. if (source[Symbol.iterator]) {
  7854. ret = Array.from(source, renderItem);
  7855. }
  7856. else {
  7857. const keys = Object.keys(source);
  7858. ret = new Array(keys.length);
  7859. for (let i = 0, l = keys.length; i < l; i++) {
  7860. const key = keys[i];
  7861. ret[i] = renderItem(source[key], key, i);
  7862. }
  7863. }
  7864. }
  7865. else {
  7866. ret = [];
  7867. }
  7868. return ret;
  7869. }
  7870. /**
  7871. * For prefixing keys in v-on="obj" with "on"
  7872. * @private
  7873. */
  7874. function toHandlers(obj) {
  7875. const ret = {};
  7876. if ( !isObject(obj)) {
  7877. warn(`v-on with no argument expects an object value.`);
  7878. return ret;
  7879. }
  7880. for (const key in obj) {
  7881. ret[toHandlerKey(key)] = obj[key];
  7882. }
  7883. return ret;
  7884. }
  7885. /**
  7886. * Compiler runtime helper for creating dynamic slots object
  7887. * @private
  7888. */
  7889. function createSlots(slots, dynamicSlots) {
  7890. for (let i = 0; i < dynamicSlots.length; i++) {
  7891. const slot = dynamicSlots[i];
  7892. // array of dynamic slot generated by <template v-for="..." #[...]>
  7893. if (isArray(slot)) {
  7894. for (let j = 0; j < slot.length; j++) {
  7895. slots[slot[j].name] = slot[j].fn;
  7896. }
  7897. }
  7898. else if (slot) {
  7899. // conditional single slot generated by <template v-if="..." #foo>
  7900. slots[slot.name] = slot.fn;
  7901. }
  7902. }
  7903. return slots;
  7904. }
  7905. // Core API ------------------------------------------------------------------
  7906. const version = "3.0.2";
  7907. /**
  7908. * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
  7909. * @internal
  7910. */
  7911. const ssrUtils = ( null);
  7912. const svgNS = 'http://www.w3.org/2000/svg';
  7913. const doc = (typeof document !== 'undefined' ? document : null);
  7914. let tempContainer;
  7915. let tempSVGContainer;
  7916. const nodeOps = {
  7917. insert: (child, parent, anchor) => {
  7918. parent.insertBefore(child, anchor || null);
  7919. },
  7920. remove: child => {
  7921. const parent = child.parentNode;
  7922. if (parent) {
  7923. parent.removeChild(child);
  7924. }
  7925. },
  7926. createElement: (tag, isSVG, is) => isSVG
  7927. ? doc.createElementNS(svgNS, tag)
  7928. : doc.createElement(tag, is ? { is } : undefined),
  7929. createText: text => doc.createTextNode(text),
  7930. createComment: text => doc.createComment(text),
  7931. setText: (node, text) => {
  7932. node.nodeValue = text;
  7933. },
  7934. setElementText: (el, text) => {
  7935. el.textContent = text;
  7936. },
  7937. parentNode: node => node.parentNode,
  7938. nextSibling: node => node.nextSibling,
  7939. querySelector: selector => doc.querySelector(selector),
  7940. setScopeId(el, id) {
  7941. el.setAttribute(id, '');
  7942. },
  7943. cloneNode(el) {
  7944. return el.cloneNode(true);
  7945. },
  7946. // __UNSAFE__
  7947. // Reason: innerHTML.
  7948. // Static content here can only come from compiled templates.
  7949. // As long as the user only uses trusted templates, this is safe.
  7950. insertStaticContent(content, parent, anchor, isSVG) {
  7951. const temp = isSVG
  7952. ? tempSVGContainer ||
  7953. (tempSVGContainer = doc.createElementNS(svgNS, 'svg'))
  7954. : tempContainer || (tempContainer = doc.createElement('div'));
  7955. temp.innerHTML = content;
  7956. const first = temp.firstChild;
  7957. let node = first;
  7958. let last = node;
  7959. while (node) {
  7960. last = node;
  7961. nodeOps.insert(node, parent, anchor);
  7962. node = temp.firstChild;
  7963. }
  7964. return [first, last];
  7965. }
  7966. };
  7967. // compiler should normalize class + :class bindings on the same element
  7968. // into a single binding ['staticClass', dynamic]
  7969. function patchClass(el, value, isSVG) {
  7970. if (value == null) {
  7971. value = '';
  7972. }
  7973. if (isSVG) {
  7974. el.setAttribute('class', value);
  7975. }
  7976. else {
  7977. // directly setting className should be faster than setAttribute in theory
  7978. // if this is an element during a transition, take the temporary transition
  7979. // classes into account.
  7980. const transitionClasses = el._vtc;
  7981. if (transitionClasses) {
  7982. value = (value
  7983. ? [value, ...transitionClasses]
  7984. : [...transitionClasses]).join(' ');
  7985. }
  7986. el.className = value;
  7987. }
  7988. }
  7989. function patchStyle(el, prev, next) {
  7990. const style = el.style;
  7991. if (!next) {
  7992. el.removeAttribute('style');
  7993. }
  7994. else if (isString(next)) {
  7995. if (prev !== next) {
  7996. style.cssText = next;
  7997. }
  7998. }
  7999. else {
  8000. for (const key in next) {
  8001. setStyle(style, key, next[key]);
  8002. }
  8003. if (prev && !isString(prev)) {
  8004. for (const key in prev) {
  8005. if (next[key] == null) {
  8006. setStyle(style, key, '');
  8007. }
  8008. }
  8009. }
  8010. }
  8011. }
  8012. const importantRE = /\s*!important$/;
  8013. function setStyle(style, name, val) {
  8014. if (isArray(val)) {
  8015. val.forEach(v => setStyle(style, name, v));
  8016. }
  8017. else {
  8018. if (name.startsWith('--')) {
  8019. // custom property definition
  8020. style.setProperty(name, val);
  8021. }
  8022. else {
  8023. const prefixed = autoPrefix(style, name);
  8024. if (importantRE.test(val)) {
  8025. // !important
  8026. style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
  8027. }
  8028. else {
  8029. style[prefixed] = val;
  8030. }
  8031. }
  8032. }
  8033. }
  8034. const prefixes = ['Webkit', 'Moz', 'ms'];
  8035. const prefixCache = {};
  8036. function autoPrefix(style, rawName) {
  8037. const cached = prefixCache[rawName];
  8038. if (cached) {
  8039. return cached;
  8040. }
  8041. let name = camelize(rawName);
  8042. if (name !== 'filter' && name in style) {
  8043. return (prefixCache[rawName] = name);
  8044. }
  8045. name = capitalize(name);
  8046. for (let i = 0; i < prefixes.length; i++) {
  8047. const prefixed = prefixes[i] + name;
  8048. if (prefixed in style) {
  8049. return (prefixCache[rawName] = prefixed);
  8050. }
  8051. }
  8052. return rawName;
  8053. }
  8054. const xlinkNS = 'http://www.w3.org/1999/xlink';
  8055. function patchAttr(el, key, value, isSVG) {
  8056. if (isSVG && key.startsWith('xlink:')) {
  8057. if (value == null) {
  8058. el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
  8059. }
  8060. else {
  8061. el.setAttributeNS(xlinkNS, key, value);
  8062. }
  8063. }
  8064. else {
  8065. // note we are only checking boolean attributes that don't have a
  8066. // corresponding dom prop of the same name here.
  8067. const isBoolean = isSpecialBooleanAttr(key);
  8068. if (value == null || (isBoolean && value === false)) {
  8069. el.removeAttribute(key);
  8070. }
  8071. else {
  8072. el.setAttribute(key, isBoolean ? '' : value);
  8073. }
  8074. }
  8075. }
  8076. // __UNSAFE__
  8077. // functions. The user is responsible for using them with only trusted content.
  8078. function patchDOMProp(el, key, value,
  8079. // the following args are passed only due to potential innerHTML/textContent
  8080. // overriding existing VNodes, in which case the old tree must be properly
  8081. // unmounted.
  8082. prevChildren, parentComponent, parentSuspense, unmountChildren) {
  8083. if (key === 'innerHTML' || key === 'textContent') {
  8084. if (prevChildren) {
  8085. unmountChildren(prevChildren, parentComponent, parentSuspense);
  8086. }
  8087. el[key] = value == null ? '' : value;
  8088. return;
  8089. }
  8090. if (key === 'value' && el.tagName !== 'PROGRESS') {
  8091. // store value as _value as well since
  8092. // non-string values will be stringified.
  8093. el._value = value;
  8094. const newValue = value == null ? '' : value;
  8095. if (el.value !== newValue) {
  8096. el.value = newValue;
  8097. }
  8098. return;
  8099. }
  8100. if (value === '' && typeof el[key] === 'boolean') {
  8101. // e.g. <select multiple> compiles to { multiple: '' }
  8102. el[key] = true;
  8103. }
  8104. else if (value == null && typeof el[key] === 'string') {
  8105. // e.g. <div :id="null">
  8106. el[key] = '';
  8107. el.removeAttribute(key);
  8108. }
  8109. else {
  8110. // some properties perform value validation and throw
  8111. try {
  8112. el[key] = value;
  8113. }
  8114. catch (e) {
  8115. {
  8116. warn(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
  8117. `value ${value} is invalid.`, e);
  8118. }
  8119. }
  8120. }
  8121. }
  8122. // Async edge case fix requires storing an event listener's attach timestamp.
  8123. let _getNow = Date.now;
  8124. // Determine what event timestamp the browser is using. Annoyingly, the
  8125. // timestamp can either be hi-res (relative to page load) or low-res
  8126. // (relative to UNIX epoch), so in order to compare time we have to use the
  8127. // same timestamp type when saving the flush timestamp.
  8128. if (typeof document !== 'undefined' &&
  8129. _getNow() > document.createEvent('Event').timeStamp) {
  8130. // if the low-res timestamp which is bigger than the event timestamp
  8131. // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
  8132. // and we need to use the hi-res version for event listeners as well.
  8133. _getNow = () => performance.now();
  8134. }
  8135. // To avoid the overhead of repeatedly calling performance.now(), we cache
  8136. // and use the same timestamp for all event listeners attached in the same tick.
  8137. let cachedNow = 0;
  8138. const p = Promise.resolve();
  8139. const reset = () => {
  8140. cachedNow = 0;
  8141. };
  8142. const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
  8143. function addEventListener(el, event, handler, options) {
  8144. el.addEventListener(event, handler, options);
  8145. }
  8146. function removeEventListener(el, event, handler, options) {
  8147. el.removeEventListener(event, handler, options);
  8148. }
  8149. function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  8150. // vei = vue event invokers
  8151. const invokers = el._vei || (el._vei = {});
  8152. const existingInvoker = invokers[rawName];
  8153. if (nextValue && existingInvoker) {
  8154. // patch
  8155. existingInvoker.value = nextValue;
  8156. }
  8157. else {
  8158. const [name, options] = parseName(rawName);
  8159. if (nextValue) {
  8160. // add
  8161. const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
  8162. addEventListener(el, name, invoker, options);
  8163. }
  8164. else if (existingInvoker) {
  8165. // remove
  8166. removeEventListener(el, name, existingInvoker, options);
  8167. invokers[rawName] = undefined;
  8168. }
  8169. }
  8170. }
  8171. const optionsModifierRE = /(?:Once|Passive|Capture)$/;
  8172. function parseName(name) {
  8173. let options;
  8174. if (optionsModifierRE.test(name)) {
  8175. options = {};
  8176. let m;
  8177. while ((m = name.match(optionsModifierRE))) {
  8178. name = name.slice(0, name.length - m[0].length);
  8179. options[m[0].toLowerCase()] = true;
  8180. }
  8181. }
  8182. return [name.slice(2).toLowerCase(), options];
  8183. }
  8184. function createInvoker(initialValue, instance) {
  8185. const invoker = (e) => {
  8186. // async edge case #6566: inner click event triggers patch, event handler
  8187. // attached to outer element during patch, and triggered again. This
  8188. // happens because browsers fire microtask ticks between event propagation.
  8189. // the solution is simple: we save the timestamp when a handler is attached,
  8190. // and the handler would only fire if the event passed to it was fired
  8191. // AFTER it was attached.
  8192. const timeStamp = e.timeStamp || _getNow();
  8193. if (timeStamp >= invoker.attached - 1) {
  8194. callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
  8195. }
  8196. };
  8197. invoker.value = initialValue;
  8198. invoker.attached = getNow();
  8199. return invoker;
  8200. }
  8201. function patchStopImmediatePropagation(e, value) {
  8202. if (isArray(value)) {
  8203. const originalStop = e.stopImmediatePropagation;
  8204. e.stopImmediatePropagation = () => {
  8205. originalStop.call(e);
  8206. e._stopped = true;
  8207. };
  8208. return value.map(fn => (e) => !e._stopped && fn(e));
  8209. }
  8210. else {
  8211. return value;
  8212. }
  8213. }
  8214. const nativeOnRE = /^on[a-z]/;
  8215. const forcePatchProp = (_, key) => key === 'value';
  8216. const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
  8217. switch (key) {
  8218. // special
  8219. case 'class':
  8220. patchClass(el, nextValue, isSVG);
  8221. break;
  8222. case 'style':
  8223. patchStyle(el, prevValue, nextValue);
  8224. break;
  8225. default:
  8226. if (isOn(key)) {
  8227. // ignore v-model listeners
  8228. if (!isModelListener(key)) {
  8229. patchEvent(el, key, prevValue, nextValue, parentComponent);
  8230. }
  8231. }
  8232. else if (shouldSetAsProp(el, key, nextValue, isSVG)) {
  8233. patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
  8234. }
  8235. else {
  8236. // special case for <input v-model type="checkbox"> with
  8237. // :true-value & :false-value
  8238. // store value as dom properties since non-string values will be
  8239. // stringified.
  8240. if (key === 'true-value') {
  8241. el._trueValue = nextValue;
  8242. }
  8243. else if (key === 'false-value') {
  8244. el._falseValue = nextValue;
  8245. }
  8246. patchAttr(el, key, nextValue, isSVG);
  8247. }
  8248. break;
  8249. }
  8250. };
  8251. function shouldSetAsProp(el, key, value, isSVG) {
  8252. if (isSVG) {
  8253. // most keys must be set as attribute on svg elements to work
  8254. // ...except innerHTML
  8255. if (key === 'innerHTML') {
  8256. return true;
  8257. }
  8258. // or native onclick with function values
  8259. if (key in el && nativeOnRE.test(key) && isFunction(value)) {
  8260. return true;
  8261. }
  8262. return false;
  8263. }
  8264. // spellcheck and draggable are numerated attrs, however their
  8265. // corresponding DOM properties are actually booleans - this leads to
  8266. // setting it with a string "false" value leading it to be coerced to
  8267. // `true`, so we need to always treat them as attributes.
  8268. // Note that `contentEditable` doesn't have this problem: its DOM
  8269. // property is also enumerated string values.
  8270. if (key === 'spellcheck' || key === 'draggable') {
  8271. return false;
  8272. }
  8273. // #1787 form as an attribute must be a string, while it accepts an Element as
  8274. // a prop
  8275. if (key === 'form' && typeof value === 'string') {
  8276. return false;
  8277. }
  8278. // #1526 <input list> must be set as attribute
  8279. if (key === 'list' && el.tagName === 'INPUT') {
  8280. return false;
  8281. }
  8282. // native onclick with string value, must be set as attribute
  8283. if (nativeOnRE.test(key) && isString(value)) {
  8284. return false;
  8285. }
  8286. return key in el;
  8287. }
  8288. function useCssModule(name = '$style') {
  8289. /* istanbul ignore else */
  8290. {
  8291. {
  8292. warn(`useCssModule() is not supported in the global build.`);
  8293. }
  8294. return EMPTY_OBJ;
  8295. }
  8296. }
  8297. function useCssVars(getter, scoped = false) {
  8298. const instance = getCurrentInstance();
  8299. /* istanbul ignore next */
  8300. if (!instance) {
  8301. warn(`useCssVars is called without current active component instance.`);
  8302. return;
  8303. }
  8304. const prefix = scoped && instance.type.__scopeId
  8305. ? `${instance.type.__scopeId.replace(/^data-v-/, '')}-`
  8306. : ``;
  8307. const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy), prefix);
  8308. onMounted(() => watchEffect(setVars));
  8309. onUpdated(setVars);
  8310. }
  8311. function setVarsOnVNode(vnode, vars, prefix) {
  8312. if ( vnode.shapeFlag & 128 /* SUSPENSE */) {
  8313. const suspense = vnode.suspense;
  8314. vnode = suspense.activeBranch;
  8315. if (suspense.pendingBranch && !suspense.isHydrating) {
  8316. suspense.effects.push(() => {
  8317. setVarsOnVNode(suspense.activeBranch, vars, prefix);
  8318. });
  8319. }
  8320. }
  8321. // drill down HOCs until it's a non-component vnode
  8322. while (vnode.component) {
  8323. vnode = vnode.component.subTree;
  8324. }
  8325. if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
  8326. const style = vnode.el.style;
  8327. for (const key in vars) {
  8328. style.setProperty(`--${prefix}${key}`, unref(vars[key]));
  8329. }
  8330. }
  8331. else if (vnode.type === Fragment) {
  8332. vnode.children.forEach(c => setVarsOnVNode(c, vars, prefix));
  8333. }
  8334. }
  8335. const TRANSITION = 'transition';
  8336. const ANIMATION = 'animation';
  8337. // DOM Transition is a higher-order-component based on the platform-agnostic
  8338. // base Transition component, with DOM-specific logic.
  8339. const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
  8340. Transition.displayName = 'Transition';
  8341. const DOMTransitionPropsValidators = {
  8342. name: String,
  8343. type: String,
  8344. css: {
  8345. type: Boolean,
  8346. default: true
  8347. },
  8348. duration: [String, Number, Object],
  8349. enterFromClass: String,
  8350. enterActiveClass: String,
  8351. enterToClass: String,
  8352. appearFromClass: String,
  8353. appearActiveClass: String,
  8354. appearToClass: String,
  8355. leaveFromClass: String,
  8356. leaveActiveClass: String,
  8357. leaveToClass: String
  8358. };
  8359. const TransitionPropsValidators = (Transition.props = /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
  8360. function resolveTransitionProps(rawProps) {
  8361. let { name = 'v', type, css = true, duration, enterFromClass = `${name}-enter-from`, enterActiveClass = `${name}-enter-active`, enterToClass = `${name}-enter-to`, appearFromClass = enterFromClass, appearActiveClass = enterActiveClass, appearToClass = enterToClass, leaveFromClass = `${name}-leave-from`, leaveActiveClass = `${name}-leave-active`, leaveToClass = `${name}-leave-to` } = rawProps;
  8362. const baseProps = {};
  8363. for (const key in rawProps) {
  8364. if (!(key in DOMTransitionPropsValidators)) {
  8365. baseProps[key] = rawProps[key];
  8366. }
  8367. }
  8368. if (!css) {
  8369. return baseProps;
  8370. }
  8371. const durations = normalizeDuration(duration);
  8372. const enterDuration = durations && durations[0];
  8373. const leaveDuration = durations && durations[1];
  8374. const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
  8375. const finishEnter = (el, isAppear, done) => {
  8376. removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
  8377. removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
  8378. done && done();
  8379. };
  8380. const finishLeave = (el, done) => {
  8381. removeTransitionClass(el, leaveToClass);
  8382. removeTransitionClass(el, leaveActiveClass);
  8383. done && done();
  8384. };
  8385. const makeEnterHook = (isAppear) => {
  8386. return (el, done) => {
  8387. const hook = isAppear ? onAppear : onEnter;
  8388. const resolve = () => finishEnter(el, isAppear, done);
  8389. hook && hook(el, resolve);
  8390. nextFrame(() => {
  8391. removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
  8392. addTransitionClass(el, isAppear ? appearToClass : enterToClass);
  8393. if (!(hook && hook.length > 1)) {
  8394. if (enterDuration) {
  8395. setTimeout(resolve, enterDuration);
  8396. }
  8397. else {
  8398. whenTransitionEnds(el, type, resolve);
  8399. }
  8400. }
  8401. });
  8402. };
  8403. };
  8404. return extend(baseProps, {
  8405. onBeforeEnter(el) {
  8406. onBeforeEnter && onBeforeEnter(el);
  8407. addTransitionClass(el, enterActiveClass);
  8408. addTransitionClass(el, enterFromClass);
  8409. },
  8410. onBeforeAppear(el) {
  8411. onBeforeAppear && onBeforeAppear(el);
  8412. addTransitionClass(el, appearActiveClass);
  8413. addTransitionClass(el, appearFromClass);
  8414. },
  8415. onEnter: makeEnterHook(false),
  8416. onAppear: makeEnterHook(true),
  8417. onLeave(el, done) {
  8418. const resolve = () => finishLeave(el, done);
  8419. addTransitionClass(el, leaveActiveClass);
  8420. addTransitionClass(el, leaveFromClass);
  8421. nextFrame(() => {
  8422. removeTransitionClass(el, leaveFromClass);
  8423. addTransitionClass(el, leaveToClass);
  8424. if (!(onLeave && onLeave.length > 1)) {
  8425. if (leaveDuration) {
  8426. setTimeout(resolve, leaveDuration);
  8427. }
  8428. else {
  8429. whenTransitionEnds(el, type, resolve);
  8430. }
  8431. }
  8432. });
  8433. onLeave && onLeave(el, resolve);
  8434. },
  8435. onEnterCancelled(el) {
  8436. finishEnter(el, false);
  8437. onEnterCancelled && onEnterCancelled(el);
  8438. },
  8439. onAppearCancelled(el) {
  8440. finishEnter(el, true);
  8441. onAppearCancelled && onAppearCancelled(el);
  8442. },
  8443. onLeaveCancelled(el) {
  8444. finishLeave(el);
  8445. onLeaveCancelled && onLeaveCancelled(el);
  8446. }
  8447. });
  8448. }
  8449. function normalizeDuration(duration) {
  8450. if (duration == null) {
  8451. return null;
  8452. }
  8453. else if (isObject(duration)) {
  8454. return [NumberOf(duration.enter), NumberOf(duration.leave)];
  8455. }
  8456. else {
  8457. const n = NumberOf(duration);
  8458. return [n, n];
  8459. }
  8460. }
  8461. function NumberOf(val) {
  8462. const res = toNumber(val);
  8463. validateDuration(res);
  8464. return res;
  8465. }
  8466. function validateDuration(val) {
  8467. if (typeof val !== 'number') {
  8468. warn(`<transition> explicit duration is not a valid number - ` +
  8469. `got ${JSON.stringify(val)}.`);
  8470. }
  8471. else if (isNaN(val)) {
  8472. warn(`<transition> explicit duration is NaN - ` +
  8473. 'the duration expression might be incorrect.');
  8474. }
  8475. }
  8476. function addTransitionClass(el, cls) {
  8477. cls.split(/\s+/).forEach(c => c && el.classList.add(c));
  8478. (el._vtc ||
  8479. (el._vtc = new Set())).add(cls);
  8480. }
  8481. function removeTransitionClass(el, cls) {
  8482. cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
  8483. const { _vtc } = el;
  8484. if (_vtc) {
  8485. _vtc.delete(cls);
  8486. if (!_vtc.size) {
  8487. el._vtc = undefined;
  8488. }
  8489. }
  8490. }
  8491. function nextFrame(cb) {
  8492. requestAnimationFrame(() => {
  8493. requestAnimationFrame(cb);
  8494. });
  8495. }
  8496. function whenTransitionEnds(el, expectedType, cb) {
  8497. const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
  8498. if (!type) {
  8499. return cb();
  8500. }
  8501. const endEvent = type + 'end';
  8502. let ended = 0;
  8503. const end = () => {
  8504. el.removeEventListener(endEvent, onEnd);
  8505. cb();
  8506. };
  8507. const onEnd = (e) => {
  8508. if (e.target === el) {
  8509. if (++ended >= propCount) {
  8510. end();
  8511. }
  8512. }
  8513. };
  8514. setTimeout(() => {
  8515. if (ended < propCount) {
  8516. end();
  8517. }
  8518. }, timeout + 1);
  8519. el.addEventListener(endEvent, onEnd);
  8520. }
  8521. function getTransitionInfo(el, expectedType) {
  8522. const styles = window.getComputedStyle(el);
  8523. // JSDOM may return undefined for transition properties
  8524. const getStyleProperties = (key) => (styles[key] || '').split(', ');
  8525. const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
  8526. const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
  8527. const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
  8528. const animationDelays = getStyleProperties(ANIMATION + 'Delay');
  8529. const animationDurations = getStyleProperties(ANIMATION + 'Duration');
  8530. const animationTimeout = getTimeout(animationDelays, animationDurations);
  8531. let type = null;
  8532. let timeout = 0;
  8533. let propCount = 0;
  8534. /* istanbul ignore if */
  8535. if (expectedType === TRANSITION) {
  8536. if (transitionTimeout > 0) {
  8537. type = TRANSITION;
  8538. timeout = transitionTimeout;
  8539. propCount = transitionDurations.length;
  8540. }
  8541. }
  8542. else if (expectedType === ANIMATION) {
  8543. if (animationTimeout > 0) {
  8544. type = ANIMATION;
  8545. timeout = animationTimeout;
  8546. propCount = animationDurations.length;
  8547. }
  8548. }
  8549. else {
  8550. timeout = Math.max(transitionTimeout, animationTimeout);
  8551. type =
  8552. timeout > 0
  8553. ? transitionTimeout > animationTimeout
  8554. ? TRANSITION
  8555. : ANIMATION
  8556. : null;
  8557. propCount = type
  8558. ? type === TRANSITION
  8559. ? transitionDurations.length
  8560. : animationDurations.length
  8561. : 0;
  8562. }
  8563. const hasTransform = type === TRANSITION &&
  8564. /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
  8565. return {
  8566. type,
  8567. timeout,
  8568. propCount,
  8569. hasTransform
  8570. };
  8571. }
  8572. function getTimeout(delays, durations) {
  8573. while (delays.length < durations.length) {
  8574. delays = delays.concat(delays);
  8575. }
  8576. return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
  8577. }
  8578. // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
  8579. // numbers in a locale-dependent way, using a comma instead of a dot.
  8580. // If comma is not replaced with a dot, the input will be rounded down
  8581. // (i.e. acting as a floor function) causing unexpected behaviors
  8582. function toMs(s) {
  8583. return Number(s.slice(0, -1).replace(',', '.')) * 1000;
  8584. }
  8585. const positionMap = new WeakMap();
  8586. const newPositionMap = new WeakMap();
  8587. const TransitionGroupImpl = {
  8588. name: 'TransitionGroup',
  8589. props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
  8590. tag: String,
  8591. moveClass: String
  8592. }),
  8593. setup(props, { slots }) {
  8594. const instance = getCurrentInstance();
  8595. const state = useTransitionState();
  8596. let prevChildren;
  8597. let children;
  8598. onUpdated(() => {
  8599. // children is guaranteed to exist after initial render
  8600. if (!prevChildren.length) {
  8601. return;
  8602. }
  8603. const moveClass = props.moveClass || `${props.name || 'v'}-move`;
  8604. if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
  8605. return;
  8606. }
  8607. // we divide the work into three loops to avoid mixing DOM reads and writes
  8608. // in each iteration - which helps prevent layout thrashing.
  8609. prevChildren.forEach(callPendingCbs);
  8610. prevChildren.forEach(recordPosition);
  8611. const movedChildren = prevChildren.filter(applyTranslation);
  8612. // force reflow to put everything in position
  8613. forceReflow();
  8614. movedChildren.forEach(c => {
  8615. const el = c.el;
  8616. const style = el.style;
  8617. addTransitionClass(el, moveClass);
  8618. style.transform = style.webkitTransform = style.transitionDuration = '';
  8619. const cb = (el._moveCb = (e) => {
  8620. if (e && e.target !== el) {
  8621. return;
  8622. }
  8623. if (!e || /transform$/.test(e.propertyName)) {
  8624. el.removeEventListener('transitionend', cb);
  8625. el._moveCb = null;
  8626. removeTransitionClass(el, moveClass);
  8627. }
  8628. });
  8629. el.addEventListener('transitionend', cb);
  8630. });
  8631. });
  8632. return () => {
  8633. const rawProps = toRaw(props);
  8634. const cssTransitionProps = resolveTransitionProps(rawProps);
  8635. const tag = rawProps.tag || Fragment;
  8636. prevChildren = children;
  8637. children = slots.default ? getTransitionRawChildren(slots.default()) : [];
  8638. for (let i = 0; i < children.length; i++) {
  8639. const child = children[i];
  8640. if (child.key != null) {
  8641. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  8642. }
  8643. else {
  8644. warn(`<TransitionGroup> children must be keyed.`);
  8645. }
  8646. }
  8647. if (prevChildren) {
  8648. for (let i = 0; i < prevChildren.length; i++) {
  8649. const child = prevChildren[i];
  8650. setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
  8651. positionMap.set(child, child.el.getBoundingClientRect());
  8652. }
  8653. }
  8654. return createVNode(tag, null, children);
  8655. };
  8656. }
  8657. };
  8658. const TransitionGroup = TransitionGroupImpl;
  8659. function callPendingCbs(c) {
  8660. const el = c.el;
  8661. if (el._moveCb) {
  8662. el._moveCb();
  8663. }
  8664. if (el._enterCb) {
  8665. el._enterCb();
  8666. }
  8667. }
  8668. function recordPosition(c) {
  8669. newPositionMap.set(c, c.el.getBoundingClientRect());
  8670. }
  8671. function applyTranslation(c) {
  8672. const oldPos = positionMap.get(c);
  8673. const newPos = newPositionMap.get(c);
  8674. const dx = oldPos.left - newPos.left;
  8675. const dy = oldPos.top - newPos.top;
  8676. if (dx || dy) {
  8677. const s = c.el.style;
  8678. s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
  8679. s.transitionDuration = '0s';
  8680. return c;
  8681. }
  8682. }
  8683. // this is put in a dedicated function to avoid the line from being treeshaken
  8684. function forceReflow() {
  8685. return document.body.offsetHeight;
  8686. }
  8687. function hasCSSTransform(el, root, moveClass) {
  8688. // Detect whether an element with the move class applied has
  8689. // CSS transitions. Since the element may be inside an entering
  8690. // transition at this very moment, we make a clone of it and remove
  8691. // all other transition classes applied to ensure only the move class
  8692. // is applied.
  8693. const clone = el.cloneNode();
  8694. if (el._vtc) {
  8695. el._vtc.forEach(cls => {
  8696. cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
  8697. });
  8698. }
  8699. moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
  8700. clone.style.display = 'none';
  8701. const container = (root.nodeType === 1
  8702. ? root
  8703. : root.parentNode);
  8704. container.appendChild(clone);
  8705. const { hasTransform } = getTransitionInfo(clone);
  8706. container.removeChild(clone);
  8707. return hasTransform;
  8708. }
  8709. const getModelAssigner = (vnode) => {
  8710. const fn = vnode.props['onUpdate:modelValue'];
  8711. return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
  8712. };
  8713. function onCompositionStart(e) {
  8714. e.target.composing = true;
  8715. }
  8716. function onCompositionEnd(e) {
  8717. const target = e.target;
  8718. if (target.composing) {
  8719. target.composing = false;
  8720. trigger$1(target, 'input');
  8721. }
  8722. }
  8723. function trigger$1(el, type) {
  8724. const e = document.createEvent('HTMLEvents');
  8725. e.initEvent(type, true, true);
  8726. el.dispatchEvent(e);
  8727. }
  8728. // We are exporting the v-model runtime directly as vnode hooks so that it can
  8729. // be tree-shaken in case v-model is never used.
  8730. const vModelText = {
  8731. created(el, { modifiers: { lazy, trim, number } }, vnode) {
  8732. el._assign = getModelAssigner(vnode);
  8733. const castToNumber = number || el.type === 'number';
  8734. addEventListener(el, lazy ? 'change' : 'input', e => {
  8735. if (e.target.composing)
  8736. return;
  8737. let domValue = el.value;
  8738. if (trim) {
  8739. domValue = domValue.trim();
  8740. }
  8741. else if (castToNumber) {
  8742. domValue = toNumber(domValue);
  8743. }
  8744. el._assign(domValue);
  8745. });
  8746. if (trim) {
  8747. addEventListener(el, 'change', () => {
  8748. el.value = el.value.trim();
  8749. });
  8750. }
  8751. if (!lazy) {
  8752. addEventListener(el, 'compositionstart', onCompositionStart);
  8753. addEventListener(el, 'compositionend', onCompositionEnd);
  8754. // Safari < 10.2 & UIWebView doesn't fire compositionend when
  8755. // switching focus before confirming composition choice
  8756. // this also fixes the issue where some browsers e.g. iOS Chrome
  8757. // fires "change" instead of "input" on autocomplete.
  8758. addEventListener(el, 'change', onCompositionEnd);
  8759. }
  8760. },
  8761. // set value on mounted so it's after min/max for type="range"
  8762. mounted(el, { value }) {
  8763. el.value = value == null ? '' : value;
  8764. },
  8765. beforeUpdate(el, { value, modifiers: { trim, number } }, vnode) {
  8766. el._assign = getModelAssigner(vnode);
  8767. // avoid clearing unresolved text. #2302
  8768. if (el.composing)
  8769. return;
  8770. if (document.activeElement === el) {
  8771. if (trim && el.value.trim() === value) {
  8772. return;
  8773. }
  8774. if ((number || el.type === 'number') && toNumber(el.value) === value) {
  8775. return;
  8776. }
  8777. }
  8778. const newValue = value == null ? '' : value;
  8779. if (el.value !== newValue) {
  8780. el.value = newValue;
  8781. }
  8782. }
  8783. };
  8784. const vModelCheckbox = {
  8785. created(el, binding, vnode) {
  8786. setChecked(el, binding, vnode);
  8787. el._assign = getModelAssigner(vnode);
  8788. addEventListener(el, 'change', () => {
  8789. const modelValue = el._modelValue;
  8790. const elementValue = getValue(el);
  8791. const checked = el.checked;
  8792. const assign = el._assign;
  8793. if (isArray(modelValue)) {
  8794. const index = looseIndexOf(modelValue, elementValue);
  8795. const found = index !== -1;
  8796. if (checked && !found) {
  8797. assign(modelValue.concat(elementValue));
  8798. }
  8799. else if (!checked && found) {
  8800. const filtered = [...modelValue];
  8801. filtered.splice(index, 1);
  8802. assign(filtered);
  8803. }
  8804. }
  8805. else if (isSet(modelValue)) {
  8806. if (checked) {
  8807. modelValue.add(elementValue);
  8808. }
  8809. else {
  8810. modelValue.delete(elementValue);
  8811. }
  8812. }
  8813. else {
  8814. assign(getCheckboxValue(el, checked));
  8815. }
  8816. });
  8817. },
  8818. beforeUpdate(el, binding, vnode) {
  8819. el._assign = getModelAssigner(vnode);
  8820. setChecked(el, binding, vnode);
  8821. }
  8822. };
  8823. function setChecked(el, { value, oldValue }, vnode) {
  8824. el._modelValue = value;
  8825. if (isArray(value)) {
  8826. el.checked = looseIndexOf(value, vnode.props.value) > -1;
  8827. }
  8828. else if (isSet(value)) {
  8829. el.checked = value.has(vnode.props.value);
  8830. }
  8831. else if (value !== oldValue) {
  8832. el.checked = looseEqual(value, getCheckboxValue(el, true));
  8833. }
  8834. }
  8835. const vModelRadio = {
  8836. created(el, { value }, vnode) {
  8837. el.checked = looseEqual(value, vnode.props.value);
  8838. el._assign = getModelAssigner(vnode);
  8839. addEventListener(el, 'change', () => {
  8840. el._assign(getValue(el));
  8841. });
  8842. },
  8843. beforeUpdate(el, { value, oldValue }, vnode) {
  8844. el._assign = getModelAssigner(vnode);
  8845. if (value !== oldValue) {
  8846. el.checked = looseEqual(value, vnode.props.value);
  8847. }
  8848. }
  8849. };
  8850. const vModelSelect = {
  8851. created(el, { modifiers: { number } }, vnode) {
  8852. addEventListener(el, 'change', () => {
  8853. const selectedVal = Array.prototype.filter
  8854. .call(el.options, (o) => o.selected)
  8855. .map((o) => number ? toNumber(getValue(o)) : getValue(o));
  8856. el._assign(el.multiple ? selectedVal : selectedVal[0]);
  8857. });
  8858. el._assign = getModelAssigner(vnode);
  8859. },
  8860. // set value in mounted & updated because <select> relies on its children
  8861. // <option>s.
  8862. mounted(el, { value }) {
  8863. setSelected(el, value);
  8864. },
  8865. beforeUpdate(el, _binding, vnode) {
  8866. el._assign = getModelAssigner(vnode);
  8867. },
  8868. updated(el, { value }) {
  8869. setSelected(el, value);
  8870. }
  8871. };
  8872. function setSelected(el, value) {
  8873. const isMultiple = el.multiple;
  8874. if (isMultiple && !isArray(value) && !isSet(value)) {
  8875. warn(`<select multiple v-model> expects an Array or Set value for its binding, ` +
  8876. `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
  8877. return;
  8878. }
  8879. for (let i = 0, l = el.options.length; i < l; i++) {
  8880. const option = el.options[i];
  8881. const optionValue = getValue(option);
  8882. if (isMultiple) {
  8883. if (isArray(value)) {
  8884. option.selected = looseIndexOf(value, optionValue) > -1;
  8885. }
  8886. else {
  8887. option.selected = value.has(optionValue);
  8888. }
  8889. }
  8890. else {
  8891. if (looseEqual(getValue(option), value)) {
  8892. el.selectedIndex = i;
  8893. return;
  8894. }
  8895. }
  8896. }
  8897. if (!isMultiple) {
  8898. el.selectedIndex = -1;
  8899. }
  8900. }
  8901. // retrieve raw value set via :value bindings
  8902. function getValue(el) {
  8903. return '_value' in el ? el._value : el.value;
  8904. }
  8905. // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
  8906. function getCheckboxValue(el, checked) {
  8907. const key = checked ? '_trueValue' : '_falseValue';
  8908. return key in el ? el[key] : checked;
  8909. }
  8910. const vModelDynamic = {
  8911. created(el, binding, vnode) {
  8912. callModelHook(el, binding, vnode, null, 'created');
  8913. },
  8914. mounted(el, binding, vnode) {
  8915. callModelHook(el, binding, vnode, null, 'mounted');
  8916. },
  8917. beforeUpdate(el, binding, vnode, prevVNode) {
  8918. callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
  8919. },
  8920. updated(el, binding, vnode, prevVNode) {
  8921. callModelHook(el, binding, vnode, prevVNode, 'updated');
  8922. }
  8923. };
  8924. function callModelHook(el, binding, vnode, prevVNode, hook) {
  8925. let modelToUse;
  8926. switch (el.tagName) {
  8927. case 'SELECT':
  8928. modelToUse = vModelSelect;
  8929. break;
  8930. case 'TEXTAREA':
  8931. modelToUse = vModelText;
  8932. break;
  8933. default:
  8934. switch (vnode.props && vnode.props.type) {
  8935. case 'checkbox':
  8936. modelToUse = vModelCheckbox;
  8937. break;
  8938. case 'radio':
  8939. modelToUse = vModelRadio;
  8940. break;
  8941. default:
  8942. modelToUse = vModelText;
  8943. }
  8944. }
  8945. const fn = modelToUse[hook];
  8946. fn && fn(el, binding, vnode, prevVNode);
  8947. }
  8948. const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
  8949. const modifierGuards = {
  8950. stop: e => e.stopPropagation(),
  8951. prevent: e => e.preventDefault(),
  8952. self: e => e.target !== e.currentTarget,
  8953. ctrl: e => !e.ctrlKey,
  8954. shift: e => !e.shiftKey,
  8955. alt: e => !e.altKey,
  8956. meta: e => !e.metaKey,
  8957. left: e => 'button' in e && e.button !== 0,
  8958. middle: e => 'button' in e && e.button !== 1,
  8959. right: e => 'button' in e && e.button !== 2,
  8960. exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
  8961. };
  8962. /**
  8963. * @private
  8964. */
  8965. const withModifiers = (fn, modifiers) => {
  8966. return (event, ...args) => {
  8967. for (let i = 0; i < modifiers.length; i++) {
  8968. const guard = modifierGuards[modifiers[i]];
  8969. if (guard && guard(event, modifiers))
  8970. return;
  8971. }
  8972. return fn(event, ...args);
  8973. };
  8974. };
  8975. // Kept for 2.x compat.
  8976. // Note: IE11 compat for `spacebar` and `del` is removed for now.
  8977. const keyNames = {
  8978. esc: 'escape',
  8979. space: ' ',
  8980. up: 'arrow-up',
  8981. left: 'arrow-left',
  8982. right: 'arrow-right',
  8983. down: 'arrow-down',
  8984. delete: 'backspace'
  8985. };
  8986. /**
  8987. * @private
  8988. */
  8989. const withKeys = (fn, modifiers) => {
  8990. return (event) => {
  8991. if (!('key' in event))
  8992. return;
  8993. const eventKey = hyphenate(event.key);
  8994. if (
  8995. // None of the provided key modifiers match the current event key
  8996. !modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
  8997. return;
  8998. }
  8999. return fn(event);
  9000. };
  9001. };
  9002. const vShow = {
  9003. beforeMount(el, { value }, { transition }) {
  9004. el._vod = el.style.display === 'none' ? '' : el.style.display;
  9005. if (transition && value) {
  9006. transition.beforeEnter(el);
  9007. }
  9008. else {
  9009. setDisplay(el, value);
  9010. }
  9011. },
  9012. mounted(el, { value }, { transition }) {
  9013. if (transition && value) {
  9014. transition.enter(el);
  9015. }
  9016. },
  9017. updated(el, { value, oldValue }, { transition }) {
  9018. if (!value === !oldValue)
  9019. return;
  9020. if (transition) {
  9021. if (value) {
  9022. transition.beforeEnter(el);
  9023. setDisplay(el, true);
  9024. transition.enter(el);
  9025. }
  9026. else {
  9027. transition.leave(el, () => {
  9028. setDisplay(el, false);
  9029. });
  9030. }
  9031. }
  9032. else {
  9033. setDisplay(el, value);
  9034. }
  9035. },
  9036. beforeUnmount(el, { value }) {
  9037. setDisplay(el, value);
  9038. }
  9039. };
  9040. function setDisplay(el, value) {
  9041. el.style.display = value ? el._vod : 'none';
  9042. }
  9043. const rendererOptions = extend({ patchProp, forcePatchProp }, nodeOps);
  9044. // lazy create the renderer - this makes core renderer logic tree-shakable
  9045. // in case the user only imports reactivity utilities from Vue.
  9046. let renderer;
  9047. let enabledHydration = false;
  9048. function ensureRenderer() {
  9049. return renderer || (renderer = createRenderer(rendererOptions));
  9050. }
  9051. function ensureHydrationRenderer() {
  9052. renderer = enabledHydration
  9053. ? renderer
  9054. : createHydrationRenderer(rendererOptions);
  9055. enabledHydration = true;
  9056. return renderer;
  9057. }
  9058. // use explicit type casts here to avoid import() calls in rolled-up d.ts
  9059. const render = ((...args) => {
  9060. ensureRenderer().render(...args);
  9061. });
  9062. const hydrate = ((...args) => {
  9063. ensureHydrationRenderer().hydrate(...args);
  9064. });
  9065. const createApp = ((...args) => {
  9066. const app = ensureRenderer().createApp(...args);
  9067. {
  9068. injectNativeTagCheck(app);
  9069. }
  9070. const { mount } = app;
  9071. app.mount = (containerOrSelector) => {
  9072. const container = normalizeContainer(containerOrSelector);
  9073. if (!container)
  9074. return;
  9075. const component = app._component;
  9076. if (!isFunction(component) && !component.render && !component.template) {
  9077. component.template = container.innerHTML;
  9078. }
  9079. // clear content before mounting
  9080. container.innerHTML = '';
  9081. const proxy = mount(container);
  9082. container.removeAttribute('v-cloak');
  9083. container.setAttribute('data-v-app', '');
  9084. return proxy;
  9085. };
  9086. return app;
  9087. });
  9088. const createSSRApp = ((...args) => {
  9089. const app = ensureHydrationRenderer().createApp(...args);
  9090. {
  9091. injectNativeTagCheck(app);
  9092. }
  9093. const { mount } = app;
  9094. app.mount = (containerOrSelector) => {
  9095. const container = normalizeContainer(containerOrSelector);
  9096. if (container) {
  9097. return mount(container, true);
  9098. }
  9099. };
  9100. return app;
  9101. });
  9102. function injectNativeTagCheck(app) {
  9103. // Inject `isNativeTag`
  9104. // this is used for component name validation (dev only)
  9105. Object.defineProperty(app.config, 'isNativeTag', {
  9106. value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
  9107. writable: false
  9108. });
  9109. }
  9110. function normalizeContainer(container) {
  9111. if (isString(container)) {
  9112. const res = document.querySelector(container);
  9113. if ( !res) {
  9114. warn(`Failed to mount app: mount target selector returned null.`);
  9115. }
  9116. return res;
  9117. }
  9118. return container;
  9119. }
  9120. function initDev() {
  9121. const target = getGlobalThis();
  9122. target.__VUE__ = true;
  9123. setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
  9124. {
  9125. console.info(`You are running a development build of Vue.\n` +
  9126. `Make sure to use the production build (*.prod.js) when deploying for production.`);
  9127. initCustomFormatter();
  9128. }
  9129. }
  9130. function defaultOnError(error) {
  9131. throw error;
  9132. }
  9133. function createCompilerError(code, loc, messages, additionalMessage) {
  9134. const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
  9135. ;
  9136. const error = new SyntaxError(String(msg));
  9137. error.code = code;
  9138. error.loc = loc;
  9139. return error;
  9140. }
  9141. const errorMessages = {
  9142. // parse errors
  9143. [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
  9144. [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
  9145. [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
  9146. [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
  9147. [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
  9148. [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
  9149. [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
  9150. [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
  9151. [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
  9152. [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
  9153. [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
  9154. [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
  9155. [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
  9156. [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
  9157. [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
  9158. [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
  9159. [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
  9160. [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
  9161. [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
  9162. [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
  9163. [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
  9164. [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
  9165. // Vue-specific parse errors
  9166. [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
  9167. [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
  9168. [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
  9169. [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
  9170. 'Note that dynamic directive argument cannot contain spaces.',
  9171. // transform errors
  9172. [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
  9173. [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
  9174. [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
  9175. [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
  9176. [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
  9177. [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
  9178. [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
  9179. [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
  9180. [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
  9181. [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
  9182. `When there are multiple named slots, all slots should use <template> ` +
  9183. `syntax to avoid scope ambiguity.`,
  9184. [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
  9185. [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
  9186. `default slot. These children will be ignored.`,
  9187. [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
  9188. [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
  9189. [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
  9190. [42 /* X_V_MODEL_ON_SCOPE_VARIABLE */]: `v-model cannot be used on v-for or v-slot scope variables because they are not writable.`,
  9191. [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
  9192. [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
  9193. // generic errors
  9194. [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
  9195. [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
  9196. [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
  9197. [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
  9198. };
  9199. const FRAGMENT = Symbol( `Fragment` );
  9200. const TELEPORT = Symbol( `Teleport` );
  9201. const SUSPENSE = Symbol( `Suspense` );
  9202. const KEEP_ALIVE = Symbol( `KeepAlive` );
  9203. const BASE_TRANSITION = Symbol( `BaseTransition` );
  9204. const OPEN_BLOCK = Symbol( `openBlock` );
  9205. const CREATE_BLOCK = Symbol( `createBlock` );
  9206. const CREATE_VNODE = Symbol( `createVNode` );
  9207. const CREATE_COMMENT = Symbol( `createCommentVNode` );
  9208. const CREATE_TEXT = Symbol( `createTextVNode` );
  9209. const CREATE_STATIC = Symbol( `createStaticVNode` );
  9210. const RESOLVE_COMPONENT = Symbol( `resolveComponent` );
  9211. const RESOLVE_DYNAMIC_COMPONENT = Symbol( `resolveDynamicComponent` );
  9212. const RESOLVE_DIRECTIVE = Symbol( `resolveDirective` );
  9213. const WITH_DIRECTIVES = Symbol( `withDirectives` );
  9214. const RENDER_LIST = Symbol( `renderList` );
  9215. const RENDER_SLOT = Symbol( `renderSlot` );
  9216. const CREATE_SLOTS = Symbol( `createSlots` );
  9217. const TO_DISPLAY_STRING = Symbol( `toDisplayString` );
  9218. const MERGE_PROPS = Symbol( `mergeProps` );
  9219. const TO_HANDLERS = Symbol( `toHandlers` );
  9220. const CAMELIZE = Symbol( `camelize` );
  9221. const CAPITALIZE = Symbol( `capitalize` );
  9222. const TO_HANDLER_KEY = Symbol( `toHandlerKey` );
  9223. const SET_BLOCK_TRACKING = Symbol( `setBlockTracking` );
  9224. const PUSH_SCOPE_ID = Symbol( `pushScopeId` );
  9225. const POP_SCOPE_ID = Symbol( `popScopeId` );
  9226. const WITH_SCOPE_ID = Symbol( `withScopeId` );
  9227. const WITH_CTX = Symbol( `withCtx` );
  9228. // Name mapping for runtime helpers that need to be imported from 'vue' in
  9229. // generated code. Make sure these are correctly exported in the runtime!
  9230. // Using `any` here because TS doesn't allow symbols as index type.
  9231. const helperNameMap = {
  9232. [FRAGMENT]: `Fragment`,
  9233. [TELEPORT]: `Teleport`,
  9234. [SUSPENSE]: `Suspense`,
  9235. [KEEP_ALIVE]: `KeepAlive`,
  9236. [BASE_TRANSITION]: `BaseTransition`,
  9237. [OPEN_BLOCK]: `openBlock`,
  9238. [CREATE_BLOCK]: `createBlock`,
  9239. [CREATE_VNODE]: `createVNode`,
  9240. [CREATE_COMMENT]: `createCommentVNode`,
  9241. [CREATE_TEXT]: `createTextVNode`,
  9242. [CREATE_STATIC]: `createStaticVNode`,
  9243. [RESOLVE_COMPONENT]: `resolveComponent`,
  9244. [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
  9245. [RESOLVE_DIRECTIVE]: `resolveDirective`,
  9246. [WITH_DIRECTIVES]: `withDirectives`,
  9247. [RENDER_LIST]: `renderList`,
  9248. [RENDER_SLOT]: `renderSlot`,
  9249. [CREATE_SLOTS]: `createSlots`,
  9250. [TO_DISPLAY_STRING]: `toDisplayString`,
  9251. [MERGE_PROPS]: `mergeProps`,
  9252. [TO_HANDLERS]: `toHandlers`,
  9253. [CAMELIZE]: `camelize`,
  9254. [CAPITALIZE]: `capitalize`,
  9255. [TO_HANDLER_KEY]: `toHandlerKey`,
  9256. [SET_BLOCK_TRACKING]: `setBlockTracking`,
  9257. [PUSH_SCOPE_ID]: `pushScopeId`,
  9258. [POP_SCOPE_ID]: `popScopeId`,
  9259. [WITH_SCOPE_ID]: `withScopeId`,
  9260. [WITH_CTX]: `withCtx`
  9261. };
  9262. function registerRuntimeHelpers(helpers) {
  9263. Object.getOwnPropertySymbols(helpers).forEach(s => {
  9264. helperNameMap[s] = helpers[s];
  9265. });
  9266. }
  9267. // AST Utilities ---------------------------------------------------------------
  9268. // Some expressions, e.g. sequence and conditional expressions, are never
  9269. // associated with template nodes, so their source locations are just a stub.
  9270. // Container types like CompoundExpression also don't need a real location.
  9271. const locStub = {
  9272. source: '',
  9273. start: { line: 1, column: 1, offset: 0 },
  9274. end: { line: 1, column: 1, offset: 0 }
  9275. };
  9276. function createRoot(children, loc = locStub) {
  9277. return {
  9278. type: 0 /* ROOT */,
  9279. children,
  9280. helpers: [],
  9281. components: [],
  9282. directives: [],
  9283. hoists: [],
  9284. imports: [],
  9285. cached: 0,
  9286. temps: 0,
  9287. codegenNode: undefined,
  9288. loc
  9289. };
  9290. }
  9291. function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
  9292. if (context) {
  9293. if (isBlock) {
  9294. context.helper(OPEN_BLOCK);
  9295. context.helper(CREATE_BLOCK);
  9296. }
  9297. else {
  9298. context.helper(CREATE_VNODE);
  9299. }
  9300. if (directives) {
  9301. context.helper(WITH_DIRECTIVES);
  9302. }
  9303. }
  9304. return {
  9305. type: 13 /* VNODE_CALL */,
  9306. tag,
  9307. props,
  9308. children,
  9309. patchFlag,
  9310. dynamicProps,
  9311. directives,
  9312. isBlock,
  9313. disableTracking,
  9314. loc
  9315. };
  9316. }
  9317. function createArrayExpression(elements, loc = locStub) {
  9318. return {
  9319. type: 17 /* JS_ARRAY_EXPRESSION */,
  9320. loc,
  9321. elements
  9322. };
  9323. }
  9324. function createObjectExpression(properties, loc = locStub) {
  9325. return {
  9326. type: 15 /* JS_OBJECT_EXPRESSION */,
  9327. loc,
  9328. properties
  9329. };
  9330. }
  9331. function createObjectProperty(key, value) {
  9332. return {
  9333. type: 16 /* JS_PROPERTY */,
  9334. loc: locStub,
  9335. key: isString(key) ? createSimpleExpression(key, true) : key,
  9336. value
  9337. };
  9338. }
  9339. function createSimpleExpression(content, isStatic, loc = locStub, isConstant = false) {
  9340. return {
  9341. type: 4 /* SIMPLE_EXPRESSION */,
  9342. loc,
  9343. isConstant,
  9344. content,
  9345. isStatic
  9346. };
  9347. }
  9348. function createCompoundExpression(children, loc = locStub) {
  9349. return {
  9350. type: 8 /* COMPOUND_EXPRESSION */,
  9351. loc,
  9352. children
  9353. };
  9354. }
  9355. function createCallExpression(callee, args = [], loc = locStub) {
  9356. return {
  9357. type: 14 /* JS_CALL_EXPRESSION */,
  9358. loc,
  9359. callee,
  9360. arguments: args
  9361. };
  9362. }
  9363. function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
  9364. return {
  9365. type: 18 /* JS_FUNCTION_EXPRESSION */,
  9366. params,
  9367. returns,
  9368. newline,
  9369. isSlot,
  9370. loc
  9371. };
  9372. }
  9373. function createConditionalExpression(test, consequent, alternate, newline = true) {
  9374. return {
  9375. type: 19 /* JS_CONDITIONAL_EXPRESSION */,
  9376. test,
  9377. consequent,
  9378. alternate,
  9379. newline,
  9380. loc: locStub
  9381. };
  9382. }
  9383. function createCacheExpression(index, value, isVNode = false) {
  9384. return {
  9385. type: 20 /* JS_CACHE_EXPRESSION */,
  9386. index,
  9387. value,
  9388. isVNode,
  9389. loc: locStub
  9390. };
  9391. }
  9392. const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
  9393. const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
  9394. function isCoreComponent(tag) {
  9395. if (isBuiltInType(tag, 'Teleport')) {
  9396. return TELEPORT;
  9397. }
  9398. else if (isBuiltInType(tag, 'Suspense')) {
  9399. return SUSPENSE;
  9400. }
  9401. else if (isBuiltInType(tag, 'KeepAlive')) {
  9402. return KEEP_ALIVE;
  9403. }
  9404. else if (isBuiltInType(tag, 'BaseTransition')) {
  9405. return BASE_TRANSITION;
  9406. }
  9407. }
  9408. const nonIdentifierRE = /^\d|[^\$\w]/;
  9409. const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
  9410. const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
  9411. const isMemberExpression = (path) => {
  9412. if (!path)
  9413. return false;
  9414. return memberExpRE.test(path.trim());
  9415. };
  9416. function getInnerRange(loc, offset, length) {
  9417. const source = loc.source.substr(offset, length);
  9418. const newLoc = {
  9419. source,
  9420. start: advancePositionWithClone(loc.start, loc.source, offset),
  9421. end: loc.end
  9422. };
  9423. if (length != null) {
  9424. newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
  9425. }
  9426. return newLoc;
  9427. }
  9428. function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
  9429. return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
  9430. }
  9431. // advance by mutation without cloning (for performance reasons), since this
  9432. // gets called a lot in the parser
  9433. function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
  9434. let linesCount = 0;
  9435. let lastNewLinePos = -1;
  9436. for (let i = 0; i < numberOfCharacters; i++) {
  9437. if (source.charCodeAt(i) === 10 /* newline char code */) {
  9438. linesCount++;
  9439. lastNewLinePos = i;
  9440. }
  9441. }
  9442. pos.offset += numberOfCharacters;
  9443. pos.line += linesCount;
  9444. pos.column =
  9445. lastNewLinePos === -1
  9446. ? pos.column + numberOfCharacters
  9447. : numberOfCharacters - lastNewLinePos;
  9448. return pos;
  9449. }
  9450. function assert(condition, msg) {
  9451. /* istanbul ignore if */
  9452. if (!condition) {
  9453. throw new Error(msg || `unexpected compiler condition`);
  9454. }
  9455. }
  9456. function findDir(node, name, allowEmpty = false) {
  9457. for (let i = 0; i < node.props.length; i++) {
  9458. const p = node.props[i];
  9459. if (p.type === 7 /* DIRECTIVE */ &&
  9460. (allowEmpty || p.exp) &&
  9461. (isString(name) ? p.name === name : name.test(p.name))) {
  9462. return p;
  9463. }
  9464. }
  9465. }
  9466. function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
  9467. for (let i = 0; i < node.props.length; i++) {
  9468. const p = node.props[i];
  9469. if (p.type === 6 /* ATTRIBUTE */) {
  9470. if (dynamicOnly)
  9471. continue;
  9472. if (p.name === name && (p.value || allowEmpty)) {
  9473. return p;
  9474. }
  9475. }
  9476. else if (p.name === 'bind' &&
  9477. (p.exp || allowEmpty) &&
  9478. isBindKey(p.arg, name)) {
  9479. return p;
  9480. }
  9481. }
  9482. }
  9483. function isBindKey(arg, name) {
  9484. return !!(arg && isStaticExp(arg) && arg.content === name);
  9485. }
  9486. function hasDynamicKeyVBind(node) {
  9487. return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
  9488. p.name === 'bind' &&
  9489. (!p.arg || // v-bind="obj"
  9490. p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
  9491. !p.arg.isStatic) // v-bind:[foo]
  9492. );
  9493. }
  9494. function isText(node) {
  9495. return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
  9496. }
  9497. function isVSlot(p) {
  9498. return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
  9499. }
  9500. function isTemplateNode(node) {
  9501. return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
  9502. }
  9503. function isSlotOutlet(node) {
  9504. return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
  9505. }
  9506. function injectProp(node, prop, context) {
  9507. let propsWithInjection;
  9508. const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
  9509. if (props == null || isString(props)) {
  9510. propsWithInjection = createObjectExpression([prop]);
  9511. }
  9512. else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
  9513. // merged props... add ours
  9514. // only inject key to object literal if it's the first argument so that
  9515. // if doesn't override user provided keys
  9516. const first = props.arguments[0];
  9517. if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
  9518. first.properties.unshift(prop);
  9519. }
  9520. else {
  9521. if (props.callee === TO_HANDLERS) {
  9522. // #2366
  9523. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  9524. createObjectExpression([prop]),
  9525. props
  9526. ]);
  9527. }
  9528. else {
  9529. props.arguments.unshift(createObjectExpression([prop]));
  9530. }
  9531. }
  9532. !propsWithInjection && (propsWithInjection = props);
  9533. }
  9534. else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  9535. let alreadyExists = false;
  9536. // check existing key to avoid overriding user provided keys
  9537. if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
  9538. const propKeyName = prop.key.content;
  9539. alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  9540. p.key.content === propKeyName);
  9541. }
  9542. if (!alreadyExists) {
  9543. props.properties.unshift(prop);
  9544. }
  9545. propsWithInjection = props;
  9546. }
  9547. else {
  9548. // single v-bind with expression, return a merged replacement
  9549. propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
  9550. createObjectExpression([prop]),
  9551. props
  9552. ]);
  9553. }
  9554. if (node.type === 13 /* VNODE_CALL */) {
  9555. node.props = propsWithInjection;
  9556. }
  9557. else {
  9558. node.arguments[2] = propsWithInjection;
  9559. }
  9560. }
  9561. function toValidAssetId(name, type) {
  9562. return `_${type}_${name.replace(/[^\w]/g, '_')}`;
  9563. }
  9564. // The default decoder only provides escapes for characters reserved as part of
  9565. // the template syntax, and is only used if the custom renderer did not provide
  9566. // a platform-specific decoder.
  9567. const decodeRE = /&(gt|lt|amp|apos|quot);/g;
  9568. const decodeMap = {
  9569. gt: '>',
  9570. lt: '<',
  9571. amp: '&',
  9572. apos: "'",
  9573. quot: '"'
  9574. };
  9575. const defaultParserOptions = {
  9576. delimiters: [`{{`, `}}`],
  9577. getNamespace: () => 0 /* HTML */,
  9578. getTextMode: () => 0 /* DATA */,
  9579. isVoidTag: NO,
  9580. isPreTag: NO,
  9581. isCustomElement: NO,
  9582. decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
  9583. onError: defaultOnError,
  9584. comments: false
  9585. };
  9586. function baseParse(content, options = {}) {
  9587. const context = createParserContext(content, options);
  9588. const start = getCursor(context);
  9589. return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
  9590. }
  9591. function createParserContext(content, rawOptions) {
  9592. const options = extend({}, defaultParserOptions);
  9593. for (const key in rawOptions) {
  9594. // @ts-ignore
  9595. options[key] = rawOptions[key] || defaultParserOptions[key];
  9596. }
  9597. return {
  9598. options,
  9599. column: 1,
  9600. line: 1,
  9601. offset: 0,
  9602. originalSource: content,
  9603. source: content,
  9604. inPre: false,
  9605. inVPre: false
  9606. };
  9607. }
  9608. function parseChildren(context, mode, ancestors) {
  9609. const parent = last(ancestors);
  9610. const ns = parent ? parent.ns : 0 /* HTML */;
  9611. const nodes = [];
  9612. while (!isEnd(context, mode, ancestors)) {
  9613. const s = context.source;
  9614. let node = undefined;
  9615. if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
  9616. if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
  9617. // '{{'
  9618. node = parseInterpolation(context, mode);
  9619. }
  9620. else if (mode === 0 /* DATA */ && s[0] === '<') {
  9621. // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
  9622. if (s.length === 1) {
  9623. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
  9624. }
  9625. else if (s[1] === '!') {
  9626. // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
  9627. if (startsWith(s, '<!--')) {
  9628. node = parseComment(context);
  9629. }
  9630. else if (startsWith(s, '<!DOCTYPE')) {
  9631. // Ignore DOCTYPE by a limitation.
  9632. node = parseBogusComment(context);
  9633. }
  9634. else if (startsWith(s, '<![CDATA[')) {
  9635. if (ns !== 0 /* HTML */) {
  9636. node = parseCDATA(context, ancestors);
  9637. }
  9638. else {
  9639. emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
  9640. node = parseBogusComment(context);
  9641. }
  9642. }
  9643. else {
  9644. emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
  9645. node = parseBogusComment(context);
  9646. }
  9647. }
  9648. else if (s[1] === '/') {
  9649. // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
  9650. if (s.length === 2) {
  9651. emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
  9652. }
  9653. else if (s[2] === '>') {
  9654. emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
  9655. advanceBy(context, 3);
  9656. continue;
  9657. }
  9658. else if (/[a-z]/i.test(s[2])) {
  9659. emitError(context, 23 /* X_INVALID_END_TAG */);
  9660. parseTag(context, 1 /* End */, parent);
  9661. continue;
  9662. }
  9663. else {
  9664. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
  9665. node = parseBogusComment(context);
  9666. }
  9667. }
  9668. else if (/[a-z]/i.test(s[1])) {
  9669. node = parseElement(context, ancestors);
  9670. }
  9671. else if (s[1] === '?') {
  9672. emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
  9673. node = parseBogusComment(context);
  9674. }
  9675. else {
  9676. emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
  9677. }
  9678. }
  9679. }
  9680. if (!node) {
  9681. node = parseText(context, mode);
  9682. }
  9683. if (isArray(node)) {
  9684. for (let i = 0; i < node.length; i++) {
  9685. pushNode(nodes, node[i]);
  9686. }
  9687. }
  9688. else {
  9689. pushNode(nodes, node);
  9690. }
  9691. }
  9692. // Whitespace management for more efficient output
  9693. // (same as v2 whitespace: 'condense')
  9694. let removedWhitespace = false;
  9695. if (mode !== 2 /* RAWTEXT */) {
  9696. for (let i = 0; i < nodes.length; i++) {
  9697. const node = nodes[i];
  9698. if (!context.inPre && node.type === 2 /* TEXT */) {
  9699. if (!/[^\t\r\n\f ]/.test(node.content)) {
  9700. const prev = nodes[i - 1];
  9701. const next = nodes[i + 1];
  9702. // If:
  9703. // - the whitespace is the first or last node, or:
  9704. // - the whitespace is adjacent to a comment, or:
  9705. // - the whitespace is between two elements AND contains newline
  9706. // Then the whitespace is ignored.
  9707. if (!prev ||
  9708. !next ||
  9709. prev.type === 3 /* COMMENT */ ||
  9710. next.type === 3 /* COMMENT */ ||
  9711. (prev.type === 1 /* ELEMENT */ &&
  9712. next.type === 1 /* ELEMENT */ &&
  9713. /[\r\n]/.test(node.content))) {
  9714. removedWhitespace = true;
  9715. nodes[i] = null;
  9716. }
  9717. else {
  9718. // Otherwise, condensed consecutive whitespace inside the text
  9719. // down to a single space
  9720. node.content = ' ';
  9721. }
  9722. }
  9723. else {
  9724. node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
  9725. }
  9726. }
  9727. }
  9728. if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
  9729. // remove leading newline per html spec
  9730. // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
  9731. const first = nodes[0];
  9732. if (first && first.type === 2 /* TEXT */) {
  9733. first.content = first.content.replace(/^\r?\n/, '');
  9734. }
  9735. }
  9736. }
  9737. return removedWhitespace ? nodes.filter(Boolean) : nodes;
  9738. }
  9739. function pushNode(nodes, node) {
  9740. if (node.type === 2 /* TEXT */) {
  9741. const prev = last(nodes);
  9742. // Merge if both this and the previous node are text and those are
  9743. // consecutive. This happens for cases like "a < b".
  9744. if (prev &&
  9745. prev.type === 2 /* TEXT */ &&
  9746. prev.loc.end.offset === node.loc.start.offset) {
  9747. prev.content += node.content;
  9748. prev.loc.end = node.loc.end;
  9749. prev.loc.source += node.loc.source;
  9750. return;
  9751. }
  9752. }
  9753. nodes.push(node);
  9754. }
  9755. function parseCDATA(context, ancestors) {
  9756. advanceBy(context, 9);
  9757. const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
  9758. if (context.source.length === 0) {
  9759. emitError(context, 6 /* EOF_IN_CDATA */);
  9760. }
  9761. else {
  9762. advanceBy(context, 3);
  9763. }
  9764. return nodes;
  9765. }
  9766. function parseComment(context) {
  9767. const start = getCursor(context);
  9768. let content;
  9769. // Regular comment.
  9770. const match = /--(\!)?>/.exec(context.source);
  9771. if (!match) {
  9772. content = context.source.slice(4);
  9773. advanceBy(context, context.source.length);
  9774. emitError(context, 7 /* EOF_IN_COMMENT */);
  9775. }
  9776. else {
  9777. if (match.index <= 3) {
  9778. emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
  9779. }
  9780. if (match[1]) {
  9781. emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
  9782. }
  9783. content = context.source.slice(4, match.index);
  9784. // Advancing with reporting nested comments.
  9785. const s = context.source.slice(0, match.index);
  9786. let prevIndex = 1, nestedIndex = 0;
  9787. while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
  9788. advanceBy(context, nestedIndex - prevIndex + 1);
  9789. if (nestedIndex + 4 < s.length) {
  9790. emitError(context, 16 /* NESTED_COMMENT */);
  9791. }
  9792. prevIndex = nestedIndex + 1;
  9793. }
  9794. advanceBy(context, match.index + match[0].length - prevIndex + 1);
  9795. }
  9796. return {
  9797. type: 3 /* COMMENT */,
  9798. content,
  9799. loc: getSelection(context, start)
  9800. };
  9801. }
  9802. function parseBogusComment(context) {
  9803. const start = getCursor(context);
  9804. const contentStart = context.source[1] === '?' ? 1 : 2;
  9805. let content;
  9806. const closeIndex = context.source.indexOf('>');
  9807. if (closeIndex === -1) {
  9808. content = context.source.slice(contentStart);
  9809. advanceBy(context, context.source.length);
  9810. }
  9811. else {
  9812. content = context.source.slice(contentStart, closeIndex);
  9813. advanceBy(context, closeIndex + 1);
  9814. }
  9815. return {
  9816. type: 3 /* COMMENT */,
  9817. content,
  9818. loc: getSelection(context, start)
  9819. };
  9820. }
  9821. function parseElement(context, ancestors) {
  9822. // Start tag.
  9823. const wasInPre = context.inPre;
  9824. const wasInVPre = context.inVPre;
  9825. const parent = last(ancestors);
  9826. const element = parseTag(context, 0 /* Start */, parent);
  9827. const isPreBoundary = context.inPre && !wasInPre;
  9828. const isVPreBoundary = context.inVPre && !wasInVPre;
  9829. if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
  9830. return element;
  9831. }
  9832. // Children.
  9833. ancestors.push(element);
  9834. const mode = context.options.getTextMode(element, parent);
  9835. const children = parseChildren(context, mode, ancestors);
  9836. ancestors.pop();
  9837. element.children = children;
  9838. // End tag.
  9839. if (startsWithEndTagOpen(context.source, element.tag)) {
  9840. parseTag(context, 1 /* End */, parent);
  9841. }
  9842. else {
  9843. emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
  9844. if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
  9845. const first = children[0];
  9846. if (first && startsWith(first.loc.source, '<!--')) {
  9847. emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
  9848. }
  9849. }
  9850. }
  9851. element.loc = getSelection(context, element.loc.start);
  9852. if (isPreBoundary) {
  9853. context.inPre = false;
  9854. }
  9855. if (isVPreBoundary) {
  9856. context.inVPre = false;
  9857. }
  9858. return element;
  9859. }
  9860. const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
  9861. /**
  9862. * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
  9863. */
  9864. function parseTag(context, type, parent) {
  9865. // Tag open.
  9866. const start = getCursor(context);
  9867. const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
  9868. const tag = match[1];
  9869. const ns = context.options.getNamespace(tag, parent);
  9870. advanceBy(context, match[0].length);
  9871. advanceSpaces(context);
  9872. // save current state in case we need to re-parse attributes with v-pre
  9873. const cursor = getCursor(context);
  9874. const currentSource = context.source;
  9875. // Attributes.
  9876. let props = parseAttributes(context, type);
  9877. // check <pre> tag
  9878. if (context.options.isPreTag(tag)) {
  9879. context.inPre = true;
  9880. }
  9881. // check v-pre
  9882. if (!context.inVPre &&
  9883. props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
  9884. context.inVPre = true;
  9885. // reset context
  9886. extend(context, cursor);
  9887. context.source = currentSource;
  9888. // re-parse attrs and filter out v-pre itself
  9889. props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
  9890. }
  9891. // Tag close.
  9892. let isSelfClosing = false;
  9893. if (context.source.length === 0) {
  9894. emitError(context, 9 /* EOF_IN_TAG */);
  9895. }
  9896. else {
  9897. isSelfClosing = startsWith(context.source, '/>');
  9898. if (type === 1 /* End */ && isSelfClosing) {
  9899. emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
  9900. }
  9901. advanceBy(context, isSelfClosing ? 2 : 1);
  9902. }
  9903. let tagType = 0 /* ELEMENT */;
  9904. const options = context.options;
  9905. if (!context.inVPre && !options.isCustomElement(tag)) {
  9906. const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
  9907. if (options.isNativeTag && !hasVIs) {
  9908. if (!options.isNativeTag(tag))
  9909. tagType = 1 /* COMPONENT */;
  9910. }
  9911. else if (hasVIs ||
  9912. isCoreComponent(tag) ||
  9913. (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
  9914. /^[A-Z]/.test(tag) ||
  9915. tag === 'component') {
  9916. tagType = 1 /* COMPONENT */;
  9917. }
  9918. if (tag === 'slot') {
  9919. tagType = 2 /* SLOT */;
  9920. }
  9921. else if (tag === 'template' &&
  9922. props.some(p => {
  9923. return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
  9924. })) {
  9925. tagType = 3 /* TEMPLATE */;
  9926. }
  9927. }
  9928. return {
  9929. type: 1 /* ELEMENT */,
  9930. ns,
  9931. tag,
  9932. tagType,
  9933. props,
  9934. isSelfClosing,
  9935. children: [],
  9936. loc: getSelection(context, start),
  9937. codegenNode: undefined // to be created during transform phase
  9938. };
  9939. }
  9940. function parseAttributes(context, type) {
  9941. const props = [];
  9942. const attributeNames = new Set();
  9943. while (context.source.length > 0 &&
  9944. !startsWith(context.source, '>') &&
  9945. !startsWith(context.source, '/>')) {
  9946. if (startsWith(context.source, '/')) {
  9947. emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
  9948. advanceBy(context, 1);
  9949. advanceSpaces(context);
  9950. continue;
  9951. }
  9952. if (type === 1 /* End */) {
  9953. emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
  9954. }
  9955. const attr = parseAttribute(context, attributeNames);
  9956. if (type === 0 /* Start */) {
  9957. props.push(attr);
  9958. }
  9959. if (/^[^\t\r\n\f />]/.test(context.source)) {
  9960. emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
  9961. }
  9962. advanceSpaces(context);
  9963. }
  9964. return props;
  9965. }
  9966. function parseAttribute(context, nameSet) {
  9967. // Name.
  9968. const start = getCursor(context);
  9969. const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
  9970. const name = match[0];
  9971. if (nameSet.has(name)) {
  9972. emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
  9973. }
  9974. nameSet.add(name);
  9975. if (name[0] === '=') {
  9976. emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
  9977. }
  9978. {
  9979. const pattern = /["'<]/g;
  9980. let m;
  9981. while ((m = pattern.exec(name))) {
  9982. emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
  9983. }
  9984. }
  9985. advanceBy(context, name.length);
  9986. // Value
  9987. let value = undefined;
  9988. if (/^[\t\r\n\f ]*=/.test(context.source)) {
  9989. advanceSpaces(context);
  9990. advanceBy(context, 1);
  9991. advanceSpaces(context);
  9992. value = parseAttributeValue(context);
  9993. if (!value) {
  9994. emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
  9995. }
  9996. }
  9997. const loc = getSelection(context, start);
  9998. if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
  9999. const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
  10000. const dirName = match[1] ||
  10001. (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
  10002. let arg;
  10003. if (match[2]) {
  10004. const isSlot = dirName === 'slot';
  10005. const startOffset = name.indexOf(match[2]);
  10006. const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
  10007. let content = match[2];
  10008. let isStatic = true;
  10009. if (content.startsWith('[')) {
  10010. isStatic = false;
  10011. if (!content.endsWith(']')) {
  10012. emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
  10013. }
  10014. content = content.substr(1, content.length - 2);
  10015. }
  10016. else if (isSlot) {
  10017. // #1241 special case for v-slot: vuetify relies extensively on slot
  10018. // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
  10019. // supports such usage so we are keeping it consistent with 2.x.
  10020. content += match[3] || '';
  10021. }
  10022. arg = {
  10023. type: 4 /* SIMPLE_EXPRESSION */,
  10024. content,
  10025. isStatic,
  10026. isConstant: isStatic,
  10027. loc
  10028. };
  10029. }
  10030. if (value && value.isQuoted) {
  10031. const valueLoc = value.loc;
  10032. valueLoc.start.offset++;
  10033. valueLoc.start.column++;
  10034. valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
  10035. valueLoc.source = valueLoc.source.slice(1, -1);
  10036. }
  10037. return {
  10038. type: 7 /* DIRECTIVE */,
  10039. name: dirName,
  10040. exp: value && {
  10041. type: 4 /* SIMPLE_EXPRESSION */,
  10042. content: value.content,
  10043. isStatic: false,
  10044. // Treat as non-constant by default. This can be potentially set to
  10045. // true by `transformExpression` to make it eligible for hoisting.
  10046. isConstant: false,
  10047. loc: value.loc
  10048. },
  10049. arg,
  10050. modifiers: match[3] ? match[3].substr(1).split('.') : [],
  10051. loc
  10052. };
  10053. }
  10054. return {
  10055. type: 6 /* ATTRIBUTE */,
  10056. name,
  10057. value: value && {
  10058. type: 2 /* TEXT */,
  10059. content: value.content,
  10060. loc: value.loc
  10061. },
  10062. loc
  10063. };
  10064. }
  10065. function parseAttributeValue(context) {
  10066. const start = getCursor(context);
  10067. let content;
  10068. const quote = context.source[0];
  10069. const isQuoted = quote === `"` || quote === `'`;
  10070. if (isQuoted) {
  10071. // Quoted value.
  10072. advanceBy(context, 1);
  10073. const endIndex = context.source.indexOf(quote);
  10074. if (endIndex === -1) {
  10075. content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
  10076. }
  10077. else {
  10078. content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
  10079. advanceBy(context, 1);
  10080. }
  10081. }
  10082. else {
  10083. // Unquoted
  10084. const match = /^[^\t\r\n\f >]+/.exec(context.source);
  10085. if (!match) {
  10086. return undefined;
  10087. }
  10088. const unexpectedChars = /["'<=`]/g;
  10089. let m;
  10090. while ((m = unexpectedChars.exec(match[0]))) {
  10091. emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
  10092. }
  10093. content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
  10094. }
  10095. return { content, isQuoted, loc: getSelection(context, start) };
  10096. }
  10097. function parseInterpolation(context, mode) {
  10098. const [open, close] = context.options.delimiters;
  10099. const closeIndex = context.source.indexOf(close, open.length);
  10100. if (closeIndex === -1) {
  10101. emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
  10102. return undefined;
  10103. }
  10104. const start = getCursor(context);
  10105. advanceBy(context, open.length);
  10106. const innerStart = getCursor(context);
  10107. const innerEnd = getCursor(context);
  10108. const rawContentLength = closeIndex - open.length;
  10109. const rawContent = context.source.slice(0, rawContentLength);
  10110. const preTrimContent = parseTextData(context, rawContentLength, mode);
  10111. const content = preTrimContent.trim();
  10112. const startOffset = preTrimContent.indexOf(content);
  10113. if (startOffset > 0) {
  10114. advancePositionWithMutation(innerStart, rawContent, startOffset);
  10115. }
  10116. const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
  10117. advancePositionWithMutation(innerEnd, rawContent, endOffset);
  10118. advanceBy(context, close.length);
  10119. return {
  10120. type: 5 /* INTERPOLATION */,
  10121. content: {
  10122. type: 4 /* SIMPLE_EXPRESSION */,
  10123. isStatic: false,
  10124. // Set `isConstant` to false by default and will decide in transformExpression
  10125. isConstant: false,
  10126. content,
  10127. loc: getSelection(context, innerStart, innerEnd)
  10128. },
  10129. loc: getSelection(context, start)
  10130. };
  10131. }
  10132. function parseText(context, mode) {
  10133. const endTokens = ['<', context.options.delimiters[0]];
  10134. if (mode === 3 /* CDATA */) {
  10135. endTokens.push(']]>');
  10136. }
  10137. let endIndex = context.source.length;
  10138. for (let i = 0; i < endTokens.length; i++) {
  10139. const index = context.source.indexOf(endTokens[i], 1);
  10140. if (index !== -1 && endIndex > index) {
  10141. endIndex = index;
  10142. }
  10143. }
  10144. const start = getCursor(context);
  10145. const content = parseTextData(context, endIndex, mode);
  10146. return {
  10147. type: 2 /* TEXT */,
  10148. content,
  10149. loc: getSelection(context, start)
  10150. };
  10151. }
  10152. /**
  10153. * Get text data with a given length from the current location.
  10154. * This translates HTML entities in the text data.
  10155. */
  10156. function parseTextData(context, length, mode) {
  10157. const rawText = context.source.slice(0, length);
  10158. advanceBy(context, length);
  10159. if (mode === 2 /* RAWTEXT */ ||
  10160. mode === 3 /* CDATA */ ||
  10161. rawText.indexOf('&') === -1) {
  10162. return rawText;
  10163. }
  10164. else {
  10165. // DATA or RCDATA containing "&"". Entity decoding required.
  10166. return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
  10167. }
  10168. }
  10169. function getCursor(context) {
  10170. const { column, line, offset } = context;
  10171. return { column, line, offset };
  10172. }
  10173. function getSelection(context, start, end) {
  10174. end = end || getCursor(context);
  10175. return {
  10176. start,
  10177. end,
  10178. source: context.originalSource.slice(start.offset, end.offset)
  10179. };
  10180. }
  10181. function last(xs) {
  10182. return xs[xs.length - 1];
  10183. }
  10184. function startsWith(source, searchString) {
  10185. return source.startsWith(searchString);
  10186. }
  10187. function advanceBy(context, numberOfCharacters) {
  10188. const { source } = context;
  10189. advancePositionWithMutation(context, source, numberOfCharacters);
  10190. context.source = source.slice(numberOfCharacters);
  10191. }
  10192. function advanceSpaces(context) {
  10193. const match = /^[\t\r\n\f ]+/.exec(context.source);
  10194. if (match) {
  10195. advanceBy(context, match[0].length);
  10196. }
  10197. }
  10198. function getNewPosition(context, start, numberOfCharacters) {
  10199. return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
  10200. }
  10201. function emitError(context, code, offset, loc = getCursor(context)) {
  10202. if (offset) {
  10203. loc.offset += offset;
  10204. loc.column += offset;
  10205. }
  10206. context.options.onError(createCompilerError(code, {
  10207. start: loc,
  10208. end: loc,
  10209. source: ''
  10210. }));
  10211. }
  10212. function isEnd(context, mode, ancestors) {
  10213. const s = context.source;
  10214. switch (mode) {
  10215. case 0 /* DATA */:
  10216. if (startsWith(s, '</')) {
  10217. //TODO: probably bad performance
  10218. for (let i = ancestors.length - 1; i >= 0; --i) {
  10219. if (startsWithEndTagOpen(s, ancestors[i].tag)) {
  10220. return true;
  10221. }
  10222. }
  10223. }
  10224. break;
  10225. case 1 /* RCDATA */:
  10226. case 2 /* RAWTEXT */: {
  10227. const parent = last(ancestors);
  10228. if (parent && startsWithEndTagOpen(s, parent.tag)) {
  10229. return true;
  10230. }
  10231. break;
  10232. }
  10233. case 3 /* CDATA */:
  10234. if (startsWith(s, ']]>')) {
  10235. return true;
  10236. }
  10237. break;
  10238. }
  10239. return !s;
  10240. }
  10241. function startsWithEndTagOpen(source, tag) {
  10242. return (startsWith(source, '</') &&
  10243. source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
  10244. /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
  10245. }
  10246. function hoistStatic(root, context) {
  10247. walk(root, context, new Map(),
  10248. // Root node is unfortunately non-hoistable due to potential parent
  10249. // fallthrough attributes.
  10250. isSingleElementRoot(root, root.children[0]));
  10251. }
  10252. function isSingleElementRoot(root, child) {
  10253. const { children } = root;
  10254. return (children.length === 1 &&
  10255. child.type === 1 /* ELEMENT */ &&
  10256. !isSlotOutlet(child));
  10257. }
  10258. function walk(node, context, resultCache, doNotHoistNode = false) {
  10259. let hasHoistedNode = false;
  10260. // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
  10261. // static bindings with expressions. These expressions are guaranteed to be
  10262. // constant so they are still eligible for hoisting, but they are only
  10263. // available at runtime and therefore cannot be evaluated ahead of time.
  10264. // This is only a concern for pre-stringification (via transformHoist by
  10265. // @vue/compiler-dom), but doing it here allows us to perform only one full
  10266. // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
  10267. // stringficiation threshold is met.
  10268. let hasRuntimeConstant = false;
  10269. const { children } = node;
  10270. for (let i = 0; i < children.length; i++) {
  10271. const child = children[i];
  10272. // only plain elements & text calls are eligible for hoisting.
  10273. if (child.type === 1 /* ELEMENT */ &&
  10274. child.tagType === 0 /* ELEMENT */) {
  10275. let staticType;
  10276. if (!doNotHoistNode &&
  10277. (staticType = getStaticType(child, resultCache)) > 0) {
  10278. if (staticType === 2 /* HAS_RUNTIME_CONSTANT */) {
  10279. hasRuntimeConstant = true;
  10280. }
  10281. child.codegenNode.patchFlag =
  10282. -1 /* HOISTED */ + ( ` /* HOISTED */` );
  10283. child.codegenNode = context.hoist(child.codegenNode);
  10284. hasHoistedNode = true;
  10285. continue;
  10286. }
  10287. else {
  10288. // node may contain dynamic children, but its props may be eligible for
  10289. // hoisting.
  10290. const codegenNode = child.codegenNode;
  10291. if (codegenNode.type === 13 /* VNODE_CALL */) {
  10292. const flag = getPatchFlag(codegenNode);
  10293. if ((!flag ||
  10294. flag === 512 /* NEED_PATCH */ ||
  10295. flag === 1 /* TEXT */) &&
  10296. !hasNonHoistableProps(child)) {
  10297. const props = getNodeProps(child);
  10298. if (props) {
  10299. codegenNode.props = context.hoist(props);
  10300. }
  10301. }
  10302. }
  10303. }
  10304. }
  10305. else if (child.type === 12 /* TEXT_CALL */) {
  10306. const staticType = getStaticType(child.content, resultCache);
  10307. if (staticType > 0) {
  10308. if (staticType === 2 /* HAS_RUNTIME_CONSTANT */) {
  10309. hasRuntimeConstant = true;
  10310. }
  10311. child.codegenNode = context.hoist(child.codegenNode);
  10312. hasHoistedNode = true;
  10313. }
  10314. }
  10315. // walk further
  10316. if (child.type === 1 /* ELEMENT */) {
  10317. walk(child, context, resultCache);
  10318. }
  10319. else if (child.type === 11 /* FOR */) {
  10320. // Do not hoist v-for single child because it has to be a block
  10321. walk(child, context, resultCache, child.children.length === 1);
  10322. }
  10323. else if (child.type === 9 /* IF */) {
  10324. for (let i = 0; i < child.branches.length; i++) {
  10325. // Do not hoist v-if single child because it has to be a block
  10326. walk(child.branches[i], context, resultCache, child.branches[i].children.length === 1);
  10327. }
  10328. }
  10329. }
  10330. if (!hasRuntimeConstant && hasHoistedNode && context.transformHoist) {
  10331. context.transformHoist(children, context, node);
  10332. }
  10333. }
  10334. function getStaticType(node, resultCache = new Map()) {
  10335. switch (node.type) {
  10336. case 1 /* ELEMENT */:
  10337. if (node.tagType !== 0 /* ELEMENT */) {
  10338. return 0 /* NOT_STATIC */;
  10339. }
  10340. const cached = resultCache.get(node);
  10341. if (cached !== undefined) {
  10342. return cached;
  10343. }
  10344. const codegenNode = node.codegenNode;
  10345. if (codegenNode.type !== 13 /* VNODE_CALL */) {
  10346. return 0 /* NOT_STATIC */;
  10347. }
  10348. const flag = getPatchFlag(codegenNode);
  10349. if (!flag && !hasNonHoistableProps(node)) {
  10350. // element self is static. check its children.
  10351. let returnType = 1 /* FULL_STATIC */;
  10352. for (let i = 0; i < node.children.length; i++) {
  10353. const childType = getStaticType(node.children[i], resultCache);
  10354. if (childType === 0 /* NOT_STATIC */) {
  10355. resultCache.set(node, 0 /* NOT_STATIC */);
  10356. return 0 /* NOT_STATIC */;
  10357. }
  10358. else if (childType === 2 /* HAS_RUNTIME_CONSTANT */) {
  10359. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  10360. }
  10361. }
  10362. // check if any of the props contain runtime constants
  10363. if (returnType !== 2 /* HAS_RUNTIME_CONSTANT */) {
  10364. for (let i = 0; i < node.props.length; i++) {
  10365. const p = node.props[i];
  10366. if (p.type === 7 /* DIRECTIVE */ &&
  10367. p.name === 'bind' &&
  10368. p.exp &&
  10369. (p.exp.type === 8 /* COMPOUND_EXPRESSION */ ||
  10370. p.exp.isRuntimeConstant)) {
  10371. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  10372. }
  10373. }
  10374. }
  10375. // only svg/foreignObject could be block here, however if they are
  10376. // stati then they don't need to be blocks since there will be no
  10377. // nested updates.
  10378. if (codegenNode.isBlock) {
  10379. codegenNode.isBlock = false;
  10380. }
  10381. resultCache.set(node, returnType);
  10382. return returnType;
  10383. }
  10384. else {
  10385. resultCache.set(node, 0 /* NOT_STATIC */);
  10386. return 0 /* NOT_STATIC */;
  10387. }
  10388. case 2 /* TEXT */:
  10389. case 3 /* COMMENT */:
  10390. return 1 /* FULL_STATIC */;
  10391. case 9 /* IF */:
  10392. case 11 /* FOR */:
  10393. case 10 /* IF_BRANCH */:
  10394. return 0 /* NOT_STATIC */;
  10395. case 5 /* INTERPOLATION */:
  10396. case 12 /* TEXT_CALL */:
  10397. return getStaticType(node.content, resultCache);
  10398. case 4 /* SIMPLE_EXPRESSION */:
  10399. return node.isConstant
  10400. ? node.isRuntimeConstant
  10401. ? 2 /* HAS_RUNTIME_CONSTANT */
  10402. : 1 /* FULL_STATIC */
  10403. : 0 /* NOT_STATIC */;
  10404. case 8 /* COMPOUND_EXPRESSION */:
  10405. let returnType = 1 /* FULL_STATIC */;
  10406. for (let i = 0; i < node.children.length; i++) {
  10407. const child = node.children[i];
  10408. if (isString(child) || isSymbol(child)) {
  10409. continue;
  10410. }
  10411. const childType = getStaticType(child, resultCache);
  10412. if (childType === 0 /* NOT_STATIC */) {
  10413. return 0 /* NOT_STATIC */;
  10414. }
  10415. else if (childType === 2 /* HAS_RUNTIME_CONSTANT */) {
  10416. returnType = 2 /* HAS_RUNTIME_CONSTANT */;
  10417. }
  10418. }
  10419. return returnType;
  10420. default:
  10421. return 0 /* NOT_STATIC */;
  10422. }
  10423. }
  10424. /**
  10425. * Even for a node with no patch flag, it is possible for it to contain
  10426. * non-hoistable expressions that refers to scope variables, e.g. compiler
  10427. * injected keys or cached event handlers. Therefore we need to always check the
  10428. * codegenNode's props to be sure.
  10429. */
  10430. function hasNonHoistableProps(node) {
  10431. const props = getNodeProps(node);
  10432. if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
  10433. const { properties } = props;
  10434. for (let i = 0; i < properties.length; i++) {
  10435. const { key, value } = properties[i];
  10436. if (key.type !== 4 /* SIMPLE_EXPRESSION */ ||
  10437. !key.isStatic ||
  10438. (value.type !== 4 /* SIMPLE_EXPRESSION */ ||
  10439. (!value.isStatic && !value.isConstant))) {
  10440. return true;
  10441. }
  10442. }
  10443. }
  10444. return false;
  10445. }
  10446. function getNodeProps(node) {
  10447. const codegenNode = node.codegenNode;
  10448. if (codegenNode.type === 13 /* VNODE_CALL */) {
  10449. return codegenNode.props;
  10450. }
  10451. }
  10452. function getPatchFlag(node) {
  10453. const flag = node.patchFlag;
  10454. return flag ? parseInt(flag, 10) : undefined;
  10455. }
  10456. function createTransformContext(root, { prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, ssr = false, ssrCssVars = ``, bindingMetadata = {}, onError = defaultOnError }) {
  10457. const context = {
  10458. // options
  10459. prefixIdentifiers,
  10460. hoistStatic,
  10461. cacheHandlers,
  10462. nodeTransforms,
  10463. directiveTransforms,
  10464. transformHoist,
  10465. isBuiltInComponent,
  10466. isCustomElement,
  10467. expressionPlugins,
  10468. scopeId,
  10469. ssr,
  10470. ssrCssVars,
  10471. bindingMetadata,
  10472. onError,
  10473. // state
  10474. root,
  10475. helpers: new Set(),
  10476. components: new Set(),
  10477. directives: new Set(),
  10478. hoists: [],
  10479. imports: new Set(),
  10480. temps: 0,
  10481. cached: 0,
  10482. identifiers: Object.create(null),
  10483. scopes: {
  10484. vFor: 0,
  10485. vSlot: 0,
  10486. vPre: 0,
  10487. vOnce: 0
  10488. },
  10489. parent: null,
  10490. currentNode: root,
  10491. childIndex: 0,
  10492. // methods
  10493. helper(name) {
  10494. context.helpers.add(name);
  10495. return name;
  10496. },
  10497. helperString(name) {
  10498. return `_${helperNameMap[context.helper(name)]}`;
  10499. },
  10500. replaceNode(node) {
  10501. /* istanbul ignore if */
  10502. {
  10503. if (!context.currentNode) {
  10504. throw new Error(`Node being replaced is already removed.`);
  10505. }
  10506. if (!context.parent) {
  10507. throw new Error(`Cannot replace root node.`);
  10508. }
  10509. }
  10510. context.parent.children[context.childIndex] = context.currentNode = node;
  10511. },
  10512. removeNode(node) {
  10513. if ( !context.parent) {
  10514. throw new Error(`Cannot remove root node.`);
  10515. }
  10516. const list = context.parent.children;
  10517. const removalIndex = node
  10518. ? list.indexOf(node)
  10519. : context.currentNode
  10520. ? context.childIndex
  10521. : -1;
  10522. /* istanbul ignore if */
  10523. if ( removalIndex < 0) {
  10524. throw new Error(`node being removed is not a child of current parent`);
  10525. }
  10526. if (!node || node === context.currentNode) {
  10527. // current node removed
  10528. context.currentNode = null;
  10529. context.onNodeRemoved();
  10530. }
  10531. else {
  10532. // sibling node removed
  10533. if (context.childIndex > removalIndex) {
  10534. context.childIndex--;
  10535. context.onNodeRemoved();
  10536. }
  10537. }
  10538. context.parent.children.splice(removalIndex, 1);
  10539. },
  10540. onNodeRemoved: () => { },
  10541. addIdentifiers(exp) {
  10542. },
  10543. removeIdentifiers(exp) {
  10544. },
  10545. hoist(exp) {
  10546. context.hoists.push(exp);
  10547. const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, true);
  10548. identifier.hoisted = exp;
  10549. return identifier;
  10550. },
  10551. cache(exp, isVNode = false) {
  10552. return createCacheExpression(++context.cached, exp, isVNode);
  10553. }
  10554. };
  10555. return context;
  10556. }
  10557. function transform(root, options) {
  10558. const context = createTransformContext(root, options);
  10559. traverseNode(root, context);
  10560. if (options.hoistStatic) {
  10561. hoistStatic(root, context);
  10562. }
  10563. if (!options.ssr) {
  10564. createRootCodegen(root, context);
  10565. }
  10566. // finalize meta information
  10567. root.helpers = [...context.helpers];
  10568. root.components = [...context.components];
  10569. root.directives = [...context.directives];
  10570. root.imports = [...context.imports];
  10571. root.hoists = context.hoists;
  10572. root.temps = context.temps;
  10573. root.cached = context.cached;
  10574. }
  10575. function createRootCodegen(root, context) {
  10576. const { helper } = context;
  10577. const { children } = root;
  10578. if (children.length === 1) {
  10579. const child = children[0];
  10580. // if the single child is an element, turn it into a block.
  10581. if (isSingleElementRoot(root, child) && child.codegenNode) {
  10582. // single element root is never hoisted so codegenNode will never be
  10583. // SimpleExpressionNode
  10584. const codegenNode = child.codegenNode;
  10585. if (codegenNode.type === 13 /* VNODE_CALL */) {
  10586. codegenNode.isBlock = true;
  10587. helper(OPEN_BLOCK);
  10588. helper(CREATE_BLOCK);
  10589. }
  10590. root.codegenNode = codegenNode;
  10591. }
  10592. else {
  10593. // - single <slot/>, IfNode, ForNode: already blocks.
  10594. // - single text node: always patched.
  10595. // root codegen falls through via genNode()
  10596. root.codegenNode = child;
  10597. }
  10598. }
  10599. else if (children.length > 1) {
  10600. // root has multiple nodes - return a fragment block.
  10601. root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, `${64 /* STABLE_FRAGMENT */} /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true);
  10602. }
  10603. else ;
  10604. }
  10605. function traverseChildren(parent, context) {
  10606. let i = 0;
  10607. const nodeRemoved = () => {
  10608. i--;
  10609. };
  10610. for (; i < parent.children.length; i++) {
  10611. const child = parent.children[i];
  10612. if (isString(child))
  10613. continue;
  10614. context.parent = parent;
  10615. context.childIndex = i;
  10616. context.onNodeRemoved = nodeRemoved;
  10617. traverseNode(child, context);
  10618. }
  10619. }
  10620. function traverseNode(node, context) {
  10621. context.currentNode = node;
  10622. // apply transform plugins
  10623. const { nodeTransforms } = context;
  10624. const exitFns = [];
  10625. for (let i = 0; i < nodeTransforms.length; i++) {
  10626. const onExit = nodeTransforms[i](node, context);
  10627. if (onExit) {
  10628. if (isArray(onExit)) {
  10629. exitFns.push(...onExit);
  10630. }
  10631. else {
  10632. exitFns.push(onExit);
  10633. }
  10634. }
  10635. if (!context.currentNode) {
  10636. // node was removed
  10637. return;
  10638. }
  10639. else {
  10640. // node may have been replaced
  10641. node = context.currentNode;
  10642. }
  10643. }
  10644. switch (node.type) {
  10645. case 3 /* COMMENT */:
  10646. if (!context.ssr) {
  10647. // inject import for the Comment symbol, which is needed for creating
  10648. // comment nodes with `createVNode`
  10649. context.helper(CREATE_COMMENT);
  10650. }
  10651. break;
  10652. case 5 /* INTERPOLATION */:
  10653. // no need to traverse, but we need to inject toString helper
  10654. if (!context.ssr) {
  10655. context.helper(TO_DISPLAY_STRING);
  10656. }
  10657. break;
  10658. // for container types, further traverse downwards
  10659. case 9 /* IF */:
  10660. for (let i = 0; i < node.branches.length; i++) {
  10661. traverseNode(node.branches[i], context);
  10662. }
  10663. break;
  10664. case 10 /* IF_BRANCH */:
  10665. case 11 /* FOR */:
  10666. case 1 /* ELEMENT */:
  10667. case 0 /* ROOT */:
  10668. traverseChildren(node, context);
  10669. break;
  10670. }
  10671. // exit transforms
  10672. context.currentNode = node;
  10673. let i = exitFns.length;
  10674. while (i--) {
  10675. exitFns[i]();
  10676. }
  10677. }
  10678. function createStructuralDirectiveTransform(name, fn) {
  10679. const matches = isString(name)
  10680. ? (n) => n === name
  10681. : (n) => name.test(n);
  10682. return (node, context) => {
  10683. if (node.type === 1 /* ELEMENT */) {
  10684. const { props } = node;
  10685. // structural directive transforms are not concerned with slots
  10686. // as they are handled separately in vSlot.ts
  10687. if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
  10688. return;
  10689. }
  10690. const exitFns = [];
  10691. for (let i = 0; i < props.length; i++) {
  10692. const prop = props[i];
  10693. if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
  10694. // structural directives are removed to avoid infinite recursion
  10695. // also we remove them *before* applying so that it can further
  10696. // traverse itself in case it moves the node around
  10697. props.splice(i, 1);
  10698. i--;
  10699. const onExit = fn(node, prop, context);
  10700. if (onExit)
  10701. exitFns.push(onExit);
  10702. }
  10703. }
  10704. return exitFns;
  10705. }
  10706. };
  10707. }
  10708. const PURE_ANNOTATION = `/*#__PURE__*/`;
  10709. function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
  10710. const context = {
  10711. mode,
  10712. prefixIdentifiers,
  10713. sourceMap,
  10714. filename,
  10715. scopeId,
  10716. optimizeImports,
  10717. runtimeGlobalName,
  10718. runtimeModuleName,
  10719. ssr,
  10720. source: ast.loc.source,
  10721. code: ``,
  10722. column: 1,
  10723. line: 1,
  10724. offset: 0,
  10725. indentLevel: 0,
  10726. pure: false,
  10727. map: undefined,
  10728. helper(key) {
  10729. return `_${helperNameMap[key]}`;
  10730. },
  10731. push(code, node) {
  10732. context.code += code;
  10733. },
  10734. indent() {
  10735. newline(++context.indentLevel);
  10736. },
  10737. deindent(withoutNewLine = false) {
  10738. if (withoutNewLine) {
  10739. --context.indentLevel;
  10740. }
  10741. else {
  10742. newline(--context.indentLevel);
  10743. }
  10744. },
  10745. newline() {
  10746. newline(context.indentLevel);
  10747. }
  10748. };
  10749. function newline(n) {
  10750. context.push('\n' + ` `.repeat(n));
  10751. }
  10752. return context;
  10753. }
  10754. function generate(ast, options = {}) {
  10755. const context = createCodegenContext(ast, options);
  10756. if (options.onContextCreated)
  10757. options.onContextCreated(context);
  10758. const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
  10759. const hasHelpers = ast.helpers.length > 0;
  10760. const useWithBlock = !prefixIdentifiers && mode !== 'module';
  10761. // preambles
  10762. {
  10763. genFunctionPreamble(ast, context);
  10764. }
  10765. // binding optimizations
  10766. const optimizeSources = options.bindingMetadata
  10767. ? `, $props, $setup, $data, $options`
  10768. : ``;
  10769. // enter render function
  10770. if (!ssr) {
  10771. push(`function render(_ctx, _cache${optimizeSources}) {`);
  10772. }
  10773. else {
  10774. push(`function ssrRender(_ctx, _push, _parent, _attrs${optimizeSources}) {`);
  10775. }
  10776. indent();
  10777. if (useWithBlock) {
  10778. push(`with (_ctx) {`);
  10779. indent();
  10780. // function mode const declarations should be inside with block
  10781. // also they should be renamed to avoid collision with user properties
  10782. if (hasHelpers) {
  10783. push(`const { ${ast.helpers
  10784. .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
  10785. .join(', ')} } = _Vue`);
  10786. push(`\n`);
  10787. newline();
  10788. }
  10789. }
  10790. // generate asset resolution statements
  10791. if (ast.components.length) {
  10792. genAssets(ast.components, 'component', context);
  10793. if (ast.directives.length || ast.temps > 0) {
  10794. newline();
  10795. }
  10796. }
  10797. if (ast.directives.length) {
  10798. genAssets(ast.directives, 'directive', context);
  10799. if (ast.temps > 0) {
  10800. newline();
  10801. }
  10802. }
  10803. if (ast.temps > 0) {
  10804. push(`let `);
  10805. for (let i = 0; i < ast.temps; i++) {
  10806. push(`${i > 0 ? `, ` : ``}_temp${i}`);
  10807. }
  10808. }
  10809. if (ast.components.length || ast.directives.length || ast.temps) {
  10810. push(`\n`);
  10811. newline();
  10812. }
  10813. // generate the VNode tree expression
  10814. if (!ssr) {
  10815. push(`return `);
  10816. }
  10817. if (ast.codegenNode) {
  10818. genNode(ast.codegenNode, context);
  10819. }
  10820. else {
  10821. push(`null`);
  10822. }
  10823. if (useWithBlock) {
  10824. deindent();
  10825. push(`}`);
  10826. }
  10827. deindent();
  10828. push(`}`);
  10829. return {
  10830. ast,
  10831. code: context.code,
  10832. // SourceMapGenerator does have toJSON() method but it's not in the types
  10833. map: context.map ? context.map.toJSON() : undefined
  10834. };
  10835. }
  10836. function genFunctionPreamble(ast, context) {
  10837. const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
  10838. const VueBinding = runtimeGlobalName;
  10839. const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
  10840. // Generate const declaration for helpers
  10841. // In prefix mode, we place the const declaration at top so it's done
  10842. // only once; But if we not prefixing, we place the declaration inside the
  10843. // with block so it doesn't incur the `in` check cost for every helper access.
  10844. if (ast.helpers.length > 0) {
  10845. {
  10846. // "with" mode.
  10847. // save Vue in a separate variable to avoid collision
  10848. push(`const _Vue = ${VueBinding}\n`);
  10849. // in "with" mode, helpers are declared inside the with block to avoid
  10850. // has check cost, but hoists are lifted out of the function - we need
  10851. // to provide the helper here.
  10852. if (ast.hoists.length) {
  10853. const staticHelpers = [
  10854. CREATE_VNODE,
  10855. CREATE_COMMENT,
  10856. CREATE_TEXT,
  10857. CREATE_STATIC
  10858. ]
  10859. .filter(helper => ast.helpers.includes(helper))
  10860. .map(aliasHelper)
  10861. .join(', ');
  10862. push(`const { ${staticHelpers} } = _Vue\n`);
  10863. }
  10864. }
  10865. }
  10866. genHoists(ast.hoists, context);
  10867. newline();
  10868. push(`return `);
  10869. }
  10870. function genAssets(assets, type, { helper, push, newline }) {
  10871. const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
  10872. for (let i = 0; i < assets.length; i++) {
  10873. const id = assets[i];
  10874. push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
  10875. if (i < assets.length - 1) {
  10876. newline();
  10877. }
  10878. }
  10879. }
  10880. function genHoists(hoists, context) {
  10881. if (!hoists.length) {
  10882. return;
  10883. }
  10884. context.pure = true;
  10885. const { push, newline, helper, scopeId, mode } = context;
  10886. newline();
  10887. hoists.forEach((exp, i) => {
  10888. if (exp) {
  10889. push(`const _hoisted_${i + 1} = `);
  10890. genNode(exp, context);
  10891. newline();
  10892. }
  10893. });
  10894. context.pure = false;
  10895. }
  10896. function isText$1(n) {
  10897. return (isString(n) ||
  10898. n.type === 4 /* SIMPLE_EXPRESSION */ ||
  10899. n.type === 2 /* TEXT */ ||
  10900. n.type === 5 /* INTERPOLATION */ ||
  10901. n.type === 8 /* COMPOUND_EXPRESSION */);
  10902. }
  10903. function genNodeListAsArray(nodes, context) {
  10904. const multilines = nodes.length > 3 ||
  10905. ( nodes.some(n => isArray(n) || !isText$1(n)));
  10906. context.push(`[`);
  10907. multilines && context.indent();
  10908. genNodeList(nodes, context, multilines);
  10909. multilines && context.deindent();
  10910. context.push(`]`);
  10911. }
  10912. function genNodeList(nodes, context, multilines = false, comma = true) {
  10913. const { push, newline } = context;
  10914. for (let i = 0; i < nodes.length; i++) {
  10915. const node = nodes[i];
  10916. if (isString(node)) {
  10917. push(node);
  10918. }
  10919. else if (isArray(node)) {
  10920. genNodeListAsArray(node, context);
  10921. }
  10922. else {
  10923. genNode(node, context);
  10924. }
  10925. if (i < nodes.length - 1) {
  10926. if (multilines) {
  10927. comma && push(',');
  10928. newline();
  10929. }
  10930. else {
  10931. comma && push(', ');
  10932. }
  10933. }
  10934. }
  10935. }
  10936. function genNode(node, context) {
  10937. if (isString(node)) {
  10938. context.push(node);
  10939. return;
  10940. }
  10941. if (isSymbol(node)) {
  10942. context.push(context.helper(node));
  10943. return;
  10944. }
  10945. switch (node.type) {
  10946. case 1 /* ELEMENT */:
  10947. case 9 /* IF */:
  10948. case 11 /* FOR */:
  10949. assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
  10950. `Apply appropriate transforms first.`);
  10951. genNode(node.codegenNode, context);
  10952. break;
  10953. case 2 /* TEXT */:
  10954. genText(node, context);
  10955. break;
  10956. case 4 /* SIMPLE_EXPRESSION */:
  10957. genExpression(node, context);
  10958. break;
  10959. case 5 /* INTERPOLATION */:
  10960. genInterpolation(node, context);
  10961. break;
  10962. case 12 /* TEXT_CALL */:
  10963. genNode(node.codegenNode, context);
  10964. break;
  10965. case 8 /* COMPOUND_EXPRESSION */:
  10966. genCompoundExpression(node, context);
  10967. break;
  10968. case 3 /* COMMENT */:
  10969. genComment(node, context);
  10970. break;
  10971. case 13 /* VNODE_CALL */:
  10972. genVNodeCall(node, context);
  10973. break;
  10974. case 14 /* JS_CALL_EXPRESSION */:
  10975. genCallExpression(node, context);
  10976. break;
  10977. case 15 /* JS_OBJECT_EXPRESSION */:
  10978. genObjectExpression(node, context);
  10979. break;
  10980. case 17 /* JS_ARRAY_EXPRESSION */:
  10981. genArrayExpression(node, context);
  10982. break;
  10983. case 18 /* JS_FUNCTION_EXPRESSION */:
  10984. genFunctionExpression(node, context);
  10985. break;
  10986. case 19 /* JS_CONDITIONAL_EXPRESSION */:
  10987. genConditionalExpression(node, context);
  10988. break;
  10989. case 20 /* JS_CACHE_EXPRESSION */:
  10990. genCacheExpression(node, context);
  10991. break;
  10992. // SSR only types
  10993. case 21 /* JS_BLOCK_STATEMENT */:
  10994. break;
  10995. case 22 /* JS_TEMPLATE_LITERAL */:
  10996. break;
  10997. case 23 /* JS_IF_STATEMENT */:
  10998. break;
  10999. case 24 /* JS_ASSIGNMENT_EXPRESSION */:
  11000. break;
  11001. case 25 /* JS_SEQUENCE_EXPRESSION */:
  11002. break;
  11003. case 26 /* JS_RETURN_STATEMENT */:
  11004. break;
  11005. /* istanbul ignore next */
  11006. case 10 /* IF_BRANCH */:
  11007. // noop
  11008. break;
  11009. default:
  11010. {
  11011. assert(false, `unhandled codegen node type: ${node.type}`);
  11012. // make sure we exhaust all possible types
  11013. const exhaustiveCheck = node;
  11014. return exhaustiveCheck;
  11015. }
  11016. }
  11017. }
  11018. function genText(node, context) {
  11019. context.push(JSON.stringify(node.content), node);
  11020. }
  11021. function genExpression(node, context) {
  11022. const { content, isStatic } = node;
  11023. context.push(isStatic ? JSON.stringify(content) : content, node);
  11024. }
  11025. function genInterpolation(node, context) {
  11026. const { push, helper, pure } = context;
  11027. if (pure)
  11028. push(PURE_ANNOTATION);
  11029. push(`${helper(TO_DISPLAY_STRING)}(`);
  11030. genNode(node.content, context);
  11031. push(`)`);
  11032. }
  11033. function genCompoundExpression(node, context) {
  11034. for (let i = 0; i < node.children.length; i++) {
  11035. const child = node.children[i];
  11036. if (isString(child)) {
  11037. context.push(child);
  11038. }
  11039. else {
  11040. genNode(child, context);
  11041. }
  11042. }
  11043. }
  11044. function genExpressionAsPropertyKey(node, context) {
  11045. const { push } = context;
  11046. if (node.type === 8 /* COMPOUND_EXPRESSION */) {
  11047. push(`[`);
  11048. genCompoundExpression(node, context);
  11049. push(`]`);
  11050. }
  11051. else if (node.isStatic) {
  11052. // only quote keys if necessary
  11053. const text = isSimpleIdentifier(node.content)
  11054. ? node.content
  11055. : JSON.stringify(node.content);
  11056. push(text, node);
  11057. }
  11058. else {
  11059. push(`[${node.content}]`, node);
  11060. }
  11061. }
  11062. function genComment(node, context) {
  11063. {
  11064. const { push, helper, pure } = context;
  11065. if (pure) {
  11066. push(PURE_ANNOTATION);
  11067. }
  11068. push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
  11069. }
  11070. }
  11071. function genVNodeCall(node, context) {
  11072. const { push, helper, pure } = context;
  11073. const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
  11074. if (directives) {
  11075. push(helper(WITH_DIRECTIVES) + `(`);
  11076. }
  11077. if (isBlock) {
  11078. push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
  11079. }
  11080. if (pure) {
  11081. push(PURE_ANNOTATION);
  11082. }
  11083. push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
  11084. genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
  11085. push(`)`);
  11086. if (isBlock) {
  11087. push(`)`);
  11088. }
  11089. if (directives) {
  11090. push(`, `);
  11091. genNode(directives, context);
  11092. push(`)`);
  11093. }
  11094. }
  11095. function genNullableArgs(args) {
  11096. let i = args.length;
  11097. while (i--) {
  11098. if (args[i] != null)
  11099. break;
  11100. }
  11101. return args.slice(0, i + 1).map(arg => arg || `null`);
  11102. }
  11103. // JavaScript
  11104. function genCallExpression(node, context) {
  11105. const { push, helper, pure } = context;
  11106. const callee = isString(node.callee) ? node.callee : helper(node.callee);
  11107. if (pure) {
  11108. push(PURE_ANNOTATION);
  11109. }
  11110. push(callee + `(`, node);
  11111. genNodeList(node.arguments, context);
  11112. push(`)`);
  11113. }
  11114. function genObjectExpression(node, context) {
  11115. const { push, indent, deindent, newline } = context;
  11116. const { properties } = node;
  11117. if (!properties.length) {
  11118. push(`{}`, node);
  11119. return;
  11120. }
  11121. const multilines = properties.length > 1 ||
  11122. (
  11123. properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
  11124. push(multilines ? `{` : `{ `);
  11125. multilines && indent();
  11126. for (let i = 0; i < properties.length; i++) {
  11127. const { key, value } = properties[i];
  11128. // key
  11129. genExpressionAsPropertyKey(key, context);
  11130. push(`: `);
  11131. // value
  11132. genNode(value, context);
  11133. if (i < properties.length - 1) {
  11134. // will only reach this if it's multilines
  11135. push(`,`);
  11136. newline();
  11137. }
  11138. }
  11139. multilines && deindent();
  11140. push(multilines ? `}` : ` }`);
  11141. }
  11142. function genArrayExpression(node, context) {
  11143. genNodeListAsArray(node.elements, context);
  11144. }
  11145. function genFunctionExpression(node, context) {
  11146. const { push, indent, deindent, scopeId, mode } = context;
  11147. const { params, returns, body, newline, isSlot } = node;
  11148. if (isSlot) {
  11149. push(`_${helperNameMap[WITH_CTX]}(`);
  11150. }
  11151. push(`(`, node);
  11152. if (isArray(params)) {
  11153. genNodeList(params, context);
  11154. }
  11155. else if (params) {
  11156. genNode(params, context);
  11157. }
  11158. push(`) => `);
  11159. if (newline || body) {
  11160. push(`{`);
  11161. indent();
  11162. }
  11163. if (returns) {
  11164. if (newline) {
  11165. push(`return `);
  11166. }
  11167. if (isArray(returns)) {
  11168. genNodeListAsArray(returns, context);
  11169. }
  11170. else {
  11171. genNode(returns, context);
  11172. }
  11173. }
  11174. else if (body) {
  11175. genNode(body, context);
  11176. }
  11177. if (newline || body) {
  11178. deindent();
  11179. push(`}`);
  11180. }
  11181. if ( isSlot) {
  11182. push(`)`);
  11183. }
  11184. }
  11185. function genConditionalExpression(node, context) {
  11186. const { test, consequent, alternate, newline: needNewline } = node;
  11187. const { push, indent, deindent, newline } = context;
  11188. if (test.type === 4 /* SIMPLE_EXPRESSION */) {
  11189. const needsParens = !isSimpleIdentifier(test.content);
  11190. needsParens && push(`(`);
  11191. genExpression(test, context);
  11192. needsParens && push(`)`);
  11193. }
  11194. else {
  11195. push(`(`);
  11196. genNode(test, context);
  11197. push(`)`);
  11198. }
  11199. needNewline && indent();
  11200. context.indentLevel++;
  11201. needNewline || push(` `);
  11202. push(`? `);
  11203. genNode(consequent, context);
  11204. context.indentLevel--;
  11205. needNewline && newline();
  11206. needNewline || push(` `);
  11207. push(`: `);
  11208. const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
  11209. if (!isNested) {
  11210. context.indentLevel++;
  11211. }
  11212. genNode(alternate, context);
  11213. if (!isNested) {
  11214. context.indentLevel--;
  11215. }
  11216. needNewline && deindent(true /* without newline */);
  11217. }
  11218. function genCacheExpression(node, context) {
  11219. const { push, helper, indent, deindent, newline } = context;
  11220. push(`_cache[${node.index}] || (`);
  11221. if (node.isVNode) {
  11222. indent();
  11223. push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
  11224. newline();
  11225. }
  11226. push(`_cache[${node.index}] = `);
  11227. genNode(node.value, context);
  11228. if (node.isVNode) {
  11229. push(`,`);
  11230. newline();
  11231. push(`${helper(SET_BLOCK_TRACKING)}(1),`);
  11232. newline();
  11233. push(`_cache[${node.index}]`);
  11234. deindent();
  11235. }
  11236. push(`)`);
  11237. }
  11238. // these keywords should not appear inside expressions, but operators like
  11239. // typeof, instanceof and in are allowed
  11240. const prohibitedKeywordRE = new RegExp('\\b' +
  11241. ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
  11242. 'super,throw,while,yield,delete,export,import,return,switch,default,' +
  11243. 'extends,finally,continue,debugger,function,arguments,typeof,void')
  11244. .split(',')
  11245. .join('\\b|\\b') +
  11246. '\\b');
  11247. // strip strings in expressions
  11248. const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
  11249. /**
  11250. * Validate a non-prefixed expression.
  11251. * This is only called when using the in-browser runtime compiler since it
  11252. * doesn't prefix expressions.
  11253. */
  11254. function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
  11255. const exp = node.content;
  11256. // empty expressions are validated per-directive since some directives
  11257. // do allow empty expressions.
  11258. if (!exp.trim()) {
  11259. return;
  11260. }
  11261. try {
  11262. new Function(asRawStatements
  11263. ? ` ${exp} `
  11264. : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
  11265. }
  11266. catch (e) {
  11267. let message = e.message;
  11268. const keywordMatch = exp
  11269. .replace(stripStringRE, '')
  11270. .match(prohibitedKeywordRE);
  11271. if (keywordMatch) {
  11272. message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
  11273. }
  11274. context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
  11275. }
  11276. }
  11277. const transformExpression = (node, context) => {
  11278. if (node.type === 5 /* INTERPOLATION */) {
  11279. node.content = processExpression(node.content, context);
  11280. }
  11281. else if (node.type === 1 /* ELEMENT */) {
  11282. // handle directives on element
  11283. for (let i = 0; i < node.props.length; i++) {
  11284. const dir = node.props[i];
  11285. // do not process for v-on & v-for since they are special handled
  11286. if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
  11287. const exp = dir.exp;
  11288. const arg = dir.arg;
  11289. // do not process exp if this is v-on:arg - we need special handling
  11290. // for wrapping inline statements.
  11291. if (exp &&
  11292. exp.type === 4 /* SIMPLE_EXPRESSION */ &&
  11293. !(dir.name === 'on' && arg)) {
  11294. dir.exp = processExpression(exp, context,
  11295. // slot args must be processed as function params
  11296. dir.name === 'slot');
  11297. }
  11298. if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
  11299. dir.arg = processExpression(arg, context);
  11300. }
  11301. }
  11302. }
  11303. }
  11304. };
  11305. // Important: since this function uses Node.js only dependencies, it should
  11306. // always be used with a leading !true check so that it can be
  11307. // tree-shaken from the browser build.
  11308. function processExpression(node, context,
  11309. // some expressions like v-slot props & v-for aliases should be parsed as
  11310. // function params
  11311. asParams = false,
  11312. // v-on handler values may contain multiple statements
  11313. asRawStatements = false) {
  11314. {
  11315. // simple in-browser validation (same logic in 2.x)
  11316. validateBrowserExpression(node, context, asParams, asRawStatements);
  11317. return node;
  11318. }
  11319. }
  11320. const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
  11321. return processIf(node, dir, context, (ifNode, branch, isRoot) => {
  11322. // #1587: We need to dynamically increment the key based on the current
  11323. // node's sibling nodes, since chained v-if/else branches are
  11324. // rendered at the same depth
  11325. const siblings = context.parent.children;
  11326. let i = siblings.indexOf(ifNode);
  11327. let key = 0;
  11328. while (i-- >= 0) {
  11329. const sibling = siblings[i];
  11330. if (sibling && sibling.type === 9 /* IF */) {
  11331. key += sibling.branches.length;
  11332. }
  11333. }
  11334. // Exit callback. Complete the codegenNode when all children have been
  11335. // transformed.
  11336. return () => {
  11337. if (isRoot) {
  11338. ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
  11339. }
  11340. else {
  11341. // attach this branch's codegen node to the v-if root.
  11342. const parentCondition = getParentCondition(ifNode.codegenNode);
  11343. parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
  11344. }
  11345. };
  11346. });
  11347. });
  11348. // target-agnostic transform used for both Client and SSR
  11349. function processIf(node, dir, context, processCodegen) {
  11350. if (dir.name !== 'else' &&
  11351. (!dir.exp || !dir.exp.content.trim())) {
  11352. const loc = dir.exp ? dir.exp.loc : node.loc;
  11353. context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
  11354. dir.exp = createSimpleExpression(`true`, false, loc);
  11355. }
  11356. if ( dir.exp) {
  11357. validateBrowserExpression(dir.exp, context);
  11358. }
  11359. if (dir.name === 'if') {
  11360. const branch = createIfBranch(node, dir);
  11361. const ifNode = {
  11362. type: 9 /* IF */,
  11363. loc: node.loc,
  11364. branches: [branch]
  11365. };
  11366. context.replaceNode(ifNode);
  11367. if (processCodegen) {
  11368. return processCodegen(ifNode, branch, true);
  11369. }
  11370. }
  11371. else {
  11372. // locate the adjacent v-if
  11373. const siblings = context.parent.children;
  11374. const comments = [];
  11375. let i = siblings.indexOf(node);
  11376. while (i-- >= -1) {
  11377. const sibling = siblings[i];
  11378. if ( sibling && sibling.type === 3 /* COMMENT */) {
  11379. context.removeNode(sibling);
  11380. comments.unshift(sibling);
  11381. continue;
  11382. }
  11383. if (sibling &&
  11384. sibling.type === 2 /* TEXT */ &&
  11385. !sibling.content.trim().length) {
  11386. context.removeNode(sibling);
  11387. continue;
  11388. }
  11389. if (sibling && sibling.type === 9 /* IF */) {
  11390. // move the node to the if node's branches
  11391. context.removeNode();
  11392. const branch = createIfBranch(node, dir);
  11393. if ( comments.length) {
  11394. branch.children = [...comments, ...branch.children];
  11395. }
  11396. // check if user is forcing same key on different branches
  11397. {
  11398. const key = branch.userKey;
  11399. if (key) {
  11400. sibling.branches.forEach(({ userKey }) => {
  11401. if (isSameKey(userKey, key)) {
  11402. context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
  11403. }
  11404. });
  11405. }
  11406. }
  11407. sibling.branches.push(branch);
  11408. const onExit = processCodegen && processCodegen(sibling, branch, false);
  11409. // since the branch was removed, it will not be traversed.
  11410. // make sure to traverse here.
  11411. traverseNode(branch, context);
  11412. // call on exit
  11413. if (onExit)
  11414. onExit();
  11415. // make sure to reset currentNode after traversal to indicate this
  11416. // node has been removed.
  11417. context.currentNode = null;
  11418. }
  11419. else {
  11420. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
  11421. }
  11422. break;
  11423. }
  11424. }
  11425. }
  11426. function createIfBranch(node, dir) {
  11427. return {
  11428. type: 10 /* IF_BRANCH */,
  11429. loc: node.loc,
  11430. condition: dir.name === 'else' ? undefined : dir.exp,
  11431. children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
  11432. ? node.children
  11433. : [node],
  11434. userKey: findProp(node, `key`)
  11435. };
  11436. }
  11437. function createCodegenNodeForBranch(branch, keyIndex, context) {
  11438. if (branch.condition) {
  11439. return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
  11440. // make sure to pass in asBlock: true so that the comment node call
  11441. // closes the current block.
  11442. createCallExpression(context.helper(CREATE_COMMENT), [
  11443. '"v-if"' ,
  11444. 'true'
  11445. ]));
  11446. }
  11447. else {
  11448. return createChildrenCodegenNode(branch, keyIndex, context);
  11449. }
  11450. }
  11451. function createChildrenCodegenNode(branch, keyIndex, context) {
  11452. const { helper } = context;
  11453. const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, true));
  11454. const { children } = branch;
  11455. const firstChild = children[0];
  11456. const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
  11457. if (needFragmentWrapper) {
  11458. if (children.length === 1 && firstChild.type === 11 /* FOR */) {
  11459. // optimize away nested fragments when child is a ForNode
  11460. const vnodeCall = firstChild.codegenNode;
  11461. injectProp(vnodeCall, keyProperty, context);
  11462. return vnodeCall;
  11463. }
  11464. else {
  11465. return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, `${64 /* STABLE_FRAGMENT */} /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true, false, branch.loc);
  11466. }
  11467. }
  11468. else {
  11469. const vnodeCall = firstChild
  11470. .codegenNode;
  11471. // Change createVNode to createBlock.
  11472. if (vnodeCall.type === 13 /* VNODE_CALL */) {
  11473. vnodeCall.isBlock = true;
  11474. helper(OPEN_BLOCK);
  11475. helper(CREATE_BLOCK);
  11476. }
  11477. // inject branch key
  11478. injectProp(vnodeCall, keyProperty, context);
  11479. return vnodeCall;
  11480. }
  11481. }
  11482. function isSameKey(a, b) {
  11483. if (!a || a.type !== b.type) {
  11484. return false;
  11485. }
  11486. if (a.type === 6 /* ATTRIBUTE */) {
  11487. if (a.value.content !== b.value.content) {
  11488. return false;
  11489. }
  11490. }
  11491. else {
  11492. // directive
  11493. const exp = a.exp;
  11494. const branchExp = b.exp;
  11495. if (exp.type !== branchExp.type) {
  11496. return false;
  11497. }
  11498. if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
  11499. (exp.isStatic !== branchExp.isStatic ||
  11500. exp.content !== branchExp.content)) {
  11501. return false;
  11502. }
  11503. }
  11504. return true;
  11505. }
  11506. function getParentCondition(node) {
  11507. while (true) {
  11508. if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  11509. if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  11510. node = node.alternate;
  11511. }
  11512. else {
  11513. return node;
  11514. }
  11515. }
  11516. else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
  11517. node = node.value;
  11518. }
  11519. }
  11520. }
  11521. const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
  11522. const { helper } = context;
  11523. return processFor(node, dir, context, forNode => {
  11524. // create the loop render function expression now, and add the
  11525. // iterator on exit after all children have been traversed
  11526. const renderExp = createCallExpression(helper(RENDER_LIST), [
  11527. forNode.source
  11528. ]);
  11529. const keyProp = findProp(node, `key`);
  11530. const keyProperty = keyProp
  11531. ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
  11532. ? createSimpleExpression(keyProp.value.content, true)
  11533. : keyProp.exp)
  11534. : null;
  11535. const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
  11536. forNode.source.isConstant;
  11537. const fragmentFlag = isStableFragment
  11538. ? 64 /* STABLE_FRAGMENT */
  11539. : keyProp
  11540. ? 128 /* KEYED_FRAGMENT */
  11541. : 256 /* UNKEYED_FRAGMENT */;
  11542. forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, `${fragmentFlag} /* ${PatchFlagNames[fragmentFlag]} */`, undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
  11543. return () => {
  11544. // finish the codegen now that all children have been traversed
  11545. let childBlock;
  11546. const isTemplate = isTemplateNode(node);
  11547. const { children } = forNode;
  11548. // check <template v-for> key placement
  11549. if ( isTemplate) {
  11550. node.children.some(c => {
  11551. if (c.type === 1 /* ELEMENT */) {
  11552. const key = findProp(c, 'key');
  11553. if (key) {
  11554. context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
  11555. return true;
  11556. }
  11557. }
  11558. });
  11559. }
  11560. const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
  11561. const slotOutlet = isSlotOutlet(node)
  11562. ? node
  11563. : isTemplate &&
  11564. node.children.length === 1 &&
  11565. isSlotOutlet(node.children[0])
  11566. ? node.children[0] // api-extractor somehow fails to infer this
  11567. : null;
  11568. if (slotOutlet) {
  11569. // <slot v-for="..."> or <template v-for="..."><slot/></template>
  11570. childBlock = slotOutlet.codegenNode;
  11571. if (isTemplate && keyProperty) {
  11572. // <template v-for="..." :key="..."><slot/></template>
  11573. // we need to inject the key to the renderSlot() call.
  11574. // the props for renderSlot is passed as the 3rd argument.
  11575. injectProp(childBlock, keyProperty, context);
  11576. }
  11577. }
  11578. else if (needFragmentWrapper) {
  11579. // <template v-for="..."> with text or multi-elements
  11580. // should generate a fragment block for each loop
  11581. childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, `${64 /* STABLE_FRAGMENT */} /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`, undefined, undefined, true);
  11582. }
  11583. else {
  11584. // Normal element v-for. Directly use the child's codegenNode
  11585. // but mark it as a block.
  11586. childBlock = children[0]
  11587. .codegenNode;
  11588. if (isTemplate && keyProperty) {
  11589. injectProp(childBlock, keyProperty, context);
  11590. }
  11591. childBlock.isBlock = !isStableFragment;
  11592. if (childBlock.isBlock) {
  11593. helper(OPEN_BLOCK);
  11594. helper(CREATE_BLOCK);
  11595. }
  11596. }
  11597. renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
  11598. };
  11599. });
  11600. });
  11601. // target-agnostic transform used for both Client and SSR
  11602. function processFor(node, dir, context, processCodegen) {
  11603. if (!dir.exp) {
  11604. context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
  11605. return;
  11606. }
  11607. const parseResult = parseForExpression(
  11608. // can only be simple expression because vFor transform is applied
  11609. // before expression transform.
  11610. dir.exp, context);
  11611. if (!parseResult) {
  11612. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
  11613. return;
  11614. }
  11615. const { addIdentifiers, removeIdentifiers, scopes } = context;
  11616. const { source, value, key, index } = parseResult;
  11617. const forNode = {
  11618. type: 11 /* FOR */,
  11619. loc: dir.loc,
  11620. source,
  11621. valueAlias: value,
  11622. keyAlias: key,
  11623. objectIndexAlias: index,
  11624. parseResult,
  11625. children: isTemplateNode(node) ? node.children : [node]
  11626. };
  11627. context.replaceNode(forNode);
  11628. // bookkeeping
  11629. scopes.vFor++;
  11630. const onExit = processCodegen && processCodegen(forNode);
  11631. return () => {
  11632. scopes.vFor--;
  11633. if (onExit)
  11634. onExit();
  11635. };
  11636. }
  11637. const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
  11638. // This regex doesn't cover the case if key or index aliases have destructuring,
  11639. // but those do not make sense in the first place, so this works in practice.
  11640. const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
  11641. const stripParensRE = /^\(|\)$/g;
  11642. function parseForExpression(input, context) {
  11643. const loc = input.loc;
  11644. const exp = input.content;
  11645. const inMatch = exp.match(forAliasRE);
  11646. if (!inMatch)
  11647. return;
  11648. const [, LHS, RHS] = inMatch;
  11649. const result = {
  11650. source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
  11651. value: undefined,
  11652. key: undefined,
  11653. index: undefined
  11654. };
  11655. {
  11656. validateBrowserExpression(result.source, context);
  11657. }
  11658. let valueContent = LHS.trim()
  11659. .replace(stripParensRE, '')
  11660. .trim();
  11661. const trimmedOffset = LHS.indexOf(valueContent);
  11662. const iteratorMatch = valueContent.match(forIteratorRE);
  11663. if (iteratorMatch) {
  11664. valueContent = valueContent.replace(forIteratorRE, '').trim();
  11665. const keyContent = iteratorMatch[1].trim();
  11666. let keyOffset;
  11667. if (keyContent) {
  11668. keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
  11669. result.key = createAliasExpression(loc, keyContent, keyOffset);
  11670. {
  11671. validateBrowserExpression(result.key, context, true);
  11672. }
  11673. }
  11674. if (iteratorMatch[2]) {
  11675. const indexContent = iteratorMatch[2].trim();
  11676. if (indexContent) {
  11677. result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
  11678. ? keyOffset + keyContent.length
  11679. : trimmedOffset + valueContent.length));
  11680. {
  11681. validateBrowserExpression(result.index, context, true);
  11682. }
  11683. }
  11684. }
  11685. }
  11686. if (valueContent) {
  11687. result.value = createAliasExpression(loc, valueContent, trimmedOffset);
  11688. {
  11689. validateBrowserExpression(result.value, context, true);
  11690. }
  11691. }
  11692. return result;
  11693. }
  11694. function createAliasExpression(range, content, offset) {
  11695. return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
  11696. }
  11697. function createForLoopParams({ value, key, index }) {
  11698. const params = [];
  11699. if (value) {
  11700. params.push(value);
  11701. }
  11702. if (key) {
  11703. if (!value) {
  11704. params.push(createSimpleExpression(`_`, false));
  11705. }
  11706. params.push(key);
  11707. }
  11708. if (index) {
  11709. if (!key) {
  11710. if (!value) {
  11711. params.push(createSimpleExpression(`_`, false));
  11712. }
  11713. params.push(createSimpleExpression(`__`, false));
  11714. }
  11715. params.push(index);
  11716. }
  11717. return params;
  11718. }
  11719. const defaultFallback = createSimpleExpression(`undefined`, false);
  11720. // A NodeTransform that:
  11721. // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
  11722. // by transformExpression. This is only applied in non-browser builds with
  11723. // { prefixIdentifiers: true }.
  11724. // 2. Track v-slot depths so that we know a slot is inside another slot.
  11725. // Note the exit callback is executed before buildSlots() on the same node,
  11726. // so only nested slots see positive numbers.
  11727. const trackSlotScopes = (node, context) => {
  11728. if (node.type === 1 /* ELEMENT */ &&
  11729. (node.tagType === 1 /* COMPONENT */ ||
  11730. node.tagType === 3 /* TEMPLATE */)) {
  11731. // We are only checking non-empty v-slot here
  11732. // since we only care about slots that introduce scope variables.
  11733. const vSlot = findDir(node, 'slot');
  11734. if (vSlot) {
  11735. const slotProps = vSlot.exp;
  11736. context.scopes.vSlot++;
  11737. return () => {
  11738. context.scopes.vSlot--;
  11739. };
  11740. }
  11741. }
  11742. };
  11743. const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
  11744. // Instead of being a DirectiveTransform, v-slot processing is called during
  11745. // transformElement to build the slots object for a component.
  11746. function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
  11747. context.helper(WITH_CTX);
  11748. const { children, loc } = node;
  11749. const slotsProperties = [];
  11750. const dynamicSlots = [];
  11751. const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
  11752. // If the slot is inside a v-for or another v-slot, force it to be dynamic
  11753. // since it likely uses a scope variable.
  11754. let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
  11755. // 1. Check for slot with slotProps on component itself.
  11756. // <Comp v-slot="{ prop }"/>
  11757. const onComponentSlot = findDir(node, 'slot', true);
  11758. if (onComponentSlot) {
  11759. const { arg, exp } = onComponentSlot;
  11760. if (arg && !isStaticExp(arg)) {
  11761. hasDynamicSlots = true;
  11762. }
  11763. slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
  11764. }
  11765. // 2. Iterate through children and check for template slots
  11766. // <template v-slot:foo="{ prop }">
  11767. let hasTemplateSlots = false;
  11768. let hasNamedDefaultSlot = false;
  11769. const implicitDefaultChildren = [];
  11770. const seenSlotNames = new Set();
  11771. for (let i = 0; i < children.length; i++) {
  11772. const slotElement = children[i];
  11773. let slotDir;
  11774. if (!isTemplateNode(slotElement) ||
  11775. !(slotDir = findDir(slotElement, 'slot', true))) {
  11776. // not a <template v-slot>, skip.
  11777. if (slotElement.type !== 3 /* COMMENT */) {
  11778. implicitDefaultChildren.push(slotElement);
  11779. }
  11780. continue;
  11781. }
  11782. if (onComponentSlot) {
  11783. // already has on-component slot - this is incorrect usage.
  11784. context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
  11785. break;
  11786. }
  11787. hasTemplateSlots = true;
  11788. const { children: slotChildren, loc: slotLoc } = slotElement;
  11789. const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
  11790. // check if name is dynamic.
  11791. let staticSlotName;
  11792. if (isStaticExp(slotName)) {
  11793. staticSlotName = slotName ? slotName.content : `default`;
  11794. }
  11795. else {
  11796. hasDynamicSlots = true;
  11797. }
  11798. const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
  11799. // check if this slot is conditional (v-if/v-for)
  11800. let vIf;
  11801. let vElse;
  11802. let vFor;
  11803. if ((vIf = findDir(slotElement, 'if'))) {
  11804. hasDynamicSlots = true;
  11805. dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
  11806. }
  11807. else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
  11808. // find adjacent v-if
  11809. let j = i;
  11810. let prev;
  11811. while (j--) {
  11812. prev = children[j];
  11813. if (prev.type !== 3 /* COMMENT */) {
  11814. break;
  11815. }
  11816. }
  11817. if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
  11818. // remove node
  11819. children.splice(i, 1);
  11820. i--;
  11821. // attach this slot to previous conditional
  11822. let conditional = dynamicSlots[dynamicSlots.length - 1];
  11823. while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
  11824. conditional = conditional.alternate;
  11825. }
  11826. conditional.alternate = vElse.exp
  11827. ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
  11828. : buildDynamicSlot(slotName, slotFunction);
  11829. }
  11830. else {
  11831. context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
  11832. }
  11833. }
  11834. else if ((vFor = findDir(slotElement, 'for'))) {
  11835. hasDynamicSlots = true;
  11836. const parseResult = vFor.parseResult ||
  11837. parseForExpression(vFor.exp, context);
  11838. if (parseResult) {
  11839. // Render the dynamic slots as an array and add it to the createSlot()
  11840. // args. The runtime knows how to handle it appropriately.
  11841. dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
  11842. parseResult.source,
  11843. createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
  11844. ]));
  11845. }
  11846. else {
  11847. context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
  11848. }
  11849. }
  11850. else {
  11851. // check duplicate static names
  11852. if (staticSlotName) {
  11853. if (seenSlotNames.has(staticSlotName)) {
  11854. context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
  11855. continue;
  11856. }
  11857. seenSlotNames.add(staticSlotName);
  11858. if (staticSlotName === 'default') {
  11859. hasNamedDefaultSlot = true;
  11860. }
  11861. }
  11862. slotsProperties.push(createObjectProperty(slotName, slotFunction));
  11863. }
  11864. }
  11865. if (!onComponentSlot) {
  11866. if (!hasTemplateSlots) {
  11867. // implicit default slot (on component)
  11868. slotsProperties.push(buildDefaultSlotProperty(undefined, children));
  11869. }
  11870. else if (implicitDefaultChildren.length) {
  11871. // implicit default slot (mixed with named slots)
  11872. if (hasNamedDefaultSlot) {
  11873. context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
  11874. }
  11875. else {
  11876. slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
  11877. }
  11878. }
  11879. }
  11880. const slotFlag = hasDynamicSlots
  11881. ? 2 /* DYNAMIC */
  11882. : hasForwardedSlots(node.children)
  11883. ? 3 /* FORWARDED */
  11884. : 1 /* STABLE */;
  11885. let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
  11886. // 2 = compiled but dynamic = can skip normalization, but must run diff
  11887. // 1 = compiled and static = can skip normalization AND diff as optimized
  11888. createSimpleExpression('' + slotFlag, false))), loc);
  11889. if (dynamicSlots.length) {
  11890. slots = createCallExpression(context.helper(CREATE_SLOTS), [
  11891. slots,
  11892. createArrayExpression(dynamicSlots)
  11893. ]);
  11894. }
  11895. return {
  11896. slots,
  11897. hasDynamicSlots
  11898. };
  11899. }
  11900. function buildDynamicSlot(name, fn) {
  11901. return createObjectExpression([
  11902. createObjectProperty(`name`, name),
  11903. createObjectProperty(`fn`, fn)
  11904. ]);
  11905. }
  11906. function hasForwardedSlots(children) {
  11907. for (let i = 0; i < children.length; i++) {
  11908. const child = children[i];
  11909. if (child.type === 1 /* ELEMENT */) {
  11910. if (child.tagType === 2 /* SLOT */ ||
  11911. (child.tagType === 0 /* ELEMENT */ &&
  11912. hasForwardedSlots(child.children))) {
  11913. return true;
  11914. }
  11915. }
  11916. }
  11917. return false;
  11918. }
  11919. // some directive transforms (e.g. v-model) may return a symbol for runtime
  11920. // import, which should be used instead of a resolveDirective call.
  11921. const directiveImportMap = new WeakMap();
  11922. // generate a JavaScript AST for this element's codegen
  11923. const transformElement = (node, context) => {
  11924. if (!(node.type === 1 /* ELEMENT */ &&
  11925. (node.tagType === 0 /* ELEMENT */ ||
  11926. node.tagType === 1 /* COMPONENT */))) {
  11927. return;
  11928. }
  11929. // perform the work on exit, after all child expressions have been
  11930. // processed and merged.
  11931. return function postTransformElement() {
  11932. const { tag, props } = node;
  11933. const isComponent = node.tagType === 1 /* COMPONENT */;
  11934. // The goal of the transform is to create a codegenNode implementing the
  11935. // VNodeCall interface.
  11936. const vnodeTag = isComponent
  11937. ? resolveComponentType(node, context)
  11938. : `"${tag}"`;
  11939. const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
  11940. let vnodeProps;
  11941. let vnodeChildren;
  11942. let vnodePatchFlag;
  11943. let patchFlag = 0;
  11944. let vnodeDynamicProps;
  11945. let dynamicPropNames;
  11946. let vnodeDirectives;
  11947. let shouldUseBlock =
  11948. // dynamic component may resolve to plain elements
  11949. isDynamicComponent ||
  11950. vnodeTag === TELEPORT ||
  11951. vnodeTag === SUSPENSE ||
  11952. (!isComponent &&
  11953. // <svg> and <foreignObject> must be forced into blocks so that block
  11954. // updates inside get proper isSVG flag at runtime. (#639, #643)
  11955. // This is technically web-specific, but splitting the logic out of core
  11956. // leads to too much unnecessary complexity.
  11957. (tag === 'svg' ||
  11958. tag === 'foreignObject' ||
  11959. // #938: elements with dynamic keys should be forced into blocks
  11960. findProp(node, 'key', true)));
  11961. // props
  11962. if (props.length > 0) {
  11963. const propsBuildResult = buildProps(node, context);
  11964. vnodeProps = propsBuildResult.props;
  11965. patchFlag = propsBuildResult.patchFlag;
  11966. dynamicPropNames = propsBuildResult.dynamicPropNames;
  11967. const directives = propsBuildResult.directives;
  11968. vnodeDirectives =
  11969. directives && directives.length
  11970. ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
  11971. : undefined;
  11972. }
  11973. // children
  11974. if (node.children.length > 0) {
  11975. if (vnodeTag === KEEP_ALIVE) {
  11976. // Although a built-in component, we compile KeepAlive with raw children
  11977. // instead of slot functions so that it can be used inside Transition
  11978. // or other Transition-wrapping HOCs.
  11979. // To ensure correct updates with block optimizations, we need to:
  11980. // 1. Force keep-alive into a block. This avoids its children being
  11981. // collected by a parent block.
  11982. shouldUseBlock = true;
  11983. // 2. Force keep-alive to always be updated, since it uses raw children.
  11984. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  11985. if ( node.children.length > 1) {
  11986. context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
  11987. start: node.children[0].loc.start,
  11988. end: node.children[node.children.length - 1].loc.end,
  11989. source: ''
  11990. }));
  11991. }
  11992. }
  11993. const shouldBuildAsSlots = isComponent &&
  11994. // Teleport is not a real component and has dedicated runtime handling
  11995. vnodeTag !== TELEPORT &&
  11996. // explained above.
  11997. vnodeTag !== KEEP_ALIVE;
  11998. if (shouldBuildAsSlots) {
  11999. const { slots, hasDynamicSlots } = buildSlots(node, context);
  12000. vnodeChildren = slots;
  12001. if (hasDynamicSlots) {
  12002. patchFlag |= 1024 /* DYNAMIC_SLOTS */;
  12003. }
  12004. }
  12005. else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
  12006. const child = node.children[0];
  12007. const type = child.type;
  12008. // check for dynamic text children
  12009. const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
  12010. type === 8 /* COMPOUND_EXPRESSION */;
  12011. if (hasDynamicTextChild && !getStaticType(child)) {
  12012. patchFlag |= 1 /* TEXT */;
  12013. }
  12014. // pass directly if the only child is a text node
  12015. // (plain / interpolation / expression)
  12016. if (hasDynamicTextChild || type === 2 /* TEXT */) {
  12017. vnodeChildren = child;
  12018. }
  12019. else {
  12020. vnodeChildren = node.children;
  12021. }
  12022. }
  12023. else {
  12024. vnodeChildren = node.children;
  12025. }
  12026. }
  12027. // patchFlag & dynamicPropNames
  12028. if (patchFlag !== 0) {
  12029. {
  12030. if (patchFlag < 0) {
  12031. // special flags (negative and mutually exclusive)
  12032. vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
  12033. }
  12034. else {
  12035. // bitwise flags
  12036. const flagNames = Object.keys(PatchFlagNames)
  12037. .map(Number)
  12038. .filter(n => n > 0 && patchFlag & n)
  12039. .map(n => PatchFlagNames[n])
  12040. .join(`, `);
  12041. vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
  12042. }
  12043. }
  12044. if (dynamicPropNames && dynamicPropNames.length) {
  12045. vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
  12046. }
  12047. }
  12048. node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
  12049. };
  12050. };
  12051. function resolveComponentType(node, context, ssr = false) {
  12052. const { tag } = node;
  12053. // 1. dynamic component
  12054. const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
  12055. if (isProp) {
  12056. const exp = isProp.type === 6 /* ATTRIBUTE */
  12057. ? isProp.value && createSimpleExpression(isProp.value.content, true)
  12058. : isProp.exp;
  12059. if (exp) {
  12060. return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
  12061. exp
  12062. ]);
  12063. }
  12064. }
  12065. // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
  12066. const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
  12067. if (builtIn) {
  12068. // built-ins are simply fallthroughs / have special handling during ssr
  12069. // no we don't need to import their runtime equivalents
  12070. if (!ssr)
  12071. context.helper(builtIn);
  12072. return builtIn;
  12073. }
  12074. // 3. user component (from setup bindings)
  12075. if (context.bindingMetadata[tag] === 'setup') {
  12076. return `$setup[${JSON.stringify(tag)}]`;
  12077. }
  12078. // 4. user component (resolve)
  12079. context.helper(RESOLVE_COMPONENT);
  12080. context.components.add(tag);
  12081. return toValidAssetId(tag, `component`);
  12082. }
  12083. function buildProps(node, context, props = node.props, ssr = false) {
  12084. const { tag, loc: elementLoc } = node;
  12085. const isComponent = node.tagType === 1 /* COMPONENT */;
  12086. let properties = [];
  12087. const mergeArgs = [];
  12088. const runtimeDirectives = [];
  12089. // patchFlag analysis
  12090. let patchFlag = 0;
  12091. let hasRef = false;
  12092. let hasClassBinding = false;
  12093. let hasStyleBinding = false;
  12094. let hasHydrationEventBinding = false;
  12095. let hasDynamicKeys = false;
  12096. let hasVnodeHook = false;
  12097. const dynamicPropNames = [];
  12098. const analyzePatchFlag = ({ key, value }) => {
  12099. if (isStaticExp(key)) {
  12100. const name = key.content;
  12101. const isEventHandler = isOn(name);
  12102. if (!isComponent &&
  12103. isEventHandler &&
  12104. // omit the flag for click handlers because hydration gives click
  12105. // dedicated fast path.
  12106. name.toLowerCase() !== 'onclick' &&
  12107. // omit v-model handlers
  12108. name !== 'onUpdate:modelValue' &&
  12109. // omit onVnodeXXX hooks
  12110. !isReservedProp(name)) {
  12111. hasHydrationEventBinding = true;
  12112. }
  12113. if (isEventHandler && isReservedProp(name)) {
  12114. hasVnodeHook = true;
  12115. }
  12116. if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
  12117. ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
  12118. value.type === 8 /* COMPOUND_EXPRESSION */) &&
  12119. getStaticType(value) > 0)) {
  12120. // skip if the prop is a cached handler or has constant value
  12121. return;
  12122. }
  12123. if (name === 'ref') {
  12124. hasRef = true;
  12125. }
  12126. else if (name === 'class' && !isComponent) {
  12127. hasClassBinding = true;
  12128. }
  12129. else if (name === 'style' && !isComponent) {
  12130. hasStyleBinding = true;
  12131. }
  12132. else if (name !== 'key' && !dynamicPropNames.includes(name)) {
  12133. dynamicPropNames.push(name);
  12134. }
  12135. }
  12136. else {
  12137. hasDynamicKeys = true;
  12138. }
  12139. };
  12140. for (let i = 0; i < props.length; i++) {
  12141. // static attribute
  12142. const prop = props[i];
  12143. if (prop.type === 6 /* ATTRIBUTE */) {
  12144. const { loc, name, value } = prop;
  12145. if (name === 'ref') {
  12146. hasRef = true;
  12147. }
  12148. // skip :is on <component>
  12149. if (name === 'is' && tag === 'component') {
  12150. continue;
  12151. }
  12152. properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', true, value ? value.loc : loc)));
  12153. }
  12154. else {
  12155. // directives
  12156. const { name, arg, exp, loc } = prop;
  12157. const isBind = name === 'bind';
  12158. const isOn = name === 'on';
  12159. // skip v-slot - it is handled by its dedicated transform.
  12160. if (name === 'slot') {
  12161. if (!isComponent) {
  12162. context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
  12163. }
  12164. continue;
  12165. }
  12166. // skip v-once - it is handled by its dedicated transform.
  12167. if (name === 'once') {
  12168. continue;
  12169. }
  12170. // skip v-is and :is on <component>
  12171. if (name === 'is' ||
  12172. (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
  12173. continue;
  12174. }
  12175. // skip v-on in SSR compilation
  12176. if (isOn && ssr) {
  12177. continue;
  12178. }
  12179. // special case for v-bind and v-on with no argument
  12180. if (!arg && (isBind || isOn)) {
  12181. hasDynamicKeys = true;
  12182. if (exp) {
  12183. if (properties.length) {
  12184. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  12185. properties = [];
  12186. }
  12187. if (isBind) {
  12188. mergeArgs.push(exp);
  12189. }
  12190. else {
  12191. // v-on="obj" -> toHandlers(obj)
  12192. mergeArgs.push({
  12193. type: 14 /* JS_CALL_EXPRESSION */,
  12194. loc,
  12195. callee: context.helper(TO_HANDLERS),
  12196. arguments: [exp]
  12197. });
  12198. }
  12199. }
  12200. else {
  12201. context.onError(createCompilerError(isBind
  12202. ? 33 /* X_V_BIND_NO_EXPRESSION */
  12203. : 34 /* X_V_ON_NO_EXPRESSION */, loc));
  12204. }
  12205. continue;
  12206. }
  12207. const directiveTransform = context.directiveTransforms[name];
  12208. if (directiveTransform) {
  12209. // has built-in directive transform.
  12210. const { props, needRuntime } = directiveTransform(prop, node, context);
  12211. !ssr && props.forEach(analyzePatchFlag);
  12212. properties.push(...props);
  12213. if (needRuntime) {
  12214. runtimeDirectives.push(prop);
  12215. if (isSymbol(needRuntime)) {
  12216. directiveImportMap.set(prop, needRuntime);
  12217. }
  12218. }
  12219. }
  12220. else {
  12221. // no built-in transform, this is a user custom directive.
  12222. runtimeDirectives.push(prop);
  12223. }
  12224. }
  12225. }
  12226. let propsExpression = undefined;
  12227. // has v-bind="object" or v-on="object", wrap with mergeProps
  12228. if (mergeArgs.length) {
  12229. if (properties.length) {
  12230. mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
  12231. }
  12232. if (mergeArgs.length > 1) {
  12233. propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
  12234. }
  12235. else {
  12236. // single v-bind with nothing else - no need for a mergeProps call
  12237. propsExpression = mergeArgs[0];
  12238. }
  12239. }
  12240. else if (properties.length) {
  12241. propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
  12242. }
  12243. // patchFlag analysis
  12244. if (hasDynamicKeys) {
  12245. patchFlag |= 16 /* FULL_PROPS */;
  12246. }
  12247. else {
  12248. if (hasClassBinding) {
  12249. patchFlag |= 2 /* CLASS */;
  12250. }
  12251. if (hasStyleBinding) {
  12252. patchFlag |= 4 /* STYLE */;
  12253. }
  12254. if (dynamicPropNames.length) {
  12255. patchFlag |= 8 /* PROPS */;
  12256. }
  12257. if (hasHydrationEventBinding) {
  12258. patchFlag |= 32 /* HYDRATE_EVENTS */;
  12259. }
  12260. }
  12261. if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
  12262. (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
  12263. patchFlag |= 512 /* NEED_PATCH */;
  12264. }
  12265. return {
  12266. props: propsExpression,
  12267. directives: runtimeDirectives,
  12268. patchFlag,
  12269. dynamicPropNames
  12270. };
  12271. }
  12272. // Dedupe props in an object literal.
  12273. // Literal duplicated attributes would have been warned during the parse phase,
  12274. // however, it's possible to encounter duplicated `onXXX` handlers with different
  12275. // modifiers. We also need to merge static and dynamic class / style attributes.
  12276. // - onXXX handlers / style: merge into array
  12277. // - class: merge into single expression with concatenation
  12278. function dedupeProperties(properties) {
  12279. const knownProps = new Map();
  12280. const deduped = [];
  12281. for (let i = 0; i < properties.length; i++) {
  12282. const prop = properties[i];
  12283. // dynamic keys are always allowed
  12284. if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
  12285. deduped.push(prop);
  12286. continue;
  12287. }
  12288. const name = prop.key.content;
  12289. const existing = knownProps.get(name);
  12290. if (existing) {
  12291. if (name === 'style' || name === 'class' || name.startsWith('on')) {
  12292. mergeAsArray(existing, prop);
  12293. }
  12294. // unexpected duplicate, should have emitted error during parse
  12295. }
  12296. else {
  12297. knownProps.set(name, prop);
  12298. deduped.push(prop);
  12299. }
  12300. }
  12301. return deduped;
  12302. }
  12303. function mergeAsArray(existing, incoming) {
  12304. if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
  12305. existing.value.elements.push(incoming.value);
  12306. }
  12307. else {
  12308. existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
  12309. }
  12310. }
  12311. function buildDirectiveArgs(dir, context) {
  12312. const dirArgs = [];
  12313. const runtime = directiveImportMap.get(dir);
  12314. if (runtime) {
  12315. dirArgs.push(context.helperString(runtime));
  12316. }
  12317. else {
  12318. // inject statement for resolving directive
  12319. context.helper(RESOLVE_DIRECTIVE);
  12320. context.directives.add(dir.name);
  12321. dirArgs.push(toValidAssetId(dir.name, `directive`));
  12322. }
  12323. const { loc } = dir;
  12324. if (dir.exp)
  12325. dirArgs.push(dir.exp);
  12326. if (dir.arg) {
  12327. if (!dir.exp) {
  12328. dirArgs.push(`void 0`);
  12329. }
  12330. dirArgs.push(dir.arg);
  12331. }
  12332. if (Object.keys(dir.modifiers).length) {
  12333. if (!dir.arg) {
  12334. if (!dir.exp) {
  12335. dirArgs.push(`void 0`);
  12336. }
  12337. dirArgs.push(`void 0`);
  12338. }
  12339. const trueExpression = createSimpleExpression(`true`, false, loc);
  12340. dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
  12341. }
  12342. return createArrayExpression(dirArgs, dir.loc);
  12343. }
  12344. function stringifyDynamicPropNames(props) {
  12345. let propsNamesString = `[`;
  12346. for (let i = 0, l = props.length; i < l; i++) {
  12347. propsNamesString += JSON.stringify(props[i]);
  12348. if (i < l - 1)
  12349. propsNamesString += ', ';
  12350. }
  12351. return propsNamesString + `]`;
  12352. }
  12353. const transformSlotOutlet = (node, context) => {
  12354. if (isSlotOutlet(node)) {
  12355. const { children, loc } = node;
  12356. const { slotName, slotProps } = processSlotOutlet(node, context);
  12357. const slotArgs = [
  12358. context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
  12359. slotName
  12360. ];
  12361. if (slotProps) {
  12362. slotArgs.push(slotProps);
  12363. }
  12364. if (children.length) {
  12365. if (!slotProps) {
  12366. slotArgs.push(`{}`);
  12367. }
  12368. slotArgs.push(createFunctionExpression([], children, false, false, loc));
  12369. }
  12370. node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
  12371. }
  12372. };
  12373. function processSlotOutlet(node, context) {
  12374. let slotName = `"default"`;
  12375. let slotProps = undefined;
  12376. // check for <slot name="xxx" OR :name="xxx" />
  12377. const name = findProp(node, 'name');
  12378. if (name) {
  12379. if (name.type === 6 /* ATTRIBUTE */ && name.value) {
  12380. // static name
  12381. slotName = JSON.stringify(name.value.content);
  12382. }
  12383. else if (name.type === 7 /* DIRECTIVE */ && name.exp) {
  12384. // dynamic name
  12385. slotName = name.exp;
  12386. }
  12387. }
  12388. const propsWithoutName = name
  12389. ? node.props.filter(p => p !== name)
  12390. : node.props;
  12391. if (propsWithoutName.length > 0) {
  12392. const { props, directives } = buildProps(node, context, propsWithoutName);
  12393. slotProps = props;
  12394. if (directives.length) {
  12395. context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
  12396. }
  12397. }
  12398. return {
  12399. slotName,
  12400. slotProps
  12401. };
  12402. }
  12403. const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
  12404. const transformOn = (dir, node, context, augmentor) => {
  12405. const { loc, modifiers, arg } = dir;
  12406. if (!dir.exp && !modifiers.length) {
  12407. context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
  12408. }
  12409. let eventName;
  12410. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  12411. if (arg.isStatic) {
  12412. const rawName = arg.content;
  12413. // for all event listeners, auto convert it to camelCase. See issue #2249
  12414. eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
  12415. }
  12416. else {
  12417. // #2388
  12418. eventName = createCompoundExpression([
  12419. `${context.helperString(TO_HANDLER_KEY)}(`,
  12420. arg,
  12421. `)`
  12422. ]);
  12423. }
  12424. }
  12425. else {
  12426. // already a compound expression.
  12427. eventName = arg;
  12428. eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
  12429. eventName.children.push(`)`);
  12430. }
  12431. // handler processing
  12432. let exp = dir.exp;
  12433. if (exp && !exp.content.trim()) {
  12434. exp = undefined;
  12435. }
  12436. let isCacheable = context.cacheHandlers && !exp;
  12437. if (exp) {
  12438. const isMemberExp = isMemberExpression(exp.content);
  12439. const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
  12440. const hasMultipleStatements = exp.content.includes(`;`);
  12441. {
  12442. validateBrowserExpression(exp, context, false, hasMultipleStatements);
  12443. }
  12444. if (isInlineStatement || (isCacheable && isMemberExp)) {
  12445. // wrap inline statement in a function expression
  12446. exp = createCompoundExpression([
  12447. `${isInlineStatement ? `$event` : `(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
  12448. exp,
  12449. hasMultipleStatements ? `}` : `)`
  12450. ]);
  12451. }
  12452. }
  12453. let ret = {
  12454. props: [
  12455. createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
  12456. ]
  12457. };
  12458. // apply extended compiler augmentor
  12459. if (augmentor) {
  12460. ret = augmentor(ret);
  12461. }
  12462. if (isCacheable) {
  12463. // cache handlers so that it's always the same handler being passed down.
  12464. // this avoids unnecessary re-renders when users use inline handlers on
  12465. // components.
  12466. ret.props[0].value = context.cache(ret.props[0].value);
  12467. }
  12468. return ret;
  12469. };
  12470. // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
  12471. // codegen for the entire props object. This transform here is only for v-bind
  12472. // *with* args.
  12473. const transformBind = (dir, node, context) => {
  12474. const { exp, modifiers, loc } = dir;
  12475. const arg = dir.arg;
  12476. if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
  12477. arg.children.unshift(`(`);
  12478. arg.children.push(`) || ""`);
  12479. }
  12480. else if (!arg.isStatic) {
  12481. arg.content = `${arg.content} || ""`;
  12482. }
  12483. // .prop is no longer necessary due to new patch behavior
  12484. // .sync is replaced by v-model:arg
  12485. if (modifiers.includes('camel')) {
  12486. if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
  12487. if (arg.isStatic) {
  12488. arg.content = camelize(arg.content);
  12489. }
  12490. else {
  12491. arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
  12492. }
  12493. }
  12494. else {
  12495. arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
  12496. arg.children.push(`)`);
  12497. }
  12498. }
  12499. if (!exp ||
  12500. (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
  12501. context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
  12502. return {
  12503. props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
  12504. };
  12505. }
  12506. return {
  12507. props: [createObjectProperty(arg, exp)]
  12508. };
  12509. };
  12510. // Merge adjacent text nodes and expressions into a single expression
  12511. // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
  12512. const transformText = (node, context) => {
  12513. if (node.type === 0 /* ROOT */ ||
  12514. node.type === 1 /* ELEMENT */ ||
  12515. node.type === 11 /* FOR */ ||
  12516. node.type === 10 /* IF_BRANCH */) {
  12517. // perform the transform on node exit so that all expressions have already
  12518. // been processed.
  12519. return () => {
  12520. const children = node.children;
  12521. let currentContainer = undefined;
  12522. let hasText = false;
  12523. for (let i = 0; i < children.length; i++) {
  12524. const child = children[i];
  12525. if (isText(child)) {
  12526. hasText = true;
  12527. for (let j = i + 1; j < children.length; j++) {
  12528. const next = children[j];
  12529. if (isText(next)) {
  12530. if (!currentContainer) {
  12531. currentContainer = children[i] = {
  12532. type: 8 /* COMPOUND_EXPRESSION */,
  12533. loc: child.loc,
  12534. children: [child]
  12535. };
  12536. }
  12537. // merge adjacent text node into current
  12538. currentContainer.children.push(` + `, next);
  12539. children.splice(j, 1);
  12540. j--;
  12541. }
  12542. else {
  12543. currentContainer = undefined;
  12544. break;
  12545. }
  12546. }
  12547. }
  12548. }
  12549. if (!hasText ||
  12550. // if this is a plain element with a single text child, leave it
  12551. // as-is since the runtime has dedicated fast path for this by directly
  12552. // setting textContent of the element.
  12553. // for component root it's always normalized anyway.
  12554. (children.length === 1 &&
  12555. (node.type === 0 /* ROOT */ ||
  12556. (node.type === 1 /* ELEMENT */ &&
  12557. node.tagType === 0 /* ELEMENT */)))) {
  12558. return;
  12559. }
  12560. // pre-convert text nodes into createTextVNode(text) calls to avoid
  12561. // runtime normalization.
  12562. for (let i = 0; i < children.length; i++) {
  12563. const child = children[i];
  12564. if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
  12565. const callArgs = [];
  12566. // createTextVNode defaults to single whitespace, so if it is a
  12567. // single space the code could be an empty call to save bytes.
  12568. if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
  12569. callArgs.push(child);
  12570. }
  12571. // mark dynamic text with flag so it gets patched inside a block
  12572. if (!context.ssr && child.type !== 2 /* TEXT */) {
  12573. callArgs.push(`${1 /* TEXT */} /* ${PatchFlagNames[1 /* TEXT */]} */`);
  12574. }
  12575. children[i] = {
  12576. type: 12 /* TEXT_CALL */,
  12577. content: child,
  12578. loc: child.loc,
  12579. codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
  12580. };
  12581. }
  12582. }
  12583. };
  12584. }
  12585. };
  12586. const seen = new WeakSet();
  12587. const transformOnce = (node, context) => {
  12588. if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
  12589. if (seen.has(node)) {
  12590. return;
  12591. }
  12592. seen.add(node);
  12593. context.helper(SET_BLOCK_TRACKING);
  12594. return () => {
  12595. const cur = context.currentNode;
  12596. if (cur.codegenNode) {
  12597. cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
  12598. }
  12599. };
  12600. }
  12601. };
  12602. const transformModel = (dir, node, context) => {
  12603. const { exp, arg } = dir;
  12604. if (!exp) {
  12605. context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
  12606. return createTransformProps();
  12607. }
  12608. const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : exp.loc.source;
  12609. if (!isMemberExpression(expString)) {
  12610. context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
  12611. return createTransformProps();
  12612. }
  12613. const propName = arg ? arg : createSimpleExpression('modelValue', true);
  12614. const eventName = arg
  12615. ? isStaticExp(arg)
  12616. ? `onUpdate:${arg.content}`
  12617. : createCompoundExpression(['"onUpdate:" + ', arg])
  12618. : `onUpdate:modelValue`;
  12619. const props = [
  12620. // modelValue: foo
  12621. createObjectProperty(propName, dir.exp),
  12622. // "onUpdate:modelValue": $event => (foo = $event)
  12623. createObjectProperty(eventName, createCompoundExpression([`$event => (`, exp, ` = $event)`]))
  12624. ];
  12625. // modelModifiers: { foo: true, "bar-baz": true }
  12626. if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
  12627. const modifiers = dir.modifiers
  12628. .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
  12629. .join(`, `);
  12630. const modifiersKey = arg
  12631. ? isStaticExp(arg)
  12632. ? `${arg.content}Modifiers`
  12633. : createCompoundExpression([arg, ' + "Modifiers"'])
  12634. : `modelModifiers`;
  12635. props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, true)));
  12636. }
  12637. return createTransformProps(props);
  12638. };
  12639. function createTransformProps(props = []) {
  12640. return { props };
  12641. }
  12642. function getBaseTransformPreset(prefixIdentifiers) {
  12643. return [
  12644. [
  12645. transformOnce,
  12646. transformIf,
  12647. transformFor,
  12648. ...( [transformExpression]
  12649. ),
  12650. transformSlotOutlet,
  12651. transformElement,
  12652. trackSlotScopes,
  12653. transformText
  12654. ],
  12655. {
  12656. on: transformOn,
  12657. bind: transformBind,
  12658. model: transformModel
  12659. }
  12660. ];
  12661. }
  12662. // we name it `baseCompile` so that higher order compilers like
  12663. // @vue/compiler-dom can export `compile` while re-exporting everything else.
  12664. function baseCompile(template, options = {}) {
  12665. const onError = options.onError || defaultOnError;
  12666. const isModuleMode = options.mode === 'module';
  12667. /* istanbul ignore if */
  12668. {
  12669. if (options.prefixIdentifiers === true) {
  12670. onError(createCompilerError(45 /* X_PREFIX_ID_NOT_SUPPORTED */));
  12671. }
  12672. else if (isModuleMode) {
  12673. onError(createCompilerError(46 /* X_MODULE_MODE_NOT_SUPPORTED */));
  12674. }
  12675. }
  12676. const prefixIdentifiers = !true ;
  12677. if ( options.cacheHandlers) {
  12678. onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
  12679. }
  12680. if (options.scopeId && !isModuleMode) {
  12681. onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
  12682. }
  12683. const ast = isString(template) ? baseParse(template, options) : template;
  12684. const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
  12685. transform(ast, extend({}, options, {
  12686. prefixIdentifiers,
  12687. nodeTransforms: [
  12688. ...nodeTransforms,
  12689. ...(options.nodeTransforms || []) // user transforms
  12690. ],
  12691. directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
  12692. )
  12693. }));
  12694. return generate(ast, extend({}, options, {
  12695. prefixIdentifiers
  12696. }));
  12697. }
  12698. const noopDirectiveTransform = () => ({ props: [] });
  12699. const V_MODEL_RADIO = Symbol( `vModelRadio` );
  12700. const V_MODEL_CHECKBOX = Symbol( `vModelCheckbox` );
  12701. const V_MODEL_TEXT = Symbol( `vModelText` );
  12702. const V_MODEL_SELECT = Symbol( `vModelSelect` );
  12703. const V_MODEL_DYNAMIC = Symbol( `vModelDynamic` );
  12704. const V_ON_WITH_MODIFIERS = Symbol( `vOnModifiersGuard` );
  12705. const V_ON_WITH_KEYS = Symbol( `vOnKeysGuard` );
  12706. const V_SHOW = Symbol( `vShow` );
  12707. const TRANSITION$1 = Symbol( `Transition` );
  12708. const TRANSITION_GROUP = Symbol( `TransitionGroup` );
  12709. registerRuntimeHelpers({
  12710. [V_MODEL_RADIO]: `vModelRadio`,
  12711. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  12712. [V_MODEL_TEXT]: `vModelText`,
  12713. [V_MODEL_SELECT]: `vModelSelect`,
  12714. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  12715. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  12716. [V_ON_WITH_KEYS]: `withKeys`,
  12717. [V_SHOW]: `vShow`,
  12718. [TRANSITION$1]: `Transition`,
  12719. [TRANSITION_GROUP]: `TransitionGroup`
  12720. });
  12721. /* eslint-disable no-restricted-globals */
  12722. let decoder;
  12723. function decodeHtmlBrowser(raw) {
  12724. (decoder || (decoder = document.createElement('div'))).innerHTML = raw;
  12725. return decoder.textContent;
  12726. }
  12727. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  12728. const parserOptions = {
  12729. isVoidTag,
  12730. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  12731. isPreTag: tag => tag === 'pre',
  12732. decodeEntities: decodeHtmlBrowser ,
  12733. isBuiltInComponent: (tag) => {
  12734. if (isBuiltInType(tag, `Transition`)) {
  12735. return TRANSITION$1;
  12736. }
  12737. else if (isBuiltInType(tag, `TransitionGroup`)) {
  12738. return TRANSITION_GROUP;
  12739. }
  12740. },
  12741. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  12742. getNamespace(tag, parent) {
  12743. let ns = parent ? parent.ns : 0 /* HTML */;
  12744. if (parent && ns === 2 /* MATH_ML */) {
  12745. if (parent.tag === 'annotation-xml') {
  12746. if (tag === 'svg') {
  12747. return 1 /* SVG */;
  12748. }
  12749. if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
  12750. a.name === 'encoding' &&
  12751. a.value != null &&
  12752. (a.value.content === 'text/html' ||
  12753. a.value.content === 'application/xhtml+xml'))) {
  12754. ns = 0 /* HTML */;
  12755. }
  12756. }
  12757. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  12758. tag !== 'mglyph' &&
  12759. tag !== 'malignmark') {
  12760. ns = 0 /* HTML */;
  12761. }
  12762. }
  12763. else if (parent && ns === 1 /* SVG */) {
  12764. if (parent.tag === 'foreignObject' ||
  12765. parent.tag === 'desc' ||
  12766. parent.tag === 'title') {
  12767. ns = 0 /* HTML */;
  12768. }
  12769. }
  12770. if (ns === 0 /* HTML */) {
  12771. if (tag === 'svg') {
  12772. return 1 /* SVG */;
  12773. }
  12774. if (tag === 'math') {
  12775. return 2 /* MATH_ML */;
  12776. }
  12777. }
  12778. return ns;
  12779. },
  12780. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  12781. getTextMode({ tag, ns }) {
  12782. if (ns === 0 /* HTML */) {
  12783. if (tag === 'textarea' || tag === 'title') {
  12784. return 1 /* RCDATA */;
  12785. }
  12786. if (isRawTextContainer(tag)) {
  12787. return 2 /* RAWTEXT */;
  12788. }
  12789. }
  12790. return 0 /* DATA */;
  12791. }
  12792. };
  12793. // Parse inline CSS strings for static style attributes into an object.
  12794. // This is a NodeTransform since it works on the static `style` attribute and
  12795. // converts it into a dynamic equivalent:
  12796. // style="color: red" -> :style='{ "color": "red" }'
  12797. // It is then processed by `transformElement` and included in the generated
  12798. // props.
  12799. const transformStyle = node => {
  12800. if (node.type === 1 /* ELEMENT */) {
  12801. node.props.forEach((p, i) => {
  12802. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  12803. // replace p with an expression node
  12804. node.props[i] = {
  12805. type: 7 /* DIRECTIVE */,
  12806. name: `bind`,
  12807. arg: createSimpleExpression(`style`, true, p.loc),
  12808. exp: parseInlineCSS(p.value.content, p.loc),
  12809. modifiers: [],
  12810. loc: p.loc
  12811. };
  12812. }
  12813. });
  12814. }
  12815. };
  12816. const parseInlineCSS = (cssText, loc) => {
  12817. const normalized = parseStringStyle(cssText);
  12818. return createSimpleExpression(JSON.stringify(normalized), false, loc, true);
  12819. };
  12820. function createDOMCompilerError(code, loc) {
  12821. return createCompilerError(code, loc, DOMErrorMessages );
  12822. }
  12823. const DOMErrorMessages = {
  12824. [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  12825. [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  12826. [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  12827. [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  12828. [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  12829. [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  12830. [55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  12831. [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  12832. [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  12833. [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  12834. [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  12835. };
  12836. const transformVHtml = (dir, node, context) => {
  12837. const { exp, loc } = dir;
  12838. if (!exp) {
  12839. context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
  12840. }
  12841. if (node.children.length) {
  12842. context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
  12843. node.children.length = 0;
  12844. }
  12845. return {
  12846. props: [
  12847. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  12848. ]
  12849. };
  12850. };
  12851. const transformVText = (dir, node, context) => {
  12852. const { exp, loc } = dir;
  12853. if (!exp) {
  12854. context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
  12855. }
  12856. if (node.children.length) {
  12857. context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
  12858. node.children.length = 0;
  12859. }
  12860. return {
  12861. props: [
  12862. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  12863. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  12864. : createSimpleExpression('', true))
  12865. ]
  12866. };
  12867. };
  12868. const transformModel$1 = (dir, node, context) => {
  12869. const baseResult = transformModel(dir, node, context);
  12870. // base transform has errors OR component v-model (only need props)
  12871. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  12872. return baseResult;
  12873. }
  12874. if (dir.arg) {
  12875. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  12876. }
  12877. function checkDuplicatedValue() {
  12878. const value = findProp(node, 'value');
  12879. if (value) {
  12880. context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  12881. }
  12882. }
  12883. const { tag } = node;
  12884. const isCustomElement = context.isCustomElement(tag);
  12885. if (tag === 'input' ||
  12886. tag === 'textarea' ||
  12887. tag === 'select' ||
  12888. isCustomElement) {
  12889. let directiveToUse = V_MODEL_TEXT;
  12890. let isInvalidType = false;
  12891. if (tag === 'input' || isCustomElement) {
  12892. const type = findProp(node, `type`);
  12893. if (type) {
  12894. if (type.type === 7 /* DIRECTIVE */) {
  12895. // :type="foo"
  12896. directiveToUse = V_MODEL_DYNAMIC;
  12897. }
  12898. else if (type.value) {
  12899. switch (type.value.content) {
  12900. case 'radio':
  12901. directiveToUse = V_MODEL_RADIO;
  12902. break;
  12903. case 'checkbox':
  12904. directiveToUse = V_MODEL_CHECKBOX;
  12905. break;
  12906. case 'file':
  12907. isInvalidType = true;
  12908. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  12909. break;
  12910. default:
  12911. // text type
  12912. checkDuplicatedValue();
  12913. break;
  12914. }
  12915. }
  12916. }
  12917. else if (hasDynamicKeyVBind(node)) {
  12918. // element has bindings with dynamic keys, which can possibly contain
  12919. // "type".
  12920. directiveToUse = V_MODEL_DYNAMIC;
  12921. }
  12922. else {
  12923. // text type
  12924. checkDuplicatedValue();
  12925. }
  12926. }
  12927. else if (tag === 'select') {
  12928. directiveToUse = V_MODEL_SELECT;
  12929. }
  12930. else {
  12931. // textarea
  12932. checkDuplicatedValue();
  12933. }
  12934. // inject runtime directive
  12935. // by returning the helper symbol via needRuntime
  12936. // the import will replaced a resolveDirective call.
  12937. if (!isInvalidType) {
  12938. baseResult.needRuntime = context.helper(directiveToUse);
  12939. }
  12940. }
  12941. else {
  12942. context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  12943. }
  12944. // native vmodel doesn't need the `modelValue` props since they are also
  12945. // passed to the runtime as `binding.value`. removing it reduces code size.
  12946. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  12947. p.key.content === 'modelValue'));
  12948. return baseResult;
  12949. };
  12950. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  12951. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  12952. // event propagation management
  12953. `stop,prevent,self,` +
  12954. // system modifiers + exact
  12955. `ctrl,shift,alt,meta,exact,` +
  12956. // mouse
  12957. `middle`);
  12958. // left & right could be mouse or key modifiers based on event type
  12959. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  12960. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  12961. const resolveModifiers = (key, modifiers) => {
  12962. const keyModifiers = [];
  12963. const nonKeyModifiers = [];
  12964. const eventOptionModifiers = [];
  12965. for (let i = 0; i < modifiers.length; i++) {
  12966. const modifier = modifiers[i];
  12967. if (isEventOptionModifier(modifier)) {
  12968. // eventOptionModifiers: modifiers for addEventListener() options,
  12969. // e.g. .passive & .capture
  12970. eventOptionModifiers.push(modifier);
  12971. }
  12972. else {
  12973. // runtimeModifiers: modifiers that needs runtime guards
  12974. if (maybeKeyModifier(modifier)) {
  12975. if (isStaticExp(key)) {
  12976. if (isKeyboardEvent(key.content)) {
  12977. keyModifiers.push(modifier);
  12978. }
  12979. else {
  12980. nonKeyModifiers.push(modifier);
  12981. }
  12982. }
  12983. else {
  12984. keyModifiers.push(modifier);
  12985. nonKeyModifiers.push(modifier);
  12986. }
  12987. }
  12988. else {
  12989. if (isNonKeyModifier(modifier)) {
  12990. nonKeyModifiers.push(modifier);
  12991. }
  12992. else {
  12993. keyModifiers.push(modifier);
  12994. }
  12995. }
  12996. }
  12997. }
  12998. return {
  12999. keyModifiers,
  13000. nonKeyModifiers,
  13001. eventOptionModifiers
  13002. };
  13003. };
  13004. const transformClick = (key, event) => {
  13005. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  13006. return isStaticClick
  13007. ? createSimpleExpression(event, true)
  13008. : key.type !== 4 /* SIMPLE_EXPRESSION */
  13009. ? createCompoundExpression([
  13010. `(`,
  13011. key,
  13012. `) === "onClick" ? "${event}" : (`,
  13013. key,
  13014. `)`
  13015. ])
  13016. : key;
  13017. };
  13018. const transformOn$1 = (dir, node, context) => {
  13019. return transformOn(dir, node, context, baseResult => {
  13020. const { modifiers } = dir;
  13021. if (!modifiers.length)
  13022. return baseResult;
  13023. let { key, value: handlerExp } = baseResult.props[0];
  13024. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
  13025. // normalize click.right and click.middle since they don't actually fire
  13026. if (nonKeyModifiers.includes('right')) {
  13027. key = transformClick(key, `onContextmenu`);
  13028. }
  13029. if (nonKeyModifiers.includes('middle')) {
  13030. key = transformClick(key, `onMouseup`);
  13031. }
  13032. if (nonKeyModifiers.length) {
  13033. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  13034. handlerExp,
  13035. JSON.stringify(nonKeyModifiers)
  13036. ]);
  13037. }
  13038. if (keyModifiers.length &&
  13039. // if event name is dynamic, always wrap with keys guard
  13040. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  13041. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  13042. handlerExp,
  13043. JSON.stringify(keyModifiers)
  13044. ]);
  13045. }
  13046. if (eventOptionModifiers.length) {
  13047. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  13048. key = isStaticExp(key)
  13049. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  13050. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  13051. }
  13052. return {
  13053. props: [createObjectProperty(key, handlerExp)]
  13054. };
  13055. });
  13056. };
  13057. const transformShow = (dir, node, context) => {
  13058. const { exp, loc } = dir;
  13059. if (!exp) {
  13060. context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
  13061. }
  13062. return {
  13063. props: [],
  13064. needRuntime: context.helper(V_SHOW)
  13065. };
  13066. };
  13067. const warnTransitionChildren = (node, context) => {
  13068. if (node.type === 1 /* ELEMENT */ &&
  13069. node.tagType === 1 /* COMPONENT */) {
  13070. const component = context.isBuiltInComponent(node.tag);
  13071. if (component === TRANSITION$1) {
  13072. return () => {
  13073. if (node.children.length && hasMultipleChildren(node)) {
  13074. context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
  13075. start: node.children[0].loc.start,
  13076. end: node.children[node.children.length - 1].loc.end,
  13077. source: ''
  13078. }));
  13079. }
  13080. };
  13081. }
  13082. }
  13083. };
  13084. function hasMultipleChildren(node) {
  13085. // #1352 filter out potential comment nodes.
  13086. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
  13087. const child = children[0];
  13088. return (children.length !== 1 ||
  13089. child.type === 11 /* FOR */ ||
  13090. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  13091. }
  13092. const ignoreSideEffectTags = (node, context) => {
  13093. if (node.type === 1 /* ELEMENT */ &&
  13094. node.tagType === 0 /* ELEMENT */ &&
  13095. (node.tag === 'script' || node.tag === 'style')) {
  13096. context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  13097. context.removeNode();
  13098. }
  13099. };
  13100. const DOMNodeTransforms = [
  13101. transformStyle,
  13102. ...( [warnTransitionChildren] )
  13103. ];
  13104. const DOMDirectiveTransforms = {
  13105. cloak: noopDirectiveTransform,
  13106. html: transformVHtml,
  13107. text: transformVText,
  13108. model: transformModel$1,
  13109. on: transformOn$1,
  13110. show: transformShow
  13111. };
  13112. function compile$1(template, options = {}) {
  13113. return baseCompile(template, extend({}, parserOptions, options, {
  13114. nodeTransforms: [
  13115. // ignore <script> and <tag>
  13116. // this is not put inside DOMNodeTransforms because that list is used
  13117. // by compiler-ssr to generate vnode fallback branches
  13118. ignoreSideEffectTags,
  13119. ...DOMNodeTransforms,
  13120. ...(options.nodeTransforms || [])
  13121. ],
  13122. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  13123. transformHoist: null
  13124. }));
  13125. }
  13126. // This entry is the "full-build" that includes both the runtime
  13127. initDev();
  13128. const compileCache = Object.create(null);
  13129. function compileToFunction(template, options) {
  13130. if (!isString(template)) {
  13131. if (template.nodeType) {
  13132. template = template.innerHTML;
  13133. }
  13134. else {
  13135. warn(`invalid template option: `, template);
  13136. return NOOP;
  13137. }
  13138. }
  13139. const key = template;
  13140. const cached = compileCache[key];
  13141. if (cached) {
  13142. return cached;
  13143. }
  13144. if (template[0] === '#') {
  13145. const el = document.querySelector(template);
  13146. if ( !el) {
  13147. warn(`Template element not found or is empty: ${template}`);
  13148. }
  13149. // __UNSAFE__
  13150. // Reason: potential execution of JS expressions in in-DOM template.
  13151. // The user must make sure the in-DOM template is trusted. If it's rendered
  13152. // by the server, the template should not contain any user data.
  13153. template = el ? el.innerHTML : ``;
  13154. }
  13155. const { code } = compile$1(template, extend({
  13156. hoistStatic: true,
  13157. onError(err) {
  13158. {
  13159. const message = `Template compilation error: ${err.message}`;
  13160. const codeFrame = err.loc &&
  13161. generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
  13162. warn(codeFrame ? `${message}\n${codeFrame}` : message);
  13163. }
  13164. }
  13165. }, options));
  13166. // The wildcard import results in a huge object with every export
  13167. // with keys that cannot be mangled, and can be quite heavy size-wise.
  13168. // In the global build we know `Vue` is available globally so we can avoid
  13169. // the wildcard object.
  13170. const render = ( new Function(code)()
  13171. );
  13172. render._rc = true;
  13173. return (compileCache[key] = render);
  13174. }
  13175. registerRuntimeCompiler(compileToFunction);
  13176. exports.BaseTransition = BaseTransition;
  13177. exports.Comment = Comment;
  13178. exports.Fragment = Fragment;
  13179. exports.KeepAlive = KeepAlive;
  13180. exports.Static = Static;
  13181. exports.Suspense = Suspense;
  13182. exports.Teleport = Teleport;
  13183. exports.Text = Text;
  13184. exports.Transition = Transition;
  13185. exports.TransitionGroup = TransitionGroup;
  13186. exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling;
  13187. exports.callWithErrorHandling = callWithErrorHandling;
  13188. exports.camelize = camelize;
  13189. exports.capitalize = capitalize;
  13190. exports.cloneVNode = cloneVNode;
  13191. exports.compile = compileToFunction;
  13192. exports.computed = computed$1;
  13193. exports.createApp = createApp;
  13194. exports.createBlock = createBlock;
  13195. exports.createCommentVNode = createCommentVNode;
  13196. exports.createHydrationRenderer = createHydrationRenderer;
  13197. exports.createRenderer = createRenderer;
  13198. exports.createSSRApp = createSSRApp;
  13199. exports.createSlots = createSlots;
  13200. exports.createStaticVNode = createStaticVNode;
  13201. exports.createTextVNode = createTextVNode;
  13202. exports.createVNode = createVNode;
  13203. exports.customRef = customRef;
  13204. exports.defineAsyncComponent = defineAsyncComponent;
  13205. exports.defineComponent = defineComponent;
  13206. exports.getCurrentInstance = getCurrentInstance;
  13207. exports.getTransitionRawChildren = getTransitionRawChildren;
  13208. exports.h = h;
  13209. exports.handleError = handleError;
  13210. exports.hydrate = hydrate;
  13211. exports.initCustomFormatter = initCustomFormatter;
  13212. exports.inject = inject;
  13213. exports.isProxy = isProxy;
  13214. exports.isReactive = isReactive;
  13215. exports.isReadonly = isReadonly;
  13216. exports.isRef = isRef;
  13217. exports.isVNode = isVNode;
  13218. exports.markRaw = markRaw;
  13219. exports.mergeProps = mergeProps;
  13220. exports.nextTick = nextTick;
  13221. exports.onActivated = onActivated;
  13222. exports.onBeforeMount = onBeforeMount;
  13223. exports.onBeforeUnmount = onBeforeUnmount;
  13224. exports.onBeforeUpdate = onBeforeUpdate;
  13225. exports.onDeactivated = onDeactivated;
  13226. exports.onErrorCaptured = onErrorCaptured;
  13227. exports.onMounted = onMounted;
  13228. exports.onRenderTracked = onRenderTracked;
  13229. exports.onRenderTriggered = onRenderTriggered;
  13230. exports.onUnmounted = onUnmounted;
  13231. exports.onUpdated = onUpdated;
  13232. exports.openBlock = openBlock;
  13233. exports.popScopeId = popScopeId;
  13234. exports.provide = provide;
  13235. exports.proxyRefs = proxyRefs;
  13236. exports.pushScopeId = pushScopeId;
  13237. exports.queuePostFlushCb = queuePostFlushCb;
  13238. exports.reactive = reactive;
  13239. exports.readonly = readonly;
  13240. exports.ref = ref;
  13241. exports.registerRuntimeCompiler = registerRuntimeCompiler;
  13242. exports.render = render;
  13243. exports.renderList = renderList;
  13244. exports.renderSlot = renderSlot;
  13245. exports.resolveComponent = resolveComponent;
  13246. exports.resolveDirective = resolveDirective;
  13247. exports.resolveDynamicComponent = resolveDynamicComponent;
  13248. exports.resolveTransitionHooks = resolveTransitionHooks;
  13249. exports.setBlockTracking = setBlockTracking;
  13250. exports.setDevtoolsHook = setDevtoolsHook;
  13251. exports.setTransitionHooks = setTransitionHooks;
  13252. exports.shallowReactive = shallowReactive;
  13253. exports.shallowReadonly = shallowReadonly;
  13254. exports.shallowRef = shallowRef;
  13255. exports.ssrContextKey = ssrContextKey;
  13256. exports.ssrUtils = ssrUtils;
  13257. exports.toDisplayString = toDisplayString;
  13258. exports.toHandlerKey = toHandlerKey;
  13259. exports.toHandlers = toHandlers;
  13260. exports.toRaw = toRaw;
  13261. exports.toRef = toRef;
  13262. exports.toRefs = toRefs;
  13263. exports.transformVNodeArgs = transformVNodeArgs;
  13264. exports.triggerRef = triggerRef;
  13265. exports.unref = unref;
  13266. exports.useCssModule = useCssModule;
  13267. exports.useCssVars = useCssVars;
  13268. exports.useSSRContext = useSSRContext;
  13269. exports.useTransitionState = useTransitionState;
  13270. exports.vModelCheckbox = vModelCheckbox;
  13271. exports.vModelDynamic = vModelDynamic;
  13272. exports.vModelRadio = vModelRadio;
  13273. exports.vModelSelect = vModelSelect;
  13274. exports.vModelText = vModelText;
  13275. exports.vShow = vShow;
  13276. exports.version = version;
  13277. exports.warn = warn;
  13278. exports.watch = watch;
  13279. exports.watchEffect = watchEffect;
  13280. exports.withCtx = withCtx;
  13281. exports.withDirectives = withDirectives;
  13282. exports.withKeys = withKeys;
  13283. exports.withModifiers = withModifiers;
  13284. exports.withScopeId = withScopeId;
  13285. return exports;
  13286. }({}));