UNPKG

546 kBJavaScriptView Raw
1var Vue = (function (exports) {
2 'use strict';
3
4 /**
5 * Make a map and return a function for checking if a key
6 * is in that map.
7 * IMPORTANT: all calls of this function must be prefixed with
8 * \/\*#\_\_PURE\_\_\*\/
9 * So that rollup can tree-shake them if necessary.
10 */
11 function makeMap(str, expectsLowerCase) {
12 const map = Object.create(null);
13 const list = str.split(',');
14 for (let i = 0; i < list.length; i++) {
15 map[list[i]] = true;
16 }
17 return expectsLowerCase ? val => !!map[val.toLowerCase()] : val => !!map[val];
18 }
19
20 /**
21 * dev only flag -> name mapping
22 */
23 const PatchFlagNames = {
24 [1 /* TEXT */]: `TEXT`,
25 [2 /* CLASS */]: `CLASS`,
26 [4 /* STYLE */]: `STYLE`,
27 [8 /* PROPS */]: `PROPS`,
28 [16 /* FULL_PROPS */]: `FULL_PROPS`,
29 [32 /* HYDRATE_EVENTS */]: `HYDRATE_EVENTS`,
30 [64 /* STABLE_FRAGMENT */]: `STABLE_FRAGMENT`,
31 [128 /* KEYED_FRAGMENT */]: `KEYED_FRAGMENT`,
32 [256 /* UNKEYED_FRAGMENT */]: `UNKEYED_FRAGMENT`,
33 [512 /* NEED_PATCH */]: `NEED_PATCH`,
34 [1024 /* DYNAMIC_SLOTS */]: `DYNAMIC_SLOTS`,
35 [2048 /* DEV_ROOT_FRAGMENT */]: `DEV_ROOT_FRAGMENT`,
36 [-1 /* HOISTED */]: `HOISTED`,
37 [-2 /* BAIL */]: `BAIL`
38 };
39
40 /**
41 * Dev only
42 */
43 const slotFlagsText = {
44 [1 /* STABLE */]: 'STABLE',
45 [2 /* DYNAMIC */]: 'DYNAMIC',
46 [3 /* FORWARDED */]: 'FORWARDED'
47 };
48
49 const GLOBALS_WHITE_LISTED = 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,' +
50 'decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,' +
51 'Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt';
52 const isGloballyWhitelisted = /*#__PURE__*/ makeMap(GLOBALS_WHITE_LISTED);
53
54 const range = 2;
55 function generateCodeFrame(source, start = 0, end = source.length) {
56 const lines = source.split(/\r?\n/);
57 let count = 0;
58 const res = [];
59 for (let i = 0; i < lines.length; i++) {
60 count += lines[i].length + 1;
61 if (count >= start) {
62 for (let j = i - range; j <= i + range || end > count; j++) {
63 if (j < 0 || j >= lines.length)
64 continue;
65 const line = j + 1;
66 res.push(`${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`);
67 const lineLength = lines[j].length;
68 if (j === i) {
69 // push underline
70 const pad = start - (count - lineLength) + 1;
71 const length = Math.max(1, end > count ? lineLength - pad : end - start);
72 res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
73 }
74 else if (j > i) {
75 if (end > count) {
76 const length = Math.max(Math.min(end - count, lineLength), 1);
77 res.push(` | ` + '^'.repeat(length));
78 }
79 count += lineLength + 1;
80 }
81 }
82 break;
83 }
84 }
85 return res.join('\n');
86 }
87
88 /**
89 * On the client we only need to offer special cases for boolean attributes that
90 * have different names from their corresponding dom properties:
91 * - itemscope -> N/A
92 * - allowfullscreen -> allowFullscreen
93 * - formnovalidate -> formNoValidate
94 * - ismap -> isMap
95 * - nomodule -> noModule
96 * - novalidate -> noValidate
97 * - readonly -> readOnly
98 */
99 const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`;
100 const isSpecialBooleanAttr = /*#__PURE__*/ makeMap(specialBooleanAttrs);
101
102 function normalizeStyle(value) {
103 if (isArray(value)) {
104 const res = {};
105 for (let i = 0; i < value.length; i++) {
106 const item = value[i];
107 const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item);
108 if (normalized) {
109 for (const key in normalized) {
110 res[key] = normalized[key];
111 }
112 }
113 }
114 return res;
115 }
116 else if (isObject(value)) {
117 return value;
118 }
119 }
120 const listDelimiterRE = /;(?![^(]*\))/g;
121 const propertyDelimiterRE = /:(.+)/;
122 function parseStringStyle(cssText) {
123 const ret = {};
124 cssText.split(listDelimiterRE).forEach(item => {
125 if (item) {
126 const tmp = item.split(propertyDelimiterRE);
127 tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim());
128 }
129 });
130 return ret;
131 }
132 function normalizeClass(value) {
133 let res = '';
134 if (isString(value)) {
135 res = value;
136 }
137 else if (isArray(value)) {
138 for (let i = 0; i < value.length; i++) {
139 const normalized = normalizeClass(value[i]);
140 if (normalized) {
141 res += normalized + ' ';
142 }
143 }
144 }
145 else if (isObject(value)) {
146 for (const name in value) {
147 if (value[name]) {
148 res += name + ' ';
149 }
150 }
151 }
152 return res.trim();
153 }
154
155 // These tag configs are shared between compiler-dom and runtime-dom, so they
156 // https://developer.mozilla.org/en-US/docs/Web/HTML/Element
157 const HTML_TAGS = 'html,body,base,head,link,meta,style,title,address,article,aside,footer,' +
158 'header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,' +
159 'figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,' +
160 'data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,' +
161 'time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,' +
162 'canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,' +
163 'th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,' +
164 'option,output,progress,select,textarea,details,dialog,menu,' +
165 'summary,template,blockquote,iframe,tfoot';
166 // https://developer.mozilla.org/en-US/docs/Web/SVG/Element
167 const SVG_TAGS = 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,' +
168 'defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,' +
169 'feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,' +
170 'feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,' +
171 'feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,' +
172 'fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,' +
173 'foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,' +
174 'mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,' +
175 'polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,' +
176 'text,textPath,title,tspan,unknown,use,view';
177 const VOID_TAGS = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr';
178 const isHTMLTag = /*#__PURE__*/ makeMap(HTML_TAGS);
179 const isSVGTag = /*#__PURE__*/ makeMap(SVG_TAGS);
180 const isVoidTag = /*#__PURE__*/ makeMap(VOID_TAGS);
181
182 function looseCompareArrays(a, b) {
183 if (a.length !== b.length)
184 return false;
185 let equal = true;
186 for (let i = 0; equal && i < a.length; i++) {
187 equal = looseEqual(a[i], b[i]);
188 }
189 return equal;
190 }
191 function looseEqual(a, b) {
192 if (a === b)
193 return true;
194 let aValidType = isDate(a);
195 let bValidType = isDate(b);
196 if (aValidType || bValidType) {
197 return aValidType && bValidType ? a.getTime() === b.getTime() : false;
198 }
199 aValidType = isArray(a);
200 bValidType = isArray(b);
201 if (aValidType || bValidType) {
202 return aValidType && bValidType ? looseCompareArrays(a, b) : false;
203 }
204 aValidType = isObject(a);
205 bValidType = isObject(b);
206 if (aValidType || bValidType) {
207 /* istanbul ignore if: this if will probably never be called */
208 if (!aValidType || !bValidType) {
209 return false;
210 }
211 const aKeysCount = Object.keys(a).length;
212 const bKeysCount = Object.keys(b).length;
213 if (aKeysCount !== bKeysCount) {
214 return false;
215 }
216 for (const key in a) {
217 const aHasKey = a.hasOwnProperty(key);
218 const bHasKey = b.hasOwnProperty(key);
219 if ((aHasKey && !bHasKey) ||
220 (!aHasKey && bHasKey) ||
221 !looseEqual(a[key], b[key])) {
222 return false;
223 }
224 }
225 }
226 return String(a) === String(b);
227 }
228 function looseIndexOf(arr, val) {
229 return arr.findIndex(item => looseEqual(item, val));
230 }
231
232 /**
233 * For converting {{ interpolation }} values to displayed strings.
234 * @private
235 */
236 const toDisplayString = (val) => {
237 return val == null
238 ? ''
239 : isObject(val)
240 ? JSON.stringify(val, replacer, 2)
241 : String(val);
242 };
243 const replacer = (_key, val) => {
244 if (isMap(val)) {
245 return {
246 [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val]) => {
247 entries[`${key} =>`] = val;
248 return entries;
249 }, {})
250 };
251 }
252 else if (isSet(val)) {
253 return {
254 [`Set(${val.size})`]: [...val.values()]
255 };
256 }
257 else if (isObject(val) && !isArray(val) && !isPlainObject(val)) {
258 return String(val);
259 }
260 return val;
261 };
262
263 const EMPTY_OBJ = Object.freeze({})
264 ;
265 const EMPTY_ARR = Object.freeze([]) ;
266 const NOOP = () => { };
267 /**
268 * Always return false.
269 */
270 const NO = () => false;
271 const onRE = /^on[^a-z]/;
272 const isOn = (key) => onRE.test(key);
273 const isModelListener = (key) => key.startsWith('onUpdate:');
274 const extend = Object.assign;
275 const remove = (arr, el) => {
276 const i = arr.indexOf(el);
277 if (i > -1) {
278 arr.splice(i, 1);
279 }
280 };
281 const hasOwnProperty = Object.prototype.hasOwnProperty;
282 const hasOwn = (val, key) => hasOwnProperty.call(val, key);
283 const isArray = Array.isArray;
284 const isMap = (val) => toTypeString(val) === '[object Map]';
285 const isSet = (val) => toTypeString(val) === '[object Set]';
286 const isDate = (val) => val instanceof Date;
287 const isFunction = (val) => typeof val === 'function';
288 const isString = (val) => typeof val === 'string';
289 const isSymbol = (val) => typeof val === 'symbol';
290 const isObject = (val) => val !== null && typeof val === 'object';
291 const isPromise = (val) => {
292 return isObject(val) && isFunction(val.then) && isFunction(val.catch);
293 };
294 const objectToString = Object.prototype.toString;
295 const toTypeString = (value) => objectToString.call(value);
296 const toRawType = (value) => {
297 // extract "RawType" from strings like "[object RawType]"
298 return toTypeString(value).slice(8, -1);
299 };
300 const isPlainObject = (val) => toTypeString(val) === '[object Object]';
301 const isIntegerKey = (key) => isString(key) &&
302 key !== 'NaN' &&
303 key[0] !== '-' &&
304 '' + parseInt(key, 10) === key;
305 const isReservedProp = /*#__PURE__*/ makeMap(
306 // the leading comma is intentional so empty string "" is also included
307 ',key,ref,' +
308 'onVnodeBeforeMount,onVnodeMounted,' +
309 'onVnodeBeforeUpdate,onVnodeUpdated,' +
310 'onVnodeBeforeUnmount,onVnodeUnmounted');
311 const cacheStringFunction = (fn) => {
312 const cache = Object.create(null);
313 return ((str) => {
314 const hit = cache[str];
315 return hit || (cache[str] = fn(str));
316 });
317 };
318 const camelizeRE = /-(\w)/g;
319 /**
320 * @private
321 */
322 const camelize = cacheStringFunction((str) => {
323 return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : ''));
324 });
325 const hyphenateRE = /\B([A-Z])/g;
326 /**
327 * @private
328 */
329 const hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, '-$1').toLowerCase());
330 /**
331 * @private
332 */
333 const capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1));
334 /**
335 * @private
336 */
337 const toHandlerKey = cacheStringFunction((str) => (str ? `on${capitalize(str)}` : ``));
338 // compare whether a value has changed, accounting for NaN.
339 const hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue);
340 const invokeArrayFns = (fns, arg) => {
341 for (let i = 0; i < fns.length; i++) {
342 fns[i](arg);
343 }
344 };
345 const def = (obj, key, value) => {
346 Object.defineProperty(obj, key, {
347 configurable: true,
348 enumerable: false,
349 value
350 });
351 };
352 const toNumber = (val) => {
353 const n = parseFloat(val);
354 return isNaN(n) ? val : n;
355 };
356 let _globalThis;
357 const getGlobalThis = () => {
358 return (_globalThis ||
359 (_globalThis =
360 typeof globalThis !== 'undefined'
361 ? globalThis
362 : typeof self !== 'undefined'
363 ? self
364 : typeof window !== 'undefined'
365 ? window
366 : typeof global !== 'undefined'
367 ? global
368 : {}));
369 };
370
371 const targetMap = new WeakMap();
372 const effectStack = [];
373 let activeEffect;
374 const ITERATE_KEY = Symbol('iterate' );
375 const MAP_KEY_ITERATE_KEY = Symbol('Map key iterate' );
376 function isEffect(fn) {
377 return fn && fn._isEffect === true;
378 }
379 function effect(fn, options = EMPTY_OBJ) {
380 if (isEffect(fn)) {
381 fn = fn.raw;
382 }
383 const effect = createReactiveEffect(fn, options);
384 if (!options.lazy) {
385 effect();
386 }
387 return effect;
388 }
389 function stop(effect) {
390 if (effect.active) {
391 cleanup(effect);
392 if (effect.options.onStop) {
393 effect.options.onStop();
394 }
395 effect.active = false;
396 }
397 }
398 let uid = 0;
399 function createReactiveEffect(fn, options) {
400 const effect = function reactiveEffect() {
401 if (!effect.active) {
402 return options.scheduler ? undefined : fn();
403 }
404 if (!effectStack.includes(effect)) {
405 cleanup(effect);
406 try {
407 enableTracking();
408 effectStack.push(effect);
409 activeEffect = effect;
410 return fn();
411 }
412 finally {
413 effectStack.pop();
414 resetTracking();
415 activeEffect = effectStack[effectStack.length - 1];
416 }
417 }
418 };
419 effect.id = uid++;
420 effect.allowRecurse = !!options.allowRecurse;
421 effect._isEffect = true;
422 effect.active = true;
423 effect.raw = fn;
424 effect.deps = [];
425 effect.options = options;
426 return effect;
427 }
428 function cleanup(effect) {
429 const { deps } = effect;
430 if (deps.length) {
431 for (let i = 0; i < deps.length; i++) {
432 deps[i].delete(effect);
433 }
434 deps.length = 0;
435 }
436 }
437 let shouldTrack = true;
438 const trackStack = [];
439 function pauseTracking() {
440 trackStack.push(shouldTrack);
441 shouldTrack = false;
442 }
443 function enableTracking() {
444 trackStack.push(shouldTrack);
445 shouldTrack = true;
446 }
447 function resetTracking() {
448 const last = trackStack.pop();
449 shouldTrack = last === undefined ? true : last;
450 }
451 function track(target, type, key) {
452 if (!shouldTrack || activeEffect === undefined) {
453 return;
454 }
455 let depsMap = targetMap.get(target);
456 if (!depsMap) {
457 targetMap.set(target, (depsMap = new Map()));
458 }
459 let dep = depsMap.get(key);
460 if (!dep) {
461 depsMap.set(key, (dep = new Set()));
462 }
463 if (!dep.has(activeEffect)) {
464 dep.add(activeEffect);
465 activeEffect.deps.push(dep);
466 if (activeEffect.options.onTrack) {
467 activeEffect.options.onTrack({
468 effect: activeEffect,
469 target,
470 type,
471 key
472 });
473 }
474 }
475 }
476 function trigger(target, type, key, newValue, oldValue, oldTarget) {
477 const depsMap = targetMap.get(target);
478 if (!depsMap) {
479 // never been tracked
480 return;
481 }
482 const effects = new Set();
483 const add = (effectsToAdd) => {
484 if (effectsToAdd) {
485 effectsToAdd.forEach(effect => {
486 if (effect !== activeEffect || effect.allowRecurse) {
487 effects.add(effect);
488 }
489 });
490 }
491 };
492 if (type === "clear" /* CLEAR */) {
493 // collection being cleared
494 // trigger all effects for target
495 depsMap.forEach(add);
496 }
497 else if (key === 'length' && isArray(target)) {
498 depsMap.forEach((dep, key) => {
499 if (key === 'length' || key >= newValue) {
500 add(dep);
501 }
502 });
503 }
504 else {
505 // schedule runs for SET | ADD | DELETE
506 if (key !== void 0) {
507 add(depsMap.get(key));
508 }
509 // also run for iteration key on ADD | DELETE | Map.SET
510 switch (type) {
511 case "add" /* ADD */:
512 if (!isArray(target)) {
513 add(depsMap.get(ITERATE_KEY));
514 if (isMap(target)) {
515 add(depsMap.get(MAP_KEY_ITERATE_KEY));
516 }
517 }
518 else if (isIntegerKey(key)) {
519 // new index added to array -> length changes
520 add(depsMap.get('length'));
521 }
522 break;
523 case "delete" /* DELETE */:
524 if (!isArray(target)) {
525 add(depsMap.get(ITERATE_KEY));
526 if (isMap(target)) {
527 add(depsMap.get(MAP_KEY_ITERATE_KEY));
528 }
529 }
530 break;
531 case "set" /* SET */:
532 if (isMap(target)) {
533 add(depsMap.get(ITERATE_KEY));
534 }
535 break;
536 }
537 }
538 const run = (effect) => {
539 if (effect.options.onTrigger) {
540 effect.options.onTrigger({
541 effect,
542 target,
543 key,
544 type,
545 newValue,
546 oldValue,
547 oldTarget
548 });
549 }
550 if (effect.options.scheduler) {
551 effect.options.scheduler(effect);
552 }
553 else {
554 effect();
555 }
556 };
557 effects.forEach(run);
558 }
559
560 const isNonTrackableKeys = /*#__PURE__*/ makeMap(`__proto__,__v_isRef,__isVue`);
561 const builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol)
562 .map(key => Symbol[key])
563 .filter(isSymbol));
564 const get = /*#__PURE__*/ createGetter();
565 const shallowGet = /*#__PURE__*/ createGetter(false, true);
566 const readonlyGet = /*#__PURE__*/ createGetter(true);
567 const shallowReadonlyGet = /*#__PURE__*/ createGetter(true, true);
568 const arrayInstrumentations = {};
569 ['includes', 'indexOf', 'lastIndexOf'].forEach(key => {
570 const method = Array.prototype[key];
571 arrayInstrumentations[key] = function (...args) {
572 const arr = toRaw(this);
573 for (let i = 0, l = this.length; i < l; i++) {
574 track(arr, "get" /* GET */, i + '');
575 }
576 // we run the method using the original args first (which may be reactive)
577 const res = method.apply(arr, args);
578 if (res === -1 || res === false) {
579 // if that didn't work, run it again using raw values.
580 return method.apply(arr, args.map(toRaw));
581 }
582 else {
583 return res;
584 }
585 };
586 });
587 ['push', 'pop', 'shift', 'unshift', 'splice'].forEach(key => {
588 const method = Array.prototype[key];
589 arrayInstrumentations[key] = function (...args) {
590 pauseTracking();
591 const res = method.apply(this, args);
592 resetTracking();
593 return res;
594 };
595 });
596 function createGetter(isReadonly = false, shallow = false) {
597 return function get(target, key, receiver) {
598 if (key === "__v_isReactive" /* IS_REACTIVE */) {
599 return !isReadonly;
600 }
601 else if (key === "__v_isReadonly" /* IS_READONLY */) {
602 return isReadonly;
603 }
604 else if (key === "__v_raw" /* RAW */ &&
605 receiver === (isReadonly ? readonlyMap : reactiveMap).get(target)) {
606 return target;
607 }
608 const targetIsArray = isArray(target);
609 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
610 return Reflect.get(arrayInstrumentations, key, receiver);
611 }
612 const res = Reflect.get(target, key, receiver);
613 if (isSymbol(key)
614 ? builtInSymbols.has(key)
615 : isNonTrackableKeys(key)) {
616 return res;
617 }
618 if (!isReadonly) {
619 track(target, "get" /* GET */, key);
620 }
621 if (shallow) {
622 return res;
623 }
624 if (isRef(res)) {
625 // ref unwrapping - does not apply for Array + integer key.
626 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
627 return shouldUnwrap ? res.value : res;
628 }
629 if (isObject(res)) {
630 // Convert returned value into a proxy as well. we do the isObject check
631 // here to avoid invalid value warning. Also need to lazy access readonly
632 // and reactive here to avoid circular dependency.
633 return isReadonly ? readonly(res) : reactive(res);
634 }
635 return res;
636 };
637 }
638 const set = /*#__PURE__*/ createSetter();
639 const shallowSet = /*#__PURE__*/ createSetter(true);
640 function createSetter(shallow = false) {
641 return function set(target, key, value, receiver) {
642 const oldValue = target[key];
643 if (!shallow) {
644 value = toRaw(value);
645 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
646 oldValue.value = value;
647 return true;
648 }
649 }
650 const hadKey = isArray(target) && isIntegerKey(key)
651 ? Number(key) < target.length
652 : hasOwn(target, key);
653 const result = Reflect.set(target, key, value, receiver);
654 // don't trigger if target is something up in the prototype chain of original
655 if (target === toRaw(receiver)) {
656 if (!hadKey) {
657 trigger(target, "add" /* ADD */, key, value);
658 }
659 else if (hasChanged(value, oldValue)) {
660 trigger(target, "set" /* SET */, key, value, oldValue);
661 }
662 }
663 return result;
664 };
665 }
666 function deleteProperty(target, key) {
667 const hadKey = hasOwn(target, key);
668 const oldValue = target[key];
669 const result = Reflect.deleteProperty(target, key);
670 if (result && hadKey) {
671 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
672 }
673 return result;
674 }
675 function has(target, key) {
676 const result = Reflect.has(target, key);
677 if (!isSymbol(key) || !builtInSymbols.has(key)) {
678 track(target, "has" /* HAS */, key);
679 }
680 return result;
681 }
682 function ownKeys(target) {
683 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
684 return Reflect.ownKeys(target);
685 }
686 const mutableHandlers = {
687 get,
688 set,
689 deleteProperty,
690 has,
691 ownKeys
692 };
693 const readonlyHandlers = {
694 get: readonlyGet,
695 set(target, key) {
696 {
697 console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
698 }
699 return true;
700 },
701 deleteProperty(target, key) {
702 {
703 console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
704 }
705 return true;
706 }
707 };
708 const shallowReactiveHandlers = extend({}, mutableHandlers, {
709 get: shallowGet,
710 set: shallowSet
711 });
712 // Props handlers are special in the sense that it should not unwrap top-level
713 // refs (in order to allow refs to be explicitly passed down), but should
714 // retain the reactivity of the normal readonly object.
715 const shallowReadonlyHandlers = extend({}, readonlyHandlers, {
716 get: shallowReadonlyGet
717 });
718
719 const toReactive = (value) => isObject(value) ? reactive(value) : value;
720 const toReadonly = (value) => isObject(value) ? readonly(value) : value;
721 const toShallow = (value) => value;
722 const getProto = (v) => Reflect.getPrototypeOf(v);
723 function get$1(target, key, isReadonly = false, isShallow = false) {
724 // #1772: readonly(reactive(Map)) should return readonly + reactive version
725 // of the value
726 target = target["__v_raw" /* RAW */];
727 const rawTarget = toRaw(target);
728 const rawKey = toRaw(key);
729 if (key !== rawKey) {
730 !isReadonly && track(rawTarget, "get" /* GET */, key);
731 }
732 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
733 const { has } = getProto(rawTarget);
734 const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
735 if (has.call(rawTarget, key)) {
736 return wrap(target.get(key));
737 }
738 else if (has.call(rawTarget, rawKey)) {
739 return wrap(target.get(rawKey));
740 }
741 }
742 function has$1(key, isReadonly = false) {
743 const target = this["__v_raw" /* RAW */];
744 const rawTarget = toRaw(target);
745 const rawKey = toRaw(key);
746 if (key !== rawKey) {
747 !isReadonly && track(rawTarget, "has" /* HAS */, key);
748 }
749 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
750 return key === rawKey
751 ? target.has(key)
752 : target.has(key) || target.has(rawKey);
753 }
754 function size(target, isReadonly = false) {
755 target = target["__v_raw" /* RAW */];
756 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
757 return Reflect.get(target, 'size', target);
758 }
759 function add(value) {
760 value = toRaw(value);
761 const target = toRaw(this);
762 const proto = getProto(target);
763 const hadKey = proto.has.call(target, value);
764 if (!hadKey) {
765 target.add(value);
766 trigger(target, "add" /* ADD */, value, value);
767 }
768 return this;
769 }
770 function set$1(key, value) {
771 value = toRaw(value);
772 const target = toRaw(this);
773 const { has, get } = getProto(target);
774 let hadKey = has.call(target, key);
775 if (!hadKey) {
776 key = toRaw(key);
777 hadKey = has.call(target, key);
778 }
779 else {
780 checkIdentityKeys(target, has, key);
781 }
782 const oldValue = get.call(target, key);
783 target.set(key, value);
784 if (!hadKey) {
785 trigger(target, "add" /* ADD */, key, value);
786 }
787 else if (hasChanged(value, oldValue)) {
788 trigger(target, "set" /* SET */, key, value, oldValue);
789 }
790 return this;
791 }
792 function deleteEntry(key) {
793 const target = toRaw(this);
794 const { has, get } = getProto(target);
795 let hadKey = has.call(target, key);
796 if (!hadKey) {
797 key = toRaw(key);
798 hadKey = has.call(target, key);
799 }
800 else {
801 checkIdentityKeys(target, has, key);
802 }
803 const oldValue = get ? get.call(target, key) : undefined;
804 // forward the operation before queueing reactions
805 const result = target.delete(key);
806 if (hadKey) {
807 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
808 }
809 return result;
810 }
811 function clear() {
812 const target = toRaw(this);
813 const hadItems = target.size !== 0;
814 const oldTarget = isMap(target)
815 ? new Map(target)
816 : new Set(target)
817 ;
818 // forward the operation before queueing reactions
819 const result = target.clear();
820 if (hadItems) {
821 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
822 }
823 return result;
824 }
825 function createForEach(isReadonly, isShallow) {
826 return function forEach(callback, thisArg) {
827 const observed = this;
828 const target = observed["__v_raw" /* RAW */];
829 const rawTarget = toRaw(target);
830 const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
831 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
832 return target.forEach((value, key) => {
833 // important: make sure the callback is
834 // 1. invoked with the reactive map as `this` and 3rd arg
835 // 2. the value received should be a corresponding reactive/readonly.
836 return callback.call(thisArg, wrap(value), wrap(key), observed);
837 });
838 };
839 }
840 function createIterableMethod(method, isReadonly, isShallow) {
841 return function (...args) {
842 const target = this["__v_raw" /* RAW */];
843 const rawTarget = toRaw(target);
844 const targetIsMap = isMap(rawTarget);
845 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
846 const isKeyOnly = method === 'keys' && targetIsMap;
847 const innerIterator = target[method](...args);
848 const wrap = isReadonly ? toReadonly : isShallow ? toShallow : toReactive;
849 !isReadonly &&
850 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
851 // return a wrapped iterator which returns observed versions of the
852 // values emitted from the real iterator
853 return {
854 // iterator protocol
855 next() {
856 const { value, done } = innerIterator.next();
857 return done
858 ? { value, done }
859 : {
860 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
861 done
862 };
863 },
864 // iterable protocol
865 [Symbol.iterator]() {
866 return this;
867 }
868 };
869 };
870 }
871 function createReadonlyMethod(type) {
872 return function (...args) {
873 {
874 const key = args[0] ? `on key "${args[0]}" ` : ``;
875 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
876 }
877 return type === "delete" /* DELETE */ ? false : this;
878 };
879 }
880 const mutableInstrumentations = {
881 get(key) {
882 return get$1(this, key);
883 },
884 get size() {
885 return size(this);
886 },
887 has: has$1,
888 add,
889 set: set$1,
890 delete: deleteEntry,
891 clear,
892 forEach: createForEach(false, false)
893 };
894 const shallowInstrumentations = {
895 get(key) {
896 return get$1(this, key, false, true);
897 },
898 get size() {
899 return size(this);
900 },
901 has: has$1,
902 add,
903 set: set$1,
904 delete: deleteEntry,
905 clear,
906 forEach: createForEach(false, true)
907 };
908 const readonlyInstrumentations = {
909 get(key) {
910 return get$1(this, key, true);
911 },
912 get size() {
913 return size(this, true);
914 },
915 has(key) {
916 return has$1.call(this, key, true);
917 },
918 add: createReadonlyMethod("add" /* ADD */),
919 set: createReadonlyMethod("set" /* SET */),
920 delete: createReadonlyMethod("delete" /* DELETE */),
921 clear: createReadonlyMethod("clear" /* CLEAR */),
922 forEach: createForEach(true, false)
923 };
924 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
925 iteratorMethods.forEach(method => {
926 mutableInstrumentations[method] = createIterableMethod(method, false, false);
927 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
928 shallowInstrumentations[method] = createIterableMethod(method, false, true);
929 });
930 function createInstrumentationGetter(isReadonly, shallow) {
931 const instrumentations = shallow
932 ? shallowInstrumentations
933 : isReadonly
934 ? readonlyInstrumentations
935 : mutableInstrumentations;
936 return (target, key, receiver) => {
937 if (key === "__v_isReactive" /* IS_REACTIVE */) {
938 return !isReadonly;
939 }
940 else if (key === "__v_isReadonly" /* IS_READONLY */) {
941 return isReadonly;
942 }
943 else if (key === "__v_raw" /* RAW */) {
944 return target;
945 }
946 return Reflect.get(hasOwn(instrumentations, key) && key in target
947 ? instrumentations
948 : target, key, receiver);
949 };
950 }
951 const mutableCollectionHandlers = {
952 get: createInstrumentationGetter(false, false)
953 };
954 const shallowCollectionHandlers = {
955 get: createInstrumentationGetter(false, true)
956 };
957 const readonlyCollectionHandlers = {
958 get: createInstrumentationGetter(true, false)
959 };
960 function checkIdentityKeys(target, has, key) {
961 const rawKey = toRaw(key);
962 if (rawKey !== key && has.call(target, rawKey)) {
963 const type = toRawType(target);
964 console.warn(`Reactive ${type} contains both the raw and reactive ` +
965 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
966 `which can lead to inconsistencies. ` +
967 `Avoid differentiating between the raw and reactive versions ` +
968 `of an object and only use the reactive version if possible.`);
969 }
970 }
971
972 const reactiveMap = new WeakMap();
973 const readonlyMap = new WeakMap();
974 function targetTypeMap(rawType) {
975 switch (rawType) {
976 case 'Object':
977 case 'Array':
978 return 1 /* COMMON */;
979 case 'Map':
980 case 'Set':
981 case 'WeakMap':
982 case 'WeakSet':
983 return 2 /* COLLECTION */;
984 default:
985 return 0 /* INVALID */;
986 }
987 }
988 function getTargetType(value) {
989 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
990 ? 0 /* INVALID */
991 : targetTypeMap(toRawType(value));
992 }
993 function reactive(target) {
994 // if trying to observe a readonly proxy, return the readonly version.
995 if (target && target["__v_isReadonly" /* IS_READONLY */]) {
996 return target;
997 }
998 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers);
999 }
1000 /**
1001 * Return a shallowly-reactive copy of the original object, where only the root
1002 * level properties are reactive. It also does not auto-unwrap refs (even at the
1003 * root level).
1004 */
1005 function shallowReactive(target) {
1006 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers);
1007 }
1008 /**
1009 * Creates a readonly copy of the original object. Note the returned copy is not
1010 * made reactive, but `readonly` can be called on an already reactive object.
1011 */
1012 function readonly(target) {
1013 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers);
1014 }
1015 /**
1016 * Returns a reactive-copy of the original object, where only the root level
1017 * properties are readonly, and does NOT unwrap refs nor recursively convert
1018 * returned properties.
1019 * This is used for creating the props proxy object for stateful components.
1020 */
1021 function shallowReadonly(target) {
1022 return createReactiveObject(target, true, shallowReadonlyHandlers, readonlyCollectionHandlers);
1023 }
1024 function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers) {
1025 if (!isObject(target)) {
1026 {
1027 console.warn(`value cannot be made reactive: ${String(target)}`);
1028 }
1029 return target;
1030 }
1031 // target is already a Proxy, return it.
1032 // exception: calling readonly() on a reactive object
1033 if (target["__v_raw" /* RAW */] &&
1034 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1035 return target;
1036 }
1037 // target already has corresponding Proxy
1038 const proxyMap = isReadonly ? readonlyMap : reactiveMap;
1039 const existingProxy = proxyMap.get(target);
1040 if (existingProxy) {
1041 return existingProxy;
1042 }
1043 // only a whitelist of value types can be observed.
1044 const targetType = getTargetType(target);
1045 if (targetType === 0 /* INVALID */) {
1046 return target;
1047 }
1048 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1049 proxyMap.set(target, proxy);
1050 return proxy;
1051 }
1052 function isReactive(value) {
1053 if (isReadonly(value)) {
1054 return isReactive(value["__v_raw" /* RAW */]);
1055 }
1056 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1057 }
1058 function isReadonly(value) {
1059 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1060 }
1061 function isProxy(value) {
1062 return isReactive(value) || isReadonly(value);
1063 }
1064 function toRaw(observed) {
1065 return ((observed && toRaw(observed["__v_raw" /* RAW */])) || observed);
1066 }
1067 function markRaw(value) {
1068 def(value, "__v_skip" /* SKIP */, true);
1069 return value;
1070 }
1071
1072 const convert = (val) => isObject(val) ? reactive(val) : val;
1073 function isRef(r) {
1074 return Boolean(r && r.__v_isRef === true);
1075 }
1076 function ref(value) {
1077 return createRef(value);
1078 }
1079 function shallowRef(value) {
1080 return createRef(value, true);
1081 }
1082 class RefImpl {
1083 constructor(_rawValue, _shallow = false) {
1084 this._rawValue = _rawValue;
1085 this._shallow = _shallow;
1086 this.__v_isRef = true;
1087 this._value = _shallow ? _rawValue : convert(_rawValue);
1088 }
1089 get value() {
1090 track(toRaw(this), "get" /* GET */, 'value');
1091 return this._value;
1092 }
1093 set value(newVal) {
1094 if (hasChanged(toRaw(newVal), this._rawValue)) {
1095 this._rawValue = newVal;
1096 this._value = this._shallow ? newVal : convert(newVal);
1097 trigger(toRaw(this), "set" /* SET */, 'value', newVal);
1098 }
1099 }
1100 }
1101 function createRef(rawValue, shallow = false) {
1102 if (isRef(rawValue)) {
1103 return rawValue;
1104 }
1105 return new RefImpl(rawValue, shallow);
1106 }
1107 function triggerRef(ref) {
1108 trigger(toRaw(ref), "set" /* SET */, 'value', ref.value );
1109 }
1110 function unref(ref) {
1111 return isRef(ref) ? ref.value : ref;
1112 }
1113 const shallowUnwrapHandlers = {
1114 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1115 set: (target, key, value, receiver) => {
1116 const oldValue = target[key];
1117 if (isRef(oldValue) && !isRef(value)) {
1118 oldValue.value = value;
1119 return true;
1120 }
1121 else {
1122 return Reflect.set(target, key, value, receiver);
1123 }
1124 }
1125 };
1126 function proxyRefs(objectWithRefs) {
1127 return isReactive(objectWithRefs)
1128 ? objectWithRefs
1129 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1130 }
1131 class CustomRefImpl {
1132 constructor(factory) {
1133 this.__v_isRef = true;
1134 const { get, set } = factory(() => track(this, "get" /* GET */, 'value'), () => trigger(this, "set" /* SET */, 'value'));
1135 this._get = get;
1136 this._set = set;
1137 }
1138 get value() {
1139 return this._get();
1140 }
1141 set value(newVal) {
1142 this._set(newVal);
1143 }
1144 }
1145 function customRef(factory) {
1146 return new CustomRefImpl(factory);
1147 }
1148 function toRefs(object) {
1149 if (!isProxy(object)) {
1150 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1151 }
1152 const ret = isArray(object) ? new Array(object.length) : {};
1153 for (const key in object) {
1154 ret[key] = toRef(object, key);
1155 }
1156 return ret;
1157 }
1158 class ObjectRefImpl {
1159 constructor(_object, _key) {
1160 this._object = _object;
1161 this._key = _key;
1162 this.__v_isRef = true;
1163 }
1164 get value() {
1165 return this._object[this._key];
1166 }
1167 set value(newVal) {
1168 this._object[this._key] = newVal;
1169 }
1170 }
1171 function toRef(object, key) {
1172 return isRef(object[key])
1173 ? object[key]
1174 : new ObjectRefImpl(object, key);
1175 }
1176
1177 class ComputedRefImpl {
1178 constructor(getter, _setter, isReadonly) {
1179 this._setter = _setter;
1180 this._dirty = true;
1181 this.__v_isRef = true;
1182 this.effect = effect(getter, {
1183 lazy: true,
1184 scheduler: () => {
1185 if (!this._dirty) {
1186 this._dirty = true;
1187 trigger(toRaw(this), "set" /* SET */, 'value');
1188 }
1189 }
1190 });
1191 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1192 }
1193 get value() {
1194 if (this._dirty) {
1195 this._value = this.effect();
1196 this._dirty = false;
1197 }
1198 track(toRaw(this), "get" /* GET */, 'value');
1199 return this._value;
1200 }
1201 set value(newValue) {
1202 this._setter(newValue);
1203 }
1204 }
1205 function computed(getterOrOptions) {
1206 let getter;
1207 let setter;
1208 if (isFunction(getterOrOptions)) {
1209 getter = getterOrOptions;
1210 setter = () => {
1211 console.warn('Write operation failed: computed value is readonly');
1212 }
1213 ;
1214 }
1215 else {
1216 getter = getterOrOptions.get;
1217 setter = getterOrOptions.set;
1218 }
1219 return new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set);
1220 }
1221
1222 const stack = [];
1223 function pushWarningContext(vnode) {
1224 stack.push(vnode);
1225 }
1226 function popWarningContext() {
1227 stack.pop();
1228 }
1229 function warn(msg, ...args) {
1230 // avoid props formatting or warn handler tracking deps that might be mutated
1231 // during patch, leading to infinite recursion.
1232 pauseTracking();
1233 const instance = stack.length ? stack[stack.length - 1].component : null;
1234 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1235 const trace = getComponentTrace();
1236 if (appWarnHandler) {
1237 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
1238 msg + args.join(''),
1239 instance && instance.proxy,
1240 trace
1241 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1242 .join('\n'),
1243 trace
1244 ]);
1245 }
1246 else {
1247 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1248 /* istanbul ignore if */
1249 if (trace.length &&
1250 // avoid spamming console during tests
1251 !false) {
1252 warnArgs.push(`\n`, ...formatTrace(trace));
1253 }
1254 console.warn(...warnArgs);
1255 }
1256 resetTracking();
1257 }
1258 function getComponentTrace() {
1259 let currentVNode = stack[stack.length - 1];
1260 if (!currentVNode) {
1261 return [];
1262 }
1263 // we can't just use the stack because it will be incomplete during updates
1264 // that did not start from the root. Re-construct the parent chain using
1265 // instance parent pointers.
1266 const normalizedStack = [];
1267 while (currentVNode) {
1268 const last = normalizedStack[0];
1269 if (last && last.vnode === currentVNode) {
1270 last.recurseCount++;
1271 }
1272 else {
1273 normalizedStack.push({
1274 vnode: currentVNode,
1275 recurseCount: 0
1276 });
1277 }
1278 const parentInstance = currentVNode.component && currentVNode.component.parent;
1279 currentVNode = parentInstance && parentInstance.vnode;
1280 }
1281 return normalizedStack;
1282 }
1283 /* istanbul ignore next */
1284 function formatTrace(trace) {
1285 const logs = [];
1286 trace.forEach((entry, i) => {
1287 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1288 });
1289 return logs;
1290 }
1291 function formatTraceEntry({ vnode, recurseCount }) {
1292 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1293 const isRoot = vnode.component ? vnode.component.parent == null : false;
1294 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1295 const close = `>` + postfix;
1296 return vnode.props
1297 ? [open, ...formatProps(vnode.props), close]
1298 : [open + close];
1299 }
1300 /* istanbul ignore next */
1301 function formatProps(props) {
1302 const res = [];
1303 const keys = Object.keys(props);
1304 keys.slice(0, 3).forEach(key => {
1305 res.push(...formatProp(key, props[key]));
1306 });
1307 if (keys.length > 3) {
1308 res.push(` ...`);
1309 }
1310 return res;
1311 }
1312 /* istanbul ignore next */
1313 function formatProp(key, value, raw) {
1314 if (isString(value)) {
1315 value = JSON.stringify(value);
1316 return raw ? value : [`${key}=${value}`];
1317 }
1318 else if (typeof value === 'number' ||
1319 typeof value === 'boolean' ||
1320 value == null) {
1321 return raw ? value : [`${key}=${value}`];
1322 }
1323 else if (isRef(value)) {
1324 value = formatProp(key, toRaw(value.value), true);
1325 return raw ? value : [`${key}=Ref<`, value, `>`];
1326 }
1327 else if (isFunction(value)) {
1328 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1329 }
1330 else {
1331 value = toRaw(value);
1332 return raw ? value : [`${key}=`, value];
1333 }
1334 }
1335
1336 const ErrorTypeStrings = {
1337 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
1338 ["c" /* CREATED */]: 'created hook',
1339 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
1340 ["m" /* MOUNTED */]: 'mounted hook',
1341 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
1342 ["u" /* UPDATED */]: 'updated',
1343 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1344 ["um" /* UNMOUNTED */]: 'unmounted hook',
1345 ["a" /* ACTIVATED */]: 'activated hook',
1346 ["da" /* DEACTIVATED */]: 'deactivated hook',
1347 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
1348 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
1349 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
1350 [0 /* SETUP_FUNCTION */]: 'setup function',
1351 [1 /* RENDER_FUNCTION */]: 'render function',
1352 [2 /* WATCH_GETTER */]: 'watcher getter',
1353 [3 /* WATCH_CALLBACK */]: 'watcher callback',
1354 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
1355 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
1356 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
1357 [7 /* VNODE_HOOK */]: 'vnode hook',
1358 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
1359 [9 /* TRANSITION_HOOK */]: 'transition hook',
1360 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
1361 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
1362 [12 /* FUNCTION_REF */]: 'ref function',
1363 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
1364 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1365 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
1366 };
1367 function callWithErrorHandling(fn, instance, type, args) {
1368 let res;
1369 try {
1370 res = args ? fn(...args) : fn();
1371 }
1372 catch (err) {
1373 handleError(err, instance, type);
1374 }
1375 return res;
1376 }
1377 function callWithAsyncErrorHandling(fn, instance, type, args) {
1378 if (isFunction(fn)) {
1379 const res = callWithErrorHandling(fn, instance, type, args);
1380 if (res && isPromise(res)) {
1381 res.catch(err => {
1382 handleError(err, instance, type);
1383 });
1384 }
1385 return res;
1386 }
1387 const values = [];
1388 for (let i = 0; i < fn.length; i++) {
1389 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1390 }
1391 return values;
1392 }
1393 function handleError(err, instance, type, throwInDev = true) {
1394 const contextVNode = instance ? instance.vnode : null;
1395 if (instance) {
1396 let cur = instance.parent;
1397 // the exposed instance is the render proxy to keep it consistent with 2.x
1398 const exposedInstance = instance.proxy;
1399 // in production the hook receives only the error code
1400 const errorInfo = ErrorTypeStrings[type] ;
1401 while (cur) {
1402 const errorCapturedHooks = cur.ec;
1403 if (errorCapturedHooks) {
1404 for (let i = 0; i < errorCapturedHooks.length; i++) {
1405 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1406 return;
1407 }
1408 }
1409 }
1410 cur = cur.parent;
1411 }
1412 // app-level handling
1413 const appErrorHandler = instance.appContext.config.errorHandler;
1414 if (appErrorHandler) {
1415 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1416 return;
1417 }
1418 }
1419 logError(err, type, contextVNode, throwInDev);
1420 }
1421 function logError(err, type, contextVNode, throwInDev = true) {
1422 {
1423 const info = ErrorTypeStrings[type];
1424 if (contextVNode) {
1425 pushWarningContext(contextVNode);
1426 }
1427 warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1428 if (contextVNode) {
1429 popWarningContext();
1430 }
1431 // crash in dev by default so it's more noticeable
1432 if (throwInDev) {
1433 throw err;
1434 }
1435 else {
1436 console.error(err);
1437 }
1438 }
1439 }
1440
1441 let isFlushing = false;
1442 let isFlushPending = false;
1443 const queue = [];
1444 let flushIndex = 0;
1445 const pendingPreFlushCbs = [];
1446 let activePreFlushCbs = null;
1447 let preFlushIndex = 0;
1448 const pendingPostFlushCbs = [];
1449 let activePostFlushCbs = null;
1450 let postFlushIndex = 0;
1451 const resolvedPromise = Promise.resolve();
1452 let currentFlushPromise = null;
1453 let currentPreFlushParentJob = null;
1454 const RECURSION_LIMIT = 100;
1455 function nextTick(fn) {
1456 const p = currentFlushPromise || resolvedPromise;
1457 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1458 }
1459 // #2768
1460 // Use binary-search to find a suitable position in the queue,
1461 // so that the queue maintains the increasing order of job's id,
1462 // which can prevent the job from being skipped and also can avoid repeated patching.
1463 function findInsertionIndex(job) {
1464 // the start index should be `flushIndex + 1`
1465 let start = flushIndex + 1;
1466 let end = queue.length;
1467 const jobId = getId(job);
1468 while (start < end) {
1469 const middle = (start + end) >>> 1;
1470 const middleJobId = getId(queue[middle]);
1471 middleJobId < jobId ? (start = middle + 1) : (end = middle);
1472 }
1473 return start;
1474 }
1475 function queueJob(job) {
1476 // the dedupe search uses the startIndex argument of Array.includes()
1477 // by default the search index includes the current job that is being run
1478 // so it cannot recursively trigger itself again.
1479 // if the job is a watch() callback, the search will start with a +1 index to
1480 // allow it recursively trigger itself - it is the user's responsibility to
1481 // ensure it doesn't end up in an infinite loop.
1482 if ((!queue.length ||
1483 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
1484 job !== currentPreFlushParentJob) {
1485 const pos = findInsertionIndex(job);
1486 if (pos > -1) {
1487 queue.splice(pos, 0, job);
1488 }
1489 else {
1490 queue.push(job);
1491 }
1492 queueFlush();
1493 }
1494 }
1495 function queueFlush() {
1496 if (!isFlushing && !isFlushPending) {
1497 isFlushPending = true;
1498 currentFlushPromise = resolvedPromise.then(flushJobs);
1499 }
1500 }
1501 function invalidateJob(job) {
1502 const i = queue.indexOf(job);
1503 if (i > -1) {
1504 queue.splice(i, 1);
1505 }
1506 }
1507 function queueCb(cb, activeQueue, pendingQueue, index) {
1508 if (!isArray(cb)) {
1509 if (!activeQueue ||
1510 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
1511 pendingQueue.push(cb);
1512 }
1513 }
1514 else {
1515 // if cb is an array, it is a component lifecycle hook which can only be
1516 // triggered by a job, which is already deduped in the main queue, so
1517 // we can skip duplicate check here to improve perf
1518 pendingQueue.push(...cb);
1519 }
1520 queueFlush();
1521 }
1522 function queuePreFlushCb(cb) {
1523 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
1524 }
1525 function queuePostFlushCb(cb) {
1526 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
1527 }
1528 function flushPreFlushCbs(seen, parentJob = null) {
1529 if (pendingPreFlushCbs.length) {
1530 currentPreFlushParentJob = parentJob;
1531 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
1532 pendingPreFlushCbs.length = 0;
1533 {
1534 seen = seen || new Map();
1535 }
1536 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
1537 {
1538 checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex]);
1539 }
1540 activePreFlushCbs[preFlushIndex]();
1541 }
1542 activePreFlushCbs = null;
1543 preFlushIndex = 0;
1544 currentPreFlushParentJob = null;
1545 // recursively flush until it drains
1546 flushPreFlushCbs(seen, parentJob);
1547 }
1548 }
1549 function flushPostFlushCbs(seen) {
1550 if (pendingPostFlushCbs.length) {
1551 const deduped = [...new Set(pendingPostFlushCbs)];
1552 pendingPostFlushCbs.length = 0;
1553 // #1947 already has active queue, nested flushPostFlushCbs call
1554 if (activePostFlushCbs) {
1555 activePostFlushCbs.push(...deduped);
1556 return;
1557 }
1558 activePostFlushCbs = deduped;
1559 {
1560 seen = seen || new Map();
1561 }
1562 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1563 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1564 {
1565 checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex]);
1566 }
1567 activePostFlushCbs[postFlushIndex]();
1568 }
1569 activePostFlushCbs = null;
1570 postFlushIndex = 0;
1571 }
1572 }
1573 const getId = (job) => job.id == null ? Infinity : job.id;
1574 function flushJobs(seen) {
1575 isFlushPending = false;
1576 isFlushing = true;
1577 {
1578 seen = seen || new Map();
1579 }
1580 flushPreFlushCbs(seen);
1581 // Sort queue before flush.
1582 // This ensures that:
1583 // 1. Components are updated from parent to child. (because parent is always
1584 // created before the child so its render effect will have smaller
1585 // priority number)
1586 // 2. If a component is unmounted during a parent component's update,
1587 // its update can be skipped.
1588 queue.sort((a, b) => getId(a) - getId(b));
1589 try {
1590 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1591 const job = queue[flushIndex];
1592 if (job) {
1593 if (true) {
1594 checkRecursiveUpdates(seen, job);
1595 }
1596 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
1597 }
1598 }
1599 }
1600 finally {
1601 flushIndex = 0;
1602 queue.length = 0;
1603 flushPostFlushCbs(seen);
1604 isFlushing = false;
1605 currentFlushPromise = null;
1606 // some postFlushCb queued jobs!
1607 // keep flushing until it drains.
1608 if (queue.length || pendingPostFlushCbs.length) {
1609 flushJobs(seen);
1610 }
1611 }
1612 }
1613 function checkRecursiveUpdates(seen, fn) {
1614 if (!seen.has(fn)) {
1615 seen.set(fn, 1);
1616 }
1617 else {
1618 const count = seen.get(fn);
1619 if (count > RECURSION_LIMIT) {
1620 throw new Error(`Maximum recursive updates exceeded. ` +
1621 `This means you have a reactive effect that is mutating its own ` +
1622 `dependencies and thus recursively triggering itself. Possible sources ` +
1623 `include component template, render function, updated hook or ` +
1624 `watcher source function.`);
1625 }
1626 else {
1627 seen.set(fn, count + 1);
1628 }
1629 }
1630 }
1631
1632 /* eslint-disable no-restricted-globals */
1633 let isHmrUpdating = false;
1634 const hmrDirtyComponents = new Set();
1635 // Expose the HMR runtime on the global object
1636 // This makes it entirely tree-shakable without polluting the exports and makes
1637 // it easier to be used in toolings like vue-loader
1638 // Note: for a component to be eligible for HMR it also needs the __hmrId option
1639 // to be set so that its instances can be registered / removed.
1640 {
1641 const globalObject = typeof global !== 'undefined'
1642 ? global
1643 : typeof self !== 'undefined'
1644 ? self
1645 : typeof window !== 'undefined'
1646 ? window
1647 : {};
1648 globalObject.__VUE_HMR_RUNTIME__ = {
1649 createRecord: tryWrap(createRecord),
1650 rerender: tryWrap(rerender),
1651 reload: tryWrap(reload)
1652 };
1653 }
1654 const map = new Map();
1655 function registerHMR(instance) {
1656 const id = instance.type.__hmrId;
1657 let record = map.get(id);
1658 if (!record) {
1659 createRecord(id, instance.type);
1660 record = map.get(id);
1661 }
1662 record.instances.add(instance);
1663 }
1664 function unregisterHMR(instance) {
1665 map.get(instance.type.__hmrId).instances.delete(instance);
1666 }
1667 function createRecord(id, component) {
1668 if (!component) {
1669 warn(`HMR API usage is out of date.\n` +
1670 `Please upgrade vue-loader/vite/rollup-plugin-vue or other relevant ` +
1671 `dependency that handles Vue SFC compilation.`);
1672 component = {};
1673 }
1674 if (map.has(id)) {
1675 return false;
1676 }
1677 map.set(id, {
1678 component: isClassComponent(component) ? component.__vccOpts : component,
1679 instances: new Set()
1680 });
1681 return true;
1682 }
1683 function rerender(id, newRender) {
1684 const record = map.get(id);
1685 if (!record)
1686 return;
1687 if (newRender)
1688 record.component.render = newRender;
1689 // Array.from creates a snapshot which avoids the set being mutated during
1690 // updates
1691 Array.from(record.instances).forEach(instance => {
1692 if (newRender) {
1693 instance.render = newRender;
1694 }
1695 instance.renderCache = [];
1696 // this flag forces child components with slot content to update
1697 isHmrUpdating = true;
1698 instance.update();
1699 isHmrUpdating = false;
1700 });
1701 }
1702 function reload(id, newComp) {
1703 const record = map.get(id);
1704 if (!record)
1705 return;
1706 // Array.from creates a snapshot which avoids the set being mutated during
1707 // updates
1708 const { component, instances } = record;
1709 if (!hmrDirtyComponents.has(component)) {
1710 // 1. Update existing comp definition to match new one
1711 newComp = isClassComponent(newComp) ? newComp.__vccOpts : newComp;
1712 extend(component, newComp);
1713 for (const key in component) {
1714 if (!(key in newComp)) {
1715 delete component[key];
1716 }
1717 }
1718 // 2. Mark component dirty. This forces the renderer to replace the component
1719 // on patch.
1720 hmrDirtyComponents.add(component);
1721 // 3. Make sure to unmark the component after the reload.
1722 queuePostFlushCb(() => {
1723 hmrDirtyComponents.delete(component);
1724 });
1725 }
1726 Array.from(instances).forEach(instance => {
1727 if (instance.parent) {
1728 // 4. Force the parent instance to re-render. This will cause all updated
1729 // components to be unmounted and re-mounted. Queue the update so that we
1730 // don't end up forcing the same parent to re-render multiple times.
1731 queueJob(instance.parent.update);
1732 }
1733 else if (instance.appContext.reload) {
1734 // root instance mounted via createApp() has a reload method
1735 instance.appContext.reload();
1736 }
1737 else if (typeof window !== 'undefined') {
1738 // root instance inside tree created via raw render(). Force reload.
1739 window.location.reload();
1740 }
1741 else {
1742 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
1743 }
1744 });
1745 }
1746 function tryWrap(fn) {
1747 return (id, arg) => {
1748 try {
1749 return fn(id, arg);
1750 }
1751 catch (e) {
1752 console.error(e);
1753 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
1754 `Full reload required.`);
1755 }
1756 };
1757 }
1758
1759 function setDevtoolsHook(hook) {
1760 exports.devtools = hook;
1761 }
1762 function devtoolsInitApp(app, version) {
1763 // TODO queue if devtools is undefined
1764 if (!exports.devtools)
1765 return;
1766 exports.devtools.emit("app:init" /* APP_INIT */, app, version, {
1767 Fragment,
1768 Text,
1769 Comment,
1770 Static
1771 });
1772 }
1773 function devtoolsUnmountApp(app) {
1774 if (!exports.devtools)
1775 return;
1776 exports.devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
1777 }
1778 const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
1779 const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
1780 const devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
1781 function createDevtoolsComponentHook(hook) {
1782 return (component) => {
1783 if (!exports.devtools)
1784 return;
1785 exports.devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
1786 };
1787 }
1788 function devtoolsComponentEmit(component, event, params) {
1789 if (!exports.devtools)
1790 return;
1791 exports.devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
1792 }
1793
1794 function emit(instance, event, ...rawArgs) {
1795 const props = instance.vnode.props || EMPTY_OBJ;
1796 {
1797 const { emitsOptions, propsOptions: [propsOptions] } = instance;
1798 if (emitsOptions) {
1799 if (!(event in emitsOptions)) {
1800 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
1801 warn(`Component emitted event "${event}" but it is neither declared in ` +
1802 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
1803 }
1804 }
1805 else {
1806 const validator = emitsOptions[event];
1807 if (isFunction(validator)) {
1808 const isValid = validator(...rawArgs);
1809 if (!isValid) {
1810 warn(`Invalid event arguments: event validation failed for event "${event}".`);
1811 }
1812 }
1813 }
1814 }
1815 }
1816 let args = rawArgs;
1817 const isModelListener = event.startsWith('update:');
1818 // for v-model update:xxx events, apply modifiers on args
1819 const modelArg = isModelListener && event.slice(7);
1820 if (modelArg && modelArg in props) {
1821 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
1822 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
1823 if (trim) {
1824 args = rawArgs.map(a => a.trim());
1825 }
1826 else if (number) {
1827 args = rawArgs.map(toNumber);
1828 }
1829 }
1830 {
1831 devtoolsComponentEmit(instance, event, args);
1832 }
1833 {
1834 const lowerCaseEvent = event.toLowerCase();
1835 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
1836 warn(`Event "${lowerCaseEvent}" is emitted in component ` +
1837 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
1838 `Note that HTML attributes are case-insensitive and you cannot use ` +
1839 `v-on to listen to camelCase events when using in-DOM templates. ` +
1840 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
1841 }
1842 }
1843 // convert handler name to camelCase. See issue #2249
1844 let handlerName = toHandlerKey(camelize(event));
1845 let handler = props[handlerName];
1846 // for v-model update:xxx events, also trigger kebab-case equivalent
1847 // for props passed via kebab-case
1848 if (!handler && isModelListener) {
1849 handlerName = toHandlerKey(hyphenate(event));
1850 handler = props[handlerName];
1851 }
1852 if (handler) {
1853 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
1854 }
1855 const onceHandler = props[handlerName + `Once`];
1856 if (onceHandler) {
1857 if (!instance.emitted) {
1858 (instance.emitted = {})[handlerName] = true;
1859 }
1860 else if (instance.emitted[handlerName]) {
1861 return;
1862 }
1863 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
1864 }
1865 }
1866 function normalizeEmitsOptions(comp, appContext, asMixin = false) {
1867 if (!appContext.deopt && comp.__emits !== undefined) {
1868 return comp.__emits;
1869 }
1870 const raw = comp.emits;
1871 let normalized = {};
1872 // apply mixin/extends props
1873 let hasExtends = false;
1874 if (!isFunction(comp)) {
1875 const extendEmits = (raw) => {
1876 hasExtends = true;
1877 extend(normalized, normalizeEmitsOptions(raw, appContext, true));
1878 };
1879 if (!asMixin && appContext.mixins.length) {
1880 appContext.mixins.forEach(extendEmits);
1881 }
1882 if (comp.extends) {
1883 extendEmits(comp.extends);
1884 }
1885 if (comp.mixins) {
1886 comp.mixins.forEach(extendEmits);
1887 }
1888 }
1889 if (!raw && !hasExtends) {
1890 return (comp.__emits = null);
1891 }
1892 if (isArray(raw)) {
1893 raw.forEach(key => (normalized[key] = null));
1894 }
1895 else {
1896 extend(normalized, raw);
1897 }
1898 return (comp.__emits = normalized);
1899 }
1900 // Check if an incoming prop key is a declared emit event listener.
1901 // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
1902 // both considered matched listeners.
1903 function isEmitListener(options, key) {
1904 if (!options || !isOn(key)) {
1905 return false;
1906 }
1907 key = key.slice(2).replace(/Once$/, '');
1908 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
1909 hasOwn(options, hyphenate(key)) ||
1910 hasOwn(options, key));
1911 }
1912
1913 /**
1914 * mark the current rendering instance for asset resolution (e.g.
1915 * resolveComponent, resolveDirective) during render
1916 */
1917 let currentRenderingInstance = null;
1918 function setCurrentRenderingInstance(instance) {
1919 currentRenderingInstance = instance;
1920 }
1921 /**
1922 * dev only flag to track whether $attrs was used during render.
1923 * If $attrs was used during render then the warning for failed attrs
1924 * fallthrough can be suppressed.
1925 */
1926 let accessedAttrs = false;
1927 function markAttrsAccessed() {
1928 accessedAttrs = true;
1929 }
1930 function renderComponentRoot(instance) {
1931 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx } = instance;
1932 let result;
1933 currentRenderingInstance = instance;
1934 {
1935 accessedAttrs = false;
1936 }
1937 try {
1938 let fallthroughAttrs;
1939 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
1940 // withProxy is a proxy with a different `has` trap only for
1941 // runtime-compiled render functions using `with` block.
1942 const proxyToUse = withProxy || proxy;
1943 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
1944 fallthroughAttrs = attrs;
1945 }
1946 else {
1947 // functional
1948 const render = Component;
1949 // in dev, mark attrs accessed if optional props (attrs === props)
1950 if (true && attrs === props) {
1951 markAttrsAccessed();
1952 }
1953 result = normalizeVNode(render.length > 1
1954 ? render(props, true
1955 ? {
1956 get attrs() {
1957 markAttrsAccessed();
1958 return attrs;
1959 },
1960 slots,
1961 emit
1962 }
1963 : { attrs, slots, emit })
1964 : render(props, null /* we know it doesn't need it */));
1965 fallthroughAttrs = Component.props
1966 ? attrs
1967 : getFunctionalFallthrough(attrs);
1968 }
1969 // attr merging
1970 // in dev mode, comments are preserved, and it's possible for a template
1971 // to have comments along side the root element which makes it a fragment
1972 let root = result;
1973 let setRoot = undefined;
1974 if (true &&
1975 result.patchFlag > 0 &&
1976 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
1977 ;
1978 [root, setRoot] = getChildRoot(result);
1979 }
1980 if (Component.inheritAttrs !== false && fallthroughAttrs) {
1981 const keys = Object.keys(fallthroughAttrs);
1982 const { shapeFlag } = root;
1983 if (keys.length) {
1984 if (shapeFlag & 1 /* ELEMENT */ ||
1985 shapeFlag & 6 /* COMPONENT */) {
1986 if (propsOptions && keys.some(isModelListener)) {
1987 // If a v-model listener (onUpdate:xxx) has a corresponding declared
1988 // prop, it indicates this component expects to handle v-model and
1989 // it should not fallthrough.
1990 // related: #1543, #1643, #1989
1991 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
1992 }
1993 root = cloneVNode(root, fallthroughAttrs);
1994 }
1995 else if (true && !accessedAttrs && root.type !== Comment) {
1996 const allAttrs = Object.keys(attrs);
1997 const eventAttrs = [];
1998 const extraAttrs = [];
1999 for (let i = 0, l = allAttrs.length; i < l; i++) {
2000 const key = allAttrs[i];
2001 if (isOn(key)) {
2002 // ignore v-model handlers when they fail to fallthrough
2003 if (!isModelListener(key)) {
2004 // remove `on`, lowercase first letter to reflect event casing
2005 // accurately
2006 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2007 }
2008 }
2009 else {
2010 extraAttrs.push(key);
2011 }
2012 }
2013 if (extraAttrs.length) {
2014 warn(`Extraneous non-props attributes (` +
2015 `${extraAttrs.join(', ')}) ` +
2016 `were passed to component but could not be automatically inherited ` +
2017 `because component renders fragment or text root nodes.`);
2018 }
2019 if (eventAttrs.length) {
2020 warn(`Extraneous non-emits event listeners (` +
2021 `${eventAttrs.join(', ')}) ` +
2022 `were passed to component but could not be automatically inherited ` +
2023 `because component renders fragment or text root nodes. ` +
2024 `If the listener is intended to be a component custom event listener only, ` +
2025 `declare it using the "emits" option.`);
2026 }
2027 }
2028 }
2029 }
2030 // inherit directives
2031 if (vnode.dirs) {
2032 if (true && !isElementRoot(root)) {
2033 warn(`Runtime directive used on component with non-element root node. ` +
2034 `The directives will not function as intended.`);
2035 }
2036 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2037 }
2038 // inherit transition data
2039 if (vnode.transition) {
2040 if (true && !isElementRoot(root)) {
2041 warn(`Component inside <Transition> renders non-element root node ` +
2042 `that cannot be animated.`);
2043 }
2044 root.transition = vnode.transition;
2045 }
2046 if (true && setRoot) {
2047 setRoot(root);
2048 }
2049 else {
2050 result = root;
2051 }
2052 }
2053 catch (err) {
2054 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2055 result = createVNode(Comment);
2056 }
2057 currentRenderingInstance = null;
2058 return result;
2059 }
2060 /**
2061 * dev only
2062 * In dev mode, template root level comments are rendered, which turns the
2063 * template into a fragment root, but we need to locate the single element
2064 * root for attrs and scope id processing.
2065 */
2066 const getChildRoot = (vnode) => {
2067 const rawChildren = vnode.children;
2068 const dynamicChildren = vnode.dynamicChildren;
2069 const childRoot = filterSingleRoot(rawChildren);
2070 if (!childRoot) {
2071 return [vnode, undefined];
2072 }
2073 const index = rawChildren.indexOf(childRoot);
2074 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2075 const setRoot = (updatedRoot) => {
2076 rawChildren[index] = updatedRoot;
2077 if (dynamicChildren) {
2078 if (dynamicIndex > -1) {
2079 dynamicChildren[dynamicIndex] = updatedRoot;
2080 }
2081 else if (updatedRoot.patchFlag > 0) {
2082 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2083 }
2084 }
2085 };
2086 return [normalizeVNode(childRoot), setRoot];
2087 };
2088 function filterSingleRoot(children) {
2089 let singleRoot;
2090 for (let i = 0; i < children.length; i++) {
2091 const child = children[i];
2092 if (isVNode(child)) {
2093 // ignore user comment
2094 if (child.type !== Comment || child.children === 'v-if') {
2095 if (singleRoot) {
2096 // has more than 1 non-comment child, return now
2097 return;
2098 }
2099 else {
2100 singleRoot = child;
2101 }
2102 }
2103 }
2104 else {
2105 return;
2106 }
2107 }
2108 return singleRoot;
2109 }
2110 const getFunctionalFallthrough = (attrs) => {
2111 let res;
2112 for (const key in attrs) {
2113 if (key === 'class' || key === 'style' || isOn(key)) {
2114 (res || (res = {}))[key] = attrs[key];
2115 }
2116 }
2117 return res;
2118 };
2119 const filterModelListeners = (attrs, props) => {
2120 const res = {};
2121 for (const key in attrs) {
2122 if (!isModelListener(key) || !(key.slice(9) in props)) {
2123 res[key] = attrs[key];
2124 }
2125 }
2126 return res;
2127 };
2128 const isElementRoot = (vnode) => {
2129 return (vnode.shapeFlag & 6 /* COMPONENT */ ||
2130 vnode.shapeFlag & 1 /* ELEMENT */ ||
2131 vnode.type === Comment // potential v-if branch switch
2132 );
2133 };
2134 function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2135 const { props: prevProps, children: prevChildren, component } = prevVNode;
2136 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2137 const emits = component.emitsOptions;
2138 // Parent component's render function was hot-updated. Since this may have
2139 // caused the child component's slots content to have changed, we need to
2140 // force the child to update as well.
2141 if ((prevChildren || nextChildren) && isHmrUpdating) {
2142 return true;
2143 }
2144 // force child update for runtime directive or transition on component vnode.
2145 if (nextVNode.dirs || nextVNode.transition) {
2146 return true;
2147 }
2148 if (optimized && patchFlag >= 0) {
2149 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2150 // slot content that references values that might have changed,
2151 // e.g. in a v-for
2152 return true;
2153 }
2154 if (patchFlag & 16 /* FULL_PROPS */) {
2155 if (!prevProps) {
2156 return !!nextProps;
2157 }
2158 // presence of this flag indicates props are always non-null
2159 return hasPropsChanged(prevProps, nextProps, emits);
2160 }
2161 else if (patchFlag & 8 /* PROPS */) {
2162 const dynamicProps = nextVNode.dynamicProps;
2163 for (let i = 0; i < dynamicProps.length; i++) {
2164 const key = dynamicProps[i];
2165 if (nextProps[key] !== prevProps[key] &&
2166 !isEmitListener(emits, key)) {
2167 return true;
2168 }
2169 }
2170 }
2171 }
2172 else {
2173 // this path is only taken by manually written render functions
2174 // so presence of any children leads to a forced update
2175 if (prevChildren || nextChildren) {
2176 if (!nextChildren || !nextChildren.$stable) {
2177 return true;
2178 }
2179 }
2180 if (prevProps === nextProps) {
2181 return false;
2182 }
2183 if (!prevProps) {
2184 return !!nextProps;
2185 }
2186 if (!nextProps) {
2187 return true;
2188 }
2189 return hasPropsChanged(prevProps, nextProps, emits);
2190 }
2191 return false;
2192 }
2193 function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2194 const nextKeys = Object.keys(nextProps);
2195 if (nextKeys.length !== Object.keys(prevProps).length) {
2196 return true;
2197 }
2198 for (let i = 0; i < nextKeys.length; i++) {
2199 const key = nextKeys[i];
2200 if (nextProps[key] !== prevProps[key] &&
2201 !isEmitListener(emitsOptions, key)) {
2202 return true;
2203 }
2204 }
2205 return false;
2206 }
2207 function updateHOCHostEl({ vnode, parent }, el // HostNode
2208 ) {
2209 while (parent && parent.subTree === vnode) {
2210 (vnode = parent.vnode).el = el;
2211 parent = parent.parent;
2212 }
2213 }
2214
2215 const isSuspense = (type) => type.__isSuspense;
2216 // Suspense exposes a component-like API, and is treated like a component
2217 // in the compiler, but internally it's a special built-in type that hooks
2218 // directly into the renderer.
2219 const SuspenseImpl = {
2220 // In order to make Suspense tree-shakable, we need to avoid importing it
2221 // directly in the renderer. The renderer checks for the __isSuspense flag
2222 // on a vnode's type and calls the `process` method, passing in renderer
2223 // internals.
2224 __isSuspense: true,
2225 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized,
2226 // platform-specific impl passed from renderer
2227 rendererInternals) {
2228 if (n1 == null) {
2229 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals);
2230 }
2231 else {
2232 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, rendererInternals);
2233 }
2234 },
2235 hydrate: hydrateSuspense,
2236 create: createSuspenseBoundary
2237 };
2238 // Force-casted public typing for h and TSX props inference
2239 const Suspense = (SuspenseImpl
2240 );
2241 function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized, rendererInternals) {
2242 const { p: patch, o: { createElement } } = rendererInternals;
2243 const hiddenContainer = createElement('div');
2244 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals));
2245 // start mounting the content subtree in an off-dom container
2246 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG);
2247 // now check if we have encountered any async deps
2248 if (suspense.deps > 0) {
2249 // has async
2250 // mount the fallback tree
2251 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2252 isSVG);
2253 setActiveBranch(suspense, vnode.ssFallback);
2254 }
2255 else {
2256 // Suspense has no async deps. Just resolve.
2257 suspense.resolve();
2258 }
2259 }
2260 function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, { p: patch, um: unmount, o: { createElement } }) {
2261 const suspense = (n2.suspense = n1.suspense);
2262 suspense.vnode = n2;
2263 n2.el = n1.el;
2264 const newBranch = n2.ssContent;
2265 const newFallback = n2.ssFallback;
2266 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2267 if (pendingBranch) {
2268 suspense.pendingBranch = newBranch;
2269 if (isSameVNodeType(newBranch, pendingBranch)) {
2270 // same root type but content may have changed.
2271 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
2272 if (suspense.deps <= 0) {
2273 suspense.resolve();
2274 }
2275 else if (isInFallback) {
2276 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2277 isSVG);
2278 setActiveBranch(suspense, newFallback);
2279 }
2280 }
2281 else {
2282 // toggled before pending tree is resolved
2283 suspense.pendingId++;
2284 if (isHydrating) {
2285 // if toggled before hydration is finished, the current DOM tree is
2286 // no longer valid. set it as the active branch so it will be unmounted
2287 // when resolved
2288 suspense.isHydrating = false;
2289 suspense.activeBranch = pendingBranch;
2290 }
2291 else {
2292 unmount(pendingBranch, parentComponent, suspense);
2293 }
2294 // increment pending ID. this is used to invalidate async callbacks
2295 // reset suspense state
2296 suspense.deps = 0;
2297 // discard effects from pending branch
2298 suspense.effects.length = 0;
2299 // discard previous container
2300 suspense.hiddenContainer = createElement('div');
2301 if (isInFallback) {
2302 // already in fallback state
2303 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
2304 if (suspense.deps <= 0) {
2305 suspense.resolve();
2306 }
2307 else {
2308 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2309 isSVG);
2310 setActiveBranch(suspense, newFallback);
2311 }
2312 }
2313 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2314 // toggled "back" to current active branch
2315 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG);
2316 // force resolve
2317 suspense.resolve(true);
2318 }
2319 else {
2320 // switched to a 3rd branch
2321 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
2322 if (suspense.deps <= 0) {
2323 suspense.resolve();
2324 }
2325 }
2326 }
2327 }
2328 else {
2329 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2330 // root did not change, just normal patch
2331 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG);
2332 setActiveBranch(suspense, newBranch);
2333 }
2334 else {
2335 // root node toggled
2336 // invoke @pending event
2337 const onPending = n2.props && n2.props.onPending;
2338 if (isFunction(onPending)) {
2339 onPending();
2340 }
2341 // mount pending branch in off-dom container
2342 suspense.pendingBranch = newBranch;
2343 suspense.pendingId++;
2344 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG);
2345 if (suspense.deps <= 0) {
2346 // incoming branch has no async deps, resolve now.
2347 suspense.resolve();
2348 }
2349 else {
2350 const { timeout, pendingId } = suspense;
2351 if (timeout > 0) {
2352 setTimeout(() => {
2353 if (suspense.pendingId === pendingId) {
2354 suspense.fallback(newFallback);
2355 }
2356 }, timeout);
2357 }
2358 else if (timeout === 0) {
2359 suspense.fallback(newFallback);
2360 }
2361 }
2362 }
2363 }
2364 }
2365 let hasWarned = false;
2366 function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, optimized, rendererInternals, isHydrating = false) {
2367 /* istanbul ignore if */
2368 if (!hasWarned) {
2369 hasWarned = true;
2370 // @ts-ignore `console.info` cannot be null error
2371 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2372 }
2373 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2374 const timeout = toNumber(vnode.props && vnode.props.timeout);
2375 const suspense = {
2376 vnode,
2377 parent,
2378 parentComponent,
2379 isSVG,
2380 container,
2381 hiddenContainer,
2382 anchor,
2383 deps: 0,
2384 pendingId: 0,
2385 timeout: typeof timeout === 'number' ? timeout : -1,
2386 activeBranch: null,
2387 pendingBranch: null,
2388 isInFallback: true,
2389 isHydrating,
2390 isUnmounted: false,
2391 effects: [],
2392 resolve(resume = false) {
2393 {
2394 if (!resume && !suspense.pendingBranch) {
2395 throw new Error(`suspense.resolve() is called without a pending branch.`);
2396 }
2397 if (suspense.isUnmounted) {
2398 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2399 }
2400 }
2401 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2402 if (suspense.isHydrating) {
2403 suspense.isHydrating = false;
2404 }
2405 else if (!resume) {
2406 const delayEnter = activeBranch &&
2407 pendingBranch.transition &&
2408 pendingBranch.transition.mode === 'out-in';
2409 if (delayEnter) {
2410 activeBranch.transition.afterLeave = () => {
2411 if (pendingId === suspense.pendingId) {
2412 move(pendingBranch, container, anchor, 0 /* ENTER */);
2413 }
2414 };
2415 }
2416 // this is initial anchor on mount
2417 let { anchor } = suspense;
2418 // unmount current active tree
2419 if (activeBranch) {
2420 // if the fallback tree was mounted, it may have been moved
2421 // as part of a parent suspense. get the latest anchor for insertion
2422 anchor = next(activeBranch);
2423 unmount(activeBranch, parentComponent, suspense, true);
2424 }
2425 if (!delayEnter) {
2426 // move content from off-dom container to actual container
2427 move(pendingBranch, container, anchor, 0 /* ENTER */);
2428 }
2429 }
2430 setActiveBranch(suspense, pendingBranch);
2431 suspense.pendingBranch = null;
2432 suspense.isInFallback = false;
2433 // flush buffered effects
2434 // check if there is a pending parent suspense
2435 let parent = suspense.parent;
2436 let hasUnresolvedAncestor = false;
2437 while (parent) {
2438 if (parent.pendingBranch) {
2439 // found a pending parent suspense, merge buffered post jobs
2440 // into that parent
2441 parent.effects.push(...effects);
2442 hasUnresolvedAncestor = true;
2443 break;
2444 }
2445 parent = parent.parent;
2446 }
2447 // no pending parent suspense, flush all jobs
2448 if (!hasUnresolvedAncestor) {
2449 queuePostFlushCb(effects);
2450 }
2451 suspense.effects = [];
2452 // invoke @resolve event
2453 const onResolve = vnode.props && vnode.props.onResolve;
2454 if (isFunction(onResolve)) {
2455 onResolve();
2456 }
2457 },
2458 fallback(fallbackVNode) {
2459 if (!suspense.pendingBranch) {
2460 return;
2461 }
2462 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2463 // invoke @fallback event
2464 const onFallback = vnode.props && vnode.props.onFallback;
2465 if (isFunction(onFallback)) {
2466 onFallback();
2467 }
2468 const anchor = next(activeBranch);
2469 const mountFallback = () => {
2470 if (!suspense.isInFallback) {
2471 return;
2472 }
2473 // mount the fallback tree
2474 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2475 isSVG);
2476 setActiveBranch(suspense, fallbackVNode);
2477 };
2478 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2479 if (delayEnter) {
2480 activeBranch.transition.afterLeave = mountFallback;
2481 }
2482 // unmount current active branch
2483 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2484 true // shouldRemove
2485 );
2486 suspense.isInFallback = true;
2487 if (!delayEnter) {
2488 mountFallback();
2489 }
2490 },
2491 move(container, anchor, type) {
2492 suspense.activeBranch &&
2493 move(suspense.activeBranch, container, anchor, type);
2494 suspense.container = container;
2495 },
2496 next() {
2497 return suspense.activeBranch && next(suspense.activeBranch);
2498 },
2499 registerDep(instance, setupRenderEffect) {
2500 const isInPendingSuspense = !!suspense.pendingBranch;
2501 if (isInPendingSuspense) {
2502 suspense.deps++;
2503 }
2504 const hydratedEl = instance.vnode.el;
2505 instance
2506 .asyncDep.catch(err => {
2507 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2508 })
2509 .then(asyncSetupResult => {
2510 // retry when the setup() promise resolves.
2511 // component may have been unmounted before resolve.
2512 if (instance.isUnmounted ||
2513 suspense.isUnmounted ||
2514 suspense.pendingId !== instance.suspenseId) {
2515 return;
2516 }
2517 // retry from this component
2518 instance.asyncResolved = true;
2519 const { vnode } = instance;
2520 {
2521 pushWarningContext(vnode);
2522 }
2523 handleSetupResult(instance, asyncSetupResult);
2524 if (hydratedEl) {
2525 // vnode may have been replaced if an update happened before the
2526 // async dep is resolved.
2527 vnode.el = hydratedEl;
2528 }
2529 const placeholder = !hydratedEl && instance.subTree.el;
2530 setupRenderEffect(instance, vnode,
2531 // component may have been moved before resolve.
2532 // if this is not a hydration, instance.subTree will be the comment
2533 // placeholder.
2534 parentNode(hydratedEl || instance.subTree.el),
2535 // anchor will not be used if this is hydration, so only need to
2536 // consider the comment placeholder case.
2537 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
2538 if (placeholder) {
2539 remove(placeholder);
2540 }
2541 updateHOCHostEl(instance, vnode.el);
2542 {
2543 popWarningContext();
2544 }
2545 // only decrease deps count if suspense is not already resolved
2546 if (isInPendingSuspense && --suspense.deps === 0) {
2547 suspense.resolve();
2548 }
2549 });
2550 },
2551 unmount(parentSuspense, doRemove) {
2552 suspense.isUnmounted = true;
2553 if (suspense.activeBranch) {
2554 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
2555 }
2556 if (suspense.pendingBranch) {
2557 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
2558 }
2559 }
2560 };
2561 return suspense;
2562 }
2563 function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, optimized, rendererInternals, hydrateNode) {
2564 /* eslint-disable no-restricted-globals */
2565 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, optimized, rendererInternals, true /* hydrating */));
2566 // there are two possible scenarios for server-rendered suspense:
2567 // - success: ssr content should be fully resolved
2568 // - failure: ssr content should be the fallback branch.
2569 // however, on the client we don't really know if it has failed or not
2570 // attempt to hydrate the DOM assuming it has succeeded, but we still
2571 // need to construct a suspense boundary first
2572 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, optimized);
2573 if (suspense.deps === 0) {
2574 suspense.resolve();
2575 }
2576 return result;
2577 /* eslint-enable no-restricted-globals */
2578 }
2579 function normalizeSuspenseChildren(vnode) {
2580 const { shapeFlag, children } = vnode;
2581 let content;
2582 let fallback;
2583 if (shapeFlag & 32 /* SLOTS_CHILDREN */) {
2584 content = normalizeSuspenseSlot(children.default);
2585 fallback = normalizeSuspenseSlot(children.fallback);
2586 }
2587 else {
2588 content = normalizeSuspenseSlot(children);
2589 fallback = normalizeVNode(null);
2590 }
2591 return {
2592 content,
2593 fallback
2594 };
2595 }
2596 function normalizeSuspenseSlot(s) {
2597 if (isFunction(s)) {
2598 s = s();
2599 }
2600 if (isArray(s)) {
2601 const singleChild = filterSingleRoot(s);
2602 if (!singleChild) {
2603 warn(`<Suspense> slots expect a single root node.`);
2604 }
2605 s = singleChild;
2606 }
2607 return normalizeVNode(s);
2608 }
2609 function queueEffectWithSuspense(fn, suspense) {
2610 if (suspense && suspense.pendingBranch) {
2611 if (isArray(fn)) {
2612 suspense.effects.push(...fn);
2613 }
2614 else {
2615 suspense.effects.push(fn);
2616 }
2617 }
2618 else {
2619 queuePostFlushCb(fn);
2620 }
2621 }
2622 function setActiveBranch(suspense, branch) {
2623 suspense.activeBranch = branch;
2624 const { vnode, parentComponent } = suspense;
2625 const el = (vnode.el = branch.el);
2626 // in case suspense is the root node of a component,
2627 // recursively update the HOC el
2628 if (parentComponent && parentComponent.subTree === vnode) {
2629 parentComponent.vnode.el = el;
2630 updateHOCHostEl(parentComponent, el);
2631 }
2632 }
2633
2634 let isRenderingCompiledSlot = 0;
2635 const setCompiledSlotRendering = (n) => (isRenderingCompiledSlot += n);
2636 /**
2637 * Compiler runtime helper for rendering `<slot/>`
2638 * @private
2639 */
2640 function renderSlot(slots, name, props = {},
2641 // this is not a user-facing function, so the fallback is always generated by
2642 // the compiler and guaranteed to be a function returning an array
2643 fallback) {
2644 let slot = slots[name];
2645 if (slot && slot.length > 1) {
2646 warn(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
2647 `function. You need to mark this component with $dynamic-slots in the ` +
2648 `parent template.`);
2649 slot = () => [];
2650 }
2651 // a compiled slot disables block tracking by default to avoid manual
2652 // invocation interfering with template-based block tracking, but in
2653 // `renderSlot` we can be sure that it's template-based so we can force
2654 // enable it.
2655 isRenderingCompiledSlot++;
2656 openBlock();
2657 const validSlotContent = slot && ensureValidVNode(slot(props));
2658 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
2659 ? 64 /* STABLE_FRAGMENT */
2660 : -2 /* BAIL */);
2661 isRenderingCompiledSlot--;
2662 return rendered;
2663 }
2664 function ensureValidVNode(vnodes) {
2665 return vnodes.some(child => {
2666 if (!isVNode(child))
2667 return true;
2668 if (child.type === Comment)
2669 return false;
2670 if (child.type === Fragment &&
2671 !ensureValidVNode(child.children))
2672 return false;
2673 return true;
2674 })
2675 ? vnodes
2676 : null;
2677 }
2678
2679 /**
2680 * Wrap a slot function to memoize current rendering instance
2681 * @private
2682 */
2683 function withCtx(fn, ctx = currentRenderingInstance) {
2684 if (!ctx)
2685 return fn;
2686 const renderFnWithContext = (...args) => {
2687 // If a user calls a compiled slot inside a template expression (#1745), it
2688 // can mess up block tracking, so by default we need to push a null block to
2689 // avoid that. This isn't necessary if rendering a compiled `<slot>`.
2690 if (!isRenderingCompiledSlot) {
2691 openBlock(true /* null block that disables tracking */);
2692 }
2693 const owner = currentRenderingInstance;
2694 setCurrentRenderingInstance(ctx);
2695 const res = fn(...args);
2696 setCurrentRenderingInstance(owner);
2697 if (!isRenderingCompiledSlot) {
2698 closeBlock();
2699 }
2700 return res;
2701 };
2702 renderFnWithContext._c = true;
2703 return renderFnWithContext;
2704 }
2705
2706 // SFC scoped style ID management.
2707 let currentScopeId = null;
2708 const scopeIdStack = [];
2709 /**
2710 * @private
2711 */
2712 function pushScopeId(id) {
2713 scopeIdStack.push((currentScopeId = id));
2714 }
2715 /**
2716 * @private
2717 */
2718 function popScopeId() {
2719 scopeIdStack.pop();
2720 currentScopeId = scopeIdStack[scopeIdStack.length - 1] || null;
2721 }
2722 /**
2723 * @private
2724 */
2725 function withScopeId(id) {
2726 return ((fn) => withCtx(function () {
2727 pushScopeId(id);
2728 const res = fn.apply(this, arguments);
2729 popScopeId();
2730 return res;
2731 }));
2732 }
2733
2734 function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
2735 isSSR = false) {
2736 const props = {};
2737 const attrs = {};
2738 def(attrs, InternalObjectKey, 1);
2739 setFullProps(instance, rawProps, props, attrs);
2740 // validation
2741 {
2742 validateProps(props, instance);
2743 }
2744 if (isStateful) {
2745 // stateful
2746 instance.props = isSSR ? props : shallowReactive(props);
2747 }
2748 else {
2749 if (!instance.type.props) {
2750 // functional w/ optional props, props === attrs
2751 instance.props = attrs;
2752 }
2753 else {
2754 // functional w/ declared props
2755 instance.props = props;
2756 }
2757 }
2758 instance.attrs = attrs;
2759 }
2760 function updateProps(instance, rawProps, rawPrevProps, optimized) {
2761 const { props, attrs, vnode: { patchFlag } } = instance;
2762 const rawCurrentProps = toRaw(props);
2763 const [options] = instance.propsOptions;
2764 if (
2765 // always force full diff in dev
2766 // - #1942 if hmr is enabled with sfc component
2767 // - vite#872 non-sfc component used by sfc component
2768 !((instance.type.__hmrId ||
2769 (instance.parent && instance.parent.type.__hmrId))) &&
2770 (optimized || patchFlag > 0) &&
2771 !(patchFlag & 16 /* FULL_PROPS */)) {
2772 if (patchFlag & 8 /* PROPS */) {
2773 // Compiler-generated props & no keys change, just set the updated
2774 // the props.
2775 const propsToUpdate = instance.vnode.dynamicProps;
2776 for (let i = 0; i < propsToUpdate.length; i++) {
2777 const key = propsToUpdate[i];
2778 // PROPS flag guarantees rawProps to be non-null
2779 const value = rawProps[key];
2780 if (options) {
2781 // attr / props separation was done on init and will be consistent
2782 // in this code path, so just check if attrs have it.
2783 if (hasOwn(attrs, key)) {
2784 attrs[key] = value;
2785 }
2786 else {
2787 const camelizedKey = camelize(key);
2788 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance);
2789 }
2790 }
2791 else {
2792 attrs[key] = value;
2793 }
2794 }
2795 }
2796 }
2797 else {
2798 // full props update.
2799 setFullProps(instance, rawProps, props, attrs);
2800 // in case of dynamic props, check if we need to delete keys from
2801 // the props object
2802 let kebabKey;
2803 for (const key in rawCurrentProps) {
2804 if (!rawProps ||
2805 // for camelCase
2806 (!hasOwn(rawProps, key) &&
2807 // it's possible the original props was passed in as kebab-case
2808 // and converted to camelCase (#955)
2809 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
2810 if (options) {
2811 if (rawPrevProps &&
2812 // for camelCase
2813 (rawPrevProps[key] !== undefined ||
2814 // for kebab-case
2815 rawPrevProps[kebabKey] !== undefined)) {
2816 props[key] = resolvePropValue(options, rawProps || EMPTY_OBJ, key, undefined, instance);
2817 }
2818 }
2819 else {
2820 delete props[key];
2821 }
2822 }
2823 }
2824 // in the case of functional component w/o props declaration, props and
2825 // attrs point to the same object so it should already have been updated.
2826 if (attrs !== rawCurrentProps) {
2827 for (const key in attrs) {
2828 if (!rawProps || !hasOwn(rawProps, key)) {
2829 delete attrs[key];
2830 }
2831 }
2832 }
2833 }
2834 // trigger updates for $attrs in case it's used in component slots
2835 trigger(instance, "set" /* SET */, '$attrs');
2836 if (rawProps) {
2837 validateProps(props, instance);
2838 }
2839 }
2840 function setFullProps(instance, rawProps, props, attrs) {
2841 const [options, needCastKeys] = instance.propsOptions;
2842 if (rawProps) {
2843 for (const key in rawProps) {
2844 const value = rawProps[key];
2845 // key, ref are reserved and never passed down
2846 if (isReservedProp(key)) {
2847 continue;
2848 }
2849 // prop option names are camelized during normalization, so to support
2850 // kebab -> camel conversion here we need to camelize the key.
2851 let camelKey;
2852 if (options && hasOwn(options, (camelKey = camelize(key)))) {
2853 props[camelKey] = value;
2854 }
2855 else if (!isEmitListener(instance.emitsOptions, key)) {
2856 // Any non-declared (either as a prop or an emitted event) props are put
2857 // into a separate `attrs` object for spreading. Make sure to preserve
2858 // original key casing
2859 attrs[key] = value;
2860 }
2861 }
2862 }
2863 if (needCastKeys) {
2864 const rawCurrentProps = toRaw(props);
2865 for (let i = 0; i < needCastKeys.length; i++) {
2866 const key = needCastKeys[i];
2867 props[key] = resolvePropValue(options, rawCurrentProps, key, rawCurrentProps[key], instance);
2868 }
2869 }
2870 }
2871 function resolvePropValue(options, props, key, value, instance) {
2872 const opt = options[key];
2873 if (opt != null) {
2874 const hasDefault = hasOwn(opt, 'default');
2875 // default values
2876 if (hasDefault && value === undefined) {
2877 const defaultValue = opt.default;
2878 if (opt.type !== Function && isFunction(defaultValue)) {
2879 setCurrentInstance(instance);
2880 value = defaultValue(props);
2881 setCurrentInstance(null);
2882 }
2883 else {
2884 value = defaultValue;
2885 }
2886 }
2887 // boolean casting
2888 if (opt[0 /* shouldCast */]) {
2889 if (!hasOwn(props, key) && !hasDefault) {
2890 value = false;
2891 }
2892 else if (opt[1 /* shouldCastTrue */] &&
2893 (value === '' || value === hyphenate(key))) {
2894 value = true;
2895 }
2896 }
2897 }
2898 return value;
2899 }
2900 function normalizePropsOptions(comp, appContext, asMixin = false) {
2901 if (!appContext.deopt && comp.__props) {
2902 return comp.__props;
2903 }
2904 const raw = comp.props;
2905 const normalized = {};
2906 const needCastKeys = [];
2907 // apply mixin/extends props
2908 let hasExtends = false;
2909 if (!isFunction(comp)) {
2910 const extendProps = (raw) => {
2911 hasExtends = true;
2912 const [props, keys] = normalizePropsOptions(raw, appContext, true);
2913 extend(normalized, props);
2914 if (keys)
2915 needCastKeys.push(...keys);
2916 };
2917 if (!asMixin && appContext.mixins.length) {
2918 appContext.mixins.forEach(extendProps);
2919 }
2920 if (comp.extends) {
2921 extendProps(comp.extends);
2922 }
2923 if (comp.mixins) {
2924 comp.mixins.forEach(extendProps);
2925 }
2926 }
2927 if (!raw && !hasExtends) {
2928 return (comp.__props = EMPTY_ARR);
2929 }
2930 if (isArray(raw)) {
2931 for (let i = 0; i < raw.length; i++) {
2932 if (!isString(raw[i])) {
2933 warn(`props must be strings when using array syntax.`, raw[i]);
2934 }
2935 const normalizedKey = camelize(raw[i]);
2936 if (validatePropName(normalizedKey)) {
2937 normalized[normalizedKey] = EMPTY_OBJ;
2938 }
2939 }
2940 }
2941 else if (raw) {
2942 if (!isObject(raw)) {
2943 warn(`invalid props options`, raw);
2944 }
2945 for (const key in raw) {
2946 const normalizedKey = camelize(key);
2947 if (validatePropName(normalizedKey)) {
2948 const opt = raw[key];
2949 const prop = (normalized[normalizedKey] =
2950 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
2951 if (prop) {
2952 const booleanIndex = getTypeIndex(Boolean, prop.type);
2953 const stringIndex = getTypeIndex(String, prop.type);
2954 prop[0 /* shouldCast */] = booleanIndex > -1;
2955 prop[1 /* shouldCastTrue */] =
2956 stringIndex < 0 || booleanIndex < stringIndex;
2957 // if the prop needs boolean casting or default value
2958 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
2959 needCastKeys.push(normalizedKey);
2960 }
2961 }
2962 }
2963 }
2964 }
2965 return (comp.__props = [normalized, needCastKeys]);
2966 }
2967 function validatePropName(key) {
2968 if (key[0] !== '$') {
2969 return true;
2970 }
2971 else {
2972 warn(`Invalid prop name: "${key}" is a reserved property.`);
2973 }
2974 return false;
2975 }
2976 // use function string name to check type constructors
2977 // so that it works across vms / iframes.
2978 function getType(ctor) {
2979 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
2980 return match ? match[1] : '';
2981 }
2982 function isSameType(a, b) {
2983 return getType(a) === getType(b);
2984 }
2985 function getTypeIndex(type, expectedTypes) {
2986 if (isArray(expectedTypes)) {
2987 for (let i = 0, len = expectedTypes.length; i < len; i++) {
2988 if (isSameType(expectedTypes[i], type)) {
2989 return i;
2990 }
2991 }
2992 }
2993 else if (isFunction(expectedTypes)) {
2994 return isSameType(expectedTypes, type) ? 0 : -1;
2995 }
2996 return -1;
2997 }
2998 /**
2999 * dev only
3000 */
3001 function validateProps(props, instance) {
3002 const rawValues = toRaw(props);
3003 const options = instance.propsOptions[0];
3004 for (const key in options) {
3005 let opt = options[key];
3006 if (opt == null)
3007 continue;
3008 validateProp(key, rawValues[key], opt, !hasOwn(rawValues, key));
3009 }
3010 }
3011 /**
3012 * dev only
3013 */
3014 function validateProp(name, value, prop, isAbsent) {
3015 const { type, required, validator } = prop;
3016 // required!
3017 if (required && isAbsent) {
3018 warn('Missing required prop: "' + name + '"');
3019 return;
3020 }
3021 // missing but optional
3022 if (value == null && !prop.required) {
3023 return;
3024 }
3025 // type check
3026 if (type != null && type !== true) {
3027 let isValid = false;
3028 const types = isArray(type) ? type : [type];
3029 const expectedTypes = [];
3030 // value is valid as long as one of the specified types match
3031 for (let i = 0; i < types.length && !isValid; i++) {
3032 const { valid, expectedType } = assertType(value, types[i]);
3033 expectedTypes.push(expectedType || '');
3034 isValid = valid;
3035 }
3036 if (!isValid) {
3037 warn(getInvalidTypeMessage(name, value, expectedTypes));
3038 return;
3039 }
3040 }
3041 // custom validator
3042 if (validator && !validator(value)) {
3043 warn('Invalid prop: custom validator check failed for prop "' + name + '".');
3044 }
3045 }
3046 const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
3047 /**
3048 * dev only
3049 */
3050 function assertType(value, type) {
3051 let valid;
3052 const expectedType = getType(type);
3053 if (isSimpleType(expectedType)) {
3054 const t = typeof value;
3055 valid = t === expectedType.toLowerCase();
3056 // for primitive wrapper objects
3057 if (!valid && t === 'object') {
3058 valid = value instanceof type;
3059 }
3060 }
3061 else if (expectedType === 'Object') {
3062 valid = isObject(value);
3063 }
3064 else if (expectedType === 'Array') {
3065 valid = isArray(value);
3066 }
3067 else {
3068 valid = value instanceof type;
3069 }
3070 return {
3071 valid,
3072 expectedType
3073 };
3074 }
3075 /**
3076 * dev only
3077 */
3078 function getInvalidTypeMessage(name, value, expectedTypes) {
3079 let message = `Invalid prop: type check failed for prop "${name}".` +
3080 ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
3081 const expectedType = expectedTypes[0];
3082 const receivedType = toRawType(value);
3083 const expectedValue = styleValue(value, expectedType);
3084 const receivedValue = styleValue(value, receivedType);
3085 // check if we need to specify expected value
3086 if (expectedTypes.length === 1 &&
3087 isExplicable(expectedType) &&
3088 !isBoolean(expectedType, receivedType)) {
3089 message += ` with value ${expectedValue}`;
3090 }
3091 message += `, got ${receivedType} `;
3092 // check if we need to specify received value
3093 if (isExplicable(receivedType)) {
3094 message += `with value ${receivedValue}.`;
3095 }
3096 return message;
3097 }
3098 /**
3099 * dev only
3100 */
3101 function styleValue(value, type) {
3102 if (type === 'String') {
3103 return `"${value}"`;
3104 }
3105 else if (type === 'Number') {
3106 return `${Number(value)}`;
3107 }
3108 else {
3109 return `${value}`;
3110 }
3111 }
3112 /**
3113 * dev only
3114 */
3115 function isExplicable(type) {
3116 const explicitTypes = ['string', 'number', 'boolean'];
3117 return explicitTypes.some(elem => type.toLowerCase() === elem);
3118 }
3119 /**
3120 * dev only
3121 */
3122 function isBoolean(...args) {
3123 return args.some(elem => elem.toLowerCase() === 'boolean');
3124 }
3125
3126 function injectHook(type, hook, target = currentInstance, prepend = false) {
3127 if (target) {
3128 const hooks = target[type] || (target[type] = []);
3129 // cache the error handling wrapper for injected hooks so the same hook
3130 // can be properly deduped by the scheduler. "__weh" stands for "with error
3131 // handling".
3132 const wrappedHook = hook.__weh ||
3133 (hook.__weh = (...args) => {
3134 if (target.isUnmounted) {
3135 return;
3136 }
3137 // disable tracking inside all lifecycle hooks
3138 // since they can potentially be called inside effects.
3139 pauseTracking();
3140 // Set currentInstance during hook invocation.
3141 // This assumes the hook does not synchronously trigger other hooks, which
3142 // can only be false when the user does something really funky.
3143 setCurrentInstance(target);
3144 const res = callWithAsyncErrorHandling(hook, target, type, args);
3145 setCurrentInstance(null);
3146 resetTracking();
3147 return res;
3148 });
3149 if (prepend) {
3150 hooks.unshift(wrappedHook);
3151 }
3152 else {
3153 hooks.push(wrappedHook);
3154 }
3155 return wrappedHook;
3156 }
3157 else {
3158 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
3159 warn(`${apiName} is called when there is no active component instance to be ` +
3160 `associated with. ` +
3161 `Lifecycle injection APIs can only be used during execution of setup().` +
3162 (` If you are using async setup(), make sure to register lifecycle ` +
3163 `hooks before the first await statement.`
3164 ));
3165 }
3166 }
3167 const createHook = (lifecycle) => (hook, target = currentInstance) =>
3168 // post-create lifecycle registrations are noops during SSR
3169 !isInSSRComponentSetup && injectHook(lifecycle, hook, target);
3170 const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
3171 const onMounted = createHook("m" /* MOUNTED */);
3172 const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
3173 const onUpdated = createHook("u" /* UPDATED */);
3174 const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
3175 const onUnmounted = createHook("um" /* UNMOUNTED */);
3176 const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
3177 const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
3178 const onErrorCaptured = (hook, target = currentInstance) => {
3179 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
3180 };
3181
3182 // Simple effect.
3183 function watchEffect(effect, options) {
3184 return doWatch(effect, null, options);
3185 }
3186 // initial value for watchers to trigger on undefined initial values
3187 const INITIAL_WATCHER_VALUE = {};
3188 // implementation
3189 function watch(source, cb, options) {
3190 if (!isFunction(cb)) {
3191 warn(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3192 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3193 `supports \`watch(source, cb, options?) signature.`);
3194 }
3195 return doWatch(source, cb, options);
3196 }
3197 function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ, instance = currentInstance) {
3198 if (!cb) {
3199 if (immediate !== undefined) {
3200 warn(`watch() "immediate" option is only respected when using the ` +
3201 `watch(source, callback, options?) signature.`);
3202 }
3203 if (deep !== undefined) {
3204 warn(`watch() "deep" option is only respected when using the ` +
3205 `watch(source, callback, options?) signature.`);
3206 }
3207 }
3208 const warnInvalidSource = (s) => {
3209 warn(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3210 `a reactive object, or an array of these types.`);
3211 };
3212 let getter;
3213 let forceTrigger = false;
3214 if (isRef(source)) {
3215 getter = () => source.value;
3216 forceTrigger = !!source._shallow;
3217 }
3218 else if (isReactive(source)) {
3219 getter = () => source;
3220 deep = true;
3221 }
3222 else if (isArray(source)) {
3223 getter = () => source.map(s => {
3224 if (isRef(s)) {
3225 return s.value;
3226 }
3227 else if (isReactive(s)) {
3228 return traverse(s);
3229 }
3230 else if (isFunction(s)) {
3231 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */, [
3232 instance && instance.proxy
3233 ]);
3234 }
3235 else {
3236 warnInvalidSource(s);
3237 }
3238 });
3239 }
3240 else if (isFunction(source)) {
3241 if (cb) {
3242 // getter with cb
3243 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */, [
3244 instance && instance.proxy
3245 ]);
3246 }
3247 else {
3248 // no cb -> simple effect
3249 getter = () => {
3250 if (instance && instance.isUnmounted) {
3251 return;
3252 }
3253 if (cleanup) {
3254 cleanup();
3255 }
3256 return callWithErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
3257 };
3258 }
3259 }
3260 else {
3261 getter = NOOP;
3262 warnInvalidSource(source);
3263 }
3264 if (cb && deep) {
3265 const baseGetter = getter;
3266 getter = () => traverse(baseGetter());
3267 }
3268 let cleanup;
3269 const onInvalidate = (fn) => {
3270 cleanup = runner.options.onStop = () => {
3271 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
3272 };
3273 };
3274 let oldValue = isArray(source) ? [] : INITIAL_WATCHER_VALUE;
3275 const job = () => {
3276 if (!runner.active) {
3277 return;
3278 }
3279 if (cb) {
3280 // watch(source, cb)
3281 const newValue = runner();
3282 if (deep || forceTrigger || hasChanged(newValue, oldValue)) {
3283 // cleanup before running cb again
3284 if (cleanup) {
3285 cleanup();
3286 }
3287 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
3288 newValue,
3289 // pass undefined as the old value when it's changed for the first time
3290 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
3291 onInvalidate
3292 ]);
3293 oldValue = newValue;
3294 }
3295 }
3296 else {
3297 // watchEffect
3298 runner();
3299 }
3300 };
3301 // important: mark the job as a watcher callback so that scheduler knows
3302 // it is allowed to self-trigger (#1727)
3303 job.allowRecurse = !!cb;
3304 let scheduler;
3305 if (flush === 'sync') {
3306 scheduler = job;
3307 }
3308 else if (flush === 'post') {
3309 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3310 }
3311 else {
3312 // default: 'pre'
3313 scheduler = () => {
3314 if (!instance || instance.isMounted) {
3315 queuePreFlushCb(job);
3316 }
3317 else {
3318 // with 'pre' option, the first call must happen before
3319 // the component is mounted so it is called synchronously.
3320 job();
3321 }
3322 };
3323 }
3324 const runner = effect(getter, {
3325 lazy: true,
3326 onTrack,
3327 onTrigger,
3328 scheduler
3329 });
3330 recordInstanceBoundEffect(runner, instance);
3331 // initial run
3332 if (cb) {
3333 if (immediate) {
3334 job();
3335 }
3336 else {
3337 oldValue = runner();
3338 }
3339 }
3340 else if (flush === 'post') {
3341 queuePostRenderEffect(runner, instance && instance.suspense);
3342 }
3343 else {
3344 runner();
3345 }
3346 return () => {
3347 stop(runner);
3348 if (instance) {
3349 remove(instance.effects, runner);
3350 }
3351 };
3352 }
3353 // this.$watch
3354 function instanceWatch(source, cb, options) {
3355 const publicThis = this.proxy;
3356 const getter = isString(source)
3357 ? () => publicThis[source]
3358 : source.bind(publicThis);
3359 return doWatch(getter, cb.bind(publicThis), options, this);
3360 }
3361 function traverse(value, seen = new Set()) {
3362 if (!isObject(value) || seen.has(value)) {
3363 return value;
3364 }
3365 seen.add(value);
3366 if (isRef(value)) {
3367 traverse(value.value, seen);
3368 }
3369 else if (isArray(value)) {
3370 for (let i = 0; i < value.length; i++) {
3371 traverse(value[i], seen);
3372 }
3373 }
3374 else if (isSet(value) || isMap(value)) {
3375 value.forEach((v) => {
3376 traverse(v, seen);
3377 });
3378 }
3379 else {
3380 for (const key in value) {
3381 traverse(value[key], seen);
3382 }
3383 }
3384 return value;
3385 }
3386
3387 function useTransitionState() {
3388 const state = {
3389 isMounted: false,
3390 isLeaving: false,
3391 isUnmounting: false,
3392 leavingVNodes: new Map()
3393 };
3394 onMounted(() => {
3395 state.isMounted = true;
3396 });
3397 onBeforeUnmount(() => {
3398 state.isUnmounting = true;
3399 });
3400 return state;
3401 }
3402 const TransitionHookValidator = [Function, Array];
3403 const BaseTransitionImpl = {
3404 name: `BaseTransition`,
3405 props: {
3406 mode: String,
3407 appear: Boolean,
3408 persisted: Boolean,
3409 // enter
3410 onBeforeEnter: TransitionHookValidator,
3411 onEnter: TransitionHookValidator,
3412 onAfterEnter: TransitionHookValidator,
3413 onEnterCancelled: TransitionHookValidator,
3414 // leave
3415 onBeforeLeave: TransitionHookValidator,
3416 onLeave: TransitionHookValidator,
3417 onAfterLeave: TransitionHookValidator,
3418 onLeaveCancelled: TransitionHookValidator,
3419 // appear
3420 onBeforeAppear: TransitionHookValidator,
3421 onAppear: TransitionHookValidator,
3422 onAfterAppear: TransitionHookValidator,
3423 onAppearCancelled: TransitionHookValidator
3424 },
3425 setup(props, { slots }) {
3426 const instance = getCurrentInstance();
3427 const state = useTransitionState();
3428 let prevTransitionKey;
3429 return () => {
3430 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3431 if (!children || !children.length) {
3432 return;
3433 }
3434 // warn multiple elements
3435 if (children.length > 1) {
3436 warn('<transition> can only be used on a single element or component. Use ' +
3437 '<transition-group> for lists.');
3438 }
3439 // there's no need to track reactivity for these props so use the raw
3440 // props for a bit better perf
3441 const rawProps = toRaw(props);
3442 const { mode } = rawProps;
3443 // check mode
3444 if (mode && !['in-out', 'out-in', 'default'].includes(mode)) {
3445 warn(`invalid <transition> mode: ${mode}`);
3446 }
3447 // at this point children has a guaranteed length of 1.
3448 const child = children[0];
3449 if (state.isLeaving) {
3450 return emptyPlaceholder(child);
3451 }
3452 // in the case of <transition><keep-alive/></transition>, we need to
3453 // compare the type of the kept-alive children.
3454 const innerChild = getKeepAliveChild(child);
3455 if (!innerChild) {
3456 return emptyPlaceholder(child);
3457 }
3458 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3459 setTransitionHooks(innerChild, enterHooks);
3460 const oldChild = instance.subTree;
3461 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3462 let transitionKeyChanged = false;
3463 const { getTransitionKey } = innerChild.type;
3464 if (getTransitionKey) {
3465 const key = getTransitionKey();
3466 if (prevTransitionKey === undefined) {
3467 prevTransitionKey = key;
3468 }
3469 else if (key !== prevTransitionKey) {
3470 prevTransitionKey = key;
3471 transitionKeyChanged = true;
3472 }
3473 }
3474 // handle mode
3475 if (oldInnerChild &&
3476 oldInnerChild.type !== Comment &&
3477 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3478 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3479 // update old tree's hooks in case of dynamic transition
3480 setTransitionHooks(oldInnerChild, leavingHooks);
3481 // switching between different views
3482 if (mode === 'out-in') {
3483 state.isLeaving = true;
3484 // return placeholder node and queue update when leave finishes
3485 leavingHooks.afterLeave = () => {
3486 state.isLeaving = false;
3487 instance.update();
3488 };
3489 return emptyPlaceholder(child);
3490 }
3491 else if (mode === 'in-out') {
3492 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3493 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3494 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3495 // early removal callback
3496 el._leaveCb = () => {
3497 earlyRemove();
3498 el._leaveCb = undefined;
3499 delete enterHooks.delayedLeave;
3500 };
3501 enterHooks.delayedLeave = delayedLeave;
3502 };
3503 }
3504 }
3505 return child;
3506 };
3507 }
3508 };
3509 // export the public type for h/tsx inference
3510 // also to avoid inline import() in generated d.ts files
3511 const BaseTransition = BaseTransitionImpl;
3512 function getLeavingNodesForType(state, vnode) {
3513 const { leavingVNodes } = state;
3514 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3515 if (!leavingVNodesCache) {
3516 leavingVNodesCache = Object.create(null);
3517 leavingVNodes.set(vnode.type, leavingVNodesCache);
3518 }
3519 return leavingVNodesCache;
3520 }
3521 // The transition hooks are attached to the vnode as vnode.transition
3522 // and will be called at appropriate timing in the renderer.
3523 function resolveTransitionHooks(vnode, props, state, instance) {
3524 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3525 const key = String(vnode.key);
3526 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3527 const callHook = (hook, args) => {
3528 hook &&
3529 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3530 };
3531 const hooks = {
3532 mode,
3533 persisted,
3534 beforeEnter(el) {
3535 let hook = onBeforeEnter;
3536 if (!state.isMounted) {
3537 if (appear) {
3538 hook = onBeforeAppear || onBeforeEnter;
3539 }
3540 else {
3541 return;
3542 }
3543 }
3544 // for same element (v-show)
3545 if (el._leaveCb) {
3546 el._leaveCb(true /* cancelled */);
3547 }
3548 // for toggled element with same key (v-if)
3549 const leavingVNode = leavingVNodesCache[key];
3550 if (leavingVNode &&
3551 isSameVNodeType(vnode, leavingVNode) &&
3552 leavingVNode.el._leaveCb) {
3553 // force early removal (not cancelled)
3554 leavingVNode.el._leaveCb();
3555 }
3556 callHook(hook, [el]);
3557 },
3558 enter(el) {
3559 let hook = onEnter;
3560 let afterHook = onAfterEnter;
3561 let cancelHook = onEnterCancelled;
3562 if (!state.isMounted) {
3563 if (appear) {
3564 hook = onAppear || onEnter;
3565 afterHook = onAfterAppear || onAfterEnter;
3566 cancelHook = onAppearCancelled || onEnterCancelled;
3567 }
3568 else {
3569 return;
3570 }
3571 }
3572 let called = false;
3573 const done = (el._enterCb = (cancelled) => {
3574 if (called)
3575 return;
3576 called = true;
3577 if (cancelled) {
3578 callHook(cancelHook, [el]);
3579 }
3580 else {
3581 callHook(afterHook, [el]);
3582 }
3583 if (hooks.delayedLeave) {
3584 hooks.delayedLeave();
3585 }
3586 el._enterCb = undefined;
3587 });
3588 if (hook) {
3589 hook(el, done);
3590 if (hook.length <= 1) {
3591 done();
3592 }
3593 }
3594 else {
3595 done();
3596 }
3597 },
3598 leave(el, remove) {
3599 const key = String(vnode.key);
3600 if (el._enterCb) {
3601 el._enterCb(true /* cancelled */);
3602 }
3603 if (state.isUnmounting) {
3604 return remove();
3605 }
3606 callHook(onBeforeLeave, [el]);
3607 let called = false;
3608 const done = (el._leaveCb = (cancelled) => {
3609 if (called)
3610 return;
3611 called = true;
3612 remove();
3613 if (cancelled) {
3614 callHook(onLeaveCancelled, [el]);
3615 }
3616 else {
3617 callHook(onAfterLeave, [el]);
3618 }
3619 el._leaveCb = undefined;
3620 if (leavingVNodesCache[key] === vnode) {
3621 delete leavingVNodesCache[key];
3622 }
3623 });
3624 leavingVNodesCache[key] = vnode;
3625 if (onLeave) {
3626 onLeave(el, done);
3627 if (onLeave.length <= 1) {
3628 done();
3629 }
3630 }
3631 else {
3632 done();
3633 }
3634 },
3635 clone(vnode) {
3636 return resolveTransitionHooks(vnode, props, state, instance);
3637 }
3638 };
3639 return hooks;
3640 }
3641 // the placeholder really only handles one special case: KeepAlive
3642 // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3643 // placeholder with empty content to avoid the KeepAlive instance from being
3644 // unmounted.
3645 function emptyPlaceholder(vnode) {
3646 if (isKeepAlive(vnode)) {
3647 vnode = cloneVNode(vnode);
3648 vnode.children = null;
3649 return vnode;
3650 }
3651 }
3652 function getKeepAliveChild(vnode) {
3653 return isKeepAlive(vnode)
3654 ? vnode.children
3655 ? vnode.children[0]
3656 : undefined
3657 : vnode;
3658 }
3659 function setTransitionHooks(vnode, hooks) {
3660 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3661 setTransitionHooks(vnode.component.subTree, hooks);
3662 }
3663 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3664 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3665 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3666 }
3667 else {
3668 vnode.transition = hooks;
3669 }
3670 }
3671 function getTransitionRawChildren(children, keepComment = false) {
3672 let ret = [];
3673 let keyedFragmentCount = 0;
3674 for (let i = 0; i < children.length; i++) {
3675 const child = children[i];
3676 // handle fragment children case, e.g. v-for
3677 if (child.type === Fragment) {
3678 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3679 keyedFragmentCount++;
3680 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3681 }
3682 // comment placeholders should be skipped, e.g. v-if
3683 else if (keepComment || child.type !== Comment) {
3684 ret.push(child);
3685 }
3686 }
3687 // #1126 if a transition children list contains multiple sub fragments, these
3688 // fragments will be merged into a flat children array. Since each v-for
3689 // fragment may contain different static bindings inside, we need to de-op
3690 // these children to force full diffs to ensure correct behavior.
3691 if (keyedFragmentCount > 1) {
3692 for (let i = 0; i < ret.length; i++) {
3693 ret[i].patchFlag = -2 /* BAIL */;
3694 }
3695 }
3696 return ret;
3697 }
3698
3699 const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3700 const KeepAliveImpl = {
3701 name: `KeepAlive`,
3702 // Marker for special handling inside the renderer. We are not using a ===
3703 // check directly on KeepAlive in the renderer, because importing it directly
3704 // would prevent it from being tree-shaken.
3705 __isKeepAlive: true,
3706 props: {
3707 include: [String, RegExp, Array],
3708 exclude: [String, RegExp, Array],
3709 max: [String, Number]
3710 },
3711 setup(props, { slots }) {
3712 const cache = new Map();
3713 const keys = new Set();
3714 let current = null;
3715 const instance = getCurrentInstance();
3716 const parentSuspense = instance.suspense;
3717 // KeepAlive communicates with the instantiated renderer via the
3718 // ctx where the renderer passes in its internals,
3719 // and the KeepAlive instance exposes activate/deactivate implementations.
3720 // The whole point of this is to avoid importing KeepAlive directly in the
3721 // renderer to facilitate tree-shaking.
3722 const sharedContext = instance.ctx;
3723 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3724 const storageContainer = createElement('div');
3725 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3726 const instance = vnode.component;
3727 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3728 // in case props have changed
3729 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, optimized);
3730 queuePostRenderEffect(() => {
3731 instance.isDeactivated = false;
3732 if (instance.a) {
3733 invokeArrayFns(instance.a);
3734 }
3735 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3736 if (vnodeHook) {
3737 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3738 }
3739 }, parentSuspense);
3740 };
3741 sharedContext.deactivate = (vnode) => {
3742 const instance = vnode.component;
3743 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3744 queuePostRenderEffect(() => {
3745 if (instance.da) {
3746 invokeArrayFns(instance.da);
3747 }
3748 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3749 if (vnodeHook) {
3750 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3751 }
3752 instance.isDeactivated = true;
3753 }, parentSuspense);
3754 };
3755 function unmount(vnode) {
3756 // reset the shapeFlag so it can be properly unmounted
3757 resetShapeFlag(vnode);
3758 _unmount(vnode, instance, parentSuspense);
3759 }
3760 function pruneCache(filter) {
3761 cache.forEach((vnode, key) => {
3762 const name = getComponentName(vnode.type);
3763 if (name && (!filter || !filter(name))) {
3764 pruneCacheEntry(key);
3765 }
3766 });
3767 }
3768 function pruneCacheEntry(key) {
3769 const cached = cache.get(key);
3770 if (!current || cached.type !== current.type) {
3771 unmount(cached);
3772 }
3773 else if (current) {
3774 // current active instance should no longer be kept-alive.
3775 // we can't unmount it now but it might be later, so reset its flag now.
3776 resetShapeFlag(current);
3777 }
3778 cache.delete(key);
3779 keys.delete(key);
3780 }
3781 // prune cache on include/exclude prop change
3782 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3783 include && pruneCache(name => matches(include, name));
3784 exclude && pruneCache(name => !matches(exclude, name));
3785 },
3786 // prune post-render after `current` has been updated
3787 { flush: 'post', deep: true });
3788 // cache sub tree after render
3789 let pendingCacheKey = null;
3790 const cacheSubtree = () => {
3791 // fix #1621, the pendingCacheKey could be 0
3792 if (pendingCacheKey != null) {
3793 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3794 }
3795 };
3796 onMounted(cacheSubtree);
3797 onUpdated(cacheSubtree);
3798 onBeforeUnmount(() => {
3799 cache.forEach(cached => {
3800 const { subTree, suspense } = instance;
3801 const vnode = getInnerChild(subTree);
3802 if (cached.type === vnode.type) {
3803 // current instance will be unmounted as part of keep-alive's unmount
3804 resetShapeFlag(vnode);
3805 // but invoke its deactivated hook here
3806 const da = vnode.component.da;
3807 da && queuePostRenderEffect(da, suspense);
3808 return;
3809 }
3810 unmount(cached);
3811 });
3812 });
3813 return () => {
3814 pendingCacheKey = null;
3815 if (!slots.default) {
3816 return null;
3817 }
3818 const children = slots.default();
3819 const rawVNode = children[0];
3820 if (children.length > 1) {
3821 {
3822 warn(`KeepAlive should contain exactly one component child.`);
3823 }
3824 current = null;
3825 return children;
3826 }
3827 else if (!isVNode(rawVNode) ||
3828 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
3829 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
3830 current = null;
3831 return rawVNode;
3832 }
3833 let vnode = getInnerChild(rawVNode);
3834 const comp = vnode.type;
3835 const name = getComponentName(comp);
3836 const { include, exclude, max } = props;
3837 if ((include && (!name || !matches(include, name))) ||
3838 (exclude && name && matches(exclude, name))) {
3839 current = vnode;
3840 return rawVNode;
3841 }
3842 const key = vnode.key == null ? comp : vnode.key;
3843 const cachedVNode = cache.get(key);
3844 // clone vnode if it's reused because we are going to mutate it
3845 if (vnode.el) {
3846 vnode = cloneVNode(vnode);
3847 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
3848 rawVNode.ssContent = vnode;
3849 }
3850 }
3851 // #1513 it's possible for the returned vnode to be cloned due to attr
3852 // fallthrough or scopeId, so the vnode here may not be the final vnode
3853 // that is mounted. Instead of caching it directly, we store the pending
3854 // key and cache `instance.subTree` (the normalized vnode) in
3855 // beforeMount/beforeUpdate hooks.
3856 pendingCacheKey = key;
3857 if (cachedVNode) {
3858 // copy over mounted state
3859 vnode.el = cachedVNode.el;
3860 vnode.component = cachedVNode.component;
3861 if (vnode.transition) {
3862 // recursively update transition hooks on subTree
3863 setTransitionHooks(vnode, vnode.transition);
3864 }
3865 // avoid vnode being mounted as fresh
3866 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
3867 // make this key the freshest
3868 keys.delete(key);
3869 keys.add(key);
3870 }
3871 else {
3872 keys.add(key);
3873 // prune oldest entry
3874 if (max && keys.size > parseInt(max, 10)) {
3875 pruneCacheEntry(keys.values().next().value);
3876 }
3877 }
3878 // avoid vnode being unmounted
3879 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3880 current = vnode;
3881 return rawVNode;
3882 };
3883 }
3884 };
3885 // export the public type for h/tsx inference
3886 // also to avoid inline import() in generated d.ts files
3887 const KeepAlive = KeepAliveImpl;
3888 function matches(pattern, name) {
3889 if (isArray(pattern)) {
3890 return pattern.some((p) => matches(p, name));
3891 }
3892 else if (isString(pattern)) {
3893 return pattern.split(',').indexOf(name) > -1;
3894 }
3895 else if (pattern.test) {
3896 return pattern.test(name);
3897 }
3898 /* istanbul ignore next */
3899 return false;
3900 }
3901 function onActivated(hook, target) {
3902 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
3903 }
3904 function onDeactivated(hook, target) {
3905 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
3906 }
3907 function registerKeepAliveHook(hook, type, target = currentInstance) {
3908 // cache the deactivate branch check wrapper for injected hooks so the same
3909 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
3910 // deactivation check".
3911 const wrappedHook = hook.__wdc ||
3912 (hook.__wdc = () => {
3913 // only fire the hook if the target instance is NOT in a deactivated branch.
3914 let current = target;
3915 while (current) {
3916 if (current.isDeactivated) {
3917 return;
3918 }
3919 current = current.parent;
3920 }
3921 hook();
3922 });
3923 injectHook(type, wrappedHook, target);
3924 // In addition to registering it on the target instance, we walk up the parent
3925 // chain and register it on all ancestor instances that are keep-alive roots.
3926 // This avoids the need to walk the entire component tree when invoking these
3927 // hooks, and more importantly, avoids the need to track child components in
3928 // arrays.
3929 if (target) {
3930 let current = target.parent;
3931 while (current && current.parent) {
3932 if (isKeepAlive(current.parent.vnode)) {
3933 injectToKeepAliveRoot(wrappedHook, type, target, current);
3934 }
3935 current = current.parent;
3936 }
3937 }
3938 }
3939 function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
3940 // injectHook wraps the original for error handling, so make sure to remove
3941 // the wrapped version.
3942 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
3943 onUnmounted(() => {
3944 remove(keepAliveRoot[type], injected);
3945 }, target);
3946 }
3947 function resetShapeFlag(vnode) {
3948 let shapeFlag = vnode.shapeFlag;
3949 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
3950 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
3951 }
3952 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
3953 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
3954 }
3955 vnode.shapeFlag = shapeFlag;
3956 }
3957 function getInnerChild(vnode) {
3958 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
3959 }
3960
3961 const isInternalKey = (key) => key[0] === '_' || key === '$stable';
3962 const normalizeSlotValue = (value) => isArray(value)
3963 ? value.map(normalizeVNode)
3964 : [normalizeVNode(value)];
3965 const normalizeSlot = (key, rawSlot, ctx) => withCtx((props) => {
3966 if (currentInstance) {
3967 warn(`Slot "${key}" invoked outside of the render function: ` +
3968 `this will not track dependencies used in the slot. ` +
3969 `Invoke the slot function inside the render function instead.`);
3970 }
3971 return normalizeSlotValue(rawSlot(props));
3972 }, ctx);
3973 const normalizeObjectSlots = (rawSlots, slots) => {
3974 const ctx = rawSlots._ctx;
3975 for (const key in rawSlots) {
3976 if (isInternalKey(key))
3977 continue;
3978 const value = rawSlots[key];
3979 if (isFunction(value)) {
3980 slots[key] = normalizeSlot(key, value, ctx);
3981 }
3982 else if (value != null) {
3983 {
3984 warn(`Non-function value encountered for slot "${key}". ` +
3985 `Prefer function slots for better performance.`);
3986 }
3987 const normalized = normalizeSlotValue(value);
3988 slots[key] = () => normalized;
3989 }
3990 }
3991 };
3992 const normalizeVNodeSlots = (instance, children) => {
3993 if (!isKeepAlive(instance.vnode)) {
3994 warn(`Non-function value encountered for default slot. ` +
3995 `Prefer function slots for better performance.`);
3996 }
3997 const normalized = normalizeSlotValue(children);
3998 instance.slots.default = () => normalized;
3999 };
4000 const initSlots = (instance, children) => {
4001 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4002 const type = children._;
4003 if (type) {
4004 instance.slots = children;
4005 // make compiler marker non-enumerable
4006 def(children, '_', type);
4007 }
4008 else {
4009 normalizeObjectSlots(children, (instance.slots = {}));
4010 }
4011 }
4012 else {
4013 instance.slots = {};
4014 if (children) {
4015 normalizeVNodeSlots(instance, children);
4016 }
4017 }
4018 def(instance.slots, InternalObjectKey, 1);
4019 };
4020 const updateSlots = (instance, children) => {
4021 const { vnode, slots } = instance;
4022 let needDeletionCheck = true;
4023 let deletionComparisonTarget = EMPTY_OBJ;
4024 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
4025 const type = children._;
4026 if (type) {
4027 // compiled slots.
4028 if (isHmrUpdating) {
4029 // Parent was HMR updated so slot content may have changed.
4030 // force update slots and mark instance for hmr as well
4031 extend(slots, children);
4032 }
4033 else if (type === 1 /* STABLE */) {
4034 // compiled AND stable.
4035 // no need to update, and skip stale slots removal.
4036 needDeletionCheck = false;
4037 }
4038 else {
4039 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
4040 // normalization.
4041 extend(slots, children);
4042 }
4043 }
4044 else {
4045 needDeletionCheck = !children.$stable;
4046 normalizeObjectSlots(children, slots);
4047 }
4048 deletionComparisonTarget = children;
4049 }
4050 else if (children) {
4051 // non slot object children (direct value) passed to a component
4052 normalizeVNodeSlots(instance, children);
4053 deletionComparisonTarget = { default: 1 };
4054 }
4055 // delete stale slots
4056 if (needDeletionCheck) {
4057 for (const key in slots) {
4058 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
4059 delete slots[key];
4060 }
4061 }
4062 }
4063 };
4064
4065 /**
4066 Runtime helper for applying directives to a vnode. Example usage:
4067
4068 const comp = resolveComponent('comp')
4069 const foo = resolveDirective('foo')
4070 const bar = resolveDirective('bar')
4071
4072 return withDirectives(h(comp), [
4073 [foo, this.x],
4074 [bar, this.y]
4075 ])
4076 */
4077 const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
4078 function validateDirectiveName(name) {
4079 if (isBuiltInDirective(name)) {
4080 warn('Do not use built-in directive ids as custom directive id: ' + name);
4081 }
4082 }
4083 /**
4084 * Adds directives to a VNode.
4085 */
4086 function withDirectives(vnode, directives) {
4087 const internalInstance = currentRenderingInstance;
4088 if (internalInstance === null) {
4089 warn(`withDirectives can only be used inside render functions.`);
4090 return vnode;
4091 }
4092 const instance = internalInstance.proxy;
4093 const bindings = vnode.dirs || (vnode.dirs = []);
4094 for (let i = 0; i < directives.length; i++) {
4095 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
4096 if (isFunction(dir)) {
4097 dir = {
4098 mounted: dir,
4099 updated: dir
4100 };
4101 }
4102 bindings.push({
4103 dir,
4104 instance,
4105 value,
4106 oldValue: void 0,
4107 arg,
4108 modifiers
4109 });
4110 }
4111 return vnode;
4112 }
4113 function invokeDirectiveHook(vnode, prevVNode, instance, name) {
4114 const bindings = vnode.dirs;
4115 const oldBindings = prevVNode && prevVNode.dirs;
4116 for (let i = 0; i < bindings.length; i++) {
4117 const binding = bindings[i];
4118 if (oldBindings) {
4119 binding.oldValue = oldBindings[i].value;
4120 }
4121 const hook = binding.dir[name];
4122 if (hook) {
4123 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
4124 vnode.el,
4125 binding,
4126 vnode,
4127 prevVNode
4128 ]);
4129 }
4130 }
4131 }
4132
4133 function createAppContext() {
4134 return {
4135 app: null,
4136 config: {
4137 isNativeTag: NO,
4138 performance: false,
4139 globalProperties: {},
4140 optionMergeStrategies: {},
4141 isCustomElement: NO,
4142 errorHandler: undefined,
4143 warnHandler: undefined
4144 },
4145 mixins: [],
4146 components: {},
4147 directives: {},
4148 provides: Object.create(null)
4149 };
4150 }
4151 let uid$1 = 0;
4152 function createAppAPI(render, hydrate) {
4153 return function createApp(rootComponent, rootProps = null) {
4154 if (rootProps != null && !isObject(rootProps)) {
4155 warn(`root props passed to app.mount() must be an object.`);
4156 rootProps = null;
4157 }
4158 const context = createAppContext();
4159 const installedPlugins = new Set();
4160 let isMounted = false;
4161 const app = (context.app = {
4162 _uid: uid$1++,
4163 _component: rootComponent,
4164 _props: rootProps,
4165 _container: null,
4166 _context: context,
4167 version,
4168 get config() {
4169 return context.config;
4170 },
4171 set config(v) {
4172 {
4173 warn(`app.config cannot be replaced. Modify individual options instead.`);
4174 }
4175 },
4176 use(plugin, ...options) {
4177 if (installedPlugins.has(plugin)) {
4178 warn(`Plugin has already been applied to target app.`);
4179 }
4180 else if (plugin && isFunction(plugin.install)) {
4181 installedPlugins.add(plugin);
4182 plugin.install(app, ...options);
4183 }
4184 else if (isFunction(plugin)) {
4185 installedPlugins.add(plugin);
4186 plugin(app, ...options);
4187 }
4188 else {
4189 warn(`A plugin must either be a function or an object with an "install" ` +
4190 `function.`);
4191 }
4192 return app;
4193 },
4194 mixin(mixin) {
4195 {
4196 if (!context.mixins.includes(mixin)) {
4197 context.mixins.push(mixin);
4198 // global mixin with props/emits de-optimizes props/emits
4199 // normalization caching.
4200 if (mixin.props || mixin.emits) {
4201 context.deopt = true;
4202 }
4203 }
4204 else {
4205 warn('Mixin has already been applied to target app' +
4206 (mixin.name ? `: ${mixin.name}` : ''));
4207 }
4208 }
4209 return app;
4210 },
4211 component(name, component) {
4212 {
4213 validateComponentName(name, context.config);
4214 }
4215 if (!component) {
4216 return context.components[name];
4217 }
4218 if (context.components[name]) {
4219 warn(`Component "${name}" has already been registered in target app.`);
4220 }
4221 context.components[name] = component;
4222 return app;
4223 },
4224 directive(name, directive) {
4225 {
4226 validateDirectiveName(name);
4227 }
4228 if (!directive) {
4229 return context.directives[name];
4230 }
4231 if (context.directives[name]) {
4232 warn(`Directive "${name}" has already been registered in target app.`);
4233 }
4234 context.directives[name] = directive;
4235 return app;
4236 },
4237 mount(rootContainer, isHydrate) {
4238 if (!isMounted) {
4239 const vnode = createVNode(rootComponent, rootProps);
4240 // store app context on the root VNode.
4241 // this will be set on the root instance on initial mount.
4242 vnode.appContext = context;
4243 // HMR root reload
4244 {
4245 context.reload = () => {
4246 render(cloneVNode(vnode), rootContainer);
4247 };
4248 }
4249 if (isHydrate && hydrate) {
4250 hydrate(vnode, rootContainer);
4251 }
4252 else {
4253 render(vnode, rootContainer);
4254 }
4255 isMounted = true;
4256 app._container = rootContainer;
4257 rootContainer.__vue_app__ = app;
4258 {
4259 devtoolsInitApp(app, version);
4260 }
4261 return vnode.component.proxy;
4262 }
4263 else {
4264 warn(`App has already been mounted.\n` +
4265 `If you want to remount the same app, move your app creation logic ` +
4266 `into a factory function and create fresh app instances for each ` +
4267 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
4268 }
4269 },
4270 unmount() {
4271 if (isMounted) {
4272 render(null, app._container);
4273 {
4274 devtoolsUnmountApp(app);
4275 }
4276 delete app._container.__vue_app__;
4277 }
4278 else {
4279 warn(`Cannot unmount an app that is not mounted.`);
4280 }
4281 },
4282 provide(key, value) {
4283 if (key in context.provides) {
4284 warn(`App already provides property with key "${String(key)}". ` +
4285 `It will be overwritten with the new value.`);
4286 }
4287 // TypeScript doesn't allow symbols as index type
4288 // https://github.com/Microsoft/TypeScript/issues/24587
4289 context.provides[key] = value;
4290 return app;
4291 }
4292 });
4293 return app;
4294 };
4295 }
4296
4297 let hasMismatch = false;
4298 const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
4299 const isComment = (node) => node.nodeType === 8 /* COMMENT */;
4300 // Note: hydration is DOM-specific
4301 // But we have to place it in core due to tight coupling with core - splitting
4302 // it out creates a ton of unnecessary complexity.
4303 // Hydration also depends on some renderer internal logic which needs to be
4304 // passed in via arguments.
4305 function createHydrationFunctions(rendererInternals) {
4306 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
4307 const hydrate = (vnode, container) => {
4308 if (!container.hasChildNodes()) {
4309 warn(`Attempting to hydrate existing markup but container is empty. ` +
4310 `Performing full mount instead.`);
4311 patch(null, vnode, container);
4312 return;
4313 }
4314 hasMismatch = false;
4315 hydrateNode(container.firstChild, vnode, null, null);
4316 flushPostFlushCbs();
4317 if (hasMismatch && !false) {
4318 // this error should show up in production
4319 console.error(`Hydration completed but contains mismatches.`);
4320 }
4321 };
4322 const hydrateNode = (node, vnode, parentComponent, parentSuspense, optimized = false) => {
4323 const isFragmentStart = isComment(node) && node.data === '[';
4324 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, isFragmentStart);
4325 const { type, ref, shapeFlag } = vnode;
4326 const domType = node.nodeType;
4327 vnode.el = node;
4328 let nextNode = null;
4329 switch (type) {
4330 case Text:
4331 if (domType !== 3 /* TEXT */) {
4332 nextNode = onMismatch();
4333 }
4334 else {
4335 if (node.data !== vnode.children) {
4336 hasMismatch = true;
4337 warn(`Hydration text mismatch:` +
4338 `\n- Client: ${JSON.stringify(node.data)}` +
4339 `\n- Server: ${JSON.stringify(vnode.children)}`);
4340 node.data = vnode.children;
4341 }
4342 nextNode = nextSibling(node);
4343 }
4344 break;
4345 case Comment:
4346 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
4347 nextNode = onMismatch();
4348 }
4349 else {
4350 nextNode = nextSibling(node);
4351 }
4352 break;
4353 case Static:
4354 if (domType !== 1 /* ELEMENT */) {
4355 nextNode = onMismatch();
4356 }
4357 else {
4358 // determine anchor, adopt content
4359 nextNode = node;
4360 // if the static vnode has its content stripped during build,
4361 // adopt it from the server-rendered HTML.
4362 const needToAdoptContent = !vnode.children.length;
4363 for (let i = 0; i < vnode.staticCount; i++) {
4364 if (needToAdoptContent)
4365 vnode.children += nextNode.outerHTML;
4366 if (i === vnode.staticCount - 1) {
4367 vnode.anchor = nextNode;
4368 }
4369 nextNode = nextSibling(nextNode);
4370 }
4371 return nextNode;
4372 }
4373 break;
4374 case Fragment:
4375 if (!isFragmentStart) {
4376 nextNode = onMismatch();
4377 }
4378 else {
4379 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, optimized);
4380 }
4381 break;
4382 default:
4383 if (shapeFlag & 1 /* ELEMENT */) {
4384 if (domType !== 1 /* ELEMENT */ ||
4385 vnode.type !== node.tagName.toLowerCase()) {
4386 nextNode = onMismatch();
4387 }
4388 else {
4389 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, optimized);
4390 }
4391 }
4392 else if (shapeFlag & 6 /* COMPONENT */) {
4393 // when setting up the render effect, if the initial vnode already
4394 // has .el set, the component will perform hydration instead of mount
4395 // on its sub-tree.
4396 const container = parentNode(node);
4397 const hydrateComponent = () => {
4398 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
4399 };
4400 // async component
4401 const loadAsync = vnode.type.__asyncLoader;
4402 if (loadAsync) {
4403 loadAsync().then(hydrateComponent);
4404 }
4405 else {
4406 hydrateComponent();
4407 }
4408 // component may be async, so in the case of fragments we cannot rely
4409 // on component's rendered output to determine the end of the fragment
4410 // instead, we do a lookahead to find the end anchor node.
4411 nextNode = isFragmentStart
4412 ? locateClosingAsyncAnchor(node)
4413 : nextSibling(node);
4414 }
4415 else if (shapeFlag & 64 /* TELEPORT */) {
4416 if (domType !== 8 /* COMMENT */) {
4417 nextNode = onMismatch();
4418 }
4419 else {
4420 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, optimized, rendererInternals, hydrateChildren);
4421 }
4422 }
4423 else if (shapeFlag & 128 /* SUSPENSE */) {
4424 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), optimized, rendererInternals, hydrateNode);
4425 }
4426 else {
4427 warn('Invalid HostVNode type:', type, `(${typeof type})`);
4428 }
4429 }
4430 if (ref != null) {
4431 setRef(ref, null, parentSuspense, vnode);
4432 }
4433 return nextNode;
4434 };
4435 const hydrateElement = (el, vnode, parentComponent, parentSuspense, optimized) => {
4436 optimized = optimized || !!vnode.dynamicChildren;
4437 const { props, patchFlag, shapeFlag, dirs } = vnode;
4438 // skip props & children if this is hoisted static nodes
4439 if (patchFlag !== -1 /* HOISTED */) {
4440 if (dirs) {
4441 invokeDirectiveHook(vnode, null, parentComponent, 'created');
4442 }
4443 // props
4444 if (props) {
4445 if (!optimized ||
4446 (patchFlag & 16 /* FULL_PROPS */ ||
4447 patchFlag & 32 /* HYDRATE_EVENTS */)) {
4448 for (const key in props) {
4449 if (!isReservedProp(key) && isOn(key)) {
4450 patchProp(el, key, null, props[key]);
4451 }
4452 }
4453 }
4454 else if (props.onClick) {
4455 // Fast path for click listeners (which is most often) to avoid
4456 // iterating through props.
4457 patchProp(el, 'onClick', null, props.onClick);
4458 }
4459 }
4460 // vnode / directive hooks
4461 let vnodeHooks;
4462 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
4463 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
4464 }
4465 if (dirs) {
4466 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
4467 }
4468 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
4469 queueEffectWithSuspense(() => {
4470 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
4471 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
4472 }, parentSuspense);
4473 }
4474 // children
4475 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
4476 // skip if element has innerHTML / textContent
4477 !(props && (props.innerHTML || props.textContent))) {
4478 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, optimized);
4479 let hasWarned = false;
4480 while (next) {
4481 hasMismatch = true;
4482 if (!hasWarned) {
4483 warn(`Hydration children mismatch in <${vnode.type}>: ` +
4484 `server rendered element contains more child nodes than client vdom.`);
4485 hasWarned = true;
4486 }
4487 // The SSRed DOM contains more nodes than it should. Remove them.
4488 const cur = next;
4489 next = next.nextSibling;
4490 remove(cur);
4491 }
4492 }
4493 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
4494 if (el.textContent !== vnode.children) {
4495 hasMismatch = true;
4496 warn(`Hydration text content mismatch in <${vnode.type}>:\n` +
4497 `- Client: ${el.textContent}\n` +
4498 `- Server: ${vnode.children}`);
4499 el.textContent = vnode.children;
4500 }
4501 }
4502 }
4503 return el.nextSibling;
4504 };
4505 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, optimized) => {
4506 optimized = optimized || !!parentVNode.dynamicChildren;
4507 const children = parentVNode.children;
4508 const l = children.length;
4509 let hasWarned = false;
4510 for (let i = 0; i < l; i++) {
4511 const vnode = optimized
4512 ? children[i]
4513 : (children[i] = normalizeVNode(children[i]));
4514 if (node) {
4515 node = hydrateNode(node, vnode, parentComponent, parentSuspense, optimized);
4516 }
4517 else {
4518 hasMismatch = true;
4519 if (!hasWarned) {
4520 warn(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
4521 `server rendered element contains fewer child nodes than client vdom.`);
4522 hasWarned = true;
4523 }
4524 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
4525 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container));
4526 }
4527 }
4528 return node;
4529 };
4530 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, optimized) => {
4531 const container = parentNode(node);
4532 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, optimized);
4533 if (next && isComment(next) && next.data === ']') {
4534 return nextSibling((vnode.anchor = next));
4535 }
4536 else {
4537 // fragment didn't hydrate successfully, since we didn't get a end anchor
4538 // back. This should have led to node/children mismatch warnings.
4539 hasMismatch = true;
4540 // since the anchor is missing, we need to create one and insert it
4541 insert((vnode.anchor = createComment(`]`)), container, next);
4542 return next;
4543 }
4544 };
4545 const handleMismatch = (node, vnode, parentComponent, parentSuspense, isFragment) => {
4546 hasMismatch = true;
4547 warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
4548 ? `(text)`
4549 : isComment(node) && node.data === '['
4550 ? `(start of fragment)`
4551 : ``);
4552 vnode.el = null;
4553 if (isFragment) {
4554 // remove excessive fragment nodes
4555 const end = locateClosingAsyncAnchor(node);
4556 while (true) {
4557 const next = nextSibling(node);
4558 if (next && next !== end) {
4559 remove(next);
4560 }
4561 else {
4562 break;
4563 }
4564 }
4565 }
4566 const next = nextSibling(node);
4567 const container = parentNode(node);
4568 remove(node);
4569 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container));
4570 return next;
4571 };
4572 const locateClosingAsyncAnchor = (node) => {
4573 let match = 0;
4574 while (node) {
4575 node = nextSibling(node);
4576 if (node && isComment(node)) {
4577 if (node.data === '[')
4578 match++;
4579 if (node.data === ']') {
4580 if (match === 0) {
4581 return nextSibling(node);
4582 }
4583 else {
4584 match--;
4585 }
4586 }
4587 }
4588 }
4589 return node;
4590 };
4591 return [hydrate, hydrateNode];
4592 }
4593
4594 let supported;
4595 let perf;
4596 function startMeasure(instance, type) {
4597 if (instance.appContext.config.performance && isSupported()) {
4598 perf.mark(`vue-${type}-${instance.uid}`);
4599 }
4600 }
4601 function endMeasure(instance, type) {
4602 if (instance.appContext.config.performance && isSupported()) {
4603 const startTag = `vue-${type}-${instance.uid}`;
4604 const endTag = startTag + `:end`;
4605 perf.mark(endTag);
4606 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
4607 perf.clearMarks(startTag);
4608 perf.clearMarks(endTag);
4609 }
4610 }
4611 function isSupported() {
4612 if (supported !== undefined) {
4613 return supported;
4614 }
4615 /* eslint-disable no-restricted-globals */
4616 if (typeof window !== 'undefined' && window.performance) {
4617 supported = true;
4618 perf = window.performance;
4619 }
4620 else {
4621 supported = false;
4622 }
4623 /* eslint-enable no-restricted-globals */
4624 return supported;
4625 }
4626
4627 // implementation, close to no-op
4628 function defineComponent(options) {
4629 return isFunction(options) ? { setup: options, name: options.name } : options;
4630 }
4631
4632 const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
4633 function defineAsyncComponent(source) {
4634 if (isFunction(source)) {
4635 source = { loader: source };
4636 }
4637 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
4638 suspensible = true, onError: userOnError } = source;
4639 let pendingRequest = null;
4640 let resolvedComp;
4641 let retries = 0;
4642 const retry = () => {
4643 retries++;
4644 pendingRequest = null;
4645 return load();
4646 };
4647 const load = () => {
4648 let thisRequest;
4649 return (pendingRequest ||
4650 (thisRequest = pendingRequest = loader()
4651 .catch(err => {
4652 err = err instanceof Error ? err : new Error(String(err));
4653 if (userOnError) {
4654 return new Promise((resolve, reject) => {
4655 const userRetry = () => resolve(retry());
4656 const userFail = () => reject(err);
4657 userOnError(err, userRetry, userFail, retries + 1);
4658 });
4659 }
4660 else {
4661 throw err;
4662 }
4663 })
4664 .then((comp) => {
4665 if (thisRequest !== pendingRequest && pendingRequest) {
4666 return pendingRequest;
4667 }
4668 if (!comp) {
4669 warn(`Async component loader resolved to undefined. ` +
4670 `If you are using retry(), make sure to return its return value.`);
4671 }
4672 // interop module default
4673 if (comp &&
4674 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
4675 comp = comp.default;
4676 }
4677 if (comp && !isObject(comp) && !isFunction(comp)) {
4678 throw new Error(`Invalid async component load result: ${comp}`);
4679 }
4680 resolvedComp = comp;
4681 return comp;
4682 })));
4683 };
4684 return defineComponent({
4685 __asyncLoader: load,
4686 name: 'AsyncComponentWrapper',
4687 setup() {
4688 const instance = currentInstance;
4689 // already resolved
4690 if (resolvedComp) {
4691 return () => createInnerComp(resolvedComp, instance);
4692 }
4693 const onError = (err) => {
4694 pendingRequest = null;
4695 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
4696 };
4697 // suspense-controlled or SSR.
4698 if ((suspensible && instance.suspense) ||
4699 (false )) {
4700 return load()
4701 .then(comp => {
4702 return () => createInnerComp(comp, instance);
4703 })
4704 .catch(err => {
4705 onError(err);
4706 return () => errorComponent
4707 ? createVNode(errorComponent, {
4708 error: err
4709 })
4710 : null;
4711 });
4712 }
4713 const loaded = ref(false);
4714 const error = ref();
4715 const delayed = ref(!!delay);
4716 if (delay) {
4717 setTimeout(() => {
4718 delayed.value = false;
4719 }, delay);
4720 }
4721 if (timeout != null) {
4722 setTimeout(() => {
4723 if (!loaded.value && !error.value) {
4724 const err = new Error(`Async component timed out after ${timeout}ms.`);
4725 onError(err);
4726 error.value = err;
4727 }
4728 }, timeout);
4729 }
4730 load()
4731 .then(() => {
4732 loaded.value = true;
4733 })
4734 .catch(err => {
4735 onError(err);
4736 error.value = err;
4737 });
4738 return () => {
4739 if (loaded.value && resolvedComp) {
4740 return createInnerComp(resolvedComp, instance);
4741 }
4742 else if (error.value && errorComponent) {
4743 return createVNode(errorComponent, {
4744 error: error.value
4745 });
4746 }
4747 else if (loadingComponent && !delayed.value) {
4748 return createVNode(loadingComponent);
4749 }
4750 };
4751 }
4752 });
4753 }
4754 function createInnerComp(comp, { vnode: { ref, props, children } }) {
4755 const vnode = createVNode(comp, props, children);
4756 // ensure inner component inherits the async wrapper's ref owner
4757 vnode.ref = ref;
4758 return vnode;
4759 }
4760
4761 function createDevEffectOptions(instance) {
4762 return {
4763 scheduler: queueJob,
4764 allowRecurse: true,
4765 onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0,
4766 onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0
4767 };
4768 }
4769 const queuePostRenderEffect = queueEffectWithSuspense
4770 ;
4771 const setRef = (rawRef, oldRawRef, parentSuspense, vnode) => {
4772 if (isArray(rawRef)) {
4773 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode));
4774 return;
4775 }
4776 let value;
4777 if (!vnode || isAsyncWrapper(vnode)) {
4778 value = null;
4779 }
4780 else {
4781 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
4782 value = vnode.component.exposed || vnode.component.proxy;
4783 }
4784 else {
4785 value = vnode.el;
4786 }
4787 }
4788 const { i: owner, r: ref } = rawRef;
4789 if (!owner) {
4790 warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
4791 `A vnode with ref must be created inside the render function.`);
4792 return;
4793 }
4794 const oldRef = oldRawRef && oldRawRef.r;
4795 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
4796 const setupState = owner.setupState;
4797 // unset old ref
4798 if (oldRef != null && oldRef !== ref) {
4799 if (isString(oldRef)) {
4800 refs[oldRef] = null;
4801 if (hasOwn(setupState, oldRef)) {
4802 setupState[oldRef] = null;
4803 }
4804 }
4805 else if (isRef(oldRef)) {
4806 oldRef.value = null;
4807 }
4808 }
4809 if (isString(ref)) {
4810 const doSet = () => {
4811 refs[ref] = value;
4812 if (hasOwn(setupState, ref)) {
4813 setupState[ref] = value;
4814 }
4815 };
4816 // #1789: for non-null values, set them after render
4817 // null values means this is unmount and it should not overwrite another
4818 // ref with the same key
4819 if (value) {
4820 doSet.id = -1;
4821 queuePostRenderEffect(doSet, parentSuspense);
4822 }
4823 else {
4824 doSet();
4825 }
4826 }
4827 else if (isRef(ref)) {
4828 const doSet = () => {
4829 ref.value = value;
4830 };
4831 if (value) {
4832 doSet.id = -1;
4833 queuePostRenderEffect(doSet, parentSuspense);
4834 }
4835 else {
4836 doSet();
4837 }
4838 }
4839 else if (isFunction(ref)) {
4840 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
4841 }
4842 else {
4843 warn('Invalid template ref type:', value, `(${typeof value})`);
4844 }
4845 };
4846 /**
4847 * The createRenderer function accepts two generic arguments:
4848 * HostNode and HostElement, corresponding to Node and Element types in the
4849 * host environment. For example, for runtime-dom, HostNode would be the DOM
4850 * `Node` interface and HostElement would be the DOM `Element` interface.
4851 *
4852 * Custom renderers can pass in the platform specific types like this:
4853 *
4854 * ``` js
4855 * const { render, createApp } = createRenderer<Node, Element>({
4856 * patchProp,
4857 * ...nodeOps
4858 * })
4859 * ```
4860 */
4861 function createRenderer(options) {
4862 return baseCreateRenderer(options);
4863 }
4864 // Separate API for creating hydration-enabled renderer.
4865 // Hydration logic is only used when calling this function, making it
4866 // tree-shakable.
4867 function createHydrationRenderer(options) {
4868 return baseCreateRenderer(options, createHydrationFunctions);
4869 }
4870 // implementation
4871 function baseCreateRenderer(options, createHydrationFns) {
4872 {
4873 const target = getGlobalThis();
4874 target.__VUE__ = true;
4875 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
4876 }
4877 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;
4878 // Note: functions inside this closure should use `const xxx = () => {}`
4879 // style in order to prevent being inlined by minifiers.
4880 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, optimized = false) => {
4881 // patching & not same type, unmount old tree
4882 if (n1 && !isSameVNodeType(n1, n2)) {
4883 anchor = getNextHostNode(n1);
4884 unmount(n1, parentComponent, parentSuspense, true);
4885 n1 = null;
4886 }
4887 if (n2.patchFlag === -2 /* BAIL */) {
4888 optimized = false;
4889 n2.dynamicChildren = null;
4890 }
4891 const { type, ref, shapeFlag } = n2;
4892 switch (type) {
4893 case Text:
4894 processText(n1, n2, container, anchor);
4895 break;
4896 case Comment:
4897 processCommentNode(n1, n2, container, anchor);
4898 break;
4899 case Static:
4900 if (n1 == null) {
4901 mountStaticNode(n2, container, anchor, isSVG);
4902 }
4903 else {
4904 patchStaticNode(n1, n2, container, isSVG);
4905 }
4906 break;
4907 case Fragment:
4908 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
4909 break;
4910 default:
4911 if (shapeFlag & 1 /* ELEMENT */) {
4912 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
4913 }
4914 else if (shapeFlag & 6 /* COMPONENT */) {
4915 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
4916 }
4917 else if (shapeFlag & 64 /* TELEPORT */) {
4918 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals);
4919 }
4920 else if (shapeFlag & 128 /* SUSPENSE */) {
4921 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals);
4922 }
4923 else {
4924 warn('Invalid VNode type:', type, `(${typeof type})`);
4925 }
4926 }
4927 // set ref
4928 if (ref != null && parentComponent) {
4929 setRef(ref, n1 && n1.ref, parentSuspense, n2);
4930 }
4931 };
4932 const processText = (n1, n2, container, anchor) => {
4933 if (n1 == null) {
4934 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
4935 }
4936 else {
4937 const el = (n2.el = n1.el);
4938 if (n2.children !== n1.children) {
4939 hostSetText(el, n2.children);
4940 }
4941 }
4942 };
4943 const processCommentNode = (n1, n2, container, anchor) => {
4944 if (n1 == null) {
4945 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
4946 }
4947 else {
4948 // there's no support for dynamic comments
4949 n2.el = n1.el;
4950 }
4951 };
4952 const mountStaticNode = (n2, container, anchor, isSVG) => {
4953 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
4954 };
4955 /**
4956 * Dev / HMR only
4957 */
4958 const patchStaticNode = (n1, n2, container, isSVG) => {
4959 // static nodes are only patched during dev for HMR
4960 if (n2.children !== n1.children) {
4961 const anchor = hostNextSibling(n1.anchor);
4962 // remove existing
4963 removeStaticNode(n1);
4964 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
4965 }
4966 else {
4967 n2.el = n1.el;
4968 n2.anchor = n1.anchor;
4969 }
4970 };
4971 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
4972 let next;
4973 while (el && el !== anchor) {
4974 next = hostNextSibling(el);
4975 hostInsert(el, container, nextSibling);
4976 el = next;
4977 }
4978 hostInsert(anchor, container, nextSibling);
4979 };
4980 const removeStaticNode = ({ el, anchor }) => {
4981 let next;
4982 while (el && el !== anchor) {
4983 next = hostNextSibling(el);
4984 hostRemove(el);
4985 el = next;
4986 }
4987 hostRemove(anchor);
4988 };
4989 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
4990 isSVG = isSVG || n2.type === 'svg';
4991 if (n1 == null) {
4992 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
4993 }
4994 else {
4995 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, optimized);
4996 }
4997 };
4998 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
4999 let el;
5000 let vnodeHook;
5001 const { type, props, shapeFlag, transition, scopeId, patchFlag, dirs } = vnode;
5002 {
5003 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is);
5004 // mount children first, since some props may rely on child content
5005 // being already rendered, e.g. `<select value>`
5006 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5007 hostSetElementText(el, vnode.children);
5008 }
5009 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5010 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', optimized || !!vnode.dynamicChildren);
5011 }
5012 if (dirs) {
5013 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5014 }
5015 // props
5016 if (props) {
5017 for (const key in props) {
5018 if (!isReservedProp(key)) {
5019 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5020 }
5021 }
5022 if ((vnodeHook = props.onVnodeBeforeMount)) {
5023 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5024 }
5025 }
5026 // scopeId
5027 setScopeId(el, scopeId, vnode, parentComponent);
5028 }
5029 {
5030 Object.defineProperty(el, '__vnode', {
5031 value: vnode,
5032 enumerable: false
5033 });
5034 Object.defineProperty(el, '__vueParentComponent', {
5035 value: parentComponent,
5036 enumerable: false
5037 });
5038 }
5039 if (dirs) {
5040 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5041 }
5042 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
5043 // #1689 For inside suspense + suspense resolved case, just call it
5044 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
5045 transition &&
5046 !transition.persisted;
5047 if (needCallTransitionHooks) {
5048 transition.beforeEnter(el);
5049 }
5050 hostInsert(el, container, anchor);
5051 if ((vnodeHook = props && props.onVnodeMounted) ||
5052 needCallTransitionHooks ||
5053 dirs) {
5054 queuePostRenderEffect(() => {
5055 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5056 needCallTransitionHooks && transition.enter(el);
5057 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5058 }, parentSuspense);
5059 }
5060 };
5061 const setScopeId = (el, scopeId, vnode, parentComponent) => {
5062 if (scopeId) {
5063 hostSetScopeId(el, scopeId);
5064 }
5065 if (parentComponent) {
5066 const treeOwnerId = parentComponent.type.__scopeId;
5067 // vnode's own scopeId and the current patched component's scopeId is
5068 // different - this is a slot content node.
5069 if (treeOwnerId && treeOwnerId !== scopeId) {
5070 hostSetScopeId(el, treeOwnerId + '-s');
5071 }
5072 let subTree = parentComponent.subTree;
5073 if (subTree.type === Fragment) {
5074 subTree =
5075 filterSingleRoot(subTree.children) || subTree;
5076 }
5077 if (vnode === subTree) {
5078 setScopeId(el, parentComponent.vnode.scopeId, parentComponent.vnode, parentComponent.parent);
5079 }
5080 }
5081 };
5082 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, optimized, start = 0) => {
5083 for (let i = start; i < children.length; i++) {
5084 const child = (children[i] = optimized
5085 ? cloneIfMounted(children[i])
5086 : normalizeVNode(children[i]));
5087 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5088 }
5089 };
5090 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, optimized) => {
5091 const el = (n2.el = n1.el);
5092 let { patchFlag, dynamicChildren, dirs } = n2;
5093 // #1426 take the old vnode's patch flag into account since user may clone a
5094 // compiler-generated vnode, which de-opts to FULL_PROPS
5095 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
5096 const oldProps = n1.props || EMPTY_OBJ;
5097 const newProps = n2.props || EMPTY_OBJ;
5098 let vnodeHook;
5099 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
5100 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5101 }
5102 if (dirs) {
5103 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
5104 }
5105 if (isHmrUpdating) {
5106 // HMR updated, force full diff
5107 patchFlag = 0;
5108 optimized = false;
5109 dynamicChildren = null;
5110 }
5111 if (patchFlag > 0) {
5112 // the presence of a patchFlag means this element's render code was
5113 // generated by the compiler and can take the fast path.
5114 // in this path old node and new node are guaranteed to have the same shape
5115 // (i.e. at the exact same position in the source template)
5116 if (patchFlag & 16 /* FULL_PROPS */) {
5117 // element props contain dynamic keys, full diff needed
5118 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5119 }
5120 else {
5121 // class
5122 // this flag is matched when the element has dynamic class bindings.
5123 if (patchFlag & 2 /* CLASS */) {
5124 if (oldProps.class !== newProps.class) {
5125 hostPatchProp(el, 'class', null, newProps.class, isSVG);
5126 }
5127 }
5128 // style
5129 // this flag is matched when the element has dynamic style bindings
5130 if (patchFlag & 4 /* STYLE */) {
5131 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
5132 }
5133 // props
5134 // This flag is matched when the element has dynamic prop/attr bindings
5135 // other than class and style. The keys of dynamic prop/attrs are saved for
5136 // faster iteration.
5137 // Note dynamic keys like :[foo]="bar" will cause this optimization to
5138 // bail out and go through a full diff because we need to unset the old key
5139 if (patchFlag & 8 /* PROPS */) {
5140 // if the flag is present then dynamicProps must be non-null
5141 const propsToUpdate = n2.dynamicProps;
5142 for (let i = 0; i < propsToUpdate.length; i++) {
5143 const key = propsToUpdate[i];
5144 const prev = oldProps[key];
5145 const next = newProps[key];
5146 if (next !== prev ||
5147 (hostForcePatchProp && hostForcePatchProp(el, key))) {
5148 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
5149 }
5150 }
5151 }
5152 }
5153 // text
5154 // This flag is matched when the element has only dynamic text children.
5155 if (patchFlag & 1 /* TEXT */) {
5156 if (n1.children !== n2.children) {
5157 hostSetElementText(el, n2.children);
5158 }
5159 }
5160 }
5161 else if (!optimized && dynamicChildren == null) {
5162 // unoptimized, full diff
5163 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
5164 }
5165 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
5166 if (dynamicChildren) {
5167 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG);
5168 if (parentComponent && parentComponent.type.__hmrId) {
5169 traverseStaticChildren(n1, n2);
5170 }
5171 }
5172 else if (!optimized) {
5173 // full diff
5174 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG);
5175 }
5176 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
5177 queuePostRenderEffect(() => {
5178 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
5179 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
5180 }, parentSuspense);
5181 }
5182 };
5183 // The fast path for blocks.
5184 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG) => {
5185 for (let i = 0; i < newChildren.length; i++) {
5186 const oldVNode = oldChildren[i];
5187 const newVNode = newChildren[i];
5188 // Determine the container (parent element) for the patch.
5189 const container =
5190 // - In the case of a Fragment, we need to provide the actual parent
5191 // of the Fragment itself so it can move its children.
5192 oldVNode.type === Fragment ||
5193 // - In the case of different nodes, there is going to be a replacement
5194 // which also requires the correct parent container
5195 !isSameVNodeType(oldVNode, newVNode) ||
5196 // - In the case of a component, it could contain anything.
5197 oldVNode.shapeFlag & 6 /* COMPONENT */ ||
5198 oldVNode.shapeFlag & 64 /* TELEPORT */
5199 ? hostParentNode(oldVNode.el)
5200 : // In other cases, the parent container is not actually used so we
5201 // just pass the block element here to avoid a DOM parentNode call.
5202 fallbackContainer;
5203 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, true);
5204 }
5205 };
5206 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
5207 if (oldProps !== newProps) {
5208 for (const key in newProps) {
5209 // empty string is not valid prop
5210 if (isReservedProp(key))
5211 continue;
5212 const next = newProps[key];
5213 const prev = oldProps[key];
5214 if (next !== prev ||
5215 (hostForcePatchProp && hostForcePatchProp(el, key))) {
5216 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5217 }
5218 }
5219 if (oldProps !== EMPTY_OBJ) {
5220 for (const key in oldProps) {
5221 if (!isReservedProp(key) && !(key in newProps)) {
5222 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5223 }
5224 }
5225 }
5226 }
5227 };
5228 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
5229 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
5230 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
5231 let { patchFlag, dynamicChildren } = n2;
5232 if (patchFlag > 0) {
5233 optimized = true;
5234 }
5235 if (isHmrUpdating) {
5236 // HMR updated, force full diff
5237 patchFlag = 0;
5238 optimized = false;
5239 dynamicChildren = null;
5240 }
5241 if (n1 == null) {
5242 hostInsert(fragmentStartAnchor, container, anchor);
5243 hostInsert(fragmentEndAnchor, container, anchor);
5244 // a fragment can only have array children
5245 // since they are either generated by the compiler, or implicitly created
5246 // from arrays.
5247 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);
5248 }
5249 else {
5250 if (patchFlag > 0 &&
5251 patchFlag & 64 /* STABLE_FRAGMENT */ &&
5252 dynamicChildren &&
5253 // #2715 the previous fragment could've been a BAILed one as a result
5254 // of renderSlot() with no valid children
5255 n1.dynamicChildren) {
5256 // a stable fragment (template root or <template v-for>) doesn't need to
5257 // patch children order, but it may contain dynamicChildren.
5258 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG);
5259 if (parentComponent && parentComponent.type.__hmrId) {
5260 traverseStaticChildren(n1, n2);
5261 }
5262 else if (
5263 // #2080 if the stable fragment has a key, it's a <template v-for> that may
5264 // get moved around. Make sure all root level vnodes inherit el.
5265 // #2134 or if it's a component root, it may also get moved around
5266 // as the component is being moved.
5267 n2.key != null ||
5268 (parentComponent && n2 === parentComponent.subTree)) {
5269 traverseStaticChildren(n1, n2, true /* shallow */);
5270 }
5271 }
5272 else {
5273 // keyed / unkeyed, or manual fragments.
5274 // for keyed & unkeyed, since they are compiler generated from v-for,
5275 // each child is guaranteed to be a block so the fragment will never
5276 // have dynamicChildren.
5277 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, optimized);
5278 }
5279 }
5280 };
5281 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
5282 if (n1 == null) {
5283 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
5284 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
5285 }
5286 else {
5287 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5288 }
5289 }
5290 else {
5291 updateComponent(n1, n2, optimized);
5292 }
5293 };
5294 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
5295 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
5296 if (instance.type.__hmrId) {
5297 registerHMR(instance);
5298 }
5299 {
5300 pushWarningContext(initialVNode);
5301 startMeasure(instance, `mount`);
5302 }
5303 // inject renderer internals for keepAlive
5304 if (isKeepAlive(initialVNode)) {
5305 instance.ctx.renderer = internals;
5306 }
5307 // resolve props and slots for setup context
5308 {
5309 startMeasure(instance, `init`);
5310 }
5311 setupComponent(instance);
5312 {
5313 endMeasure(instance, `init`);
5314 }
5315 // setup() is async. This component relies on async logic to be resolved
5316 // before proceeding
5317 if (instance.asyncDep) {
5318 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
5319 // Give it a placeholder if this is not hydration
5320 // TODO handle self-defined fallback
5321 if (!initialVNode.el) {
5322 const placeholder = (instance.subTree = createVNode(Comment));
5323 processCommentNode(null, placeholder, container, anchor);
5324 }
5325 return;
5326 }
5327 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
5328 {
5329 popWarningContext();
5330 endMeasure(instance, `mount`);
5331 }
5332 };
5333 const updateComponent = (n1, n2, optimized) => {
5334 const instance = (n2.component = n1.component);
5335 if (shouldUpdateComponent(n1, n2, optimized)) {
5336 if (instance.asyncDep &&
5337 !instance.asyncResolved) {
5338 // async & still pending - just update props and slots
5339 // since the component's reactive effect for render isn't set-up yet
5340 {
5341 pushWarningContext(n2);
5342 }
5343 updateComponentPreRender(instance, n2, optimized);
5344 {
5345 popWarningContext();
5346 }
5347 return;
5348 }
5349 else {
5350 // normal update
5351 instance.next = n2;
5352 // in case the child component is also queued, remove it to avoid
5353 // double updating the same child component in the same flush.
5354 invalidateJob(instance.update);
5355 // instance.update is the reactive effect runner.
5356 instance.update();
5357 }
5358 }
5359 else {
5360 // no update needed. just copy over properties
5361 n2.component = n1.component;
5362 n2.el = n1.el;
5363 instance.vnode = n2;
5364 }
5365 };
5366 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
5367 // create reactive effect for rendering
5368 instance.update = effect(function componentEffect() {
5369 if (!instance.isMounted) {
5370 let vnodeHook;
5371 const { el, props } = initialVNode;
5372 const { bm, m, parent } = instance;
5373 // beforeMount hook
5374 if (bm) {
5375 invokeArrayFns(bm);
5376 }
5377 // onVnodeBeforeMount
5378 if ((vnodeHook = props && props.onVnodeBeforeMount)) {
5379 invokeVNodeHook(vnodeHook, parent, initialVNode);
5380 }
5381 // render
5382 {
5383 startMeasure(instance, `render`);
5384 }
5385 const subTree = (instance.subTree = renderComponentRoot(instance));
5386 {
5387 endMeasure(instance, `render`);
5388 }
5389 if (el && hydrateNode) {
5390 {
5391 startMeasure(instance, `hydrate`);
5392 }
5393 // vnode has adopted host node - perform hydration instead of mount.
5394 hydrateNode(initialVNode.el, subTree, instance, parentSuspense);
5395 {
5396 endMeasure(instance, `hydrate`);
5397 }
5398 }
5399 else {
5400 {
5401 startMeasure(instance, `patch`);
5402 }
5403 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
5404 {
5405 endMeasure(instance, `patch`);
5406 }
5407 initialVNode.el = subTree.el;
5408 }
5409 // mounted hook
5410 if (m) {
5411 queuePostRenderEffect(m, parentSuspense);
5412 }
5413 // onVnodeMounted
5414 if ((vnodeHook = props && props.onVnodeMounted)) {
5415 const scopedInitialVNode = initialVNode;
5416 queuePostRenderEffect(() => {
5417 invokeVNodeHook(vnodeHook, parent, scopedInitialVNode);
5418 }, parentSuspense);
5419 }
5420 // activated hook for keep-alive roots.
5421 // #1742 activated hook must be accessed after first render
5422 // since the hook may be injected by a child keep-alive
5423 const { a } = instance;
5424 if (a &&
5425 initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
5426 queuePostRenderEffect(a, parentSuspense);
5427 }
5428 instance.isMounted = true;
5429 {
5430 devtoolsComponentAdded(instance);
5431 }
5432 // #2458: deference mount-only object parameters to prevent memleaks
5433 initialVNode = container = anchor = null;
5434 }
5435 else {
5436 // updateComponent
5437 // This is triggered by mutation of component's own state (next: null)
5438 // OR parent calling processComponent (next: VNode)
5439 let { next, bu, u, parent, vnode } = instance;
5440 let originNext = next;
5441 let vnodeHook;
5442 {
5443 pushWarningContext(next || instance.vnode);
5444 }
5445 if (next) {
5446 next.el = vnode.el;
5447 updateComponentPreRender(instance, next, optimized);
5448 }
5449 else {
5450 next = vnode;
5451 }
5452 // beforeUpdate hook
5453 if (bu) {
5454 invokeArrayFns(bu);
5455 }
5456 // onVnodeBeforeUpdate
5457 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
5458 invokeVNodeHook(vnodeHook, parent, next, vnode);
5459 }
5460 // render
5461 {
5462 startMeasure(instance, `render`);
5463 }
5464 const nextTree = renderComponentRoot(instance);
5465 {
5466 endMeasure(instance, `render`);
5467 }
5468 const prevTree = instance.subTree;
5469 instance.subTree = nextTree;
5470 {
5471 startMeasure(instance, `patch`);
5472 }
5473 patch(prevTree, nextTree,
5474 // parent may have changed if it's in a teleport
5475 hostParentNode(prevTree.el),
5476 // anchor may have changed if it's in a fragment
5477 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
5478 {
5479 endMeasure(instance, `patch`);
5480 }
5481 next.el = nextTree.el;
5482 if (originNext === null) {
5483 // self-triggered update. In case of HOC, update parent component
5484 // vnode el. HOC is indicated by parent instance's subTree pointing
5485 // to child component's vnode
5486 updateHOCHostEl(instance, nextTree.el);
5487 }
5488 // updated hook
5489 if (u) {
5490 queuePostRenderEffect(u, parentSuspense);
5491 }
5492 // onVnodeUpdated
5493 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
5494 queuePostRenderEffect(() => {
5495 invokeVNodeHook(vnodeHook, parent, next, vnode);
5496 }, parentSuspense);
5497 }
5498 {
5499 devtoolsComponentUpdated(instance);
5500 }
5501 {
5502 popWarningContext();
5503 }
5504 }
5505 }, createDevEffectOptions(instance) );
5506 };
5507 const updateComponentPreRender = (instance, nextVNode, optimized) => {
5508 nextVNode.component = instance;
5509 const prevProps = instance.vnode.props;
5510 instance.vnode = nextVNode;
5511 instance.next = null;
5512 updateProps(instance, nextVNode.props, prevProps, optimized);
5513 updateSlots(instance, nextVNode.children);
5514 // props update may have triggered pre-flush watchers.
5515 // flush them before the render update.
5516 flushPreFlushCbs(undefined, instance.update);
5517 };
5518 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized = false) => {
5519 const c1 = n1 && n1.children;
5520 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
5521 const c2 = n2.children;
5522 const { patchFlag, shapeFlag } = n2;
5523 // fast path
5524 if (patchFlag > 0) {
5525 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
5526 // this could be either fully-keyed or mixed (some keyed some not)
5527 // presence of patchFlag means children are guaranteed to be arrays
5528 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5529 return;
5530 }
5531 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
5532 // unkeyed
5533 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5534 return;
5535 }
5536 }
5537 // children has 3 possibilities: text, array or no children.
5538 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5539 // text children fast path
5540 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
5541 unmountChildren(c1, parentComponent, parentSuspense);
5542 }
5543 if (c2 !== c1) {
5544 hostSetElementText(container, c2);
5545 }
5546 }
5547 else {
5548 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
5549 // prev children was array
5550 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5551 // two arrays, cannot assume anything, do full diff
5552 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5553 }
5554 else {
5555 // no new children, just unmount old
5556 unmountChildren(c1, parentComponent, parentSuspense, true);
5557 }
5558 }
5559 else {
5560 // prev children was text OR null
5561 // new children is array OR null
5562 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
5563 hostSetElementText(container, '');
5564 }
5565 // mount new if array
5566 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5567 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
5568 }
5569 }
5570 }
5571 };
5572 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
5573 c1 = c1 || EMPTY_ARR;
5574 c2 = c2 || EMPTY_ARR;
5575 const oldLength = c1.length;
5576 const newLength = c2.length;
5577 const commonLength = Math.min(oldLength, newLength);
5578 let i;
5579 for (i = 0; i < commonLength; i++) {
5580 const nextChild = (c2[i] = optimized
5581 ? cloneIfMounted(c2[i])
5582 : normalizeVNode(c2[i]));
5583 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, optimized);
5584 }
5585 if (oldLength > newLength) {
5586 // remove old
5587 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
5588 }
5589 else {
5590 // mount new
5591 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, commonLength);
5592 }
5593 };
5594 // can be all-keyed or mixed
5595 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, optimized) => {
5596 let i = 0;
5597 const l2 = c2.length;
5598 let e1 = c1.length - 1; // prev ending index
5599 let e2 = l2 - 1; // next ending index
5600 // 1. sync from start
5601 // (a b) c
5602 // (a b) d e
5603 while (i <= e1 && i <= e2) {
5604 const n1 = c1[i];
5605 const n2 = (c2[i] = optimized
5606 ? cloneIfMounted(c2[i])
5607 : normalizeVNode(c2[i]));
5608 if (isSameVNodeType(n1, n2)) {
5609 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, optimized);
5610 }
5611 else {
5612 break;
5613 }
5614 i++;
5615 }
5616 // 2. sync from end
5617 // a (b c)
5618 // d e (b c)
5619 while (i <= e1 && i <= e2) {
5620 const n1 = c1[e1];
5621 const n2 = (c2[e2] = optimized
5622 ? cloneIfMounted(c2[e2])
5623 : normalizeVNode(c2[e2]));
5624 if (isSameVNodeType(n1, n2)) {
5625 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, optimized);
5626 }
5627 else {
5628 break;
5629 }
5630 e1--;
5631 e2--;
5632 }
5633 // 3. common sequence + mount
5634 // (a b)
5635 // (a b) c
5636 // i = 2, e1 = 1, e2 = 2
5637 // (a b)
5638 // c (a b)
5639 // i = 0, e1 = -1, e2 = 0
5640 if (i > e1) {
5641 if (i <= e2) {
5642 const nextPos = e2 + 1;
5643 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
5644 while (i <= e2) {
5645 patch(null, (c2[i] = optimized
5646 ? cloneIfMounted(c2[i])
5647 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG);
5648 i++;
5649 }
5650 }
5651 }
5652 // 4. common sequence + unmount
5653 // (a b) c
5654 // (a b)
5655 // i = 2, e1 = 2, e2 = 1
5656 // a (b c)
5657 // (b c)
5658 // i = 0, e1 = 0, e2 = -1
5659 else if (i > e2) {
5660 while (i <= e1) {
5661 unmount(c1[i], parentComponent, parentSuspense, true);
5662 i++;
5663 }
5664 }
5665 // 5. unknown sequence
5666 // [i ... e1 + 1]: a b [c d e] f g
5667 // [i ... e2 + 1]: a b [e d c h] f g
5668 // i = 2, e1 = 4, e2 = 5
5669 else {
5670 const s1 = i; // prev starting index
5671 const s2 = i; // next starting index
5672 // 5.1 build key:index map for newChildren
5673 const keyToNewIndexMap = new Map();
5674 for (i = s2; i <= e2; i++) {
5675 const nextChild = (c2[i] = optimized
5676 ? cloneIfMounted(c2[i])
5677 : normalizeVNode(c2[i]));
5678 if (nextChild.key != null) {
5679 if (keyToNewIndexMap.has(nextChild.key)) {
5680 warn(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
5681 }
5682 keyToNewIndexMap.set(nextChild.key, i);
5683 }
5684 }
5685 // 5.2 loop through old children left to be patched and try to patch
5686 // matching nodes & remove nodes that are no longer present
5687 let j;
5688 let patched = 0;
5689 const toBePatched = e2 - s2 + 1;
5690 let moved = false;
5691 // used to track whether any node has moved
5692 let maxNewIndexSoFar = 0;
5693 // works as Map<newIndex, oldIndex>
5694 // Note that oldIndex is offset by +1
5695 // and oldIndex = 0 is a special value indicating the new node has
5696 // no corresponding old node.
5697 // used for determining longest stable subsequence
5698 const newIndexToOldIndexMap = new Array(toBePatched);
5699 for (i = 0; i < toBePatched; i++)
5700 newIndexToOldIndexMap[i] = 0;
5701 for (i = s1; i <= e1; i++) {
5702 const prevChild = c1[i];
5703 if (patched >= toBePatched) {
5704 // all new children have been patched so this can only be a removal
5705 unmount(prevChild, parentComponent, parentSuspense, true);
5706 continue;
5707 }
5708 let newIndex;
5709 if (prevChild.key != null) {
5710 newIndex = keyToNewIndexMap.get(prevChild.key);
5711 }
5712 else {
5713 // key-less node, try to locate a key-less node of the same type
5714 for (j = s2; j <= e2; j++) {
5715 if (newIndexToOldIndexMap[j - s2] === 0 &&
5716 isSameVNodeType(prevChild, c2[j])) {
5717 newIndex = j;
5718 break;
5719 }
5720 }
5721 }
5722 if (newIndex === undefined) {
5723 unmount(prevChild, parentComponent, parentSuspense, true);
5724 }
5725 else {
5726 newIndexToOldIndexMap[newIndex - s2] = i + 1;
5727 if (newIndex >= maxNewIndexSoFar) {
5728 maxNewIndexSoFar = newIndex;
5729 }
5730 else {
5731 moved = true;
5732 }
5733 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, optimized);
5734 patched++;
5735 }
5736 }
5737 // 5.3 move and mount
5738 // generate longest stable subsequence only when nodes have moved
5739 const increasingNewIndexSequence = moved
5740 ? getSequence(newIndexToOldIndexMap)
5741 : EMPTY_ARR;
5742 j = increasingNewIndexSequence.length - 1;
5743 // looping backwards so that we can use last patched node as anchor
5744 for (i = toBePatched - 1; i >= 0; i--) {
5745 const nextIndex = s2 + i;
5746 const nextChild = c2[nextIndex];
5747 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
5748 if (newIndexToOldIndexMap[i] === 0) {
5749 // mount new
5750 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG);
5751 }
5752 else if (moved) {
5753 // move if:
5754 // There is no stable subsequence (e.g. a reverse)
5755 // OR current node is not among the stable sequence
5756 if (j < 0 || i !== increasingNewIndexSequence[j]) {
5757 move(nextChild, container, anchor, 2 /* REORDER */);
5758 }
5759 else {
5760 j--;
5761 }
5762 }
5763 }
5764 }
5765 };
5766 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
5767 const { el, type, transition, children, shapeFlag } = vnode;
5768 if (shapeFlag & 6 /* COMPONENT */) {
5769 move(vnode.component.subTree, container, anchor, moveType);
5770 return;
5771 }
5772 if (shapeFlag & 128 /* SUSPENSE */) {
5773 vnode.suspense.move(container, anchor, moveType);
5774 return;
5775 }
5776 if (shapeFlag & 64 /* TELEPORT */) {
5777 type.move(vnode, container, anchor, internals);
5778 return;
5779 }
5780 if (type === Fragment) {
5781 hostInsert(el, container, anchor);
5782 for (let i = 0; i < children.length; i++) {
5783 move(children[i], container, anchor, moveType);
5784 }
5785 hostInsert(vnode.anchor, container, anchor);
5786 return;
5787 }
5788 if (type === Static) {
5789 moveStaticNode(vnode, container, anchor);
5790 return;
5791 }
5792 // single nodes
5793 const needTransition = moveType !== 2 /* REORDER */ &&
5794 shapeFlag & 1 /* ELEMENT */ &&
5795 transition;
5796 if (needTransition) {
5797 if (moveType === 0 /* ENTER */) {
5798 transition.beforeEnter(el);
5799 hostInsert(el, container, anchor);
5800 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
5801 }
5802 else {
5803 const { leave, delayLeave, afterLeave } = transition;
5804 const remove = () => hostInsert(el, container, anchor);
5805 const performLeave = () => {
5806 leave(el, () => {
5807 remove();
5808 afterLeave && afterLeave();
5809 });
5810 };
5811 if (delayLeave) {
5812 delayLeave(el, remove, performLeave);
5813 }
5814 else {
5815 performLeave();
5816 }
5817 }
5818 }
5819 else {
5820 hostInsert(el, container, anchor);
5821 }
5822 };
5823 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
5824 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
5825 // unset ref
5826 if (ref != null) {
5827 setRef(ref, null, parentSuspense, null);
5828 }
5829 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
5830 parentComponent.ctx.deactivate(vnode);
5831 return;
5832 }
5833 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
5834 let vnodeHook;
5835 if ((vnodeHook = props && props.onVnodeBeforeUnmount)) {
5836 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5837 }
5838 if (shapeFlag & 6 /* COMPONENT */) {
5839 unmountComponent(vnode.component, parentSuspense, doRemove);
5840 }
5841 else {
5842 if (shapeFlag & 128 /* SUSPENSE */) {
5843 vnode.suspense.unmount(parentSuspense, doRemove);
5844 return;
5845 }
5846 if (shouldInvokeDirs) {
5847 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
5848 }
5849 if (dynamicChildren &&
5850 // #1153: fast path should not be taken for non-stable (v-for) fragments
5851 (type !== Fragment ||
5852 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
5853 // fast path for block nodes: only need to unmount dynamic children.
5854 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
5855 }
5856 else if ((type === Fragment &&
5857 (patchFlag & 128 /* KEYED_FRAGMENT */ ||
5858 patchFlag & 256 /* UNKEYED_FRAGMENT */)) ||
5859 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
5860 unmountChildren(children, parentComponent, parentSuspense);
5861 }
5862 // an unmounted teleport should always remove its children if not disabled
5863 if (shapeFlag & 64 /* TELEPORT */ &&
5864 (doRemove || !isTeleportDisabled(vnode.props))) {
5865 vnode.type.remove(vnode, internals);
5866 }
5867 if (doRemove) {
5868 remove(vnode);
5869 }
5870 }
5871 if ((vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {
5872 queuePostRenderEffect(() => {
5873 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5874 shouldInvokeDirs &&
5875 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
5876 }, parentSuspense);
5877 }
5878 };
5879 const remove = vnode => {
5880 const { type, el, anchor, transition } = vnode;
5881 if (type === Fragment) {
5882 removeFragment(el, anchor);
5883 return;
5884 }
5885 if (type === Static) {
5886 removeStaticNode(vnode);
5887 return;
5888 }
5889 const performRemove = () => {
5890 hostRemove(el);
5891 if (transition && !transition.persisted && transition.afterLeave) {
5892 transition.afterLeave();
5893 }
5894 };
5895 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
5896 transition &&
5897 !transition.persisted) {
5898 const { leave, delayLeave } = transition;
5899 const performLeave = () => leave(el, performRemove);
5900 if (delayLeave) {
5901 delayLeave(vnode.el, performRemove, performLeave);
5902 }
5903 else {
5904 performLeave();
5905 }
5906 }
5907 else {
5908 performRemove();
5909 }
5910 };
5911 const removeFragment = (cur, end) => {
5912 // For fragments, directly remove all contained DOM nodes.
5913 // (fragment child nodes cannot have transition)
5914 let next;
5915 while (cur !== end) {
5916 next = hostNextSibling(cur);
5917 hostRemove(cur);
5918 cur = next;
5919 }
5920 hostRemove(end);
5921 };
5922 const unmountComponent = (instance, parentSuspense, doRemove) => {
5923 if (instance.type.__hmrId) {
5924 unregisterHMR(instance);
5925 }
5926 const { bum, effects, update, subTree, um } = instance;
5927 // beforeUnmount hook
5928 if (bum) {
5929 invokeArrayFns(bum);
5930 }
5931 if (effects) {
5932 for (let i = 0; i < effects.length; i++) {
5933 stop(effects[i]);
5934 }
5935 }
5936 // update may be null if a component is unmounted before its async
5937 // setup has resolved.
5938 if (update) {
5939 stop(update);
5940 unmount(subTree, instance, parentSuspense, doRemove);
5941 }
5942 // unmounted hook
5943 if (um) {
5944 queuePostRenderEffect(um, parentSuspense);
5945 }
5946 queuePostRenderEffect(() => {
5947 instance.isUnmounted = true;
5948 }, parentSuspense);
5949 // A component with async dep inside a pending suspense is unmounted before
5950 // its async dep resolves. This should remove the dep from the suspense, and
5951 // cause the suspense to resolve immediately if that was the last dep.
5952 if (parentSuspense &&
5953 parentSuspense.pendingBranch &&
5954 !parentSuspense.isUnmounted &&
5955 instance.asyncDep &&
5956 !instance.asyncResolved &&
5957 instance.suspenseId === parentSuspense.pendingId) {
5958 parentSuspense.deps--;
5959 if (parentSuspense.deps === 0) {
5960 parentSuspense.resolve();
5961 }
5962 }
5963 {
5964 devtoolsComponentRemoved(instance);
5965 }
5966 };
5967 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
5968 for (let i = start; i < children.length; i++) {
5969 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
5970 }
5971 };
5972 const getNextHostNode = vnode => {
5973 if (vnode.shapeFlag & 6 /* COMPONENT */) {
5974 return getNextHostNode(vnode.component.subTree);
5975 }
5976 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
5977 return vnode.suspense.next();
5978 }
5979 return hostNextSibling((vnode.anchor || vnode.el));
5980 };
5981 const render = (vnode, container) => {
5982 if (vnode == null) {
5983 if (container._vnode) {
5984 unmount(container._vnode, null, null, true);
5985 }
5986 }
5987 else {
5988 patch(container._vnode || null, vnode, container);
5989 }
5990 flushPostFlushCbs();
5991 container._vnode = vnode;
5992 };
5993 const internals = {
5994 p: patch,
5995 um: unmount,
5996 m: move,
5997 r: remove,
5998 mt: mountComponent,
5999 mc: mountChildren,
6000 pc: patchChildren,
6001 pbc: patchBlockChildren,
6002 n: getNextHostNode,
6003 o: options
6004 };
6005 let hydrate;
6006 let hydrateNode;
6007 if (createHydrationFns) {
6008 [hydrate, hydrateNode] = createHydrationFns(internals);
6009 }
6010 return {
6011 render,
6012 hydrate,
6013 createApp: createAppAPI(render, hydrate)
6014 };
6015 }
6016 function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
6017 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
6018 vnode,
6019 prevVNode
6020 ]);
6021 }
6022 /**
6023 * #1156
6024 * When a component is HMR-enabled, we need to make sure that all static nodes
6025 * inside a block also inherit the DOM element from the previous tree so that
6026 * HMR updates (which are full updates) can retrieve the element for patching.
6027 *
6028 * #2080
6029 * Inside keyed `template` fragment static children, if a fragment is moved,
6030 * the children will always moved so that need inherit el form previous nodes
6031 * to ensure correct moved position.
6032 */
6033 function traverseStaticChildren(n1, n2, shallow = false) {
6034 const ch1 = n1.children;
6035 const ch2 = n2.children;
6036 if (isArray(ch1) && isArray(ch2)) {
6037 for (let i = 0; i < ch1.length; i++) {
6038 // this is only called in the optimized path so array children are
6039 // guaranteed to be vnodes
6040 const c1 = ch1[i];
6041 let c2 = ch2[i];
6042 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
6043 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
6044 c2 = ch2[i] = cloneIfMounted(ch2[i]);
6045 c2.el = c1.el;
6046 }
6047 if (!shallow)
6048 traverseStaticChildren(c1, c2);
6049 }
6050 // also inherit for comment nodes, but not placeholders (e.g. v-if which
6051 // would have received .el during block patch)
6052 if (c2.type === Comment && !c2.el) {
6053 c2.el = c1.el;
6054 }
6055 }
6056 }
6057 }
6058 // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
6059 function getSequence(arr) {
6060 const p = arr.slice();
6061 const result = [0];
6062 let i, j, u, v, c;
6063 const len = arr.length;
6064 for (i = 0; i < len; i++) {
6065 const arrI = arr[i];
6066 if (arrI !== 0) {
6067 j = result[result.length - 1];
6068 if (arr[j] < arrI) {
6069 p[i] = j;
6070 result.push(i);
6071 continue;
6072 }
6073 u = 0;
6074 v = result.length - 1;
6075 while (u < v) {
6076 c = ((u + v) / 2) | 0;
6077 if (arr[result[c]] < arrI) {
6078 u = c + 1;
6079 }
6080 else {
6081 v = c;
6082 }
6083 }
6084 if (arrI < arr[result[u]]) {
6085 if (u > 0) {
6086 p[i] = result[u - 1];
6087 }
6088 result[u] = i;
6089 }
6090 }
6091 }
6092 u = result.length;
6093 v = result[u - 1];
6094 while (u-- > 0) {
6095 result[u] = v;
6096 v = p[v];
6097 }
6098 return result;
6099 }
6100
6101 const isTeleport = (type) => type.__isTeleport;
6102 const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
6103 const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
6104 const resolveTarget = (props, select) => {
6105 const targetSelector = props && props.to;
6106 if (isString(targetSelector)) {
6107 if (!select) {
6108 warn(`Current renderer does not support string target for Teleports. ` +
6109 `(missing querySelector renderer option)`);
6110 return null;
6111 }
6112 else {
6113 const target = select(targetSelector);
6114 if (!target) {
6115 warn(`Failed to locate Teleport target with selector "${targetSelector}". ` +
6116 `Note the target element must exist before the component is mounted - ` +
6117 `i.e. the target cannot be rendered by the component itself, and ` +
6118 `ideally should be outside of the entire Vue component tree.`);
6119 }
6120 return target;
6121 }
6122 }
6123 else {
6124 if (!targetSelector && !isTeleportDisabled(props)) {
6125 warn(`Invalid Teleport target: ${targetSelector}`);
6126 }
6127 return targetSelector;
6128 }
6129 };
6130 const TeleportImpl = {
6131 __isTeleport: true,
6132 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized, internals) {
6133 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
6134 const disabled = isTeleportDisabled(n2.props);
6135 const { shapeFlag, children } = n2;
6136 if (n1 == null) {
6137 // insert anchors in the main view
6138 const placeholder = (n2.el = createComment('teleport start')
6139 );
6140 const mainAnchor = (n2.anchor = createComment('teleport end')
6141 );
6142 insert(placeholder, container, anchor);
6143 insert(mainAnchor, container, anchor);
6144 const target = (n2.target = resolveTarget(n2.props, querySelector));
6145 const targetAnchor = (n2.targetAnchor = createText(''));
6146 if (target) {
6147 insert(targetAnchor, target);
6148 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
6149 isSVG = isSVG || isTargetSVG(target);
6150 }
6151 else if (!disabled) {
6152 warn('Invalid Teleport target on mount:', target, `(${typeof target})`);
6153 }
6154 const mount = (container, anchor) => {
6155 // Teleport *always* has Array children. This is enforced in both the
6156 // compiler and vnode children normalization.
6157 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6158 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
6159 }
6160 };
6161 if (disabled) {
6162 mount(container, mainAnchor);
6163 }
6164 else if (target) {
6165 mount(target, targetAnchor);
6166 }
6167 }
6168 else {
6169 // update content
6170 n2.el = n1.el;
6171 const mainAnchor = (n2.anchor = n1.anchor);
6172 const target = (n2.target = n1.target);
6173 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
6174 const wasDisabled = isTeleportDisabled(n1.props);
6175 const currentContainer = wasDisabled ? container : target;
6176 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
6177 isSVG = isSVG || isTargetSVG(target);
6178 if (n2.dynamicChildren) {
6179 // fast path when the teleport happens to be a block root
6180 patchBlockChildren(n1.dynamicChildren, n2.dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG);
6181 // even in block tree mode we need to make sure all root-level nodes
6182 // in the teleport inherit previous DOM references so that they can
6183 // be moved in future patches.
6184 traverseStaticChildren(n1, n2, true);
6185 }
6186 else if (!optimized) {
6187 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG);
6188 }
6189 if (disabled) {
6190 if (!wasDisabled) {
6191 // enabled -> disabled
6192 // move into main container
6193 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
6194 }
6195 }
6196 else {
6197 // target changed
6198 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
6199 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
6200 if (nextTarget) {
6201 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
6202 }
6203 else {
6204 warn('Invalid Teleport target on update:', target, `(${typeof target})`);
6205 }
6206 }
6207 else if (wasDisabled) {
6208 // disabled -> enabled
6209 // move into teleport target
6210 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
6211 }
6212 }
6213 }
6214 },
6215 remove(vnode, { r: remove, o: { remove: hostRemove } }) {
6216 const { shapeFlag, children, anchor } = vnode;
6217 hostRemove(anchor);
6218 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6219 for (let i = 0; i < children.length; i++) {
6220 remove(children[i]);
6221 }
6222 }
6223 },
6224 move: moveTeleport,
6225 hydrate: hydrateTeleport
6226 };
6227 function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
6228 // move target anchor if this is a target change.
6229 if (moveType === 0 /* TARGET_CHANGE */) {
6230 insert(vnode.targetAnchor, container, parentAnchor);
6231 }
6232 const { el, anchor, shapeFlag, children, props } = vnode;
6233 const isReorder = moveType === 2 /* REORDER */;
6234 // move main view anchor if this is a re-order.
6235 if (isReorder) {
6236 insert(el, container, parentAnchor);
6237 }
6238 // if this is a re-order and teleport is enabled (content is in target)
6239 // do not move children. So the opposite is: only move children if this
6240 // is not a reorder, or the teleport is disabled
6241 if (!isReorder || isTeleportDisabled(props)) {
6242 // Teleport has either Array children or no children.
6243 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6244 for (let i = 0; i < children.length; i++) {
6245 move(children[i], container, parentAnchor, 2 /* REORDER */);
6246 }
6247 }
6248 }
6249 // move main view anchor if this is a re-order.
6250 if (isReorder) {
6251 insert(anchor, container, parentAnchor);
6252 }
6253 }
6254 function hydrateTeleport(node, vnode, parentComponent, parentSuspense, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
6255 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
6256 if (target) {
6257 // if multiple teleports rendered to the same target element, we need to
6258 // pick up from where the last teleport finished instead of the first node
6259 const targetNode = target._lpa || target.firstChild;
6260 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
6261 if (isTeleportDisabled(vnode.props)) {
6262 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, optimized);
6263 vnode.targetAnchor = targetNode;
6264 }
6265 else {
6266 vnode.anchor = nextSibling(node);
6267 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, optimized);
6268 }
6269 target._lpa =
6270 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
6271 }
6272 }
6273 return vnode.anchor && nextSibling(vnode.anchor);
6274 }
6275 // Force-casted public typing for h and TSX props inference
6276 const Teleport = TeleportImpl;
6277
6278 const COMPONENTS = 'components';
6279 const DIRECTIVES = 'directives';
6280 /**
6281 * @private
6282 */
6283 function resolveComponent(name) {
6284 return resolveAsset(COMPONENTS, name) || name;
6285 }
6286 const NULL_DYNAMIC_COMPONENT = Symbol();
6287 /**
6288 * @private
6289 */
6290 function resolveDynamicComponent(component) {
6291 if (isString(component)) {
6292 return resolveAsset(COMPONENTS, component, false) || component;
6293 }
6294 else {
6295 // invalid types will fallthrough to createVNode and raise warning
6296 return (component || NULL_DYNAMIC_COMPONENT);
6297 }
6298 }
6299 /**
6300 * @private
6301 */
6302 function resolveDirective(name) {
6303 return resolveAsset(DIRECTIVES, name);
6304 }
6305 // implementation
6306 function resolveAsset(type, name, warnMissing = true) {
6307 const instance = currentRenderingInstance || currentInstance;
6308 if (instance) {
6309 const Component = instance.type;
6310 // self name has highest priority
6311 if (type === COMPONENTS) {
6312 // special self referencing call generated by compiler
6313 // inferred from SFC filename
6314 if (name === `_self`) {
6315 return Component;
6316 }
6317 const selfName = getComponentName(Component);
6318 if (selfName &&
6319 (selfName === name ||
6320 selfName === camelize(name) ||
6321 selfName === capitalize(camelize(name)))) {
6322 return Component;
6323 }
6324 }
6325 const res =
6326 // local registration
6327 // check instance[type] first for components with mixin or extends.
6328 resolve(instance[type] || Component[type], name) ||
6329 // global registration
6330 resolve(instance.appContext[type], name);
6331 if (warnMissing && !res) {
6332 warn(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
6333 }
6334 return res;
6335 }
6336 else {
6337 warn(`resolve${capitalize(type.slice(0, -1))} ` +
6338 `can only be used in render() or setup().`);
6339 }
6340 }
6341 function resolve(registry, name) {
6342 return (registry &&
6343 (registry[name] ||
6344 registry[camelize(name)] ||
6345 registry[capitalize(camelize(name))]));
6346 }
6347
6348 const Fragment = Symbol('Fragment' );
6349 const Text = Symbol('Text' );
6350 const Comment = Symbol('Comment' );
6351 const Static = Symbol('Static' );
6352 // Since v-if and v-for are the two possible ways node structure can dynamically
6353 // change, once we consider v-if branches and each v-for fragment a block, we
6354 // can divide a template into nested blocks, and within each block the node
6355 // structure would be stable. This allows us to skip most children diffing
6356 // and only worry about the dynamic nodes (indicated by patch flags).
6357 const blockStack = [];
6358 let currentBlock = null;
6359 /**
6360 * Open a block.
6361 * This must be called before `createBlock`. It cannot be part of `createBlock`
6362 * because the children of the block are evaluated before `createBlock` itself
6363 * is called. The generated code typically looks like this:
6364 *
6365 * ```js
6366 * function render() {
6367 * return (openBlock(),createBlock('div', null, [...]))
6368 * }
6369 * ```
6370 * disableTracking is true when creating a v-for fragment block, since a v-for
6371 * fragment always diffs its children.
6372 *
6373 * @private
6374 */
6375 function openBlock(disableTracking = false) {
6376 blockStack.push((currentBlock = disableTracking ? null : []));
6377 }
6378 function closeBlock() {
6379 blockStack.pop();
6380 currentBlock = blockStack[blockStack.length - 1] || null;
6381 }
6382 // Whether we should be tracking dynamic child nodes inside a block.
6383 // Only tracks when this value is > 0
6384 // We are not using a simple boolean because this value may need to be
6385 // incremented/decremented by nested usage of v-once (see below)
6386 let shouldTrack$1 = 1;
6387 /**
6388 * Block tracking sometimes needs to be disabled, for example during the
6389 * creation of a tree that needs to be cached by v-once. The compiler generates
6390 * code like this:
6391 *
6392 * ``` js
6393 * _cache[1] || (
6394 * setBlockTracking(-1),
6395 * _cache[1] = createVNode(...),
6396 * setBlockTracking(1),
6397 * _cache[1]
6398 * )
6399 * ```
6400 *
6401 * @private
6402 */
6403 function setBlockTracking(value) {
6404 shouldTrack$1 += value;
6405 }
6406 /**
6407 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
6408 * A block root keeps track of dynamic nodes within the block in the
6409 * `dynamicChildren` array.
6410 *
6411 * @private
6412 */
6413 function createBlock(type, props, children, patchFlag, dynamicProps) {
6414 const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */);
6415 // save current block children on the block vnode
6416 vnode.dynamicChildren = currentBlock || EMPTY_ARR;
6417 // close block
6418 closeBlock();
6419 // a block is always going to be patched, so track it as a child of its
6420 // parent block
6421 if (shouldTrack$1 > 0 && currentBlock) {
6422 currentBlock.push(vnode);
6423 }
6424 return vnode;
6425 }
6426 function isVNode(value) {
6427 return value ? value.__v_isVNode === true : false;
6428 }
6429 function isSameVNodeType(n1, n2) {
6430 if (n2.shapeFlag & 6 /* COMPONENT */ &&
6431 hmrDirtyComponents.has(n2.type)) {
6432 // HMR only: if the component has been hot-updated, force a reload.
6433 return false;
6434 }
6435 return n1.type === n2.type && n1.key === n2.key;
6436 }
6437 let vnodeArgsTransformer;
6438 /**
6439 * Internal API for registering an arguments transform for createVNode
6440 * used for creating stubs in the test-utils
6441 * It is *internal* but needs to be exposed for test-utils to pick up proper
6442 * typings
6443 */
6444 function transformVNodeArgs(transformer) {
6445 vnodeArgsTransformer = transformer;
6446 }
6447 const createVNodeWithArgsTransform = (...args) => {
6448 return _createVNode(...(vnodeArgsTransformer
6449 ? vnodeArgsTransformer(args, currentRenderingInstance)
6450 : args));
6451 };
6452 const InternalObjectKey = `__vInternal`;
6453 const normalizeKey = ({ key }) => key != null ? key : null;
6454 const normalizeRef = ({ ref }) => {
6455 return (ref != null
6456 ? isString(ref) || isRef(ref) || isFunction(ref)
6457 ? { i: currentRenderingInstance, r: ref }
6458 : ref
6459 : null);
6460 };
6461 const createVNode = (createVNodeWithArgsTransform
6462 );
6463 function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
6464 if (!type || type === NULL_DYNAMIC_COMPONENT) {
6465 if (!type) {
6466 warn(`Invalid vnode type when creating vnode: ${type}.`);
6467 }
6468 type = Comment;
6469 }
6470 if (isVNode(type)) {
6471 // createVNode receiving an existing vnode. This happens in cases like
6472 // <component :is="vnode"/>
6473 // #2078 make sure to merge refs during the clone instead of overwriting it
6474 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
6475 if (children) {
6476 normalizeChildren(cloned, children);
6477 }
6478 return cloned;
6479 }
6480 // class component normalization.
6481 if (isClassComponent(type)) {
6482 type = type.__vccOpts;
6483 }
6484 // class & style normalization.
6485 if (props) {
6486 // for reactive or proxy objects, we need to clone it to enable mutation.
6487 if (isProxy(props) || InternalObjectKey in props) {
6488 props = extend({}, props);
6489 }
6490 let { class: klass, style } = props;
6491 if (klass && !isString(klass)) {
6492 props.class = normalizeClass(klass);
6493 }
6494 if (isObject(style)) {
6495 // reactive state objects need to be cloned since they are likely to be
6496 // mutated
6497 if (isProxy(style) && !isArray(style)) {
6498 style = extend({}, style);
6499 }
6500 props.style = normalizeStyle(style);
6501 }
6502 }
6503 // encode the vnode type information into a bitmap
6504 const shapeFlag = isString(type)
6505 ? 1 /* ELEMENT */
6506 : isSuspense(type)
6507 ? 128 /* SUSPENSE */
6508 : isTeleport(type)
6509 ? 64 /* TELEPORT */
6510 : isObject(type)
6511 ? 4 /* STATEFUL_COMPONENT */
6512 : isFunction(type)
6513 ? 2 /* FUNCTIONAL_COMPONENT */
6514 : 0;
6515 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
6516 type = toRaw(type);
6517 warn(`Vue received a Component which was made a reactive object. This can ` +
6518 `lead to unnecessary performance overhead, and should be avoided by ` +
6519 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
6520 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
6521 }
6522 const vnode = {
6523 __v_isVNode: true,
6524 ["__v_skip" /* SKIP */]: true,
6525 type,
6526 props,
6527 key: props && normalizeKey(props),
6528 ref: props && normalizeRef(props),
6529 scopeId: currentScopeId,
6530 children: null,
6531 component: null,
6532 suspense: null,
6533 ssContent: null,
6534 ssFallback: null,
6535 dirs: null,
6536 transition: null,
6537 el: null,
6538 anchor: null,
6539 target: null,
6540 targetAnchor: null,
6541 staticCount: 0,
6542 shapeFlag,
6543 patchFlag,
6544 dynamicProps,
6545 dynamicChildren: null,
6546 appContext: null
6547 };
6548 // validate key
6549 if (vnode.key !== vnode.key) {
6550 warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
6551 }
6552 normalizeChildren(vnode, children);
6553 // normalize suspense children
6554 if (shapeFlag & 128 /* SUSPENSE */) {
6555 const { content, fallback } = normalizeSuspenseChildren(vnode);
6556 vnode.ssContent = content;
6557 vnode.ssFallback = fallback;
6558 }
6559 if (shouldTrack$1 > 0 &&
6560 // avoid a block node from tracking itself
6561 !isBlockNode &&
6562 // has current parent block
6563 currentBlock &&
6564 // presence of a patch flag indicates this node needs patching on updates.
6565 // component nodes also should always be patched, because even if the
6566 // component doesn't need to update, it needs to persist the instance on to
6567 // the next vnode so that it can be properly unmounted later.
6568 (patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
6569 // the EVENTS flag is only for hydration and if it is the only flag, the
6570 // vnode should not be considered dynamic due to handler caching.
6571 patchFlag !== 32 /* HYDRATE_EVENTS */) {
6572 currentBlock.push(vnode);
6573 }
6574 return vnode;
6575 }
6576 function cloneVNode(vnode, extraProps, mergeRef = false) {
6577 // This is intentionally NOT using spread or extend to avoid the runtime
6578 // key enumeration cost.
6579 const { props, ref, patchFlag, children } = vnode;
6580 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
6581 return {
6582 __v_isVNode: true,
6583 ["__v_skip" /* SKIP */]: true,
6584 type: vnode.type,
6585 props: mergedProps,
6586 key: mergedProps && normalizeKey(mergedProps),
6587 ref: extraProps && extraProps.ref
6588 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
6589 // if the vnode itself already has a ref, cloneVNode will need to merge
6590 // the refs so the single vnode can be set on multiple refs
6591 mergeRef && ref
6592 ? isArray(ref)
6593 ? ref.concat(normalizeRef(extraProps))
6594 : [ref, normalizeRef(extraProps)]
6595 : normalizeRef(extraProps)
6596 : ref,
6597 scopeId: vnode.scopeId,
6598 children: patchFlag === -1 /* HOISTED */ && isArray(children)
6599 ? children.map(deepCloneVNode)
6600 : children,
6601 target: vnode.target,
6602 targetAnchor: vnode.targetAnchor,
6603 staticCount: vnode.staticCount,
6604 shapeFlag: vnode.shapeFlag,
6605 // if the vnode is cloned with extra props, we can no longer assume its
6606 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
6607 // note: perserve flag for fragments since they use the flag for children
6608 // fast paths only.
6609 patchFlag: extraProps && vnode.type !== Fragment
6610 ? patchFlag === -1 // hoisted node
6611 ? 16 /* FULL_PROPS */
6612 : patchFlag | 16 /* FULL_PROPS */
6613 : patchFlag,
6614 dynamicProps: vnode.dynamicProps,
6615 dynamicChildren: vnode.dynamicChildren,
6616 appContext: vnode.appContext,
6617 dirs: vnode.dirs,
6618 transition: vnode.transition,
6619 // These should technically only be non-null on mounted VNodes. However,
6620 // they *should* be copied for kept-alive vnodes. So we just always copy
6621 // them since them being non-null during a mount doesn't affect the logic as
6622 // they will simply be overwritten.
6623 component: vnode.component,
6624 suspense: vnode.suspense,
6625 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
6626 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
6627 el: vnode.el,
6628 anchor: vnode.anchor
6629 };
6630 }
6631 /**
6632 * Dev only, for HMR of hoisted vnodes reused in v-for
6633 * https://github.com/vitejs/vite/issues/2022
6634 */
6635 function deepCloneVNode(vnode) {
6636 const cloned = cloneVNode(vnode);
6637 if (isArray(vnode.children)) {
6638 cloned.children = vnode.children.map(deepCloneVNode);
6639 }
6640 return cloned;
6641 }
6642 /**
6643 * @private
6644 */
6645 function createTextVNode(text = ' ', flag = 0) {
6646 return createVNode(Text, null, text, flag);
6647 }
6648 /**
6649 * @private
6650 */
6651 function createStaticVNode(content, numberOfNodes) {
6652 // A static vnode can contain multiple stringified elements, and the number
6653 // of elements is necessary for hydration.
6654 const vnode = createVNode(Static, null, content);
6655 vnode.staticCount = numberOfNodes;
6656 return vnode;
6657 }
6658 /**
6659 * @private
6660 */
6661 function createCommentVNode(text = '',
6662 // when used as the v-else branch, the comment node must be created as a
6663 // block to ensure correct updates.
6664 asBlock = false) {
6665 return asBlock
6666 ? (openBlock(), createBlock(Comment, null, text))
6667 : createVNode(Comment, null, text);
6668 }
6669 function normalizeVNode(child) {
6670 if (child == null || typeof child === 'boolean') {
6671 // empty placeholder
6672 return createVNode(Comment);
6673 }
6674 else if (isArray(child)) {
6675 // fragment
6676 return createVNode(Fragment, null, child);
6677 }
6678 else if (typeof child === 'object') {
6679 // already vnode, this should be the most common since compiled templates
6680 // always produce all-vnode children arrays
6681 return child.el === null ? child : cloneVNode(child);
6682 }
6683 else {
6684 // strings and numbers
6685 return createVNode(Text, null, String(child));
6686 }
6687 }
6688 // optimized normalization for template-compiled render fns
6689 function cloneIfMounted(child) {
6690 return child.el === null ? child : cloneVNode(child);
6691 }
6692 function normalizeChildren(vnode, children) {
6693 let type = 0;
6694 const { shapeFlag } = vnode;
6695 if (children == null) {
6696 children = null;
6697 }
6698 else if (isArray(children)) {
6699 type = 16 /* ARRAY_CHILDREN */;
6700 }
6701 else if (typeof children === 'object') {
6702 if (shapeFlag & 1 /* ELEMENT */ || shapeFlag & 64 /* TELEPORT */) {
6703 // Normalize slot to plain children for plain element and Teleport
6704 const slot = children.default;
6705 if (slot) {
6706 // _c marker is added by withCtx() indicating this is a compiled slot
6707 slot._c && setCompiledSlotRendering(1);
6708 normalizeChildren(vnode, slot());
6709 slot._c && setCompiledSlotRendering(-1);
6710 }
6711 return;
6712 }
6713 else {
6714 type = 32 /* SLOTS_CHILDREN */;
6715 const slotFlag = children._;
6716 if (!slotFlag && !(InternalObjectKey in children)) {
6717 children._ctx = currentRenderingInstance;
6718 }
6719 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
6720 // a child component receives forwarded slots from the parent.
6721 // its slot type is determined by its parent's slot type.
6722 if (currentRenderingInstance.vnode.patchFlag & 1024 /* DYNAMIC_SLOTS */) {
6723 children._ = 2 /* DYNAMIC */;
6724 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
6725 }
6726 else {
6727 children._ = 1 /* STABLE */;
6728 }
6729 }
6730 }
6731 }
6732 else if (isFunction(children)) {
6733 children = { default: children, _ctx: currentRenderingInstance };
6734 type = 32 /* SLOTS_CHILDREN */;
6735 }
6736 else {
6737 children = String(children);
6738 // force teleport children to array so it can be moved around
6739 if (shapeFlag & 64 /* TELEPORT */) {
6740 type = 16 /* ARRAY_CHILDREN */;
6741 children = [createTextVNode(children)];
6742 }
6743 else {
6744 type = 8 /* TEXT_CHILDREN */;
6745 }
6746 }
6747 vnode.children = children;
6748 vnode.shapeFlag |= type;
6749 }
6750 function mergeProps(...args) {
6751 const ret = extend({}, args[0]);
6752 for (let i = 1; i < args.length; i++) {
6753 const toMerge = args[i];
6754 for (const key in toMerge) {
6755 if (key === 'class') {
6756 if (ret.class !== toMerge.class) {
6757 ret.class = normalizeClass([ret.class, toMerge.class]);
6758 }
6759 }
6760 else if (key === 'style') {
6761 ret.style = normalizeStyle([ret.style, toMerge.style]);
6762 }
6763 else if (isOn(key)) {
6764 const existing = ret[key];
6765 const incoming = toMerge[key];
6766 if (existing !== incoming) {
6767 ret[key] = existing
6768 ? [].concat(existing, toMerge[key])
6769 : incoming;
6770 }
6771 }
6772 else if (key !== '') {
6773 ret[key] = toMerge[key];
6774 }
6775 }
6776 }
6777 return ret;
6778 }
6779
6780 function provide(key, value) {
6781 if (!currentInstance) {
6782 {
6783 warn(`provide() can only be used inside setup().`);
6784 }
6785 }
6786 else {
6787 let provides = currentInstance.provides;
6788 // by default an instance inherits its parent's provides object
6789 // but when it needs to provide values of its own, it creates its
6790 // own provides object using parent provides object as prototype.
6791 // this way in `inject` we can simply look up injections from direct
6792 // parent and let the prototype chain do the work.
6793 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
6794 if (parentProvides === provides) {
6795 provides = currentInstance.provides = Object.create(parentProvides);
6796 }
6797 // TS doesn't allow symbol as index type
6798 provides[key] = value;
6799 }
6800 }
6801 function inject(key, defaultValue, treatDefaultAsFactory = false) {
6802 // fallback to `currentRenderingInstance` so that this can be called in
6803 // a functional component
6804 const instance = currentInstance || currentRenderingInstance;
6805 if (instance) {
6806 // #2400
6807 // to support `app.use` plugins,
6808 // fallback to appContext's `provides` if the intance is at root
6809 const provides = instance.parent == null
6810 ? instance.vnode.appContext && instance.vnode.appContext.provides
6811 : instance.parent.provides;
6812 if (provides && key in provides) {
6813 // TS doesn't allow symbol as index type
6814 return provides[key];
6815 }
6816 else if (arguments.length > 1) {
6817 return treatDefaultAsFactory && isFunction(defaultValue)
6818 ? defaultValue()
6819 : defaultValue;
6820 }
6821 else {
6822 warn(`injection "${String(key)}" not found.`);
6823 }
6824 }
6825 else {
6826 warn(`inject() can only be used inside setup() or functional components.`);
6827 }
6828 }
6829
6830 function createDuplicateChecker() {
6831 const cache = Object.create(null);
6832 return (type, key) => {
6833 if (cache[key]) {
6834 warn(`${type} property "${key}" is already defined in ${cache[key]}.`);
6835 }
6836 else {
6837 cache[key] = type;
6838 }
6839 };
6840 }
6841 let isInBeforeCreate = false;
6842 function applyOptions(instance, options, deferredData = [], deferredWatch = [], deferredProvide = [], asMixin = false) {
6843 const {
6844 // composition
6845 mixins, extends: extendsOptions,
6846 // state
6847 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
6848 // assets
6849 components, directives,
6850 // lifecycle
6851 beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured,
6852 // public API
6853 expose } = options;
6854 const publicThis = instance.proxy;
6855 const ctx = instance.ctx;
6856 const globalMixins = instance.appContext.mixins;
6857 if (asMixin && render && instance.render === NOOP) {
6858 instance.render = render;
6859 }
6860 // applyOptions is called non-as-mixin once per instance
6861 if (!asMixin) {
6862 isInBeforeCreate = true;
6863 callSyncHook('beforeCreate', "bc" /* BEFORE_CREATE */, options, instance, globalMixins);
6864 isInBeforeCreate = false;
6865 // global mixins are applied first
6866 applyMixins(instance, globalMixins, deferredData, deferredWatch, deferredProvide);
6867 }
6868 // extending a base component...
6869 if (extendsOptions) {
6870 applyOptions(instance, extendsOptions, deferredData, deferredWatch, deferredProvide, true);
6871 }
6872 // local mixins
6873 if (mixins) {
6874 applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide);
6875 }
6876 const checkDuplicateProperties = createDuplicateChecker() ;
6877 {
6878 const [propsOptions] = instance.propsOptions;
6879 if (propsOptions) {
6880 for (const key in propsOptions) {
6881 checkDuplicateProperties("Props" /* PROPS */, key);
6882 }
6883 }
6884 }
6885 // options initialization order (to be consistent with Vue 2):
6886 // - props (already done outside of this function)
6887 // - inject
6888 // - methods
6889 // - data (deferred since it relies on `this` access)
6890 // - computed
6891 // - watch (deferred since it relies on `this` access)
6892 if (injectOptions) {
6893 if (isArray(injectOptions)) {
6894 for (let i = 0; i < injectOptions.length; i++) {
6895 const key = injectOptions[i];
6896 ctx[key] = inject(key);
6897 {
6898 checkDuplicateProperties("Inject" /* INJECT */, key);
6899 }
6900 }
6901 }
6902 else {
6903 for (const key in injectOptions) {
6904 const opt = injectOptions[key];
6905 if (isObject(opt)) {
6906 ctx[key] = inject(opt.from || key, opt.default, true /* treat default function as factory */);
6907 }
6908 else {
6909 ctx[key] = inject(opt);
6910 }
6911 {
6912 checkDuplicateProperties("Inject" /* INJECT */, key);
6913 }
6914 }
6915 }
6916 }
6917 if (methods) {
6918 for (const key in methods) {
6919 const methodHandler = methods[key];
6920 if (isFunction(methodHandler)) {
6921 // In dev mode, we use the `createRenderContext` function to define methods to the proxy target,
6922 // and those are read-only but reconfigurable, so it needs to be redefined here
6923 {
6924 Object.defineProperty(ctx, key, {
6925 value: methodHandler.bind(publicThis),
6926 configurable: true,
6927 enumerable: true,
6928 writable: true
6929 });
6930 }
6931 {
6932 checkDuplicateProperties("Methods" /* METHODS */, key);
6933 }
6934 }
6935 else {
6936 warn(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
6937 `Did you reference the function correctly?`);
6938 }
6939 }
6940 }
6941 if (!asMixin) {
6942 if (deferredData.length) {
6943 deferredData.forEach(dataFn => resolveData(instance, dataFn, publicThis));
6944 }
6945 if (dataOptions) {
6946 // @ts-ignore dataOptions is not fully type safe
6947 resolveData(instance, dataOptions, publicThis);
6948 }
6949 {
6950 const rawData = toRaw(instance.data);
6951 for (const key in rawData) {
6952 checkDuplicateProperties("Data" /* DATA */, key);
6953 // expose data on ctx during dev
6954 if (key[0] !== '$' && key[0] !== '_') {
6955 Object.defineProperty(ctx, key, {
6956 configurable: true,
6957 enumerable: true,
6958 get: () => rawData[key],
6959 set: NOOP
6960 });
6961 }
6962 }
6963 }
6964 }
6965 else if (dataOptions) {
6966 deferredData.push(dataOptions);
6967 }
6968 if (computedOptions) {
6969 for (const key in computedOptions) {
6970 const opt = computedOptions[key];
6971 const get = isFunction(opt)
6972 ? opt.bind(publicThis, publicThis)
6973 : isFunction(opt.get)
6974 ? opt.get.bind(publicThis, publicThis)
6975 : NOOP;
6976 if (get === NOOP) {
6977 warn(`Computed property "${key}" has no getter.`);
6978 }
6979 const set = !isFunction(opt) && isFunction(opt.set)
6980 ? opt.set.bind(publicThis)
6981 : () => {
6982 warn(`Write operation failed: computed property "${key}" is readonly.`);
6983 }
6984 ;
6985 const c = computed$1({
6986 get,
6987 set
6988 });
6989 Object.defineProperty(ctx, key, {
6990 enumerable: true,
6991 configurable: true,
6992 get: () => c.value,
6993 set: v => (c.value = v)
6994 });
6995 {
6996 checkDuplicateProperties("Computed" /* COMPUTED */, key);
6997 }
6998 }
6999 }
7000 if (watchOptions) {
7001 deferredWatch.push(watchOptions);
7002 }
7003 if (!asMixin && deferredWatch.length) {
7004 deferredWatch.forEach(watchOptions => {
7005 for (const key in watchOptions) {
7006 createWatcher(watchOptions[key], ctx, publicThis, key);
7007 }
7008 });
7009 }
7010 if (provideOptions) {
7011 deferredProvide.push(provideOptions);
7012 }
7013 if (!asMixin && deferredProvide.length) {
7014 deferredProvide.forEach(provideOptions => {
7015 const provides = isFunction(provideOptions)
7016 ? provideOptions.call(publicThis)
7017 : provideOptions;
7018 Reflect.ownKeys(provides).forEach(key => {
7019 provide(key, provides[key]);
7020 });
7021 });
7022 }
7023 // asset options.
7024 // To reduce memory usage, only components with mixins or extends will have
7025 // resolved asset registry attached to instance.
7026 if (asMixin) {
7027 if (components) {
7028 extend(instance.components ||
7029 (instance.components = extend({}, instance.type.components)), components);
7030 }
7031 if (directives) {
7032 extend(instance.directives ||
7033 (instance.directives = extend({}, instance.type.directives)), directives);
7034 }
7035 }
7036 // lifecycle options
7037 if (!asMixin) {
7038 callSyncHook('created', "c" /* CREATED */, options, instance, globalMixins);
7039 }
7040 if (beforeMount) {
7041 onBeforeMount(beforeMount.bind(publicThis));
7042 }
7043 if (mounted) {
7044 onMounted(mounted.bind(publicThis));
7045 }
7046 if (beforeUpdate) {
7047 onBeforeUpdate(beforeUpdate.bind(publicThis));
7048 }
7049 if (updated) {
7050 onUpdated(updated.bind(publicThis));
7051 }
7052 if (activated) {
7053 onActivated(activated.bind(publicThis));
7054 }
7055 if (deactivated) {
7056 onDeactivated(deactivated.bind(publicThis));
7057 }
7058 if (errorCaptured) {
7059 onErrorCaptured(errorCaptured.bind(publicThis));
7060 }
7061 if (renderTracked) {
7062 onRenderTracked(renderTracked.bind(publicThis));
7063 }
7064 if (renderTriggered) {
7065 onRenderTriggered(renderTriggered.bind(publicThis));
7066 }
7067 if (beforeDestroy) {
7068 warn(`\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`);
7069 }
7070 if (beforeUnmount) {
7071 onBeforeUnmount(beforeUnmount.bind(publicThis));
7072 }
7073 if (destroyed) {
7074 warn(`\`destroyed\` has been renamed to \`unmounted\`.`);
7075 }
7076 if (unmounted) {
7077 onUnmounted(unmounted.bind(publicThis));
7078 }
7079 if (isArray(expose)) {
7080 if (!asMixin) {
7081 if (expose.length) {
7082 const exposed = instance.exposed || (instance.exposed = proxyRefs({}));
7083 expose.forEach(key => {
7084 exposed[key] = toRef(publicThis, key);
7085 });
7086 }
7087 else if (!instance.exposed) {
7088 instance.exposed = EMPTY_OBJ;
7089 }
7090 }
7091 else {
7092 warn(`The \`expose\` option is ignored when used in mixins.`);
7093 }
7094 }
7095 }
7096 function callSyncHook(name, type, options, instance, globalMixins) {
7097 callHookFromMixins(name, type, globalMixins, instance);
7098 const { extends: base, mixins } = options;
7099 if (base) {
7100 callHookFromExtends(name, type, base, instance);
7101 }
7102 if (mixins) {
7103 callHookFromMixins(name, type, mixins, instance);
7104 }
7105 const selfHook = options[name];
7106 if (selfHook) {
7107 callWithAsyncErrorHandling(selfHook.bind(instance.proxy), instance, type);
7108 }
7109 }
7110 function callHookFromExtends(name, type, base, instance) {
7111 if (base.extends) {
7112 callHookFromExtends(name, type, base.extends, instance);
7113 }
7114 const baseHook = base[name];
7115 if (baseHook) {
7116 callWithAsyncErrorHandling(baseHook.bind(instance.proxy), instance, type);
7117 }
7118 }
7119 function callHookFromMixins(name, type, mixins, instance) {
7120 for (let i = 0; i < mixins.length; i++) {
7121 const chainedMixins = mixins[i].mixins;
7122 if (chainedMixins) {
7123 callHookFromMixins(name, type, chainedMixins, instance);
7124 }
7125 const fn = mixins[i][name];
7126 if (fn) {
7127 callWithAsyncErrorHandling(fn.bind(instance.proxy), instance, type);
7128 }
7129 }
7130 }
7131 function applyMixins(instance, mixins, deferredData, deferredWatch, deferredProvide) {
7132 for (let i = 0; i < mixins.length; i++) {
7133 applyOptions(instance, mixins[i], deferredData, deferredWatch, deferredProvide, true);
7134 }
7135 }
7136 function resolveData(instance, dataFn, publicThis) {
7137 if (!isFunction(dataFn)) {
7138 warn(`The data option must be a function. ` +
7139 `Plain object usage is no longer supported.`);
7140 }
7141 const data = dataFn.call(publicThis, publicThis);
7142 if (isPromise(data)) {
7143 warn(`data() returned a Promise - note data() cannot be async; If you ` +
7144 `intend to perform data fetching before component renders, use ` +
7145 `async setup() + <Suspense>.`);
7146 }
7147 if (!isObject(data)) {
7148 warn(`data() should return an object.`);
7149 }
7150 else if (instance.data === EMPTY_OBJ) {
7151 instance.data = reactive(data);
7152 }
7153 else {
7154 // existing data: this is a mixin or extends.
7155 extend(instance.data, data);
7156 }
7157 }
7158 function createWatcher(raw, ctx, publicThis, key) {
7159 const getter = key.includes('.')
7160 ? createPathGetter(publicThis, key)
7161 : () => publicThis[key];
7162 if (isString(raw)) {
7163 const handler = ctx[raw];
7164 if (isFunction(handler)) {
7165 watch(getter, handler);
7166 }
7167 else {
7168 warn(`Invalid watch handler specified by key "${raw}"`, handler);
7169 }
7170 }
7171 else if (isFunction(raw)) {
7172 watch(getter, raw.bind(publicThis));
7173 }
7174 else if (isObject(raw)) {
7175 if (isArray(raw)) {
7176 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
7177 }
7178 else {
7179 const handler = isFunction(raw.handler)
7180 ? raw.handler.bind(publicThis)
7181 : ctx[raw.handler];
7182 if (isFunction(handler)) {
7183 watch(getter, handler, raw);
7184 }
7185 else {
7186 warn(`Invalid watch handler specified by key "${raw.handler}"`, handler);
7187 }
7188 }
7189 }
7190 else {
7191 warn(`Invalid watch option: "${key}"`, raw);
7192 }
7193 }
7194 function createPathGetter(ctx, path) {
7195 const segments = path.split('.');
7196 return () => {
7197 let cur = ctx;
7198 for (let i = 0; i < segments.length && cur; i++) {
7199 cur = cur[segments[i]];
7200 }
7201 return cur;
7202 };
7203 }
7204 function resolveMergedOptions(instance) {
7205 const raw = instance.type;
7206 const { __merged, mixins, extends: extendsOptions } = raw;
7207 if (__merged)
7208 return __merged;
7209 const globalMixins = instance.appContext.mixins;
7210 if (!globalMixins.length && !mixins && !extendsOptions)
7211 return raw;
7212 const options = {};
7213 globalMixins.forEach(m => mergeOptions(options, m, instance));
7214 mergeOptions(options, raw, instance);
7215 return (raw.__merged = options);
7216 }
7217 function mergeOptions(to, from, instance) {
7218 const strats = instance.appContext.config.optionMergeStrategies;
7219 const { mixins, extends: extendsOptions } = from;
7220 extendsOptions && mergeOptions(to, extendsOptions, instance);
7221 mixins &&
7222 mixins.forEach((m) => mergeOptions(to, m, instance));
7223 for (const key in from) {
7224 if (strats && hasOwn(strats, key)) {
7225 to[key] = strats[key](to[key], from[key], instance.proxy, key);
7226 }
7227 else {
7228 to[key] = from[key];
7229 }
7230 }
7231 }
7232
7233 /**
7234 * #2437 In Vue 3, functional components do not have a public instance proxy but
7235 * they exist in the internal parent chain. For code that relies on traversing
7236 * public $parent chains, skip functional ones and go to the parent instead.
7237 */
7238 const getPublicInstance = (i) => {
7239 if (!i)
7240 return null;
7241 if (isStatefulComponent(i))
7242 return i.exposed ? i.exposed : i.proxy;
7243 return getPublicInstance(i.parent);
7244 };
7245 const publicPropertiesMap = extend(Object.create(null), {
7246 $: i => i,
7247 $el: i => i.vnode.el,
7248 $data: i => i.data,
7249 $props: i => (shallowReadonly(i.props) ),
7250 $attrs: i => (shallowReadonly(i.attrs) ),
7251 $slots: i => (shallowReadonly(i.slots) ),
7252 $refs: i => (shallowReadonly(i.refs) ),
7253 $parent: i => getPublicInstance(i.parent),
7254 $root: i => getPublicInstance(i.root),
7255 $emit: i => i.emit,
7256 $options: i => (resolveMergedOptions(i) ),
7257 $forceUpdate: i => () => queueJob(i.update),
7258 $nextTick: i => nextTick.bind(i.proxy),
7259 $watch: i => (instanceWatch.bind(i) )
7260 });
7261 const PublicInstanceProxyHandlers = {
7262 get({ _: instance }, key) {
7263 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
7264 // let @vue/reactivity know it should never observe Vue public instances.
7265 if (key === "__v_skip" /* SKIP */) {
7266 return true;
7267 }
7268 // for internal formatters to know that this is a Vue instance
7269 if (key === '__isVue') {
7270 return true;
7271 }
7272 // data / props / ctx
7273 // This getter gets called for every property access on the render context
7274 // during render and is a major hotspot. The most expensive part of this
7275 // is the multiple hasOwn() calls. It's much faster to do a simple property
7276 // access on a plain object, so we use an accessCache object (with null
7277 // prototype) to memoize what access type a key corresponds to.
7278 let normalizedProps;
7279 if (key[0] !== '$') {
7280 const n = accessCache[key];
7281 if (n !== undefined) {
7282 switch (n) {
7283 case 0 /* SETUP */:
7284 return setupState[key];
7285 case 1 /* DATA */:
7286 return data[key];
7287 case 3 /* CONTEXT */:
7288 return ctx[key];
7289 case 2 /* PROPS */:
7290 return props[key];
7291 // default: just fallthrough
7292 }
7293 }
7294 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7295 accessCache[key] = 0 /* SETUP */;
7296 return setupState[key];
7297 }
7298 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7299 accessCache[key] = 1 /* DATA */;
7300 return data[key];
7301 }
7302 else if (
7303 // only cache other properties when instance has declared (thus stable)
7304 // props
7305 (normalizedProps = instance.propsOptions[0]) &&
7306 hasOwn(normalizedProps, key)) {
7307 accessCache[key] = 2 /* PROPS */;
7308 return props[key];
7309 }
7310 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7311 accessCache[key] = 3 /* CONTEXT */;
7312 return ctx[key];
7313 }
7314 else if (!isInBeforeCreate) {
7315 accessCache[key] = 4 /* OTHER */;
7316 }
7317 }
7318 const publicGetter = publicPropertiesMap[key];
7319 let cssModule, globalProperties;
7320 // public $xxx properties
7321 if (publicGetter) {
7322 if (key === '$attrs') {
7323 track(instance, "get" /* GET */, key);
7324 markAttrsAccessed();
7325 }
7326 return publicGetter(instance);
7327 }
7328 else if (
7329 // css module (injected by vue-loader)
7330 (cssModule = type.__cssModules) &&
7331 (cssModule = cssModule[key])) {
7332 return cssModule;
7333 }
7334 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7335 // user may set custom properties to `this` that start with `$`
7336 accessCache[key] = 3 /* CONTEXT */;
7337 return ctx[key];
7338 }
7339 else if (
7340 // global properties
7341 ((globalProperties = appContext.config.globalProperties),
7342 hasOwn(globalProperties, key))) {
7343 return globalProperties[key];
7344 }
7345 else if (currentRenderingInstance &&
7346 (!isString(key) ||
7347 // #1091 avoid internal isRef/isVNode checks on component instance leading
7348 // to infinite warning loop
7349 key.indexOf('__v') !== 0)) {
7350 if (data !== EMPTY_OBJ &&
7351 (key[0] === '$' || key[0] === '_') &&
7352 hasOwn(data, key)) {
7353 warn(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
7354 `character ("$" or "_") and is not proxied on the render context.`);
7355 }
7356 else if (instance === currentRenderingInstance) {
7357 warn(`Property ${JSON.stringify(key)} was accessed during render ` +
7358 `but is not defined on instance.`);
7359 }
7360 }
7361 },
7362 set({ _: instance }, key, value) {
7363 const { data, setupState, ctx } = instance;
7364 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7365 setupState[key] = value;
7366 }
7367 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7368 data[key] = value;
7369 }
7370 else if (hasOwn(instance.props, key)) {
7371 warn(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
7372 return false;
7373 }
7374 if (key[0] === '$' && key.slice(1) in instance) {
7375 warn(`Attempting to mutate public property "${key}". ` +
7376 `Properties starting with $ are reserved and readonly.`, instance);
7377 return false;
7378 }
7379 else {
7380 if (key in instance.appContext.config.globalProperties) {
7381 Object.defineProperty(ctx, key, {
7382 enumerable: true,
7383 configurable: true,
7384 value
7385 });
7386 }
7387 else {
7388 ctx[key] = value;
7389 }
7390 }
7391 return true;
7392 },
7393 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
7394 let normalizedProps;
7395 return (accessCache[key] !== undefined ||
7396 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
7397 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
7398 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
7399 hasOwn(ctx, key) ||
7400 hasOwn(publicPropertiesMap, key) ||
7401 hasOwn(appContext.config.globalProperties, key));
7402 }
7403 };
7404 {
7405 PublicInstanceProxyHandlers.ownKeys = (target) => {
7406 warn(`Avoid app logic that relies on enumerating keys on a component instance. ` +
7407 `The keys will be empty in production mode to avoid performance overhead.`);
7408 return Reflect.ownKeys(target);
7409 };
7410 }
7411 const RuntimeCompiledPublicInstanceProxyHandlers = extend({}, PublicInstanceProxyHandlers, {
7412 get(target, key) {
7413 // fast path for unscopables when using `with` block
7414 if (key === Symbol.unscopables) {
7415 return;
7416 }
7417 return PublicInstanceProxyHandlers.get(target, key, target);
7418 },
7419 has(_, key) {
7420 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
7421 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
7422 warn(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
7423 }
7424 return has;
7425 }
7426 });
7427 // In dev mode, the proxy target exposes the same properties as seen on `this`
7428 // for easier console inspection. In prod mode it will be an empty object so
7429 // these properties definitions can be skipped.
7430 function createRenderContext(instance) {
7431 const target = {};
7432 // expose internal instance for proxy handlers
7433 Object.defineProperty(target, `_`, {
7434 configurable: true,
7435 enumerable: false,
7436 get: () => instance
7437 });
7438 // expose public properties
7439 Object.keys(publicPropertiesMap).forEach(key => {
7440 Object.defineProperty(target, key, {
7441 configurable: true,
7442 enumerable: false,
7443 get: () => publicPropertiesMap[key](instance),
7444 // intercepted by the proxy so no need for implementation,
7445 // but needed to prevent set errors
7446 set: NOOP
7447 });
7448 });
7449 // expose global properties
7450 const { globalProperties } = instance.appContext.config;
7451 Object.keys(globalProperties).forEach(key => {
7452 Object.defineProperty(target, key, {
7453 configurable: true,
7454 enumerable: false,
7455 get: () => globalProperties[key],
7456 set: NOOP
7457 });
7458 });
7459 return target;
7460 }
7461 // dev only
7462 function exposePropsOnRenderContext(instance) {
7463 const { ctx, propsOptions: [propsOptions] } = instance;
7464 if (propsOptions) {
7465 Object.keys(propsOptions).forEach(key => {
7466 Object.defineProperty(ctx, key, {
7467 enumerable: true,
7468 configurable: true,
7469 get: () => instance.props[key],
7470 set: NOOP
7471 });
7472 });
7473 }
7474 }
7475 // dev only
7476 function exposeSetupStateOnRenderContext(instance) {
7477 const { ctx, setupState } = instance;
7478 Object.keys(toRaw(setupState)).forEach(key => {
7479 if (key[0] === '$' || key[0] === '_') {
7480 warn(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
7481 `which are reserved prefixes for Vue internals.`);
7482 return;
7483 }
7484 Object.defineProperty(ctx, key, {
7485 enumerable: true,
7486 configurable: true,
7487 get: () => setupState[key],
7488 set: NOOP
7489 });
7490 });
7491 }
7492
7493 const emptyAppContext = createAppContext();
7494 let uid$2 = 0;
7495 function createComponentInstance(vnode, parent, suspense) {
7496 const type = vnode.type;
7497 // inherit parent app context - or - if root, adopt from root vnode
7498 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
7499 const instance = {
7500 uid: uid$2++,
7501 vnode,
7502 type,
7503 parent,
7504 appContext,
7505 root: null,
7506 next: null,
7507 subTree: null,
7508 update: null,
7509 render: null,
7510 proxy: null,
7511 exposed: null,
7512 withProxy: null,
7513 effects: null,
7514 provides: parent ? parent.provides : Object.create(appContext.provides),
7515 accessCache: null,
7516 renderCache: [],
7517 // local resovled assets
7518 components: null,
7519 directives: null,
7520 // resolved props and emits options
7521 propsOptions: normalizePropsOptions(type, appContext),
7522 emitsOptions: normalizeEmitsOptions(type, appContext),
7523 // emit
7524 emit: null,
7525 emitted: null,
7526 // state
7527 ctx: EMPTY_OBJ,
7528 data: EMPTY_OBJ,
7529 props: EMPTY_OBJ,
7530 attrs: EMPTY_OBJ,
7531 slots: EMPTY_OBJ,
7532 refs: EMPTY_OBJ,
7533 setupState: EMPTY_OBJ,
7534 setupContext: null,
7535 // suspense related
7536 suspense,
7537 suspenseId: suspense ? suspense.pendingId : 0,
7538 asyncDep: null,
7539 asyncResolved: false,
7540 // lifecycle hooks
7541 // not using enums here because it results in computed properties
7542 isMounted: false,
7543 isUnmounted: false,
7544 isDeactivated: false,
7545 bc: null,
7546 c: null,
7547 bm: null,
7548 m: null,
7549 bu: null,
7550 u: null,
7551 um: null,
7552 bum: null,
7553 da: null,
7554 a: null,
7555 rtg: null,
7556 rtc: null,
7557 ec: null
7558 };
7559 {
7560 instance.ctx = createRenderContext(instance);
7561 }
7562 instance.root = parent ? parent.root : instance;
7563 instance.emit = emit.bind(null, instance);
7564 return instance;
7565 }
7566 let currentInstance = null;
7567 const getCurrentInstance = () => currentInstance || currentRenderingInstance;
7568 const setCurrentInstance = (instance) => {
7569 currentInstance = instance;
7570 };
7571 const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
7572 function validateComponentName(name, config) {
7573 const appIsNativeTag = config.isNativeTag || NO;
7574 if (isBuiltInTag(name) || appIsNativeTag(name)) {
7575 warn('Do not use built-in or reserved HTML elements as component id: ' + name);
7576 }
7577 }
7578 function isStatefulComponent(instance) {
7579 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
7580 }
7581 let isInSSRComponentSetup = false;
7582 function setupComponent(instance, isSSR = false) {
7583 isInSSRComponentSetup = isSSR;
7584 const { props, children } = instance.vnode;
7585 const isStateful = isStatefulComponent(instance);
7586 initProps(instance, props, isStateful, isSSR);
7587 initSlots(instance, children);
7588 const setupResult = isStateful
7589 ? setupStatefulComponent(instance, isSSR)
7590 : undefined;
7591 isInSSRComponentSetup = false;
7592 return setupResult;
7593 }
7594 function setupStatefulComponent(instance, isSSR) {
7595 const Component = instance.type;
7596 {
7597 if (Component.name) {
7598 validateComponentName(Component.name, instance.appContext.config);
7599 }
7600 if (Component.components) {
7601 const names = Object.keys(Component.components);
7602 for (let i = 0; i < names.length; i++) {
7603 validateComponentName(names[i], instance.appContext.config);
7604 }
7605 }
7606 if (Component.directives) {
7607 const names = Object.keys(Component.directives);
7608 for (let i = 0; i < names.length; i++) {
7609 validateDirectiveName(names[i]);
7610 }
7611 }
7612 }
7613 // 0. create render proxy property access cache
7614 instance.accessCache = Object.create(null);
7615 // 1. create public instance / render proxy
7616 // also mark it raw so it's never observed
7617 instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
7618 {
7619 exposePropsOnRenderContext(instance);
7620 }
7621 // 2. call setup()
7622 const { setup } = Component;
7623 if (setup) {
7624 const setupContext = (instance.setupContext =
7625 setup.length > 1 ? createSetupContext(instance) : null);
7626 currentInstance = instance;
7627 pauseTracking();
7628 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
7629 resetTracking();
7630 currentInstance = null;
7631 if (isPromise(setupResult)) {
7632 if (isSSR) {
7633 // return the promise so server-renderer can wait on it
7634 return setupResult.then((resolvedResult) => {
7635 handleSetupResult(instance, resolvedResult);
7636 });
7637 }
7638 else {
7639 // async setup returned Promise.
7640 // bail here and wait for re-entry.
7641 instance.asyncDep = setupResult;
7642 }
7643 }
7644 else {
7645 handleSetupResult(instance, setupResult);
7646 }
7647 }
7648 else {
7649 finishComponentSetup(instance);
7650 }
7651 }
7652 function handleSetupResult(instance, setupResult, isSSR) {
7653 if (isFunction(setupResult)) {
7654 // setup returned an inline render function
7655 {
7656 instance.render = setupResult;
7657 }
7658 }
7659 else if (isObject(setupResult)) {
7660 if (isVNode(setupResult)) {
7661 warn(`setup() should not return VNodes directly - ` +
7662 `return a render function instead.`);
7663 }
7664 // setup returned bindings.
7665 // assuming a render function compiled from template is present.
7666 {
7667 instance.devtoolsRawSetupState = setupResult;
7668 }
7669 instance.setupState = proxyRefs(setupResult);
7670 {
7671 exposeSetupStateOnRenderContext(instance);
7672 }
7673 }
7674 else if (setupResult !== undefined) {
7675 warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
7676 }
7677 finishComponentSetup(instance);
7678 }
7679 let compile;
7680 // dev only
7681 const isRuntimeOnly = () => !compile;
7682 /**
7683 * For runtime-dom to register the compiler.
7684 * Note the exported method uses any to avoid d.ts relying on the compiler types.
7685 */
7686 function registerRuntimeCompiler(_compile) {
7687 compile = _compile;
7688 }
7689 function finishComponentSetup(instance, isSSR) {
7690 const Component = instance.type;
7691 // template / render function normalization
7692 if (!instance.render) {
7693 // could be set from setup()
7694 if (compile && Component.template && !Component.render) {
7695 {
7696 startMeasure(instance, `compile`);
7697 }
7698 Component.render = compile(Component.template, {
7699 isCustomElement: instance.appContext.config.isCustomElement,
7700 delimiters: Component.delimiters
7701 });
7702 {
7703 endMeasure(instance, `compile`);
7704 }
7705 }
7706 instance.render = (Component.render || NOOP);
7707 // for runtime-compiled render functions using `with` blocks, the render
7708 // proxy used needs a different `has` handler which is more performant and
7709 // also only allows a whitelist of globals to fallthrough.
7710 if (instance.render._rc) {
7711 instance.withProxy = new Proxy(instance.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
7712 }
7713 }
7714 // support for 2.x options
7715 {
7716 currentInstance = instance;
7717 pauseTracking();
7718 applyOptions(instance, Component);
7719 resetTracking();
7720 currentInstance = null;
7721 }
7722 // warn missing template/render
7723 if (!Component.render && instance.render === NOOP) {
7724 /* istanbul ignore if */
7725 if (!compile && Component.template) {
7726 warn(`Component provided template option but ` +
7727 `runtime compilation is not supported in this build of Vue.` +
7728 (` Use "vue.global.js" instead.`
7729 ) /* should not happen */);
7730 }
7731 else {
7732 warn(`Component is missing template or render function.`);
7733 }
7734 }
7735 }
7736 const attrHandlers = {
7737 get: (target, key) => {
7738 {
7739 markAttrsAccessed();
7740 }
7741 return target[key];
7742 },
7743 set: () => {
7744 warn(`setupContext.attrs is readonly.`);
7745 return false;
7746 },
7747 deleteProperty: () => {
7748 warn(`setupContext.attrs is readonly.`);
7749 return false;
7750 }
7751 };
7752 function createSetupContext(instance) {
7753 const expose = exposed => {
7754 if (instance.exposed) {
7755 warn(`expose() should be called only once per setup().`);
7756 }
7757 instance.exposed = proxyRefs(exposed);
7758 };
7759 {
7760 // We use getters in dev in case libs like test-utils overwrite instance
7761 // properties (overwrites should not be done in prod)
7762 return Object.freeze({
7763 get props() {
7764 return instance.props;
7765 },
7766 get attrs() {
7767 return new Proxy(instance.attrs, attrHandlers);
7768 },
7769 get slots() {
7770 return shallowReadonly(instance.slots);
7771 },
7772 get emit() {
7773 return (event, ...args) => instance.emit(event, ...args);
7774 },
7775 expose
7776 });
7777 }
7778 }
7779 // record effects created during a component's setup() so that they can be
7780 // stopped when the component unmounts
7781 function recordInstanceBoundEffect(effect, instance = currentInstance) {
7782 if (instance) {
7783 (instance.effects || (instance.effects = [])).push(effect);
7784 }
7785 }
7786 const classifyRE = /(?:^|[-_])(\w)/g;
7787 const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
7788 function getComponentName(Component) {
7789 return isFunction(Component)
7790 ? Component.displayName || Component.name
7791 : Component.name;
7792 }
7793 /* istanbul ignore next */
7794 function formatComponentName(instance, Component, isRoot = false) {
7795 let name = getComponentName(Component);
7796 if (!name && Component.__file) {
7797 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
7798 if (match) {
7799 name = match[1];
7800 }
7801 }
7802 if (!name && instance && instance.parent) {
7803 // try to infer the name based on reverse resolution
7804 const inferFromRegistry = (registry) => {
7805 for (const key in registry) {
7806 if (registry[key] === Component) {
7807 return key;
7808 }
7809 }
7810 };
7811 name =
7812 inferFromRegistry(instance.components ||
7813 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
7814 }
7815 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
7816 }
7817 function isClassComponent(value) {
7818 return isFunction(value) && '__vccOpts' in value;
7819 }
7820
7821 function computed$1(getterOrOptions) {
7822 const c = computed(getterOrOptions);
7823 recordInstanceBoundEffect(c.effect);
7824 return c;
7825 }
7826
7827 // implementation
7828 function defineProps() {
7829 {
7830 warn(`defineProps() is a compiler-hint helper that is only usable inside ` +
7831 `<script setup> of a single file component. Its arguments should be ` +
7832 `compiled away and passing it at runtime has no effect.`);
7833 }
7834 return null;
7835 }
7836 // implementation
7837 function defineEmit() {
7838 {
7839 warn(`defineEmit() is a compiler-hint helper that is only usable inside ` +
7840 `<script setup> of a single file component. Its arguments should be ` +
7841 `compiled away and passing it at runtime has no effect.`);
7842 }
7843 return null;
7844 }
7845 function useContext() {
7846 const i = getCurrentInstance();
7847 if (!i) {
7848 warn(`useContext() called without active instance.`);
7849 }
7850 return i.setupContext || (i.setupContext = createSetupContext(i));
7851 }
7852
7853 // Actual implementation
7854 function h(type, propsOrChildren, children) {
7855 const l = arguments.length;
7856 if (l === 2) {
7857 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
7858 // single vnode without props
7859 if (isVNode(propsOrChildren)) {
7860 return createVNode(type, null, [propsOrChildren]);
7861 }
7862 // props without children
7863 return createVNode(type, propsOrChildren);
7864 }
7865 else {
7866 // omit props
7867 return createVNode(type, null, propsOrChildren);
7868 }
7869 }
7870 else {
7871 if (l > 3) {
7872 children = Array.prototype.slice.call(arguments, 2);
7873 }
7874 else if (l === 3 && isVNode(children)) {
7875 children = [children];
7876 }
7877 return createVNode(type, propsOrChildren, children);
7878 }
7879 }
7880
7881 const ssrContextKey = Symbol(`ssrContext` );
7882 const useSSRContext = () => {
7883 {
7884 warn(`useSSRContext() is not supported in the global build.`);
7885 }
7886 };
7887
7888 function initCustomFormatter() {
7889 /* eslint-disable no-restricted-globals */
7890 if (typeof window === 'undefined') {
7891 return;
7892 }
7893 const vueStyle = { style: 'color:#3ba776' };
7894 const numberStyle = { style: 'color:#0b1bc9' };
7895 const stringStyle = { style: 'color:#b62e24' };
7896 const keywordStyle = { style: 'color:#9d288c' };
7897 // custom formatter for Chrome
7898 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
7899 const formatter = {
7900 header(obj) {
7901 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
7902 if (!isObject(obj)) {
7903 return null;
7904 }
7905 if (obj.__isVue) {
7906 return ['div', vueStyle, `VueInstance`];
7907 }
7908 else if (isRef(obj)) {
7909 return [
7910 'div',
7911 {},
7912 ['span', vueStyle, genRefFlag(obj)],
7913 '<',
7914 formatValue(obj.value),
7915 `>`
7916 ];
7917 }
7918 else if (isReactive(obj)) {
7919 return [
7920 'div',
7921 {},
7922 ['span', vueStyle, 'Reactive'],
7923 '<',
7924 formatValue(obj),
7925 `>${isReadonly(obj) ? ` (readonly)` : ``}`
7926 ];
7927 }
7928 else if (isReadonly(obj)) {
7929 return [
7930 'div',
7931 {},
7932 ['span', vueStyle, 'Readonly'],
7933 '<',
7934 formatValue(obj),
7935 '>'
7936 ];
7937 }
7938 return null;
7939 },
7940 hasBody(obj) {
7941 return obj && obj.__isVue;
7942 },
7943 body(obj) {
7944 if (obj && obj.__isVue) {
7945 return [
7946 'div',
7947 {},
7948 ...formatInstance(obj.$)
7949 ];
7950 }
7951 }
7952 };
7953 function formatInstance(instance) {
7954 const blocks = [];
7955 if (instance.type.props && instance.props) {
7956 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
7957 }
7958 if (instance.setupState !== EMPTY_OBJ) {
7959 blocks.push(createInstanceBlock('setup', instance.setupState));
7960 }
7961 if (instance.data !== EMPTY_OBJ) {
7962 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
7963 }
7964 const computed = extractKeys(instance, 'computed');
7965 if (computed) {
7966 blocks.push(createInstanceBlock('computed', computed));
7967 }
7968 const injected = extractKeys(instance, 'inject');
7969 if (injected) {
7970 blocks.push(createInstanceBlock('injected', injected));
7971 }
7972 blocks.push([
7973 'div',
7974 {},
7975 [
7976 'span',
7977 {
7978 style: keywordStyle.style + ';opacity:0.66'
7979 },
7980 '$ (internal): '
7981 ],
7982 ['object', { object: instance }]
7983 ]);
7984 return blocks;
7985 }
7986 function createInstanceBlock(type, target) {
7987 target = extend({}, target);
7988 if (!Object.keys(target).length) {
7989 return ['span', {}];
7990 }
7991 return [
7992 'div',
7993 { style: 'line-height:1.25em;margin-bottom:0.6em' },
7994 [
7995 'div',
7996 {
7997 style: 'color:#476582'
7998 },
7999 type
8000 ],
8001 [
8002 'div',
8003 {
8004 style: 'padding-left:1.25em'
8005 },
8006 ...Object.keys(target).map(key => {
8007 return [
8008 'div',
8009 {},
8010 ['span', keywordStyle, key + ': '],
8011 formatValue(target[key], false)
8012 ];
8013 })
8014 ]
8015 ];
8016 }
8017 function formatValue(v, asRaw = true) {
8018 if (typeof v === 'number') {
8019 return ['span', numberStyle, v];
8020 }
8021 else if (typeof v === 'string') {
8022 return ['span', stringStyle, JSON.stringify(v)];
8023 }
8024 else if (typeof v === 'boolean') {
8025 return ['span', keywordStyle, v];
8026 }
8027 else if (isObject(v)) {
8028 return ['object', { object: asRaw ? toRaw(v) : v }];
8029 }
8030 else {
8031 return ['span', stringStyle, String(v)];
8032 }
8033 }
8034 function extractKeys(instance, type) {
8035 const Comp = instance.type;
8036 if (isFunction(Comp)) {
8037 return;
8038 }
8039 const extracted = {};
8040 for (const key in instance.ctx) {
8041 if (isKeyOfType(Comp, key, type)) {
8042 extracted[key] = instance.ctx[key];
8043 }
8044 }
8045 return extracted;
8046 }
8047 function isKeyOfType(Comp, key, type) {
8048 const opts = Comp[type];
8049 if ((isArray(opts) && opts.includes(key)) ||
8050 (isObject(opts) && key in opts)) {
8051 return true;
8052 }
8053 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
8054 return true;
8055 }
8056 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
8057 return true;
8058 }
8059 }
8060 function genRefFlag(v) {
8061 if (v._shallow) {
8062 return `ShallowRef`;
8063 }
8064 if (v.effect) {
8065 return `ComputedRef`;
8066 }
8067 return `Ref`;
8068 }
8069 if (window.devtoolsFormatters) {
8070 window.devtoolsFormatters.push(formatter);
8071 }
8072 else {
8073 window.devtoolsFormatters = [formatter];
8074 }
8075 }
8076
8077 /**
8078 * Actual implementation
8079 */
8080 function renderList(source, renderItem) {
8081 let ret;
8082 if (isArray(source) || isString(source)) {
8083 ret = new Array(source.length);
8084 for (let i = 0, l = source.length; i < l; i++) {
8085 ret[i] = renderItem(source[i], i);
8086 }
8087 }
8088 else if (typeof source === 'number') {
8089 if (!Number.isInteger(source)) {
8090 warn(`The v-for range expect an integer value but got ${source}.`);
8091 return [];
8092 }
8093 ret = new Array(source);
8094 for (let i = 0; i < source; i++) {
8095 ret[i] = renderItem(i + 1, i);
8096 }
8097 }
8098 else if (isObject(source)) {
8099 if (source[Symbol.iterator]) {
8100 ret = Array.from(source, renderItem);
8101 }
8102 else {
8103 const keys = Object.keys(source);
8104 ret = new Array(keys.length);
8105 for (let i = 0, l = keys.length; i < l; i++) {
8106 const key = keys[i];
8107 ret[i] = renderItem(source[key], key, i);
8108 }
8109 }
8110 }
8111 else {
8112 ret = [];
8113 }
8114 return ret;
8115 }
8116
8117 /**
8118 * For prefixing keys in v-on="obj" with "on"
8119 * @private
8120 */
8121 function toHandlers(obj) {
8122 const ret = {};
8123 if (!isObject(obj)) {
8124 warn(`v-on with no argument expects an object value.`);
8125 return ret;
8126 }
8127 for (const key in obj) {
8128 ret[toHandlerKey(key)] = obj[key];
8129 }
8130 return ret;
8131 }
8132
8133 /**
8134 * Compiler runtime helper for creating dynamic slots object
8135 * @private
8136 */
8137 function createSlots(slots, dynamicSlots) {
8138 for (let i = 0; i < dynamicSlots.length; i++) {
8139 const slot = dynamicSlots[i];
8140 // array of dynamic slot generated by <template v-for="..." #[...]>
8141 if (isArray(slot)) {
8142 for (let j = 0; j < slot.length; j++) {
8143 slots[slot[j].name] = slot[j].fn;
8144 }
8145 }
8146 else if (slot) {
8147 // conditional single slot generated by <template v-if="..." #foo>
8148 slots[slot.name] = slot.fn;
8149 }
8150 }
8151 return slots;
8152 }
8153
8154 // Core API ------------------------------------------------------------------
8155 const version = "3.0.7";
8156 /**
8157 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
8158 * @internal
8159 */
8160 const ssrUtils = (null);
8161
8162 const svgNS = 'http://www.w3.org/2000/svg';
8163 const doc = (typeof document !== 'undefined' ? document : null);
8164 let tempContainer;
8165 let tempSVGContainer;
8166 const nodeOps = {
8167 insert: (child, parent, anchor) => {
8168 parent.insertBefore(child, anchor || null);
8169 },
8170 remove: child => {
8171 const parent = child.parentNode;
8172 if (parent) {
8173 parent.removeChild(child);
8174 }
8175 },
8176 createElement: (tag, isSVG, is) => isSVG
8177 ? doc.createElementNS(svgNS, tag)
8178 : doc.createElement(tag, is ? { is } : undefined),
8179 createText: text => doc.createTextNode(text),
8180 createComment: text => doc.createComment(text),
8181 setText: (node, text) => {
8182 node.nodeValue = text;
8183 },
8184 setElementText: (el, text) => {
8185 el.textContent = text;
8186 },
8187 parentNode: node => node.parentNode,
8188 nextSibling: node => node.nextSibling,
8189 querySelector: selector => doc.querySelector(selector),
8190 setScopeId(el, id) {
8191 el.setAttribute(id, '');
8192 },
8193 cloneNode(el) {
8194 return el.cloneNode(true);
8195 },
8196 // __UNSAFE__
8197 // Reason: innerHTML.
8198 // Static content here can only come from compiled templates.
8199 // As long as the user only uses trusted templates, this is safe.
8200 insertStaticContent(content, parent, anchor, isSVG) {
8201 const temp = isSVG
8202 ? tempSVGContainer ||
8203 (tempSVGContainer = doc.createElementNS(svgNS, 'svg'))
8204 : tempContainer || (tempContainer = doc.createElement('div'));
8205 temp.innerHTML = content;
8206 const first = temp.firstChild;
8207 let node = first;
8208 let last = node;
8209 while (node) {
8210 last = node;
8211 nodeOps.insert(node, parent, anchor);
8212 node = temp.firstChild;
8213 }
8214 return [first, last];
8215 }
8216 };
8217
8218 // compiler should normalize class + :class bindings on the same element
8219 // into a single binding ['staticClass', dynamic]
8220 function patchClass(el, value, isSVG) {
8221 if (value == null) {
8222 value = '';
8223 }
8224 if (isSVG) {
8225 el.setAttribute('class', value);
8226 }
8227 else {
8228 // directly setting className should be faster than setAttribute in theory
8229 // if this is an element during a transition, take the temporary transition
8230 // classes into account.
8231 const transitionClasses = el._vtc;
8232 if (transitionClasses) {
8233 value = (value
8234 ? [value, ...transitionClasses]
8235 : [...transitionClasses]).join(' ');
8236 }
8237 el.className = value;
8238 }
8239 }
8240
8241 function patchStyle(el, prev, next) {
8242 const style = el.style;
8243 if (!next) {
8244 el.removeAttribute('style');
8245 }
8246 else if (isString(next)) {
8247 if (prev !== next) {
8248 const current = style.display;
8249 style.cssText = next;
8250 // indicates that the `display` of the element is controlled by `v-show`,
8251 // so we always keep the current `display` value regardless of the `style` value,
8252 // thus handing over control to `v-show`.
8253 if ('_vod' in el) {
8254 style.display = current;
8255 }
8256 }
8257 }
8258 else {
8259 for (const key in next) {
8260 setStyle(style, key, next[key]);
8261 }
8262 if (prev && !isString(prev)) {
8263 for (const key in prev) {
8264 if (next[key] == null) {
8265 setStyle(style, key, '');
8266 }
8267 }
8268 }
8269 }
8270 }
8271 const importantRE = /\s*!important$/;
8272 function setStyle(style, name, val) {
8273 if (isArray(val)) {
8274 val.forEach(v => setStyle(style, name, v));
8275 }
8276 else {
8277 if (name.startsWith('--')) {
8278 // custom property definition
8279 style.setProperty(name, val);
8280 }
8281 else {
8282 const prefixed = autoPrefix(style, name);
8283 if (importantRE.test(val)) {
8284 // !important
8285 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
8286 }
8287 else {
8288 style[prefixed] = val;
8289 }
8290 }
8291 }
8292 }
8293 const prefixes = ['Webkit', 'Moz', 'ms'];
8294 const prefixCache = {};
8295 function autoPrefix(style, rawName) {
8296 const cached = prefixCache[rawName];
8297 if (cached) {
8298 return cached;
8299 }
8300 let name = camelize(rawName);
8301 if (name !== 'filter' && name in style) {
8302 return (prefixCache[rawName] = name);
8303 }
8304 name = capitalize(name);
8305 for (let i = 0; i < prefixes.length; i++) {
8306 const prefixed = prefixes[i] + name;
8307 if (prefixed in style) {
8308 return (prefixCache[rawName] = prefixed);
8309 }
8310 }
8311 return rawName;
8312 }
8313
8314 const xlinkNS = 'http://www.w3.org/1999/xlink';
8315 function patchAttr(el, key, value, isSVG) {
8316 if (isSVG && key.startsWith('xlink:')) {
8317 if (value == null) {
8318 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
8319 }
8320 else {
8321 el.setAttributeNS(xlinkNS, key, value);
8322 }
8323 }
8324 else {
8325 // note we are only checking boolean attributes that don't have a
8326 // corresponding dom prop of the same name here.
8327 const isBoolean = isSpecialBooleanAttr(key);
8328 if (value == null || (isBoolean && value === false)) {
8329 el.removeAttribute(key);
8330 }
8331 else {
8332 el.setAttribute(key, isBoolean ? '' : value);
8333 }
8334 }
8335 }
8336
8337 // __UNSAFE__
8338 // functions. The user is responsible for using them with only trusted content.
8339 function patchDOMProp(el, key, value,
8340 // the following args are passed only due to potential innerHTML/textContent
8341 // overriding existing VNodes, in which case the old tree must be properly
8342 // unmounted.
8343 prevChildren, parentComponent, parentSuspense, unmountChildren) {
8344 if (key === 'innerHTML' || key === 'textContent') {
8345 if (prevChildren) {
8346 unmountChildren(prevChildren, parentComponent, parentSuspense);
8347 }
8348 el[key] = value == null ? '' : value;
8349 return;
8350 }
8351 if (key === 'value' && el.tagName !== 'PROGRESS') {
8352 // store value as _value as well since
8353 // non-string values will be stringified.
8354 el._value = value;
8355 const newValue = value == null ? '' : value;
8356 if (el.value !== newValue) {
8357 el.value = newValue;
8358 }
8359 return;
8360 }
8361 if (value === '' || value == null) {
8362 const type = typeof el[key];
8363 if (value === '' && type === 'boolean') {
8364 // e.g. <select multiple> compiles to { multiple: '' }
8365 el[key] = true;
8366 return;
8367 }
8368 else if (value == null && type === 'string') {
8369 // e.g. <div :id="null">
8370 el[key] = '';
8371 el.removeAttribute(key);
8372 return;
8373 }
8374 else if (type === 'number') {
8375 // e.g. <img :width="null">
8376 el[key] = 0;
8377 el.removeAttribute(key);
8378 return;
8379 }
8380 }
8381 // some properties perform value validation and throw
8382 try {
8383 el[key] = value;
8384 }
8385 catch (e) {
8386 {
8387 warn(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
8388 `value ${value} is invalid.`, e);
8389 }
8390 }
8391 }
8392
8393 // Async edge case fix requires storing an event listener's attach timestamp.
8394 let _getNow = Date.now;
8395 // Determine what event timestamp the browser is using. Annoyingly, the
8396 // timestamp can either be hi-res (relative to page load) or low-res
8397 // (relative to UNIX epoch), so in order to compare time we have to use the
8398 // same timestamp type when saving the flush timestamp.
8399 if (typeof document !== 'undefined' &&
8400 _getNow() > document.createEvent('Event').timeStamp) {
8401 // if the low-res timestamp which is bigger than the event timestamp
8402 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
8403 // and we need to use the hi-res version for event listeners as well.
8404 _getNow = () => performance.now();
8405 }
8406 // To avoid the overhead of repeatedly calling performance.now(), we cache
8407 // and use the same timestamp for all event listeners attached in the same tick.
8408 let cachedNow = 0;
8409 const p = Promise.resolve();
8410 const reset = () => {
8411 cachedNow = 0;
8412 };
8413 const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
8414 function addEventListener(el, event, handler, options) {
8415 el.addEventListener(event, handler, options);
8416 }
8417 function removeEventListener(el, event, handler, options) {
8418 el.removeEventListener(event, handler, options);
8419 }
8420 function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
8421 // vei = vue event invokers
8422 const invokers = el._vei || (el._vei = {});
8423 const existingInvoker = invokers[rawName];
8424 if (nextValue && existingInvoker) {
8425 // patch
8426 existingInvoker.value = nextValue;
8427 }
8428 else {
8429 const [name, options] = parseName(rawName);
8430 if (nextValue) {
8431 // add
8432 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
8433 addEventListener(el, name, invoker, options);
8434 }
8435 else if (existingInvoker) {
8436 // remove
8437 removeEventListener(el, name, existingInvoker, options);
8438 invokers[rawName] = undefined;
8439 }
8440 }
8441 }
8442 const optionsModifierRE = /(?:Once|Passive|Capture)$/;
8443 function parseName(name) {
8444 let options;
8445 if (optionsModifierRE.test(name)) {
8446 options = {};
8447 let m;
8448 while ((m = name.match(optionsModifierRE))) {
8449 name = name.slice(0, name.length - m[0].length);
8450 options[m[0].toLowerCase()] = true;
8451 }
8452 }
8453 return [hyphenate(name.slice(2)), options];
8454 }
8455 function createInvoker(initialValue, instance) {
8456 const invoker = (e) => {
8457 // async edge case #6566: inner click event triggers patch, event handler
8458 // attached to outer element during patch, and triggered again. This
8459 // happens because browsers fire microtask ticks between event propagation.
8460 // the solution is simple: we save the timestamp when a handler is attached,
8461 // and the handler would only fire if the event passed to it was fired
8462 // AFTER it was attached.
8463 const timeStamp = e.timeStamp || _getNow();
8464 if (timeStamp >= invoker.attached - 1) {
8465 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
8466 }
8467 };
8468 invoker.value = initialValue;
8469 invoker.attached = getNow();
8470 return invoker;
8471 }
8472 function patchStopImmediatePropagation(e, value) {
8473 if (isArray(value)) {
8474 const originalStop = e.stopImmediatePropagation;
8475 e.stopImmediatePropagation = () => {
8476 originalStop.call(e);
8477 e._stopped = true;
8478 };
8479 return value.map(fn => (e) => !e._stopped && fn(e));
8480 }
8481 else {
8482 return value;
8483 }
8484 }
8485
8486 const nativeOnRE = /^on[a-z]/;
8487 const forcePatchProp = (_, key) => key === 'value';
8488 const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
8489 switch (key) {
8490 // special
8491 case 'class':
8492 patchClass(el, nextValue, isSVG);
8493 break;
8494 case 'style':
8495 patchStyle(el, prevValue, nextValue);
8496 break;
8497 default:
8498 if (isOn(key)) {
8499 // ignore v-model listeners
8500 if (!isModelListener(key)) {
8501 patchEvent(el, key, prevValue, nextValue, parentComponent);
8502 }
8503 }
8504 else if (shouldSetAsProp(el, key, nextValue, isSVG)) {
8505 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
8506 }
8507 else {
8508 // special case for <input v-model type="checkbox"> with
8509 // :true-value & :false-value
8510 // store value as dom properties since non-string values will be
8511 // stringified.
8512 if (key === 'true-value') {
8513 el._trueValue = nextValue;
8514 }
8515 else if (key === 'false-value') {
8516 el._falseValue = nextValue;
8517 }
8518 patchAttr(el, key, nextValue, isSVG);
8519 }
8520 break;
8521 }
8522 };
8523 function shouldSetAsProp(el, key, value, isSVG) {
8524 if (isSVG) {
8525 // most keys must be set as attribute on svg elements to work
8526 // ...except innerHTML
8527 if (key === 'innerHTML') {
8528 return true;
8529 }
8530 // or native onclick with function values
8531 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
8532 return true;
8533 }
8534 return false;
8535 }
8536 // spellcheck and draggable are numerated attrs, however their
8537 // corresponding DOM properties are actually booleans - this leads to
8538 // setting it with a string "false" value leading it to be coerced to
8539 // `true`, so we need to always treat them as attributes.
8540 // Note that `contentEditable` doesn't have this problem: its DOM
8541 // property is also enumerated string values.
8542 if (key === 'spellcheck' || key === 'draggable') {
8543 return false;
8544 }
8545 // #1787, #2840 form property on form elements is readonly and must be set as
8546 // attribute.
8547 if (key === 'form') {
8548 return false;
8549 }
8550 // #1526 <input list> must be set as attribute
8551 if (key === 'list' && el.tagName === 'INPUT') {
8552 return false;
8553 }
8554 // #2766 <textarea type> must be set as attribute
8555 if (key === 'type' && el.tagName === 'TEXTAREA') {
8556 return false;
8557 }
8558 // native onclick with string value, must be set as attribute
8559 if (nativeOnRE.test(key) && isString(value)) {
8560 return false;
8561 }
8562 return key in el;
8563 }
8564
8565 function useCssModule(name = '$style') {
8566 /* istanbul ignore else */
8567 {
8568 {
8569 warn(`useCssModule() is not supported in the global build.`);
8570 }
8571 return EMPTY_OBJ;
8572 }
8573 }
8574
8575 /**
8576 * Runtime helper for SFC's CSS variable injection feature.
8577 * @private
8578 */
8579 function useCssVars(getter) {
8580 const instance = getCurrentInstance();
8581 /* istanbul ignore next */
8582 if (!instance) {
8583 warn(`useCssVars is called without current active component instance.`);
8584 return;
8585 }
8586 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
8587 onMounted(() => watchEffect(setVars, { flush: 'post' }));
8588 onUpdated(setVars);
8589 }
8590 function setVarsOnVNode(vnode, vars) {
8591 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
8592 const suspense = vnode.suspense;
8593 vnode = suspense.activeBranch;
8594 if (suspense.pendingBranch && !suspense.isHydrating) {
8595 suspense.effects.push(() => {
8596 setVarsOnVNode(suspense.activeBranch, vars);
8597 });
8598 }
8599 }
8600 // drill down HOCs until it's a non-component vnode
8601 while (vnode.component) {
8602 vnode = vnode.component.subTree;
8603 }
8604 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
8605 const style = vnode.el.style;
8606 for (const key in vars) {
8607 style.setProperty(`--${key}`, vars[key]);
8608 }
8609 }
8610 else if (vnode.type === Fragment) {
8611 vnode.children.forEach(c => setVarsOnVNode(c, vars));
8612 }
8613 }
8614
8615 const TRANSITION = 'transition';
8616 const ANIMATION = 'animation';
8617 // DOM Transition is a higher-order-component based on the platform-agnostic
8618 // base Transition component, with DOM-specific logic.
8619 const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
8620 Transition.displayName = 'Transition';
8621 const DOMTransitionPropsValidators = {
8622 name: String,
8623 type: String,
8624 css: {
8625 type: Boolean,
8626 default: true
8627 },
8628 duration: [String, Number, Object],
8629 enterFromClass: String,
8630 enterActiveClass: String,
8631 enterToClass: String,
8632 appearFromClass: String,
8633 appearActiveClass: String,
8634 appearToClass: String,
8635 leaveFromClass: String,
8636 leaveActiveClass: String,
8637 leaveToClass: String
8638 };
8639 const TransitionPropsValidators = (Transition.props = /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
8640 function resolveTransitionProps(rawProps) {
8641 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;
8642 const baseProps = {};
8643 for (const key in rawProps) {
8644 if (!(key in DOMTransitionPropsValidators)) {
8645 baseProps[key] = rawProps[key];
8646 }
8647 }
8648 if (!css) {
8649 return baseProps;
8650 }
8651 const durations = normalizeDuration(duration);
8652 const enterDuration = durations && durations[0];
8653 const leaveDuration = durations && durations[1];
8654 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
8655 const finishEnter = (el, isAppear, done) => {
8656 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
8657 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
8658 done && done();
8659 };
8660 const finishLeave = (el, done) => {
8661 removeTransitionClass(el, leaveToClass);
8662 removeTransitionClass(el, leaveActiveClass);
8663 done && done();
8664 };
8665 const makeEnterHook = (isAppear) => {
8666 return (el, done) => {
8667 const hook = isAppear ? onAppear : onEnter;
8668 const resolve = () => finishEnter(el, isAppear, done);
8669 hook && hook(el, resolve);
8670 nextFrame(() => {
8671 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
8672 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
8673 if (!(hook && hook.length > 1)) {
8674 whenTransitionEnds(el, type, enterDuration, resolve);
8675 }
8676 });
8677 };
8678 };
8679 return extend(baseProps, {
8680 onBeforeEnter(el) {
8681 onBeforeEnter && onBeforeEnter(el);
8682 addTransitionClass(el, enterFromClass);
8683 addTransitionClass(el, enterActiveClass);
8684 },
8685 onBeforeAppear(el) {
8686 onBeforeAppear && onBeforeAppear(el);
8687 addTransitionClass(el, appearFromClass);
8688 addTransitionClass(el, appearActiveClass);
8689 },
8690 onEnter: makeEnterHook(false),
8691 onAppear: makeEnterHook(true),
8692 onLeave(el, done) {
8693 const resolve = () => finishLeave(el, done);
8694 addTransitionClass(el, leaveFromClass);
8695 // force reflow so *-leave-from classes immediately take effect (#2593)
8696 forceReflow();
8697 addTransitionClass(el, leaveActiveClass);
8698 nextFrame(() => {
8699 removeTransitionClass(el, leaveFromClass);
8700 addTransitionClass(el, leaveToClass);
8701 if (!(onLeave && onLeave.length > 1)) {
8702 whenTransitionEnds(el, type, leaveDuration, resolve);
8703 }
8704 });
8705 onLeave && onLeave(el, resolve);
8706 },
8707 onEnterCancelled(el) {
8708 finishEnter(el, false);
8709 onEnterCancelled && onEnterCancelled(el);
8710 },
8711 onAppearCancelled(el) {
8712 finishEnter(el, true);
8713 onAppearCancelled && onAppearCancelled(el);
8714 },
8715 onLeaveCancelled(el) {
8716 finishLeave(el);
8717 onLeaveCancelled && onLeaveCancelled(el);
8718 }
8719 });
8720 }
8721 function normalizeDuration(duration) {
8722 if (duration == null) {
8723 return null;
8724 }
8725 else if (isObject(duration)) {
8726 return [NumberOf(duration.enter), NumberOf(duration.leave)];
8727 }
8728 else {
8729 const n = NumberOf(duration);
8730 return [n, n];
8731 }
8732 }
8733 function NumberOf(val) {
8734 const res = toNumber(val);
8735 validateDuration(res);
8736 return res;
8737 }
8738 function validateDuration(val) {
8739 if (typeof val !== 'number') {
8740 warn(`<transition> explicit duration is not a valid number - ` +
8741 `got ${JSON.stringify(val)}.`);
8742 }
8743 else if (isNaN(val)) {
8744 warn(`<transition> explicit duration is NaN - ` +
8745 'the duration expression might be incorrect.');
8746 }
8747 }
8748 function addTransitionClass(el, cls) {
8749 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
8750 (el._vtc ||
8751 (el._vtc = new Set())).add(cls);
8752 }
8753 function removeTransitionClass(el, cls) {
8754 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
8755 const { _vtc } = el;
8756 if (_vtc) {
8757 _vtc.delete(cls);
8758 if (!_vtc.size) {
8759 el._vtc = undefined;
8760 }
8761 }
8762 }
8763 function nextFrame(cb) {
8764 requestAnimationFrame(() => {
8765 requestAnimationFrame(cb);
8766 });
8767 }
8768 let endId = 0;
8769 function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
8770 const id = (el._endId = ++endId);
8771 const resolveIfNotStale = () => {
8772 if (id === el._endId) {
8773 resolve();
8774 }
8775 };
8776 if (explicitTimeout) {
8777 return setTimeout(resolveIfNotStale, explicitTimeout);
8778 }
8779 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
8780 if (!type) {
8781 return resolve();
8782 }
8783 const endEvent = type + 'end';
8784 let ended = 0;
8785 const end = () => {
8786 el.removeEventListener(endEvent, onEnd);
8787 resolveIfNotStale();
8788 };
8789 const onEnd = (e) => {
8790 if (e.target === el && ++ended >= propCount) {
8791 end();
8792 }
8793 };
8794 setTimeout(() => {
8795 if (ended < propCount) {
8796 end();
8797 }
8798 }, timeout + 1);
8799 el.addEventListener(endEvent, onEnd);
8800 }
8801 function getTransitionInfo(el, expectedType) {
8802 const styles = window.getComputedStyle(el);
8803 // JSDOM may return undefined for transition properties
8804 const getStyleProperties = (key) => (styles[key] || '').split(', ');
8805 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
8806 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
8807 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
8808 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
8809 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
8810 const animationTimeout = getTimeout(animationDelays, animationDurations);
8811 let type = null;
8812 let timeout = 0;
8813 let propCount = 0;
8814 /* istanbul ignore if */
8815 if (expectedType === TRANSITION) {
8816 if (transitionTimeout > 0) {
8817 type = TRANSITION;
8818 timeout = transitionTimeout;
8819 propCount = transitionDurations.length;
8820 }
8821 }
8822 else if (expectedType === ANIMATION) {
8823 if (animationTimeout > 0) {
8824 type = ANIMATION;
8825 timeout = animationTimeout;
8826 propCount = animationDurations.length;
8827 }
8828 }
8829 else {
8830 timeout = Math.max(transitionTimeout, animationTimeout);
8831 type =
8832 timeout > 0
8833 ? transitionTimeout > animationTimeout
8834 ? TRANSITION
8835 : ANIMATION
8836 : null;
8837 propCount = type
8838 ? type === TRANSITION
8839 ? transitionDurations.length
8840 : animationDurations.length
8841 : 0;
8842 }
8843 const hasTransform = type === TRANSITION &&
8844 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
8845 return {
8846 type,
8847 timeout,
8848 propCount,
8849 hasTransform
8850 };
8851 }
8852 function getTimeout(delays, durations) {
8853 while (delays.length < durations.length) {
8854 delays = delays.concat(delays);
8855 }
8856 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
8857 }
8858 // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
8859 // numbers in a locale-dependent way, using a comma instead of a dot.
8860 // If comma is not replaced with a dot, the input will be rounded down
8861 // (i.e. acting as a floor function) causing unexpected behaviors
8862 function toMs(s) {
8863 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
8864 }
8865 // synchronously force layout to put elements into a certain state
8866 function forceReflow() {
8867 return document.body.offsetHeight;
8868 }
8869
8870 const positionMap = new WeakMap();
8871 const newPositionMap = new WeakMap();
8872 const TransitionGroupImpl = {
8873 name: 'TransitionGroup',
8874 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
8875 tag: String,
8876 moveClass: String
8877 }),
8878 setup(props, { slots }) {
8879 const instance = getCurrentInstance();
8880 const state = useTransitionState();
8881 let prevChildren;
8882 let children;
8883 onUpdated(() => {
8884 // children is guaranteed to exist after initial render
8885 if (!prevChildren.length) {
8886 return;
8887 }
8888 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
8889 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
8890 return;
8891 }
8892 // we divide the work into three loops to avoid mixing DOM reads and writes
8893 // in each iteration - which helps prevent layout thrashing.
8894 prevChildren.forEach(callPendingCbs);
8895 prevChildren.forEach(recordPosition);
8896 const movedChildren = prevChildren.filter(applyTranslation);
8897 // force reflow to put everything in position
8898 forceReflow();
8899 movedChildren.forEach(c => {
8900 const el = c.el;
8901 const style = el.style;
8902 addTransitionClass(el, moveClass);
8903 style.transform = style.webkitTransform = style.transitionDuration = '';
8904 const cb = (el._moveCb = (e) => {
8905 if (e && e.target !== el) {
8906 return;
8907 }
8908 if (!e || /transform$/.test(e.propertyName)) {
8909 el.removeEventListener('transitionend', cb);
8910 el._moveCb = null;
8911 removeTransitionClass(el, moveClass);
8912 }
8913 });
8914 el.addEventListener('transitionend', cb);
8915 });
8916 });
8917 return () => {
8918 const rawProps = toRaw(props);
8919 const cssTransitionProps = resolveTransitionProps(rawProps);
8920 const tag = rawProps.tag || Fragment;
8921 prevChildren = children;
8922 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
8923 for (let i = 0; i < children.length; i++) {
8924 const child = children[i];
8925 if (child.key != null) {
8926 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
8927 }
8928 else {
8929 warn(`<TransitionGroup> children must be keyed.`);
8930 }
8931 }
8932 if (prevChildren) {
8933 for (let i = 0; i < prevChildren.length; i++) {
8934 const child = prevChildren[i];
8935 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
8936 positionMap.set(child, child.el.getBoundingClientRect());
8937 }
8938 }
8939 return createVNode(tag, null, children);
8940 };
8941 }
8942 };
8943 const TransitionGroup = TransitionGroupImpl;
8944 function callPendingCbs(c) {
8945 const el = c.el;
8946 if (el._moveCb) {
8947 el._moveCb();
8948 }
8949 if (el._enterCb) {
8950 el._enterCb();
8951 }
8952 }
8953 function recordPosition(c) {
8954 newPositionMap.set(c, c.el.getBoundingClientRect());
8955 }
8956 function applyTranslation(c) {
8957 const oldPos = positionMap.get(c);
8958 const newPos = newPositionMap.get(c);
8959 const dx = oldPos.left - newPos.left;
8960 const dy = oldPos.top - newPos.top;
8961 if (dx || dy) {
8962 const s = c.el.style;
8963 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
8964 s.transitionDuration = '0s';
8965 return c;
8966 }
8967 }
8968 function hasCSSTransform(el, root, moveClass) {
8969 // Detect whether an element with the move class applied has
8970 // CSS transitions. Since the element may be inside an entering
8971 // transition at this very moment, we make a clone of it and remove
8972 // all other transition classes applied to ensure only the move class
8973 // is applied.
8974 const clone = el.cloneNode();
8975 if (el._vtc) {
8976 el._vtc.forEach(cls => {
8977 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
8978 });
8979 }
8980 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
8981 clone.style.display = 'none';
8982 const container = (root.nodeType === 1
8983 ? root
8984 : root.parentNode);
8985 container.appendChild(clone);
8986 const { hasTransform } = getTransitionInfo(clone);
8987 container.removeChild(clone);
8988 return hasTransform;
8989 }
8990
8991 const getModelAssigner = (vnode) => {
8992 const fn = vnode.props['onUpdate:modelValue'];
8993 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
8994 };
8995 function onCompositionStart(e) {
8996 e.target.composing = true;
8997 }
8998 function onCompositionEnd(e) {
8999 const target = e.target;
9000 if (target.composing) {
9001 target.composing = false;
9002 trigger$1(target, 'input');
9003 }
9004 }
9005 function trigger$1(el, type) {
9006 const e = document.createEvent('HTMLEvents');
9007 e.initEvent(type, true, true);
9008 el.dispatchEvent(e);
9009 }
9010 // We are exporting the v-model runtime directly as vnode hooks so that it can
9011 // be tree-shaken in case v-model is never used.
9012 const vModelText = {
9013 created(el, { modifiers: { lazy, trim, number } }, vnode) {
9014 el._assign = getModelAssigner(vnode);
9015 const castToNumber = number || el.type === 'number';
9016 addEventListener(el, lazy ? 'change' : 'input', e => {
9017 if (e.target.composing)
9018 return;
9019 let domValue = el.value;
9020 if (trim) {
9021 domValue = domValue.trim();
9022 }
9023 else if (castToNumber) {
9024 domValue = toNumber(domValue);
9025 }
9026 el._assign(domValue);
9027 });
9028 if (trim) {
9029 addEventListener(el, 'change', () => {
9030 el.value = el.value.trim();
9031 });
9032 }
9033 if (!lazy) {
9034 addEventListener(el, 'compositionstart', onCompositionStart);
9035 addEventListener(el, 'compositionend', onCompositionEnd);
9036 // Safari < 10.2 & UIWebView doesn't fire compositionend when
9037 // switching focus before confirming composition choice
9038 // this also fixes the issue where some browsers e.g. iOS Chrome
9039 // fires "change" instead of "input" on autocomplete.
9040 addEventListener(el, 'change', onCompositionEnd);
9041 }
9042 },
9043 // set value on mounted so it's after min/max for type="range"
9044 mounted(el, { value }) {
9045 el.value = value == null ? '' : value;
9046 },
9047 beforeUpdate(el, { value, modifiers: { trim, number } }, vnode) {
9048 el._assign = getModelAssigner(vnode);
9049 // avoid clearing unresolved text. #2302
9050 if (el.composing)
9051 return;
9052 if (document.activeElement === el) {
9053 if (trim && el.value.trim() === value) {
9054 return;
9055 }
9056 if ((number || el.type === 'number') && toNumber(el.value) === value) {
9057 return;
9058 }
9059 }
9060 const newValue = value == null ? '' : value;
9061 if (el.value !== newValue) {
9062 el.value = newValue;
9063 }
9064 }
9065 };
9066 const vModelCheckbox = {
9067 created(el, _, vnode) {
9068 el._assign = getModelAssigner(vnode);
9069 addEventListener(el, 'change', () => {
9070 const modelValue = el._modelValue;
9071 const elementValue = getValue(el);
9072 const checked = el.checked;
9073 const assign = el._assign;
9074 if (isArray(modelValue)) {
9075 const index = looseIndexOf(modelValue, elementValue);
9076 const found = index !== -1;
9077 if (checked && !found) {
9078 assign(modelValue.concat(elementValue));
9079 }
9080 else if (!checked && found) {
9081 const filtered = [...modelValue];
9082 filtered.splice(index, 1);
9083 assign(filtered);
9084 }
9085 }
9086 else if (isSet(modelValue)) {
9087 const cloned = new Set(modelValue);
9088 if (checked) {
9089 cloned.add(elementValue);
9090 }
9091 else {
9092 cloned.delete(elementValue);
9093 }
9094 assign(cloned);
9095 }
9096 else {
9097 assign(getCheckboxValue(el, checked));
9098 }
9099 });
9100 },
9101 // set initial checked on mount to wait for true-value/false-value
9102 mounted: setChecked,
9103 beforeUpdate(el, binding, vnode) {
9104 el._assign = getModelAssigner(vnode);
9105 setChecked(el, binding, vnode);
9106 }
9107 };
9108 function setChecked(el, { value, oldValue }, vnode) {
9109 el._modelValue = value;
9110 if (isArray(value)) {
9111 el.checked = looseIndexOf(value, vnode.props.value) > -1;
9112 }
9113 else if (isSet(value)) {
9114 el.checked = value.has(vnode.props.value);
9115 }
9116 else if (value !== oldValue) {
9117 el.checked = looseEqual(value, getCheckboxValue(el, true));
9118 }
9119 }
9120 const vModelRadio = {
9121 created(el, { value }, vnode) {
9122 el.checked = looseEqual(value, vnode.props.value);
9123 el._assign = getModelAssigner(vnode);
9124 addEventListener(el, 'change', () => {
9125 el._assign(getValue(el));
9126 });
9127 },
9128 beforeUpdate(el, { value, oldValue }, vnode) {
9129 el._assign = getModelAssigner(vnode);
9130 if (value !== oldValue) {
9131 el.checked = looseEqual(value, vnode.props.value);
9132 }
9133 }
9134 };
9135 const vModelSelect = {
9136 created(el, { value, modifiers: { number } }, vnode) {
9137 const isSetModel = isSet(value);
9138 addEventListener(el, 'change', () => {
9139 const selectedVal = Array.prototype.filter
9140 .call(el.options, (o) => o.selected)
9141 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
9142 el._assign(el.multiple
9143 ? isSetModel
9144 ? new Set(selectedVal)
9145 : selectedVal
9146 : selectedVal[0]);
9147 });
9148 el._assign = getModelAssigner(vnode);
9149 },
9150 // set value in mounted & updated because <select> relies on its children
9151 // <option>s.
9152 mounted(el, { value }) {
9153 setSelected(el, value);
9154 },
9155 beforeUpdate(el, _binding, vnode) {
9156 el._assign = getModelAssigner(vnode);
9157 },
9158 updated(el, { value }) {
9159 setSelected(el, value);
9160 }
9161 };
9162 function setSelected(el, value) {
9163 const isMultiple = el.multiple;
9164 if (isMultiple && !isArray(value) && !isSet(value)) {
9165 warn(`<select multiple v-model> expects an Array or Set value for its binding, ` +
9166 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
9167 return;
9168 }
9169 for (let i = 0, l = el.options.length; i < l; i++) {
9170 const option = el.options[i];
9171 const optionValue = getValue(option);
9172 if (isMultiple) {
9173 if (isArray(value)) {
9174 option.selected = looseIndexOf(value, optionValue) > -1;
9175 }
9176 else {
9177 option.selected = value.has(optionValue);
9178 }
9179 }
9180 else {
9181 if (looseEqual(getValue(option), value)) {
9182 el.selectedIndex = i;
9183 return;
9184 }
9185 }
9186 }
9187 if (!isMultiple) {
9188 el.selectedIndex = -1;
9189 }
9190 }
9191 // retrieve raw value set via :value bindings
9192 function getValue(el) {
9193 return '_value' in el ? el._value : el.value;
9194 }
9195 // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
9196 function getCheckboxValue(el, checked) {
9197 const key = checked ? '_trueValue' : '_falseValue';
9198 return key in el ? el[key] : checked;
9199 }
9200 const vModelDynamic = {
9201 created(el, binding, vnode) {
9202 callModelHook(el, binding, vnode, null, 'created');
9203 },
9204 mounted(el, binding, vnode) {
9205 callModelHook(el, binding, vnode, null, 'mounted');
9206 },
9207 beforeUpdate(el, binding, vnode, prevVNode) {
9208 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
9209 },
9210 updated(el, binding, vnode, prevVNode) {
9211 callModelHook(el, binding, vnode, prevVNode, 'updated');
9212 }
9213 };
9214 function callModelHook(el, binding, vnode, prevVNode, hook) {
9215 let modelToUse;
9216 switch (el.tagName) {
9217 case 'SELECT':
9218 modelToUse = vModelSelect;
9219 break;
9220 case 'TEXTAREA':
9221 modelToUse = vModelText;
9222 break;
9223 default:
9224 switch (vnode.props && vnode.props.type) {
9225 case 'checkbox':
9226 modelToUse = vModelCheckbox;
9227 break;
9228 case 'radio':
9229 modelToUse = vModelRadio;
9230 break;
9231 default:
9232 modelToUse = vModelText;
9233 }
9234 }
9235 const fn = modelToUse[hook];
9236 fn && fn(el, binding, vnode, prevVNode);
9237 }
9238
9239 const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
9240 const modifierGuards = {
9241 stop: e => e.stopPropagation(),
9242 prevent: e => e.preventDefault(),
9243 self: e => e.target !== e.currentTarget,
9244 ctrl: e => !e.ctrlKey,
9245 shift: e => !e.shiftKey,
9246 alt: e => !e.altKey,
9247 meta: e => !e.metaKey,
9248 left: e => 'button' in e && e.button !== 0,
9249 middle: e => 'button' in e && e.button !== 1,
9250 right: e => 'button' in e && e.button !== 2,
9251 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
9252 };
9253 /**
9254 * @private
9255 */
9256 const withModifiers = (fn, modifiers) => {
9257 return (event, ...args) => {
9258 for (let i = 0; i < modifiers.length; i++) {
9259 const guard = modifierGuards[modifiers[i]];
9260 if (guard && guard(event, modifiers))
9261 return;
9262 }
9263 return fn(event, ...args);
9264 };
9265 };
9266 // Kept for 2.x compat.
9267 // Note: IE11 compat for `spacebar` and `del` is removed for now.
9268 const keyNames = {
9269 esc: 'escape',
9270 space: ' ',
9271 up: 'arrow-up',
9272 left: 'arrow-left',
9273 right: 'arrow-right',
9274 down: 'arrow-down',
9275 delete: 'backspace'
9276 };
9277 /**
9278 * @private
9279 */
9280 const withKeys = (fn, modifiers) => {
9281 return (event) => {
9282 if (!('key' in event))
9283 return;
9284 const eventKey = hyphenate(event.key);
9285 if (
9286 // None of the provided key modifiers match the current event key
9287 !modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
9288 return;
9289 }
9290 return fn(event);
9291 };
9292 };
9293
9294 const vShow = {
9295 beforeMount(el, { value }, { transition }) {
9296 el._vod = el.style.display === 'none' ? '' : el.style.display;
9297 if (transition && value) {
9298 transition.beforeEnter(el);
9299 }
9300 else {
9301 setDisplay(el, value);
9302 }
9303 },
9304 mounted(el, { value }, { transition }) {
9305 if (transition && value) {
9306 transition.enter(el);
9307 }
9308 },
9309 updated(el, { value, oldValue }, { transition }) {
9310 if (!value === !oldValue)
9311 return;
9312 if (transition) {
9313 if (value) {
9314 transition.beforeEnter(el);
9315 setDisplay(el, true);
9316 transition.enter(el);
9317 }
9318 else {
9319 transition.leave(el, () => {
9320 setDisplay(el, false);
9321 });
9322 }
9323 }
9324 else {
9325 setDisplay(el, value);
9326 }
9327 },
9328 beforeUnmount(el, { value }) {
9329 setDisplay(el, value);
9330 }
9331 };
9332 function setDisplay(el, value) {
9333 el.style.display = value ? el._vod : 'none';
9334 }
9335
9336 const rendererOptions = extend({ patchProp, forcePatchProp }, nodeOps);
9337 // lazy create the renderer - this makes core renderer logic tree-shakable
9338 // in case the user only imports reactivity utilities from Vue.
9339 let renderer;
9340 let enabledHydration = false;
9341 function ensureRenderer() {
9342 return renderer || (renderer = createRenderer(rendererOptions));
9343 }
9344 function ensureHydrationRenderer() {
9345 renderer = enabledHydration
9346 ? renderer
9347 : createHydrationRenderer(rendererOptions);
9348 enabledHydration = true;
9349 return renderer;
9350 }
9351 // use explicit type casts here to avoid import() calls in rolled-up d.ts
9352 const render = ((...args) => {
9353 ensureRenderer().render(...args);
9354 });
9355 const hydrate = ((...args) => {
9356 ensureHydrationRenderer().hydrate(...args);
9357 });
9358 const createApp = ((...args) => {
9359 const app = ensureRenderer().createApp(...args);
9360 {
9361 injectNativeTagCheck(app);
9362 injectCustomElementCheck(app);
9363 }
9364 const { mount } = app;
9365 app.mount = (containerOrSelector) => {
9366 const container = normalizeContainer(containerOrSelector);
9367 if (!container)
9368 return;
9369 const component = app._component;
9370 if (!isFunction(component) && !component.render && !component.template) {
9371 component.template = container.innerHTML;
9372 }
9373 // clear content before mounting
9374 container.innerHTML = '';
9375 const proxy = mount(container);
9376 if (container instanceof Element) {
9377 container.removeAttribute('v-cloak');
9378 container.setAttribute('data-v-app', '');
9379 }
9380 return proxy;
9381 };
9382 return app;
9383 });
9384 const createSSRApp = ((...args) => {
9385 const app = ensureHydrationRenderer().createApp(...args);
9386 {
9387 injectNativeTagCheck(app);
9388 injectCustomElementCheck(app);
9389 }
9390 const { mount } = app;
9391 app.mount = (containerOrSelector) => {
9392 const container = normalizeContainer(containerOrSelector);
9393 if (container) {
9394 return mount(container, true);
9395 }
9396 };
9397 return app;
9398 });
9399 function injectNativeTagCheck(app) {
9400 // Inject `isNativeTag`
9401 // this is used for component name validation (dev only)
9402 Object.defineProperty(app.config, 'isNativeTag', {
9403 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
9404 writable: false
9405 });
9406 }
9407 // dev only
9408 function injectCustomElementCheck(app) {
9409 if (isRuntimeOnly()) {
9410 const value = app.config.isCustomElement;
9411 Object.defineProperty(app.config, 'isCustomElement', {
9412 get() {
9413 return value;
9414 },
9415 set() {
9416 warn(`The \`isCustomElement\` config option is only respected when using the runtime compiler.` +
9417 `If you are using the runtime-only build, \`isCustomElement\` must be passed to \`@vue/compiler-dom\` in the build setup instead` +
9418 `- for example, via the \`compilerOptions\` option in vue-loader: https://vue-loader.vuejs.org/options.html#compileroptions.`);
9419 }
9420 });
9421 }
9422 }
9423 function normalizeContainer(container) {
9424 if (isString(container)) {
9425 const res = document.querySelector(container);
9426 if (!res) {
9427 warn(`Failed to mount app: mount target selector "${container}" returned null.`);
9428 }
9429 return res;
9430 }
9431 if (container instanceof window.ShadowRoot &&
9432 container.mode === 'closed') {
9433 warn(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
9434 }
9435 return container;
9436 }
9437
9438 function initDev() {
9439 {
9440 {
9441 console.info(`You are running a development build of Vue.\n` +
9442 `Make sure to use the production build (*.prod.js) when deploying for production.`);
9443 }
9444 initCustomFormatter();
9445 }
9446 }
9447
9448 function defaultOnError(error) {
9449 throw error;
9450 }
9451 function createCompilerError(code, loc, messages, additionalMessage) {
9452 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
9453 ;
9454 const error = new SyntaxError(String(msg));
9455 error.code = code;
9456 error.loc = loc;
9457 return error;
9458 }
9459 const errorMessages = {
9460 // parse errors
9461 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
9462 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
9463 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
9464 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
9465 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
9466 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
9467 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
9468 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
9469 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
9470 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
9471 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
9472 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
9473 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
9474 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
9475 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
9476 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
9477 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
9478 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
9479 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
9480 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
9481 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
9482 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
9483 // Vue-specific parse errors
9484 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
9485 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
9486 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
9487 [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
9488 'Note that dynamic directive argument cannot contain spaces.',
9489 // transform errors
9490 [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
9491 [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
9492 [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
9493 [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
9494 [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
9495 [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
9496 [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
9497 [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
9498 [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
9499 [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
9500 `When there are multiple named slots, all slots should use <template> ` +
9501 `syntax to avoid scope ambiguity.`,
9502 [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
9503 [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
9504 `default slot. These children will be ignored.`,
9505 [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
9506 [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
9507 [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
9508 [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.`,
9509 [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
9510 [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
9511 // generic errors
9512 [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
9513 [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
9514 [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
9515 [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`
9516 };
9517
9518 const FRAGMENT = Symbol(`Fragment` );
9519 const TELEPORT = Symbol(`Teleport` );
9520 const SUSPENSE = Symbol(`Suspense` );
9521 const KEEP_ALIVE = Symbol(`KeepAlive` );
9522 const BASE_TRANSITION = Symbol(`BaseTransition` );
9523 const OPEN_BLOCK = Symbol(`openBlock` );
9524 const CREATE_BLOCK = Symbol(`createBlock` );
9525 const CREATE_VNODE = Symbol(`createVNode` );
9526 const CREATE_COMMENT = Symbol(`createCommentVNode` );
9527 const CREATE_TEXT = Symbol(`createTextVNode` );
9528 const CREATE_STATIC = Symbol(`createStaticVNode` );
9529 const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
9530 const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
9531 const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
9532 const WITH_DIRECTIVES = Symbol(`withDirectives` );
9533 const RENDER_LIST = Symbol(`renderList` );
9534 const RENDER_SLOT = Symbol(`renderSlot` );
9535 const CREATE_SLOTS = Symbol(`createSlots` );
9536 const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
9537 const MERGE_PROPS = Symbol(`mergeProps` );
9538 const TO_HANDLERS = Symbol(`toHandlers` );
9539 const CAMELIZE = Symbol(`camelize` );
9540 const CAPITALIZE = Symbol(`capitalize` );
9541 const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
9542 const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
9543 const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
9544 const POP_SCOPE_ID = Symbol(`popScopeId` );
9545 const WITH_SCOPE_ID = Symbol(`withScopeId` );
9546 const WITH_CTX = Symbol(`withCtx` );
9547 const UNREF = Symbol(`unref` );
9548 const IS_REF = Symbol(`isRef` );
9549 // Name mapping for runtime helpers that need to be imported from 'vue' in
9550 // generated code. Make sure these are correctly exported in the runtime!
9551 // Using `any` here because TS doesn't allow symbols as index type.
9552 const helperNameMap = {
9553 [FRAGMENT]: `Fragment`,
9554 [TELEPORT]: `Teleport`,
9555 [SUSPENSE]: `Suspense`,
9556 [KEEP_ALIVE]: `KeepAlive`,
9557 [BASE_TRANSITION]: `BaseTransition`,
9558 [OPEN_BLOCK]: `openBlock`,
9559 [CREATE_BLOCK]: `createBlock`,
9560 [CREATE_VNODE]: `createVNode`,
9561 [CREATE_COMMENT]: `createCommentVNode`,
9562 [CREATE_TEXT]: `createTextVNode`,
9563 [CREATE_STATIC]: `createStaticVNode`,
9564 [RESOLVE_COMPONENT]: `resolveComponent`,
9565 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
9566 [RESOLVE_DIRECTIVE]: `resolveDirective`,
9567 [WITH_DIRECTIVES]: `withDirectives`,
9568 [RENDER_LIST]: `renderList`,
9569 [RENDER_SLOT]: `renderSlot`,
9570 [CREATE_SLOTS]: `createSlots`,
9571 [TO_DISPLAY_STRING]: `toDisplayString`,
9572 [MERGE_PROPS]: `mergeProps`,
9573 [TO_HANDLERS]: `toHandlers`,
9574 [CAMELIZE]: `camelize`,
9575 [CAPITALIZE]: `capitalize`,
9576 [TO_HANDLER_KEY]: `toHandlerKey`,
9577 [SET_BLOCK_TRACKING]: `setBlockTracking`,
9578 [PUSH_SCOPE_ID]: `pushScopeId`,
9579 [POP_SCOPE_ID]: `popScopeId`,
9580 [WITH_SCOPE_ID]: `withScopeId`,
9581 [WITH_CTX]: `withCtx`,
9582 [UNREF]: `unref`,
9583 [IS_REF]: `isRef`
9584 };
9585 function registerRuntimeHelpers(helpers) {
9586 Object.getOwnPropertySymbols(helpers).forEach(s => {
9587 helperNameMap[s] = helpers[s];
9588 });
9589 }
9590
9591 // AST Utilities ---------------------------------------------------------------
9592 // Some expressions, e.g. sequence and conditional expressions, are never
9593 // associated with template nodes, so their source locations are just a stub.
9594 // Container types like CompoundExpression also don't need a real location.
9595 const locStub = {
9596 source: '',
9597 start: { line: 1, column: 1, offset: 0 },
9598 end: { line: 1, column: 1, offset: 0 }
9599 };
9600 function createRoot(children, loc = locStub) {
9601 return {
9602 type: 0 /* ROOT */,
9603 children,
9604 helpers: [],
9605 components: [],
9606 directives: [],
9607 hoists: [],
9608 imports: [],
9609 cached: 0,
9610 temps: 0,
9611 codegenNode: undefined,
9612 loc
9613 };
9614 }
9615 function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
9616 if (context) {
9617 if (isBlock) {
9618 context.helper(OPEN_BLOCK);
9619 context.helper(CREATE_BLOCK);
9620 }
9621 else {
9622 context.helper(CREATE_VNODE);
9623 }
9624 if (directives) {
9625 context.helper(WITH_DIRECTIVES);
9626 }
9627 }
9628 return {
9629 type: 13 /* VNODE_CALL */,
9630 tag,
9631 props,
9632 children,
9633 patchFlag,
9634 dynamicProps,
9635 directives,
9636 isBlock,
9637 disableTracking,
9638 loc
9639 };
9640 }
9641 function createArrayExpression(elements, loc = locStub) {
9642 return {
9643 type: 17 /* JS_ARRAY_EXPRESSION */,
9644 loc,
9645 elements
9646 };
9647 }
9648 function createObjectExpression(properties, loc = locStub) {
9649 return {
9650 type: 15 /* JS_OBJECT_EXPRESSION */,
9651 loc,
9652 properties
9653 };
9654 }
9655 function createObjectProperty(key, value) {
9656 return {
9657 type: 16 /* JS_PROPERTY */,
9658 loc: locStub,
9659 key: isString(key) ? createSimpleExpression(key, true) : key,
9660 value
9661 };
9662 }
9663 function createSimpleExpression(content, isStatic, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
9664 return {
9665 type: 4 /* SIMPLE_EXPRESSION */,
9666 loc,
9667 content,
9668 isStatic,
9669 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
9670 };
9671 }
9672 function createCompoundExpression(children, loc = locStub) {
9673 return {
9674 type: 8 /* COMPOUND_EXPRESSION */,
9675 loc,
9676 children
9677 };
9678 }
9679 function createCallExpression(callee, args = [], loc = locStub) {
9680 return {
9681 type: 14 /* JS_CALL_EXPRESSION */,
9682 loc,
9683 callee,
9684 arguments: args
9685 };
9686 }
9687 function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
9688 return {
9689 type: 18 /* JS_FUNCTION_EXPRESSION */,
9690 params,
9691 returns,
9692 newline,
9693 isSlot,
9694 loc
9695 };
9696 }
9697 function createConditionalExpression(test, consequent, alternate, newline = true) {
9698 return {
9699 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
9700 test,
9701 consequent,
9702 alternate,
9703 newline,
9704 loc: locStub
9705 };
9706 }
9707 function createCacheExpression(index, value, isVNode = false) {
9708 return {
9709 type: 20 /* JS_CACHE_EXPRESSION */,
9710 index,
9711 value,
9712 isVNode,
9713 loc: locStub
9714 };
9715 }
9716
9717 const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
9718 const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
9719 function isCoreComponent(tag) {
9720 if (isBuiltInType(tag, 'Teleport')) {
9721 return TELEPORT;
9722 }
9723 else if (isBuiltInType(tag, 'Suspense')) {
9724 return SUSPENSE;
9725 }
9726 else if (isBuiltInType(tag, 'KeepAlive')) {
9727 return KEEP_ALIVE;
9728 }
9729 else if (isBuiltInType(tag, 'BaseTransition')) {
9730 return BASE_TRANSITION;
9731 }
9732 }
9733 const nonIdentifierRE = /^\d|[^\$\w]/;
9734 const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
9735 const memberExpRE = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*|\[[^\]]+\])*$/;
9736 const isMemberExpression = (path) => {
9737 if (!path)
9738 return false;
9739 return memberExpRE.test(path.trim());
9740 };
9741 function getInnerRange(loc, offset, length) {
9742 const source = loc.source.substr(offset, length);
9743 const newLoc = {
9744 source,
9745 start: advancePositionWithClone(loc.start, loc.source, offset),
9746 end: loc.end
9747 };
9748 if (length != null) {
9749 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
9750 }
9751 return newLoc;
9752 }
9753 function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
9754 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
9755 }
9756 // advance by mutation without cloning (for performance reasons), since this
9757 // gets called a lot in the parser
9758 function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
9759 let linesCount = 0;
9760 let lastNewLinePos = -1;
9761 for (let i = 0; i < numberOfCharacters; i++) {
9762 if (source.charCodeAt(i) === 10 /* newline char code */) {
9763 linesCount++;
9764 lastNewLinePos = i;
9765 }
9766 }
9767 pos.offset += numberOfCharacters;
9768 pos.line += linesCount;
9769 pos.column =
9770 lastNewLinePos === -1
9771 ? pos.column + numberOfCharacters
9772 : numberOfCharacters - lastNewLinePos;
9773 return pos;
9774 }
9775 function assert(condition, msg) {
9776 /* istanbul ignore if */
9777 if (!condition) {
9778 throw new Error(msg || `unexpected compiler condition`);
9779 }
9780 }
9781 function findDir(node, name, allowEmpty = false) {
9782 for (let i = 0; i < node.props.length; i++) {
9783 const p = node.props[i];
9784 if (p.type === 7 /* DIRECTIVE */ &&
9785 (allowEmpty || p.exp) &&
9786 (isString(name) ? p.name === name : name.test(p.name))) {
9787 return p;
9788 }
9789 }
9790 }
9791 function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
9792 for (let i = 0; i < node.props.length; i++) {
9793 const p = node.props[i];
9794 if (p.type === 6 /* ATTRIBUTE */) {
9795 if (dynamicOnly)
9796 continue;
9797 if (p.name === name && (p.value || allowEmpty)) {
9798 return p;
9799 }
9800 }
9801 else if (p.name === 'bind' &&
9802 (p.exp || allowEmpty) &&
9803 isBindKey(p.arg, name)) {
9804 return p;
9805 }
9806 }
9807 }
9808 function isBindKey(arg, name) {
9809 return !!(arg && isStaticExp(arg) && arg.content === name);
9810 }
9811 function hasDynamicKeyVBind(node) {
9812 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
9813 p.name === 'bind' &&
9814 (!p.arg || // v-bind="obj"
9815 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
9816 !p.arg.isStatic) // v-bind:[foo]
9817 );
9818 }
9819 function isText(node) {
9820 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
9821 }
9822 function isVSlot(p) {
9823 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
9824 }
9825 function isTemplateNode(node) {
9826 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
9827 }
9828 function isSlotOutlet(node) {
9829 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
9830 }
9831 function injectProp(node, prop, context) {
9832 let propsWithInjection;
9833 const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
9834 if (props == null || isString(props)) {
9835 propsWithInjection = createObjectExpression([prop]);
9836 }
9837 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
9838 // merged props... add ours
9839 // only inject key to object literal if it's the first argument so that
9840 // if doesn't override user provided keys
9841 const first = props.arguments[0];
9842 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
9843 first.properties.unshift(prop);
9844 }
9845 else {
9846 if (props.callee === TO_HANDLERS) {
9847 // #2366
9848 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
9849 createObjectExpression([prop]),
9850 props
9851 ]);
9852 }
9853 else {
9854 props.arguments.unshift(createObjectExpression([prop]));
9855 }
9856 }
9857 !propsWithInjection && (propsWithInjection = props);
9858 }
9859 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
9860 let alreadyExists = false;
9861 // check existing key to avoid overriding user provided keys
9862 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
9863 const propKeyName = prop.key.content;
9864 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
9865 p.key.content === propKeyName);
9866 }
9867 if (!alreadyExists) {
9868 props.properties.unshift(prop);
9869 }
9870 propsWithInjection = props;
9871 }
9872 else {
9873 // single v-bind with expression, return a merged replacement
9874 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
9875 createObjectExpression([prop]),
9876 props
9877 ]);
9878 }
9879 if (node.type === 13 /* VNODE_CALL */) {
9880 node.props = propsWithInjection;
9881 }
9882 else {
9883 node.arguments[2] = propsWithInjection;
9884 }
9885 }
9886 function toValidAssetId(name, type) {
9887 return `_${type}_${name.replace(/[^\w]/g, '_')}`;
9888 }
9889
9890 // The default decoder only provides escapes for characters reserved as part of
9891 // the template syntax, and is only used if the custom renderer did not provide
9892 // a platform-specific decoder.
9893 const decodeRE = /&(gt|lt|amp|apos|quot);/g;
9894 const decodeMap = {
9895 gt: '>',
9896 lt: '<',
9897 amp: '&',
9898 apos: "'",
9899 quot: '"'
9900 };
9901 const defaultParserOptions = {
9902 delimiters: [`{{`, `}}`],
9903 getNamespace: () => 0 /* HTML */,
9904 getTextMode: () => 0 /* DATA */,
9905 isVoidTag: NO,
9906 isPreTag: NO,
9907 isCustomElement: NO,
9908 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
9909 onError: defaultOnError,
9910 comments: false
9911 };
9912 function baseParse(content, options = {}) {
9913 const context = createParserContext(content, options);
9914 const start = getCursor(context);
9915 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
9916 }
9917 function createParserContext(content, rawOptions) {
9918 const options = extend({}, defaultParserOptions);
9919 for (const key in rawOptions) {
9920 // @ts-ignore
9921 options[key] = rawOptions[key] || defaultParserOptions[key];
9922 }
9923 return {
9924 options,
9925 column: 1,
9926 line: 1,
9927 offset: 0,
9928 originalSource: content,
9929 source: content,
9930 inPre: false,
9931 inVPre: false
9932 };
9933 }
9934 function parseChildren(context, mode, ancestors) {
9935 const parent = last(ancestors);
9936 const ns = parent ? parent.ns : 0 /* HTML */;
9937 const nodes = [];
9938 while (!isEnd(context, mode, ancestors)) {
9939 const s = context.source;
9940 let node = undefined;
9941 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
9942 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
9943 // '{{'
9944 node = parseInterpolation(context, mode);
9945 }
9946 else if (mode === 0 /* DATA */ && s[0] === '<') {
9947 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
9948 if (s.length === 1) {
9949 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
9950 }
9951 else if (s[1] === '!') {
9952 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
9953 if (startsWith(s, '<!--')) {
9954 node = parseComment(context);
9955 }
9956 else if (startsWith(s, '<!DOCTYPE')) {
9957 // Ignore DOCTYPE by a limitation.
9958 node = parseBogusComment(context);
9959 }
9960 else if (startsWith(s, '<![CDATA[')) {
9961 if (ns !== 0 /* HTML */) {
9962 node = parseCDATA(context, ancestors);
9963 }
9964 else {
9965 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
9966 node = parseBogusComment(context);
9967 }
9968 }
9969 else {
9970 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
9971 node = parseBogusComment(context);
9972 }
9973 }
9974 else if (s[1] === '/') {
9975 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
9976 if (s.length === 2) {
9977 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
9978 }
9979 else if (s[2] === '>') {
9980 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
9981 advanceBy(context, 3);
9982 continue;
9983 }
9984 else if (/[a-z]/i.test(s[2])) {
9985 emitError(context, 23 /* X_INVALID_END_TAG */);
9986 parseTag(context, 1 /* End */, parent);
9987 continue;
9988 }
9989 else {
9990 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
9991 node = parseBogusComment(context);
9992 }
9993 }
9994 else if (/[a-z]/i.test(s[1])) {
9995 node = parseElement(context, ancestors);
9996 }
9997 else if (s[1] === '?') {
9998 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
9999 node = parseBogusComment(context);
10000 }
10001 else {
10002 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
10003 }
10004 }
10005 }
10006 if (!node) {
10007 node = parseText(context, mode);
10008 }
10009 if (isArray(node)) {
10010 for (let i = 0; i < node.length; i++) {
10011 pushNode(nodes, node[i]);
10012 }
10013 }
10014 else {
10015 pushNode(nodes, node);
10016 }
10017 }
10018 // Whitespace management for more efficient output
10019 // (same as v2 whitespace: 'condense')
10020 let removedWhitespace = false;
10021 if (mode !== 2 /* RAWTEXT */) {
10022 for (let i = 0; i < nodes.length; i++) {
10023 const node = nodes[i];
10024 if (!context.inPre && node.type === 2 /* TEXT */) {
10025 if (!/[^\t\r\n\f ]/.test(node.content)) {
10026 const prev = nodes[i - 1];
10027 const next = nodes[i + 1];
10028 // If:
10029 // - the whitespace is the first or last node, or:
10030 // - the whitespace is adjacent to a comment, or:
10031 // - the whitespace is between two elements AND contains newline
10032 // Then the whitespace is ignored.
10033 if (!prev ||
10034 !next ||
10035 prev.type === 3 /* COMMENT */ ||
10036 next.type === 3 /* COMMENT */ ||
10037 (prev.type === 1 /* ELEMENT */ &&
10038 next.type === 1 /* ELEMENT */ &&
10039 /[\r\n]/.test(node.content))) {
10040 removedWhitespace = true;
10041 nodes[i] = null;
10042 }
10043 else {
10044 // Otherwise, condensed consecutive whitespace inside the text
10045 // down to a single space
10046 node.content = ' ';
10047 }
10048 }
10049 else {
10050 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
10051 }
10052 }
10053 }
10054 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
10055 // remove leading newline per html spec
10056 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
10057 const first = nodes[0];
10058 if (first && first.type === 2 /* TEXT */) {
10059 first.content = first.content.replace(/^\r?\n/, '');
10060 }
10061 }
10062 }
10063 return removedWhitespace ? nodes.filter(Boolean) : nodes;
10064 }
10065 function pushNode(nodes, node) {
10066 if (node.type === 2 /* TEXT */) {
10067 const prev = last(nodes);
10068 // Merge if both this and the previous node are text and those are
10069 // consecutive. This happens for cases like "a < b".
10070 if (prev &&
10071 prev.type === 2 /* TEXT */ &&
10072 prev.loc.end.offset === node.loc.start.offset) {
10073 prev.content += node.content;
10074 prev.loc.end = node.loc.end;
10075 prev.loc.source += node.loc.source;
10076 return;
10077 }
10078 }
10079 nodes.push(node);
10080 }
10081 function parseCDATA(context, ancestors) {
10082 advanceBy(context, 9);
10083 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
10084 if (context.source.length === 0) {
10085 emitError(context, 6 /* EOF_IN_CDATA */);
10086 }
10087 else {
10088 advanceBy(context, 3);
10089 }
10090 return nodes;
10091 }
10092 function parseComment(context) {
10093 const start = getCursor(context);
10094 let content;
10095 // Regular comment.
10096 const match = /--(\!)?>/.exec(context.source);
10097 if (!match) {
10098 content = context.source.slice(4);
10099 advanceBy(context, context.source.length);
10100 emitError(context, 7 /* EOF_IN_COMMENT */);
10101 }
10102 else {
10103 if (match.index <= 3) {
10104 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
10105 }
10106 if (match[1]) {
10107 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
10108 }
10109 content = context.source.slice(4, match.index);
10110 // Advancing with reporting nested comments.
10111 const s = context.source.slice(0, match.index);
10112 let prevIndex = 1, nestedIndex = 0;
10113 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
10114 advanceBy(context, nestedIndex - prevIndex + 1);
10115 if (nestedIndex + 4 < s.length) {
10116 emitError(context, 16 /* NESTED_COMMENT */);
10117 }
10118 prevIndex = nestedIndex + 1;
10119 }
10120 advanceBy(context, match.index + match[0].length - prevIndex + 1);
10121 }
10122 return {
10123 type: 3 /* COMMENT */,
10124 content,
10125 loc: getSelection(context, start)
10126 };
10127 }
10128 function parseBogusComment(context) {
10129 const start = getCursor(context);
10130 const contentStart = context.source[1] === '?' ? 1 : 2;
10131 let content;
10132 const closeIndex = context.source.indexOf('>');
10133 if (closeIndex === -1) {
10134 content = context.source.slice(contentStart);
10135 advanceBy(context, context.source.length);
10136 }
10137 else {
10138 content = context.source.slice(contentStart, closeIndex);
10139 advanceBy(context, closeIndex + 1);
10140 }
10141 return {
10142 type: 3 /* COMMENT */,
10143 content,
10144 loc: getSelection(context, start)
10145 };
10146 }
10147 function parseElement(context, ancestors) {
10148 // Start tag.
10149 const wasInPre = context.inPre;
10150 const wasInVPre = context.inVPre;
10151 const parent = last(ancestors);
10152 const element = parseTag(context, 0 /* Start */, parent);
10153 const isPreBoundary = context.inPre && !wasInPre;
10154 const isVPreBoundary = context.inVPre && !wasInVPre;
10155 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
10156 return element;
10157 }
10158 // Children.
10159 ancestors.push(element);
10160 const mode = context.options.getTextMode(element, parent);
10161 const children = parseChildren(context, mode, ancestors);
10162 ancestors.pop();
10163 element.children = children;
10164 // End tag.
10165 if (startsWithEndTagOpen(context.source, element.tag)) {
10166 parseTag(context, 1 /* End */, parent);
10167 }
10168 else {
10169 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
10170 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
10171 const first = children[0];
10172 if (first && startsWith(first.loc.source, '<!--')) {
10173 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
10174 }
10175 }
10176 }
10177 element.loc = getSelection(context, element.loc.start);
10178 if (isPreBoundary) {
10179 context.inPre = false;
10180 }
10181 if (isVPreBoundary) {
10182 context.inVPre = false;
10183 }
10184 return element;
10185 }
10186 const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
10187 /**
10188 * Parse a tag (E.g. `<div id=a>`) with that type (start tag or end tag).
10189 */
10190 function parseTag(context, type, parent) {
10191 // Tag open.
10192 const start = getCursor(context);
10193 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
10194 const tag = match[1];
10195 const ns = context.options.getNamespace(tag, parent);
10196 advanceBy(context, match[0].length);
10197 advanceSpaces(context);
10198 // save current state in case we need to re-parse attributes with v-pre
10199 const cursor = getCursor(context);
10200 const currentSource = context.source;
10201 // Attributes.
10202 let props = parseAttributes(context, type);
10203 // check <pre> tag
10204 if (context.options.isPreTag(tag)) {
10205 context.inPre = true;
10206 }
10207 // check v-pre
10208 if (!context.inVPre &&
10209 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
10210 context.inVPre = true;
10211 // reset context
10212 extend(context, cursor);
10213 context.source = currentSource;
10214 // re-parse attrs and filter out v-pre itself
10215 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
10216 }
10217 // Tag close.
10218 let isSelfClosing = false;
10219 if (context.source.length === 0) {
10220 emitError(context, 9 /* EOF_IN_TAG */);
10221 }
10222 else {
10223 isSelfClosing = startsWith(context.source, '/>');
10224 if (type === 1 /* End */ && isSelfClosing) {
10225 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
10226 }
10227 advanceBy(context, isSelfClosing ? 2 : 1);
10228 }
10229 let tagType = 0 /* ELEMENT */;
10230 const options = context.options;
10231 if (!context.inVPre && !options.isCustomElement(tag)) {
10232 const hasVIs = props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'is');
10233 if (options.isNativeTag && !hasVIs) {
10234 if (!options.isNativeTag(tag))
10235 tagType = 1 /* COMPONENT */;
10236 }
10237 else if (hasVIs ||
10238 isCoreComponent(tag) ||
10239 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
10240 /^[A-Z]/.test(tag) ||
10241 tag === 'component') {
10242 tagType = 1 /* COMPONENT */;
10243 }
10244 if (tag === 'slot') {
10245 tagType = 2 /* SLOT */;
10246 }
10247 else if (tag === 'template' &&
10248 props.some(p => {
10249 return (p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name));
10250 })) {
10251 tagType = 3 /* TEMPLATE */;
10252 }
10253 }
10254 return {
10255 type: 1 /* ELEMENT */,
10256 ns,
10257 tag,
10258 tagType,
10259 props,
10260 isSelfClosing,
10261 children: [],
10262 loc: getSelection(context, start),
10263 codegenNode: undefined // to be created during transform phase
10264 };
10265 }
10266 function parseAttributes(context, type) {
10267 const props = [];
10268 const attributeNames = new Set();
10269 while (context.source.length > 0 &&
10270 !startsWith(context.source, '>') &&
10271 !startsWith(context.source, '/>')) {
10272 if (startsWith(context.source, '/')) {
10273 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
10274 advanceBy(context, 1);
10275 advanceSpaces(context);
10276 continue;
10277 }
10278 if (type === 1 /* End */) {
10279 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
10280 }
10281 const attr = parseAttribute(context, attributeNames);
10282 if (type === 0 /* Start */) {
10283 props.push(attr);
10284 }
10285 if (/^[^\t\r\n\f />]/.test(context.source)) {
10286 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
10287 }
10288 advanceSpaces(context);
10289 }
10290 return props;
10291 }
10292 function parseAttribute(context, nameSet) {
10293 // Name.
10294 const start = getCursor(context);
10295 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
10296 const name = match[0];
10297 if (nameSet.has(name)) {
10298 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
10299 }
10300 nameSet.add(name);
10301 if (name[0] === '=') {
10302 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
10303 }
10304 {
10305 const pattern = /["'<]/g;
10306 let m;
10307 while ((m = pattern.exec(name))) {
10308 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
10309 }
10310 }
10311 advanceBy(context, name.length);
10312 // Value
10313 let value = undefined;
10314 if (/^[\t\r\n\f ]*=/.test(context.source)) {
10315 advanceSpaces(context);
10316 advanceBy(context, 1);
10317 advanceSpaces(context);
10318 value = parseAttributeValue(context);
10319 if (!value) {
10320 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
10321 }
10322 }
10323 const loc = getSelection(context, start);
10324 if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
10325 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
10326 const dirName = match[1] ||
10327 (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
10328 let arg;
10329 if (match[2]) {
10330 const isSlot = dirName === 'slot';
10331 const startOffset = name.indexOf(match[2]);
10332 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
10333 let content = match[2];
10334 let isStatic = true;
10335 if (content.startsWith('[')) {
10336 isStatic = false;
10337 if (!content.endsWith(']')) {
10338 emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
10339 }
10340 content = content.substr(1, content.length - 2);
10341 }
10342 else if (isSlot) {
10343 // #1241 special case for v-slot: vuetify relies extensively on slot
10344 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
10345 // supports such usage so we are keeping it consistent with 2.x.
10346 content += match[3] || '';
10347 }
10348 arg = {
10349 type: 4 /* SIMPLE_EXPRESSION */,
10350 content,
10351 isStatic,
10352 constType: isStatic
10353 ? 3 /* CAN_STRINGIFY */
10354 : 0 /* NOT_CONSTANT */,
10355 loc
10356 };
10357 }
10358 if (value && value.isQuoted) {
10359 const valueLoc = value.loc;
10360 valueLoc.start.offset++;
10361 valueLoc.start.column++;
10362 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
10363 valueLoc.source = valueLoc.source.slice(1, -1);
10364 }
10365 return {
10366 type: 7 /* DIRECTIVE */,
10367 name: dirName,
10368 exp: value && {
10369 type: 4 /* SIMPLE_EXPRESSION */,
10370 content: value.content,
10371 isStatic: false,
10372 // Treat as non-constant by default. This can be potentially set to
10373 // other values by `transformExpression` to make it eligible for hoisting.
10374 constType: 0 /* NOT_CONSTANT */,
10375 loc: value.loc
10376 },
10377 arg,
10378 modifiers: match[3] ? match[3].substr(1).split('.') : [],
10379 loc
10380 };
10381 }
10382 return {
10383 type: 6 /* ATTRIBUTE */,
10384 name,
10385 value: value && {
10386 type: 2 /* TEXT */,
10387 content: value.content,
10388 loc: value.loc
10389 },
10390 loc
10391 };
10392 }
10393 function parseAttributeValue(context) {
10394 const start = getCursor(context);
10395 let content;
10396 const quote = context.source[0];
10397 const isQuoted = quote === `"` || quote === `'`;
10398 if (isQuoted) {
10399 // Quoted value.
10400 advanceBy(context, 1);
10401 const endIndex = context.source.indexOf(quote);
10402 if (endIndex === -1) {
10403 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
10404 }
10405 else {
10406 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
10407 advanceBy(context, 1);
10408 }
10409 }
10410 else {
10411 // Unquoted
10412 const match = /^[^\t\r\n\f >]+/.exec(context.source);
10413 if (!match) {
10414 return undefined;
10415 }
10416 const unexpectedChars = /["'<=`]/g;
10417 let m;
10418 while ((m = unexpectedChars.exec(match[0]))) {
10419 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
10420 }
10421 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
10422 }
10423 return { content, isQuoted, loc: getSelection(context, start) };
10424 }
10425 function parseInterpolation(context, mode) {
10426 const [open, close] = context.options.delimiters;
10427 const closeIndex = context.source.indexOf(close, open.length);
10428 if (closeIndex === -1) {
10429 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
10430 return undefined;
10431 }
10432 const start = getCursor(context);
10433 advanceBy(context, open.length);
10434 const innerStart = getCursor(context);
10435 const innerEnd = getCursor(context);
10436 const rawContentLength = closeIndex - open.length;
10437 const rawContent = context.source.slice(0, rawContentLength);
10438 const preTrimContent = parseTextData(context, rawContentLength, mode);
10439 const content = preTrimContent.trim();
10440 const startOffset = preTrimContent.indexOf(content);
10441 if (startOffset > 0) {
10442 advancePositionWithMutation(innerStart, rawContent, startOffset);
10443 }
10444 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
10445 advancePositionWithMutation(innerEnd, rawContent, endOffset);
10446 advanceBy(context, close.length);
10447 return {
10448 type: 5 /* INTERPOLATION */,
10449 content: {
10450 type: 4 /* SIMPLE_EXPRESSION */,
10451 isStatic: false,
10452 // Set `isConstant` to false by default and will decide in transformExpression
10453 constType: 0 /* NOT_CONSTANT */,
10454 content,
10455 loc: getSelection(context, innerStart, innerEnd)
10456 },
10457 loc: getSelection(context, start)
10458 };
10459 }
10460 function parseText(context, mode) {
10461 const endTokens = ['<', context.options.delimiters[0]];
10462 if (mode === 3 /* CDATA */) {
10463 endTokens.push(']]>');
10464 }
10465 let endIndex = context.source.length;
10466 for (let i = 0; i < endTokens.length; i++) {
10467 const index = context.source.indexOf(endTokens[i], 1);
10468 if (index !== -1 && endIndex > index) {
10469 endIndex = index;
10470 }
10471 }
10472 const start = getCursor(context);
10473 const content = parseTextData(context, endIndex, mode);
10474 return {
10475 type: 2 /* TEXT */,
10476 content,
10477 loc: getSelection(context, start)
10478 };
10479 }
10480 /**
10481 * Get text data with a given length from the current location.
10482 * This translates HTML entities in the text data.
10483 */
10484 function parseTextData(context, length, mode) {
10485 const rawText = context.source.slice(0, length);
10486 advanceBy(context, length);
10487 if (mode === 2 /* RAWTEXT */ ||
10488 mode === 3 /* CDATA */ ||
10489 rawText.indexOf('&') === -1) {
10490 return rawText;
10491 }
10492 else {
10493 // DATA or RCDATA containing "&"". Entity decoding required.
10494 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
10495 }
10496 }
10497 function getCursor(context) {
10498 const { column, line, offset } = context;
10499 return { column, line, offset };
10500 }
10501 function getSelection(context, start, end) {
10502 end = end || getCursor(context);
10503 return {
10504 start,
10505 end,
10506 source: context.originalSource.slice(start.offset, end.offset)
10507 };
10508 }
10509 function last(xs) {
10510 return xs[xs.length - 1];
10511 }
10512 function startsWith(source, searchString) {
10513 return source.startsWith(searchString);
10514 }
10515 function advanceBy(context, numberOfCharacters) {
10516 const { source } = context;
10517 advancePositionWithMutation(context, source, numberOfCharacters);
10518 context.source = source.slice(numberOfCharacters);
10519 }
10520 function advanceSpaces(context) {
10521 const match = /^[\t\r\n\f ]+/.exec(context.source);
10522 if (match) {
10523 advanceBy(context, match[0].length);
10524 }
10525 }
10526 function getNewPosition(context, start, numberOfCharacters) {
10527 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
10528 }
10529 function emitError(context, code, offset, loc = getCursor(context)) {
10530 if (offset) {
10531 loc.offset += offset;
10532 loc.column += offset;
10533 }
10534 context.options.onError(createCompilerError(code, {
10535 start: loc,
10536 end: loc,
10537 source: ''
10538 }));
10539 }
10540 function isEnd(context, mode, ancestors) {
10541 const s = context.source;
10542 switch (mode) {
10543 case 0 /* DATA */:
10544 if (startsWith(s, '</')) {
10545 // TODO: probably bad performance
10546 for (let i = ancestors.length - 1; i >= 0; --i) {
10547 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
10548 return true;
10549 }
10550 }
10551 }
10552 break;
10553 case 1 /* RCDATA */:
10554 case 2 /* RAWTEXT */: {
10555 const parent = last(ancestors);
10556 if (parent && startsWithEndTagOpen(s, parent.tag)) {
10557 return true;
10558 }
10559 break;
10560 }
10561 case 3 /* CDATA */:
10562 if (startsWith(s, ']]>')) {
10563 return true;
10564 }
10565 break;
10566 }
10567 return !s;
10568 }
10569 function startsWithEndTagOpen(source, tag) {
10570 return (startsWith(source, '</') &&
10571 source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
10572 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
10573 }
10574
10575 function hoistStatic(root, context) {
10576 walk(root, context,
10577 // Root node is unfortunately non-hoistable due to potential parent
10578 // fallthrough attributes.
10579 isSingleElementRoot(root, root.children[0]));
10580 }
10581 function isSingleElementRoot(root, child) {
10582 const { children } = root;
10583 return (children.length === 1 &&
10584 child.type === 1 /* ELEMENT */ &&
10585 !isSlotOutlet(child));
10586 }
10587 function walk(node, context, doNotHoistNode = false) {
10588 let hasHoistedNode = false;
10589 // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
10590 // static bindings with expressions. These expressions are guaranteed to be
10591 // constant so they are still eligible for hoisting, but they are only
10592 // available at runtime and therefore cannot be evaluated ahead of time.
10593 // This is only a concern for pre-stringification (via transformHoist by
10594 // @vue/compiler-dom), but doing it here allows us to perform only one full
10595 // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
10596 // stringficiation threshold is met.
10597 let canStringify = true;
10598 const { children } = node;
10599 for (let i = 0; i < children.length; i++) {
10600 const child = children[i];
10601 // only plain elements & text calls are eligible for hoisting.
10602 if (child.type === 1 /* ELEMENT */ &&
10603 child.tagType === 0 /* ELEMENT */) {
10604 const constantType = doNotHoistNode
10605 ? 0 /* NOT_CONSTANT */
10606 : getConstantType(child, context);
10607 if (constantType > 0 /* NOT_CONSTANT */) {
10608 if (constantType < 3 /* CAN_STRINGIFY */) {
10609 canStringify = false;
10610 }
10611 if (constantType >= 2 /* CAN_HOIST */) {
10612 child.codegenNode.patchFlag =
10613 -1 /* HOISTED */ + (` /* HOISTED */` );
10614 child.codegenNode = context.hoist(child.codegenNode);
10615 hasHoistedNode = true;
10616 continue;
10617 }
10618 }
10619 else {
10620 // node may contain dynamic children, but its props may be eligible for
10621 // hoisting.
10622 const codegenNode = child.codegenNode;
10623 if (codegenNode.type === 13 /* VNODE_CALL */) {
10624 const flag = getPatchFlag(codegenNode);
10625 if ((!flag ||
10626 flag === 512 /* NEED_PATCH */ ||
10627 flag === 1 /* TEXT */) &&
10628 getGeneratedPropsConstantType(child, context) >=
10629 2 /* CAN_HOIST */) {
10630 const props = getNodeProps(child);
10631 if (props) {
10632 codegenNode.props = context.hoist(props);
10633 }
10634 }
10635 }
10636 }
10637 }
10638 else if (child.type === 12 /* TEXT_CALL */) {
10639 const contentType = getConstantType(child.content, context);
10640 if (contentType > 0) {
10641 if (contentType < 3 /* CAN_STRINGIFY */) {
10642 canStringify = false;
10643 }
10644 if (contentType >= 2 /* CAN_HOIST */) {
10645 child.codegenNode = context.hoist(child.codegenNode);
10646 hasHoistedNode = true;
10647 }
10648 }
10649 }
10650 // walk further
10651 if (child.type === 1 /* ELEMENT */) {
10652 walk(child, context);
10653 }
10654 else if (child.type === 11 /* FOR */) {
10655 // Do not hoist v-for single child because it has to be a block
10656 walk(child, context, child.children.length === 1);
10657 }
10658 else if (child.type === 9 /* IF */) {
10659 for (let i = 0; i < child.branches.length; i++) {
10660 // Do not hoist v-if single child because it has to be a block
10661 walk(child.branches[i], context, child.branches[i].children.length === 1);
10662 }
10663 }
10664 }
10665 if (canStringify && hasHoistedNode && context.transformHoist) {
10666 context.transformHoist(children, context, node);
10667 }
10668 }
10669 function getConstantType(node, context) {
10670 const { constantCache } = context;
10671 switch (node.type) {
10672 case 1 /* ELEMENT */:
10673 if (node.tagType !== 0 /* ELEMENT */) {
10674 return 0 /* NOT_CONSTANT */;
10675 }
10676 const cached = constantCache.get(node);
10677 if (cached !== undefined) {
10678 return cached;
10679 }
10680 const codegenNode = node.codegenNode;
10681 if (codegenNode.type !== 13 /* VNODE_CALL */) {
10682 return 0 /* NOT_CONSTANT */;
10683 }
10684 const flag = getPatchFlag(codegenNode);
10685 if (!flag) {
10686 let returnType = 3 /* CAN_STRINGIFY */;
10687 // Element itself has no patch flag. However we still need to check:
10688 // 1. Even for a node with no patch flag, it is possible for it to contain
10689 // non-hoistable expressions that refers to scope variables, e.g. compiler
10690 // injected keys or cached event handlers. Therefore we need to always
10691 // check the codegenNode's props to be sure.
10692 const generatedPropsType = getGeneratedPropsConstantType(node, context);
10693 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
10694 constantCache.set(node, 0 /* NOT_CONSTANT */);
10695 return 0 /* NOT_CONSTANT */;
10696 }
10697 if (generatedPropsType < returnType) {
10698 returnType = generatedPropsType;
10699 }
10700 // 2. its children.
10701 for (let i = 0; i < node.children.length; i++) {
10702 const childType = getConstantType(node.children[i], context);
10703 if (childType === 0 /* NOT_CONSTANT */) {
10704 constantCache.set(node, 0 /* NOT_CONSTANT */);
10705 return 0 /* NOT_CONSTANT */;
10706 }
10707 if (childType < returnType) {
10708 returnType = childType;
10709 }
10710 }
10711 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
10712 // type, check if any of the props can cause the type to be lowered
10713 // we can skip can_patch because it's guaranteed by the absence of a
10714 // patchFlag.
10715 if (returnType > 1 /* CAN_SKIP_PATCH */) {
10716 for (let i = 0; i < node.props.length; i++) {
10717 const p = node.props[i];
10718 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
10719 const expType = getConstantType(p.exp, context);
10720 if (expType === 0 /* NOT_CONSTANT */) {
10721 constantCache.set(node, 0 /* NOT_CONSTANT */);
10722 return 0 /* NOT_CONSTANT */;
10723 }
10724 if (expType < returnType) {
10725 returnType = expType;
10726 }
10727 }
10728 }
10729 }
10730 // only svg/foreignObject could be block here, however if they are
10731 // static then they don't need to be blocks since there will be no
10732 // nested updates.
10733 if (codegenNode.isBlock) {
10734 codegenNode.isBlock = false;
10735 context.helper(CREATE_VNODE);
10736 }
10737 constantCache.set(node, returnType);
10738 return returnType;
10739 }
10740 else {
10741 constantCache.set(node, 0 /* NOT_CONSTANT */);
10742 return 0 /* NOT_CONSTANT */;
10743 }
10744 case 2 /* TEXT */:
10745 case 3 /* COMMENT */:
10746 return 3 /* CAN_STRINGIFY */;
10747 case 9 /* IF */:
10748 case 11 /* FOR */:
10749 case 10 /* IF_BRANCH */:
10750 return 0 /* NOT_CONSTANT */;
10751 case 5 /* INTERPOLATION */:
10752 case 12 /* TEXT_CALL */:
10753 return getConstantType(node.content, context);
10754 case 4 /* SIMPLE_EXPRESSION */:
10755 return node.constType;
10756 case 8 /* COMPOUND_EXPRESSION */:
10757 let returnType = 3 /* CAN_STRINGIFY */;
10758 for (let i = 0; i < node.children.length; i++) {
10759 const child = node.children[i];
10760 if (isString(child) || isSymbol(child)) {
10761 continue;
10762 }
10763 const childType = getConstantType(child, context);
10764 if (childType === 0 /* NOT_CONSTANT */) {
10765 return 0 /* NOT_CONSTANT */;
10766 }
10767 else if (childType < returnType) {
10768 returnType = childType;
10769 }
10770 }
10771 return returnType;
10772 default:
10773 return 0 /* NOT_CONSTANT */;
10774 }
10775 }
10776 function getGeneratedPropsConstantType(node, context) {
10777 let returnType = 3 /* CAN_STRINGIFY */;
10778 const props = getNodeProps(node);
10779 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
10780 const { properties } = props;
10781 for (let i = 0; i < properties.length; i++) {
10782 const { key, value } = properties[i];
10783 const keyType = getConstantType(key, context);
10784 if (keyType === 0 /* NOT_CONSTANT */) {
10785 return keyType;
10786 }
10787 if (keyType < returnType) {
10788 returnType = keyType;
10789 }
10790 if (value.type !== 4 /* SIMPLE_EXPRESSION */) {
10791 return 0 /* NOT_CONSTANT */;
10792 }
10793 const valueType = getConstantType(value, context);
10794 if (valueType === 0 /* NOT_CONSTANT */) {
10795 return valueType;
10796 }
10797 if (valueType < returnType) {
10798 returnType = valueType;
10799 }
10800 }
10801 }
10802 return returnType;
10803 }
10804 function getNodeProps(node) {
10805 const codegenNode = node.codegenNode;
10806 if (codegenNode.type === 13 /* VNODE_CALL */) {
10807 return codegenNode.props;
10808 }
10809 }
10810 function getPatchFlag(node) {
10811 const flag = node.patchFlag;
10812 return flag ? parseInt(flag, 10) : undefined;
10813 }
10814
10815 function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, ssr = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError }) {
10816 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
10817 const context = {
10818 // options
10819 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
10820 prefixIdentifiers,
10821 hoistStatic,
10822 cacheHandlers,
10823 nodeTransforms,
10824 directiveTransforms,
10825 transformHoist,
10826 isBuiltInComponent,
10827 isCustomElement,
10828 expressionPlugins,
10829 scopeId,
10830 ssr,
10831 ssrCssVars,
10832 bindingMetadata,
10833 inline,
10834 isTS,
10835 onError,
10836 // state
10837 root,
10838 helpers: new Set(),
10839 components: new Set(),
10840 directives: new Set(),
10841 hoists: [],
10842 imports: [],
10843 constantCache: new Map(),
10844 temps: 0,
10845 cached: 0,
10846 identifiers: Object.create(null),
10847 scopes: {
10848 vFor: 0,
10849 vSlot: 0,
10850 vPre: 0,
10851 vOnce: 0
10852 },
10853 parent: null,
10854 currentNode: root,
10855 childIndex: 0,
10856 // methods
10857 helper(name) {
10858 context.helpers.add(name);
10859 return name;
10860 },
10861 helperString(name) {
10862 return `_${helperNameMap[context.helper(name)]}`;
10863 },
10864 replaceNode(node) {
10865 /* istanbul ignore if */
10866 {
10867 if (!context.currentNode) {
10868 throw new Error(`Node being replaced is already removed.`);
10869 }
10870 if (!context.parent) {
10871 throw new Error(`Cannot replace root node.`);
10872 }
10873 }
10874 context.parent.children[context.childIndex] = context.currentNode = node;
10875 },
10876 removeNode(node) {
10877 if (!context.parent) {
10878 throw new Error(`Cannot remove root node.`);
10879 }
10880 const list = context.parent.children;
10881 const removalIndex = node
10882 ? list.indexOf(node)
10883 : context.currentNode
10884 ? context.childIndex
10885 : -1;
10886 /* istanbul ignore if */
10887 if (removalIndex < 0) {
10888 throw new Error(`node being removed is not a child of current parent`);
10889 }
10890 if (!node || node === context.currentNode) {
10891 // current node removed
10892 context.currentNode = null;
10893 context.onNodeRemoved();
10894 }
10895 else {
10896 // sibling node removed
10897 if (context.childIndex > removalIndex) {
10898 context.childIndex--;
10899 context.onNodeRemoved();
10900 }
10901 }
10902 context.parent.children.splice(removalIndex, 1);
10903 },
10904 onNodeRemoved: () => { },
10905 addIdentifiers(exp) {
10906 },
10907 removeIdentifiers(exp) {
10908 },
10909 hoist(exp) {
10910 context.hoists.push(exp);
10911 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
10912 identifier.hoisted = exp;
10913 return identifier;
10914 },
10915 cache(exp, isVNode = false) {
10916 return createCacheExpression(++context.cached, exp, isVNode);
10917 }
10918 };
10919 return context;
10920 }
10921 function transform(root, options) {
10922 const context = createTransformContext(root, options);
10923 traverseNode(root, context);
10924 if (options.hoistStatic) {
10925 hoistStatic(root, context);
10926 }
10927 if (!options.ssr) {
10928 createRootCodegen(root, context);
10929 }
10930 // finalize meta information
10931 root.helpers = [...context.helpers];
10932 root.components = [...context.components];
10933 root.directives = [...context.directives];
10934 root.imports = context.imports;
10935 root.hoists = context.hoists;
10936 root.temps = context.temps;
10937 root.cached = context.cached;
10938 }
10939 function createRootCodegen(root, context) {
10940 const { helper } = context;
10941 const { children } = root;
10942 if (children.length === 1) {
10943 const child = children[0];
10944 // if the single child is an element, turn it into a block.
10945 if (isSingleElementRoot(root, child) && child.codegenNode) {
10946 // single element root is never hoisted so codegenNode will never be
10947 // SimpleExpressionNode
10948 const codegenNode = child.codegenNode;
10949 if (codegenNode.type === 13 /* VNODE_CALL */) {
10950 codegenNode.isBlock = true;
10951 helper(OPEN_BLOCK);
10952 helper(CREATE_BLOCK);
10953 }
10954 root.codegenNode = codegenNode;
10955 }
10956 else {
10957 // - single <slot/>, IfNode, ForNode: already blocks.
10958 // - single text node: always patched.
10959 // root codegen falls through via genNode()
10960 root.codegenNode = child;
10961 }
10962 }
10963 else if (children.length > 1) {
10964 // root has multiple nodes - return a fragment block.
10965 let patchFlag = 64 /* STABLE_FRAGMENT */;
10966 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
10967 // check if the fragment actually contains a single valid child with
10968 // the rest being comments
10969 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
10970 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
10971 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
10972 }
10973 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true);
10974 }
10975 else ;
10976 }
10977 function traverseChildren(parent, context) {
10978 let i = 0;
10979 const nodeRemoved = () => {
10980 i--;
10981 };
10982 for (; i < parent.children.length; i++) {
10983 const child = parent.children[i];
10984 if (isString(child))
10985 continue;
10986 context.parent = parent;
10987 context.childIndex = i;
10988 context.onNodeRemoved = nodeRemoved;
10989 traverseNode(child, context);
10990 }
10991 }
10992 function traverseNode(node, context) {
10993 context.currentNode = node;
10994 // apply transform plugins
10995 const { nodeTransforms } = context;
10996 const exitFns = [];
10997 for (let i = 0; i < nodeTransforms.length; i++) {
10998 const onExit = nodeTransforms[i](node, context);
10999 if (onExit) {
11000 if (isArray(onExit)) {
11001 exitFns.push(...onExit);
11002 }
11003 else {
11004 exitFns.push(onExit);
11005 }
11006 }
11007 if (!context.currentNode) {
11008 // node was removed
11009 return;
11010 }
11011 else {
11012 // node may have been replaced
11013 node = context.currentNode;
11014 }
11015 }
11016 switch (node.type) {
11017 case 3 /* COMMENT */:
11018 if (!context.ssr) {
11019 // inject import for the Comment symbol, which is needed for creating
11020 // comment nodes with `createVNode`
11021 context.helper(CREATE_COMMENT);
11022 }
11023 break;
11024 case 5 /* INTERPOLATION */:
11025 // no need to traverse, but we need to inject toString helper
11026 if (!context.ssr) {
11027 context.helper(TO_DISPLAY_STRING);
11028 }
11029 break;
11030 // for container types, further traverse downwards
11031 case 9 /* IF */:
11032 for (let i = 0; i < node.branches.length; i++) {
11033 traverseNode(node.branches[i], context);
11034 }
11035 break;
11036 case 10 /* IF_BRANCH */:
11037 case 11 /* FOR */:
11038 case 1 /* ELEMENT */:
11039 case 0 /* ROOT */:
11040 traverseChildren(node, context);
11041 break;
11042 }
11043 // exit transforms
11044 context.currentNode = node;
11045 let i = exitFns.length;
11046 while (i--) {
11047 exitFns[i]();
11048 }
11049 }
11050 function createStructuralDirectiveTransform(name, fn) {
11051 const matches = isString(name)
11052 ? (n) => n === name
11053 : (n) => name.test(n);
11054 return (node, context) => {
11055 if (node.type === 1 /* ELEMENT */) {
11056 const { props } = node;
11057 // structural directive transforms are not concerned with slots
11058 // as they are handled separately in vSlot.ts
11059 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
11060 return;
11061 }
11062 const exitFns = [];
11063 for (let i = 0; i < props.length; i++) {
11064 const prop = props[i];
11065 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
11066 // structural directives are removed to avoid infinite recursion
11067 // also we remove them *before* applying so that it can further
11068 // traverse itself in case it moves the node around
11069 props.splice(i, 1);
11070 i--;
11071 const onExit = fn(node, prop, context);
11072 if (onExit)
11073 exitFns.push(onExit);
11074 }
11075 }
11076 return exitFns;
11077 }
11078 };
11079 }
11080
11081 const PURE_ANNOTATION = `/*#__PURE__*/`;
11082 function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
11083 const context = {
11084 mode,
11085 prefixIdentifiers,
11086 sourceMap,
11087 filename,
11088 scopeId,
11089 optimizeImports,
11090 runtimeGlobalName,
11091 runtimeModuleName,
11092 ssr,
11093 source: ast.loc.source,
11094 code: ``,
11095 column: 1,
11096 line: 1,
11097 offset: 0,
11098 indentLevel: 0,
11099 pure: false,
11100 map: undefined,
11101 helper(key) {
11102 return `_${helperNameMap[key]}`;
11103 },
11104 push(code, node) {
11105 context.code += code;
11106 },
11107 indent() {
11108 newline(++context.indentLevel);
11109 },
11110 deindent(withoutNewLine = false) {
11111 if (withoutNewLine) {
11112 --context.indentLevel;
11113 }
11114 else {
11115 newline(--context.indentLevel);
11116 }
11117 },
11118 newline() {
11119 newline(context.indentLevel);
11120 }
11121 };
11122 function newline(n) {
11123 context.push('\n' + ` `.repeat(n));
11124 }
11125 return context;
11126 }
11127 function generate(ast, options = {}) {
11128 const context = createCodegenContext(ast, options);
11129 if (options.onContextCreated)
11130 options.onContextCreated(context);
11131 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
11132 const hasHelpers = ast.helpers.length > 0;
11133 const useWithBlock = !prefixIdentifiers && mode !== 'module';
11134 // preambles
11135 // in setup() inline mode, the preamble is generated in a sub context
11136 // and returned separately.
11137 const preambleContext = context;
11138 {
11139 genFunctionPreamble(ast, preambleContext);
11140 }
11141 // enter render function
11142 const functionName = ssr ? `ssrRender` : `render`;
11143 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
11144 const signature = args.join(', ');
11145 {
11146 push(`function ${functionName}(${signature}) {`);
11147 }
11148 indent();
11149 if (useWithBlock) {
11150 push(`with (_ctx) {`);
11151 indent();
11152 // function mode const declarations should be inside with block
11153 // also they should be renamed to avoid collision with user properties
11154 if (hasHelpers) {
11155 push(`const { ${ast.helpers
11156 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
11157 .join(', ')} } = _Vue`);
11158 push(`\n`);
11159 newline();
11160 }
11161 }
11162 // generate asset resolution statements
11163 if (ast.components.length) {
11164 genAssets(ast.components, 'component', context);
11165 if (ast.directives.length || ast.temps > 0) {
11166 newline();
11167 }
11168 }
11169 if (ast.directives.length) {
11170 genAssets(ast.directives, 'directive', context);
11171 if (ast.temps > 0) {
11172 newline();
11173 }
11174 }
11175 if (ast.temps > 0) {
11176 push(`let `);
11177 for (let i = 0; i < ast.temps; i++) {
11178 push(`${i > 0 ? `, ` : ``}_temp${i}`);
11179 }
11180 }
11181 if (ast.components.length || ast.directives.length || ast.temps) {
11182 push(`\n`);
11183 newline();
11184 }
11185 // generate the VNode tree expression
11186 if (!ssr) {
11187 push(`return `);
11188 }
11189 if (ast.codegenNode) {
11190 genNode(ast.codegenNode, context);
11191 }
11192 else {
11193 push(`null`);
11194 }
11195 if (useWithBlock) {
11196 deindent();
11197 push(`}`);
11198 }
11199 deindent();
11200 push(`}`);
11201 return {
11202 ast,
11203 code: context.code,
11204 preamble: ``,
11205 // SourceMapGenerator does have toJSON() method but it's not in the types
11206 map: context.map ? context.map.toJSON() : undefined
11207 };
11208 }
11209 function genFunctionPreamble(ast, context) {
11210 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
11211 const VueBinding = runtimeGlobalName;
11212 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
11213 // Generate const declaration for helpers
11214 // In prefix mode, we place the const declaration at top so it's done
11215 // only once; But if we not prefixing, we place the declaration inside the
11216 // with block so it doesn't incur the `in` check cost for every helper access.
11217 if (ast.helpers.length > 0) {
11218 {
11219 // "with" mode.
11220 // save Vue in a separate variable to avoid collision
11221 push(`const _Vue = ${VueBinding}\n`);
11222 // in "with" mode, helpers are declared inside the with block to avoid
11223 // has check cost, but hoists are lifted out of the function - we need
11224 // to provide the helper here.
11225 if (ast.hoists.length) {
11226 const staticHelpers = [
11227 CREATE_VNODE,
11228 CREATE_COMMENT,
11229 CREATE_TEXT,
11230 CREATE_STATIC
11231 ]
11232 .filter(helper => ast.helpers.includes(helper))
11233 .map(aliasHelper)
11234 .join(', ');
11235 push(`const { ${staticHelpers} } = _Vue\n`);
11236 }
11237 }
11238 }
11239 genHoists(ast.hoists, context);
11240 newline();
11241 push(`return `);
11242 }
11243 function genAssets(assets, type, { helper, push, newline }) {
11244 const resolver = helper(type === 'component' ? RESOLVE_COMPONENT : RESOLVE_DIRECTIVE);
11245 for (let i = 0; i < assets.length; i++) {
11246 const id = assets[i];
11247 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)})`);
11248 if (i < assets.length - 1) {
11249 newline();
11250 }
11251 }
11252 }
11253 function genHoists(hoists, context) {
11254 if (!hoists.length) {
11255 return;
11256 }
11257 context.pure = true;
11258 const { push, newline, helper, scopeId, mode } = context;
11259 newline();
11260 hoists.forEach((exp, i) => {
11261 if (exp) {
11262 push(`const _hoisted_${i + 1} = `);
11263 genNode(exp, context);
11264 newline();
11265 }
11266 });
11267 context.pure = false;
11268 }
11269 function isText$1(n) {
11270 return (isString(n) ||
11271 n.type === 4 /* SIMPLE_EXPRESSION */ ||
11272 n.type === 2 /* TEXT */ ||
11273 n.type === 5 /* INTERPOLATION */ ||
11274 n.type === 8 /* COMPOUND_EXPRESSION */);
11275 }
11276 function genNodeListAsArray(nodes, context) {
11277 const multilines = nodes.length > 3 ||
11278 (nodes.some(n => isArray(n) || !isText$1(n)));
11279 context.push(`[`);
11280 multilines && context.indent();
11281 genNodeList(nodes, context, multilines);
11282 multilines && context.deindent();
11283 context.push(`]`);
11284 }
11285 function genNodeList(nodes, context, multilines = false, comma = true) {
11286 const { push, newline } = context;
11287 for (let i = 0; i < nodes.length; i++) {
11288 const node = nodes[i];
11289 if (isString(node)) {
11290 push(node);
11291 }
11292 else if (isArray(node)) {
11293 genNodeListAsArray(node, context);
11294 }
11295 else {
11296 genNode(node, context);
11297 }
11298 if (i < nodes.length - 1) {
11299 if (multilines) {
11300 comma && push(',');
11301 newline();
11302 }
11303 else {
11304 comma && push(', ');
11305 }
11306 }
11307 }
11308 }
11309 function genNode(node, context) {
11310 if (isString(node)) {
11311 context.push(node);
11312 return;
11313 }
11314 if (isSymbol(node)) {
11315 context.push(context.helper(node));
11316 return;
11317 }
11318 switch (node.type) {
11319 case 1 /* ELEMENT */:
11320 case 9 /* IF */:
11321 case 11 /* FOR */:
11322 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
11323 `Apply appropriate transforms first.`);
11324 genNode(node.codegenNode, context);
11325 break;
11326 case 2 /* TEXT */:
11327 genText(node, context);
11328 break;
11329 case 4 /* SIMPLE_EXPRESSION */:
11330 genExpression(node, context);
11331 break;
11332 case 5 /* INTERPOLATION */:
11333 genInterpolation(node, context);
11334 break;
11335 case 12 /* TEXT_CALL */:
11336 genNode(node.codegenNode, context);
11337 break;
11338 case 8 /* COMPOUND_EXPRESSION */:
11339 genCompoundExpression(node, context);
11340 break;
11341 case 3 /* COMMENT */:
11342 genComment(node, context);
11343 break;
11344 case 13 /* VNODE_CALL */:
11345 genVNodeCall(node, context);
11346 break;
11347 case 14 /* JS_CALL_EXPRESSION */:
11348 genCallExpression(node, context);
11349 break;
11350 case 15 /* JS_OBJECT_EXPRESSION */:
11351 genObjectExpression(node, context);
11352 break;
11353 case 17 /* JS_ARRAY_EXPRESSION */:
11354 genArrayExpression(node, context);
11355 break;
11356 case 18 /* JS_FUNCTION_EXPRESSION */:
11357 genFunctionExpression(node, context);
11358 break;
11359 case 19 /* JS_CONDITIONAL_EXPRESSION */:
11360 genConditionalExpression(node, context);
11361 break;
11362 case 20 /* JS_CACHE_EXPRESSION */:
11363 genCacheExpression(node, context);
11364 break;
11365 // SSR only types
11366 case 21 /* JS_BLOCK_STATEMENT */:
11367 break;
11368 case 22 /* JS_TEMPLATE_LITERAL */:
11369 break;
11370 case 23 /* JS_IF_STATEMENT */:
11371 break;
11372 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
11373 break;
11374 case 25 /* JS_SEQUENCE_EXPRESSION */:
11375 break;
11376 case 26 /* JS_RETURN_STATEMENT */:
11377 break;
11378 /* istanbul ignore next */
11379 case 10 /* IF_BRANCH */:
11380 // noop
11381 break;
11382 default:
11383 {
11384 assert(false, `unhandled codegen node type: ${node.type}`);
11385 // make sure we exhaust all possible types
11386 const exhaustiveCheck = node;
11387 return exhaustiveCheck;
11388 }
11389 }
11390 }
11391 function genText(node, context) {
11392 context.push(JSON.stringify(node.content), node);
11393 }
11394 function genExpression(node, context) {
11395 const { content, isStatic } = node;
11396 context.push(isStatic ? JSON.stringify(content) : content, node);
11397 }
11398 function genInterpolation(node, context) {
11399 const { push, helper, pure } = context;
11400 if (pure)
11401 push(PURE_ANNOTATION);
11402 push(`${helper(TO_DISPLAY_STRING)}(`);
11403 genNode(node.content, context);
11404 push(`)`);
11405 }
11406 function genCompoundExpression(node, context) {
11407 for (let i = 0; i < node.children.length; i++) {
11408 const child = node.children[i];
11409 if (isString(child)) {
11410 context.push(child);
11411 }
11412 else {
11413 genNode(child, context);
11414 }
11415 }
11416 }
11417 function genExpressionAsPropertyKey(node, context) {
11418 const { push } = context;
11419 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
11420 push(`[`);
11421 genCompoundExpression(node, context);
11422 push(`]`);
11423 }
11424 else if (node.isStatic) {
11425 // only quote keys if necessary
11426 const text = isSimpleIdentifier(node.content)
11427 ? node.content
11428 : JSON.stringify(node.content);
11429 push(text, node);
11430 }
11431 else {
11432 push(`[${node.content}]`, node);
11433 }
11434 }
11435 function genComment(node, context) {
11436 {
11437 const { push, helper, pure } = context;
11438 if (pure) {
11439 push(PURE_ANNOTATION);
11440 }
11441 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
11442 }
11443 }
11444 function genVNodeCall(node, context) {
11445 const { push, helper, pure } = context;
11446 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
11447 if (directives) {
11448 push(helper(WITH_DIRECTIVES) + `(`);
11449 }
11450 if (isBlock) {
11451 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
11452 }
11453 if (pure) {
11454 push(PURE_ANNOTATION);
11455 }
11456 push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
11457 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
11458 push(`)`);
11459 if (isBlock) {
11460 push(`)`);
11461 }
11462 if (directives) {
11463 push(`, `);
11464 genNode(directives, context);
11465 push(`)`);
11466 }
11467 }
11468 function genNullableArgs(args) {
11469 let i = args.length;
11470 while (i--) {
11471 if (args[i] != null)
11472 break;
11473 }
11474 return args.slice(0, i + 1).map(arg => arg || `null`);
11475 }
11476 // JavaScript
11477 function genCallExpression(node, context) {
11478 const { push, helper, pure } = context;
11479 const callee = isString(node.callee) ? node.callee : helper(node.callee);
11480 if (pure) {
11481 push(PURE_ANNOTATION);
11482 }
11483 push(callee + `(`, node);
11484 genNodeList(node.arguments, context);
11485 push(`)`);
11486 }
11487 function genObjectExpression(node, context) {
11488 const { push, indent, deindent, newline } = context;
11489 const { properties } = node;
11490 if (!properties.length) {
11491 push(`{}`, node);
11492 return;
11493 }
11494 const multilines = properties.length > 1 ||
11495 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
11496 push(multilines ? `{` : `{ `);
11497 multilines && indent();
11498 for (let i = 0; i < properties.length; i++) {
11499 const { key, value } = properties[i];
11500 // key
11501 genExpressionAsPropertyKey(key, context);
11502 push(`: `);
11503 // value
11504 genNode(value, context);
11505 if (i < properties.length - 1) {
11506 // will only reach this if it's multilines
11507 push(`,`);
11508 newline();
11509 }
11510 }
11511 multilines && deindent();
11512 push(multilines ? `}` : ` }`);
11513 }
11514 function genArrayExpression(node, context) {
11515 genNodeListAsArray(node.elements, context);
11516 }
11517 function genFunctionExpression(node, context) {
11518 const { push, indent, deindent, scopeId, mode } = context;
11519 const { params, returns, body, newline, isSlot } = node;
11520 if (isSlot) {
11521 push(`_${helperNameMap[WITH_CTX]}(`);
11522 }
11523 push(`(`, node);
11524 if (isArray(params)) {
11525 genNodeList(params, context);
11526 }
11527 else if (params) {
11528 genNode(params, context);
11529 }
11530 push(`) => `);
11531 if (newline || body) {
11532 push(`{`);
11533 indent();
11534 }
11535 if (returns) {
11536 if (newline) {
11537 push(`return `);
11538 }
11539 if (isArray(returns)) {
11540 genNodeListAsArray(returns, context);
11541 }
11542 else {
11543 genNode(returns, context);
11544 }
11545 }
11546 else if (body) {
11547 genNode(body, context);
11548 }
11549 if (newline || body) {
11550 deindent();
11551 push(`}`);
11552 }
11553 if (isSlot) {
11554 push(`)`);
11555 }
11556 }
11557 function genConditionalExpression(node, context) {
11558 const { test, consequent, alternate, newline: needNewline } = node;
11559 const { push, indent, deindent, newline } = context;
11560 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
11561 const needsParens = !isSimpleIdentifier(test.content);
11562 needsParens && push(`(`);
11563 genExpression(test, context);
11564 needsParens && push(`)`);
11565 }
11566 else {
11567 push(`(`);
11568 genNode(test, context);
11569 push(`)`);
11570 }
11571 needNewline && indent();
11572 context.indentLevel++;
11573 needNewline || push(` `);
11574 push(`? `);
11575 genNode(consequent, context);
11576 context.indentLevel--;
11577 needNewline && newline();
11578 needNewline || push(` `);
11579 push(`: `);
11580 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
11581 if (!isNested) {
11582 context.indentLevel++;
11583 }
11584 genNode(alternate, context);
11585 if (!isNested) {
11586 context.indentLevel--;
11587 }
11588 needNewline && deindent(true /* without newline */);
11589 }
11590 function genCacheExpression(node, context) {
11591 const { push, helper, indent, deindent, newline } = context;
11592 push(`_cache[${node.index}] || (`);
11593 if (node.isVNode) {
11594 indent();
11595 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
11596 newline();
11597 }
11598 push(`_cache[${node.index}] = `);
11599 genNode(node.value, context);
11600 if (node.isVNode) {
11601 push(`,`);
11602 newline();
11603 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
11604 newline();
11605 push(`_cache[${node.index}]`);
11606 deindent();
11607 }
11608 push(`)`);
11609 }
11610
11611 // these keywords should not appear inside expressions, but operators like
11612 // typeof, instanceof and in are allowed
11613 const prohibitedKeywordRE = new RegExp('\\b' +
11614 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
11615 'super,throw,while,yield,delete,export,import,return,switch,default,' +
11616 'extends,finally,continue,debugger,function,arguments,typeof,void')
11617 .split(',')
11618 .join('\\b|\\b') +
11619 '\\b');
11620 // strip strings in expressions
11621 const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
11622 /**
11623 * Validate a non-prefixed expression.
11624 * This is only called when using the in-browser runtime compiler since it
11625 * doesn't prefix expressions.
11626 */
11627 function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
11628 const exp = node.content;
11629 // empty expressions are validated per-directive since some directives
11630 // do allow empty expressions.
11631 if (!exp.trim()) {
11632 return;
11633 }
11634 try {
11635 new Function(asRawStatements
11636 ? ` ${exp} `
11637 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
11638 }
11639 catch (e) {
11640 let message = e.message;
11641 const keywordMatch = exp
11642 .replace(stripStringRE, '')
11643 .match(prohibitedKeywordRE);
11644 if (keywordMatch) {
11645 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
11646 }
11647 context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
11648 }
11649 }
11650
11651 const transformExpression = (node, context) => {
11652 if (node.type === 5 /* INTERPOLATION */) {
11653 node.content = processExpression(node.content, context);
11654 }
11655 else if (node.type === 1 /* ELEMENT */) {
11656 // handle directives on element
11657 for (let i = 0; i < node.props.length; i++) {
11658 const dir = node.props[i];
11659 // do not process for v-on & v-for since they are special handled
11660 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
11661 const exp = dir.exp;
11662 const arg = dir.arg;
11663 // do not process exp if this is v-on:arg - we need special handling
11664 // for wrapping inline statements.
11665 if (exp &&
11666 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
11667 !(dir.name === 'on' && arg)) {
11668 dir.exp = processExpression(exp, context,
11669 // slot args must be processed as function params
11670 dir.name === 'slot');
11671 }
11672 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
11673 dir.arg = processExpression(arg, context);
11674 }
11675 }
11676 }
11677 }
11678 };
11679 // Important: since this function uses Node.js only dependencies, it should
11680 // always be used with a leading !true check so that it can be
11681 // tree-shaken from the browser build.
11682 function processExpression(node, context,
11683 // some expressions like v-slot props & v-for aliases should be parsed as
11684 // function params
11685 asParams = false,
11686 // v-on handler values may contain multiple statements
11687 asRawStatements = false) {
11688 {
11689 {
11690 // simple in-browser validation (same logic in 2.x)
11691 validateBrowserExpression(node, context, asParams, asRawStatements);
11692 }
11693 return node;
11694 }
11695 }
11696
11697 const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
11698 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
11699 // #1587: We need to dynamically increment the key based on the current
11700 // node's sibling nodes, since chained v-if/else branches are
11701 // rendered at the same depth
11702 const siblings = context.parent.children;
11703 let i = siblings.indexOf(ifNode);
11704 let key = 0;
11705 while (i-- >= 0) {
11706 const sibling = siblings[i];
11707 if (sibling && sibling.type === 9 /* IF */) {
11708 key += sibling.branches.length;
11709 }
11710 }
11711 // Exit callback. Complete the codegenNode when all children have been
11712 // transformed.
11713 return () => {
11714 if (isRoot) {
11715 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
11716 }
11717 else {
11718 // attach this branch's codegen node to the v-if root.
11719 const parentCondition = getParentCondition(ifNode.codegenNode);
11720 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
11721 }
11722 };
11723 });
11724 });
11725 // target-agnostic transform used for both Client and SSR
11726 function processIf(node, dir, context, processCodegen) {
11727 if (dir.name !== 'else' &&
11728 (!dir.exp || !dir.exp.content.trim())) {
11729 const loc = dir.exp ? dir.exp.loc : node.loc;
11730 context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
11731 dir.exp = createSimpleExpression(`true`, false, loc);
11732 }
11733 if (dir.exp) {
11734 validateBrowserExpression(dir.exp, context);
11735 }
11736 if (dir.name === 'if') {
11737 const branch = createIfBranch(node, dir);
11738 const ifNode = {
11739 type: 9 /* IF */,
11740 loc: node.loc,
11741 branches: [branch]
11742 };
11743 context.replaceNode(ifNode);
11744 if (processCodegen) {
11745 return processCodegen(ifNode, branch, true);
11746 }
11747 }
11748 else {
11749 // locate the adjacent v-if
11750 const siblings = context.parent.children;
11751 const comments = [];
11752 let i = siblings.indexOf(node);
11753 while (i-- >= -1) {
11754 const sibling = siblings[i];
11755 if (sibling && sibling.type === 3 /* COMMENT */) {
11756 context.removeNode(sibling);
11757 comments.unshift(sibling);
11758 continue;
11759 }
11760 if (sibling &&
11761 sibling.type === 2 /* TEXT */ &&
11762 !sibling.content.trim().length) {
11763 context.removeNode(sibling);
11764 continue;
11765 }
11766 if (sibling && sibling.type === 9 /* IF */) {
11767 // move the node to the if node's branches
11768 context.removeNode();
11769 const branch = createIfBranch(node, dir);
11770 if (comments.length) {
11771 branch.children = [...comments, ...branch.children];
11772 }
11773 // check if user is forcing same key on different branches
11774 {
11775 const key = branch.userKey;
11776 if (key) {
11777 sibling.branches.forEach(({ userKey }) => {
11778 if (isSameKey(userKey, key)) {
11779 context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
11780 }
11781 });
11782 }
11783 }
11784 sibling.branches.push(branch);
11785 const onExit = processCodegen && processCodegen(sibling, branch, false);
11786 // since the branch was removed, it will not be traversed.
11787 // make sure to traverse here.
11788 traverseNode(branch, context);
11789 // call on exit
11790 if (onExit)
11791 onExit();
11792 // make sure to reset currentNode after traversal to indicate this
11793 // node has been removed.
11794 context.currentNode = null;
11795 }
11796 else {
11797 context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
11798 }
11799 break;
11800 }
11801 }
11802 }
11803 function createIfBranch(node, dir) {
11804 return {
11805 type: 10 /* IF_BRANCH */,
11806 loc: node.loc,
11807 condition: dir.name === 'else' ? undefined : dir.exp,
11808 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
11809 ? node.children
11810 : [node],
11811 userKey: findProp(node, `key`)
11812 };
11813 }
11814 function createCodegenNodeForBranch(branch, keyIndex, context) {
11815 if (branch.condition) {
11816 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
11817 // make sure to pass in asBlock: true so that the comment node call
11818 // closes the current block.
11819 createCallExpression(context.helper(CREATE_COMMENT), [
11820 '"v-if"' ,
11821 'true'
11822 ]));
11823 }
11824 else {
11825 return createChildrenCodegenNode(branch, keyIndex, context);
11826 }
11827 }
11828 function createChildrenCodegenNode(branch, keyIndex, context) {
11829 const { helper } = context;
11830 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
11831 const { children } = branch;
11832 const firstChild = children[0];
11833 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
11834 if (needFragmentWrapper) {
11835 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
11836 // optimize away nested fragments when child is a ForNode
11837 const vnodeCall = firstChild.codegenNode;
11838 injectProp(vnodeCall, keyProperty, context);
11839 return vnodeCall;
11840 }
11841 else {
11842 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, 64 /* STABLE_FRAGMENT */ +
11843 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
11844 ), undefined, undefined, true, false, branch.loc);
11845 }
11846 }
11847 else {
11848 const vnodeCall = firstChild
11849 .codegenNode;
11850 // Change createVNode to createBlock.
11851 if (vnodeCall.type === 13 /* VNODE_CALL */) {
11852 vnodeCall.isBlock = true;
11853 helper(OPEN_BLOCK);
11854 helper(CREATE_BLOCK);
11855 }
11856 // inject branch key
11857 injectProp(vnodeCall, keyProperty, context);
11858 return vnodeCall;
11859 }
11860 }
11861 function isSameKey(a, b) {
11862 if (!a || a.type !== b.type) {
11863 return false;
11864 }
11865 if (a.type === 6 /* ATTRIBUTE */) {
11866 if (a.value.content !== b.value.content) {
11867 return false;
11868 }
11869 }
11870 else {
11871 // directive
11872 const exp = a.exp;
11873 const branchExp = b.exp;
11874 if (exp.type !== branchExp.type) {
11875 return false;
11876 }
11877 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
11878 (exp.isStatic !== branchExp.isStatic ||
11879 exp.content !== branchExp.content)) {
11880 return false;
11881 }
11882 }
11883 return true;
11884 }
11885 function getParentCondition(node) {
11886 while (true) {
11887 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
11888 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
11889 node = node.alternate;
11890 }
11891 else {
11892 return node;
11893 }
11894 }
11895 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
11896 node = node.value;
11897 }
11898 }
11899 }
11900
11901 const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
11902 const { helper } = context;
11903 return processFor(node, dir, context, forNode => {
11904 // create the loop render function expression now, and add the
11905 // iterator on exit after all children have been traversed
11906 const renderExp = createCallExpression(helper(RENDER_LIST), [
11907 forNode.source
11908 ]);
11909 const keyProp = findProp(node, `key`);
11910 const keyProperty = keyProp
11911 ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
11912 ? createSimpleExpression(keyProp.value.content, true)
11913 : keyProp.exp)
11914 : null;
11915 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
11916 forNode.source.constType > 0 /* NOT_CONSTANT */;
11917 const fragmentFlag = isStableFragment
11918 ? 64 /* STABLE_FRAGMENT */
11919 : keyProp
11920 ? 128 /* KEYED_FRAGMENT */
11921 : 256 /* UNKEYED_FRAGMENT */;
11922 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
11923 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
11924 return () => {
11925 // finish the codegen now that all children have been traversed
11926 let childBlock;
11927 const isTemplate = isTemplateNode(node);
11928 const { children } = forNode;
11929 // check <template v-for> key placement
11930 if (isTemplate) {
11931 node.children.some(c => {
11932 if (c.type === 1 /* ELEMENT */) {
11933 const key = findProp(c, 'key');
11934 if (key) {
11935 context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
11936 return true;
11937 }
11938 }
11939 });
11940 }
11941 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
11942 const slotOutlet = isSlotOutlet(node)
11943 ? node
11944 : isTemplate &&
11945 node.children.length === 1 &&
11946 isSlotOutlet(node.children[0])
11947 ? node.children[0] // api-extractor somehow fails to infer this
11948 : null;
11949 if (slotOutlet) {
11950 // <slot v-for="..."> or <template v-for="..."><slot/></template>
11951 childBlock = slotOutlet.codegenNode;
11952 if (isTemplate && keyProperty) {
11953 // <template v-for="..." :key="..."><slot/></template>
11954 // we need to inject the key to the renderSlot() call.
11955 // the props for renderSlot is passed as the 3rd argument.
11956 injectProp(childBlock, keyProperty, context);
11957 }
11958 }
11959 else if (needFragmentWrapper) {
11960 // <template v-for="..."> with text or multi-elements
11961 // should generate a fragment block for each loop
11962 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
11963 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
11964 ), undefined, undefined, true);
11965 }
11966 else {
11967 // Normal element v-for. Directly use the child's codegenNode
11968 // but mark it as a block.
11969 childBlock = children[0]
11970 .codegenNode;
11971 if (isTemplate && keyProperty) {
11972 injectProp(childBlock, keyProperty, context);
11973 }
11974 childBlock.isBlock = !isStableFragment;
11975 if (childBlock.isBlock) {
11976 helper(OPEN_BLOCK);
11977 helper(CREATE_BLOCK);
11978 }
11979 else {
11980 helper(CREATE_VNODE);
11981 }
11982 }
11983 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
11984 };
11985 });
11986 });
11987 // target-agnostic transform used for both Client and SSR
11988 function processFor(node, dir, context, processCodegen) {
11989 if (!dir.exp) {
11990 context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
11991 return;
11992 }
11993 const parseResult = parseForExpression(
11994 // can only be simple expression because vFor transform is applied
11995 // before expression transform.
11996 dir.exp, context);
11997 if (!parseResult) {
11998 context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
11999 return;
12000 }
12001 const { addIdentifiers, removeIdentifiers, scopes } = context;
12002 const { source, value, key, index } = parseResult;
12003 const forNode = {
12004 type: 11 /* FOR */,
12005 loc: dir.loc,
12006 source,
12007 valueAlias: value,
12008 keyAlias: key,
12009 objectIndexAlias: index,
12010 parseResult,
12011 children: isTemplateNode(node) ? node.children : [node]
12012 };
12013 context.replaceNode(forNode);
12014 // bookkeeping
12015 scopes.vFor++;
12016 const onExit = processCodegen && processCodegen(forNode);
12017 return () => {
12018 scopes.vFor--;
12019 if (onExit)
12020 onExit();
12021 };
12022 }
12023 const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
12024 // This regex doesn't cover the case if key or index aliases have destructuring,
12025 // but those do not make sense in the first place, so this works in practice.
12026 const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
12027 const stripParensRE = /^\(|\)$/g;
12028 function parseForExpression(input, context) {
12029 const loc = input.loc;
12030 const exp = input.content;
12031 const inMatch = exp.match(forAliasRE);
12032 if (!inMatch)
12033 return;
12034 const [, LHS, RHS] = inMatch;
12035 const result = {
12036 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
12037 value: undefined,
12038 key: undefined,
12039 index: undefined
12040 };
12041 {
12042 validateBrowserExpression(result.source, context);
12043 }
12044 let valueContent = LHS.trim()
12045 .replace(stripParensRE, '')
12046 .trim();
12047 const trimmedOffset = LHS.indexOf(valueContent);
12048 const iteratorMatch = valueContent.match(forIteratorRE);
12049 if (iteratorMatch) {
12050 valueContent = valueContent.replace(forIteratorRE, '').trim();
12051 const keyContent = iteratorMatch[1].trim();
12052 let keyOffset;
12053 if (keyContent) {
12054 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
12055 result.key = createAliasExpression(loc, keyContent, keyOffset);
12056 {
12057 validateBrowserExpression(result.key, context, true);
12058 }
12059 }
12060 if (iteratorMatch[2]) {
12061 const indexContent = iteratorMatch[2].trim();
12062 if (indexContent) {
12063 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
12064 ? keyOffset + keyContent.length
12065 : trimmedOffset + valueContent.length));
12066 {
12067 validateBrowserExpression(result.index, context, true);
12068 }
12069 }
12070 }
12071 }
12072 if (valueContent) {
12073 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
12074 {
12075 validateBrowserExpression(result.value, context, true);
12076 }
12077 }
12078 return result;
12079 }
12080 function createAliasExpression(range, content, offset) {
12081 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
12082 }
12083 function createForLoopParams({ value, key, index }) {
12084 const params = [];
12085 if (value) {
12086 params.push(value);
12087 }
12088 if (key) {
12089 if (!value) {
12090 params.push(createSimpleExpression(`_`, false));
12091 }
12092 params.push(key);
12093 }
12094 if (index) {
12095 if (!key) {
12096 if (!value) {
12097 params.push(createSimpleExpression(`_`, false));
12098 }
12099 params.push(createSimpleExpression(`__`, false));
12100 }
12101 params.push(index);
12102 }
12103 return params;
12104 }
12105
12106 const defaultFallback = createSimpleExpression(`undefined`, false);
12107 // A NodeTransform that:
12108 // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
12109 // by transformExpression. This is only applied in non-browser builds with
12110 // { prefixIdentifiers: true }.
12111 // 2. Track v-slot depths so that we know a slot is inside another slot.
12112 // Note the exit callback is executed before buildSlots() on the same node,
12113 // so only nested slots see positive numbers.
12114 const trackSlotScopes = (node, context) => {
12115 if (node.type === 1 /* ELEMENT */ &&
12116 (node.tagType === 1 /* COMPONENT */ ||
12117 node.tagType === 3 /* TEMPLATE */)) {
12118 // We are only checking non-empty v-slot here
12119 // since we only care about slots that introduce scope variables.
12120 const vSlot = findDir(node, 'slot');
12121 if (vSlot) {
12122 vSlot.exp;
12123 context.scopes.vSlot++;
12124 return () => {
12125 context.scopes.vSlot--;
12126 };
12127 }
12128 }
12129 };
12130 const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
12131 // Instead of being a DirectiveTransform, v-slot processing is called during
12132 // transformElement to build the slots object for a component.
12133 function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
12134 context.helper(WITH_CTX);
12135 const { children, loc } = node;
12136 const slotsProperties = [];
12137 const dynamicSlots = [];
12138 const buildDefaultSlotProperty = (props, children) => createObjectProperty(`default`, buildSlotFn(props, children, loc));
12139 // If the slot is inside a v-for or another v-slot, force it to be dynamic
12140 // since it likely uses a scope variable.
12141 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
12142 // 1. Check for slot with slotProps on component itself.
12143 // <Comp v-slot="{ prop }"/>
12144 const onComponentSlot = findDir(node, 'slot', true);
12145 if (onComponentSlot) {
12146 const { arg, exp } = onComponentSlot;
12147 if (arg && !isStaticExp(arg)) {
12148 hasDynamicSlots = true;
12149 }
12150 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
12151 }
12152 // 2. Iterate through children and check for template slots
12153 // <template v-slot:foo="{ prop }">
12154 let hasTemplateSlots = false;
12155 let hasNamedDefaultSlot = false;
12156 const implicitDefaultChildren = [];
12157 const seenSlotNames = new Set();
12158 for (let i = 0; i < children.length; i++) {
12159 const slotElement = children[i];
12160 let slotDir;
12161 if (!isTemplateNode(slotElement) ||
12162 !(slotDir = findDir(slotElement, 'slot', true))) {
12163 // not a <template v-slot>, skip.
12164 if (slotElement.type !== 3 /* COMMENT */) {
12165 implicitDefaultChildren.push(slotElement);
12166 }
12167 continue;
12168 }
12169 if (onComponentSlot) {
12170 // already has on-component slot - this is incorrect usage.
12171 context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
12172 break;
12173 }
12174 hasTemplateSlots = true;
12175 const { children: slotChildren, loc: slotLoc } = slotElement;
12176 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
12177 // check if name is dynamic.
12178 let staticSlotName;
12179 if (isStaticExp(slotName)) {
12180 staticSlotName = slotName ? slotName.content : `default`;
12181 }
12182 else {
12183 hasDynamicSlots = true;
12184 }
12185 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
12186 // check if this slot is conditional (v-if/v-for)
12187 let vIf;
12188 let vElse;
12189 let vFor;
12190 if ((vIf = findDir(slotElement, 'if'))) {
12191 hasDynamicSlots = true;
12192 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
12193 }
12194 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
12195 // find adjacent v-if
12196 let j = i;
12197 let prev;
12198 while (j--) {
12199 prev = children[j];
12200 if (prev.type !== 3 /* COMMENT */) {
12201 break;
12202 }
12203 }
12204 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
12205 // remove node
12206 children.splice(i, 1);
12207 i--;
12208 // attach this slot to previous conditional
12209 let conditional = dynamicSlots[dynamicSlots.length - 1];
12210 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12211 conditional = conditional.alternate;
12212 }
12213 conditional.alternate = vElse.exp
12214 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
12215 : buildDynamicSlot(slotName, slotFunction);
12216 }
12217 else {
12218 context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
12219 }
12220 }
12221 else if ((vFor = findDir(slotElement, 'for'))) {
12222 hasDynamicSlots = true;
12223 const parseResult = vFor.parseResult ||
12224 parseForExpression(vFor.exp, context);
12225 if (parseResult) {
12226 // Render the dynamic slots as an array and add it to the createSlot()
12227 // args. The runtime knows how to handle it appropriately.
12228 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
12229 parseResult.source,
12230 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
12231 ]));
12232 }
12233 else {
12234 context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
12235 }
12236 }
12237 else {
12238 // check duplicate static names
12239 if (staticSlotName) {
12240 if (seenSlotNames.has(staticSlotName)) {
12241 context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
12242 continue;
12243 }
12244 seenSlotNames.add(staticSlotName);
12245 if (staticSlotName === 'default') {
12246 hasNamedDefaultSlot = true;
12247 }
12248 }
12249 slotsProperties.push(createObjectProperty(slotName, slotFunction));
12250 }
12251 }
12252 if (!onComponentSlot) {
12253 if (!hasTemplateSlots) {
12254 // implicit default slot (on component)
12255 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
12256 }
12257 else if (implicitDefaultChildren.length) {
12258 // implicit default slot (mixed with named slots)
12259 if (hasNamedDefaultSlot) {
12260 context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
12261 }
12262 else {
12263 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
12264 }
12265 }
12266 }
12267 const slotFlag = hasDynamicSlots
12268 ? 2 /* DYNAMIC */
12269 : hasForwardedSlots(node.children)
12270 ? 3 /* FORWARDED */
12271 : 1 /* STABLE */;
12272 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
12273 // 2 = compiled but dynamic = can skip normalization, but must run diff
12274 // 1 = compiled and static = can skip normalization AND diff as optimized
12275 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
12276 if (dynamicSlots.length) {
12277 slots = createCallExpression(context.helper(CREATE_SLOTS), [
12278 slots,
12279 createArrayExpression(dynamicSlots)
12280 ]);
12281 }
12282 return {
12283 slots,
12284 hasDynamicSlots
12285 };
12286 }
12287 function buildDynamicSlot(name, fn) {
12288 return createObjectExpression([
12289 createObjectProperty(`name`, name),
12290 createObjectProperty(`fn`, fn)
12291 ]);
12292 }
12293 function hasForwardedSlots(children) {
12294 for (let i = 0; i < children.length; i++) {
12295 const child = children[i];
12296 if (child.type === 1 /* ELEMENT */) {
12297 if (child.tagType === 2 /* SLOT */ ||
12298 (child.tagType === 0 /* ELEMENT */ &&
12299 hasForwardedSlots(child.children))) {
12300 return true;
12301 }
12302 }
12303 }
12304 return false;
12305 }
12306
12307 // some directive transforms (e.g. v-model) may return a symbol for runtime
12308 // import, which should be used instead of a resolveDirective call.
12309 const directiveImportMap = new WeakMap();
12310 // generate a JavaScript AST for this element's codegen
12311 const transformElement = (node, context) => {
12312 if (!(node.type === 1 /* ELEMENT */ &&
12313 (node.tagType === 0 /* ELEMENT */ ||
12314 node.tagType === 1 /* COMPONENT */))) {
12315 return;
12316 }
12317 // perform the work on exit, after all child expressions have been
12318 // processed and merged.
12319 return function postTransformElement() {
12320 const { tag, props } = node;
12321 const isComponent = node.tagType === 1 /* COMPONENT */;
12322 // The goal of the transform is to create a codegenNode implementing the
12323 // VNodeCall interface.
12324 const vnodeTag = isComponent
12325 ? resolveComponentType(node, context)
12326 : `"${tag}"`;
12327 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
12328 let vnodeProps;
12329 let vnodeChildren;
12330 let vnodePatchFlag;
12331 let patchFlag = 0;
12332 let vnodeDynamicProps;
12333 let dynamicPropNames;
12334 let vnodeDirectives;
12335 let shouldUseBlock =
12336 // dynamic component may resolve to plain elements
12337 isDynamicComponent ||
12338 vnodeTag === TELEPORT ||
12339 vnodeTag === SUSPENSE ||
12340 (!isComponent &&
12341 // <svg> and <foreignObject> must be forced into blocks so that block
12342 // updates inside get proper isSVG flag at runtime. (#639, #643)
12343 // This is technically web-specific, but splitting the logic out of core
12344 // leads to too much unnecessary complexity.
12345 (tag === 'svg' ||
12346 tag === 'foreignObject' ||
12347 // #938: elements with dynamic keys should be forced into blocks
12348 findProp(node, 'key', true)));
12349 // props
12350 if (props.length > 0) {
12351 const propsBuildResult = buildProps(node, context);
12352 vnodeProps = propsBuildResult.props;
12353 patchFlag = propsBuildResult.patchFlag;
12354 dynamicPropNames = propsBuildResult.dynamicPropNames;
12355 const directives = propsBuildResult.directives;
12356 vnodeDirectives =
12357 directives && directives.length
12358 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
12359 : undefined;
12360 }
12361 // children
12362 if (node.children.length > 0) {
12363 if (vnodeTag === KEEP_ALIVE) {
12364 // Although a built-in component, we compile KeepAlive with raw children
12365 // instead of slot functions so that it can be used inside Transition
12366 // or other Transition-wrapping HOCs.
12367 // To ensure correct updates with block optimizations, we need to:
12368 // 1. Force keep-alive into a block. This avoids its children being
12369 // collected by a parent block.
12370 shouldUseBlock = true;
12371 // 2. Force keep-alive to always be updated, since it uses raw children.
12372 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
12373 if (node.children.length > 1) {
12374 context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
12375 start: node.children[0].loc.start,
12376 end: node.children[node.children.length - 1].loc.end,
12377 source: ''
12378 }));
12379 }
12380 }
12381 const shouldBuildAsSlots = isComponent &&
12382 // Teleport is not a real component and has dedicated runtime handling
12383 vnodeTag !== TELEPORT &&
12384 // explained above.
12385 vnodeTag !== KEEP_ALIVE;
12386 if (shouldBuildAsSlots) {
12387 const { slots, hasDynamicSlots } = buildSlots(node, context);
12388 vnodeChildren = slots;
12389 if (hasDynamicSlots) {
12390 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
12391 }
12392 }
12393 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
12394 const child = node.children[0];
12395 const type = child.type;
12396 // check for dynamic text children
12397 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
12398 type === 8 /* COMPOUND_EXPRESSION */;
12399 if (hasDynamicTextChild &&
12400 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
12401 patchFlag |= 1 /* TEXT */;
12402 }
12403 // pass directly if the only child is a text node
12404 // (plain / interpolation / expression)
12405 if (hasDynamicTextChild || type === 2 /* TEXT */) {
12406 vnodeChildren = child;
12407 }
12408 else {
12409 vnodeChildren = node.children;
12410 }
12411 }
12412 else {
12413 vnodeChildren = node.children;
12414 }
12415 }
12416 // patchFlag & dynamicPropNames
12417 if (patchFlag !== 0) {
12418 {
12419 if (patchFlag < 0) {
12420 // special flags (negative and mutually exclusive)
12421 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
12422 }
12423 else {
12424 // bitwise flags
12425 const flagNames = Object.keys(PatchFlagNames)
12426 .map(Number)
12427 .filter(n => n > 0 && patchFlag & n)
12428 .map(n => PatchFlagNames[n])
12429 .join(`, `);
12430 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
12431 }
12432 }
12433 if (dynamicPropNames && dynamicPropNames.length) {
12434 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
12435 }
12436 }
12437 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
12438 };
12439 };
12440 function resolveComponentType(node, context, ssr = false) {
12441 const { tag } = node;
12442 // 1. dynamic component
12443 const isProp = node.tag === 'component' ? findProp(node, 'is') : findDir(node, 'is');
12444 if (isProp) {
12445 const exp = isProp.type === 6 /* ATTRIBUTE */
12446 ? isProp.value && createSimpleExpression(isProp.value.content, true)
12447 : isProp.exp;
12448 if (exp) {
12449 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
12450 exp
12451 ]);
12452 }
12453 }
12454 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
12455 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
12456 if (builtIn) {
12457 // built-ins are simply fallthroughs / have special handling during ssr
12458 // so we don't need to import their runtime equivalents
12459 if (!ssr)
12460 context.helper(builtIn);
12461 return builtIn;
12462 }
12463 // 5. user component (resolve)
12464 context.helper(RESOLVE_COMPONENT);
12465 context.components.add(tag);
12466 return toValidAssetId(tag, `component`);
12467 }
12468 function buildProps(node, context, props = node.props, ssr = false) {
12469 const { tag, loc: elementLoc } = node;
12470 const isComponent = node.tagType === 1 /* COMPONENT */;
12471 let properties = [];
12472 const mergeArgs = [];
12473 const runtimeDirectives = [];
12474 // patchFlag analysis
12475 let patchFlag = 0;
12476 let hasRef = false;
12477 let hasClassBinding = false;
12478 let hasStyleBinding = false;
12479 let hasHydrationEventBinding = false;
12480 let hasDynamicKeys = false;
12481 let hasVnodeHook = false;
12482 const dynamicPropNames = [];
12483 const analyzePatchFlag = ({ key, value }) => {
12484 if (isStaticExp(key)) {
12485 const name = key.content;
12486 const isEventHandler = isOn(name);
12487 if (!isComponent &&
12488 isEventHandler &&
12489 // omit the flag for click handlers because hydration gives click
12490 // dedicated fast path.
12491 name.toLowerCase() !== 'onclick' &&
12492 // omit v-model handlers
12493 name !== 'onUpdate:modelValue' &&
12494 // omit onVnodeXXX hooks
12495 !isReservedProp(name)) {
12496 hasHydrationEventBinding = true;
12497 }
12498 if (isEventHandler && isReservedProp(name)) {
12499 hasVnodeHook = true;
12500 }
12501 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
12502 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
12503 value.type === 8 /* COMPOUND_EXPRESSION */) &&
12504 getConstantType(value, context) > 0)) {
12505 // skip if the prop is a cached handler or has constant value
12506 return;
12507 }
12508 if (name === 'ref') {
12509 hasRef = true;
12510 }
12511 else if (name === 'class' && !isComponent) {
12512 hasClassBinding = true;
12513 }
12514 else if (name === 'style' && !isComponent) {
12515 hasStyleBinding = true;
12516 }
12517 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
12518 dynamicPropNames.push(name);
12519 }
12520 }
12521 else {
12522 hasDynamicKeys = true;
12523 }
12524 };
12525 for (let i = 0; i < props.length; i++) {
12526 // static attribute
12527 const prop = props[i];
12528 if (prop.type === 6 /* ATTRIBUTE */) {
12529 const { loc, name, value } = prop;
12530 let isStatic = true;
12531 if (name === 'ref') {
12532 hasRef = true;
12533 }
12534 // skip :is on <component>
12535 if (name === 'is' && tag === 'component') {
12536 continue;
12537 }
12538 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
12539 }
12540 else {
12541 // directives
12542 const { name, arg, exp, loc } = prop;
12543 const isBind = name === 'bind';
12544 const isOn = name === 'on';
12545 // skip v-slot - it is handled by its dedicated transform.
12546 if (name === 'slot') {
12547 if (!isComponent) {
12548 context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
12549 }
12550 continue;
12551 }
12552 // skip v-once - it is handled by its dedicated transform.
12553 if (name === 'once') {
12554 continue;
12555 }
12556 // skip v-is and :is on <component>
12557 if (name === 'is' ||
12558 (isBind && tag === 'component' && isBindKey(arg, 'is'))) {
12559 continue;
12560 }
12561 // skip v-on in SSR compilation
12562 if (isOn && ssr) {
12563 continue;
12564 }
12565 // special case for v-bind and v-on with no argument
12566 if (!arg && (isBind || isOn)) {
12567 hasDynamicKeys = true;
12568 if (exp) {
12569 if (properties.length) {
12570 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
12571 properties = [];
12572 }
12573 if (isBind) {
12574 mergeArgs.push(exp);
12575 }
12576 else {
12577 // v-on="obj" -> toHandlers(obj)
12578 mergeArgs.push({
12579 type: 14 /* JS_CALL_EXPRESSION */,
12580 loc,
12581 callee: context.helper(TO_HANDLERS),
12582 arguments: [exp]
12583 });
12584 }
12585 }
12586 else {
12587 context.onError(createCompilerError(isBind
12588 ? 33 /* X_V_BIND_NO_EXPRESSION */
12589 : 34 /* X_V_ON_NO_EXPRESSION */, loc));
12590 }
12591 continue;
12592 }
12593 const directiveTransform = context.directiveTransforms[name];
12594 if (directiveTransform) {
12595 // has built-in directive transform.
12596 const { props, needRuntime } = directiveTransform(prop, node, context);
12597 !ssr && props.forEach(analyzePatchFlag);
12598 properties.push(...props);
12599 if (needRuntime) {
12600 runtimeDirectives.push(prop);
12601 if (isSymbol(needRuntime)) {
12602 directiveImportMap.set(prop, needRuntime);
12603 }
12604 }
12605 }
12606 else {
12607 // no built-in transform, this is a user custom directive.
12608 runtimeDirectives.push(prop);
12609 }
12610 }
12611 }
12612 let propsExpression = undefined;
12613 // has v-bind="object" or v-on="object", wrap with mergeProps
12614 if (mergeArgs.length) {
12615 if (properties.length) {
12616 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
12617 }
12618 if (mergeArgs.length > 1) {
12619 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
12620 }
12621 else {
12622 // single v-bind with nothing else - no need for a mergeProps call
12623 propsExpression = mergeArgs[0];
12624 }
12625 }
12626 else if (properties.length) {
12627 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
12628 }
12629 // patchFlag analysis
12630 if (hasDynamicKeys) {
12631 patchFlag |= 16 /* FULL_PROPS */;
12632 }
12633 else {
12634 if (hasClassBinding) {
12635 patchFlag |= 2 /* CLASS */;
12636 }
12637 if (hasStyleBinding) {
12638 patchFlag |= 4 /* STYLE */;
12639 }
12640 if (dynamicPropNames.length) {
12641 patchFlag |= 8 /* PROPS */;
12642 }
12643 if (hasHydrationEventBinding) {
12644 patchFlag |= 32 /* HYDRATE_EVENTS */;
12645 }
12646 }
12647 if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
12648 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
12649 patchFlag |= 512 /* NEED_PATCH */;
12650 }
12651 return {
12652 props: propsExpression,
12653 directives: runtimeDirectives,
12654 patchFlag,
12655 dynamicPropNames
12656 };
12657 }
12658 // Dedupe props in an object literal.
12659 // Literal duplicated attributes would have been warned during the parse phase,
12660 // however, it's possible to encounter duplicated `onXXX` handlers with different
12661 // modifiers. We also need to merge static and dynamic class / style attributes.
12662 // - onXXX handlers / style: merge into array
12663 // - class: merge into single expression with concatenation
12664 function dedupeProperties(properties) {
12665 const knownProps = new Map();
12666 const deduped = [];
12667 for (let i = 0; i < properties.length; i++) {
12668 const prop = properties[i];
12669 // dynamic keys are always allowed
12670 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
12671 deduped.push(prop);
12672 continue;
12673 }
12674 const name = prop.key.content;
12675 const existing = knownProps.get(name);
12676 if (existing) {
12677 if (name === 'style' || name === 'class' || name.startsWith('on')) {
12678 mergeAsArray(existing, prop);
12679 }
12680 // unexpected duplicate, should have emitted error during parse
12681 }
12682 else {
12683 knownProps.set(name, prop);
12684 deduped.push(prop);
12685 }
12686 }
12687 return deduped;
12688 }
12689 function mergeAsArray(existing, incoming) {
12690 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
12691 existing.value.elements.push(incoming.value);
12692 }
12693 else {
12694 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
12695 }
12696 }
12697 function buildDirectiveArgs(dir, context) {
12698 const dirArgs = [];
12699 const runtime = directiveImportMap.get(dir);
12700 if (runtime) {
12701 // built-in directive with runtime
12702 dirArgs.push(context.helperString(runtime));
12703 }
12704 else {
12705 {
12706 // inject statement for resolving directive
12707 context.helper(RESOLVE_DIRECTIVE);
12708 context.directives.add(dir.name);
12709 dirArgs.push(toValidAssetId(dir.name, `directive`));
12710 }
12711 }
12712 const { loc } = dir;
12713 if (dir.exp)
12714 dirArgs.push(dir.exp);
12715 if (dir.arg) {
12716 if (!dir.exp) {
12717 dirArgs.push(`void 0`);
12718 }
12719 dirArgs.push(dir.arg);
12720 }
12721 if (Object.keys(dir.modifiers).length) {
12722 if (!dir.arg) {
12723 if (!dir.exp) {
12724 dirArgs.push(`void 0`);
12725 }
12726 dirArgs.push(`void 0`);
12727 }
12728 const trueExpression = createSimpleExpression(`true`, false, loc);
12729 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
12730 }
12731 return createArrayExpression(dirArgs, dir.loc);
12732 }
12733 function stringifyDynamicPropNames(props) {
12734 let propsNamesString = `[`;
12735 for (let i = 0, l = props.length; i < l; i++) {
12736 propsNamesString += JSON.stringify(props[i]);
12737 if (i < l - 1)
12738 propsNamesString += ', ';
12739 }
12740 return propsNamesString + `]`;
12741 }
12742
12743 const transformSlotOutlet = (node, context) => {
12744 if (isSlotOutlet(node)) {
12745 const { children, loc } = node;
12746 const { slotName, slotProps } = processSlotOutlet(node, context);
12747 const slotArgs = [
12748 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
12749 slotName
12750 ];
12751 if (slotProps) {
12752 slotArgs.push(slotProps);
12753 }
12754 if (children.length) {
12755 if (!slotProps) {
12756 slotArgs.push(`{}`);
12757 }
12758 slotArgs.push(createFunctionExpression([], children, false, false, loc));
12759 }
12760 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
12761 }
12762 };
12763 function processSlotOutlet(node, context) {
12764 let slotName = `"default"`;
12765 let slotProps = undefined;
12766 const nonNameProps = [];
12767 for (let i = 0; i < node.props.length; i++) {
12768 const p = node.props[i];
12769 if (p.type === 6 /* ATTRIBUTE */) {
12770 if (p.value) {
12771 if (p.name === 'name') {
12772 slotName = JSON.stringify(p.value.content);
12773 }
12774 else {
12775 p.name = camelize(p.name);
12776 nonNameProps.push(p);
12777 }
12778 }
12779 }
12780 else {
12781 if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
12782 if (p.exp)
12783 slotName = p.exp;
12784 }
12785 else {
12786 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
12787 p.arg.content = camelize(p.arg.content);
12788 }
12789 nonNameProps.push(p);
12790 }
12791 }
12792 }
12793 if (nonNameProps.length > 0) {
12794 const { props, directives } = buildProps(node, context, nonNameProps);
12795 slotProps = props;
12796 if (directives.length) {
12797 context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
12798 }
12799 }
12800 return {
12801 slotName,
12802 slotProps
12803 };
12804 }
12805
12806 const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
12807 const transformOn = (dir, node, context, augmentor) => {
12808 const { loc, modifiers, arg } = dir;
12809 if (!dir.exp && !modifiers.length) {
12810 context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
12811 }
12812 let eventName;
12813 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12814 if (arg.isStatic) {
12815 const rawName = arg.content;
12816 // for all event listeners, auto convert it to camelCase. See issue #2249
12817 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
12818 }
12819 else {
12820 // #2388
12821 eventName = createCompoundExpression([
12822 `${context.helperString(TO_HANDLER_KEY)}(`,
12823 arg,
12824 `)`
12825 ]);
12826 }
12827 }
12828 else {
12829 // already a compound expression.
12830 eventName = arg;
12831 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
12832 eventName.children.push(`)`);
12833 }
12834 // handler processing
12835 let exp = dir.exp;
12836 if (exp && !exp.content.trim()) {
12837 exp = undefined;
12838 }
12839 let shouldCache = context.cacheHandlers && !exp;
12840 if (exp) {
12841 const isMemberExp = isMemberExpression(exp.content);
12842 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
12843 const hasMultipleStatements = exp.content.includes(`;`);
12844 {
12845 validateBrowserExpression(exp, context, false, hasMultipleStatements);
12846 }
12847 if (isInlineStatement || (shouldCache && isMemberExp)) {
12848 // wrap inline statement in a function expression
12849 exp = createCompoundExpression([
12850 `${isInlineStatement
12851 ? `$event`
12852 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
12853 exp,
12854 hasMultipleStatements ? `}` : `)`
12855 ]);
12856 }
12857 }
12858 let ret = {
12859 props: [
12860 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
12861 ]
12862 };
12863 // apply extended compiler augmentor
12864 if (augmentor) {
12865 ret = augmentor(ret);
12866 }
12867 if (shouldCache) {
12868 // cache handlers so that it's always the same handler being passed down.
12869 // this avoids unnecessary re-renders when users use inline handlers on
12870 // components.
12871 ret.props[0].value = context.cache(ret.props[0].value);
12872 }
12873 return ret;
12874 };
12875
12876 // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
12877 // codegen for the entire props object. This transform here is only for v-bind
12878 // *with* args.
12879 const transformBind = (dir, node, context) => {
12880 const { exp, modifiers, loc } = dir;
12881 const arg = dir.arg;
12882 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
12883 arg.children.unshift(`(`);
12884 arg.children.push(`) || ""`);
12885 }
12886 else if (!arg.isStatic) {
12887 arg.content = `${arg.content} || ""`;
12888 }
12889 // .prop is no longer necessary due to new patch behavior
12890 // .sync is replaced by v-model:arg
12891 if (modifiers.includes('camel')) {
12892 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
12893 if (arg.isStatic) {
12894 arg.content = camelize(arg.content);
12895 }
12896 else {
12897 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
12898 }
12899 }
12900 else {
12901 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
12902 arg.children.push(`)`);
12903 }
12904 }
12905 if (!exp ||
12906 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
12907 context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
12908 return {
12909 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
12910 };
12911 }
12912 return {
12913 props: [createObjectProperty(arg, exp)]
12914 };
12915 };
12916
12917 // Merge adjacent text nodes and expressions into a single expression
12918 // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
12919 const transformText = (node, context) => {
12920 if (node.type === 0 /* ROOT */ ||
12921 node.type === 1 /* ELEMENT */ ||
12922 node.type === 11 /* FOR */ ||
12923 node.type === 10 /* IF_BRANCH */) {
12924 // perform the transform on node exit so that all expressions have already
12925 // been processed.
12926 return () => {
12927 const children = node.children;
12928 let currentContainer = undefined;
12929 let hasText = false;
12930 for (let i = 0; i < children.length; i++) {
12931 const child = children[i];
12932 if (isText(child)) {
12933 hasText = true;
12934 for (let j = i + 1; j < children.length; j++) {
12935 const next = children[j];
12936 if (isText(next)) {
12937 if (!currentContainer) {
12938 currentContainer = children[i] = {
12939 type: 8 /* COMPOUND_EXPRESSION */,
12940 loc: child.loc,
12941 children: [child]
12942 };
12943 }
12944 // merge adjacent text node into current
12945 currentContainer.children.push(` + `, next);
12946 children.splice(j, 1);
12947 j--;
12948 }
12949 else {
12950 currentContainer = undefined;
12951 break;
12952 }
12953 }
12954 }
12955 }
12956 if (!hasText ||
12957 // if this is a plain element with a single text child, leave it
12958 // as-is since the runtime has dedicated fast path for this by directly
12959 // setting textContent of the element.
12960 // for component root it's always normalized anyway.
12961 (children.length === 1 &&
12962 (node.type === 0 /* ROOT */ ||
12963 (node.type === 1 /* ELEMENT */ &&
12964 node.tagType === 0 /* ELEMENT */)))) {
12965 return;
12966 }
12967 // pre-convert text nodes into createTextVNode(text) calls to avoid
12968 // runtime normalization.
12969 for (let i = 0; i < children.length; i++) {
12970 const child = children[i];
12971 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
12972 const callArgs = [];
12973 // createTextVNode defaults to single whitespace, so if it is a
12974 // single space the code could be an empty call to save bytes.
12975 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
12976 callArgs.push(child);
12977 }
12978 // mark dynamic text with flag so it gets patched inside a block
12979 if (!context.ssr &&
12980 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
12981 callArgs.push(1 /* TEXT */ +
12982 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
12983 }
12984 children[i] = {
12985 type: 12 /* TEXT_CALL */,
12986 content: child,
12987 loc: child.loc,
12988 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
12989 };
12990 }
12991 }
12992 };
12993 }
12994 };
12995
12996 const seen = new WeakSet();
12997 const transformOnce = (node, context) => {
12998 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
12999 if (seen.has(node)) {
13000 return;
13001 }
13002 seen.add(node);
13003 context.helper(SET_BLOCK_TRACKING);
13004 return () => {
13005 const cur = context.currentNode;
13006 if (cur.codegenNode) {
13007 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
13008 }
13009 };
13010 }
13011 };
13012
13013 const transformModel = (dir, node, context) => {
13014 const { exp, arg } = dir;
13015 if (!exp) {
13016 context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
13017 return createTransformProps();
13018 }
13019 const rawExp = exp.loc.source;
13020 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
13021 // im SFC <script setup> inline mode, the exp may have been transformed into
13022 // _unref(exp)
13023 context.bindingMetadata[rawExp];
13024 const maybeRef = !true /* SETUP_CONST */;
13025 if (!isMemberExpression(expString) && !maybeRef) {
13026 context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
13027 return createTransformProps();
13028 }
13029 const propName = arg ? arg : createSimpleExpression('modelValue', true);
13030 const eventName = arg
13031 ? isStaticExp(arg)
13032 ? `onUpdate:${arg.content}`
13033 : createCompoundExpression(['"onUpdate:" + ', arg])
13034 : `onUpdate:modelValue`;
13035 let assignmentExp;
13036 const eventArg = context.isTS ? `($event: any)` : `$event`;
13037 {
13038 assignmentExp = createCompoundExpression([
13039 `${eventArg} => (`,
13040 exp,
13041 ` = $event)`
13042 ]);
13043 }
13044 const props = [
13045 // modelValue: foo
13046 createObjectProperty(propName, dir.exp),
13047 // "onUpdate:modelValue": $event => (foo = $event)
13048 createObjectProperty(eventName, assignmentExp)
13049 ];
13050 // modelModifiers: { foo: true, "bar-baz": true }
13051 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
13052 const modifiers = dir.modifiers
13053 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
13054 .join(`, `);
13055 const modifiersKey = arg
13056 ? isStaticExp(arg)
13057 ? `${arg.content}Modifiers`
13058 : createCompoundExpression([arg, ' + "Modifiers"'])
13059 : `modelModifiers`;
13060 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
13061 }
13062 return createTransformProps(props);
13063 };
13064 function createTransformProps(props = []) {
13065 return { props };
13066 }
13067
13068 function getBaseTransformPreset(prefixIdentifiers) {
13069 return [
13070 [
13071 transformOnce,
13072 transformIf,
13073 transformFor,
13074 ...([transformExpression]
13075 ),
13076 transformSlotOutlet,
13077 transformElement,
13078 trackSlotScopes,
13079 transformText
13080 ],
13081 {
13082 on: transformOn,
13083 bind: transformBind,
13084 model: transformModel
13085 }
13086 ];
13087 }
13088 // we name it `baseCompile` so that higher order compilers like
13089 // @vue/compiler-dom can export `compile` while re-exporting everything else.
13090 function baseCompile(template, options = {}) {
13091 const onError = options.onError || defaultOnError;
13092 const isModuleMode = options.mode === 'module';
13093 /* istanbul ignore if */
13094 {
13095 if (options.prefixIdentifiers === true) {
13096 onError(createCompilerError(45 /* X_PREFIX_ID_NOT_SUPPORTED */));
13097 }
13098 else if (isModuleMode) {
13099 onError(createCompilerError(46 /* X_MODULE_MODE_NOT_SUPPORTED */));
13100 }
13101 }
13102 const prefixIdentifiers = !true ;
13103 if (options.cacheHandlers) {
13104 onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
13105 }
13106 if (options.scopeId && !isModuleMode) {
13107 onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
13108 }
13109 const ast = isString(template) ? baseParse(template, options) : template;
13110 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
13111 transform(ast, extend({}, options, {
13112 prefixIdentifiers,
13113 nodeTransforms: [
13114 ...nodeTransforms,
13115 ...(options.nodeTransforms || []) // user transforms
13116 ],
13117 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
13118 )
13119 }));
13120 return generate(ast, extend({}, options, {
13121 prefixIdentifiers
13122 }));
13123 }
13124
13125 const noopDirectiveTransform = () => ({ props: [] });
13126
13127 const V_MODEL_RADIO = Symbol(`vModelRadio` );
13128 const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
13129 const V_MODEL_TEXT = Symbol(`vModelText` );
13130 const V_MODEL_SELECT = Symbol(`vModelSelect` );
13131 const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
13132 const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
13133 const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
13134 const V_SHOW = Symbol(`vShow` );
13135 const TRANSITION$1 = Symbol(`Transition` );
13136 const TRANSITION_GROUP = Symbol(`TransitionGroup` );
13137 registerRuntimeHelpers({
13138 [V_MODEL_RADIO]: `vModelRadio`,
13139 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
13140 [V_MODEL_TEXT]: `vModelText`,
13141 [V_MODEL_SELECT]: `vModelSelect`,
13142 [V_MODEL_DYNAMIC]: `vModelDynamic`,
13143 [V_ON_WITH_MODIFIERS]: `withModifiers`,
13144 [V_ON_WITH_KEYS]: `withKeys`,
13145 [V_SHOW]: `vShow`,
13146 [TRANSITION$1]: `Transition`,
13147 [TRANSITION_GROUP]: `TransitionGroup`
13148 });
13149
13150 /* eslint-disable no-restricted-globals */
13151 let decoder;
13152 function decodeHtmlBrowser(raw) {
13153 (decoder || (decoder = document.createElement('div'))).innerHTML = raw;
13154 return decoder.textContent;
13155 }
13156
13157 const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
13158 const parserOptions = {
13159 isVoidTag,
13160 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
13161 isPreTag: tag => tag === 'pre',
13162 decodeEntities: decodeHtmlBrowser ,
13163 isBuiltInComponent: (tag) => {
13164 if (isBuiltInType(tag, `Transition`)) {
13165 return TRANSITION$1;
13166 }
13167 else if (isBuiltInType(tag, `TransitionGroup`)) {
13168 return TRANSITION_GROUP;
13169 }
13170 },
13171 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
13172 getNamespace(tag, parent) {
13173 let ns = parent ? parent.ns : 0 /* HTML */;
13174 if (parent && ns === 2 /* MATH_ML */) {
13175 if (parent.tag === 'annotation-xml') {
13176 if (tag === 'svg') {
13177 return 1 /* SVG */;
13178 }
13179 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
13180 a.name === 'encoding' &&
13181 a.value != null &&
13182 (a.value.content === 'text/html' ||
13183 a.value.content === 'application/xhtml+xml'))) {
13184 ns = 0 /* HTML */;
13185 }
13186 }
13187 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
13188 tag !== 'mglyph' &&
13189 tag !== 'malignmark') {
13190 ns = 0 /* HTML */;
13191 }
13192 }
13193 else if (parent && ns === 1 /* SVG */) {
13194 if (parent.tag === 'foreignObject' ||
13195 parent.tag === 'desc' ||
13196 parent.tag === 'title') {
13197 ns = 0 /* HTML */;
13198 }
13199 }
13200 if (ns === 0 /* HTML */) {
13201 if (tag === 'svg') {
13202 return 1 /* SVG */;
13203 }
13204 if (tag === 'math') {
13205 return 2 /* MATH_ML */;
13206 }
13207 }
13208 return ns;
13209 },
13210 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
13211 getTextMode({ tag, ns }) {
13212 if (ns === 0 /* HTML */) {
13213 if (tag === 'textarea' || tag === 'title') {
13214 return 1 /* RCDATA */;
13215 }
13216 if (isRawTextContainer(tag)) {
13217 return 2 /* RAWTEXT */;
13218 }
13219 }
13220 return 0 /* DATA */;
13221 }
13222 };
13223
13224 // Parse inline CSS strings for static style attributes into an object.
13225 // This is a NodeTransform since it works on the static `style` attribute and
13226 // converts it into a dynamic equivalent:
13227 // style="color: red" -> :style='{ "color": "red" }'
13228 // It is then processed by `transformElement` and included in the generated
13229 // props.
13230 const transformStyle = node => {
13231 if (node.type === 1 /* ELEMENT */) {
13232 node.props.forEach((p, i) => {
13233 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
13234 // replace p with an expression node
13235 node.props[i] = {
13236 type: 7 /* DIRECTIVE */,
13237 name: `bind`,
13238 arg: createSimpleExpression(`style`, true, p.loc),
13239 exp: parseInlineCSS(p.value.content, p.loc),
13240 modifiers: [],
13241 loc: p.loc
13242 };
13243 }
13244 });
13245 }
13246 };
13247 const parseInlineCSS = (cssText, loc) => {
13248 const normalized = parseStringStyle(cssText);
13249 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
13250 };
13251
13252 function createDOMCompilerError(code, loc) {
13253 return createCompilerError(code, loc, DOMErrorMessages );
13254 }
13255 const DOMErrorMessages = {
13256 [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
13257 [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
13258 [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
13259 [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
13260 [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
13261 [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
13262 [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.`,
13263 [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
13264 [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
13265 [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
13266 [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
13267 };
13268
13269 const transformVHtml = (dir, node, context) => {
13270 const { exp, loc } = dir;
13271 if (!exp) {
13272 context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
13273 }
13274 if (node.children.length) {
13275 context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
13276 node.children.length = 0;
13277 }
13278 return {
13279 props: [
13280 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
13281 ]
13282 };
13283 };
13284
13285 const transformVText = (dir, node, context) => {
13286 const { exp, loc } = dir;
13287 if (!exp) {
13288 context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
13289 }
13290 if (node.children.length) {
13291 context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
13292 node.children.length = 0;
13293 }
13294 return {
13295 props: [
13296 createObjectProperty(createSimpleExpression(`textContent`, true), exp
13297 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
13298 : createSimpleExpression('', true))
13299 ]
13300 };
13301 };
13302
13303 const transformModel$1 = (dir, node, context) => {
13304 const baseResult = transformModel(dir, node, context);
13305 // base transform has errors OR component v-model (only need props)
13306 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
13307 return baseResult;
13308 }
13309 if (dir.arg) {
13310 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
13311 }
13312 function checkDuplicatedValue() {
13313 const value = findProp(node, 'value');
13314 if (value) {
13315 context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
13316 }
13317 }
13318 const { tag } = node;
13319 const isCustomElement = context.isCustomElement(tag);
13320 if (tag === 'input' ||
13321 tag === 'textarea' ||
13322 tag === 'select' ||
13323 isCustomElement) {
13324 let directiveToUse = V_MODEL_TEXT;
13325 let isInvalidType = false;
13326 if (tag === 'input' || isCustomElement) {
13327 const type = findProp(node, `type`);
13328 if (type) {
13329 if (type.type === 7 /* DIRECTIVE */) {
13330 // :type="foo"
13331 directiveToUse = V_MODEL_DYNAMIC;
13332 }
13333 else if (type.value) {
13334 switch (type.value.content) {
13335 case 'radio':
13336 directiveToUse = V_MODEL_RADIO;
13337 break;
13338 case 'checkbox':
13339 directiveToUse = V_MODEL_CHECKBOX;
13340 break;
13341 case 'file':
13342 isInvalidType = true;
13343 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
13344 break;
13345 default:
13346 // text type
13347 checkDuplicatedValue();
13348 break;
13349 }
13350 }
13351 }
13352 else if (hasDynamicKeyVBind(node)) {
13353 // element has bindings with dynamic keys, which can possibly contain
13354 // "type".
13355 directiveToUse = V_MODEL_DYNAMIC;
13356 }
13357 else {
13358 // text type
13359 checkDuplicatedValue();
13360 }
13361 }
13362 else if (tag === 'select') {
13363 directiveToUse = V_MODEL_SELECT;
13364 }
13365 else {
13366 // textarea
13367 checkDuplicatedValue();
13368 }
13369 // inject runtime directive
13370 // by returning the helper symbol via needRuntime
13371 // the import will replaced a resolveDirective call.
13372 if (!isInvalidType) {
13373 baseResult.needRuntime = context.helper(directiveToUse);
13374 }
13375 }
13376 else {
13377 context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
13378 }
13379 // native vmodel doesn't need the `modelValue` props since they are also
13380 // passed to the runtime as `binding.value`. removing it reduces code size.
13381 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
13382 p.key.content === 'modelValue'));
13383 return baseResult;
13384 };
13385
13386 const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
13387 const isNonKeyModifier = /*#__PURE__*/ makeMap(
13388 // event propagation management
13389`stop,prevent,self,` +
13390 // system modifiers + exact
13391 `ctrl,shift,alt,meta,exact,` +
13392 // mouse
13393 `middle`);
13394 // left & right could be mouse or key modifiers based on event type
13395 const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
13396 const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
13397 const resolveModifiers = (key, modifiers) => {
13398 const keyModifiers = [];
13399 const nonKeyModifiers = [];
13400 const eventOptionModifiers = [];
13401 for (let i = 0; i < modifiers.length; i++) {
13402 const modifier = modifiers[i];
13403 if (isEventOptionModifier(modifier)) {
13404 // eventOptionModifiers: modifiers for addEventListener() options,
13405 // e.g. .passive & .capture
13406 eventOptionModifiers.push(modifier);
13407 }
13408 else {
13409 // runtimeModifiers: modifiers that needs runtime guards
13410 if (maybeKeyModifier(modifier)) {
13411 if (isStaticExp(key)) {
13412 if (isKeyboardEvent(key.content)) {
13413 keyModifiers.push(modifier);
13414 }
13415 else {
13416 nonKeyModifiers.push(modifier);
13417 }
13418 }
13419 else {
13420 keyModifiers.push(modifier);
13421 nonKeyModifiers.push(modifier);
13422 }
13423 }
13424 else {
13425 if (isNonKeyModifier(modifier)) {
13426 nonKeyModifiers.push(modifier);
13427 }
13428 else {
13429 keyModifiers.push(modifier);
13430 }
13431 }
13432 }
13433 }
13434 return {
13435 keyModifiers,
13436 nonKeyModifiers,
13437 eventOptionModifiers
13438 };
13439 };
13440 const transformClick = (key, event) => {
13441 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
13442 return isStaticClick
13443 ? createSimpleExpression(event, true)
13444 : key.type !== 4 /* SIMPLE_EXPRESSION */
13445 ? createCompoundExpression([
13446 `(`,
13447 key,
13448 `) === "onClick" ? "${event}" : (`,
13449 key,
13450 `)`
13451 ])
13452 : key;
13453 };
13454 const transformOn$1 = (dir, node, context) => {
13455 return transformOn(dir, node, context, baseResult => {
13456 const { modifiers } = dir;
13457 if (!modifiers.length)
13458 return baseResult;
13459 let { key, value: handlerExp } = baseResult.props[0];
13460 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers);
13461 // normalize click.right and click.middle since they don't actually fire
13462 if (nonKeyModifiers.includes('right')) {
13463 key = transformClick(key, `onContextmenu`);
13464 }
13465 if (nonKeyModifiers.includes('middle')) {
13466 key = transformClick(key, `onMouseup`);
13467 }
13468 if (nonKeyModifiers.length) {
13469 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
13470 handlerExp,
13471 JSON.stringify(nonKeyModifiers)
13472 ]);
13473 }
13474 if (keyModifiers.length &&
13475 // if event name is dynamic, always wrap with keys guard
13476 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
13477 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
13478 handlerExp,
13479 JSON.stringify(keyModifiers)
13480 ]);
13481 }
13482 if (eventOptionModifiers.length) {
13483 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
13484 key = isStaticExp(key)
13485 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
13486 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
13487 }
13488 return {
13489 props: [createObjectProperty(key, handlerExp)]
13490 };
13491 });
13492 };
13493
13494 const transformShow = (dir, node, context) => {
13495 const { exp, loc } = dir;
13496 if (!exp) {
13497 context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
13498 }
13499 return {
13500 props: [],
13501 needRuntime: context.helper(V_SHOW)
13502 };
13503 };
13504
13505 const warnTransitionChildren = (node, context) => {
13506 if (node.type === 1 /* ELEMENT */ &&
13507 node.tagType === 1 /* COMPONENT */) {
13508 const component = context.isBuiltInComponent(node.tag);
13509 if (component === TRANSITION$1) {
13510 return () => {
13511 if (node.children.length && hasMultipleChildren(node)) {
13512 context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
13513 start: node.children[0].loc.start,
13514 end: node.children[node.children.length - 1].loc.end,
13515 source: ''
13516 }));
13517 }
13518 };
13519 }
13520 }
13521 };
13522 function hasMultipleChildren(node) {
13523 // #1352 filter out potential comment nodes.
13524 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
13525 const child = children[0];
13526 return (children.length !== 1 ||
13527 child.type === 11 /* FOR */ ||
13528 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
13529 }
13530
13531 const ignoreSideEffectTags = (node, context) => {
13532 if (node.type === 1 /* ELEMENT */ &&
13533 node.tagType === 0 /* ELEMENT */ &&
13534 (node.tag === 'script' || node.tag === 'style')) {
13535 context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
13536 context.removeNode();
13537 }
13538 };
13539
13540 const DOMNodeTransforms = [
13541 transformStyle,
13542 ...([warnTransitionChildren] )
13543 ];
13544 const DOMDirectiveTransforms = {
13545 cloak: noopDirectiveTransform,
13546 html: transformVHtml,
13547 text: transformVText,
13548 model: transformModel$1,
13549 on: transformOn$1,
13550 show: transformShow
13551 };
13552 function compile$1(template, options = {}) {
13553 return baseCompile(template, extend({}, parserOptions, options, {
13554 nodeTransforms: [
13555 // ignore <script> and <tag>
13556 // this is not put inside DOMNodeTransforms because that list is used
13557 // by compiler-ssr to generate vnode fallback branches
13558 ignoreSideEffectTags,
13559 ...DOMNodeTransforms,
13560 ...(options.nodeTransforms || [])
13561 ],
13562 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
13563 transformHoist: null
13564 }));
13565 }
13566
13567 // This entry is the "full-build" that includes both the runtime
13568 {
13569 initDev();
13570 }
13571 const compileCache = Object.create(null);
13572 function compileToFunction(template, options) {
13573 if (!isString(template)) {
13574 if (template.nodeType) {
13575 template = template.innerHTML;
13576 }
13577 else {
13578 warn(`invalid template option: `, template);
13579 return NOOP;
13580 }
13581 }
13582 const key = template;
13583 const cached = compileCache[key];
13584 if (cached) {
13585 return cached;
13586 }
13587 if (template[0] === '#') {
13588 const el = document.querySelector(template);
13589 if (!el) {
13590 warn(`Template element not found or is empty: ${template}`);
13591 }
13592 // __UNSAFE__
13593 // Reason: potential execution of JS expressions in in-DOM template.
13594 // The user must make sure the in-DOM template is trusted. If it's rendered
13595 // by the server, the template should not contain any user data.
13596 template = el ? el.innerHTML : ``;
13597 }
13598 const { code } = compile$1(template, extend({
13599 hoistStatic: true,
13600 onError(err) {
13601 {
13602 const message = `Template compilation error: ${err.message}`;
13603 const codeFrame = err.loc &&
13604 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
13605 warn(codeFrame ? `${message}\n${codeFrame}` : message);
13606 }
13607 }
13608 }, options));
13609 // The wildcard import results in a huge object with every export
13610 // with keys that cannot be mangled, and can be quite heavy size-wise.
13611 // In the global build we know `Vue` is available globally so we can avoid
13612 // the wildcard object.
13613 const render = (new Function(code)()
13614 );
13615 render._rc = true;
13616 return (compileCache[key] = render);
13617 }
13618 registerRuntimeCompiler(compileToFunction);
13619
13620 exports.BaseTransition = BaseTransition;
13621 exports.Comment = Comment;
13622 exports.Fragment = Fragment;
13623 exports.KeepAlive = KeepAlive;
13624 exports.Static = Static;
13625 exports.Suspense = Suspense;
13626 exports.Teleport = Teleport;
13627 exports.Text = Text;
13628 exports.Transition = Transition;
13629 exports.TransitionGroup = TransitionGroup;
13630 exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling;
13631 exports.callWithErrorHandling = callWithErrorHandling;
13632 exports.camelize = camelize;
13633 exports.capitalize = capitalize;
13634 exports.cloneVNode = cloneVNode;
13635 exports.compile = compileToFunction;
13636 exports.computed = computed$1;
13637 exports.createApp = createApp;
13638 exports.createBlock = createBlock;
13639 exports.createCommentVNode = createCommentVNode;
13640 exports.createHydrationRenderer = createHydrationRenderer;
13641 exports.createRenderer = createRenderer;
13642 exports.createSSRApp = createSSRApp;
13643 exports.createSlots = createSlots;
13644 exports.createStaticVNode = createStaticVNode;
13645 exports.createTextVNode = createTextVNode;
13646 exports.createVNode = createVNode;
13647 exports.customRef = customRef;
13648 exports.defineAsyncComponent = defineAsyncComponent;
13649 exports.defineComponent = defineComponent;
13650 exports.defineEmit = defineEmit;
13651 exports.defineProps = defineProps;
13652 exports.getCurrentInstance = getCurrentInstance;
13653 exports.getTransitionRawChildren = getTransitionRawChildren;
13654 exports.h = h;
13655 exports.handleError = handleError;
13656 exports.hydrate = hydrate;
13657 exports.initCustomFormatter = initCustomFormatter;
13658 exports.inject = inject;
13659 exports.isProxy = isProxy;
13660 exports.isReactive = isReactive;
13661 exports.isReadonly = isReadonly;
13662 exports.isRef = isRef;
13663 exports.isRuntimeOnly = isRuntimeOnly;
13664 exports.isVNode = isVNode;
13665 exports.markRaw = markRaw;
13666 exports.mergeProps = mergeProps;
13667 exports.nextTick = nextTick;
13668 exports.onActivated = onActivated;
13669 exports.onBeforeMount = onBeforeMount;
13670 exports.onBeforeUnmount = onBeforeUnmount;
13671 exports.onBeforeUpdate = onBeforeUpdate;
13672 exports.onDeactivated = onDeactivated;
13673 exports.onErrorCaptured = onErrorCaptured;
13674 exports.onMounted = onMounted;
13675 exports.onRenderTracked = onRenderTracked;
13676 exports.onRenderTriggered = onRenderTriggered;
13677 exports.onUnmounted = onUnmounted;
13678 exports.onUpdated = onUpdated;
13679 exports.openBlock = openBlock;
13680 exports.popScopeId = popScopeId;
13681 exports.provide = provide;
13682 exports.proxyRefs = proxyRefs;
13683 exports.pushScopeId = pushScopeId;
13684 exports.queuePostFlushCb = queuePostFlushCb;
13685 exports.reactive = reactive;
13686 exports.readonly = readonly;
13687 exports.ref = ref;
13688 exports.registerRuntimeCompiler = registerRuntimeCompiler;
13689 exports.render = render;
13690 exports.renderList = renderList;
13691 exports.renderSlot = renderSlot;
13692 exports.resolveComponent = resolveComponent;
13693 exports.resolveDirective = resolveDirective;
13694 exports.resolveDynamicComponent = resolveDynamicComponent;
13695 exports.resolveTransitionHooks = resolveTransitionHooks;
13696 exports.setBlockTracking = setBlockTracking;
13697 exports.setDevtoolsHook = setDevtoolsHook;
13698 exports.setTransitionHooks = setTransitionHooks;
13699 exports.shallowReactive = shallowReactive;
13700 exports.shallowReadonly = shallowReadonly;
13701 exports.shallowRef = shallowRef;
13702 exports.ssrContextKey = ssrContextKey;
13703 exports.ssrUtils = ssrUtils;
13704 exports.toDisplayString = toDisplayString;
13705 exports.toHandlerKey = toHandlerKey;
13706 exports.toHandlers = toHandlers;
13707 exports.toRaw = toRaw;
13708 exports.toRef = toRef;
13709 exports.toRefs = toRefs;
13710 exports.transformVNodeArgs = transformVNodeArgs;
13711 exports.triggerRef = triggerRef;
13712 exports.unref = unref;
13713 exports.useContext = useContext;
13714 exports.useCssModule = useCssModule;
13715 exports.useCssVars = useCssVars;
13716 exports.useSSRContext = useSSRContext;
13717 exports.useTransitionState = useTransitionState;
13718 exports.vModelCheckbox = vModelCheckbox;
13719 exports.vModelDynamic = vModelDynamic;
13720 exports.vModelRadio = vModelRadio;
13721 exports.vModelSelect = vModelSelect;
13722 exports.vModelText = vModelText;
13723 exports.vShow = vShow;
13724 exports.version = version;
13725 exports.warn = warn;
13726 exports.watch = watch;
13727 exports.watchEffect = watchEffect;
13728 exports.withCtx = withCtx;
13729 exports.withDirectives = withDirectives;
13730 exports.withKeys = withKeys;
13731 exports.withModifiers = withModifiers;
13732 exports.withScopeId = withScopeId;
13733
13734 Object.defineProperty(exports, '__esModule', { value: true });
13735
13736 return exports;
13737
13738}({}));