UNPKG

589 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 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 ===
606 (isReadonly
607 ? shallow
608 ? shallowReadonlyMap
609 : readonlyMap
610 : shallow
611 ? shallowReactiveMap
612 : reactiveMap).get(target)) {
613 return target;
614 }
615 const targetIsArray = isArray(target);
616 if (!isReadonly && targetIsArray && hasOwn(arrayInstrumentations, key)) {
617 return Reflect.get(arrayInstrumentations, key, receiver);
618 }
619 const res = Reflect.get(target, key, receiver);
620 if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) {
621 return res;
622 }
623 if (!isReadonly) {
624 track(target, "get" /* GET */, key);
625 }
626 if (shallow) {
627 return res;
628 }
629 if (isRef(res)) {
630 // ref unwrapping - does not apply for Array + integer key.
631 const shouldUnwrap = !targetIsArray || !isIntegerKey(key);
632 return shouldUnwrap ? res.value : res;
633 }
634 if (isObject(res)) {
635 // Convert returned value into a proxy as well. we do the isObject check
636 // here to avoid invalid value warning. Also need to lazy access readonly
637 // and reactive here to avoid circular dependency.
638 return isReadonly ? readonly(res) : reactive(res);
639 }
640 return res;
641 };
642 }
643 const set = /*#__PURE__*/ createSetter();
644 const shallowSet = /*#__PURE__*/ createSetter(true);
645 function createSetter(shallow = false) {
646 return function set(target, key, value, receiver) {
647 let oldValue = target[key];
648 if (!shallow) {
649 value = toRaw(value);
650 oldValue = toRaw(oldValue);
651 if (!isArray(target) && isRef(oldValue) && !isRef(value)) {
652 oldValue.value = value;
653 return true;
654 }
655 }
656 const hadKey = isArray(target) && isIntegerKey(key)
657 ? Number(key) < target.length
658 : hasOwn(target, key);
659 const result = Reflect.set(target, key, value, receiver);
660 // don't trigger if target is something up in the prototype chain of original
661 if (target === toRaw(receiver)) {
662 if (!hadKey) {
663 trigger(target, "add" /* ADD */, key, value);
664 }
665 else if (hasChanged(value, oldValue)) {
666 trigger(target, "set" /* SET */, key, value, oldValue);
667 }
668 }
669 return result;
670 };
671 }
672 function deleteProperty(target, key) {
673 const hadKey = hasOwn(target, key);
674 const oldValue = target[key];
675 const result = Reflect.deleteProperty(target, key);
676 if (result && hadKey) {
677 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
678 }
679 return result;
680 }
681 function has(target, key) {
682 const result = Reflect.has(target, key);
683 if (!isSymbol(key) || !builtInSymbols.has(key)) {
684 track(target, "has" /* HAS */, key);
685 }
686 return result;
687 }
688 function ownKeys(target) {
689 track(target, "iterate" /* ITERATE */, isArray(target) ? 'length' : ITERATE_KEY);
690 return Reflect.ownKeys(target);
691 }
692 const mutableHandlers = {
693 get,
694 set,
695 deleteProperty,
696 has,
697 ownKeys
698 };
699 const readonlyHandlers = {
700 get: readonlyGet,
701 set(target, key) {
702 {
703 console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target);
704 }
705 return true;
706 },
707 deleteProperty(target, key) {
708 {
709 console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target);
710 }
711 return true;
712 }
713 };
714 const shallowReactiveHandlers = extend({}, mutableHandlers, {
715 get: shallowGet,
716 set: shallowSet
717 });
718 // Props handlers are special in the sense that it should not unwrap top-level
719 // refs (in order to allow refs to be explicitly passed down), but should
720 // retain the reactivity of the normal readonly object.
721 const shallowReadonlyHandlers = extend({}, readonlyHandlers, {
722 get: shallowReadonlyGet
723 });
724
725 const toReactive = (value) => isObject(value) ? reactive(value) : value;
726 const toReadonly = (value) => isObject(value) ? readonly(value) : value;
727 const toShallow = (value) => value;
728 const getProto = (v) => Reflect.getPrototypeOf(v);
729 function get$1(target, key, isReadonly = false, isShallow = false) {
730 // #1772: readonly(reactive(Map)) should return readonly + reactive version
731 // of the value
732 target = target["__v_raw" /* RAW */];
733 const rawTarget = toRaw(target);
734 const rawKey = toRaw(key);
735 if (key !== rawKey) {
736 !isReadonly && track(rawTarget, "get" /* GET */, key);
737 }
738 !isReadonly && track(rawTarget, "get" /* GET */, rawKey);
739 const { has } = getProto(rawTarget);
740 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
741 if (has.call(rawTarget, key)) {
742 return wrap(target.get(key));
743 }
744 else if (has.call(rawTarget, rawKey)) {
745 return wrap(target.get(rawKey));
746 }
747 else if (target !== rawTarget) {
748 // #3602 readonly(reactive(Map))
749 // ensure that the nested reactive `Map` can do tracking for itself
750 target.get(key);
751 }
752 }
753 function has$1(key, isReadonly = false) {
754 const target = this["__v_raw" /* RAW */];
755 const rawTarget = toRaw(target);
756 const rawKey = toRaw(key);
757 if (key !== rawKey) {
758 !isReadonly && track(rawTarget, "has" /* HAS */, key);
759 }
760 !isReadonly && track(rawTarget, "has" /* HAS */, rawKey);
761 return key === rawKey
762 ? target.has(key)
763 : target.has(key) || target.has(rawKey);
764 }
765 function size(target, isReadonly = false) {
766 target = target["__v_raw" /* RAW */];
767 !isReadonly && track(toRaw(target), "iterate" /* ITERATE */, ITERATE_KEY);
768 return Reflect.get(target, 'size', target);
769 }
770 function add(value) {
771 value = toRaw(value);
772 const target = toRaw(this);
773 const proto = getProto(target);
774 const hadKey = proto.has.call(target, value);
775 if (!hadKey) {
776 target.add(value);
777 trigger(target, "add" /* ADD */, value, value);
778 }
779 return this;
780 }
781 function set$1(key, value) {
782 value = toRaw(value);
783 const target = toRaw(this);
784 const { has, get } = getProto(target);
785 let hadKey = has.call(target, key);
786 if (!hadKey) {
787 key = toRaw(key);
788 hadKey = has.call(target, key);
789 }
790 else {
791 checkIdentityKeys(target, has, key);
792 }
793 const oldValue = get.call(target, key);
794 target.set(key, value);
795 if (!hadKey) {
796 trigger(target, "add" /* ADD */, key, value);
797 }
798 else if (hasChanged(value, oldValue)) {
799 trigger(target, "set" /* SET */, key, value, oldValue);
800 }
801 return this;
802 }
803 function deleteEntry(key) {
804 const target = toRaw(this);
805 const { has, get } = getProto(target);
806 let hadKey = has.call(target, key);
807 if (!hadKey) {
808 key = toRaw(key);
809 hadKey = has.call(target, key);
810 }
811 else {
812 checkIdentityKeys(target, has, key);
813 }
814 const oldValue = get ? get.call(target, key) : undefined;
815 // forward the operation before queueing reactions
816 const result = target.delete(key);
817 if (hadKey) {
818 trigger(target, "delete" /* DELETE */, key, undefined, oldValue);
819 }
820 return result;
821 }
822 function clear() {
823 const target = toRaw(this);
824 const hadItems = target.size !== 0;
825 const oldTarget = isMap(target)
826 ? new Map(target)
827 : new Set(target)
828 ;
829 // forward the operation before queueing reactions
830 const result = target.clear();
831 if (hadItems) {
832 trigger(target, "clear" /* CLEAR */, undefined, undefined, oldTarget);
833 }
834 return result;
835 }
836 function createForEach(isReadonly, isShallow) {
837 return function forEach(callback, thisArg) {
838 const observed = this;
839 const target = observed["__v_raw" /* RAW */];
840 const rawTarget = toRaw(target);
841 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
842 !isReadonly && track(rawTarget, "iterate" /* ITERATE */, ITERATE_KEY);
843 return target.forEach((value, key) => {
844 // important: make sure the callback is
845 // 1. invoked with the reactive map as `this` and 3rd arg
846 // 2. the value received should be a corresponding reactive/readonly.
847 return callback.call(thisArg, wrap(value), wrap(key), observed);
848 });
849 };
850 }
851 function createIterableMethod(method, isReadonly, isShallow) {
852 return function (...args) {
853 const target = this["__v_raw" /* RAW */];
854 const rawTarget = toRaw(target);
855 const targetIsMap = isMap(rawTarget);
856 const isPair = method === 'entries' || (method === Symbol.iterator && targetIsMap);
857 const isKeyOnly = method === 'keys' && targetIsMap;
858 const innerIterator = target[method](...args);
859 const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive;
860 !isReadonly &&
861 track(rawTarget, "iterate" /* ITERATE */, isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY);
862 // return a wrapped iterator which returns observed versions of the
863 // values emitted from the real iterator
864 return {
865 // iterator protocol
866 next() {
867 const { value, done } = innerIterator.next();
868 return done
869 ? { value, done }
870 : {
871 value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value),
872 done
873 };
874 },
875 // iterable protocol
876 [Symbol.iterator]() {
877 return this;
878 }
879 };
880 };
881 }
882 function createReadonlyMethod(type) {
883 return function (...args) {
884 {
885 const key = args[0] ? `on key "${args[0]}" ` : ``;
886 console.warn(`${capitalize(type)} operation ${key}failed: target is readonly.`, toRaw(this));
887 }
888 return type === "delete" /* DELETE */ ? false : this;
889 };
890 }
891 const mutableInstrumentations = {
892 get(key) {
893 return get$1(this, key);
894 },
895 get size() {
896 return size(this);
897 },
898 has: has$1,
899 add,
900 set: set$1,
901 delete: deleteEntry,
902 clear,
903 forEach: createForEach(false, false)
904 };
905 const shallowInstrumentations = {
906 get(key) {
907 return get$1(this, key, false, true);
908 },
909 get size() {
910 return size(this);
911 },
912 has: has$1,
913 add,
914 set: set$1,
915 delete: deleteEntry,
916 clear,
917 forEach: createForEach(false, true)
918 };
919 const readonlyInstrumentations = {
920 get(key) {
921 return get$1(this, key, true);
922 },
923 get size() {
924 return size(this, true);
925 },
926 has(key) {
927 return has$1.call(this, key, true);
928 },
929 add: createReadonlyMethod("add" /* ADD */),
930 set: createReadonlyMethod("set" /* SET */),
931 delete: createReadonlyMethod("delete" /* DELETE */),
932 clear: createReadonlyMethod("clear" /* CLEAR */),
933 forEach: createForEach(true, false)
934 };
935 const shallowReadonlyInstrumentations = {
936 get(key) {
937 return get$1(this, key, true, true);
938 },
939 get size() {
940 return size(this, true);
941 },
942 has(key) {
943 return has$1.call(this, key, true);
944 },
945 add: createReadonlyMethod("add" /* ADD */),
946 set: createReadonlyMethod("set" /* SET */),
947 delete: createReadonlyMethod("delete" /* DELETE */),
948 clear: createReadonlyMethod("clear" /* CLEAR */),
949 forEach: createForEach(true, true)
950 };
951 const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator];
952 iteratorMethods.forEach(method => {
953 mutableInstrumentations[method] = createIterableMethod(method, false, false);
954 readonlyInstrumentations[method] = createIterableMethod(method, true, false);
955 shallowInstrumentations[method] = createIterableMethod(method, false, true);
956 shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true);
957 });
958 function createInstrumentationGetter(isReadonly, shallow) {
959 const instrumentations = shallow
960 ? isReadonly
961 ? shallowReadonlyInstrumentations
962 : shallowInstrumentations
963 : isReadonly
964 ? readonlyInstrumentations
965 : mutableInstrumentations;
966 return (target, key, receiver) => {
967 if (key === "__v_isReactive" /* IS_REACTIVE */) {
968 return !isReadonly;
969 }
970 else if (key === "__v_isReadonly" /* IS_READONLY */) {
971 return isReadonly;
972 }
973 else if (key === "__v_raw" /* RAW */) {
974 return target;
975 }
976 return Reflect.get(hasOwn(instrumentations, key) && key in target
977 ? instrumentations
978 : target, key, receiver);
979 };
980 }
981 const mutableCollectionHandlers = {
982 get: createInstrumentationGetter(false, false)
983 };
984 const shallowCollectionHandlers = {
985 get: createInstrumentationGetter(false, true)
986 };
987 const readonlyCollectionHandlers = {
988 get: createInstrumentationGetter(true, false)
989 };
990 const shallowReadonlyCollectionHandlers = {
991 get: createInstrumentationGetter(true, true)
992 };
993 function checkIdentityKeys(target, has, key) {
994 const rawKey = toRaw(key);
995 if (rawKey !== key && has.call(target, rawKey)) {
996 const type = toRawType(target);
997 console.warn(`Reactive ${type} contains both the raw and reactive ` +
998 `versions of the same object${type === `Map` ? ` as keys` : ``}, ` +
999 `which can lead to inconsistencies. ` +
1000 `Avoid differentiating between the raw and reactive versions ` +
1001 `of an object and only use the reactive version if possible.`);
1002 }
1003 }
1004
1005 const reactiveMap = new WeakMap();
1006 const shallowReactiveMap = new WeakMap();
1007 const readonlyMap = new WeakMap();
1008 const shallowReadonlyMap = new WeakMap();
1009 function targetTypeMap(rawType) {
1010 switch (rawType) {
1011 case 'Object':
1012 case 'Array':
1013 return 1 /* COMMON */;
1014 case 'Map':
1015 case 'Set':
1016 case 'WeakMap':
1017 case 'WeakSet':
1018 return 2 /* COLLECTION */;
1019 default:
1020 return 0 /* INVALID */;
1021 }
1022 }
1023 function getTargetType(value) {
1024 return value["__v_skip" /* SKIP */] || !Object.isExtensible(value)
1025 ? 0 /* INVALID */
1026 : targetTypeMap(toRawType(value));
1027 }
1028 function reactive(target) {
1029 // if trying to observe a readonly proxy, return the readonly version.
1030 if (target && target["__v_isReadonly" /* IS_READONLY */]) {
1031 return target;
1032 }
1033 return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap);
1034 }
1035 /**
1036 * Return a shallowly-reactive copy of the original object, where only the root
1037 * level properties are reactive. It also does not auto-unwrap refs (even at the
1038 * root level).
1039 */
1040 function shallowReactive(target) {
1041 return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap);
1042 }
1043 /**
1044 * Creates a readonly copy of the original object. Note the returned copy is not
1045 * made reactive, but `readonly` can be called on an already reactive object.
1046 */
1047 function readonly(target) {
1048 return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap);
1049 }
1050 /**
1051 * Returns a reactive-copy of the original object, where only the root level
1052 * properties are readonly, and does NOT unwrap refs nor recursively convert
1053 * returned properties.
1054 * This is used for creating the props proxy object for stateful components.
1055 */
1056 function shallowReadonly(target) {
1057 return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap);
1058 }
1059 function createReactiveObject(target, isReadonly, baseHandlers, collectionHandlers, proxyMap) {
1060 if (!isObject(target)) {
1061 {
1062 console.warn(`value cannot be made reactive: ${String(target)}`);
1063 }
1064 return target;
1065 }
1066 // target is already a Proxy, return it.
1067 // exception: calling readonly() on a reactive object
1068 if (target["__v_raw" /* RAW */] &&
1069 !(isReadonly && target["__v_isReactive" /* IS_REACTIVE */])) {
1070 return target;
1071 }
1072 // target already has corresponding Proxy
1073 const existingProxy = proxyMap.get(target);
1074 if (existingProxy) {
1075 return existingProxy;
1076 }
1077 // only a whitelist of value types can be observed.
1078 const targetType = getTargetType(target);
1079 if (targetType === 0 /* INVALID */) {
1080 return target;
1081 }
1082 const proxy = new Proxy(target, targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers);
1083 proxyMap.set(target, proxy);
1084 return proxy;
1085 }
1086 function isReactive(value) {
1087 if (isReadonly(value)) {
1088 return isReactive(value["__v_raw" /* RAW */]);
1089 }
1090 return !!(value && value["__v_isReactive" /* IS_REACTIVE */]);
1091 }
1092 function isReadonly(value) {
1093 return !!(value && value["__v_isReadonly" /* IS_READONLY */]);
1094 }
1095 function isProxy(value) {
1096 return isReactive(value) || isReadonly(value);
1097 }
1098 function toRaw(observed) {
1099 return ((observed && toRaw(observed["__v_raw" /* RAW */])) || observed);
1100 }
1101 function markRaw(value) {
1102 def(value, "__v_skip" /* SKIP */, true);
1103 return value;
1104 }
1105
1106 const convert = (val) => isObject(val) ? reactive(val) : val;
1107 function isRef(r) {
1108 return Boolean(r && r.__v_isRef === true);
1109 }
1110 function ref(value) {
1111 return createRef(value);
1112 }
1113 function shallowRef(value) {
1114 return createRef(value, true);
1115 }
1116 class RefImpl {
1117 constructor(_rawValue, _shallow = false) {
1118 this._rawValue = _rawValue;
1119 this._shallow = _shallow;
1120 this.__v_isRef = true;
1121 this._value = _shallow ? _rawValue : convert(_rawValue);
1122 }
1123 get value() {
1124 track(toRaw(this), "get" /* GET */, 'value');
1125 return this._value;
1126 }
1127 set value(newVal) {
1128 if (hasChanged(toRaw(newVal), this._rawValue)) {
1129 this._rawValue = newVal;
1130 this._value = this._shallow ? newVal : convert(newVal);
1131 trigger(toRaw(this), "set" /* SET */, 'value', newVal);
1132 }
1133 }
1134 }
1135 function createRef(rawValue, shallow = false) {
1136 if (isRef(rawValue)) {
1137 return rawValue;
1138 }
1139 return new RefImpl(rawValue, shallow);
1140 }
1141 function triggerRef(ref) {
1142 trigger(toRaw(ref), "set" /* SET */, 'value', ref.value );
1143 }
1144 function unref(ref) {
1145 return isRef(ref) ? ref.value : ref;
1146 }
1147 const shallowUnwrapHandlers = {
1148 get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)),
1149 set: (target, key, value, receiver) => {
1150 const oldValue = target[key];
1151 if (isRef(oldValue) && !isRef(value)) {
1152 oldValue.value = value;
1153 return true;
1154 }
1155 else {
1156 return Reflect.set(target, key, value, receiver);
1157 }
1158 }
1159 };
1160 function proxyRefs(objectWithRefs) {
1161 return isReactive(objectWithRefs)
1162 ? objectWithRefs
1163 : new Proxy(objectWithRefs, shallowUnwrapHandlers);
1164 }
1165 class CustomRefImpl {
1166 constructor(factory) {
1167 this.__v_isRef = true;
1168 const { get, set } = factory(() => track(this, "get" /* GET */, 'value'), () => trigger(this, "set" /* SET */, 'value'));
1169 this._get = get;
1170 this._set = set;
1171 }
1172 get value() {
1173 return this._get();
1174 }
1175 set value(newVal) {
1176 this._set(newVal);
1177 }
1178 }
1179 function customRef(factory) {
1180 return new CustomRefImpl(factory);
1181 }
1182 function toRefs(object) {
1183 if (!isProxy(object)) {
1184 console.warn(`toRefs() expects a reactive object but received a plain one.`);
1185 }
1186 const ret = isArray(object) ? new Array(object.length) : {};
1187 for (const key in object) {
1188 ret[key] = toRef(object, key);
1189 }
1190 return ret;
1191 }
1192 class ObjectRefImpl {
1193 constructor(_object, _key) {
1194 this._object = _object;
1195 this._key = _key;
1196 this.__v_isRef = true;
1197 }
1198 get value() {
1199 return this._object[this._key];
1200 }
1201 set value(newVal) {
1202 this._object[this._key] = newVal;
1203 }
1204 }
1205 function toRef(object, key) {
1206 return isRef(object[key])
1207 ? object[key]
1208 : new ObjectRefImpl(object, key);
1209 }
1210
1211 class ComputedRefImpl {
1212 constructor(getter, _setter, isReadonly) {
1213 this._setter = _setter;
1214 this._dirty = true;
1215 this.__v_isRef = true;
1216 this.effect = effect(getter, {
1217 lazy: true,
1218 scheduler: () => {
1219 if (!this._dirty) {
1220 this._dirty = true;
1221 trigger(toRaw(this), "set" /* SET */, 'value');
1222 }
1223 }
1224 });
1225 this["__v_isReadonly" /* IS_READONLY */] = isReadonly;
1226 }
1227 get value() {
1228 // the computed ref may get wrapped by other proxies e.g. readonly() #3376
1229 const self = toRaw(this);
1230 if (self._dirty) {
1231 self._value = this.effect();
1232 self._dirty = false;
1233 }
1234 track(self, "get" /* GET */, 'value');
1235 return self._value;
1236 }
1237 set value(newValue) {
1238 this._setter(newValue);
1239 }
1240 }
1241 function computed(getterOrOptions) {
1242 let getter;
1243 let setter;
1244 if (isFunction(getterOrOptions)) {
1245 getter = getterOrOptions;
1246 setter = () => {
1247 console.warn('Write operation failed: computed value is readonly');
1248 }
1249 ;
1250 }
1251 else {
1252 getter = getterOrOptions.get;
1253 setter = getterOrOptions.set;
1254 }
1255 return new ComputedRefImpl(getter, setter, isFunction(getterOrOptions) || !getterOrOptions.set);
1256 }
1257
1258 const stack = [];
1259 function pushWarningContext(vnode) {
1260 stack.push(vnode);
1261 }
1262 function popWarningContext() {
1263 stack.pop();
1264 }
1265 function warn(msg, ...args) {
1266 // avoid props formatting or warn handler tracking deps that might be mutated
1267 // during patch, leading to infinite recursion.
1268 pauseTracking();
1269 const instance = stack.length ? stack[stack.length - 1].component : null;
1270 const appWarnHandler = instance && instance.appContext.config.warnHandler;
1271 const trace = getComponentTrace();
1272 if (appWarnHandler) {
1273 callWithErrorHandling(appWarnHandler, instance, 11 /* APP_WARN_HANDLER */, [
1274 msg + args.join(''),
1275 instance && instance.proxy,
1276 trace
1277 .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`)
1278 .join('\n'),
1279 trace
1280 ]);
1281 }
1282 else {
1283 const warnArgs = [`[Vue warn]: ${msg}`, ...args];
1284 /* istanbul ignore if */
1285 if (trace.length &&
1286 // avoid spamming console during tests
1287 !false) {
1288 warnArgs.push(`\n`, ...formatTrace(trace));
1289 }
1290 console.warn(...warnArgs);
1291 }
1292 resetTracking();
1293 }
1294 function getComponentTrace() {
1295 let currentVNode = stack[stack.length - 1];
1296 if (!currentVNode) {
1297 return [];
1298 }
1299 // we can't just use the stack because it will be incomplete during updates
1300 // that did not start from the root. Re-construct the parent chain using
1301 // instance parent pointers.
1302 const normalizedStack = [];
1303 while (currentVNode) {
1304 const last = normalizedStack[0];
1305 if (last && last.vnode === currentVNode) {
1306 last.recurseCount++;
1307 }
1308 else {
1309 normalizedStack.push({
1310 vnode: currentVNode,
1311 recurseCount: 0
1312 });
1313 }
1314 const parentInstance = currentVNode.component && currentVNode.component.parent;
1315 currentVNode = parentInstance && parentInstance.vnode;
1316 }
1317 return normalizedStack;
1318 }
1319 /* istanbul ignore next */
1320 function formatTrace(trace) {
1321 const logs = [];
1322 trace.forEach((entry, i) => {
1323 logs.push(...(i === 0 ? [] : [`\n`]), ...formatTraceEntry(entry));
1324 });
1325 return logs;
1326 }
1327 function formatTraceEntry({ vnode, recurseCount }) {
1328 const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``;
1329 const isRoot = vnode.component ? vnode.component.parent == null : false;
1330 const open = ` at <${formatComponentName(vnode.component, vnode.type, isRoot)}`;
1331 const close = `>` + postfix;
1332 return vnode.props
1333 ? [open, ...formatProps(vnode.props), close]
1334 : [open + close];
1335 }
1336 /* istanbul ignore next */
1337 function formatProps(props) {
1338 const res = [];
1339 const keys = Object.keys(props);
1340 keys.slice(0, 3).forEach(key => {
1341 res.push(...formatProp(key, props[key]));
1342 });
1343 if (keys.length > 3) {
1344 res.push(` ...`);
1345 }
1346 return res;
1347 }
1348 /* istanbul ignore next */
1349 function formatProp(key, value, raw) {
1350 if (isString(value)) {
1351 value = JSON.stringify(value);
1352 return raw ? value : [`${key}=${value}`];
1353 }
1354 else if (typeof value === 'number' ||
1355 typeof value === 'boolean' ||
1356 value == null) {
1357 return raw ? value : [`${key}=${value}`];
1358 }
1359 else if (isRef(value)) {
1360 value = formatProp(key, toRaw(value.value), true);
1361 return raw ? value : [`${key}=Ref<`, value, `>`];
1362 }
1363 else if (isFunction(value)) {
1364 return [`${key}=fn${value.name ? `<${value.name}>` : ``}`];
1365 }
1366 else {
1367 value = toRaw(value);
1368 return raw ? value : [`${key}=`, value];
1369 }
1370 }
1371
1372 const ErrorTypeStrings = {
1373 ["bc" /* BEFORE_CREATE */]: 'beforeCreate hook',
1374 ["c" /* CREATED */]: 'created hook',
1375 ["bm" /* BEFORE_MOUNT */]: 'beforeMount hook',
1376 ["m" /* MOUNTED */]: 'mounted hook',
1377 ["bu" /* BEFORE_UPDATE */]: 'beforeUpdate hook',
1378 ["u" /* UPDATED */]: 'updated',
1379 ["bum" /* BEFORE_UNMOUNT */]: 'beforeUnmount hook',
1380 ["um" /* UNMOUNTED */]: 'unmounted hook',
1381 ["a" /* ACTIVATED */]: 'activated hook',
1382 ["da" /* DEACTIVATED */]: 'deactivated hook',
1383 ["ec" /* ERROR_CAPTURED */]: 'errorCaptured hook',
1384 ["rtc" /* RENDER_TRACKED */]: 'renderTracked hook',
1385 ["rtg" /* RENDER_TRIGGERED */]: 'renderTriggered hook',
1386 [0 /* SETUP_FUNCTION */]: 'setup function',
1387 [1 /* RENDER_FUNCTION */]: 'render function',
1388 [2 /* WATCH_GETTER */]: 'watcher getter',
1389 [3 /* WATCH_CALLBACK */]: 'watcher callback',
1390 [4 /* WATCH_CLEANUP */]: 'watcher cleanup function',
1391 [5 /* NATIVE_EVENT_HANDLER */]: 'native event handler',
1392 [6 /* COMPONENT_EVENT_HANDLER */]: 'component event handler',
1393 [7 /* VNODE_HOOK */]: 'vnode hook',
1394 [8 /* DIRECTIVE_HOOK */]: 'directive hook',
1395 [9 /* TRANSITION_HOOK */]: 'transition hook',
1396 [10 /* APP_ERROR_HANDLER */]: 'app errorHandler',
1397 [11 /* APP_WARN_HANDLER */]: 'app warnHandler',
1398 [12 /* FUNCTION_REF */]: 'ref function',
1399 [13 /* ASYNC_COMPONENT_LOADER */]: 'async component loader',
1400 [14 /* SCHEDULER */]: 'scheduler flush. This is likely a Vue internals bug. ' +
1401 'Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next'
1402 };
1403 function callWithErrorHandling(fn, instance, type, args) {
1404 let res;
1405 try {
1406 res = args ? fn(...args) : fn();
1407 }
1408 catch (err) {
1409 handleError(err, instance, type);
1410 }
1411 return res;
1412 }
1413 function callWithAsyncErrorHandling(fn, instance, type, args) {
1414 if (isFunction(fn)) {
1415 const res = callWithErrorHandling(fn, instance, type, args);
1416 if (res && isPromise(res)) {
1417 res.catch(err => {
1418 handleError(err, instance, type);
1419 });
1420 }
1421 return res;
1422 }
1423 const values = [];
1424 for (let i = 0; i < fn.length; i++) {
1425 values.push(callWithAsyncErrorHandling(fn[i], instance, type, args));
1426 }
1427 return values;
1428 }
1429 function handleError(err, instance, type, throwInDev = true) {
1430 const contextVNode = instance ? instance.vnode : null;
1431 if (instance) {
1432 let cur = instance.parent;
1433 // the exposed instance is the render proxy to keep it consistent with 2.x
1434 const exposedInstance = instance.proxy;
1435 // in production the hook receives only the error code
1436 const errorInfo = ErrorTypeStrings[type] ;
1437 while (cur) {
1438 const errorCapturedHooks = cur.ec;
1439 if (errorCapturedHooks) {
1440 for (let i = 0; i < errorCapturedHooks.length; i++) {
1441 if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) {
1442 return;
1443 }
1444 }
1445 }
1446 cur = cur.parent;
1447 }
1448 // app-level handling
1449 const appErrorHandler = instance.appContext.config.errorHandler;
1450 if (appErrorHandler) {
1451 callWithErrorHandling(appErrorHandler, null, 10 /* APP_ERROR_HANDLER */, [err, exposedInstance, errorInfo]);
1452 return;
1453 }
1454 }
1455 logError(err, type, contextVNode, throwInDev);
1456 }
1457 function logError(err, type, contextVNode, throwInDev = true) {
1458 {
1459 const info = ErrorTypeStrings[type];
1460 if (contextVNode) {
1461 pushWarningContext(contextVNode);
1462 }
1463 warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`);
1464 if (contextVNode) {
1465 popWarningContext();
1466 }
1467 // crash in dev by default so it's more noticeable
1468 if (throwInDev) {
1469 throw err;
1470 }
1471 else {
1472 console.error(err);
1473 }
1474 }
1475 }
1476
1477 let isFlushing = false;
1478 let isFlushPending = false;
1479 const queue = [];
1480 let flushIndex = 0;
1481 const pendingPreFlushCbs = [];
1482 let activePreFlushCbs = null;
1483 let preFlushIndex = 0;
1484 const pendingPostFlushCbs = [];
1485 let activePostFlushCbs = null;
1486 let postFlushIndex = 0;
1487 const resolvedPromise = Promise.resolve();
1488 let currentFlushPromise = null;
1489 let currentPreFlushParentJob = null;
1490 const RECURSION_LIMIT = 100;
1491 function nextTick(fn) {
1492 const p = currentFlushPromise || resolvedPromise;
1493 return fn ? p.then(this ? fn.bind(this) : fn) : p;
1494 }
1495 // #2768
1496 // Use binary-search to find a suitable position in the queue,
1497 // so that the queue maintains the increasing order of job's id,
1498 // which can prevent the job from being skipped and also can avoid repeated patching.
1499 function findInsertionIndex(job) {
1500 // the start index should be `flushIndex + 1`
1501 let start = flushIndex + 1;
1502 let end = queue.length;
1503 const jobId = getId(job);
1504 while (start < end) {
1505 const middle = (start + end) >>> 1;
1506 const middleJobId = getId(queue[middle]);
1507 middleJobId < jobId ? (start = middle + 1) : (end = middle);
1508 }
1509 return start;
1510 }
1511 function queueJob(job) {
1512 // the dedupe search uses the startIndex argument of Array.includes()
1513 // by default the search index includes the current job that is being run
1514 // so it cannot recursively trigger itself again.
1515 // if the job is a watch() callback, the search will start with a +1 index to
1516 // allow it recursively trigger itself - it is the user's responsibility to
1517 // ensure it doesn't end up in an infinite loop.
1518 if ((!queue.length ||
1519 !queue.includes(job, isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex)) &&
1520 job !== currentPreFlushParentJob) {
1521 const pos = findInsertionIndex(job);
1522 if (pos > -1) {
1523 queue.splice(pos, 0, job);
1524 }
1525 else {
1526 queue.push(job);
1527 }
1528 queueFlush();
1529 }
1530 }
1531 function queueFlush() {
1532 if (!isFlushing && !isFlushPending) {
1533 isFlushPending = true;
1534 currentFlushPromise = resolvedPromise.then(flushJobs);
1535 }
1536 }
1537 function invalidateJob(job) {
1538 const i = queue.indexOf(job);
1539 if (i > flushIndex) {
1540 queue.splice(i, 1);
1541 }
1542 }
1543 function queueCb(cb, activeQueue, pendingQueue, index) {
1544 if (!isArray(cb)) {
1545 if (!activeQueue ||
1546 !activeQueue.includes(cb, cb.allowRecurse ? index + 1 : index)) {
1547 pendingQueue.push(cb);
1548 }
1549 }
1550 else {
1551 // if cb is an array, it is a component lifecycle hook which can only be
1552 // triggered by a job, which is already deduped in the main queue, so
1553 // we can skip duplicate check here to improve perf
1554 pendingQueue.push(...cb);
1555 }
1556 queueFlush();
1557 }
1558 function queuePreFlushCb(cb) {
1559 queueCb(cb, activePreFlushCbs, pendingPreFlushCbs, preFlushIndex);
1560 }
1561 function queuePostFlushCb(cb) {
1562 queueCb(cb, activePostFlushCbs, pendingPostFlushCbs, postFlushIndex);
1563 }
1564 function flushPreFlushCbs(seen, parentJob = null) {
1565 if (pendingPreFlushCbs.length) {
1566 currentPreFlushParentJob = parentJob;
1567 activePreFlushCbs = [...new Set(pendingPreFlushCbs)];
1568 pendingPreFlushCbs.length = 0;
1569 {
1570 seen = seen || new Map();
1571 }
1572 for (preFlushIndex = 0; preFlushIndex < activePreFlushCbs.length; preFlushIndex++) {
1573 if (checkRecursiveUpdates(seen, activePreFlushCbs[preFlushIndex])) {
1574 continue;
1575 }
1576 activePreFlushCbs[preFlushIndex]();
1577 }
1578 activePreFlushCbs = null;
1579 preFlushIndex = 0;
1580 currentPreFlushParentJob = null;
1581 // recursively flush until it drains
1582 flushPreFlushCbs(seen, parentJob);
1583 }
1584 }
1585 function flushPostFlushCbs(seen) {
1586 if (pendingPostFlushCbs.length) {
1587 const deduped = [...new Set(pendingPostFlushCbs)];
1588 pendingPostFlushCbs.length = 0;
1589 // #1947 already has active queue, nested flushPostFlushCbs call
1590 if (activePostFlushCbs) {
1591 activePostFlushCbs.push(...deduped);
1592 return;
1593 }
1594 activePostFlushCbs = deduped;
1595 {
1596 seen = seen || new Map();
1597 }
1598 activePostFlushCbs.sort((a, b) => getId(a) - getId(b));
1599 for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) {
1600 if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) {
1601 continue;
1602 }
1603 activePostFlushCbs[postFlushIndex]();
1604 }
1605 activePostFlushCbs = null;
1606 postFlushIndex = 0;
1607 }
1608 }
1609 const getId = (job) => job.id == null ? Infinity : job.id;
1610 function flushJobs(seen) {
1611 isFlushPending = false;
1612 isFlushing = true;
1613 {
1614 seen = seen || new Map();
1615 }
1616 flushPreFlushCbs(seen);
1617 // Sort queue before flush.
1618 // This ensures that:
1619 // 1. Components are updated from parent to child. (because parent is always
1620 // created before the child so its render effect will have smaller
1621 // priority number)
1622 // 2. If a component is unmounted during a parent component's update,
1623 // its update can be skipped.
1624 queue.sort((a, b) => getId(a) - getId(b));
1625 try {
1626 for (flushIndex = 0; flushIndex < queue.length; flushIndex++) {
1627 const job = queue[flushIndex];
1628 if (job && job.active !== false) {
1629 if (true && checkRecursiveUpdates(seen, job)) {
1630 continue;
1631 }
1632 callWithErrorHandling(job, null, 14 /* SCHEDULER */);
1633 }
1634 }
1635 }
1636 finally {
1637 flushIndex = 0;
1638 queue.length = 0;
1639 flushPostFlushCbs(seen);
1640 isFlushing = false;
1641 currentFlushPromise = null;
1642 // some postFlushCb queued jobs!
1643 // keep flushing until it drains.
1644 if (queue.length ||
1645 pendingPreFlushCbs.length ||
1646 pendingPostFlushCbs.length) {
1647 flushJobs(seen);
1648 }
1649 }
1650 }
1651 function checkRecursiveUpdates(seen, fn) {
1652 if (!seen.has(fn)) {
1653 seen.set(fn, 1);
1654 }
1655 else {
1656 const count = seen.get(fn);
1657 if (count > RECURSION_LIMIT) {
1658 const instance = fn.ownerInstance;
1659 const componentName = instance && getComponentName(instance.type);
1660 warn(`Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. ` +
1661 `This means you have a reactive effect that is mutating its own ` +
1662 `dependencies and thus recursively triggering itself. Possible sources ` +
1663 `include component template, render function, updated hook or ` +
1664 `watcher source function.`);
1665 return true;
1666 }
1667 else {
1668 seen.set(fn, count + 1);
1669 }
1670 }
1671 }
1672
1673 /* eslint-disable no-restricted-globals */
1674 let isHmrUpdating = false;
1675 const hmrDirtyComponents = new Set();
1676 // Expose the HMR runtime on the global object
1677 // This makes it entirely tree-shakable without polluting the exports and makes
1678 // it easier to be used in toolings like vue-loader
1679 // Note: for a component to be eligible for HMR it also needs the __hmrId option
1680 // to be set so that its instances can be registered / removed.
1681 {
1682 const globalObject = typeof global !== 'undefined'
1683 ? global
1684 : typeof self !== 'undefined'
1685 ? self
1686 : typeof window !== 'undefined'
1687 ? window
1688 : {};
1689 globalObject.__VUE_HMR_RUNTIME__ = {
1690 createRecord: tryWrap(createRecord),
1691 rerender: tryWrap(rerender),
1692 reload: tryWrap(reload)
1693 };
1694 }
1695 const map = new Map();
1696 function registerHMR(instance) {
1697 const id = instance.type.__hmrId;
1698 let record = map.get(id);
1699 if (!record) {
1700 createRecord(id, instance.type);
1701 record = map.get(id);
1702 }
1703 record.instances.add(instance);
1704 }
1705 function unregisterHMR(instance) {
1706 map.get(instance.type.__hmrId).instances.delete(instance);
1707 }
1708 function createRecord(id, component) {
1709 if (!component) {
1710 warn(`HMR API usage is out of date.\n` +
1711 `Please upgrade vue-loader/vite/rollup-plugin-vue or other relevant ` +
1712 `dependency that handles Vue SFC compilation.`);
1713 component = {};
1714 }
1715 if (map.has(id)) {
1716 return false;
1717 }
1718 map.set(id, {
1719 component: isClassComponent(component) ? component.__vccOpts : component,
1720 instances: new Set()
1721 });
1722 return true;
1723 }
1724 function rerender(id, newRender) {
1725 const record = map.get(id);
1726 if (!record)
1727 return;
1728 if (newRender)
1729 record.component.render = newRender;
1730 // Array.from creates a snapshot which avoids the set being mutated during
1731 // updates
1732 Array.from(record.instances).forEach(instance => {
1733 if (newRender) {
1734 instance.render = newRender;
1735 }
1736 instance.renderCache = [];
1737 // this flag forces child components with slot content to update
1738 isHmrUpdating = true;
1739 instance.update();
1740 isHmrUpdating = false;
1741 });
1742 }
1743 function reload(id, newComp) {
1744 const record = map.get(id);
1745 if (!record)
1746 return;
1747 // Array.from creates a snapshot which avoids the set being mutated during
1748 // updates
1749 const { component, instances } = record;
1750 if (!hmrDirtyComponents.has(component)) {
1751 // 1. Update existing comp definition to match new one
1752 newComp = isClassComponent(newComp) ? newComp.__vccOpts : newComp;
1753 extend(component, newComp);
1754 for (const key in component) {
1755 if (key !== '__file' && !(key in newComp)) {
1756 delete component[key];
1757 }
1758 }
1759 // 2. Mark component dirty. This forces the renderer to replace the component
1760 // on patch.
1761 hmrDirtyComponents.add(component);
1762 // 3. Make sure to unmark the component after the reload.
1763 queuePostFlushCb(() => {
1764 hmrDirtyComponents.delete(component);
1765 });
1766 }
1767 Array.from(instances).forEach(instance => {
1768 if (instance.parent) {
1769 // 4. Force the parent instance to re-render. This will cause all updated
1770 // components to be unmounted and re-mounted. Queue the update so that we
1771 // don't end up forcing the same parent to re-render multiple times.
1772 queueJob(instance.parent.update);
1773 }
1774 else if (instance.appContext.reload) {
1775 // root instance mounted via createApp() has a reload method
1776 instance.appContext.reload();
1777 }
1778 else if (typeof window !== 'undefined') {
1779 // root instance inside tree created via raw render(). Force reload.
1780 window.location.reload();
1781 }
1782 else {
1783 console.warn('[HMR] Root or manually mounted instance modified. Full reload required.');
1784 }
1785 });
1786 }
1787 function tryWrap(fn) {
1788 return (id, arg) => {
1789 try {
1790 return fn(id, arg);
1791 }
1792 catch (e) {
1793 console.error(e);
1794 console.warn(`[HMR] Something went wrong during Vue component hot-reload. ` +
1795 `Full reload required.`);
1796 }
1797 };
1798 }
1799
1800 function setDevtoolsHook(hook) {
1801 exports.devtools = hook;
1802 }
1803 function devtoolsInitApp(app, version) {
1804 // TODO queue if devtools is undefined
1805 if (!exports.devtools)
1806 return;
1807 exports.devtools.emit("app:init" /* APP_INIT */, app, version, {
1808 Fragment,
1809 Text,
1810 Comment: Comment$1,
1811 Static
1812 });
1813 }
1814 function devtoolsUnmountApp(app) {
1815 if (!exports.devtools)
1816 return;
1817 exports.devtools.emit("app:unmount" /* APP_UNMOUNT */, app);
1818 }
1819 const devtoolsComponentAdded = /*#__PURE__*/ createDevtoolsComponentHook("component:added" /* COMPONENT_ADDED */);
1820 const devtoolsComponentUpdated = /*#__PURE__*/ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */);
1821 const devtoolsComponentRemoved = /*#__PURE__*/ createDevtoolsComponentHook("component:removed" /* COMPONENT_REMOVED */);
1822 function createDevtoolsComponentHook(hook) {
1823 return (component) => {
1824 if (!exports.devtools)
1825 return;
1826 exports.devtools.emit(hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component);
1827 };
1828 }
1829 const devtoolsPerfStart = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:start" /* PERFORMANCE_START */);
1830 const devtoolsPerfEnd = /*#__PURE__*/ createDevtoolsPerformanceHook("perf:end" /* PERFORMANCE_END */);
1831 function createDevtoolsPerformanceHook(hook) {
1832 return (component, type, time) => {
1833 if (!exports.devtools)
1834 return;
1835 exports.devtools.emit(hook, component.appContext.app, component.uid, component, type, time);
1836 };
1837 }
1838 function devtoolsComponentEmit(component, event, params) {
1839 if (!exports.devtools)
1840 return;
1841 exports.devtools.emit("component:emit" /* COMPONENT_EMIT */, component.appContext.app, component, event, params);
1842 }
1843
1844 const deprecationData = {
1845 ["GLOBAL_MOUNT" /* GLOBAL_MOUNT */]: {
1846 message: `The global app bootstrapping API has changed: vm.$mount() and the "el" ` +
1847 `option have been removed. Use createApp(RootComponent).mount() instead.`,
1848 link: `https://v3.vuejs.org/guide/migration/global-api.html#mounting-app-instance`
1849 },
1850 ["GLOBAL_MOUNT_CONTAINER" /* GLOBAL_MOUNT_CONTAINER */]: {
1851 message: `Vue detected directives on the mount container. ` +
1852 `In Vue 3, the container is no longer considered part of the template ` +
1853 `and will not be processed/replaced.`,
1854 link: `https://v3.vuejs.org/guide/migration/mount-changes.html`
1855 },
1856 ["GLOBAL_EXTEND" /* GLOBAL_EXTEND */]: {
1857 message: `Vue.extend() has been removed in Vue 3. ` +
1858 `Use defineComponent() instead.`,
1859 link: `https://v3.vuejs.org/api/global-api.html#definecomponent`
1860 },
1861 ["GLOBAL_PROTOTYPE" /* GLOBAL_PROTOTYPE */]: {
1862 message: `Vue.prototype is no longer available in Vue 3. ` +
1863 `Use app.config.globalProperties instead.`,
1864 link: `https://v3.vuejs.org/guide/migration/global-api.html#vue-prototype-replaced-by-config-globalproperties`
1865 },
1866 ["GLOBAL_SET" /* GLOBAL_SET */]: {
1867 message: `Vue.set() has been removed as it is no longer needed in Vue 3. ` +
1868 `Simply use native JavaScript mutations.`
1869 },
1870 ["GLOBAL_DELETE" /* GLOBAL_DELETE */]: {
1871 message: `Vue.delete() has been removed as it is no longer needed in Vue 3. ` +
1872 `Simply use native JavaScript mutations.`
1873 },
1874 ["GLOBAL_OBSERVABLE" /* GLOBAL_OBSERVABLE */]: {
1875 message: `Vue.observable() has been removed. ` +
1876 `Use \`import { reactive } from "vue"\` from Composition API instead.`,
1877 link: `https://v3.vuejs.org/api/basic-reactivity.html`
1878 },
1879 ["GLOBAL_PRIVATE_UTIL" /* GLOBAL_PRIVATE_UTIL */]: {
1880 message: `Vue.util has been removed. Please refactor to avoid its usage ` +
1881 `since it was an internal API even in Vue 2.`
1882 },
1883 ["CONFIG_SILENT" /* CONFIG_SILENT */]: {
1884 message: `config.silent has been removed because it is not good practice to ` +
1885 `intentionally suppress warnings. You can use your browser console's ` +
1886 `filter features to focus on relevant messages.`
1887 },
1888 ["CONFIG_DEVTOOLS" /* CONFIG_DEVTOOLS */]: {
1889 message: `config.devtools has been removed. To enable devtools for ` +
1890 `production, configure the __VUE_PROD_DEVTOOLS__ compile-time flag.`,
1891 link: `https://github.com/vuejs/vue-next/tree/master/packages/vue#bundler-build-feature-flags`
1892 },
1893 ["CONFIG_KEY_CODES" /* CONFIG_KEY_CODES */]: {
1894 message: `config.keyCodes has been removed. ` +
1895 `In Vue 3, you can directly use the kebab-case key names as v-on modifiers.`,
1896 link: `https://v3.vuejs.org/guide/migration/keycode-modifiers.html`
1897 },
1898 ["CONFIG_PRODUCTION_TIP" /* CONFIG_PRODUCTION_TIP */]: {
1899 message: `config.productionTip has been removed.`,
1900 link: `https://v3.vuejs.org/guide/migration/global-api.html#config-productiontip-removed`
1901 },
1902 ["CONFIG_IGNORED_ELEMENTS" /* CONFIG_IGNORED_ELEMENTS */]: {
1903 message: () => {
1904 let msg = `config.ignoredElements has been removed.`;
1905 if (isRuntimeOnly()) {
1906 msg += ` Pass the "isCustomElement" option to @vue/compiler-dom instead.`;
1907 }
1908 else {
1909 msg += ` Use config.isCustomElement instead.`;
1910 }
1911 return msg;
1912 },
1913 link: `https://v3.vuejs.org/guide/migration/global-api.html#config-ignoredelements-is-now-config-iscustomelement`
1914 },
1915 ["CONFIG_WHITESPACE" /* CONFIG_WHITESPACE */]: {
1916 // this warning is only relevant in the full build when using runtime
1917 // compilation, so it's put in the runtime compatConfig list.
1918 message: `Vue 3 compiler's whitespace option will default to "condense" instead of ` +
1919 `"preserve". To suppress this warning, provide an explicit value for ` +
1920 `\`config.compilerOptions.whitespace\`.`
1921 },
1922 ["CONFIG_OPTION_MERGE_STRATS" /* CONFIG_OPTION_MERGE_STRATS */]: {
1923 message: `config.optionMergeStrategies no longer exposes internal strategies. ` +
1924 `Use custom merge functions instead.`
1925 },
1926 ["INSTANCE_SET" /* INSTANCE_SET */]: {
1927 message: `vm.$set() has been removed as it is no longer needed in Vue 3. ` +
1928 `Simply use native JavaScript mutations.`
1929 },
1930 ["INSTANCE_DELETE" /* INSTANCE_DELETE */]: {
1931 message: `vm.$delete() has been removed as it is no longer needed in Vue 3. ` +
1932 `Simply use native JavaScript mutations.`
1933 },
1934 ["INSTANCE_DESTROY" /* INSTANCE_DESTROY */]: {
1935 message: `vm.$destroy() has been removed. Use app.unmount() instead.`,
1936 link: `https://v3.vuejs.org/api/application-api.html#unmount`
1937 },
1938 ["INSTANCE_EVENT_EMITTER" /* INSTANCE_EVENT_EMITTER */]: {
1939 message: `vm.$on/$once/$off() have been removed. ` +
1940 `Use an external event emitter library instead.`,
1941 link: `https://v3.vuejs.org/guide/migration/events-api.html`
1942 },
1943 ["INSTANCE_EVENT_HOOKS" /* INSTANCE_EVENT_HOOKS */]: {
1944 message: event => `"${event}" lifecycle events are no longer supported. From templates, ` +
1945 `use the "vnode" prefix instead of "hook:". For example, @${event} ` +
1946 `should be changed to @vnode-${event.slice(5)}. ` +
1947 `From JavaScript, use Composition API to dynamically register lifecycle ` +
1948 `hooks.`,
1949 link: `https://v3.vuejs.org/guide/migration/vnode-lifecycle-events.html`
1950 },
1951 ["INSTANCE_CHILDREN" /* INSTANCE_CHILDREN */]: {
1952 message: `vm.$children has been removed. Consider refactoring your logic ` +
1953 `to avoid relying on direct access to child components.`,
1954 link: `https://v3.vuejs.org/guide/migration/children.html`
1955 },
1956 ["INSTANCE_LISTENERS" /* INSTANCE_LISTENERS */]: {
1957 message: `vm.$listeners has been removed. In Vue 3, parent v-on listeners are ` +
1958 `included in vm.$attrs and it is no longer necessary to separately use ` +
1959 `v-on="$listeners" if you are already using v-bind="$attrs". ` +
1960 `(Note: the Vue 3 behavior only applies if this compat config is disabled)`,
1961 link: `https://v3.vuejs.org/guide/migration/listeners-removed.html`
1962 },
1963 ["INSTANCE_SCOPED_SLOTS" /* INSTANCE_SCOPED_SLOTS */]: {
1964 message: `vm.$scopedSlots has been removed. Use vm.$slots instead.`,
1965 link: `https://v3.vuejs.org/guide/migration/slots-unification.html`
1966 },
1967 ["INSTANCE_ATTRS_CLASS_STYLE" /* INSTANCE_ATTRS_CLASS_STYLE */]: {
1968 message: componentName => `Component <${componentName ||
1969 'Anonymous'}> has \`inheritAttrs: false\` but is ` +
1970 `relying on class/style fallthrough from parent. In Vue 3, class/style ` +
1971 `are now included in $attrs and will no longer fallthrough when ` +
1972 `inheritAttrs is false. If you are already using v-bind="$attrs" on ` +
1973 `component root it should render the same end result. ` +
1974 `If you are binding $attrs to a non-root element and expecting ` +
1975 `class/style to fallthrough on root, you will need to now manually bind ` +
1976 `them on root via :class="$attrs.class".`,
1977 link: `https://v3.vuejs.org/guide/migration/attrs-includes-class-style.html`
1978 },
1979 ["OPTIONS_DATA_FN" /* OPTIONS_DATA_FN */]: {
1980 message: `The "data" option can no longer be a plain object. ` +
1981 `Always use a function.`,
1982 link: `https://v3.vuejs.org/guide/migration/data-option.html`
1983 },
1984 ["OPTIONS_DATA_MERGE" /* OPTIONS_DATA_MERGE */]: {
1985 message: (key) => `Detected conflicting key "${key}" when merging data option values. ` +
1986 `In Vue 3, data keys are merged shallowly and will override one another.`,
1987 link: `https://v3.vuejs.org/guide/migration/data-option.html#mixin-merge-behavior-change`
1988 },
1989 ["OPTIONS_BEFORE_DESTROY" /* OPTIONS_BEFORE_DESTROY */]: {
1990 message: `\`beforeDestroy\` has been renamed to \`beforeUnmount\`.`
1991 },
1992 ["OPTIONS_DESTROYED" /* OPTIONS_DESTROYED */]: {
1993 message: `\`destroyed\` has been renamed to \`unmounted\`.`
1994 },
1995 ["WATCH_ARRAY" /* WATCH_ARRAY */]: {
1996 message: `"watch" option or vm.$watch on an array value will no longer ` +
1997 `trigger on array mutation unless the "deep" option is specified. ` +
1998 `If current usage is intended, you can disable the compat behavior and ` +
1999 `suppress this warning with:` +
2000 `\n\n configureCompat({ ${"WATCH_ARRAY" /* WATCH_ARRAY */}: false })\n`,
2001 link: `https://v3.vuejs.org/guide/migration/watch.html`
2002 },
2003 ["PROPS_DEFAULT_THIS" /* PROPS_DEFAULT_THIS */]: {
2004 message: (key) => `props default value function no longer has access to "this". The compat ` +
2005 `build only offers access to this.$options.` +
2006 `(found in prop "${key}")`,
2007 link: `https://v3.vuejs.org/guide/migration/props-default-this.html`
2008 },
2009 ["CUSTOM_DIR" /* CUSTOM_DIR */]: {
2010 message: (legacyHook, newHook) => `Custom directive hook "${legacyHook}" has been removed. ` +
2011 `Use "${newHook}" instead.`,
2012 link: `https://v3.vuejs.org/guide/migration/custom-directives.html`
2013 },
2014 ["V_FOR_REF" /* V_FOR_REF */]: {
2015 message: `Ref usage on v-for no longer creates array ref values in Vue 3. ` +
2016 `Consider using function refs or refactor to avoid ref usage altogether.`,
2017 link: `https://v3.vuejs.org/guide/migration/array-refs.html`
2018 },
2019 ["V_ON_KEYCODE_MODIFIER" /* V_ON_KEYCODE_MODIFIER */]: {
2020 message: `Using keyCode as v-on modifier is no longer supported. ` +
2021 `Use kebab-case key name modifiers instead.`,
2022 link: `https://v3.vuejs.org/guide/migration/keycode-modifiers.html`
2023 },
2024 ["ATTR_FALSE_VALUE" /* ATTR_FALSE_VALUE */]: {
2025 message: (name) => `Attribute "${name}" with v-bind value \`false\` will render ` +
2026 `${name}="false" instead of removing it in Vue 3. To remove the attribute, ` +
2027 `use \`null\` or \`undefined\` instead. If the usage is intended, ` +
2028 `you can disable the compat behavior and suppress this warning with:` +
2029 `\n\n configureCompat({ ${"ATTR_FALSE_VALUE" /* ATTR_FALSE_VALUE */}: false })\n`,
2030 link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
2031 },
2032 ["ATTR_ENUMERATED_COERCION" /* ATTR_ENUMERATED_COERCION */]: {
2033 message: (name, value, coerced) => `Enumerated attribute "${name}" with v-bind value \`${value}\` will ` +
2034 `${value === null ? `be removed` : `render the value as-is`} instead of coercing the value to "${coerced}" in Vue 3. ` +
2035 `Always use explicit "true" or "false" values for enumerated attributes. ` +
2036 `If the usage is intended, ` +
2037 `you can disable the compat behavior and suppress this warning with:` +
2038 `\n\n configureCompat({ ${"ATTR_ENUMERATED_COERCION" /* ATTR_ENUMERATED_COERCION */}: false })\n`,
2039 link: `https://v3.vuejs.org/guide/migration/attribute-coercion.html`
2040 },
2041 ["TRANSITION_CLASSES" /* TRANSITION_CLASSES */]: {
2042 message: `` // this feature cannot be runtime-detected
2043 },
2044 ["TRANSITION_GROUP_ROOT" /* TRANSITION_GROUP_ROOT */]: {
2045 message: `<TransitionGroup> no longer renders a root <span> element by ` +
2046 `default if no "tag" prop is specified. If you do not rely on the span ` +
2047 `for styling, you can disable the compat behavior and suppress this ` +
2048 `warning with:` +
2049 `\n\n configureCompat({ ${"TRANSITION_GROUP_ROOT" /* TRANSITION_GROUP_ROOT */}: false })\n`,
2050 link: `https://v3.vuejs.org/guide/migration/transition-group.html`
2051 },
2052 ["COMPONENT_ASYNC" /* COMPONENT_ASYNC */]: {
2053 message: (comp) => {
2054 const name = getComponentName(comp);
2055 return (`Async component${name ? ` <${name}>` : `s`} should be explicitly created via \`defineAsyncComponent()\` ` +
2056 `in Vue 3. Plain functions will be treated as functional components in ` +
2057 `non-compat build. If you have already migrated all async component ` +
2058 `usage and intend to use plain functions for functional components, ` +
2059 `you can disable the compat behavior and suppress this ` +
2060 `warning with:` +
2061 `\n\n configureCompat({ ${"COMPONENT_ASYNC" /* COMPONENT_ASYNC */}: false })\n`);
2062 },
2063 link: `https://v3.vuejs.org/guide/migration/async-components.html`
2064 },
2065 ["COMPONENT_FUNCTIONAL" /* COMPONENT_FUNCTIONAL */]: {
2066 message: (comp) => {
2067 const name = getComponentName(comp);
2068 return (`Functional component${name ? ` <${name}>` : `s`} should be defined as a plain function in Vue 3. The "functional" ` +
2069 `option has been removed. NOTE: Before migrating to use plain ` +
2070 `functions for functional components, first make sure that all async ` +
2071 `components usage have been migrated and its compat behavior has ` +
2072 `been disabled.`);
2073 },
2074 link: `https://v3.vuejs.org/guide/migration/functional-components.html`
2075 },
2076 ["COMPONENT_V_MODEL" /* COMPONENT_V_MODEL */]: {
2077 message: (comp) => {
2078 const configMsg = `opt-in to ` +
2079 `Vue 3 behavior on a per-component basis with \`compatConfig: { ${"COMPONENT_V_MODEL" /* COMPONENT_V_MODEL */}: false }\`.`;
2080 if (comp.props && isArray(comp.props)
2081 ? comp.props.includes('modelValue')
2082 : hasOwn(comp.props, 'modelValue')) {
2083 return (`Component delcares "modelValue" prop, which is Vue 3 usage, but ` +
2084 `is running under Vue 2 compat v-model behavior. You can ${configMsg}`);
2085 }
2086 return (`v-model usage on component has changed in Vue 3. Component that expects ` +
2087 `to work with v-model should now use the "modelValue" prop and emit the ` +
2088 `"update:modelValue" event. You can update the usage and then ${configMsg}`);
2089 },
2090 link: `https://v3.vuejs.org/guide/migration/v-model.html`
2091 },
2092 ["RENDER_FUNCTION" /* RENDER_FUNCTION */]: {
2093 message: `Vue 3's render function API has changed. ` +
2094 `You can opt-in to the new API with:` +
2095 `\n\n configureCompat({ ${"RENDER_FUNCTION" /* RENDER_FUNCTION */}: false })\n` +
2096 `\n (This can also be done per-component via the "compatConfig" option.)`,
2097 link: `https://v3.vuejs.org/guide/migration/render-function-api.html`
2098 },
2099 ["FILTERS" /* FILTERS */]: {
2100 message: `filters have been removed in Vue 3. ` +
2101 `The "|" symbol will be treated as native JavaScript bitwise OR operator. ` +
2102 `Use method calls or computed properties instead.`,
2103 link: `https://v3.vuejs.org/guide/migration/filters.html`
2104 },
2105 ["PRIVATE_APIS" /* PRIVATE_APIS */]: {
2106 message: name => `"${name}" is a Vue 2 private API that no longer exists in Vue 3. ` +
2107 `If you are seeing this warning only due to a dependency, you can ` +
2108 `suppress this warning via { PRIVATE_APIS: 'supress-warning' }.`
2109 }
2110 };
2111 const instanceWarned = Object.create(null);
2112 const warnCount = Object.create(null);
2113 function warnDeprecation(key, instance, ...args) {
2114 instance = instance || getCurrentInstance();
2115 // check user config
2116 const config = getCompatConfigForKey(key, instance);
2117 if (config === 'suppress-warning') {
2118 return;
2119 }
2120 const dupKey = key + args.join('');
2121 let compId = instance && formatComponentName(instance, instance.type);
2122 if (compId === 'Anonymous' && instance) {
2123 compId = instance.uid;
2124 }
2125 // skip if the same warning is emitted for the same component type
2126 const componentDupKey = dupKey + compId;
2127 if (componentDupKey in instanceWarned) {
2128 return;
2129 }
2130 instanceWarned[componentDupKey] = true;
2131 // same warning, but different component. skip the long message and just
2132 // log the key and count.
2133 if (dupKey in warnCount) {
2134 warn(`(deprecation ${key}) (${++warnCount[dupKey] + 1})`);
2135 return;
2136 }
2137 warnCount[dupKey] = 0;
2138 const { message, link } = deprecationData[key];
2139 warn(`(deprecation ${key}) ${typeof message === 'function' ? message(...args) : message}${link ? `\n Details: ${link}` : ``}`);
2140 if (!isCompatEnabled(key, instance, true)) {
2141 console.error(`^ The above deprecation's compat behavior is disabled and will likely ` +
2142 `lead to runtime errors.`);
2143 }
2144 }
2145 const globalCompatConfig = {
2146 MODE: 2
2147 };
2148 function getCompatConfigForKey(key, instance) {
2149 const instanceConfig = instance && instance.type.compatConfig;
2150 if (instanceConfig && key in instanceConfig) {
2151 return instanceConfig[key];
2152 }
2153 return globalCompatConfig[key];
2154 }
2155 function isCompatEnabled(key, instance, enableForBuiltIn = false) {
2156 // skip compat for built-in components
2157 if (!enableForBuiltIn && instance && instance.type.__isBuiltIn) {
2158 return false;
2159 }
2160 const rawMode = getCompatConfigForKey('MODE', instance) || 2;
2161 const val = getCompatConfigForKey(key, instance);
2162 const mode = isFunction(rawMode)
2163 ? rawMode(instance && instance.type)
2164 : rawMode;
2165 if (mode === 2) {
2166 return val !== false;
2167 }
2168 else {
2169 return val === true || val === 'suppress-warning';
2170 }
2171 }
2172
2173 function emit(instance, event, ...rawArgs) {
2174 const props = instance.vnode.props || EMPTY_OBJ;
2175 {
2176 const { emitsOptions, propsOptions: [propsOptions] } = instance;
2177 if (emitsOptions) {
2178 if (!(event in emitsOptions) &&
2179 !(false )) {
2180 if (!propsOptions || !(toHandlerKey(event) in propsOptions)) {
2181 warn(`Component emitted event "${event}" but it is neither declared in ` +
2182 `the emits option nor as an "${toHandlerKey(event)}" prop.`);
2183 }
2184 }
2185 else {
2186 const validator = emitsOptions[event];
2187 if (isFunction(validator)) {
2188 const isValid = validator(...rawArgs);
2189 if (!isValid) {
2190 warn(`Invalid event arguments: event validation failed for event "${event}".`);
2191 }
2192 }
2193 }
2194 }
2195 }
2196 let args = rawArgs;
2197 const isModelListener = event.startsWith('update:');
2198 // for v-model update:xxx events, apply modifiers on args
2199 const modelArg = isModelListener && event.slice(7);
2200 if (modelArg && modelArg in props) {
2201 const modifiersKey = `${modelArg === 'modelValue' ? 'model' : modelArg}Modifiers`;
2202 const { number, trim } = props[modifiersKey] || EMPTY_OBJ;
2203 if (trim) {
2204 args = rawArgs.map(a => a.trim());
2205 }
2206 else if (number) {
2207 args = rawArgs.map(toNumber);
2208 }
2209 }
2210 {
2211 devtoolsComponentEmit(instance, event, args);
2212 }
2213 {
2214 const lowerCaseEvent = event.toLowerCase();
2215 if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) {
2216 warn(`Event "${lowerCaseEvent}" is emitted in component ` +
2217 `${formatComponentName(instance, instance.type)} but the handler is registered for "${event}". ` +
2218 `Note that HTML attributes are case-insensitive and you cannot use ` +
2219 `v-on to listen to camelCase events when using in-DOM templates. ` +
2220 `You should probably use "${hyphenate(event)}" instead of "${event}".`);
2221 }
2222 }
2223 let handlerName;
2224 let handler = props[(handlerName = toHandlerKey(event))] ||
2225 // also try camelCase event handler (#2249)
2226 props[(handlerName = toHandlerKey(camelize(event)))];
2227 // for v-model update:xxx events, also trigger kebab-case equivalent
2228 // for props passed via kebab-case
2229 if (!handler && isModelListener) {
2230 handler = props[(handlerName = toHandlerKey(hyphenate(event)))];
2231 }
2232 if (handler) {
2233 callWithAsyncErrorHandling(handler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2234 }
2235 const onceHandler = props[handlerName + `Once`];
2236 if (onceHandler) {
2237 if (!instance.emitted) {
2238 (instance.emitted = {})[handlerName] = true;
2239 }
2240 else if (instance.emitted[handlerName]) {
2241 return;
2242 }
2243 callWithAsyncErrorHandling(onceHandler, instance, 6 /* COMPONENT_EVENT_HANDLER */, args);
2244 }
2245 }
2246 function normalizeEmitsOptions(comp, appContext, asMixin = false) {
2247 const cache = appContext.emitsCache;
2248 const cached = cache.get(comp);
2249 if (cached !== undefined) {
2250 return cached;
2251 }
2252 const raw = comp.emits;
2253 let normalized = {};
2254 // apply mixin/extends props
2255 let hasExtends = false;
2256 if (!isFunction(comp)) {
2257 const extendEmits = (raw) => {
2258 const normalizedFromExtend = normalizeEmitsOptions(raw, appContext, true);
2259 if (normalizedFromExtend) {
2260 hasExtends = true;
2261 extend(normalized, normalizedFromExtend);
2262 }
2263 };
2264 if (!asMixin && appContext.mixins.length) {
2265 appContext.mixins.forEach(extendEmits);
2266 }
2267 if (comp.extends) {
2268 extendEmits(comp.extends);
2269 }
2270 if (comp.mixins) {
2271 comp.mixins.forEach(extendEmits);
2272 }
2273 }
2274 if (!raw && !hasExtends) {
2275 cache.set(comp, null);
2276 return null;
2277 }
2278 if (isArray(raw)) {
2279 raw.forEach(key => (normalized[key] = null));
2280 }
2281 else {
2282 extend(normalized, raw);
2283 }
2284 cache.set(comp, normalized);
2285 return normalized;
2286 }
2287 // Check if an incoming prop key is a declared emit event listener.
2288 // e.g. With `emits: { click: null }`, props named `onClick` and `onclick` are
2289 // both considered matched listeners.
2290 function isEmitListener(options, key) {
2291 if (!options || !isOn(key)) {
2292 return false;
2293 }
2294 key = key.slice(2).replace(/Once$/, '');
2295 return (hasOwn(options, key[0].toLowerCase() + key.slice(1)) ||
2296 hasOwn(options, hyphenate(key)) ||
2297 hasOwn(options, key));
2298 }
2299
2300 /**
2301 * mark the current rendering instance for asset resolution (e.g.
2302 * resolveComponent, resolveDirective) during render
2303 */
2304 let currentRenderingInstance = null;
2305 let currentScopeId = null;
2306 /**
2307 * Note: rendering calls maybe nested. The function returns the parent rendering
2308 * instance if present, which should be restored after the render is done:
2309 *
2310 * ```js
2311 * const prev = setCurrentRenderingInstance(i)
2312 * // ...render
2313 * setCurrentRenderingInstance(prev)
2314 * ```
2315 */
2316 function setCurrentRenderingInstance(instance) {
2317 const prev = currentRenderingInstance;
2318 currentRenderingInstance = instance;
2319 currentScopeId = (instance && instance.type.__scopeId) || null;
2320 return prev;
2321 }
2322 /**
2323 * Set scope id when creating hoisted vnodes.
2324 * @private compiler helper
2325 */
2326 function pushScopeId(id) {
2327 currentScopeId = id;
2328 }
2329 /**
2330 * Technically we no longer need this after 3.0.8 but we need to keep the same
2331 * API for backwards compat w/ code generated by compilers.
2332 * @private
2333 */
2334 function popScopeId() {
2335 currentScopeId = null;
2336 }
2337 /**
2338 * Only for backwards compat
2339 * @private
2340 */
2341 const withScopeId = (_id) => withCtx;
2342 /**
2343 * Wrap a slot function to memoize current rendering instance
2344 * @private compiler helper
2345 */
2346 function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot // false only
2347 ) {
2348 if (!ctx)
2349 return fn;
2350 // already normalized
2351 if (fn._n) {
2352 return fn;
2353 }
2354 const renderFnWithContext = (...args) => {
2355 // If a user calls a compiled slot inside a template expression (#1745), it
2356 // can mess up block tracking, so by default we disable block tracking and
2357 // force bail out when invoking a compiled slot (indicated by the ._d flag).
2358 // This isn't necessary if rendering a compiled `<slot>`, so we flip the
2359 // ._d flag off when invoking the wrapped fn inside `renderSlot`.
2360 if (renderFnWithContext._d) {
2361 setBlockTracking(-1);
2362 }
2363 const prevInstance = setCurrentRenderingInstance(ctx);
2364 const res = fn(...args);
2365 setCurrentRenderingInstance(prevInstance);
2366 if (renderFnWithContext._d) {
2367 setBlockTracking(1);
2368 }
2369 {
2370 devtoolsComponentUpdated(ctx);
2371 }
2372 return res;
2373 };
2374 // mark normalized to avoid duplicated wrapping
2375 renderFnWithContext._n = true;
2376 // mark this as compiled by default
2377 // this is used in vnode.ts -> normalizeChildren() to set the slot
2378 // rendering flag.
2379 renderFnWithContext._c = true;
2380 // disable block tracking by default
2381 renderFnWithContext._d = true;
2382 return renderFnWithContext;
2383 }
2384
2385 /**
2386 * dev only flag to track whether $attrs was used during render.
2387 * If $attrs was used during render then the warning for failed attrs
2388 * fallthrough can be suppressed.
2389 */
2390 let accessedAttrs = false;
2391 function markAttrsAccessed() {
2392 accessedAttrs = true;
2393 }
2394 function renderComponentRoot(instance) {
2395 const { type: Component, vnode, proxy, withProxy, props, propsOptions: [propsOptions], slots, attrs, emit, render, renderCache, data, setupState, ctx, inheritAttrs } = instance;
2396 let result;
2397 const prev = setCurrentRenderingInstance(instance);
2398 {
2399 accessedAttrs = false;
2400 }
2401 try {
2402 let fallthroughAttrs;
2403 if (vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */) {
2404 // withProxy is a proxy with a different `has` trap only for
2405 // runtime-compiled render functions using `with` block.
2406 const proxyToUse = withProxy || proxy;
2407 result = normalizeVNode(render.call(proxyToUse, proxyToUse, renderCache, props, setupState, data, ctx));
2408 fallthroughAttrs = attrs;
2409 }
2410 else {
2411 // functional
2412 const render = Component;
2413 // in dev, mark attrs accessed if optional props (attrs === props)
2414 if (true && attrs === props) {
2415 markAttrsAccessed();
2416 }
2417 result = normalizeVNode(render.length > 1
2418 ? render(props, true
2419 ? {
2420 get attrs() {
2421 markAttrsAccessed();
2422 return attrs;
2423 },
2424 slots,
2425 emit
2426 }
2427 : { attrs, slots, emit })
2428 : render(props, null /* we know it doesn't need it */));
2429 fallthroughAttrs = Component.props
2430 ? attrs
2431 : getFunctionalFallthrough(attrs);
2432 }
2433 // attr merging
2434 // in dev mode, comments are preserved, and it's possible for a template
2435 // to have comments along side the root element which makes it a fragment
2436 let root = result;
2437 let setRoot = undefined;
2438 if (true &&
2439 result.patchFlag > 0 &&
2440 result.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
2441 ;
2442 [root, setRoot] = getChildRoot(result);
2443 }
2444 if (fallthroughAttrs && inheritAttrs !== false) {
2445 const keys = Object.keys(fallthroughAttrs);
2446 const { shapeFlag } = root;
2447 if (keys.length) {
2448 if (shapeFlag & 1 /* ELEMENT */ ||
2449 shapeFlag & 6 /* COMPONENT */) {
2450 if (propsOptions && keys.some(isModelListener)) {
2451 // If a v-model listener (onUpdate:xxx) has a corresponding declared
2452 // prop, it indicates this component expects to handle v-model and
2453 // it should not fallthrough.
2454 // related: #1543, #1643, #1989
2455 fallthroughAttrs = filterModelListeners(fallthroughAttrs, propsOptions);
2456 }
2457 root = cloneVNode(root, fallthroughAttrs);
2458 }
2459 else if (true && !accessedAttrs && root.type !== Comment$1) {
2460 const allAttrs = Object.keys(attrs);
2461 const eventAttrs = [];
2462 const extraAttrs = [];
2463 for (let i = 0, l = allAttrs.length; i < l; i++) {
2464 const key = allAttrs[i];
2465 if (isOn(key)) {
2466 // ignore v-model handlers when they fail to fallthrough
2467 if (!isModelListener(key)) {
2468 // remove `on`, lowercase first letter to reflect event casing
2469 // accurately
2470 eventAttrs.push(key[2].toLowerCase() + key.slice(3));
2471 }
2472 }
2473 else {
2474 extraAttrs.push(key);
2475 }
2476 }
2477 if (extraAttrs.length) {
2478 warn(`Extraneous non-props attributes (` +
2479 `${extraAttrs.join(', ')}) ` +
2480 `were passed to component but could not be automatically inherited ` +
2481 `because component renders fragment or text root nodes.`);
2482 }
2483 if (eventAttrs.length) {
2484 warn(`Extraneous non-emits event listeners (` +
2485 `${eventAttrs.join(', ')}) ` +
2486 `were passed to component but could not be automatically inherited ` +
2487 `because component renders fragment or text root nodes. ` +
2488 `If the listener is intended to be a component custom event listener only, ` +
2489 `declare it using the "emits" option.`);
2490 }
2491 }
2492 }
2493 }
2494 if (false &&
2495 isCompatEnabled("INSTANCE_ATTRS_CLASS_STYLE" /* INSTANCE_ATTRS_CLASS_STYLE */, instance) &&
2496 vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */ &&
2497 (root.shapeFlag & 1 /* ELEMENT */ ||
2498 root.shapeFlag & 6 /* COMPONENT */)) ;
2499 // inherit directives
2500 if (vnode.dirs) {
2501 if (true && !isElementRoot(root)) {
2502 warn(`Runtime directive used on component with non-element root node. ` +
2503 `The directives will not function as intended.`);
2504 }
2505 root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs;
2506 }
2507 // inherit transition data
2508 if (vnode.transition) {
2509 if (true && !isElementRoot(root)) {
2510 warn(`Component inside <Transition> renders non-element root node ` +
2511 `that cannot be animated.`);
2512 }
2513 root.transition = vnode.transition;
2514 }
2515 if (true && setRoot) {
2516 setRoot(root);
2517 }
2518 else {
2519 result = root;
2520 }
2521 }
2522 catch (err) {
2523 blockStack.length = 0;
2524 handleError(err, instance, 1 /* RENDER_FUNCTION */);
2525 result = createVNode(Comment$1);
2526 }
2527 setCurrentRenderingInstance(prev);
2528 return result;
2529 }
2530 /**
2531 * dev only
2532 * In dev mode, template root level comments are rendered, which turns the
2533 * template into a fragment root, but we need to locate the single element
2534 * root for attrs and scope id processing.
2535 */
2536 const getChildRoot = (vnode) => {
2537 const rawChildren = vnode.children;
2538 const dynamicChildren = vnode.dynamicChildren;
2539 const childRoot = filterSingleRoot(rawChildren);
2540 if (!childRoot) {
2541 return [vnode, undefined];
2542 }
2543 const index = rawChildren.indexOf(childRoot);
2544 const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1;
2545 const setRoot = (updatedRoot) => {
2546 rawChildren[index] = updatedRoot;
2547 if (dynamicChildren) {
2548 if (dynamicIndex > -1) {
2549 dynamicChildren[dynamicIndex] = updatedRoot;
2550 }
2551 else if (updatedRoot.patchFlag > 0) {
2552 vnode.dynamicChildren = [...dynamicChildren, updatedRoot];
2553 }
2554 }
2555 };
2556 return [normalizeVNode(childRoot), setRoot];
2557 };
2558 function filterSingleRoot(children) {
2559 let singleRoot;
2560 for (let i = 0; i < children.length; i++) {
2561 const child = children[i];
2562 if (isVNode(child)) {
2563 // ignore user comment
2564 if (child.type !== Comment$1 || child.children === 'v-if') {
2565 if (singleRoot) {
2566 // has more than 1 non-comment child, return now
2567 return;
2568 }
2569 else {
2570 singleRoot = child;
2571 }
2572 }
2573 }
2574 else {
2575 return;
2576 }
2577 }
2578 return singleRoot;
2579 }
2580 const getFunctionalFallthrough = (attrs) => {
2581 let res;
2582 for (const key in attrs) {
2583 if (key === 'class' || key === 'style' || isOn(key)) {
2584 (res || (res = {}))[key] = attrs[key];
2585 }
2586 }
2587 return res;
2588 };
2589 const filterModelListeners = (attrs, props) => {
2590 const res = {};
2591 for (const key in attrs) {
2592 if (!isModelListener(key) || !(key.slice(9) in props)) {
2593 res[key] = attrs[key];
2594 }
2595 }
2596 return res;
2597 };
2598 const isElementRoot = (vnode) => {
2599 return (vnode.shapeFlag & 6 /* COMPONENT */ ||
2600 vnode.shapeFlag & 1 /* ELEMENT */ ||
2601 vnode.type === Comment$1 // potential v-if branch switch
2602 );
2603 };
2604 function shouldUpdateComponent(prevVNode, nextVNode, optimized) {
2605 const { props: prevProps, children: prevChildren, component } = prevVNode;
2606 const { props: nextProps, children: nextChildren, patchFlag } = nextVNode;
2607 const emits = component.emitsOptions;
2608 // Parent component's render function was hot-updated. Since this may have
2609 // caused the child component's slots content to have changed, we need to
2610 // force the child to update as well.
2611 if ((prevChildren || nextChildren) && isHmrUpdating) {
2612 return true;
2613 }
2614 // force child update for runtime directive or transition on component vnode.
2615 if (nextVNode.dirs || nextVNode.transition) {
2616 return true;
2617 }
2618 if (optimized && patchFlag >= 0) {
2619 if (patchFlag & 1024 /* DYNAMIC_SLOTS */) {
2620 // slot content that references values that might have changed,
2621 // e.g. in a v-for
2622 return true;
2623 }
2624 if (patchFlag & 16 /* FULL_PROPS */) {
2625 if (!prevProps) {
2626 return !!nextProps;
2627 }
2628 // presence of this flag indicates props are always non-null
2629 return hasPropsChanged(prevProps, nextProps, emits);
2630 }
2631 else if (patchFlag & 8 /* PROPS */) {
2632 const dynamicProps = nextVNode.dynamicProps;
2633 for (let i = 0; i < dynamicProps.length; i++) {
2634 const key = dynamicProps[i];
2635 if (nextProps[key] !== prevProps[key] &&
2636 !isEmitListener(emits, key)) {
2637 return true;
2638 }
2639 }
2640 }
2641 }
2642 else {
2643 // this path is only taken by manually written render functions
2644 // so presence of any children leads to a forced update
2645 if (prevChildren || nextChildren) {
2646 if (!nextChildren || !nextChildren.$stable) {
2647 return true;
2648 }
2649 }
2650 if (prevProps === nextProps) {
2651 return false;
2652 }
2653 if (!prevProps) {
2654 return !!nextProps;
2655 }
2656 if (!nextProps) {
2657 return true;
2658 }
2659 return hasPropsChanged(prevProps, nextProps, emits);
2660 }
2661 return false;
2662 }
2663 function hasPropsChanged(prevProps, nextProps, emitsOptions) {
2664 const nextKeys = Object.keys(nextProps);
2665 if (nextKeys.length !== Object.keys(prevProps).length) {
2666 return true;
2667 }
2668 for (let i = 0; i < nextKeys.length; i++) {
2669 const key = nextKeys[i];
2670 if (nextProps[key] !== prevProps[key] &&
2671 !isEmitListener(emitsOptions, key)) {
2672 return true;
2673 }
2674 }
2675 return false;
2676 }
2677 function updateHOCHostEl({ vnode, parent }, el // HostNode
2678 ) {
2679 while (parent && parent.subTree === vnode) {
2680 (vnode = parent.vnode).el = el;
2681 parent = parent.parent;
2682 }
2683 }
2684
2685 const isSuspense = (type) => type.__isSuspense;
2686 // Suspense exposes a component-like API, and is treated like a component
2687 // in the compiler, but internally it's a special built-in type that hooks
2688 // directly into the renderer.
2689 const SuspenseImpl = {
2690 name: 'Suspense',
2691 // In order to make Suspense tree-shakable, we need to avoid importing it
2692 // directly in the renderer. The renderer checks for the __isSuspense flag
2693 // on a vnode's type and calls the `process` method, passing in renderer
2694 // internals.
2695 __isSuspense: true,
2696 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized,
2697 // platform-specific impl passed from renderer
2698 rendererInternals) {
2699 if (n1 == null) {
2700 mountSuspense(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals);
2701 }
2702 else {
2703 patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, rendererInternals);
2704 }
2705 },
2706 hydrate: hydrateSuspense,
2707 create: createSuspenseBoundary,
2708 normalize: normalizeSuspenseChildren
2709 };
2710 // Force-casted public typing for h and TSX props inference
2711 const Suspense = (SuspenseImpl
2712 );
2713 function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) {
2714 const { p: patch, o: { createElement } } = rendererInternals;
2715 const hiddenContainer = createElement('div');
2716 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals));
2717 // start mounting the content subtree in an off-dom container
2718 patch(null, (suspense.pendingBranch = vnode.ssContent), hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds);
2719 // now check if we have encountered any async deps
2720 if (suspense.deps > 0) {
2721 // has async
2722 // mount the fallback tree
2723 patch(null, vnode.ssFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2724 isSVG, slotScopeIds);
2725 setActiveBranch(suspense, vnode.ssFallback);
2726 }
2727 else {
2728 // Suspense has no async deps. Just resolve.
2729 suspense.resolve();
2730 }
2731 }
2732 function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) {
2733 const suspense = (n2.suspense = n1.suspense);
2734 suspense.vnode = n2;
2735 n2.el = n1.el;
2736 const newBranch = n2.ssContent;
2737 const newFallback = n2.ssFallback;
2738 const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense;
2739 if (pendingBranch) {
2740 suspense.pendingBranch = newBranch;
2741 if (isSameVNodeType(newBranch, pendingBranch)) {
2742 // same root type but content may have changed.
2743 patch(pendingBranch, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2744 if (suspense.deps <= 0) {
2745 suspense.resolve();
2746 }
2747 else if (isInFallback) {
2748 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2749 isSVG, slotScopeIds, optimized);
2750 setActiveBranch(suspense, newFallback);
2751 }
2752 }
2753 else {
2754 // toggled before pending tree is resolved
2755 suspense.pendingId++;
2756 if (isHydrating) {
2757 // if toggled before hydration is finished, the current DOM tree is
2758 // no longer valid. set it as the active branch so it will be unmounted
2759 // when resolved
2760 suspense.isHydrating = false;
2761 suspense.activeBranch = pendingBranch;
2762 }
2763 else {
2764 unmount(pendingBranch, parentComponent, suspense);
2765 }
2766 // increment pending ID. this is used to invalidate async callbacks
2767 // reset suspense state
2768 suspense.deps = 0;
2769 // discard effects from pending branch
2770 suspense.effects.length = 0;
2771 // discard previous container
2772 suspense.hiddenContainer = createElement('div');
2773 if (isInFallback) {
2774 // already in fallback state
2775 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2776 if (suspense.deps <= 0) {
2777 suspense.resolve();
2778 }
2779 else {
2780 patch(activeBranch, newFallback, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2781 isSVG, slotScopeIds, optimized);
2782 setActiveBranch(suspense, newFallback);
2783 }
2784 }
2785 else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2786 // toggled "back" to current active branch
2787 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2788 // force resolve
2789 suspense.resolve(true);
2790 }
2791 else {
2792 // switched to a 3rd branch
2793 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2794 if (suspense.deps <= 0) {
2795 suspense.resolve();
2796 }
2797 }
2798 }
2799 }
2800 else {
2801 if (activeBranch && isSameVNodeType(newBranch, activeBranch)) {
2802 // root did not change, just normal patch
2803 patch(activeBranch, newBranch, container, anchor, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2804 setActiveBranch(suspense, newBranch);
2805 }
2806 else {
2807 // root node toggled
2808 // invoke @pending event
2809 const onPending = n2.props && n2.props.onPending;
2810 if (isFunction(onPending)) {
2811 onPending();
2812 }
2813 // mount pending branch in off-dom container
2814 suspense.pendingBranch = newBranch;
2815 suspense.pendingId++;
2816 patch(null, newBranch, suspense.hiddenContainer, null, parentComponent, suspense, isSVG, slotScopeIds, optimized);
2817 if (suspense.deps <= 0) {
2818 // incoming branch has no async deps, resolve now.
2819 suspense.resolve();
2820 }
2821 else {
2822 const { timeout, pendingId } = suspense;
2823 if (timeout > 0) {
2824 setTimeout(() => {
2825 if (suspense.pendingId === pendingId) {
2826 suspense.fallback(newFallback);
2827 }
2828 }, timeout);
2829 }
2830 else if (timeout === 0) {
2831 suspense.fallback(newFallback);
2832 }
2833 }
2834 }
2835 }
2836 }
2837 let hasWarned = false;
2838 function createSuspenseBoundary(vnode, parent, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) {
2839 /* istanbul ignore if */
2840 if (!hasWarned) {
2841 hasWarned = true;
2842 // @ts-ignore `console.info` cannot be null error
2843 console[console.info ? 'info' : 'log'](`<Suspense> is an experimental feature and its API will likely change.`);
2844 }
2845 const { p: patch, m: move, um: unmount, n: next, o: { parentNode, remove } } = rendererInternals;
2846 const timeout = toNumber(vnode.props && vnode.props.timeout);
2847 const suspense = {
2848 vnode,
2849 parent,
2850 parentComponent,
2851 isSVG,
2852 container,
2853 hiddenContainer,
2854 anchor,
2855 deps: 0,
2856 pendingId: 0,
2857 timeout: typeof timeout === 'number' ? timeout : -1,
2858 activeBranch: null,
2859 pendingBranch: null,
2860 isInFallback: true,
2861 isHydrating,
2862 isUnmounted: false,
2863 effects: [],
2864 resolve(resume = false) {
2865 {
2866 if (!resume && !suspense.pendingBranch) {
2867 throw new Error(`suspense.resolve() is called without a pending branch.`);
2868 }
2869 if (suspense.isUnmounted) {
2870 throw new Error(`suspense.resolve() is called on an already unmounted suspense boundary.`);
2871 }
2872 }
2873 const { vnode, activeBranch, pendingBranch, pendingId, effects, parentComponent, container } = suspense;
2874 if (suspense.isHydrating) {
2875 suspense.isHydrating = false;
2876 }
2877 else if (!resume) {
2878 const delayEnter = activeBranch &&
2879 pendingBranch.transition &&
2880 pendingBranch.transition.mode === 'out-in';
2881 if (delayEnter) {
2882 activeBranch.transition.afterLeave = () => {
2883 if (pendingId === suspense.pendingId) {
2884 move(pendingBranch, container, anchor, 0 /* ENTER */);
2885 }
2886 };
2887 }
2888 // this is initial anchor on mount
2889 let { anchor } = suspense;
2890 // unmount current active tree
2891 if (activeBranch) {
2892 // if the fallback tree was mounted, it may have been moved
2893 // as part of a parent suspense. get the latest anchor for insertion
2894 anchor = next(activeBranch);
2895 unmount(activeBranch, parentComponent, suspense, true);
2896 }
2897 if (!delayEnter) {
2898 // move content from off-dom container to actual container
2899 move(pendingBranch, container, anchor, 0 /* ENTER */);
2900 }
2901 }
2902 setActiveBranch(suspense, pendingBranch);
2903 suspense.pendingBranch = null;
2904 suspense.isInFallback = false;
2905 // flush buffered effects
2906 // check if there is a pending parent suspense
2907 let parent = suspense.parent;
2908 let hasUnresolvedAncestor = false;
2909 while (parent) {
2910 if (parent.pendingBranch) {
2911 // found a pending parent suspense, merge buffered post jobs
2912 // into that parent
2913 parent.effects.push(...effects);
2914 hasUnresolvedAncestor = true;
2915 break;
2916 }
2917 parent = parent.parent;
2918 }
2919 // no pending parent suspense, flush all jobs
2920 if (!hasUnresolvedAncestor) {
2921 queuePostFlushCb(effects);
2922 }
2923 suspense.effects = [];
2924 // invoke @resolve event
2925 const onResolve = vnode.props && vnode.props.onResolve;
2926 if (isFunction(onResolve)) {
2927 onResolve();
2928 }
2929 },
2930 fallback(fallbackVNode) {
2931 if (!suspense.pendingBranch) {
2932 return;
2933 }
2934 const { vnode, activeBranch, parentComponent, container, isSVG } = suspense;
2935 // invoke @fallback event
2936 const onFallback = vnode.props && vnode.props.onFallback;
2937 if (isFunction(onFallback)) {
2938 onFallback();
2939 }
2940 const anchor = next(activeBranch);
2941 const mountFallback = () => {
2942 if (!suspense.isInFallback) {
2943 return;
2944 }
2945 // mount the fallback tree
2946 patch(null, fallbackVNode, container, anchor, parentComponent, null, // fallback tree will not have suspense context
2947 isSVG, slotScopeIds, optimized);
2948 setActiveBranch(suspense, fallbackVNode);
2949 };
2950 const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === 'out-in';
2951 if (delayEnter) {
2952 activeBranch.transition.afterLeave = mountFallback;
2953 }
2954 // unmount current active branch
2955 unmount(activeBranch, parentComponent, null, // no suspense so unmount hooks fire now
2956 true // shouldRemove
2957 );
2958 suspense.isInFallback = true;
2959 if (!delayEnter) {
2960 mountFallback();
2961 }
2962 },
2963 move(container, anchor, type) {
2964 suspense.activeBranch &&
2965 move(suspense.activeBranch, container, anchor, type);
2966 suspense.container = container;
2967 },
2968 next() {
2969 return suspense.activeBranch && next(suspense.activeBranch);
2970 },
2971 registerDep(instance, setupRenderEffect) {
2972 const isInPendingSuspense = !!suspense.pendingBranch;
2973 if (isInPendingSuspense) {
2974 suspense.deps++;
2975 }
2976 const hydratedEl = instance.vnode.el;
2977 instance
2978 .asyncDep.catch(err => {
2979 handleError(err, instance, 0 /* SETUP_FUNCTION */);
2980 })
2981 .then(asyncSetupResult => {
2982 // retry when the setup() promise resolves.
2983 // component may have been unmounted before resolve.
2984 if (instance.isUnmounted ||
2985 suspense.isUnmounted ||
2986 suspense.pendingId !== instance.suspenseId) {
2987 return;
2988 }
2989 // retry from this component
2990 instance.asyncResolved = true;
2991 const { vnode } = instance;
2992 {
2993 pushWarningContext(vnode);
2994 }
2995 handleSetupResult(instance, asyncSetupResult, false);
2996 if (hydratedEl) {
2997 // vnode may have been replaced if an update happened before the
2998 // async dep is resolved.
2999 vnode.el = hydratedEl;
3000 }
3001 const placeholder = !hydratedEl && instance.subTree.el;
3002 setupRenderEffect(instance, vnode,
3003 // component may have been moved before resolve.
3004 // if this is not a hydration, instance.subTree will be the comment
3005 // placeholder.
3006 parentNode(hydratedEl || instance.subTree.el),
3007 // anchor will not be used if this is hydration, so only need to
3008 // consider the comment placeholder case.
3009 hydratedEl ? null : next(instance.subTree), suspense, isSVG, optimized);
3010 if (placeholder) {
3011 remove(placeholder);
3012 }
3013 updateHOCHostEl(instance, vnode.el);
3014 {
3015 popWarningContext();
3016 }
3017 // only decrease deps count if suspense is not already resolved
3018 if (isInPendingSuspense && --suspense.deps === 0) {
3019 suspense.resolve();
3020 }
3021 });
3022 },
3023 unmount(parentSuspense, doRemove) {
3024 suspense.isUnmounted = true;
3025 if (suspense.activeBranch) {
3026 unmount(suspense.activeBranch, parentComponent, parentSuspense, doRemove);
3027 }
3028 if (suspense.pendingBranch) {
3029 unmount(suspense.pendingBranch, parentComponent, parentSuspense, doRemove);
3030 }
3031 }
3032 };
3033 return suspense;
3034 }
3035 function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) {
3036 /* eslint-disable no-restricted-globals */
3037 const suspense = (vnode.suspense = createSuspenseBoundary(vnode, parentSuspense, parentComponent, node.parentNode, document.createElement('div'), null, isSVG, slotScopeIds, optimized, rendererInternals, true /* hydrating */));
3038 // there are two possible scenarios for server-rendered suspense:
3039 // - success: ssr content should be fully resolved
3040 // - failure: ssr content should be the fallback branch.
3041 // however, on the client we don't really know if it has failed or not
3042 // attempt to hydrate the DOM assuming it has succeeded, but we still
3043 // need to construct a suspense boundary first
3044 const result = hydrateNode(node, (suspense.pendingBranch = vnode.ssContent), parentComponent, suspense, slotScopeIds, optimized);
3045 if (suspense.deps === 0) {
3046 suspense.resolve();
3047 }
3048 return result;
3049 /* eslint-enable no-restricted-globals */
3050 }
3051 function normalizeSuspenseChildren(vnode) {
3052 const { shapeFlag, children } = vnode;
3053 const isSlotChildren = shapeFlag & 32 /* SLOTS_CHILDREN */;
3054 vnode.ssContent = normalizeSuspenseSlot(isSlotChildren ? children.default : children);
3055 vnode.ssFallback = isSlotChildren
3056 ? normalizeSuspenseSlot(children.fallback)
3057 : createVNode(Comment);
3058 }
3059 function normalizeSuspenseSlot(s) {
3060 let block;
3061 if (isFunction(s)) {
3062 const isCompiledSlot = s._c;
3063 if (isCompiledSlot) {
3064 // disableTracking: false
3065 // allow block tracking for compiled slots
3066 // (see ./componentRenderContext.ts)
3067 s._d = false;
3068 openBlock();
3069 }
3070 s = s();
3071 if (isCompiledSlot) {
3072 s._d = true;
3073 block = currentBlock;
3074 closeBlock();
3075 }
3076 }
3077 if (isArray(s)) {
3078 const singleChild = filterSingleRoot(s);
3079 if (!singleChild) {
3080 warn(`<Suspense> slots expect a single root node.`);
3081 }
3082 s = singleChild;
3083 }
3084 s = normalizeVNode(s);
3085 if (block) {
3086 s.dynamicChildren = block.filter(c => c !== s);
3087 }
3088 return s;
3089 }
3090 function queueEffectWithSuspense(fn, suspense) {
3091 if (suspense && suspense.pendingBranch) {
3092 if (isArray(fn)) {
3093 suspense.effects.push(...fn);
3094 }
3095 else {
3096 suspense.effects.push(fn);
3097 }
3098 }
3099 else {
3100 queuePostFlushCb(fn);
3101 }
3102 }
3103 function setActiveBranch(suspense, branch) {
3104 suspense.activeBranch = branch;
3105 const { vnode, parentComponent } = suspense;
3106 const el = (vnode.el = branch.el);
3107 // in case suspense is the root node of a component,
3108 // recursively update the HOC el
3109 if (parentComponent && parentComponent.subTree === vnode) {
3110 parentComponent.vnode.el = el;
3111 updateHOCHostEl(parentComponent, el);
3112 }
3113 }
3114
3115 function provide(key, value) {
3116 if (!currentInstance) {
3117 {
3118 warn(`provide() can only be used inside setup().`);
3119 }
3120 }
3121 else {
3122 let provides = currentInstance.provides;
3123 // by default an instance inherits its parent's provides object
3124 // but when it needs to provide values of its own, it creates its
3125 // own provides object using parent provides object as prototype.
3126 // this way in `inject` we can simply look up injections from direct
3127 // parent and let the prototype chain do the work.
3128 const parentProvides = currentInstance.parent && currentInstance.parent.provides;
3129 if (parentProvides === provides) {
3130 provides = currentInstance.provides = Object.create(parentProvides);
3131 }
3132 // TS doesn't allow symbol as index type
3133 provides[key] = value;
3134 }
3135 }
3136 function inject(key, defaultValue, treatDefaultAsFactory = false) {
3137 // fallback to `currentRenderingInstance` so that this can be called in
3138 // a functional component
3139 const instance = currentInstance || currentRenderingInstance;
3140 if (instance) {
3141 // #2400
3142 // to support `app.use` plugins,
3143 // fallback to appContext's `provides` if the intance is at root
3144 const provides = instance.parent == null
3145 ? instance.vnode.appContext && instance.vnode.appContext.provides
3146 : instance.parent.provides;
3147 if (provides && key in provides) {
3148 // TS doesn't allow symbol as index type
3149 return provides[key];
3150 }
3151 else if (arguments.length > 1) {
3152 return treatDefaultAsFactory && isFunction(defaultValue)
3153 ? defaultValue()
3154 : defaultValue;
3155 }
3156 else {
3157 warn(`injection "${String(key)}" not found.`);
3158 }
3159 }
3160 else {
3161 warn(`inject() can only be used inside setup() or functional components.`);
3162 }
3163 }
3164
3165 // Simple effect.
3166 function watchEffect(effect, options) {
3167 return doWatch(effect, null, options);
3168 }
3169 // initial value for watchers to trigger on undefined initial values
3170 const INITIAL_WATCHER_VALUE = {};
3171 // implementation
3172 function watch(source, cb, options) {
3173 if (!isFunction(cb)) {
3174 warn(`\`watch(fn, options?)\` signature has been moved to a separate API. ` +
3175 `Use \`watchEffect(fn, options?)\` instead. \`watch\` now only ` +
3176 `supports \`watch(source, cb, options?) signature.`);
3177 }
3178 return doWatch(source, cb, options);
3179 }
3180 function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ, instance = currentInstance) {
3181 if (!cb) {
3182 if (immediate !== undefined) {
3183 warn(`watch() "immediate" option is only respected when using the ` +
3184 `watch(source, callback, options?) signature.`);
3185 }
3186 if (deep !== undefined) {
3187 warn(`watch() "deep" option is only respected when using the ` +
3188 `watch(source, callback, options?) signature.`);
3189 }
3190 }
3191 const warnInvalidSource = (s) => {
3192 warn(`Invalid watch source: `, s, `A watch source can only be a getter/effect function, a ref, ` +
3193 `a reactive object, or an array of these types.`);
3194 };
3195 let getter;
3196 let forceTrigger = false;
3197 let isMultiSource = false;
3198 if (isRef(source)) {
3199 getter = () => source.value;
3200 forceTrigger = !!source._shallow;
3201 }
3202 else if (isReactive(source)) {
3203 getter = () => source;
3204 deep = true;
3205 }
3206 else if (isArray(source)) {
3207 isMultiSource = true;
3208 forceTrigger = source.some(isReactive);
3209 getter = () => source.map(s => {
3210 if (isRef(s)) {
3211 return s.value;
3212 }
3213 else if (isReactive(s)) {
3214 return traverse(s);
3215 }
3216 else if (isFunction(s)) {
3217 return callWithErrorHandling(s, instance, 2 /* WATCH_GETTER */);
3218 }
3219 else {
3220 warnInvalidSource(s);
3221 }
3222 });
3223 }
3224 else if (isFunction(source)) {
3225 if (cb) {
3226 // getter with cb
3227 getter = () => callWithErrorHandling(source, instance, 2 /* WATCH_GETTER */);
3228 }
3229 else {
3230 // no cb -> simple effect
3231 getter = () => {
3232 if (instance && instance.isUnmounted) {
3233 return;
3234 }
3235 if (cleanup) {
3236 cleanup();
3237 }
3238 return callWithAsyncErrorHandling(source, instance, 3 /* WATCH_CALLBACK */, [onInvalidate]);
3239 };
3240 }
3241 }
3242 else {
3243 getter = NOOP;
3244 warnInvalidSource(source);
3245 }
3246 if (cb && deep) {
3247 const baseGetter = getter;
3248 getter = () => traverse(baseGetter());
3249 }
3250 let cleanup;
3251 let onInvalidate = (fn) => {
3252 cleanup = runner.options.onStop = () => {
3253 callWithErrorHandling(fn, instance, 4 /* WATCH_CLEANUP */);
3254 };
3255 };
3256 let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE;
3257 const job = () => {
3258 if (!runner.active) {
3259 return;
3260 }
3261 if (cb) {
3262 // watch(source, cb)
3263 const newValue = runner();
3264 if (deep ||
3265 forceTrigger ||
3266 (isMultiSource
3267 ? newValue.some((v, i) => hasChanged(v, oldValue[i]))
3268 : hasChanged(newValue, oldValue)) ||
3269 (false )) {
3270 // cleanup before running cb again
3271 if (cleanup) {
3272 cleanup();
3273 }
3274 callWithAsyncErrorHandling(cb, instance, 3 /* WATCH_CALLBACK */, [
3275 newValue,
3276 // pass undefined as the old value when it's changed for the first time
3277 oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
3278 onInvalidate
3279 ]);
3280 oldValue = newValue;
3281 }
3282 }
3283 else {
3284 // watchEffect
3285 runner();
3286 }
3287 };
3288 // important: mark the job as a watcher callback so that scheduler knows
3289 // it is allowed to self-trigger (#1727)
3290 job.allowRecurse = !!cb;
3291 let scheduler;
3292 if (flush === 'sync') {
3293 scheduler = job; // the scheduler function gets called directly
3294 }
3295 else if (flush === 'post') {
3296 scheduler = () => queuePostRenderEffect(job, instance && instance.suspense);
3297 }
3298 else {
3299 // default: 'pre'
3300 scheduler = () => {
3301 if (!instance || instance.isMounted) {
3302 queuePreFlushCb(job);
3303 }
3304 else {
3305 // with 'pre' option, the first call must happen before
3306 // the component is mounted so it is called synchronously.
3307 job();
3308 }
3309 };
3310 }
3311 const runner = effect(getter, {
3312 lazy: true,
3313 onTrack,
3314 onTrigger,
3315 scheduler
3316 });
3317 recordInstanceBoundEffect(runner, instance);
3318 // initial run
3319 if (cb) {
3320 if (immediate) {
3321 job();
3322 }
3323 else {
3324 oldValue = runner();
3325 }
3326 }
3327 else if (flush === 'post') {
3328 queuePostRenderEffect(runner, instance && instance.suspense);
3329 }
3330 else {
3331 runner();
3332 }
3333 return () => {
3334 stop(runner);
3335 if (instance) {
3336 remove(instance.effects, runner);
3337 }
3338 };
3339 }
3340 // this.$watch
3341 function instanceWatch(source, value, options) {
3342 const publicThis = this.proxy;
3343 const getter = isString(source)
3344 ? source.includes('.')
3345 ? createPathGetter(publicThis, source)
3346 : () => publicThis[source]
3347 : source.bind(publicThis, publicThis);
3348 let cb;
3349 if (isFunction(value)) {
3350 cb = value;
3351 }
3352 else {
3353 cb = value.handler;
3354 options = value;
3355 }
3356 return doWatch(getter, cb.bind(publicThis), options, this);
3357 }
3358 function createPathGetter(ctx, path) {
3359 const segments = path.split('.');
3360 return () => {
3361 let cur = ctx;
3362 for (let i = 0; i < segments.length && cur; i++) {
3363 cur = cur[segments[i]];
3364 }
3365 return cur;
3366 };
3367 }
3368 function traverse(value, seen = new Set()) {
3369 if (!isObject(value) ||
3370 seen.has(value) ||
3371 value["__v_skip" /* SKIP */]) {
3372 return value;
3373 }
3374 seen.add(value);
3375 if (isRef(value)) {
3376 traverse(value.value, seen);
3377 }
3378 else if (isArray(value)) {
3379 for (let i = 0; i < value.length; i++) {
3380 traverse(value[i], seen);
3381 }
3382 }
3383 else if (isSet(value) || isMap(value)) {
3384 value.forEach((v) => {
3385 traverse(v, seen);
3386 });
3387 }
3388 else if (isPlainObject(value)) {
3389 for (const key in value) {
3390 traverse(value[key], seen);
3391 }
3392 }
3393 return value;
3394 }
3395
3396 function useTransitionState() {
3397 const state = {
3398 isMounted: false,
3399 isLeaving: false,
3400 isUnmounting: false,
3401 leavingVNodes: new Map()
3402 };
3403 onMounted(() => {
3404 state.isMounted = true;
3405 });
3406 onBeforeUnmount(() => {
3407 state.isUnmounting = true;
3408 });
3409 return state;
3410 }
3411 const TransitionHookValidator = [Function, Array];
3412 const BaseTransitionImpl = {
3413 name: `BaseTransition`,
3414 props: {
3415 mode: String,
3416 appear: Boolean,
3417 persisted: Boolean,
3418 // enter
3419 onBeforeEnter: TransitionHookValidator,
3420 onEnter: TransitionHookValidator,
3421 onAfterEnter: TransitionHookValidator,
3422 onEnterCancelled: TransitionHookValidator,
3423 // leave
3424 onBeforeLeave: TransitionHookValidator,
3425 onLeave: TransitionHookValidator,
3426 onAfterLeave: TransitionHookValidator,
3427 onLeaveCancelled: TransitionHookValidator,
3428 // appear
3429 onBeforeAppear: TransitionHookValidator,
3430 onAppear: TransitionHookValidator,
3431 onAfterAppear: TransitionHookValidator,
3432 onAppearCancelled: TransitionHookValidator
3433 },
3434 setup(props, { slots }) {
3435 const instance = getCurrentInstance();
3436 const state = useTransitionState();
3437 let prevTransitionKey;
3438 return () => {
3439 const children = slots.default && getTransitionRawChildren(slots.default(), true);
3440 if (!children || !children.length) {
3441 return;
3442 }
3443 // warn multiple elements
3444 if (children.length > 1) {
3445 warn('<transition> can only be used on a single element or component. Use ' +
3446 '<transition-group> for lists.');
3447 }
3448 // there's no need to track reactivity for these props so use the raw
3449 // props for a bit better perf
3450 const rawProps = toRaw(props);
3451 const { mode } = rawProps;
3452 // check mode
3453 if (mode && !['in-out', 'out-in', 'default'].includes(mode)) {
3454 warn(`invalid <transition> mode: ${mode}`);
3455 }
3456 // at this point children has a guaranteed length of 1.
3457 const child = children[0];
3458 if (state.isLeaving) {
3459 return emptyPlaceholder(child);
3460 }
3461 // in the case of <transition><keep-alive/></transition>, we need to
3462 // compare the type of the kept-alive children.
3463 const innerChild = getKeepAliveChild(child);
3464 if (!innerChild) {
3465 return emptyPlaceholder(child);
3466 }
3467 const enterHooks = resolveTransitionHooks(innerChild, rawProps, state, instance);
3468 setTransitionHooks(innerChild, enterHooks);
3469 const oldChild = instance.subTree;
3470 const oldInnerChild = oldChild && getKeepAliveChild(oldChild);
3471 let transitionKeyChanged = false;
3472 const { getTransitionKey } = innerChild.type;
3473 if (getTransitionKey) {
3474 const key = getTransitionKey();
3475 if (prevTransitionKey === undefined) {
3476 prevTransitionKey = key;
3477 }
3478 else if (key !== prevTransitionKey) {
3479 prevTransitionKey = key;
3480 transitionKeyChanged = true;
3481 }
3482 }
3483 // handle mode
3484 if (oldInnerChild &&
3485 oldInnerChild.type !== Comment$1 &&
3486 (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) {
3487 const leavingHooks = resolveTransitionHooks(oldInnerChild, rawProps, state, instance);
3488 // update old tree's hooks in case of dynamic transition
3489 setTransitionHooks(oldInnerChild, leavingHooks);
3490 // switching between different views
3491 if (mode === 'out-in') {
3492 state.isLeaving = true;
3493 // return placeholder node and queue update when leave finishes
3494 leavingHooks.afterLeave = () => {
3495 state.isLeaving = false;
3496 instance.update();
3497 };
3498 return emptyPlaceholder(child);
3499 }
3500 else if (mode === 'in-out' && innerChild.type !== Comment$1) {
3501 leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => {
3502 const leavingVNodesCache = getLeavingNodesForType(state, oldInnerChild);
3503 leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild;
3504 // early removal callback
3505 el._leaveCb = () => {
3506 earlyRemove();
3507 el._leaveCb = undefined;
3508 delete enterHooks.delayedLeave;
3509 };
3510 enterHooks.delayedLeave = delayedLeave;
3511 };
3512 }
3513 }
3514 return child;
3515 };
3516 }
3517 };
3518 // export the public type for h/tsx inference
3519 // also to avoid inline import() in generated d.ts files
3520 const BaseTransition = BaseTransitionImpl;
3521 function getLeavingNodesForType(state, vnode) {
3522 const { leavingVNodes } = state;
3523 let leavingVNodesCache = leavingVNodes.get(vnode.type);
3524 if (!leavingVNodesCache) {
3525 leavingVNodesCache = Object.create(null);
3526 leavingVNodes.set(vnode.type, leavingVNodesCache);
3527 }
3528 return leavingVNodesCache;
3529 }
3530 // The transition hooks are attached to the vnode as vnode.transition
3531 // and will be called at appropriate timing in the renderer.
3532 function resolveTransitionHooks(vnode, props, state, instance) {
3533 const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props;
3534 const key = String(vnode.key);
3535 const leavingVNodesCache = getLeavingNodesForType(state, vnode);
3536 const callHook = (hook, args) => {
3537 hook &&
3538 callWithAsyncErrorHandling(hook, instance, 9 /* TRANSITION_HOOK */, args);
3539 };
3540 const hooks = {
3541 mode,
3542 persisted,
3543 beforeEnter(el) {
3544 let hook = onBeforeEnter;
3545 if (!state.isMounted) {
3546 if (appear) {
3547 hook = onBeforeAppear || onBeforeEnter;
3548 }
3549 else {
3550 return;
3551 }
3552 }
3553 // for same element (v-show)
3554 if (el._leaveCb) {
3555 el._leaveCb(true /* cancelled */);
3556 }
3557 // for toggled element with same key (v-if)
3558 const leavingVNode = leavingVNodesCache[key];
3559 if (leavingVNode &&
3560 isSameVNodeType(vnode, leavingVNode) &&
3561 leavingVNode.el._leaveCb) {
3562 // force early removal (not cancelled)
3563 leavingVNode.el._leaveCb();
3564 }
3565 callHook(hook, [el]);
3566 },
3567 enter(el) {
3568 let hook = onEnter;
3569 let afterHook = onAfterEnter;
3570 let cancelHook = onEnterCancelled;
3571 if (!state.isMounted) {
3572 if (appear) {
3573 hook = onAppear || onEnter;
3574 afterHook = onAfterAppear || onAfterEnter;
3575 cancelHook = onAppearCancelled || onEnterCancelled;
3576 }
3577 else {
3578 return;
3579 }
3580 }
3581 let called = false;
3582 const done = (el._enterCb = (cancelled) => {
3583 if (called)
3584 return;
3585 called = true;
3586 if (cancelled) {
3587 callHook(cancelHook, [el]);
3588 }
3589 else {
3590 callHook(afterHook, [el]);
3591 }
3592 if (hooks.delayedLeave) {
3593 hooks.delayedLeave();
3594 }
3595 el._enterCb = undefined;
3596 });
3597 if (hook) {
3598 hook(el, done);
3599 if (hook.length <= 1) {
3600 done();
3601 }
3602 }
3603 else {
3604 done();
3605 }
3606 },
3607 leave(el, remove) {
3608 const key = String(vnode.key);
3609 if (el._enterCb) {
3610 el._enterCb(true /* cancelled */);
3611 }
3612 if (state.isUnmounting) {
3613 return remove();
3614 }
3615 callHook(onBeforeLeave, [el]);
3616 let called = false;
3617 const done = (el._leaveCb = (cancelled) => {
3618 if (called)
3619 return;
3620 called = true;
3621 remove();
3622 if (cancelled) {
3623 callHook(onLeaveCancelled, [el]);
3624 }
3625 else {
3626 callHook(onAfterLeave, [el]);
3627 }
3628 el._leaveCb = undefined;
3629 if (leavingVNodesCache[key] === vnode) {
3630 delete leavingVNodesCache[key];
3631 }
3632 });
3633 leavingVNodesCache[key] = vnode;
3634 if (onLeave) {
3635 onLeave(el, done);
3636 if (onLeave.length <= 1) {
3637 done();
3638 }
3639 }
3640 else {
3641 done();
3642 }
3643 },
3644 clone(vnode) {
3645 return resolveTransitionHooks(vnode, props, state, instance);
3646 }
3647 };
3648 return hooks;
3649 }
3650 // the placeholder really only handles one special case: KeepAlive
3651 // in the case of a KeepAlive in a leave phase we need to return a KeepAlive
3652 // placeholder with empty content to avoid the KeepAlive instance from being
3653 // unmounted.
3654 function emptyPlaceholder(vnode) {
3655 if (isKeepAlive(vnode)) {
3656 vnode = cloneVNode(vnode);
3657 vnode.children = null;
3658 return vnode;
3659 }
3660 }
3661 function getKeepAliveChild(vnode) {
3662 return isKeepAlive(vnode)
3663 ? vnode.children
3664 ? vnode.children[0]
3665 : undefined
3666 : vnode;
3667 }
3668 function setTransitionHooks(vnode, hooks) {
3669 if (vnode.shapeFlag & 6 /* COMPONENT */ && vnode.component) {
3670 setTransitionHooks(vnode.component.subTree, hooks);
3671 }
3672 else if (vnode.shapeFlag & 128 /* SUSPENSE */) {
3673 vnode.ssContent.transition = hooks.clone(vnode.ssContent);
3674 vnode.ssFallback.transition = hooks.clone(vnode.ssFallback);
3675 }
3676 else {
3677 vnode.transition = hooks;
3678 }
3679 }
3680 function getTransitionRawChildren(children, keepComment = false) {
3681 let ret = [];
3682 let keyedFragmentCount = 0;
3683 for (let i = 0; i < children.length; i++) {
3684 const child = children[i];
3685 // handle fragment children case, e.g. v-for
3686 if (child.type === Fragment) {
3687 if (child.patchFlag & 128 /* KEYED_FRAGMENT */)
3688 keyedFragmentCount++;
3689 ret = ret.concat(getTransitionRawChildren(child.children, keepComment));
3690 }
3691 // comment placeholders should be skipped, e.g. v-if
3692 else if (keepComment || child.type !== Comment$1) {
3693 ret.push(child);
3694 }
3695 }
3696 // #1126 if a transition children list contains multiple sub fragments, these
3697 // fragments will be merged into a flat children array. Since each v-for
3698 // fragment may contain different static bindings inside, we need to de-op
3699 // these children to force full diffs to ensure correct behavior.
3700 if (keyedFragmentCount > 1) {
3701 for (let i = 0; i < ret.length; i++) {
3702 ret[i].patchFlag = -2 /* BAIL */;
3703 }
3704 }
3705 return ret;
3706 }
3707
3708 // implementation, close to no-op
3709 function defineComponent(options) {
3710 return isFunction(options) ? { setup: options, name: options.name } : options;
3711 }
3712
3713 const isAsyncWrapper = (i) => !!i.type.__asyncLoader;
3714 function defineAsyncComponent(source) {
3715 if (isFunction(source)) {
3716 source = { loader: source };
3717 }
3718 const { loader, loadingComponent, errorComponent, delay = 200, timeout, // undefined = never times out
3719 suspensible = true, onError: userOnError } = source;
3720 let pendingRequest = null;
3721 let resolvedComp;
3722 let retries = 0;
3723 const retry = () => {
3724 retries++;
3725 pendingRequest = null;
3726 return load();
3727 };
3728 const load = () => {
3729 let thisRequest;
3730 return (pendingRequest ||
3731 (thisRequest = pendingRequest = loader()
3732 .catch(err => {
3733 err = err instanceof Error ? err : new Error(String(err));
3734 if (userOnError) {
3735 return new Promise((resolve, reject) => {
3736 const userRetry = () => resolve(retry());
3737 const userFail = () => reject(err);
3738 userOnError(err, userRetry, userFail, retries + 1);
3739 });
3740 }
3741 else {
3742 throw err;
3743 }
3744 })
3745 .then((comp) => {
3746 if (thisRequest !== pendingRequest && pendingRequest) {
3747 return pendingRequest;
3748 }
3749 if (!comp) {
3750 warn(`Async component loader resolved to undefined. ` +
3751 `If you are using retry(), make sure to return its return value.`);
3752 }
3753 // interop module default
3754 if (comp &&
3755 (comp.__esModule || comp[Symbol.toStringTag] === 'Module')) {
3756 comp = comp.default;
3757 }
3758 if (comp && !isObject(comp) && !isFunction(comp)) {
3759 throw new Error(`Invalid async component load result: ${comp}`);
3760 }
3761 resolvedComp = comp;
3762 return comp;
3763 })));
3764 };
3765 return defineComponent({
3766 name: 'AsyncComponentWrapper',
3767 __asyncLoader: load,
3768 get __asyncResolved() {
3769 return resolvedComp;
3770 },
3771 setup() {
3772 const instance = currentInstance;
3773 // already resolved
3774 if (resolvedComp) {
3775 return () => createInnerComp(resolvedComp, instance);
3776 }
3777 const onError = (err) => {
3778 pendingRequest = null;
3779 handleError(err, instance, 13 /* ASYNC_COMPONENT_LOADER */, !errorComponent /* do not throw in dev if user provided error component */);
3780 };
3781 // suspense-controlled or SSR.
3782 if ((suspensible && instance.suspense) ||
3783 (false )) {
3784 return load()
3785 .then(comp => {
3786 return () => createInnerComp(comp, instance);
3787 })
3788 .catch(err => {
3789 onError(err);
3790 return () => errorComponent
3791 ? createVNode(errorComponent, {
3792 error: err
3793 })
3794 : null;
3795 });
3796 }
3797 const loaded = ref(false);
3798 const error = ref();
3799 const delayed = ref(!!delay);
3800 if (delay) {
3801 setTimeout(() => {
3802 delayed.value = false;
3803 }, delay);
3804 }
3805 if (timeout != null) {
3806 setTimeout(() => {
3807 if (!loaded.value && !error.value) {
3808 const err = new Error(`Async component timed out after ${timeout}ms.`);
3809 onError(err);
3810 error.value = err;
3811 }
3812 }, timeout);
3813 }
3814 load()
3815 .then(() => {
3816 loaded.value = true;
3817 if (instance.parent && isKeepAlive(instance.parent.vnode)) {
3818 // parent is keep-alive, force update so the loaded component's
3819 // name is taken into account
3820 queueJob(instance.parent.update);
3821 }
3822 })
3823 .catch(err => {
3824 onError(err);
3825 error.value = err;
3826 });
3827 return () => {
3828 if (loaded.value && resolvedComp) {
3829 return createInnerComp(resolvedComp, instance);
3830 }
3831 else if (error.value && errorComponent) {
3832 return createVNode(errorComponent, {
3833 error: error.value
3834 });
3835 }
3836 else if (loadingComponent && !delayed.value) {
3837 return createVNode(loadingComponent);
3838 }
3839 };
3840 }
3841 });
3842 }
3843 function createInnerComp(comp, { vnode: { ref, props, children } }) {
3844 const vnode = createVNode(comp, props, children);
3845 // ensure inner component inherits the async wrapper's ref owner
3846 vnode.ref = ref;
3847 return vnode;
3848 }
3849
3850 const isKeepAlive = (vnode) => vnode.type.__isKeepAlive;
3851 const KeepAliveImpl = {
3852 name: `KeepAlive`,
3853 // Marker for special handling inside the renderer. We are not using a ===
3854 // check directly on KeepAlive in the renderer, because importing it directly
3855 // would prevent it from being tree-shaken.
3856 __isKeepAlive: true,
3857 props: {
3858 include: [String, RegExp, Array],
3859 exclude: [String, RegExp, Array],
3860 max: [String, Number]
3861 },
3862 setup(props, { slots }) {
3863 const instance = getCurrentInstance();
3864 // KeepAlive communicates with the instantiated renderer via the
3865 // ctx where the renderer passes in its internals,
3866 // and the KeepAlive instance exposes activate/deactivate implementations.
3867 // The whole point of this is to avoid importing KeepAlive directly in the
3868 // renderer to facilitate tree-shaking.
3869 const sharedContext = instance.ctx;
3870 // if the internal renderer is not registered, it indicates that this is server-side rendering,
3871 // for KeepAlive, we just need to render its children
3872 if (!sharedContext.renderer) {
3873 return slots.default;
3874 }
3875 const cache = new Map();
3876 const keys = new Set();
3877 let current = null;
3878 {
3879 instance.__v_cache = cache;
3880 }
3881 const parentSuspense = instance.suspense;
3882 const { renderer: { p: patch, m: move, um: _unmount, o: { createElement } } } = sharedContext;
3883 const storageContainer = createElement('div');
3884 sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => {
3885 const instance = vnode.component;
3886 move(vnode, container, anchor, 0 /* ENTER */, parentSuspense);
3887 // in case props have changed
3888 patch(instance.vnode, vnode, container, anchor, instance, parentSuspense, isSVG, vnode.slotScopeIds, optimized);
3889 queuePostRenderEffect(() => {
3890 instance.isDeactivated = false;
3891 if (instance.a) {
3892 invokeArrayFns(instance.a);
3893 }
3894 const vnodeHook = vnode.props && vnode.props.onVnodeMounted;
3895 if (vnodeHook) {
3896 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3897 }
3898 }, parentSuspense);
3899 {
3900 // Update components tree
3901 devtoolsComponentAdded(instance);
3902 }
3903 };
3904 sharedContext.deactivate = (vnode) => {
3905 const instance = vnode.component;
3906 move(vnode, storageContainer, null, 1 /* LEAVE */, parentSuspense);
3907 queuePostRenderEffect(() => {
3908 if (instance.da) {
3909 invokeArrayFns(instance.da);
3910 }
3911 const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted;
3912 if (vnodeHook) {
3913 invokeVNodeHook(vnodeHook, instance.parent, vnode);
3914 }
3915 instance.isDeactivated = true;
3916 }, parentSuspense);
3917 {
3918 // Update components tree
3919 devtoolsComponentAdded(instance);
3920 }
3921 };
3922 function unmount(vnode) {
3923 // reset the shapeFlag so it can be properly unmounted
3924 resetShapeFlag(vnode);
3925 _unmount(vnode, instance, parentSuspense);
3926 }
3927 function pruneCache(filter) {
3928 cache.forEach((vnode, key) => {
3929 const name = getComponentName(vnode.type);
3930 if (name && (!filter || !filter(name))) {
3931 pruneCacheEntry(key);
3932 }
3933 });
3934 }
3935 function pruneCacheEntry(key) {
3936 const cached = cache.get(key);
3937 if (!current || cached.type !== current.type) {
3938 unmount(cached);
3939 }
3940 else if (current) {
3941 // current active instance should no longer be kept-alive.
3942 // we can't unmount it now but it might be later, so reset its flag now.
3943 resetShapeFlag(current);
3944 }
3945 cache.delete(key);
3946 keys.delete(key);
3947 }
3948 // prune cache on include/exclude prop change
3949 watch(() => [props.include, props.exclude], ([include, exclude]) => {
3950 include && pruneCache(name => matches(include, name));
3951 exclude && pruneCache(name => !matches(exclude, name));
3952 },
3953 // prune post-render after `current` has been updated
3954 { flush: 'post', deep: true });
3955 // cache sub tree after render
3956 let pendingCacheKey = null;
3957 const cacheSubtree = () => {
3958 // fix #1621, the pendingCacheKey could be 0
3959 if (pendingCacheKey != null) {
3960 cache.set(pendingCacheKey, getInnerChild(instance.subTree));
3961 }
3962 };
3963 onMounted(cacheSubtree);
3964 onUpdated(cacheSubtree);
3965 onBeforeUnmount(() => {
3966 cache.forEach(cached => {
3967 const { subTree, suspense } = instance;
3968 const vnode = getInnerChild(subTree);
3969 if (cached.type === vnode.type) {
3970 // current instance will be unmounted as part of keep-alive's unmount
3971 resetShapeFlag(vnode);
3972 // but invoke its deactivated hook here
3973 const da = vnode.component.da;
3974 da && queuePostRenderEffect(da, suspense);
3975 return;
3976 }
3977 unmount(cached);
3978 });
3979 });
3980 return () => {
3981 pendingCacheKey = null;
3982 if (!slots.default) {
3983 return null;
3984 }
3985 const children = slots.default();
3986 const rawVNode = children[0];
3987 if (children.length > 1) {
3988 {
3989 warn(`KeepAlive should contain exactly one component child.`);
3990 }
3991 current = null;
3992 return children;
3993 }
3994 else if (!isVNode(rawVNode) ||
3995 (!(rawVNode.shapeFlag & 4 /* STATEFUL_COMPONENT */) &&
3996 !(rawVNode.shapeFlag & 128 /* SUSPENSE */))) {
3997 current = null;
3998 return rawVNode;
3999 }
4000 let vnode = getInnerChild(rawVNode);
4001 const comp = vnode.type;
4002 // for async components, name check should be based in its loaded
4003 // inner component if available
4004 const name = getComponentName(isAsyncWrapper(vnode)
4005 ? vnode.type.__asyncResolved || {}
4006 : comp);
4007 const { include, exclude, max } = props;
4008 if ((include && (!name || !matches(include, name))) ||
4009 (exclude && name && matches(exclude, name))) {
4010 current = vnode;
4011 return rawVNode;
4012 }
4013 const key = vnode.key == null ? comp : vnode.key;
4014 const cachedVNode = cache.get(key);
4015 // clone vnode if it's reused because we are going to mutate it
4016 if (vnode.el) {
4017 vnode = cloneVNode(vnode);
4018 if (rawVNode.shapeFlag & 128 /* SUSPENSE */) {
4019 rawVNode.ssContent = vnode;
4020 }
4021 }
4022 // #1513 it's possible for the returned vnode to be cloned due to attr
4023 // fallthrough or scopeId, so the vnode here may not be the final vnode
4024 // that is mounted. Instead of caching it directly, we store the pending
4025 // key and cache `instance.subTree` (the normalized vnode) in
4026 // beforeMount/beforeUpdate hooks.
4027 pendingCacheKey = key;
4028 if (cachedVNode) {
4029 // copy over mounted state
4030 vnode.el = cachedVNode.el;
4031 vnode.component = cachedVNode.component;
4032 if (vnode.transition) {
4033 // recursively update transition hooks on subTree
4034 setTransitionHooks(vnode, vnode.transition);
4035 }
4036 // avoid vnode being mounted as fresh
4037 vnode.shapeFlag |= 512 /* COMPONENT_KEPT_ALIVE */;
4038 // make this key the freshest
4039 keys.delete(key);
4040 keys.add(key);
4041 }
4042 else {
4043 keys.add(key);
4044 // prune oldest entry
4045 if (max && keys.size > parseInt(max, 10)) {
4046 pruneCacheEntry(keys.values().next().value);
4047 }
4048 }
4049 // avoid vnode being unmounted
4050 vnode.shapeFlag |= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4051 current = vnode;
4052 return rawVNode;
4053 };
4054 }
4055 };
4056 // export the public type for h/tsx inference
4057 // also to avoid inline import() in generated d.ts files
4058 const KeepAlive = KeepAliveImpl;
4059 function matches(pattern, name) {
4060 if (isArray(pattern)) {
4061 return pattern.some((p) => matches(p, name));
4062 }
4063 else if (isString(pattern)) {
4064 return pattern.split(',').indexOf(name) > -1;
4065 }
4066 else if (pattern.test) {
4067 return pattern.test(name);
4068 }
4069 /* istanbul ignore next */
4070 return false;
4071 }
4072 function onActivated(hook, target) {
4073 registerKeepAliveHook(hook, "a" /* ACTIVATED */, target);
4074 }
4075 function onDeactivated(hook, target) {
4076 registerKeepAliveHook(hook, "da" /* DEACTIVATED */, target);
4077 }
4078 function registerKeepAliveHook(hook, type, target = currentInstance) {
4079 // cache the deactivate branch check wrapper for injected hooks so the same
4080 // hook can be properly deduped by the scheduler. "__wdc" stands for "with
4081 // deactivation check".
4082 const wrappedHook = hook.__wdc ||
4083 (hook.__wdc = () => {
4084 // only fire the hook if the target instance is NOT in a deactivated branch.
4085 let current = target;
4086 while (current) {
4087 if (current.isDeactivated) {
4088 return;
4089 }
4090 current = current.parent;
4091 }
4092 hook();
4093 });
4094 injectHook(type, wrappedHook, target);
4095 // In addition to registering it on the target instance, we walk up the parent
4096 // chain and register it on all ancestor instances that are keep-alive roots.
4097 // This avoids the need to walk the entire component tree when invoking these
4098 // hooks, and more importantly, avoids the need to track child components in
4099 // arrays.
4100 if (target) {
4101 let current = target.parent;
4102 while (current && current.parent) {
4103 if (isKeepAlive(current.parent.vnode)) {
4104 injectToKeepAliveRoot(wrappedHook, type, target, current);
4105 }
4106 current = current.parent;
4107 }
4108 }
4109 }
4110 function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) {
4111 // injectHook wraps the original for error handling, so make sure to remove
4112 // the wrapped version.
4113 const injected = injectHook(type, hook, keepAliveRoot, true /* prepend */);
4114 onUnmounted(() => {
4115 remove(keepAliveRoot[type], injected);
4116 }, target);
4117 }
4118 function resetShapeFlag(vnode) {
4119 let shapeFlag = vnode.shapeFlag;
4120 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
4121 shapeFlag -= 256 /* COMPONENT_SHOULD_KEEP_ALIVE */;
4122 }
4123 if (shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
4124 shapeFlag -= 512 /* COMPONENT_KEPT_ALIVE */;
4125 }
4126 vnode.shapeFlag = shapeFlag;
4127 }
4128 function getInnerChild(vnode) {
4129 return vnode.shapeFlag & 128 /* SUSPENSE */ ? vnode.ssContent : vnode;
4130 }
4131
4132 function injectHook(type, hook, target = currentInstance, prepend = false) {
4133 if (target) {
4134 const hooks = target[type] || (target[type] = []);
4135 // cache the error handling wrapper for injected hooks so the same hook
4136 // can be properly deduped by the scheduler. "__weh" stands for "with error
4137 // handling".
4138 const wrappedHook = hook.__weh ||
4139 (hook.__weh = (...args) => {
4140 if (target.isUnmounted) {
4141 return;
4142 }
4143 // disable tracking inside all lifecycle hooks
4144 // since they can potentially be called inside effects.
4145 pauseTracking();
4146 // Set currentInstance during hook invocation.
4147 // This assumes the hook does not synchronously trigger other hooks, which
4148 // can only be false when the user does something really funky.
4149 setCurrentInstance(target);
4150 const res = callWithAsyncErrorHandling(hook, target, type, args);
4151 setCurrentInstance(null);
4152 resetTracking();
4153 return res;
4154 });
4155 if (prepend) {
4156 hooks.unshift(wrappedHook);
4157 }
4158 else {
4159 hooks.push(wrappedHook);
4160 }
4161 return wrappedHook;
4162 }
4163 else {
4164 const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, ''));
4165 warn(`${apiName} is called when there is no active component instance to be ` +
4166 `associated with. ` +
4167 `Lifecycle injection APIs can only be used during execution of setup().` +
4168 (` If you are using async setup(), make sure to register lifecycle ` +
4169 `hooks before the first await statement.`
4170 ));
4171 }
4172 }
4173 const createHook = (lifecycle) => (hook, target = currentInstance) =>
4174 // post-create lifecycle registrations are noops during SSR (except for serverPrefetch)
4175 (!isInSSRComponentSetup || lifecycle === "sp" /* SERVER_PREFETCH */) &&
4176 injectHook(lifecycle, hook, target);
4177 const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
4178 const onMounted = createHook("m" /* MOUNTED */);
4179 const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
4180 const onUpdated = createHook("u" /* UPDATED */);
4181 const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
4182 const onUnmounted = createHook("um" /* UNMOUNTED */);
4183 const onServerPrefetch = createHook("sp" /* SERVER_PREFETCH */);
4184 const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
4185 const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
4186 function onErrorCaptured(hook, target = currentInstance) {
4187 injectHook("ec" /* ERROR_CAPTURED */, hook, target);
4188 }
4189
4190 function createDuplicateChecker() {
4191 const cache = Object.create(null);
4192 return (type, key) => {
4193 if (cache[key]) {
4194 warn(`${type} property "${key}" is already defined in ${cache[key]}.`);
4195 }
4196 else {
4197 cache[key] = type;
4198 }
4199 };
4200 }
4201 let shouldCacheAccess = true;
4202 function applyOptions(instance) {
4203 const options = resolveMergedOptions(instance);
4204 const publicThis = instance.proxy;
4205 const ctx = instance.ctx;
4206 // do not cache property access on public proxy during state initialization
4207 shouldCacheAccess = false;
4208 // call beforeCreate first before accessing other options since
4209 // the hook may mutate resolved options (#2791)
4210 if (options.beforeCreate) {
4211 callHook(options.beforeCreate, instance, "bc" /* BEFORE_CREATE */);
4212 }
4213 const {
4214 // state
4215 data: dataOptions, computed: computedOptions, methods, watch: watchOptions, provide: provideOptions, inject: injectOptions,
4216 // lifecycle
4217 created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, beforeUnmount, destroyed, unmounted, render, renderTracked, renderTriggered, errorCaptured, serverPrefetch,
4218 // public API
4219 expose, inheritAttrs,
4220 // assets
4221 components, directives, filters } = options;
4222 const checkDuplicateProperties = createDuplicateChecker() ;
4223 {
4224 const [propsOptions] = instance.propsOptions;
4225 if (propsOptions) {
4226 for (const key in propsOptions) {
4227 checkDuplicateProperties("Props" /* PROPS */, key);
4228 }
4229 }
4230 }
4231 // options initialization order (to be consistent with Vue 2):
4232 // - props (already done outside of this function)
4233 // - inject
4234 // - methods
4235 // - data (deferred since it relies on `this` access)
4236 // - computed
4237 // - watch (deferred since it relies on `this` access)
4238 if (injectOptions) {
4239 resolveInjections(injectOptions, ctx, checkDuplicateProperties);
4240 }
4241 if (methods) {
4242 for (const key in methods) {
4243 const methodHandler = methods[key];
4244 if (isFunction(methodHandler)) {
4245 // In dev mode, we use the `createRenderContext` function to define methods to the proxy target,
4246 // and those are read-only but reconfigurable, so it needs to be redefined here
4247 {
4248 Object.defineProperty(ctx, key, {
4249 value: methodHandler.bind(publicThis),
4250 configurable: true,
4251 enumerable: true,
4252 writable: true
4253 });
4254 }
4255 {
4256 checkDuplicateProperties("Methods" /* METHODS */, key);
4257 }
4258 }
4259 else {
4260 warn(`Method "${key}" has type "${typeof methodHandler}" in the component definition. ` +
4261 `Did you reference the function correctly?`);
4262 }
4263 }
4264 }
4265 if (dataOptions) {
4266 if (!isFunction(dataOptions)) {
4267 warn(`The data option must be a function. ` +
4268 `Plain object usage is no longer supported.`);
4269 }
4270 const data = dataOptions.call(publicThis, publicThis);
4271 if (isPromise(data)) {
4272 warn(`data() returned a Promise - note data() cannot be async; If you ` +
4273 `intend to perform data fetching before component renders, use ` +
4274 `async setup() + <Suspense>.`);
4275 }
4276 if (!isObject(data)) {
4277 warn(`data() should return an object.`);
4278 }
4279 else {
4280 instance.data = reactive(data);
4281 {
4282 for (const key in data) {
4283 checkDuplicateProperties("Data" /* DATA */, key);
4284 // expose data on ctx during dev
4285 if (key[0] !== '$' && key[0] !== '_') {
4286 Object.defineProperty(ctx, key, {
4287 configurable: true,
4288 enumerable: true,
4289 get: () => data[key],
4290 set: NOOP
4291 });
4292 }
4293 }
4294 }
4295 }
4296 }
4297 // state initialization complete at this point - start caching access
4298 shouldCacheAccess = true;
4299 if (computedOptions) {
4300 for (const key in computedOptions) {
4301 const opt = computedOptions[key];
4302 const get = isFunction(opt)
4303 ? opt.bind(publicThis, publicThis)
4304 : isFunction(opt.get)
4305 ? opt.get.bind(publicThis, publicThis)
4306 : NOOP;
4307 if (get === NOOP) {
4308 warn(`Computed property "${key}" has no getter.`);
4309 }
4310 const set = !isFunction(opt) && isFunction(opt.set)
4311 ? opt.set.bind(publicThis)
4312 : () => {
4313 warn(`Write operation failed: computed property "${key}" is readonly.`);
4314 }
4315 ;
4316 const c = computed$1({
4317 get,
4318 set
4319 });
4320 Object.defineProperty(ctx, key, {
4321 enumerable: true,
4322 configurable: true,
4323 get: () => c.value,
4324 set: v => (c.value = v)
4325 });
4326 {
4327 checkDuplicateProperties("Computed" /* COMPUTED */, key);
4328 }
4329 }
4330 }
4331 if (watchOptions) {
4332 for (const key in watchOptions) {
4333 createWatcher(watchOptions[key], ctx, publicThis, key);
4334 }
4335 }
4336 if (provideOptions) {
4337 const provides = isFunction(provideOptions)
4338 ? provideOptions.call(publicThis)
4339 : provideOptions;
4340 Reflect.ownKeys(provides).forEach(key => {
4341 provide(key, provides[key]);
4342 });
4343 }
4344 if (created) {
4345 callHook(created, instance, "c" /* CREATED */);
4346 }
4347 function registerLifecycleHook(register, hook) {
4348 if (isArray(hook)) {
4349 hook.forEach(_hook => register(_hook.bind(publicThis)));
4350 }
4351 else if (hook) {
4352 register(hook.bind(publicThis));
4353 }
4354 }
4355 registerLifecycleHook(onBeforeMount, beforeMount);
4356 registerLifecycleHook(onMounted, mounted);
4357 registerLifecycleHook(onBeforeUpdate, beforeUpdate);
4358 registerLifecycleHook(onUpdated, updated);
4359 registerLifecycleHook(onActivated, activated);
4360 registerLifecycleHook(onDeactivated, deactivated);
4361 registerLifecycleHook(onErrorCaptured, errorCaptured);
4362 registerLifecycleHook(onRenderTracked, renderTracked);
4363 registerLifecycleHook(onRenderTriggered, renderTriggered);
4364 registerLifecycleHook(onBeforeUnmount, beforeUnmount);
4365 registerLifecycleHook(onUnmounted, unmounted);
4366 registerLifecycleHook(onServerPrefetch, serverPrefetch);
4367 if (isArray(expose)) {
4368 if (expose.length) {
4369 const exposed = instance.exposed || (instance.exposed = proxyRefs({}));
4370 expose.forEach(key => {
4371 exposed[key] = toRef(publicThis, key);
4372 });
4373 }
4374 else if (!instance.exposed) {
4375 instance.exposed = EMPTY_OBJ;
4376 }
4377 }
4378 // options that are handled when creating the instance but also need to be
4379 // applied from mixins
4380 if (render && instance.render === NOOP) {
4381 instance.render = render;
4382 }
4383 if (inheritAttrs != null) {
4384 instance.inheritAttrs = inheritAttrs;
4385 }
4386 // asset options.
4387 if (components)
4388 instance.components = components;
4389 if (directives)
4390 instance.directives = directives;
4391 }
4392 function resolveInjections(injectOptions, ctx, checkDuplicateProperties = NOOP) {
4393 if (isArray(injectOptions)) {
4394 injectOptions = normalizeInject(injectOptions);
4395 }
4396 for (const key in injectOptions) {
4397 const opt = injectOptions[key];
4398 if (isObject(opt)) {
4399 if ('default' in opt) {
4400 ctx[key] = inject(opt.from || key, opt.default, true /* treat default function as factory */);
4401 }
4402 else {
4403 ctx[key] = inject(opt.from || key);
4404 }
4405 }
4406 else {
4407 ctx[key] = inject(opt);
4408 }
4409 {
4410 checkDuplicateProperties("Inject" /* INJECT */, key);
4411 }
4412 }
4413 }
4414 function callHook(hook, instance, type) {
4415 callWithAsyncErrorHandling(isArray(hook)
4416 ? hook.map(h => h.bind(instance.proxy))
4417 : hook.bind(instance.proxy), instance, type);
4418 }
4419 function createWatcher(raw, ctx, publicThis, key) {
4420 const getter = key.includes('.')
4421 ? createPathGetter(publicThis, key)
4422 : () => publicThis[key];
4423 if (isString(raw)) {
4424 const handler = ctx[raw];
4425 if (isFunction(handler)) {
4426 watch(getter, handler);
4427 }
4428 else {
4429 warn(`Invalid watch handler specified by key "${raw}"`, handler);
4430 }
4431 }
4432 else if (isFunction(raw)) {
4433 watch(getter, raw.bind(publicThis));
4434 }
4435 else if (isObject(raw)) {
4436 if (isArray(raw)) {
4437 raw.forEach(r => createWatcher(r, ctx, publicThis, key));
4438 }
4439 else {
4440 const handler = isFunction(raw.handler)
4441 ? raw.handler.bind(publicThis)
4442 : ctx[raw.handler];
4443 if (isFunction(handler)) {
4444 watch(getter, handler, raw);
4445 }
4446 else {
4447 warn(`Invalid watch handler specified by key "${raw.handler}"`, handler);
4448 }
4449 }
4450 }
4451 else {
4452 warn(`Invalid watch option: "${key}"`, raw);
4453 }
4454 }
4455 /**
4456 * Resolve merged options and cache it on the component.
4457 * This is done only once per-component since the merging does not involve
4458 * instances.
4459 */
4460 function resolveMergedOptions(instance) {
4461 const base = instance.type;
4462 const { mixins, extends: extendsOptions } = base;
4463 const { mixins: globalMixins, optionsCache: cache, config: { optionMergeStrategies } } = instance.appContext;
4464 const cached = cache.get(base);
4465 let resolved;
4466 if (cached) {
4467 resolved = cached;
4468 }
4469 else if (!globalMixins.length && !mixins && !extendsOptions) {
4470 {
4471 resolved = base;
4472 }
4473 }
4474 else {
4475 resolved = {};
4476 if (globalMixins.length) {
4477 globalMixins.forEach(m => mergeOptions(resolved, m, optionMergeStrategies, true));
4478 }
4479 mergeOptions(resolved, base, optionMergeStrategies);
4480 }
4481 cache.set(base, resolved);
4482 return resolved;
4483 }
4484 function mergeOptions(to, from, strats, asMixin = false) {
4485 const { mixins, extends: extendsOptions } = from;
4486 if (extendsOptions) {
4487 mergeOptions(to, extendsOptions, strats, true);
4488 }
4489 if (mixins) {
4490 mixins.forEach((m) => mergeOptions(to, m, strats, true));
4491 }
4492 for (const key in from) {
4493 if (asMixin && key === 'expose') {
4494 warn(`"expose" option is ignored when declared in mixins or extends. ` +
4495 `It should only be declared in the base component itself.`);
4496 }
4497 else {
4498 const strat = internalOptionMergeStrats[key] || (strats && strats[key]);
4499 to[key] = strat ? strat(to[key], from[key]) : from[key];
4500 }
4501 }
4502 return to;
4503 }
4504 const internalOptionMergeStrats = {
4505 data: mergeDataFn,
4506 props: mergeObjectOptions,
4507 emits: mergeObjectOptions,
4508 // objects
4509 methods: mergeObjectOptions,
4510 computed: mergeObjectOptions,
4511 // lifecycle
4512 beforeCreate: mergeHook,
4513 created: mergeHook,
4514 beforeMount: mergeHook,
4515 mounted: mergeHook,
4516 beforeUpdate: mergeHook,
4517 updated: mergeHook,
4518 beforeDestroy: mergeHook,
4519 destroyed: mergeHook,
4520 activated: mergeHook,
4521 deactivated: mergeHook,
4522 errorCaptured: mergeHook,
4523 serverPrefetch: mergeHook,
4524 // assets
4525 components: mergeObjectOptions,
4526 directives: mergeObjectOptions,
4527 // watch has special merge behavior in v2, but isn't actually needed in v3.
4528 // since we are only exposing these for compat and nobody should be relying
4529 // on the watch-specific behavior, just expose the object merge strat.
4530 watch: mergeObjectOptions,
4531 // provide / inject
4532 provide: mergeDataFn,
4533 inject: mergeInject
4534 };
4535 function mergeDataFn(to, from) {
4536 if (!from) {
4537 return to;
4538 }
4539 if (!to) {
4540 return from;
4541 }
4542 return function mergedDataFn() {
4543 return (extend)(isFunction(to) ? to.call(this, this) : to, isFunction(from) ? from.call(this, this) : from);
4544 };
4545 }
4546 function mergeInject(to, from) {
4547 return mergeObjectOptions(normalizeInject(to), normalizeInject(from));
4548 }
4549 function normalizeInject(raw) {
4550 if (isArray(raw)) {
4551 const res = {};
4552 for (let i = 0; i < raw.length; i++) {
4553 res[raw[i]] = raw[i];
4554 }
4555 return res;
4556 }
4557 return raw;
4558 }
4559 function mergeHook(to, from) {
4560 return to ? [...new Set([].concat(to, from))] : from;
4561 }
4562 function mergeObjectOptions(to, from) {
4563 return to ? extend(extend(Object.create(null), to), from) : from;
4564 }
4565
4566 function initProps(instance, rawProps, isStateful, // result of bitwise flag comparison
4567 isSSR = false) {
4568 const props = {};
4569 const attrs = {};
4570 def(attrs, InternalObjectKey, 1);
4571 instance.propsDefaults = Object.create(null);
4572 setFullProps(instance, rawProps, props, attrs);
4573 // ensure all declared prop keys are present
4574 for (const key in instance.propsOptions[0]) {
4575 if (!(key in props)) {
4576 props[key] = undefined;
4577 }
4578 }
4579 // validation
4580 {
4581 validateProps(rawProps || {}, props, instance);
4582 }
4583 if (isStateful) {
4584 // stateful
4585 instance.props = isSSR ? props : shallowReactive(props);
4586 }
4587 else {
4588 if (!instance.type.props) {
4589 // functional w/ optional props, props === attrs
4590 instance.props = attrs;
4591 }
4592 else {
4593 // functional w/ declared props
4594 instance.props = props;
4595 }
4596 }
4597 instance.attrs = attrs;
4598 }
4599 function updateProps(instance, rawProps, rawPrevProps, optimized) {
4600 const { props, attrs, vnode: { patchFlag } } = instance;
4601 const rawCurrentProps = toRaw(props);
4602 const [options] = instance.propsOptions;
4603 let hasAttrsChanged = false;
4604 if (
4605 // always force full diff in dev
4606 // - #1942 if hmr is enabled with sfc component
4607 // - vite#872 non-sfc component used by sfc component
4608 !((instance.type.__hmrId ||
4609 (instance.parent && instance.parent.type.__hmrId))) &&
4610 (optimized || patchFlag > 0) &&
4611 !(patchFlag & 16 /* FULL_PROPS */)) {
4612 if (patchFlag & 8 /* PROPS */) {
4613 // Compiler-generated props & no keys change, just set the updated
4614 // the props.
4615 const propsToUpdate = instance.vnode.dynamicProps;
4616 for (let i = 0; i < propsToUpdate.length; i++) {
4617 let key = propsToUpdate[i];
4618 // PROPS flag guarantees rawProps to be non-null
4619 const value = rawProps[key];
4620 if (options) {
4621 // attr / props separation was done on init and will be consistent
4622 // in this code path, so just check if attrs have it.
4623 if (hasOwn(attrs, key)) {
4624 if (value !== attrs[key]) {
4625 attrs[key] = value;
4626 hasAttrsChanged = true;
4627 }
4628 }
4629 else {
4630 const camelizedKey = camelize(key);
4631 props[camelizedKey] = resolvePropValue(options, rawCurrentProps, camelizedKey, value, instance, false /* isAbsent */);
4632 }
4633 }
4634 else {
4635 if (value !== attrs[key]) {
4636 attrs[key] = value;
4637 hasAttrsChanged = true;
4638 }
4639 }
4640 }
4641 }
4642 }
4643 else {
4644 // full props update.
4645 if (setFullProps(instance, rawProps, props, attrs)) {
4646 hasAttrsChanged = true;
4647 }
4648 // in case of dynamic props, check if we need to delete keys from
4649 // the props object
4650 let kebabKey;
4651 for (const key in rawCurrentProps) {
4652 if (!rawProps ||
4653 // for camelCase
4654 (!hasOwn(rawProps, key) &&
4655 // it's possible the original props was passed in as kebab-case
4656 // and converted to camelCase (#955)
4657 ((kebabKey = hyphenate(key)) === key || !hasOwn(rawProps, kebabKey)))) {
4658 if (options) {
4659 if (rawPrevProps &&
4660 // for camelCase
4661 (rawPrevProps[key] !== undefined ||
4662 // for kebab-case
4663 rawPrevProps[kebabKey] !== undefined)) {
4664 props[key] = resolvePropValue(options, rawCurrentProps, key, undefined, instance, true /* isAbsent */);
4665 }
4666 }
4667 else {
4668 delete props[key];
4669 }
4670 }
4671 }
4672 // in the case of functional component w/o props declaration, props and
4673 // attrs point to the same object so it should already have been updated.
4674 if (attrs !== rawCurrentProps) {
4675 for (const key in attrs) {
4676 if (!rawProps || !hasOwn(rawProps, key)) {
4677 delete attrs[key];
4678 hasAttrsChanged = true;
4679 }
4680 }
4681 }
4682 }
4683 // trigger updates for $attrs in case it's used in component slots
4684 if (hasAttrsChanged) {
4685 trigger(instance, "set" /* SET */, '$attrs');
4686 }
4687 {
4688 validateProps(rawProps || {}, props, instance);
4689 }
4690 }
4691 function setFullProps(instance, rawProps, props, attrs) {
4692 const [options, needCastKeys] = instance.propsOptions;
4693 let hasAttrsChanged = false;
4694 let rawCastValues;
4695 if (rawProps) {
4696 for (let key in rawProps) {
4697 // key, ref are reserved and never passed down
4698 if (isReservedProp(key)) {
4699 continue;
4700 }
4701 const value = rawProps[key];
4702 // prop option names are camelized during normalization, so to support
4703 // kebab -> camel conversion here we need to camelize the key.
4704 let camelKey;
4705 if (options && hasOwn(options, (camelKey = camelize(key)))) {
4706 if (!needCastKeys || !needCastKeys.includes(camelKey)) {
4707 props[camelKey] = value;
4708 }
4709 else {
4710 (rawCastValues || (rawCastValues = {}))[camelKey] = value;
4711 }
4712 }
4713 else if (!isEmitListener(instance.emitsOptions, key)) {
4714 if (value !== attrs[key]) {
4715 attrs[key] = value;
4716 hasAttrsChanged = true;
4717 }
4718 }
4719 }
4720 }
4721 if (needCastKeys) {
4722 const rawCurrentProps = toRaw(props);
4723 const castValues = rawCastValues || EMPTY_OBJ;
4724 for (let i = 0; i < needCastKeys.length; i++) {
4725 const key = needCastKeys[i];
4726 props[key] = resolvePropValue(options, rawCurrentProps, key, castValues[key], instance, !hasOwn(castValues, key));
4727 }
4728 }
4729 return hasAttrsChanged;
4730 }
4731 function resolvePropValue(options, props, key, value, instance, isAbsent) {
4732 const opt = options[key];
4733 if (opt != null) {
4734 const hasDefault = hasOwn(opt, 'default');
4735 // default values
4736 if (hasDefault && value === undefined) {
4737 const defaultValue = opt.default;
4738 if (opt.type !== Function && isFunction(defaultValue)) {
4739 const { propsDefaults } = instance;
4740 if (key in propsDefaults) {
4741 value = propsDefaults[key];
4742 }
4743 else {
4744 setCurrentInstance(instance);
4745 value = propsDefaults[key] = defaultValue.call(null, props);
4746 setCurrentInstance(null);
4747 }
4748 }
4749 else {
4750 value = defaultValue;
4751 }
4752 }
4753 // boolean casting
4754 if (opt[0 /* shouldCast */]) {
4755 if (isAbsent && !hasDefault) {
4756 value = false;
4757 }
4758 else if (opt[1 /* shouldCastTrue */] &&
4759 (value === '' || value === hyphenate(key))) {
4760 value = true;
4761 }
4762 }
4763 }
4764 return value;
4765 }
4766 function normalizePropsOptions(comp, appContext, asMixin = false) {
4767 const cache = appContext.propsCache;
4768 const cached = cache.get(comp);
4769 if (cached) {
4770 return cached;
4771 }
4772 const raw = comp.props;
4773 const normalized = {};
4774 const needCastKeys = [];
4775 // apply mixin/extends props
4776 let hasExtends = false;
4777 if (!isFunction(comp)) {
4778 const extendProps = (raw) => {
4779 hasExtends = true;
4780 const [props, keys] = normalizePropsOptions(raw, appContext, true);
4781 extend(normalized, props);
4782 if (keys)
4783 needCastKeys.push(...keys);
4784 };
4785 if (!asMixin && appContext.mixins.length) {
4786 appContext.mixins.forEach(extendProps);
4787 }
4788 if (comp.extends) {
4789 extendProps(comp.extends);
4790 }
4791 if (comp.mixins) {
4792 comp.mixins.forEach(extendProps);
4793 }
4794 }
4795 if (!raw && !hasExtends) {
4796 cache.set(comp, EMPTY_ARR);
4797 return EMPTY_ARR;
4798 }
4799 if (isArray(raw)) {
4800 for (let i = 0; i < raw.length; i++) {
4801 if (!isString(raw[i])) {
4802 warn(`props must be strings when using array syntax.`, raw[i]);
4803 }
4804 const normalizedKey = camelize(raw[i]);
4805 if (validatePropName(normalizedKey)) {
4806 normalized[normalizedKey] = EMPTY_OBJ;
4807 }
4808 }
4809 }
4810 else if (raw) {
4811 if (!isObject(raw)) {
4812 warn(`invalid props options`, raw);
4813 }
4814 for (const key in raw) {
4815 const normalizedKey = camelize(key);
4816 if (validatePropName(normalizedKey)) {
4817 const opt = raw[key];
4818 const prop = (normalized[normalizedKey] =
4819 isArray(opt) || isFunction(opt) ? { type: opt } : opt);
4820 if (prop) {
4821 const booleanIndex = getTypeIndex(Boolean, prop.type);
4822 const stringIndex = getTypeIndex(String, prop.type);
4823 prop[0 /* shouldCast */] = booleanIndex > -1;
4824 prop[1 /* shouldCastTrue */] =
4825 stringIndex < 0 || booleanIndex < stringIndex;
4826 // if the prop needs boolean casting or default value
4827 if (booleanIndex > -1 || hasOwn(prop, 'default')) {
4828 needCastKeys.push(normalizedKey);
4829 }
4830 }
4831 }
4832 }
4833 }
4834 const res = [normalized, needCastKeys];
4835 cache.set(comp, res);
4836 return res;
4837 }
4838 function validatePropName(key) {
4839 if (key[0] !== '$') {
4840 return true;
4841 }
4842 else {
4843 warn(`Invalid prop name: "${key}" is a reserved property.`);
4844 }
4845 return false;
4846 }
4847 // use function string name to check type constructors
4848 // so that it works across vms / iframes.
4849 function getType(ctor) {
4850 const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
4851 return match ? match[1] : '';
4852 }
4853 function isSameType(a, b) {
4854 return getType(a) === getType(b);
4855 }
4856 function getTypeIndex(type, expectedTypes) {
4857 if (isArray(expectedTypes)) {
4858 return expectedTypes.findIndex(t => isSameType(t, type));
4859 }
4860 else if (isFunction(expectedTypes)) {
4861 return isSameType(expectedTypes, type) ? 0 : -1;
4862 }
4863 return -1;
4864 }
4865 /**
4866 * dev only
4867 */
4868 function validateProps(rawProps, props, instance) {
4869 const resolvedValues = toRaw(props);
4870 const options = instance.propsOptions[0];
4871 for (const key in options) {
4872 let opt = options[key];
4873 if (opt == null)
4874 continue;
4875 validateProp(key, resolvedValues[key], opt, !hasOwn(rawProps, key) && !hasOwn(rawProps, hyphenate(key)));
4876 }
4877 }
4878 /**
4879 * dev only
4880 */
4881 function validateProp(name, value, prop, isAbsent) {
4882 const { type, required, validator } = prop;
4883 // required!
4884 if (required && isAbsent) {
4885 warn('Missing required prop: "' + name + '"');
4886 return;
4887 }
4888 // missing but optional
4889 if (value == null && !prop.required) {
4890 return;
4891 }
4892 // type check
4893 if (type != null && type !== true) {
4894 let isValid = false;
4895 const types = isArray(type) ? type : [type];
4896 const expectedTypes = [];
4897 // value is valid as long as one of the specified types match
4898 for (let i = 0; i < types.length && !isValid; i++) {
4899 const { valid, expectedType } = assertType(value, types[i]);
4900 expectedTypes.push(expectedType || '');
4901 isValid = valid;
4902 }
4903 if (!isValid) {
4904 warn(getInvalidTypeMessage(name, value, expectedTypes));
4905 return;
4906 }
4907 }
4908 // custom validator
4909 if (validator && !validator(value)) {
4910 warn('Invalid prop: custom validator check failed for prop "' + name + '".');
4911 }
4912 }
4913 const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol,BigInt');
4914 /**
4915 * dev only
4916 */
4917 function assertType(value, type) {
4918 let valid;
4919 const expectedType = getType(type);
4920 if (isSimpleType(expectedType)) {
4921 const t = typeof value;
4922 valid = t === expectedType.toLowerCase();
4923 // for primitive wrapper objects
4924 if (!valid && t === 'object') {
4925 valid = value instanceof type;
4926 }
4927 }
4928 else if (expectedType === 'Object') {
4929 valid = isObject(value);
4930 }
4931 else if (expectedType === 'Array') {
4932 valid = isArray(value);
4933 }
4934 else {
4935 valid = value instanceof type;
4936 }
4937 return {
4938 valid,
4939 expectedType
4940 };
4941 }
4942 /**
4943 * dev only
4944 */
4945 function getInvalidTypeMessage(name, value, expectedTypes) {
4946 let message = `Invalid prop: type check failed for prop "${name}".` +
4947 ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
4948 const expectedType = expectedTypes[0];
4949 const receivedType = toRawType(value);
4950 const expectedValue = styleValue(value, expectedType);
4951 const receivedValue = styleValue(value, receivedType);
4952 // check if we need to specify expected value
4953 if (expectedTypes.length === 1 &&
4954 isExplicable(expectedType) &&
4955 !isBoolean(expectedType, receivedType)) {
4956 message += ` with value ${expectedValue}`;
4957 }
4958 message += `, got ${receivedType} `;
4959 // check if we need to specify received value
4960 if (isExplicable(receivedType)) {
4961 message += `with value ${receivedValue}.`;
4962 }
4963 return message;
4964 }
4965 /**
4966 * dev only
4967 */
4968 function styleValue(value, type) {
4969 if (type === 'String') {
4970 return `"${value}"`;
4971 }
4972 else if (type === 'Number') {
4973 return `${Number(value)}`;
4974 }
4975 else {
4976 return `${value}`;
4977 }
4978 }
4979 /**
4980 * dev only
4981 */
4982 function isExplicable(type) {
4983 const explicitTypes = ['string', 'number', 'boolean'];
4984 return explicitTypes.some(elem => type.toLowerCase() === elem);
4985 }
4986 /**
4987 * dev only
4988 */
4989 function isBoolean(...args) {
4990 return args.some(elem => elem.toLowerCase() === 'boolean');
4991 }
4992
4993 const isInternalKey = (key) => key[0] === '_' || key === '$stable';
4994 const normalizeSlotValue = (value) => isArray(value)
4995 ? value.map(normalizeVNode)
4996 : [normalizeVNode(value)];
4997 const normalizeSlot = (key, rawSlot, ctx) => {
4998 const normalized = withCtx((props) => {
4999 if (currentInstance) {
5000 warn(`Slot "${key}" invoked outside of the render function: ` +
5001 `this will not track dependencies used in the slot. ` +
5002 `Invoke the slot function inside the render function instead.`);
5003 }
5004 return normalizeSlotValue(rawSlot(props));
5005 }, ctx);
5006 normalized._c = false;
5007 return normalized;
5008 };
5009 const normalizeObjectSlots = (rawSlots, slots, instance) => {
5010 const ctx = rawSlots._ctx;
5011 for (const key in rawSlots) {
5012 if (isInternalKey(key))
5013 continue;
5014 const value = rawSlots[key];
5015 if (isFunction(value)) {
5016 slots[key] = normalizeSlot(key, value, ctx);
5017 }
5018 else if (value != null) {
5019 {
5020 warn(`Non-function value encountered for slot "${key}". ` +
5021 `Prefer function slots for better performance.`);
5022 }
5023 const normalized = normalizeSlotValue(value);
5024 slots[key] = () => normalized;
5025 }
5026 }
5027 };
5028 const normalizeVNodeSlots = (instance, children) => {
5029 if (!isKeepAlive(instance.vnode) &&
5030 !(false )) {
5031 warn(`Non-function value encountered for default slot. ` +
5032 `Prefer function slots for better performance.`);
5033 }
5034 const normalized = normalizeSlotValue(children);
5035 instance.slots.default = () => normalized;
5036 };
5037 const initSlots = (instance, children) => {
5038 if (instance.vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5039 const type = children._;
5040 if (type) {
5041 // users can get the shallow readonly version of the slots object through `this.$slots`,
5042 // we should avoid the proxy object polluting the slots of the internal instance
5043 instance.slots = toRaw(children);
5044 // make compiler marker non-enumerable
5045 def(children, '_', type);
5046 }
5047 else {
5048 normalizeObjectSlots(children, (instance.slots = {}));
5049 }
5050 }
5051 else {
5052 instance.slots = {};
5053 if (children) {
5054 normalizeVNodeSlots(instance, children);
5055 }
5056 }
5057 def(instance.slots, InternalObjectKey, 1);
5058 };
5059 const updateSlots = (instance, children, optimized) => {
5060 const { vnode, slots } = instance;
5061 let needDeletionCheck = true;
5062 let deletionComparisonTarget = EMPTY_OBJ;
5063 if (vnode.shapeFlag & 32 /* SLOTS_CHILDREN */) {
5064 const type = children._;
5065 if (type) {
5066 // compiled slots.
5067 if (isHmrUpdating) {
5068 // Parent was HMR updated so slot content may have changed.
5069 // force update slots and mark instance for hmr as well
5070 extend(slots, children);
5071 }
5072 else if (optimized && type === 1 /* STABLE */) {
5073 // compiled AND stable.
5074 // no need to update, and skip stale slots removal.
5075 needDeletionCheck = false;
5076 }
5077 else {
5078 // compiled but dynamic (v-if/v-for on slots) - update slots, but skip
5079 // normalization.
5080 extend(slots, children);
5081 // #2893
5082 // when rendering the optimized slots by manually written render function,
5083 // we need to delete the `slots._` flag if necessary to make subsequent updates reliable,
5084 // i.e. let the `renderSlot` create the bailed Fragment
5085 if (!optimized && type === 1 /* STABLE */) {
5086 delete slots._;
5087 }
5088 }
5089 }
5090 else {
5091 needDeletionCheck = !children.$stable;
5092 normalizeObjectSlots(children, slots);
5093 }
5094 deletionComparisonTarget = children;
5095 }
5096 else if (children) {
5097 // non slot object children (direct value) passed to a component
5098 normalizeVNodeSlots(instance, children);
5099 deletionComparisonTarget = { default: 1 };
5100 }
5101 // delete stale slots
5102 if (needDeletionCheck) {
5103 for (const key in slots) {
5104 if (!isInternalKey(key) && !(key in deletionComparisonTarget)) {
5105 delete slots[key];
5106 }
5107 }
5108 }
5109 };
5110
5111 /**
5112 Runtime helper for applying directives to a vnode. Example usage:
5113
5114 const comp = resolveComponent('comp')
5115 const foo = resolveDirective('foo')
5116 const bar = resolveDirective('bar')
5117
5118 return withDirectives(h(comp), [
5119 [foo, this.x],
5120 [bar, this.y]
5121 ])
5122 */
5123 const isBuiltInDirective = /*#__PURE__*/ makeMap('bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text');
5124 function validateDirectiveName(name) {
5125 if (isBuiltInDirective(name)) {
5126 warn('Do not use built-in directive ids as custom directive id: ' + name);
5127 }
5128 }
5129 /**
5130 * Adds directives to a VNode.
5131 */
5132 function withDirectives(vnode, directives) {
5133 const internalInstance = currentRenderingInstance;
5134 if (internalInstance === null) {
5135 warn(`withDirectives can only be used inside render functions.`);
5136 return vnode;
5137 }
5138 const instance = internalInstance.proxy;
5139 const bindings = vnode.dirs || (vnode.dirs = []);
5140 for (let i = 0; i < directives.length; i++) {
5141 let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i];
5142 if (isFunction(dir)) {
5143 dir = {
5144 mounted: dir,
5145 updated: dir
5146 };
5147 }
5148 bindings.push({
5149 dir,
5150 instance,
5151 value,
5152 oldValue: void 0,
5153 arg,
5154 modifiers
5155 });
5156 }
5157 return vnode;
5158 }
5159 function invokeDirectiveHook(vnode, prevVNode, instance, name) {
5160 const bindings = vnode.dirs;
5161 const oldBindings = prevVNode && prevVNode.dirs;
5162 for (let i = 0; i < bindings.length; i++) {
5163 const binding = bindings[i];
5164 if (oldBindings) {
5165 binding.oldValue = oldBindings[i].value;
5166 }
5167 let hook = binding.dir[name];
5168 if (hook) {
5169 // disable tracking inside all lifecycle hooks
5170 // since they can potentially be called inside effects.
5171 pauseTracking();
5172 callWithAsyncErrorHandling(hook, instance, 8 /* DIRECTIVE_HOOK */, [
5173 vnode.el,
5174 binding,
5175 vnode,
5176 prevVNode
5177 ]);
5178 resetTracking();
5179 }
5180 }
5181 }
5182
5183 function createAppContext() {
5184 return {
5185 app: null,
5186 config: {
5187 isNativeTag: NO,
5188 performance: false,
5189 globalProperties: {},
5190 optionMergeStrategies: {},
5191 errorHandler: undefined,
5192 warnHandler: undefined,
5193 compilerOptions: {}
5194 },
5195 mixins: [],
5196 components: {},
5197 directives: {},
5198 provides: Object.create(null),
5199 optionsCache: new WeakMap(),
5200 propsCache: new WeakMap(),
5201 emitsCache: new WeakMap()
5202 };
5203 }
5204 let uid$1 = 0;
5205 function createAppAPI(render, hydrate) {
5206 return function createApp(rootComponent, rootProps = null) {
5207 if (rootProps != null && !isObject(rootProps)) {
5208 warn(`root props passed to app.mount() must be an object.`);
5209 rootProps = null;
5210 }
5211 const context = createAppContext();
5212 const installedPlugins = new Set();
5213 let isMounted = false;
5214 const app = (context.app = {
5215 _uid: uid$1++,
5216 _component: rootComponent,
5217 _props: rootProps,
5218 _container: null,
5219 _context: context,
5220 version,
5221 get config() {
5222 return context.config;
5223 },
5224 set config(v) {
5225 {
5226 warn(`app.config cannot be replaced. Modify individual options instead.`);
5227 }
5228 },
5229 use(plugin, ...options) {
5230 if (installedPlugins.has(plugin)) {
5231 warn(`Plugin has already been applied to target app.`);
5232 }
5233 else if (plugin && isFunction(plugin.install)) {
5234 installedPlugins.add(plugin);
5235 plugin.install(app, ...options);
5236 }
5237 else if (isFunction(plugin)) {
5238 installedPlugins.add(plugin);
5239 plugin(app, ...options);
5240 }
5241 else {
5242 warn(`A plugin must either be a function or an object with an "install" ` +
5243 `function.`);
5244 }
5245 return app;
5246 },
5247 mixin(mixin) {
5248 {
5249 if (!context.mixins.includes(mixin)) {
5250 context.mixins.push(mixin);
5251 }
5252 else {
5253 warn('Mixin has already been applied to target app' +
5254 (mixin.name ? `: ${mixin.name}` : ''));
5255 }
5256 }
5257 return app;
5258 },
5259 component(name, component) {
5260 {
5261 validateComponentName(name, context.config);
5262 }
5263 if (!component) {
5264 return context.components[name];
5265 }
5266 if (context.components[name]) {
5267 warn(`Component "${name}" has already been registered in target app.`);
5268 }
5269 context.components[name] = component;
5270 return app;
5271 },
5272 directive(name, directive) {
5273 {
5274 validateDirectiveName(name);
5275 }
5276 if (!directive) {
5277 return context.directives[name];
5278 }
5279 if (context.directives[name]) {
5280 warn(`Directive "${name}" has already been registered in target app.`);
5281 }
5282 context.directives[name] = directive;
5283 return app;
5284 },
5285 mount(rootContainer, isHydrate, isSVG) {
5286 if (!isMounted) {
5287 const vnode = createVNode(rootComponent, rootProps);
5288 // store app context on the root VNode.
5289 // this will be set on the root instance on initial mount.
5290 vnode.appContext = context;
5291 // HMR root reload
5292 {
5293 context.reload = () => {
5294 render(cloneVNode(vnode), rootContainer, isSVG);
5295 };
5296 }
5297 if (isHydrate && hydrate) {
5298 hydrate(vnode, rootContainer);
5299 }
5300 else {
5301 render(vnode, rootContainer, isSVG);
5302 }
5303 isMounted = true;
5304 app._container = rootContainer;
5305 rootContainer.__vue_app__ = app;
5306 {
5307 devtoolsInitApp(app, version);
5308 }
5309 return vnode.component.proxy;
5310 }
5311 else {
5312 warn(`App has already been mounted.\n` +
5313 `If you want to remount the same app, move your app creation logic ` +
5314 `into a factory function and create fresh app instances for each ` +
5315 `mount - e.g. \`const createMyApp = () => createApp(App)\``);
5316 }
5317 },
5318 unmount() {
5319 if (isMounted) {
5320 render(null, app._container);
5321 {
5322 devtoolsUnmountApp(app);
5323 }
5324 delete app._container.__vue_app__;
5325 }
5326 else {
5327 warn(`Cannot unmount an app that is not mounted.`);
5328 }
5329 },
5330 provide(key, value) {
5331 if (key in context.provides) {
5332 warn(`App already provides property with key "${String(key)}". ` +
5333 `It will be overwritten with the new value.`);
5334 }
5335 // TypeScript doesn't allow symbols as index type
5336 // https://github.com/Microsoft/TypeScript/issues/24587
5337 context.provides[key] = value;
5338 return app;
5339 }
5340 });
5341 return app;
5342 };
5343 }
5344
5345 let hasMismatch = false;
5346 const isSVGContainer = (container) => /svg/.test(container.namespaceURI) && container.tagName !== 'foreignObject';
5347 const isComment = (node) => node.nodeType === 8 /* COMMENT */;
5348 // Note: hydration is DOM-specific
5349 // But we have to place it in core due to tight coupling with core - splitting
5350 // it out creates a ton of unnecessary complexity.
5351 // Hydration also depends on some renderer internal logic which needs to be
5352 // passed in via arguments.
5353 function createHydrationFunctions(rendererInternals) {
5354 const { mt: mountComponent, p: patch, o: { patchProp, nextSibling, parentNode, remove, insert, createComment } } = rendererInternals;
5355 const hydrate = (vnode, container) => {
5356 if (!container.hasChildNodes()) {
5357 warn(`Attempting to hydrate existing markup but container is empty. ` +
5358 `Performing full mount instead.`);
5359 patch(null, vnode, container);
5360 return;
5361 }
5362 hasMismatch = false;
5363 hydrateNode(container.firstChild, vnode, null, null, null);
5364 flushPostFlushCbs();
5365 if (hasMismatch && !false) {
5366 // this error should show up in production
5367 console.error(`Hydration completed but contains mismatches.`);
5368 }
5369 };
5370 const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => {
5371 const isFragmentStart = isComment(node) && node.data === '[';
5372 const onMismatch = () => handleMismatch(node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragmentStart);
5373 const { type, ref, shapeFlag } = vnode;
5374 const domType = node.nodeType;
5375 vnode.el = node;
5376 let nextNode = null;
5377 switch (type) {
5378 case Text:
5379 if (domType !== 3 /* TEXT */) {
5380 nextNode = onMismatch();
5381 }
5382 else {
5383 if (node.data !== vnode.children) {
5384 hasMismatch = true;
5385 warn(`Hydration text mismatch:` +
5386 `\n- Client: ${JSON.stringify(node.data)}` +
5387 `\n- Server: ${JSON.stringify(vnode.children)}`);
5388 node.data = vnode.children;
5389 }
5390 nextNode = nextSibling(node);
5391 }
5392 break;
5393 case Comment$1:
5394 if (domType !== 8 /* COMMENT */ || isFragmentStart) {
5395 nextNode = onMismatch();
5396 }
5397 else {
5398 nextNode = nextSibling(node);
5399 }
5400 break;
5401 case Static:
5402 if (domType !== 1 /* ELEMENT */) {
5403 nextNode = onMismatch();
5404 }
5405 else {
5406 // determine anchor, adopt content
5407 nextNode = node;
5408 // if the static vnode has its content stripped during build,
5409 // adopt it from the server-rendered HTML.
5410 const needToAdoptContent = !vnode.children.length;
5411 for (let i = 0; i < vnode.staticCount; i++) {
5412 if (needToAdoptContent)
5413 vnode.children += nextNode.outerHTML;
5414 if (i === vnode.staticCount - 1) {
5415 vnode.anchor = nextNode;
5416 }
5417 nextNode = nextSibling(nextNode);
5418 }
5419 return nextNode;
5420 }
5421 break;
5422 case Fragment:
5423 if (!isFragmentStart) {
5424 nextNode = onMismatch();
5425 }
5426 else {
5427 nextNode = hydrateFragment(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5428 }
5429 break;
5430 default:
5431 if (shapeFlag & 1 /* ELEMENT */) {
5432 if (domType !== 1 /* ELEMENT */ ||
5433 vnode.type.toLowerCase() !==
5434 node.tagName.toLowerCase()) {
5435 nextNode = onMismatch();
5436 }
5437 else {
5438 nextNode = hydrateElement(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5439 }
5440 }
5441 else if (shapeFlag & 6 /* COMPONENT */) {
5442 // when setting up the render effect, if the initial vnode already
5443 // has .el set, the component will perform hydration instead of mount
5444 // on its sub-tree.
5445 vnode.slotScopeIds = slotScopeIds;
5446 const container = parentNode(node);
5447 mountComponent(vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), optimized);
5448 // component may be async, so in the case of fragments we cannot rely
5449 // on component's rendered output to determine the end of the fragment
5450 // instead, we do a lookahead to find the end anchor node.
5451 nextNode = isFragmentStart
5452 ? locateClosingAsyncAnchor(node)
5453 : nextSibling(node);
5454 // #3787
5455 // if component is async, it may get moved / unmounted before its
5456 // inner component is loaded, so we need to give it a placeholder
5457 // vnode that matches its adopted DOM.
5458 if (isAsyncWrapper(vnode)) {
5459 let subTree;
5460 if (isFragmentStart) {
5461 subTree = createVNode(Fragment);
5462 subTree.anchor = nextNode
5463 ? nextNode.previousSibling
5464 : container.lastChild;
5465 }
5466 else {
5467 subTree =
5468 node.nodeType === 3 ? createTextVNode('') : createVNode('div');
5469 }
5470 subTree.el = node;
5471 vnode.component.subTree = subTree;
5472 }
5473 }
5474 else if (shapeFlag & 64 /* TELEPORT */) {
5475 if (domType !== 8 /* COMMENT */) {
5476 nextNode = onMismatch();
5477 }
5478 else {
5479 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, rendererInternals, hydrateChildren);
5480 }
5481 }
5482 else if (shapeFlag & 128 /* SUSPENSE */) {
5483 nextNode = vnode.type.hydrate(node, vnode, parentComponent, parentSuspense, isSVGContainer(parentNode(node)), slotScopeIds, optimized, rendererInternals, hydrateNode);
5484 }
5485 else {
5486 warn('Invalid HostVNode type:', type, `(${typeof type})`);
5487 }
5488 }
5489 if (ref != null) {
5490 setRef(ref, null, parentSuspense, vnode);
5491 }
5492 return nextNode;
5493 };
5494 const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5495 optimized = optimized || !!vnode.dynamicChildren;
5496 const { props, patchFlag, shapeFlag, dirs } = vnode;
5497 // skip props & children if this is hoisted static nodes
5498 if (patchFlag !== -1 /* HOISTED */) {
5499 if (dirs) {
5500 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5501 }
5502 // props
5503 if (props) {
5504 if (!optimized ||
5505 (patchFlag & 16 /* FULL_PROPS */ ||
5506 patchFlag & 32 /* HYDRATE_EVENTS */)) {
5507 for (const key in props) {
5508 if (!isReservedProp(key) && isOn(key)) {
5509 patchProp(el, key, null, props[key]);
5510 }
5511 }
5512 }
5513 else if (props.onClick) {
5514 // Fast path for click listeners (which is most often) to avoid
5515 // iterating through props.
5516 patchProp(el, 'onClick', null, props.onClick);
5517 }
5518 }
5519 // vnode / directive hooks
5520 let vnodeHooks;
5521 if ((vnodeHooks = props && props.onVnodeBeforeMount)) {
5522 invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5523 }
5524 if (dirs) {
5525 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5526 }
5527 if ((vnodeHooks = props && props.onVnodeMounted) || dirs) {
5528 queueEffectWithSuspense(() => {
5529 vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode);
5530 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5531 }, parentSuspense);
5532 }
5533 // children
5534 if (shapeFlag & 16 /* ARRAY_CHILDREN */ &&
5535 // skip if element has innerHTML / textContent
5536 !(props && (props.innerHTML || props.textContent))) {
5537 let next = hydrateChildren(el.firstChild, vnode, el, parentComponent, parentSuspense, slotScopeIds, optimized);
5538 let hasWarned = false;
5539 while (next) {
5540 hasMismatch = true;
5541 if (!hasWarned) {
5542 warn(`Hydration children mismatch in <${vnode.type}>: ` +
5543 `server rendered element contains more child nodes than client vdom.`);
5544 hasWarned = true;
5545 }
5546 // The SSRed DOM contains more nodes than it should. Remove them.
5547 const cur = next;
5548 next = next.nextSibling;
5549 remove(cur);
5550 }
5551 }
5552 else if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5553 if (el.textContent !== vnode.children) {
5554 hasMismatch = true;
5555 warn(`Hydration text content mismatch in <${vnode.type}>:\n` +
5556 `- Client: ${el.textContent}\n` +
5557 `- Server: ${vnode.children}`);
5558 el.textContent = vnode.children;
5559 }
5560 }
5561 }
5562 return el.nextSibling;
5563 };
5564 const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5565 optimized = optimized || !!parentVNode.dynamicChildren;
5566 const children = parentVNode.children;
5567 const l = children.length;
5568 let hasWarned = false;
5569 for (let i = 0; i < l; i++) {
5570 const vnode = optimized
5571 ? children[i]
5572 : (children[i] = normalizeVNode(children[i]));
5573 if (node) {
5574 node = hydrateNode(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized);
5575 }
5576 else if (vnode.type === Text && !vnode.children) {
5577 continue;
5578 }
5579 else {
5580 hasMismatch = true;
5581 if (!hasWarned) {
5582 warn(`Hydration children mismatch in <${container.tagName.toLowerCase()}>: ` +
5583 `server rendered element contains fewer child nodes than client vdom.`);
5584 hasWarned = true;
5585 }
5586 // the SSRed DOM didn't contain enough nodes. Mount the missing ones.
5587 patch(null, vnode, container, null, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5588 }
5589 }
5590 return node;
5591 };
5592 const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => {
5593 const { slotScopeIds: fragmentSlotScopeIds } = vnode;
5594 if (fragmentSlotScopeIds) {
5595 slotScopeIds = slotScopeIds
5596 ? slotScopeIds.concat(fragmentSlotScopeIds)
5597 : fragmentSlotScopeIds;
5598 }
5599 const container = parentNode(node);
5600 const next = hydrateChildren(nextSibling(node), vnode, container, parentComponent, parentSuspense, slotScopeIds, optimized);
5601 if (next && isComment(next) && next.data === ']') {
5602 return nextSibling((vnode.anchor = next));
5603 }
5604 else {
5605 // fragment didn't hydrate successfully, since we didn't get a end anchor
5606 // back. This should have led to node/children mismatch warnings.
5607 hasMismatch = true;
5608 // since the anchor is missing, we need to create one and insert it
5609 insert((vnode.anchor = createComment(`]`)), container, next);
5610 return next;
5611 }
5612 };
5613 const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => {
5614 hasMismatch = true;
5615 warn(`Hydration node mismatch:\n- Client vnode:`, vnode.type, `\n- Server rendered DOM:`, node, node.nodeType === 3 /* TEXT */
5616 ? `(text)`
5617 : isComment(node) && node.data === '['
5618 ? `(start of fragment)`
5619 : ``);
5620 vnode.el = null;
5621 if (isFragment) {
5622 // remove excessive fragment nodes
5623 const end = locateClosingAsyncAnchor(node);
5624 while (true) {
5625 const next = nextSibling(node);
5626 if (next && next !== end) {
5627 remove(next);
5628 }
5629 else {
5630 break;
5631 }
5632 }
5633 }
5634 const next = nextSibling(node);
5635 const container = parentNode(node);
5636 remove(node);
5637 patch(null, vnode, container, next, parentComponent, parentSuspense, isSVGContainer(container), slotScopeIds);
5638 return next;
5639 };
5640 const locateClosingAsyncAnchor = (node) => {
5641 let match = 0;
5642 while (node) {
5643 node = nextSibling(node);
5644 if (node && isComment(node)) {
5645 if (node.data === '[')
5646 match++;
5647 if (node.data === ']') {
5648 if (match === 0) {
5649 return nextSibling(node);
5650 }
5651 else {
5652 match--;
5653 }
5654 }
5655 }
5656 }
5657 return node;
5658 };
5659 return [hydrate, hydrateNode];
5660 }
5661
5662 let supported;
5663 let perf;
5664 function startMeasure(instance, type) {
5665 if (instance.appContext.config.performance && isSupported()) {
5666 perf.mark(`vue-${type}-${instance.uid}`);
5667 }
5668 {
5669 devtoolsPerfStart(instance, type, supported ? perf.now() : Date.now());
5670 }
5671 }
5672 function endMeasure(instance, type) {
5673 if (instance.appContext.config.performance && isSupported()) {
5674 const startTag = `vue-${type}-${instance.uid}`;
5675 const endTag = startTag + `:end`;
5676 perf.mark(endTag);
5677 perf.measure(`<${formatComponentName(instance, instance.type)}> ${type}`, startTag, endTag);
5678 perf.clearMarks(startTag);
5679 perf.clearMarks(endTag);
5680 }
5681 {
5682 devtoolsPerfEnd(instance, type, supported ? perf.now() : Date.now());
5683 }
5684 }
5685 function isSupported() {
5686 if (supported !== undefined) {
5687 return supported;
5688 }
5689 /* eslint-disable no-restricted-globals */
5690 if (typeof window !== 'undefined' && window.performance) {
5691 supported = true;
5692 perf = window.performance;
5693 }
5694 else {
5695 supported = false;
5696 }
5697 /* eslint-enable no-restricted-globals */
5698 return supported;
5699 }
5700
5701 function createDevEffectOptions(instance) {
5702 return {
5703 scheduler: queueJob,
5704 allowRecurse: true,
5705 onTrack: instance.rtc ? e => invokeArrayFns(instance.rtc, e) : void 0,
5706 onTrigger: instance.rtg ? e => invokeArrayFns(instance.rtg, e) : void 0
5707 };
5708 }
5709 const queuePostRenderEffect = queueEffectWithSuspense
5710 ;
5711 const setRef = (rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) => {
5712 if (isArray(rawRef)) {
5713 rawRef.forEach((r, i) => setRef(r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, vnode, isUnmount));
5714 return;
5715 }
5716 if (isAsyncWrapper(vnode) && !isUnmount) {
5717 // when mounting async components, nothing needs to be done,
5718 // because the template ref is forwarded to inner component
5719 return;
5720 }
5721 const refValue = vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */
5722 ? vnode.component.exposed || vnode.component.proxy
5723 : vnode.el;
5724 const value = isUnmount ? null : refValue;
5725 const { i: owner, r: ref } = rawRef;
5726 if (!owner) {
5727 warn(`Missing ref owner context. ref cannot be used on hoisted vnodes. ` +
5728 `A vnode with ref must be created inside the render function.`);
5729 return;
5730 }
5731 const oldRef = oldRawRef && oldRawRef.r;
5732 const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs;
5733 const setupState = owner.setupState;
5734 // dynamic ref changed. unset old ref
5735 if (oldRef != null && oldRef !== ref) {
5736 if (isString(oldRef)) {
5737 refs[oldRef] = null;
5738 if (hasOwn(setupState, oldRef)) {
5739 setupState[oldRef] = null;
5740 }
5741 }
5742 else if (isRef(oldRef)) {
5743 oldRef.value = null;
5744 }
5745 }
5746 if (isString(ref)) {
5747 const doSet = () => {
5748 {
5749 refs[ref] = value;
5750 }
5751 if (hasOwn(setupState, ref)) {
5752 setupState[ref] = value;
5753 }
5754 };
5755 // #1789: for non-null values, set them after render
5756 // null values means this is unmount and it should not overwrite another
5757 // ref with the same key
5758 if (value) {
5759 doSet.id = -1;
5760 queuePostRenderEffect(doSet, parentSuspense);
5761 }
5762 else {
5763 doSet();
5764 }
5765 }
5766 else if (isRef(ref)) {
5767 const doSet = () => {
5768 ref.value = value;
5769 };
5770 if (value) {
5771 doSet.id = -1;
5772 queuePostRenderEffect(doSet, parentSuspense);
5773 }
5774 else {
5775 doSet();
5776 }
5777 }
5778 else if (isFunction(ref)) {
5779 callWithErrorHandling(ref, owner, 12 /* FUNCTION_REF */, [value, refs]);
5780 }
5781 else {
5782 warn('Invalid template ref type:', value, `(${typeof value})`);
5783 }
5784 };
5785 /**
5786 * The createRenderer function accepts two generic arguments:
5787 * HostNode and HostElement, corresponding to Node and Element types in the
5788 * host environment. For example, for runtime-dom, HostNode would be the DOM
5789 * `Node` interface and HostElement would be the DOM `Element` interface.
5790 *
5791 * Custom renderers can pass in the platform specific types like this:
5792 *
5793 * ``` js
5794 * const { render, createApp } = createRenderer<Node, Element>({
5795 * patchProp,
5796 * ...nodeOps
5797 * })
5798 * ```
5799 */
5800 function createRenderer(options) {
5801 return baseCreateRenderer(options);
5802 }
5803 // Separate API for creating hydration-enabled renderer.
5804 // Hydration logic is only used when calling this function, making it
5805 // tree-shakable.
5806 function createHydrationRenderer(options) {
5807 return baseCreateRenderer(options, createHydrationFunctions);
5808 }
5809 // implementation
5810 function baseCreateRenderer(options, createHydrationFns) {
5811 {
5812 const target = getGlobalThis();
5813 target.__VUE__ = true;
5814 setDevtoolsHook(target.__VUE_DEVTOOLS_GLOBAL_HOOK__);
5815 }
5816 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;
5817 // Note: functions inside this closure should use `const xxx = () => {}`
5818 // style in order to prevent being inlined by minifiers.
5819 const patch = (n1, n2, container, anchor = null, parentComponent = null, parentSuspense = null, isSVG = false, slotScopeIds = null, optimized = false) => {
5820 // patching & not same type, unmount old tree
5821 if (n1 && !isSameVNodeType(n1, n2)) {
5822 anchor = getNextHostNode(n1);
5823 unmount(n1, parentComponent, parentSuspense, true);
5824 n1 = null;
5825 }
5826 if (n2.patchFlag === -2 /* BAIL */) {
5827 optimized = false;
5828 n2.dynamicChildren = null;
5829 }
5830 const { type, ref, shapeFlag } = n2;
5831 switch (type) {
5832 case Text:
5833 processText(n1, n2, container, anchor);
5834 break;
5835 case Comment$1:
5836 processCommentNode(n1, n2, container, anchor);
5837 break;
5838 case Static:
5839 if (n1 == null) {
5840 mountStaticNode(n2, container, anchor, isSVG);
5841 }
5842 else {
5843 patchStaticNode(n1, n2, container, isSVG);
5844 }
5845 break;
5846 case Fragment:
5847 processFragment(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5848 break;
5849 default:
5850 if (shapeFlag & 1 /* ELEMENT */) {
5851 processElement(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5852 }
5853 else if (shapeFlag & 6 /* COMPONENT */) {
5854 processComponent(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5855 }
5856 else if (shapeFlag & 64 /* TELEPORT */) {
5857 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5858 }
5859 else if (shapeFlag & 128 /* SUSPENSE */) {
5860 type.process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals);
5861 }
5862 else {
5863 warn('Invalid VNode type:', type, `(${typeof type})`);
5864 }
5865 }
5866 // set ref
5867 if (ref != null && parentComponent) {
5868 setRef(ref, n1 && n1.ref, parentSuspense, n2 || n1, !n2);
5869 }
5870 };
5871 const processText = (n1, n2, container, anchor) => {
5872 if (n1 == null) {
5873 hostInsert((n2.el = hostCreateText(n2.children)), container, anchor);
5874 }
5875 else {
5876 const el = (n2.el = n1.el);
5877 if (n2.children !== n1.children) {
5878 hostSetText(el, n2.children);
5879 }
5880 }
5881 };
5882 const processCommentNode = (n1, n2, container, anchor) => {
5883 if (n1 == null) {
5884 hostInsert((n2.el = hostCreateComment(n2.children || '')), container, anchor);
5885 }
5886 else {
5887 // there's no support for dynamic comments
5888 n2.el = n1.el;
5889 }
5890 };
5891 const mountStaticNode = (n2, container, anchor, isSVG) => {
5892 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5893 };
5894 /**
5895 * Dev / HMR only
5896 */
5897 const patchStaticNode = (n1, n2, container, isSVG) => {
5898 // static nodes are only patched during dev for HMR
5899 if (n2.children !== n1.children) {
5900 const anchor = hostNextSibling(n1.anchor);
5901 // remove existing
5902 removeStaticNode(n1);
5903 [n2.el, n2.anchor] = hostInsertStaticContent(n2.children, container, anchor, isSVG);
5904 }
5905 else {
5906 n2.el = n1.el;
5907 n2.anchor = n1.anchor;
5908 }
5909 };
5910 const moveStaticNode = ({ el, anchor }, container, nextSibling) => {
5911 let next;
5912 while (el && el !== anchor) {
5913 next = hostNextSibling(el);
5914 hostInsert(el, container, nextSibling);
5915 el = next;
5916 }
5917 hostInsert(anchor, container, nextSibling);
5918 };
5919 const removeStaticNode = ({ el, anchor }) => {
5920 let next;
5921 while (el && el !== anchor) {
5922 next = hostNextSibling(el);
5923 hostRemove(el);
5924 el = next;
5925 }
5926 hostRemove(anchor);
5927 };
5928 const processElement = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5929 isSVG = isSVG || n2.type === 'svg';
5930 if (n1 == null) {
5931 mountElement(n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5932 }
5933 else {
5934 patchElement(n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
5935 }
5936 };
5937 const mountElement = (vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
5938 let el;
5939 let vnodeHook;
5940 const { type, props, shapeFlag, transition, patchFlag, dirs } = vnode;
5941 {
5942 el = vnode.el = hostCreateElement(vnode.type, isSVG, props && props.is, props);
5943 // mount children first, since some props may rely on child content
5944 // being already rendered, e.g. `<select value>`
5945 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
5946 hostSetElementText(el, vnode.children);
5947 }
5948 else if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
5949 mountChildren(vnode.children, el, null, parentComponent, parentSuspense, isSVG && type !== 'foreignObject', slotScopeIds, optimized || !!vnode.dynamicChildren);
5950 }
5951 if (dirs) {
5952 invokeDirectiveHook(vnode, null, parentComponent, 'created');
5953 }
5954 // props
5955 if (props) {
5956 for (const key in props) {
5957 if (!isReservedProp(key)) {
5958 hostPatchProp(el, key, null, props[key], isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
5959 }
5960 }
5961 if ((vnodeHook = props.onVnodeBeforeMount)) {
5962 invokeVNodeHook(vnodeHook, parentComponent, vnode);
5963 }
5964 }
5965 // scopeId
5966 setScopeId(el, vnode, vnode.scopeId, slotScopeIds, parentComponent);
5967 }
5968 {
5969 Object.defineProperty(el, '__vnode', {
5970 value: vnode,
5971 enumerable: false
5972 });
5973 Object.defineProperty(el, '__vueParentComponent', {
5974 value: parentComponent,
5975 enumerable: false
5976 });
5977 }
5978 if (dirs) {
5979 invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount');
5980 }
5981 // #1583 For inside suspense + suspense not resolved case, enter hook should call when suspense resolved
5982 // #1689 For inside suspense + suspense resolved case, just call it
5983 const needCallTransitionHooks = (!parentSuspense || (parentSuspense && !parentSuspense.pendingBranch)) &&
5984 transition &&
5985 !transition.persisted;
5986 if (needCallTransitionHooks) {
5987 transition.beforeEnter(el);
5988 }
5989 hostInsert(el, container, anchor);
5990 if ((vnodeHook = props && props.onVnodeMounted) ||
5991 needCallTransitionHooks ||
5992 dirs) {
5993 queuePostRenderEffect(() => {
5994 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
5995 needCallTransitionHooks && transition.enter(el);
5996 dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted');
5997 }, parentSuspense);
5998 }
5999 };
6000 const setScopeId = (el, vnode, scopeId, slotScopeIds, parentComponent) => {
6001 if (scopeId) {
6002 hostSetScopeId(el, scopeId);
6003 }
6004 if (slotScopeIds) {
6005 for (let i = 0; i < slotScopeIds.length; i++) {
6006 hostSetScopeId(el, slotScopeIds[i]);
6007 }
6008 }
6009 if (parentComponent) {
6010 let subTree = parentComponent.subTree;
6011 if (subTree.patchFlag > 0 &&
6012 subTree.patchFlag & 2048 /* DEV_ROOT_FRAGMENT */) {
6013 subTree =
6014 filterSingleRoot(subTree.children) || subTree;
6015 }
6016 if (vnode === subTree) {
6017 const parentVNode = parentComponent.vnode;
6018 setScopeId(el, parentVNode, parentVNode.scopeId, parentVNode.slotScopeIds, parentComponent.parent);
6019 }
6020 }
6021 };
6022 const mountChildren = (children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, start = 0) => {
6023 for (let i = start; i < children.length; i++) {
6024 const child = (children[i] = optimized
6025 ? cloneIfMounted(children[i])
6026 : normalizeVNode(children[i]));
6027 patch(null, child, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6028 }
6029 };
6030 const patchElement = (n1, n2, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6031 const el = (n2.el = n1.el);
6032 let { patchFlag, dynamicChildren, dirs } = n2;
6033 // #1426 take the old vnode's patch flag into account since user may clone a
6034 // compiler-generated vnode, which de-opts to FULL_PROPS
6035 patchFlag |= n1.patchFlag & 16 /* FULL_PROPS */;
6036 const oldProps = n1.props || EMPTY_OBJ;
6037 const newProps = n2.props || EMPTY_OBJ;
6038 let vnodeHook;
6039 if ((vnodeHook = newProps.onVnodeBeforeUpdate)) {
6040 invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6041 }
6042 if (dirs) {
6043 invokeDirectiveHook(n2, n1, parentComponent, 'beforeUpdate');
6044 }
6045 if (isHmrUpdating) {
6046 // HMR updated, force full diff
6047 patchFlag = 0;
6048 optimized = false;
6049 dynamicChildren = null;
6050 }
6051 if (patchFlag > 0) {
6052 // the presence of a patchFlag means this element's render code was
6053 // generated by the compiler and can take the fast path.
6054 // in this path old node and new node are guaranteed to have the same shape
6055 // (i.e. at the exact same position in the source template)
6056 if (patchFlag & 16 /* FULL_PROPS */) {
6057 // element props contain dynamic keys, full diff needed
6058 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6059 }
6060 else {
6061 // class
6062 // this flag is matched when the element has dynamic class bindings.
6063 if (patchFlag & 2 /* CLASS */) {
6064 if (oldProps.class !== newProps.class) {
6065 hostPatchProp(el, 'class', null, newProps.class, isSVG);
6066 }
6067 }
6068 // style
6069 // this flag is matched when the element has dynamic style bindings
6070 if (patchFlag & 4 /* STYLE */) {
6071 hostPatchProp(el, 'style', oldProps.style, newProps.style, isSVG);
6072 }
6073 // props
6074 // This flag is matched when the element has dynamic prop/attr bindings
6075 // other than class and style. The keys of dynamic prop/attrs are saved for
6076 // faster iteration.
6077 // Note dynamic keys like :[foo]="bar" will cause this optimization to
6078 // bail out and go through a full diff because we need to unset the old key
6079 if (patchFlag & 8 /* PROPS */) {
6080 // if the flag is present then dynamicProps must be non-null
6081 const propsToUpdate = n2.dynamicProps;
6082 for (let i = 0; i < propsToUpdate.length; i++) {
6083 const key = propsToUpdate[i];
6084 const prev = oldProps[key];
6085 const next = newProps[key];
6086 if (next !== prev ||
6087 (hostForcePatchProp && hostForcePatchProp(el, key))) {
6088 hostPatchProp(el, key, prev, next, isSVG, n1.children, parentComponent, parentSuspense, unmountChildren);
6089 }
6090 }
6091 }
6092 }
6093 // text
6094 // This flag is matched when the element has only dynamic text children.
6095 if (patchFlag & 1 /* TEXT */) {
6096 if (n1.children !== n2.children) {
6097 hostSetElementText(el, n2.children);
6098 }
6099 }
6100 }
6101 else if (!optimized && dynamicChildren == null) {
6102 // unoptimized, full diff
6103 patchProps(el, n2, oldProps, newProps, parentComponent, parentSuspense, isSVG);
6104 }
6105 const areChildrenSVG = isSVG && n2.type !== 'foreignObject';
6106 if (dynamicChildren) {
6107 patchBlockChildren(n1.dynamicChildren, dynamicChildren, el, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds);
6108 if (parentComponent && parentComponent.type.__hmrId) {
6109 traverseStaticChildren(n1, n2);
6110 }
6111 }
6112 else if (!optimized) {
6113 // full diff
6114 patchChildren(n1, n2, el, null, parentComponent, parentSuspense, areChildrenSVG, slotScopeIds, false);
6115 }
6116 if ((vnodeHook = newProps.onVnodeUpdated) || dirs) {
6117 queuePostRenderEffect(() => {
6118 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, n2, n1);
6119 dirs && invokeDirectiveHook(n2, n1, parentComponent, 'updated');
6120 }, parentSuspense);
6121 }
6122 };
6123 // The fast path for blocks.
6124 const patchBlockChildren = (oldChildren, newChildren, fallbackContainer, parentComponent, parentSuspense, isSVG, slotScopeIds) => {
6125 for (let i = 0; i < newChildren.length; i++) {
6126 const oldVNode = oldChildren[i];
6127 const newVNode = newChildren[i];
6128 // Determine the container (parent element) for the patch.
6129 const container =
6130 // oldVNode may be an errored async setup() component inside Suspense
6131 // which will not have a mounted element
6132 oldVNode.el &&
6133 // - In the case of a Fragment, we need to provide the actual parent
6134 // of the Fragment itself so it can move its children.
6135 (oldVNode.type === Fragment ||
6136 // - In the case of different nodes, there is going to be a replacement
6137 // which also requires the correct parent container
6138 !isSameVNodeType(oldVNode, newVNode) ||
6139 // - In the case of a component, it could contain anything.
6140 oldVNode.shapeFlag & 6 /* COMPONENT */ ||
6141 oldVNode.shapeFlag & 64 /* TELEPORT */)
6142 ? hostParentNode(oldVNode.el)
6143 : // In other cases, the parent container is not actually used so we
6144 // just pass the block element here to avoid a DOM parentNode call.
6145 fallbackContainer;
6146 patch(oldVNode, newVNode, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, true);
6147 }
6148 };
6149 const patchProps = (el, vnode, oldProps, newProps, parentComponent, parentSuspense, isSVG) => {
6150 if (oldProps !== newProps) {
6151 for (const key in newProps) {
6152 // empty string is not valid prop
6153 if (isReservedProp(key))
6154 continue;
6155 const next = newProps[key];
6156 const prev = oldProps[key];
6157 if (next !== prev ||
6158 (hostForcePatchProp && hostForcePatchProp(el, key))) {
6159 hostPatchProp(el, key, prev, next, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6160 }
6161 }
6162 if (oldProps !== EMPTY_OBJ) {
6163 for (const key in oldProps) {
6164 if (!isReservedProp(key) && !(key in newProps)) {
6165 hostPatchProp(el, key, oldProps[key], null, isSVG, vnode.children, parentComponent, parentSuspense, unmountChildren);
6166 }
6167 }
6168 }
6169 }
6170 };
6171 const processFragment = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6172 const fragmentStartAnchor = (n2.el = n1 ? n1.el : hostCreateText(''));
6173 const fragmentEndAnchor = (n2.anchor = n1 ? n1.anchor : hostCreateText(''));
6174 let { patchFlag, dynamicChildren, slotScopeIds: fragmentSlotScopeIds } = n2;
6175 if (dynamicChildren) {
6176 optimized = true;
6177 }
6178 // check if this is a slot fragment with :slotted scope ids
6179 if (fragmentSlotScopeIds) {
6180 slotScopeIds = slotScopeIds
6181 ? slotScopeIds.concat(fragmentSlotScopeIds)
6182 : fragmentSlotScopeIds;
6183 }
6184 if (isHmrUpdating) {
6185 // HMR updated, force full diff
6186 patchFlag = 0;
6187 optimized = false;
6188 dynamicChildren = null;
6189 }
6190 if (n1 == null) {
6191 hostInsert(fragmentStartAnchor, container, anchor);
6192 hostInsert(fragmentEndAnchor, container, anchor);
6193 // a fragment can only have array children
6194 // since they are either generated by the compiler, or implicitly created
6195 // from arrays.
6196 mountChildren(n2.children, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6197 }
6198 else {
6199 if (patchFlag > 0 &&
6200 patchFlag & 64 /* STABLE_FRAGMENT */ &&
6201 dynamicChildren &&
6202 // #2715 the previous fragment could've been a BAILed one as a result
6203 // of renderSlot() with no valid children
6204 n1.dynamicChildren) {
6205 // a stable fragment (template root or <template v-for>) doesn't need to
6206 // patch children order, but it may contain dynamicChildren.
6207 patchBlockChildren(n1.dynamicChildren, dynamicChildren, container, parentComponent, parentSuspense, isSVG, slotScopeIds);
6208 if (parentComponent && parentComponent.type.__hmrId) {
6209 traverseStaticChildren(n1, n2);
6210 }
6211 else if (
6212 // #2080 if the stable fragment has a key, it's a <template v-for> that may
6213 // get moved around. Make sure all root level vnodes inherit el.
6214 // #2134 or if it's a component root, it may also get moved around
6215 // as the component is being moved.
6216 n2.key != null ||
6217 (parentComponent && n2 === parentComponent.subTree)) {
6218 traverseStaticChildren(n1, n2, true /* shallow */);
6219 }
6220 }
6221 else {
6222 // keyed / unkeyed, or manual fragments.
6223 // for keyed & unkeyed, since they are compiler generated from v-for,
6224 // each child is guaranteed to be a block so the fragment will never
6225 // have dynamicChildren.
6226 patchChildren(n1, n2, container, fragmentEndAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6227 }
6228 }
6229 };
6230 const processComponent = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6231 n2.slotScopeIds = slotScopeIds;
6232 if (n1 == null) {
6233 if (n2.shapeFlag & 512 /* COMPONENT_KEPT_ALIVE */) {
6234 parentComponent.ctx.activate(n2, container, anchor, isSVG, optimized);
6235 }
6236 else {
6237 mountComponent(n2, container, anchor, parentComponent, parentSuspense, isSVG, optimized);
6238 }
6239 }
6240 else {
6241 updateComponent(n1, n2, optimized);
6242 }
6243 };
6244 const mountComponent = (initialVNode, container, anchor, parentComponent, parentSuspense, isSVG, optimized) => {
6245 const instance = (initialVNode.component = createComponentInstance(initialVNode, parentComponent, parentSuspense));
6246 if (instance.type.__hmrId) {
6247 registerHMR(instance);
6248 }
6249 {
6250 pushWarningContext(initialVNode);
6251 startMeasure(instance, `mount`);
6252 }
6253 // inject renderer internals for keepAlive
6254 if (isKeepAlive(initialVNode)) {
6255 instance.ctx.renderer = internals;
6256 }
6257 // resolve props and slots for setup context
6258 {
6259 {
6260 startMeasure(instance, `init`);
6261 }
6262 setupComponent(instance);
6263 {
6264 endMeasure(instance, `init`);
6265 }
6266 }
6267 // setup() is async. This component relies on async logic to be resolved
6268 // before proceeding
6269 if (instance.asyncDep) {
6270 parentSuspense && parentSuspense.registerDep(instance, setupRenderEffect);
6271 // Give it a placeholder if this is not hydration
6272 // TODO handle self-defined fallback
6273 if (!initialVNode.el) {
6274 const placeholder = (instance.subTree = createVNode(Comment$1));
6275 processCommentNode(null, placeholder, container, anchor);
6276 }
6277 return;
6278 }
6279 setupRenderEffect(instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized);
6280 {
6281 popWarningContext();
6282 endMeasure(instance, `mount`);
6283 }
6284 };
6285 const updateComponent = (n1, n2, optimized) => {
6286 const instance = (n2.component = n1.component);
6287 if (shouldUpdateComponent(n1, n2, optimized)) {
6288 if (instance.asyncDep &&
6289 !instance.asyncResolved) {
6290 // async & still pending - just update props and slots
6291 // since the component's reactive effect for render isn't set-up yet
6292 {
6293 pushWarningContext(n2);
6294 }
6295 updateComponentPreRender(instance, n2, optimized);
6296 {
6297 popWarningContext();
6298 }
6299 return;
6300 }
6301 else {
6302 // normal update
6303 instance.next = n2;
6304 // in case the child component is also queued, remove it to avoid
6305 // double updating the same child component in the same flush.
6306 invalidateJob(instance.update);
6307 // instance.update is the reactive effect runner.
6308 instance.update();
6309 }
6310 }
6311 else {
6312 // no update needed. just copy over properties
6313 n2.component = n1.component;
6314 n2.el = n1.el;
6315 instance.vnode = n2;
6316 }
6317 };
6318 const setupRenderEffect = (instance, initialVNode, container, anchor, parentSuspense, isSVG, optimized) => {
6319 // create reactive effect for rendering
6320 instance.update = effect(function componentEffect() {
6321 if (!instance.isMounted) {
6322 let vnodeHook;
6323 const { el, props } = initialVNode;
6324 const { bm, m, parent } = instance;
6325 // beforeMount hook
6326 if (bm) {
6327 invokeArrayFns(bm);
6328 }
6329 // onVnodeBeforeMount
6330 if ((vnodeHook = props && props.onVnodeBeforeMount)) {
6331 invokeVNodeHook(vnodeHook, parent, initialVNode);
6332 }
6333 if (el && hydrateNode) {
6334 // vnode has adopted host node - perform hydration instead of mount.
6335 const hydrateSubTree = () => {
6336 {
6337 startMeasure(instance, `render`);
6338 }
6339 instance.subTree = renderComponentRoot(instance);
6340 {
6341 endMeasure(instance, `render`);
6342 }
6343 {
6344 startMeasure(instance, `hydrate`);
6345 }
6346 hydrateNode(el, instance.subTree, instance, parentSuspense, null);
6347 {
6348 endMeasure(instance, `hydrate`);
6349 }
6350 };
6351 if (isAsyncWrapper(initialVNode)) {
6352 initialVNode.type.__asyncLoader().then(
6353 // note: we are moving the render call into an async callback,
6354 // which means it won't track dependencies - but it's ok because
6355 // a server-rendered async wrapper is already in resolved state
6356 // and it will never need to change.
6357 () => !instance.isUnmounted && hydrateSubTree());
6358 }
6359 else {
6360 hydrateSubTree();
6361 }
6362 }
6363 else {
6364 {
6365 startMeasure(instance, `render`);
6366 }
6367 const subTree = (instance.subTree = renderComponentRoot(instance));
6368 {
6369 endMeasure(instance, `render`);
6370 }
6371 {
6372 startMeasure(instance, `patch`);
6373 }
6374 patch(null, subTree, container, anchor, instance, parentSuspense, isSVG);
6375 {
6376 endMeasure(instance, `patch`);
6377 }
6378 initialVNode.el = subTree.el;
6379 }
6380 // mounted hook
6381 if (m) {
6382 queuePostRenderEffect(m, parentSuspense);
6383 }
6384 // onVnodeMounted
6385 if ((vnodeHook = props && props.onVnodeMounted)) {
6386 const scopedInitialVNode = initialVNode;
6387 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, scopedInitialVNode), parentSuspense);
6388 }
6389 // activated hook for keep-alive roots.
6390 // #1742 activated hook must be accessed after first render
6391 // since the hook may be injected by a child keep-alive
6392 if (initialVNode.shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6393 instance.a && queuePostRenderEffect(instance.a, parentSuspense);
6394 }
6395 instance.isMounted = true;
6396 {
6397 devtoolsComponentAdded(instance);
6398 }
6399 // #2458: deference mount-only object parameters to prevent memleaks
6400 initialVNode = container = anchor = null;
6401 }
6402 else {
6403 // updateComponent
6404 // This is triggered by mutation of component's own state (next: null)
6405 // OR parent calling processComponent (next: VNode)
6406 let { next, bu, u, parent, vnode } = instance;
6407 let originNext = next;
6408 let vnodeHook;
6409 {
6410 pushWarningContext(next || instance.vnode);
6411 }
6412 if (next) {
6413 next.el = vnode.el;
6414 updateComponentPreRender(instance, next, optimized);
6415 }
6416 else {
6417 next = vnode;
6418 }
6419 // beforeUpdate hook
6420 if (bu) {
6421 invokeArrayFns(bu);
6422 }
6423 // onVnodeBeforeUpdate
6424 if ((vnodeHook = next.props && next.props.onVnodeBeforeUpdate)) {
6425 invokeVNodeHook(vnodeHook, parent, next, vnode);
6426 }
6427 // render
6428 {
6429 startMeasure(instance, `render`);
6430 }
6431 const nextTree = renderComponentRoot(instance);
6432 {
6433 endMeasure(instance, `render`);
6434 }
6435 const prevTree = instance.subTree;
6436 instance.subTree = nextTree;
6437 {
6438 startMeasure(instance, `patch`);
6439 }
6440 patch(prevTree, nextTree,
6441 // parent may have changed if it's in a teleport
6442 hostParentNode(prevTree.el),
6443 // anchor may have changed if it's in a fragment
6444 getNextHostNode(prevTree), instance, parentSuspense, isSVG);
6445 {
6446 endMeasure(instance, `patch`);
6447 }
6448 next.el = nextTree.el;
6449 if (originNext === null) {
6450 // self-triggered update. In case of HOC, update parent component
6451 // vnode el. HOC is indicated by parent instance's subTree pointing
6452 // to child component's vnode
6453 updateHOCHostEl(instance, nextTree.el);
6454 }
6455 // updated hook
6456 if (u) {
6457 queuePostRenderEffect(u, parentSuspense);
6458 }
6459 // onVnodeUpdated
6460 if ((vnodeHook = next.props && next.props.onVnodeUpdated)) {
6461 queuePostRenderEffect(() => invokeVNodeHook(vnodeHook, parent, next, vnode), parentSuspense);
6462 }
6463 {
6464 devtoolsComponentUpdated(instance);
6465 }
6466 {
6467 popWarningContext();
6468 }
6469 }
6470 }, createDevEffectOptions(instance) );
6471 {
6472 // @ts-ignore
6473 instance.update.ownerInstance = instance;
6474 }
6475 };
6476 const updateComponentPreRender = (instance, nextVNode, optimized) => {
6477 nextVNode.component = instance;
6478 const prevProps = instance.vnode.props;
6479 instance.vnode = nextVNode;
6480 instance.next = null;
6481 updateProps(instance, nextVNode.props, prevProps, optimized);
6482 updateSlots(instance, nextVNode.children, optimized);
6483 pauseTracking();
6484 // props update may have triggered pre-flush watchers.
6485 // flush them before the render update.
6486 flushPreFlushCbs(undefined, instance.update);
6487 resetTracking();
6488 };
6489 const patchChildren = (n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized = false) => {
6490 const c1 = n1 && n1.children;
6491 const prevShapeFlag = n1 ? n1.shapeFlag : 0;
6492 const c2 = n2.children;
6493 const { patchFlag, shapeFlag } = n2;
6494 // fast path
6495 if (patchFlag > 0) {
6496 if (patchFlag & 128 /* KEYED_FRAGMENT */) {
6497 // this could be either fully-keyed or mixed (some keyed some not)
6498 // presence of patchFlag means children are guaranteed to be arrays
6499 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6500 return;
6501 }
6502 else if (patchFlag & 256 /* UNKEYED_FRAGMENT */) {
6503 // unkeyed
6504 patchUnkeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6505 return;
6506 }
6507 }
6508 // children has 3 possibilities: text, array or no children.
6509 if (shapeFlag & 8 /* TEXT_CHILDREN */) {
6510 // text children fast path
6511 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6512 unmountChildren(c1, parentComponent, parentSuspense);
6513 }
6514 if (c2 !== c1) {
6515 hostSetElementText(container, c2);
6516 }
6517 }
6518 else {
6519 if (prevShapeFlag & 16 /* ARRAY_CHILDREN */) {
6520 // prev children was array
6521 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6522 // two arrays, cannot assume anything, do full diff
6523 patchKeyedChildren(c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6524 }
6525 else {
6526 // no new children, just unmount old
6527 unmountChildren(c1, parentComponent, parentSuspense, true);
6528 }
6529 }
6530 else {
6531 // prev children was text OR null
6532 // new children is array OR null
6533 if (prevShapeFlag & 8 /* TEXT_CHILDREN */) {
6534 hostSetElementText(container, '');
6535 }
6536 // mount new if array
6537 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
6538 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6539 }
6540 }
6541 }
6542 };
6543 const patchUnkeyedChildren = (c1, c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6544 c1 = c1 || EMPTY_ARR;
6545 c2 = c2 || EMPTY_ARR;
6546 const oldLength = c1.length;
6547 const newLength = c2.length;
6548 const commonLength = Math.min(oldLength, newLength);
6549 let i;
6550 for (i = 0; i < commonLength; i++) {
6551 const nextChild = (c2[i] = optimized
6552 ? cloneIfMounted(c2[i])
6553 : normalizeVNode(c2[i]));
6554 patch(c1[i], nextChild, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6555 }
6556 if (oldLength > newLength) {
6557 // remove old
6558 unmountChildren(c1, parentComponent, parentSuspense, true, false, commonLength);
6559 }
6560 else {
6561 // mount new
6562 mountChildren(c2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, commonLength);
6563 }
6564 };
6565 // can be all-keyed or mixed
6566 const patchKeyedChildren = (c1, c2, container, parentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized) => {
6567 let i = 0;
6568 const l2 = c2.length;
6569 let e1 = c1.length - 1; // prev ending index
6570 let e2 = l2 - 1; // next ending index
6571 // 1. sync from start
6572 // (a b) c
6573 // (a b) d e
6574 while (i <= e1 && i <= e2) {
6575 const n1 = c1[i];
6576 const n2 = (c2[i] = optimized
6577 ? cloneIfMounted(c2[i])
6578 : normalizeVNode(c2[i]));
6579 if (isSameVNodeType(n1, n2)) {
6580 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6581 }
6582 else {
6583 break;
6584 }
6585 i++;
6586 }
6587 // 2. sync from end
6588 // a (b c)
6589 // d e (b c)
6590 while (i <= e1 && i <= e2) {
6591 const n1 = c1[e1];
6592 const n2 = (c2[e2] = optimized
6593 ? cloneIfMounted(c2[e2])
6594 : normalizeVNode(c2[e2]));
6595 if (isSameVNodeType(n1, n2)) {
6596 patch(n1, n2, container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6597 }
6598 else {
6599 break;
6600 }
6601 e1--;
6602 e2--;
6603 }
6604 // 3. common sequence + mount
6605 // (a b)
6606 // (a b) c
6607 // i = 2, e1 = 1, e2 = 2
6608 // (a b)
6609 // c (a b)
6610 // i = 0, e1 = -1, e2 = 0
6611 if (i > e1) {
6612 if (i <= e2) {
6613 const nextPos = e2 + 1;
6614 const anchor = nextPos < l2 ? c2[nextPos].el : parentAnchor;
6615 while (i <= e2) {
6616 patch(null, (c2[i] = optimized
6617 ? cloneIfMounted(c2[i])
6618 : normalizeVNode(c2[i])), container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6619 i++;
6620 }
6621 }
6622 }
6623 // 4. common sequence + unmount
6624 // (a b) c
6625 // (a b)
6626 // i = 2, e1 = 2, e2 = 1
6627 // a (b c)
6628 // (b c)
6629 // i = 0, e1 = 0, e2 = -1
6630 else if (i > e2) {
6631 while (i <= e1) {
6632 unmount(c1[i], parentComponent, parentSuspense, true);
6633 i++;
6634 }
6635 }
6636 // 5. unknown sequence
6637 // [i ... e1 + 1]: a b [c d e] f g
6638 // [i ... e2 + 1]: a b [e d c h] f g
6639 // i = 2, e1 = 4, e2 = 5
6640 else {
6641 const s1 = i; // prev starting index
6642 const s2 = i; // next starting index
6643 // 5.1 build key:index map for newChildren
6644 const keyToNewIndexMap = new Map();
6645 for (i = s2; i <= e2; i++) {
6646 const nextChild = (c2[i] = optimized
6647 ? cloneIfMounted(c2[i])
6648 : normalizeVNode(c2[i]));
6649 if (nextChild.key != null) {
6650 if (keyToNewIndexMap.has(nextChild.key)) {
6651 warn(`Duplicate keys found during update:`, JSON.stringify(nextChild.key), `Make sure keys are unique.`);
6652 }
6653 keyToNewIndexMap.set(nextChild.key, i);
6654 }
6655 }
6656 // 5.2 loop through old children left to be patched and try to patch
6657 // matching nodes & remove nodes that are no longer present
6658 let j;
6659 let patched = 0;
6660 const toBePatched = e2 - s2 + 1;
6661 let moved = false;
6662 // used to track whether any node has moved
6663 let maxNewIndexSoFar = 0;
6664 // works as Map<newIndex, oldIndex>
6665 // Note that oldIndex is offset by +1
6666 // and oldIndex = 0 is a special value indicating the new node has
6667 // no corresponding old node.
6668 // used for determining longest stable subsequence
6669 const newIndexToOldIndexMap = new Array(toBePatched);
6670 for (i = 0; i < toBePatched; i++)
6671 newIndexToOldIndexMap[i] = 0;
6672 for (i = s1; i <= e1; i++) {
6673 const prevChild = c1[i];
6674 if (patched >= toBePatched) {
6675 // all new children have been patched so this can only be a removal
6676 unmount(prevChild, parentComponent, parentSuspense, true);
6677 continue;
6678 }
6679 let newIndex;
6680 if (prevChild.key != null) {
6681 newIndex = keyToNewIndexMap.get(prevChild.key);
6682 }
6683 else {
6684 // key-less node, try to locate a key-less node of the same type
6685 for (j = s2; j <= e2; j++) {
6686 if (newIndexToOldIndexMap[j - s2] === 0 &&
6687 isSameVNodeType(prevChild, c2[j])) {
6688 newIndex = j;
6689 break;
6690 }
6691 }
6692 }
6693 if (newIndex === undefined) {
6694 unmount(prevChild, parentComponent, parentSuspense, true);
6695 }
6696 else {
6697 newIndexToOldIndexMap[newIndex - s2] = i + 1;
6698 if (newIndex >= maxNewIndexSoFar) {
6699 maxNewIndexSoFar = newIndex;
6700 }
6701 else {
6702 moved = true;
6703 }
6704 patch(prevChild, c2[newIndex], container, null, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6705 patched++;
6706 }
6707 }
6708 // 5.3 move and mount
6709 // generate longest stable subsequence only when nodes have moved
6710 const increasingNewIndexSequence = moved
6711 ? getSequence(newIndexToOldIndexMap)
6712 : EMPTY_ARR;
6713 j = increasingNewIndexSequence.length - 1;
6714 // looping backwards so that we can use last patched node as anchor
6715 for (i = toBePatched - 1; i >= 0; i--) {
6716 const nextIndex = s2 + i;
6717 const nextChild = c2[nextIndex];
6718 const anchor = nextIndex + 1 < l2 ? c2[nextIndex + 1].el : parentAnchor;
6719 if (newIndexToOldIndexMap[i] === 0) {
6720 // mount new
6721 patch(null, nextChild, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
6722 }
6723 else if (moved) {
6724 // move if:
6725 // There is no stable subsequence (e.g. a reverse)
6726 // OR current node is not among the stable sequence
6727 if (j < 0 || i !== increasingNewIndexSequence[j]) {
6728 move(nextChild, container, anchor, 2 /* REORDER */);
6729 }
6730 else {
6731 j--;
6732 }
6733 }
6734 }
6735 }
6736 };
6737 const move = (vnode, container, anchor, moveType, parentSuspense = null) => {
6738 const { el, type, transition, children, shapeFlag } = vnode;
6739 if (shapeFlag & 6 /* COMPONENT */) {
6740 move(vnode.component.subTree, container, anchor, moveType);
6741 return;
6742 }
6743 if (shapeFlag & 128 /* SUSPENSE */) {
6744 vnode.suspense.move(container, anchor, moveType);
6745 return;
6746 }
6747 if (shapeFlag & 64 /* TELEPORT */) {
6748 type.move(vnode, container, anchor, internals);
6749 return;
6750 }
6751 if (type === Fragment) {
6752 hostInsert(el, container, anchor);
6753 for (let i = 0; i < children.length; i++) {
6754 move(children[i], container, anchor, moveType);
6755 }
6756 hostInsert(vnode.anchor, container, anchor);
6757 return;
6758 }
6759 if (type === Static) {
6760 moveStaticNode(vnode, container, anchor);
6761 return;
6762 }
6763 // single nodes
6764 const needTransition = moveType !== 2 /* REORDER */ &&
6765 shapeFlag & 1 /* ELEMENT */ &&
6766 transition;
6767 if (needTransition) {
6768 if (moveType === 0 /* ENTER */) {
6769 transition.beforeEnter(el);
6770 hostInsert(el, container, anchor);
6771 queuePostRenderEffect(() => transition.enter(el), parentSuspense);
6772 }
6773 else {
6774 const { leave, delayLeave, afterLeave } = transition;
6775 const remove = () => hostInsert(el, container, anchor);
6776 const performLeave = () => {
6777 leave(el, () => {
6778 remove();
6779 afterLeave && afterLeave();
6780 });
6781 };
6782 if (delayLeave) {
6783 delayLeave(el, remove, performLeave);
6784 }
6785 else {
6786 performLeave();
6787 }
6788 }
6789 }
6790 else {
6791 hostInsert(el, container, anchor);
6792 }
6793 };
6794 const unmount = (vnode, parentComponent, parentSuspense, doRemove = false, optimized = false) => {
6795 const { type, props, ref, children, dynamicChildren, shapeFlag, patchFlag, dirs } = vnode;
6796 // unset ref
6797 if (ref != null) {
6798 setRef(ref, null, parentSuspense, vnode, true);
6799 }
6800 if (shapeFlag & 256 /* COMPONENT_SHOULD_KEEP_ALIVE */) {
6801 parentComponent.ctx.deactivate(vnode);
6802 return;
6803 }
6804 const shouldInvokeDirs = shapeFlag & 1 /* ELEMENT */ && dirs;
6805 let vnodeHook;
6806 if ((vnodeHook = props && props.onVnodeBeforeUnmount)) {
6807 invokeVNodeHook(vnodeHook, parentComponent, vnode);
6808 }
6809 if (shapeFlag & 6 /* COMPONENT */) {
6810 unmountComponent(vnode.component, parentSuspense, doRemove);
6811 }
6812 else {
6813 if (shapeFlag & 128 /* SUSPENSE */) {
6814 vnode.suspense.unmount(parentSuspense, doRemove);
6815 return;
6816 }
6817 if (shouldInvokeDirs) {
6818 invokeDirectiveHook(vnode, null, parentComponent, 'beforeUnmount');
6819 }
6820 if (shapeFlag & 64 /* TELEPORT */) {
6821 vnode.type.remove(vnode, parentComponent, parentSuspense, optimized, internals, doRemove);
6822 }
6823 else if (dynamicChildren &&
6824 // #1153: fast path should not be taken for non-stable (v-for) fragments
6825 (type !== Fragment ||
6826 (patchFlag > 0 && patchFlag & 64 /* STABLE_FRAGMENT */))) {
6827 // fast path for block nodes: only need to unmount dynamic children.
6828 unmountChildren(dynamicChildren, parentComponent, parentSuspense, false, true);
6829 }
6830 else if ((type === Fragment &&
6831 (patchFlag & 128 /* KEYED_FRAGMENT */ ||
6832 patchFlag & 256 /* UNKEYED_FRAGMENT */)) ||
6833 (!optimized && shapeFlag & 16 /* ARRAY_CHILDREN */)) {
6834 unmountChildren(children, parentComponent, parentSuspense);
6835 }
6836 if (doRemove) {
6837 remove(vnode);
6838 }
6839 }
6840 if ((vnodeHook = props && props.onVnodeUnmounted) || shouldInvokeDirs) {
6841 queuePostRenderEffect(() => {
6842 vnodeHook && invokeVNodeHook(vnodeHook, parentComponent, vnode);
6843 shouldInvokeDirs &&
6844 invokeDirectiveHook(vnode, null, parentComponent, 'unmounted');
6845 }, parentSuspense);
6846 }
6847 };
6848 const remove = vnode => {
6849 const { type, el, anchor, transition } = vnode;
6850 if (type === Fragment) {
6851 removeFragment(el, anchor);
6852 return;
6853 }
6854 if (type === Static) {
6855 removeStaticNode(vnode);
6856 return;
6857 }
6858 const performRemove = () => {
6859 hostRemove(el);
6860 if (transition && !transition.persisted && transition.afterLeave) {
6861 transition.afterLeave();
6862 }
6863 };
6864 if (vnode.shapeFlag & 1 /* ELEMENT */ &&
6865 transition &&
6866 !transition.persisted) {
6867 const { leave, delayLeave } = transition;
6868 const performLeave = () => leave(el, performRemove);
6869 if (delayLeave) {
6870 delayLeave(vnode.el, performRemove, performLeave);
6871 }
6872 else {
6873 performLeave();
6874 }
6875 }
6876 else {
6877 performRemove();
6878 }
6879 };
6880 const removeFragment = (cur, end) => {
6881 // For fragments, directly remove all contained DOM nodes.
6882 // (fragment child nodes cannot have transition)
6883 let next;
6884 while (cur !== end) {
6885 next = hostNextSibling(cur);
6886 hostRemove(cur);
6887 cur = next;
6888 }
6889 hostRemove(end);
6890 };
6891 const unmountComponent = (instance, parentSuspense, doRemove) => {
6892 if (instance.type.__hmrId) {
6893 unregisterHMR(instance);
6894 }
6895 const { bum, effects, update, subTree, um } = instance;
6896 // beforeUnmount hook
6897 if (bum) {
6898 invokeArrayFns(bum);
6899 }
6900 if (effects) {
6901 for (let i = 0; i < effects.length; i++) {
6902 stop(effects[i]);
6903 }
6904 }
6905 // update may be null if a component is unmounted before its async
6906 // setup has resolved.
6907 if (update) {
6908 stop(update);
6909 unmount(subTree, instance, parentSuspense, doRemove);
6910 }
6911 // unmounted hook
6912 if (um) {
6913 queuePostRenderEffect(um, parentSuspense);
6914 }
6915 queuePostRenderEffect(() => {
6916 instance.isUnmounted = true;
6917 }, parentSuspense);
6918 // A component with async dep inside a pending suspense is unmounted before
6919 // its async dep resolves. This should remove the dep from the suspense, and
6920 // cause the suspense to resolve immediately if that was the last dep.
6921 if (parentSuspense &&
6922 parentSuspense.pendingBranch &&
6923 !parentSuspense.isUnmounted &&
6924 instance.asyncDep &&
6925 !instance.asyncResolved &&
6926 instance.suspenseId === parentSuspense.pendingId) {
6927 parentSuspense.deps--;
6928 if (parentSuspense.deps === 0) {
6929 parentSuspense.resolve();
6930 }
6931 }
6932 {
6933 devtoolsComponentRemoved(instance);
6934 }
6935 };
6936 const unmountChildren = (children, parentComponent, parentSuspense, doRemove = false, optimized = false, start = 0) => {
6937 for (let i = start; i < children.length; i++) {
6938 unmount(children[i], parentComponent, parentSuspense, doRemove, optimized);
6939 }
6940 };
6941 const getNextHostNode = vnode => {
6942 if (vnode.shapeFlag & 6 /* COMPONENT */) {
6943 return getNextHostNode(vnode.component.subTree);
6944 }
6945 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
6946 return vnode.suspense.next();
6947 }
6948 return hostNextSibling((vnode.anchor || vnode.el));
6949 };
6950 const render = (vnode, container, isSVG) => {
6951 if (vnode == null) {
6952 if (container._vnode) {
6953 unmount(container._vnode, null, null, true);
6954 }
6955 }
6956 else {
6957 patch(container._vnode || null, vnode, container, null, null, null, isSVG);
6958 }
6959 flushPostFlushCbs();
6960 container._vnode = vnode;
6961 };
6962 const internals = {
6963 p: patch,
6964 um: unmount,
6965 m: move,
6966 r: remove,
6967 mt: mountComponent,
6968 mc: mountChildren,
6969 pc: patchChildren,
6970 pbc: patchBlockChildren,
6971 n: getNextHostNode,
6972 o: options
6973 };
6974 let hydrate;
6975 let hydrateNode;
6976 if (createHydrationFns) {
6977 [hydrate, hydrateNode] = createHydrationFns(internals);
6978 }
6979 return {
6980 render,
6981 hydrate,
6982 createApp: createAppAPI(render, hydrate)
6983 };
6984 }
6985 function invokeVNodeHook(hook, instance, vnode, prevVNode = null) {
6986 callWithAsyncErrorHandling(hook, instance, 7 /* VNODE_HOOK */, [
6987 vnode,
6988 prevVNode
6989 ]);
6990 }
6991 /**
6992 * #1156
6993 * When a component is HMR-enabled, we need to make sure that all static nodes
6994 * inside a block also inherit the DOM element from the previous tree so that
6995 * HMR updates (which are full updates) can retrieve the element for patching.
6996 *
6997 * #2080
6998 * Inside keyed `template` fragment static children, if a fragment is moved,
6999 * the children will always moved so that need inherit el form previous nodes
7000 * to ensure correct moved position.
7001 */
7002 function traverseStaticChildren(n1, n2, shallow = false) {
7003 const ch1 = n1.children;
7004 const ch2 = n2.children;
7005 if (isArray(ch1) && isArray(ch2)) {
7006 for (let i = 0; i < ch1.length; i++) {
7007 // this is only called in the optimized path so array children are
7008 // guaranteed to be vnodes
7009 const c1 = ch1[i];
7010 let c2 = ch2[i];
7011 if (c2.shapeFlag & 1 /* ELEMENT */ && !c2.dynamicChildren) {
7012 if (c2.patchFlag <= 0 || c2.patchFlag === 32 /* HYDRATE_EVENTS */) {
7013 c2 = ch2[i] = cloneIfMounted(ch2[i]);
7014 c2.el = c1.el;
7015 }
7016 if (!shallow)
7017 traverseStaticChildren(c1, c2);
7018 }
7019 // also inherit for comment nodes, but not placeholders (e.g. v-if which
7020 // would have received .el during block patch)
7021 if (c2.type === Comment$1 && !c2.el) {
7022 c2.el = c1.el;
7023 }
7024 }
7025 }
7026 }
7027 // https://en.wikipedia.org/wiki/Longest_increasing_subsequence
7028 function getSequence(arr) {
7029 const p = arr.slice();
7030 const result = [0];
7031 let i, j, u, v, c;
7032 const len = arr.length;
7033 for (i = 0; i < len; i++) {
7034 const arrI = arr[i];
7035 if (arrI !== 0) {
7036 j = result[result.length - 1];
7037 if (arr[j] < arrI) {
7038 p[i] = j;
7039 result.push(i);
7040 continue;
7041 }
7042 u = 0;
7043 v = result.length - 1;
7044 while (u < v) {
7045 c = ((u + v) / 2) | 0;
7046 if (arr[result[c]] < arrI) {
7047 u = c + 1;
7048 }
7049 else {
7050 v = c;
7051 }
7052 }
7053 if (arrI < arr[result[u]]) {
7054 if (u > 0) {
7055 p[i] = result[u - 1];
7056 }
7057 result[u] = i;
7058 }
7059 }
7060 }
7061 u = result.length;
7062 v = result[u - 1];
7063 while (u-- > 0) {
7064 result[u] = v;
7065 v = p[v];
7066 }
7067 return result;
7068 }
7069
7070 const isTeleport = (type) => type.__isTeleport;
7071 const isTeleportDisabled = (props) => props && (props.disabled || props.disabled === '');
7072 const isTargetSVG = (target) => typeof SVGElement !== 'undefined' && target instanceof SVGElement;
7073 const resolveTarget = (props, select) => {
7074 const targetSelector = props && props.to;
7075 if (isString(targetSelector)) {
7076 if (!select) {
7077 warn(`Current renderer does not support string target for Teleports. ` +
7078 `(missing querySelector renderer option)`);
7079 return null;
7080 }
7081 else {
7082 const target = select(targetSelector);
7083 if (!target) {
7084 warn(`Failed to locate Teleport target with selector "${targetSelector}". ` +
7085 `Note the target element must exist before the component is mounted - ` +
7086 `i.e. the target cannot be rendered by the component itself, and ` +
7087 `ideally should be outside of the entire Vue component tree.`);
7088 }
7089 return target;
7090 }
7091 }
7092 else {
7093 if (!targetSelector && !isTeleportDisabled(props)) {
7094 warn(`Invalid Teleport target: ${targetSelector}`);
7095 }
7096 return targetSelector;
7097 }
7098 };
7099 const TeleportImpl = {
7100 __isTeleport: true,
7101 process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, internals) {
7102 const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, o: { insert, querySelector, createText, createComment } } = internals;
7103 const disabled = isTeleportDisabled(n2.props);
7104 let { shapeFlag, children, dynamicChildren } = n2;
7105 // #3302
7106 // HMR updated, force full diff
7107 if (isHmrUpdating) {
7108 optimized = false;
7109 dynamicChildren = null;
7110 }
7111 if (n1 == null) {
7112 // insert anchors in the main view
7113 const placeholder = (n2.el = createComment('teleport start')
7114 );
7115 const mainAnchor = (n2.anchor = createComment('teleport end')
7116 );
7117 insert(placeholder, container, anchor);
7118 insert(mainAnchor, container, anchor);
7119 const target = (n2.target = resolveTarget(n2.props, querySelector));
7120 const targetAnchor = (n2.targetAnchor = createText(''));
7121 if (target) {
7122 insert(targetAnchor, target);
7123 // #2652 we could be teleporting from a non-SVG tree into an SVG tree
7124 isSVG = isSVG || isTargetSVG(target);
7125 }
7126 else if (!disabled) {
7127 warn('Invalid Teleport target on mount:', target, `(${typeof target})`);
7128 }
7129 const mount = (container, anchor) => {
7130 // Teleport *always* has Array children. This is enforced in both the
7131 // compiler and vnode children normalization.
7132 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7133 mountChildren(children, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized);
7134 }
7135 };
7136 if (disabled) {
7137 mount(container, mainAnchor);
7138 }
7139 else if (target) {
7140 mount(target, targetAnchor);
7141 }
7142 }
7143 else {
7144 // update content
7145 n2.el = n1.el;
7146 const mainAnchor = (n2.anchor = n1.anchor);
7147 const target = (n2.target = n1.target);
7148 const targetAnchor = (n2.targetAnchor = n1.targetAnchor);
7149 const wasDisabled = isTeleportDisabled(n1.props);
7150 const currentContainer = wasDisabled ? container : target;
7151 const currentAnchor = wasDisabled ? mainAnchor : targetAnchor;
7152 isSVG = isSVG || isTargetSVG(target);
7153 if (dynamicChildren) {
7154 // fast path when the teleport happens to be a block root
7155 patchBlockChildren(n1.dynamicChildren, dynamicChildren, currentContainer, parentComponent, parentSuspense, isSVG, slotScopeIds);
7156 // even in block tree mode we need to make sure all root-level nodes
7157 // in the teleport inherit previous DOM references so that they can
7158 // be moved in future patches.
7159 traverseStaticChildren(n1, n2, true);
7160 }
7161 else if (!optimized) {
7162 patchChildren(n1, n2, currentContainer, currentAnchor, parentComponent, parentSuspense, isSVG, slotScopeIds, false);
7163 }
7164 if (disabled) {
7165 if (!wasDisabled) {
7166 // enabled -> disabled
7167 // move into main container
7168 moveTeleport(n2, container, mainAnchor, internals, 1 /* TOGGLE */);
7169 }
7170 }
7171 else {
7172 // target changed
7173 if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) {
7174 const nextTarget = (n2.target = resolveTarget(n2.props, querySelector));
7175 if (nextTarget) {
7176 moveTeleport(n2, nextTarget, null, internals, 0 /* TARGET_CHANGE */);
7177 }
7178 else {
7179 warn('Invalid Teleport target on update:', target, `(${typeof target})`);
7180 }
7181 }
7182 else if (wasDisabled) {
7183 // disabled -> enabled
7184 // move into teleport target
7185 moveTeleport(n2, target, targetAnchor, internals, 1 /* TOGGLE */);
7186 }
7187 }
7188 }
7189 },
7190 remove(vnode, parentComponent, parentSuspense, optimized, { um: unmount, o: { remove: hostRemove } }, doRemove) {
7191 const { shapeFlag, children, anchor, targetAnchor, target, props } = vnode;
7192 if (target) {
7193 hostRemove(targetAnchor);
7194 }
7195 // an unmounted teleport should always remove its children if not disabled
7196 if (doRemove || !isTeleportDisabled(props)) {
7197 hostRemove(anchor);
7198 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7199 for (let i = 0; i < children.length; i++) {
7200 const child = children[i];
7201 unmount(child, parentComponent, parentSuspense, true, !!child.dynamicChildren);
7202 }
7203 }
7204 }
7205 },
7206 move: moveTeleport,
7207 hydrate: hydrateTeleport
7208 };
7209 function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2 /* REORDER */) {
7210 // move target anchor if this is a target change.
7211 if (moveType === 0 /* TARGET_CHANGE */) {
7212 insert(vnode.targetAnchor, container, parentAnchor);
7213 }
7214 const { el, anchor, shapeFlag, children, props } = vnode;
7215 const isReorder = moveType === 2 /* REORDER */;
7216 // move main view anchor if this is a re-order.
7217 if (isReorder) {
7218 insert(el, container, parentAnchor);
7219 }
7220 // if this is a re-order and teleport is enabled (content is in target)
7221 // do not move children. So the opposite is: only move children if this
7222 // is not a reorder, or the teleport is disabled
7223 if (!isReorder || isTeleportDisabled(props)) {
7224 // Teleport has either Array children or no children.
7225 if (shapeFlag & 16 /* ARRAY_CHILDREN */) {
7226 for (let i = 0; i < children.length; i++) {
7227 move(children[i], container, parentAnchor, 2 /* REORDER */);
7228 }
7229 }
7230 }
7231 // move main view anchor if this is a re-order.
7232 if (isReorder) {
7233 insert(anchor, container, parentAnchor);
7234 }
7235 }
7236 function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { o: { nextSibling, parentNode, querySelector } }, hydrateChildren) {
7237 const target = (vnode.target = resolveTarget(vnode.props, querySelector));
7238 if (target) {
7239 // if multiple teleports rendered to the same target element, we need to
7240 // pick up from where the last teleport finished instead of the first node
7241 const targetNode = target._lpa || target.firstChild;
7242 if (vnode.shapeFlag & 16 /* ARRAY_CHILDREN */) {
7243 if (isTeleportDisabled(vnode.props)) {
7244 vnode.anchor = hydrateChildren(nextSibling(node), vnode, parentNode(node), parentComponent, parentSuspense, slotScopeIds, optimized);
7245 vnode.targetAnchor = targetNode;
7246 }
7247 else {
7248 vnode.anchor = nextSibling(node);
7249 vnode.targetAnchor = hydrateChildren(targetNode, vnode, target, parentComponent, parentSuspense, slotScopeIds, optimized);
7250 }
7251 target._lpa =
7252 vnode.targetAnchor && nextSibling(vnode.targetAnchor);
7253 }
7254 }
7255 return vnode.anchor && nextSibling(vnode.anchor);
7256 }
7257 // Force-casted public typing for h and TSX props inference
7258 const Teleport = TeleportImpl;
7259
7260 const COMPONENTS = 'components';
7261 const DIRECTIVES = 'directives';
7262 /**
7263 * @private
7264 */
7265 function resolveComponent(name, maybeSelfReference) {
7266 return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name;
7267 }
7268 const NULL_DYNAMIC_COMPONENT = Symbol();
7269 /**
7270 * @private
7271 */
7272 function resolveDynamicComponent(component) {
7273 if (isString(component)) {
7274 return resolveAsset(COMPONENTS, component, false) || component;
7275 }
7276 else {
7277 // invalid types will fallthrough to createVNode and raise warning
7278 return (component || NULL_DYNAMIC_COMPONENT);
7279 }
7280 }
7281 /**
7282 * @private
7283 */
7284 function resolveDirective(name) {
7285 return resolveAsset(DIRECTIVES, name);
7286 }
7287 // implementation
7288 function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) {
7289 const instance = currentRenderingInstance || currentInstance;
7290 if (instance) {
7291 const Component = instance.type;
7292 // explicit self name has highest priority
7293 if (type === COMPONENTS) {
7294 const selfName = getComponentName(Component);
7295 if (selfName &&
7296 (selfName === name ||
7297 selfName === camelize(name) ||
7298 selfName === capitalize(camelize(name)))) {
7299 return Component;
7300 }
7301 }
7302 const res =
7303 // local registration
7304 // check instance[type] first which is resolved for options API
7305 resolve(instance[type] || Component[type], name) ||
7306 // global registration
7307 resolve(instance.appContext[type], name);
7308 if (!res && maybeSelfReference) {
7309 // fallback to implicit self-reference
7310 return Component;
7311 }
7312 if (warnMissing && !res) {
7313 warn(`Failed to resolve ${type.slice(0, -1)}: ${name}`);
7314 }
7315 return res;
7316 }
7317 else {
7318 warn(`resolve${capitalize(type.slice(0, -1))} ` +
7319 `can only be used in render() or setup().`);
7320 }
7321 }
7322 function resolve(registry, name) {
7323 return (registry &&
7324 (registry[name] ||
7325 registry[camelize(name)] ||
7326 registry[capitalize(camelize(name))]));
7327 }
7328
7329 const Fragment = Symbol('Fragment' );
7330 const Text = Symbol('Text' );
7331 const Comment$1 = Symbol('Comment' );
7332 const Static = Symbol('Static' );
7333 // Since v-if and v-for are the two possible ways node structure can dynamically
7334 // change, once we consider v-if branches and each v-for fragment a block, we
7335 // can divide a template into nested blocks, and within each block the node
7336 // structure would be stable. This allows us to skip most children diffing
7337 // and only worry about the dynamic nodes (indicated by patch flags).
7338 const blockStack = [];
7339 let currentBlock = null;
7340 /**
7341 * Open a block.
7342 * This must be called before `createBlock`. It cannot be part of `createBlock`
7343 * because the children of the block are evaluated before `createBlock` itself
7344 * is called. The generated code typically looks like this:
7345 *
7346 * ```js
7347 * function render() {
7348 * return (openBlock(),createBlock('div', null, [...]))
7349 * }
7350 * ```
7351 * disableTracking is true when creating a v-for fragment block, since a v-for
7352 * fragment always diffs its children.
7353 *
7354 * @private
7355 */
7356 function openBlock(disableTracking = false) {
7357 blockStack.push((currentBlock = disableTracking ? null : []));
7358 }
7359 function closeBlock() {
7360 blockStack.pop();
7361 currentBlock = blockStack[blockStack.length - 1] || null;
7362 }
7363 // Whether we should be tracking dynamic child nodes inside a block.
7364 // Only tracks when this value is > 0
7365 // We are not using a simple boolean because this value may need to be
7366 // incremented/decremented by nested usage of v-once (see below)
7367 let isBlockTreeEnabled = 1;
7368 /**
7369 * Block tracking sometimes needs to be disabled, for example during the
7370 * creation of a tree that needs to be cached by v-once. The compiler generates
7371 * code like this:
7372 *
7373 * ``` js
7374 * _cache[1] || (
7375 * setBlockTracking(-1),
7376 * _cache[1] = createVNode(...),
7377 * setBlockTracking(1),
7378 * _cache[1]
7379 * )
7380 * ```
7381 *
7382 * @private
7383 */
7384 function setBlockTracking(value) {
7385 isBlockTreeEnabled += value;
7386 }
7387 /**
7388 * Create a block root vnode. Takes the same exact arguments as `createVNode`.
7389 * A block root keeps track of dynamic nodes within the block in the
7390 * `dynamicChildren` array.
7391 *
7392 * @private
7393 */
7394 function createBlock(type, props, children, patchFlag, dynamicProps) {
7395 const vnode = createVNode(type, props, children, patchFlag, dynamicProps, true /* isBlock: prevent a block from tracking itself */);
7396 // save current block children on the block vnode
7397 vnode.dynamicChildren =
7398 isBlockTreeEnabled > 0 ? currentBlock || EMPTY_ARR : null;
7399 // close block
7400 closeBlock();
7401 // a block is always going to be patched, so track it as a child of its
7402 // parent block
7403 if (isBlockTreeEnabled > 0 && currentBlock) {
7404 currentBlock.push(vnode);
7405 }
7406 return vnode;
7407 }
7408 function isVNode(value) {
7409 return value ? value.__v_isVNode === true : false;
7410 }
7411 function isSameVNodeType(n1, n2) {
7412 if (n2.shapeFlag & 6 /* COMPONENT */ &&
7413 hmrDirtyComponents.has(n2.type)) {
7414 // HMR only: if the component has been hot-updated, force a reload.
7415 return false;
7416 }
7417 return n1.type === n2.type && n1.key === n2.key;
7418 }
7419 let vnodeArgsTransformer;
7420 /**
7421 * Internal API for registering an arguments transform for createVNode
7422 * used for creating stubs in the test-utils
7423 * It is *internal* but needs to be exposed for test-utils to pick up proper
7424 * typings
7425 */
7426 function transformVNodeArgs(transformer) {
7427 vnodeArgsTransformer = transformer;
7428 }
7429 const createVNodeWithArgsTransform = (...args) => {
7430 return _createVNode(...(vnodeArgsTransformer
7431 ? vnodeArgsTransformer(args, currentRenderingInstance)
7432 : args));
7433 };
7434 const InternalObjectKey = `__vInternal`;
7435 const normalizeKey = ({ key }) => key != null ? key : null;
7436 const normalizeRef = ({ ref }) => {
7437 return (ref != null
7438 ? isString(ref) || isRef(ref) || isFunction(ref)
7439 ? { i: currentRenderingInstance, r: ref }
7440 : ref
7441 : null);
7442 };
7443 const createVNode = (createVNodeWithArgsTransform
7444 );
7445 function _createVNode(type, props = null, children = null, patchFlag = 0, dynamicProps = null, isBlockNode = false) {
7446 if (!type || type === NULL_DYNAMIC_COMPONENT) {
7447 if (!type) {
7448 warn(`Invalid vnode type when creating vnode: ${type}.`);
7449 }
7450 type = Comment$1;
7451 }
7452 if (isVNode(type)) {
7453 // createVNode receiving an existing vnode. This happens in cases like
7454 // <component :is="vnode"/>
7455 // #2078 make sure to merge refs during the clone instead of overwriting it
7456 const cloned = cloneVNode(type, props, true /* mergeRef: true */);
7457 if (children) {
7458 normalizeChildren(cloned, children);
7459 }
7460 return cloned;
7461 }
7462 // class component normalization.
7463 if (isClassComponent(type)) {
7464 type = type.__vccOpts;
7465 }
7466 // class & style normalization.
7467 if (props) {
7468 // for reactive or proxy objects, we need to clone it to enable mutation.
7469 if (isProxy(props) || InternalObjectKey in props) {
7470 props = extend({}, props);
7471 }
7472 let { class: klass, style } = props;
7473 if (klass && !isString(klass)) {
7474 props.class = normalizeClass(klass);
7475 }
7476 if (isObject(style)) {
7477 // reactive state objects need to be cloned since they are likely to be
7478 // mutated
7479 if (isProxy(style) && !isArray(style)) {
7480 style = extend({}, style);
7481 }
7482 props.style = normalizeStyle(style);
7483 }
7484 }
7485 // encode the vnode type information into a bitmap
7486 const shapeFlag = isString(type)
7487 ? 1 /* ELEMENT */
7488 : isSuspense(type)
7489 ? 128 /* SUSPENSE */
7490 : isTeleport(type)
7491 ? 64 /* TELEPORT */
7492 : isObject(type)
7493 ? 4 /* STATEFUL_COMPONENT */
7494 : isFunction(type)
7495 ? 2 /* FUNCTIONAL_COMPONENT */
7496 : 0;
7497 if (shapeFlag & 4 /* STATEFUL_COMPONENT */ && isProxy(type)) {
7498 type = toRaw(type);
7499 warn(`Vue received a Component which was made a reactive object. This can ` +
7500 `lead to unnecessary performance overhead, and should be avoided by ` +
7501 `marking the component with \`markRaw\` or using \`shallowRef\` ` +
7502 `instead of \`ref\`.`, `\nComponent that was made reactive: `, type);
7503 }
7504 const vnode = {
7505 __v_isVNode: true,
7506 __v_skip: true,
7507 type,
7508 props,
7509 key: props && normalizeKey(props),
7510 ref: props && normalizeRef(props),
7511 scopeId: currentScopeId,
7512 slotScopeIds: null,
7513 children: null,
7514 component: null,
7515 suspense: null,
7516 ssContent: null,
7517 ssFallback: null,
7518 dirs: null,
7519 transition: null,
7520 el: null,
7521 anchor: null,
7522 target: null,
7523 targetAnchor: null,
7524 staticCount: 0,
7525 shapeFlag,
7526 patchFlag,
7527 dynamicProps,
7528 dynamicChildren: null,
7529 appContext: null
7530 };
7531 // validate key
7532 if (vnode.key !== vnode.key) {
7533 warn(`VNode created with invalid key (NaN). VNode type:`, vnode.type);
7534 }
7535 normalizeChildren(vnode, children);
7536 // normalize suspense children
7537 if (shapeFlag & 128 /* SUSPENSE */) {
7538 type.normalize(vnode);
7539 }
7540 if (isBlockTreeEnabled > 0 &&
7541 // avoid a block node from tracking itself
7542 !isBlockNode &&
7543 // has current parent block
7544 currentBlock &&
7545 // presence of a patch flag indicates this node needs patching on updates.
7546 // component nodes also should always be patched, because even if the
7547 // component doesn't need to update, it needs to persist the instance on to
7548 // the next vnode so that it can be properly unmounted later.
7549 (patchFlag > 0 || shapeFlag & 6 /* COMPONENT */) &&
7550 // the EVENTS flag is only for hydration and if it is the only flag, the
7551 // vnode should not be considered dynamic due to handler caching.
7552 patchFlag !== 32 /* HYDRATE_EVENTS */) {
7553 currentBlock.push(vnode);
7554 }
7555 return vnode;
7556 }
7557 function cloneVNode(vnode, extraProps, mergeRef = false) {
7558 // This is intentionally NOT using spread or extend to avoid the runtime
7559 // key enumeration cost.
7560 const { props, ref, patchFlag, children } = vnode;
7561 const mergedProps = extraProps ? mergeProps(props || {}, extraProps) : props;
7562 const cloned = {
7563 __v_isVNode: true,
7564 __v_skip: true,
7565 type: vnode.type,
7566 props: mergedProps,
7567 key: mergedProps && normalizeKey(mergedProps),
7568 ref: extraProps && extraProps.ref
7569 ? // #2078 in the case of <component :is="vnode" ref="extra"/>
7570 // if the vnode itself already has a ref, cloneVNode will need to merge
7571 // the refs so the single vnode can be set on multiple refs
7572 mergeRef && ref
7573 ? isArray(ref)
7574 ? ref.concat(normalizeRef(extraProps))
7575 : [ref, normalizeRef(extraProps)]
7576 : normalizeRef(extraProps)
7577 : ref,
7578 scopeId: vnode.scopeId,
7579 slotScopeIds: vnode.slotScopeIds,
7580 children: patchFlag === -1 /* HOISTED */ && isArray(children)
7581 ? children.map(deepCloneVNode)
7582 : children,
7583 target: vnode.target,
7584 targetAnchor: vnode.targetAnchor,
7585 staticCount: vnode.staticCount,
7586 shapeFlag: vnode.shapeFlag,
7587 // if the vnode is cloned with extra props, we can no longer assume its
7588 // existing patch flag to be reliable and need to add the FULL_PROPS flag.
7589 // note: perserve flag for fragments since they use the flag for children
7590 // fast paths only.
7591 patchFlag: extraProps && vnode.type !== Fragment
7592 ? patchFlag === -1 // hoisted node
7593 ? 16 /* FULL_PROPS */
7594 : patchFlag | 16 /* FULL_PROPS */
7595 : patchFlag,
7596 dynamicProps: vnode.dynamicProps,
7597 dynamicChildren: vnode.dynamicChildren,
7598 appContext: vnode.appContext,
7599 dirs: vnode.dirs,
7600 transition: vnode.transition,
7601 // These should technically only be non-null on mounted VNodes. However,
7602 // they *should* be copied for kept-alive vnodes. So we just always copy
7603 // them since them being non-null during a mount doesn't affect the logic as
7604 // they will simply be overwritten.
7605 component: vnode.component,
7606 suspense: vnode.suspense,
7607 ssContent: vnode.ssContent && cloneVNode(vnode.ssContent),
7608 ssFallback: vnode.ssFallback && cloneVNode(vnode.ssFallback),
7609 el: vnode.el,
7610 anchor: vnode.anchor
7611 };
7612 return cloned;
7613 }
7614 /**
7615 * Dev only, for HMR of hoisted vnodes reused in v-for
7616 * https://github.com/vitejs/vite/issues/2022
7617 */
7618 function deepCloneVNode(vnode) {
7619 const cloned = cloneVNode(vnode);
7620 if (isArray(vnode.children)) {
7621 cloned.children = vnode.children.map(deepCloneVNode);
7622 }
7623 return cloned;
7624 }
7625 /**
7626 * @private
7627 */
7628 function createTextVNode(text = ' ', flag = 0) {
7629 return createVNode(Text, null, text, flag);
7630 }
7631 /**
7632 * @private
7633 */
7634 function createStaticVNode(content, numberOfNodes) {
7635 // A static vnode can contain multiple stringified elements, and the number
7636 // of elements is necessary for hydration.
7637 const vnode = createVNode(Static, null, content);
7638 vnode.staticCount = numberOfNodes;
7639 return vnode;
7640 }
7641 /**
7642 * @private
7643 */
7644 function createCommentVNode(text = '',
7645 // when used as the v-else branch, the comment node must be created as a
7646 // block to ensure correct updates.
7647 asBlock = false) {
7648 return asBlock
7649 ? (openBlock(), createBlock(Comment$1, null, text))
7650 : createVNode(Comment$1, null, text);
7651 }
7652 function normalizeVNode(child) {
7653 if (child == null || typeof child === 'boolean') {
7654 // empty placeholder
7655 return createVNode(Comment$1);
7656 }
7657 else if (isArray(child)) {
7658 // fragment
7659 return createVNode(Fragment, null,
7660 // #3666, avoid reference pollution when reusing vnode
7661 child.slice());
7662 }
7663 else if (typeof child === 'object') {
7664 // already vnode, this should be the most common since compiled templates
7665 // always produce all-vnode children arrays
7666 return cloneIfMounted(child);
7667 }
7668 else {
7669 // strings and numbers
7670 return createVNode(Text, null, String(child));
7671 }
7672 }
7673 // optimized normalization for template-compiled render fns
7674 function cloneIfMounted(child) {
7675 return child.el === null ? child : cloneVNode(child);
7676 }
7677 function normalizeChildren(vnode, children) {
7678 let type = 0;
7679 const { shapeFlag } = vnode;
7680 if (children == null) {
7681 children = null;
7682 }
7683 else if (isArray(children)) {
7684 type = 16 /* ARRAY_CHILDREN */;
7685 }
7686 else if (typeof children === 'object') {
7687 if (shapeFlag & 1 /* ELEMENT */ || shapeFlag & 64 /* TELEPORT */) {
7688 // Normalize slot to plain children for plain element and Teleport
7689 const slot = children.default;
7690 if (slot) {
7691 // _c marker is added by withCtx() indicating this is a compiled slot
7692 slot._c && (slot._d = false);
7693 normalizeChildren(vnode, slot());
7694 slot._c && (slot._d = true);
7695 }
7696 return;
7697 }
7698 else {
7699 type = 32 /* SLOTS_CHILDREN */;
7700 const slotFlag = children._;
7701 if (!slotFlag && !(InternalObjectKey in children)) {
7702 children._ctx = currentRenderingInstance;
7703 }
7704 else if (slotFlag === 3 /* FORWARDED */ && currentRenderingInstance) {
7705 // a child component receives forwarded slots from the parent.
7706 // its slot type is determined by its parent's slot type.
7707 if (currentRenderingInstance.slots._ === 1 /* STABLE */) {
7708 children._ = 1 /* STABLE */;
7709 }
7710 else {
7711 children._ = 2 /* DYNAMIC */;
7712 vnode.patchFlag |= 1024 /* DYNAMIC_SLOTS */;
7713 }
7714 }
7715 }
7716 }
7717 else if (isFunction(children)) {
7718 children = { default: children, _ctx: currentRenderingInstance };
7719 type = 32 /* SLOTS_CHILDREN */;
7720 }
7721 else {
7722 children = String(children);
7723 // force teleport children to array so it can be moved around
7724 if (shapeFlag & 64 /* TELEPORT */) {
7725 type = 16 /* ARRAY_CHILDREN */;
7726 children = [createTextVNode(children)];
7727 }
7728 else {
7729 type = 8 /* TEXT_CHILDREN */;
7730 }
7731 }
7732 vnode.children = children;
7733 vnode.shapeFlag |= type;
7734 }
7735 function mergeProps(...args) {
7736 const ret = extend({}, args[0]);
7737 for (let i = 1; i < args.length; i++) {
7738 const toMerge = args[i];
7739 for (const key in toMerge) {
7740 if (key === 'class') {
7741 if (ret.class !== toMerge.class) {
7742 ret.class = normalizeClass([ret.class, toMerge.class]);
7743 }
7744 }
7745 else if (key === 'style') {
7746 ret.style = normalizeStyle([ret.style, toMerge.style]);
7747 }
7748 else if (isOn(key)) {
7749 const existing = ret[key];
7750 const incoming = toMerge[key];
7751 if (existing !== incoming) {
7752 ret[key] = existing
7753 ? [].concat(existing, incoming)
7754 : incoming;
7755 }
7756 }
7757 else if (key !== '') {
7758 ret[key] = toMerge[key];
7759 }
7760 }
7761 }
7762 return ret;
7763 }
7764
7765 /**
7766 * Actual implementation
7767 */
7768 function renderList(source, renderItem) {
7769 let ret;
7770 if (isArray(source) || isString(source)) {
7771 ret = new Array(source.length);
7772 for (let i = 0, l = source.length; i < l; i++) {
7773 ret[i] = renderItem(source[i], i);
7774 }
7775 }
7776 else if (typeof source === 'number') {
7777 if (!Number.isInteger(source)) {
7778 warn(`The v-for range expect an integer value but got ${source}.`);
7779 return [];
7780 }
7781 ret = new Array(source);
7782 for (let i = 0; i < source; i++) {
7783 ret[i] = renderItem(i + 1, i);
7784 }
7785 }
7786 else if (isObject(source)) {
7787 if (source[Symbol.iterator]) {
7788 ret = Array.from(source, renderItem);
7789 }
7790 else {
7791 const keys = Object.keys(source);
7792 ret = new Array(keys.length);
7793 for (let i = 0, l = keys.length; i < l; i++) {
7794 const key = keys[i];
7795 ret[i] = renderItem(source[key], key, i);
7796 }
7797 }
7798 }
7799 else {
7800 ret = [];
7801 }
7802 return ret;
7803 }
7804
7805 /**
7806 * Compiler runtime helper for creating dynamic slots object
7807 * @private
7808 */
7809 function createSlots(slots, dynamicSlots) {
7810 for (let i = 0; i < dynamicSlots.length; i++) {
7811 const slot = dynamicSlots[i];
7812 // array of dynamic slot generated by <template v-for="..." #[...]>
7813 if (isArray(slot)) {
7814 for (let j = 0; j < slot.length; j++) {
7815 slots[slot[j].name] = slot[j].fn;
7816 }
7817 }
7818 else if (slot) {
7819 // conditional single slot generated by <template v-if="..." #foo>
7820 slots[slot.name] = slot.fn;
7821 }
7822 }
7823 return slots;
7824 }
7825
7826 /**
7827 * Compiler runtime helper for rendering `<slot/>`
7828 * @private
7829 */
7830 function renderSlot(slots, name, props = {},
7831 // this is not a user-facing function, so the fallback is always generated by
7832 // the compiler and guaranteed to be a function returning an array
7833 fallback, noSlotted) {
7834 let slot = slots[name];
7835 if (slot && slot.length > 1) {
7836 warn(`SSR-optimized slot function detected in a non-SSR-optimized render ` +
7837 `function. You need to mark this component with $dynamic-slots in the ` +
7838 `parent template.`);
7839 slot = () => [];
7840 }
7841 // a compiled slot disables block tracking by default to avoid manual
7842 // invocation interfering with template-based block tracking, but in
7843 // `renderSlot` we can be sure that it's template-based so we can force
7844 // enable it.
7845 if (slot && slot._c) {
7846 slot._d = false;
7847 }
7848 openBlock();
7849 const validSlotContent = slot && ensureValidVNode(slot(props));
7850 const rendered = createBlock(Fragment, { key: props.key || `_${name}` }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 /* STABLE */
7851 ? 64 /* STABLE_FRAGMENT */
7852 : -2 /* BAIL */);
7853 if (!noSlotted && rendered.scopeId) {
7854 rendered.slotScopeIds = [rendered.scopeId + '-s'];
7855 }
7856 if (slot && slot._c) {
7857 slot._d = true;
7858 }
7859 return rendered;
7860 }
7861 function ensureValidVNode(vnodes) {
7862 return vnodes.some(child => {
7863 if (!isVNode(child))
7864 return true;
7865 if (child.type === Comment$1)
7866 return false;
7867 if (child.type === Fragment &&
7868 !ensureValidVNode(child.children))
7869 return false;
7870 return true;
7871 })
7872 ? vnodes
7873 : null;
7874 }
7875
7876 /**
7877 * For prefixing keys in v-on="obj" with "on"
7878 * @private
7879 */
7880 function toHandlers(obj) {
7881 const ret = {};
7882 if (!isObject(obj)) {
7883 warn(`v-on with no argument expects an object value.`);
7884 return ret;
7885 }
7886 for (const key in obj) {
7887 ret[toHandlerKey(key)] = obj[key];
7888 }
7889 return ret;
7890 }
7891
7892 /**
7893 * #2437 In Vue 3, functional components do not have a public instance proxy but
7894 * they exist in the internal parent chain. For code that relies on traversing
7895 * public $parent chains, skip functional ones and go to the parent instead.
7896 */
7897 const getPublicInstance = (i) => {
7898 if (!i)
7899 return null;
7900 if (isStatefulComponent(i))
7901 return i.exposed ? i.exposed : i.proxy;
7902 return getPublicInstance(i.parent);
7903 };
7904 const publicPropertiesMap = extend(Object.create(null), {
7905 $: i => i,
7906 $el: i => i.vnode.el,
7907 $data: i => i.data,
7908 $props: i => (shallowReadonly(i.props) ),
7909 $attrs: i => (shallowReadonly(i.attrs) ),
7910 $slots: i => (shallowReadonly(i.slots) ),
7911 $refs: i => (shallowReadonly(i.refs) ),
7912 $parent: i => getPublicInstance(i.parent),
7913 $root: i => getPublicInstance(i.root),
7914 $emit: i => i.emit,
7915 $options: i => (resolveMergedOptions(i) ),
7916 $forceUpdate: i => () => queueJob(i.update),
7917 $nextTick: i => nextTick.bind(i.proxy),
7918 $watch: i => (instanceWatch.bind(i) )
7919 });
7920 const PublicInstanceProxyHandlers = {
7921 get({ _: instance }, key) {
7922 const { ctx, setupState, data, props, accessCache, type, appContext } = instance;
7923 // let @vue/reactivity know it should never observe Vue public instances.
7924 if (key === "__v_skip" /* SKIP */) {
7925 return true;
7926 }
7927 // for internal formatters to know that this is a Vue instance
7928 if (key === '__isVue') {
7929 return true;
7930 }
7931 // data / props / ctx
7932 // This getter gets called for every property access on the render context
7933 // during render and is a major hotspot. The most expensive part of this
7934 // is the multiple hasOwn() calls. It's much faster to do a simple property
7935 // access on a plain object, so we use an accessCache object (with null
7936 // prototype) to memoize what access type a key corresponds to.
7937 let normalizedProps;
7938 if (key[0] !== '$') {
7939 const n = accessCache[key];
7940 if (n !== undefined) {
7941 switch (n) {
7942 case 0 /* SETUP */:
7943 return setupState[key];
7944 case 1 /* DATA */:
7945 return data[key];
7946 case 3 /* CONTEXT */:
7947 return ctx[key];
7948 case 2 /* PROPS */:
7949 return props[key];
7950 // default: just fallthrough
7951 }
7952 }
7953 else if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
7954 accessCache[key] = 0 /* SETUP */;
7955 return setupState[key];
7956 }
7957 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
7958 accessCache[key] = 1 /* DATA */;
7959 return data[key];
7960 }
7961 else if (
7962 // only cache other properties when instance has declared (thus stable)
7963 // props
7964 (normalizedProps = instance.propsOptions[0]) &&
7965 hasOwn(normalizedProps, key)) {
7966 accessCache[key] = 2 /* PROPS */;
7967 return props[key];
7968 }
7969 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7970 accessCache[key] = 3 /* CONTEXT */;
7971 return ctx[key];
7972 }
7973 else if (shouldCacheAccess) {
7974 accessCache[key] = 4 /* OTHER */;
7975 }
7976 }
7977 const publicGetter = publicPropertiesMap[key];
7978 let cssModule, globalProperties;
7979 // public $xxx properties
7980 if (publicGetter) {
7981 if (key === '$attrs') {
7982 track(instance, "get" /* GET */, key);
7983 markAttrsAccessed();
7984 }
7985 return publicGetter(instance);
7986 }
7987 else if (
7988 // css module (injected by vue-loader)
7989 (cssModule = type.__cssModules) &&
7990 (cssModule = cssModule[key])) {
7991 return cssModule;
7992 }
7993 else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) {
7994 // user may set custom properties to `this` that start with `$`
7995 accessCache[key] = 3 /* CONTEXT */;
7996 return ctx[key];
7997 }
7998 else if (
7999 // global properties
8000 ((globalProperties = appContext.config.globalProperties),
8001 hasOwn(globalProperties, key))) {
8002 {
8003 return globalProperties[key];
8004 }
8005 }
8006 else if (currentRenderingInstance &&
8007 (!isString(key) ||
8008 // #1091 avoid internal isRef/isVNode checks on component instance leading
8009 // to infinite warning loop
8010 key.indexOf('__v') !== 0)) {
8011 if (data !== EMPTY_OBJ &&
8012 (key[0] === '$' || key[0] === '_') &&
8013 hasOwn(data, key)) {
8014 warn(`Property ${JSON.stringify(key)} must be accessed via $data because it starts with a reserved ` +
8015 `character ("$" or "_") and is not proxied on the render context.`);
8016 }
8017 else if (instance === currentRenderingInstance) {
8018 warn(`Property ${JSON.stringify(key)} was accessed during render ` +
8019 `but is not defined on instance.`);
8020 }
8021 }
8022 },
8023 set({ _: instance }, key, value) {
8024 const { data, setupState, ctx } = instance;
8025 if (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) {
8026 setupState[key] = value;
8027 }
8028 else if (data !== EMPTY_OBJ && hasOwn(data, key)) {
8029 data[key] = value;
8030 }
8031 else if (hasOwn(instance.props, key)) {
8032 warn(`Attempting to mutate prop "${key}". Props are readonly.`, instance);
8033 return false;
8034 }
8035 if (key[0] === '$' && key.slice(1) in instance) {
8036 warn(`Attempting to mutate public property "${key}". ` +
8037 `Properties starting with $ are reserved and readonly.`, instance);
8038 return false;
8039 }
8040 else {
8041 if (key in instance.appContext.config.globalProperties) {
8042 Object.defineProperty(ctx, key, {
8043 enumerable: true,
8044 configurable: true,
8045 value
8046 });
8047 }
8048 else {
8049 ctx[key] = value;
8050 }
8051 }
8052 return true;
8053 },
8054 has({ _: { data, setupState, accessCache, ctx, appContext, propsOptions } }, key) {
8055 let normalizedProps;
8056 return (accessCache[key] !== undefined ||
8057 (data !== EMPTY_OBJ && hasOwn(data, key)) ||
8058 (setupState !== EMPTY_OBJ && hasOwn(setupState, key)) ||
8059 ((normalizedProps = propsOptions[0]) && hasOwn(normalizedProps, key)) ||
8060 hasOwn(ctx, key) ||
8061 hasOwn(publicPropertiesMap, key) ||
8062 hasOwn(appContext.config.globalProperties, key));
8063 }
8064 };
8065 {
8066 PublicInstanceProxyHandlers.ownKeys = (target) => {
8067 warn(`Avoid app logic that relies on enumerating keys on a component instance. ` +
8068 `The keys will be empty in production mode to avoid performance overhead.`);
8069 return Reflect.ownKeys(target);
8070 };
8071 }
8072 const RuntimeCompiledPublicInstanceProxyHandlers = extend({}, PublicInstanceProxyHandlers, {
8073 get(target, key) {
8074 // fast path for unscopables when using `with` block
8075 if (key === Symbol.unscopables) {
8076 return;
8077 }
8078 return PublicInstanceProxyHandlers.get(target, key, target);
8079 },
8080 has(_, key) {
8081 const has = key[0] !== '_' && !isGloballyWhitelisted(key);
8082 if (!has && PublicInstanceProxyHandlers.has(_, key)) {
8083 warn(`Property ${JSON.stringify(key)} should not start with _ which is a reserved prefix for Vue internals.`);
8084 }
8085 return has;
8086 }
8087 });
8088 // In dev mode, the proxy target exposes the same properties as seen on `this`
8089 // for easier console inspection. In prod mode it will be an empty object so
8090 // these properties definitions can be skipped.
8091 function createRenderContext(instance) {
8092 const target = {};
8093 // expose internal instance for proxy handlers
8094 Object.defineProperty(target, `_`, {
8095 configurable: true,
8096 enumerable: false,
8097 get: () => instance
8098 });
8099 // expose public properties
8100 Object.keys(publicPropertiesMap).forEach(key => {
8101 Object.defineProperty(target, key, {
8102 configurable: true,
8103 enumerable: false,
8104 get: () => publicPropertiesMap[key](instance),
8105 // intercepted by the proxy so no need for implementation,
8106 // but needed to prevent set errors
8107 set: NOOP
8108 });
8109 });
8110 return target;
8111 }
8112 // dev only
8113 function exposePropsOnRenderContext(instance) {
8114 const { ctx, propsOptions: [propsOptions] } = instance;
8115 if (propsOptions) {
8116 Object.keys(propsOptions).forEach(key => {
8117 Object.defineProperty(ctx, key, {
8118 enumerable: true,
8119 configurable: true,
8120 get: () => instance.props[key],
8121 set: NOOP
8122 });
8123 });
8124 }
8125 }
8126 // dev only
8127 function exposeSetupStateOnRenderContext(instance) {
8128 const { ctx, setupState } = instance;
8129 Object.keys(toRaw(setupState)).forEach(key => {
8130 if (key[0] === '$' || key[0] === '_') {
8131 warn(`setup() return property ${JSON.stringify(key)} should not start with "$" or "_" ` +
8132 `which are reserved prefixes for Vue internals.`);
8133 return;
8134 }
8135 Object.defineProperty(ctx, key, {
8136 enumerable: true,
8137 configurable: true,
8138 get: () => setupState[key],
8139 set: NOOP
8140 });
8141 });
8142 }
8143
8144 const emptyAppContext = createAppContext();
8145 let uid$2 = 0;
8146 function createComponentInstance(vnode, parent, suspense) {
8147 const type = vnode.type;
8148 // inherit parent app context - or - if root, adopt from root vnode
8149 const appContext = (parent ? parent.appContext : vnode.appContext) || emptyAppContext;
8150 const instance = {
8151 uid: uid$2++,
8152 vnode,
8153 type,
8154 parent,
8155 appContext,
8156 root: null,
8157 next: null,
8158 subTree: null,
8159 update: null,
8160 render: null,
8161 proxy: null,
8162 exposed: null,
8163 withProxy: null,
8164 effects: null,
8165 provides: parent ? parent.provides : Object.create(appContext.provides),
8166 accessCache: null,
8167 renderCache: [],
8168 // local resovled assets
8169 components: null,
8170 directives: null,
8171 // resolved props and emits options
8172 propsOptions: normalizePropsOptions(type, appContext),
8173 emitsOptions: normalizeEmitsOptions(type, appContext),
8174 // emit
8175 emit: null,
8176 emitted: null,
8177 // props default value
8178 propsDefaults: EMPTY_OBJ,
8179 // inheritAttrs
8180 inheritAttrs: type.inheritAttrs,
8181 // state
8182 ctx: EMPTY_OBJ,
8183 data: EMPTY_OBJ,
8184 props: EMPTY_OBJ,
8185 attrs: EMPTY_OBJ,
8186 slots: EMPTY_OBJ,
8187 refs: EMPTY_OBJ,
8188 setupState: EMPTY_OBJ,
8189 setupContext: null,
8190 // suspense related
8191 suspense,
8192 suspenseId: suspense ? suspense.pendingId : 0,
8193 asyncDep: null,
8194 asyncResolved: false,
8195 // lifecycle hooks
8196 // not using enums here because it results in computed properties
8197 isMounted: false,
8198 isUnmounted: false,
8199 isDeactivated: false,
8200 bc: null,
8201 c: null,
8202 bm: null,
8203 m: null,
8204 bu: null,
8205 u: null,
8206 um: null,
8207 bum: null,
8208 da: null,
8209 a: null,
8210 rtg: null,
8211 rtc: null,
8212 ec: null,
8213 sp: null
8214 };
8215 {
8216 instance.ctx = createRenderContext(instance);
8217 }
8218 instance.root = parent ? parent.root : instance;
8219 instance.emit = emit.bind(null, instance);
8220 return instance;
8221 }
8222 let currentInstance = null;
8223 const getCurrentInstance = () => currentInstance || currentRenderingInstance;
8224 const setCurrentInstance = (instance) => {
8225 currentInstance = instance;
8226 };
8227 const isBuiltInTag = /*#__PURE__*/ makeMap('slot,component');
8228 function validateComponentName(name, config) {
8229 const appIsNativeTag = config.isNativeTag || NO;
8230 if (isBuiltInTag(name) || appIsNativeTag(name)) {
8231 warn('Do not use built-in or reserved HTML elements as component id: ' + name);
8232 }
8233 }
8234 function isStatefulComponent(instance) {
8235 return instance.vnode.shapeFlag & 4 /* STATEFUL_COMPONENT */;
8236 }
8237 let isInSSRComponentSetup = false;
8238 function setupComponent(instance, isSSR = false) {
8239 isInSSRComponentSetup = isSSR;
8240 const { props, children } = instance.vnode;
8241 const isStateful = isStatefulComponent(instance);
8242 initProps(instance, props, isStateful, isSSR);
8243 initSlots(instance, children);
8244 const setupResult = isStateful
8245 ? setupStatefulComponent(instance, isSSR)
8246 : undefined;
8247 isInSSRComponentSetup = false;
8248 return setupResult;
8249 }
8250 function setupStatefulComponent(instance, isSSR) {
8251 const Component = instance.type;
8252 {
8253 if (Component.name) {
8254 validateComponentName(Component.name, instance.appContext.config);
8255 }
8256 if (Component.components) {
8257 const names = Object.keys(Component.components);
8258 for (let i = 0; i < names.length; i++) {
8259 validateComponentName(names[i], instance.appContext.config);
8260 }
8261 }
8262 if (Component.directives) {
8263 const names = Object.keys(Component.directives);
8264 for (let i = 0; i < names.length; i++) {
8265 validateDirectiveName(names[i]);
8266 }
8267 }
8268 if (Component.compilerOptions && isRuntimeOnly()) {
8269 warn(`"compilerOptions" is only supported when using a build of Vue that ` +
8270 `includes the runtime compiler. Since you are using a runtime-only ` +
8271 `build, the options should be passed via your build tool config instead.`);
8272 }
8273 }
8274 // 0. create render proxy property access cache
8275 instance.accessCache = Object.create(null);
8276 // 1. create public instance / render proxy
8277 // also mark it raw so it's never observed
8278 instance.proxy = new Proxy(instance.ctx, PublicInstanceProxyHandlers);
8279 {
8280 exposePropsOnRenderContext(instance);
8281 }
8282 // 2. call setup()
8283 const { setup } = Component;
8284 if (setup) {
8285 const setupContext = (instance.setupContext =
8286 setup.length > 1 ? createSetupContext(instance) : null);
8287 currentInstance = instance;
8288 pauseTracking();
8289 const setupResult = callWithErrorHandling(setup, instance, 0 /* SETUP_FUNCTION */, [shallowReadonly(instance.props) , setupContext]);
8290 resetTracking();
8291 currentInstance = null;
8292 if (isPromise(setupResult)) {
8293 if (isSSR) {
8294 // return the promise so server-renderer can wait on it
8295 return setupResult
8296 .then((resolvedResult) => {
8297 handleSetupResult(instance, resolvedResult, isSSR);
8298 })
8299 .catch(e => {
8300 handleError(e, instance, 0 /* SETUP_FUNCTION */);
8301 });
8302 }
8303 else {
8304 // async setup returned Promise.
8305 // bail here and wait for re-entry.
8306 instance.asyncDep = setupResult;
8307 }
8308 }
8309 else {
8310 handleSetupResult(instance, setupResult, isSSR);
8311 }
8312 }
8313 else {
8314 finishComponentSetup(instance, isSSR);
8315 }
8316 }
8317 function handleSetupResult(instance, setupResult, isSSR) {
8318 if (isFunction(setupResult)) {
8319 // setup returned an inline render function
8320 {
8321 instance.render = setupResult;
8322 }
8323 }
8324 else if (isObject(setupResult)) {
8325 if (isVNode(setupResult)) {
8326 warn(`setup() should not return VNodes directly - ` +
8327 `return a render function instead.`);
8328 }
8329 // setup returned bindings.
8330 // assuming a render function compiled from template is present.
8331 {
8332 instance.devtoolsRawSetupState = setupResult;
8333 }
8334 instance.setupState = proxyRefs(setupResult);
8335 {
8336 exposeSetupStateOnRenderContext(instance);
8337 }
8338 }
8339 else if (setupResult !== undefined) {
8340 warn(`setup() should return an object. Received: ${setupResult === null ? 'null' : typeof setupResult}`);
8341 }
8342 finishComponentSetup(instance, isSSR);
8343 }
8344 let compile;
8345 // dev only
8346 const isRuntimeOnly = () => !compile;
8347 /**
8348 * For runtime-dom to register the compiler.
8349 * Note the exported method uses any to avoid d.ts relying on the compiler types.
8350 */
8351 function registerRuntimeCompiler(_compile) {
8352 compile = _compile;
8353 }
8354 function finishComponentSetup(instance, isSSR, skipOptions) {
8355 const Component = instance.type;
8356 // template / render function normalization
8357 if (!instance.render) {
8358 // could be set from setup()
8359 if (compile && !Component.render) {
8360 const template = Component.template;
8361 if (template) {
8362 {
8363 startMeasure(instance, `compile`);
8364 }
8365 const { isCustomElement, compilerOptions } = instance.appContext.config;
8366 const { delimiters, compilerOptions: componentCompilerOptions } = Component;
8367 const finalCompilerOptions = extend(extend({
8368 isCustomElement,
8369 delimiters
8370 }, compilerOptions), componentCompilerOptions);
8371 Component.render = compile(template, finalCompilerOptions);
8372 {
8373 endMeasure(instance, `compile`);
8374 }
8375 }
8376 }
8377 instance.render = (Component.render || NOOP);
8378 // for runtime-compiled render functions using `with` blocks, the render
8379 // proxy used needs a different `has` handler which is more performant and
8380 // also only allows a whitelist of globals to fallthrough.
8381 if (instance.render._rc) {
8382 instance.withProxy = new Proxy(instance.ctx, RuntimeCompiledPublicInstanceProxyHandlers);
8383 }
8384 }
8385 // support for 2.x options
8386 {
8387 currentInstance = instance;
8388 pauseTracking();
8389 applyOptions(instance);
8390 resetTracking();
8391 currentInstance = null;
8392 }
8393 // warn missing template/render
8394 // the runtime compilation of template in SSR is done by server-render
8395 if (!Component.render && instance.render === NOOP && !isSSR) {
8396 /* istanbul ignore if */
8397 if (!compile && Component.template) {
8398 warn(`Component provided template option but ` +
8399 `runtime compilation is not supported in this build of Vue.` +
8400 (` Use "vue.global.js" instead.`
8401 ) /* should not happen */);
8402 }
8403 else {
8404 warn(`Component is missing template or render function.`);
8405 }
8406 }
8407 }
8408 const attrHandlers = {
8409 get: (target, key) => {
8410 {
8411 markAttrsAccessed();
8412 }
8413 return target[key];
8414 },
8415 set: () => {
8416 warn(`setupContext.attrs is readonly.`);
8417 return false;
8418 },
8419 deleteProperty: () => {
8420 warn(`setupContext.attrs is readonly.`);
8421 return false;
8422 }
8423 };
8424 function createSetupContext(instance) {
8425 const expose = exposed => {
8426 if (instance.exposed) {
8427 warn(`expose() should be called only once per setup().`);
8428 }
8429 instance.exposed = proxyRefs(exposed);
8430 };
8431 {
8432 // We use getters in dev in case libs like test-utils overwrite instance
8433 // properties (overwrites should not be done in prod)
8434 return Object.freeze({
8435 get attrs() {
8436 return new Proxy(instance.attrs, attrHandlers);
8437 },
8438 get slots() {
8439 return shallowReadonly(instance.slots);
8440 },
8441 get emit() {
8442 return (event, ...args) => instance.emit(event, ...args);
8443 },
8444 expose
8445 });
8446 }
8447 }
8448 // record effects created during a component's setup() so that they can be
8449 // stopped when the component unmounts
8450 function recordInstanceBoundEffect(effect, instance = currentInstance) {
8451 if (instance) {
8452 (instance.effects || (instance.effects = [])).push(effect);
8453 }
8454 }
8455 const classifyRE = /(?:^|[-_])(\w)/g;
8456 const classify = (str) => str.replace(classifyRE, c => c.toUpperCase()).replace(/[-_]/g, '');
8457 function getComponentName(Component) {
8458 return isFunction(Component)
8459 ? Component.displayName || Component.name
8460 : Component.name;
8461 }
8462 /* istanbul ignore next */
8463 function formatComponentName(instance, Component, isRoot = false) {
8464 let name = getComponentName(Component);
8465 if (!name && Component.__file) {
8466 const match = Component.__file.match(/([^/\\]+)\.\w+$/);
8467 if (match) {
8468 name = match[1];
8469 }
8470 }
8471 if (!name && instance && instance.parent) {
8472 // try to infer the name based on reverse resolution
8473 const inferFromRegistry = (registry) => {
8474 for (const key in registry) {
8475 if (registry[key] === Component) {
8476 return key;
8477 }
8478 }
8479 };
8480 name =
8481 inferFromRegistry(instance.components ||
8482 instance.parent.type.components) || inferFromRegistry(instance.appContext.components);
8483 }
8484 return name ? classify(name) : isRoot ? `App` : `Anonymous`;
8485 }
8486 function isClassComponent(value) {
8487 return isFunction(value) && '__vccOpts' in value;
8488 }
8489
8490 function computed$1(getterOrOptions) {
8491 const c = computed(getterOrOptions);
8492 recordInstanceBoundEffect(c.effect);
8493 return c;
8494 }
8495
8496 // implementation
8497 function defineProps() {
8498 {
8499 warn(`defineProps() is a compiler-hint helper that is only usable inside ` +
8500 `<script setup> of a single file component. Its arguments should be ` +
8501 `compiled away and passing it at runtime has no effect.`);
8502 }
8503 return null;
8504 }
8505 // implementation
8506 function defineEmit() {
8507 {
8508 warn(`defineEmit() is a compiler-hint helper that is only usable inside ` +
8509 `<script setup> of a single file component. Its arguments should be ` +
8510 `compiled away and passing it at runtime has no effect.`);
8511 }
8512 return null;
8513 }
8514 function useContext() {
8515 const i = getCurrentInstance();
8516 if (!i) {
8517 warn(`useContext() called without active instance.`);
8518 }
8519 return i.setupContext || (i.setupContext = createSetupContext(i));
8520 }
8521
8522 // Actual implementation
8523 function h(type, propsOrChildren, children) {
8524 const l = arguments.length;
8525 if (l === 2) {
8526 if (isObject(propsOrChildren) && !isArray(propsOrChildren)) {
8527 // single vnode without props
8528 if (isVNode(propsOrChildren)) {
8529 return createVNode(type, null, [propsOrChildren]);
8530 }
8531 // props without children
8532 return createVNode(type, propsOrChildren);
8533 }
8534 else {
8535 // omit props
8536 return createVNode(type, null, propsOrChildren);
8537 }
8538 }
8539 else {
8540 if (l > 3) {
8541 children = Array.prototype.slice.call(arguments, 2);
8542 }
8543 else if (l === 3 && isVNode(children)) {
8544 children = [children];
8545 }
8546 return createVNode(type, propsOrChildren, children);
8547 }
8548 }
8549
8550 const ssrContextKey = Symbol(`ssrContext` );
8551 const useSSRContext = () => {
8552 {
8553 warn(`useSSRContext() is not supported in the global build.`);
8554 }
8555 };
8556
8557 function initCustomFormatter() {
8558 /* eslint-disable no-restricted-globals */
8559 if (typeof window === 'undefined') {
8560 return;
8561 }
8562 const vueStyle = { style: 'color:#3ba776' };
8563 const numberStyle = { style: 'color:#0b1bc9' };
8564 const stringStyle = { style: 'color:#b62e24' };
8565 const keywordStyle = { style: 'color:#9d288c' };
8566 // custom formatter for Chrome
8567 // https://www.mattzeunert.com/2016/02/19/custom-chrome-devtools-object-formatters.html
8568 const formatter = {
8569 header(obj) {
8570 // TODO also format ComponentPublicInstance & ctx.slots/attrs in setup
8571 if (!isObject(obj)) {
8572 return null;
8573 }
8574 if (obj.__isVue) {
8575 return ['div', vueStyle, `VueInstance`];
8576 }
8577 else if (isRef(obj)) {
8578 return [
8579 'div',
8580 {},
8581 ['span', vueStyle, genRefFlag(obj)],
8582 '<',
8583 formatValue(obj.value),
8584 `>`
8585 ];
8586 }
8587 else if (isReactive(obj)) {
8588 return [
8589 'div',
8590 {},
8591 ['span', vueStyle, 'Reactive'],
8592 '<',
8593 formatValue(obj),
8594 `>${isReadonly(obj) ? ` (readonly)` : ``}`
8595 ];
8596 }
8597 else if (isReadonly(obj)) {
8598 return [
8599 'div',
8600 {},
8601 ['span', vueStyle, 'Readonly'],
8602 '<',
8603 formatValue(obj),
8604 '>'
8605 ];
8606 }
8607 return null;
8608 },
8609 hasBody(obj) {
8610 return obj && obj.__isVue;
8611 },
8612 body(obj) {
8613 if (obj && obj.__isVue) {
8614 return [
8615 'div',
8616 {},
8617 ...formatInstance(obj.$)
8618 ];
8619 }
8620 }
8621 };
8622 function formatInstance(instance) {
8623 const blocks = [];
8624 if (instance.type.props && instance.props) {
8625 blocks.push(createInstanceBlock('props', toRaw(instance.props)));
8626 }
8627 if (instance.setupState !== EMPTY_OBJ) {
8628 blocks.push(createInstanceBlock('setup', instance.setupState));
8629 }
8630 if (instance.data !== EMPTY_OBJ) {
8631 blocks.push(createInstanceBlock('data', toRaw(instance.data)));
8632 }
8633 const computed = extractKeys(instance, 'computed');
8634 if (computed) {
8635 blocks.push(createInstanceBlock('computed', computed));
8636 }
8637 const injected = extractKeys(instance, 'inject');
8638 if (injected) {
8639 blocks.push(createInstanceBlock('injected', injected));
8640 }
8641 blocks.push([
8642 'div',
8643 {},
8644 [
8645 'span',
8646 {
8647 style: keywordStyle.style + ';opacity:0.66'
8648 },
8649 '$ (internal): '
8650 ],
8651 ['object', { object: instance }]
8652 ]);
8653 return blocks;
8654 }
8655 function createInstanceBlock(type, target) {
8656 target = extend({}, target);
8657 if (!Object.keys(target).length) {
8658 return ['span', {}];
8659 }
8660 return [
8661 'div',
8662 { style: 'line-height:1.25em;margin-bottom:0.6em' },
8663 [
8664 'div',
8665 {
8666 style: 'color:#476582'
8667 },
8668 type
8669 ],
8670 [
8671 'div',
8672 {
8673 style: 'padding-left:1.25em'
8674 },
8675 ...Object.keys(target).map(key => {
8676 return [
8677 'div',
8678 {},
8679 ['span', keywordStyle, key + ': '],
8680 formatValue(target[key], false)
8681 ];
8682 })
8683 ]
8684 ];
8685 }
8686 function formatValue(v, asRaw = true) {
8687 if (typeof v === 'number') {
8688 return ['span', numberStyle, v];
8689 }
8690 else if (typeof v === 'string') {
8691 return ['span', stringStyle, JSON.stringify(v)];
8692 }
8693 else if (typeof v === 'boolean') {
8694 return ['span', keywordStyle, v];
8695 }
8696 else if (isObject(v)) {
8697 return ['object', { object: asRaw ? toRaw(v) : v }];
8698 }
8699 else {
8700 return ['span', stringStyle, String(v)];
8701 }
8702 }
8703 function extractKeys(instance, type) {
8704 const Comp = instance.type;
8705 if (isFunction(Comp)) {
8706 return;
8707 }
8708 const extracted = {};
8709 for (const key in instance.ctx) {
8710 if (isKeyOfType(Comp, key, type)) {
8711 extracted[key] = instance.ctx[key];
8712 }
8713 }
8714 return extracted;
8715 }
8716 function isKeyOfType(Comp, key, type) {
8717 const opts = Comp[type];
8718 if ((isArray(opts) && opts.includes(key)) ||
8719 (isObject(opts) && key in opts)) {
8720 return true;
8721 }
8722 if (Comp.extends && isKeyOfType(Comp.extends, key, type)) {
8723 return true;
8724 }
8725 if (Comp.mixins && Comp.mixins.some(m => isKeyOfType(m, key, type))) {
8726 return true;
8727 }
8728 }
8729 function genRefFlag(v) {
8730 if (v._shallow) {
8731 return `ShallowRef`;
8732 }
8733 if (v.effect) {
8734 return `ComputedRef`;
8735 }
8736 return `Ref`;
8737 }
8738 if (window.devtoolsFormatters) {
8739 window.devtoolsFormatters.push(formatter);
8740 }
8741 else {
8742 window.devtoolsFormatters = [formatter];
8743 }
8744 }
8745
8746 // Core API ------------------------------------------------------------------
8747 const version = "3.1.1";
8748 /**
8749 * SSR utils for \@vue/server-renderer. Only exposed in cjs builds.
8750 * @internal
8751 */
8752 const ssrUtils = (null);
8753 /**
8754 * @internal only exposed in compat builds
8755 */
8756 const resolveFilter = null;
8757 /**
8758 * @internal only exposed in compat builds.
8759 */
8760 const compatUtils = (null);
8761
8762 const svgNS = 'http://www.w3.org/2000/svg';
8763 const doc = (typeof document !== 'undefined' ? document : null);
8764 let tempContainer;
8765 let tempSVGContainer;
8766 const nodeOps = {
8767 insert: (child, parent, anchor) => {
8768 parent.insertBefore(child, anchor || null);
8769 },
8770 remove: child => {
8771 const parent = child.parentNode;
8772 if (parent) {
8773 parent.removeChild(child);
8774 }
8775 },
8776 createElement: (tag, isSVG, is, props) => {
8777 const el = isSVG
8778 ? doc.createElementNS(svgNS, tag)
8779 : doc.createElement(tag, is ? { is } : undefined);
8780 if (tag === 'select' && props && props.multiple != null) {
8781 el.setAttribute('multiple', props.multiple);
8782 }
8783 return el;
8784 },
8785 createText: text => doc.createTextNode(text),
8786 createComment: text => doc.createComment(text),
8787 setText: (node, text) => {
8788 node.nodeValue = text;
8789 },
8790 setElementText: (el, text) => {
8791 el.textContent = text;
8792 },
8793 parentNode: node => node.parentNode,
8794 nextSibling: node => node.nextSibling,
8795 querySelector: selector => doc.querySelector(selector),
8796 setScopeId(el, id) {
8797 el.setAttribute(id, '');
8798 },
8799 cloneNode(el) {
8800 const cloned = el.cloneNode(true);
8801 // #3072
8802 // - in `patchDOMProp`, we store the actual value in the `el._value` property.
8803 // - normally, elements using `:value` bindings will not be hoisted, but if
8804 // the bound value is a constant, e.g. `:value="true"` - they do get
8805 // hoisted.
8806 // - in production, hoisted nodes are cloned when subsequent inserts, but
8807 // cloneNode() does not copy the custom property we attached.
8808 // - This may need to account for other custom DOM properties we attach to
8809 // elements in addition to `_value` in the future.
8810 if (`_value` in el) {
8811 cloned._value = el._value;
8812 }
8813 return cloned;
8814 },
8815 // __UNSAFE__
8816 // Reason: innerHTML.
8817 // Static content here can only come from compiled templates.
8818 // As long as the user only uses trusted templates, this is safe.
8819 insertStaticContent(content, parent, anchor, isSVG) {
8820 const temp = isSVG
8821 ? tempSVGContainer ||
8822 (tempSVGContainer = doc.createElementNS(svgNS, 'svg'))
8823 : tempContainer || (tempContainer = doc.createElement('div'));
8824 temp.innerHTML = content;
8825 const first = temp.firstChild;
8826 let node = first;
8827 let last = node;
8828 while (node) {
8829 last = node;
8830 nodeOps.insert(node, parent, anchor);
8831 node = temp.firstChild;
8832 }
8833 return [first, last];
8834 }
8835 };
8836
8837 // compiler should normalize class + :class bindings on the same element
8838 // into a single binding ['staticClass', dynamic]
8839 function patchClass(el, value, isSVG) {
8840 if (value == null) {
8841 value = '';
8842 }
8843 if (isSVG) {
8844 el.setAttribute('class', value);
8845 }
8846 else {
8847 // directly setting className should be faster than setAttribute in theory
8848 // if this is an element during a transition, take the temporary transition
8849 // classes into account.
8850 const transitionClasses = el._vtc;
8851 if (transitionClasses) {
8852 value = (value
8853 ? [value, ...transitionClasses]
8854 : [...transitionClasses]).join(' ');
8855 }
8856 el.className = value;
8857 }
8858 }
8859
8860 function patchStyle(el, prev, next) {
8861 const style = el.style;
8862 if (!next) {
8863 el.removeAttribute('style');
8864 }
8865 else if (isString(next)) {
8866 if (prev !== next) {
8867 const current = style.display;
8868 style.cssText = next;
8869 // indicates that the `display` of the element is controlled by `v-show`,
8870 // so we always keep the current `display` value regardless of the `style` value,
8871 // thus handing over control to `v-show`.
8872 if ('_vod' in el) {
8873 style.display = current;
8874 }
8875 }
8876 }
8877 else {
8878 for (const key in next) {
8879 setStyle(style, key, next[key]);
8880 }
8881 if (prev && !isString(prev)) {
8882 for (const key in prev) {
8883 if (next[key] == null) {
8884 setStyle(style, key, '');
8885 }
8886 }
8887 }
8888 }
8889 }
8890 const importantRE = /\s*!important$/;
8891 function setStyle(style, name, val) {
8892 if (isArray(val)) {
8893 val.forEach(v => setStyle(style, name, v));
8894 }
8895 else {
8896 if (name.startsWith('--')) {
8897 // custom property definition
8898 style.setProperty(name, val);
8899 }
8900 else {
8901 const prefixed = autoPrefix(style, name);
8902 if (importantRE.test(val)) {
8903 // !important
8904 style.setProperty(hyphenate(prefixed), val.replace(importantRE, ''), 'important');
8905 }
8906 else {
8907 style[prefixed] = val;
8908 }
8909 }
8910 }
8911 }
8912 const prefixes = ['Webkit', 'Moz', 'ms'];
8913 const prefixCache = {};
8914 function autoPrefix(style, rawName) {
8915 const cached = prefixCache[rawName];
8916 if (cached) {
8917 return cached;
8918 }
8919 let name = camelize(rawName);
8920 if (name !== 'filter' && name in style) {
8921 return (prefixCache[rawName] = name);
8922 }
8923 name = capitalize(name);
8924 for (let i = 0; i < prefixes.length; i++) {
8925 const prefixed = prefixes[i] + name;
8926 if (prefixed in style) {
8927 return (prefixCache[rawName] = prefixed);
8928 }
8929 }
8930 return rawName;
8931 }
8932
8933 const xlinkNS = 'http://www.w3.org/1999/xlink';
8934 function patchAttr(el, key, value, isSVG, instance) {
8935 if (isSVG && key.startsWith('xlink:')) {
8936 if (value == null) {
8937 el.removeAttributeNS(xlinkNS, key.slice(6, key.length));
8938 }
8939 else {
8940 el.setAttributeNS(xlinkNS, key, value);
8941 }
8942 }
8943 else {
8944 // note we are only checking boolean attributes that don't have a
8945 // corresponding dom prop of the same name here.
8946 const isBoolean = isSpecialBooleanAttr(key);
8947 if (value == null || (isBoolean && value === false)) {
8948 el.removeAttribute(key);
8949 }
8950 else {
8951 el.setAttribute(key, isBoolean ? '' : value);
8952 }
8953 }
8954 }
8955
8956 // __UNSAFE__
8957 // functions. The user is responsible for using them with only trusted content.
8958 function patchDOMProp(el, key, value,
8959 // the following args are passed only due to potential innerHTML/textContent
8960 // overriding existing VNodes, in which case the old tree must be properly
8961 // unmounted.
8962 prevChildren, parentComponent, parentSuspense, unmountChildren) {
8963 if (key === 'innerHTML' || key === 'textContent') {
8964 if (prevChildren) {
8965 unmountChildren(prevChildren, parentComponent, parentSuspense);
8966 }
8967 el[key] = value == null ? '' : value;
8968 return;
8969 }
8970 if (key === 'value' && el.tagName !== 'PROGRESS') {
8971 // store value as _value as well since
8972 // non-string values will be stringified.
8973 el._value = value;
8974 const newValue = value == null ? '' : value;
8975 if (el.value !== newValue) {
8976 el.value = newValue;
8977 }
8978 if (value == null) {
8979 el.removeAttribute(key);
8980 }
8981 return;
8982 }
8983 if (value === '' || value == null) {
8984 const type = typeof el[key];
8985 if (value === '' && type === 'boolean') {
8986 // e.g. <select multiple> compiles to { multiple: '' }
8987 el[key] = true;
8988 return;
8989 }
8990 else if (value == null && type === 'string') {
8991 // e.g. <div :id="null">
8992 el[key] = '';
8993 el.removeAttribute(key);
8994 return;
8995 }
8996 else if (type === 'number') {
8997 // e.g. <img :width="null">
8998 el[key] = 0;
8999 el.removeAttribute(key);
9000 return;
9001 }
9002 }
9003 // some properties perform value validation and throw
9004 try {
9005 el[key] = value;
9006 }
9007 catch (e) {
9008 {
9009 warn(`Failed setting prop "${key}" on <${el.tagName.toLowerCase()}>: ` +
9010 `value ${value} is invalid.`, e);
9011 }
9012 }
9013 }
9014
9015 // Async edge case fix requires storing an event listener's attach timestamp.
9016 let _getNow = Date.now;
9017 let skipTimestampCheck = false;
9018 if (typeof window !== 'undefined') {
9019 // Determine what event timestamp the browser is using. Annoyingly, the
9020 // timestamp can either be hi-res (relative to page load) or low-res
9021 // (relative to UNIX epoch), so in order to compare time we have to use the
9022 // same timestamp type when saving the flush timestamp.
9023 if (_getNow() > document.createEvent('Event').timeStamp) {
9024 // if the low-res timestamp which is bigger than the event timestamp
9025 // (which is evaluated AFTER) it means the event is using a hi-res timestamp,
9026 // and we need to use the hi-res version for event listeners as well.
9027 _getNow = () => performance.now();
9028 }
9029 // #3485: Firefox <= 53 has incorrect Event.timeStamp implementation
9030 // and does not fire microtasks in between event propagation, so safe to exclude.
9031 const ffMatch = navigator.userAgent.match(/firefox\/(\d+)/i);
9032 skipTimestampCheck = !!(ffMatch && Number(ffMatch[1]) <= 53);
9033 }
9034 // To avoid the overhead of repeatedly calling performance.now(), we cache
9035 // and use the same timestamp for all event listeners attached in the same tick.
9036 let cachedNow = 0;
9037 const p = Promise.resolve();
9038 const reset = () => {
9039 cachedNow = 0;
9040 };
9041 const getNow = () => cachedNow || (p.then(reset), (cachedNow = _getNow()));
9042 function addEventListener(el, event, handler, options) {
9043 el.addEventListener(event, handler, options);
9044 }
9045 function removeEventListener(el, event, handler, options) {
9046 el.removeEventListener(event, handler, options);
9047 }
9048 function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
9049 // vei = vue event invokers
9050 const invokers = el._vei || (el._vei = {});
9051 const existingInvoker = invokers[rawName];
9052 if (nextValue && existingInvoker) {
9053 // patch
9054 existingInvoker.value = nextValue;
9055 }
9056 else {
9057 const [name, options] = parseName(rawName);
9058 if (nextValue) {
9059 // add
9060 const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
9061 addEventListener(el, name, invoker, options);
9062 }
9063 else if (existingInvoker) {
9064 // remove
9065 removeEventListener(el, name, existingInvoker, options);
9066 invokers[rawName] = undefined;
9067 }
9068 }
9069 }
9070 const optionsModifierRE = /(?:Once|Passive|Capture)$/;
9071 function parseName(name) {
9072 let options;
9073 if (optionsModifierRE.test(name)) {
9074 options = {};
9075 let m;
9076 while ((m = name.match(optionsModifierRE))) {
9077 name = name.slice(0, name.length - m[0].length);
9078 options[m[0].toLowerCase()] = true;
9079 }
9080 }
9081 return [hyphenate(name.slice(2)), options];
9082 }
9083 function createInvoker(initialValue, instance) {
9084 const invoker = (e) => {
9085 // async edge case #6566: inner click event triggers patch, event handler
9086 // attached to outer element during patch, and triggered again. This
9087 // happens because browsers fire microtask ticks between event propagation.
9088 // the solution is simple: we save the timestamp when a handler is attached,
9089 // and the handler would only fire if the event passed to it was fired
9090 // AFTER it was attached.
9091 const timeStamp = e.timeStamp || _getNow();
9092 if (skipTimestampCheck || timeStamp >= invoker.attached - 1) {
9093 callWithAsyncErrorHandling(patchStopImmediatePropagation(e, invoker.value), instance, 5 /* NATIVE_EVENT_HANDLER */, [e]);
9094 }
9095 };
9096 invoker.value = initialValue;
9097 invoker.attached = getNow();
9098 return invoker;
9099 }
9100 function patchStopImmediatePropagation(e, value) {
9101 if (isArray(value)) {
9102 const originalStop = e.stopImmediatePropagation;
9103 e.stopImmediatePropagation = () => {
9104 originalStop.call(e);
9105 e._stopped = true;
9106 };
9107 return value.map(fn => (e) => !e._stopped && fn(e));
9108 }
9109 else {
9110 return value;
9111 }
9112 }
9113
9114 const nativeOnRE = /^on[a-z]/;
9115 const forcePatchProp = (_, key) => key === 'value';
9116 const patchProp = (el, key, prevValue, nextValue, isSVG = false, prevChildren, parentComponent, parentSuspense, unmountChildren) => {
9117 switch (key) {
9118 // special
9119 case 'class':
9120 patchClass(el, nextValue, isSVG);
9121 break;
9122 case 'style':
9123 patchStyle(el, prevValue, nextValue);
9124 break;
9125 default:
9126 if (isOn(key)) {
9127 // ignore v-model listeners
9128 if (!isModelListener(key)) {
9129 patchEvent(el, key, prevValue, nextValue, parentComponent);
9130 }
9131 }
9132 else if (shouldSetAsProp(el, key, nextValue, isSVG)) {
9133 patchDOMProp(el, key, nextValue, prevChildren, parentComponent, parentSuspense, unmountChildren);
9134 }
9135 else {
9136 // special case for <input v-model type="checkbox"> with
9137 // :true-value & :false-value
9138 // store value as dom properties since non-string values will be
9139 // stringified.
9140 if (key === 'true-value') {
9141 el._trueValue = nextValue;
9142 }
9143 else if (key === 'false-value') {
9144 el._falseValue = nextValue;
9145 }
9146 patchAttr(el, key, nextValue, isSVG);
9147 }
9148 break;
9149 }
9150 };
9151 function shouldSetAsProp(el, key, value, isSVG) {
9152 if (isSVG) {
9153 // most keys must be set as attribute on svg elements to work
9154 // ...except innerHTML
9155 if (key === 'innerHTML') {
9156 return true;
9157 }
9158 // or native onclick with function values
9159 if (key in el && nativeOnRE.test(key) && isFunction(value)) {
9160 return true;
9161 }
9162 return false;
9163 }
9164 // spellcheck and draggable are numerated attrs, however their
9165 // corresponding DOM properties are actually booleans - this leads to
9166 // setting it with a string "false" value leading it to be coerced to
9167 // `true`, so we need to always treat them as attributes.
9168 // Note that `contentEditable` doesn't have this problem: its DOM
9169 // property is also enumerated string values.
9170 if (key === 'spellcheck' || key === 'draggable') {
9171 return false;
9172 }
9173 // #1787, #2840 form property on form elements is readonly and must be set as
9174 // attribute.
9175 if (key === 'form') {
9176 return false;
9177 }
9178 // #1526 <input list> must be set as attribute
9179 if (key === 'list' && el.tagName === 'INPUT') {
9180 return false;
9181 }
9182 // #2766 <textarea type> must be set as attribute
9183 if (key === 'type' && el.tagName === 'TEXTAREA') {
9184 return false;
9185 }
9186 // native onclick with string value, must be set as attribute
9187 if (nativeOnRE.test(key) && isString(value)) {
9188 return false;
9189 }
9190 return key in el;
9191 }
9192
9193 function useCssModule(name = '$style') {
9194 /* istanbul ignore else */
9195 {
9196 {
9197 warn(`useCssModule() is not supported in the global build.`);
9198 }
9199 return EMPTY_OBJ;
9200 }
9201 }
9202
9203 /**
9204 * Runtime helper for SFC's CSS variable injection feature.
9205 * @private
9206 */
9207 function useCssVars(getter) {
9208 const instance = getCurrentInstance();
9209 /* istanbul ignore next */
9210 if (!instance) {
9211 warn(`useCssVars is called without current active component instance.`);
9212 return;
9213 }
9214 const setVars = () => setVarsOnVNode(instance.subTree, getter(instance.proxy));
9215 onMounted(() => watchEffect(setVars, { flush: 'post' }));
9216 onUpdated(setVars);
9217 }
9218 function setVarsOnVNode(vnode, vars) {
9219 if (vnode.shapeFlag & 128 /* SUSPENSE */) {
9220 const suspense = vnode.suspense;
9221 vnode = suspense.activeBranch;
9222 if (suspense.pendingBranch && !suspense.isHydrating) {
9223 suspense.effects.push(() => {
9224 setVarsOnVNode(suspense.activeBranch, vars);
9225 });
9226 }
9227 }
9228 // drill down HOCs until it's a non-component vnode
9229 while (vnode.component) {
9230 vnode = vnode.component.subTree;
9231 }
9232 if (vnode.shapeFlag & 1 /* ELEMENT */ && vnode.el) {
9233 const style = vnode.el.style;
9234 for (const key in vars) {
9235 style.setProperty(`--${key}`, vars[key]);
9236 }
9237 }
9238 else if (vnode.type === Fragment) {
9239 vnode.children.forEach(c => setVarsOnVNode(c, vars));
9240 }
9241 }
9242
9243 const TRANSITION = 'transition';
9244 const ANIMATION = 'animation';
9245 // DOM Transition is a higher-order-component based on the platform-agnostic
9246 // base Transition component, with DOM-specific logic.
9247 const Transition = (props, { slots }) => h(BaseTransition, resolveTransitionProps(props), slots);
9248 Transition.displayName = 'Transition';
9249 const DOMTransitionPropsValidators = {
9250 name: String,
9251 type: String,
9252 css: {
9253 type: Boolean,
9254 default: true
9255 },
9256 duration: [String, Number, Object],
9257 enterFromClass: String,
9258 enterActiveClass: String,
9259 enterToClass: String,
9260 appearFromClass: String,
9261 appearActiveClass: String,
9262 appearToClass: String,
9263 leaveFromClass: String,
9264 leaveActiveClass: String,
9265 leaveToClass: String
9266 };
9267 const TransitionPropsValidators = (Transition.props = /*#__PURE__*/ extend({}, BaseTransition.props, DOMTransitionPropsValidators));
9268 /**
9269 * #3227 Incoming hooks may be merged into arrays when wrapping Transition
9270 * with custom HOCs.
9271 */
9272 const callHook$1 = (hook, args = []) => {
9273 if (isArray(hook)) {
9274 hook.forEach(h => h(...args));
9275 }
9276 else if (hook) {
9277 hook(...args);
9278 }
9279 };
9280 /**
9281 * Check if a hook expects a callback (2nd arg), which means the user
9282 * intends to explicitly control the end of the transition.
9283 */
9284 const hasExplicitCallback = (hook) => {
9285 return hook
9286 ? isArray(hook)
9287 ? hook.some(h => h.length > 1)
9288 : hook.length > 1
9289 : false;
9290 };
9291 function resolveTransitionProps(rawProps) {
9292 const baseProps = {};
9293 for (const key in rawProps) {
9294 if (!(key in DOMTransitionPropsValidators)) {
9295 baseProps[key] = rawProps[key];
9296 }
9297 }
9298 if (rawProps.css === false) {
9299 return baseProps;
9300 }
9301 const { name = 'v', type, 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;
9302 const durations = normalizeDuration(duration);
9303 const enterDuration = durations && durations[0];
9304 const leaveDuration = durations && durations[1];
9305 const { onBeforeEnter, onEnter, onEnterCancelled, onLeave, onLeaveCancelled, onBeforeAppear = onBeforeEnter, onAppear = onEnter, onAppearCancelled = onEnterCancelled } = baseProps;
9306 const finishEnter = (el, isAppear, done) => {
9307 removeTransitionClass(el, isAppear ? appearToClass : enterToClass);
9308 removeTransitionClass(el, isAppear ? appearActiveClass : enterActiveClass);
9309 done && done();
9310 };
9311 const finishLeave = (el, done) => {
9312 removeTransitionClass(el, leaveToClass);
9313 removeTransitionClass(el, leaveActiveClass);
9314 done && done();
9315 };
9316 const makeEnterHook = (isAppear) => {
9317 return (el, done) => {
9318 const hook = isAppear ? onAppear : onEnter;
9319 const resolve = () => finishEnter(el, isAppear, done);
9320 callHook$1(hook, [el, resolve]);
9321 nextFrame(() => {
9322 removeTransitionClass(el, isAppear ? appearFromClass : enterFromClass);
9323 addTransitionClass(el, isAppear ? appearToClass : enterToClass);
9324 if (!hasExplicitCallback(hook)) {
9325 whenTransitionEnds(el, type, enterDuration, resolve);
9326 }
9327 });
9328 };
9329 };
9330 return extend(baseProps, {
9331 onBeforeEnter(el) {
9332 callHook$1(onBeforeEnter, [el]);
9333 addTransitionClass(el, enterFromClass);
9334 addTransitionClass(el, enterActiveClass);
9335 },
9336 onBeforeAppear(el) {
9337 callHook$1(onBeforeAppear, [el]);
9338 addTransitionClass(el, appearFromClass);
9339 addTransitionClass(el, appearActiveClass);
9340 },
9341 onEnter: makeEnterHook(false),
9342 onAppear: makeEnterHook(true),
9343 onLeave(el, done) {
9344 const resolve = () => finishLeave(el, done);
9345 addTransitionClass(el, leaveFromClass);
9346 // force reflow so *-leave-from classes immediately take effect (#2593)
9347 forceReflow();
9348 addTransitionClass(el, leaveActiveClass);
9349 nextFrame(() => {
9350 removeTransitionClass(el, leaveFromClass);
9351 addTransitionClass(el, leaveToClass);
9352 if (!hasExplicitCallback(onLeave)) {
9353 whenTransitionEnds(el, type, leaveDuration, resolve);
9354 }
9355 });
9356 callHook$1(onLeave, [el, resolve]);
9357 },
9358 onEnterCancelled(el) {
9359 finishEnter(el, false);
9360 callHook$1(onEnterCancelled, [el]);
9361 },
9362 onAppearCancelled(el) {
9363 finishEnter(el, true);
9364 callHook$1(onAppearCancelled, [el]);
9365 },
9366 onLeaveCancelled(el) {
9367 finishLeave(el);
9368 callHook$1(onLeaveCancelled, [el]);
9369 }
9370 });
9371 }
9372 function normalizeDuration(duration) {
9373 if (duration == null) {
9374 return null;
9375 }
9376 else if (isObject(duration)) {
9377 return [NumberOf(duration.enter), NumberOf(duration.leave)];
9378 }
9379 else {
9380 const n = NumberOf(duration);
9381 return [n, n];
9382 }
9383 }
9384 function NumberOf(val) {
9385 const res = toNumber(val);
9386 validateDuration(res);
9387 return res;
9388 }
9389 function validateDuration(val) {
9390 if (typeof val !== 'number') {
9391 warn(`<transition> explicit duration is not a valid number - ` +
9392 `got ${JSON.stringify(val)}.`);
9393 }
9394 else if (isNaN(val)) {
9395 warn(`<transition> explicit duration is NaN - ` +
9396 'the duration expression might be incorrect.');
9397 }
9398 }
9399 function addTransitionClass(el, cls) {
9400 cls.split(/\s+/).forEach(c => c && el.classList.add(c));
9401 (el._vtc ||
9402 (el._vtc = new Set())).add(cls);
9403 }
9404 function removeTransitionClass(el, cls) {
9405 cls.split(/\s+/).forEach(c => c && el.classList.remove(c));
9406 const { _vtc } = el;
9407 if (_vtc) {
9408 _vtc.delete(cls);
9409 if (!_vtc.size) {
9410 el._vtc = undefined;
9411 }
9412 }
9413 }
9414 function nextFrame(cb) {
9415 requestAnimationFrame(() => {
9416 requestAnimationFrame(cb);
9417 });
9418 }
9419 let endId = 0;
9420 function whenTransitionEnds(el, expectedType, explicitTimeout, resolve) {
9421 const id = (el._endId = ++endId);
9422 const resolveIfNotStale = () => {
9423 if (id === el._endId) {
9424 resolve();
9425 }
9426 };
9427 if (explicitTimeout) {
9428 return setTimeout(resolveIfNotStale, explicitTimeout);
9429 }
9430 const { type, timeout, propCount } = getTransitionInfo(el, expectedType);
9431 if (!type) {
9432 return resolve();
9433 }
9434 const endEvent = type + 'end';
9435 let ended = 0;
9436 const end = () => {
9437 el.removeEventListener(endEvent, onEnd);
9438 resolveIfNotStale();
9439 };
9440 const onEnd = (e) => {
9441 if (e.target === el && ++ended >= propCount) {
9442 end();
9443 }
9444 };
9445 setTimeout(() => {
9446 if (ended < propCount) {
9447 end();
9448 }
9449 }, timeout + 1);
9450 el.addEventListener(endEvent, onEnd);
9451 }
9452 function getTransitionInfo(el, expectedType) {
9453 const styles = window.getComputedStyle(el);
9454 // JSDOM may return undefined for transition properties
9455 const getStyleProperties = (key) => (styles[key] || '').split(', ');
9456 const transitionDelays = getStyleProperties(TRANSITION + 'Delay');
9457 const transitionDurations = getStyleProperties(TRANSITION + 'Duration');
9458 const transitionTimeout = getTimeout(transitionDelays, transitionDurations);
9459 const animationDelays = getStyleProperties(ANIMATION + 'Delay');
9460 const animationDurations = getStyleProperties(ANIMATION + 'Duration');
9461 const animationTimeout = getTimeout(animationDelays, animationDurations);
9462 let type = null;
9463 let timeout = 0;
9464 let propCount = 0;
9465 /* istanbul ignore if */
9466 if (expectedType === TRANSITION) {
9467 if (transitionTimeout > 0) {
9468 type = TRANSITION;
9469 timeout = transitionTimeout;
9470 propCount = transitionDurations.length;
9471 }
9472 }
9473 else if (expectedType === ANIMATION) {
9474 if (animationTimeout > 0) {
9475 type = ANIMATION;
9476 timeout = animationTimeout;
9477 propCount = animationDurations.length;
9478 }
9479 }
9480 else {
9481 timeout = Math.max(transitionTimeout, animationTimeout);
9482 type =
9483 timeout > 0
9484 ? transitionTimeout > animationTimeout
9485 ? TRANSITION
9486 : ANIMATION
9487 : null;
9488 propCount = type
9489 ? type === TRANSITION
9490 ? transitionDurations.length
9491 : animationDurations.length
9492 : 0;
9493 }
9494 const hasTransform = type === TRANSITION &&
9495 /\b(transform|all)(,|$)/.test(styles[TRANSITION + 'Property']);
9496 return {
9497 type,
9498 timeout,
9499 propCount,
9500 hasTransform
9501 };
9502 }
9503 function getTimeout(delays, durations) {
9504 while (delays.length < durations.length) {
9505 delays = delays.concat(delays);
9506 }
9507 return Math.max(...durations.map((d, i) => toMs(d) + toMs(delays[i])));
9508 }
9509 // Old versions of Chromium (below 61.0.3163.100) formats floating pointer
9510 // numbers in a locale-dependent way, using a comma instead of a dot.
9511 // If comma is not replaced with a dot, the input will be rounded down
9512 // (i.e. acting as a floor function) causing unexpected behaviors
9513 function toMs(s) {
9514 return Number(s.slice(0, -1).replace(',', '.')) * 1000;
9515 }
9516 // synchronously force layout to put elements into a certain state
9517 function forceReflow() {
9518 return document.body.offsetHeight;
9519 }
9520
9521 const positionMap = new WeakMap();
9522 const newPositionMap = new WeakMap();
9523 const TransitionGroupImpl = {
9524 name: 'TransitionGroup',
9525 props: /*#__PURE__*/ extend({}, TransitionPropsValidators, {
9526 tag: String,
9527 moveClass: String
9528 }),
9529 setup(props, { slots }) {
9530 const instance = getCurrentInstance();
9531 const state = useTransitionState();
9532 let prevChildren;
9533 let children;
9534 onUpdated(() => {
9535 // children is guaranteed to exist after initial render
9536 if (!prevChildren.length) {
9537 return;
9538 }
9539 const moveClass = props.moveClass || `${props.name || 'v'}-move`;
9540 if (!hasCSSTransform(prevChildren[0].el, instance.vnode.el, moveClass)) {
9541 return;
9542 }
9543 // we divide the work into three loops to avoid mixing DOM reads and writes
9544 // in each iteration - which helps prevent layout thrashing.
9545 prevChildren.forEach(callPendingCbs);
9546 prevChildren.forEach(recordPosition);
9547 const movedChildren = prevChildren.filter(applyTranslation);
9548 // force reflow to put everything in position
9549 forceReflow();
9550 movedChildren.forEach(c => {
9551 const el = c.el;
9552 const style = el.style;
9553 addTransitionClass(el, moveClass);
9554 style.transform = style.webkitTransform = style.transitionDuration = '';
9555 const cb = (el._moveCb = (e) => {
9556 if (e && e.target !== el) {
9557 return;
9558 }
9559 if (!e || /transform$/.test(e.propertyName)) {
9560 el.removeEventListener('transitionend', cb);
9561 el._moveCb = null;
9562 removeTransitionClass(el, moveClass);
9563 }
9564 });
9565 el.addEventListener('transitionend', cb);
9566 });
9567 });
9568 return () => {
9569 const rawProps = toRaw(props);
9570 const cssTransitionProps = resolveTransitionProps(rawProps);
9571 let tag = rawProps.tag || Fragment;
9572 prevChildren = children;
9573 children = slots.default ? getTransitionRawChildren(slots.default()) : [];
9574 for (let i = 0; i < children.length; i++) {
9575 const child = children[i];
9576 if (child.key != null) {
9577 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
9578 }
9579 else {
9580 warn(`<TransitionGroup> children must be keyed.`);
9581 }
9582 }
9583 if (prevChildren) {
9584 for (let i = 0; i < prevChildren.length; i++) {
9585 const child = prevChildren[i];
9586 setTransitionHooks(child, resolveTransitionHooks(child, cssTransitionProps, state, instance));
9587 positionMap.set(child, child.el.getBoundingClientRect());
9588 }
9589 }
9590 return createVNode(tag, null, children);
9591 };
9592 }
9593 };
9594 const TransitionGroup = TransitionGroupImpl;
9595 function callPendingCbs(c) {
9596 const el = c.el;
9597 if (el._moveCb) {
9598 el._moveCb();
9599 }
9600 if (el._enterCb) {
9601 el._enterCb();
9602 }
9603 }
9604 function recordPosition(c) {
9605 newPositionMap.set(c, c.el.getBoundingClientRect());
9606 }
9607 function applyTranslation(c) {
9608 const oldPos = positionMap.get(c);
9609 const newPos = newPositionMap.get(c);
9610 const dx = oldPos.left - newPos.left;
9611 const dy = oldPos.top - newPos.top;
9612 if (dx || dy) {
9613 const s = c.el.style;
9614 s.transform = s.webkitTransform = `translate(${dx}px,${dy}px)`;
9615 s.transitionDuration = '0s';
9616 return c;
9617 }
9618 }
9619 function hasCSSTransform(el, root, moveClass) {
9620 // Detect whether an element with the move class applied has
9621 // CSS transitions. Since the element may be inside an entering
9622 // transition at this very moment, we make a clone of it and remove
9623 // all other transition classes applied to ensure only the move class
9624 // is applied.
9625 const clone = el.cloneNode();
9626 if (el._vtc) {
9627 el._vtc.forEach(cls => {
9628 cls.split(/\s+/).forEach(c => c && clone.classList.remove(c));
9629 });
9630 }
9631 moveClass.split(/\s+/).forEach(c => c && clone.classList.add(c));
9632 clone.style.display = 'none';
9633 const container = (root.nodeType === 1
9634 ? root
9635 : root.parentNode);
9636 container.appendChild(clone);
9637 const { hasTransform } = getTransitionInfo(clone);
9638 container.removeChild(clone);
9639 return hasTransform;
9640 }
9641
9642 const getModelAssigner = (vnode) => {
9643 const fn = vnode.props['onUpdate:modelValue'];
9644 return isArray(fn) ? value => invokeArrayFns(fn, value) : fn;
9645 };
9646 function onCompositionStart(e) {
9647 e.target.composing = true;
9648 }
9649 function onCompositionEnd(e) {
9650 const target = e.target;
9651 if (target.composing) {
9652 target.composing = false;
9653 trigger$1(target, 'input');
9654 }
9655 }
9656 function trigger$1(el, type) {
9657 const e = document.createEvent('HTMLEvents');
9658 e.initEvent(type, true, true);
9659 el.dispatchEvent(e);
9660 }
9661 // We are exporting the v-model runtime directly as vnode hooks so that it can
9662 // be tree-shaken in case v-model is never used.
9663 const vModelText = {
9664 created(el, { modifiers: { lazy, trim, number } }, vnode) {
9665 el._assign = getModelAssigner(vnode);
9666 const castToNumber = number || el.type === 'number';
9667 addEventListener(el, lazy ? 'change' : 'input', e => {
9668 if (e.target.composing)
9669 return;
9670 let domValue = el.value;
9671 if (trim) {
9672 domValue = domValue.trim();
9673 }
9674 else if (castToNumber) {
9675 domValue = toNumber(domValue);
9676 }
9677 el._assign(domValue);
9678 });
9679 if (trim) {
9680 addEventListener(el, 'change', () => {
9681 el.value = el.value.trim();
9682 });
9683 }
9684 if (!lazy) {
9685 addEventListener(el, 'compositionstart', onCompositionStart);
9686 addEventListener(el, 'compositionend', onCompositionEnd);
9687 // Safari < 10.2 & UIWebView doesn't fire compositionend when
9688 // switching focus before confirming composition choice
9689 // this also fixes the issue where some browsers e.g. iOS Chrome
9690 // fires "change" instead of "input" on autocomplete.
9691 addEventListener(el, 'change', onCompositionEnd);
9692 }
9693 },
9694 // set value on mounted so it's after min/max for type="range"
9695 mounted(el, { value }) {
9696 el.value = value == null ? '' : value;
9697 },
9698 beforeUpdate(el, { value, modifiers: { trim, number } }, vnode) {
9699 el._assign = getModelAssigner(vnode);
9700 // avoid clearing unresolved text. #2302
9701 if (el.composing)
9702 return;
9703 if (document.activeElement === el) {
9704 if (trim && el.value.trim() === value) {
9705 return;
9706 }
9707 if ((number || el.type === 'number') && toNumber(el.value) === value) {
9708 return;
9709 }
9710 }
9711 const newValue = value == null ? '' : value;
9712 if (el.value !== newValue) {
9713 el.value = newValue;
9714 }
9715 }
9716 };
9717 const vModelCheckbox = {
9718 created(el, _, vnode) {
9719 el._assign = getModelAssigner(vnode);
9720 addEventListener(el, 'change', () => {
9721 const modelValue = el._modelValue;
9722 const elementValue = getValue(el);
9723 const checked = el.checked;
9724 const assign = el._assign;
9725 if (isArray(modelValue)) {
9726 const index = looseIndexOf(modelValue, elementValue);
9727 const found = index !== -1;
9728 if (checked && !found) {
9729 assign(modelValue.concat(elementValue));
9730 }
9731 else if (!checked && found) {
9732 const filtered = [...modelValue];
9733 filtered.splice(index, 1);
9734 assign(filtered);
9735 }
9736 }
9737 else if (isSet(modelValue)) {
9738 const cloned = new Set(modelValue);
9739 if (checked) {
9740 cloned.add(elementValue);
9741 }
9742 else {
9743 cloned.delete(elementValue);
9744 }
9745 assign(cloned);
9746 }
9747 else {
9748 assign(getCheckboxValue(el, checked));
9749 }
9750 });
9751 },
9752 // set initial checked on mount to wait for true-value/false-value
9753 mounted: setChecked,
9754 beforeUpdate(el, binding, vnode) {
9755 el._assign = getModelAssigner(vnode);
9756 setChecked(el, binding, vnode);
9757 }
9758 };
9759 function setChecked(el, { value, oldValue }, vnode) {
9760 el._modelValue = value;
9761 if (isArray(value)) {
9762 el.checked = looseIndexOf(value, vnode.props.value) > -1;
9763 }
9764 else if (isSet(value)) {
9765 el.checked = value.has(vnode.props.value);
9766 }
9767 else if (value !== oldValue) {
9768 el.checked = looseEqual(value, getCheckboxValue(el, true));
9769 }
9770 }
9771 const vModelRadio = {
9772 created(el, { value }, vnode) {
9773 el.checked = looseEqual(value, vnode.props.value);
9774 el._assign = getModelAssigner(vnode);
9775 addEventListener(el, 'change', () => {
9776 el._assign(getValue(el));
9777 });
9778 },
9779 beforeUpdate(el, { value, oldValue }, vnode) {
9780 el._assign = getModelAssigner(vnode);
9781 if (value !== oldValue) {
9782 el.checked = looseEqual(value, vnode.props.value);
9783 }
9784 }
9785 };
9786 const vModelSelect = {
9787 created(el, { value, modifiers: { number } }, vnode) {
9788 const isSetModel = isSet(value);
9789 addEventListener(el, 'change', () => {
9790 const selectedVal = Array.prototype.filter
9791 .call(el.options, (o) => o.selected)
9792 .map((o) => number ? toNumber(getValue(o)) : getValue(o));
9793 el._assign(el.multiple
9794 ? isSetModel
9795 ? new Set(selectedVal)
9796 : selectedVal
9797 : selectedVal[0]);
9798 });
9799 el._assign = getModelAssigner(vnode);
9800 },
9801 // set value in mounted & updated because <select> relies on its children
9802 // <option>s.
9803 mounted(el, { value }) {
9804 setSelected(el, value);
9805 },
9806 beforeUpdate(el, _binding, vnode) {
9807 el._assign = getModelAssigner(vnode);
9808 },
9809 updated(el, { value }) {
9810 setSelected(el, value);
9811 }
9812 };
9813 function setSelected(el, value) {
9814 const isMultiple = el.multiple;
9815 if (isMultiple && !isArray(value) && !isSet(value)) {
9816 warn(`<select multiple v-model> expects an Array or Set value for its binding, ` +
9817 `but got ${Object.prototype.toString.call(value).slice(8, -1)}.`);
9818 return;
9819 }
9820 for (let i = 0, l = el.options.length; i < l; i++) {
9821 const option = el.options[i];
9822 const optionValue = getValue(option);
9823 if (isMultiple) {
9824 if (isArray(value)) {
9825 option.selected = looseIndexOf(value, optionValue) > -1;
9826 }
9827 else {
9828 option.selected = value.has(optionValue);
9829 }
9830 }
9831 else {
9832 if (looseEqual(getValue(option), value)) {
9833 if (el.selectedIndex !== i)
9834 el.selectedIndex = i;
9835 return;
9836 }
9837 }
9838 }
9839 if (!isMultiple && el.selectedIndex !== -1) {
9840 el.selectedIndex = -1;
9841 }
9842 }
9843 // retrieve raw value set via :value bindings
9844 function getValue(el) {
9845 return '_value' in el ? el._value : el.value;
9846 }
9847 // retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
9848 function getCheckboxValue(el, checked) {
9849 const key = checked ? '_trueValue' : '_falseValue';
9850 return key in el ? el[key] : checked;
9851 }
9852 const vModelDynamic = {
9853 created(el, binding, vnode) {
9854 callModelHook(el, binding, vnode, null, 'created');
9855 },
9856 mounted(el, binding, vnode) {
9857 callModelHook(el, binding, vnode, null, 'mounted');
9858 },
9859 beforeUpdate(el, binding, vnode, prevVNode) {
9860 callModelHook(el, binding, vnode, prevVNode, 'beforeUpdate');
9861 },
9862 updated(el, binding, vnode, prevVNode) {
9863 callModelHook(el, binding, vnode, prevVNode, 'updated');
9864 }
9865 };
9866 function callModelHook(el, binding, vnode, prevVNode, hook) {
9867 let modelToUse;
9868 switch (el.tagName) {
9869 case 'SELECT':
9870 modelToUse = vModelSelect;
9871 break;
9872 case 'TEXTAREA':
9873 modelToUse = vModelText;
9874 break;
9875 default:
9876 switch (vnode.props && vnode.props.type) {
9877 case 'checkbox':
9878 modelToUse = vModelCheckbox;
9879 break;
9880 case 'radio':
9881 modelToUse = vModelRadio;
9882 break;
9883 default:
9884 modelToUse = vModelText;
9885 }
9886 }
9887 const fn = modelToUse[hook];
9888 fn && fn(el, binding, vnode, prevVNode);
9889 }
9890
9891 const systemModifiers = ['ctrl', 'shift', 'alt', 'meta'];
9892 const modifierGuards = {
9893 stop: e => e.stopPropagation(),
9894 prevent: e => e.preventDefault(),
9895 self: e => e.target !== e.currentTarget,
9896 ctrl: e => !e.ctrlKey,
9897 shift: e => !e.shiftKey,
9898 alt: e => !e.altKey,
9899 meta: e => !e.metaKey,
9900 left: e => 'button' in e && e.button !== 0,
9901 middle: e => 'button' in e && e.button !== 1,
9902 right: e => 'button' in e && e.button !== 2,
9903 exact: (e, modifiers) => systemModifiers.some(m => e[`${m}Key`] && !modifiers.includes(m))
9904 };
9905 /**
9906 * @private
9907 */
9908 const withModifiers = (fn, modifiers) => {
9909 return (event, ...args) => {
9910 for (let i = 0; i < modifiers.length; i++) {
9911 const guard = modifierGuards[modifiers[i]];
9912 if (guard && guard(event, modifiers))
9913 return;
9914 }
9915 return fn(event, ...args);
9916 };
9917 };
9918 // Kept for 2.x compat.
9919 // Note: IE11 compat for `spacebar` and `del` is removed for now.
9920 const keyNames = {
9921 esc: 'escape',
9922 space: ' ',
9923 up: 'arrow-up',
9924 left: 'arrow-left',
9925 right: 'arrow-right',
9926 down: 'arrow-down',
9927 delete: 'backspace'
9928 };
9929 /**
9930 * @private
9931 */
9932 const withKeys = (fn, modifiers) => {
9933 return (event) => {
9934 if (!('key' in event)) {
9935 return;
9936 }
9937 const eventKey = hyphenate(event.key);
9938 if (modifiers.some(k => k === eventKey || keyNames[k] === eventKey)) {
9939 return fn(event);
9940 }
9941 };
9942 };
9943
9944 const vShow = {
9945 beforeMount(el, { value }, { transition }) {
9946 el._vod = el.style.display === 'none' ? '' : el.style.display;
9947 if (transition && value) {
9948 transition.beforeEnter(el);
9949 }
9950 else {
9951 setDisplay(el, value);
9952 }
9953 },
9954 mounted(el, { value }, { transition }) {
9955 if (transition && value) {
9956 transition.enter(el);
9957 }
9958 },
9959 updated(el, { value, oldValue }, { transition }) {
9960 if (!value === !oldValue)
9961 return;
9962 if (transition) {
9963 if (value) {
9964 transition.beforeEnter(el);
9965 setDisplay(el, true);
9966 transition.enter(el);
9967 }
9968 else {
9969 transition.leave(el, () => {
9970 setDisplay(el, false);
9971 });
9972 }
9973 }
9974 else {
9975 setDisplay(el, value);
9976 }
9977 },
9978 beforeUnmount(el, { value }) {
9979 setDisplay(el, value);
9980 }
9981 };
9982 function setDisplay(el, value) {
9983 el.style.display = value ? el._vod : 'none';
9984 }
9985
9986 const rendererOptions = extend({ patchProp, forcePatchProp }, nodeOps);
9987 // lazy create the renderer - this makes core renderer logic tree-shakable
9988 // in case the user only imports reactivity utilities from Vue.
9989 let renderer;
9990 let enabledHydration = false;
9991 function ensureRenderer() {
9992 return renderer || (renderer = createRenderer(rendererOptions));
9993 }
9994 function ensureHydrationRenderer() {
9995 renderer = enabledHydration
9996 ? renderer
9997 : createHydrationRenderer(rendererOptions);
9998 enabledHydration = true;
9999 return renderer;
10000 }
10001 // use explicit type casts here to avoid import() calls in rolled-up d.ts
10002 const render = ((...args) => {
10003 ensureRenderer().render(...args);
10004 });
10005 const hydrate = ((...args) => {
10006 ensureHydrationRenderer().hydrate(...args);
10007 });
10008 const createApp = ((...args) => {
10009 const app = ensureRenderer().createApp(...args);
10010 {
10011 injectNativeTagCheck(app);
10012 injectCompilerOptionsCheck(app);
10013 }
10014 const { mount } = app;
10015 app.mount = (containerOrSelector) => {
10016 const container = normalizeContainer(containerOrSelector);
10017 if (!container)
10018 return;
10019 const component = app._component;
10020 if (!isFunction(component) && !component.render && !component.template) {
10021 // __UNSAFE__
10022 // Reason: potential execution of JS expressions in in-DOM template.
10023 // The user must make sure the in-DOM template is trusted. If it's
10024 // rendered by the server, the template should not contain any user data.
10025 component.template = container.innerHTML;
10026 }
10027 // clear content before mounting
10028 container.innerHTML = '';
10029 const proxy = mount(container, false, container instanceof SVGElement);
10030 if (container instanceof Element) {
10031 container.removeAttribute('v-cloak');
10032 container.setAttribute('data-v-app', '');
10033 }
10034 return proxy;
10035 };
10036 return app;
10037 });
10038 const createSSRApp = ((...args) => {
10039 const app = ensureHydrationRenderer().createApp(...args);
10040 {
10041 injectNativeTagCheck(app);
10042 injectCompilerOptionsCheck(app);
10043 }
10044 const { mount } = app;
10045 app.mount = (containerOrSelector) => {
10046 const container = normalizeContainer(containerOrSelector);
10047 if (container) {
10048 return mount(container, true, container instanceof SVGElement);
10049 }
10050 };
10051 return app;
10052 });
10053 function injectNativeTagCheck(app) {
10054 // Inject `isNativeTag`
10055 // this is used for component name validation (dev only)
10056 Object.defineProperty(app.config, 'isNativeTag', {
10057 value: (tag) => isHTMLTag(tag) || isSVGTag(tag),
10058 writable: false
10059 });
10060 }
10061 // dev only
10062 function injectCompilerOptionsCheck(app) {
10063 if (isRuntimeOnly()) {
10064 const isCustomElement = app.config.isCustomElement;
10065 Object.defineProperty(app.config, 'isCustomElement', {
10066 get() {
10067 return isCustomElement;
10068 },
10069 set() {
10070 warn(`The \`isCustomElement\` config option is deprecated. Use ` +
10071 `\`compilerOptions.isCustomElement\` instead.`);
10072 }
10073 });
10074 const compilerOptions = app.config.compilerOptions;
10075 const msg = `The \`compilerOptions\` config option is only respected when using ` +
10076 `a build of Vue.js that includes the runtime compiler (aka "full build"). ` +
10077 `Since you are using the runtime-only build, \`compilerOptions\` ` +
10078 `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` +
10079 `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` +
10080 `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` +
10081 `- For vite: pass it via @vitejs/plugin-vue options. See https://github.com/vitejs/vite/tree/main/packages/plugin-vue#example-for-passing-options-to-vuecompiler-dom`;
10082 Object.defineProperty(app.config, 'compilerOptions', {
10083 get() {
10084 warn(msg);
10085 return compilerOptions;
10086 },
10087 set() {
10088 warn(msg);
10089 }
10090 });
10091 }
10092 }
10093 function normalizeContainer(container) {
10094 if (isString(container)) {
10095 const res = document.querySelector(container);
10096 if (!res) {
10097 warn(`Failed to mount app: mount target selector "${container}" returned null.`);
10098 }
10099 return res;
10100 }
10101 if (container instanceof window.ShadowRoot &&
10102 container.mode === 'closed') {
10103 warn(`mounting on a ShadowRoot with \`{mode: "closed"}\` may lead to unpredictable bugs`);
10104 }
10105 return container;
10106 }
10107
10108 function initDev() {
10109 {
10110 {
10111 console.info(`You are running a development build of Vue.\n` +
10112 `Make sure to use the production build (*.prod.js) when deploying for production.`);
10113 }
10114 initCustomFormatter();
10115 }
10116 }
10117
10118 function defaultOnError(error) {
10119 throw error;
10120 }
10121 function defaultOnWarn(msg) {
10122 console.warn(`[Vue warn] ${msg.message}`);
10123 }
10124 function createCompilerError(code, loc, messages, additionalMessage) {
10125 const msg = (messages || errorMessages)[code] + (additionalMessage || ``)
10126 ;
10127 const error = new SyntaxError(String(msg));
10128 error.code = code;
10129 error.loc = loc;
10130 return error;
10131 }
10132 const errorMessages = {
10133 // parse errors
10134 [0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */]: 'Illegal comment.',
10135 [1 /* CDATA_IN_HTML_CONTENT */]: 'CDATA section is allowed only in XML context.',
10136 [2 /* DUPLICATE_ATTRIBUTE */]: 'Duplicate attribute.',
10137 [3 /* END_TAG_WITH_ATTRIBUTES */]: 'End tag cannot have attributes.',
10138 [4 /* END_TAG_WITH_TRAILING_SOLIDUS */]: "Illegal '/' in tags.",
10139 [5 /* EOF_BEFORE_TAG_NAME */]: 'Unexpected EOF in tag.',
10140 [6 /* EOF_IN_CDATA */]: 'Unexpected EOF in CDATA section.',
10141 [7 /* EOF_IN_COMMENT */]: 'Unexpected EOF in comment.',
10142 [8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */]: 'Unexpected EOF in script.',
10143 [9 /* EOF_IN_TAG */]: 'Unexpected EOF in tag.',
10144 [10 /* INCORRECTLY_CLOSED_COMMENT */]: 'Incorrectly closed comment.',
10145 [11 /* INCORRECTLY_OPENED_COMMENT */]: 'Incorrectly opened comment.',
10146 [12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */]: "Illegal tag name. Use '&lt;' to print '<'.",
10147 [13 /* MISSING_ATTRIBUTE_VALUE */]: 'Attribute value was expected.',
10148 [14 /* MISSING_END_TAG_NAME */]: 'End tag name was expected.',
10149 [15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */]: 'Whitespace was expected.',
10150 [16 /* NESTED_COMMENT */]: "Unexpected '<!--' in comment.",
10151 [17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */]: 'Attribute name cannot contain U+0022 ("), U+0027 (\'), and U+003C (<).',
10152 [18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */]: 'Unquoted attribute value cannot contain U+0022 ("), U+0027 (\'), U+003C (<), U+003D (=), and U+0060 (`).',
10153 [19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */]: "Attribute name cannot start with '='.",
10154 [21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */]: "'<?' is allowed only in XML context.",
10155 [20 /* UNEXPECTED_NULL_CHARACTER */]: `Unexpected null cahracter.`,
10156 [22 /* UNEXPECTED_SOLIDUS_IN_TAG */]: "Illegal '/' in tags.",
10157 // Vue-specific parse errors
10158 [23 /* X_INVALID_END_TAG */]: 'Invalid end tag.',
10159 [24 /* X_MISSING_END_TAG */]: 'Element is missing end tag.',
10160 [25 /* X_MISSING_INTERPOLATION_END */]: 'Interpolation end sign was not found.',
10161 [26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */]: 'End bracket for dynamic directive argument was not found. ' +
10162 'Note that dynamic directive argument cannot contain spaces.',
10163 // transform errors
10164 [27 /* X_V_IF_NO_EXPRESSION */]: `v-if/v-else-if is missing expression.`,
10165 [28 /* X_V_IF_SAME_KEY */]: `v-if/else branches must use unique keys.`,
10166 [29 /* X_V_ELSE_NO_ADJACENT_IF */]: `v-else/v-else-if has no adjacent v-if.`,
10167 [30 /* X_V_FOR_NO_EXPRESSION */]: `v-for is missing expression.`,
10168 [31 /* X_V_FOR_MALFORMED_EXPRESSION */]: `v-for has invalid expression.`,
10169 [32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */]: `<template v-for> key should be placed on the <template> tag.`,
10170 [33 /* X_V_BIND_NO_EXPRESSION */]: `v-bind is missing expression.`,
10171 [34 /* X_V_ON_NO_EXPRESSION */]: `v-on is missing expression.`,
10172 [35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */]: `Unexpected custom directive on <slot> outlet.`,
10173 [36 /* X_V_SLOT_MIXED_SLOT_USAGE */]: `Mixed v-slot usage on both the component and nested <template>.` +
10174 `When there are multiple named slots, all slots should use <template> ` +
10175 `syntax to avoid scope ambiguity.`,
10176 [37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */]: `Duplicate slot names found. `,
10177 [38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */]: `Extraneous children found when component already has explicitly named ` +
10178 `default slot. These children will be ignored.`,
10179 [39 /* X_V_SLOT_MISPLACED */]: `v-slot can only be used on components or <template> tags.`,
10180 [40 /* X_V_MODEL_NO_EXPRESSION */]: `v-model is missing expression.`,
10181 [41 /* X_V_MODEL_MALFORMED_EXPRESSION */]: `v-model value must be a valid JavaScript member expression.`,
10182 [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.`,
10183 [43 /* X_INVALID_EXPRESSION */]: `Error parsing JavaScript expression: `,
10184 [44 /* X_KEEP_ALIVE_INVALID_CHILDREN */]: `<KeepAlive> expects exactly one child component.`,
10185 // generic errors
10186 [45 /* X_PREFIX_ID_NOT_SUPPORTED */]: `"prefixIdentifiers" option is not supported in this build of compiler.`,
10187 [46 /* X_MODULE_MODE_NOT_SUPPORTED */]: `ES module mode is not supported in this build of compiler.`,
10188 [47 /* X_CACHE_HANDLER_NOT_SUPPORTED */]: `"cacheHandlers" option is only supported when the "prefixIdentifiers" option is enabled.`,
10189 [48 /* X_SCOPE_ID_NOT_SUPPORTED */]: `"scopeId" option is only supported in module mode.`,
10190 // just to fullfill types
10191 [49 /* __EXTEND_POINT__ */]: ``
10192 };
10193
10194 const FRAGMENT = Symbol(`Fragment` );
10195 const TELEPORT = Symbol(`Teleport` );
10196 const SUSPENSE = Symbol(`Suspense` );
10197 const KEEP_ALIVE = Symbol(`KeepAlive` );
10198 const BASE_TRANSITION = Symbol(`BaseTransition` );
10199 const OPEN_BLOCK = Symbol(`openBlock` );
10200 const CREATE_BLOCK = Symbol(`createBlock` );
10201 const CREATE_VNODE = Symbol(`createVNode` );
10202 const CREATE_COMMENT = Symbol(`createCommentVNode` );
10203 const CREATE_TEXT = Symbol(`createTextVNode` );
10204 const CREATE_STATIC = Symbol(`createStaticVNode` );
10205 const RESOLVE_COMPONENT = Symbol(`resolveComponent` );
10206 const RESOLVE_DYNAMIC_COMPONENT = Symbol(`resolveDynamicComponent` );
10207 const RESOLVE_DIRECTIVE = Symbol(`resolveDirective` );
10208 const RESOLVE_FILTER = Symbol(`resolveFilter` );
10209 const WITH_DIRECTIVES = Symbol(`withDirectives` );
10210 const RENDER_LIST = Symbol(`renderList` );
10211 const RENDER_SLOT = Symbol(`renderSlot` );
10212 const CREATE_SLOTS = Symbol(`createSlots` );
10213 const TO_DISPLAY_STRING = Symbol(`toDisplayString` );
10214 const MERGE_PROPS = Symbol(`mergeProps` );
10215 const TO_HANDLERS = Symbol(`toHandlers` );
10216 const CAMELIZE = Symbol(`camelize` );
10217 const CAPITALIZE = Symbol(`capitalize` );
10218 const TO_HANDLER_KEY = Symbol(`toHandlerKey` );
10219 const SET_BLOCK_TRACKING = Symbol(`setBlockTracking` );
10220 const PUSH_SCOPE_ID = Symbol(`pushScopeId` );
10221 const POP_SCOPE_ID = Symbol(`popScopeId` );
10222 const WITH_SCOPE_ID = Symbol(`withScopeId` );
10223 const WITH_CTX = Symbol(`withCtx` );
10224 const UNREF = Symbol(`unref` );
10225 const IS_REF = Symbol(`isRef` );
10226 // Name mapping for runtime helpers that need to be imported from 'vue' in
10227 // generated code. Make sure these are correctly exported in the runtime!
10228 // Using `any` here because TS doesn't allow symbols as index type.
10229 const helperNameMap = {
10230 [FRAGMENT]: `Fragment`,
10231 [TELEPORT]: `Teleport`,
10232 [SUSPENSE]: `Suspense`,
10233 [KEEP_ALIVE]: `KeepAlive`,
10234 [BASE_TRANSITION]: `BaseTransition`,
10235 [OPEN_BLOCK]: `openBlock`,
10236 [CREATE_BLOCK]: `createBlock`,
10237 [CREATE_VNODE]: `createVNode`,
10238 [CREATE_COMMENT]: `createCommentVNode`,
10239 [CREATE_TEXT]: `createTextVNode`,
10240 [CREATE_STATIC]: `createStaticVNode`,
10241 [RESOLVE_COMPONENT]: `resolveComponent`,
10242 [RESOLVE_DYNAMIC_COMPONENT]: `resolveDynamicComponent`,
10243 [RESOLVE_DIRECTIVE]: `resolveDirective`,
10244 [RESOLVE_FILTER]: `resolveFilter`,
10245 [WITH_DIRECTIVES]: `withDirectives`,
10246 [RENDER_LIST]: `renderList`,
10247 [RENDER_SLOT]: `renderSlot`,
10248 [CREATE_SLOTS]: `createSlots`,
10249 [TO_DISPLAY_STRING]: `toDisplayString`,
10250 [MERGE_PROPS]: `mergeProps`,
10251 [TO_HANDLERS]: `toHandlers`,
10252 [CAMELIZE]: `camelize`,
10253 [CAPITALIZE]: `capitalize`,
10254 [TO_HANDLER_KEY]: `toHandlerKey`,
10255 [SET_BLOCK_TRACKING]: `setBlockTracking`,
10256 [PUSH_SCOPE_ID]: `pushScopeId`,
10257 [POP_SCOPE_ID]: `popScopeId`,
10258 [WITH_SCOPE_ID]: `withScopeId`,
10259 [WITH_CTX]: `withCtx`,
10260 [UNREF]: `unref`,
10261 [IS_REF]: `isRef`
10262 };
10263 function registerRuntimeHelpers(helpers) {
10264 Object.getOwnPropertySymbols(helpers).forEach(s => {
10265 helperNameMap[s] = helpers[s];
10266 });
10267 }
10268
10269 // AST Utilities ---------------------------------------------------------------
10270 // Some expressions, e.g. sequence and conditional expressions, are never
10271 // associated with template nodes, so their source locations are just a stub.
10272 // Container types like CompoundExpression also don't need a real location.
10273 const locStub = {
10274 source: '',
10275 start: { line: 1, column: 1, offset: 0 },
10276 end: { line: 1, column: 1, offset: 0 }
10277 };
10278 function createRoot(children, loc = locStub) {
10279 return {
10280 type: 0 /* ROOT */,
10281 children,
10282 helpers: [],
10283 components: [],
10284 directives: [],
10285 hoists: [],
10286 imports: [],
10287 cached: 0,
10288 temps: 0,
10289 codegenNode: undefined,
10290 loc
10291 };
10292 }
10293 function createVNodeCall(context, tag, props, children, patchFlag, dynamicProps, directives, isBlock = false, disableTracking = false, loc = locStub) {
10294 if (context) {
10295 if (isBlock) {
10296 context.helper(OPEN_BLOCK);
10297 context.helper(CREATE_BLOCK);
10298 }
10299 else {
10300 context.helper(CREATE_VNODE);
10301 }
10302 if (directives) {
10303 context.helper(WITH_DIRECTIVES);
10304 }
10305 }
10306 return {
10307 type: 13 /* VNODE_CALL */,
10308 tag,
10309 props,
10310 children,
10311 patchFlag,
10312 dynamicProps,
10313 directives,
10314 isBlock,
10315 disableTracking,
10316 loc
10317 };
10318 }
10319 function createArrayExpression(elements, loc = locStub) {
10320 return {
10321 type: 17 /* JS_ARRAY_EXPRESSION */,
10322 loc,
10323 elements
10324 };
10325 }
10326 function createObjectExpression(properties, loc = locStub) {
10327 return {
10328 type: 15 /* JS_OBJECT_EXPRESSION */,
10329 loc,
10330 properties
10331 };
10332 }
10333 function createObjectProperty(key, value) {
10334 return {
10335 type: 16 /* JS_PROPERTY */,
10336 loc: locStub,
10337 key: isString(key) ? createSimpleExpression(key, true) : key,
10338 value
10339 };
10340 }
10341 function createSimpleExpression(content, isStatic, loc = locStub, constType = 0 /* NOT_CONSTANT */) {
10342 return {
10343 type: 4 /* SIMPLE_EXPRESSION */,
10344 loc,
10345 content,
10346 isStatic,
10347 constType: isStatic ? 3 /* CAN_STRINGIFY */ : constType
10348 };
10349 }
10350 function createCompoundExpression(children, loc = locStub) {
10351 return {
10352 type: 8 /* COMPOUND_EXPRESSION */,
10353 loc,
10354 children
10355 };
10356 }
10357 function createCallExpression(callee, args = [], loc = locStub) {
10358 return {
10359 type: 14 /* JS_CALL_EXPRESSION */,
10360 loc,
10361 callee,
10362 arguments: args
10363 };
10364 }
10365 function createFunctionExpression(params, returns = undefined, newline = false, isSlot = false, loc = locStub) {
10366 return {
10367 type: 18 /* JS_FUNCTION_EXPRESSION */,
10368 params,
10369 returns,
10370 newline,
10371 isSlot,
10372 loc
10373 };
10374 }
10375 function createConditionalExpression(test, consequent, alternate, newline = true) {
10376 return {
10377 type: 19 /* JS_CONDITIONAL_EXPRESSION */,
10378 test,
10379 consequent,
10380 alternate,
10381 newline,
10382 loc: locStub
10383 };
10384 }
10385 function createCacheExpression(index, value, isVNode = false) {
10386 return {
10387 type: 20 /* JS_CACHE_EXPRESSION */,
10388 index,
10389 value,
10390 isVNode,
10391 loc: locStub
10392 };
10393 }
10394
10395 const isStaticExp = (p) => p.type === 4 /* SIMPLE_EXPRESSION */ && p.isStatic;
10396 const isBuiltInType = (tag, expected) => tag === expected || tag === hyphenate(expected);
10397 function isCoreComponent(tag) {
10398 if (isBuiltInType(tag, 'Teleport')) {
10399 return TELEPORT;
10400 }
10401 else if (isBuiltInType(tag, 'Suspense')) {
10402 return SUSPENSE;
10403 }
10404 else if (isBuiltInType(tag, 'KeepAlive')) {
10405 return KEEP_ALIVE;
10406 }
10407 else if (isBuiltInType(tag, 'BaseTransition')) {
10408 return BASE_TRANSITION;
10409 }
10410 }
10411 const nonIdentifierRE = /^\d|[^\$\w]/;
10412 const isSimpleIdentifier = (name) => !nonIdentifierRE.test(name);
10413 const memberExpRE = /^[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*(?:\s*\.\s*[A-Za-z_$\xA0-\uFFFF][\w$\xA0-\uFFFF]*|\[(.+)\])*$/;
10414 const isMemberExpression = (path) => {
10415 if (!path)
10416 return false;
10417 const matched = memberExpRE.exec(path.trim());
10418 if (!matched)
10419 return false;
10420 if (!matched[1])
10421 return true;
10422 if (!/[\[\]]/.test(matched[1]))
10423 return true;
10424 return isMemberExpression(matched[1].trim());
10425 };
10426 function getInnerRange(loc, offset, length) {
10427 const source = loc.source.substr(offset, length);
10428 const newLoc = {
10429 source,
10430 start: advancePositionWithClone(loc.start, loc.source, offset),
10431 end: loc.end
10432 };
10433 if (length != null) {
10434 newLoc.end = advancePositionWithClone(loc.start, loc.source, offset + length);
10435 }
10436 return newLoc;
10437 }
10438 function advancePositionWithClone(pos, source, numberOfCharacters = source.length) {
10439 return advancePositionWithMutation(extend({}, pos), source, numberOfCharacters);
10440 }
10441 // advance by mutation without cloning (for performance reasons), since this
10442 // gets called a lot in the parser
10443 function advancePositionWithMutation(pos, source, numberOfCharacters = source.length) {
10444 let linesCount = 0;
10445 let lastNewLinePos = -1;
10446 for (let i = 0; i < numberOfCharacters; i++) {
10447 if (source.charCodeAt(i) === 10 /* newline char code */) {
10448 linesCount++;
10449 lastNewLinePos = i;
10450 }
10451 }
10452 pos.offset += numberOfCharacters;
10453 pos.line += linesCount;
10454 pos.column =
10455 lastNewLinePos === -1
10456 ? pos.column + numberOfCharacters
10457 : numberOfCharacters - lastNewLinePos;
10458 return pos;
10459 }
10460 function assert(condition, msg) {
10461 /* istanbul ignore if */
10462 if (!condition) {
10463 throw new Error(msg || `unexpected compiler condition`);
10464 }
10465 }
10466 function findDir(node, name, allowEmpty = false) {
10467 for (let i = 0; i < node.props.length; i++) {
10468 const p = node.props[i];
10469 if (p.type === 7 /* DIRECTIVE */ &&
10470 (allowEmpty || p.exp) &&
10471 (isString(name) ? p.name === name : name.test(p.name))) {
10472 return p;
10473 }
10474 }
10475 }
10476 function findProp(node, name, dynamicOnly = false, allowEmpty = false) {
10477 for (let i = 0; i < node.props.length; i++) {
10478 const p = node.props[i];
10479 if (p.type === 6 /* ATTRIBUTE */) {
10480 if (dynamicOnly)
10481 continue;
10482 if (p.name === name && (p.value || allowEmpty)) {
10483 return p;
10484 }
10485 }
10486 else if (p.name === 'bind' &&
10487 (p.exp || allowEmpty) &&
10488 isBindKey(p.arg, name)) {
10489 return p;
10490 }
10491 }
10492 }
10493 function isBindKey(arg, name) {
10494 return !!(arg && isStaticExp(arg) && arg.content === name);
10495 }
10496 function hasDynamicKeyVBind(node) {
10497 return node.props.some(p => p.type === 7 /* DIRECTIVE */ &&
10498 p.name === 'bind' &&
10499 (!p.arg || // v-bind="obj"
10500 p.arg.type !== 4 /* SIMPLE_EXPRESSION */ || // v-bind:[_ctx.foo]
10501 !p.arg.isStatic) // v-bind:[foo]
10502 );
10503 }
10504 function isText(node) {
10505 return node.type === 5 /* INTERPOLATION */ || node.type === 2 /* TEXT */;
10506 }
10507 function isVSlot(p) {
10508 return p.type === 7 /* DIRECTIVE */ && p.name === 'slot';
10509 }
10510 function isTemplateNode(node) {
10511 return (node.type === 1 /* ELEMENT */ && node.tagType === 3 /* TEMPLATE */);
10512 }
10513 function isSlotOutlet(node) {
10514 return node.type === 1 /* ELEMENT */ && node.tagType === 2 /* SLOT */;
10515 }
10516 function injectProp(node, prop, context) {
10517 let propsWithInjection;
10518 const props = node.type === 13 /* VNODE_CALL */ ? node.props : node.arguments[2];
10519 if (props == null || isString(props)) {
10520 propsWithInjection = createObjectExpression([prop]);
10521 }
10522 else if (props.type === 14 /* JS_CALL_EXPRESSION */) {
10523 // merged props... add ours
10524 // only inject key to object literal if it's the first argument so that
10525 // if doesn't override user provided keys
10526 const first = props.arguments[0];
10527 if (!isString(first) && first.type === 15 /* JS_OBJECT_EXPRESSION */) {
10528 first.properties.unshift(prop);
10529 }
10530 else {
10531 if (props.callee === TO_HANDLERS) {
10532 // #2366
10533 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
10534 createObjectExpression([prop]),
10535 props
10536 ]);
10537 }
10538 else {
10539 props.arguments.unshift(createObjectExpression([prop]));
10540 }
10541 }
10542 !propsWithInjection && (propsWithInjection = props);
10543 }
10544 else if (props.type === 15 /* JS_OBJECT_EXPRESSION */) {
10545 let alreadyExists = false;
10546 // check existing key to avoid overriding user provided keys
10547 if (prop.key.type === 4 /* SIMPLE_EXPRESSION */) {
10548 const propKeyName = prop.key.content;
10549 alreadyExists = props.properties.some(p => p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
10550 p.key.content === propKeyName);
10551 }
10552 if (!alreadyExists) {
10553 props.properties.unshift(prop);
10554 }
10555 propsWithInjection = props;
10556 }
10557 else {
10558 // single v-bind with expression, return a merged replacement
10559 propsWithInjection = createCallExpression(context.helper(MERGE_PROPS), [
10560 createObjectExpression([prop]),
10561 props
10562 ]);
10563 }
10564 if (node.type === 13 /* VNODE_CALL */) {
10565 node.props = propsWithInjection;
10566 }
10567 else {
10568 node.arguments[2] = propsWithInjection;
10569 }
10570 }
10571 function toValidAssetId(name, type) {
10572 return `_${type}_${name.replace(/[^\w]/g, '_')}`;
10573 }
10574
10575 // The default decoder only provides escapes for characters reserved as part of
10576 // the template syntax, and is only used if the custom renderer did not provide
10577 // a platform-specific decoder.
10578 const decodeRE = /&(gt|lt|amp|apos|quot);/g;
10579 const decodeMap = {
10580 gt: '>',
10581 lt: '<',
10582 amp: '&',
10583 apos: "'",
10584 quot: '"'
10585 };
10586 const defaultParserOptions = {
10587 delimiters: [`{{`, `}}`],
10588 getNamespace: () => 0 /* HTML */,
10589 getTextMode: () => 0 /* DATA */,
10590 isVoidTag: NO,
10591 isPreTag: NO,
10592 isCustomElement: NO,
10593 decodeEntities: (rawText) => rawText.replace(decodeRE, (_, p1) => decodeMap[p1]),
10594 onError: defaultOnError,
10595 onWarn: defaultOnWarn,
10596 comments: false
10597 };
10598 function baseParse(content, options = {}) {
10599 const context = createParserContext(content, options);
10600 const start = getCursor(context);
10601 return createRoot(parseChildren(context, 0 /* DATA */, []), getSelection(context, start));
10602 }
10603 function createParserContext(content, rawOptions) {
10604 const options = extend({}, defaultParserOptions);
10605 for (const key in rawOptions) {
10606 // @ts-ignore
10607 options[key] = rawOptions[key] || defaultParserOptions[key];
10608 }
10609 return {
10610 options,
10611 column: 1,
10612 line: 1,
10613 offset: 0,
10614 originalSource: content,
10615 source: content,
10616 inPre: false,
10617 inVPre: false,
10618 onWarn: options.onWarn
10619 };
10620 }
10621 function parseChildren(context, mode, ancestors) {
10622 const parent = last(ancestors);
10623 const ns = parent ? parent.ns : 0 /* HTML */;
10624 const nodes = [];
10625 while (!isEnd(context, mode, ancestors)) {
10626 const s = context.source;
10627 let node = undefined;
10628 if (mode === 0 /* DATA */ || mode === 1 /* RCDATA */) {
10629 if (!context.inVPre && startsWith(s, context.options.delimiters[0])) {
10630 // '{{'
10631 node = parseInterpolation(context, mode);
10632 }
10633 else if (mode === 0 /* DATA */ && s[0] === '<') {
10634 // https://html.spec.whatwg.org/multipage/parsing.html#tag-open-state
10635 if (s.length === 1) {
10636 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 1);
10637 }
10638 else if (s[1] === '!') {
10639 // https://html.spec.whatwg.org/multipage/parsing.html#markup-declaration-open-state
10640 if (startsWith(s, '<!--')) {
10641 node = parseComment(context);
10642 }
10643 else if (startsWith(s, '<!DOCTYPE')) {
10644 // Ignore DOCTYPE by a limitation.
10645 node = parseBogusComment(context);
10646 }
10647 else if (startsWith(s, '<![CDATA[')) {
10648 if (ns !== 0 /* HTML */) {
10649 node = parseCDATA(context, ancestors);
10650 }
10651 else {
10652 emitError(context, 1 /* CDATA_IN_HTML_CONTENT */);
10653 node = parseBogusComment(context);
10654 }
10655 }
10656 else {
10657 emitError(context, 11 /* INCORRECTLY_OPENED_COMMENT */);
10658 node = parseBogusComment(context);
10659 }
10660 }
10661 else if (s[1] === '/') {
10662 // https://html.spec.whatwg.org/multipage/parsing.html#end-tag-open-state
10663 if (s.length === 2) {
10664 emitError(context, 5 /* EOF_BEFORE_TAG_NAME */, 2);
10665 }
10666 else if (s[2] === '>') {
10667 emitError(context, 14 /* MISSING_END_TAG_NAME */, 2);
10668 advanceBy(context, 3);
10669 continue;
10670 }
10671 else if (/[a-z]/i.test(s[2])) {
10672 emitError(context, 23 /* X_INVALID_END_TAG */);
10673 parseTag(context, 1 /* End */, parent);
10674 continue;
10675 }
10676 else {
10677 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 2);
10678 node = parseBogusComment(context);
10679 }
10680 }
10681 else if (/[a-z]/i.test(s[1])) {
10682 node = parseElement(context, ancestors);
10683 }
10684 else if (s[1] === '?') {
10685 emitError(context, 21 /* UNEXPECTED_QUESTION_MARK_INSTEAD_OF_TAG_NAME */, 1);
10686 node = parseBogusComment(context);
10687 }
10688 else {
10689 emitError(context, 12 /* INVALID_FIRST_CHARACTER_OF_TAG_NAME */, 1);
10690 }
10691 }
10692 }
10693 if (!node) {
10694 node = parseText(context, mode);
10695 }
10696 if (isArray(node)) {
10697 for (let i = 0; i < node.length; i++) {
10698 pushNode(nodes, node[i]);
10699 }
10700 }
10701 else {
10702 pushNode(nodes, node);
10703 }
10704 }
10705 // Whitespace handling strategy like v2
10706 let removedWhitespace = false;
10707 if (mode !== 2 /* RAWTEXT */ && mode !== 1 /* RCDATA */) {
10708 const preserve = context.options.whitespace === 'preserve';
10709 for (let i = 0; i < nodes.length; i++) {
10710 const node = nodes[i];
10711 if (!context.inPre && node.type === 2 /* TEXT */) {
10712 if (!/[^\t\r\n\f ]/.test(node.content)) {
10713 const prev = nodes[i - 1];
10714 const next = nodes[i + 1];
10715 // Remove if:
10716 // - the whitespace is the first or last node, or:
10717 // - (condense mode) the whitespace is adjacent to a comment, or:
10718 // - (condense mode) the whitespace is between two elements AND contains newline
10719 if (!prev ||
10720 !next ||
10721 (!preserve &&
10722 (prev.type === 3 /* COMMENT */ ||
10723 next.type === 3 /* COMMENT */ ||
10724 (prev.type === 1 /* ELEMENT */ &&
10725 next.type === 1 /* ELEMENT */ &&
10726 /[\r\n]/.test(node.content))))) {
10727 removedWhitespace = true;
10728 nodes[i] = null;
10729 }
10730 else {
10731 // Otherwise, the whitespace is condensed into a single space
10732 node.content = ' ';
10733 }
10734 }
10735 else if (!preserve) {
10736 // in condense mode, consecutive whitespaces in text are condensed
10737 // down to a single space.
10738 node.content = node.content.replace(/[\t\r\n\f ]+/g, ' ');
10739 }
10740 }
10741 }
10742 if (context.inPre && parent && context.options.isPreTag(parent.tag)) {
10743 // remove leading newline per html spec
10744 // https://html.spec.whatwg.org/multipage/grouping-content.html#the-pre-element
10745 const first = nodes[0];
10746 if (first && first.type === 2 /* TEXT */) {
10747 first.content = first.content.replace(/^\r?\n/, '');
10748 }
10749 }
10750 }
10751 return removedWhitespace ? nodes.filter(Boolean) : nodes;
10752 }
10753 function pushNode(nodes, node) {
10754 if (node.type === 2 /* TEXT */) {
10755 const prev = last(nodes);
10756 // Merge if both this and the previous node are text and those are
10757 // consecutive. This happens for cases like "a < b".
10758 if (prev &&
10759 prev.type === 2 /* TEXT */ &&
10760 prev.loc.end.offset === node.loc.start.offset) {
10761 prev.content += node.content;
10762 prev.loc.end = node.loc.end;
10763 prev.loc.source += node.loc.source;
10764 return;
10765 }
10766 }
10767 nodes.push(node);
10768 }
10769 function parseCDATA(context, ancestors) {
10770 advanceBy(context, 9);
10771 const nodes = parseChildren(context, 3 /* CDATA */, ancestors);
10772 if (context.source.length === 0) {
10773 emitError(context, 6 /* EOF_IN_CDATA */);
10774 }
10775 else {
10776 advanceBy(context, 3);
10777 }
10778 return nodes;
10779 }
10780 function parseComment(context) {
10781 const start = getCursor(context);
10782 let content;
10783 // Regular comment.
10784 const match = /--(\!)?>/.exec(context.source);
10785 if (!match) {
10786 content = context.source.slice(4);
10787 advanceBy(context, context.source.length);
10788 emitError(context, 7 /* EOF_IN_COMMENT */);
10789 }
10790 else {
10791 if (match.index <= 3) {
10792 emitError(context, 0 /* ABRUPT_CLOSING_OF_EMPTY_COMMENT */);
10793 }
10794 if (match[1]) {
10795 emitError(context, 10 /* INCORRECTLY_CLOSED_COMMENT */);
10796 }
10797 content = context.source.slice(4, match.index);
10798 // Advancing with reporting nested comments.
10799 const s = context.source.slice(0, match.index);
10800 let prevIndex = 1, nestedIndex = 0;
10801 while ((nestedIndex = s.indexOf('<!--', prevIndex)) !== -1) {
10802 advanceBy(context, nestedIndex - prevIndex + 1);
10803 if (nestedIndex + 4 < s.length) {
10804 emitError(context, 16 /* NESTED_COMMENT */);
10805 }
10806 prevIndex = nestedIndex + 1;
10807 }
10808 advanceBy(context, match.index + match[0].length - prevIndex + 1);
10809 }
10810 return {
10811 type: 3 /* COMMENT */,
10812 content,
10813 loc: getSelection(context, start)
10814 };
10815 }
10816 function parseBogusComment(context) {
10817 const start = getCursor(context);
10818 const contentStart = context.source[1] === '?' ? 1 : 2;
10819 let content;
10820 const closeIndex = context.source.indexOf('>');
10821 if (closeIndex === -1) {
10822 content = context.source.slice(contentStart);
10823 advanceBy(context, context.source.length);
10824 }
10825 else {
10826 content = context.source.slice(contentStart, closeIndex);
10827 advanceBy(context, closeIndex + 1);
10828 }
10829 return {
10830 type: 3 /* COMMENT */,
10831 content,
10832 loc: getSelection(context, start)
10833 };
10834 }
10835 function parseElement(context, ancestors) {
10836 // Start tag.
10837 const wasInPre = context.inPre;
10838 const wasInVPre = context.inVPre;
10839 const parent = last(ancestors);
10840 const element = parseTag(context, 0 /* Start */, parent);
10841 const isPreBoundary = context.inPre && !wasInPre;
10842 const isVPreBoundary = context.inVPre && !wasInVPre;
10843 if (element.isSelfClosing || context.options.isVoidTag(element.tag)) {
10844 return element;
10845 }
10846 // Children.
10847 ancestors.push(element);
10848 const mode = context.options.getTextMode(element, parent);
10849 const children = parseChildren(context, mode, ancestors);
10850 ancestors.pop();
10851 element.children = children;
10852 // End tag.
10853 if (startsWithEndTagOpen(context.source, element.tag)) {
10854 parseTag(context, 1 /* End */, parent);
10855 }
10856 else {
10857 emitError(context, 24 /* X_MISSING_END_TAG */, 0, element.loc.start);
10858 if (context.source.length === 0 && element.tag.toLowerCase() === 'script') {
10859 const first = children[0];
10860 if (first && startsWith(first.loc.source, '<!--')) {
10861 emitError(context, 8 /* EOF_IN_SCRIPT_HTML_COMMENT_LIKE_TEXT */);
10862 }
10863 }
10864 }
10865 element.loc = getSelection(context, element.loc.start);
10866 if (isPreBoundary) {
10867 context.inPre = false;
10868 }
10869 if (isVPreBoundary) {
10870 context.inVPre = false;
10871 }
10872 return element;
10873 }
10874 const isSpecialTemplateDirective = /*#__PURE__*/ makeMap(`if,else,else-if,for,slot`);
10875 function parseTag(context, type, parent) {
10876 // Tag open.
10877 const start = getCursor(context);
10878 const match = /^<\/?([a-z][^\t\r\n\f />]*)/i.exec(context.source);
10879 const tag = match[1];
10880 const ns = context.options.getNamespace(tag, parent);
10881 advanceBy(context, match[0].length);
10882 advanceSpaces(context);
10883 // save current state in case we need to re-parse attributes with v-pre
10884 const cursor = getCursor(context);
10885 const currentSource = context.source;
10886 // Attributes.
10887 let props = parseAttributes(context, type);
10888 // check <pre> tag
10889 if (context.options.isPreTag(tag)) {
10890 context.inPre = true;
10891 }
10892 // check v-pre
10893 if (type === 0 /* Start */ &&
10894 !context.inVPre &&
10895 props.some(p => p.type === 7 /* DIRECTIVE */ && p.name === 'pre')) {
10896 context.inVPre = true;
10897 // reset context
10898 extend(context, cursor);
10899 context.source = currentSource;
10900 // re-parse attrs and filter out v-pre itself
10901 props = parseAttributes(context, type).filter(p => p.name !== 'v-pre');
10902 }
10903 // Tag close.
10904 let isSelfClosing = false;
10905 if (context.source.length === 0) {
10906 emitError(context, 9 /* EOF_IN_TAG */);
10907 }
10908 else {
10909 isSelfClosing = startsWith(context.source, '/>');
10910 if (type === 1 /* End */ && isSelfClosing) {
10911 emitError(context, 4 /* END_TAG_WITH_TRAILING_SOLIDUS */);
10912 }
10913 advanceBy(context, isSelfClosing ? 2 : 1);
10914 }
10915 if (type === 1 /* End */) {
10916 return;
10917 }
10918 let tagType = 0 /* ELEMENT */;
10919 const options = context.options;
10920 if (!context.inVPre && !options.isCustomElement(tag)) {
10921 const hasVIs = props.some(p => {
10922 if (p.name !== 'is')
10923 return;
10924 // v-is="xxx" (TODO: deprecate)
10925 if (p.type === 7 /* DIRECTIVE */) {
10926 return true;
10927 }
10928 // is="vue:xxx"
10929 if (p.value && p.value.content.startsWith('vue:')) {
10930 return true;
10931 }
10932 });
10933 if (options.isNativeTag && !hasVIs) {
10934 if (!options.isNativeTag(tag))
10935 tagType = 1 /* COMPONENT */;
10936 }
10937 else if (hasVIs ||
10938 isCoreComponent(tag) ||
10939 (options.isBuiltInComponent && options.isBuiltInComponent(tag)) ||
10940 /^[A-Z]/.test(tag) ||
10941 tag === 'component') {
10942 tagType = 1 /* COMPONENT */;
10943 }
10944 if (tag === 'slot') {
10945 tagType = 2 /* SLOT */;
10946 }
10947 else if (tag === 'template' &&
10948 props.some(p => p.type === 7 /* DIRECTIVE */ && isSpecialTemplateDirective(p.name))) {
10949 tagType = 3 /* TEMPLATE */;
10950 }
10951 }
10952 return {
10953 type: 1 /* ELEMENT */,
10954 ns,
10955 tag,
10956 tagType,
10957 props,
10958 isSelfClosing,
10959 children: [],
10960 loc: getSelection(context, start),
10961 codegenNode: undefined // to be created during transform phase
10962 };
10963 }
10964 function parseAttributes(context, type) {
10965 const props = [];
10966 const attributeNames = new Set();
10967 while (context.source.length > 0 &&
10968 !startsWith(context.source, '>') &&
10969 !startsWith(context.source, '/>')) {
10970 if (startsWith(context.source, '/')) {
10971 emitError(context, 22 /* UNEXPECTED_SOLIDUS_IN_TAG */);
10972 advanceBy(context, 1);
10973 advanceSpaces(context);
10974 continue;
10975 }
10976 if (type === 1 /* End */) {
10977 emitError(context, 3 /* END_TAG_WITH_ATTRIBUTES */);
10978 }
10979 const attr = parseAttribute(context, attributeNames);
10980 if (type === 0 /* Start */) {
10981 props.push(attr);
10982 }
10983 if (/^[^\t\r\n\f />]/.test(context.source)) {
10984 emitError(context, 15 /* MISSING_WHITESPACE_BETWEEN_ATTRIBUTES */);
10985 }
10986 advanceSpaces(context);
10987 }
10988 return props;
10989 }
10990 function parseAttribute(context, nameSet) {
10991 // Name.
10992 const start = getCursor(context);
10993 const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source);
10994 const name = match[0];
10995 if (nameSet.has(name)) {
10996 emitError(context, 2 /* DUPLICATE_ATTRIBUTE */);
10997 }
10998 nameSet.add(name);
10999 if (name[0] === '=') {
11000 emitError(context, 19 /* UNEXPECTED_EQUALS_SIGN_BEFORE_ATTRIBUTE_NAME */);
11001 }
11002 {
11003 const pattern = /["'<]/g;
11004 let m;
11005 while ((m = pattern.exec(name))) {
11006 emitError(context, 17 /* UNEXPECTED_CHARACTER_IN_ATTRIBUTE_NAME */, m.index);
11007 }
11008 }
11009 advanceBy(context, name.length);
11010 // Value
11011 let value = undefined;
11012 if (/^[\t\r\n\f ]*=/.test(context.source)) {
11013 advanceSpaces(context);
11014 advanceBy(context, 1);
11015 advanceSpaces(context);
11016 value = parseAttributeValue(context);
11017 if (!value) {
11018 emitError(context, 13 /* MISSING_ATTRIBUTE_VALUE */);
11019 }
11020 }
11021 const loc = getSelection(context, start);
11022 if (!context.inVPre && /^(v-|:|@|#)/.test(name)) {
11023 const match = /(?:^v-([a-z0-9-]+))?(?:(?::|^@|^#)(\[[^\]]+\]|[^\.]+))?(.+)?$/i.exec(name);
11024 let dirName = match[1] ||
11025 (startsWith(name, ':') ? 'bind' : startsWith(name, '@') ? 'on' : 'slot');
11026 let arg;
11027 if (match[2]) {
11028 const isSlot = dirName === 'slot';
11029 const startOffset = name.lastIndexOf(match[2]);
11030 const loc = getSelection(context, getNewPosition(context, start, startOffset), getNewPosition(context, start, startOffset + match[2].length + ((isSlot && match[3]) || '').length));
11031 let content = match[2];
11032 let isStatic = true;
11033 if (content.startsWith('[')) {
11034 isStatic = false;
11035 if (!content.endsWith(']')) {
11036 emitError(context, 26 /* X_MISSING_DYNAMIC_DIRECTIVE_ARGUMENT_END */);
11037 }
11038 content = content.substr(1, content.length - 2);
11039 }
11040 else if (isSlot) {
11041 // #1241 special case for v-slot: vuetify relies extensively on slot
11042 // names containing dots. v-slot doesn't have any modifiers and Vue 2.x
11043 // supports such usage so we are keeping it consistent with 2.x.
11044 content += match[3] || '';
11045 }
11046 arg = {
11047 type: 4 /* SIMPLE_EXPRESSION */,
11048 content,
11049 isStatic,
11050 constType: isStatic
11051 ? 3 /* CAN_STRINGIFY */
11052 : 0 /* NOT_CONSTANT */,
11053 loc
11054 };
11055 }
11056 if (value && value.isQuoted) {
11057 const valueLoc = value.loc;
11058 valueLoc.start.offset++;
11059 valueLoc.start.column++;
11060 valueLoc.end = advancePositionWithClone(valueLoc.start, value.content);
11061 valueLoc.source = valueLoc.source.slice(1, -1);
11062 }
11063 const modifiers = match[3] ? match[3].substr(1).split('.') : [];
11064 return {
11065 type: 7 /* DIRECTIVE */,
11066 name: dirName,
11067 exp: value && {
11068 type: 4 /* SIMPLE_EXPRESSION */,
11069 content: value.content,
11070 isStatic: false,
11071 // Treat as non-constant by default. This can be potentially set to
11072 // other values by `transformExpression` to make it eligible for hoisting.
11073 constType: 0 /* NOT_CONSTANT */,
11074 loc: value.loc
11075 },
11076 arg,
11077 modifiers,
11078 loc
11079 };
11080 }
11081 return {
11082 type: 6 /* ATTRIBUTE */,
11083 name,
11084 value: value && {
11085 type: 2 /* TEXT */,
11086 content: value.content,
11087 loc: value.loc
11088 },
11089 loc
11090 };
11091 }
11092 function parseAttributeValue(context) {
11093 const start = getCursor(context);
11094 let content;
11095 const quote = context.source[0];
11096 const isQuoted = quote === `"` || quote === `'`;
11097 if (isQuoted) {
11098 // Quoted value.
11099 advanceBy(context, 1);
11100 const endIndex = context.source.indexOf(quote);
11101 if (endIndex === -1) {
11102 content = parseTextData(context, context.source.length, 4 /* ATTRIBUTE_VALUE */);
11103 }
11104 else {
11105 content = parseTextData(context, endIndex, 4 /* ATTRIBUTE_VALUE */);
11106 advanceBy(context, 1);
11107 }
11108 }
11109 else {
11110 // Unquoted
11111 const match = /^[^\t\r\n\f >]+/.exec(context.source);
11112 if (!match) {
11113 return undefined;
11114 }
11115 const unexpectedChars = /["'<=`]/g;
11116 let m;
11117 while ((m = unexpectedChars.exec(match[0]))) {
11118 emitError(context, 18 /* UNEXPECTED_CHARACTER_IN_UNQUOTED_ATTRIBUTE_VALUE */, m.index);
11119 }
11120 content = parseTextData(context, match[0].length, 4 /* ATTRIBUTE_VALUE */);
11121 }
11122 return { content, isQuoted, loc: getSelection(context, start) };
11123 }
11124 function parseInterpolation(context, mode) {
11125 const [open, close] = context.options.delimiters;
11126 const closeIndex = context.source.indexOf(close, open.length);
11127 if (closeIndex === -1) {
11128 emitError(context, 25 /* X_MISSING_INTERPOLATION_END */);
11129 return undefined;
11130 }
11131 const start = getCursor(context);
11132 advanceBy(context, open.length);
11133 const innerStart = getCursor(context);
11134 const innerEnd = getCursor(context);
11135 const rawContentLength = closeIndex - open.length;
11136 const rawContent = context.source.slice(0, rawContentLength);
11137 const preTrimContent = parseTextData(context, rawContentLength, mode);
11138 const content = preTrimContent.trim();
11139 const startOffset = preTrimContent.indexOf(content);
11140 if (startOffset > 0) {
11141 advancePositionWithMutation(innerStart, rawContent, startOffset);
11142 }
11143 const endOffset = rawContentLength - (preTrimContent.length - content.length - startOffset);
11144 advancePositionWithMutation(innerEnd, rawContent, endOffset);
11145 advanceBy(context, close.length);
11146 return {
11147 type: 5 /* INTERPOLATION */,
11148 content: {
11149 type: 4 /* SIMPLE_EXPRESSION */,
11150 isStatic: false,
11151 // Set `isConstant` to false by default and will decide in transformExpression
11152 constType: 0 /* NOT_CONSTANT */,
11153 content,
11154 loc: getSelection(context, innerStart, innerEnd)
11155 },
11156 loc: getSelection(context, start)
11157 };
11158 }
11159 function parseText(context, mode) {
11160 const endTokens = ['<', context.options.delimiters[0]];
11161 if (mode === 3 /* CDATA */) {
11162 endTokens.push(']]>');
11163 }
11164 let endIndex = context.source.length;
11165 for (let i = 0; i < endTokens.length; i++) {
11166 const index = context.source.indexOf(endTokens[i], 1);
11167 if (index !== -1 && endIndex > index) {
11168 endIndex = index;
11169 }
11170 }
11171 const start = getCursor(context);
11172 const content = parseTextData(context, endIndex, mode);
11173 return {
11174 type: 2 /* TEXT */,
11175 content,
11176 loc: getSelection(context, start)
11177 };
11178 }
11179 /**
11180 * Get text data with a given length from the current location.
11181 * This translates HTML entities in the text data.
11182 */
11183 function parseTextData(context, length, mode) {
11184 const rawText = context.source.slice(0, length);
11185 advanceBy(context, length);
11186 if (mode === 2 /* RAWTEXT */ ||
11187 mode === 3 /* CDATA */ ||
11188 rawText.indexOf('&') === -1) {
11189 return rawText;
11190 }
11191 else {
11192 // DATA or RCDATA containing "&"". Entity decoding required.
11193 return context.options.decodeEntities(rawText, mode === 4 /* ATTRIBUTE_VALUE */);
11194 }
11195 }
11196 function getCursor(context) {
11197 const { column, line, offset } = context;
11198 return { column, line, offset };
11199 }
11200 function getSelection(context, start, end) {
11201 end = end || getCursor(context);
11202 return {
11203 start,
11204 end,
11205 source: context.originalSource.slice(start.offset, end.offset)
11206 };
11207 }
11208 function last(xs) {
11209 return xs[xs.length - 1];
11210 }
11211 function startsWith(source, searchString) {
11212 return source.startsWith(searchString);
11213 }
11214 function advanceBy(context, numberOfCharacters) {
11215 const { source } = context;
11216 advancePositionWithMutation(context, source, numberOfCharacters);
11217 context.source = source.slice(numberOfCharacters);
11218 }
11219 function advanceSpaces(context) {
11220 const match = /^[\t\r\n\f ]+/.exec(context.source);
11221 if (match) {
11222 advanceBy(context, match[0].length);
11223 }
11224 }
11225 function getNewPosition(context, start, numberOfCharacters) {
11226 return advancePositionWithClone(start, context.originalSource.slice(start.offset, numberOfCharacters), numberOfCharacters);
11227 }
11228 function emitError(context, code, offset, loc = getCursor(context)) {
11229 if (offset) {
11230 loc.offset += offset;
11231 loc.column += offset;
11232 }
11233 context.options.onError(createCompilerError(code, {
11234 start: loc,
11235 end: loc,
11236 source: ''
11237 }));
11238 }
11239 function isEnd(context, mode, ancestors) {
11240 const s = context.source;
11241 switch (mode) {
11242 case 0 /* DATA */:
11243 if (startsWith(s, '</')) {
11244 // TODO: probably bad performance
11245 for (let i = ancestors.length - 1; i >= 0; --i) {
11246 if (startsWithEndTagOpen(s, ancestors[i].tag)) {
11247 return true;
11248 }
11249 }
11250 }
11251 break;
11252 case 1 /* RCDATA */:
11253 case 2 /* RAWTEXT */: {
11254 const parent = last(ancestors);
11255 if (parent && startsWithEndTagOpen(s, parent.tag)) {
11256 return true;
11257 }
11258 break;
11259 }
11260 case 3 /* CDATA */:
11261 if (startsWith(s, ']]>')) {
11262 return true;
11263 }
11264 break;
11265 }
11266 return !s;
11267 }
11268 function startsWithEndTagOpen(source, tag) {
11269 return (startsWith(source, '</') &&
11270 source.substr(2, tag.length).toLowerCase() === tag.toLowerCase() &&
11271 /[\t\r\n\f />]/.test(source[2 + tag.length] || '>'));
11272 }
11273
11274 function hoistStatic(root, context) {
11275 walk(root, context,
11276 // Root node is unfortunately non-hoistable due to potential parent
11277 // fallthrough attributes.
11278 isSingleElementRoot(root, root.children[0]));
11279 }
11280 function isSingleElementRoot(root, child) {
11281 const { children } = root;
11282 return (children.length === 1 &&
11283 child.type === 1 /* ELEMENT */ &&
11284 !isSlotOutlet(child));
11285 }
11286 function walk(node, context, doNotHoistNode = false) {
11287 let hasHoistedNode = false;
11288 // Some transforms, e.g. transformAssetUrls from @vue/compiler-sfc, replaces
11289 // static bindings with expressions. These expressions are guaranteed to be
11290 // constant so they are still eligible for hoisting, but they are only
11291 // available at runtime and therefore cannot be evaluated ahead of time.
11292 // This is only a concern for pre-stringification (via transformHoist by
11293 // @vue/compiler-dom), but doing it here allows us to perform only one full
11294 // walk of the AST and allow `stringifyStatic` to stop walking as soon as its
11295 // stringficiation threshold is met.
11296 let canStringify = true;
11297 const { children } = node;
11298 for (let i = 0; i < children.length; i++) {
11299 const child = children[i];
11300 // only plain elements & text calls are eligible for hoisting.
11301 if (child.type === 1 /* ELEMENT */ &&
11302 child.tagType === 0 /* ELEMENT */) {
11303 const constantType = doNotHoistNode
11304 ? 0 /* NOT_CONSTANT */
11305 : getConstantType(child, context);
11306 if (constantType > 0 /* NOT_CONSTANT */) {
11307 if (constantType < 3 /* CAN_STRINGIFY */) {
11308 canStringify = false;
11309 }
11310 if (constantType >= 2 /* CAN_HOIST */) {
11311 child.codegenNode.patchFlag =
11312 -1 /* HOISTED */ + (` /* HOISTED */` );
11313 child.codegenNode = context.hoist(child.codegenNode);
11314 hasHoistedNode = true;
11315 continue;
11316 }
11317 }
11318 else {
11319 // node may contain dynamic children, but its props may be eligible for
11320 // hoisting.
11321 const codegenNode = child.codegenNode;
11322 if (codegenNode.type === 13 /* VNODE_CALL */) {
11323 const flag = getPatchFlag(codegenNode);
11324 if ((!flag ||
11325 flag === 512 /* NEED_PATCH */ ||
11326 flag === 1 /* TEXT */) &&
11327 getGeneratedPropsConstantType(child, context) >=
11328 2 /* CAN_HOIST */) {
11329 const props = getNodeProps(child);
11330 if (props) {
11331 codegenNode.props = context.hoist(props);
11332 }
11333 }
11334 }
11335 }
11336 }
11337 else if (child.type === 12 /* TEXT_CALL */) {
11338 const contentType = getConstantType(child.content, context);
11339 if (contentType > 0) {
11340 if (contentType < 3 /* CAN_STRINGIFY */) {
11341 canStringify = false;
11342 }
11343 if (contentType >= 2 /* CAN_HOIST */) {
11344 child.codegenNode = context.hoist(child.codegenNode);
11345 hasHoistedNode = true;
11346 }
11347 }
11348 }
11349 // walk further
11350 if (child.type === 1 /* ELEMENT */) {
11351 const isComponent = child.tagType === 1 /* COMPONENT */;
11352 if (isComponent) {
11353 context.scopes.vSlot++;
11354 }
11355 walk(child, context);
11356 if (isComponent) {
11357 context.scopes.vSlot--;
11358 }
11359 }
11360 else if (child.type === 11 /* FOR */) {
11361 // Do not hoist v-for single child because it has to be a block
11362 walk(child, context, child.children.length === 1);
11363 }
11364 else if (child.type === 9 /* IF */) {
11365 for (let i = 0; i < child.branches.length; i++) {
11366 // Do not hoist v-if single child because it has to be a block
11367 walk(child.branches[i], context, child.branches[i].children.length === 1);
11368 }
11369 }
11370 }
11371 if (canStringify && hasHoistedNode && context.transformHoist) {
11372 context.transformHoist(children, context, node);
11373 }
11374 }
11375 function getConstantType(node, context) {
11376 const { constantCache } = context;
11377 switch (node.type) {
11378 case 1 /* ELEMENT */:
11379 if (node.tagType !== 0 /* ELEMENT */) {
11380 return 0 /* NOT_CONSTANT */;
11381 }
11382 const cached = constantCache.get(node);
11383 if (cached !== undefined) {
11384 return cached;
11385 }
11386 const codegenNode = node.codegenNode;
11387 if (codegenNode.type !== 13 /* VNODE_CALL */) {
11388 return 0 /* NOT_CONSTANT */;
11389 }
11390 const flag = getPatchFlag(codegenNode);
11391 if (!flag) {
11392 let returnType = 3 /* CAN_STRINGIFY */;
11393 // Element itself has no patch flag. However we still need to check:
11394 // 1. Even for a node with no patch flag, it is possible for it to contain
11395 // non-hoistable expressions that refers to scope variables, e.g. compiler
11396 // injected keys or cached event handlers. Therefore we need to always
11397 // check the codegenNode's props to be sure.
11398 const generatedPropsType = getGeneratedPropsConstantType(node, context);
11399 if (generatedPropsType === 0 /* NOT_CONSTANT */) {
11400 constantCache.set(node, 0 /* NOT_CONSTANT */);
11401 return 0 /* NOT_CONSTANT */;
11402 }
11403 if (generatedPropsType < returnType) {
11404 returnType = generatedPropsType;
11405 }
11406 // 2. its children.
11407 for (let i = 0; i < node.children.length; i++) {
11408 const childType = getConstantType(node.children[i], context);
11409 if (childType === 0 /* NOT_CONSTANT */) {
11410 constantCache.set(node, 0 /* NOT_CONSTANT */);
11411 return 0 /* NOT_CONSTANT */;
11412 }
11413 if (childType < returnType) {
11414 returnType = childType;
11415 }
11416 }
11417 // 3. if the type is not already CAN_SKIP_PATCH which is the lowest non-0
11418 // type, check if any of the props can cause the type to be lowered
11419 // we can skip can_patch because it's guaranteed by the absence of a
11420 // patchFlag.
11421 if (returnType > 1 /* CAN_SKIP_PATCH */) {
11422 for (let i = 0; i < node.props.length; i++) {
11423 const p = node.props[i];
11424 if (p.type === 7 /* DIRECTIVE */ && p.name === 'bind' && p.exp) {
11425 const expType = getConstantType(p.exp, context);
11426 if (expType === 0 /* NOT_CONSTANT */) {
11427 constantCache.set(node, 0 /* NOT_CONSTANT */);
11428 return 0 /* NOT_CONSTANT */;
11429 }
11430 if (expType < returnType) {
11431 returnType = expType;
11432 }
11433 }
11434 }
11435 }
11436 // only svg/foreignObject could be block here, however if they are
11437 // static then they don't need to be blocks since there will be no
11438 // nested updates.
11439 if (codegenNode.isBlock) {
11440 context.removeHelper(OPEN_BLOCK);
11441 context.removeHelper(CREATE_BLOCK);
11442 codegenNode.isBlock = false;
11443 context.helper(CREATE_VNODE);
11444 }
11445 constantCache.set(node, returnType);
11446 return returnType;
11447 }
11448 else {
11449 constantCache.set(node, 0 /* NOT_CONSTANT */);
11450 return 0 /* NOT_CONSTANT */;
11451 }
11452 case 2 /* TEXT */:
11453 case 3 /* COMMENT */:
11454 return 3 /* CAN_STRINGIFY */;
11455 case 9 /* IF */:
11456 case 11 /* FOR */:
11457 case 10 /* IF_BRANCH */:
11458 return 0 /* NOT_CONSTANT */;
11459 case 5 /* INTERPOLATION */:
11460 case 12 /* TEXT_CALL */:
11461 return getConstantType(node.content, context);
11462 case 4 /* SIMPLE_EXPRESSION */:
11463 return node.constType;
11464 case 8 /* COMPOUND_EXPRESSION */:
11465 let returnType = 3 /* CAN_STRINGIFY */;
11466 for (let i = 0; i < node.children.length; i++) {
11467 const child = node.children[i];
11468 if (isString(child) || isSymbol(child)) {
11469 continue;
11470 }
11471 const childType = getConstantType(child, context);
11472 if (childType === 0 /* NOT_CONSTANT */) {
11473 return 0 /* NOT_CONSTANT */;
11474 }
11475 else if (childType < returnType) {
11476 returnType = childType;
11477 }
11478 }
11479 return returnType;
11480 default:
11481 return 0 /* NOT_CONSTANT */;
11482 }
11483 }
11484 function getGeneratedPropsConstantType(node, context) {
11485 let returnType = 3 /* CAN_STRINGIFY */;
11486 const props = getNodeProps(node);
11487 if (props && props.type === 15 /* JS_OBJECT_EXPRESSION */) {
11488 const { properties } = props;
11489 for (let i = 0; i < properties.length; i++) {
11490 const { key, value } = properties[i];
11491 const keyType = getConstantType(key, context);
11492 if (keyType === 0 /* NOT_CONSTANT */) {
11493 return keyType;
11494 }
11495 if (keyType < returnType) {
11496 returnType = keyType;
11497 }
11498 if (value.type !== 4 /* SIMPLE_EXPRESSION */) {
11499 return 0 /* NOT_CONSTANT */;
11500 }
11501 const valueType = getConstantType(value, context);
11502 if (valueType === 0 /* NOT_CONSTANT */) {
11503 return valueType;
11504 }
11505 if (valueType < returnType) {
11506 returnType = valueType;
11507 }
11508 }
11509 }
11510 return returnType;
11511 }
11512 function getNodeProps(node) {
11513 const codegenNode = node.codegenNode;
11514 if (codegenNode.type === 13 /* VNODE_CALL */) {
11515 return codegenNode.props;
11516 }
11517 }
11518 function getPatchFlag(node) {
11519 const flag = node.patchFlag;
11520 return flag ? parseInt(flag, 10) : undefined;
11521 }
11522
11523 function createTransformContext(root, { filename = '', prefixIdentifiers = false, hoistStatic = false, cacheHandlers = false, nodeTransforms = [], directiveTransforms = {}, transformHoist = null, isBuiltInComponent = NOOP, isCustomElement = NOOP, expressionPlugins = [], scopeId = null, slotted = true, ssr = false, ssrCssVars = ``, bindingMetadata = EMPTY_OBJ, inline = false, isTS = false, onError = defaultOnError, onWarn = defaultOnWarn, compatConfig }) {
11524 const nameMatch = filename.replace(/\?.*$/, '').match(/([^/\\]+)\.\w+$/);
11525 const context = {
11526 // options
11527 selfName: nameMatch && capitalize(camelize(nameMatch[1])),
11528 prefixIdentifiers,
11529 hoistStatic,
11530 cacheHandlers,
11531 nodeTransforms,
11532 directiveTransforms,
11533 transformHoist,
11534 isBuiltInComponent,
11535 isCustomElement,
11536 expressionPlugins,
11537 scopeId,
11538 slotted,
11539 ssr,
11540 ssrCssVars,
11541 bindingMetadata,
11542 inline,
11543 isTS,
11544 onError,
11545 onWarn,
11546 compatConfig,
11547 // state
11548 root,
11549 helpers: new Map(),
11550 components: new Set(),
11551 directives: new Set(),
11552 hoists: [],
11553 imports: [],
11554 constantCache: new Map(),
11555 temps: 0,
11556 cached: 0,
11557 identifiers: Object.create(null),
11558 scopes: {
11559 vFor: 0,
11560 vSlot: 0,
11561 vPre: 0,
11562 vOnce: 0
11563 },
11564 parent: null,
11565 currentNode: root,
11566 childIndex: 0,
11567 // methods
11568 helper(name) {
11569 const count = context.helpers.get(name) || 0;
11570 context.helpers.set(name, count + 1);
11571 return name;
11572 },
11573 removeHelper(name) {
11574 const count = context.helpers.get(name);
11575 if (count) {
11576 const currentCount = count - 1;
11577 if (!currentCount) {
11578 context.helpers.delete(name);
11579 }
11580 else {
11581 context.helpers.set(name, currentCount);
11582 }
11583 }
11584 },
11585 helperString(name) {
11586 return `_${helperNameMap[context.helper(name)]}`;
11587 },
11588 replaceNode(node) {
11589 /* istanbul ignore if */
11590 {
11591 if (!context.currentNode) {
11592 throw new Error(`Node being replaced is already removed.`);
11593 }
11594 if (!context.parent) {
11595 throw new Error(`Cannot replace root node.`);
11596 }
11597 }
11598 context.parent.children[context.childIndex] = context.currentNode = node;
11599 },
11600 removeNode(node) {
11601 if (!context.parent) {
11602 throw new Error(`Cannot remove root node.`);
11603 }
11604 const list = context.parent.children;
11605 const removalIndex = node
11606 ? list.indexOf(node)
11607 : context.currentNode
11608 ? context.childIndex
11609 : -1;
11610 /* istanbul ignore if */
11611 if (removalIndex < 0) {
11612 throw new Error(`node being removed is not a child of current parent`);
11613 }
11614 if (!node || node === context.currentNode) {
11615 // current node removed
11616 context.currentNode = null;
11617 context.onNodeRemoved();
11618 }
11619 else {
11620 // sibling node removed
11621 if (context.childIndex > removalIndex) {
11622 context.childIndex--;
11623 context.onNodeRemoved();
11624 }
11625 }
11626 context.parent.children.splice(removalIndex, 1);
11627 },
11628 onNodeRemoved: () => { },
11629 addIdentifiers(exp) {
11630 },
11631 removeIdentifiers(exp) {
11632 },
11633 hoist(exp) {
11634 context.hoists.push(exp);
11635 const identifier = createSimpleExpression(`_hoisted_${context.hoists.length}`, false, exp.loc, 2 /* CAN_HOIST */);
11636 identifier.hoisted = exp;
11637 return identifier;
11638 },
11639 cache(exp, isVNode = false) {
11640 return createCacheExpression(++context.cached, exp, isVNode);
11641 }
11642 };
11643 return context;
11644 }
11645 function transform(root, options) {
11646 const context = createTransformContext(root, options);
11647 traverseNode(root, context);
11648 if (options.hoistStatic) {
11649 hoistStatic(root, context);
11650 }
11651 if (!options.ssr) {
11652 createRootCodegen(root, context);
11653 }
11654 // finalize meta information
11655 root.helpers = [...context.helpers.keys()];
11656 root.components = [...context.components];
11657 root.directives = [...context.directives];
11658 root.imports = context.imports;
11659 root.hoists = context.hoists;
11660 root.temps = context.temps;
11661 root.cached = context.cached;
11662 }
11663 function createRootCodegen(root, context) {
11664 const { helper, removeHelper } = context;
11665 const { children } = root;
11666 if (children.length === 1) {
11667 const child = children[0];
11668 // if the single child is an element, turn it into a block.
11669 if (isSingleElementRoot(root, child) && child.codegenNode) {
11670 // single element root is never hoisted so codegenNode will never be
11671 // SimpleExpressionNode
11672 const codegenNode = child.codegenNode;
11673 if (codegenNode.type === 13 /* VNODE_CALL */) {
11674 if (!codegenNode.isBlock) {
11675 removeHelper(CREATE_VNODE);
11676 codegenNode.isBlock = true;
11677 helper(OPEN_BLOCK);
11678 helper(CREATE_BLOCK);
11679 }
11680 }
11681 root.codegenNode = codegenNode;
11682 }
11683 else {
11684 // - single <slot/>, IfNode, ForNode: already blocks.
11685 // - single text node: always patched.
11686 // root codegen falls through via genNode()
11687 root.codegenNode = child;
11688 }
11689 }
11690 else if (children.length > 1) {
11691 // root has multiple nodes - return a fragment block.
11692 let patchFlag = 64 /* STABLE_FRAGMENT */;
11693 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
11694 // check if the fragment actually contains a single valid child with
11695 // the rest being comments
11696 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
11697 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
11698 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
11699 }
11700 root.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, root.children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true);
11701 }
11702 else ;
11703 }
11704 function traverseChildren(parent, context) {
11705 let i = 0;
11706 const nodeRemoved = () => {
11707 i--;
11708 };
11709 for (; i < parent.children.length; i++) {
11710 const child = parent.children[i];
11711 if (isString(child))
11712 continue;
11713 context.parent = parent;
11714 context.childIndex = i;
11715 context.onNodeRemoved = nodeRemoved;
11716 traverseNode(child, context);
11717 }
11718 }
11719 function traverseNode(node, context) {
11720 context.currentNode = node;
11721 // apply transform plugins
11722 const { nodeTransforms } = context;
11723 const exitFns = [];
11724 for (let i = 0; i < nodeTransforms.length; i++) {
11725 const onExit = nodeTransforms[i](node, context);
11726 if (onExit) {
11727 if (isArray(onExit)) {
11728 exitFns.push(...onExit);
11729 }
11730 else {
11731 exitFns.push(onExit);
11732 }
11733 }
11734 if (!context.currentNode) {
11735 // node was removed
11736 return;
11737 }
11738 else {
11739 // node may have been replaced
11740 node = context.currentNode;
11741 }
11742 }
11743 switch (node.type) {
11744 case 3 /* COMMENT */:
11745 if (!context.ssr) {
11746 // inject import for the Comment symbol, which is needed for creating
11747 // comment nodes with `createVNode`
11748 context.helper(CREATE_COMMENT);
11749 }
11750 break;
11751 case 5 /* INTERPOLATION */:
11752 // no need to traverse, but we need to inject toString helper
11753 if (!context.ssr) {
11754 context.helper(TO_DISPLAY_STRING);
11755 }
11756 break;
11757 // for container types, further traverse downwards
11758 case 9 /* IF */:
11759 for (let i = 0; i < node.branches.length; i++) {
11760 traverseNode(node.branches[i], context);
11761 }
11762 break;
11763 case 10 /* IF_BRANCH */:
11764 case 11 /* FOR */:
11765 case 1 /* ELEMENT */:
11766 case 0 /* ROOT */:
11767 traverseChildren(node, context);
11768 break;
11769 }
11770 // exit transforms
11771 context.currentNode = node;
11772 let i = exitFns.length;
11773 while (i--) {
11774 exitFns[i]();
11775 }
11776 }
11777 function createStructuralDirectiveTransform(name, fn) {
11778 const matches = isString(name)
11779 ? (n) => n === name
11780 : (n) => name.test(n);
11781 return (node, context) => {
11782 if (node.type === 1 /* ELEMENT */) {
11783 const { props } = node;
11784 // structural directive transforms are not concerned with slots
11785 // as they are handled separately in vSlot.ts
11786 if (node.tagType === 3 /* TEMPLATE */ && props.some(isVSlot)) {
11787 return;
11788 }
11789 const exitFns = [];
11790 for (let i = 0; i < props.length; i++) {
11791 const prop = props[i];
11792 if (prop.type === 7 /* DIRECTIVE */ && matches(prop.name)) {
11793 // structural directives are removed to avoid infinite recursion
11794 // also we remove them *before* applying so that it can further
11795 // traverse itself in case it moves the node around
11796 props.splice(i, 1);
11797 i--;
11798 const onExit = fn(node, prop, context);
11799 if (onExit)
11800 exitFns.push(onExit);
11801 }
11802 }
11803 return exitFns;
11804 }
11805 };
11806 }
11807
11808 const PURE_ANNOTATION = `/*#__PURE__*/`;
11809 function createCodegenContext(ast, { mode = 'function', prefixIdentifiers = mode === 'module', sourceMap = false, filename = `template.vue.html`, scopeId = null, optimizeImports = false, runtimeGlobalName = `Vue`, runtimeModuleName = `vue`, ssr = false }) {
11810 const context = {
11811 mode,
11812 prefixIdentifiers,
11813 sourceMap,
11814 filename,
11815 scopeId,
11816 optimizeImports,
11817 runtimeGlobalName,
11818 runtimeModuleName,
11819 ssr,
11820 source: ast.loc.source,
11821 code: ``,
11822 column: 1,
11823 line: 1,
11824 offset: 0,
11825 indentLevel: 0,
11826 pure: false,
11827 map: undefined,
11828 helper(key) {
11829 return `_${helperNameMap[key]}`;
11830 },
11831 push(code, node) {
11832 context.code += code;
11833 },
11834 indent() {
11835 newline(++context.indentLevel);
11836 },
11837 deindent(withoutNewLine = false) {
11838 if (withoutNewLine) {
11839 --context.indentLevel;
11840 }
11841 else {
11842 newline(--context.indentLevel);
11843 }
11844 },
11845 newline() {
11846 newline(context.indentLevel);
11847 }
11848 };
11849 function newline(n) {
11850 context.push('\n' + ` `.repeat(n));
11851 }
11852 return context;
11853 }
11854 function generate(ast, options = {}) {
11855 const context = createCodegenContext(ast, options);
11856 if (options.onContextCreated)
11857 options.onContextCreated(context);
11858 const { mode, push, prefixIdentifiers, indent, deindent, newline, scopeId, ssr } = context;
11859 const hasHelpers = ast.helpers.length > 0;
11860 const useWithBlock = !prefixIdentifiers && mode !== 'module';
11861 // preambles
11862 // in setup() inline mode, the preamble is generated in a sub context
11863 // and returned separately.
11864 const preambleContext = context;
11865 {
11866 genFunctionPreamble(ast, preambleContext);
11867 }
11868 // enter render function
11869 const functionName = ssr ? `ssrRender` : `render`;
11870 const args = ssr ? ['_ctx', '_push', '_parent', '_attrs'] : ['_ctx', '_cache'];
11871 const signature = args.join(', ');
11872 {
11873 push(`function ${functionName}(${signature}) {`);
11874 }
11875 indent();
11876 if (useWithBlock) {
11877 push(`with (_ctx) {`);
11878 indent();
11879 // function mode const declarations should be inside with block
11880 // also they should be renamed to avoid collision with user properties
11881 if (hasHelpers) {
11882 push(`const { ${ast.helpers
11883 .map(s => `${helperNameMap[s]}: _${helperNameMap[s]}`)
11884 .join(', ')} } = _Vue`);
11885 push(`\n`);
11886 newline();
11887 }
11888 }
11889 // generate asset resolution statements
11890 if (ast.components.length) {
11891 genAssets(ast.components, 'component', context);
11892 if (ast.directives.length || ast.temps > 0) {
11893 newline();
11894 }
11895 }
11896 if (ast.directives.length) {
11897 genAssets(ast.directives, 'directive', context);
11898 if (ast.temps > 0) {
11899 newline();
11900 }
11901 }
11902 if (ast.temps > 0) {
11903 push(`let `);
11904 for (let i = 0; i < ast.temps; i++) {
11905 push(`${i > 0 ? `, ` : ``}_temp${i}`);
11906 }
11907 }
11908 if (ast.components.length || ast.directives.length || ast.temps) {
11909 push(`\n`);
11910 newline();
11911 }
11912 // generate the VNode tree expression
11913 if (!ssr) {
11914 push(`return `);
11915 }
11916 if (ast.codegenNode) {
11917 genNode(ast.codegenNode, context);
11918 }
11919 else {
11920 push(`null`);
11921 }
11922 if (useWithBlock) {
11923 deindent();
11924 push(`}`);
11925 }
11926 deindent();
11927 push(`}`);
11928 return {
11929 ast,
11930 code: context.code,
11931 preamble: ``,
11932 // SourceMapGenerator does have toJSON() method but it's not in the types
11933 map: context.map ? context.map.toJSON() : undefined
11934 };
11935 }
11936 function genFunctionPreamble(ast, context) {
11937 const { ssr, prefixIdentifiers, push, newline, runtimeModuleName, runtimeGlobalName } = context;
11938 const VueBinding = runtimeGlobalName;
11939 const aliasHelper = (s) => `${helperNameMap[s]}: _${helperNameMap[s]}`;
11940 // Generate const declaration for helpers
11941 // In prefix mode, we place the const declaration at top so it's done
11942 // only once; But if we not prefixing, we place the declaration inside the
11943 // with block so it doesn't incur the `in` check cost for every helper access.
11944 if (ast.helpers.length > 0) {
11945 {
11946 // "with" mode.
11947 // save Vue in a separate variable to avoid collision
11948 push(`const _Vue = ${VueBinding}\n`);
11949 // in "with" mode, helpers are declared inside the with block to avoid
11950 // has check cost, but hoists are lifted out of the function - we need
11951 // to provide the helper here.
11952 if (ast.hoists.length) {
11953 const staticHelpers = [
11954 CREATE_VNODE,
11955 CREATE_COMMENT,
11956 CREATE_TEXT,
11957 CREATE_STATIC
11958 ]
11959 .filter(helper => ast.helpers.includes(helper))
11960 .map(aliasHelper)
11961 .join(', ');
11962 push(`const { ${staticHelpers} } = _Vue\n`);
11963 }
11964 }
11965 }
11966 genHoists(ast.hoists, context);
11967 newline();
11968 push(`return `);
11969 }
11970 function genAssets(assets, type, { helper, push, newline }) {
11971 const resolver = helper(type === 'component'
11972 ? RESOLVE_COMPONENT
11973 : RESOLVE_DIRECTIVE);
11974 for (let i = 0; i < assets.length; i++) {
11975 let id = assets[i];
11976 // potential component implicit self-reference inferred from SFC filename
11977 const maybeSelfReference = id.endsWith('__self');
11978 if (maybeSelfReference) {
11979 id = id.slice(0, -6);
11980 }
11981 push(`const ${toValidAssetId(id, type)} = ${resolver}(${JSON.stringify(id)}${maybeSelfReference ? `, true` : ``})`);
11982 if (i < assets.length - 1) {
11983 newline();
11984 }
11985 }
11986 }
11987 function genHoists(hoists, context) {
11988 if (!hoists.length) {
11989 return;
11990 }
11991 context.pure = true;
11992 const { push, newline, helper, scopeId, mode } = context;
11993 newline();
11994 hoists.forEach((exp, i) => {
11995 if (exp) {
11996 push(`const _hoisted_${i + 1} = `);
11997 genNode(exp, context);
11998 newline();
11999 }
12000 });
12001 context.pure = false;
12002 }
12003 function isText$1(n) {
12004 return (isString(n) ||
12005 n.type === 4 /* SIMPLE_EXPRESSION */ ||
12006 n.type === 2 /* TEXT */ ||
12007 n.type === 5 /* INTERPOLATION */ ||
12008 n.type === 8 /* COMPOUND_EXPRESSION */);
12009 }
12010 function genNodeListAsArray(nodes, context) {
12011 const multilines = nodes.length > 3 ||
12012 (nodes.some(n => isArray(n) || !isText$1(n)));
12013 context.push(`[`);
12014 multilines && context.indent();
12015 genNodeList(nodes, context, multilines);
12016 multilines && context.deindent();
12017 context.push(`]`);
12018 }
12019 function genNodeList(nodes, context, multilines = false, comma = true) {
12020 const { push, newline } = context;
12021 for (let i = 0; i < nodes.length; i++) {
12022 const node = nodes[i];
12023 if (isString(node)) {
12024 push(node);
12025 }
12026 else if (isArray(node)) {
12027 genNodeListAsArray(node, context);
12028 }
12029 else {
12030 genNode(node, context);
12031 }
12032 if (i < nodes.length - 1) {
12033 if (multilines) {
12034 comma && push(',');
12035 newline();
12036 }
12037 else {
12038 comma && push(', ');
12039 }
12040 }
12041 }
12042 }
12043 function genNode(node, context) {
12044 if (isString(node)) {
12045 context.push(node);
12046 return;
12047 }
12048 if (isSymbol(node)) {
12049 context.push(context.helper(node));
12050 return;
12051 }
12052 switch (node.type) {
12053 case 1 /* ELEMENT */:
12054 case 9 /* IF */:
12055 case 11 /* FOR */:
12056 assert(node.codegenNode != null, `Codegen node is missing for element/if/for node. ` +
12057 `Apply appropriate transforms first.`);
12058 genNode(node.codegenNode, context);
12059 break;
12060 case 2 /* TEXT */:
12061 genText(node, context);
12062 break;
12063 case 4 /* SIMPLE_EXPRESSION */:
12064 genExpression(node, context);
12065 break;
12066 case 5 /* INTERPOLATION */:
12067 genInterpolation(node, context);
12068 break;
12069 case 12 /* TEXT_CALL */:
12070 genNode(node.codegenNode, context);
12071 break;
12072 case 8 /* COMPOUND_EXPRESSION */:
12073 genCompoundExpression(node, context);
12074 break;
12075 case 3 /* COMMENT */:
12076 genComment(node, context);
12077 break;
12078 case 13 /* VNODE_CALL */:
12079 genVNodeCall(node, context);
12080 break;
12081 case 14 /* JS_CALL_EXPRESSION */:
12082 genCallExpression(node, context);
12083 break;
12084 case 15 /* JS_OBJECT_EXPRESSION */:
12085 genObjectExpression(node, context);
12086 break;
12087 case 17 /* JS_ARRAY_EXPRESSION */:
12088 genArrayExpression(node, context);
12089 break;
12090 case 18 /* JS_FUNCTION_EXPRESSION */:
12091 genFunctionExpression(node, context);
12092 break;
12093 case 19 /* JS_CONDITIONAL_EXPRESSION */:
12094 genConditionalExpression(node, context);
12095 break;
12096 case 20 /* JS_CACHE_EXPRESSION */:
12097 genCacheExpression(node, context);
12098 break;
12099 // SSR only types
12100 case 21 /* JS_BLOCK_STATEMENT */:
12101 break;
12102 case 22 /* JS_TEMPLATE_LITERAL */:
12103 break;
12104 case 23 /* JS_IF_STATEMENT */:
12105 break;
12106 case 24 /* JS_ASSIGNMENT_EXPRESSION */:
12107 break;
12108 case 25 /* JS_SEQUENCE_EXPRESSION */:
12109 break;
12110 case 26 /* JS_RETURN_STATEMENT */:
12111 break;
12112 /* istanbul ignore next */
12113 case 10 /* IF_BRANCH */:
12114 // noop
12115 break;
12116 default:
12117 {
12118 assert(false, `unhandled codegen node type: ${node.type}`);
12119 // make sure we exhaust all possible types
12120 const exhaustiveCheck = node;
12121 return exhaustiveCheck;
12122 }
12123 }
12124 }
12125 function genText(node, context) {
12126 context.push(JSON.stringify(node.content), node);
12127 }
12128 function genExpression(node, context) {
12129 const { content, isStatic } = node;
12130 context.push(isStatic ? JSON.stringify(content) : content, node);
12131 }
12132 function genInterpolation(node, context) {
12133 const { push, helper, pure } = context;
12134 if (pure)
12135 push(PURE_ANNOTATION);
12136 push(`${helper(TO_DISPLAY_STRING)}(`);
12137 genNode(node.content, context);
12138 push(`)`);
12139 }
12140 function genCompoundExpression(node, context) {
12141 for (let i = 0; i < node.children.length; i++) {
12142 const child = node.children[i];
12143 if (isString(child)) {
12144 context.push(child);
12145 }
12146 else {
12147 genNode(child, context);
12148 }
12149 }
12150 }
12151 function genExpressionAsPropertyKey(node, context) {
12152 const { push } = context;
12153 if (node.type === 8 /* COMPOUND_EXPRESSION */) {
12154 push(`[`);
12155 genCompoundExpression(node, context);
12156 push(`]`);
12157 }
12158 else if (node.isStatic) {
12159 // only quote keys if necessary
12160 const text = isSimpleIdentifier(node.content)
12161 ? node.content
12162 : JSON.stringify(node.content);
12163 push(text, node);
12164 }
12165 else {
12166 push(`[${node.content}]`, node);
12167 }
12168 }
12169 function genComment(node, context) {
12170 const { push, helper, pure } = context;
12171 if (pure) {
12172 push(PURE_ANNOTATION);
12173 }
12174 push(`${helper(CREATE_COMMENT)}(${JSON.stringify(node.content)})`, node);
12175 }
12176 function genVNodeCall(node, context) {
12177 const { push, helper, pure } = context;
12178 const { tag, props, children, patchFlag, dynamicProps, directives, isBlock, disableTracking } = node;
12179 if (directives) {
12180 push(helper(WITH_DIRECTIVES) + `(`);
12181 }
12182 if (isBlock) {
12183 push(`(${helper(OPEN_BLOCK)}(${disableTracking ? `true` : ``}), `);
12184 }
12185 if (pure) {
12186 push(PURE_ANNOTATION);
12187 }
12188 push(helper(isBlock ? CREATE_BLOCK : CREATE_VNODE) + `(`, node);
12189 genNodeList(genNullableArgs([tag, props, children, patchFlag, dynamicProps]), context);
12190 push(`)`);
12191 if (isBlock) {
12192 push(`)`);
12193 }
12194 if (directives) {
12195 push(`, `);
12196 genNode(directives, context);
12197 push(`)`);
12198 }
12199 }
12200 function genNullableArgs(args) {
12201 let i = args.length;
12202 while (i--) {
12203 if (args[i] != null)
12204 break;
12205 }
12206 return args.slice(0, i + 1).map(arg => arg || `null`);
12207 }
12208 // JavaScript
12209 function genCallExpression(node, context) {
12210 const { push, helper, pure } = context;
12211 const callee = isString(node.callee) ? node.callee : helper(node.callee);
12212 if (pure) {
12213 push(PURE_ANNOTATION);
12214 }
12215 push(callee + `(`, node);
12216 genNodeList(node.arguments, context);
12217 push(`)`);
12218 }
12219 function genObjectExpression(node, context) {
12220 const { push, indent, deindent, newline } = context;
12221 const { properties } = node;
12222 if (!properties.length) {
12223 push(`{}`, node);
12224 return;
12225 }
12226 const multilines = properties.length > 1 ||
12227 (properties.some(p => p.value.type !== 4 /* SIMPLE_EXPRESSION */));
12228 push(multilines ? `{` : `{ `);
12229 multilines && indent();
12230 for (let i = 0; i < properties.length; i++) {
12231 const { key, value } = properties[i];
12232 // key
12233 genExpressionAsPropertyKey(key, context);
12234 push(`: `);
12235 // value
12236 genNode(value, context);
12237 if (i < properties.length - 1) {
12238 // will only reach this if it's multilines
12239 push(`,`);
12240 newline();
12241 }
12242 }
12243 multilines && deindent();
12244 push(multilines ? `}` : ` }`);
12245 }
12246 function genArrayExpression(node, context) {
12247 genNodeListAsArray(node.elements, context);
12248 }
12249 function genFunctionExpression(node, context) {
12250 const { push, indent, deindent, scopeId, mode } = context;
12251 const { params, returns, body, newline, isSlot } = node;
12252 if (isSlot) {
12253 // wrap slot functions with owner context
12254 push(`_${helperNameMap[WITH_CTX]}(`);
12255 }
12256 push(`(`, node);
12257 if (isArray(params)) {
12258 genNodeList(params, context);
12259 }
12260 else if (params) {
12261 genNode(params, context);
12262 }
12263 push(`) => `);
12264 if (newline || body) {
12265 push(`{`);
12266 indent();
12267 }
12268 if (returns) {
12269 if (newline) {
12270 push(`return `);
12271 }
12272 if (isArray(returns)) {
12273 genNodeListAsArray(returns, context);
12274 }
12275 else {
12276 genNode(returns, context);
12277 }
12278 }
12279 else if (body) {
12280 genNode(body, context);
12281 }
12282 if (newline || body) {
12283 deindent();
12284 push(`}`);
12285 }
12286 if (isSlot) {
12287 push(`)`);
12288 }
12289 }
12290 function genConditionalExpression(node, context) {
12291 const { test, consequent, alternate, newline: needNewline } = node;
12292 const { push, indent, deindent, newline } = context;
12293 if (test.type === 4 /* SIMPLE_EXPRESSION */) {
12294 const needsParens = !isSimpleIdentifier(test.content);
12295 needsParens && push(`(`);
12296 genExpression(test, context);
12297 needsParens && push(`)`);
12298 }
12299 else {
12300 push(`(`);
12301 genNode(test, context);
12302 push(`)`);
12303 }
12304 needNewline && indent();
12305 context.indentLevel++;
12306 needNewline || push(` `);
12307 push(`? `);
12308 genNode(consequent, context);
12309 context.indentLevel--;
12310 needNewline && newline();
12311 needNewline || push(` `);
12312 push(`: `);
12313 const isNested = alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */;
12314 if (!isNested) {
12315 context.indentLevel++;
12316 }
12317 genNode(alternate, context);
12318 if (!isNested) {
12319 context.indentLevel--;
12320 }
12321 needNewline && deindent(true /* without newline */);
12322 }
12323 function genCacheExpression(node, context) {
12324 const { push, helper, indent, deindent, newline } = context;
12325 push(`_cache[${node.index}] || (`);
12326 if (node.isVNode) {
12327 indent();
12328 push(`${helper(SET_BLOCK_TRACKING)}(-1),`);
12329 newline();
12330 }
12331 push(`_cache[${node.index}] = `);
12332 genNode(node.value, context);
12333 if (node.isVNode) {
12334 push(`,`);
12335 newline();
12336 push(`${helper(SET_BLOCK_TRACKING)}(1),`);
12337 newline();
12338 push(`_cache[${node.index}]`);
12339 deindent();
12340 }
12341 push(`)`);
12342 }
12343
12344 // these keywords should not appear inside expressions, but operators like
12345 // typeof, instanceof and in are allowed
12346 const prohibitedKeywordRE = new RegExp('\\b' +
12347 ('do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' +
12348 'super,throw,while,yield,delete,export,import,return,switch,default,' +
12349 'extends,finally,continue,debugger,function,arguments,typeof,void')
12350 .split(',')
12351 .join('\\b|\\b') +
12352 '\\b');
12353 // strip strings in expressions
12354 const stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g;
12355 /**
12356 * Validate a non-prefixed expression.
12357 * This is only called when using the in-browser runtime compiler since it
12358 * doesn't prefix expressions.
12359 */
12360 function validateBrowserExpression(node, context, asParams = false, asRawStatements = false) {
12361 const exp = node.content;
12362 // empty expressions are validated per-directive since some directives
12363 // do allow empty expressions.
12364 if (!exp.trim()) {
12365 return;
12366 }
12367 try {
12368 new Function(asRawStatements
12369 ? ` ${exp} `
12370 : `return ${asParams ? `(${exp}) => {}` : `(${exp})`}`);
12371 }
12372 catch (e) {
12373 let message = e.message;
12374 const keywordMatch = exp
12375 .replace(stripStringRE, '')
12376 .match(prohibitedKeywordRE);
12377 if (keywordMatch) {
12378 message = `avoid using JavaScript keyword as property name: "${keywordMatch[0]}"`;
12379 }
12380 context.onError(createCompilerError(43 /* X_INVALID_EXPRESSION */, node.loc, undefined, message));
12381 }
12382 }
12383
12384 const transformExpression = (node, context) => {
12385 if (node.type === 5 /* INTERPOLATION */) {
12386 node.content = processExpression(node.content, context);
12387 }
12388 else if (node.type === 1 /* ELEMENT */) {
12389 // handle directives on element
12390 for (let i = 0; i < node.props.length; i++) {
12391 const dir = node.props[i];
12392 // do not process for v-on & v-for since they are special handled
12393 if (dir.type === 7 /* DIRECTIVE */ && dir.name !== 'for') {
12394 const exp = dir.exp;
12395 const arg = dir.arg;
12396 // do not process exp if this is v-on:arg - we need special handling
12397 // for wrapping inline statements.
12398 if (exp &&
12399 exp.type === 4 /* SIMPLE_EXPRESSION */ &&
12400 !(dir.name === 'on' && arg)) {
12401 dir.exp = processExpression(exp, context,
12402 // slot args must be processed as function params
12403 dir.name === 'slot');
12404 }
12405 if (arg && arg.type === 4 /* SIMPLE_EXPRESSION */ && !arg.isStatic) {
12406 dir.arg = processExpression(arg, context);
12407 }
12408 }
12409 }
12410 }
12411 };
12412 // Important: since this function uses Node.js only dependencies, it should
12413 // always be used with a leading !true check so that it can be
12414 // tree-shaken from the browser build.
12415 function processExpression(node, context,
12416 // some expressions like v-slot props & v-for aliases should be parsed as
12417 // function params
12418 asParams = false,
12419 // v-on handler values may contain multiple statements
12420 asRawStatements = false) {
12421 {
12422 {
12423 // simple in-browser validation (same logic in 2.x)
12424 validateBrowserExpression(node, context, asParams, asRawStatements);
12425 }
12426 return node;
12427 }
12428 }
12429
12430 const transformIf = createStructuralDirectiveTransform(/^(if|else|else-if)$/, (node, dir, context) => {
12431 return processIf(node, dir, context, (ifNode, branch, isRoot) => {
12432 // #1587: We need to dynamically increment the key based on the current
12433 // node's sibling nodes, since chained v-if/else branches are
12434 // rendered at the same depth
12435 const siblings = context.parent.children;
12436 let i = siblings.indexOf(ifNode);
12437 let key = 0;
12438 while (i-- >= 0) {
12439 const sibling = siblings[i];
12440 if (sibling && sibling.type === 9 /* IF */) {
12441 key += sibling.branches.length;
12442 }
12443 }
12444 // Exit callback. Complete the codegenNode when all children have been
12445 // transformed.
12446 return () => {
12447 if (isRoot) {
12448 ifNode.codegenNode = createCodegenNodeForBranch(branch, key, context);
12449 }
12450 else {
12451 // attach this branch's codegen node to the v-if root.
12452 const parentCondition = getParentCondition(ifNode.codegenNode);
12453 parentCondition.alternate = createCodegenNodeForBranch(branch, key + ifNode.branches.length - 1, context);
12454 }
12455 };
12456 });
12457 });
12458 // target-agnostic transform used for both Client and SSR
12459 function processIf(node, dir, context, processCodegen) {
12460 if (dir.name !== 'else' &&
12461 (!dir.exp || !dir.exp.content.trim())) {
12462 const loc = dir.exp ? dir.exp.loc : node.loc;
12463 context.onError(createCompilerError(27 /* X_V_IF_NO_EXPRESSION */, dir.loc));
12464 dir.exp = createSimpleExpression(`true`, false, loc);
12465 }
12466 if (dir.exp) {
12467 validateBrowserExpression(dir.exp, context);
12468 }
12469 if (dir.name === 'if') {
12470 const branch = createIfBranch(node, dir);
12471 const ifNode = {
12472 type: 9 /* IF */,
12473 loc: node.loc,
12474 branches: [branch]
12475 };
12476 context.replaceNode(ifNode);
12477 if (processCodegen) {
12478 return processCodegen(ifNode, branch, true);
12479 }
12480 }
12481 else {
12482 // locate the adjacent v-if
12483 const siblings = context.parent.children;
12484 const comments = [];
12485 let i = siblings.indexOf(node);
12486 while (i-- >= -1) {
12487 const sibling = siblings[i];
12488 if (sibling && sibling.type === 3 /* COMMENT */) {
12489 context.removeNode(sibling);
12490 comments.unshift(sibling);
12491 continue;
12492 }
12493 if (sibling &&
12494 sibling.type === 2 /* TEXT */ &&
12495 !sibling.content.trim().length) {
12496 context.removeNode(sibling);
12497 continue;
12498 }
12499 if (sibling && sibling.type === 9 /* IF */) {
12500 // move the node to the if node's branches
12501 context.removeNode();
12502 const branch = createIfBranch(node, dir);
12503 if (comments.length &&
12504 // #3619 ignore comments if the v-if is direct child of <transition>
12505 !(context.parent &&
12506 context.parent.type === 1 /* ELEMENT */ &&
12507 isBuiltInType(context.parent.tag, 'transition'))) {
12508 branch.children = [...comments, ...branch.children];
12509 }
12510 // check if user is forcing same key on different branches
12511 {
12512 const key = branch.userKey;
12513 if (key) {
12514 sibling.branches.forEach(({ userKey }) => {
12515 if (isSameKey(userKey, key)) {
12516 context.onError(createCompilerError(28 /* X_V_IF_SAME_KEY */, branch.userKey.loc));
12517 }
12518 });
12519 }
12520 }
12521 sibling.branches.push(branch);
12522 const onExit = processCodegen && processCodegen(sibling, branch, false);
12523 // since the branch was removed, it will not be traversed.
12524 // make sure to traverse here.
12525 traverseNode(branch, context);
12526 // call on exit
12527 if (onExit)
12528 onExit();
12529 // make sure to reset currentNode after traversal to indicate this
12530 // node has been removed.
12531 context.currentNode = null;
12532 }
12533 else {
12534 context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, node.loc));
12535 }
12536 break;
12537 }
12538 }
12539 }
12540 function createIfBranch(node, dir) {
12541 return {
12542 type: 10 /* IF_BRANCH */,
12543 loc: node.loc,
12544 condition: dir.name === 'else' ? undefined : dir.exp,
12545 children: node.tagType === 3 /* TEMPLATE */ && !findDir(node, 'for')
12546 ? node.children
12547 : [node],
12548 userKey: findProp(node, `key`)
12549 };
12550 }
12551 function createCodegenNodeForBranch(branch, keyIndex, context) {
12552 if (branch.condition) {
12553 return createConditionalExpression(branch.condition, createChildrenCodegenNode(branch, keyIndex, context),
12554 // make sure to pass in asBlock: true so that the comment node call
12555 // closes the current block.
12556 createCallExpression(context.helper(CREATE_COMMENT), [
12557 '"v-if"' ,
12558 'true'
12559 ]));
12560 }
12561 else {
12562 return createChildrenCodegenNode(branch, keyIndex, context);
12563 }
12564 }
12565 function createChildrenCodegenNode(branch, keyIndex, context) {
12566 const { helper, removeHelper } = context;
12567 const keyProperty = createObjectProperty(`key`, createSimpleExpression(`${keyIndex}`, false, locStub, 2 /* CAN_HOIST */));
12568 const { children } = branch;
12569 const firstChild = children[0];
12570 const needFragmentWrapper = children.length !== 1 || firstChild.type !== 1 /* ELEMENT */;
12571 if (needFragmentWrapper) {
12572 if (children.length === 1 && firstChild.type === 11 /* FOR */) {
12573 // optimize away nested fragments when child is a ForNode
12574 const vnodeCall = firstChild.codegenNode;
12575 injectProp(vnodeCall, keyProperty, context);
12576 return vnodeCall;
12577 }
12578 else {
12579 let patchFlag = 64 /* STABLE_FRAGMENT */;
12580 let patchFlagText = PatchFlagNames[64 /* STABLE_FRAGMENT */];
12581 // check if the fragment actually contains a single valid child with
12582 // the rest being comments
12583 if (children.filter(c => c.type !== 3 /* COMMENT */).length === 1) {
12584 patchFlag |= 2048 /* DEV_ROOT_FRAGMENT */;
12585 patchFlagText += `, ${PatchFlagNames[2048 /* DEV_ROOT_FRAGMENT */]}`;
12586 }
12587 return createVNodeCall(context, helper(FRAGMENT), createObjectExpression([keyProperty]), children, patchFlag + (` /* ${patchFlagText} */` ), undefined, undefined, true, false, branch.loc);
12588 }
12589 }
12590 else {
12591 const vnodeCall = firstChild
12592 .codegenNode;
12593 // Change createVNode to createBlock.
12594 if (vnodeCall.type === 13 /* VNODE_CALL */ && !vnodeCall.isBlock) {
12595 removeHelper(CREATE_VNODE);
12596 vnodeCall.isBlock = true;
12597 helper(OPEN_BLOCK);
12598 helper(CREATE_BLOCK);
12599 }
12600 // inject branch key
12601 injectProp(vnodeCall, keyProperty, context);
12602 return vnodeCall;
12603 }
12604 }
12605 function isSameKey(a, b) {
12606 if (!a || a.type !== b.type) {
12607 return false;
12608 }
12609 if (a.type === 6 /* ATTRIBUTE */) {
12610 if (a.value.content !== b.value.content) {
12611 return false;
12612 }
12613 }
12614 else {
12615 // directive
12616 const exp = a.exp;
12617 const branchExp = b.exp;
12618 if (exp.type !== branchExp.type) {
12619 return false;
12620 }
12621 if (exp.type !== 4 /* SIMPLE_EXPRESSION */ ||
12622 (exp.isStatic !== branchExp.isStatic ||
12623 exp.content !== branchExp.content)) {
12624 return false;
12625 }
12626 }
12627 return true;
12628 }
12629 function getParentCondition(node) {
12630 while (true) {
12631 if (node.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12632 if (node.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12633 node = node.alternate;
12634 }
12635 else {
12636 return node;
12637 }
12638 }
12639 else if (node.type === 20 /* JS_CACHE_EXPRESSION */) {
12640 node = node.value;
12641 }
12642 }
12643 }
12644
12645 const transformFor = createStructuralDirectiveTransform('for', (node, dir, context) => {
12646 const { helper, removeHelper } = context;
12647 return processFor(node, dir, context, forNode => {
12648 // create the loop render function expression now, and add the
12649 // iterator on exit after all children have been traversed
12650 const renderExp = createCallExpression(helper(RENDER_LIST), [
12651 forNode.source
12652 ]);
12653 const keyProp = findProp(node, `key`);
12654 const keyProperty = keyProp
12655 ? createObjectProperty(`key`, keyProp.type === 6 /* ATTRIBUTE */
12656 ? createSimpleExpression(keyProp.value.content, true)
12657 : keyProp.exp)
12658 : null;
12659 const isStableFragment = forNode.source.type === 4 /* SIMPLE_EXPRESSION */ &&
12660 forNode.source.constType > 0 /* NOT_CONSTANT */;
12661 const fragmentFlag = isStableFragment
12662 ? 64 /* STABLE_FRAGMENT */
12663 : keyProp
12664 ? 128 /* KEYED_FRAGMENT */
12665 : 256 /* UNKEYED_FRAGMENT */;
12666 forNode.codegenNode = createVNodeCall(context, helper(FRAGMENT), undefined, renderExp, fragmentFlag +
12667 (` /* ${PatchFlagNames[fragmentFlag]} */` ), undefined, undefined, true /* isBlock */, !isStableFragment /* disableTracking */, node.loc);
12668 return () => {
12669 // finish the codegen now that all children have been traversed
12670 let childBlock;
12671 const isTemplate = isTemplateNode(node);
12672 const { children } = forNode;
12673 // check <template v-for> key placement
12674 if (isTemplate) {
12675 node.children.some(c => {
12676 if (c.type === 1 /* ELEMENT */) {
12677 const key = findProp(c, 'key');
12678 if (key) {
12679 context.onError(createCompilerError(32 /* X_V_FOR_TEMPLATE_KEY_PLACEMENT */, key.loc));
12680 return true;
12681 }
12682 }
12683 });
12684 }
12685 const needFragmentWrapper = children.length !== 1 || children[0].type !== 1 /* ELEMENT */;
12686 const slotOutlet = isSlotOutlet(node)
12687 ? node
12688 : isTemplate &&
12689 node.children.length === 1 &&
12690 isSlotOutlet(node.children[0])
12691 ? node.children[0] // api-extractor somehow fails to infer this
12692 : null;
12693 if (slotOutlet) {
12694 // <slot v-for="..."> or <template v-for="..."><slot/></template>
12695 childBlock = slotOutlet.codegenNode;
12696 if (isTemplate && keyProperty) {
12697 // <template v-for="..." :key="..."><slot/></template>
12698 // we need to inject the key to the renderSlot() call.
12699 // the props for renderSlot is passed as the 3rd argument.
12700 injectProp(childBlock, keyProperty, context);
12701 }
12702 }
12703 else if (needFragmentWrapper) {
12704 // <template v-for="..."> with text or multi-elements
12705 // should generate a fragment block for each loop
12706 childBlock = createVNodeCall(context, helper(FRAGMENT), keyProperty ? createObjectExpression([keyProperty]) : undefined, node.children, 64 /* STABLE_FRAGMENT */ +
12707 (` /* ${PatchFlagNames[64 /* STABLE_FRAGMENT */]} */`
12708 ), undefined, undefined, true);
12709 }
12710 else {
12711 // Normal element v-for. Directly use the child's codegenNode
12712 // but mark it as a block.
12713 childBlock = children[0]
12714 .codegenNode;
12715 if (isTemplate && keyProperty) {
12716 injectProp(childBlock, keyProperty, context);
12717 }
12718 if (childBlock.isBlock !== !isStableFragment) {
12719 if (childBlock.isBlock) {
12720 // switch from block to vnode
12721 removeHelper(OPEN_BLOCK);
12722 removeHelper(CREATE_BLOCK);
12723 }
12724 else {
12725 // switch from vnode to block
12726 removeHelper(CREATE_VNODE);
12727 }
12728 }
12729 childBlock.isBlock = !isStableFragment;
12730 if (childBlock.isBlock) {
12731 helper(OPEN_BLOCK);
12732 helper(CREATE_BLOCK);
12733 }
12734 else {
12735 helper(CREATE_VNODE);
12736 }
12737 }
12738 renderExp.arguments.push(createFunctionExpression(createForLoopParams(forNode.parseResult), childBlock, true /* force newline */));
12739 };
12740 });
12741 });
12742 // target-agnostic transform used for both Client and SSR
12743 function processFor(node, dir, context, processCodegen) {
12744 if (!dir.exp) {
12745 context.onError(createCompilerError(30 /* X_V_FOR_NO_EXPRESSION */, dir.loc));
12746 return;
12747 }
12748 const parseResult = parseForExpression(
12749 // can only be simple expression because vFor transform is applied
12750 // before expression transform.
12751 dir.exp, context);
12752 if (!parseResult) {
12753 context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, dir.loc));
12754 return;
12755 }
12756 const { addIdentifiers, removeIdentifiers, scopes } = context;
12757 const { source, value, key, index } = parseResult;
12758 const forNode = {
12759 type: 11 /* FOR */,
12760 loc: dir.loc,
12761 source,
12762 valueAlias: value,
12763 keyAlias: key,
12764 objectIndexAlias: index,
12765 parseResult,
12766 children: isTemplateNode(node) ? node.children : [node]
12767 };
12768 context.replaceNode(forNode);
12769 // bookkeeping
12770 scopes.vFor++;
12771 const onExit = processCodegen && processCodegen(forNode);
12772 return () => {
12773 scopes.vFor--;
12774 if (onExit)
12775 onExit();
12776 };
12777 }
12778 const forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/;
12779 // This regex doesn't cover the case if key or index aliases have destructuring,
12780 // but those do not make sense in the first place, so this works in practice.
12781 const forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/;
12782 const stripParensRE = /^\(|\)$/g;
12783 function parseForExpression(input, context) {
12784 const loc = input.loc;
12785 const exp = input.content;
12786 const inMatch = exp.match(forAliasRE);
12787 if (!inMatch)
12788 return;
12789 const [, LHS, RHS] = inMatch;
12790 const result = {
12791 source: createAliasExpression(loc, RHS.trim(), exp.indexOf(RHS, LHS.length)),
12792 value: undefined,
12793 key: undefined,
12794 index: undefined
12795 };
12796 {
12797 validateBrowserExpression(result.source, context);
12798 }
12799 let valueContent = LHS.trim()
12800 .replace(stripParensRE, '')
12801 .trim();
12802 const trimmedOffset = LHS.indexOf(valueContent);
12803 const iteratorMatch = valueContent.match(forIteratorRE);
12804 if (iteratorMatch) {
12805 valueContent = valueContent.replace(forIteratorRE, '').trim();
12806 const keyContent = iteratorMatch[1].trim();
12807 let keyOffset;
12808 if (keyContent) {
12809 keyOffset = exp.indexOf(keyContent, trimmedOffset + valueContent.length);
12810 result.key = createAliasExpression(loc, keyContent, keyOffset);
12811 {
12812 validateBrowserExpression(result.key, context, true);
12813 }
12814 }
12815 if (iteratorMatch[2]) {
12816 const indexContent = iteratorMatch[2].trim();
12817 if (indexContent) {
12818 result.index = createAliasExpression(loc, indexContent, exp.indexOf(indexContent, result.key
12819 ? keyOffset + keyContent.length
12820 : trimmedOffset + valueContent.length));
12821 {
12822 validateBrowserExpression(result.index, context, true);
12823 }
12824 }
12825 }
12826 }
12827 if (valueContent) {
12828 result.value = createAliasExpression(loc, valueContent, trimmedOffset);
12829 {
12830 validateBrowserExpression(result.value, context, true);
12831 }
12832 }
12833 return result;
12834 }
12835 function createAliasExpression(range, content, offset) {
12836 return createSimpleExpression(content, false, getInnerRange(range, offset, content.length));
12837 }
12838 function createForLoopParams({ value, key, index }) {
12839 const params = [];
12840 if (value) {
12841 params.push(value);
12842 }
12843 if (key) {
12844 if (!value) {
12845 params.push(createSimpleExpression(`_`, false));
12846 }
12847 params.push(key);
12848 }
12849 if (index) {
12850 if (!key) {
12851 if (!value) {
12852 params.push(createSimpleExpression(`_`, false));
12853 }
12854 params.push(createSimpleExpression(`__`, false));
12855 }
12856 params.push(index);
12857 }
12858 return params;
12859 }
12860
12861 const defaultFallback = createSimpleExpression(`undefined`, false);
12862 // A NodeTransform that:
12863 // 1. Tracks scope identifiers for scoped slots so that they don't get prefixed
12864 // by transformExpression. This is only applied in non-browser builds with
12865 // { prefixIdentifiers: true }.
12866 // 2. Track v-slot depths so that we know a slot is inside another slot.
12867 // Note the exit callback is executed before buildSlots() on the same node,
12868 // so only nested slots see positive numbers.
12869 const trackSlotScopes = (node, context) => {
12870 if (node.type === 1 /* ELEMENT */ &&
12871 (node.tagType === 1 /* COMPONENT */ ||
12872 node.tagType === 3 /* TEMPLATE */)) {
12873 // We are only checking non-empty v-slot here
12874 // since we only care about slots that introduce scope variables.
12875 const vSlot = findDir(node, 'slot');
12876 if (vSlot) {
12877 vSlot.exp;
12878 context.scopes.vSlot++;
12879 return () => {
12880 context.scopes.vSlot--;
12881 };
12882 }
12883 }
12884 };
12885 const buildClientSlotFn = (props, children, loc) => createFunctionExpression(props, children, false /* newline */, true /* isSlot */, children.length ? children[0].loc : loc);
12886 // Instead of being a DirectiveTransform, v-slot processing is called during
12887 // transformElement to build the slots object for a component.
12888 function buildSlots(node, context, buildSlotFn = buildClientSlotFn) {
12889 context.helper(WITH_CTX);
12890 const { children, loc } = node;
12891 const slotsProperties = [];
12892 const dynamicSlots = [];
12893 // If the slot is inside a v-for or another v-slot, force it to be dynamic
12894 // since it likely uses a scope variable.
12895 let hasDynamicSlots = context.scopes.vSlot > 0 || context.scopes.vFor > 0;
12896 // 1. Check for slot with slotProps on component itself.
12897 // <Comp v-slot="{ prop }"/>
12898 const onComponentSlot = findDir(node, 'slot', true);
12899 if (onComponentSlot) {
12900 const { arg, exp } = onComponentSlot;
12901 if (arg && !isStaticExp(arg)) {
12902 hasDynamicSlots = true;
12903 }
12904 slotsProperties.push(createObjectProperty(arg || createSimpleExpression('default', true), buildSlotFn(exp, children, loc)));
12905 }
12906 // 2. Iterate through children and check for template slots
12907 // <template v-slot:foo="{ prop }">
12908 let hasTemplateSlots = false;
12909 let hasNamedDefaultSlot = false;
12910 const implicitDefaultChildren = [];
12911 const seenSlotNames = new Set();
12912 for (let i = 0; i < children.length; i++) {
12913 const slotElement = children[i];
12914 let slotDir;
12915 if (!isTemplateNode(slotElement) ||
12916 !(slotDir = findDir(slotElement, 'slot', true))) {
12917 // not a <template v-slot>, skip.
12918 if (slotElement.type !== 3 /* COMMENT */) {
12919 implicitDefaultChildren.push(slotElement);
12920 }
12921 continue;
12922 }
12923 if (onComponentSlot) {
12924 // already has on-component slot - this is incorrect usage.
12925 context.onError(createCompilerError(36 /* X_V_SLOT_MIXED_SLOT_USAGE */, slotDir.loc));
12926 break;
12927 }
12928 hasTemplateSlots = true;
12929 const { children: slotChildren, loc: slotLoc } = slotElement;
12930 const { arg: slotName = createSimpleExpression(`default`, true), exp: slotProps, loc: dirLoc } = slotDir;
12931 // check if name is dynamic.
12932 let staticSlotName;
12933 if (isStaticExp(slotName)) {
12934 staticSlotName = slotName ? slotName.content : `default`;
12935 }
12936 else {
12937 hasDynamicSlots = true;
12938 }
12939 const slotFunction = buildSlotFn(slotProps, slotChildren, slotLoc);
12940 // check if this slot is conditional (v-if/v-for)
12941 let vIf;
12942 let vElse;
12943 let vFor;
12944 if ((vIf = findDir(slotElement, 'if'))) {
12945 hasDynamicSlots = true;
12946 dynamicSlots.push(createConditionalExpression(vIf.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback));
12947 }
12948 else if ((vElse = findDir(slotElement, /^else(-if)?$/, true /* allowEmpty */))) {
12949 // find adjacent v-if
12950 let j = i;
12951 let prev;
12952 while (j--) {
12953 prev = children[j];
12954 if (prev.type !== 3 /* COMMENT */) {
12955 break;
12956 }
12957 }
12958 if (prev && isTemplateNode(prev) && findDir(prev, 'if')) {
12959 // remove node
12960 children.splice(i, 1);
12961 i--;
12962 // attach this slot to previous conditional
12963 let conditional = dynamicSlots[dynamicSlots.length - 1];
12964 while (conditional.alternate.type === 19 /* JS_CONDITIONAL_EXPRESSION */) {
12965 conditional = conditional.alternate;
12966 }
12967 conditional.alternate = vElse.exp
12968 ? createConditionalExpression(vElse.exp, buildDynamicSlot(slotName, slotFunction), defaultFallback)
12969 : buildDynamicSlot(slotName, slotFunction);
12970 }
12971 else {
12972 context.onError(createCompilerError(29 /* X_V_ELSE_NO_ADJACENT_IF */, vElse.loc));
12973 }
12974 }
12975 else if ((vFor = findDir(slotElement, 'for'))) {
12976 hasDynamicSlots = true;
12977 const parseResult = vFor.parseResult ||
12978 parseForExpression(vFor.exp, context);
12979 if (parseResult) {
12980 // Render the dynamic slots as an array and add it to the createSlot()
12981 // args. The runtime knows how to handle it appropriately.
12982 dynamicSlots.push(createCallExpression(context.helper(RENDER_LIST), [
12983 parseResult.source,
12984 createFunctionExpression(createForLoopParams(parseResult), buildDynamicSlot(slotName, slotFunction), true /* force newline */)
12985 ]));
12986 }
12987 else {
12988 context.onError(createCompilerError(31 /* X_V_FOR_MALFORMED_EXPRESSION */, vFor.loc));
12989 }
12990 }
12991 else {
12992 // check duplicate static names
12993 if (staticSlotName) {
12994 if (seenSlotNames.has(staticSlotName)) {
12995 context.onError(createCompilerError(37 /* X_V_SLOT_DUPLICATE_SLOT_NAMES */, dirLoc));
12996 continue;
12997 }
12998 seenSlotNames.add(staticSlotName);
12999 if (staticSlotName === 'default') {
13000 hasNamedDefaultSlot = true;
13001 }
13002 }
13003 slotsProperties.push(createObjectProperty(slotName, slotFunction));
13004 }
13005 }
13006 if (!onComponentSlot) {
13007 const buildDefaultSlotProperty = (props, children) => {
13008 const fn = buildSlotFn(props, children, loc);
13009 return createObjectProperty(`default`, fn);
13010 };
13011 if (!hasTemplateSlots) {
13012 // implicit default slot (on component)
13013 slotsProperties.push(buildDefaultSlotProperty(undefined, children));
13014 }
13015 else if (implicitDefaultChildren.length &&
13016 // #3766
13017 // with whitespace: 'preserve', whitespaces between slots will end up in
13018 // implicitDefaultChildren. Ignore if all implicit children are whitespaces.
13019 implicitDefaultChildren.some(node => isNonWhitespaceContent(node))) {
13020 // implicit default slot (mixed with named slots)
13021 if (hasNamedDefaultSlot) {
13022 context.onError(createCompilerError(38 /* X_V_SLOT_EXTRANEOUS_DEFAULT_SLOT_CHILDREN */, implicitDefaultChildren[0].loc));
13023 }
13024 else {
13025 slotsProperties.push(buildDefaultSlotProperty(undefined, implicitDefaultChildren));
13026 }
13027 }
13028 }
13029 const slotFlag = hasDynamicSlots
13030 ? 2 /* DYNAMIC */
13031 : hasForwardedSlots(node.children)
13032 ? 3 /* FORWARDED */
13033 : 1 /* STABLE */;
13034 let slots = createObjectExpression(slotsProperties.concat(createObjectProperty(`_`,
13035 // 2 = compiled but dynamic = can skip normalization, but must run diff
13036 // 1 = compiled and static = can skip normalization AND diff as optimized
13037 createSimpleExpression(slotFlag + (` /* ${slotFlagsText[slotFlag]} */` ), false))), loc);
13038 if (dynamicSlots.length) {
13039 slots = createCallExpression(context.helper(CREATE_SLOTS), [
13040 slots,
13041 createArrayExpression(dynamicSlots)
13042 ]);
13043 }
13044 return {
13045 slots,
13046 hasDynamicSlots
13047 };
13048 }
13049 function buildDynamicSlot(name, fn) {
13050 return createObjectExpression([
13051 createObjectProperty(`name`, name),
13052 createObjectProperty(`fn`, fn)
13053 ]);
13054 }
13055 function hasForwardedSlots(children) {
13056 for (let i = 0; i < children.length; i++) {
13057 const child = children[i];
13058 switch (child.type) {
13059 case 1 /* ELEMENT */:
13060 if (child.tagType === 2 /* SLOT */ ||
13061 (child.tagType === 0 /* ELEMENT */ &&
13062 hasForwardedSlots(child.children))) {
13063 return true;
13064 }
13065 break;
13066 case 9 /* IF */:
13067 if (hasForwardedSlots(child.branches))
13068 return true;
13069 break;
13070 case 10 /* IF_BRANCH */:
13071 case 11 /* FOR */:
13072 if (hasForwardedSlots(child.children))
13073 return true;
13074 break;
13075 }
13076 }
13077 return false;
13078 }
13079 function isNonWhitespaceContent(node) {
13080 if (node.type !== 2 /* TEXT */ && node.type !== 12 /* TEXT_CALL */)
13081 return true;
13082 return node.type === 2 /* TEXT */
13083 ? !!node.content.trim()
13084 : isNonWhitespaceContent(node.content);
13085 }
13086
13087 // some directive transforms (e.g. v-model) may return a symbol for runtime
13088 // import, which should be used instead of a resolveDirective call.
13089 const directiveImportMap = new WeakMap();
13090 // generate a JavaScript AST for this element's codegen
13091 const transformElement = (node, context) => {
13092 // perform the work on exit, after all child expressions have been
13093 // processed and merged.
13094 return function postTransformElement() {
13095 node = context.currentNode;
13096 if (!(node.type === 1 /* ELEMENT */ &&
13097 (node.tagType === 0 /* ELEMENT */ ||
13098 node.tagType === 1 /* COMPONENT */))) {
13099 return;
13100 }
13101 const { tag, props } = node;
13102 const isComponent = node.tagType === 1 /* COMPONENT */;
13103 // The goal of the transform is to create a codegenNode implementing the
13104 // VNodeCall interface.
13105 let vnodeTag = isComponent
13106 ? resolveComponentType(node, context)
13107 : `"${tag}"`;
13108 const isDynamicComponent = isObject(vnodeTag) && vnodeTag.callee === RESOLVE_DYNAMIC_COMPONENT;
13109 let vnodeProps;
13110 let vnodeChildren;
13111 let vnodePatchFlag;
13112 let patchFlag = 0;
13113 let vnodeDynamicProps;
13114 let dynamicPropNames;
13115 let vnodeDirectives;
13116 let shouldUseBlock =
13117 // dynamic component may resolve to plain elements
13118 isDynamicComponent ||
13119 vnodeTag === TELEPORT ||
13120 vnodeTag === SUSPENSE ||
13121 (!isComponent &&
13122 // <svg> and <foreignObject> must be forced into blocks so that block
13123 // updates inside get proper isSVG flag at runtime. (#639, #643)
13124 // This is technically web-specific, but splitting the logic out of core
13125 // leads to too much unnecessary complexity.
13126 (tag === 'svg' ||
13127 tag === 'foreignObject' ||
13128 // #938: elements with dynamic keys should be forced into blocks
13129 findProp(node, 'key', true)));
13130 // props
13131 if (props.length > 0) {
13132 const propsBuildResult = buildProps(node, context);
13133 vnodeProps = propsBuildResult.props;
13134 patchFlag = propsBuildResult.patchFlag;
13135 dynamicPropNames = propsBuildResult.dynamicPropNames;
13136 const directives = propsBuildResult.directives;
13137 vnodeDirectives =
13138 directives && directives.length
13139 ? createArrayExpression(directives.map(dir => buildDirectiveArgs(dir, context)))
13140 : undefined;
13141 }
13142 // children
13143 if (node.children.length > 0) {
13144 if (vnodeTag === KEEP_ALIVE) {
13145 // Although a built-in component, we compile KeepAlive with raw children
13146 // instead of slot functions so that it can be used inside Transition
13147 // or other Transition-wrapping HOCs.
13148 // To ensure correct updates with block optimizations, we need to:
13149 // 1. Force keep-alive into a block. This avoids its children being
13150 // collected by a parent block.
13151 shouldUseBlock = true;
13152 // 2. Force keep-alive to always be updated, since it uses raw children.
13153 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
13154 if (node.children.length > 1) {
13155 context.onError(createCompilerError(44 /* X_KEEP_ALIVE_INVALID_CHILDREN */, {
13156 start: node.children[0].loc.start,
13157 end: node.children[node.children.length - 1].loc.end,
13158 source: ''
13159 }));
13160 }
13161 }
13162 const shouldBuildAsSlots = isComponent &&
13163 // Teleport is not a real component and has dedicated runtime handling
13164 vnodeTag !== TELEPORT &&
13165 // explained above.
13166 vnodeTag !== KEEP_ALIVE;
13167 if (shouldBuildAsSlots) {
13168 const { slots, hasDynamicSlots } = buildSlots(node, context);
13169 vnodeChildren = slots;
13170 if (hasDynamicSlots) {
13171 patchFlag |= 1024 /* DYNAMIC_SLOTS */;
13172 }
13173 }
13174 else if (node.children.length === 1 && vnodeTag !== TELEPORT) {
13175 const child = node.children[0];
13176 const type = child.type;
13177 // check for dynamic text children
13178 const hasDynamicTextChild = type === 5 /* INTERPOLATION */ ||
13179 type === 8 /* COMPOUND_EXPRESSION */;
13180 if (hasDynamicTextChild &&
13181 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
13182 patchFlag |= 1 /* TEXT */;
13183 }
13184 // pass directly if the only child is a text node
13185 // (plain / interpolation / expression)
13186 if (hasDynamicTextChild || type === 2 /* TEXT */) {
13187 vnodeChildren = child;
13188 }
13189 else {
13190 vnodeChildren = node.children;
13191 }
13192 }
13193 else {
13194 vnodeChildren = node.children;
13195 }
13196 }
13197 // patchFlag & dynamicPropNames
13198 if (patchFlag !== 0) {
13199 {
13200 if (patchFlag < 0) {
13201 // special flags (negative and mutually exclusive)
13202 vnodePatchFlag = patchFlag + ` /* ${PatchFlagNames[patchFlag]} */`;
13203 }
13204 else {
13205 // bitwise flags
13206 const flagNames = Object.keys(PatchFlagNames)
13207 .map(Number)
13208 .filter(n => n > 0 && patchFlag & n)
13209 .map(n => PatchFlagNames[n])
13210 .join(`, `);
13211 vnodePatchFlag = patchFlag + ` /* ${flagNames} */`;
13212 }
13213 }
13214 if (dynamicPropNames && dynamicPropNames.length) {
13215 vnodeDynamicProps = stringifyDynamicPropNames(dynamicPropNames);
13216 }
13217 }
13218 node.codegenNode = createVNodeCall(context, vnodeTag, vnodeProps, vnodeChildren, vnodePatchFlag, vnodeDynamicProps, vnodeDirectives, !!shouldUseBlock, false /* disableTracking */, node.loc);
13219 };
13220 };
13221 function resolveComponentType(node, context, ssr = false) {
13222 let { tag } = node;
13223 // 1. dynamic component
13224 const isExplicitDynamic = isComponentTag(tag);
13225 const isProp = findProp(node, 'is') || (!isExplicitDynamic && findDir(node, 'is'));
13226 if (isProp) {
13227 if (!isExplicitDynamic && isProp.type === 6 /* ATTRIBUTE */) {
13228 // <button is="vue:xxx">
13229 // if not <component>, only is value that starts with "vue:" will be
13230 // treated as component by the parse phase and reach here, unless it's
13231 // compat mode where all is values are considered components
13232 tag = isProp.value.content.replace(/^vue:/, '');
13233 }
13234 else {
13235 const exp = isProp.type === 6 /* ATTRIBUTE */
13236 ? isProp.value && createSimpleExpression(isProp.value.content, true)
13237 : isProp.exp;
13238 if (exp) {
13239 return createCallExpression(context.helper(RESOLVE_DYNAMIC_COMPONENT), [
13240 exp
13241 ]);
13242 }
13243 }
13244 }
13245 // 2. built-in components (Teleport, Transition, KeepAlive, Suspense...)
13246 const builtIn = isCoreComponent(tag) || context.isBuiltInComponent(tag);
13247 if (builtIn) {
13248 // built-ins are simply fallthroughs / have special handling during ssr
13249 // so we don't need to import their runtime equivalents
13250 if (!ssr)
13251 context.helper(builtIn);
13252 return builtIn;
13253 }
13254 // 5. user component (resolve)
13255 context.helper(RESOLVE_COMPONENT);
13256 context.components.add(tag);
13257 return toValidAssetId(tag, `component`);
13258 }
13259 function buildProps(node, context, props = node.props, ssr = false) {
13260 const { tag, loc: elementLoc } = node;
13261 const isComponent = node.tagType === 1 /* COMPONENT */;
13262 let properties = [];
13263 const mergeArgs = [];
13264 const runtimeDirectives = [];
13265 // patchFlag analysis
13266 let patchFlag = 0;
13267 let hasRef = false;
13268 let hasClassBinding = false;
13269 let hasStyleBinding = false;
13270 let hasHydrationEventBinding = false;
13271 let hasDynamicKeys = false;
13272 let hasVnodeHook = false;
13273 const dynamicPropNames = [];
13274 const analyzePatchFlag = ({ key, value }) => {
13275 if (isStaticExp(key)) {
13276 const name = key.content;
13277 const isEventHandler = isOn(name);
13278 if (!isComponent &&
13279 isEventHandler &&
13280 // omit the flag for click handlers because hydration gives click
13281 // dedicated fast path.
13282 name.toLowerCase() !== 'onclick' &&
13283 // omit v-model handlers
13284 name !== 'onUpdate:modelValue' &&
13285 // omit onVnodeXXX hooks
13286 !isReservedProp(name)) {
13287 hasHydrationEventBinding = true;
13288 }
13289 if (isEventHandler && isReservedProp(name)) {
13290 hasVnodeHook = true;
13291 }
13292 if (value.type === 20 /* JS_CACHE_EXPRESSION */ ||
13293 ((value.type === 4 /* SIMPLE_EXPRESSION */ ||
13294 value.type === 8 /* COMPOUND_EXPRESSION */) &&
13295 getConstantType(value, context) > 0)) {
13296 // skip if the prop is a cached handler or has constant value
13297 return;
13298 }
13299 if (name === 'ref') {
13300 hasRef = true;
13301 }
13302 else if (name === 'class' && !isComponent) {
13303 hasClassBinding = true;
13304 }
13305 else if (name === 'style' && !isComponent) {
13306 hasStyleBinding = true;
13307 }
13308 else if (name !== 'key' && !dynamicPropNames.includes(name)) {
13309 dynamicPropNames.push(name);
13310 }
13311 }
13312 else {
13313 hasDynamicKeys = true;
13314 }
13315 };
13316 for (let i = 0; i < props.length; i++) {
13317 // static attribute
13318 const prop = props[i];
13319 if (prop.type === 6 /* ATTRIBUTE */) {
13320 const { loc, name, value } = prop;
13321 let isStatic = true;
13322 if (name === 'ref') {
13323 hasRef = true;
13324 }
13325 // skip is on <component>, or is="vue:xxx"
13326 if (name === 'is' &&
13327 (isComponentTag(tag) || (value && value.content.startsWith('vue:')))) {
13328 continue;
13329 }
13330 properties.push(createObjectProperty(createSimpleExpression(name, true, getInnerRange(loc, 0, name.length)), createSimpleExpression(value ? value.content : '', isStatic, value ? value.loc : loc)));
13331 }
13332 else {
13333 // directives
13334 const { name, arg, exp, loc } = prop;
13335 const isVBind = name === 'bind';
13336 const isVOn = name === 'on';
13337 // skip v-slot - it is handled by its dedicated transform.
13338 if (name === 'slot') {
13339 if (!isComponent) {
13340 context.onError(createCompilerError(39 /* X_V_SLOT_MISPLACED */, loc));
13341 }
13342 continue;
13343 }
13344 // skip v-once - it is handled by its dedicated transform.
13345 if (name === 'once') {
13346 continue;
13347 }
13348 // skip v-is and :is on <component>
13349 if (name === 'is' ||
13350 (isVBind && isComponentTag(tag) && isBindKey(arg, 'is'))) {
13351 continue;
13352 }
13353 // skip v-on in SSR compilation
13354 if (isVOn && ssr) {
13355 continue;
13356 }
13357 // special case for v-bind and v-on with no argument
13358 if (!arg && (isVBind || isVOn)) {
13359 hasDynamicKeys = true;
13360 if (exp) {
13361 if (properties.length) {
13362 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
13363 properties = [];
13364 }
13365 if (isVBind) {
13366 mergeArgs.push(exp);
13367 }
13368 else {
13369 // v-on="obj" -> toHandlers(obj)
13370 mergeArgs.push({
13371 type: 14 /* JS_CALL_EXPRESSION */,
13372 loc,
13373 callee: context.helper(TO_HANDLERS),
13374 arguments: [exp]
13375 });
13376 }
13377 }
13378 else {
13379 context.onError(createCompilerError(isVBind
13380 ? 33 /* X_V_BIND_NO_EXPRESSION */
13381 : 34 /* X_V_ON_NO_EXPRESSION */, loc));
13382 }
13383 continue;
13384 }
13385 const directiveTransform = context.directiveTransforms[name];
13386 if (directiveTransform) {
13387 // has built-in directive transform.
13388 const { props, needRuntime } = directiveTransform(prop, node, context);
13389 !ssr && props.forEach(analyzePatchFlag);
13390 properties.push(...props);
13391 if (needRuntime) {
13392 runtimeDirectives.push(prop);
13393 if (isSymbol(needRuntime)) {
13394 directiveImportMap.set(prop, needRuntime);
13395 }
13396 }
13397 }
13398 else {
13399 // no built-in transform, this is a user custom directive.
13400 runtimeDirectives.push(prop);
13401 }
13402 }
13403 }
13404 let propsExpression = undefined;
13405 // has v-bind="object" or v-on="object", wrap with mergeProps
13406 if (mergeArgs.length) {
13407 if (properties.length) {
13408 mergeArgs.push(createObjectExpression(dedupeProperties(properties), elementLoc));
13409 }
13410 if (mergeArgs.length > 1) {
13411 propsExpression = createCallExpression(context.helper(MERGE_PROPS), mergeArgs, elementLoc);
13412 }
13413 else {
13414 // single v-bind with nothing else - no need for a mergeProps call
13415 propsExpression = mergeArgs[0];
13416 }
13417 }
13418 else if (properties.length) {
13419 propsExpression = createObjectExpression(dedupeProperties(properties), elementLoc);
13420 }
13421 // patchFlag analysis
13422 if (hasDynamicKeys) {
13423 patchFlag |= 16 /* FULL_PROPS */;
13424 }
13425 else {
13426 if (hasClassBinding) {
13427 patchFlag |= 2 /* CLASS */;
13428 }
13429 if (hasStyleBinding) {
13430 patchFlag |= 4 /* STYLE */;
13431 }
13432 if (dynamicPropNames.length) {
13433 patchFlag |= 8 /* PROPS */;
13434 }
13435 if (hasHydrationEventBinding) {
13436 patchFlag |= 32 /* HYDRATE_EVENTS */;
13437 }
13438 }
13439 if ((patchFlag === 0 || patchFlag === 32 /* HYDRATE_EVENTS */) &&
13440 (hasRef || hasVnodeHook || runtimeDirectives.length > 0)) {
13441 patchFlag |= 512 /* NEED_PATCH */;
13442 }
13443 return {
13444 props: propsExpression,
13445 directives: runtimeDirectives,
13446 patchFlag,
13447 dynamicPropNames
13448 };
13449 }
13450 // Dedupe props in an object literal.
13451 // Literal duplicated attributes would have been warned during the parse phase,
13452 // however, it's possible to encounter duplicated `onXXX` handlers with different
13453 // modifiers. We also need to merge static and dynamic class / style attributes.
13454 // - onXXX handlers / style: merge into array
13455 // - class: merge into single expression with concatenation
13456 function dedupeProperties(properties) {
13457 const knownProps = new Map();
13458 const deduped = [];
13459 for (let i = 0; i < properties.length; i++) {
13460 const prop = properties[i];
13461 // dynamic keys are always allowed
13462 if (prop.key.type === 8 /* COMPOUND_EXPRESSION */ || !prop.key.isStatic) {
13463 deduped.push(prop);
13464 continue;
13465 }
13466 const name = prop.key.content;
13467 const existing = knownProps.get(name);
13468 if (existing) {
13469 if (name === 'style' || name === 'class' || name.startsWith('on')) {
13470 mergeAsArray(existing, prop);
13471 }
13472 // unexpected duplicate, should have emitted error during parse
13473 }
13474 else {
13475 knownProps.set(name, prop);
13476 deduped.push(prop);
13477 }
13478 }
13479 return deduped;
13480 }
13481 function mergeAsArray(existing, incoming) {
13482 if (existing.value.type === 17 /* JS_ARRAY_EXPRESSION */) {
13483 existing.value.elements.push(incoming.value);
13484 }
13485 else {
13486 existing.value = createArrayExpression([existing.value, incoming.value], existing.loc);
13487 }
13488 }
13489 function buildDirectiveArgs(dir, context) {
13490 const dirArgs = [];
13491 const runtime = directiveImportMap.get(dir);
13492 if (runtime) {
13493 // built-in directive with runtime
13494 dirArgs.push(context.helperString(runtime));
13495 }
13496 else {
13497 {
13498 // inject statement for resolving directive
13499 context.helper(RESOLVE_DIRECTIVE);
13500 context.directives.add(dir.name);
13501 dirArgs.push(toValidAssetId(dir.name, `directive`));
13502 }
13503 }
13504 const { loc } = dir;
13505 if (dir.exp)
13506 dirArgs.push(dir.exp);
13507 if (dir.arg) {
13508 if (!dir.exp) {
13509 dirArgs.push(`void 0`);
13510 }
13511 dirArgs.push(dir.arg);
13512 }
13513 if (Object.keys(dir.modifiers).length) {
13514 if (!dir.arg) {
13515 if (!dir.exp) {
13516 dirArgs.push(`void 0`);
13517 }
13518 dirArgs.push(`void 0`);
13519 }
13520 const trueExpression = createSimpleExpression(`true`, false, loc);
13521 dirArgs.push(createObjectExpression(dir.modifiers.map(modifier => createObjectProperty(modifier, trueExpression)), loc));
13522 }
13523 return createArrayExpression(dirArgs, dir.loc);
13524 }
13525 function stringifyDynamicPropNames(props) {
13526 let propsNamesString = `[`;
13527 for (let i = 0, l = props.length; i < l; i++) {
13528 propsNamesString += JSON.stringify(props[i]);
13529 if (i < l - 1)
13530 propsNamesString += ', ';
13531 }
13532 return propsNamesString + `]`;
13533 }
13534 function isComponentTag(tag) {
13535 return tag[0].toLowerCase() + tag.slice(1) === 'component';
13536 }
13537
13538 const transformSlotOutlet = (node, context) => {
13539 if (isSlotOutlet(node)) {
13540 const { children, loc } = node;
13541 const { slotName, slotProps } = processSlotOutlet(node, context);
13542 const slotArgs = [
13543 context.prefixIdentifiers ? `_ctx.$slots` : `$slots`,
13544 slotName
13545 ];
13546 if (slotProps) {
13547 slotArgs.push(slotProps);
13548 }
13549 if (children.length) {
13550 if (!slotProps) {
13551 slotArgs.push(`{}`);
13552 }
13553 slotArgs.push(createFunctionExpression([], children, false, false, loc));
13554 }
13555 if (context.scopeId && !context.slotted) {
13556 if (!slotProps) {
13557 slotArgs.push(`{}`);
13558 }
13559 if (!children.length) {
13560 slotArgs.push(`undefined`);
13561 }
13562 slotArgs.push(`true`);
13563 }
13564 node.codegenNode = createCallExpression(context.helper(RENDER_SLOT), slotArgs, loc);
13565 }
13566 };
13567 function processSlotOutlet(node, context) {
13568 let slotName = `"default"`;
13569 let slotProps = undefined;
13570 const nonNameProps = [];
13571 for (let i = 0; i < node.props.length; i++) {
13572 const p = node.props[i];
13573 if (p.type === 6 /* ATTRIBUTE */) {
13574 if (p.value) {
13575 if (p.name === 'name') {
13576 slotName = JSON.stringify(p.value.content);
13577 }
13578 else {
13579 p.name = camelize(p.name);
13580 nonNameProps.push(p);
13581 }
13582 }
13583 }
13584 else {
13585 if (p.name === 'bind' && isBindKey(p.arg, 'name')) {
13586 if (p.exp)
13587 slotName = p.exp;
13588 }
13589 else {
13590 if (p.name === 'bind' && p.arg && isStaticExp(p.arg)) {
13591 p.arg.content = camelize(p.arg.content);
13592 }
13593 nonNameProps.push(p);
13594 }
13595 }
13596 }
13597 if (nonNameProps.length > 0) {
13598 const { props, directives } = buildProps(node, context, nonNameProps);
13599 slotProps = props;
13600 if (directives.length) {
13601 context.onError(createCompilerError(35 /* X_V_SLOT_UNEXPECTED_DIRECTIVE_ON_SLOT_OUTLET */, directives[0].loc));
13602 }
13603 }
13604 return {
13605 slotName,
13606 slotProps
13607 };
13608 }
13609
13610 const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^\s*function(?:\s+[\w$]+)?\s*\(/;
13611 const transformOn = (dir, node, context, augmentor) => {
13612 const { loc, modifiers, arg } = dir;
13613 if (!dir.exp && !modifiers.length) {
13614 context.onError(createCompilerError(34 /* X_V_ON_NO_EXPRESSION */, loc));
13615 }
13616 let eventName;
13617 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
13618 if (arg.isStatic) {
13619 const rawName = arg.content;
13620 // for all event listeners, auto convert it to camelCase. See issue #2249
13621 eventName = createSimpleExpression(toHandlerKey(camelize(rawName)), true, arg.loc);
13622 }
13623 else {
13624 // #2388
13625 eventName = createCompoundExpression([
13626 `${context.helperString(TO_HANDLER_KEY)}(`,
13627 arg,
13628 `)`
13629 ]);
13630 }
13631 }
13632 else {
13633 // already a compound expression.
13634 eventName = arg;
13635 eventName.children.unshift(`${context.helperString(TO_HANDLER_KEY)}(`);
13636 eventName.children.push(`)`);
13637 }
13638 // handler processing
13639 let exp = dir.exp;
13640 if (exp && !exp.content.trim()) {
13641 exp = undefined;
13642 }
13643 let shouldCache = context.cacheHandlers && !exp;
13644 if (exp) {
13645 const isMemberExp = isMemberExpression(exp.content);
13646 const isInlineStatement = !(isMemberExp || fnExpRE.test(exp.content));
13647 const hasMultipleStatements = exp.content.includes(`;`);
13648 {
13649 validateBrowserExpression(exp, context, false, hasMultipleStatements);
13650 }
13651 if (isInlineStatement || (shouldCache && isMemberExp)) {
13652 // wrap inline statement in a function expression
13653 exp = createCompoundExpression([
13654 `${isInlineStatement
13655 ? `$event`
13656 : `${``}(...args)`} => ${hasMultipleStatements ? `{` : `(`}`,
13657 exp,
13658 hasMultipleStatements ? `}` : `)`
13659 ]);
13660 }
13661 }
13662 let ret = {
13663 props: [
13664 createObjectProperty(eventName, exp || createSimpleExpression(`() => {}`, false, loc))
13665 ]
13666 };
13667 // apply extended compiler augmentor
13668 if (augmentor) {
13669 ret = augmentor(ret);
13670 }
13671 if (shouldCache) {
13672 // cache handlers so that it's always the same handler being passed down.
13673 // this avoids unnecessary re-renders when users use inline handlers on
13674 // components.
13675 ret.props[0].value = context.cache(ret.props[0].value);
13676 }
13677 return ret;
13678 };
13679
13680 // v-bind without arg is handled directly in ./transformElements.ts due to it affecting
13681 // codegen for the entire props object. This transform here is only for v-bind
13682 // *with* args.
13683 const transformBind = (dir, _node, context) => {
13684 const { exp, modifiers, loc } = dir;
13685 const arg = dir.arg;
13686 if (arg.type !== 4 /* SIMPLE_EXPRESSION */) {
13687 arg.children.unshift(`(`);
13688 arg.children.push(`) || ""`);
13689 }
13690 else if (!arg.isStatic) {
13691 arg.content = `${arg.content} || ""`;
13692 }
13693 // .prop is no longer necessary due to new patch behavior
13694 // .sync is replaced by v-model:arg
13695 if (modifiers.includes('camel')) {
13696 if (arg.type === 4 /* SIMPLE_EXPRESSION */) {
13697 if (arg.isStatic) {
13698 arg.content = camelize(arg.content);
13699 }
13700 else {
13701 arg.content = `${context.helperString(CAMELIZE)}(${arg.content})`;
13702 }
13703 }
13704 else {
13705 arg.children.unshift(`${context.helperString(CAMELIZE)}(`);
13706 arg.children.push(`)`);
13707 }
13708 }
13709 if (!exp ||
13710 (exp.type === 4 /* SIMPLE_EXPRESSION */ && !exp.content.trim())) {
13711 context.onError(createCompilerError(33 /* X_V_BIND_NO_EXPRESSION */, loc));
13712 return {
13713 props: [createObjectProperty(arg, createSimpleExpression('', true, loc))]
13714 };
13715 }
13716 return {
13717 props: [createObjectProperty(arg, exp)]
13718 };
13719 };
13720
13721 // Merge adjacent text nodes and expressions into a single expression
13722 // e.g. <div>abc {{ d }} {{ e }}</div> should have a single expression node as child.
13723 const transformText = (node, context) => {
13724 if (node.type === 0 /* ROOT */ ||
13725 node.type === 1 /* ELEMENT */ ||
13726 node.type === 11 /* FOR */ ||
13727 node.type === 10 /* IF_BRANCH */) {
13728 // perform the transform on node exit so that all expressions have already
13729 // been processed.
13730 return () => {
13731 const children = node.children;
13732 let currentContainer = undefined;
13733 let hasText = false;
13734 for (let i = 0; i < children.length; i++) {
13735 const child = children[i];
13736 if (isText(child)) {
13737 hasText = true;
13738 for (let j = i + 1; j < children.length; j++) {
13739 const next = children[j];
13740 if (isText(next)) {
13741 if (!currentContainer) {
13742 currentContainer = children[i] = {
13743 type: 8 /* COMPOUND_EXPRESSION */,
13744 loc: child.loc,
13745 children: [child]
13746 };
13747 }
13748 // merge adjacent text node into current
13749 currentContainer.children.push(` + `, next);
13750 children.splice(j, 1);
13751 j--;
13752 }
13753 else {
13754 currentContainer = undefined;
13755 break;
13756 }
13757 }
13758 }
13759 }
13760 if (!hasText ||
13761 // if this is a plain element with a single text child, leave it
13762 // as-is since the runtime has dedicated fast path for this by directly
13763 // setting textContent of the element.
13764 // for component root it's always normalized anyway.
13765 (children.length === 1 &&
13766 (node.type === 0 /* ROOT */ ||
13767 (node.type === 1 /* ELEMENT */ &&
13768 node.tagType === 0 /* ELEMENT */ &&
13769 // #3756
13770 // custom directives can potentially add DOM elements arbitrarily,
13771 // we need to avoid setting textContent of the element at runtime
13772 // to avoid accidentally overwriting the DOM elements added
13773 // by the user through custom directives.
13774 !node.props.find(p => p.type === 7 /* DIRECTIVE */ &&
13775 !context.directiveTransforms[p.name]) &&
13776 // in compat mode, <template> tags with no special directives
13777 // will be rendered as a fragment so its children must be
13778 // converted into vnodes.
13779 !(false ))))) {
13780 return;
13781 }
13782 // pre-convert text nodes into createTextVNode(text) calls to avoid
13783 // runtime normalization.
13784 for (let i = 0; i < children.length; i++) {
13785 const child = children[i];
13786 if (isText(child) || child.type === 8 /* COMPOUND_EXPRESSION */) {
13787 const callArgs = [];
13788 // createTextVNode defaults to single whitespace, so if it is a
13789 // single space the code could be an empty call to save bytes.
13790 if (child.type !== 2 /* TEXT */ || child.content !== ' ') {
13791 callArgs.push(child);
13792 }
13793 // mark dynamic text with flag so it gets patched inside a block
13794 if (!context.ssr &&
13795 getConstantType(child, context) === 0 /* NOT_CONSTANT */) {
13796 callArgs.push(1 /* TEXT */ +
13797 (` /* ${PatchFlagNames[1 /* TEXT */]} */` ));
13798 }
13799 children[i] = {
13800 type: 12 /* TEXT_CALL */,
13801 content: child,
13802 loc: child.loc,
13803 codegenNode: createCallExpression(context.helper(CREATE_TEXT), callArgs)
13804 };
13805 }
13806 }
13807 };
13808 }
13809 };
13810
13811 const seen = new WeakSet();
13812 const transformOnce = (node, context) => {
13813 if (node.type === 1 /* ELEMENT */ && findDir(node, 'once', true)) {
13814 if (seen.has(node)) {
13815 return;
13816 }
13817 seen.add(node);
13818 context.helper(SET_BLOCK_TRACKING);
13819 return () => {
13820 const cur = context.currentNode;
13821 if (cur.codegenNode) {
13822 cur.codegenNode = context.cache(cur.codegenNode, true /* isVNode */);
13823 }
13824 };
13825 }
13826 };
13827
13828 const transformModel = (dir, node, context) => {
13829 const { exp, arg } = dir;
13830 if (!exp) {
13831 context.onError(createCompilerError(40 /* X_V_MODEL_NO_EXPRESSION */, dir.loc));
13832 return createTransformProps();
13833 }
13834 const rawExp = exp.loc.source;
13835 const expString = exp.type === 4 /* SIMPLE_EXPRESSION */ ? exp.content : rawExp;
13836 // im SFC <script setup> inline mode, the exp may have been transformed into
13837 // _unref(exp)
13838 context.bindingMetadata[rawExp];
13839 const maybeRef = !true /* SETUP_CONST */;
13840 if (!isMemberExpression(expString) && !maybeRef) {
13841 context.onError(createCompilerError(41 /* X_V_MODEL_MALFORMED_EXPRESSION */, exp.loc));
13842 return createTransformProps();
13843 }
13844 const propName = arg ? arg : createSimpleExpression('modelValue', true);
13845 const eventName = arg
13846 ? isStaticExp(arg)
13847 ? `onUpdate:${arg.content}`
13848 : createCompoundExpression(['"onUpdate:" + ', arg])
13849 : `onUpdate:modelValue`;
13850 let assignmentExp;
13851 const eventArg = context.isTS ? `($event: any)` : `$event`;
13852 {
13853 assignmentExp = createCompoundExpression([
13854 `${eventArg} => (`,
13855 exp,
13856 ` = $event)`
13857 ]);
13858 }
13859 const props = [
13860 // modelValue: foo
13861 createObjectProperty(propName, dir.exp),
13862 // "onUpdate:modelValue": $event => (foo = $event)
13863 createObjectProperty(eventName, assignmentExp)
13864 ];
13865 // modelModifiers: { foo: true, "bar-baz": true }
13866 if (dir.modifiers.length && node.tagType === 1 /* COMPONENT */) {
13867 const modifiers = dir.modifiers
13868 .map(m => (isSimpleIdentifier(m) ? m : JSON.stringify(m)) + `: true`)
13869 .join(`, `);
13870 const modifiersKey = arg
13871 ? isStaticExp(arg)
13872 ? `${arg.content}Modifiers`
13873 : createCompoundExpression([arg, ' + "Modifiers"'])
13874 : `modelModifiers`;
13875 props.push(createObjectProperty(modifiersKey, createSimpleExpression(`{ ${modifiers} }`, false, dir.loc, 2 /* CAN_HOIST */)));
13876 }
13877 return createTransformProps(props);
13878 };
13879 function createTransformProps(props = []) {
13880 return { props };
13881 }
13882
13883 function getBaseTransformPreset(prefixIdentifiers) {
13884 return [
13885 [
13886 transformOnce,
13887 transformIf,
13888 transformFor,
13889 ...([]),
13890 ...([transformExpression]
13891 ),
13892 transformSlotOutlet,
13893 transformElement,
13894 trackSlotScopes,
13895 transformText
13896 ],
13897 {
13898 on: transformOn,
13899 bind: transformBind,
13900 model: transformModel
13901 }
13902 ];
13903 }
13904 // we name it `baseCompile` so that higher order compilers like
13905 // @vue/compiler-dom can export `compile` while re-exporting everything else.
13906 function baseCompile(template, options = {}) {
13907 const onError = options.onError || defaultOnError;
13908 const isModuleMode = options.mode === 'module';
13909 /* istanbul ignore if */
13910 {
13911 if (options.prefixIdentifiers === true) {
13912 onError(createCompilerError(45 /* X_PREFIX_ID_NOT_SUPPORTED */));
13913 }
13914 else if (isModuleMode) {
13915 onError(createCompilerError(46 /* X_MODULE_MODE_NOT_SUPPORTED */));
13916 }
13917 }
13918 const prefixIdentifiers = !true ;
13919 if (options.cacheHandlers) {
13920 onError(createCompilerError(47 /* X_CACHE_HANDLER_NOT_SUPPORTED */));
13921 }
13922 if (options.scopeId && !isModuleMode) {
13923 onError(createCompilerError(48 /* X_SCOPE_ID_NOT_SUPPORTED */));
13924 }
13925 const ast = isString(template) ? baseParse(template, options) : template;
13926 const [nodeTransforms, directiveTransforms] = getBaseTransformPreset();
13927 transform(ast, extend({}, options, {
13928 prefixIdentifiers,
13929 nodeTransforms: [
13930 ...nodeTransforms,
13931 ...(options.nodeTransforms || []) // user transforms
13932 ],
13933 directiveTransforms: extend({}, directiveTransforms, options.directiveTransforms || {} // user transforms
13934 )
13935 }));
13936 return generate(ast, extend({}, options, {
13937 prefixIdentifiers
13938 }));
13939 }
13940
13941 const noopDirectiveTransform = () => ({ props: [] });
13942
13943 const V_MODEL_RADIO = Symbol(`vModelRadio` );
13944 const V_MODEL_CHECKBOX = Symbol(`vModelCheckbox` );
13945 const V_MODEL_TEXT = Symbol(`vModelText` );
13946 const V_MODEL_SELECT = Symbol(`vModelSelect` );
13947 const V_MODEL_DYNAMIC = Symbol(`vModelDynamic` );
13948 const V_ON_WITH_MODIFIERS = Symbol(`vOnModifiersGuard` );
13949 const V_ON_WITH_KEYS = Symbol(`vOnKeysGuard` );
13950 const V_SHOW = Symbol(`vShow` );
13951 const TRANSITION$1 = Symbol(`Transition` );
13952 const TRANSITION_GROUP = Symbol(`TransitionGroup` );
13953 registerRuntimeHelpers({
13954 [V_MODEL_RADIO]: `vModelRadio`,
13955 [V_MODEL_CHECKBOX]: `vModelCheckbox`,
13956 [V_MODEL_TEXT]: `vModelText`,
13957 [V_MODEL_SELECT]: `vModelSelect`,
13958 [V_MODEL_DYNAMIC]: `vModelDynamic`,
13959 [V_ON_WITH_MODIFIERS]: `withModifiers`,
13960 [V_ON_WITH_KEYS]: `withKeys`,
13961 [V_SHOW]: `vShow`,
13962 [TRANSITION$1]: `Transition`,
13963 [TRANSITION_GROUP]: `TransitionGroup`
13964 });
13965
13966 /* eslint-disable no-restricted-globals */
13967 let decoder;
13968 function decodeHtmlBrowser(raw, asAttr = false) {
13969 if (!decoder) {
13970 decoder = document.createElement('div');
13971 }
13972 if (asAttr) {
13973 decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
13974 return decoder.children[0].getAttribute('foo');
13975 }
13976 else {
13977 decoder.innerHTML = raw;
13978 return decoder.textContent;
13979 }
13980 }
13981
13982 const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
13983 const parserOptions = {
13984 isVoidTag,
13985 isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
13986 isPreTag: tag => tag === 'pre',
13987 decodeEntities: decodeHtmlBrowser ,
13988 isBuiltInComponent: (tag) => {
13989 if (isBuiltInType(tag, `Transition`)) {
13990 return TRANSITION$1;
13991 }
13992 else if (isBuiltInType(tag, `TransitionGroup`)) {
13993 return TRANSITION_GROUP;
13994 }
13995 },
13996 // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
13997 getNamespace(tag, parent) {
13998 let ns = parent ? parent.ns : 0 /* HTML */;
13999 if (parent && ns === 2 /* MATH_ML */) {
14000 if (parent.tag === 'annotation-xml') {
14001 if (tag === 'svg') {
14002 return 1 /* SVG */;
14003 }
14004 if (parent.props.some(a => a.type === 6 /* ATTRIBUTE */ &&
14005 a.name === 'encoding' &&
14006 a.value != null &&
14007 (a.value.content === 'text/html' ||
14008 a.value.content === 'application/xhtml+xml'))) {
14009 ns = 0 /* HTML */;
14010 }
14011 }
14012 else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
14013 tag !== 'mglyph' &&
14014 tag !== 'malignmark') {
14015 ns = 0 /* HTML */;
14016 }
14017 }
14018 else if (parent && ns === 1 /* SVG */) {
14019 if (parent.tag === 'foreignObject' ||
14020 parent.tag === 'desc' ||
14021 parent.tag === 'title') {
14022 ns = 0 /* HTML */;
14023 }
14024 }
14025 if (ns === 0 /* HTML */) {
14026 if (tag === 'svg') {
14027 return 1 /* SVG */;
14028 }
14029 if (tag === 'math') {
14030 return 2 /* MATH_ML */;
14031 }
14032 }
14033 return ns;
14034 },
14035 // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
14036 getTextMode({ tag, ns }) {
14037 if (ns === 0 /* HTML */) {
14038 if (tag === 'textarea' || tag === 'title') {
14039 return 1 /* RCDATA */;
14040 }
14041 if (isRawTextContainer(tag)) {
14042 return 2 /* RAWTEXT */;
14043 }
14044 }
14045 return 0 /* DATA */;
14046 }
14047 };
14048
14049 // Parse inline CSS strings for static style attributes into an object.
14050 // This is a NodeTransform since it works on the static `style` attribute and
14051 // converts it into a dynamic equivalent:
14052 // style="color: red" -> :style='{ "color": "red" }'
14053 // It is then processed by `transformElement` and included in the generated
14054 // props.
14055 const transformStyle = node => {
14056 if (node.type === 1 /* ELEMENT */) {
14057 node.props.forEach((p, i) => {
14058 if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
14059 // replace p with an expression node
14060 node.props[i] = {
14061 type: 7 /* DIRECTIVE */,
14062 name: `bind`,
14063 arg: createSimpleExpression(`style`, true, p.loc),
14064 exp: parseInlineCSS(p.value.content, p.loc),
14065 modifiers: [],
14066 loc: p.loc
14067 };
14068 }
14069 });
14070 }
14071 };
14072 const parseInlineCSS = (cssText, loc) => {
14073 const normalized = parseStringStyle(cssText);
14074 return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* CAN_STRINGIFY */);
14075 };
14076
14077 function createDOMCompilerError(code, loc) {
14078 return createCompilerError(code, loc, DOMErrorMessages );
14079 }
14080 const DOMErrorMessages = {
14081 [49 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
14082 [50 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
14083 [51 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
14084 [52 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
14085 [53 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
14086 [54 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
14087 [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.`,
14088 [56 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
14089 [57 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
14090 [58 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
14091 [59 /* X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
14092 };
14093
14094 const transformVHtml = (dir, node, context) => {
14095 const { exp, loc } = dir;
14096 if (!exp) {
14097 context.onError(createDOMCompilerError(49 /* X_V_HTML_NO_EXPRESSION */, loc));
14098 }
14099 if (node.children.length) {
14100 context.onError(createDOMCompilerError(50 /* X_V_HTML_WITH_CHILDREN */, loc));
14101 node.children.length = 0;
14102 }
14103 return {
14104 props: [
14105 createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
14106 ]
14107 };
14108 };
14109
14110 const transformVText = (dir, node, context) => {
14111 const { exp, loc } = dir;
14112 if (!exp) {
14113 context.onError(createDOMCompilerError(51 /* X_V_TEXT_NO_EXPRESSION */, loc));
14114 }
14115 if (node.children.length) {
14116 context.onError(createDOMCompilerError(52 /* X_V_TEXT_WITH_CHILDREN */, loc));
14117 node.children.length = 0;
14118 }
14119 return {
14120 props: [
14121 createObjectProperty(createSimpleExpression(`textContent`, true), exp
14122 ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
14123 : createSimpleExpression('', true))
14124 ]
14125 };
14126 };
14127
14128 const transformModel$1 = (dir, node, context) => {
14129 const baseResult = transformModel(dir, node, context);
14130 // base transform has errors OR component v-model (only need props)
14131 if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
14132 return baseResult;
14133 }
14134 if (dir.arg) {
14135 context.onError(createDOMCompilerError(54 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
14136 }
14137 function checkDuplicatedValue() {
14138 const value = findProp(node, 'value');
14139 if (value) {
14140 context.onError(createDOMCompilerError(56 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
14141 }
14142 }
14143 const { tag } = node;
14144 const isCustomElement = context.isCustomElement(tag);
14145 if (tag === 'input' ||
14146 tag === 'textarea' ||
14147 tag === 'select' ||
14148 isCustomElement) {
14149 let directiveToUse = V_MODEL_TEXT;
14150 let isInvalidType = false;
14151 if (tag === 'input' || isCustomElement) {
14152 const type = findProp(node, `type`);
14153 if (type) {
14154 if (type.type === 7 /* DIRECTIVE */) {
14155 // :type="foo"
14156 directiveToUse = V_MODEL_DYNAMIC;
14157 }
14158 else if (type.value) {
14159 switch (type.value.content) {
14160 case 'radio':
14161 directiveToUse = V_MODEL_RADIO;
14162 break;
14163 case 'checkbox':
14164 directiveToUse = V_MODEL_CHECKBOX;
14165 break;
14166 case 'file':
14167 isInvalidType = true;
14168 context.onError(createDOMCompilerError(55 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
14169 break;
14170 default:
14171 // text type
14172 checkDuplicatedValue();
14173 break;
14174 }
14175 }
14176 }
14177 else if (hasDynamicKeyVBind(node)) {
14178 // element has bindings with dynamic keys, which can possibly contain
14179 // "type".
14180 directiveToUse = V_MODEL_DYNAMIC;
14181 }
14182 else {
14183 // text type
14184 checkDuplicatedValue();
14185 }
14186 }
14187 else if (tag === 'select') {
14188 directiveToUse = V_MODEL_SELECT;
14189 }
14190 else {
14191 // textarea
14192 checkDuplicatedValue();
14193 }
14194 // inject runtime directive
14195 // by returning the helper symbol via needRuntime
14196 // the import will replaced a resolveDirective call.
14197 if (!isInvalidType) {
14198 baseResult.needRuntime = context.helper(directiveToUse);
14199 }
14200 }
14201 else {
14202 context.onError(createDOMCompilerError(53 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
14203 }
14204 // native vmodel doesn't need the `modelValue` props since they are also
14205 // passed to the runtime as `binding.value`. removing it reduces code size.
14206 baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
14207 p.key.content === 'modelValue'));
14208 return baseResult;
14209 };
14210
14211 const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
14212 const isNonKeyModifier = /*#__PURE__*/ makeMap(
14213 // event propagation management
14214`stop,prevent,self,` +
14215 // system modifiers + exact
14216 `ctrl,shift,alt,meta,exact,` +
14217 // mouse
14218 `middle`);
14219 // left & right could be mouse or key modifiers based on event type
14220 const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
14221 const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
14222 const resolveModifiers = (key, modifiers, context, loc) => {
14223 const keyModifiers = [];
14224 const nonKeyModifiers = [];
14225 const eventOptionModifiers = [];
14226 for (let i = 0; i < modifiers.length; i++) {
14227 const modifier = modifiers[i];
14228 if (isEventOptionModifier(modifier)) {
14229 // eventOptionModifiers: modifiers for addEventListener() options,
14230 // e.g. .passive & .capture
14231 eventOptionModifiers.push(modifier);
14232 }
14233 else {
14234 // runtimeModifiers: modifiers that needs runtime guards
14235 if (maybeKeyModifier(modifier)) {
14236 if (isStaticExp(key)) {
14237 if (isKeyboardEvent(key.content)) {
14238 keyModifiers.push(modifier);
14239 }
14240 else {
14241 nonKeyModifiers.push(modifier);
14242 }
14243 }
14244 else {
14245 keyModifiers.push(modifier);
14246 nonKeyModifiers.push(modifier);
14247 }
14248 }
14249 else {
14250 if (isNonKeyModifier(modifier)) {
14251 nonKeyModifiers.push(modifier);
14252 }
14253 else {
14254 keyModifiers.push(modifier);
14255 }
14256 }
14257 }
14258 }
14259 return {
14260 keyModifiers,
14261 nonKeyModifiers,
14262 eventOptionModifiers
14263 };
14264 };
14265 const transformClick = (key, event) => {
14266 const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
14267 return isStaticClick
14268 ? createSimpleExpression(event, true)
14269 : key.type !== 4 /* SIMPLE_EXPRESSION */
14270 ? createCompoundExpression([
14271 `(`,
14272 key,
14273 `) === "onClick" ? "${event}" : (`,
14274 key,
14275 `)`
14276 ])
14277 : key;
14278 };
14279 const transformOn$1 = (dir, node, context) => {
14280 return transformOn(dir, node, context, baseResult => {
14281 const { modifiers } = dir;
14282 if (!modifiers.length)
14283 return baseResult;
14284 let { key, value: handlerExp } = baseResult.props[0];
14285 const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
14286 // normalize click.right and click.middle since they don't actually fire
14287 if (nonKeyModifiers.includes('right')) {
14288 key = transformClick(key, `onContextmenu`);
14289 }
14290 if (nonKeyModifiers.includes('middle')) {
14291 key = transformClick(key, `onMouseup`);
14292 }
14293 if (nonKeyModifiers.length) {
14294 handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
14295 handlerExp,
14296 JSON.stringify(nonKeyModifiers)
14297 ]);
14298 }
14299 if (keyModifiers.length &&
14300 // if event name is dynamic, always wrap with keys guard
14301 (!isStaticExp(key) || isKeyboardEvent(key.content))) {
14302 handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
14303 handlerExp,
14304 JSON.stringify(keyModifiers)
14305 ]);
14306 }
14307 if (eventOptionModifiers.length) {
14308 const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
14309 key = isStaticExp(key)
14310 ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
14311 : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
14312 }
14313 return {
14314 props: [createObjectProperty(key, handlerExp)]
14315 };
14316 });
14317 };
14318
14319 const transformShow = (dir, node, context) => {
14320 const { exp, loc } = dir;
14321 if (!exp) {
14322 context.onError(createDOMCompilerError(57 /* X_V_SHOW_NO_EXPRESSION */, loc));
14323 }
14324 return {
14325 props: [],
14326 needRuntime: context.helper(V_SHOW)
14327 };
14328 };
14329
14330 const warnTransitionChildren = (node, context) => {
14331 if (node.type === 1 /* ELEMENT */ &&
14332 node.tagType === 1 /* COMPONENT */) {
14333 const component = context.isBuiltInComponent(node.tag);
14334 if (component === TRANSITION$1) {
14335 return () => {
14336 if (node.children.length && hasMultipleChildren(node)) {
14337 context.onError(createDOMCompilerError(58 /* X_TRANSITION_INVALID_CHILDREN */, {
14338 start: node.children[0].loc.start,
14339 end: node.children[node.children.length - 1].loc.end,
14340 source: ''
14341 }));
14342 }
14343 };
14344 }
14345 }
14346 };
14347 function hasMultipleChildren(node) {
14348 // #1352 filter out potential comment nodes.
14349 const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
14350 const child = children[0];
14351 return (children.length !== 1 ||
14352 child.type === 11 /* FOR */ ||
14353 (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
14354 }
14355
14356 const ignoreSideEffectTags = (node, context) => {
14357 if (node.type === 1 /* ELEMENT */ &&
14358 node.tagType === 0 /* ELEMENT */ &&
14359 (node.tag === 'script' || node.tag === 'style')) {
14360 context.onError(createDOMCompilerError(59 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
14361 context.removeNode();
14362 }
14363 };
14364
14365 const DOMNodeTransforms = [
14366 transformStyle,
14367 ...([warnTransitionChildren] )
14368 ];
14369 const DOMDirectiveTransforms = {
14370 cloak: noopDirectiveTransform,
14371 html: transformVHtml,
14372 text: transformVText,
14373 model: transformModel$1,
14374 on: transformOn$1,
14375 show: transformShow
14376 };
14377 function compile$1(template, options = {}) {
14378 return baseCompile(template, extend({}, parserOptions, options, {
14379 nodeTransforms: [
14380 // ignore <script> and <tag>
14381 // this is not put inside DOMNodeTransforms because that list is used
14382 // by compiler-ssr to generate vnode fallback branches
14383 ignoreSideEffectTags,
14384 ...DOMNodeTransforms,
14385 ...(options.nodeTransforms || [])
14386 ],
14387 directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
14388 transformHoist: null
14389 }));
14390 }
14391
14392 // This entry is the "full-build" that includes both the runtime
14393 {
14394 initDev();
14395 }
14396 const compileCache = Object.create(null);
14397 function compileToFunction(template, options) {
14398 if (!isString(template)) {
14399 if (template.nodeType) {
14400 template = template.innerHTML;
14401 }
14402 else {
14403 warn(`invalid template option: `, template);
14404 return NOOP;
14405 }
14406 }
14407 const key = template;
14408 const cached = compileCache[key];
14409 if (cached) {
14410 return cached;
14411 }
14412 if (template[0] === '#') {
14413 const el = document.querySelector(template);
14414 if (!el) {
14415 warn(`Template element not found or is empty: ${template}`);
14416 }
14417 // __UNSAFE__
14418 // Reason: potential execution of JS expressions in in-DOM template.
14419 // The user must make sure the in-DOM template is trusted. If it's rendered
14420 // by the server, the template should not contain any user data.
14421 template = el ? el.innerHTML : ``;
14422 }
14423 const { code } = compile$1(template, extend({
14424 hoistStatic: true,
14425 onError: onError ,
14426 onWarn: e => onError(e, true)
14427 }, options));
14428 function onError(err, asWarning = false) {
14429 const message = asWarning
14430 ? err.message
14431 : `Template compilation error: ${err.message}`;
14432 const codeFrame = err.loc &&
14433 generateCodeFrame(template, err.loc.start.offset, err.loc.end.offset);
14434 warn(codeFrame ? `${message}\n${codeFrame}` : message);
14435 }
14436 // The wildcard import results in a huge object with every export
14437 // with keys that cannot be mangled, and can be quite heavy size-wise.
14438 // In the global build we know `Vue` is available globally so we can avoid
14439 // the wildcard object.
14440 const render = (new Function(code)()
14441 );
14442 render._rc = true;
14443 return (compileCache[key] = render);
14444 }
14445 registerRuntimeCompiler(compileToFunction);
14446
14447 exports.BaseTransition = BaseTransition;
14448 exports.Comment = Comment$1;
14449 exports.Fragment = Fragment;
14450 exports.KeepAlive = KeepAlive;
14451 exports.Static = Static;
14452 exports.Suspense = Suspense;
14453 exports.Teleport = Teleport;
14454 exports.Text = Text;
14455 exports.Transition = Transition;
14456 exports.TransitionGroup = TransitionGroup;
14457 exports.callWithAsyncErrorHandling = callWithAsyncErrorHandling;
14458 exports.callWithErrorHandling = callWithErrorHandling;
14459 exports.camelize = camelize;
14460 exports.capitalize = capitalize;
14461 exports.cloneVNode = cloneVNode;
14462 exports.compatUtils = compatUtils;
14463 exports.compile = compileToFunction;
14464 exports.computed = computed$1;
14465 exports.createApp = createApp;
14466 exports.createBlock = createBlock;
14467 exports.createCommentVNode = createCommentVNode;
14468 exports.createHydrationRenderer = createHydrationRenderer;
14469 exports.createRenderer = createRenderer;
14470 exports.createSSRApp = createSSRApp;
14471 exports.createSlots = createSlots;
14472 exports.createStaticVNode = createStaticVNode;
14473 exports.createTextVNode = createTextVNode;
14474 exports.createVNode = createVNode;
14475 exports.customRef = customRef;
14476 exports.defineAsyncComponent = defineAsyncComponent;
14477 exports.defineComponent = defineComponent;
14478 exports.defineEmit = defineEmit;
14479 exports.defineProps = defineProps;
14480 exports.getCurrentInstance = getCurrentInstance;
14481 exports.getTransitionRawChildren = getTransitionRawChildren;
14482 exports.h = h;
14483 exports.handleError = handleError;
14484 exports.hydrate = hydrate;
14485 exports.initCustomFormatter = initCustomFormatter;
14486 exports.inject = inject;
14487 exports.isProxy = isProxy;
14488 exports.isReactive = isReactive;
14489 exports.isReadonly = isReadonly;
14490 exports.isRef = isRef;
14491 exports.isRuntimeOnly = isRuntimeOnly;
14492 exports.isVNode = isVNode;
14493 exports.markRaw = markRaw;
14494 exports.mergeProps = mergeProps;
14495 exports.nextTick = nextTick;
14496 exports.onActivated = onActivated;
14497 exports.onBeforeMount = onBeforeMount;
14498 exports.onBeforeUnmount = onBeforeUnmount;
14499 exports.onBeforeUpdate = onBeforeUpdate;
14500 exports.onDeactivated = onDeactivated;
14501 exports.onErrorCaptured = onErrorCaptured;
14502 exports.onMounted = onMounted;
14503 exports.onRenderTracked = onRenderTracked;
14504 exports.onRenderTriggered = onRenderTriggered;
14505 exports.onServerPrefetch = onServerPrefetch;
14506 exports.onUnmounted = onUnmounted;
14507 exports.onUpdated = onUpdated;
14508 exports.openBlock = openBlock;
14509 exports.popScopeId = popScopeId;
14510 exports.provide = provide;
14511 exports.proxyRefs = proxyRefs;
14512 exports.pushScopeId = pushScopeId;
14513 exports.queuePostFlushCb = queuePostFlushCb;
14514 exports.reactive = reactive;
14515 exports.readonly = readonly;
14516 exports.ref = ref;
14517 exports.registerRuntimeCompiler = registerRuntimeCompiler;
14518 exports.render = render;
14519 exports.renderList = renderList;
14520 exports.renderSlot = renderSlot;
14521 exports.resolveComponent = resolveComponent;
14522 exports.resolveDirective = resolveDirective;
14523 exports.resolveDynamicComponent = resolveDynamicComponent;
14524 exports.resolveFilter = resolveFilter;
14525 exports.resolveTransitionHooks = resolveTransitionHooks;
14526 exports.setBlockTracking = setBlockTracking;
14527 exports.setDevtoolsHook = setDevtoolsHook;
14528 exports.setTransitionHooks = setTransitionHooks;
14529 exports.shallowReactive = shallowReactive;
14530 exports.shallowReadonly = shallowReadonly;
14531 exports.shallowRef = shallowRef;
14532 exports.ssrContextKey = ssrContextKey;
14533 exports.ssrUtils = ssrUtils;
14534 exports.toDisplayString = toDisplayString;
14535 exports.toHandlerKey = toHandlerKey;
14536 exports.toHandlers = toHandlers;
14537 exports.toRaw = toRaw;
14538 exports.toRef = toRef;
14539 exports.toRefs = toRefs;
14540 exports.transformVNodeArgs = transformVNodeArgs;
14541 exports.triggerRef = triggerRef;
14542 exports.unref = unref;
14543 exports.useContext = useContext;
14544 exports.useCssModule = useCssModule;
14545 exports.useCssVars = useCssVars;
14546 exports.useSSRContext = useSSRContext;
14547 exports.useTransitionState = useTransitionState;
14548 exports.vModelCheckbox = vModelCheckbox;
14549 exports.vModelDynamic = vModelDynamic;
14550 exports.vModelRadio = vModelRadio;
14551 exports.vModelSelect = vModelSelect;
14552 exports.vModelText = vModelText;
14553 exports.vShow = vShow;
14554 exports.version = version;
14555 exports.warn = warn;
14556 exports.watch = watch;
14557 exports.watchEffect = watchEffect;
14558 exports.withCtx = withCtx;
14559 exports.withDirectives = withDirectives;
14560 exports.withKeys = withKeys;
14561 exports.withModifiers = withModifiers;
14562 exports.withScopeId = withScopeId;
14563
14564 Object.defineProperty(exports, '__esModule', { value: true });
14565
14566 return exports;
14567
14568}({}));